gnustep-corebase-0.2/0000755000175000017500000000000014661613221013705 5ustar yavoryavorgnustep-corebase-0.2/Version0000644000175000017500000000117013222706330015250 0ustar yavoryavor# This file is included in various Makefile's to get version information. # Compatible with Bourne shell syntax, so it can included there too. # The gcc version required to compile the library. GCC_VERSION=4.0.0 # The version number of this release. MAJOR_VERSION=0 MINOR_VERSION=2 # numeric value should match above VERSION_NUMBER=1 GNUSTEP_COREBASE_VERSION=${MAJOR_VERSION}.${MINOR_VERSION} VERSION=${GNUSTEP_COREBASE_VERSION} GNUSTEP_COREBASE_FTP_MACHINE=ftp.gnustep.org GNUSTEP_COREBASE_FTP_DIRECTORY=pub/gnustep/core GNUSTEP_COREBASE_SNAP_FTP_MACHINE=ftp.gnustep.org GNUSTEP_COREBASE_SNAP_FTP_DIRECTORY=pub/daily-snapshots gnustep-corebase-0.2/Examples/0000755000175000017500000000000013222706330015457 5ustar yavoryavorgnustep-corebase-0.2/Examples/EXUInt32.c0000644000175000017500000000746513222706330017120 0ustar yavoryavor/* EXUInt32.c Copyright (C) 2014 Free Software Foundation, Inc. This file is part of the GNUstep CoreBase Library distribution. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include #include #include #include "EXUInt32.h" struct __EXUInt32 { CFRuntimeBase _parent; UInt32 _value; }; static Boolean EXUInt32Equal (CFTypeRef cf1, CFTypeRef cf2) { EXUInt32Ref u1 = (EXUInt32Ref) cf1; EXUInt32Ref u2 = (EXUInt32Ref) cf2; if (u1->_value == u2->_value) return true; return false; } static CFHashCode EXUInt32Hash (CFTypeRef cf) { EXUInt32Ref u = (EXUInt32Ref) cf; return (CFHashCode) u->_value; } static CFStringRef EXUInt32CopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOpts) { EXUInt32Ref u = (EXUInt32Ref) cf; return CFStringCreateWithFormat (kCFAllocatorDefault, formatOpts, CFSTR ("%u"), (unsigned int) u->_value); } static CFStringRef EXUInt32CopyDebugDesc (CFTypeRef cf) { EXUInt32Ref u = (EXUInt32Ref) cf; return CFStringCreateWithFormat (kCFAllocatorDefault, formatOpts, CFSTR ("{ value = %u }"), u, CFGetAllocator (u), (unsigned int) u->_value); } static void EXUInt32Finalize (CFTypeRef cf) { /* Nothing to do before finalizing. If this object were have other objects as variables, we would need to call CFRelease() for each. */ } static CFTypeID _kEXUInt32TypeID = _kCFRuntimeNotATypeID; static const CFRuntimeClass _kEXRangeClass = { 0, /* version */ "EXUInt32", /* className */ NULL, /* init */ NULL, /* copy */ EXUInt32Finalize, /* finalize */ EXUInt32Equal, /* equal */ EXUInt32Hash, /* hash */ EXUInt32CopyFormattingDesc, /* copyFormattingDesc */ EXUInt32CopyDebugDesc, /* copyDebugDesc */ NULL, /* reclaim */ NULL /* refCount */ }; void __EXUInt32ClassInitialize (void) { _kEXUInt32TypeID = _CFRuntimeRegisterClass (&_kEXUInt32Class); } CFTypeID EXUInt32GetTypeID (void) { return _kEXUInt32TypeID; } EXUInt32Ref EXUInt32Create (CFAllocatorRef alloc, UInt32 value) { struct __EXUInt32 *new; #define EXUINT32_EXTRA sizeof (struct __EXUInt32) - sizeof (CFRuntimeBase) new = (struct __EXUInt32 *) _CFRuntimeCreateInstance (alloc, _kEXRangeTypeID, EXUINT32REF_EXTRA, NULL); if (new) { new->_value = value; } return new; } UInt32 EXUInt32GetValue (EXUInt32Ref u) { return u->_value; } gnustep-corebase-0.2/Examples/EXUInt32.h0000644000175000017500000000275213222706330017117 0ustar yavoryavor/* EXUInt32.h Copyright (C) 2014 Free Software Foundation, Inc. This file is part of the GNUstep CoreBase Library distribution. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __EXUINT32_H__ #define __EXUINT32_H__ 1 #include typedef const struct __EXUInt32 *UInt32Ref; CFTypeID EXUInt32GetTypeID (void); EXUInt32Ref EXUInt32Create (CFAllocatorRef alloc, UInt32 value); UInt32 EXUInt32GetValue (EXUInt32Ref u); #endif /* __EXUINT32_H__ */ gnustep-corebase-0.2/Documentation/0000755000175000017500000000000014661612735016527 5ustar yavoryavorgnustep-corebase-0.2/Documentation/ExampleEXUInt32.dox0000644000175000017500000000315613222706330022030 0ustar yavoryavor/** \page ExampleEXUInt32 Creating a CF opaque type (EXUInt32) The GNUstep CoreBase Library supports the creating of new opaque types through the functions provided by the \ref CFRuntimeUtils. Creating new opaque types is easy, but requires some knowledge about structures used internally by the runtime. In particular, a \ref __CFRuntimeClass "CFRuntimeClass" structure will need to be defined and registered with the runtime. The only required fields for this structure is version and className. For more information, see the documentation for the \ref __CFRuntimeClass "CFRuntimeClass structure". \note This example utilizes functions that are marked as private and may not work across all implementations of the Core Foundation API. \note Caution should be taken when porting to other implementations. The opaque type described in this example is a simple container for UInt32 integers. Firstly, define the public interface to the new opaque type. The functions are prefixed with EX for EXample. This allows for a rudimentary form of namespace. EXUInt32 type only provides 3 functions: -# Getting the CFTypeID -# Creating a new instance -# Fetch the value associated with this instance \include EXUInt32.h The implementation of opaque types require that not only the public interface is implemented, but also the CFRuntimeClass and a structure to represent our EXUInt32Ref instances. \note The __EXUInt32ClassInitialize() function must be called during initialization of your software. This function registers this opaque type with the runtime. \include EXUInt32.c */ gnustep-corebase-0.2/Documentation/CompilingApplications.dox0000644000175000017500000000270013222706330023515 0ustar yavoryavor/** \page CompilingApplications Compiling Applications The information in this page describes how to compile application that make use of functionality provided GNUstep CoreBase Library. To compile tools and/or application that make use of the GNUstep CoreBase Library, you will need tell the compiler where to find the header files, and the linker to use library and where it is located. Most modern compilers allow you to do this in a single command. For example, to compile a simple 'hello world' program you would type the following: \code{.sh} cc -I/path/to/header/files/ hello.c -L/path/to/library/ -lgnustep-corebase -o hello \endcode Where cc is the C Compiler. If GNUstep CoreBase was installed to a standard location you can omit the -I and -L options. To compile an application using GNUstep Make, simply add -lgnustep-corebase to \$(NAME)_LIBRARIES_DEPEND_UPON. An example GNUmakefile for a simple 'hello world' program using GNUstep CoreBase would be: \code include $(GNUSTEP_MAKEFILES)/common.make CTOOL_NAME = hello $(CTOOL_NAME)_C_FILES = hello.c $(CTOOL_NAME)_LIBRARIES_DEPEND_UPON = -lgnustep-corebase include $(GNUSTEP_MAKEFILES)/ctool.make \endcode For more information about how to create GNUstep Make makefiles, visit the Make Utility manual. */ gnustep-corebase-0.2/Documentation/DoxygenLayout.xml0000644000175000017500000000274613222706330022060 0ustar yavoryavor gnustep-corebase-0.2/Documentation/ConfiguringAndCompiling.dox0000644000175000017500000001043513222706330023770 0ustar yavoryavor/** \page ConfiguringAndCompiling Configuring and Compiling How to compile the GNUstep CoreBase Library. \tableofcontents \section ConfiguringAndCompilingIntroduction Introduction The GNUstep CoreBase Library uses the GNU autoconf for package configuration, and the GNUStep Make tool for generating object files and building the shared library. The recommended sequence for compiling and install the library is by running the following commands: \code{.sh} $ ./configure $ make # make install \endcode Note that the \shcmd{make install} command must be executed as system administrator (\em root on UNIX-like operating systems). \section ConfiguringAndCompilingDependencies Dependencies Before configuring and compiling the GNUstep CoreBase Library you will need to have various tools, libraries and development headers installed on your system. The following tools are required by GNUstep CoreBase before - C Compiler An ISO C99 compilant C compiler is required. The recommended compilers are the GNU Compiler Collection or Clang with LLVM. For Blocks support, Clang is required. - Objective-C Compiler Additionally, GNUstep CoreBase also makes use of some Objective-C features. Both C compilers recommended above are able to compile Objective-C code. - GNU make The GNUstep CoreBase makefiles use features specific to GNU make, and will will not be correctly built if other make variants. If your default make tool is not GNU make, please install it before attempting to compile. Be mindful that in some systems, the GNU make tool is invoked as \shcmd{gmake}. - GNUstep Make In addition to the GNU make tool, the GNUstep Make package is required. - Zoneinfo Database To support Time Zones, a complete zoneinfo database must be installed on your system. - Doxygen (Recommended) Documentation is extracted from the sources by the doxygen tool. This is a recommended tool, but not required. If the doxygen tool is not found during the configuration process, API documentation will not be generated and installed. In addition to the tools listed above, GNUstep CoreBase also depends on other libraries. To successfully configure and compile, you will need to install the libraries listed below along with their development headers. - C standard library A POSIX compilant C standard library is required and provides basic functionalities, such as memory allocation and socket support. - Objective-C Runtime Library To support "toll-free bridging", a modern Objective-C Runtime in required. See \ref ConfiguringAndCompilingOptions for information on how to compile without this package. - GNUstep Base Library Required for "toll-free bridging" support. - International Components for Unicode The ICU package provides robust Unicode and Internationalization support. - Grand Central Dispatch (Recommended) The \ref CFRunLoopRef "CFRunLoop type" uses GCD for compatibility. Compiling without this library leads to a loss of functionality. See \ref ConfiguringAndCompilingOptions for information on how to compile without this package. \section ConfiguringAndCompilingOptions Configuration Options \par \--without-gcd Compiles the library without Grand Central Dispatch Support. Leads to loss of functionality. \par \--without-objc (not recommended) Compiles the library without Objective-C runtime support. This leads to the loss the of the toll-free bridge capability between objects created by this library and those created by the GNUstep Base library. \par \--with-zoneinfo-dir=DIR Specify the directory where the zoneinfo database can be found. The configure script looks for the database files in some standard location and this option only needs to be used if the zoneinfo database is in a non-standard directory. DIR is an absolute path. */ gnustep-corebase-0.2/Documentation/MainPage.dox0000644000175000017500000001201013222706330020701 0ustar yavoryavor/** \mainpage GNUstep CoreBase Library Manual The GNUstep CoreBase Library is a free software, cross-platform general-purpose utility library implementing the API of Apple's Core Foundation framework. It works on many UNIX-like platforms such as GNU/Linux, FreeBSD, OpenBSD, NetBSD and Windows, and is frequently tested on x86, AMD64 and ARM CPU architectures. GNUstep CoreBase provides abstractions to common data types such as strings, raw data, numbers, arrays and dictionaries, supports internationalization by providing native support for Unicode strings and locale-based formatting, and includes a suite of utilities for property lists, run loops, sockets and much more. The library is part of the GNU Project and licensed under the GNU General Public License version 2.1 or a later version. \tableofcontents \section Overview Overview - \ref ConfiguringAndCompiling - \ref CompilingApplications \section Examples Examples - \ref ExampleEXUInt32 \section LibraryReference Library Reference \#include
Opaque Type References Utilities GNUstep Additions
\ref CFAllocatorRef "CFAllocator" \ref BaseUtils \ref CharUtils
\ref CFArrayRef "CFArray" \ref CFByteOrderUtils \ref UnicodeUtils
\ref CFAttributedStringRef "CFAttributedtring" \ref CFRuntimeUtils
\ref CFBagRef "CFBag" \ref CFSocketUtils
\ref CFBinaryHeapRef "CFBinaryHeap" \ref CFStreamUtils
\ref CFBitVectorRef "CFBitVector" \ref TimeUtils
\ref CFBooleanRef "CFBoolean" \ref CFURLAccessUtils
CFBundle (unimplemented)
\ref CFCalendarRef "CFCalendar"
\ref CFCharacterSetRef "CFCharacterSet"
\ref CFDataRef "CFData"
\ref CFDateRef "CFDate"
\ref CFDateFormatterRef "CFDateFormatter"
\ref CFDictionaryRef "CFDictionary"
\ref CFErrorRef "CFError"
CFFileDescriptor (unimplemented)
\ref CFLocaleRef "CFLocale"
CFMessagePort (unimplemented)
\ref CFMutableArrayRef "CFMutableArray"
\ref CFMutableAttributedStringRef "CFMutableAttributedString"
\ref CFMutableBagRef "CFMutableBag"
\ref CFMutableBitVectorRef "CFMutableBitVector"
\ref CFMutableCharacterSetRef "CFMutableCharacterSet"
\ref CFMutableDataRef "CFMutableData"
\ref CFMutableDictionaryRef "CFMutableDictionary"
\ref CFMutableSetRef "CFMutableSet"
\ref CFMutableStringRef "CFMutableString"
CFNotificationCenter (unimplemented)
\ref CFNullRef "CFNull"
\ref CFNumberRef "CFNumber"
\ref CFNumberFormatterRef "CFNumberFormatter"
CFPlugIn (unimplemented)
CFPlugInInstance (unimplemented)
\ref CFPropertyListRef "CFPropertyList"
\ref CFReadStreamRef "CFReadStream"
\ref CFRunLoopRef "CFRunLoop"
\ref CFRunLoopObserverRef "CFRunLoopObserver"
\ref CFRunLoopSourceRef "CFRunLoopSource"
\ref CFRunLoopTimerRef "CFRunLoopTimer"
\ref CFSetRef "CFSet"
\ref CFSocketRef "CFSocket"
\ref CFStringRef "CFString"
CFStringTokenizer (unimplemented)
\ref CFTimeZoneRef "CFTimeZone"
\ref CFTreeRef "CFTree"
\ref CFTypeRef "CFType"
\ref CFURLRef "CFURL"
CFUserNotification (unimplemented)
\ref CFUUIDRef "CFUUID"
\ref CFWriteStreamRef "CFWriteStream"
\ref CFXMLNodeRef "CFXMLNode (deprecated)"
\ref CFXMLParserRef "CFXMLParser (deprecated)"
\ref CFXMLTreeRef "CFXMLTree (deprecated)"
*/ gnustep-corebase-0.2/ChangeLog0000644000175000017500000024370314551015633015471 0ustar yavoryavor2021-09-30 Frederik Seiffert * Source/CFDate.c: Fix logic in CFGregorianDateIsValid() 2021-09-30 Frederik Seiffert * Source/CFString.c, * Source/config.h.in, * configure, * configure: Use unorm2 API instead of deprecated unorm 2021-03-22 Frederik Seiffert * Source/CFRunLoop.c, * Source/CFRuntime.c * Source/CFSocket.c * Source/CFStream.c * Source/CFStringEncoding.c * Source/CFURLAccess.c * Source/config.h.in, * configure, * configure: Fixed support for building on Windows. CFRunLoop and directory enumeration in CFURLAccess is currently not implemented on Windows, and Windows-specific implementations of CFSocket, CFStream, and CFURLAccess are largely untested so far. 2021-03-19 Frederik Seiffert * Source/CFRunLoop.c, * Source/GSPrivate.h, * Source/config.h.in, * configure, * configure: Add support for building without pthread library. 2022-09-12 Stefan Bidigaray * configure.ac, * configure, * Source/GNUmakefile: Add ICU_CFLAGS and ICU_LIBS to CFLAGS and LIBS, respectively. Fixes issue GH-19 and GH-21. 2020-03-12 Frederik Seiffert * Source/CFNumber: Add equality and hash functions. 2020-03-10 Frederik Seiffert * Source/GSHashTable.c: Fix second hash function for double hashing collision case to avoid possible infinite loop. 2020-03-06 Frederik Seiffert * Source/GNUmakefile.in, * Source/NSCFNumber.m, * Source/NSCFType.m: Implement toll-free bridging of CFNumber to NSNumber. * Tests/CFNumber/bridge.m: Add CFNumber bridging tests. 2019-11-15 Stefan Bidigaray * Source/CFNumber.c: Implement toll-free bridging in CFNumberGetValue(). 2019-11-09 Stefan Bidigaray * Source/CFNumber.c: Implement partial toll-free bridging. 2019-11-09 Stefan Bidigaray * aclocal.m4, * configure, * configure.ac: Update configure to use pkg-config instead of icu-config. 2017-08-29 Stefan Bidigaray * Source/CFRuntime.c, * Source/GSObjCRuntime.h, * Source/config.h.in, * configure, * configure.ac: Clean up and simplify configure tests. 2017-08-25 Stefan Bidigaray * Headers/CoreFoundation/CFBase.h.in, * Headers/CoreFoundation/CFAvailability.h: Move availibility macros to the appropriate header. * configure, * configure.ac: Clean up configure macros. 2017-08-23 Stefan Bidigaray * Headers/CoreFoundation/CFBase.h.in * Source/CFRuntime.c: Implement CFAutorelease(), which is supposed to send a CF object into an autorelease pool regardless of ARC. 2017-08-04 Daniel Ferreira * Headers/CoreFoundation/CFBase.h.in: Create the CF_OPTIONS() macro, an equivalent to CF_ENUM() for defining enumerations. 2017-08-04 Daniel Ferreira * Headers/CoreFoundation/CFRunLoop.h: Redefine the `CFRunLoopActivity` enum type to allow it to be mixed in bitwise-OR operations with other types in C++, thus increasing compatibility with the reference platform. 2017-08-04 Daniel Ferreira * Headers/CoreFoundation/CFBase.h.in * Source/CFRuntime.c: Automatic Reference Counting (ARC) can only handle the memory management of Objective-C objects and not that of C structs. To preserve the ease of toll-free bridging, ARC has added the __bridge_retained and __bridge_transfer directives for casting between these two types. __bridge_retained specifies that an Objective-C object should be cast to a C struct and that the struct needs to be manually released. __bridge_transfer works the other way, and turns a C struct that would need a manual release into an object that is now managed by ARC and no longer needs that. The Apple CoreFoundation API specifies the CFBridgingRetain() and CFBridgingRelease() functions that do, respectively, the same things these directives do. This commit implements these two functions exactly as the compiler would handle the directives. This change was co-authored with Stefan Bidigaray. 2017-06-30 Daniel Ferreira * Source/CFPropertyList.c: The CFPropertyListCreateWithStream() documentation allows for a zero-valued streamLength parameter, which directs the implementation to read a stream until its end. A bug in CoreBase caused this case to pass a negative buffer length to read(2), which caused a segfault. We fix this issue here. * Headers/CoreFoundation/GSCharacter.h: In the valid case that we passed a destination parameter to GSUnicodeFromEncoding() that was smaller than the bytes read in the source, CoreBase should continue reading the source and just not write to the destination buffer. GSUTF16CharacterAppend() did not guarantee that when converting from UTF8 this would be the case, which caused a segfault due to a buffer overflow. We fix this issue here. 2017-06-30 Daniel Ferreira * .gitignore: Add a .gitignore file to CoreBase to avoid committing build products into the tree. 2017-06-05 Daniel Ferreira * Source/CFRunLoop.c: When calling CFRunLoopRemoveTimer() and other CFRunLoopRemove*() functions on CoreBase with kCFRunLoopCommonModes, CFRunLoopCommonModesRemoveFunc() would be called, which in turn called CFRunLoopRemove*() again, generating a deadlock. This issue is fixed by calling the no-lock counterparts of the remove functions from CFRunLoopCommonModesRemoveFunc(), as is done on CFRunLoopCommonModesAddFunc() and CFRunLoopCommonModesContainFunc(). 2017-06-01 Daniel Ferreira * Headers/CoreFoundation/CFBase.h.in: Define CF_RETURN_* macros on CFBase. 2017-05-09 Ivan Vucica * Headers/CoreFoundation/CFBase.h.in: CFEnum macro for type definitions. Patch by Daniel Ferreira . 2016-07-27 Stefan Bidigaray * Source/GNUmakefile: Added CFStringInitialize.c to build. 2016-07-09 Stefan Bidigaray * Source/CFConstantString.c, * Source/CFString.c: Move constant string initialization to separate file. * Source/CFRuntime.c: Initialize CFConstantString. * Source/GSObjCRuntime.h: Include GSPrivate.h to avoid error. 2016-07-08 Stefan Bidigaray * configure, * configure.ac: Put CC/CXX test after checking for gnustep-config. 2015-09-23 Riccardo Mottola * configure.ac, * configure: Use gnustep make compilers if CC/CXX not overridden. 2015-07-12 Stefan Bidigaray * Source/CFPropertyList.c: Fix string size bug. * Source/CFString.c: Fix string conversion bug. 2015-07-10 Stefan Bidigaray * Doxyfile: Adjust documentation options. * Documentation/MainPage.dox: Fix typo. 2015-07-10 Stefan Bidigaray * Doxyfile: Updated. * Headers/CoreFoundation/CFArray.h, * Headers/CoreFoundation/CFAttributedString.h, * Headers/CoreFoundation/CFBag.h, * Headers/CoreFoundation/CFBase.h.in, * Headers/CoreFoundation/CFBinaryHeap.h, * Headers/CoreFoundation/CFBitVector.h, * Headers/CoreFoundation/CFByteOrder.h, * Headers/CoreFoundation/CFCalendar.h, * Headers/CoreFoundation/CFCharacterSet.h, * Headers/CoreFoundation/CFData.h, * Headers/CoreFoundation/CFDateFormatter.h, * Headers/CoreFoundation/CFDate.h, * Headers/CoreFoundation/CFDictionary.h, * Headers/CoreFoundation/CFError.h, * Headers/CoreFoundation/CFLocale.h, * Headers/CoreFoundation/CFNumberFormatter.h, * Headers/CoreFoundation/CFNumber.h, * Headers/CoreFoundation/CFPropertyList.h, * Headers/CoreFoundation/CFRunLoop.h, * Headers/CoreFoundation/CFRuntime.h, * Headers/CoreFoundation/CFSet.h, * Headers/CoreFoundation/CFSocket.h, * Headers/CoreFoundation/CFStream.h, * Headers/CoreFoundation/CFString.h, * Headers/CoreFoundation/CFTimeZone.h, * Headers/CoreFoundation/CFTree.h, * Headers/CoreFoundation/CFURLAccess.h, * Headers/CoreFoundation/CFURL.h, * Headers/CoreFoundation/CFUUID.h, * Headers/CoreFoundation/CFXMLNode.h, * Headers/CoreFoundation/CFXMLParser.h, * Headers/CoreFoundation/GSCharacter.h: Added/modified documentation. * Documentation/CompilingApplications.dox, * Documentation/ConfiguringAndCompiling.dox, * Documentation/DoxygenLayout.xml, * Documentation/ExampleEXUInt32.dox, * Documentation/MainPage.dox: Initial documentation pages. * Examples/EXUInt32.c, * Examples/EXUInt32.h: Added first library usage example. 2015-07-09 Stefan Bidigaray * Source/config.h.in, * configure, * configure.ac: Add better checks for features. 2015-07-09 Stefan Bidigaray * Source/CFPropertyList.c: Implemented reading and writing OpenStep format property lists. * Tests/CFPropertyList/openstep.m: Simple tests for OpenStep format property lists. 2015-06-26 Stefan Bidigaray * Headers/CoreFoundation/GSCharacter.h, * Source/GSUnicode.c: Modified UTF conversion functions slightly to better support conversions. * Source/CFURL.c: Rewrite CFURL function that replaces percent escaped strings. 2015-06-24 Stefan Bidigaray * Headers/CoreFoundation/GSCharacter.h, * Headers/CoreFoundation/GSUnicode.h, * Source/GSUnicode.c: Introduce new Unicode conversion functions. * Source/GSUnicode.h: Replaced by public GSUnicode.h header. * Source/CFString.c, * Source/CFURL.c: Modify code to use new conversion functions. * Source/CFNumberFormatter.c: Fix bug exposed by new Unicode functions. 2015-06-23 Stefan Bidigaray * Source/CFBundle.m, * Source/NSCFData.m, * Source/NSCFError.m, * Source/NSCFLocale.m, * Source/NSCFString.m: Cast between NS and CF types to avoid compiler warnings. 2015-03-13 Stefan Bidigaray * Headers/CoreFoundation/CFBase.h.in, * Headers/CoreFoundation/CFError.h: Do not define CF types as Objective C objects. 2015-02-20 Stefan Bidigaray * Source/CFRuntime.c: Do nothing if CFRetain/CFRelease are called on small objects. * Source/GSObjCRuntime.h: Cast to unsigned int to avoid warning. 2015-02-19 Stefan Bidigaray * Source/GSObjCRuntime.h: Check for small objects. 2015-02-19 Stefan Bidigaray * Headers/CoreFoundation/CFArray.h, * Headers/CoreFoundation/CFBag.h, * Headers/CoreFoundation/CFData.h, * Headers/CoreFoundation/CFDate.h, * Headers/CoreFoundation/CFDictionary.h, * Headers/CoreFoundation/CFSet.h, * Headers/CoreFoundation/CFURL.h: Do not define CF types as Objective C objects. * Headers/CoreFoundation/GSCharacter.h: Fix bug in UTF-8 conversion function. * Source/NSCFArray.m, * Source/NSCFData.m, * Source/NSCFError.m: Explicitly cast NS to CF objects. 2015-02-16 Stefan Bidigaray * Source/NSCFDictionary.m: Add category to match class definition. * Source/NSCFType.m: Use correct number of classes to register. 2015-02-14 Stefan Bidigaray * Headers/CoreFoundation/GSCharacter.h: Fix minor compare bug. 2015-02-13 Stefan Bidigaray * Source/GSUnicode.c: Completed isnan/isinf functions for long double. 2015-02-12 Stefan Bidigaray * Source/config.h.in, * configure, * configure.ac: Correctly handle existence of compatible GCD library. * Source/GSUnicode.c: Temperarily disable 96-bit long double error. 2015-01-30 Stefan Bidigaray * Source/config.h.in, * configure, * configure.ac: Disable check for GCD as it is broken. 2014-12-09 Stefan Bidigaray * Headers/CoreFoundation/GSCharUtilities.h: Fixed function case. * Source/CFString.c: Use new whitespace function. 2014-12-09 Stefan Bidigaray * Headers/CoreFoundation/GSCharUtilities.h: Added whitespace function, implemented UTF-8 get function, and renamed UTF-8 trailing bytes count function. * Source/GSUnicode.c: Use renamed function. * Tests/CFLocale/displayvalues.m, * Tests/CFTimeZone/general.m: Remove unreliable tests. 2014-11-17 Stefan Bidigaray * Headers/CoreFoundation/GSCharUtilities.h, * Headers/CoreFoundation/GSCharacter.h: Rename file. * Headers/CoreFoundation/GSUnicode.h: Add API for Unicode string. Not yet part of build and install. * Source/GSUnicode.c: Update part of the code to use new character utilities. * Source/GSUnicode.h: remove redundant functionality. This file will eventually be completely superceded by GSCharacter.h and GSUnicode.h. 2014-11-13 Stefan Bidigaray * configure, * configure.ac: Use '--without-' to compile without a specific library. * Source/config.h.in: Define sizeof double and long double. 2014-11-12 Stefan Bidigaray * Headers/CoreFoundation/GSCharUtilities.c: Add new public character utilities API. 2014-10-17 Stefan Bidigaray * Source/GSUnicode.c: Rework some of the string formatting code. 2014-10-07 Stefan Bidigaray * Source/GSUnicode.c: Initial double formatting implementation. Only supports inf and nan for now. * Tests/CFString/format_errors.m: Test for common errors. * Tests/CFString/format_float.m: Test for inf and nan. 2014-09-26 Stefan Bidigaray * Source/CFRuntime.c: Handle NULL pointer correctly. * Source/CFString.c: Switch to using GSUnicodeFormatWithArguments. * Source/CFStringFormat.c: Deleted. New formatting facilities available. * Source/GSUnicode.c: Fixed many bugs found by test suite. * Tests/CFString/format.m: Deleted. * Tests/CFString/format_int.m: Integer only tests. * Tests/CFString/format_misc.m: Miscellaneous tests, including string, character and pointer. 2014-09-19 Stefan Bidigaray * Source/CFSocket.c: Fix build without libdispatch. * Headers/CoreFoundation/CFBase.h.in, configure, configure.ac: Use correct sign for data types. 2014-05-06 Lubos Dolezel * Source/CFRunLoop.c, Headers/CoreFoundation/CFRunLoop.h: CFRunLoop improvements & fixes * Source/CFArray.c: Fixes * Source/CFSocket.c: CFSocket integration with CFRunLoop * Source/config.h.in, configure, configure.ac: libdispatch detection * Source/GNUmakefile.in, Source/NSCFType.m, Source/NSCFDate.m, Source/CFDate.c: CFDateRef toll-free bridging 2014-04-20 Lubos Dolezel * Source/CFRunLoop.c, Tests/CFRunLoop/timers.m: CFRunLoop timer fixes and tests 2014-04-18 Lubos Dolezel * Source/CFRunLoop.c, Tests/CFRunLoop/source.m: CFRunLoop impl that passes the test 2014-04-16 Lubos Dolezel * Source/CFRunLoop.c, Source/CFRuntime.c: Work on CFRunLoop 2014-02-19 Stefan Bidigaray * configure, * configure.ac: Use autoconf's built-in functions and introduce function to check the architecture's data model. * Headers/CoreFoundation/CFBase.h, * Headers/CoreFoundation/CFBase.h.in: Used data model information. * Source/CFLocale.c: Use CF defined type (UInt32). 2014-02-03 Lubos Dolezel * Source/CFStream.c: Initial CFReadStream implementation, generalization * Tests/CFStream/write.m: Tests for CFWriteStream * Tests/CFStream/read.m: Test for CFReadStream * Source/NSCFInputStream.m, * Source/NSCFOutputStream.m: TFB for CFRead/WriteStream * Source/CFError.c: Prevent crash on NULL user dictionary 2014-02-02 Lubos Dolezel * Source/CFStream.c: Initial CFWriteStream implementation 2014-01-14 Lubos Dolezel * Source/NSBundle.m: Add CFBundleCopyResourcesDirectoryURL 2013-08-11 Lubos Dolezel * Source/GSMemory.h: Introduce wrappers for platform-dependent memory functions. * Source/GSUnicode.c, * Source/GSUnicode.h: Add printf-type functions. Not currently used. 2013-08-11 Lubos Dolezel * Source/CFBundle.m: Added CFBundleCopyPrivateFrameworksURL and CFBundleCopyAuxiliaryExecutableURL * Tests/CFLocale/bridge.m: Added the other half of tests, courtesy of mahimahi42 2013-08-11 Lubos Dolezel * Tests/CFString/objc_bridge_from_cf.m: mark -getBytes* tests as hopeful * Source/CFBundle.m: CFBundle as a proper CF type 2013-08-10 Lubos Dolezel * Source/CFStringEncoding.c: Fixed a crash in CFStringGetListOfAvailableEncodings() * Source/CFBundle.m: added many (but not all) CFBundle functions 2013-08-08 Lubos Dolezel * Source/CFString.c: TFB support in CFStringTransform 2013-08-08 Lubos Dolezel * Tests/CFString/hash.m: Make the test work on big endian machines * Tests/CFString/normalize.m, * Source/CFString.c: make CFStringNormalize() work, support TFB 2013-08-06 Lubos Dolezel * Tests/CFString/hash.m, * Source/CFString.c: Always use UTF-16 in CFStringHash() 2013-07-25 Stefan Bidigaray * Source/CFPropertyList.c: Add some property list writing code. * Source/CFRuntime.c, * Source/GSPrivate.h: Remove unneeded GSTypeCreateCopy() function. 2013-07-25 Stefan Bidigaray * Source/CFArray.c, * Source/CFAttributedString.c, * Source/CFBag.c, * Source/CFData.c, * Source/CFDate.c, * Source/CFDictionary.c, * Source/CFError.c, * Source/CFRuntime.c, * Source/CFNumber.c, * Source/CFLocale.c, * Source/CFTimeZone.c, * Source/CFSet.c, * Source/CFString.c, * Source/CFRunLoop.c, * Source/CFURL.c: Include new headers. * Source/GSPrivate.h: Move functionality. * Source/GSObjCRuntime.h: Move ObjC runtime functionality to separate header. * Source/GSUnicode.c, * Source/GSUnicode.h: Move Unicode conversion functions to separate header. * Source/CFStringEncoding.c: Use GSUnicode.h. 2013-07-21 Stefan Bidigaray * Source/CFArray.c: Use new sort function. 2013-07-21 Stefan Bidigaray * Source/GSCArray.h, * Source/GSCArray.c: Add function to sort and search C arrays. 2013-07-14 Stefan Bidigaray * configure.ac: Check for math library. * Source/CFAttributedString.c, * Source/CFData.c, * Source/CFError.c, * Source/CFDate.c, * Source/CFNumber.c, * Source/CFRunLoop.c, * Source/CFRuntime.c, * Source/CFURL.c: Use CF_OBJC_FUNCDISPATCHV. * Source/CFStringEncoding.c: Fix character Unicode conversion. * Source/GSHashTable.h: Use GS_PRIVATE for hidden functions. * Source/GSPrivate.h: Add GS_PRIVATE for hidden visibility functions. Remove CF_OBJC_FUNCDISPATCH[012345] in favor of CF_OBJC_FUNCDISPATCHV. 2013-07-14 Stefan Bidigaray * Source/CFStringEncoding.c: Fix ASCII conversion. 2013-07-03 Ivan Vucica * Source/CFNumber.c: Improved the way INFINITY and NAN are defined, preferring to only get them from , and using hacks in case does not define them for some reason. * Headers/CoreFoundation/CFBase.h: Replaced manual definitions of MAC_OS_X_VERSION macros with inclusion of GSVersionMacros.h. This fixes the issue where the macros were sometimes defined multiple, and fixes the issue where the macros were (by now) no longer matching values in GNUstep Base. 2013-06-13 Stefan Bidigaray * configure.ac: Check for existance of ICU headers. * Source/CFString.c: Only build ICU support if headers are installed. * Source/CFStringEncoding.c: Incorporate nonlossy ASCII conversion function. Check ICU headers. * Source/CFRuntime.c: Only check for small objects if they are supported. * Source/NSCFTimeZone.m, * Tests/CFLocale/bridge.m, * Tests/CFDictionary/bridge.m, * Tests/CFArray/bridge.m: Include Foundation/NSString.h. 2013-06-08 Lubos Dolezel * Source/CFRuntime.c: fix a TFB crash with small objects * Source/GNUmakefile.in, * Tests/GNUmakefile.super: remove a macro that causes all OS X Base methods to be unavailable * Source/CFTimeZone.c, * Source/NSCFTimeZone.m, * Tests/CFTimeZone/bridge.m: TFB support for CFTimeZone 2013-06-06 Lubos Dolezel * Tests/CFArray/bridge.m, * Source/NSCFArray.m, * Source/CFArray.c: TFB for CFArray and other fixes 2013-06-06 Lubos Dolezel * Tests/CFDictionary/bridge.m, * Source/CFDictionary.c, * Source/NSCFDictionary.m: TFB for CFDictionary * Source/NSCFData.m: fixing the _cfGetTypeID call * Source/NSCFError.m: fixing the _cfGetTypeID call 2013-06-06 Lubos Dolezel * Source/NSCFType.m: leave hash calculation to NS classes, so that they match when compaing NS and CF objects * Tests/CFLocale/bridge.m * Source/NSCFLocale.m, * Source/CFLocale.c: TFB for CFLocale 2013-06-06 Lubos Dolezel * Source/NSCFString.m, * Tests/CFString/objc_bridge.m, * Tests/CFString/objc_bridge_from_cf.m, * Source/CFString.c: Improved TFB for CFString 2013-06-06 Lubos Dolezel * Source/CFSet.c, * Source/NSCFSet.m, * Tests/CFSet/objc_bridge.m: Add CFSet bridging support * Source/GSPrivate.h: Add variable argument helper macros 2013-03-16 Fred Kiefer * Source/CFPropertyList.c, * Source/CFString.c, * Source/CFRunLoop.c: Remove compiler warnings * Source/CFURL.c: Remove compiler warnings and get tests to work. * Source/CFStringEncoding.c: Add missing code for UTF16. * Source/NSCFString.m: Comment out all methods where super class code is more complete. 2012-12-20 Stefan Bidigaray * Source/CFStringEncoding.c: Added UTF-32 conversion. Added non-lossy ASCII conversion functions. Consolidated some frequently used constructs into macros for easy maintenance. * Source/CFString.c: Short-cut for converting UTF-16 to UTF-16. * Tests/CFString/encodings.m: Added another test. 2012-12-18 Stefan Bidigaray * Source/CFStringEncoding.c: Added local function to convert UTF-32 to/from UTF-16 (unused at this time). * Source/CFString.c: Fix bugs related to changes to GSStringEncodingToUnicode(). * Tests/CFString/encodings.m: Add test for some of the changes made to Unicode conversion. 2012-12-17 Stefan Bidigaray * Source/CFStringEncoding.c: Add local function to converted UTF-8 to/from UTF-16. * Source/CFString.c: Modify functions for getting characters. * Source/NSCFError.m: * Source/NSCFData.m: Include NSString.h to avoid compiler warning. 2012-12-12 Stefan Bidigaray * Source/config.h.in: * configure: * configure.ac: Add test for endianess and size of void *. * Source/GSPrivate.h: Use result of endianess test. 2012-11-11 Stefan Bidigaray * Source/CFRuntime.c: * Source/NSCFType.m: * Source/NSCFString.m: Apply modified version of Lubos Dolezel's patch. * Tests/CFString/objc_bridge.m: Tests for toll-free bridge. 2012-10-12 Stefan Bidigaray * Source/CFSocket.c: Implement CopyAddress functions. 2012-10-09 Stefan Bidigaray * Headers/CoreFoundation/CFSocket.h: Use winsock on Windows. * Source/CFSocket.c: Implement Create and Address functions. 2012-09-16 Stefan Bidigaray * Headers/CoreFoundation/CFSocket.h: Use winsock on Windows. * Source/CFSocket.c: Implement Create and Address functions. 2012-09-16 Stefan Bidigaray * Source/NSCFType.m: Call the CoreBase initialization code before trying to initialize the bridged classes. 2012-09-04 Stefan Bidigaray * Headers/CoreFoundation/CoreFoundation.h: * Headers/CoreFoundation/CFSocket.h: * Source/GNUmakefile.in: * Source/CFSocket.c: Add CFSocket skeleton. 2012-09-03 Stefan Bidigaray * Source/CFRunLoop.c: Implement add, remove and search functions. 2012-08-30 Stefan Bidigaray * Source/CFRunLoop.h: Add missing bits. * Source/CFString.c: Initialize CFRunLooop contant strings. * Source/CFRunLoop.c: Implement create functions. 2012-08-27 Stefan Bidigaray * Source/GSPrivate.h: * Source/CFRuntime.c: Add a private deallocation function. * Source/NSCFArray.m: * Source/NSCFData.m: * Source/NSCFError.m: * Source/NSCFString.m: * Source/NSCFType.m: Implement -dealloc. 2012-08-16 Stefan Bidigaray * Header/CoreFoundation/CFRunLoop.h: * Source/GNUmakefile.in: * Source/CFRunLoop.c: * Source/CFRuntime.c: Add CFRunLoop skeleton. 2012-08-16 Stefan Bidigaray * Source/CFStream.m: Delete. * Source/CFStream.c: Add CFStream skeleton. * Source/GNUmakefile: Include CFStream.c to build. 2012-08-09 Stefan Bidigaray * Source/CFDate.c: Added copy, equal and hash functions. * Source/CFNumber.c: Added copy function. * Source/CFPropertyList.c: Implement CFPropertyListCreateDeepCopy(). * Source/GSPrivate.h: * Source/CFRuntime.c: Added a function to copy CFTypeRefs. 2012-08-05 Stefan Bidigaray * Source/GNUmakefile.in: Include CFPropertyList.c in build. * Source/CFPropertyList.c: Implement CFPropertyListIsValid(). * Tests/CFPropertyList/validate.m: Tests for CFPropertyListIsValid(). 2012-08-05 Stefan Bidigaray * Headers/CoreFoundation/CoreFoundation.h: Include CFPropertyList.h and CFStream.h. * Headers/CoreFoundation/CFRunLoop.h: Protect against multiple inclusion. * Headers/CoreFoundation/CFBase.h: Fix CFPropertyListRef definition. * Headers/CoreFoundation/CFStream.h: Include CFRunLoop.h. * Source/GNUmakefile.in: Install CFPropertyList.h and CFStream.h. 2012-08-05 Stefan Bidigaray * Source/CFDictionary.c: Implement CFDictionaryApplyFunction(). * Source/GSHashTable.c: Reduce count when key-value pair is removed. 2012-08-04 Stefan Bidigaray * Tests/CFTesting.h: Implement a version of pass() and PASS() so that testing of Corebase types are not dependent of ObjC classes. 2012-08-04 Stefan Bidigaray * Headers/CoreFoundation/CFPropertyList.h: * Source/CFPropertyList.m: Replace ObjC wrapper with a C implementation. * Source/CFPropertyList.c: Stub implementation for CFPropertyList. functions. 2012-08-04 Stefan Bidigaray * Source/CFXMLNode.c: Rearrange __CFXMLNode structure. * Source/CFXMLParser.c: Implement CFXMLParserClass and CFXMLParserCreate(). 2012-07-26 Adam Fedor * Version 0.1 2012-07-21 Stefan Bidigaray * Source/CFStringFormat.c: Use pointer value when formatting a pointer. 2012-07-19 Stefan Bidigaray * Source/CFStringFormat.c: Always format floating numbers and endianness problem in character formatting. 2012-07-17 Stefan Bidigaray * configure.ac: * configure: Fix typo. * Source/GSPrivate.h: Define ObjC macros for libobjc2, too. * Tests/CFString/create.m: Fix for big endian machines. * Tests/CFNumber/general.m: Be more verbose. 2012-07-17 Stefan Bidigaray * Source/config.h.in: * configure.ac: * configure: Correctly detect libobjc2 on some systems. * Source/CFLocal.c: Don't search past the end of the _kCFLocaleValues array. 2012-07-16 Stefan Bidigaray * configure.ac: * configure: Use gnustep-config to find include directories. * COPYING: * COPYING.LIB: * INSTALL: * README: Add distribution files. 2012-06-08 Stefan Bidigaray * Source/CFCharacterSet.c: Avoid memory leak. * Source/CFString.c: Simplify constant string generation. * Source/CFTimeZone.c: Fix bug in CFTimeZoneGetDaylightSavingTimeOffset(). 2012-06-07 Stefan Bidigaray * Source/ GSHashTable.c: Correctly hash keys when a hash function is provided. * Source/CFTimeZone.c: Implement abbreviation dictionary. * Tests/CFTimeZone/general.m: Uncomment abbreviation dictionary test. 2012-05-28 Stefan Bidigaray * Source/CFTimeZone.c: Avoid memory leak. * Source/CFURL.c: Correctly copy file system path. * Source/CFBase.c: Do a memory copy of the context. * Source/CFCharacterSet.c: Correctly calculate string length. * Tests/CFCharacterSet/basic.m: New tests. 2012-05-27 Stefan Bidigaray * Source/CFTimeZone.c: * Source/CFURL.c: * Source/CFString.c: * Source/CFCalendar.c: * Source/CFAttributedString.c: * Source/CFLocale.c: * Source/CFDateFormatter.c: * Source/CFXMLParser.c: * Source/CFURLAccess.c: Fix some bugs found by static analyzer. * Source/NSCFError.m: Avoid compiler warnings. 2012-05-27 Stefan Bidigaray * Source/NSCFType.m: Remove unneede call to Objective-C runtime. * Source/CFCalendar.c: * Source/CFLocale.c: * Source/CFDateFormatter.c: * Source/CFStringUtilities.c: * Source/CFNumberFormatter.c: * Source/GSPrivate.h: Modify function to get the locale as a C string. * Source/CFArray.c: Allocate the correct amount of memory. * Tests/CFTree/basic.m: Fix premature call to release. * Tests/CFURL/create.m: Mark test as hopeful. * configure.ac: * configure: Remove option to build without ICU. * autom4te.cache/: Remove. 2012-05-16 Stefan Bidigaray * Source/CFLocale.c: * Source/CFURL.c: * Tests/CFLocale/displayvalues.m: * Tests/CFTimeZone/general.m: * Tests/CFURL/create.m: CoreFoundation compatibility fixes. 2012-05-11 Stefan Bidigaray * Source/CFURL.c: Correctly set resource specifier location. * Tests/CFURL/create.m: Add test. 2012-05-11 Stefan Bidigaray * Source/GSFunctions.c: Fixed bug in GSBSearch (). * Source/CFAttributedString.c: Implemented mutable attributed strings. * Tests/CFAttributedString/mutable.m: New tests. 2012-05-06 Stefan Bidigaray * Source/GSFunctions.c: (GSBSearch) Return index of array item including value. * Source/CFTimeZone.c: Adapt to this change and fix time calculation bug. * Tests/CFTimeZone/general.m: Fix tests. * Source/CFAttributedString.c: Added code to copy and create mutable instances. * Tests/CFAttributedString/general.m: Added more tests. 2012-05-06 Stefan Bidigaray * configure.ac: Display error if zoneinfo directory cannot be found. * Source/CFCalendar.c: Fix CFCalendarGetTimeRangeOfUnit(). * Tests/CFArray/mutablearray.m: * Tests/CFAttributedString/general.m: * Tests/CFBinaryHeap/general.m: Avoid compiler warnings. * Tests/CFCalendar/basic.m: * Tests/CFNumberFormatter/parse.m: * Tests/CFNumber/general.m: * Tests/CFLocale/displayvalues.m: * Tests/CFURL/create.m: Fix tests based on results from OS X. 2012-05-05 Stefan Bidigaray * configure: * configure.ac: Add test for zoneinfo directory. * Source/tzfile.h: Remove TZDIR define. * Source/config.h.in: Add TZDIR define based on configure's findings. * Source/CFTimeZone.c: Search for * Tests/CFTimeZone/general.m: Added a few new tests to CFTimeZone. 2012-05-01 Stefan Bidigaray * Source/CFAttributedString.c: Implement CFAttributedStringCreate(). * Tests/CFAttributedString/: Add simple tests. 2012-04-27 Stefan Bidigaray * Source/CFRuntime.c: Fix incompatibility in retain/release. * Source/CFLocale.c: * Source/CFNumberFormatter.c: Do not release NULL pointer. 2012-04-27 Stefan Bidigaray * Source/CFTimeZone.c: Correctly generate time zone data. * Source/CFCalendar.c: Use CFTimeZone when opening a new calendar. * Tests/CFCalendar/basic.m: * Tests/CFLocale/displayvalues.m: * Tests/CFURL/create.m: Fix tests. 2012-04-27 Stefan Bidigaray * Source/CFTimeZone.c: Pass correct data size. * Tests/CFTimeZone/basic.m: Fix tests. * Tests/CFLocale/values.m: Fix error in previous commit. 2012-04-26 Stefan Bidigaray * Source/CFTimeZone.c: Correctly calculate GMT offset for zone name. * Source/CFDateFormatter.c: Reset formatter before using it. * Source/CFStringUtilities.c: Fix bug in find utility. 2012-04-26 Stefan Bidigaray * Source/CFBinaryHeap.c: Fix bug when removing minimum value. * Tests/CFString/general.m: * Tests/CFCalendar/basic.m: * Tests/CFNumberFormatter/parse.m: * Tests/CFArray/mutablearray.m: * Tests/CFArray/create.m: * Tests/CFBinaryHeap/general.m: * Tests/CFURLAccess/basic.m: * Tests/CFNumber/general.m: * Tests/CFLocale/displayvalues.m: * Tests/CFLocale/values.m: * Tests/CFDateFormatter/basic.m: Fixes for 64-bit system and more verbose output to help debug. 2012-04-24 Stefan Bidigaray * Source/CFBag.c: * Source/CFTimeZone.c: * Source/CFBitVector.c: * Source/CFDictionary.c: * Source/CFString.c: * Source/CFCalendar.c: * Source/CFBase.c: * Source/CFStringFormat.c: * Source/CFSet.c: * Source/CFLocale.c: * Source/CFTree.c: * Source/CFDateFormatter.c: * Source/CFStringUtilities.c: * Source/CFXMLNode.c: * Source/CFUUID.c: * Source/CFCharacterSet.c: * Source/GSHashTable.c: * Source/CFNumberFormatter.c: * Source/CFXMLParser.c: * Source/CFStringEncoding.c: * Source/CFDate.c: * Source/CFArray.c: * Source/GSHashTable.h: * Source/CFRuntime.c: * Headers/CoreFoundation/CFRuntime.h: * Headers/CoreFoundation/CFBag.h: * Headers/CoreFoundation/CFError.h: * Headers/CoreFoundation/CFStringEncodingExt.h: * Headers/CoreFoundation/CFByteOrder.h: * Headers/CoreFoundation/CFBitVector.h: * Headers/CoreFoundation/CFURL.h: * Headers/CoreFoundation/CFDictionary.h: * Headers/CoreFoundation/CFString.h: * Headers/CoreFoundation/CFCalendar.h: * Headers/CoreFoundation/CFBase.h: * Headers/CoreFoundation/CFPropertyList.h: * Headers/CoreFoundation/CFNumber.h: * Headers/CoreFoundation/CFSet.h: * Headers/CoreFoundation/CFStream.h: * Headers/CoreFoundation/CFAttributedString.h: * Headers/CoreFoundation/CFRunLoop.h: * Headers/CoreFoundation/CFLocale.h: * Headers/CoreFoundation/CFTree.h: * Headers/CoreFoundation/CFDateFormatter.h: * Headers/CoreFoundation/CFUUID.h: * Headers/CoreFoundation/CFXMLNode.h: * Headers/CoreFoundation/CFCharacterSet.h: * Headers/CoreFoundation/CFData.h: * Headers/CoreFoundation/CFNumberFormatter.h: * Headers/CoreFoundation/CFDate.h: * Headers/CoreFoundation/CFXMLParser.h: * Headers/CoreFoundation/CFArray.h: Use '/* */' comments instead of '//'. 2012-04-24 Stefan Bidigaray * Headers/CoreFoundation/CFAttributedString.h: * Source/CFAttributedString.c: * Source/CFRuntime.c: * Source/common.mk: Added CFAttributedString skeleton. 2012-04-21 Stefan Bidigaray * Source/CFURLAccess.c: Fix compiler warnings. 2012-04-21 Stefan Bidigaray * autom4te.cache: * Source/config.h.in: * configure: * configure.ac: Add configure. * Source/GSPrivate.h: Use results of configure. * Source/GNUmakefile: Move from here... * Source/GNUmakefile.in: ...to here and use results of configure. 2012-04-16 Stefan Bidigaray * Source/CFString.c: Initialize CFURLAccess string constants. * Source/CFURLAccess.c: Completed file scheme implementation. * Tests/CFURLAccess/basic.m: Added tests. 2012-04-15 Stefan Bidigaray * Headers/CoreFoundation/CoreFoundation.h: Added CFURLAccess.h * Source/CFURL.c: Implement file system representation functions. * Source/CFURLAccess.c: Implemented file/directory operations. * Tests/CFURLAccess: * Tests/CFURLAccess/TestInfo: * Tests/CFURLAccess/basic.m: Add basic CFURLAccess tests. * Tests/CFArray/create.m: Addition CFArray test. * Source/CFRuntime.c: Initialize CFBinaryHeap. 2012-04-14 Stefan Bidigaray * Headers/CoreFoundation/CFBinaryHeap.h: * Source/CFBinaryHeap.c: Implemented CFBinaryHeap. * Tests/CFBinaryHeap: Added tests. 2012-04-12 Stefan Bidigaray * Headers/CoreFoundation/CFURLAccess.h: * Source/CFURLAccess.c: * Source/common.mk: Add CFURLAccess skeleton. 2012-04-12 Stefan Bidigaray * Source/CFURL.c: * Source/CFStringFormat.c: * Source/GSPrivate.h: Use ASCII characters directly instead of their numberical value. 2012-04-11 Stefan Bidigaray * Source/CFURL.c: Fix bug in CFURL string percent unescaping. * Tests/CFURL/escaping.m: Added more tests. 2012-04-11 Stefan Bidigaray * Source/CFArray.c: Fix bug in CFArrayGetFirstIndexOfValue(). * Tests/CFArray/create.m: * Tests/CFArray/mutablearray.m: Add tests. 2012-04-10 Stefan Bidigaray * Source/CFTimeZone.c: Add code to search transition times. * Source/GSPrivate.h: Declare GSBSearch() to perform bsearches on C arrays. * Source/common.mk: * Source/GSFunctions.c: New file for functions that work on C types. * Tests/CFTimeZone/create.m: Move from here... * Tests/CFTimeZone/basic.m: ...to here and new tests. 2012-04-08 Stefan Bidigaray * Source/CFTimeZone.c: Start implementing CFTimeZone. * Tests/CFTimeZone/create.c: Added very basic tests. 2012-02-18 Stefan Bidigaray * Source/CFURL.c: Fixes to CFURLStringParse() and CFURLCopyAbsoluteURL(). * Tests/CFString/general.m: * Tests/CFLocale/displayvalues.m: * Tests/CFURL/file_system_path.m: * Tests/CFURL/create.m: Fix tests. 2012-02-16 Stefan Bidigaray * Source/CFURL.c: A little clean up. * Tests/CFURL/file_system_path.m: * Tests/CFURL/create.m: Added more tests. 2012-02-15 Stefan Bidigaray * Source/CFURL.c: Some more work on file system paths. * Tests/CFNumber/general.m: * Tests/CFLocale/create.m: Modified tests. * Tests/CFURL/create.m: Moved file system path tests from here... * Tests/CFURL/file_system_path.m: ...to here. 2012-02-14 Stefan Bidigaray * Source/CFString.c: * Source/CFStringUtilities.c: Implement function to separate strings. * CFString/general.m: Added new tests. * CFLocale/displayvalues.m: Remove some unnecessary tests. * CFURL/create.m: Added more tests. 2012-02-07 Stefan Bidigaray * Source/CFURL.c: Add "file://localhost/" to file URLs. * Tests/CFURL/create.m: Fixed tests. 2012-02-01 Stefan Bidigaray * Source/CFNumberFormatter.c: Revert back to using '*' as padding character. 2012-02-01 Stefan Bidigaray * Tests/CFNumberFormatter/format.m: * Tests/CFTree/basic.m: * Tests/CFDateFormatter/basic.m: * Tests/CFURL/create.m: First attempt at fixing tests for OS X. 2012-01-29 Stefan Bidigaray * Source/CFCharacterSet.c: Fixed bugs found with new tests. * Tests/CFCharacterSet: * Tests/CFTree: New tests. 2012-01-29 Stefan Bidigaray * Source/CFString.c: * Source/CFBase.c: * Source/CFNumber.c: * Source/CFRuntime.c: * Source/GSPrivate.h: * Source/NSCFType.m: Generate a table of constant instances to be initialized. 2012-01-29 Stefan Bidigaray * Source/CFData.c: Fix bug in CFDataEqual(). * Tests/CFData: * Tests/CFDate: New tests. 2012-01-29 Stefan Bidigaray * Source/CFError.c: * Source/CFString.c: * Source/CFLocale.c: * Source/GSPrivate.h: * Source/CFDateFormatter.c: * Source/CFNumberFormatter.c: * Source/CFXMLParser.c: * Source/NSCFType.m: Try to work around library loading issues a little better and initialize all constant instances. * Headers/CoreFoundation/CFBase.h: Define CF_EXPORT for C++ files. * Source/common.mk: * Source/Keys+Identifiers.c: Removed. 2012-01-28 Stefan Bidigaray * Source/CFUUID.c: Correctly identify OpenBSD. 2012-01-26 Stefan Bidigaray * Tests/GNUmakefile: Done print command. * Tests/CFDateFormatter/basic.m: Added some more tests. * Tests/CFURL/create.m: Marked failing tests as hopefuls. 2012-01-26 Stefan Bidigaray * Source/common.mk: Remove CFStream.h and CFPropertyList.h. * Headers/CoreFoundation/CoreFoundation.h: Remove CFPropertyList.h. 2012-01-25 Ivan Vucica * Source/common.mk: Added missing CFStream.h to list of headers. 2012-01-25 Stefan Bidigaray * Source/CFDateFormatter.c: Fix bug in CFDateFormatterCreateStringFromAbsoluteTime(). * Headers/CoreFoundation/CFDateFormatter.h: Include CFDate.h. * Tests/CFDateFormatter: Basic tests for CFDateFormatter. 2012-01-24 Stefan Bidigaray * Source/Makefile.nmake: * Source/CFString.c: * Source/GSPrivate.h: * Headers/CoreFoundation/CFString.h: * Headers/CoreFoundation/CFBase.h: Fixes for Windows. 2012-01-24 Stefan Bidigaray * Source/CFURL.c: Added class functions. * Source/GSPrivate.h: Fix for atomic operations on Windows. 2012-01-24 Stefan Bidigaray * Tests/CFArray/mutablearray.m: * Tests/CFArray/create.m: Fix tests for 64-bit systems. * Tests/CFNumberFormatter/parse.m: * Tests/CFRuntime/runtime.m: * Tests/CFString/format.m: * Tests/CFString/mutablestring.m: * Tests/CFString/create.m: Quiet compiler. 2012-01-24 Stefan Bidigaray * GNUMakefile: Include Tests as a subproject. * Tests/GNUmakefile: Add 'make check'. 2012-01-24 Stefan Bidigaray * Source/CFURL.c: Implmented function to remove dot segments in paths. * Tests/CFURL/ref_resolution.m: Added an extra test. 2012-01-23 Stefan Bidigaray * Source/CFURL.c: Resolve URIs in CFURLCopyAbsoluteURL(). * Source/CFString.c: Fixed a few big bugs in CFMutableString. * Tests/CFURL/ref_resolution.m: Added a few more tests. 2012-01-21 Stefan Bidigaray * Source/CFURL.c: Added a URI parser. * Source/GSPrivate.h: Added CHAR_V. * Tests/CFURL/create.m: Added a few more tests. * Tests/CFURL/ref_resolution.m: Tests for reference resolution. 2012-01-17 Stefan Bidigaray * Source/GNUmakefile: Remove CFPropertyList from build. * Source/CFURL.c: Basic work on Append functions. * Tests/CFURL/create.m: Add more tests. 2012-01-17 Stefan Bidigaray * Headers/CoreFoundation/CFBase.h: * Source/CFStringFormat.c: * Source/CFNumber.c: * Source/GSPrivate.h: * Source/GSHashTable.c: Fixes for 64-bit Windows. 2012-01-17 Stefan Bidigaray * Tools/: Remove make_c_interface tool. * Headers/CoreFoundation/CoreFoundation.h: * Source/GNUmakefile: * Source/common.mk: Remove CFStream from build for now. 2012-01-17 Stefan Bidigaray * Source/CFURL.c: Set correct delimiter and return an empty string instead of NULL for some functions just so the test suite won't crash. * Source/CFString.c: Fixed bug in CFStringCreateWithBytesNoCopy. * Source/CFBase.c: Fixed bug with kCFAllocatorNull. * Tests/CFURL/create.m: Ported some tests from -base. 2012-01-17 Stefan Bidigaray * Source/GSPrivate.h: Added function to guess file system encoding. * Source/CFURL.c: Added some more create functions. * Source/CFRuntime.c: Initialize CFURL class. * Tests/CFURL/create.m: Some simple create tests. 2012-01-15 Stefan Bidigaray * Source/GSPrivate.h: * Source/CFURL.c: Added percent escape replacement function. * Tests/CFURL/escaping.m: Added more tests. 2012-01-15 Stefan Bidigaray * Source/GSPrivate.h: * Source/CFURL.c: Fixed bug in percent escape function. * Tests/CFURL/escaping.m: Added first CFURL test. 2012-01-14 Stefan Bidigaray * Source/CFURL.c: * Source/CFString.c: * Source/CFStringEncoding.c: * Source/GSPrivate.h: Redesigned Unicode conversion. * Headers/CoreFoundation/CFBase.h: Define __BIG_ENDIAN__ or __LITTLE_ENDIAN__ macros for platforms do not already define them. * Headers/CoreFoundation/CFByteOrder.h: Use new endian macros. * Headers/CoreFoundation/ForFoundationOnly.h: Delete. 2012-01-11 Stefan Bidigaray * Source/CFURL.c: * Source/CFURL.m: * Source/common.mk: * Source/GNUmakefile: Replace CFURL.m with CFURL.c. CFURL still not functional. * Source/CFStringEncoding.c: * Source/CFStringFormat.c: * Source/GSPrivate.h: Moved some defines and functions to GSPrivate.h. 2012-01-11 Stefan Bidigaray * Source/CFCalendar.c: * Source/CFDateFormatter.c: * Source/CFBundle.m: Avoid compiler warnings. * Source/Keys+Identifiers.c: Fix broken build. 2012-01-08 Stefan Bidigaray * Headers/CoreFoundation/CFRuntime.h: * Headers/CoreFoundation/CFByteOrder.h: * Headers/CoreFoundation/CFString.h: * Headers/CoreFoundation/CFLocale.h: * Headers/CoreFoundation/CFNumberFormatter.h: * Source/CFString.c: * Source/CFStringFormat.c: * Source/CFBundle.m: * Source/CFLocale.c: * Source/GSPrivate.h: * Source/CFDateFormatter.c: * Source/CFStringUtilities.c: * Source/Keys+Identifiers.c: * Source/CFBinaryHeap.c: * Source/CFRuntime.c: More portability improvements. 2012-01-08 Stefan Bidigaray * Source/CFTimeZone.c: * Source/CFBitVector.c: * Source/CFCalendar.c: * Source/CFBase.c: * Source/CFStringFormat.c: * Source/CFNumber.c: * Source/tzfile.h: * Source/CFLocale.c: * Source/GSPrivate.h: * Source/Keys+Identifiers.c: * Source/CFUUID.c: * Source/CFXMLNode.c: * Source/GSHashTable.c: * Source/CFStringEncoding.c: * Source/CFXMLParser.c: * Source/CFRuntime.c: * Headers/CoreFoundation/CFRuntime.h: * Headers/CoreFoundation/CFBase.h: Improve portability. * Source/CFBinaryHeap.c: Started adding code. 2012-01-05 Stefan Bidigaray * Source/CFStringUtilities.c: Include GSPrivate.h. * Source/CFURL.c: CFURL implementation. Not included as part of build. 2012-01-03 Stefan Bidigaray * Source/CFLocale.c: * Source/CFDateFormatter.c: * Source/CFNumberFormatter.c: * Source/CFStringUtilities.c: * Source/GSPrivate.h: Introduce private function to get a C string locale. 2012-01-02 Stefan Bidigaray * Source/CFCharacterSet.c: Added predefined set support. 2012-01-02 Stefan Bidigaray * Source/CFCharacterSet.c: Added most functions. 2012-01-01 Stefan Bidigaray * Source/GNUmakefile: * Headers/CoreFoundation/CFCharacterSet.h: * Source/CFCharacterSet.c: CFCharacterSet skeleton. 2012-01-01 Stefan Bidigaray * Source/GSPrivate.h: New CAS atomic function. * Source/CFRuntime.c: Make sure corebase is only initialized once. * Source/GNUmakefile: * Source/Identifers.m: * Source/Keys+Identifiers.c: Make constant strings CFString types. * Source/CFString.c: * Source/NSCFType.m: Hack to support constant strings. 2011-12-30 Stefan Bidigaray * Headers/CoreFoundation/CFRuntime.h: * Source/CFRuntime.c: Added GC functions and variables. Not currently used in corebase. 2011-12-30 Stefan Bidigaray * Source/CFBitVector.c: Added implementation to most functinos. * Source/CFUUID.c: Fixed sscanf usage bug. 2011-12-28 Stefan Bidigaray * Source/GSPrivate.h: Added GSHashBytes(). * Source/CFString.c: Use GSHashBytes() for hashing strings. * Source/CFUUID.c: Some changes to the Windows code. * Source/GSHashTable.c: * Source/GSHashTable.h: Copy call backs. 2011-12-21 Stefan Bidigaray * Source/CFBitVector.c: Some work on CFBitVector. 2011-12-21 Stefan Bidigaray * Source/GNUmakefile: * Source/CFBitVector.c: * Source/CFBinaryHeap.c: * Headers/CoreFoundation/CFBinaryHeap.h: * Headers/CoreFoundation/CFBitVector.h: Added skeleton for CFBinaryHeap and CFBitVector. 2011-12-19 Stefan Bidigaray * Headers/CoreFoundation/CFURL.h: Populate with definitions up to Mac OS X 10.7. 2011-12-19 Stefan Bidigaray * Source/CFXMLParser.c: Added some code to CFXMLTree. * Source/CFTree.c: Changes to support CFXMLTree. * Source/Identifier.m: Added CFXMLTree error dictionary keys. * Headers/CoreFoundation/CFXMLNode.h: * Headers/CoreFoundation/CFXMLParser.h: Moved declarations to correct header. 2011-12-18 Stefan Bidigaray * Source/CFXMLNode.c: Added rest of the code. 2011-12-17 Stefan Bidigaray * Source/CFXMLNode.c: Started adding code. 2011-12-16 Stefan Bidigaray * Headers/CoreFoundation/CFXMLNode.h: * Headers/CoreFoundation/CFXMLParser.h: * Source/CFXMLNode.c: * Source/CFXMLParser.c: * Source/GNUmakefile: Added skeleton for XML types. 2011-12-16 Stefan Bidigaray * Source/CFTree.c: Added code. 2011-12-15 Stefan Bidigaray * Source/CFRuntime.c: * Source/CFTree.c: * Headers/CoreFoundation/CFTree.h: Add CFTree skeleton. 2011-12-15 Stefan Bidigaray * Source/CFBag.c: * Source/CFDictionary.c: * Source/CFSet.c: * Source/GSHashTable.c: * Source/GSHashTable.h: Redesigned GSHashTable to reduce code duplication. * Source/GSPrivate.h: Moved hash functions here. * Headers/CoreFoundation/CFBase.h: Made CFIndex and CFTypeID a long integer everywhere again, including Windows. 2011-12-10 Stefan Bidigaray * Source/CFCalendar.c: * Source/CFDate.c: * Source/GSPrivate.h: Moved UDate to CFAbsoluteTime conversion macro. * Source/CFDateFormatter.c: Added implementation to most functions. 2011-12-10 Stefan Bidigaray * Source/CFSet.c: * Headers/CoreFoundation/CFSet.h: * Source/GNUmakefile: New CFSet based on CFBag. * Source/CFBag.c: * Headers/CoreFoundation/CFBag.h: Fixed copy-and-paste error. * Source/GSHashTable.h: * Source/GSHashTable.c: Fixed definition of GSHashTableRemoveValue(). 2011-12-08 Stefan Bidigaray * Source/CFBag.c: * Headers/CoreFoundation/CFBag.h: Added CFBag. Code is based on CFDicitonary implementation. 2011-12-07 Stefan Bidigaray * Source/Identifiers.m: * Source/GNUmakefile: * Source/CFDateFormatter.c: * Headers/CoreFoundation/CFDateFormatter.h: Added CFDateFormatter skeleton. 2011-12-07 Stefan Bidigaray * Source/CFArray.c: Cleaned up CFArrayReplaceValue() and had other functions call it to insert, remove, etc. * Source/CFNumber.c: Added description function. 2011-12-06 Stefan Bidigaray * Source/objc_interface.h: * Source/atomic_ops.h: * Source/callbacks.h: * Source/threading.h: * Source/GSPrivate.h: * Source/CFError.c: * Source/CFArray.c: * Source/CFTimeZone.c: * Source/CFDictionary.c: * Source/CFCalendar.c: * Source/CFBase.c: * Source/CFStringEncoding.c: * Source/CFStringFormat.c: * Source/CFNumber.c: * Source/CFLocale.c: * Source/CFData.c: * Source/CFDate.c: * Source/CFRuntime.c: Replaced four different header files with GSPrivate.h. * Source/CFString.c: Cleaned up. 2011-12-04 Stefan Bidigaray * Source/CFCalendar.c: Clean up. 2011-12-04 Stefan Bidigaray * Source/CFLocale.c: Don't use libicu to create locale identifier. 2011-12-04 Stefan Bidigaray * Source/CFLocale.c: Clean up. 2011-12-03 Stefan Bidigaray * Source/GSHashTable.c: * Source/GSHashTable.h: Add new function to copy hash tables. * Source/CFDictionary.c: Use new GSHashTable functions. * Source/CFRuntime.c: Fix bug in _CFRuntimeGetClassWithTypeID(). 2011-12-03 Stefan Bidigaray * Source/CFDictionary.c: Worked on CFMutableDictionary functions. * Source/GSHashTable.c: * Source/GSHashTable.h: Cleaned up. 2011-12-03 Stefan Bidigaray * Source/CFDictionary.c: Added class functions. * Source/GSHashTable.c: * Source/GSHashTable.h: Added add, set, replace, and remove functions. 2011-12-02 Stefan Bidigaray * Source/CFRuntime.c: Added CFDictionary to build and fixed bug in _CFRuntimeInitStaticInstance(). * Source/GNUmakefile: Added CFDictionary.c. * Source/CFDictionary.m: Removed. * Source/GSHashTable.c: * Source/CFDictionary.c: Fixed bugs. * Source/CFString.c: Modified __CFStringMakeConstantString() to use the new CFDictionary functionality. 2011-12-02 Stefan Bidigaray * Source/CFRuntime.c: * Source/atomic_ops.h: Specify type for atomic operations. * Source/CFDiciontary.c: New CFDictionary implementation in C. 2011-12-01 Stefan Bidigaray * Source/GSHashTable.c: * Source/GSHashTable.h: Added new function to help iterate through hash table. 2011-12-01 Stefan Bidigaray * Source/GSHashTable.c: * Source/GSHashTable.h: A hash table implementation to be used in CFDictionary, CFBag and CFSet. 2011-12-01 Stefan Bidigaray * Source/CFBase.c: Move standard includes from here... * Headers/CoreFoundation/CFBase.h: ...to here. Also define CFHashCode, CFTypeID and CFOptionFlags to be a 64-bit integer, even on Windows. * Source/callbacks.h: * Source/CFArray.c: * Source/CFRuntime.c: Moved callback functions for retain/release of CFTypeRef in collection objects. 2011-11-26 Stefan Bidigaray * Source/CFRuntime.c: Do not set NSCFTypeClass in CFInitialize(). 2011-11-26 Stefan Bidigaray * Source/CFArray.c: Fixed quicksort algorithm. 2011-11-26 Stefan Bidigaray * Source/CFRuntime.c: * Source/NSCFType.h: * Source/NSCFType.m: * Source/NSCFArray.m: * Source/NSCFData.m: * Source/NSCFError.m: * Source/NSCFString.m: Make sure runtime is initialized before trying briding classes. * Source/CFStringEncoding.c: Check both MIME and IANA standard encoding names. * Headers/CoreFoundation/CFString.h: Always define CFSTR() to be __CFStringMakeConstantString(). 2011-11-25 Stefan Bidigaray * Source/NSCFType.m: * Source/NSCFString.m: * Source/atomic_ops.h: Avoid warnings on FreeBSD. * Source/CFRuntime.c: Improve thread safety. * Source/CFStream.m: Fix bug. * Source/CFStringEncoding.c: Use "MIME" instead of "IANA" standard. 2011-11-23 Stefan Bidigaray * Source/GNUmakefile: * Source/NSCFArray.m: Objective-C class for CFArray. 2011-11-23 Stefan Bidigaray * Source/CFNumber.c: Remove unneeded #if statement. * Source/CFNumberFormatter.c: Simplify SetProperty and CopyProperty functions. 2011-11-23 Stefan Bidigaray * Headers/Foundation/CFBase.h: * Source/GNUmakefile: Do not define MAC_OS_X_VERSION_MIN_ALLOWED. 2011-11-20 Stefan Bidigaray * Source/CFString.c: * Source/CFBase.c: * Source/CFStringFormat.c: * Source/CFLocale.c: * Source/CFUUID.c: * Source/CFArray.c: * Source/CFRuntime.c: * Headers/CoreFoundation/CFPropertyList.h: * Headers/CoreFoundation/CFRuntime.h: * Headers/CoreFoundation/CFNumber.h: * Headers/CoreFoundation/CFError.h: * Headers/CoreFoundation/CFTimeZone.h: * Headers/CoreFoundation/CFStream.h: * Headers/CoreFoundation/CFStringEncodingExt.h: * Headers/CoreFoundation/CFLocale.h: * Headers/CoreFoundation/CFString.h: * Headers/CoreFoundation/CFCalendar.h: * Headers/CoreFoundation/CFBase.h: * Headers/CoreFoundation/CFNumberFormatter.h: Do not include GSVersionMacros.h as this file was causing problems due objc extensions in it. 2011-11-20 Stefan Bidigaray * Source/CFArray.c: Finish runtime function for CFArray type. 2011-11-04 Stefan Bidigaray * Source/CFArray.c: Fix bugs. * Tests/CFArray: Added tests. 2011-10-29 Stefan Bidigaray * Source/CFArray.c: Finished up CFArray for now. 2011-10-27 Stefan Bidigaray * Source/GNUmakefile: * Source/CFArray.c: * Source/CFArray.m: * Source/CFRuntime.c: Completely replace CFArray with a pure C implementation. * Headers/CoreFoundation/CFArray.h: Export functions for C++ compatibility. 2011-10-03 Stefan Bidigaray * Source/CFArray.c: Start work on C-only implementation of CFArray. 2011-10-01 Stefan Bidigaray * Source/CFNumber.c: Removed branch that never existed in the first place. 2011-10-01 Stefan Bidigaray * Source/GNUmakefile: * Source/CFRuntime.c: * Source/CFNumber.m: * Source/CFNumber.c: Started writing a C-only implementation of CFNumber. * Tests/CFNumber: Added some basic tests for CFNumber. 2011-09-29 Stefan Bidigaray * Source/CFBase.c: Initialize allocators. 2011-09-29 Stefan Bidigaray * Source/CFBase.c: Continued work on CFAllocators. 2011-09-28 Stefan Bidigaray * Source/CFBundle.m: Do not try to use dlfcn.h on Windows. * Source/CFUUID.c: Define INITRANDOM() on Windows. * Source/GNUmakefile: Add -L/mingw/bin to LDFLAGS on mingw. 2011-09-28 Stefan Bidigaray * Source/CFUUID.c: Add random number generation on Windows. 2011-09-28 Stefan Bidigaray * Source/objc_interface.h: Move CFRuntimeBridgeClass() to NSCFType.h. * Source/CFBase.c: * Source/CFData.c: * Source/CFString.c: Delay bridging until ObjC classes are initialized. * Source/NSCFData.m: Bridge to CFData. * Source/NSCFError.m: Bridge to CFError. * Source/NSCFString.m: Bridge to CFString. * Source/NSCFType.m: * Source/NSCFType.h: Move NSCFType interface and some extras to NSCFType.h. 2011-09-27 Stefan Bidigaray * Source/CFData.c: Bridge CFData to NSCFData. 2011-09-26 Stefan Bidigaray * Source/threading.h: * Source/CFBase.c: * Source/CFCalendar.c: * Source/CFLocale.c: * Source/CFString.c: * Source/CFStringEncoding.c: * Source/CFRuntime.c: Abstract threading functions for platforms that do not include pthread. 2011-09-26 Stefan Bidigaray * Source/objc_interface.h: * Source/atomic_ops.h: * Source/GNUmakefile: * Source/CFBase.c: * Headers/CoreFoundation/CFRuntime.h: * Headers/CoreFoundation/CFBase.h: Fixes for compilation on Windows. 2011-09-24 Stefan Bidigaray * Source/CFError.c: Retain objects before returning on Copy operations. * Source/CFUUID.c: * Source/CFCalendar.c: * Headers/CoreFoundation/CFCalendar.h: Avoid warnings. 2011-09-24 Stefan Bidigaray * Source/CFError.m: * Source/CFError.c: * Source/NSCFError.m: * Source/CFRuntime.c: * Source/GNUmakefile: Add C only implementation of CFError. 2011-09-24 Stefan Bidigaray * Source/CFRuntime.c: Initialize CFData. * Source/CFData.c: Release instead of deallocate ivar. 2011-09-24 Stefan Bidigaray * Source/NSCFType.h: * Source/NSCFType.m: Delete NSCFType.h and move interface definition to NSCFType.m. * Source/NSCFData.m: Added Objective-C interface to CFData. * Source/Data.c: Check deallocator before setting it. 2011-09-23 Stefan Bidigaray * Source/CFString.c: Do not require the use of libicuio. * Source/GNUmakefile: Update library dependency. 2011-09-23 Stefan Bidigaray * Headers/CoreFoundation/CFData.h: * Source/CFData.m: * Source/CFData.c: * Source/GNUmakefile: Replace CFData.m with CFData.c. 2011-09-22 Stefan Bidigaray * Source/CFRuntime.m: * Source/CFRuntime.c: Increment and decrement reference count ourselves instead of relying on Foundation functions. * Source/GNUmakefile: Replace CFRuntime.m with CFRuntime.c. * Source/atomic_ops.h: Atomic increment and decrement operations. 2011-09-21 Stefan Bidigaray * Source/CFRuntime.m: Set memory to 0 when creating new objects, and do not accept anything but an actual CFTypeID in CFCopyTypeIDDescription(). * Source/CFString.c: Reverted previous changes, bug was actually in CFRuntime. 2011-09-21 Stefan Bidigaray * Source/CFRuntime.m: Create instances ourselves instead relying on gnustep-base. * Source/GNUmakefile: * Source/CFBase.c: * Source/CFBase.m: Implement a true CFAllocator type. It is no longer compatible with a NSZone. This change also eliminates the objc dependency so the file is now pure C. * Source/CFArray.m: * Source/CFNumber.m: * Source/CFStream.m: * Source/CFURL.m: * Source/CFDictionary.m: * Source/CFData.m: Do not use CFAllocators as NSZones. * Source/NSCFType.h: * Source/NSCFType.m: NSCFType no longer conforms to NSCopying. I'm not sure it ever had to. * Source/CFString.c: Fix bug in CFStringCreateMutable(). 2011-09-19 Stefan Bidigaray * Source/CFRuntime.m: Update to reflect latest changes in gnustep-base. * Source/CFError.m: * Source/Identifiers.m: Moved definition of identifiers. * Headers/CoreFoundation/CFString.h: Do not define CFSTR() to @"" in ObjC source files. 2011-08-28 Matt Rice * Source/objc_interface.h: Remove referene to preface.h add runtime.h. (CF_IS_OBJC): Add cast to avoid warning. * Source/CFUUID.c: Replace BOOL/YES/NO with Boolean/true/false. * Source/CFBase.m (CFNullInitialize): Avoid +initialize. 2011-07-20 Stefan Bidigaray * Source/CFDate.c: * Source/CFCalendar.m: Modify absolute time function to not require ucal support and move back into CFDate.c. 2011-07-17 Stefan Bidigaray * Source/CFTimeZone.c: Fixed bug in CFTimeZoneCreateWithName (). * Source/CFRuntime.m: Fixed bug when setting isa. 2011-07-15 Stefan Bidigaray * Source/CFTimeZone.c: Complete CFTimeZoneCreateWithName(). * Source/CFString.c: Fix a few bugs. * Source/CFStringUtilities.c: Fix compare bug. 2011-07-15 10:57 David Chisnall * libs/corebase/trunk/Source/CFBundle.m, * libs/corebase/trunk/Source/GNUmakefile: Define RTLD_DEFAULT on systems where it isn't defined (stupid glibc headers). Remove -luuid, since it seems not to be required anymore. 2011-07-15 10:52 David Chisnall * libs/corebase/trunk/Source/objc_interface.h: Include a file that actually exists, instead of one that might exist. 2011-07-15 Stefan Bidigaray * Source/GNUmakefile: * Source/CFRuntime.m: * Source/CFTimeZone.c: * Headers/CoreFoundation/CFTimeZone.h: Added new CFTimeZone type base on ICU's zoneinfo64 resource bundle. 2011-07-12 Stefan Bidigaray * Source/CFCalendar.c: * Source/CFDate.c: Added most time utility functions. 2011-07-12 Stefan Bidigaray * Source/CFCalendar.c: Added CFCalendarGetTimeRangeOfUnit(). 2011-07-11 Stefan Bidigaray * Source/CFCalendar.c: Implemented CFCalendarGetComponentDifference(). 2011-07-11 Stefan Bidigaray * Source/CFCalendar.c: Implemented CFCalendarAddComponents() and CFCalendarDecomposeAbsoluteTime(). 2011-07-10 Stefan Bidigaray * Source/CFCalendar.c: Implemented a few more functions. * Source/CFString.c: Fixed bug in CFStringPad(). 2011-07-10 Stefan Bidigaray * Source/CFString.c: Fixed string hashing and implemented CFStringGetRangeOfComposedCharactersAtIndex(). 2011-07-10 Stefan Bidigaray * Source/objc_interface.h: * Source/CFRuntime.m: Add bridging function. * Source/CFString.c: Bridge NSCFString with CFString types. 2011-07-09 Stefan Bidigaray * Source/objc_interface.h: * Source/CFRuntime.m: Minor fixes to ObjC interface. * Source/CFString.c: Add ObjC dispatch to CFStringGetCharacters(). 2011-07-09 Stefan Bidigaray * Source/objc_interface.h: Add Objective-C runtime interface. * Source/CFRuntime.m: Moved private functions to objc_interface.h. * Source/CFString.c: First steps towards toll-free bridged objects. 2011-07-08 Stefan Bidigaray * Source/CFCalendar.c: Added implementation for CFCalendarGetMaximumRangeOfUnit and CFCalendarGetMinimumRangeOfUnit. 2011-07-08 Stefan Bidigaray * Source/CFDate.m: * Source/CFDate.c: * Source/GNUmakefile: * Headers/CoreFoundation/CFDate.h: Make CFDate a C file. Will use CFCalendar and ICU functions to implement this functionality. * Source/CFLocale.c: Fix a few bugs found when testing CFCalendar. * Source/Identifiers.m: Add ISO8601 calendar identifier. * Source/CFCalendar.c: * Headers/CoreFoundation/CFCalendar.h: Started implementing CFCalendar. 2011-06-27 Stefan Bidigaray * Source/CFString.c: Implemented CFStringCreateWithBytesNoCopy() and fixed a bug in CFStringCreateByCombiningStrings(). 2011-06-26 Stefan Bidigaray * Source/CFString.c: Implement CFStringPad(). 2011-06-26 Stefan Bidigaray * Source/CFStringFormat.c: Fix a few bugs in string formatting code. 2011-06-25 Stefan Bidigaray * Source/CFStringFormat.c: Added hex and octal formatting code. * Tests/CFString/format.m: Add hex and octal formatting test. 2011-06-24 Stefan Bidigaray * Source/CFStringFormat.c: Added double formatting code. * Tests/CFString/format.m: Add double formatting test. 2011-06-24 Stefan Bidigaray * Source/CFStringUtilities.c: Remove use of alloca(). * Source/CFStringEncoding.c: Fix conversion bug. * Source/CFStringFormat.c: Added more formatting code. 2011-06-22 Stefan Bidigaray * Source/CFUUID.c: Generate uuids using random function instead of relying on libuuid. 2011-06-21 Stefan Bidigaray * Source/GNUmakefile: Added CFStringFormat.c to build. * Source/CFString.c: Fixed bugs and added a work around. * Source/CFStringFormat.c: Added, still incomplete, string formatting code. * Tests/CFString/format.m: String formatting tests. 2011-06-16 Stefan Bidigaray * Source/CFString.c: Added CFStringAppendCharacters() 2011-06-15 Stefan Bidigaray * Source/CFRuntime.m: * Source/CFLocale.c: Use pthread directly. * Source/internal.h: Delete. * Source/CFString.c: Added *FileSystemRepresentation functions. * Source/CFStringEncoding.c: Implemented more encoding functions. * Source/CFStringFormat.c: New file for CFString formatting functions. * Headers/CoreFoundation/CFByteOrder.h: Fix compile mistake. 2011-06-13 Stefan Bidigaray * Headers/CoreFoundation/CFByteOrder.h: Actually swap byte order in CFSwappedFloat functions. 2011-06-09 Stefan Bidigaray * Source/GNUmakefile: * Source/CFByteOrder.c: Delete CFByteOrder.c. * Headers/CoreFoundation/CFByteOrder.h: Inline byte order functions. 2011-06-04 Stefan Bidigaray * Source/CFString.c: Fixed a few bugs. * Tests/CFString/mutablestring.m: Modified tests. 2011-06-04 Stefan Bidigaray * Source/CFString.c: Implemented CFStringReplace(). * Tests/CFString/mutablestring.m: Added more tests. 2011-06-04 Stefan Bidigaray * Source/CFString.c: Use CFStringInlineBuffer where appropriate. Also added CFStringTimeWhitespace(). * Source/CFStringEncoding.c: Fixed a bug uncovered by tests. * Tests/CFString/create.m: * Tests/CFString/mutablestring.m: Added a few more tests. 2011-06-03 Stefan Bidigaray * Source/CFString.c: * Source/CFStringEncoding.c: Fixed bugs uncovered by tests. * Tests/CFString/mutablestring.m: Added CFMutableString tests. 2011-06-03 Stefan Bidigaray * Source/CFString.c: Implemented a few more functions. * Headers/CoreFoundation/ForFoundationOnly.h: Added 2 more functions to be used internally by CoreFoundation and Foundation. 2011-05-31 Stefan Bidigaray * Source/internal.h: Define mutex functions to be used internally. * Source/CFLocale.c: * Source/CFRuntime.m: Use a mutex instead of spinlock. 2011-05-30 Stefan Bidigaray * Source/CFString.c: Added CFStringNormalize and CFStringTransform. * Source/NSCFString.m: Return CFString's type ID. 2011-05-29 Stefan Bidigaray * Source/NSCFString.m: Add NSCFString class. 2011-05-27 Stefan Bidigaray * Source/CFString.c: Added case mapping functions to CFMutableString. 2011-05-26 Stefan Bidigaray * Source/GNUmakefile: * Source/CFString.c: * Source/CFStringUtilities.c: Moved some CFString functions to a different file to reduce clutter and implemented them. 2011-05-26 Stefan Bidigaray * GNUmakefile: * Source/CFUUID.c: * Source/CFRuntime.m: * Headers/CoreFoundation/CFUUID.h: Added CFUUID. * Tests/CFUUID: And some tests. 2011-05-20 Stefan Bidigaray * Source/NSCFType.m: * Source/NSCFType.h: Add NSCopying. * Headers/CoreFoundation/CFBase.h: No longer define CFString as NSString. 2011-05-20 Stefan Bidigaray * Source/CFString.m: Deleted. * Source/GNUmakefile: * Source/CFRuntime.m: * Source/Identifier.m: * Source/CFString.c: * Source/CFStringEncoding.c: * Headers/CoreFoundation/ForFoundationOnly.h: Added initial CFString implementation using the ICU library. * Headers/CoreFoundation/CFStringEncodingExt.h: Protect against multiple includes. * Tests/CFString: Basic CFString test. 2011-05-06 Stefan Bidigaray * Source/CFString.m: * Headers/CoreFoundation/CFString.h: Make inline string buffer functions inline functions. * Headers/CoreFoundation/CFBase.h: Add CF_INLINE. 2011-04-15 Stefan Bidigaray * Source/CFArray.m: * Source/CFDictionary.m: * Headers/CoreFoundation/CFNumber.h * Headers/CoreFoundation/CFLocale.h * Headers/CoreFoundation/CFDictionary.h * Headers/CoreFoundation/CFString.h * Headers/CoreFoundation/CFBase.h * Headers/CoreFoundation/CFNumberFormatter.h * Headers/CoreFoundation/CFDate.h * Headers/CoreFoundation/CFArray.h: Fixes for C++. 2011-04-02 Stefan Bidigaray * Source/CFRuntime.m: * Source/GNUmakefile: * Source/CFCalendar.c: * Headers/CoreFoundation/CFCalendar.h: Added empty CFCalendar. * Source/CFLocale.c: Return a CFCalendar for kCFLocaleCalendar. 2011-03-30 Stefan Bidigaray * Source/CFNumberFormatter.c: (CFNumberFormatterCreateStringWithValue) Implemented. * Tests/CFNumberFormatter/format.m: Added tests. 2011-03-30 Stefan Bidigaray * Source/CFNumberFormatter.c: (CFNumberFormatterGetValueFromString) Fixed copy-and-paste mistake. * Tests/CFNumberFormatter/parse.m: Added tests. 2011-03-30 Stefan Bidigaray * Source/CFNumberFormatter.c: (CFNumberFormatterSetProperty) (CFNumberFormatterCreateNumberFromString) (CFNumberFormatterCreateStringWithNumber) (CFNumberFormatterGetValueFromString) Implemented. 2011-03-29 Stefan Bidigaray * Source/CFLocale.c: * Source/CFNumberFormatter.c: Add class functions. * Headers/CoreFoundation/CFBase.h: Define CFTypeRef as const. 2011-03-29 Stefan Bidigaray * Source/CFLocale.c: Minor fixes. * Source/CFNumberFormatter.c: Set default format. * Tests/CFNumberFormatter/create.m: * Tests/CFLocale/values.m: * Tests/CFLocale/identifier.m: * Tests/CFRuntime/runtime.m: Minor fixes. 2011-03-29 Stefan Bidigaray * Source/CFNumberFormatter.c: (CFNumberFormatterCopyProperty) Implemented. 2011-03-29 Stefan Bidigaray * Source/CFRuntime.m: * Source/CFNumber.m: * Headers/CoreFoundation/CFNumber.h: Added CFBoolean. 2011-03-27 Stefan Bidigaray * Source/CFLocale.c: (CFLocaleGetValue) Some more code. (CFLocaleCopyISOCurrencyCodes) (CFLocaleCopyCommonISOCurrencyCodes) Implemented. * Source/Identifiers.m: Added CFNumberFormatter identifiers. * Source/CFNumberFormatter.c: Return NULL from all function for now. * Tests/CFLocale/values.m: Worked on test a little more. 2011-03-26 Stefan Bidigaray * Source/CFNumberFormatter.c: (CFNumberFormatterSetFormat) Implemented. 2011-03-26 Stefan Bidigaray * Source/GNUmakefile: * Source/CFRuntime.m: * Source/CFNumberFormatter.c: * Headers/CoreFoundation/CFNumberFormatter.h: New type. * Tests/CFNumberFormatter/create.m: First couple of tests. 2011-03-26 Stefan Bidigaray * Source/CFLocale.c: (CFLocaleCopyDisplayNameForPropertyValue) Implemented. 2011-03-26 Stefan Bidigaray * Source/CFArray.m: * Source/NSCFType.m: * Source/CFNumber.m: * Source/CFError.m: * Source/CFStream.m: * Source/CFURL.m: * Source/CFDictionary.m: * Source/CFString.m: * Source/CFData.m: All NS objects should return _kCFRuntimeNotATypeID, except for NSCFType. * Source/CFRuntime.m: Check for NULL before trying to do anything. * Tests/CFLocale/create.m: Compile again. * Tests/CFTesting.h: Fixed mistake when PASS_CFNEQ was made into macro. 2011-03-26 Stefan Bidigaray * Source/GNUmakefile: * Source/CFByteOrder.m: * Source/CFByteOrder.c: Rename. 2011-03-26 Stefan Bidigaray * Source/CFLocale.c: (CFLocaleCreateComponentsFromLocaleIdentifier) (CFLocaleCreateLocaleIdentifierFromComponents) Implemented. * Source/CFString.m: ([NSString-_cfTypeID]) Return the class. * Tests/CFTesting.h: Make arguments more unique. * Tests/CFLocale/general.m: * Tests/CFLocale/value.m: Renamed. * Tests/CFLocale/identifier.m: New set of tests. 2011-03-24 Stefan Bidigaray * Source/CFRuntime.m: Improve interaction with ObjC objects. * Tests/CFTesting.h: Output in the same format as macros in Testing.h. * Tests/CFRuntime/runtime.m: Added toll-free bridge tests. 2011-03-23 Stefan Bidigaray * Source/CFRuntime.m: (CFEqual) Check that type IDs are equal. * Tests/CFRuntime/runtime.m: Added description output tests. 2011-03-22 Stefan Bidigaray * Source/CFRuntime.m: * Source/NSCFType.m: Make NSCFType class call CF functions instead of the other way around. * Tests/CFTesting.h: Include Testing.h here and make PASS_CF{,N}EQ inline functions. * Tests/CFRuntime/runtime.m: Added a couple of tests. 2011-03-22 Stefan Bidigaray * Source/CFRuntime.m: Moved NSCFType definition... * Source/NSCFType.m: ...To here. * Source/NSCFType.h: NSCFType interface. * Source/GNUmakefile: Added NSCFType.m. * Headers/CoreFoundation/CFRuntime.h: Additional ivars to help identify CF types. * Tests/CFRuntime/runtime.m: Initial CFRuntime tests. 2011-03-20 Stefan Bidigaray * Source/CFRuntime.m: Minor changes to make CF types more ObjC friendly. * Source/CFLocale.c: (CFLocaleCreateCanonicalLanguageIdentifierFromString) Added. (CFLocaleGetValue) Added more code. * Tests/CFTesting.h: Fixed output of PASS_CFNEQ. 2011-03-19 Stefan Bidigaray * Source/CFRuntime.m: Initializae CFNull. * Source/CFBase.m: Create a CFNull class and initialize kCFNull. * Headers/CoreFoundation/CFRuntime.h: Add INIT_CFRUNTIME_BASE() macro. * Headers/CoreFoundation/CFBase.h: Minor fixed to CFNull. 2011-03-19 Stefan Bidigaray * Source/CFRuntime.m: Add check for NULL in CFEqual. * Source/CFLocale.c: Added a bit of code to CFLocaleGetValue(). * Source/Identifiers.m: Added definition for calendar identifiers. * Tests/CFLocale/general.m: New tests. * Tests/CFTesting.h: Initialize char array. 2011-03-18 Stefan Bidigaray * Headers/CoreFoundation/CFLocale.h: Added some CFLocale keys. * Source/CFLocale.c: Added implementation for a few more functions and fixed a few possible threading issues. * Source/GNUmakefile: * Source/Identifiers.m: New file to define ObjC constant string. 2011-03-14 Richard Frith-Macdonald * Tests/GNUmakefile.super: * Tests/CFLocale/create.m: * Tests/CFTesting.h: Minor changes to use testsuite from gnustep-make ... Rename .c file to .m Rename Testing.h to avoid conflict with testsuite header. Add makefile fragment to link corebase 2011-03-13 Stefan Bidigaray * GNUmakefile: * Headers/CoreFoundation/CFLocale.h: * Source/CFLocale.c: New, mostly unimplemented CFLocale type. * Source/CFRuntime.m: Fixed a problem in CFCopyDescription where it tried to look up a typeID > __CFRuntimeClassTableSize. * Source/CFBase.m: Define kCFAllocatorSystemDefault = kCFAllocatorDefault. * Source/CFString.h: * Source/CFBase.h: Changes due to introduction of CFLocale.h. Also fixed wrong definition of CF_EXTERN_C_{BEGIN,END}. 2010-09-18 Fred Kiefer * Source/CFPropertyList.m (CFPropertyListCreateDeepCopy): Implement deep copy. 2010-06-22 Stefan Bidigaray * Source/CFRuntime.m: Use NSAllocateObject() instead of duplicating code in this function. 2010-03-23 Stefan Bidigaray * Source/CFString.m: Fixed typo in CFShowStr() and return for CFStringGet*Ptr(). 2010-03-23 Stefan Bidigaray * Headers/CoreFoundation/CFBase.h: * Source/CFString.m: Fixed a few bugs and implemented CFShowStr(). 2010-03-23 Stefan Bidigaray * Source/CFStream.m: * Source/CFArray.m: * Source/CFURL.m: * Source/CFDictionary.m: * Source/CFString.m: * Source/CFNumber.m: * Source/CFData.m: * Source/CFError.m: Added -_cfTypeID to bridged ObjC classes. 2010-03-23 Stefan Bidigaray * Source/CFRuntime.m: Correct output of CFCopyDescription(), fixed CFCopyTypeIDDescription() and added copyright notice. * Headers/CoreFoundation/CFRuntime.h: Added copyright notice. * Source/CFString.m: Fixed typo. 2010-03-22 Stefan Bidigaray * Source/CFRuntime.m: Fixed output of -description. * Source/CFString.m: * Headers/CoreFoundation/CFString.h: Added CFShow(). 2010-03-21 Stefan Bidigaray * Source/GNUmakefile: * Source/CFRuntime: * Headers/CoreFoundation/CFRuntime.h: Added CFRuntime implementation. * Source/CFBase.m: * Headers/CoreFoundation/CFBase.h: Moved CFType function to Source/CFRuntime.m. * Source/CFString.m: Fixed encoding conversion. 2010-03-21 Stefan Bidigaray * Source/CFBase.m: Cleaned up CFAllocator and removed things that should not have been there in the first place. * Source/CFString.m: * Source/CFDate.m: * Source/CFArray.m: * Source/CFPropertyList.m: * Source/CFString.m: * Source/CFNumber.m: Cleaned up * Headers/CoreFoundation/CFBase.h: Added and fixed defines and types. 2010-02-28 08:43-EST Gregory John Casamento * Headers/CoreFoundation/CFBase.h: Declare externs where appropriate. 2010-02-12 19:35-EST Gregory John Casamento * Source/CFPropertyList.m: Use stream length instead of bufferLength. Correction for compilation error. 2010-01-26 Fred Kiefer * Source/CFPropertyList.m: Fill in a bit more code. 2010-01-24 Stefan Bidigaray * Headers/CoreFoundation/CoreFoundation.h: * Headers/CoreFoundation/CFNumber.h: * Source/GNUmakefile: * Source/CFNumber.m: Added initial CFNumber implementation. 2010-01-24 Stefan Bidigaray * Headers/CoreFoundation/CFArray.h: * Headers/CoreFoundation/CFDictionary.h: Made immutable and mutable versions of these class be the same structure. 2010-01-24 Stefan Bidigaray * Source/CFStream.m: Fixed typo. 2010-01-24 Stefan Bidigaray * Headers/CoreFoundation/CFString.h: * Headers/CoreFoundation/CFBase.h: Revert previous change, the correct place for CFSTR is in CFString.h. * Source/CFError.m: Include CFString.h. 2010-01-23 Stefan Bidigaray * Headers/CoreFoundation/CFString.h: Moved CFSTR definition from here... * Headers/CoreFoundation/CFBase.h: To here. * Source/CFError.m: * Source/CFString.m: Use CFSTR() instead of @"". 2010-01-23 Stefan Bidigaray * Headers/CoreFoundation/CoreFoundation.h: * Headers/CoreFoundation/CFBase.h * Headers/CoreFoundation/CFPropertyList.h: * Source/GNUmakefile: * Source/CFPropertyList.m: Added rudimentary CFPropertyList implementaion 2010-01-23 Stefan Bidigaray * Headers/CoreFoundation/CoreFoundation.h: * Headers/CoreFoundation/CFStream.h: * Source/GNUmakefile: * Source/CFStream.m: Added CFStream implementation. 2010-01-23 Stefan Bidigaray * Headers/CoreFoundation/CFString.h: Add availability macros. 2010-01-22 Stefan Bidigaray * Source/CFBase.m: * Source/CFArray.m: * Source/CFData.m: * Source/CFDate.m: * Source/CFError.m: * Source/CFString.m: * Source/CFURL.m: Adopt to GNU coding standards. 2010-01-22 Stefan Bidigaray * Source/GNUmakefile: * Source/CFDate.m: * Headers/CoreFoundation/CFDate.h: Initial CFDate implementation * Headers/CoreFoundation/CoreFoundation.h: Added CFDate.h and CFURL.h 2010-01-21 Eric Wasylishen * Source/CFURL.m: * Headers/CoreFoundation/CFURL.h: Start implementing CFURL 2010-01-19 Stefan Bidigaray * Source/CFBase.m: * Source/CFError.m: Correct missing CFRetain in copied objects. 2010-01-19 Stefan Bidigaray * Headers/CoreFoundation/CFString.h: Include stdarg.h. * Headers/CoreFoundation/CoreFoundation.h: * Headers/CoreFoundation/CFError.h: * Source/CFError.m: * Source/GNUmakefile: Added CFError. 2010-01-17 Fred Kiefer * Headers/CoreFoundation/CFString.h: Correct return type of CFStringCreateExternalRepresentation. * Source/CFArray.m, * Source/CFDictionary.m, * Source/CFString.m, * Source/CFData.m: Implement soem missing or incorrect functions. 2010-01-17 Fred Kiefer * Headers/CoreFoundation/CFDictionary.h, * Headers/CoreFoundation/CFCharacterSet.h: Remove remaining includes of Foundation.h. * Source/CFDictionary.m: Adopt to this change by using type casts. * Source/CFString.m: Add include for NSArray.h. 2010-01-17 Stefan Bidigaray * Source/CFBase.m: Implemented kCFAllocatorNull and kCFAllocatorMalloc. 2010-01-17 Fred Kiefer * Headers/CoreFoundation/CFBase.h, * Headers/CoreFoundation/CFArray.h, * Headers/CoreFoundation/CFData.h: Don't include Foundation,h, use abstract types instead. * Source/CFArray.m, * Source/CFData.m, * Source/CFString.m: Adopt to this change by using plenty of type casts. 2010-01-16 Stefan Bidigaray * Source/CFBase.m: Correctly reallocate memory. 2010-01-16 Fred Kiefer * Source/CFArray.m: Implement more of the functions and remove compiler warnings. 2010-01-16 Eric Wasylishen * Initial import of code by Stefan Bidigaray. gnustep-corebase-0.2/Source/0000755000175000017500000000000014661613221015145 5ustar yavoryavorgnustep-corebase-0.2/Source/GSFunctions.c0000644000175000017500000000326613222706330017516 0ustar yavoryavor/* GSFunctions.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: April, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "GSPrivate.h" CFIndex GSBSearch (const void *array, const void *key, CFRange range, CFIndex size, CFComparatorFunction comp, void *ctxt) { CFIndex min; CFIndex mid; CFIndex max; const void *cur; min = range.location; max = min + range.length; while (max > min) { CFComparisonResult r; mid = (min + max) >> 1; cur = ((const UInt8*)array) + (mid * size); r = comp (key, cur, ctxt); if (r == kCFCompareLessThan) { max = mid - 1; } else if (r == kCFCompareGreaterThan) { min = mid + 1; } else { min = mid + 1; break; } } return min - 1; } gnustep-corebase-0.2/Source/CFPropertyList.c0000644000175000017500000012152113222706330020200 0ustar yavoryavor/* CFPropertyList.c Copyright (C) 2012 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: August, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFPropertyList.h" #include "CoreFoundation/CFArray.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFData.h" #include "CoreFoundation/CFDate.h" #include "CoreFoundation/CFDictionary.h" #include "CoreFoundation/CFNumber.h" #include "CoreFoundation/CFSet.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFStream.h" #include "CoreFoundation/GSCharacter.h" #include "CoreFoundation/GSUnicode.h" #include "GSPrivate.h" #include "GSCArray.h" #include "GSMemory.h" static CFTypeID _kCFArrayTypeID = 0; static CFTypeID _kCFBooleanTypeID = 0; static CFTypeID _kCFDataTypeID = 0; static CFTypeID _kCFDateTypeID = 0; static CFTypeID _kCFDictionaryTypeID = 0; static CFTypeID _kCFNumberTypeID = 0; static CFTypeID _kCFStringTypeID = 0; static Boolean _kCFPropertyListTypeIDsInitialized = false; static const UInt32 _kCFOpenStepPlistQuotables[4] = { 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001 }; #define CFOpenStepPlistCharacterIsQuotable(c) \ (((c) > 128) \ || ((_kCFOpenStepPlistQuotables[(c) >> 5] & (1 << ((c) & 0x1F))) > 0)) #if 0 static const UInt8 *_kCFPlistXMLArrayTag = (const UInt8 *) "array"; static const UInt8 *_kCFPlistXMLDictTag = (const UInt8 *) "dict"; static const UInt8 *_kCFPlistXMLKeyTag = (const UInt8 *) "key"; static const UInt8 *_kCFPlistXMLValueTag = (const UInt8 *) "value"; static const UInt8 *_kCFPlistXMLDataTag = (const UInt8 *) "data"; static const UInt8 *_kCFPlistXMLDateTag = (const UInt8 *) "date"; static const UInt8 *_kCFPlistXMLIntegerTag = (const UInt8 *) "integer"; static const UInt8 *_kCFPlistXMLRealTag = (const UInt8 *) "real"; static const UInt8 *_kCFPlistXMLTrueTag = (const UInt8 *) "true"; static const UInt8 *_kCFPlistXMLFalseTag = (const UInt8 *) "false"; static const CFIndex _kCFPlistXMLArrayTagLength = 5; static const CFIndex _kCFPlistXMLDictTagLength = 4; static const CFIndex _kCFPlistXMLKeyTagLength = 3; static const CFIndex _kCFPlistXMLValueTagLength = 5; static const CFIndex _kCFPlistXMLDataTagLength = 4; static const CFIndex _kCFPlistXMLDateTagLength = 4; static const CFIndex _kCFPlistXMLIntegerTagLength = 7; static const CFIndex _kCFPlistXMLRealTagLength = 4; static const CFIndex _kCFPlistXMLTrueTagLength = 4; static const CFIndex _kCFPlistXMLFalseTagLength = 5; #endif #define _kCFPlistBufferSize 1024 typedef struct { CFWriteStreamRef stream; CFOptionFlags options; CFErrorRef error; CFIndex written; UInt8 *cursor; const UInt8 *limit; UInt8 buffer[_kCFPlistBufferSize]; } CFPlistWriteStream; typedef struct { UniChar *buffer; CFOptionFlags options; CFErrorRef error; CFMutableSetRef unique; UniChar *cursor; const UniChar *limit; } CFPlistString; struct CFPlistIsValidContext { Boolean isValid; CFPropertyListFormat fmt; CFMutableSetRef set; /* Used to check for cycles */ }; static void CFPropertyListInitTypeIDs (void) { if (_kCFPropertyListTypeIDsInitialized) return; _kCFArrayTypeID = CFArrayGetTypeID (); _kCFBooleanTypeID = CFBooleanGetTypeID (); _kCFDataTypeID = CFDataGetTypeID (); _kCFDateTypeID = CFDateGetTypeID (); _kCFDictionaryTypeID = CFDictionaryGetTypeID (); _kCFNumberTypeID = CFNumberGetTypeID (); _kCFStringTypeID = CFStringGetTypeID (); _kCFPropertyListTypeIDsInitialized = true; } static Boolean CFPlistTypeIsValid (CFPropertyListRef plist, CFPropertyListFormat fmt, CFMutableSetRef set); static void CFArrayIsValidFunction (const void *value, void *context) { struct CFPlistIsValidContext *ctx = (struct CFPlistIsValidContext *) context; if (ctx->isValid) ctx->isValid = value && CFPlistTypeIsValid (value, ctx->fmt, ctx->set); } static void CFDictionaryIsValidFunction (const void *key, const void *value, void *context) { struct CFPlistIsValidContext *ctx = (struct CFPlistIsValidContext *) context; if (ctx->isValid) { ctx->isValid = key && (CFGetTypeID (key) == _kCFStringTypeID) && value && CFPlistTypeIsValid (value, ctx->fmt, ctx->set); } } static Boolean CFPlistTypeIsValid (CFPropertyListRef plist, CFPropertyListFormat fmt, CFMutableSetRef set) { CFTypeID typeID; CFPropertyListInitTypeIDs (); typeID = CFGetTypeID (plist); if (typeID == _kCFDataTypeID || typeID == _kCFStringTypeID) return true; if (fmt != kCFPropertyListOpenStepFormat) { /* These are not supported by the OPENSTEP property list format. */ if (typeID == _kCFBooleanTypeID || typeID == _kCFDateTypeID || typeID == _kCFNumberTypeID) return true; } /* Check for cycles */ if (CFSetContainsValue (set, plist)) return false; CFSetAddValue (set, plist); if (typeID == _kCFArrayTypeID) { CFRange range; struct CFPlistIsValidContext ctx; range = CFRangeMake (0, CFArrayGetCount (plist)); ctx.isValid = true; ctx.fmt = fmt; ctx.set = set; CFArrayApplyFunction (plist, range, CFArrayIsValidFunction, &ctx); CFSetRemoveValue (set, plist); return ctx.isValid; } else if (typeID == _kCFDictionaryTypeID) { struct CFPlistIsValidContext ctx; ctx.isValid = true; ctx.fmt = fmt; ctx.set = set; CFDictionaryApplyFunction (plist, CFDictionaryIsValidFunction, &ctx); CFSetRemoveValue (set, plist); return ctx.isValid; } return false; } Boolean CFPropertyListIsValid (CFPropertyListRef plist, CFPropertyListFormat fmt) { CFMutableSetRef set; Boolean ret; set = CFSetCreateMutable (NULL, 0, &kCFTypeSetCallBacks); ret = CFPlistTypeIsValid (plist, fmt, set); CFRelease (set); return ret; } struct CFPlistCopyContext { CFOptionFlags opts; CFAllocatorRef alloc; CFTypeRef container; }; static void CFArrayCopyFunction (const void *value, void *context) { CFPropertyListRef newValue; struct CFPlistCopyContext *ctx = (struct CFPlistCopyContext *) context; CFMutableArrayRef array = (CFMutableArrayRef) ctx->container; newValue = CFPropertyListCreateDeepCopy (ctx->alloc, value, ctx->opts); CFArrayAppendValue (array, newValue); CFRelease (newValue); } static void CFDictionaryCopyFunction (const void *key, const void *value, void *context) { CFPropertyListRef newValue; struct CFPlistCopyContext *ctx = (struct CFPlistCopyContext *) context; CFMutableDictionaryRef dict = (CFMutableDictionaryRef) ctx->container; newValue = CFPropertyListCreateDeepCopy (ctx->alloc, value, ctx->opts); CFDictionaryAddValue (dict, key, newValue); CFRelease (newValue); } CFPropertyListRef CFPropertyListCreateDeepCopy (CFAllocatorRef alloc, CFPropertyListRef plist, CFOptionFlags opts) { CFPropertyListRef copy; CFTypeID typeID; typeID = CFGetTypeID (plist); if (typeID == _kCFArrayTypeID) { CFIndex cnt; cnt = CFArrayGetCount (plist); if (opts == kCFPropertyListImmutable) { CFIndex i; CFTypeRef *values; CFArrayRef array; CFRange range; values = CFAllocatorAllocate (alloc, cnt * sizeof (CFTypeRef), 0); range = CFRangeMake (0, cnt); CFArrayGetValues (plist, range, values); for (i = 0; i < cnt; ++i) values[i] = CFPropertyListCreateDeepCopy (alloc, values[i], opts); array = CFArrayCreate (alloc, values, cnt, &kCFTypeArrayCallBacks); for (i = 0; i < cnt; ++i) CFRelease (values[i]); CFAllocatorDeallocate (alloc, values); copy = array; } else { struct CFPlistCopyContext ctx; CFMutableArrayRef array; CFRange range; array = CFArrayCreateMutable (alloc, cnt, &kCFTypeArrayCallBacks); ctx.opts = opts; ctx.alloc = alloc; ctx.container = (CFTypeRef) array; range = CFRangeMake (0, cnt); CFArrayApplyFunction (array, range, CFArrayCopyFunction, &ctx); copy = array; } } else if (typeID == _kCFDictionaryTypeID) { CFIndex cnt; cnt = CFDictionaryGetCount (plist); if (opts == kCFPropertyListImmutable) { CFIndex i; CFTypeRef *keys; CFTypeRef *values; CFDictionaryRef dict; keys = CFAllocatorAllocate (alloc, 2 * cnt * sizeof (CFTypeRef), 0); values = keys + cnt; CFDictionaryGetKeysAndValues (plist, keys, values); for (i = 0; i < cnt; ++i) values[i] = CFPropertyListCreateDeepCopy (alloc, values[i], opts); dict = CFDictionaryCreate (alloc, keys, values, cnt, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); for (i = 0; i < cnt; ++i) { CFRelease (keys[i]); CFRelease (values[i]); } CFAllocatorDeallocate (alloc, keys); copy = dict; } else { struct CFPlistCopyContext ctx; CFMutableDictionaryRef dict; dict = CFDictionaryCreateMutable (alloc, cnt, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); ctx.opts = opts; ctx.alloc = alloc; ctx.container = (CFTypeRef) dict; CFDictionaryApplyFunction (dict, CFDictionaryCopyFunction, &ctx); copy = dict; } } else if (typeID == _kCFStringTypeID) { if (opts == kCFPropertyListMutableContainersAndLeaves) copy = CFStringCreateMutableCopy (alloc, 0, plist); else copy = CFStringCreateCopy (alloc, plist); } else if (typeID == _kCFDataTypeID) { if (opts == kCFPropertyListMutableContainersAndLeaves) copy = CFDataCreateMutableCopy (alloc, 0, plist); else copy = CFDataCreateCopy (alloc, plist); } else if (typeID == _kCFDateTypeID) { copy = CFDateCreate (alloc, CFDateGetAbsoluteTime (plist)); } else if (typeID == _kCFNumberTypeID) { UInt8 number[16]; /* Largest type size */ CFNumberType type; type = CFNumberGetType (plist); CFNumberGetValue (plist, type, number); copy = CFNumberCreate (alloc, type, number); } else if (typeID == _kCFBooleanTypeID) { /* CFBoolean instances are singletons */ copy = plist; } else { copy = NULL; } return copy; } #if 0 /* Binary property list object ref */ #define PL_BOOL 0x0 #define PL_INT 0x1 #define PL_REAL 0x2 #define PL_DATE 0x3 #define PL_DATA 0x4 #define PL_ASTR 0x5 #define PL_USTR 0x6 #define PL_UID 0x8 #define PL_ARRY 0xA #define PL_SET 0xC #define PL_DICT 0xD static void CFBinaryPlistWriteObject (CFPropertyListRef plist, CFPlistWriteStream stream, CFIndex lev, CFOptionFlags opts) { CFTypeID typeID; typeID = CFGetTypeID (plist); if (typeID == CFArrayGetTypeID ()) { } else if (typeID == CFBooleanGetTypeID ()) { } else if (typeID == CFDataGetTypeID ()) { } else if (typeID == CFDateGetTypeID ()) { } else if (typeID == CFDictionaryGetTypeID ()) { } else if (typeID == CFNumberGetTypeID ()) { } else if (typeID == CFStringGetTypeID ()) { } else { return; } } #endif static CFErrorRef CFPlistCreateError (CFIndex code, CFStringRef message) { const void *key[1]; const void *value[1]; CFErrorRef error; key[0] = kCFErrorDescriptionKey; value[0] = message; error = CFErrorCreateWithUserInfoKeysAndValues (kCFAllocatorSystemDefault, kCFErrorDomainCocoa, code, key, value, 1); return error; } static Boolean CFPlistStringSkipWhitespace (CFPlistString * string) { UniChar ch; while (string->cursor < string->limit) { ch = *string->cursor; while (string->cursor < string->limit && GSCharacterIsWhitespace (ch)) { string->cursor++; ch = *string->cursor; } if (ch == '/') { string->cursor++; ch = *string->cursor; if (ch == '/') { do { string->cursor++; ch = *string->cursor; if (ch == '\n') break; } while (ch); } else if (ch == '*') { do { string->cursor++; ch = *string->cursor; if (ch == '*') { string->cursor++; ch = *string->cursor; if (ch == '/') break; } } while (ch); } else { string->cursor--; break; } } else { return true; } } return false; } CF_INLINE UInt8 getNibble (UniChar c) { if (c >= '0' && c <= '9') return c - '0'; else if ((c | 0x20) >= 'a' && (c | 0x20) <= 'z') return (c | 0x20) - 'a'; return 0xFF; /* This function return 0xFF on error. */ } static CFDataRef CFOpenStepPlistParseData (CFAllocatorRef alloc, CFPlistString * string) { UInt8 bytes[_kCFPlistBufferSize]; UInt8 nibble1; UInt8 nibble2; CFMutableDataRef obj; UniChar ch; CFIndex i; if (!CFPlistStringSkipWhitespace (string)) return NULL; obj = CFDataCreateMutable (alloc, 0); i = 0; ch = *string->cursor++; nibble1 = getNibble (ch); while (nibble1 < 0x10 && string->cursor < string->limit) { ch = *string->cursor++; nibble2 = getNibble (ch); if (nibble2 > 0x0F) { string->error = CFPlistCreateError (kCFPropertyListReadCorruptError, CFSTR ("Unexpected character while reading property list data.")); break; } bytes[i++] = (nibble1 << 4) | nibble2; if (i == _kCFPlistBufferSize) { CFDataAppendBytes (obj, bytes, _kCFPlistBufferSize); i = 0; } if (!CFPlistStringSkipWhitespace (string) && string->cursor < string->limit) break; ch = *string->cursor++; nibble1 = getNibble (ch); } if (!CFPlistStringSkipWhitespace (string)) { string->error = CFPlistCreateError (kCFPropertyListReadCorruptError, CFSTR ("")); } if (ch == '>') { CFDataAppendBytes (obj, bytes, i); } else { CFRelease (obj); obj = NULL; } return obj; } static CFStringRef CFOpenStepPlistParseString (CFAllocatorRef alloc, CFPlistString * string) { UniChar ch; CFStringRef obj; if (string->error || !CFPlistStringSkipWhitespace (string)) return NULL; obj = NULL; ch = *string->cursor; if (ch == '\"') { const UniChar *mark; CFIndex len; CFMutableStringRef tmp; string->cursor++; mark = string->cursor; tmp = NULL; while (string->cursor < string->limit) { ch = *string->cursor++; if (ch == '\"') { break; } else if (ch == '\\') { if (tmp == NULL) tmp = CFStringCreateMutable (alloc, 0); CFStringAppendCharacters (tmp, mark, string->cursor - mark); ch = *string->cursor++; /* FIXME */ if (ch >= '0' && ch <= '9') { } else if (ch == 'u' || ch == 'U') { } else { } } } len = string->cursor - mark; if (tmp == NULL) { if (string->options == kCFPropertyListMutableContainersAndLeaves) { obj = CFStringCreateMutable (alloc, len); CFStringAppendCharacters ((CFMutableStringRef) obj, (const UniChar *) mark, len); } else { obj = CFStringCreateWithCharacters (alloc, mark, len); } } else { CFStringAppendCharacters (tmp, mark, len); if (string->options == kCFPropertyListMutableContainersAndLeaves) { obj = (CFStringRef) tmp; } else { obj = CFStringCreateCopy (alloc, tmp); CFRelease (tmp); } } } else if (!CFOpenStepPlistCharacterIsQuotable (ch)) { UniChar *mark; mark = string->cursor; while (string->cursor < string->limit) { if (CFOpenStepPlistCharacterIsQuotable (ch)) break; string->cursor++; ch = *string->cursor; } if (mark != string->cursor) { CFIndex len; len = string->cursor - mark; if (string->options == kCFPropertyListMutableContainersAndLeaves) { obj = CFStringCreateMutable (alloc, len); CFStringAppendCharacters ((CFMutableStringRef) obj, (const UniChar *) mark, len); } else { obj = CFStringCreateWithCharacters (alloc, mark, len); } } } return obj; } static CFPropertyListRef CFOpenStepPlistParseObject (CFAllocatorRef alloc, CFPlistString * string) { UniChar ch; CFPropertyListRef obj; /* If we have an error, return immediately. */ if (string->error) return NULL; if (!CFPlistStringSkipWhitespace (string)) return NULL; ch = *string->cursor++; if (ch == '{') { CFMutableDictionaryRef dict; CFStringRef key; CFPropertyListRef value; dict = CFDictionaryCreateMutable (alloc, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); key = CFOpenStepPlistParseString (alloc, string); while (key) { if (!CFPlistStringSkipWhitespace (string) || *string->cursor != '=') { CFRelease (key); break; } string->cursor++; value = CFOpenStepPlistParseObject (alloc, string); if (value == NULL) { CFRelease (key); break; } CFDictionaryAddValue (dict, key, value); CFRelease (key); CFRelease (value); if (!CFPlistStringSkipWhitespace (string) || *string->cursor != ';') { key = NULL; } else { string->cursor++; key = CFOpenStepPlistParseString (alloc, string); } } if (*string->cursor == '}') { string->cursor++; obj = dict; } else { CFRelease (dict); obj = NULL; } } else if (ch == '(') { CFMutableArrayRef array; CFPropertyListRef value; array = CFArrayCreateMutable (alloc, 0, &kCFTypeArrayCallBacks); value = CFOpenStepPlistParseObject (alloc, string); while (value) { CFArrayAppendValue (array, value); CFRelease (value); if (!CFPlistStringSkipWhitespace (string) || *string->cursor != ',') { value = NULL; } else { string->cursor++; value = CFOpenStepPlistParseObject (alloc, string); } } if (*string->cursor == ')') { string->cursor++; obj = array; } else { CFRelease (array); obj = NULL; } } else if (ch == '<') { obj = CFOpenStepPlistParseData (alloc, string); } else { string->cursor--; obj = CFOpenStepPlistParseString (alloc, string); } return obj; } static void CFPlistWriteStreamFlush (CFPlistWriteStream * stream) { CFIndex ret; UInt8 *buf; /* If an error has already been set, return immediately. */ if (stream->error) return; buf = stream->buffer; ret = CFWriteStreamWrite (stream->stream, buf, stream->cursor - buf); if (ret < 0) { CFErrorRef error; error = CFWriteStreamCopyError (stream->stream); if (error) { stream->error = error; } else { stream->error = CFPlistCreateError (kCFPropertyListWriteStreamError, CFSTR ("Unknown stream error encountered while trying to write property list.")); } } else if (ret == 0) { stream->error = CFPlistCreateError (kCFPropertyListWriteStreamError, CFSTR ("Property list write could not be completed. Stream is full.")); } stream->written += ret; stream->cursor = stream->buffer; } static void CFPlistWriteStreamWrite (CFPlistWriteStream * stream, const UInt8 * buf, CFIndex len) { do { CFIndex writeLen; /* Flush buffer if needed */ if (stream->cursor == stream->buffer + _kCFPlistBufferSize) CFPlistWriteStreamFlush (stream); /* If an error was set, return immediately. */ if (stream->error != NULL) return; if (len > _kCFPlistBufferSize - (stream->cursor - stream->buffer)) writeLen = _kCFPlistBufferSize - (stream->cursor - stream->buffer); else writeLen = len; GSMemoryCopy (stream->cursor, buf, writeLen); stream->cursor += writeLen; buf += writeLen; len -= writeLen; } while (len > 0); } static const UInt8 *indentString = (const UInt8 *) "\t\t\t\t\t\t\t\t"; #define _kCFPlistIndentStringLength 8 static void CFPlistIndent (CFPlistWriteStream * stream, CFIndex lev) { while (lev > _kCFPlistIndentStringLength) { CFPlistWriteStreamWrite (stream, indentString, _kCFPlistIndentStringLength); lev -= _kCFPlistIndentStringLength; } CFPlistWriteStreamWrite (stream, indentString, lev); } static const UInt8 *base16 = (const UInt8 *) "0123456789ABCDEF"; static void CFPlistWriteDataBase16 (CFDataRef data, CFPlistWriteStream * stream) { CFIndex len; CFIndex i; const UInt8 *d; const UInt8 *dLimit; UInt8 buffer[_kCFPlistBufferSize]; CFPlistWriteStreamFlush (stream); len = CFDataGetLength (data); if (len == 0) return; d = CFDataGetBytePtr (data); dLimit = d + len; i = 0; while (d < dLimit) { buffer[i++] = base16[((*d) >> 4)]; buffer[i++] = base16[(*d) & 0xF]; d++; if (i == _kCFPlistBufferSize) { CFPlistWriteStreamWrite (stream, buffer, _kCFPlistBufferSize); i = 0; } } CFPlistWriteStreamWrite (stream, buffer, i); } static void CFPlistWriteDataBase64 (CFDataRef data, CFPlistWriteStream * stream) { } static void CFPlistWriteXMLString (CFStringRef str, CFPlistWriteStream * stream) { } static void CFXMLPlistWriteObject (CFPropertyListRef plist, CFPlistWriteStream * stream, CFIndex lev) { CFTypeID typeID; CFPlistIndent (stream, lev); typeID = CFGetTypeID (plist); if (typeID == CFArrayGetTypeID ()) { /* * Object 1 * Object 2 * ... * */ CFIndex idx; CFIndex count; CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 7); count = CFArrayGetCount ((CFArrayRef) plist); for (idx = 0; idx < count; ++idx) { CFPropertyListRef obj; obj = CFArrayGetValueAtIndex ((CFArrayRef) plist, idx); CFXMLPlistWriteObject (obj, stream, lev + 1); } CFPlistIndent (stream, lev); CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 8); } else if (typeID == CFBooleanGetTypeID ()) { /* or */ if (plist == kCFBooleanTrue) CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 7); else if (plist == kCFBooleanFalse) CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 8); } else if (typeID == CFDataGetTypeID ()) { /* Base64 Data */ CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 6); CFPlistWriteDataBase64 ((CFDataRef) plist, stream); CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 7); } else if (typeID == CFDateGetTypeID ()) { /* %04d-%02d-%02dT%02d:%02d:%02dZ */ CFAbsoluteTime at; CFGregorianDate gdate; int printed; char buffer[21]; /* Size of "%04d-%02d-%02dT%02d:%02d:%02dZ" + '\0' */ at = CFDateGetAbsoluteTime ((CFDateRef) plist); gdate = CFAbsoluteTimeGetGregorianDate (at, NULL); printed = sprintf (buffer, "%04d-%02d-%02dT%02d:%02d:%02dZ", gdate.year, gdate.month, gdate.day, gdate.hour, gdate.minute, (SInt32) gdate.second); if (printed < 20) return; /* Do something with the error? */ CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 6); CFPlistWriteStreamWrite (stream, (const UInt8 *) buffer, 20); CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 7); } else if (typeID == CFDictionaryGetTypeID ()) { } else if (typeID == CFNumberGetTypeID ()) { if (CFNumberIsFloatType ((CFNumberRef) plist)) { CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 6); CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 7); } else { CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 9); CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 10); } } else if (typeID == CFStringGetTypeID ()) { /* String */ CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 8); CFPlistWriteXMLString ((CFStringRef) plist, stream); CFPlistWriteStreamWrite (stream, (const UInt8 *) "", 9); } else { return; } CFPlistWriteStreamWrite (stream, (const UInt8 *) "\n", 1); } static Boolean CFOpenStepPlistStringHasQuotables (CFStringRef str) { UniChar ch; UniChar *cursor; UniChar buffer[_kCFPlistBufferSize]; CFIndex loc; CFIndex len; CFIndex read; loc = 0; len = CFStringGetLength (str); do { read = len > _kCFPlistBufferSize ? _kCFPlistBufferSize : len; CFStringGetCharacters (str, CFRangeMake (loc, read), buffer); cursor = buffer; do { ch = *cursor++; if (CFOpenStepPlistCharacterIsQuotable (ch)) return true; } while (cursor < (buffer + read)); loc += read; len -= read; } while (len > 0); return false; } static void CFPlistWriteOpenStepString (CFStringRef str, CFPlistWriteStream * stream) { /* An encoding parameter could be added to this function, but we write every string on human readable property lists (OpenStep and XML) in UTF-8 encoding, so this is not necessary. */ UInt8 buffer[_kCFPlistBufferSize]; CFIndex length; CFIndex loc; CFIndex read; CFIndex used; length = CFStringGetLength (str); loc = 0; if (length == 0) { CFPlistWriteStreamWrite (stream, (const UInt8 *) "\"\"", 2); } else if (CFOpenStepPlistStringHasQuotables (str)) { const UInt8 *mark; const UInt8 *cursor; UInt8 ch; CFPlistWriteStreamWrite (stream, (const UInt8 *) "\"", 1); do { read = CFStringGetBytes (str, CFRangeMake (loc, length), kCFStringEncodingUTF8, 0, false, buffer, _kCFPlistBufferSize, &used); mark = (const UInt8 *) buffer; cursor = (const UInt8 *) buffer; while ((cursor - mark) < read) { ch = *cursor++; if (ch == '\a' || ch == '\b' || ch == '\v' || ch == '\f' || ch == '\"') { CFPlistWriteStreamWrite (stream, mark, cursor - mark); CFPlistWriteStreamWrite (stream, (const UInt8 *) "\\", 1); if (ch == '\a') CFPlistWriteStreamWrite (stream, (const UInt8 *) "a", 1); else if (ch == '\b') CFPlistWriteStreamWrite (stream, (const UInt8 *) "b", 1); else if (ch == '\v') CFPlistWriteStreamWrite (stream, (const UInt8 *) "v", 1); else if (ch == '\f') CFPlistWriteStreamWrite (stream, (const UInt8 *) "f", 1); else if (ch == '\"') CFPlistWriteStreamWrite (stream, (const UInt8 *) "\"", 1); } } CFPlistWriteStreamWrite (stream, mark, cursor - mark); loc += read; length -= read; } while (length > 0); CFPlistWriteStreamWrite (stream, (const UInt8 *) "\"", 1); } else { do { read = CFStringGetBytes (str, CFRangeMake (loc, length), kCFStringEncodingUTF8, 0, false, buffer, _kCFPlistBufferSize, &used); CFPlistWriteStreamWrite (stream, (const UInt8 *) buffer, used); loc += read; length -= read; } while (length > 0); } } static void CFOpenStepPlistWriteObject (CFPropertyListRef plist, CFPlistWriteStream * stream, CFIndex lev) { CFTypeID typeID; if (stream->error) return; typeID = CFGetTypeID (plist); if (typeID == CFArrayGetTypeID ()) { /* ( Object1, Object2, ... ) */ CFIndex i; CFIndex count; CFPlistWriteStreamWrite (stream, (const UInt8 *) "(\n", 2); i = 0; count = CFArrayGetCount ((CFArrayRef) plist); while (i < count) { CFPropertyListRef obj; obj = CFArrayGetValueAtIndex ((CFArrayRef) plist, i++); CFPlistIndent (stream, lev + 1); CFOpenStepPlistWriteObject (obj, stream, 0); if (i < count) CFPlistWriteStreamWrite (stream, (const UInt8 *) ",\n", 2); } CFPlistWriteStreamWrite (stream, (const UInt8 *) "\n", 1); CFPlistIndent (stream, lev); CFPlistWriteStreamWrite (stream, (const UInt8 *) ")", 1); } else if (typeID == CFDataGetTypeID ()) { /* */ CFPlistWriteStreamWrite (stream, (const UInt8 *) "<", 1); CFPlistWriteDataBase16 ((CFDataRef) plist, stream); CFPlistWriteStreamWrite (stream, (const UInt8 *) ">", 1); } else if (typeID == CFDictionaryGetTypeID ()) { /* { Key1 = Value1; Key2 = Value2; ... } */ CFIndex count; CFIndex i; const void **keys; CFPlistWriteStreamWrite (stream, (const UInt8 *) "{\n", 2); count = CFDictionaryGetCount ((CFDictionaryRef) plist); keys = CFAllocatorAllocate (kCFAllocatorSystemDefault, sizeof (void *) * count, 0); CFDictionaryGetKeysAndValues ((CFDictionaryRef) plist, keys, NULL); GSCArrayQuickSort (keys, count, (CFComparatorFunction) CFStringCompare, NULL); for (i = 0; i < count; ++i) { CFPropertyListRef obj; CFPlistIndent (stream, lev + 1); CFPlistWriteOpenStepString ((CFStringRef) keys[i], stream); CFPlistWriteStreamWrite (stream, (const UInt8 *) " = ", 3); obj = CFDictionaryGetValue ((CFDictionaryRef) plist, keys[i]); CFOpenStepPlistWriteObject (obj, stream, lev + 1); CFPlistWriteStreamWrite (stream, (const UInt8 *) ";\n", 2); } CFPlistIndent (stream, lev); CFPlistWriteStreamWrite (stream, (const UInt8 *) "}\n", 2); } else if (typeID == CFStringGetTypeID ()) { /* String or "Quotable String" */ CFPlistWriteOpenStepString ((CFStringRef) plist, stream); } else { stream->error = CFPlistCreateError (0, CFSTR ("Invalid property list item encountered while writing OpenStep format.")); } } #if 0 static CFPropertyListRef CFBinaryPlistCreate (CFAllocatorRef alloc, CFDataRef data, CFOptionFlags opts, CFErrorRef * err) { return NULL; } #endif static CFPropertyListRef CFXMLPlistCreate (CFAllocatorRef alloc, CFPlistString * stream) { return NULL; } static const UInt8 _kCFBinaryPlistHeader[] = "bplist00"; static const CFIndex _kCFBinaryPlistHeaderLength = sizeof (_kCFBinaryPlistHeader) - 1; static void CFBinaryPlistWrite (CFPropertyListRef plist, CFPlistWriteStream * stream) { } static const UInt8 _kCFXMLPlistHeader[] = "\n" "\n" "\n"; static const CFIndex _kCFXMLPlistHeaderLength = sizeof (_kCFXMLPlistHeader) - 1; static void CFXMLPlistWrite (CFPropertyListRef plist, CFPlistWriteStream * stream) { CFPlistWriteStreamWrite (stream, _kCFXMLPlistHeader, _kCFXMLPlistHeaderLength); CFXMLPlistWriteObject (plist, stream, 0); CFPlistWriteStreamWrite (stream, (const UInt8 *) "\n", 9); CFPlistWriteStreamFlush (stream); } static const UInt8 UTF8BOM[3] = { 0xEF, 0xBB, 0xBF }; static void CFOpenStepPlistWrite (CFPropertyListRef plist, CFPlistWriteStream * stream) { /* We'll include a UTF-8 BOM to OpenStep formatted property lists. */ CFPlistWriteStreamWrite (stream, UTF8BOM, 3); CFOpenStepPlistWriteObject (plist, stream, 0); CFPlistWriteStreamFlush (stream); } static CFStringEncoding CFPlistGetEncoding (CFDataRef data) { return kCFStringEncodingUTF8; /* FIXME */ } CFPropertyListRef CFPropertyListCreateWithData (CFAllocatorRef alloc, CFDataRef data, CFOptionFlags opts, CFPropertyListFormat * fmt, CFErrorRef * err) { CFPropertyListRef result; CFStringEncoding enc; CFIndex count; CFIndex dataLen; UniChar *start; UniChar *tmp; UniChar buffer[_kCFPlistBufferSize]; const UInt8 *bytes; CFPlistString string; enc = CFPlistGetEncoding (data); if (enc == kCFStringEncodingInvalidId) { if (err) *err = NULL; #if 0 *err = CFPlistCreateError (kCFPropertyListReadCorruptError, CFSTR ("Property list is in an unknown string encoding.")); #endif return NULL; } bytes = CFDataGetBytePtr (data); dataLen = CFDataGetLength (data); start = buffer; tmp = buffer; count = GSUnicodeFromEncoding (&tmp, start + _kCFPlistBufferSize, enc, &bytes, bytes + dataLen, 0); if (count < 0) return NULL; if (count > _kCFPlistBufferSize) { start = CFAllocatorAllocate (kCFAllocatorSystemDefault, count * sizeof (UniChar), 0); if (start == NULL) return NULL; tmp = start; bytes = CFDataGetBytePtr (data); GSUnicodeFromEncoding (&tmp, start + count, enc, &bytes, bytes + dataLen, 0); } string.buffer = start; string.options = opts; string.error = NULL; string.unique = NULL; string.cursor = string.buffer; string.limit = string.buffer + count; result = CFXMLPlistCreate (alloc, &string); if (result) { if (fmt) *fmt = kCFPropertyListXMLFormat_v1_0; return result; } result = CFOpenStepPlistParseObject (alloc, &string); if (result) { if (fmt) *fmt = kCFPropertyListOpenStepFormat; return result; } if (start != buffer) CFAllocatorDeallocate (kCFAllocatorSystemDefault, tmp); return NULL; } CFPropertyListRef CFPropertyListCreateWithStream (CFAllocatorRef alloc, CFReadStreamRef stream, CFIndex len, CFOptionFlags opts, CFPropertyListFormat * fmt, CFErrorRef * err) { CFMutableDataRef data; UInt8 buffer[_kCFPlistBufferSize]; CFIndex read; CFPropertyListRef result; /* We'll read the stream completely into a CFDataRef object for processing. */ data = CFDataCreateMutable (kCFAllocatorSystemDefault, len); do { CFIndex toRead; if (len == 0 || len > _kCFPlistBufferSize) toRead = _kCFPlistBufferSize; else toRead = len; read = CFReadStreamRead (stream, buffer, toRead); if (read > 0) CFDataAppendBytes (data, buffer, read); if (len != 0) len -= read; } while (read > 0); if (read < 0) { CFErrorRef streamError; streamError = CFReadStreamCopyError (stream); if (streamError && err) *err = streamError; return NULL; } result = CFPropertyListCreateWithData (alloc, data, opts, fmt, err); CFRelease (data); return result; } CFDataRef CFPropertyListCreateData (CFAllocatorRef alloc, CFPropertyListRef plist, CFPropertyListFormat fmt, CFOptionFlags opts, CFErrorRef * err) { CFWriteStreamRef stream; CFIndex written; CFDataRef data; stream = CFWriteStreamCreateWithAllocatedBuffers (alloc, alloc); CFWriteStreamOpen (stream); written = CFPropertyListWrite (plist, stream, fmt, opts, err); data = NULL; if (written > 0) data = CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten); CFWriteStreamClose (stream); CFRelease (stream); return data; } CFIndex CFPropertyListWrite (CFPropertyListRef plist, CFWriteStreamRef stream, CFPropertyListFormat fmt, CFOptionFlags opts, CFErrorRef * err) { CFPlistWriteStream plStream; plStream.stream = stream; plStream.options = opts; plStream.error = NULL; plStream.written = 0; plStream.cursor = plStream.buffer; if (fmt == kCFPropertyListOpenStepFormat) CFOpenStepPlistWrite (plist, &plStream); else if (fmt == kCFPropertyListXMLFormat_v1_0) CFXMLPlistWrite (plist, &plStream); else if (fmt == kCFPropertyListBinaryFormat_v1_0) CFBinaryPlistWrite (plist, &plStream); if (plStream.error) { if (err) *err = plStream.error; else CFRelease (plStream.error); return 0; } return plStream.written; } /* The following functions are marked as obsolete as of Mac OS X 10.6. They * will be implemented as wrappers around the new functions. */ CFDataRef CFPropertyListCreateXMLData (CFAllocatorRef alloc, CFPropertyListRef plist) { return CFPropertyListCreateData (alloc, plist, kCFPropertyListXMLFormat_v1_0, 0, NULL); } CFIndex CFPropertyListWriteToStream (CFPropertyListRef plist, CFWriteStreamRef stream, CFPropertyListFormat fmt, CFStringRef * errStr) { CFIndex ret; CFErrorRef err = NULL; ret = CFPropertyListWrite (plist, stream, fmt, 0, &err); if (ret == 0) { if (errStr) *errStr = CFErrorCopyDescription (err); CFRelease (err); } return ret; } CFPropertyListRef CFPropertyListCreateFromXMLData (CFAllocatorRef alloc, CFDataRef data, CFOptionFlags opts, CFStringRef * errStr) { CFPropertyListRef plist; CFErrorRef err = NULL; plist = CFPropertyListCreateWithData (alloc, data, opts, NULL, &err); if (err) { if (errStr) *errStr = CFErrorCopyDescription (err); CFRelease (err); } return plist; } CFPropertyListRef CFPropertyListCreateFromStream (CFAllocatorRef alloc, CFReadStreamRef stream, CFIndex len, CFOptionFlags opts, CFPropertyListFormat * fmt, CFStringRef * errStr) { CFPropertyListRef plist; CFErrorRef err = NULL; plist = CFPropertyListCreateWithStream (alloc, stream, len, opts, fmt, &err); if (err) { if (errStr) *errStr = CFErrorCopyDescription (err); CFRelease (err); } return plist; } gnustep-corebase-0.2/Source/CFRunLoop.c0000644000175000017500000014233114551015633017125 0ustar yavoryavor/* CFRunLoop.c Copyright (C) 2012 Free Software Foundation, Inc. Author: Stefan Bidigaray Date: August, 2012 Author: Lubos Dolezel Date: May, 2014 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFRunLoop.h" #include "CoreFoundation/CFArray.h" #include "CoreFoundation/CFDictionary.h" #include "CoreFoundation/CFSet.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" #if HAVE_CFRUNLOOP_SUPPORT # include # include # include # include #endif #ifdef HAVE_LIBDISPATCH # include #endif /* From NSDate.m in GNUstep-base */ #define DISTANT_FUTURE 63113990400.0 static CFTypeID _kCFRunLoopTypeID = 0; static CFTypeID _kCFRunLoopSourceTypeID = 0; static CFTypeID _kCFRunLoopObserverTypeID = 0; static CFTypeID _kCFRunLoopTimerTypeID = 0; static CFRunLoopRef static_mainLoop = NULL; #if HAVE_CFRUNLOOP_SUPPORT static pthread_key_t static_loopKey; #endif CONST_STRING_DECL(kCFRunLoopDefaultMode, "kCFRunLoopDefaultMode"); CONST_STRING_DECL(kCFRunLoopCommonModes, "kCFRunLoopCommonModes"); typedef struct GSRunLoopContext * GSRunLoopContextRef; struct GSRunLoopContext { CFRunLoopActivity activities; CFMutableArrayRef timers; CFMutableSetRef observers; CFMutableSetRef sources0set; CFMutableArrayRef sources0; CFMutableSetRef sources1; /* This is only a place holder for now. */ CFMutableArrayRef blocks; }; struct __CFRunLoop { CFRuntimeBase parent; GSMutex _lock; CFStringRef _currentMode; CFMutableSetRef _commonModes; CFMutableArrayRef _commonObjects; CFMutableDictionaryRef _contexts; int _wakeUpPipe[2]; Boolean _isWaiting; /* Whether the runloop is currently in a select/poll call */ Boolean _stop; /* Whether the runloop was told to stop */ }; struct __CFRunLoopSource { CFRuntimeBase parent; GSMutex _lock; CFIndex _order; Boolean _isSignaled; // version 0 only Boolean _isValid; union { CFRunLoopSourceContext _context; CFRunLoopSourceContext1 _context1; }; CFRunLoopRef _runloop; }; struct __CFRunLoopObserver { CFRuntimeBase parent; GSMutex _lock; CFOptionFlags _activities; CFIndex _order; Boolean _repeats; Boolean _isValid; CFRunLoopObserverCallBack _callback; CFRunLoopObserverContext _context; CFRunLoopRef _runloop; }; struct __CFRunLoopTimer { CFRuntimeBase base; GSMutex _lock; CFAbsoluteTime _nextFireDate; CFTimeInterval _interval; CFIndex _order; Boolean _isValid; CFRunLoopTimerCallBack _callback; CFRunLoopTimerContext _context; CFRunLoopRef _runloop; }; static GSRunLoopContextRef GSRunLoopContextNew (CFAllocatorRef alloc); static void GSRunLoopContextFinalize (GSRunLoopContextRef ctxt); static void GSRunLoopContextDeallocFunc (const void *key, const void *value, void *ctxt); static void CFRunLoopTimerRemoveFromRunLoop(CFRunLoopRef rl, CFRunLoopTimerRef timer); static const void * BlockRetainCallback(CFAllocatorRef allocator, const void *value) { return (const void *) _Block_copy((void *) value); } static void BlockReleaseCallback(CFAllocatorRef allocator, const void *value) { _Block_release((void *) value); } static const CFArrayCallBacks _kBlockArrayCallbacks = { .version = 0, .retain = BlockRetainCallback, .release = BlockReleaseCallback, .copyDescription = NULL, .equal = NULL }; static void CFRunLoopFinalize (CFTypeRef cf) { CFRunLoopRef rl = (CFRunLoopRef)cf; CFAllocatorRef alloc = CFGetAllocator (rl); CFRelease (rl->_commonModes); CFRelease (rl->_commonObjects); CFDictionaryApplyFunction (rl->_contexts, GSRunLoopContextDeallocFunc, (void*)alloc); CFRelease (rl->_contexts); } static void CFRunLoopSourceFinalize (CFTypeRef cf) { CFRunLoopSourceRef source = (CFRunLoopSourceRef)cf; if (source->_context.release && source->_context.info) source->_context.release (source->_context.info); } static void CFRunLoopObserverFinalize (CFTypeRef cf) { CFRunLoopObserverRef rlo = (CFRunLoopObserverRef)cf; if (rlo->_context.release && rlo->_context.info) rlo->_context.release (rlo->_context.info); } static void CFRunLoopTimerFinalize (CFTypeRef cf) { CFRunLoopTimerRef rlt = (CFRunLoopTimerRef)cf; if (rlt->_context.release && rlt->_context.info) rlt->_context.release (rlt->_context.info); } static CFRuntimeClass CFRunLoopClass = { 0, "CFRunLoop", NULL, NULL, CFRunLoopFinalize, NULL, NULL, NULL, NULL }; static CFRuntimeClass CFRunLoopSourceClass = { 0, "CFRunLoopSource", NULL, NULL, CFRunLoopSourceFinalize, NULL, NULL, NULL, NULL }; static CFRuntimeClass CFRunLoopObserverClass = { 0, "CFRunLoopObserver", NULL, NULL, CFRunLoopObserverFinalize, NULL, NULL, NULL, NULL }; static CFRuntimeClass CFRunLoopTimerClass = { 0, "CFRunLoopTimer", NULL, NULL, CFRunLoopTimerFinalize, NULL, NULL, NULL, NULL }; #define CFRUNLOOP_SIZE \ sizeof(struct __CFRunLoop) - sizeof(CFRuntimeBase) void CFRunLoopInitialize (void) { _kCFRunLoopTypeID = _CFRuntimeRegisterClass (&CFRunLoopClass); _kCFRunLoopSourceTypeID = _CFRuntimeRegisterClass (&CFRunLoopSourceClass); _kCFRunLoopObserverTypeID = _CFRuntimeRegisterClass (&CFRunLoopObserverClass); _kCFRunLoopTimerTypeID = _CFRuntimeRegisterClass (&CFRunLoopTimerClass); } CFTypeID CFRunLoopGetTypeID (void) { return _kCFRunLoopTypeID; } CFTypeID CFRunLoopSourceGetTypeID (void) { return _kCFRunLoopSourceTypeID; } CFTypeID CFRunLoopObserverGetTypeID (void) { return _kCFRunLoopObserverTypeID; } CFTypeID CFRunLoopTimerGetTypeID (void) { return _kCFRunLoopTimerTypeID; } static GSRunLoopContextRef GSRunLoopContextNew (CFAllocatorRef alloc) { GSRunLoopContextRef new; new = CFAllocatorAllocate (alloc, sizeof(struct GSRunLoopContext), 0); if (new) { new->timers = CFArrayCreateMutable (alloc, 0, &kCFTypeArrayCallBacks); new->observers = CFSetCreateMutable (alloc, 0, &kCFTypeSetCallBacks); new->sources0 = CFArrayCreateMutable (alloc, 0, &kCFTypeArrayCallBacks); new->sources0set = CFSetCreateMutable (alloc, 0, &kCFTypeSetCallBacks); new->sources1 = CFSetCreateMutable (alloc, 0, &kCFTypeSetCallBacks); new->blocks = CFArrayCreateMutable (alloc, 0, &_kBlockArrayCallbacks); } return new; } static void GSRunLoopContextFinalize (GSRunLoopContextRef ctxt) { CFRelease (ctxt->timers); CFRelease (ctxt->observers); CFRelease (ctxt->sources0); CFRelease (ctxt->sources0set); CFRelease (ctxt->sources1); CFRelease (ctxt->blocks); } static void GSRunLoopContextDeallocFunc (const void *key, const void *value, void *ctxt) { GSRunLoopContextFinalize ((GSRunLoopContextRef)value); CFAllocatorDeallocate ((CFAllocatorRef)ctxt, (void*)value); } static CFComparisonResult Context0Comparator (const void *val1, const void *val2, void *ctxt) { CFRunLoopSourceRef s1 = (CFRunLoopSourceRef) val1; CFRunLoopSourceRef s2 = (CFRunLoopSourceRef) val2; if (s1->_order < s2->_order) return kCFCompareLessThan; else if (s1->_order > s2->_order) return kCFCompareGreaterThan; else return kCFCompareEqualTo; } static void GSRunLoopContextAddFunc (const void *value, void *context) { CFTypeID typeID = CFGetTypeID (value); GSRunLoopContextRef ctxt = (GSRunLoopContextRef)context; if (typeID == _kCFRunLoopSourceTypeID) { CFRunLoopSourceRef source = (CFRunLoopSourceRef)value; if (source->_context.version == 0) { if (!CFSetContainsValue(ctxt->sources0set, value)) { CFSetAddValue (ctxt->sources0set, value); CFArrayAppendValue (ctxt->sources0, value); CFArraySortValues (ctxt->sources0, CFRangeMake(0, CFArrayGetCount (ctxt->sources0)), Context0Comparator, NULL); } } else if (source->_context.version == 1) CFSetAddValue (ctxt->sources1, value); } else if (typeID == _kCFRunLoopObserverTypeID) { CFSetAddValue (ctxt->observers, value); } else if (typeID == _kCFRunLoopTimerTypeID) { CFRange range = CFRangeMake (0, CFArrayGetCount (ctxt->timers)); if (CFArrayContainsValue (ctxt->timers, range, value) == false) CFArrayAppendValue (ctxt->timers, value); } } static GSRunLoopContextRef GSRunLoopContextGet (CFRunLoopRef rl, CFStringRef mode) { GSRunLoopContextRef ctxt; /* If the modes doesn't exist, create it */ if (!CFDictionaryGetValueIfPresent (rl->_contexts, mode, (const void**)&ctxt)) { ctxt = GSRunLoopContextNew (CFGetAllocator (rl)); CFDictionaryAddValue (rl->_contexts, mode, (const void*)ctxt); } return ctxt; } static CFRunLoopRef CFRunLoopCreate (void) { #if HAVE_CFRUNLOOP_SUPPORT CFRunLoopRef rl; rl = (CFRunLoopRef)_CFRuntimeCreateInstance (kCFAllocatorDefault, _kCFRunLoopTypeID, CFRUNLOOP_SIZE, 0); rl->_commonModes = CFSetCreateMutable(kCFAllocatorDefault, 0, &kCFTypeSetCallBacks); rl->_commonObjects = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks); rl->_contexts = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, NULL); CFSetAddValue(rl->_commonModes, kCFRunLoopDefaultMode); pipe(rl->_wakeUpPipe); fcntl(rl->_wakeUpPipe[0], F_SETFL, O_NONBLOCK); fcntl(rl->_wakeUpPipe[1], F_SETFL, O_NONBLOCK); return rl; #else return NULL; #endif // HAVE_CFRUNLOOP_SUPPORT } static void _CFRunLoopCreateThreadKey (void) { #if HAVE_CFRUNLOOP_SUPPORT pthread_key_create(&static_loopKey, (void(*)(void*)) CFRelease); #endif } CFRunLoopRef CFRunLoopGetCurrent (void) { CFRunLoopRef rl = NULL; #if HAVE_CFRUNLOOP_SUPPORT static pthread_once_t once = PTHREAD_ONCE_INIT; pthread_once(&once, _CFRunLoopCreateThreadKey); rl = pthread_getspecific(static_loopKey); if (rl == NULL) { rl = CFRunLoopCreate(); pthread_setspecific(static_loopKey, rl); } #endif return rl; } static void _CFRunLoopCreateMain (void) { static_mainLoop = CFRunLoopGetCurrent(); } CFRunLoopRef CFRunLoopGetMain (void) { #if HAVE_CFRUNLOOP_SUPPORT static pthread_once_t once = PTHREAD_ONCE_INIT; pthread_once(&once, _CFRunLoopCreateMain); #endif return static_mainLoop; } void CFRunLoopRun (void) { SInt32 code; do { code = CFRunLoopRunInMode (kCFRunLoopDefaultMode, DISTANT_FUTURE, false); } while (code != kCFRunLoopRunFinished && code != kCFRunLoopRunStopped); } static void CFRunLoopNotifyObservers (CFRunLoopRef rl, GSRunLoopContextRef context, CFRunLoopActivity activity) { CFRunLoopObserverRef *observers; CFIndex i, count; GSMutexLock (&rl->_lock); count = CFSetGetCount(context->observers); observers = (CFRunLoopObserverRef*) CFAllocatorAllocate(NULL, sizeof(CFRunLoopObserverRef)*count, 0); CFSetGetValues(context->observers, (const void**) observers); GSMutexUnlock (&rl->_lock); for (i = 0; i < count; i++) CFRetain(observers[i]); for (i = 0; i < count; i++) { CFRunLoopObserverRef observer = observers[i]; if (observer->_isValid && observer->_activities & activity) { observer->_callback(observer, activity, observer->_context.info); if (!observer->_repeats) observer->_isValid = false; } CFRelease(observer); } CFAllocatorDeallocate(NULL, (void*) observers); } static Boolean CFRunLoopProcessTimers (CFRunLoopRef rl, CFAbsoluteTime now, GSRunLoopContextRef context, Boolean singleSource) { CFIndex i, count; CFRunLoopTimerRef *timers; Boolean hadTimer = false; CFRunLoopNotifyObservers(rl, context, kCFRunLoopBeforeTimers); GSMutexLock (&rl->_lock); // Make a copy of timers so that we don't hold the mutex when using the callback // and cause a deadlock. count = CFArrayGetCount(context->timers); timers = (CFRunLoopTimerRef*) CFAllocatorAllocate(NULL, sizeof(CFRunLoopTimerRef)*count, 0); CFArrayGetValues(context->timers, CFRangeMake(0, count), (const void**) timers); GSMutexUnlock (&rl->_lock); for (i = 0; i < count; i++) CFRetain(timers[i]); for (i = 0; i < count; i++) { CFRunLoopTimerRef timer = timers[i]; CFAbsoluteTime nextFireDate = CFRunLoopTimerGetNextFireDate(timer); if (CFRunLoopTimerIsValid(timer)) { if (nextFireDate < now || fabs(now - nextFireDate) < 0.001) { hadTimer = true; if (CF_IS_OBJC(_kCFRunLoopTimerTypeID, timer)) CF_OBJC_VOIDCALLV(timer, "fire"); else timer->_callback(timer, timer->_context.info); // Compute the next time if (!CFRunLoopTimerDoesRepeat(timer)) CFRunLoopTimerInvalidate(timer); } else CFRunLoopTimerSetNextFireDate(timer, now + CFRunLoopTimerGetInterval(timer)); } else CFRunLoopTimerRemoveFromRunLoop(rl, timer); CFRelease(timer); if (singleSource && hadTimer) break; } CFAllocatorDeallocate(NULL, (void*) timers); return hadTimer; } #if HAVE_CFRUNLOOP_SUPPORT static Boolean CFRunLoopProcessSourcesVersion1 (CFRunLoopRef rl, CFAbsoluteTime now, GSRunLoopContextRef context, struct pollfd* pfd, int count) { int i; Boolean hadSource = false; for (i = 0; i < count; i++) { if (pfd[i].revents != 0) { hadSource = true; // TODO: find the corresponding source } } return hadSource; } static Boolean CFRunLoopProcessSourcesVersion0 (CFRunLoopRef rl, CFAbsoluteTime now, GSRunLoopContextRef context, Boolean singleSource) { CFIndex i, count; CFRunLoopSourceRef *sources; Boolean hadSource = false; // Notify observers with kCFRunLoopBeforeSources activity. CFRunLoopNotifyObservers(rl, context, kCFRunLoopBeforeSources); GSMutexLock (&rl->_lock); count = CFArrayGetCount(context->sources0); sources = (CFRunLoopSourceRef*) CFAllocatorAllocate(NULL, sizeof(CFRunLoopSourceRef)*count, 0); CFArrayGetValues(context->sources0, CFRangeMake(0, CFArrayGetCount(context->sources0)), (const void**) sources); GSMutexUnlock (&rl->_lock); for (i = 0; i < count; i++) CFRetain(sources[i]); for (i = 0; i < count; i++) { CFRunLoopSourceRef source = sources[i]; if (source->_isValid && source->_isSignaled) { hadSource = true; source->_isSignaled = false; source->_context.perform(source->_context.info); } CFRelease(source); if (singleSource && hadSource) break; } CFAllocatorDeallocate(NULL, (void*) sources); return hadSource; } static void CFRunLoopPerformBlocks (GSRunLoopContextRef context) { CFIndex i, count; count = CFArrayGetCount(context->blocks); for (i = 0; i < count; i++) { PerformBlockType block = (PerformBlockType) CFArrayGetValueAtIndex(context->blocks, i); CALL_BLOCK_NO_ARGS(block); } CFArrayRemoveAllValues(context->blocks); } #endif // HAVE_CFRUNLOOP_SUPPORT static void CFRunLoopHasAnyValidSources_SourceApplier(const void *value, void *context) { CFRunLoopSourceRef source = (CFRunLoopSourceRef) value; Boolean* hasSource = (Boolean*) context; if (source->_isValid) *hasSource = true; } static void CFRunLoopHasAnyValidSources_TimerApplier(const void *value, void *context) { CFRunLoopTimerRef timer = (CFRunLoopTimerRef) value; Boolean* hasSource = (Boolean*) context; if (timer->_isValid) *hasSource = true; } static Boolean CFRunLoopHasAnyValidSources (CFRunLoopRef rl, GSRunLoopContextRef context) { Boolean hasSource = false; GSMutexLock (&rl->_lock); CFArrayApplyFunction(context->sources0, CFRangeMake(0, CFArrayGetCount(context->sources0)), CFRunLoopHasAnyValidSources_SourceApplier, &hasSource); if (!hasSource) { CFArrayApplyFunction(context->timers, CFRangeMake(0, CFArrayGetCount(context->timers)), CFRunLoopHasAnyValidSources_TimerApplier, &hasSource); } GSMutexUnlock (&rl->_lock); return hasSource; } Boolean _CFRunLoopHasAnyValidSources (CFRunLoopRef rl, CFStringRef mode) { GSRunLoopContextRef context = GSRunLoopContextGet(rl, mode); return CFRunLoopHasAnyValidSources(rl, context); } #if HAVE_CFRUNLOOP_SUPPORT static void Source1Applier(const void *value, void *context) { struct pollfd** ppfd = (struct pollfd**) context; CFRunLoopSourceRef src = (CFRunLoopSourceRef) value; mach_port_t port; port = src->_context1.getPort(src->_context1.info); (*ppfd)->fd = port; (*ppfd)->events = POLLIN | POLLOUT; (*ppfd)++; } static struct pollfd* CFRunLoopPrepareForPoll(struct pollfd* pfd, int* numSources, CFRunLoopRef rl, GSRunLoopContextRef context) { int newSourceCount = 2; struct pollfd* pos; newSourceCount += CFSetGetCount(context->sources1); if (pfd == NULL) { pfd = (struct pollfd*) CFAllocatorAllocate(NULL, newSourceCount * sizeof(struct pollfd), 0); pfd[0].fd = rl->_wakeUpPipe[0]; pfd[0].events = POLLIN; #if HAVE_LIBDISPATCH if (CFRunLoopGetCurrent() == CFRunLoopGetMain()) { // integrate libdispatch pfd[1].fd = dispatch_get_main_queue_eventfd_np(); pfd[1].events = POLLIN; } else #endif { pfd[1].fd = -1; } } else { pfd = (struct pollfd*) CFAllocatorReallocate(NULL, pfd, newSourceCount * sizeof(struct pollfd), 0); } pos = &pfd[2]; GSMutexLock (&rl->_lock); CFSetApplyFunction(context->sources1, Source1Applier, &pos); GSMutexUnlock (&rl->_lock); *numSources = newSourceCount; return pfd; } #endif // HAVE_CFRUNLOOP_SUPPORT SInt32 CFRunLoopRunInMode (CFStringRef mode, CFTimeInterval seconds, Boolean returnAfterSourceHandled) { #if HAVE_CFRUNLOOP_SUPPORT /* This is the sequence of events: * 1. Notify observers with kCFRunLoopEntry activity. * 2. Notify observers with kCFRunLoopBeforeTimers activitiy. * 3. Notify observers with kCFRunLoopBeforeSources activity. * 4. Fire version 0 sources. * 5. If a version 1 source is ready and waiting to fire, process the * event immediately. Go to step 9. * 6. Notify observers with kCFRunLoopBeforeWaiting activity. * 7. Put the thread to sleep until one of the following events occurs: * - An event arrives for a port-based input source. * - A timer fires. * - The seconds argument expires. * - Someone calls CFRunLoopWakeUp(). * 8. Notify observers with kCFRunLoopAfterWaiting activity. * 9. Process the pending event. * - Process timers with fire dates in the past. * - If an input source fired, deliver the event. * - If CFRunLoopWakeUp() was called but the run loop has not timed out, * restart the loop. Go to step 2. * 10. Notify observers with kCFRunLoopExit activity. */ CFRunLoopRef rl = CFRunLoopGetCurrent(); const CFAbsoluteTime timeStart = CFAbsoluteTimeGetCurrent(); CFAbsoluteTime timeNow = timeStart; SInt32 exitReason = 0; Boolean hadSource = false; struct pollfd* pfd = NULL; int numSources = 0; GSRunLoopContextRef context = GSRunLoopContextGet(rl, mode); rl->_currentMode = mode; // Notify observers with kCFRunLoopEntry activity. CFRunLoopNotifyObservers(rl, context, kCFRunLoopEntry); CFRunLoopProcessTimers(rl, timeStart, context, returnAfterSourceHandled); if (!returnAfterSourceHandled || !hadSource) hadSource |= CFRunLoopProcessSourcesVersion0(rl, timeStart, context, returnAfterSourceHandled); GSMutexUnlock (&rl->_lock); if (returnAfterSourceHandled && hadSource) { exitReason = kCFRunLoopRunHandledSource; } timeNow = CFAbsoluteTimeGetCurrent(); while (exitReason == 0) { int sourcesFired, timeout; hadSource = false; if (!returnAfterSourceHandled) { if (seconds == 0) timeout = 0; // only one pass else if (seconds >= DISTANT_FUTURE) timeout = -1; else timeout = (int) ((seconds - (timeNow - timeStart)) * 1000); } else { timeout = -1; } if (!CFRunLoopHasAnyValidSources(rl, context)) { exitReason = kCFRunLoopRunFinished; break; } if (timeout != 0) { // Check all timers in current mode and plan the timeout accordingly. CFAbsoluteTime nextTimer = CFRunLoopGetNextTimerFireDate(rl, mode); if (nextTimer < DISTANT_FUTURE) { int delay = (int) ( (nextTimer - timeNow)*1000 ); // printf("(%f-%f)*1000=%d\n", nextTimer, timeNow, delay); if (timeout == -1 || delay < timeout) timeout = delay; if (timeout < 0) timeout = 0; } } if (rl->_stop) { exitReason = kCFRunLoopRunStopped; rl->_stop = false; break; } GSMutexLock (&rl->_lock); CFRunLoopPerformBlocks(context); GSMutexUnlock (&rl->_lock); // Notify observers with kCFRunLoopBeforeWaiting activity. CFRunLoopNotifyObservers(rl, context, kCFRunLoopBeforeWaiting); rl->_isWaiting = true; pfd = CFRunLoopPrepareForPoll(pfd, &numSources, rl, context); // printf("poll: %d ms\n", timeout); // printf("poll %d sources\n", numSources); sourcesFired = poll(pfd, numSources, timeout); rl->_isWaiting = false; // Notify observers with kCFRunLoopAfterWaiting activity. CFRunLoopNotifyObservers(rl, context, kCFRunLoopAfterWaiting); if (sourcesFired < 0) // error { // TODO: print explanation into the console? exitReason = kCFRunLoopRunFinished; break; } else if (sourcesFired > 0) { if (pfd[0].revents != 0) { int dummy; // printf("loop woken up!\n"); // Remove everything from the notification pipe that woke us up while (read(pfd[0].fd, &dummy, sizeof(dummy)) > 0); } #if HAVE_LIBDISPATCH if (pfd[1].revents != 0) { dispatch_main_queue_drain_np(); hadSource = true; } #endif } CFRunLoopProcessTimers(rl, timeNow, context, returnAfterSourceHandled); if (!returnAfterSourceHandled || !hadSource) { hadSource |= CFRunLoopProcessSourcesVersion0(rl, timeNow, context, returnAfterSourceHandled); } if (!returnAfterSourceHandled || !hadSource) { hadSource |= CFRunLoopProcessSourcesVersion1(rl, timeNow, context, &pfd[2], numSources-2); } if (returnAfterSourceHandled && hadSource) { exitReason = kCFRunLoopRunHandledSource; break; } timeNow = CFAbsoluteTimeGetCurrent(); if (CFAbsoluteTimeGetCurrent() >= timeStart+seconds) { exitReason = kCFRunLoopRunTimedOut; break; } } // Notify observers with kCFRunLoopExit activity. CFRunLoopNotifyObservers(rl, context, kCFRunLoopExit); rl->_currentMode = NULL; CFAllocatorDeallocate(NULL, pfd); return exitReason; #else return kCFRunLoopRunStopped; // not implemented #endif // HAVE_CFRUNLOOP_SUPPORT } void CFRunLoopWakeUp (CFRunLoopRef rl) { if (CFRunLoopIsWaiting(rl)) { #if HAVE_CFRUNLOOP_SUPPORT int dummy = 1; write(rl->_wakeUpPipe[1], &dummy, sizeof(dummy)); #endif } } void CFRunLoopStop (CFRunLoopRef rl) { if (rl->_currentMode != NULL) rl->_stop = true; } Boolean CFRunLoopIsWaiting (CFRunLoopRef rl) { return rl->_isWaiting; } void CFRunLoopAddCommonMode (CFRunLoopRef rl, CFStringRef mode) { GSMutexLock (&rl->_lock); if (CFSetContainsValue (rl->_commonModes, mode) == false) { GSRunLoopContextRef new; CFIndex cnt; CFSetAddValue (rl->_commonModes, mode); new = GSRunLoopContextNew (CFGetAllocator(rl)); cnt = CFArrayGetCount(rl->_commonObjects); CFArrayApplyFunction (rl->_commonObjects, CFRangeMake (0, cnt), GSRunLoopContextAddFunc, new); CFDictionaryAddValue (rl->_contexts, mode, new); } GSMutexUnlock (&rl->_lock); } static void CFRunLoopCopyKeysFunc (const void *key, const void *value, void *context) { CFMutableArrayRef array = (CFMutableArrayRef)context; CFArrayAppendValue (array, key); } CFArrayRef CFRunLoopCopyAllModes (CFRunLoopRef rl) { CFArrayRef ret; CFMutableArrayRef a; CFIndex cnt; GSMutexLock (&rl->_lock); cnt = CFDictionaryGetCount (rl->_contexts); a = CFArrayCreateMutable (NULL, cnt, &kCFTypeArrayCallBacks); CFDictionaryApplyFunction (rl->_contexts, CFRunLoopCopyKeysFunc, a); GSMutexUnlock (&rl->_lock); ret = CFArrayCreateCopy (NULL, a); CFRelease (a); return ret; } CFStringRef CFRunLoopCopyCurrentMode (CFRunLoopRef rl) { CFStringRef mode = rl->_currentMode; if (mode != NULL) return CFRetain (rl->_currentMode); else return NULL; } static void CFRunLoopPerformBlock_nolock (CFRunLoopRef rl, CFTypeRef mode, PerformBlockType block) { if (CFGetTypeID(mode) == CFStringGetTypeID()) { GSRunLoopContextRef ctxt; ctxt = GSRunLoopContextGet (rl, mode); CFArrayAppendValue(ctxt->blocks, block); } else if (CFGetTypeID(mode) == CFArrayGetTypeID()) { CFIndex i, count; CFArrayRef array = (CFArrayRef) mode; count = CFArrayGetCount(array); for (i = 0; i < count; i++) { CFTypeRef m = CFArrayGetValueAtIndex(array, i); CFRunLoopPerformBlock_nolock(rl, m, block); } } } void CFRunLoopPerformBlock (CFRunLoopRef rl, CFTypeRef mode, PerformBlockType block) { GSMutexLock (&rl->_lock); CFRunLoopPerformBlock_nolock(rl, mode, block); GSMutexUnlock (&rl->_lock); } /* The next few function are used to add objects to the common modes */ struct common_mode_info { CFRunLoopRef rl; CFTypeRef obj; Boolean ret; }; /* Call the _nolock variant of the Add, Remove and Contain functions * when the run loop is already locked. */ static void CFRunLoopAddSource_nolock (CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode) { GSRunLoopContextRef ctxt; if (source->_runloop != NULL && source->_runloop != rl) return; // This source is already added elsewhere source->_runloop = rl; ctxt = GSRunLoopContextGet (rl, mode); if (source->_context.version == 0) { if (!CFSetContainsValue(ctxt->sources0set, source)) { CFSetAddValue (ctxt->sources0set, source); CFArrayAppendValue (ctxt->sources0, source); CFArraySortValues (ctxt->sources0, CFRangeMake(0, CFArrayGetCount (ctxt->sources0)), Context0Comparator, NULL); } } else if (source->_context.version == 1) CFSetAddValue (ctxt->sources1, source); CFRunLoopWakeUp(rl); } static void CFRunLoopAddObserver_nolock (CFRunLoopRef rl, CFRunLoopObserverRef obs, CFStringRef mode) { GSRunLoopContextRef ctxt; CFMutableSetRef observers; if (obs->_runloop != NULL && obs->_runloop != rl) return; // This observer is already added elsewhere obs->_runloop = rl; ctxt = GSRunLoopContextGet (rl, mode); observers = ctxt->observers; CFSetAddValue (observers, obs); } static void CFRunLoopAddTimer_nolock (CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode) { GSRunLoopContextRef ctxt; CFRange range; if (timer->_runloop != NULL && timer->_runloop != rl) return; // This timer is already added elsewhere timer->_runloop = rl; ctxt = GSRunLoopContextGet (rl, mode); /* Only add the timer if one doesn't exist */ range = CFRangeMake (0, CFArrayGetCount (ctxt->timers)); if (CFArrayContainsValue (ctxt->timers, range, timer) == false) CFArrayAppendValue (ctxt->timers, timer); // Wake up the runloop so that it can recalculate the next timer date CFRunLoopWakeUp(rl); } static Boolean CFRunLoopContainsSource_nolock (CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode) { Boolean ret = false; GSRunLoopContextRef ctxt; ctxt = GSRunLoopContextGet (rl, mode); if (source->_context.version == 0) ret = CFSetContainsValue (ctxt->sources0set, source); else if (source->_context.version == 1) ret = CFSetContainsValue (ctxt->sources1, source); return ret; } static Boolean CFRunLoopContainsObserver_nolock (CFRunLoopRef rl, CFRunLoopObserverRef obs, CFStringRef mode) { Boolean ret; GSRunLoopContextRef ctxt; ctxt = GSRunLoopContextGet (rl, mode); ret = CFSetContainsValue (ctxt->observers, obs); return ret; } static Boolean CFRunLoopContainsTimer_nolock (CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode) { Boolean ret; GSRunLoopContextRef ctxt; CFRange range; ctxt = GSRunLoopContextGet (rl, mode); range = CFRangeMake (0, CFArrayGetCount (ctxt->timers)); ret = CFArrayContainsValue (ctxt->timers, range, timer); return ret; } static void CFRunLoopRemoveSource_nolock (CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode) { GSRunLoopContextRef ctxt; ctxt = GSRunLoopContextGet (rl, mode); if (source->_context.version == 0) { CFIndex idx = CFArrayGetFirstIndexOfValue(ctxt->sources0, CFRangeMake(0, CFArrayGetCount(ctxt->sources0)), source); if (idx != -1) { CFSetRemoveValue (ctxt->sources0set, source); CFArrayRemoveValueAtIndex(ctxt->sources0, idx); } } else if (source->_context.version == 1) CFSetRemoveValue (ctxt->sources1, source); } static void CFRunLoopRemoveObserver_nolock (CFRunLoopRef rl, CFRunLoopObserverRef obs, CFStringRef mode) { GSRunLoopContextRef ctxt; ctxt = GSRunLoopContextGet (rl, mode); CFSetRemoveValue (ctxt->observers, obs); } static void CFRunLoopRemoveTimer_nolock (CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode) { GSRunLoopContextRef ctxt; CFIndex idx; CFRange range; ctxt = GSRunLoopContextGet (rl, mode); range = CFRangeMake (0, CFArrayGetCount (ctxt->timers)); idx = CFArrayGetFirstIndexOfValue (ctxt->timers, range, timer); if (idx != kCFNotFound) CFArrayRemoveValueAtIndex (ctxt->timers, idx); } static void CFRunLoopCommonModesAddFunc (const void *value, void *context) { struct common_mode_info *info = (struct common_mode_info*)context; CFTypeID typeID = CFGetTypeID (info->obj); if (typeID == _kCFRunLoopSourceTypeID) CFRunLoopAddSource_nolock (info->rl, (CFRunLoopSourceRef)info->obj, (CFStringRef)value); else if (typeID == _kCFRunLoopObserverTypeID) CFRunLoopAddObserver_nolock (info->rl, (CFRunLoopObserverRef)info->obj, (CFStringRef)value); else if (typeID == _kCFRunLoopTimerTypeID) CFRunLoopAddTimer_nolock (info->rl, (CFRunLoopTimerRef)info->obj, (CFStringRef)value); } static void CFRunLoopCommonModesAdd (CFRunLoopRef rl, CFTypeRef obj) { struct common_mode_info info = { rl, obj, false }; CFSetApplyFunction (rl->_commonModes, CFRunLoopCommonModesAddFunc, &info); CFArrayAppendValue (rl->_commonObjects, obj); } static void CFRunLoopCommonModesContainFunc (const void *value, void *context) { Boolean ret = false; struct common_mode_info *info = (struct common_mode_info*)context; CFTypeID typeID = CFGetTypeID (info->obj); if (typeID == _kCFRunLoopSourceTypeID) ret = CFRunLoopContainsSource_nolock (info->rl, (CFRunLoopSourceRef)info->obj, (CFStringRef)value); else if (typeID == _kCFRunLoopObserverTypeID) ret = CFRunLoopContainsObserver_nolock (info->rl, (CFRunLoopObserverRef)info->obj, (CFStringRef)value); else if (typeID == _kCFRunLoopTimerTypeID) ret = CFRunLoopContainsTimer_nolock (info->rl, (CFRunLoopTimerRef)info->obj, (CFStringRef)value); if (ret) { info->ret = ret; } } static Boolean CFRunLoopCommonModesContain (CFRunLoopRef rl, CFTypeRef obj) { CFRange range = CFRangeMake (0, CFArrayGetCount (rl->_commonObjects)); if (CFArrayContainsValue (rl->_commonObjects, range, obj)) { return true; } else { struct common_mode_info info = { rl, obj, false }; CFSetApplyFunction (rl->_commonModes, CFRunLoopCommonModesContainFunc, &info); return info.ret; } } static void CFRunLoopCommonModesRemoveFunc (const void *value, void *context) { struct common_mode_info *info = (struct common_mode_info*)context; CFTypeID typeID = CFGetTypeID (info->obj); if (typeID == _kCFRunLoopSourceTypeID) CFRunLoopRemoveSource_nolock (info->rl, (CFRunLoopSourceRef)info->obj, (CFStringRef)value); else if (typeID == _kCFRunLoopObserverTypeID) CFRunLoopRemoveObserver_nolock (info->rl, (CFRunLoopObserverRef)info->obj, (CFStringRef)value); else if (typeID == _kCFRunLoopTimerTypeID) CFRunLoopRemoveTimer_nolock (info->rl, (CFRunLoopTimerRef)info->obj, (CFStringRef)value); } static void CFRunLoopCommonModesRemove (CFRunLoopRef rl, CFTypeRef obj) { CFRange range; CFIndex idx; struct common_mode_info info = { rl, obj, false }; range = CFRangeMake (0, CFArrayGetCount (rl->_commonObjects)); idx = CFArrayContainsValue (rl->_commonObjects, range, obj); if (idx != kCFNotFound) CFArrayRemoveValueAtIndex (rl->_commonObjects, idx); CFSetApplyFunction (rl->_commonModes, CFRunLoopCommonModesRemoveFunc, &info); } void CFRunLoopAddSource (CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode) { GSMutexLock (&rl->_lock); if (mode == kCFRunLoopCommonModes) CFRunLoopCommonModesAdd (rl, source); else CFRunLoopAddSource_nolock (rl, source, mode); GSMutexUnlock (&rl->_lock); /* Call the schedule callback if it exists, but do it only once */ if (source->_context.version == 0 && source->_context.schedule != NULL) source->_context.schedule (source->_context.info, rl, mode); } void CFRunLoopAddObserver (CFRunLoopRef rl, CFRunLoopObserverRef observer, CFStringRef mode) { GSMutexLock (&rl->_lock); if (mode == kCFRunLoopCommonModes) CFRunLoopCommonModesAdd (rl, observer); else CFRunLoopAddObserver_nolock (rl, observer, mode); GSMutexUnlock (&rl->_lock); } void CFRunLoopAddTimer (CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode) { GSMutexLock (&rl->_lock); if (mode == kCFRunLoopCommonModes) CFRunLoopCommonModesAdd (rl, timer); else CFRunLoopAddTimer_nolock (rl, timer, mode); GSMutexUnlock (&rl->_lock); } Boolean CFRunLoopContainsSource (CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode) { Boolean ret = false; GSMutexLock (&rl->_lock); if (mode == kCFRunLoopCommonModes) ret = CFRunLoopCommonModesContain (rl, source); else ret = CFRunLoopContainsSource_nolock (rl, source, mode); GSMutexUnlock (&rl->_lock); return ret; } Boolean CFRunLoopContainsObserver (CFRunLoopRef rl, CFRunLoopObserverRef observer, CFStringRef mode) { Boolean ret; GSMutexLock (&rl->_lock); if (mode == kCFRunLoopCommonModes) ret = CFRunLoopCommonModesContain (rl, observer); else ret = CFRunLoopContainsObserver_nolock (rl, observer, mode); GSMutexUnlock (&rl->_lock); return ret; } Boolean CFRunLoopContainsTimer (CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode) { Boolean ret; GSMutexLock (&rl->_lock); if (mode == kCFRunLoopCommonModes) ret = CFRunLoopCommonModesContain (rl, timer); else ret = CFRunLoopContainsTimer_nolock (rl, timer, mode); GSMutexUnlock (&rl->_lock); return ret; } void CFRunLoopRemoveSource (CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode) { GSMutexLock (&rl->_lock); if (mode == kCFRunLoopCommonModes) CFRunLoopCommonModesRemove (rl, source); else CFRunLoopRemoveSource_nolock (rl, source, mode); GSMutexUnlock (&rl->_lock); /* Call the cancel callback if it exists, but do it only once */ if (source->_context.version == 0 && source->_context.cancel != NULL) source->_context.cancel (source->_context.info, rl, mode); } void CFRunLoopRemoveObserver (CFRunLoopRef rl, CFRunLoopObserverRef observer, CFStringRef mode) { GSMutexLock (&rl->_lock); if (mode == kCFRunLoopCommonModes) CFRunLoopCommonModesRemove (rl, observer); else CFRunLoopRemoveObserver_nolock (rl, observer, mode); GSMutexUnlock (&rl->_lock); } void CFRunLoopRemoveTimer (CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode) { GSMutexLock (&rl->_lock); if (mode == kCFRunLoopCommonModes) CFRunLoopCommonModesRemove (rl, timer); else CFRunLoopRemoveTimer_nolock (rl, timer, mode); GSMutexUnlock (&rl->_lock); } #define CFRUNLOOPSOURCE_SIZE \ sizeof(struct __CFRunLoopSource) - sizeof(CFRuntimeBase) CFRunLoopSourceRef CFRunLoopSourceCreate (CFAllocatorRef alloc, CFIndex order, CFRunLoopSourceContext *context) { CFRunLoopSourceRef new; new = (CFRunLoopSourceRef)_CFRuntimeCreateInstance (alloc, _kCFRunLoopSourceTypeID, CFRUNLOOPSOURCE_SIZE, 0); if (new) { GSMutexInitialize (&(new->_lock)); new->_isValid = true; new->_order = order; if (context) { switch (context->version) { case 0: new->_context = *context; if (context->retain) new->_context.info = (void*)context->retain (context->info); break; case 1: new->_context1 = *((CFRunLoopSourceContext1*)context); if (new->_context1.retain) new->_context1.info = (void*)new->_context1.retain (((CFRunLoopSourceContext1*)context)->info); break; } } } return new; } void CFRunLoopSourceGetContext (CFRunLoopSourceRef source, CFRunLoopSourceContext *context) { if (source->_context.version == 0) *context = source->_context; else if (source->_context.version == 1) *((CFRunLoopSourceContext1*) context) = source->_context1; } CFIndex CFRunLoopSourceGetOrder (CFRunLoopSourceRef source) { return source->_order; } static void CFRunLoopSourceRemoveInvalidated(const void *key, const void *value, void *source) { GSRunLoopContextRef ctxt = (GSRunLoopContextRef) value; CFIndex idx = CFArrayGetFirstIndexOfValue(ctxt->sources0, CFRangeMake(0, CFArrayGetCount(ctxt->timers)), (CFRunLoopSourceRef) source); if (idx != -1) { CFArrayRemoveValueAtIndex(ctxt->sources0, idx); CFSetRemoveValue(ctxt->sources0set, source); } } void CFRunLoopSourceInvalidate (CFRunLoopSourceRef source) { source->_isValid = false; if (source->_runloop != NULL) { GSMutexLock(&source->_runloop->_lock); CFIndex idx = CFArrayGetFirstIndexOfValue(source->_runloop->_commonObjects, CFRangeMake(0, CFArrayGetCount(source->_runloop->_commonObjects)), source); if (idx != -1) CFArrayRemoveValueAtIndex(source->_runloop->_commonObjects, idx); CFDictionaryApplyFunction(source->_runloop->_contexts, CFRunLoopSourceRemoveInvalidated, source); GSMutexUnlock(&source->_runloop->_lock); } } Boolean CFRunLoopSourceIsValid (CFRunLoopSourceRef source) { return source->_isValid; } void CFRunLoopSourceSignal (CFRunLoopSourceRef source) { source->_isSignaled = true; CFRunLoopWakeUp(source->_runloop); } #define CFRUNLOOPOBSERVER_SIZE \ sizeof(struct __CFRunLoopObserver) - sizeof(CFRuntimeBase) CFRunLoopObserverRef CFRunLoopObserverCreate (CFAllocatorRef alloc, CFOptionFlags activities, Boolean repeats, CFIndex order, CFRunLoopObserverCallBack callback, CFRunLoopObserverContext *context) { CFRunLoopObserverRef new; new = (CFRunLoopObserverRef)_CFRuntimeCreateInstance (alloc, _kCFRunLoopObserverTypeID, CFRUNLOOPOBSERVER_SIZE, 0); if (new) { GSMutexInitialize (&(new->_lock)); new->_activities = activities; new->_repeats = repeats; new->_order = order; new->_callback = callback; if (context) { new->_context = *context; if (context->retain) new->_context.info = (void*)context->retain (context->info); } } return new; } Boolean CFRunLoopObserverDoesRepeat (CFRunLoopObserverRef observer) { return observer->_repeats; } CFOptionFlags CFRunLoopObserverGetActivities (CFRunLoopObserverRef observer) { return observer->_activities; } void CFRunLoopObserverGetContext (CFRunLoopObserverRef observer, CFRunLoopObserverContext *context) { *context = observer->_context; } CFIndex CFRunLoopObserverGetOrder (CFRunLoopObserverRef observer) { return observer->_order; } static void CFRunLoopObserverRemoveInvalidated(const void *key, const void *value, void *observer) { GSRunLoopContextRef ctxt = (GSRunLoopContextRef) value; CFSetRemoveValue(ctxt->observers, observer); } void CFRunLoopObserverInvalidate (CFRunLoopObserverRef observer) { observer->_isValid = false; if (observer->_runloop != NULL) { GSMutexLock(&observer->_runloop->_lock); CFIndex idx = CFArrayGetFirstIndexOfValue(observer->_runloop->_commonObjects, CFRangeMake(0, CFArrayGetCount(observer->_runloop->_commonObjects)), observer); if (idx != -1) CFArrayRemoveValueAtIndex(observer->_runloop->_commonObjects, idx); CFDictionaryApplyFunction(observer->_runloop->_contexts, CFRunLoopObserverRemoveInvalidated, observer); GSMutexUnlock(&observer->_runloop->_lock); } } Boolean CFRunLoopObserverIsValid (CFRunLoopObserverRef observer) { return observer->_isValid; } CFAbsoluteTime CFRunLoopGetNextTimerFireDate (CFRunLoopRef rl, CFStringRef mode) { CFAbsoluteTime rv = DISTANT_FUTURE; CFIndex i, count; GSRunLoopContextRef context = GSRunLoopContextGet(rl, mode); count = CFArrayGetCount(context->timers); // printf("Current time: %f\n", CFAbsoluteTimeGetCurrent()); for (i = 0; i < count; i++) { CFRunLoopTimerRef timer = (CFRunLoopTimerRef) CFArrayGetValueAtIndex(context->timers, i); // printf("Timer %p valid:%d nextFireDate:%f\n", timer, timer->_isValid, timer->_nextFireDate); if (CFRunLoopTimerIsValid(timer)) { CFAbsoluteTime t = CFRunLoopTimerGetNextFireDate(timer); if (t < rv) rv = t; } } return rv; } #define CFRUNLOOPTIMER_SIZE \ sizeof(struct __CFRunLoopTimer) - sizeof(CFRuntimeBase) CFRunLoopTimerRef CFRunLoopTimerCreate (CFAllocatorRef alloc, CFAbsoluteTime fireDate, CFTimeInterval interval, CFOptionFlags flags, CFIndex order, CFRunLoopTimerCallBack callback, CFRunLoopTimerContext *context) { CFRunLoopTimerRef new; new = (CFRunLoopTimerRef)_CFRuntimeCreateInstance (alloc, _kCFRunLoopTimerTypeID, CFRUNLOOPTIMER_SIZE, 0); if (new) { GSMutexInitialize (&(new->_lock)); new->_isValid = true; new->_nextFireDate = fireDate; new->_interval = interval; /* 'flags' is ignored */ new->_order = order; new->_callback = callback; if (context) { new->_context = *context; if (context->retain) new->_context.info = (void*)context->retain (context->info); } } return new; } Boolean CFRunLoopTimerDoesRepeat (CFRunLoopTimerRef timer) { if (CF_IS_OBJC(_kCFRunLoopTimerTypeID, timer)) { CFTimeInterval iv; CF_OBJC_CALLV(CFTimeInterval, iv, timer, "timeInterval"); return iv > 0.0; } return (timer->_interval > 0.0); } void CFRunLoopTimerGetContext (CFRunLoopTimerRef timer, CFRunLoopTimerContext *context) { /* FIXME: need this method in NSTimer. */ CF_OBJC_FUNCDISPATCHV(_kCFRunLoopTimerTypeID, void, timer, "_cfContext:", context); *context = timer->_context; } CFTimeInterval CFRunLoopTimerGetInterval (CFRunLoopTimerRef timer) { CF_OBJC_FUNCDISPATCHV(_kCFRunLoopTimerTypeID, CFTimeInterval, timer, "timeInterval"); return timer->_interval; } CFAbsoluteTime CFRunLoopTimerGetNextFireDate (CFRunLoopTimerRef timer) { if (CF_IS_OBJC(_kCFRunLoopTimerTypeID, timer)) { CFDateRef date; CF_OBJC_CALLV(CFDateRef, date, timer, "fireDate"); return CFDateGetAbsoluteTime(date); } return timer->_nextFireDate; } CFIndex CFRunLoopTimerGetOrder (CFRunLoopTimerRef timer) { /* FIXME: need this method in NSTimer. */ CF_OBJC_FUNCDISPATCHV(_kCFRunLoopTimerTypeID, CFIndex, timer, "_cfOrder"); return timer->_order; } static void CFRunLoopTimerRemoveInvalidated(const void *key, const void *value, void *timer) { GSRunLoopContextRef ctxt = (GSRunLoopContextRef) value; CFIndex idx = CFArrayGetFirstIndexOfValue(ctxt->timers, CFRangeMake(0, CFArrayGetCount(ctxt->timers)), (CFRunLoopTimerRef) timer); if (idx != -1) CFArrayRemoveValueAtIndex(ctxt->timers, idx); } static void CFRunLoopTimerRemoveFromRunLoop(CFRunLoopRef rl, CFRunLoopTimerRef timer) { GSMutexLock(&rl->_lock); CFIndex idx = CFArrayGetFirstIndexOfValue(rl->_commonObjects, CFRangeMake(0, CFArrayGetCount(rl->_commonObjects)), timer); if (idx != -1) CFArrayRemoveValueAtIndex(rl->_commonObjects, idx); CFDictionaryApplyFunction(rl->_contexts, CFRunLoopTimerRemoveInvalidated, timer); GSMutexUnlock(&rl->_lock); } void CFRunLoopTimerInvalidate (CFRunLoopTimerRef timer) { CF_OBJC_FUNCDISPATCHV(_kCFRunLoopTimerTypeID, void, timer, "invalidate"); timer->_isValid = false; } Boolean CFRunLoopTimerIsValid (CFRunLoopTimerRef timer) { CF_OBJC_FUNCDISPATCHV(_kCFRunLoopTimerTypeID, Boolean, timer, "isValid"); return timer->_isValid; } void CFRunLoopTimerSetNextFireDate (CFRunLoopTimerRef timer, CFAbsoluteTime fireDate) { if (CF_IS_OBJC(_kCFRunLoopTimerTypeID, timer)) { CFDateRef date = CFDateCreate(NULL, fireDate); CF_OBJC_VOIDCALLV(timer, "setFireDate:", date); return; } timer->_nextFireDate = fireDate; // Wake up the runloop so that it can recalculate the next timer date // but since timers should be planned on current runloop only (NSTimer // says so), this may not be necessary. CFRunLoopWakeUp(timer->_runloop); } gnustep-corebase-0.2/Source/NSCFNumber.m0000644000175000017500000001103614551015633017227 0ustar yavoryavor/* NSCFNumber.m Copyright (C) 2020 Free Software Foundation, Inc. Written by: Frederik Seiffert Date: March, 2020 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #import #include "NSCFType.h" #include "CoreFoundation/CFNumber.h" @interface NSCFNumber : NSNumber NSCFTYPE_VARS @end @interface NSNumber (CoreBaseAdditions) - (CFTypeID) _cfTypeID; @end @implementation NSCFNumber + (void) load { NSCFInitialize (); } + (void) initialize { GSObjCAddClassBehavior (self, [NSCFType class]); } - (const char *) objCType { CFNumberType type = CFNumberGetType((CFNumberRef)self); switch (type) { case kCFNumberSInt8Type: return @encode(SInt8); case kCFNumberSInt16Type: return @encode(SInt16); case kCFNumberSInt32Type: return @encode(SInt32); case kCFNumberSInt64Type: return @encode(SInt64); case kCFNumberFloat32Type: return @encode(Float32); case kCFNumberFloat64Type: return @encode(Float64); case kCFNumberCharType: return @encode(char); case kCFNumberShortType: return @encode(short); case kCFNumberIntType: return @encode(int); case kCFNumberLongType: return @encode(long); case kCFNumberLongLongType: return @encode(long long); case kCFNumberFloatType: return @encode(float); case kCFNumberDoubleType: return @encode(double); case kCFNumberCFIndexType: return @encode(CFIndex); #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) case kCFNumberNSIntegerType: return @encode(NSInteger); case kCFNumberCGFloatType: return @encode(CGFloat); #endif } return NULL; } - (NSString*) descriptionWithLocale: (id)aLocale { return AUTORELEASE((id) CFCopyDescription(self)); } - (BOOL) boolValue { BOOL value; CFNumberGetValue((CFNumberRef)self, kCFNumberCharType, &value); return value; } - (signed char) charValue { signed char value; CFNumberGetValue((CFNumberRef)self, kCFNumberCharType, &value); return value; } - (double) doubleValue { double value; CFNumberGetValue((CFNumberRef)self, kCFNumberDoubleType, &value); return value; } - (float) floatValue { float value; CFNumberGetValue((CFNumberRef)self, kCFNumberFloatType, &value); return value; } - (signed int) intValue { signed int value; CFNumberGetValue((CFNumberRef)self, kCFNumberIntType, &value); return value; } - (signed long) longValue { signed long value; CFNumberGetValue((CFNumberRef)self, kCFNumberLongType, &value); return value; } - (signed long long) longLongValue { signed long long value; CFNumberGetValue((CFNumberRef)self, kCFNumberLongLongType, &value); return value; } - (signed short) shortValue { signed short value; CFNumberGetValue((CFNumberRef)self, kCFNumberShortType, &value); return value; } - (unsigned char) unsignedCharValue { unsigned char value; CFNumberGetValue((CFNumberRef)self, kCFNumberCharType, &value); return value; } - (unsigned int) unsignedIntValue { unsigned int value; CFNumberGetValue((CFNumberRef)self, kCFNumberIntType, &value); return value; } - (unsigned long) unsignedLongValue { unsigned long value; CFNumberGetValue((CFNumberRef)self, kCFNumberLongType, &value); return value; } - (unsigned long long) unsignedLongLongValue { unsigned long long value; CFNumberGetValue((CFNumberRef)self, kCFNumberLongLongType, &value); return value; } - (unsigned short) unsignedShortValue { unsigned short value; CFNumberGetValue((CFNumberRef)self, kCFNumberShortType, &value); return value; } @end @implementation NSNumber (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFNumberGetTypeID(); } @end gnustep-corebase-0.2/Source/CFLocale.c0000664000175000017500000007736114661604117016745 0ustar yavoryavor/* CFLocale.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: March, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFCalendar.h" #include "CoreFoundation/CFNumberFormatter.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFLocale.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" #include #if defined(HAVE_UNICODE_ULOC_H) #include #endif #if defined(HAVE_UNICODE_ULOCDATA_H) #include #endif #if defined(HAVE_UNICODE_UCURR_H) #include #endif #if defined(HAVE_ICU_H) #include #endif #define BUFFER_SIZE 256 #define ICU_CALENDAR_KEY "calendar" #define ICU_COLLATION_KEY "collation" #define ICU_CURRENCY_KEY "currency" CONST_STRING_DECL(kCFLocaleMeasurementSystem, "kCFLocaleMeasurementSystem"); CONST_STRING_DECL(kCFLocaleDecimalSeparator, "kCFLocaleDecimalSeparator"); CONST_STRING_DECL(kCFLocaleGroupingSeparator, "kCFLocaleGroupingSeparator"); CONST_STRING_DECL(kCFLocaleCurrencySymbol, "kCFLocaleCurrencySymbol"); CONST_STRING_DECL(kCFLocaleCurrencyCode, "currency"); CONST_STRING_DECL(kCFLocaleIdentifier, "kCFLocaleIdentifier"); CONST_STRING_DECL(kCFLocaleLanguageCode, "kCFLocaleLanguageCode"); CONST_STRING_DECL(kCFLocaleCountryCode, "kCFLocaleCountryCode"); CONST_STRING_DECL(kCFLocaleScriptCode, "kCFLocaleScriptCode"); CONST_STRING_DECL(kCFLocaleVariantCode, "kCFLocaleVariantCode"); CONST_STRING_DECL(kCFLocaleExemplarCharacterSet, "kCFLocaleExemplarCharacterSet"); CONST_STRING_DECL(kCFLocaleCalendarIdentifier, "kCFLocaleCalendarIdentifier"); CONST_STRING_DECL(kCFLocaleCalendar, "calendar"); CONST_STRING_DECL(kCFLocaleCollationIdentifier, "collation"); CONST_STRING_DECL(kCFLocaleUsesMetricSystem, "kCFLocaleUsesMetricSystem"); CONST_STRING_DECL(kCFLocaleCollatorIdentifier, "kCFLocaleCollatorIdentifier"); CONST_STRING_DECL(kCFLocaleQuotationBeginDelimiterKey, "kCFLocaleQuotationBeginDelimiterKey"); CONST_STRING_DECL(kCFLocaleQuotationEndDelimiterKey, "kCFLocaleQuotationEndDelimiterKey"); CONST_STRING_DECL(kCFLocaleAlternateQuotationBeginDelimiterKey, "kCFLocaleAlternateQuotationBeginDelimiterKey"); CONST_STRING_DECL(kCFLocaleAlternateQuotationEndDelimiterKey, "kCFLocaleAlternateQuotationEndDelimiterKey"); CONST_STRING_DECL(kCFGregorianCalendar, "gregorian"); CONST_STRING_DECL(kCFBuddhistCalendar, "buddhist"); CONST_STRING_DECL(kCFChineseCalendar, "chinese"); CONST_STRING_DECL(kCFHebrewCalendar, "hebrew"); CONST_STRING_DECL(kCFIslamicCalendar, "islamic"); CONST_STRING_DECL(kCFIslamicCivilCalendar, "islamic-civil"); CONST_STRING_DECL(kCFJapaneseCalendar, "japanese"); CONST_STRING_DECL(kCFRepublicOfChinaCalendar, "roc"); CONST_STRING_DECL(kCFPersianCalendar, "persian"); CONST_STRING_DECL(kCFIndianCalendar, "indian"); CONST_STRING_DECL(kCFISO8601Calendar, "iso8601"); /* Introduced on UTS #35 v2.0 */ struct __CFLocale { /* The ivar order is important... must be exactly like NSLocale's. */ CFRuntimeBase _parent; CFStringRef _identifier; CFMutableDictionaryRef _components; }; static GSMutex _kCFLocaleLock; static CFTypeID _kCFLocaleTypeID = 0; static CFLocaleRef _kCFLocaleCurrent = NULL; static CFLocaleRef _kCFLocaleSystem = NULL; static CFArrayRef _kCFLocaleAvailableLocaleIdentifiers = NULL; static CFArrayRef _kCFLocaleISOCountryCodes = NULL; static CFArrayRef _kCFLocaleISOLanguageCodes = NULL; static void CFLocaleFinalize (CFTypeRef cf) { struct __CFLocale *o = (struct __CFLocale *)cf; CFRelease (o->_identifier); CFRelease (o->_components); } static Boolean CFLocaleEqual (CFTypeRef cf1, CFTypeRef cf2) { return CFEqual (((CFLocaleRef)cf1)->_identifier, ((CFLocaleRef)cf2)->_identifier); } static CFHashCode CFLocaleHash (CFTypeRef cf) { return CFHash (((CFLocaleRef)cf)->_identifier); } static CFStringRef CFLocaleCopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOptions) { return CFRetain (((CFLocaleRef)cf)->_identifier); } static const CFRuntimeClass CFLocaleClass = { 0, "CFLocale", NULL, (CFTypeRef (*)(CFAllocatorRef, CFTypeRef))CFLocaleCreateCopy, CFLocaleFinalize, CFLocaleEqual, CFLocaleHash, CFLocaleCopyFormattingDesc, NULL }; void CFLocaleInitialize (void) { _kCFLocaleTypeID = _CFRuntimeRegisterClass(&CFLocaleClass); GSMutexInitialize (&_kCFLocaleLock); } CF_INLINE CFLocaleLanguageDirection ICUToCFLocaleOrientation (ULayoutType layout) { switch (layout) { case ULOC_LAYOUT_LTR: return kCFLocaleLanguageDirectionLeftToRight; case ULOC_LAYOUT_RTL: return kCFLocaleLanguageDirectionRightToLeft; case ULOC_LAYOUT_TTB: return kCFLocaleLanguageDirectionTopToBottom; case ULOC_LAYOUT_BTT: return kCFLocaleLanguageDirectionBottomToTop; default: return kCFLocaleLanguageDirectionUnknown; } } const char * CFLocaleGetCStringIdentifier (CFLocaleRef locale, char *buf, CFIndex maxlen) { CFStringRef ident; ident = CFLocaleGetIdentifier (locale); if (CFStringGetCString (ident, buf, maxlen, kCFStringEncodingASCII)) return (const char *)buf; return NULL; } static CFArrayRef CFArrayCreateArrayWithUEnumeration (UEnumeration *en) { CFMutableArrayRef mArray; CFArrayRef result; int32_t count; int32_t len; const UChar *current; UErrorCode err = U_ZERO_ERROR; count = uenum_count (en, &err); if (U_FAILURE(err)) return NULL; mArray = CFArrayCreateMutable (NULL, (CFIndex)count, &kCFTypeArrayCallBacks); while ((current = uenum_unext(en, &len, &err))) { CFStringRef string; if (U_SUCCESS(err)) { string = CFStringCreateWithCharacters (NULL, current, (CFIndex)len); CFArrayAppendValue (mArray, string); CFRelease (string); } } /* Close it UEnumeration here so it doesn't get leaked. */ uenum_close (en); result = CFArrayCreateCopy (NULL, mArray); CFRelease (mArray); return result; } static CFTypeRef CFLocaleCopyMeasurementSystem (CFLocaleRef loc, const void *context) { CFTypeRef result; UMeasurementSystem ums; char buffer[ULOC_FULLNAME_CAPACITY]; const char *cLocale; UErrorCode err = U_ZERO_ERROR; cLocale = CFLocaleGetCStringIdentifier (loc, buffer, ULOC_FULLNAME_CAPACITY); ums = ulocdata_getMeasurementSystem (cLocale, &err); if (CFEqual(*((CFTypeRef*)context), kCFLocaleMeasurementSystem)) { if (ums == UMS_SI) result = CFSTR("Metric"); else result = CFSTR("U.S."); } else { if (ums == UMS_SI) result = kCFBooleanTrue; else result = kCFBooleanFalse; } return result; } struct _kCFNumberFormatterProperty { const CFStringRef *key; CFNumberFormatterStyle style; }; static struct _kCFNumberFormatterProperty decimalSep = { &kCFNumberFormatterDecimalSeparator, kCFNumberFormatterDecimalStyle }; static struct _kCFNumberFormatterProperty groupingSep = { &kCFNumberFormatterGroupingSeparator, kCFNumberFormatterDecimalStyle }; static struct _kCFNumberFormatterProperty currencySym = { &kCFNumberFormatterCurrencySymbol, kCFNumberFormatterCurrencyStyle }; static struct _kCFNumberFormatterProperty currecyCode = { &kCFNumberFormatterCurrencyCode, kCFNumberFormatterCurrencyStyle }; static CFTypeRef CFLocaleCopyNumberFormatterProperty (CFLocaleRef loc, const void *context) { CFTypeRef result; CFNumberFormatterRef fmt; struct _kCFNumberFormatterProperty *c = (struct _kCFNumberFormatterProperty*)context; fmt = CFNumberFormatterCreate (NULL, loc, c->style); result = CFNumberFormatterCopyProperty (fmt, *(c->key)); CFRelease (fmt); return result; } static CFTypeRef CFLocaleCopyIdentifierProperty (CFLocaleRef loc, const void *context) { CFTypeRef result; const char *cLocale; char buffer[ULOC_FULLNAME_CAPACITY]; char prop[ULOC_FULLNAME_CAPACITY]; int32_t length; int32_t (*func)(const char*, char*, int32_t, UErrorCode*) = context; UErrorCode err = U_ZERO_ERROR; cLocale = CFLocaleGetCStringIdentifier (loc, buffer, ULOC_FULLNAME_CAPACITY); length = (*func)(cLocale, prop, ULOC_FULLNAME_CAPACITY, &err); if (U_FAILURE(err) || length <= 0) result = NULL; else result = CFStringCreateWithCString (NULL, prop, kCFStringEncodingASCII); return result; } static CFTypeRef CFLocaleCopyCalendar (CFLocaleRef loc, const void *context) { CFTypeRef result; CFStringRef calId; CFAllocatorRef allocator = CFGetAllocator (loc); int len; const char *cLocale; char buffer[ULOC_FULLNAME_CAPACITY]; char cal[ULOC_KEYWORDS_CAPACITY]; UErrorCode err = U_ZERO_ERROR; cLocale = CFLocaleGetCStringIdentifier (loc, buffer, ULOC_FULLNAME_CAPACITY); len = uloc_getKeywordValue (cLocale, ICU_CALENDAR_KEY, cal, ULOC_KEYWORDS_CAPACITY, &err); if (U_SUCCESS(err) && len > 0) calId = CFStringCreateWithCString (allocator, cal, kCFStringEncodingASCII); else calId = kCFGregorianCalendar; result = CFCalendarCreateWithIdentifier (allocator, calId); CFRelease (calId); return result; } static CFTypeRef CFLocaleCopyKeyword (CFLocaleRef loc, const void *context) { CFTypeRef result = NULL; const char *cLocale; char buffer[ULOC_FULLNAME_CAPACITY]; char value[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; if (context == (const void*)ICU_CALENDAR_KEY) { CFCalendarRef cal; cal = (CFCalendarRef)CFLocaleCopyCalendar (loc, NULL); result = CFRetain (CFCalendarGetIdentifier (cal)); CFRelease (cal); return result; } cLocale = CFLocaleGetCStringIdentifier (loc, buffer, ULOC_FULLNAME_CAPACITY); if (uloc_getKeywordValue (cLocale, context, value, BUFFER_SIZE, &err) > 0 && U_SUCCESS(err)) { result = CFStringCreateWithCString (NULL, value, kCFStringEncodingASCII); } return result; } static CFTypeRef CFLocaleCopyDelimiter (CFLocaleRef loc, const void *context) { const char *cLocale; char buffer[ULOC_FULLNAME_CAPACITY]; UniChar ubuffer[BUFFER_SIZE]; CFIndex length; ULocaleData *uld; UErrorCode err = U_ZERO_ERROR; cLocale = CFLocaleGetCStringIdentifier (loc, buffer, ULOC_FULLNAME_CAPACITY); uld = ulocdata_open (cLocale, &err); length = ulocdata_getDelimiter (uld, (ULocaleDataDelimiterType)context, ubuffer, BUFFER_SIZE, &err); if (U_FAILURE(err)) return NULL; return CFStringCreateWithCharacters (NULL, ubuffer, length); } static CFTypeRef CFLocaleReturnNull (CFLocaleRef loc, const void *context) { return NULL; } #if HAVE_LIBOBJC || HAVE_LIBOBJC2 static CFStringRef CFLocaleKeyToNSLocaleKey(CFStringRef key) { CFStringRef nsKey = NULL; #define CASE(keyName) if(CFStringCompare(key, kCF##keyName, 0) == 0) nsKey = CFSTR("NS" #keyName); else CASE(LocaleIdentifier) CASE(LocaleLanguageCode) CASE(LocaleCountryCode) CASE(LocaleScriptCode) CASE(LocaleVariantCode) CASE(LocaleExemplarCharacterSet) CASE(LocaleCalendar) CASE(LocaleCollationIdentifier) CASE(LocaleUsesMetricSystem) CASE(LocaleMeasurementSystem) CASE(LocaleDecimalSeparator) CASE(LocaleGroupingSeparator) CASE(LocaleCurrencySymbol) CASE(LocaleCurrencyCode) CASE(LocaleCollatorIdentifier) CASE(LocaleQuotationBeginDelimiterKey) CASE(LocaleQuotationEndDelimiterKey) CASE(LocaleAlternateQuotationBeginDelimiterKey) CASE(LocaleAlternateQuotationEndDelimiterKey); #undef CASE return nsKey; } #else static CFStringRef CFLocaleKeyToNSLocaleKey(CFStringRef key) { return NULL; } #endif static struct _kCFLocaleValues { const CFStringRef *value; const void *context; CFTypeRef (*copy)(CFLocaleRef loc, const void *context); } _kCFLocaleValues[] = { { &kCFLocaleMeasurementSystem, &kCFLocaleMeasurementSystem, CFLocaleCopyMeasurementSystem }, { &kCFLocaleDecimalSeparator, &decimalSep, CFLocaleCopyNumberFormatterProperty }, { &kCFLocaleGroupingSeparator, &groupingSep, CFLocaleCopyNumberFormatterProperty }, { &kCFLocaleCurrencySymbol, ¤cySym, CFLocaleCopyNumberFormatterProperty }, { &kCFLocaleCurrencyCode, &currecyCode, CFLocaleCopyNumberFormatterProperty }, { &kCFLocaleLanguageCode, (const void*)&uloc_getLanguage, CFLocaleCopyIdentifierProperty }, { &kCFLocaleCountryCode, (const void*)&uloc_getCountry, CFLocaleCopyIdentifierProperty }, { &kCFLocaleScriptCode, (const void*)&uloc_getScript, CFLocaleCopyIdentifierProperty }, { &kCFLocaleVariantCode, (const void*)&uloc_getVariant, CFLocaleCopyIdentifierProperty }, { &kCFLocaleExemplarCharacterSet, NULL, CFLocaleReturnNull }, { &kCFLocaleCalendarIdentifier, ICU_CALENDAR_KEY, CFLocaleCopyKeyword }, { &kCFLocaleCalendar, NULL, CFLocaleCopyCalendar }, { &kCFLocaleCollationIdentifier, ICU_COLLATION_KEY, CFLocaleCopyKeyword }, { &kCFLocaleUsesMetricSystem, &kCFLocaleUsesMetricSystem, CFLocaleCopyMeasurementSystem }, { &kCFLocaleCollatorIdentifier, NULL, CFLocaleReturnNull }, { &kCFLocaleQuotationBeginDelimiterKey, (const void*)ULOCDATA_QUOTATION_START, CFLocaleCopyDelimiter }, { &kCFLocaleQuotationEndDelimiterKey, (const void*)ULOCDATA_QUOTATION_END, CFLocaleCopyDelimiter }, { &kCFLocaleAlternateQuotationBeginDelimiterKey, (const void*)ULOCDATA_ALT_QUOTATION_START, CFLocaleCopyDelimiter }, { &kCFLocaleAlternateQuotationEndDelimiterKey, (const void*)ULOCDATA_ALT_QUOTATION_END, CFLocaleCopyDelimiter } }; static const CFIndex _kCFLocaleValuesSize = sizeof(_kCFLocaleValues) / sizeof(struct _kCFLocaleValues); CFLocaleRef CFLocaleCopyCurrent (void) { CFLocaleRef result; GSMutexLock (&_kCFLocaleLock); if (_kCFLocaleCurrent) { result = (CFLocaleRef)CFRetain (_kCFLocaleCurrent); GSMutexUnlock (&_kCFLocaleLock); return result; } result = CFLocaleCreate (kCFAllocatorSystemDefault, NULL); _kCFLocaleCurrent = (CFLocaleRef)CFRetain (result); GSMutexUnlock (&_kCFLocaleLock); return result; } CFLocaleRef CFLocaleCreate (CFAllocatorRef allocator, CFStringRef localeIdent) { struct __CFLocale *new; new = (struct __CFLocale *)_CFRuntimeCreateInstance (allocator, CFLocaleGetTypeID(), sizeof(struct __CFLocale) - sizeof(CFRuntimeBase), NULL); new->_identifier = CFLocaleCreateCanonicalLocaleIdentifierFromString (allocator, localeIdent); new->_components = CFDictionaryCreateMutable (allocator, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); return new; } CFLocaleRef CFLocaleCreateCopy (CFAllocatorRef allocator, CFLocaleRef locale) { return (CFLocaleRef)CFRetain(locale); } CFLocaleRef CFLocaleGetSystem (void) { CFLocaleRef result; GSMutexLock (&_kCFLocaleLock); if (_kCFLocaleSystem) { result = (CFLocaleRef)CFRetain (_kCFLocaleSystem); GSMutexUnlock (&_kCFLocaleLock); return result; } result = CFLocaleCreate (kCFAllocatorSystemDefault, CFSTR("")); _kCFLocaleSystem = (CFLocaleRef)CFRetain (result); GSMutexUnlock (&_kCFLocaleLock); return result; } CFArrayRef CFLocaleCopyAvailableLocaleIdentifiers (void) { int32_t count; int32_t idx; CFMutableArrayRef mArray; GSMutexLock (&_kCFLocaleLock); if (_kCFLocaleAvailableLocaleIdentifiers) { GSMutexUnlock (&_kCFLocaleLock); return (CFArrayRef)CFRetain (_kCFLocaleAvailableLocaleIdentifiers); } count = uloc_countAvailable (); mArray = CFArrayCreateMutable (kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks); for (idx = 0 ; idx < count ; ++idx) { const char *str = uloc_getAvailable (idx); CFStringRef cfStr = CFStringCreateWithCString (kCFAllocatorSystemDefault, str, kCFStringEncodingASCII); CFArrayAppendValue (mArray, cfStr); CFRelease (cfStr); } _kCFLocaleAvailableLocaleIdentifiers = CFArrayCreateCopy (kCFAllocatorSystemDefault, mArray); GSMutexUnlock (&_kCFLocaleLock); CFRelease (mArray); return (CFArrayRef)CFRetain (_kCFLocaleAvailableLocaleIdentifiers); } static CFArrayRef CFLocaleCreateArrayWithCodes (const char *const *codes) { CFArrayRef array; CFMutableArrayRef mArray; CFStringRef str; CFIndex idx; mArray = CFArrayCreateMutable (kCFAllocatorSystemDefault, 0, &kCFTypeArrayCallBacks); for (idx = 0 ; codes[idx] ; ++idx) { str = CFStringCreateWithCString (kCFAllocatorSystemDefault, codes[idx], kCFStringEncodingASCII); CFArrayAppendValue (mArray, str); CFRelease (str); } array = CFArrayCreateCopy (kCFAllocatorSystemDefault, mArray); CFRelease (mArray); return array; } CFArrayRef CFLocaleCopyISOCountryCodes (void) { const char *const *cCodes; GSMutexLock (&_kCFLocaleLock); if (_kCFLocaleISOCountryCodes) { GSMutexUnlock (&_kCFLocaleLock); return (CFArrayRef)CFRetain (_kCFLocaleISOCountryCodes); } cCodes = uloc_getISOCountries (); _kCFLocaleISOCountryCodes = CFLocaleCreateArrayWithCodes (cCodes); GSMutexUnlock (&_kCFLocaleLock); return (CFArrayRef)CFRetain (_kCFLocaleISOCountryCodes); } CFArrayRef CFLocaleCopyISOLanguageCodes (void) { const char *const *cCodes; GSMutexLock (&_kCFLocaleLock); if (_kCFLocaleISOLanguageCodes) { GSMutexUnlock (&_kCFLocaleLock); return (CFArrayRef)CFRetain (_kCFLocaleISOLanguageCodes); } cCodes = uloc_getISOLanguages (); _kCFLocaleISOLanguageCodes = CFLocaleCreateArrayWithCodes (cCodes); GSMutexUnlock (&_kCFLocaleLock); return (CFArrayRef)CFRetain (_kCFLocaleISOLanguageCodes); } CFArrayRef CFLocaleCopyISOCurrencyCodes (void) { UEnumeration *en; UErrorCode err = U_ZERO_ERROR; en = ucurr_openISOCurrencies (UCURR_ALL, &err); if (U_FAILURE(err)) return NULL; return CFArrayCreateArrayWithUEnumeration (en); } CFArrayRef CFLocaleCopyCommonISOCurrencyCodes (void) { UEnumeration *en; UErrorCode err = U_ZERO_ERROR; en = ucurr_openISOCurrencies (UCURR_COMMON, &err); if (U_FAILURE(err)) return NULL; return CFArrayCreateArrayWithUEnumeration (en); } CFArrayRef CFLocaleCopyPreferredLanguages (void); CFStringRef CFLocaleCopyDisplayNameForPropertyValue (CFLocaleRef displayLocale, CFStringRef key, CFStringRef value) { CF_OBJC_FUNCDISPATCHV(_kCFLocaleTypeID, CFTypeRef, displayLocale, "displayNameForKey:value:", CFLocaleKeyToNSLocaleKey(key), value); CFStringRef ident; CFIndex cvaluelen; char displocale[ULOC_FULLNAME_CAPACITY]; char locale[ULOC_FULLNAME_CAPACITY]; char cvalue[ULOC_KEYWORDS_CAPACITY]; /* Can't be larger than this */ UChar buffer[BUFFER_SIZE]; int32_t len; UErrorCode err = U_ZERO_ERROR; ident = CFLocaleGetIdentifier (displayLocale); if (!CFStringGetCString (ident, displocale, ULOC_FULLNAME_CAPACITY, kCFStringEncodingASCII) || !CFStringGetCString (value, cvalue, ULOC_KEYWORDS_CAPACITY, kCFStringEncodingASCII)) return NULL; cvaluelen = CFStringGetLength (value); if (cvaluelen > ULOC_KEYWORDS_CAPACITY) cvaluelen = ULOC_KEYWORDS_CAPACITY; #define GET_DISPLAY_VALUE(loc, func) \ len = func (loc, displocale, buffer, BUFFER_SIZE, &err) if (key == kCFLocaleIdentifier) { GET_DISPLAY_VALUE(cvalue, uloc_getDisplayName); } else if (key == kCFLocaleLanguageCode) { GET_DISPLAY_VALUE(cvalue, uloc_getDisplayLanguage); } else if (key == kCFLocaleCountryCode) { strncpy (locale, "en_", sizeof("en_")); strncat (locale, cvalue, cvaluelen); GET_DISPLAY_VALUE(locale, uloc_getDisplayCountry); } else if (key == kCFLocaleScriptCode) { strncpy (locale, "en_", sizeof("en_")); strncat (locale, cvalue, cvaluelen); strncat (locale, "_US", sizeof("_US")); GET_DISPLAY_VALUE(locale, uloc_getDisplayScript); } else if (key == kCFLocaleVariantCode) { strncpy (locale, "en_US_", sizeof("en_US_")); strncat (locale, cvalue, cvaluelen); GET_DISPLAY_VALUE(locale, uloc_getDisplayVariant); } else if (key == kCFLocaleCalendarIdentifier) { strncpy (locale, "en_US@calendar=", sizeof("en_US@calendar=")); strncat (locale, cvalue, cvaluelen); len = uloc_getDisplayKeywordValue (locale, ICU_CALENDAR_KEY, displocale, buffer, BUFFER_SIZE, &err); } else if (key == kCFLocaleCollationIdentifier) { strncpy (locale, "en_US@collation=", sizeof("en_US@collation=")); strncat (locale, cvalue, cvaluelen); len = uloc_getDisplayKeywordValue (locale, ICU_COLLATION_KEY, displocale, buffer, BUFFER_SIZE, &err); } else if (key == kCFLocaleCurrencyCode) { strncpy (locale, "en_US@currency=", sizeof("en_US@currency=")); strncat (locale, cvalue, cvaluelen); len = uloc_getDisplayKeywordValue (locale, ICU_CURRENCY_KEY, displocale, buffer, BUFFER_SIZE, &err); } else { len = 0; } if (U_SUCCESS(err) && len > 0) return CFStringCreateWithCharacters (NULL, buffer, len); return NULL; } CFTypeRef CFLocaleGetValue (CFLocaleRef locale, CFStringRef key) { CF_OBJC_FUNCDISPATCHV(_kCFLocaleTypeID, CFTypeRef, locale, "objectForKey:", CFLocaleKeyToNSLocaleKey(key)); CFTypeRef result = NULL; CFIndex idx; Boolean found = false; /* Don't waste any time. */ if (locale == NULL || key == NULL) return NULL; if (key == kCFLocaleIdentifier) return locale->_identifier; /* Make sure we haven't been through this already. */ if (CFDictionaryGetValueIfPresent(locale->_components, key, &result)) return result; for (idx = 0 ; idx < _kCFLocaleValuesSize ; ++idx) { if (key == *(_kCFLocaleValues[idx].value)) { result = (_kCFLocaleValues[idx].copy)(locale, _kCFLocaleValues[idx].context); found = true; break; } } if (found == false) { for (idx = 0 ; idx < _kCFLocaleValuesSize ; ++idx) { if (CFEqual(key, *(_kCFLocaleValues[idx].value))) { result = (_kCFLocaleValues[idx].copy)(locale, _kCFLocaleValues[idx].context); break; } } } if (result != NULL) { CFDictionaryAddValue (locale->_components, key, result); CFRelease (result); } return result; } CFStringRef CFLocaleGetIdentifier (CFLocaleRef locale) { CF_OBJC_FUNCDISPATCHV(_kCFLocaleTypeID, CFStringRef, locale, "localeIdentifier"); return locale->_identifier; } CFStringRef CFLocaleCreateCanonicalLocaleIdentifierFromString (CFAllocatorRef allocator, CFStringRef localeIdent) { char *cLocale; char buffer[ULOC_FULLNAME_CAPACITY]; char canonical[ULOC_FULLNAME_CAPACITY]; UErrorCode err = U_ZERO_ERROR; if (localeIdent == NULL) { cLocale = (char *)uloc_getDefault (); } else { if (!CFStringGetCString(localeIdent, buffer, ULOC_FULLNAME_CAPACITY, kCFStringEncodingASCII)) return NULL; cLocale = buffer; } uloc_canonicalize (cLocale, canonical, ULOC_FULLNAME_CAPACITY, &err); if (U_FAILURE(err)) return NULL; return CFStringCreateWithCString (allocator, canonical, kCFStringEncodingASCII); } CFStringRef CFLocaleCreateCanonicalLanguageIdentifierFromString (CFAllocatorRef allocator, CFStringRef localeIdent) { CFStringRef result; char cLocale[ULOC_FULLNAME_CAPACITY]; char canonical[ULOC_FULLNAME_CAPACITY]; char lang[ULOC_LANG_CAPACITY]; UErrorCode err = U_ZERO_ERROR; if (!CFStringGetCString(localeIdent, cLocale, ULOC_FULLNAME_CAPACITY, kCFStringEncodingASCII)) return NULL; uloc_canonicalize (cLocale, canonical, BUFFER_SIZE, &err); uloc_getLanguage (canonical, lang, ULOC_LANG_CAPACITY, &err); if (U_FAILURE(err)) return NULL; result = CFStringCreateWithCString (allocator, lang, kCFStringEncodingASCII); return result; } static void CFLocaleAddKeyValuePairToDictionary (CFMutableDictionaryRef dict, CFStringRef key, char *str, int32_t length, UErrorCode *error) { if (U_SUCCESS(*error) && length > 0) { CFStringRef value = CFStringCreateWithCString (NULL, str, kCFStringEncodingASCII); CFDictionaryAddValue (dict, key, value); CFRelease (value); } *error = U_ZERO_ERROR; } CFDictionaryRef CFLocaleCreateComponentsFromLocaleIdentifier (CFAllocatorRef allocator, CFStringRef localeIdent) { char locale[ULOC_FULLNAME_CAPACITY]; char buffer[ULOC_KEYWORDS_CAPACITY]; CFDictionaryRef result; CFMutableDictionaryRef dict; int32_t len; UErrorCode err = U_ZERO_ERROR; if (!CFStringGetCString (localeIdent, locale, ULOC_FULLNAME_CAPACITY, kCFStringEncodingASCII)) return NULL; /* Using capacity = 7 because that's the most amount of keys we'll have: language_script_country_variant@calendar;collation;currency. */ dict = CFDictionaryCreateMutable (NULL, 7, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); len = uloc_getLanguage (locale, buffer, ULOC_KEYWORDS_CAPACITY, &err); CFLocaleAddKeyValuePairToDictionary (dict, kCFLocaleLanguageCode, buffer, len, &err); len = uloc_getCountry (locale, buffer, ULOC_KEYWORDS_CAPACITY, &err); CFLocaleAddKeyValuePairToDictionary (dict, kCFLocaleCountryCode, buffer, len, &err); len = uloc_getScript (locale, buffer, ULOC_KEYWORDS_CAPACITY, &err); CFLocaleAddKeyValuePairToDictionary (dict, kCFLocaleScriptCode, buffer, len, &err); len = uloc_getVariant (locale, buffer, ULOC_KEYWORDS_CAPACITY, &err); CFLocaleAddKeyValuePairToDictionary (dict, kCFLocaleVariantCode, buffer, len, &err); len = uloc_getKeywordValue (locale, ICU_CALENDAR_KEY, buffer, ULOC_KEYWORDS_CAPACITY, &err); CFLocaleAddKeyValuePairToDictionary (dict, kCFLocaleCalendarIdentifier, buffer, len, &err); len = uloc_getKeywordValue (locale, ICU_COLLATION_KEY, buffer, ULOC_KEYWORDS_CAPACITY, &err); CFLocaleAddKeyValuePairToDictionary (dict, kCFLocaleCollationIdentifier, buffer, len, &err); len = uloc_getKeywordValue (locale, ICU_CURRENCY_KEY, buffer, ULOC_KEYWORDS_CAPACITY, &err); CFLocaleAddKeyValuePairToDictionary (dict, kCFLocaleCurrencyCode, buffer, len, &err); result = CFDictionaryCreateCopy (allocator, (CFDictionaryRef)dict); CFRelease(dict); return result; } CFStringRef CFLocaleCreateLocaleIdentifierFromComponents (CFAllocatorRef allocator, CFDictionaryRef dictionary) { /* A locale identifier only includes a few of the keys provided by CFLocale. According to UTS #35 (http://unicode.org/reports/tr35/tr35-6.html) locales have the following format: locale_id := base_locale_id options? base_locale_id := extended_RFC3066bis_identifiers options := "@" key "=" type ("," key "=" type )* Keep in mind, however, that ICU's key separator is ";". This shouldn't be a problem as long as we use ULOC_KEYWORD_ITEM_SEPARATOR (and friends). */ CFMutableStringRef locale; CFStringRef ret; CFStringRef lang; CFStringRef country; CFStringRef script; CFStringRef variant; CFStringRef keyword; Boolean hasCountry; Boolean hasScript; Boolean hasVariant; Boolean separated = false; if (dictionary == NULL) return NULL; /* We'll return NULL if kCFLocaleLanguageCode doesn't exist. This is the only key that is absolutely necessary. */ if (!CFDictionaryGetValueIfPresent(dictionary, kCFLocaleLanguageCode, (const void **)&lang)) return NULL; hasCountry = CFDictionaryGetValueIfPresent(dictionary, kCFLocaleCountryCode, (const void **)&country); hasScript = CFDictionaryGetValueIfPresent(dictionary, kCFLocaleScriptCode, (const void **)&script); hasVariant = CFDictionaryGetValueIfPresent(dictionary, kCFLocaleVariantCode, (const void **)&variant); #define TEST_CODE(x, y) (x ? "_" : ""), (x ? y : CFSTR("")) locale = CFStringCreateMutable (NULL, ULOC_FULLNAME_CAPACITY); CFStringAppendFormat (locale, NULL, CFSTR("%@%s%@%s%@%s%@"), lang, TEST_CODE(hasScript, script), TEST_CODE(hasCountry, country), TEST_CODE(hasVariant, variant)); if (CFDictionaryGetValueIfPresent(dictionary, kCFLocaleCalendarIdentifier, (const void **)&keyword)) { CFStringAppend (locale, CFSTR("@")); CFStringAppendFormat (locale, NULL, CFSTR("calendar=%@"), keyword); separated = true; } if (CFDictionaryGetValueIfPresent(dictionary, kCFLocaleCollationIdentifier, (const void **)&keyword)) { if (separated == false) CFStringAppend (locale, CFSTR("@")); else CFStringAppend (locale, CFSTR(";")); CFStringAppendFormat (locale, NULL, CFSTR("collation=%@"), keyword); separated = true; } if (CFDictionaryGetValueIfPresent(dictionary, kCFLocaleCurrencyCode, (const void **)&keyword)) { if (separated == false) CFStringAppend (locale, CFSTR("@")); else CFStringAppend (locale, CFSTR(";")); CFStringAppendFormat (locale, NULL, CFSTR("currency=%@"), keyword); } ret = CFStringCreateCopy (allocator, locale); CFRelease (locale); return ret; } CFTypeID CFLocaleGetTypeID (void) { return _kCFLocaleTypeID; } CFStringRef CFLocaleCreateLocaleIdentifierFromWindowsLocaleCode (CFAllocatorRef allocator, UInt32 lcid) { CFStringRef result = NULL; char buffer[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; uloc_getLocaleForLCID (lcid, buffer, BUFFER_SIZE-1, &err); if (U_FAILURE(err) && err != U_BUFFER_OVERFLOW_ERROR) return NULL; result = CFStringCreateWithCString (allocator, buffer, kCFStringEncodingASCII); return result; } CFLocaleLanguageDirection CFLocaleGetLanguageCharacterDirection (CFStringRef isoLangCode) { char buffer[BUFFER_SIZE]; ULayoutType result; UErrorCode err = U_ZERO_ERROR; if (!CFStringGetCString (isoLangCode, buffer, BUFFER_SIZE - 1, kCFStringEncodingASCII)) return kCFLocaleLanguageDirectionUnknown; result = uloc_getCharacterOrientation (buffer, &err); if (U_FAILURE(err)) return kCFLocaleLanguageDirectionUnknown; return ICUToCFLocaleOrientation (result); } CFLocaleLanguageDirection CFLocaleGetLanguageLineDirection (CFStringRef isoLangCode) { char buffer[BUFFER_SIZE]; ULayoutType result; UErrorCode err = U_ZERO_ERROR; if (!CFStringGetCString (isoLangCode, buffer, BUFFER_SIZE - 1, kCFStringEncodingASCII)) return kCFLocaleLanguageDirectionUnknown; result = uloc_getLineOrientation (buffer, &err); if (U_FAILURE(err)) return kCFLocaleLanguageDirectionUnknown; return ICUToCFLocaleOrientation (result); } UInt32 CFLocaleGetWindowsLocaleCodeFromLocaleIdentifier (CFStringRef localeIdent) { char buffer[BUFFER_SIZE]; if (CFStringGetCString (localeIdent, buffer, BUFFER_SIZE - 1, kCFStringEncodingASCII)) return uloc_getLCID (buffer); return 0; } gnustep-corebase-0.2/Source/CFSet.c0000644000175000017500000001646113222706330016261 0ustar yavoryavor/* CFSet.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: November, 2011 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFSet.h" #include "CoreFoundation/CFString.h" #include "GSHashTable.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" static CFTypeID _kCFSetTypeID = 0; static void CFSetFinalize (CFTypeRef cf) { GSHashTableFinalize ((GSHashTableRef) cf); } static Boolean CFSetEqual (CFTypeRef cf1, CFTypeRef cf2) { return GSHashTableEqual ((GSHashTableRef) cf1, (GSHashTableRef) cf2); } static CFHashCode CFSetHash (CFTypeRef cf) { return GSHashTableHash ((GSHashTableRef) cf); } static CFStringRef CFSetCopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOptions) { return CFSTR (""); } static CFRuntimeClass CFSetClass = { 0, "CFSet", NULL, (CFTypeRef (*)(CFAllocatorRef, CFTypeRef)) CFSetCreateCopy, CFSetFinalize, CFSetEqual, CFSetHash, CFSetCopyFormattingDesc, NULL }; void CFSetInitialize (void) { _kCFSetTypeID = _CFRuntimeRegisterClass (&CFSetClass); } const CFSetCallBacks kCFCopyStringSetCallBacks = { 0, (CFTypeRef (*)(CFAllocatorRef, CFTypeRef)) CFStringCreateCopy, CFTypeReleaseCallBack, CFCopyDescription, CFEqual, CFHash }; const CFSetCallBacks kCFTypeSetCallBacks = { 0, CFTypeRetainCallBack, CFTypeReleaseCallBack, CFCopyDescription, CFEqual, CFHash }; CFSetRef CFSetCreate (CFAllocatorRef allocator, const void **values, CFIndex numValues, const CFSetCallBacks * callBacks) { return (CFSetRef) GSHashTableCreate (allocator, _kCFSetTypeID, values, values, numValues, (const GSHashTableKeyCallBacks *) callBacks, NULL); } CFSetRef CFSetCreateCopy (CFAllocatorRef allocator, CFSetRef set) { if (CF_IS_OBJC (_kCFSetTypeID, set)) { CFSetRef result; const CFIndex count = CFSetGetCount (set); void **values = (void **) CFAllocatorAllocate (allocator, sizeof (void *) * count, 0); CFSetGetValues (set, (const void **) values); result = CFSetCreate (allocator, (const void **) values, count, &kCFTypeSetCallBacks); CFAllocatorDeallocate (allocator, (void *) values); return result; } return (CFSetRef) GSHashTableCreateCopy (allocator, (GSHashTableRef) set); } void CFSetApplyFunction (CFSetRef set, CFSetApplierFunction applier, void *context) { // TODO: could be made more efficient by providing a specialized // implementation for the CF_IS_OBJC case const CFIndex count = CFSetGetCount (set); void **values = (void **) CFAllocatorAllocate (NULL, sizeof (void *) * count, 0); CFIndex i; CFSetGetValues (set, (const void **) values); for (i = 0; i < count; i++) { applier (values[i], context); } CFAllocatorDeallocate (NULL, (void *) values); } Boolean CFSetContainsValue (CFSetRef set, const void *value) { CF_OBJC_FUNCDISPATCHV (_kCFSetTypeID, Boolean, set, "containsObject:", value); return GSHashTableContainsKey ((GSHashTableRef) set, value); } CFIndex CFSetGetCount (CFSetRef set) { CF_OBJC_FUNCDISPATCHV (_kCFSetTypeID, CFIndex, set, "count"); return GSHashTableGetCount ((GSHashTableRef) set); } CFIndex CFSetGetCountOfValue (CFSetRef set, const void *value) { return CFSetContainsValue (set, value) ? 1 : 0; } void CFSetGetValues (CFSetRef set, const void **values) { CF_OBJC_FUNCDISPATCHV (_kCFSetTypeID, void, set, "_cfGetValues:", values); GSHashTableGetKeysAndValues ((GSHashTableRef) set, values, NULL); } const void * CFSetGetValue (CFSetRef set, const void *value) { CF_OBJC_FUNCDISPATCHV (_kCFSetTypeID, void *, set, "_cfGetValue:", value); return GSHashTableGetValue ((GSHashTableRef) set, value); } Boolean CFSetGetValueIfPresent (CFSetRef set, const void *candidate, const void **value) { const void *v; v = CFSetGetValue (set, candidate); if (v) { if (value) *value = v; return true; } return false; } CFTypeID CFSetGetTypeID (void) { return _kCFSetTypeID; } CFMutableSetRef CFSetCreateMutable (CFAllocatorRef allocator, CFIndex capacity, const CFSetCallBacks * callBacks) { return (CFMutableSetRef) GSHashTableCreateMutable (allocator, _kCFSetTypeID, capacity, (const GSHashTableKeyCallBacks *) callBacks, NULL); } CFMutableSetRef CFSetCreateMutableCopy (CFAllocatorRef allocator, CFIndex capacity, CFSetRef set) { if (CF_IS_OBJC (_kCFSetTypeID, set)) { CFMutableSetRef result; const CFIndex count = CFSetGetCount (set); void **values = (void **) CFAllocatorAllocate (allocator, sizeof (void *) * count, 0); CFIndex i; CFSetGetValues (set, (const void **) values); result = CFSetCreateMutable (allocator, count, &kCFTypeSetCallBacks); for (i = 0; i < count; i++) GSHashTableAddValue ((GSHashTableRef) result, values[i], values[i]); CFAllocatorDeallocate (allocator, (void *) values); return result; } return (CFMutableSetRef) GSHashTableCreateMutableCopy (allocator, (GSHashTableRef) set, capacity); } void CFSetAddValue (CFMutableSetRef set, const void *value) { CF_OBJC_FUNCDISPATCHV (_kCFSetTypeID, void, set, "addObject:", value); GSHashTableAddValue ((GSHashTableRef) set, value, value); } void CFSetRemoveAllValues (CFMutableSetRef set) { CF_OBJC_FUNCDISPATCHV (_kCFSetTypeID, void, set, "removeAllObjects"); GSHashTableRemoveAll ((GSHashTableRef) set); } void CFSetRemoveValue (CFMutableSetRef set, const void *value) { CF_OBJC_FUNCDISPATCHV (_kCFSetTypeID, void, set, "removeObject:", value); GSHashTableRemoveValue ((GSHashTableRef) set, value); } void CFSetReplaceValue (CFMutableSetRef set, const void *value) { CF_OBJC_FUNCDISPATCHV (_kCFSetTypeID, void, set, "_cfReplaceValue:", value); GSHashTableReplaceValue ((GSHashTableRef) set, value, value); } void CFSetSetValue (CFMutableSetRef set, const void *value) { CF_OBJC_FUNCDISPATCHV (_kCFSetTypeID, void, set, "_cfSetValue:", value); GSHashTableSetValue ((GSHashTableRef) set, value, value); } gnustep-corebase-0.2/Source/CFNumber.c0000644000175000017500000003616314551015633016764 0ustar yavoryavor/* CFNumber.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: September, 2011 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFNumberFormatter.h" #include "CoreFoundation/CFNumber.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" #include #include #ifndef INFINITY # if defined(_MSC_VER) # include # define INFINITY DBL_MAX + DBL_MAX # define NAN (INFINITY) - (INFINITY) # else # define INFINITY 1.0 / 0.0 # define NAN 0.0 / 0.0 # endif #endif struct __CFBoolean { CFRuntimeBase _parent; }; static struct __CFBoolean _kCFBooleanTrue = { INIT_CFRUNTIME_BASE() }; static struct __CFBoolean _kCFBooleanFalse = { INIT_CFRUNTIME_BASE() }; const CFBooleanRef kCFBooleanTrue = &_kCFBooleanTrue; const CFBooleanRef kCFBooleanFalse = &_kCFBooleanFalse; static CFTypeID _kCFBooleanTypeID = 0; static CFStringRef CFBooleanCopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOptions) { return cf == kCFBooleanTrue ? CFSTR("true") : CFSTR("false"); } static const CFRuntimeClass CFBooleanClass = { 0, "CFBoolean", NULL, NULL, NULL, NULL, NULL, CFBooleanCopyFormattingDesc, NULL }; void CFBooleanInitialize (void) { _kCFBooleanTypeID = _CFRuntimeRegisterClass(&CFBooleanClass); GSRuntimeConstantInit (kCFBooleanTrue, _kCFBooleanTypeID); GSRuntimeConstantInit (kCFBooleanFalse, _kCFBooleanTypeID); } CFTypeID CFBooleanGetTypeID (void) { return _kCFBooleanTypeID; } Boolean CFBooleanGetValue (CFBooleanRef boolean) { return (boolean == kCFBooleanTrue) ? true : false; } /* We do not include a pointer for the actual number because it will be right after the object itself and the CFNumberType will be stored in the info section of CFRuntimeBase. This implementation of CFNumber will hold 3 possible types: 32-bit int, 64-bit int and 64-bit float. */ struct __CFNumber { CFRuntimeBase _parent; }; struct __CFNumber_static { struct __CFNumber _cfnum; Float64 f64; }; static struct __CFNumber_static _kCFNumberNaN = { { INIT_CFRUNTIME_BASE() }, ( NAN ) }; static struct __CFNumber_static _kCFNumberNegInf = { { INIT_CFRUNTIME_BASE() }, ( -INFINITY ) }; static struct __CFNumber_static _kCFNumberPosInf = { { INIT_CFRUNTIME_BASE() }, ( INFINITY ) }; const CFNumberRef kCFNumberNaN = (CFNumberRef)&_kCFNumberNaN; const CFNumberRef kCFNumberNegativeInfinity = (CFNumberRef)&_kCFNumberNegInf; const CFNumberRef kCFNumberPositiveInfinity = (CFNumberRef)&_kCFNumberPosInf; static CFTypeID _kCFNumberTypeID = 0; static CFTypeRef CFNumberCopy (CFAllocatorRef alloc, CFTypeRef cf) { CFNumberRef num; CFNumberType type; UInt8 bytes[sizeof(double)]; num = (CFNumberRef)cf; type = CFNumberGetType (num); CFNumberGetValue (num, type, (void*)bytes); return CFNumberCreate (alloc, type, (void*)bytes); } static Boolean CFNumberEqual (CFTypeRef cf1, CFTypeRef cf2) { CFNumberRef num1 = (CFNumberRef) cf1; CFNumberRef num2 = (CFNumberRef) cf2; if (CFNumberIsFloatType (num1) || CFNumberIsFloatType (num2)) { Float64 value1, value2; CFNumberGetValue (num1, kCFNumberFloat64Type, &value1); CFNumberGetValue (num2, kCFNumberFloat64Type, &value2); return value1 == value2; } else { SInt64 value1, value2; CFNumberGetValue (num1, kCFNumberSInt64Type, &value1); CFNumberGetValue (num2, kCFNumberSInt64Type, &value2); return value1 == value2; } } static CFHashCode CFNumberHash (CFTypeRef cf) { CFNumberRef num = (CFNumberRef) cf; CFHashCode hash; CFNumberGetValue (num, kCFNumberLongType, &hash); return hash; } static CFStringRef CFNumberCopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOptions) { CFNumberFormatterRef fmt; CFStringRef str; fmt = CFNumberFormatterCreate (NULL, NULL, kCFNumberFormatterNoStyle); str = CFNumberFormatterCreateStringWithNumber (NULL, NULL, cf); CFRelease (fmt); return str; } static CFRuntimeClass CFNumberClass = { 0, "CFNumber", NULL, CFNumberCopy, NULL, CFNumberEqual, CFNumberHash, CFNumberCopyFormattingDesc, NULL }; void CFNumberInitialize (void) { _kCFNumberTypeID = _CFRuntimeRegisterClass (&CFNumberClass); GSRuntimeConstantInit (kCFNumberNaN, _kCFNumberTypeID); _kCFNumberNaN._cfnum._parent._flags.info = kCFNumberDoubleType; GSRuntimeConstantInit (kCFNumberNegativeInfinity, _kCFNumberTypeID); _kCFNumberNegInf._cfnum._parent._flags.info = kCFNumberDoubleType; GSRuntimeConstantInit (kCFNumberPositiveInfinity, _kCFNumberTypeID); _kCFNumberPosInf._cfnum._parent._flags.info = kCFNumberDoubleType; } CF_INLINE CFNumberType CFNumberGetType_internal(CFNumberRef num) { return (CFNumberType)num->_parent._flags.info; } CF_INLINE CFIndex CFNumberByteSizeOfType (CFNumberType type) { switch (type) { case kCFNumberSInt8Type: return sizeof(SInt8); case kCFNumberSInt16Type: return sizeof(SInt16); case kCFNumberSInt32Type: return sizeof(SInt32); case kCFNumberSInt64Type: return sizeof(SInt64); case kCFNumberFloat32Type: return sizeof(Float32); case kCFNumberFloat64Type: return sizeof(Float64); case kCFNumberCharType: return sizeof(char); case kCFNumberShortType: return sizeof(short); case kCFNumberIntType: return sizeof(int); case kCFNumberLongType: return sizeof(long); case kCFNumberCFIndexType: return sizeof(CFIndex); case kCFNumberNSIntegerType: return sizeof(uintptr_t); case kCFNumberLongLongType: return sizeof(long long); case kCFNumberFloatType: return sizeof(float); case kCFNumberDoubleType: return sizeof(double); #if defined(__LP64__) case kCFNumberCGFloatType: return sizeof(double); #else case kCFNumberCGFloatType: return sizeof(float); #endif } return 0; } CF_INLINE CFNumberType CFNumberBestType (CFNumberType type) { switch (type) { case kCFNumberSInt8Type: case kCFNumberCharType: case kCFNumberSInt16Type: case kCFNumberShortType: case kCFNumberSInt32Type: case kCFNumberIntType: #if !defined(__LP64__) && !defined(_WIN64) case kCFNumberLongType: case kCFNumberCFIndexType: case kCFNumberNSIntegerType: #endif return kCFNumberSInt32Type; break; case kCFNumberSInt64Type: case kCFNumberLongLongType: #if defined(__LP64__) || defined(_WIN64) case kCFNumberLongType: case kCFNumberCFIndexType: case kCFNumberNSIntegerType: #endif return kCFNumberSInt64Type; break; case kCFNumberFloat32Type: case kCFNumberFloatType: case kCFNumberFloat64Type: case kCFNumberDoubleType: case kCFNumberCGFloatType: return kCFNumberFloat64Type; break; } return 0; } CFComparisonResult CFNumberCompare (CFNumberRef num, CFNumberRef oNum, void *context) { CF_OBJC_FUNCDISPATCHV(_kCFNumberTypeID, CFComparisonResult, num, "compare:", oNum); CF_OBJC_FUNCDISPATCHV(_kCFNumberTypeID, CFComparisonResult, oNum, "compare:", num); return -1; } CFNumberRef CFNumberCreate (CFAllocatorRef alloc, CFNumberType type, const void *valuePtr) { struct __CFNumber *new; CFIndex size; CFIndex byteSize; CFNumberType bestType; SInt32 value32; Boolean hasValue32; switch (type) { case kCFNumberSInt8Type: case kCFNumberCharType: value32 = *(const SInt8*)valuePtr; hasValue32 = true; break; case kCFNumberSInt16Type: case kCFNumberShortType: value32 = *(const SInt16*)valuePtr; hasValue32 = true; break; case kCFNumberSInt32Type: case kCFNumberIntType: value32 = *(const SInt32*)valuePtr; hasValue32 = true; break; default: value32 = 0; hasValue32 = false; } bestType = CFNumberBestType (type); byteSize = CFNumberByteSizeOfType(bestType); size = sizeof(struct __CFNumber) - sizeof(CFRuntimeBase) + byteSize; new = (struct __CFNumber*)_CFRuntimeCreateInstance (alloc, _kCFNumberTypeID, size, 0); new->_parent._flags.info = bestType; if (hasValue32) { memcpy ((void*)&new[1], &value32, sizeof(SInt32)); } else if (type == kCFNumberFloat32Type || type == kCFNumberFloatType #if !defined(__LP64__) && !defined(_WIN64) || type == kCFNumberCGFloatType #endif ) { Float64 d = *(const float*)valuePtr; memcpy ((void*)&new[1], &d, sizeof(Float64)); } else { memcpy ((void*)&new[1], valuePtr, byteSize); } return new; } CFIndex CFNumberGetByteSize (CFNumberRef num) { return CFNumberByteSizeOfType (CFNumberGetType(num)); } CFNumberType CFNumberGetType (CFNumberRef num) { #if HAVE_OBJC_RUNTIME_H if (CF_IS_OBJC(_kCFNumberTypeID, num)) { const char *objcType; CFNumberType cfType; CF_OBJC_CALLV(const char *, objcType, num, "objCType"); cfType = 0; switch (*objcType) { case _C_CHR: case _C_UCHR: cfType = kCFNumberCharType; case _C_SHT: case _C_USHT: cfType = kCFNumberShortType; case _C_INT: case _C_UINT: cfType = kCFNumberIntType; case _C_LNG: case _C_ULNG: cfType = kCFNumberLongType; case _C_LNG_LNG: case _C_ULNG_LNG: cfType = kCFNumberLongLongType; case _C_FLT: cfType = kCFNumberFloatType; case _C_DBL: cfType = kCFNumberDoubleType; } return cfType; } #endif /* HAVE_OBJC_RUNTIME_H */ return CFNumberGetType_internal (num); } CFTypeID CFNumberGetTypeID (void) { return _kCFNumberTypeID; } #define CFNumberConvert(srcType, src, dstType, dst, success) do \ { \ srcType source; \ dstType destination; \ memcpy (&source, src, sizeof(srcType)); \ destination = (dstType)source; \ memcpy (dst, &destination, sizeof(dstType)); \ success = (*(dstType*)dst == *(srcType*)src); \ } while(0) Boolean CFNumberGetValue (CFNumberRef num, CFNumberType type, void *valuePtr) { CFNumberType numType = CFNumberGetType (num); Boolean success = true; switch (type) { case kCFNumberSInt8Type: case kCFNumberCharType: if (CF_IS_OBJC(_kCFNumberTypeID, num)) CF_OBJC_CALLV(signed char, *(signed char*)valuePtr, num, "charValue"); else if (numType == kCFNumberSInt32Type) CFNumberConvert (SInt32, &(num[1]), SInt8, valuePtr, success); else if (numType == kCFNumberSInt64Type) CFNumberConvert (SInt64, &(num[1]), SInt8, valuePtr, success); else CFNumberConvert (Float64, &(num[1]), SInt8, valuePtr, success); return success; case kCFNumberSInt16Type: case kCFNumberShortType: if (CF_IS_OBJC(_kCFNumberTypeID, num)) CF_OBJC_CALLV(signed short, *(signed short*)valuePtr, num, "shortValue"); else if (numType == kCFNumberSInt32Type) CFNumberConvert (SInt32, &(num[1]), SInt16, valuePtr, success); else if (numType == kCFNumberSInt64Type) CFNumberConvert (SInt64, &(num[1]), SInt16, valuePtr, success); else CFNumberConvert (Float64, &(num[1]), SInt16, valuePtr, success); return success; case kCFNumberSInt32Type: case kCFNumberIntType: #if !defined(__LP64__) && !defined(_WIN64) case kCFNumberLongType: case kCFNumberCFIndexType: case kCFNumberNSIntegerType: #endif if (CF_IS_OBJC(_kCFNumberTypeID, num)) CF_OBJC_CALLV(signed int, *(signed int*)valuePtr, num, "intValue"); else if (numType == kCFNumberSInt32Type) CFNumberConvert (SInt32, &(num[1]), SInt32, valuePtr, success); else if (numType == kCFNumberSInt64Type) CFNumberConvert (SInt64, &(num[1]), SInt32, valuePtr, success); else CFNumberConvert (Float64, &(num[1]), SInt32, valuePtr, success); return success; case kCFNumberSInt64Type: case kCFNumberLongLongType: #if defined(__LP64__) || defined(_WIN64) case kCFNumberLongType: case kCFNumberCFIndexType: case kCFNumberNSIntegerType: #endif if (CF_IS_OBJC(_kCFNumberTypeID, num)) CF_OBJC_CALLV(signed long long, *(signed long long*)valuePtr, num, "longLongValue"); else if (numType == kCFNumberSInt32Type) CFNumberConvert (SInt32, &(num[1]), SInt64, valuePtr, success); else if (numType == kCFNumberSInt64Type) CFNumberConvert (SInt64, &(num[1]), SInt64, valuePtr, success); else CFNumberConvert (Float64, &(num[1]), SInt64, valuePtr, success); return success; case kCFNumberFloat32Type: case kCFNumberFloatType: #if !defined(__LP64__) && !defined(_WIN64) case kCFNumberCGFloatType: #endif if (CF_IS_OBJC(_kCFNumberTypeID, num)) CF_OBJC_CALLV(float, *(float*)valuePtr, num, "floatValue"); else if (numType == kCFNumberSInt32Type) CFNumberConvert (SInt32, &(num[1]), Float32, valuePtr, success); else if (numType == kCFNumberSInt64Type) CFNumberConvert (SInt64, &(num[1]), Float32, valuePtr, success); else CFNumberConvert (Float64, &(num[1]), Float32, valuePtr, success); return success; case kCFNumberFloat64Type: case kCFNumberDoubleType: #if defined(__LP64__) || defined(_WIN64) case kCFNumberCGFloatType: #endif if (CF_IS_OBJC(_kCFNumberTypeID, num)) CF_OBJC_CALLV(double, *(double*)valuePtr, num, "doubleValue"); else if (numType == kCFNumberSInt32Type) CFNumberConvert (SInt32, &(num[1]), Float64, valuePtr, success); else if (numType == kCFNumberSInt64Type) CFNumberConvert (SInt64, &(num[1]), Float64, valuePtr, success); else CFNumberConvert (Float64, &(num[1]), Float64, valuePtr, success); return success; } return false; } Boolean CFNumberIsFloatType (CFNumberRef num) { CFNumberType type = CFNumberGetType (num); switch (type) { case kCFNumberFloat32Type: case kCFNumberFloat64Type: case kCFNumberFloatType: case kCFNumberDoubleType: case kCFNumberCGFloatType: return true; default: return false; } } gnustep-corebase-0.2/Source/NSCFSet.m0000644000175000017500000000755313222706330016536 0ustar yavoryavor/* NSCFSet.m Copyright (C) 2013 Free Software Foundation, Inc. Written by: Lubos Dolezel Date: March, 2013 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #import #include "NSCFType.h" #include "CoreFoundation/CFSet.h" @interface NSCFSet : NSMutableSet NSCFTYPE_VARS @end @interface NSSet (CoreBaseAdditions) - (CFTypeID) _cfTypeID; - (id) _cfGetValue: (id) value; - (void) _cfGetValues: (id[]) values; @end @interface NSMutableSet (CoreBaseAdditions) - (void) _cfReplaceValue: (id) value; - (void) _cfSetValue: (id) value; @end @implementation NSCFSet + (void) load { NSCFInitialize (); } + (void) initialize { GSObjCAddClassBehavior (self, [NSCFType class]); } - (id) initWithObjects: (const id[])objects count: (NSUInteger)count { RELEASE(self); self = (NSCFSet*) CFSetCreate(NULL, (const void**)objects, count, &kCFTypeSetCallBacks); return self; } - (NSUInteger) count { return CFSetGetCount((CFSetRef)self); } - (id) member: (id)anObject { id retval; if (CFSetGetValueIfPresent((CFSetRef)self, anObject, (const void **)&retval)) { return retval; } else { return NULL; } } - (NSEnumerator*) objectEnumerator { NSArray *array; const void* values; const CFIndex count = CFSetGetCount((CFSetRef)self); values = malloc(sizeof(void*) * count); CFSetGetValues((CFSetRef)self, &values); array = [NSArray arrayWithObjects: (const id*)values count: count]; free((void*)values); return [array objectEnumerator]; } - (NSUInteger) countByEnumeratingWithState: (NSFastEnumerationState*)state objects: (id*)stackbuf count: (NSUInteger)len { // TODO: inefficient NSEnumerator *enuM = [self objectEnumerator]; return [enuM countByEnumeratingWithState: state objects: stackbuf count: len]; } - (void) addObject: (id)anObject { CFSetAddValue((CFMutableSetRef) self, anObject); } - (void) removeObject: (id)anObject { CFSetRemoveValue((CFMutableSetRef) self, anObject); } - (void) removeAllObjects { CFSetRemoveAllValues((CFMutableSetRef) self); } @end @implementation NSSet (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFSetGetTypeID(); } - (id) _cfGetValue: (id) value { NSEnumerator *enuM = [self objectEnumerator]; id elem; while ((elem = [enuM nextObject])) { if ([elem isEqual: value]) return elem; } return NULL; } - (void) _cfGetValues: (id[]) values { NSArray *array = [self allObjects]; [array getObjects: values range: NSMakeRange(0, [self count])]; } @end @implementation NSMutableSet (CoreBaseAdditions) - (void) _cfReplaceValue: (id) value { if ([self containsObject: value]) { [self removeObject: value]; [self addObject: value]; } } - (void) _cfSetValue: (id) value { [self removeObject: value]; [self addObject: value]; } @end gnustep-corebase-0.2/Source/CFCalendar.c0000644000175000017500000005330614551015633017243 0ustar yavoryavor/* CFCalendar.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: March, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFDate.h" #include "CoreFoundation/CFLocale.h" #include "CoreFoundation/CFCalendar.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFTimeZone.h" #include "CoreFoundation/CFRuntime.h" #include "GSPrivate.h" #if defined(HAVE_UNICODE_UCAL_H) #include #endif #if defined(HAVE_ICU_H) #include #endif struct __CFCalendar { CFRuntimeBase _parent; UCalendar *_ucal; CFStringRef _ident; CFStringRef _localeIdent; CFStringRef _tzIdent; }; static CFTypeID _kCFCalendarTypeID = 0; static CFCalendarRef _kCFCalendarCurrent = NULL; static GSMutex _kCFCalendarLock; #define BUFFER_SIZE 64 static void CFCalendarOpenUCalendar (CFCalendarRef cal) { if (cal->_ucal == NULL) { char localeIdent[ULOC_FULLNAME_CAPACITY]; char calIdent[ULOC_KEYWORDS_CAPACITY]; UniChar tzIdent[BUFFER_SIZE]; CFIndex tzLen; UCalendar *ucal; UErrorCode err = U_ZERO_ERROR; CFStringGetCString (cal->_localeIdent, localeIdent, ULOC_FULLNAME_CAPACITY, kCFStringEncodingASCII); CFStringGetCString (cal->_ident, calIdent, ULOC_KEYWORDS_CAPACITY, kCFStringEncodingASCII); uloc_setKeywordValue ("calendar", (const char*)calIdent, localeIdent, ULOC_FULLNAME_CAPACITY, &err); tzLen = CFStringGetLength (cal->_tzIdent); if (tzLen > BUFFER_SIZE) tzLen = BUFFER_SIZE; CFStringGetCharacters (cal->_tzIdent, CFRangeMake(0, tzLen), tzIdent); ucal = ucal_open (tzIdent, tzLen, localeIdent, UCAL_TRADITIONAL, &err); cal->_ucal = ucal; } else { ucal_clear (cal->_ucal); } } CF_INLINE void CFCalendarCloseUCalendar (CFCalendarRef cal) { if (cal->_ucal) { ucal_close (cal->_ucal); cal->_ucal = NULL; } } static void CFCalendarDealloc (CFTypeRef cf) { CFCalendarRef cal = (CFCalendarRef)cf; CFCalendarCloseUCalendar (cal); CFRelease (cal->_ident); CFRelease (cal->_localeIdent); CFRelease (cal->_tzIdent); } static Boolean CFCalendarEqual (CFTypeRef cf1, CFTypeRef cf2) { CFCalendarRef o1 = (CFCalendarRef)cf1; CFCalendarRef o2 = (CFCalendarRef)cf2; return (Boolean)(CFEqual(o1->_ident, o2->_ident) && CFEqual(o1->_localeIdent, o2->_localeIdent) && CFEqual(o1->_tzIdent, o2->_tzIdent)); } static CFHashCode CFCalendarHash (CFTypeRef cf) { return CFHash (((CFCalendarRef)cf)->_ident); } static CFStringRef CFCalendarCopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOptions) { return CFRetain (((CFCalendarRef)cf)->_ident); } static const CFRuntimeClass CFCalendarClass = { 0, "CFCalendar", NULL, NULL, CFCalendarDealloc, CFCalendarEqual, CFCalendarHash, CFCalendarCopyFormattingDesc, NULL }; void CFCalendarInitialize (void) { _kCFCalendarTypeID = _CFRuntimeRegisterClass (&CFCalendarClass); GSMutexInitialize (&_kCFCalendarLock); } CF_INLINE UCalendarDateFields CFCalendarUnitToUCalendarDateFields (CFCalendarUnit unit) { UCalendarDateFields ret; switch (unit) { case kCFCalendarUnitEra: ret = UCAL_ERA; break; case kCFCalendarUnitYear: ret = UCAL_YEAR; break; case kCFCalendarUnitMonth: ret = UCAL_MONTH; break; case kCFCalendarUnitDay: ret = UCAL_DATE; break; case kCFCalendarUnitHour: ret = UCAL_HOUR_OF_DAY; break; case kCFCalendarUnitMinute: ret = UCAL_MINUTE; break; case kCFCalendarUnitSecond: ret = UCAL_SECOND; break; case kCFCalendarUnitWeek: ret = UCAL_WEEK_OF_YEAR; break; case kCFCalendarUnitWeekday: ret = UCAL_DAY_OF_WEEK; break; case kCFCalendarUnitWeekdayOrdinal: ret = UCAL_DAY_OF_WEEK_IN_MONTH; break; case kCFCalendarUnitQuarter: ret = UCAL_MONTH; /* FIXME */ break; default: ret = -1; } return ret; } /* This function returns true is there is still characters to be consumed. */ CF_INLINE Boolean CFCalendarGetCalendarUnitFromDescription (const char **description, CFCalendarUnit *unit) { const char *current = *description; if (current == NULL || *current == '\0') return false; switch (*current++) { case 'y': *unit = kCFCalendarUnitYear; break; case 'M': *unit = kCFCalendarUnitMonth; break; case 'd': *unit = kCFCalendarUnitDay; break; case 'H': *unit = kCFCalendarUnitHour; break; case 'm': *unit = kCFCalendarUnitMinute; break; case 's': *unit = kCFCalendarUnitSecond; break; } *description = current; return true; } CFTypeID CFCalendarGetTypeID (void) { return _kCFCalendarTypeID; } CFCalendarRef CFCalendarCopyCurrent (void) { if (_kCFCalendarCurrent == NULL) { GSMutexLock (&_kCFCalendarLock); if (_kCFCalendarCurrent == NULL) { CFLocaleRef locale; CFStringRef calIdent; CFCalendarRef cal; locale = CFLocaleCopyCurrent (); calIdent = CFLocaleGetValue (locale, kCFLocaleCalendarIdentifier); cal = CFCalendarCreateWithIdentifier (NULL, calIdent); CFCalendarSetLocale (cal, locale); CFRelease (locale); _kCFCalendarCurrent = cal; } GSMutexUnlock (&_kCFCalendarLock); } return _kCFCalendarCurrent; } CFCalendarRef CFCalendarCreateWithIdentifier (CFAllocatorRef allocator, CFStringRef ident) { CFLocaleRef locale; CFCalendarRef new; CFTimeZoneRef tz; if (!(ident == kCFGregorianCalendar || ident == kCFBuddhistCalendar || ident == kCFChineseCalendar || ident == kCFHebrewCalendar || ident == kCFIslamicCalendar || ident == kCFIslamicCivilCalendar || ident == kCFJapaneseCalendar || ident == kCFRepublicOfChinaCalendar || ident == kCFPersianCalendar || ident == kCFIndianCalendar || ident == kCFISO8601Calendar)) { if (CFEqual(ident, kCFGregorianCalendar)) ident = kCFGregorianCalendar; else if (CFEqual(ident, kCFBuddhistCalendar)) ident = kCFBuddhistCalendar; else if (CFEqual(ident, kCFChineseCalendar)) ident = kCFChineseCalendar; else if (CFEqual(ident, kCFHebrewCalendar)) ident = kCFHebrewCalendar; else if (CFEqual(ident, kCFIslamicCalendar)) ident = kCFIslamicCalendar; else if (CFEqual(ident, kCFIslamicCivilCalendar)) ident = kCFIslamicCivilCalendar; else if (CFEqual(ident, kCFJapaneseCalendar)) ident = kCFJapaneseCalendar; else if (CFEqual(ident, kCFRepublicOfChinaCalendar)) ident = kCFRepublicOfChinaCalendar; else if (CFEqual(ident, kCFPersianCalendar)) ident = kCFPersianCalendar; else if (CFEqual(ident, kCFIndianCalendar)) ident = kCFIndianCalendar; else if (CFEqual(ident, kCFISO8601Calendar)) ident = kCFISO8601Calendar; else return NULL; } new = (CFCalendarRef)_CFRuntimeCreateInstance (allocator, _kCFCalendarTypeID, sizeof(struct __CFCalendar) - sizeof(CFRuntimeBase), NULL); new->_ident = ident; locale = CFLocaleCopyCurrent (); new->_localeIdent = CFRetain (CFLocaleGetIdentifier(locale)); CFRelease (locale); tz = CFTimeZoneCopyDefault (); new->_tzIdent = CFRetain (CFTimeZoneGetName (tz)); CFRelease (tz); return new; } CFTimeZoneRef CFCalendarCopyTimeZone (CFCalendarRef cal) { return CFTimeZoneCreateWithName (CFGetAllocator(cal), cal->_tzIdent, true); } void CFCalendarSetTimeZone (CFCalendarRef cal, CFTimeZoneRef tz) { CFStringRef tzIdent; tzIdent = CFTimeZoneGetName(tz); if (CFStringCompare (cal->_tzIdent, tzIdent, 0) != 0) { CFIndex len; UniChar buffer[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; CFCalendarOpenUCalendar (cal); len = CFStringGetLength (tzIdent); if (len > BUFFER_SIZE) len = BUFFER_SIZE; CFStringGetCharacters (tzIdent, CFRangeMake(0, len), buffer); ucal_setTimeZone (cal->_ucal, buffer, len, &err); } } CFStringRef CFCalendarGetIdentifier (CFCalendarRef cal) { return cal->_ident; } CFLocaleRef CFCalendarCopyLocale (CFCalendarRef cal) { return CFLocaleCreate (NULL, cal->_localeIdent); } void CFCalendarSetLocale (CFCalendarRef cal, CFLocaleRef locale) { if (cal->_localeIdent != NULL) CFRelease (cal->_localeIdent); cal->_localeIdent = CFRetain (CFLocaleGetIdentifier(locale)); CFCalendarCloseUCalendar (cal); } CFIndex CFCalendarGetFirstWeekday (CFCalendarRef cal) { CFCalendarOpenUCalendar (cal); return ucal_getAttribute (cal->_ucal, UCAL_FIRST_DAY_OF_WEEK); } void CFCalendarSetFirstWeekday (CFCalendarRef cal, CFIndex wkdy) { CFCalendarOpenUCalendar (cal); ucal_setAttribute (cal->_ucal, UCAL_FIRST_DAY_OF_WEEK, wkdy); } CFIndex CFCalendarGetMinimumDaysInFirstWeek (CFCalendarRef cal) { CFCalendarOpenUCalendar (cal); return ucal_getAttribute (cal->_ucal, UCAL_MINIMAL_DAYS_IN_FIRST_WEEK); } void CFCalendarSetMinimumDaysInFirstWeek (CFCalendarRef cal, CFIndex mwd) { CFCalendarOpenUCalendar (cal); ucal_setAttribute (cal->_ucal, UCAL_MINIMAL_DAYS_IN_FIRST_WEEK, mwd); } Boolean CFCalendarAddComponents (CFCalendarRef cal, CFAbsoluteTime *at, CFOptionFlags options, const char *componentDesc, ...) { va_list arg; int value; CFCalendarUnit unit = 0; UCalendarDateFields field; UErrorCode err = U_ZERO_ERROR; CFCalendarOpenUCalendar(cal); ucal_setMillis (cal->_ucal, ABSOLUTETIME_TO_UDATE(*at), &err); if (U_FAILURE(err)) return false; va_start (arg, componentDesc); while (CFCalendarGetCalendarUnitFromDescription(&componentDesc, &unit)) { switch (unit) { case kCFCalendarUnitYear: field = UCAL_YEAR; value = va_arg (arg, int); break; case kCFCalendarUnitMonth: field = UCAL_MONTH; value = va_arg (arg, int); break; case kCFCalendarUnitDay: field = UCAL_DAY_OF_MONTH; value = va_arg (arg, int); break; case kCFCalendarUnitHour: field = UCAL_HOUR_OF_DAY; value = va_arg (arg, int); break; case kCFCalendarUnitMinute: field = UCAL_MINUTE; value = va_arg (arg, int); break; case kCFCalendarUnitSecond: field = UCAL_SECOND; value = va_arg (arg, int) - 1; break; default: va_arg (arg, int); /* Skip */ continue; } if (options & kCFCalendarComponentsWrap) ucal_roll (cal->_ucal, field, value, &err); else ucal_add (cal->_ucal, field, value, &err); } va_end(arg); *at = UDATE_TO_ABSOLUTETIME(ucal_getMillis (cal->_ucal, &err)); if (U_FAILURE(err)) return false; return true; } Boolean CFCalendarComposeAbsoluteTime (CFCalendarRef cal, CFAbsoluteTime *at, const char *componentDesc, ...) { va_list arg; int value; UCalendarDateFields field; CFCalendarUnit unit = 0; UErrorCode err = U_ZERO_ERROR; CFCalendarOpenUCalendar(cal); va_start (arg, componentDesc); while (CFCalendarGetCalendarUnitFromDescription(&componentDesc, &unit)) { switch (unit) { case kCFCalendarUnitYear: value = va_arg (arg, int); field = UCAL_YEAR; break; case kCFCalendarUnitMonth: value = va_arg (arg, int) - 1; field = UCAL_MONTH; break; case kCFCalendarUnitDay: value = va_arg (arg, int); field = UCAL_DATE; break; case kCFCalendarUnitHour: value = va_arg (arg, int); field = UCAL_HOUR_OF_DAY; break; case kCFCalendarUnitMinute: value = va_arg (arg, int); field = UCAL_MINUTE; break; case kCFCalendarUnitSecond: value = va_arg (arg, int); field = UCAL_SECOND; break; default: va_arg (arg, int); /* Skip */ continue; } ucal_set (cal->_ucal, field, value); } va_end(arg); *at = UDATE_TO_ABSOLUTETIME(ucal_getMillis (cal->_ucal, &err)); if (U_FAILURE(err)) return false; return true; } Boolean CFCalendarDecomposeAbsoluteTime (CFCalendarRef cal, CFAbsoluteTime at, const char *componentDesc, ...) { va_list arg; int *value; CFCalendarUnit unit = 0; UCalendarDateFields field; UErrorCode err = U_ZERO_ERROR; CFCalendarOpenUCalendar(cal); ucal_setMillis (cal->_ucal, ABSOLUTETIME_TO_UDATE(at), &err); if (U_FAILURE(err)) return false; va_start (arg, componentDesc); while (CFCalendarGetCalendarUnitFromDescription(&componentDesc, &unit)) { value = NULL; switch (unit) { case kCFCalendarUnitYear: field = UCAL_YEAR; value = va_arg (arg, int*); break; case kCFCalendarUnitMonth: field = UCAL_MONTH; value = va_arg (arg, int*); break; case kCFCalendarUnitDay: field = UCAL_DAY_OF_MONTH; value = va_arg (arg, int*); break; case kCFCalendarUnitHour: field = UCAL_HOUR_OF_DAY; value = va_arg (arg, int*); break; case kCFCalendarUnitMinute: field = UCAL_MINUTE; value = va_arg (arg, int*); break; case kCFCalendarUnitSecond: field = UCAL_SECOND; value = va_arg (arg, int*); break; default: va_arg (arg, int*); /* Skip */ } if (value) { *value = ucal_get (cal->_ucal, field, &err); if (unit == kCFCalendarUnitMonth) *value += 1; } } va_end(arg); if (U_FAILURE(err)) return false; return true; } Boolean CFCalendarGetComponentDifference (CFCalendarRef cal, CFAbsoluteTime startAT, CFAbsoluteTime resultAT, CFOptionFlags options, const char *componentDesc, ...) { /* FIXME: ICU 4.8 introduced ucal_getFieldDifference() which should make implementing this function very easy. */ va_list arg; int *value; int32_t mult; CFCalendarUnit unit = 0; UDate start; UDate end; UCalendarDateFields field; UCalendar *ucal; UErrorCode err = U_ZERO_ERROR; CFCalendarOpenUCalendar(cal); if (startAT > resultAT) { start = ABSOLUTETIME_TO_UDATE(resultAT); end = ABSOLUTETIME_TO_UDATE(startAT); mult = -1; } else { start = ABSOLUTETIME_TO_UDATE(startAT); end = ABSOLUTETIME_TO_UDATE(resultAT); mult = 1; } ucal = cal->_ucal; ucal_setMillis (ucal, start, &err); if (U_FAILURE(err)) return false; va_start (arg, componentDesc); while (CFCalendarGetCalendarUnitFromDescription(&componentDesc, &unit)) { int32_t min = 0; int32_t max = 1; double millis; value = NULL; switch (unit) { case kCFCalendarUnitYear: field = UCAL_YEAR; value = va_arg (arg, int*); break; case kCFCalendarUnitMonth: field = UCAL_MONTH; value = va_arg (arg, int*); break; case kCFCalendarUnitDay: field = UCAL_DAY_OF_MONTH; value = va_arg (arg, int*); break; case kCFCalendarUnitHour: field = UCAL_HOUR_OF_DAY; value = va_arg (arg, int*); break; case kCFCalendarUnitMinute: field = UCAL_MINUTE; value = va_arg (arg, int*); break; case kCFCalendarUnitSecond: field = UCAL_SECOND; value = va_arg (arg, int*); break; default: va_arg (arg, int*); /* Skip */ continue; } /* Get a range */ do { ucal_setMillis (ucal, start, &err); if (options & kCFCalendarComponentsWrap) ucal_roll (cal->_ucal, field, max, &err); else ucal_add (cal->_ucal, field, max, &err); millis = ucal_getMillis (ucal, &err); if (millis < end) { min = max; max <<= 1; /* multiply by 2... */ if (max < 0) return false; } } while (millis < end && U_SUCCESS(err)); if (millis != end) { while ((max - min) > 1 && U_SUCCESS(err)) { int32_t add = (max + min) / 2; ucal_setMillis (ucal, start, &err); if (options & kCFCalendarComponentsWrap) ucal_roll (cal->_ucal, field, add, &err); else ucal_add (cal->_ucal, field, add, &err); millis = ucal_getMillis (ucal, &err); if (millis == end) { *value = add * mult; break; } else if (millis < end) { min = add; } else { max = add; } } if (millis > end) *value = min * mult; } else { *value = max * mult; } ucal_setMillis (ucal, start, &err); if (options & kCFCalendarComponentsWrap) ucal_roll (cal->_ucal, field, min, &err); else ucal_add (cal->_ucal, field, min, &err); start = ucal_getMillis (ucal, &err); if (U_FAILURE(err)) return false; } va_end(arg); return true; } Boolean CFCalendarGetTimeRangeOfUnit (CFCalendarRef cal, CFCalendarUnit unit, CFAbsoluteTime at, CFAbsoluteTime *startp, CFTimeInterval *tip) { double start; double end; UCalendar *ucal; UErrorCode err = U_ZERO_ERROR; UCalendarDateFields field = CFCalendarUnitToUCalendarDateFields (unit); CFCalendarOpenUCalendar (cal); ucal = cal->_ucal; ucal_setMillis (ucal, ABSOLUTETIME_TO_UDATE(at), &err); if (U_FAILURE(err)) return false; /* Clear lower fields */ switch (field) { case UCAL_ERA: ucal_set (ucal, UCAL_YEAR, ucal_getLimit(ucal, UCAL_YEAR, UCAL_ACTUAL_MINIMUM, &err)); case UCAL_YEAR: ucal_set (ucal, UCAL_MONTH, ucal_getLimit(ucal, UCAL_MONTH, UCAL_ACTUAL_MINIMUM, &err)); case UCAL_MONTH: ucal_set (ucal, UCAL_DATE, ucal_getLimit(ucal, UCAL_DATE, UCAL_ACTUAL_MINIMUM, &err)); case UCAL_DATE: case UCAL_DAY_OF_YEAR: case UCAL_DAY_OF_WEEK: case UCAL_DAY_OF_WEEK_IN_MONTH: ucal_set (ucal, UCAL_HOUR_OF_DAY, ucal_getLimit(ucal, UCAL_HOUR_OF_DAY, UCAL_ACTUAL_MINIMUM, &err)); case UCAL_HOUR_OF_DAY: ucal_set (ucal, UCAL_MINUTE, ucal_getLimit(ucal, UCAL_MINUTE, UCAL_ACTUAL_MINIMUM, &err)); case UCAL_MINUTE: ucal_set (ucal, UCAL_SECOND, ucal_getLimit(ucal, UCAL_SECOND, UCAL_ACTUAL_MINIMUM, &err)); default: break; } start = UDATE_TO_ABSOLUTETIME(ucal_getMillis (cal->_ucal, &err)); if (startp) *startp = start; if (tip) { ucal_add (ucal, field, 1, &err); end = UDATE_TO_ABSOLUTETIME(ucal_getMillis (cal->_ucal, &err)); *tip = end - start; } if (U_FAILURE(err)) return false; return true; } CFRange CFCalendarGetRangeOfUnit (CFCalendarRef cal, CFCalendarUnit smallerUnit, CFCalendarUnit biggerUnit, CFAbsoluteTime at) { return CFRangeMake (kCFNotFound, kCFNotFound); } CFIndex CFCalendarGetOrdinalityOfUnit (CFCalendarRef cal, CFCalendarUnit smallerUnit, CFCalendarUnit biggerUnit, CFAbsoluteTime at) { return kCFNotFound; } static CFRange CFCalendarGetMinMaxRangeOfUnit (CFCalendarRef cal, CFCalendarUnit unit, UCalendarLimitType min, UCalendarLimitType max) { CFRange range; UErrorCode err = U_ZERO_ERROR; UCalendarDateFields field = CFCalendarUnitToUCalendarDateFields (unit); CFCalendarOpenUCalendar (cal); range.location = ucal_getLimit (cal->_ucal, field, min, &err); range.length = ucal_getLimit (cal->_ucal, field, max, &err) - range.location + 1; if (unit == kCFCalendarUnitMonth) range.location += 1; return range; } CFRange CFCalendarGetMaximumRangeOfUnit (CFCalendarRef cal, CFCalendarUnit unit) { return CFCalendarGetMinMaxRangeOfUnit (cal, unit, UCAL_GREATEST_MINIMUM, UCAL_LEAST_MAXIMUM); } CFRange CFCalendarGetMinimumRangeOfUnit (CFCalendarRef cal, CFCalendarUnit unit) { return CFCalendarGetMinMaxRangeOfUnit (cal, unit, UCAL_MINIMUM, UCAL_MAXIMUM); } gnustep-corebase-0.2/Source/CFURL.c0000644000175000017500000014152713222706330016172 0ustar yavoryavor/* CFURL.c Copyright (C) 2012 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* READ FIRST * Using RFC 3986 instead of 2396 because it is the latest URL/URI * specification when this file was written in January 2012. The main * difference is that RFC 3986 adds IPv6 address support, allowing * this implementation to be a little more future proof than if we were * using only RFC 2396. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFURL.h" #include "CoreFoundation/GSUnicode.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" #include #define BUFFER_SIZE 256 #if defined(_WIN32) #define CFURL_DEFAULT_PATH_STYLE kCFURLWindowsPathStyle #else #define CFURL_DEFAULT_PATH_STYLE kCFURLPOSIXPathStyle #endif #define URL_IS_LEGAL(c) (c > 0x0020 && c < 0x007F) #define URL_IS_SCHEME(c) (CHAR_IS_ALPHA(c) || CHAR_IS_DIGIT(c) \ || c == '+' || c == '-' || c == '.') #define URL_IS_PCHAR(c) (URL_IS_UNRESERVED(c) || c == '%' \ || URL_IS_SUB_DELIMS(c) || c == ':' || c == '@') #define URL_IS_RESERVED(c) (URL_IS_GEN_DELIMS(c) || URL_IS_SUB_DELIMS(c)) #define URL_IS_UNRESERVED(c) (CHAR_IS_ALPHA(c) || CHAR_IS_DIGIT(c) \ || c == '-' || c == '.' || c == '_' || c == '~') #define URL_IS_GEN_DELIMS(c) (c == ':' || c == '/' || c == '?' \ || c == '#' || c == '[' || c == ']' || c == '@') #define URL_IS_SUB_DELIMS(c) (c == '!' || c == '$' || c == '&' || c == '\'' \ || c == '(' || c == '*' || c == '+' || c == ',' || c == ';' || c == '=') static CFTypeID _kCFURLTypeID = 0; struct __CFURL { CFRuntimeBase _parent; CFStringRef _urlString; CFURLRef _baseURL; CFStringEncoding _encoding; /* The encoding of the escape characters */ CFRange _ranges[12]; /* CFURLComponentType ranges */ }; enum { _kCFURLIsDecomposable = (1<<0), _kCFURLIsFileSystemPath = (1<<1) }; CF_INLINE Boolean CFURLIsDecomposable (CFURLRef url) { return ((CFRuntimeBase *)url)->_flags.info & _kCFURLIsDecomposable ? true : false; } CF_INLINE Boolean CFURLIsFileSystemPath (CFURLRef url) { return ((CFRuntimeBase *)url)->_flags.info & _kCFURLIsFileSystemPath ? true : false; } CF_INLINE void CFURLSetIsDecomposable (CFURLRef url) { ((CFRuntimeBase *)url)->_flags.info |= _kCFURLIsDecomposable; } CF_INLINE void CFURLSetIsFileSystemPath (CFURLRef url) { ((CFRuntimeBase *)url)->_flags.info |= _kCFURLIsFileSystemPath; } static void CFURLFinalize (CFTypeRef cf) { CFURLRef url = (CFURLRef)cf; CFRelease (url->_urlString); if (url->_baseURL) CFRelease (url->_baseURL); } static Boolean CFURLEqual (CFTypeRef cf1, CFTypeRef cf2) { Boolean equal; CFURLRef url1 = CFURLCopyAbsoluteURL ((CFURLRef)cf1); CFURLRef url2 = CFURLCopyAbsoluteURL ((CFURLRef)cf2); equal = CFEqual (CFURLGetString(url1), CFURLGetString(url2)); CFRelease (url1); CFRelease (url2); return equal; } static CFHashCode CFURLHash (CFTypeRef cf) { CFHashCode hash; CFURLRef url = CFURLCopyAbsoluteURL ((CFURLRef)cf); hash = CFHash (CFURLGetString(url)); CFRelease (url); return hash; } static CFStringRef CFURLCopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOptions) { CFStringRef str; CFURLRef url = CFURLCopyAbsoluteURL ((CFURLRef)cf); str = CFRetain (CFURLGetString(url)); CFRelease (url); return str; } static const CFRuntimeClass CFURLClass = { 0, "CFURL", NULL, NULL, CFURLFinalize, CFURLEqual, CFURLHash, CFURLCopyFormattingDesc, NULL }; void CFURLInitialize (void) { _kCFURLTypeID = _CFRuntimeRegisterClass (&CFURLClass); } CFTypeID CFURLGetTypeID (void) { return _kCFURLTypeID; } static Boolean CFURLStringParse (CFStringRef urlString, CFRange ranges[12]) { /* URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] * hier-part = "//" authority path-abempty * / path-absolute * / path-rootless * / path-empty * URI-reference = URI / relative-ref * relative-ref = "//" authority path-abempty * / path-absolute * / path-noscheme * / path-empty */ CFStringInlineBuffer iBuffer; CFIndex idx; CFIndex start; CFIndex resourceSpecifierStart; CFIndex length; UniChar c; Boolean hasScheme; Boolean hasNetLoc; for (idx = 0 ; idx < 12 ; ++idx) ranges[idx] = CFRangeMake (kCFNotFound, 0); length = CFStringGetLength (urlString); CFStringInitInlineBuffer (urlString, &iBuffer, CFRangeMake(0, length)); idx = start = 0; resourceSpecifierStart = kCFNotFound; /* Since ':' can appear anywhere in the string, we'll try to find * the scheme first. */ /* Scheme component */ c = CFStringGetCharacterFromInlineBuffer (&iBuffer, idx++); hasScheme = false; if (CHAR_IS_ALPHA(c)) { do { c = CFStringGetCharacterFromInlineBuffer (&iBuffer, idx++); } while (URL_IS_SCHEME(c)); if (c == ':') { ranges[kCFURLComponentScheme - 1] = CFRangeMake (start, idx - start - 1); hasScheme = true; } else { idx = 0; /* Start over... */ } start = idx; c = CFStringGetCharacterFromInlineBuffer (&iBuffer, idx++); } /* Parse the relative-ref: * hier-part = "//" authority path-abempty * / path-absolute * / path-rootless * / path-empty * relative-ref = "//" authority path-abempty * / path-absolute * / path-noscheme * / path-empty */ /* Net Location component */ hasNetLoc = false; if (c == '/' && CFStringGetCharacterFromInlineBuffer (&iBuffer, idx) == '/') { /* "//" authority path-abempty */ CFIndex end; CFIndex i; hasNetLoc = true; ++idx; i = idx; start = i; /* Go to the end so we can parse backwards. */ do { c = CFStringGetCharacterFromInlineBuffer (&iBuffer, i++); } while (URL_IS_PCHAR(c)); ranges[kCFURLComponentNetLocation - 1] = CFRangeMake (start, i-start-1); end = i; i = start; while (i < end) { /* FIXME: RFC 3986 is a little vague on what goes in the * UserInfo section, and Apple requires both User Name and * Password. We simply consider everything after the first ':' * to be part of the password. This behavior needs to be tested. */ c = CFStringGetCharacterFromInlineBuffer (&iBuffer, i++); if (c == '@') { CFIndex userInfoEnd; ranges[kCFURLComponentUserInfo - 1] = CFRangeMake (start, i - start); userInfoEnd = i; i = start; while (i < userInfoEnd) { c = CFStringGetCharacterFromInlineBuffer (&iBuffer, i++); if (c == ':') { ranges[kCFURLComponentPassword - 1] = CFRangeMake (i, userInfoEnd - i - 1); break; } } ranges[kCFURLComponentUser - 1] = CFRangeMake (start, i - start - 1); start = userInfoEnd; break; } } i = end; idx = end; /* Set idx before we move it to search for a port. */ /* Try to find a port. */ while (i > start) { c = CFStringGetCharacterFromInlineBuffer (&iBuffer, --i); if (c == ':') { ranges[kCFURLComponentPort - 1] = CFRangeMake (i, end - i); end = i; break; } } /* Whatever's left is the host name. */ ranges[kCFURLComponentHost - 1] = CFRangeMake (start, end - start - 1); start = idx - 1; /* Shift back to just before '/' */ c = CFStringGetCharacterFromInlineBuffer (&iBuffer, start); } /* Path component */ while ((URL_IS_PCHAR(c) || c == '/') && c != ';') c = CFStringGetCharacterFromInlineBuffer (&iBuffer, idx++); ranges[kCFURLComponentPath - 1] = CFRangeMake (start, idx - start - 1); if (hasScheme == false && hasNetLoc == false) resourceSpecifierStart = start; /* Parameter String component */ if (c == ';') { start = idx; do { c = CFStringGetCharacterFromInlineBuffer (&iBuffer, idx++); } while (URL_IS_PCHAR(c) || c == '/'); ranges[kCFURLComponentParameterString - 1] = CFRangeMake (start, idx - start - 1); ranges[kCFURLComponentPath - 1].length += idx - start; if (resourceSpecifierStart == kCFNotFound) resourceSpecifierStart = start - 1; } /* Query component */ if (c == '?') { start = idx; do { c = CFStringGetCharacterFromInlineBuffer (&iBuffer, idx++); } while (URL_IS_PCHAR(c) || c == '/' || c == '?'); ranges[kCFURLComponentQuery - 1] = CFRangeMake (start, idx - start - 1); if (resourceSpecifierStart == kCFNotFound) resourceSpecifierStart = start - 1; } /* Fragment component */ if (c == '#') { start = idx; do { c = CFStringGetCharacterFromInlineBuffer (&iBuffer, idx++); } while (URL_IS_PCHAR(c) || c == '/' || c == '?'); ranges[kCFURLComponentFragment - 1] = CFRangeMake (start, idx-start-1); if (resourceSpecifierStart == kCFNotFound) resourceSpecifierStart = start - 1; } if (c != 0x0000) return false; if (resourceSpecifierStart != kCFNotFound) ranges[kCFURLComponentResourceSpecifier - 1] = CFRangeMake (resourceSpecifierStart, idx - resourceSpecifierStart); return true; } #define CFURL_SIZE sizeof(struct __CFURL) - sizeof(CFRuntimeBase) static CFURLRef CFURLCreate_internal (CFAllocatorRef alloc, CFStringRef string, CFURLRef baseURL, CFStringEncoding encoding) { struct __CFURL *new; CFRange ranges[12]; if (!CFURLStringParse (string, ranges)) return NULL; new = (struct __CFURL*)_CFRuntimeCreateInstance (alloc, _kCFURLTypeID, CFURL_SIZE, 0); if (new) { new->_urlString = CFStringCreateCopy (alloc, string); if (ranges[kCFURLComponentScheme - 1].location == kCFNotFound && baseURL) { new->_baseURL = CFURLCopyAbsoluteURL (baseURL); } else { CFURLSetIsDecomposable (new); } new->_encoding = encoding; memcpy (new->_ranges, ranges, sizeof(ranges)); } return new; } CFURLRef CFURLCreateWithString (CFAllocatorRef alloc, CFStringRef string, CFURLRef baseURL) { return CFURLCreate_internal (alloc, string, baseURL, kCFStringEncodingUTF8); } static void CFURLStringAppendByRemovingDotSegments (CFMutableStringRef string, UniChar *buffer, CFIndex length) { UniChar *bufferStart; UniChar *bufferEnd; CFIndex pathStart; bufferStart = buffer; bufferEnd = bufferStart + length; pathStart = CFStringGetLength (string); /* Skip any '../' and './' */ if (buffer < bufferEnd && *buffer == '.') { if ((buffer + 1) < bufferEnd && buffer[1] == '/') { buffer += 1; } else if ((buffer + 2) < bufferEnd && buffer[1] == '.' && buffer[2] == '/') { buffer += 2; } } bufferStart = buffer; /* Start checking for '/.' and '/..' */ while (buffer < bufferEnd) { if ((buffer + 1) < bufferEnd && buffer[0] == '/' && buffer[1] == '.') { /* Skip '/./' or '/.'EOS */ if (((buffer + 2) < bufferEnd && buffer[2] == '/') || (buffer + 2) == bufferEnd) { if ((buffer + 2) == bufferEnd) { buffer[1] = '/'; buffer += 1; } else { buffer += 2; } } /* Skip '/../' or '/..'EOS */ else if (((buffer + 3) < bufferEnd && buffer[2] == '.' && buffer[3] == '/') || ((buffer + 3) == bufferEnd && buffer[2] == '.')) { CFStringInlineBuffer iBuffer; UniChar c; CFIndex i; CFIndex pathLength; pathLength = CFStringGetLength(string) - pathStart; CFStringInitInlineBuffer (string, &iBuffer, CFRangeMake(pathStart, pathLength)); i = pathLength - 1; while (i >= 0) { c = CFStringGetCharacterFromInlineBuffer (&iBuffer, i--); if (c == '/') break; } CFStringDelete (string, CFRangeMake(pathStart + i + 1, pathLength - i - 1)); if ((buffer + 3) == bufferEnd) { buffer[2] = '/'; buffer += 2; } else { buffer += 3; } } /* Something like '/..*' */ else { /* Skip onto the next '/' */ do { buffer++; } while (buffer < bufferEnd && *buffer != '/'); CFStringAppendCharacters (string, bufferStart, buffer - bufferStart); } } else { /* Skip onto the next '/' */ do { buffer++; } while (buffer < bufferEnd && *buffer != '/'); CFStringAppendCharacters (string, bufferStart, buffer - bufferStart); } bufferStart = buffer; } } CFURLRef CFURLCopyAbsoluteURL (CFURLRef relativeURL) { CFAllocatorRef alloc; CFMutableStringRef targetString; CFStringRef relString; CFStringRef baseString; CFURLRef base; CFURLRef target; UniChar *buffer; CFIndex capacity; CFRange *relRanges; CFRange baseRanges[12]; CFRange range; base = relativeURL->_baseURL; if (base == NULL) return CFRetain (relativeURL); /* This is a bit of a pain. We can't assume _baseURL is a CFURL, so we * need to parse it before moving forward. To avoid parsing the same * string twice (in the case that _baseURL is a CFURL) we check first. */ baseString = CFURLGetString (base); if (CF_IS_OBJC(_kCFURLTypeID, base)) CFURLStringParse (baseString, baseRanges); else memcpy (baseRanges, base->_ranges, sizeof(baseRanges)); relString = relativeURL->_urlString; relRanges = (CFRange*)relativeURL->_ranges; alloc = CFGetAllocator(relativeURL); capacity = CFStringGetLength(relString) + CFStringGetLength(baseString); buffer = CFAllocatorAllocate (alloc, capacity * sizeof(UniChar), 0); targetString = CFStringCreateMutable (alloc, capacity); range = relRanges[kCFURLComponentScheme - 1]; if (range.location != kCFNotFound) { /* Scheme */ CFStringGetCharacters (relString, range, buffer); CFStringAppendCharacters (targetString, buffer, range.length); CFStringAppendCString (targetString, ":", kCFStringEncodingASCII); /* Authority */ range = relRanges[kCFURLComponentNetLocation - 1]; if (range.location != kCFNotFound) { CFStringAppendCString (targetString, "//", kCFStringEncodingASCII); CFStringGetCharacters (relString, range, buffer); CFStringAppendCharacters (targetString, buffer, range.length); } /* Path */ range = relRanges[kCFURLComponentPath - 1]; if (range.location != kCFNotFound) { CFStringGetCharacters (relString, range, buffer); CFURLStringAppendByRemovingDotSegments (targetString, buffer, range.length); } /* Query */ range = relRanges[kCFURLComponentQuery - 1]; if (range.location != kCFNotFound) { CFStringAppendCString (targetString, "?", kCFStringEncodingASCII); CFStringGetCharacters (relString, range, buffer); CFStringAppendCharacters (targetString, buffer, range.length); } } else { /* Scheme */ range = baseRanges[kCFURLComponentScheme - 1]; if (range.location != kCFNotFound) { CFStringGetCharacters (baseString, range, buffer); CFStringAppendCharacters (targetString, buffer, range.length); CFStringAppendCString (targetString, ":", kCFStringEncodingASCII); } range = relRanges[kCFURLComponentNetLocation - 1]; if (range.location != kCFNotFound) { /* Authority */ CFStringAppendCString (targetString, "//", kCFStringEncodingASCII); CFStringGetCharacters (relString, range, buffer); CFStringAppendCharacters (targetString, buffer, range.length); /* Path */ range = relRanges[kCFURLComponentPath - 1]; if (range.location != kCFNotFound) { CFStringGetCharacters (relString, range, buffer); CFURLStringAppendByRemovingDotSegments (targetString, buffer, range.length); } /* Query */ range = relRanges[kCFURLComponentQuery - 1]; if (range.location != kCFNotFound) { CFStringAppendCString (targetString, "?", kCFStringEncodingASCII); CFStringGetCharacters (relString, range, buffer); CFStringAppendCharacters (targetString, buffer, range.length); } } else { /* Authority */ range = baseRanges[kCFURLComponentNetLocation - 1]; if (range.location != kCFNotFound) { CFStringAppendCString (targetString, "//", kCFStringEncodingASCII); CFStringGetCharacters (baseString, range, buffer); CFStringAppendCharacters (targetString, buffer, range.length); } range = relRanges[kCFURLComponentPath - 1]; if (range.location != kCFNotFound) { /* Path */ if (range.length == 0) { range = baseRanges[kCFURLComponentPath - 1]; if (range.location != kCFNotFound) { CFStringGetCharacters (baseString, range, buffer); CFStringAppendCharacters (targetString, buffer, range.length); } /* Query */ range = relRanges[kCFURLComponentQuery - 1]; if (range.location != kCFNotFound) { CFStringAppendCString (targetString, "?", kCFStringEncodingASCII); CFStringGetCharacters (relString, range, buffer); CFStringAppendCharacters (targetString, buffer, range.length); } else { /* Query */ range = baseRanges[kCFURLComponentQuery - 1]; if (range.location != kCFNotFound) { CFStringAppendCString (targetString, "?", kCFStringEncodingASCII); CFStringGetCharacters (baseString, range, buffer); CFStringAppendCharacters (targetString, buffer, range.length); } } } else { if (CFStringGetCharacterAtIndex(relString, range.location) == '/') { CFStringGetCharacters (relString, range, buffer); CFURLStringAppendByRemovingDotSegments (targetString, buffer, range.length); } else { CFRange baseRange; baseRange = baseRanges[kCFURLComponentPath - 1]; if (baseRange.location != kCFNotFound) { CFStringGetCharacters (baseString, baseRange, buffer); if (baseRange.length > 0 && buffer[baseRange.length - 1] != '/') { /* Remove last path component */ CFIndex count; count = baseRange.length - 1; while (buffer[--count] != '/'); baseRange.length = count + 1; } } CFStringGetCharacters (relString, range, &buffer[baseRange.length]); range.length += baseRange.length; CFURLStringAppendByRemovingDotSegments (targetString, buffer, range.length); } range = relRanges[kCFURLComponentQuery - 1]; if (range.location != kCFNotFound) { CFStringAppendCString (targetString, "?", kCFStringEncodingASCII); CFStringGetCharacters (relString, range, buffer); CFStringAppendCharacters (targetString, buffer, range.length); } } } } } /* Fragment */ range = relRanges[kCFURLComponentFragment - 1]; if (range.location != kCFNotFound) { CFStringAppendCString (targetString, "#", kCFStringEncodingASCII); CFStringGetCharacters (relString, range, buffer); CFStringAppendCharacters (targetString, buffer, range.length); } target = CFURLCreate_internal (alloc, targetString, NULL, kCFStringEncodingUTF8); CFRelease (targetString); CFAllocatorDeallocate (alloc, buffer); return target; } CFURLRef CFURLCreateAbsoluteURLWithBytes (CFAllocatorRef alloc, const UInt8 *relativeURLBytes, CFIndex length, CFStringEncoding encoding, CFURLRef baseURL, Boolean useCompatibilityMode) { /* FIXME: what to do with useCompatibilityMode? */ CFURLRef url; CFStringRef str; str = CFStringCreateWithBytes (alloc, relativeURLBytes, length, encoding, false); if (str == NULL) return NULL; url = CFURLCreate_internal (alloc, str, baseURL, encoding); if (url) { CFURLRef tmp = CFURLCopyAbsoluteURL (url); CFRelease (url); url = tmp; } CFRelease (str); return url; } CFURLRef CFURLCreateCopyAppendingPathComponent (CFAllocatorRef alloc, CFURLRef url, CFStringRef pathComponent, Boolean isDirectory) { return NULL; /* FIXME */ } CFURLRef CFURLCreateCopyAppendingPathExtension (CFAllocatorRef alloc, CFURLRef url, CFStringRef extension) { return NULL; /* FIXME */ } CFURLRef CFURLCreateCopyDeletingLastPathComponent (CFAllocatorRef alloc, CFURLRef url) { return NULL; /* FIXME */ } CFURLRef CFURLCreateCopyDeletingPathExtension (CFAllocatorRef alloc, CFURLRef url) { return NULL; /* FIXME */ } CFURLRef CFURLCreateFilePathURL (CFAllocatorRef alloc, CFURLRef url, CFErrorRef *error) { return NULL; /* FIXME */ } CFURLRef CFURLCreateFileReferenceURL (CFAllocatorRef alloc, CFURLRef url, CFErrorRef *error) { return NULL; /* FIXME */ } CFURLRef CFURLCreateFromFileSystemRepresentation (CFAllocatorRef alloc, const UInt8 *buffer, CFIndex bufLen, Boolean isDirectory) { return CFURLCreateFromFileSystemRepresentationRelativeToBase (alloc, buffer, bufLen, isDirectory, NULL); } CFURLRef CFURLCreateFromFileSystemRepresentationRelativeToBase (CFAllocatorRef alloc, const UInt8 *buffer, CFIndex bufLen, Boolean isDirectory, CFURLRef baseURL) { CFURLRef ret; CFStringRef path; path = CFStringCreateWithBytesNoCopy (alloc, buffer, bufLen, GSStringGetFileSystemEncoding(), false, kCFAllocatorNull); ret = CFURLCreateWithFileSystemPathRelativeToBase (alloc, path, CFURL_DEFAULT_PATH_STYLE, isDirectory, baseURL); CFRelease (path); return ret; } CFURLRef CFURLCreateWithFileSystemPath (CFAllocatorRef alloc, CFStringRef fileSystemPath, CFURLPathStyle style, Boolean isDirectory) { CFURLRef ret; ret = CFURLCreateWithFileSystemPathRelativeToBase (alloc, fileSystemPath, style, isDirectory, NULL); return ret; } #if defined(_WIN32) #include #else #include #include #endif CF_INLINE CFURLRef CFURLCreateWithCurrentDirectory (CFAllocatorRef alloc) { CFURLRef ret; CFStringRef cwd; CFMutableStringRef str; #if defined(_WIN32) wchar_t buffer[MAX_PATH]; DWORD length; length = GetCurrentDirectoryW (MAX_PATH, buffer); if (length == 0) return NULL; cwd = CFStringCreateWithBytesNoCopy (alloc, (const UInt8 *)buffer, length, GSStringGetFileSystemEncoding(), false, kCFAllocatorNull); #else char buffer[1024]; if (getcwd(buffer, 1024) == NULL) return NULL; cwd = CFStringCreateWithBytesNoCopy (alloc, (const UInt8 *)buffer, strlen(buffer), GSStringGetFileSystemEncoding(), false, kCFAllocatorNull); #endif str = CFStringCreateMutable (alloc, 0); CFStringAppend (str, CFSTR("file://localhost/")); CFStringAppend (str, cwd); ret = CFURLCreateWithString (alloc, str, NULL); CFRelease (cwd); CFRelease (str); return ret; } static CFStringRef CFURLCreateStringFromHFSPathStyle (CFAllocatorRef alloc, CFStringRef filePath, Boolean isAbsolute, Boolean isDirectory) { return NULL; /* FIXME */ } static CFStringRef CFURLCreateStringFromWindowsPathStyle (CFAllocatorRef alloc, CFStringRef filePath, Boolean isAbsolute, Boolean isDirectory) { CFMutableArrayRef comps; CFArrayRef tmp; CFStringRef ret; CFIndex count; CFIndex idx; tmp = CFStringCreateArrayBySeparatingStrings (alloc, filePath, CFSTR("\\")); comps = CFArrayCreateMutableCopy (alloc, 0, tmp); CFRelease (tmp); idx = 0; if (isAbsolute) /* Instead empty string to get leading '/' */ { CFArrayInsertValueAtIndex (comps, 0, CFSTR("")); idx = 2; /* Skip drive letter */ } count = CFArrayGetCount (comps); while (idx < count) { CFStringRef unescaped; CFStringRef escaped; unescaped = CFArrayGetValueAtIndex(comps, idx); escaped = CFURLCreateStringByAddingPercentEscapes (alloc, unescaped, NULL, NULL, kCFStringEncodingUTF8); if (escaped != unescaped) CFArraySetValueAtIndex (comps, idx, escaped); CFRelease (escaped); ++idx; } /* Add '/' for directories */ if (isDirectory && !CFEqual(CFArrayGetValueAtIndex(comps, idx - 1), CFSTR(""))) CFArrayInsertValueAtIndex (comps, count, CFSTR("")); ret = CFStringCreateByCombiningStrings (alloc, comps, CFSTR("/")); CFRelease (comps); return ret; } CFURLRef CFURLCreateWithFileSystemPathRelativeToBase (CFAllocatorRef alloc, CFStringRef filePath, CFURLPathStyle style, Boolean isDirectory, CFURLRef baseURL) { CFURLRef ret; CFStringRef path; Boolean abs; CFIndex filePathLen; switch (style) { case kCFURLPOSIXPathStyle: abs = (CFStringGetCharacterAtIndex(filePath, 0) == '/'); path = CFURLCreateStringByAddingPercentEscapes (alloc, filePath, NULL, NULL, kCFStringEncodingUTF8); if (path != filePath) CFRetain (path); filePathLen = CFStringGetLength(path); if (isDirectory && CFStringGetCharacterAtIndex(path, filePathLen) != '/') { CFStringRef tmp; tmp = CFStringCreateWithFormat (alloc, NULL, CFSTR("%@/"), path); CFRelease (path); path = tmp; } break; case kCFURLHFSPathStyle: /* FIXME: I believe HFS path style is like POSIX with ':' instead * of '/' as the separator. */ abs = (CFStringGetCharacterAtIndex(filePath, 0) == ':'); path = CFURLCreateStringFromHFSPathStyle (alloc, filePath, abs, isDirectory); break; case kCFURLWindowsPathStyle: abs = (CFStringGetCharacterAtIndex(filePath, 1) == ':' && CFStringGetCharacterAtIndex(filePath, 2) == '\\'); path = CFURLCreateStringFromWindowsPathStyle (alloc, filePath, abs, isDirectory); break; default: return NULL; } if (abs) { CFMutableStringRef tmp; tmp = CFStringCreateMutableCopy (alloc, 0, CFSTR("file://localhost")); CFStringAppend (tmp, path); CFRelease (path); path = (CFStringRef)tmp; baseURL = NULL; } else if (baseURL == NULL) { baseURL = CFURLCreateWithCurrentDirectory (alloc); } else { CFRetain (baseURL); } ret = CFURLCreate_internal (alloc, path, baseURL, kCFStringEncodingUTF8); if (ret) CFURLSetIsFileSystemPath (ret); CFRelease (path); if (baseURL) CFRelease (baseURL); return ret; } CFURLRef CFURLCreateWithBytes (CFAllocatorRef alloc, const UInt8 *bytes, CFIndex length, CFStringEncoding encoding, CFURLRef baseURL) { CFStringRef str; CFURLRef ret; str = CFStringCreateWithBytesNoCopy (NULL, bytes, length, encoding, false, kCFAllocatorNull); ret = CFURLCreate_internal (alloc, str, baseURL, encoding); CFRelease (str); return ret; } Boolean CFURLCanBeDecomposed (CFURLRef url) { if (CFURLIsDecomposable(url)) return true; else return url->_baseURL ? CFURLCanBeDecomposed(url->_baseURL) : false; } static CFStringRef CFURLCreateHFSStylePath (CFAllocatorRef alloc, CFStringRef path) { return NULL; } static CFStringRef CFURLCreateWindowsStylePath (CFAllocatorRef alloc, CFStringRef path) { CFArrayRef comps; CFStringRef ret; comps = CFStringCreateArrayBySeparatingStrings (alloc, path, CFSTR("/")); if (CFEqual(CFArrayGetValueAtIndex(comps, 0), CFSTR(""))) { CFMutableArrayRef tmp; tmp = CFArrayCreateMutableCopy (alloc, 0, comps); CFArrayRemoveValueAtIndex (tmp, 0); CFRelease (comps); comps = tmp; } ret = CFStringCreateByCombiningStrings (alloc, comps, CFSTR("\\")); CFRelease (comps); return ret; } CFStringRef CFURLCopyFileSystemPath (CFURLRef url, CFURLPathStyle style) { CFStringRef urlStr; CFStringRef path; CFAllocatorRef alloc; CFRange r; r = url->_ranges[kCFURLComponentPath - 1]; if (r.location == kCFNotFound) return NULL; alloc = CFGetAllocator(url); urlStr = url->_urlString; if (r.length > 1) { CFStringRef tmp; if (CFStringGetCharacterAtIndex(urlStr, r.location + r.length - 1) == '/') r.length -= 1; tmp = CFStringCreateWithSubstring (alloc, urlStr, r); path = CFURLCreateStringByReplacingPercentEscapesUsingEncoding (alloc, tmp, CFSTR(""), url->_encoding); CFRelease (tmp); } else { path = CFSTR("/"); } switch (style) { case kCFURLPOSIXPathStyle: /* Do nothing. */ break; case kCFURLHFSPathStyle: { CFStringRef t; t = CFURLCreateHFSStylePath (CFGetAllocator(url), path); CFRelease (path); path = t; } break; case kCFURLWindowsPathStyle: { CFStringRef t; t = CFURLCreateWindowsStylePath (CFGetAllocator(url), path); CFRelease (path); path = t; } break; default: break; } return path; } CFStringRef CFURLCopyFragment (CFURLRef url, CFStringRef charactersToLeaveEscaped) { CFRange range = url->_ranges[kCFURLComponentFragment - 1]; if (range.location == kCFNotFound) { if (url->_baseURL) return CFURLCopyFragment (url->_baseURL, charactersToLeaveEscaped); return NULL; } return CFStringCreateWithSubstring (CFGetAllocator(url), url->_urlString, range); } CFStringRef CFURLCopyHostName (CFURLRef url) { CFRange range = url->_ranges[kCFURLComponentHost - 1]; if (range.location == kCFNotFound) { if (url->_baseURL) return CFURLCopyHostName (url->_baseURL); return NULL; } return CFStringCreateWithSubstring (CFGetAllocator(url), url->_urlString, range); } CFStringRef CFURLCopyLastPathComponent (CFURLRef url) { return NULL; /* FIXME */ } CFStringRef CFURLCopyNetLocation (CFURLRef url) { CFRange range = url->_ranges[kCFURLComponentNetLocation - 1]; if (range.location == kCFNotFound) { if (url->_baseURL) return CFURLCopyNetLocation (url->_baseURL); return NULL; } return CFStringCreateWithSubstring (CFGetAllocator(url), url->_urlString, range); } CFStringRef CFURLCopyParameterString (CFURLRef url, CFStringRef charactersToLeaveEscaped) { CFRange range = url->_ranges[kCFURLComponentParameterString - 1]; if (range.location == kCFNotFound) return NULL; return CFStringCreateWithSubstring (CFGetAllocator(url), url->_urlString, range); } CFStringRef CFURLCopyPassword (CFURLRef url) { CFRange range = url->_ranges[kCFURLComponentPassword - 1]; if (range.location == kCFNotFound) { if (url->_baseURL) return CFURLCopyPassword (url->_baseURL); return NULL; } return CFStringCreateWithSubstring (CFGetAllocator(url), url->_urlString, range); } CFStringRef CFURLCopyPath (CFURLRef url) { CFRange range = url->_ranges[kCFURLComponentPath - 1]; if (range.location == kCFNotFound) { if (url->_baseURL) return CFURLCopyPath (url->_baseURL); return NULL; } return CFStringCreateWithSubstring (CFGetAllocator(url), url->_urlString, range); } CFStringRef CFURLCopyPathExtension (CFURLRef url) { return NULL; /* FIXME */ } CFStringRef CFURLCopyQueryString (CFURLRef url, CFStringRef charactersToLeaveEscaped) { CFRange range = url->_ranges[kCFURLComponentQuery - 1]; if (range.location == kCFNotFound) { if (url->_baseURL) return CFURLCopyQueryString (url->_baseURL, charactersToLeaveEscaped); return NULL; } return CFStringCreateWithSubstring (CFGetAllocator(url), url->_urlString, range); } CFStringRef CFURLCopyResourceSpecifier (CFURLRef url) { CFRange range = url->_ranges[kCFURLComponentResourceSpecifier - 1]; if (range.location == kCFNotFound) return NULL; return CFStringCreateWithSubstring (CFGetAllocator(url), url->_urlString, range); } CFStringRef CFURLCopyScheme (CFURLRef url) { CFRange range = url->_ranges[kCFURLComponentScheme - 1]; if (range.location == kCFNotFound) { if (url->_baseURL) return CFURLCopyScheme (url->_baseURL); return NULL; } return CFStringCreateWithSubstring (CFGetAllocator(url), url->_urlString, range); } CFStringRef CFURLCopyStrictPath (CFURLRef url, Boolean *isAbsolute) { CFStringRef path; Boolean abs = false; path = CFURLCopyPath(url); if (path) { if (CFStringGetCharacterAtIndex(path, 0) == '/') { CFStringRef tmp; abs = true; tmp = CFStringCreateWithSubstring (CFGetAllocator(url), path, CFRangeMake (1, CFStringGetLength(path) - 1)); CFRelease (path); path = tmp; } } if (isAbsolute) *isAbsolute = abs; return path; } CFStringRef CFURLCopyUserName (CFURLRef url) { CFRange range = url->_ranges[kCFURLComponentUser - 1]; if (range.location == kCFNotFound) { if (url->_baseURL) return CFURLCopyUserName (url->_baseURL); return NULL; } return CFStringCreateWithSubstring (CFGetAllocator(url), url->_urlString, range); } SInt32 CFURLGetPortNumber (CFURLRef url) { CFStringRef str; CFRange range; SInt32 intValue; range = url->_ranges[kCFURLComponentPort - 1]; if (range.location == kCFNotFound) { if (url->_baseURL) return CFURLGetPortNumber (url->_baseURL); return -1; } str = CFStringCreateWithSubstring (CFGetAllocator(url), url->_urlString, range); intValue = CFStringGetIntValue (str); CFRelease (str); return intValue; } Boolean CFURLHasDirectoryPath (CFURLRef url) { CFStringRef str = CFURLGetString (url); return (CFStringGetCharacterAtIndex(str, CFStringGetLength(str) - 1) == '/'); } CFDataRef CFURLCreateData (CFAllocatorRef alloc, CFURLRef url, CFStringEncoding encoding, Boolean escapeWhiteSpace) { CFDataRef ret; CFURLRef abs; CFStringRef absStr; abs = CFURLCopyAbsoluteURL (url); absStr = CFURLGetString (abs); if (escapeWhiteSpace) absStr = CFURLCreateStringByAddingPercentEscapes (alloc, absStr, NULL, CFSTR(" \r\n\t"), encoding); ret = CFStringCreateExternalRepresentation (alloc, absStr, encoding, 0); if (escapeWhiteSpace) CFRelease (absStr); CFRelease (abs); return ret; } /* This is the maximum number of UTF-8 bytes needed to represent everything * possible Unicode character */ #define MAX_BYTES 4 static Boolean CFURLAppendPercentEscapedForCharacter (char **dst, UniChar c, CFStringEncoding enc) { CFIndex len; UInt8 buffer[MAX_BYTES]; UInt8 *target; const UInt8 *end; const UniChar *source; target = buffer; end = buffer + MAX_BYTES; source = &c; len = GSUnicodeToEncoding (&target, end, enc, &source, source + 1, 0, 0); if (len > 0) { UInt8 hi; UInt8 lo; target = buffer; end = target + len; do { (*(*dst)++) = '%'; hi = ((*target >> 4) & 0x0F); lo = (*target & 0x0F); (*(*dst)++) = (hi > 9) ? hi + 'A' - 10 : hi + '0'; (*(*dst)++) = (lo > 9) ? lo + 'A' - 10 : lo + '0'; ++target; } while (target < end); return true; } return false; } static Boolean CFURLStringContainsCharacter (CFStringRef toEscape, UniChar ch) { CFStringInlineBuffer iBuffer; CFIndex sLength; CFIndex i; UniChar c; sLength = CFStringGetLength (toEscape); CFStringInitInlineBuffer (toEscape, &iBuffer, CFRangeMake (0, sLength)); for (i = 0 ; i < sLength ; ++i) { c = CFStringGetCharacterFromInlineBuffer (&iBuffer, i); if (c == ch) return true; } return false; } CF_INLINE Boolean CFURLShouldEscapeCharacter (UniChar c, CFStringRef leaveUnescaped, CFStringRef toEscape) { if (URL_IS_UNRESERVED(c) || URL_IS_RESERVED(c)) { if (toEscape && CFURLStringContainsCharacter(toEscape, c)) return true; return false; } if (leaveUnescaped && CFURLStringContainsCharacter(leaveUnescaped, c)) return false; return true; } CFStringRef CFURLCreateStringByAddingPercentEscapes (CFAllocatorRef alloc, CFStringRef origString, CFStringRef leaveUnescaped, CFStringRef toEscape, CFStringEncoding encoding) { CFStringInlineBuffer iBuffer; CFStringRef ret; CFIndex sLength; CFIndex idx; char *dst; char *dpos; UniChar c; sLength = CFStringGetLength (origString); CFStringInitInlineBuffer (origString, &iBuffer, CFRangeMake (0, sLength)); dst = NULL; dpos = dst; for (idx = 0 ; idx < sLength ; ++idx) { c = CFStringGetCharacterFromInlineBuffer (&iBuffer, idx); if (CFURLShouldEscapeCharacter(c, leaveUnescaped, toEscape)) { if (dst == NULL) { dst = CFAllocatorAllocate (alloc, sizeof(char) * sLength * 3, 0); CFStringGetBytes (origString, CFRangeMake(0, idx), kCFStringEncodingASCII, 0, false, (UInt8*)dst, sLength * 3, NULL); dpos = dst + idx; } if (!CFURLAppendPercentEscapedForCharacter (&dpos, c, encoding)) { CFAllocatorDeallocate (alloc, dst); return NULL; } } else if (dst != NULL) { (*dpos++) = (char)c; } } if (dst) { ret = CFStringCreateWithBytes (alloc, (UInt8*)dst, (CFIndex)(dpos - dst), kCFStringEncodingASCII, false); CFAllocatorDeallocate (alloc, dst); } else { ret = CFRetain (origString); } return ret; } CFStringRef CFURLCreateStringByReplacingPercentEscapes (CFAllocatorRef alloc, CFStringRef origString, CFStringRef leaveEscaped) { return CFURLCreateStringByReplacingPercentEscapesUsingEncoding (alloc, origString, leaveEscaped, kCFStringEncodingUTF8); } CFStringRef CFURLCreateStringByReplacingPercentEscapesUsingEncoding (CFAllocatorRef alloc, CFStringRef origString, CFStringRef leaveEscaped, CFStringEncoding encoding) { CFIndex origLen; CFRange origRange; CFRange escapeRange; Boolean success; CFMutableStringRef retString; if (leaveEscaped == NULL) /* Leave all escaped */ return CFStringCreateCopy (alloc, origString); origLen = CFStringGetLength (origString); origRange = CFRangeMake (0, origLen); success = true; retString = NULL; while (success && CFStringFindWithOptions (origString, CFSTR ("%"), origRange, 0, &escapeRange)) { CFIndex subLen; CFIndex i; UniChar ch; UInt8 buffer[BUFFER_SIZE]; UInt8 *current; UInt8 *limit; CFStringRef unescapedString; if (retString == NULL) { retString = CFStringCreateMutable (alloc, origLen); if (retString == NULL) { success = false; break; } } subLen = escapeRange.location - origRange.location; while (subLen > 0) { CFIndex len; CFRange range; UniChar b[BUFFER_SIZE]; len = subLen > BUFFER_SIZE ? BUFFER_SIZE : subLen; range = CFRangeMake (origRange.location, len); CFStringGetCharacters (origString, range, b); CFStringAppendCharacters (retString, b, len); subLen -= BUFFER_SIZE; } /* FIXME: The code currently does not support escaped string longer than BUFFER_SIZE continuously. This is obviously a problem. */ i = escapeRange.location; current = buffer; limit = buffer + BUFFER_SIZE; do { ch = CFStringGetCharacterAtIndex (origString, ++i); if (ch >= '0' && ch <= '9') { *current = ch - '0'; } else if ((ch | 0x20) >= 'a' && (ch | 0x20) <= 'z') { *current = 10 + ((ch | 0x20) - 'a'); } else { success = false; break; } *current <<= 4; ch = CFStringGetCharacterAtIndex (origString, ++i); if (ch >= '0' && ch <= '9') { *current |= ch - '0'; } else if ((ch | 0x20) >= 'a' && (ch | 0x20) <= 'z') { *current |= 10 + ((ch | 0x20) - 'a'); } else { success = false; break; } ++current; ch = CFStringGetCharacterAtIndex (origString, ++i); } while (current < limit && ch == '%'); if (success == false) break; unescapedString = CFStringCreateWithBytes (kCFAllocatorSystemDefault, (const UInt8 *) buffer, current - buffer, encoding, false); if (unescapedString == NULL) { success = false; break; } CFStringAppend (retString, unescapedString); CFRelease (unescapedString); origRange.location = i; origRange.length = origLen - i; } /* FIXME: Use leaveUnescaped */ if (success == false) { if (retString) CFRelease (retString); return NULL; } else if (retString) { /* Need to append the rest of the string. */ CFIndex subLen; subLen = origRange.length; while (subLen > 0) { CFIndex len; CFRange range; UniChar b[BUFFER_SIZE]; len = subLen > BUFFER_SIZE ? BUFFER_SIZE : subLen; range = CFRangeMake (origRange.location, len); CFStringGetCharacters (origString, range, b); CFStringAppendCharacters (retString, b, len); subLen -= BUFFER_SIZE; } } return retString ? retString : CFStringCreateCopy (alloc, origString); } CFStringRef CFURLGetString (CFURLRef url) { CF_OBJC_FUNCDISPATCHV(_kCFURLTypeID, CFStringRef, url, "relativeString"); return url->_urlString; } CFURLRef CFURLGetBaseURL (CFURLRef url) { CF_OBJC_FUNCDISPATCHV(_kCFURLTypeID, CFURLRef, url, "baseURL"); return url->_baseURL; } Boolean CFURLGetFileSystemRepresentation (CFURLRef url, Boolean resolveAgainstBase, UInt8 *buffer, CFIndex bufLen) { CFStringRef str; CFStringRef unescaped; CFStringEncoding enc; Boolean ret; if (CF_IS_OBJC(_kCFURLTypeID, url)) enc = kCFStringEncodingUTF8; else enc = url->_encoding; if (resolveAgainstBase) url = CFURLCopyAbsoluteURL (url); str = CFURLCopyFileSystemPath (url, CFURL_DEFAULT_PATH_STYLE); if (resolveAgainstBase) CFRelease (url); unescaped = CFURLCreateStringByReplacingPercentEscapesUsingEncoding (NULL, str, CFSTR(""), enc); CFRelease (str); ret = CFStringGetFileSystemRepresentation (unescaped, (char*)buffer, bufLen); CFRelease (unescaped); return ret; } CFIndex CFURLGetBytes (CFURLRef url, UInt8 *buffer, CFIndex bufLen) { CFIndex used; CFIndex length; CFIndex converted; CFStringRef str; CFStringEncoding enc; if (CF_IS_OBJC(_kCFURLTypeID, url)) enc = kCFStringEncodingUTF8; else enc = url->_encoding; str = CFURLGetString (url); length = CFStringGetLength (str); converted = CFStringGetBytes (str, CFRangeMake(0, length), enc, 0, false, buffer, bufLen, &used); if (converted != used) used = -1; return used; } CFRange CFURLGetByteRangeForComponent (CFURLRef url, CFURLComponentType comp, CFRange *rangeIncludingSeparators) { return CFRangeMake (kCFNotFound, 0); /* FIXME */ } Boolean CFURLResourceIsReachable (CFURLRef url, CFErrorRef *error) { return false; } void CFURLClearResourcePropertyCache (CFURLRef url) { } void CFURLClearResourcePropertyCacheForKey (CFURLRef url, CFStringRef key) { } CFDictionaryRef CFURLCopyResourcePropertiesForKeys (CFURLRef url, CFArrayRef keys, CFErrorRef *error) { return NULL; } Boolean CFURLCopyResourcePropertyForKey (CFURLRef url, CFStringRef key, void *propertyValueTypeRefPtr, CFErrorRef *error) { return false; } CFDictionaryRef CFURLCreateResourcePropertiesForKeysFromBookmarkData (CFAllocatorRef alloc, CFArrayRef resourcePropertiesToReturn, CFDataRef bookmark) { return NULL; /* FIXME */ } CFTypeRef CFURLCreateResourcePropertyForKeyFromBookmarkData (CFAllocatorRef alloc, CFStringRef resourcePropertyKey, CFDataRef bookmark) { return NULL; /* FIXME */ } Boolean CFURLSetResourcePropertiesForKeys (CFURLRef url, CFDictionaryRef keyedPropertyValues, CFErrorRef *error) { return false; } Boolean CFURLSetResourcePropertyForKey (CFURLRef url, CFStringRef key, CFTypeRef propertValue, CFErrorRef *error) { return false; } void CFURLSetTemporaryResourcePropertyForKey (CFURLRef url, CFStringRef key, CFTypeRef propertyValue) { } CFURLRef CFURLCreateByResolvingBookmarkData (CFAllocatorRef alloc, CFDataRef bookmark, CFURLBookmarkResolutionOptions options, CFURLRef relativeToURL, CFArrayRef resourcePropertiesToInclude, Boolean *isStale, CFErrorRef *error) { return NULL; /* FIXME */ } CFDataRef CFURLCreateBookmarkData (CFAllocatorRef alloc, CFURLRef url, CFURLBookmarkCreationOptions options, CFArrayRef resourcePropertiesToInclude, CFURLRef relativeToURL, CFErrorRef *error) { return NULL; /* FIXME */ } CFDataRef CFURLCreateBookmarkDataFromAliasRecord (CFAllocatorRef alloc, CFDataRef aliasRecordDataRef) { return NULL; /* FIXME */ } CFDataRef CFURLCreateBookmarkDataFromFile (CFAllocatorRef alloc, CFURLRef fileURL, CFErrorRef *errorRef) { return NULL; /* FIXME */ } Boolean CFURLWriteBookmarkDataToFile (CFDataRef bookmarkRef, CFURLRef fileURL, CFURLBookmarkFileCreationOptions options, CFErrorRef *errorRef) { return false; /* FIXME */ } gnustep-corebase-0.2/Source/GSUnicode.c0000664000175000017500000020104414661604117017140 0ustar yavoryavor/* GSUnicode.c Copyright (C) 2013 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: July, 2013 This file is part of GNUstep CoreBase library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "CoreFoundation/CFByteOrder.h" #include "CoreFoundation/CFDictionary.h" #include "CoreFoundation/CFLocale.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/GSCharacter.h" #include "CoreFoundation/GSUnicode.h" #include "GSPrivate.h" #include "GSMemory.h" #if defined(HAVE_UNICODE_UCNV_H) #include #endif #if defined(HAVE_ICU_H) #include #endif #define BUFFER_SIZE 512 static CFIndex GSUnicodeFromNonLossyASCII (const char *s, CFIndex slen, UniChar lossChar, UniChar * d, CFIndex dlen, CFIndex * usedLen) { const char *sstart; const char *slimit; UniChar *dstart; UniChar *dlimit; sstart = s; slimit = sstart + slen; if (d == NULL) dlen = 0; dstart = d; dlimit = dstart + dlen; while (s < slimit && (dlen == 0 || d < dlimit)) { UniChar c; c = *s; if (c < 0x80 && c != '\\') { if (dlen != 0) *d = *s; d++; s++; } else if (c == '\\') { CFIndex convCount; c = s[1]; if (c == '\\') { convCount = 2; } else if (CHAR_IS_OCTAL (c) && CHAR_IS_OCTAL (s[2]) && CHAR_IS_OCTAL (s[3])) { c = (s[1] - '0') << 6; c |= (s[2] - '0') << 3; c |= s[3] - '0'; convCount = 4; } else if (c == 'u' && CHAR_IS_HEX (s[2]) && CHAR_IS_HEX (s[3]) && CHAR_IS_HEX (s[4]) && CHAR_IS_HEX (s[5])) { /* The first part of this equation gives us a value between 0 and 9, the second part adds 9 to that if the char is alphabetic. */ c = ((s[5] & 0xF) + (s[5] >> 6) * 9) & 0x000F; c |= ((s[4] & 0xF) + (s[4] >> 6) * 9) << 4; c |= ((s[3] & 0xF) + (s[3] >> 6) * 9) << 8; c |= ((s[2] & 0xF) + (s[2] >> 6) * 9) << 12; convCount = 6; } else { break; } if (dlen != 0) *d = c; d++; s += convCount; } else { break; } } if (usedLen) *usedLen = d - dstart; return s - sstart; } static const char *base16 = "0123456789ABCDEF"; static CFIndex GSUnicodeToNonLossyASCII (const UniChar * s, CFIndex slen, UniChar lossChar, char *d, CFIndex dlen, CFIndex * usedLen) { const UniChar *sstart; const UniChar *slimit; char *dstart; char *dlimit; sstart = s; slimit = sstart + slen; if (d == NULL) dlen = 0; dstart = d; dlimit = dstart + dlen; while (s < slimit && (dlen == 0 || d < dlimit)) { UniChar c; c = *s; if (c < 0x80 && c != '\\') { if (dlen != 0) *d = c; d++; s++; } else { char conv[6]; CFIndex convCount; conv[0] = '\\'; if (c == '\\') { conv[1] = '\\'; convCount = 2; } else if (c <= 0x00FF) { conv[3] = (c & 0x7) + '0'; conv[2] = ((c >> 3) & 0x7) + '0'; conv[1] = ((c >> 6) & 0x7) + '0'; convCount = 4; } else { conv[5] = base16[(c & 0xF)]; conv[4] = base16[((c >> 4) & 0xF)]; conv[3] = base16[((c >> 8) & 0xF)]; conv[2] = base16[((c >> 12) & 0xF)]; conv[1] = 'u'; convCount = 6; } if (dlen != 0 && convCount < dlimit - d) { CFIndex i; for (i = 0; i < convCount; ++i) d[i] = conv[i]; } d += convCount; } } if (usedLen) *usedLen = d - dstart; return s - sstart; } CFIndex GSUnicodeFromEncoding (UniChar ** d, const UniChar * const dLimit, CFStringEncoding enc, const UInt8 ** s, const UInt8 * const sLimit, const UniChar loss) { UniChar *dStart; UniChar *dWorking; dStart = d ? *d : NULL; dWorking = dStart; if (enc == kCFStringEncodingUTF8) { UTF32Char c; CFIndex add; GSUTF8CharacterSkipByteOrderMark (s, sLimit); while (*s < sLimit) { add = GSUTF8CharacterGet (*s, sLimit, &c); /* RFC 3629 (https://tools.ietf.org/html/rfc3629) specifically prohibits encoding surrogates in UTF-8. */ if (add == 0 || GSCharacterIsSurrogate (c) || c > 0x10FFFF) { if (loss) c = loss; else break; add = 1; } *s += add; dWorking += GSUTF16CharacterAppend (dWorking, dLimit, c); } } else if (enc == kCFStringEncodingUTF16 || enc == kCFStringEncodingUTF16BE || enc == kCFStringEncodingUTF16LE) { const UTF16Char *sWorking; Boolean swap; UTF32Char c; sWorking = (const UTF16Char *) *s; swap = false; if (enc == kCFStringEncodingUTF16) { c = *sWorking; if (c == kGSUTF16CharacterByteOrderMark || c == kGSUTF16CharacterSwappedByteOrderMark) sWorking++; if (c == kGSUTF16CharacterSwappedByteOrderMark) swap = true; } #if __BIG_ENDIAN__ if (enc == kCFStringEncodingUTF16LE) swap = true; #else if (enc == kCFStringEncodingUTF16BE) swap = true; #endif /* This is not the most efficient way to check for invalid character in a UTF-16 string and copy it over to the destination buffer, but it'll do for now. */ if (swap) { while (sWorking < (const UTF16Char *) sLimit) { /* We have to mimic GSUTF16CharacterGet () here but swap the endianness while we're at it. */ c = CFSwapInt16 (*sWorking++); if (GSCharacterIsSurrogate (c)) { if (GSCharacterIsLeadSurrogate (c) && sWorking < (const UTF16Char *) sLimit && GSCharacterIsTrailSurrogate (*sWorking)) { c = (c << 10) + CFSwapInt16 (*sWorking++) - ((0xD7C0 << 10) + 0xDC00); } else if (loss) { c = loss; } else { --sWorking; break; } } dWorking += GSUTF16CharacterAppend (dWorking, dLimit, c); } } else { CFIndex add; while (sWorking < (const UTF16Char *) sLimit) { add = GSUTF16CharacterGet (sWorking, (const UTF16Char *) sLimit, &c); if (add == 0) { if (loss) c = loss; else break; add = 1; } sWorking += add; dWorking += GSUTF16CharacterAppend (dWorking, dLimit, c); } } *s = (const UInt8 *) sWorking; } else if (enc == kCFStringEncodingUTF32 || enc == kCFStringEncodingUTF32BE || enc == kCFStringEncodingUTF32LE) { const UTF32Char *sWorking; Boolean swap; UTF32Char c; sWorking = (const UTF32Char *) *s; swap = false; if (enc == kCFStringEncodingUTF32) { c = *sWorking; if (c == kGSUTF32CharacterByteOrderMark || c == kGSUTF32CharacterSwappedByteOrderMark) sWorking++; if (c == kGSUTF32CharacterSwappedByteOrderMark) swap = true; } #if __BIG_ENDIAN__ if (enc == kCFStringEncodingUTF32LE) swap = true; #else if (enc == kCFStringEncodingUTF32BE) swap = true; #endif if (swap) { while (sWorking < (const UTF32Char *) sLimit) { c = CFSwapInt32 (*sWorking); if (GSCharacterIsSurrogate (c) || c > 0x10FFFF) c = loss; else break; ++sWorking; dWorking += GSUTF16CharacterAppend (dWorking, dLimit, c); } } else { while (sWorking < (const UTF32Char *) sLimit) { c = *sWorking; if ((GSCharacterIsSurrogate (c) || c > 0x10FFFF) && loss) c = loss; else break; ++sWorking; dWorking += GSUTF16CharacterAppend (dWorking, dLimit, c); } } *s = (const UInt8 *) sWorking; } else if (enc == kCFStringEncodingASCII || enc == kCFStringEncodingISOLatin1) { const UInt8 *sWorking; UInt8 c; sWorking = *s; while (sWorking < sLimit) { c = *sWorking++; if (dWorking < dLimit) *dWorking = c; ++dWorking; } *s = sWorking; } else if (enc == kCFStringEncodingNonLossyASCII) { /* FIXME */ } else { /* FIXME */ } *d = (dWorking > dLimit) ? (UniChar *) dLimit : dWorking; /* Return -1 if we were not to process the whole source buffer. */ return *s < sLimit ? -1 : dWorking - dStart; } CFIndex GSUnicodeToEncoding (UInt8 ** d, const UInt8 * const dLimit, CFStringEncoding enc, const UniChar ** s, const UniChar * const sLimit, const char loss, Boolean addBOM) { UInt8 *dStart; UInt8 *dStop; dStart = d ? *d : NULL; dStop = dStart; if (enc == kCFStringEncodingUTF8) { UTF32Char c; CFIndex add; if (addBOM) dStop += GSUTF8CharacterAppendByteOrderMark (dStop, dLimit); while (*s < sLimit && (dLimit == NULL || dStop < dLimit)) { add = GSUTF16CharacterGet (*s, sLimit, &c); if (add == 0) { if (loss) c = loss; else break; add = 1; } *s += add; dStop += GSUTF8CharacterAppend (dStop, dLimit, c); } } else if (enc == kCFStringEncodingUTF16 || enc == kCFStringEncodingUTF16BE || enc == kCFStringEncodingUTF16LE) { UTF16Char *dWorking; CFIndex dLen; CFIndex sLen; CFIndex bytesToCopy; dWorking = (UTF16Char *) dStart; if (addBOM && dWorking < (UTF16Char *) dLimit) { if (dLimit != NULL) *dWorking = kGSUTF16CharacterByteOrderMark; ++dWorking; } dLen = dLimit - (const UInt8*) dWorking; sLen = sLimit - *s; bytesToCopy = dLen > sLen ? sLen : dLen; GSMemoryCopy (dWorking, *s, bytesToCopy); #if __BIG_ENDIAN__ if (enc == kCFStringEncodingUTF32LE) #else if (enc == kCFStringEncodingUTF32BE) #endif { dWorking = (UTF16Char *) dStart; while (dWorking < (UTF16Char *) dLimit) { *dWorking = CFSwapInt16 (*dWorking); ++dWorking; } dStop = (UInt8 *) dWorking; } else { dStop += bytesToCopy; } *s += bytesToCopy / sizeof (UniChar); } else if (enc == kCFStringEncodingUTF32 || enc == kCFStringEncodingUTF32BE || enc == kCFStringEncodingUTF32LE) { UTF32Char *dWorking; UTF32Char c; CFIndex add; dWorking = (UTF32Char *) dStart; if (addBOM && dWorking < (UTF32Char *) dLimit) { if (dLimit != NULL) *dWorking = kGSUTF32CharacterByteOrderMark; ++dWorking; } while (*s < sLimit && (dLimit == NULL || dWorking < (UTF32Char *) dLimit)) { add = GSUTF16CharacterGet (*s, sLimit, &c); if (add == 0) { if (loss) c = loss; else break; } *s += add; if (dWorking < (UTF32Char *) dLimit) *dWorking = c; ++dWorking; } #if __BIG_ENDIAN__ if (enc == kCFStringEncodingUTF32LE) #else if (enc == kCFStringEncodingUTF32BE) #endif { dWorking = (UTF32Char *) dStart; while (dWorking < (UTF32Char *) dLimit) { *dWorking = CFSwapInt32 (*dWorking); ++dWorking; } } dStop = (UInt8 *) dWorking; } else if (enc == kCFStringEncodingASCII) { UInt8 *dWorking; const UniChar *sWorking; UniChar c; dWorking = dStart; sWorking = *s; while (sWorking < sLimit && (dLimit == NULL || dWorking < dLimit)) { c = *sWorking++; if (c > 0x7F) c = loss; if (dWorking < dLimit) *dWorking = c; ++dWorking; } dStop = dWorking; *s = sWorking; } else if (enc == kCFStringEncodingISOLatin1) { UInt8 *dWorking; const UniChar *sWorking; UniChar c; dWorking = dStart; sWorking = *s; while (sWorking < sLimit && (dLimit == NULL || dWorking < dLimit)) { c = *sWorking++; if (c > 0xFF) c = loss; if (dWorking < dLimit) *dWorking = c; ++dWorking; } dStop = dWorking; *s = sWorking; } else if (enc == kCFStringEncodingNonLossyASCII) { } else { /* FIXME */ } *d = dStop; return dLimit == NULL && *s < sLimit ? -1 : dStop - dStart; } typedef union format_argument { int intValue; long int lintValue; long long int llintValue; double dblValue; #if SIZEOF_LONG_DOUBLE > SIZEOF_DOUBLE long double ldblValue; #endif void *ptrValue; } format_argument_t; #define FMT_MOD_INT 0 enum { FMT_UNKNOWN = 0, FMT_SPACE, /* ' ' */ FMT_HASH, /* '#' */ FMT_QUOTE, /* '\'' */ FMT_PLUS, /* '+' */ FMT_MINUS, /* '-' */ FMT_ZERO, /* '0' */ FMT_NUMBER, /* '1' ... '9' */ FMT_POSITION, /* '$' */ FMT_WIDTH_AST, /* '*' */ FMT_PRECISION, /* '.' */ FMT_MOD_CHAR, /* 'hh' NOTE: Note in fmt_table[] */ FMT_MOD_SHORT, /* 'h' */ FMT_MOD_LONG, /* 'l' */ FMT_MOD_LONGLONG, /* 'll' NOTE: Not in fmt_table[] */ FMT_MOD_SIZE, /* 'z' */ FMT_MOD_PTRDIFF, /* 't' */ FMT_MOD_INTMAX, /* 'j' */ FMT_MOD_LDBL, /* 'L' */ FMT_PERCENT, /* '%' */ FMT_OBJECT, /* '@' */ FMT_POINTER, /* 'p' */ FMT_INTEGER, /* 'd', 'D' or 'i' */ FMT_OCTAL, /* 'o' or 'O' */ FMT_HEX, /* 'x' or 'X' */ FMT_UINTEGER, /* 'u' */ FMT_DOUBLE, /* 'a', 'A', 'e', 'E', 'f', 'F', 'g' or 'G' */ FMT_LONG_DOUBLE, /* any of above with 'L' modifier */ FMT_GETCOUNT, /* 'n' */ FMT_CHARACTER, /* 'c' or 'C' */ FMT_STRING /* 's' or 'S' */ }; static const UInt8 fmt_table[] = { /* 0x20 */ FMT_SPACE, FMT_UNKNOWN, FMT_UNKNOWN, FMT_HASH, FMT_POSITION, FMT_PERCENT, FMT_UNKNOWN, FMT_QUOTE, FMT_UNKNOWN, FMT_UNKNOWN, FMT_WIDTH_AST, FMT_PLUS, FMT_UNKNOWN, FMT_MINUS, FMT_PRECISION, FMT_UNKNOWN, /* 0x30 */ FMT_ZERO, FMT_NUMBER, FMT_NUMBER, FMT_NUMBER, FMT_NUMBER, FMT_NUMBER, FMT_NUMBER, FMT_NUMBER, FMT_NUMBER, FMT_NUMBER, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, /* 0x40 */ FMT_OBJECT, FMT_DOUBLE, FMT_UNKNOWN, FMT_CHARACTER, FMT_INTEGER, FMT_DOUBLE, FMT_DOUBLE, FMT_DOUBLE, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, FMT_MOD_LDBL, FMT_UNKNOWN, FMT_UNKNOWN, FMT_OCTAL, /* 0x50 */ FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, FMT_STRING, FMT_UNKNOWN, FMT_UINTEGER, FMT_UNKNOWN, FMT_UNKNOWN, FMT_HEX, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, /* 0x60 */ FMT_UNKNOWN, FMT_DOUBLE, FMT_UNKNOWN, FMT_CHARACTER, FMT_INTEGER, FMT_DOUBLE, FMT_DOUBLE, FMT_DOUBLE, FMT_MOD_SHORT, FMT_INTEGER, FMT_MOD_INTMAX, FMT_UNKNOWN, FMT_MOD_LONG, FMT_UNKNOWN, FMT_GETCOUNT, FMT_OCTAL, /* 0x70 */ FMT_POINTER, FMT_UNKNOWN, FMT_UNKNOWN, FMT_STRING, FMT_MOD_PTRDIFF, FMT_UINTEGER, FMT_UNKNOWN, FMT_UNKNOWN, FMT_HEX, FMT_UNKNOWN, FMT_MOD_SIZE, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN, FMT_UNKNOWN }; /* Step 0: At the beginning of the spec */ #define STEP_0_JUMP do \ { \ type = (fmt < fmtlimit) ? *fmt++ : 0; \ switch ((type >= 0x20 && type <= 0x7A) ? fmt_table[type - 0x20] : 0) \ { \ case FMT_UNKNOWN: goto handle_error; \ case FMT_SPACE: goto flag_space_prefix; \ case FMT_HASH: goto flag_alternate; \ case FMT_QUOTE: goto flag_grouping; \ case FMT_PLUS: goto flag_show_sign; \ case FMT_MINUS: goto flag_left_align; \ case FMT_ZERO: goto flag_pad_zeros; \ case FMT_NUMBER: goto width_number; \ case FMT_POSITION: goto get_position; \ case FMT_WIDTH_AST: goto width_asterisk; \ case FMT_PRECISION: goto precision; \ case FMT_MOD_SHORT: goto mod_short; \ case FMT_MOD_LONG: goto mod_long; \ case FMT_MOD_SIZE: goto mod_size_t; \ case FMT_MOD_PTRDIFF: goto mod_ptrdiff_t; \ case FMT_MOD_INTMAX: goto mod_intmax_t; \ case FMT_MOD_LDBL: goto mod_ldbl; \ case FMT_PERCENT: goto fmt_percent; \ case FMT_OBJECT: goto fmt_object; \ case FMT_POINTER: goto fmt_pointer; \ case FMT_INTEGER: goto fmt_decimal; \ case FMT_OCTAL: goto fmt_octal; \ case FMT_HEX: goto fmt_hex; \ case FMT_UINTEGER: goto fmt_unsigned_decimal; \ case FMT_GETCOUNT: goto fmt_getcount; \ case FMT_DOUBLE: goto fmt_double; \ case FMT_CHARACTER: goto fmt_character; \ case FMT_STRING: goto fmt_string; \ } \ } while (0) /* Step 1: After reading flags and/or width */ #define STEP_1_JUMP do \ { \ type = (fmt < fmtlimit) ? *fmt++ : 0; \ switch ((type >= 0x20 && type <= 0x7A) ? fmt_table[type - 0x20] : 0) \ { \ case FMT_UNKNOWN: goto handle_error; \ case FMT_SPACE: goto handle_error; \ case FMT_HASH: goto handle_error; \ case FMT_QUOTE: goto handle_error; \ case FMT_PLUS: goto handle_error; \ case FMT_MINUS: goto handle_error; \ case FMT_ZERO: goto handle_error; \ case FMT_NUMBER: goto handle_error; \ case FMT_POSITION: goto get_position; \ case FMT_WIDTH_AST: goto handle_error; \ case FMT_PRECISION: goto precision; \ case FMT_MOD_SHORT: goto mod_short; \ case FMT_MOD_LONG: goto mod_long; \ case FMT_MOD_SIZE: goto mod_size_t; \ case FMT_MOD_PTRDIFF: goto mod_ptrdiff_t; \ case FMT_MOD_INTMAX: goto mod_intmax_t; \ case FMT_MOD_LDBL: goto mod_ldbl; \ case FMT_PERCENT: goto fmt_percent; \ case FMT_OBJECT: goto fmt_object; \ case FMT_POINTER: goto fmt_pointer; \ case FMT_INTEGER: goto fmt_decimal; \ case FMT_OCTAL: goto fmt_octal; \ case FMT_HEX: goto fmt_hex; \ case FMT_UINTEGER: goto fmt_unsigned_decimal; \ case FMT_GETCOUNT: goto fmt_getcount; \ case FMT_DOUBLE: goto fmt_double; \ case FMT_CHARACTER: goto fmt_character; \ case FMT_STRING: goto fmt_string; \ } \ } while (0) /* Step 2: After processing precision */ #define STEP_2_JUMP do \ { \ type = (fmt < fmtlimit) ? *fmt++ : 0; \ switch ((type >= 0x20 && type <= 0x7A) ? fmt_table[type - 0x20] : 0) \ { \ case FMT_UNKNOWN: goto handle_error; \ case FMT_SPACE: goto handle_error; \ case FMT_HASH: goto handle_error; \ case FMT_QUOTE: goto handle_error; \ case FMT_PLUS: goto handle_error; \ case FMT_MINUS: goto handle_error; \ case FMT_ZERO: goto handle_error; \ case FMT_NUMBER: goto handle_error; \ case FMT_POSITION: goto handle_error; \ case FMT_WIDTH_AST: goto handle_error; \ case FMT_PRECISION: goto handle_error; \ case FMT_MOD_SHORT: goto mod_short; \ case FMT_MOD_LONG: goto mod_long; \ case FMT_MOD_SIZE: goto mod_size_t; \ case FMT_MOD_PTRDIFF: goto mod_ptrdiff_t; \ case FMT_MOD_INTMAX: goto mod_intmax_t; \ case FMT_MOD_LDBL: goto mod_ldbl; \ case FMT_PERCENT: goto fmt_percent; \ case FMT_OBJECT: goto fmt_object; \ case FMT_POINTER: goto fmt_pointer; \ case FMT_INTEGER: goto fmt_decimal; \ case FMT_OCTAL: goto fmt_octal; \ case FMT_HEX: goto fmt_hex; \ case FMT_UINTEGER: goto fmt_unsigned_decimal; \ case FMT_GETCOUNT: goto fmt_getcount; \ case FMT_DOUBLE: goto fmt_double; \ case FMT_CHARACTER: goto fmt_character; \ case FMT_STRING: goto fmt_string; \ } \ } while (0) /* Step 3L: After reading length modifier 'l' */ #define STEP_3L_JUMP do \ { \ type = (fmt < fmtlimit) ? *fmt++ : 0; \ switch ((type >= 0x20 && type <= 0x7A) ? fmt_table[type - 0x20] : 0) \ { \ case FMT_UNKNOWN: goto handle_error; \ case FMT_SPACE: goto handle_error; \ case FMT_HASH: goto handle_error; \ case FMT_QUOTE: goto handle_error; \ case FMT_PLUS: goto handle_error; \ case FMT_MINUS: goto handle_error; \ case FMT_ZERO: goto handle_error; \ case FMT_NUMBER: goto handle_error; \ case FMT_POSITION: goto handle_error; \ case FMT_WIDTH_AST: goto handle_error; \ case FMT_PRECISION: goto handle_error; \ case FMT_MOD_SHORT: goto handle_error; \ case FMT_MOD_LONG: goto mod_longlong; \ case FMT_MOD_SIZE: goto handle_error; \ case FMT_MOD_PTRDIFF: goto handle_error; \ case FMT_MOD_INTMAX: goto handle_error; \ case FMT_MOD_LDBL: goto handle_error; \ case FMT_PERCENT: goto fmt_percent; \ case FMT_OBJECT: goto fmt_object; \ case FMT_POINTER: goto fmt_pointer; \ case FMT_INTEGER: goto fmt_decimal; \ case FMT_OCTAL: goto fmt_octal; \ case FMT_HEX: goto fmt_hex; \ case FMT_UINTEGER: goto fmt_unsigned_decimal; \ case FMT_GETCOUNT: goto fmt_getcount; \ case FMT_DOUBLE: goto handle_error; \ case FMT_CHARACTER: goto fmt_character; \ case FMT_STRING: goto fmt_string; \ } \ } while (0) /* Step 3H: After reading length modifier 'h' */ #define STEP_3H_JUMP do \ { \ type = (fmt < fmtlimit) ? *fmt++ : 0; \ switch ((type >= 0x20 && type <= 0x7A) ? fmt_table[type - 0x20] : 0) \ { \ case FMT_UNKNOWN: goto handle_error; \ case FMT_SPACE: goto handle_error; \ case FMT_HASH: goto handle_error; \ case FMT_QUOTE: goto handle_error; \ case FMT_PLUS: goto handle_error; \ case FMT_MINUS: goto handle_error; \ case FMT_ZERO: goto handle_error; \ case FMT_NUMBER: goto handle_error; \ case FMT_POSITION: goto handle_error; \ case FMT_WIDTH_AST: goto handle_error; \ case FMT_PRECISION: goto handle_error; \ case FMT_MOD_SHORT: goto mod_char; \ case FMT_MOD_LONG: goto handle_error; \ case FMT_MOD_SIZE: goto handle_error; \ case FMT_MOD_PTRDIFF: goto handle_error; \ case FMT_MOD_INTMAX: goto handle_error; \ case FMT_MOD_LDBL: goto handle_error; \ case FMT_PERCENT: goto fmt_percent; \ case FMT_OBJECT: goto fmt_object; \ case FMT_POINTER: goto fmt_pointer; \ case FMT_INTEGER: goto fmt_decimal; \ case FMT_OCTAL: goto fmt_octal; \ case FMT_HEX: goto fmt_hex; \ case FMT_UINTEGER: goto fmt_unsigned_decimal; \ case FMT_GETCOUNT: goto fmt_getcount; \ case FMT_DOUBLE: goto handle_error; \ case FMT_CHARACTER: goto fmt_character; \ case FMT_STRING: goto fmt_string; \ } \ } while (0) /* Step 4INT: After reading an integer conversion specifier */ #define STEP_4INT_JUMP do \ { \ type = (fmt < fmtlimit) ? *fmt++ : 0; \ switch ((type >= 0x20 && type <= 0x7A) ? fmt_table[type - 0x20] : 0) \ { \ case FMT_UNKNOWN: goto handle_error; \ case FMT_SPACE: goto handle_error; \ case FMT_HASH: goto handle_error; \ case FMT_QUOTE: goto handle_error; \ case FMT_PLUS: goto handle_error; \ case FMT_MINUS: goto handle_error; \ case FMT_ZERO: goto handle_error; \ case FMT_NUMBER: goto handle_error; \ case FMT_POSITION: goto handle_error; \ case FMT_WIDTH_AST: goto handle_error; \ case FMT_PRECISION: goto handle_error; \ case FMT_MOD_SHORT: goto handle_error; \ case FMT_MOD_LONG: goto handle_error; \ case FMT_MOD_SIZE: goto handle_error; \ case FMT_MOD_PTRDIFF: goto handle_error; \ case FMT_MOD_INTMAX: goto handle_error; \ case FMT_MOD_LDBL: goto handle_error; \ case FMT_PERCENT: goto fmt_percent; \ case FMT_OBJECT: goto fmt_object; \ case FMT_POINTER: goto fmt_pointer; \ case FMT_INTEGER: goto fmt_decimal; \ case FMT_OCTAL: goto fmt_octal; \ case FMT_HEX: goto fmt_hex; \ case FMT_UINTEGER: goto fmt_unsigned_decimal; \ case FMT_GETCOUNT: goto fmt_getcount; \ case FMT_DOUBLE: goto handle_error; \ case FMT_CHARACTER: goto fmt_character; \ case FMT_STRING: goto fmt_string; \ } \ } while (0) /* Step 4DBL: after reading a long double conversion specifier */ #define STEP_4DBL_JUMP do \ { \ type = (fmt < fmtlimit) ? *fmt++ : 0; \ switch ((type >= 0x20 && type <= 0x7A) ? fmt_table[type - 0x20] : 0) \ { \ case FMT_UNKNOWN: goto handle_error; \ case FMT_SPACE: goto handle_error; \ case FMT_HASH: goto handle_error; \ case FMT_QUOTE: goto handle_error; \ case FMT_PLUS: goto handle_error; \ case FMT_MINUS: goto handle_error; \ case FMT_ZERO: goto handle_error; \ case FMT_NUMBER: goto handle_error; \ case FMT_POSITION: goto handle_error; \ case FMT_WIDTH_AST: goto handle_error; \ case FMT_PRECISION: goto handle_error; \ case FMT_MOD_SHORT: goto handle_error; \ case FMT_MOD_LONG: goto handle_error; \ case FMT_MOD_SIZE: goto handle_error; \ case FMT_MOD_PTRDIFF: goto handle_error; \ case FMT_MOD_INTMAX: goto handle_error; \ case FMT_MOD_LDBL: goto handle_error; \ case FMT_PERCENT: goto handle_error; \ case FMT_OBJECT: goto handle_error; \ case FMT_POINTER: goto handle_error; \ case FMT_INTEGER: goto handle_error; \ case FMT_OCTAL: goto handle_error; \ case FMT_HEX: goto handle_error; \ case FMT_UINTEGER: goto handle_error; \ case FMT_GETCOUNT: goto handle_error; \ case FMT_DOUBLE: goto fmt_long_double; \ case FMT_CHARACTER: goto handle_error; \ case FMT_STRING: goto handle_error; \ } \ } while (0) CF_INLINE CFIndex _ustring_length (const UniChar * string, size_t maxlen) { size_t len; #if HOST_OS_WINDOWS if (maxlen < 0) maxlen = STRSAFE_MAX_CCH * sizeof (UniChar); return SUCCEEDED (StringCbLengthW (string, maxlen, &len)) ? len : 0; #elif (SIZEOF_WCHAR_T == SIZEOF_UNICHAR) && HAVE_WCHAR_H if (maxlen < 0) len = wcslen (string); else len = wcsnlen (string, maxlen); #else if (maxlen < 0) maxlen = INT_MAX; /* We test 64-bits at a time */ for (len = 0; maxlen != 0 && string[len] != '\0'; ++len, --maxlen) { if (--maxlen == 0 || string[++len] == '\0') break; if (--maxlen == 0 || string[++len] == '\0') break; if (--maxlen == 0 || string[++len] == '\0') break; } return len; #endif } CF_INLINE CFIndex _cstring_length (const char *string, size_t maxlen) { size_t len; #if HOST_OS_WINDOWS if (maxlen < 0) maxlen = STRSAFE_MAX_CCH * sizeof (char); return SUCCEEDED (StringCbLengthA (string, maxlen, &len)) ? len : 0; #elif HAVE_STRING_H if (maxlen < 0) len = strlen (string); else len = strnlen (string, maxlen); return len; #else if (maxlen < 0) maxlen = INT_MAX; /* We test 64-bits at a time */ for (len = 0; maxlen != 0 && string[len] != '\0'; ++len, --maxlen) { if (--maxlen == 0 || string[++len] == '\0') break; if (--maxlen == 0 || string[++len] == '\0') break; if (--maxlen == 0 || string[++len] == '\0') break; if (--maxlen == 0 || string[++len] == '\0') break; if (--maxlen == 0 || string[++len] == '\0') break; if (--maxlen == 0 || string[++len] == '\0') break; if (--maxlen == 0 || string[++len] == '\0') break; } return len; #endif } /* Returns 0 if number is not infinite. Will return 1 for positive infinity and -1 for negative infinity */ static int _dbl_is_inf (double d) { /* Infinity is defined to be: exponent = 0x7FF, mantissa = 0 */ SInt32 l; SInt32 h; SInt32 *dint; dint = (SInt32 *) & d; #if WORDS_BIGENDIAN l = dint[1]; h = dint[0]; #else l = dint[0]; h = dint[1]; #endif /* Written by J.T. Conklin . Changed to return -1 for -Inf by Ulrich Drepper . Public domain. */ l |= (h & 0x7FFFFFFF) ^ 0x7FF00000; l |= -l; return ~(l >> 31) & (h >> 30); } /* Returns 0 if number is not nan. Will return 1 for positive nan and -1 for negative nan. */ static int _dbl_is_nan (double d) { SInt32 l; SInt32 h; SInt32 *dint; dint = (SInt32 *) & d; #if WORDS_BIGENDIAN l = dint[1]; h = dint[0]; #else l = dint[0]; h = dint[1]; #endif l |= (h & 0x000FFFFF); l |= -l; l = ((h & 0x7FF00000) ^ 0x7FF00000) - ((UInt32) l >> 31); return (l >> 31) & (h >> 30); } #if SIZEOF_LONG_DOUBLE > SIZEOF_DOUBLE #if SIZEOF_LONG_DOUBLE == 12 static int _ldbl_is_inf (long double d) { SInt32 h; SInt32 m; SInt32 l; SInt32 *dint; dint = (SInt32 *) & d; #if WORDS_BIGENDIAN l = dint[2]; m = dint[1]; h = dint[0]; #else l = dint[0]; m = dint[1]; h = dint[2]; #endif l |= (m & 0x7FFFFFFF) | ((h & 0x7FFF) ^ 0x7FFF); l |= -l; return ~(l >> 31) & ((h << 16) >> 30); } static int _ldbl_is_nan (long double d) { SInt32 h; SInt32 m; SInt32 l; SInt32 *dint; dint = (SInt32 *) & d; #if WORDS_BIGENDIAN l = dint[2]; m = dint[1]; h = dint[0]; #else l = dint[0]; m = dint[1]; h = dint[2]; #endif l |= (m & 0x7FFFFFFF); l |= -l; l = ((h & 0x7FFF) ^ 0x7FFF) - ((UInt32) l >> 31); return (l >> 31) & ((h << 16) >> 30); } #elif SIZEOF_LONG_DOUBLE == 16 static int _ldbl_is_inf (long double d) { /* Infinity is defined to be: exponent = 0x7FF, mantissa = 0 */ SInt64 l; SInt64 h; SInt64 *dint; dint = (SInt64 *) & d; #if WORDS_BIGENDIAN l = dint[1]; h = dint[0]; #else l = dint[0]; h = dint[1]; #endif /* Written by J.T. Conklin . Changed to return -1 for -Inf by Ulrich Drepper . Public domain. */ l |= (h & 0x7FFFFFFFFFFFFFFF) ^ 0x7FFF000000000000; l |= -l; return ~(l >> 63) & (h >> 62); } static int _ldbl_is_nan (long double d) { SInt64 l; SInt64 h; SInt64 *dint; dint = (SInt64 *) & d; #if WORDS_BIGENDIAN l = dint[1]; h = dint[0]; #else l = dint[0]; h = dint[1]; #endif l |= (h & 0x0000FFFFFFFFFFFF); l |= -l; l = ((h & 0x7FFF000000000000) ^ 0x7FFF000000000000) - ((UInt64) l >> 63); return (l >> 63) & (h >> 62); } #else #error Unsupported size of long double! #endif #endif /* format MUST already be pointing to a digit */ static int _read_number (const UniChar ** __restrict__ format) { int number; const UniChar *start; start = *format; number = *(*format)++ - '0'; /* Don't read more than 3 characters (max value '999'). This is already * an unrealistically high number for the types of numbers this function * is used for. */ while ((**format >= '0') && (**format <= '9') && (*format - start < 3)) number = (number * 10) + (*(*format++) - '0'); return number; } static const UniChar _lookup_upper[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; static const UniChar _lookup_lower[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; CF_INLINE UniChar * _uint_to_string (unsigned long long int value, UniChar * bufend, int base, Boolean uppercase) { UniChar *cur = bufend; const UniChar *lookup = uppercase ? _lookup_upper : _lookup_lower; switch (base) { case 8: do *--cur = lookup[value & 7]; while ((value >>= 3)); break; case 10: do *--cur = lookup[value % base]; while ((value /= base)); break; case 16: do *--cur = lookup[value & 15]; while ((value >>= 4)); break; } return cur; } static CFIndex _write_char (UniChar * obuf, UniChar * obuf_end, const UniChar c) { int remain = obuf_end - obuf; if (remain > 0) *obuf = c; return 1; } static CFIndex _write (UniChar * obuf, UniChar * obuf_end, const UniChar * s, CFIndex len) { int remain = obuf_end - obuf; if (remain > 0) GSMemoryCopy (obuf, s, remain < len ? remain : len * sizeof (UniChar)); return len; } #define PAD_SIZE 8 static const UniChar _pad_space[] = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' }; static const UniChar _pad_zero[] = { '0', '0', '0', '0', '0', '0', '0', '0' }; static CFIndex _pad (UniChar * obuf, UniChar * obuf_end, const UniChar padchar, CFIndex len) { CFIndex written = 0; if (len > 0) { const UniChar *pad_string; if (padchar == ' ') pad_string = _pad_space; else pad_string = _pad_zero; for (; len > PAD_SIZE; len -= PAD_SIZE) written += _write (obuf, obuf_end, (UniChar *) pad_string, PAD_SIZE); written += _write (obuf, obuf_end, (UniChar *) pad_string, len); } return written; } CF_INLINE format_argument_t * GSUnicodeCreateArgumentList (const UniChar * __restrict__ format, CFIndex fmtlen, va_list ap) { int max; int idx; const UniChar *fmt; const UniChar *fmtlimit; format_argument_t *arglist; UInt8 *lengthlist; UInt8 *typelist; max = 0; fmt = format; fmtlimit = fmt + fmtlen; /* Find the maximum number of arguments. */ /* We'll first get to the first occurrence of '%' and make sure it includes * a position field. * POSIX.1-2008 allows the following pattern: '%n$[*m$][.*o$]' * http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html */ while (fmt < fmtlimit) { int pos; Boolean doingposition; doingposition = true; while (fmt < fmtlimit && *fmt != '%') fmt++; if (!(fmt < fmtlimit)) break; fmt++; if (*fmt == '%') /* Search again if we find a '%%' pattern. */ continue; /* Must start with 1 - 9 or it is not a position argument */ if (!(*fmt >= '1' && *fmt <= '9')) return NULL; /* Get the maximum position */ while (fmt < fmtlimit) { switch (*fmt) { /* Skip flags */ case ' ': case '#': case '\'': case '+': case '-': case '0': fmt++; continue; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (doingposition == true) { pos = _read_number (&fmt); /* If there isn't a '$' at this point, there is an error in the specification. Return NULL and the error will be caught when doing the real parsing later. */ if (*fmt != '$') return NULL; if (pos > max) max = pos; doingposition = false; /* Position already done. */ } fmt++; continue; case '.': /* Precision is the last possibility for a position argument. If it is not '*' we can just move on. */ if (*++fmt != '*') break; case '*': fmt++; doingposition = true; continue; default: break; } break; } } if (max <= 0) return NULL; arglist = (format_argument_t *) CFAllocatorAllocate (kCFAllocatorSystemDefault, sizeof (format_argument_t) * max, 0); lengthlist = (UInt8 *) CFAllocatorAllocate (kCFAllocatorSystemDefault, sizeof (UInt8) * max, 0); typelist = (UInt8 *) CFAllocatorAllocate (kCFAllocatorSystemDefault, sizeof (UInt8) * max, 0); if (arglist == NULL || lengthlist == NULL || typelist == NULL) { if (arglist != NULL) CFAllocatorDeallocate (kCFAllocatorSystemDefault, arglist); if (lengthlist != NULL) CFAllocatorDeallocate (kCFAllocatorSystemDefault, lengthlist); if (typelist != NULL) CFAllocatorDeallocate (kCFAllocatorSystemDefault, typelist); return NULL; } GSMemoryZero (lengthlist, sizeof (UInt8) * max); GSMemoryZero (typelist, sizeof (UInt8) * max); /* Gather all the length and type. */ fmt = format; while (1) { int pos; while (fmt < fmtlimit && *fmt != '%') fmt++; if (!(fmt < fmtlimit)) break; fmt++; if (*fmt == '%') { fmt++; continue; } /* Read position parameter * The previous loop already established that the spec is well formed, * so we do not need to check it again. */ pos = _read_number (&fmt) - 1; fmt++; /* Skip '$' */ /* Skip over any flags */ while (fmt < fmtlimit) { switch (*fmt) { case ' ': case '#': case '\'': case '+': case '-': case '0': fmt++; continue; default: break; } break; } /* Width */ if (fmt < fmtlimit && *fmt == '*') { int width_pos; width_pos = _read_number (&fmt) - 1; if (*fmt == '$') { lengthlist[width_pos] = FMT_MOD_INT; fmt++; } } else { while (fmt < fmtlimit && (*fmt >= '0' && *fmt <= '9')) fmt++; } /* Precision */ if (fmt < fmtlimit && *fmt == '.') { fmt++; if (fmt < fmtlimit && *fmt++ == '*') { int prec_pos; prec_pos = -1; if (*fmt >= '1' && *fmt <= '9') { prec_pos = _read_number (&fmt) - 1; if (*fmt == '$') { lengthlist[prec_pos] = FMT_MOD_INT; fmt++; } } } else { while (fmt < fmtlimit && (*fmt >= '0' && *fmt <= '9')) fmt++; } } if (!(fmt < fmtlimit)) /* Double check */ goto args_handle_error; /* Length */ switch (*fmt++) { case 'L': lengthlist[pos] = FMT_MOD_LONG; break; case 'h': if (*fmt == 'h') { fmt++; lengthlist[pos] = FMT_MOD_CHAR; } else { lengthlist[pos] = FMT_MOD_SHORT; } break; case 'j': lengthlist[pos] = FMT_MOD_INTMAX; break; case 'l': if (*fmt == 'l') { ++fmt; lengthlist[pos] = FMT_MOD_LONGLONG; } else { lengthlist[pos] = FMT_MOD_LONG; } break; case 't': lengthlist[pos] = FMT_MOD_PTRDIFF; break; case 'z': lengthlist[pos] = FMT_MOD_SIZE; break; default: fmt--; break; } /* Get the type */ if (fmt < fmtlimit) { switch (*fmt++) { case 'C': case 'c': case 'd': case 'i': case 'o': case 'u': case 'X': case 'x': typelist[pos] = FMT_INTEGER; break; case 'A': case 'a': case 'E': case 'e': case 'F': case 'f': case 'G': case 'g': typelist[pos] = FMT_DOUBLE; break; case '@': case 'n': case 'p': case 'S': case 's': typelist[pos] = FMT_POINTER; break; default: goto args_handle_error; } } } /* Collect the arguments */ for (idx = 0; idx < max; ++idx) { switch (typelist[idx]) { case FMT_POINTER: arglist[idx].ptrValue = va_arg (ap, void *); break; case FMT_INTEGER: if (lengthlist[idx] == FMT_MOD_LONGLONG) arglist[idx].intValue = va_arg (ap, long long); else if (lengthlist[idx] == FMT_MOD_LONG) arglist[idx].lintValue = va_arg (ap, long); else arglist[idx].intValue = va_arg (ap, int); break; case FMT_DOUBLE: #if SIZEOF_LONG_DOUBLE > SIZEOF_DOUBLE if (lengthlist[idx] == FMT_MOD_LONG) arglist[idx].ldblValue = va_arg (ap, long double); else #endif arglist[idx].dblValue = va_arg (ap, double); break; default: goto args_handle_error; } } CFAllocatorDeallocate (kCFAllocatorSystemDefault, typelist); CFAllocatorDeallocate (kCFAllocatorSystemDefault, lengthlist); return arglist; args_handle_error: CFAllocatorDeallocate (kCFAllocatorSystemDefault, arglist); CFAllocatorDeallocate (kCFAllocatorSystemDefault, typelist); CFAllocatorDeallocate (kCFAllocatorSystemDefault, lengthlist); return NULL; } CFIndex GSUnicodeFormat (UniChar * __restrict__ s, CFIndex n, CFTypeRef locale, const UniChar * __restrict__ format, CFIndex fmtlen, ...) { CFIndex result; va_list ap; va_start (ap, fmtlen); result = GSUnicodeFormatWithArguments (s, n, locale, format, fmtlen, ap); va_end (ap); return result; } static const UniChar nil_string[] = { '(', 'n', 'i', 'l', ')' }; static const CFIndex nil_string_len = 5; static const UniChar null_string[] = { '(', 'n', 'u', 'l', 'l', ')' }; static const CFIndex null_string_len = 6; static const UniChar nan_string[] = { 'N', 'A', 'N' }; static const UniChar inf_string[] = { 'I', 'N', 'F' }; static const CFIndex nan_inf_string_len = 3; /* String Formatting function. * I used GLIBC's implementation of vfprintf() as a model. This seemed like * the most sensible thing to do at the time. The implementation is fairly * efficient in that it doesn't call a lot functions. I still tried to * simplify it it even further but not separating between the slow * positional parameters path and regular path. * * POSIX.1-2008 (http://pubs.opengroup.org/onlinepubs/9699919799/) allows * two possible styles of format strings: * format-string = non-positional / positional * * non-positional = "%" [flags] [width] [precision] [length] specifier * positional = "%" DIGIT "$" [flags] [pos-width] [pos-precision] [length] specifier * * flags = *("'" / "-" / "+" / SP / "#" / "0") * * width = *DIGIT / "*" * pos-width = *DIGIT / ("*" 1*DIGIT) * * precision = "." (*DIGIT / "*") * pos-precision = "." *DIGIT / ("*" 1*DIGIT) * * length = "hh" / "h" / "l" / "ll" / "j" / "z" / "t" / "L" * * specifier = int-spec / float-spec / special-spec * int-specifier = "d" / "i" / "o" / "u" / "x" / "X" * float-spec = "f" / "F" / "e" / "E" / "g" / "G" / "a" / "A" * special-spec = "p" / "c" / "C" / "s" / "S" / "n" / "%" * * -- Stefan */ CFIndex GSUnicodeFormatWithArguments (UniChar * __restrict__ s, CFIndex n, CFTypeRef locale, const UniChar * __restrict__ format, CFIndex fmtlen, va_list ap) { UniChar *obuf; UniChar *obuf_end; const UniChar *fmt; const UniChar *fmtlimit; format_argument_t *arglist; if (fmtlen == 0) return 0; if (s == NULL) n = 0; obuf = s; obuf_end = s + n; fmt = format; fmtlimit = fmt + fmtlen; arglist = GSUnicodeCreateArgumentList (fmt, fmtlen, ap); while (fmt < fmtlimit) { const UniChar *prev; UniChar buffer[BUFFER_SIZE]; UniChar *bufend; UniChar *string; UniChar type; CFIndex string_len; int base; unsigned long long number; int position; Boolean is_negative; Boolean show_sign; Boolean show_space; Boolean alternate; Boolean grouping; Boolean left_align; Boolean pad_zeros; int width; int prec; int length; prev = fmt; while (fmt < fmtlimit && *fmt != '%') fmt++; obuf += _write (obuf, obuf_end, prev, fmt - prev); if (!(fmt < fmtlimit)) break; fmt++; /* skip '%' */ bufend = buffer + BUFFER_SIZE; is_negative = false; show_sign = false; show_space = false; alternate = false; grouping = false; left_align = false; pad_zeros = false; width = 0; /* 0 for not specified */ prec = -1; /* -1 for not specified */ length = FMT_MOD_INT; /* standard length */ STEP_0_JUMP; /* Process the flags */ flag_space_prefix: show_space = true; STEP_0_JUMP; flag_alternate: alternate = true; STEP_0_JUMP; flag_grouping: grouping = true; STEP_0_JUMP; flag_show_sign: show_sign = true; STEP_0_JUMP; flag_left_align: left_align = true; STEP_0_JUMP; flag_pad_zeros: pad_zeros = true; STEP_0_JUMP; /* Process width or position (if '$' exists at the end) */ width_number: fmt--; /* STEP_0_JUMP would have moved fmt forward */ width = _read_number (&fmt); if (width < 0) goto handle_error; STEP_1_JUMP; get_position: if (arglist == NULL) goto handle_error; position = width - 1; width = 0; STEP_0_JUMP; /* This is a position field, so do step 0 again. */ width_asterisk: if (fmt < fmtlimit && (*fmt >= '1' && *fmt <= '9')) { int width_pos = _read_number (&fmt); if (fmt < fmtlimit && (*fmt == '$' && arglist != NULL)) width = arglist[width_pos].intValue; else goto handle_error; } else { width = va_arg (ap, int); } STEP_1_JUMP; /* Process precision */ precision: if (fmt < fmtlimit) { pad_zeros = false; if (*fmt == '*') { fmt++; if (fmt < fmtlimit && (*fmt >= '1' && *fmt <= '9')) { int prec_pos = _read_number (&fmt); if (fmt < fmtlimit && (*fmt == '$' && arglist != NULL)) prec = arglist[prec_pos].intValue; else goto handle_error; } else { prec = va_arg (ap, int); } } else if (*fmt >= '0' && *fmt <= '9') { prec = _read_number (&fmt); } else { /* Treat %.? as %.0? */ prec = 0; } STEP_2_JUMP; } else { goto handle_error; } /* Process length modifiers */ mod_char: length = FMT_MOD_CHAR; STEP_4INT_JUMP; mod_short: length = FMT_MOD_SHORT; STEP_3H_JUMP; mod_long: length = FMT_MOD_LONG; STEP_3L_JUMP; mod_longlong: length = FMT_MOD_LONGLONG; STEP_4INT_JUMP; mod_size_t: length = FMT_MOD_SIZE; STEP_4INT_JUMP; mod_ptrdiff_t: length = FMT_MOD_PTRDIFF; STEP_4INT_JUMP; mod_intmax_t: length = FMT_MOD_INTMAX; STEP_4INT_JUMP; mod_ldbl: STEP_4DBL_JUMP; /* Process specification */ fmt_percent: _write_char (obuf++, obuf_end, '%'); continue; fmt_object: { CFTypeRef o; o = arglist == NULL ? va_arg (ap, CFTypeRef) : arglist[position].ptrValue; if (o == NULL) { string = (UniChar *) nil_string; string_len = nil_string_len; goto print_string; } else { const CFRuntimeClass *cls; CFStringRef desc; cls = _CFRuntimeGetClassWithTypeID (CFGetTypeID (o)); if (cls->copyFormattingDesc) desc = cls->copyFormattingDesc (o, locale); else desc = CFCopyDescription (o); string = (UniChar *) CFStringGetCharactersPtr (desc); string_len = CFStringGetLength (desc); width -= string_len; if (!left_align) obuf += _pad (obuf, obuf_end, ' ', width); if (string) { obuf += _write (obuf, obuf_end, string, string_len); } else { CFRange r; width -= string_len; string = buffer; r.location = 0; do { r.length = GS_MIN (string_len, BUFFER_SIZE); CFStringGetCharacters (desc, r, string); obuf += _write (obuf, obuf_end, string, r.length); r.location += r.length; string_len -= BUFFER_SIZE; } while (string_len > 0); } CFRelease (desc); if (left_align) obuf += _pad (obuf, obuf_end, ' ', width); } continue; } fmt_pointer: { const void *ptr; ptr = arglist == NULL ? va_arg (ap, void *) : arglist[position].ptrValue; if (ptr == NULL) { string = (UniChar *) nil_string; string_len = nil_string_len; goto print_string; } else { base = 16; alternate = true; show_sign = false; show_space = false; type = 'x'; number = (unsigned long long) ptr; goto fmt_integer; } } fmt_decimal: { signed long long int signed_number; if (arglist == NULL) { if (length == FMT_MOD_INT) signed_number = va_arg (ap, int); else if (length == FMT_MOD_LONG) signed_number = va_arg (ap, long int); else if (length == FMT_MOD_LONGLONG) signed_number = va_arg (ap, long long int); else if (length == FMT_MOD_SHORT) signed_number = (short int) va_arg (ap, int); else /* Must be FMT_MOD_CHAR */ signed_number = (char) va_arg (ap, int); } else { if (length == FMT_MOD_INT) signed_number = arglist[position].intValue; else if (length == FMT_MOD_LONG) signed_number = arglist[position].lintValue; else if (length == FMT_MOD_LONGLONG) signed_number = arglist[position].llintValue; else if (length == FMT_MOD_SHORT) signed_number = (short int) arglist[position].intValue; else /* Must be FMT_MOD_CHAR */ signed_number = (char) arglist[position].intValue; } if (signed_number < 0) is_negative = true; number = is_negative ? (-signed_number) : signed_number; base = 10; } goto fmt_integer; fmt_octal: base = 8; goto fmt_unsigned_integer; fmt_hex: base = 16; goto fmt_unsigned_integer; fmt_unsigned_decimal: base = 10; fmt_unsigned_integer: if (arglist == NULL) { if (length == FMT_MOD_INT) number = va_arg (ap, unsigned int); else if (length == FMT_MOD_LONG) number = va_arg (ap, unsigned long int); else if (length == FMT_MOD_LONGLONG) number = va_arg (ap, unsigned long long int); else if (length == FMT_MOD_SHORT) number = (unsigned short int) va_arg (ap, unsigned int); else /* Must be FMT_MOD_CHAR */ number = (unsigned char) va_arg (ap, unsigned int); } else { if (length == FMT_MOD_INT) number = arglist[position].intValue; else if (length == FMT_MOD_LONG) number = arglist[position].lintValue; else if (length == FMT_MOD_LONGLONG) number = arglist[position].llintValue; else if (length == FMT_MOD_SHORT) number = (unsigned short int) arglist[position].intValue; else /* Must be FMT_MOD_CHAR */ number = (unsigned char) arglist[position].intValue; } show_sign = false; show_space = false; if (prec == 0 && number == 0) { /* If number and precision are zero we print nothing, unless * we are formatting an octal value with the alternate flag. */ string = bufend; if (base == 8 && alternate) *--string = '0'; continue; } else { fmt_integer: #if 0 /* Is is not important for this to be part of the build as CFString formatting functions do not support supplying a locale. Implementing this is a long term goal to support passing both {CF, NS}Dictionary and {CF, NS}Locale objects to help format integers. */ if (base == 10 && locale != NULL) { /* This is a slower than using _uint_to_string () because * we have to go through the trouble of opening a formatter. * That's why we only do it if a locale is specified. */ string = NULL; } else #endif { /* This is the "fast" integer formatting path. * All the writing is done here, too. */ string = _uint_to_string (number, bufend, base, type == 'X'); if (base == 8 && alternate) *--string = '0'; string_len = bufend - string; prec = prec >= string_len ? prec - string_len : 0; width -= string_len + prec; /* Account for sign symbols */ if (is_negative || show_sign || show_space) --width; if (!left_align) { /* Account for '0x' prefix for hexadecimal formatting. */ if (base == 16 && alternate) width -= 2; if (pad_zeros == false && width > 0) obuf += _pad (obuf, obuf_end, ' ', width); if (is_negative) _write_char (obuf++, obuf_end, '-'); else if (show_sign) _write_char (obuf++, obuf_end, '+'); else if (show_space) _write_char (obuf++, obuf_end, ' '); if (base == 16 && alternate) { _write_char (obuf++, obuf_end, '0'); _write_char (obuf++, obuf_end, type); } if (pad_zeros && width > 0) prec += width; if (prec > 0) obuf += _pad (obuf, obuf_end, '0', prec); obuf += _write (obuf, obuf_end, string, string_len); } else { if (is_negative) _write_char (obuf++, obuf_end, '-'); else if (show_sign) _write_char (obuf++, obuf_end, '+'); else if (show_space) _write_char (obuf++, obuf_end, ' '); if (base == 16 && alternate) { _write_char (obuf++, obuf_end, '0'); _write_char (obuf++, obuf_end, type); width -= 2; } if (prec > 0) obuf += _pad (obuf, obuf_end, '0', prec); obuf += _write (obuf, obuf_end, string, string_len); if (width > 0) obuf += _pad (obuf, obuf_end, ' ', width); } continue; } goto print_string; } fmt_getcount: { int written = obuf - s; if (arglist == NULL) { if (length == FMT_MOD_INT) *(int *) va_arg (ap, void *) = written; else if (length == FMT_MOD_LONG) *(long int *) va_arg (ap, void *) = written; else if (length == FMT_MOD_LONGLONG) *(long long int *) va_arg (ap, void *) = written; else if (length == FMT_MOD_SHORT) *(short int *) va_arg (ap, void *) = written; else /* Must be FMT_MOD_CHAR */ *(char *) va_arg (ap, void *) = written; } else { if (length == FMT_MOD_INT) *(int *) arglist[position].ptrValue = written; else if (length == FMT_MOD_LONG) *(long int *) arglist[position].ptrValue = written; else if (length == FMT_MOD_LONGLONG) *(long long int *) arglist[position].ptrValue = written; else if (length == FMT_MOD_SHORT) *(short int *) arglist[position].ptrValue = written; else /* Must be FMT_MOD_CHAR */ *(char *) arglist[position].ptrValue = written; } } continue; fmt_long_double: #if SIZEOF_LONG_DOUBLE > SIZEOF_DOUBLE { long double ldbl_number; if (arglist == NULL) ldbl_number = va_arg (ap, long double); else ldbl_number = arglist[position].ldblValue; if (_ldbl_is_nan (ldbl_number)) { string = (UniChar *) nan_string; string_len = nan_inf_string_len; } else if (_ldbl_is_inf (ldbl_number)) { string = (UniChar *) inf_string; string_len = nan_inf_string_len; } else { string = NULL; } goto fmt_double_parts; } #endif fmt_double: { double dbl_number; int ret; if (arglist == NULL) dbl_number = va_arg (ap, double); else dbl_number = arglist[position].dblValue; if ((ret = _dbl_is_nan (dbl_number))) { is_negative = ret < 0; string = (UniChar *) nan_string; string_len = nan_inf_string_len; } else if ((ret = _dbl_is_inf (dbl_number))) { is_negative = ret < 0; string = (UniChar *) inf_string; string_len = nan_inf_string_len; } else { /* FIXME */ string = NULL; } } #if SIZEOF_LONG_DOUBLE > SIZEOF_DOUBLE /* Avoid unused warning */ fmt_double_parts: #endif if (string != NULL) { /* Must be 'nan' or 'inf' */ if (is_negative || show_sign || show_space) { string_len += 1; if (is_negative) _write_char (obuf++, obuf_end, '-'); else if (show_sign) _write_char (obuf++, obuf_end, '+'); else if (show_space) _write_char (obuf++, obuf_end, ' '); } _write_char (obuf++, obuf_end, *string++ | (type & 0x20)); _write_char (obuf++, obuf_end, *string++ | (type & 0x20)); _write_char (obuf++, obuf_end, *string | (type & 0x20)); continue; } goto handle_error; fmt_character: if (length == FMT_MOD_LONG || type == 'C') { if (arglist == NULL) buffer[0] = (UniChar) va_arg (ap, int); else buffer[0] = (UniChar) arglist[position].intValue; string = buffer; } else { if (arglist == NULL) buffer[0] = (char) va_arg (ap, int); else buffer[0] = (char) arglist[position].intValue; string = buffer; } string_len = 1; goto print_string; fmt_string: string = arglist == NULL ? va_arg (ap, UniChar *) : arglist[position].ptrValue; if (string == NULL) { string = (UniChar *) null_string; string_len = null_string_len; } else if (length == FMT_MOD_LONG || type == 'S') { string_len = _ustring_length (string, prec); } else { UniChar *tmp; const UniChar *tmp_limit; const UInt8 *cstring = (const UInt8 *) string; string_len = _cstring_length ((const char *) cstring, prec); width -= string_len; if (!left_align) obuf += _pad (obuf, obuf_end, ' ', width); tmp_limit = buffer + BUFFER_SIZE; do { tmp = buffer; GSUnicodeFromEncoding (&tmp, tmp_limit, CFStringGetSystemEncoding (), &cstring, cstring + string_len, 0); obuf += _write (obuf, obuf_end, buffer, tmp - buffer); string_len -= BUFFER_SIZE; } while (string_len > 0); if (left_align) obuf += _pad (obuf, obuf_end, ' ', width); continue; } print_string: width -= string_len; if (!left_align) obuf += _pad (obuf, obuf_end, ' ', width); obuf += _write (obuf, obuf_end, string, string_len); if (left_align) obuf += _pad (obuf, obuf_end, ' ', width); } if (arglist != NULL) CFAllocatorDeallocate (kCFAllocatorSystemDefault, arglist); return obuf - s; handle_error: if (arglist != NULL) CFAllocatorDeallocate (kCFAllocatorSystemDefault, arglist); return -1; } gnustep-corebase-0.2/Source/CFString.c0000644000175000017500000014543114551015633017001 0ustar yavoryavor/* CFString.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: May, 2011 This file is part of GNUstep CoreBase Library. This library is free software; you can redisibute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is disibuted in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFArray.h" #include "CoreFoundation/CFData.h" #include "CoreFoundation/CFDictionary.h" #include "CoreFoundation/CFNumberFormatter.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFStringEncodingExt.h" #include "CoreFoundation/GSCharacter.h" #include "CoreFoundation/GSUnicode.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" #include "GSMemory.h" #include #include #include #include #if defined(HAVE_UNICODE_UNORM2_H) #include #endif #if defined(HAVE_UNICODE_USTRING_H) #include #endif #if defined(HAVE_UNICODE_UTRANS_H) #include #endif #if defined(HAVE_ICU_H) #include #endif #define BUFFER_SIZE 512 CONST_STRING_DECL (kCFStringTransformStripCombiningMarks, "NFD; [:nonspacing mark:]Remove; NFC"); CONST_STRING_DECL (kCFStringTransformToLatin, "Any-Latin"); CONST_STRING_DECL (kCFStringTransformFullwidthHalfwidth, "Fullwidth-Halfwidth"); CONST_STRING_DECL (kCFStringTransformLatinKatakana, "Latin-Katakana"); CONST_STRING_DECL (kCFStringTransformLatinHiragana, "Latin-Hiragana"); CONST_STRING_DECL (kCFStringTransformHiraganaKatakana, "Hiragana-Katakana"); CONST_STRING_DECL (kCFStringTransformMandarinLatin, "Mandarin-Latin"); CONST_STRING_DECL (kCFStringTransformLatinHangul, "Latin-Hangul"); CONST_STRING_DECL (kCFStringTransformLatinArabic, "Latin-Arabic"); CONST_STRING_DECL (kCFStringTransformLatinHebrew, "Latin-Hebrew"); CONST_STRING_DECL (kCFStringTransformLatinThai, "Latin-Thai"); CONST_STRING_DECL (kCFStringTransformLatinCyrillic, "Latin-Cyrillic"); CONST_STRING_DECL (kCFStringTransformLatinGreek, "Latin-Greek"); CONST_STRING_DECL (kCFStringTransformToXMLHex, "Any-Hex/XML"); CONST_STRING_DECL (kCFStringTransformToUnicodeName, "Any-Name"); CONST_STRING_DECL (kCFStringTransformStripDiacritics, "NFD; [:nonspacing marks:]Remove; NFC"); /* CFString has two possible internal encodings: * UTF-16 (preferable) * ASCII If the encoding is not one of the two listed above, it will be converted to UTF-16 any character is not ASCII. */ struct __CFString { CFRuntimeBase _parent; void *_contents; CFIndex _count; CFHashCode _hash; CFAllocatorRef _deallocator; }; struct __CFMutableString { CFRuntimeBase _parent; UniChar *_contents; CFIndex _count; CFHashCode _hash; CFAllocatorRef _allocator; CFIndex _capacity; }; static CFTypeID _kCFStringTypeID; /* These are some masks to access the data in CFRuntimeBase's _flags.info field. */ enum { _kCFStringIsMutable = (1 << 0), _kCFStringIsInline = (1 << 1), _kCFStringIsUnicode = (1 << 2), _kCFStringHasLengthByte = (1 << 3), /* This is used for Pascal strings */ _kCFStringHasNullByte = (1 << 4) }; // TODO: dispatch to ObjC in all of these methods OR check its use CF_INLINE Boolean CFStringIsMutable (CFStringRef str) { return ((CFRuntimeBase *) str)->_flags.info & _kCFStringIsMutable ? true : false; } CF_INLINE Boolean CFStringIsUnicode (CFStringRef str) { return ((CFRuntimeBase *) str)-> _flags.info & _kCFStringIsUnicode ? true : false; } CF_INLINE Boolean CFStringIsInline (CFStringRef str) { return ((CFRuntimeBase *) str)->_flags.info & _kCFStringIsInline ? true : false; } CF_INLINE Boolean CFStringHasNullByte (CFStringRef str) { return ((CFRuntimeBase *) str)-> _flags.info & _kCFStringHasNullByte ? true : false; } CF_INLINE void CFStringSetMutable (CFStringRef str) { ((CFRuntimeBase *) str)->_flags.info |= _kCFStringIsMutable; } CF_INLINE void CFStringSetUnicode (CFStringRef str) { ((CFRuntimeBase *) str)->_flags.info |= _kCFStringIsUnicode; } CF_INLINE void CFStringSetInline (CFStringRef str) { ((CFRuntimeBase *) str)->_flags.info |= _kCFStringIsInline; } CF_INLINE void CFStringSetNullByte (CFStringRef str) { ((CFRuntimeBase *) str)->_flags.info |= _kCFStringHasNullByte; } static void CFStringFinalize (CFTypeRef cf) { CFStringRef str = (CFStringRef) cf; if (!CFStringIsInline (str)) CFAllocatorDeallocate (str->_deallocator, str->_contents); } static Boolean CFStringEqual (CFTypeRef cf1, CFTypeRef cf2) { return CFStringCompare (cf1, cf2, 0) == 0 ? true : false; } static CFHashCode CFStringHash (CFTypeRef cf) { CFStringRef str = (CFStringRef) cf; UniChar *buf; CFIndex len; Boolean isObjc; CFHashCode hash; isObjc = CF_IS_OBJC (_kCFStringTypeID, str); if (!isObjc) { if (str->_hash == 0) { if (CFStringIsUnicode (str)) { len = CFStringGetLength (str) * sizeof (UniChar); ((struct __CFString *) str)->_hash = GSHashBytes (str->_contents, len); return str->_hash; } } else return str->_hash; } len = CFStringGetLength (str) * sizeof (UniChar); buf = CFAllocatorAllocate (kCFAllocatorSystemDefault, len, 0); CFStringGetCharacters (str, CFRangeMake (0, len / 2), buf); hash = GSHashBytes (buf, len); if (!isObjc) ((struct __CFString *) str)->_hash = hash; CFAllocatorDeallocate (kCFAllocatorSystemDefault, buf); return hash; } static CFStringRef CFStringCopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOptions) { return CFStringCreateCopy (kCFAllocatorSystemDefault, cf); } static const CFRuntimeClass CFStringClass = { 0, "CFString", NULL, (CFTypeRef (*)(CFAllocatorRef, CFTypeRef)) CFStringCreateCopy, CFStringFinalize, CFStringEqual, CFStringHash, CFStringCopyFormattingDesc, NULL }; static GSMutex static_strings_lock; static CFMutableDictionaryRef static_strings; /* * Hack to allocated CFStrings uniquely without compiler support. */ CFStringRef __CFStringMakeConstantString (const char *str) { CFStringRef old; if (static_strings == NULL) { /* The 170 capacity is really arbitrary. I just wanted to make the * number large enough so that the hash table size comes out to 257, * a table large enough to fit most needs before needing to expand. */ GSMutexLock (&static_strings_lock); if (static_strings == NULL) static_strings = CFDictionaryCreateMutable (NULL, 170, NULL, NULL); GSMutexUnlock (&static_strings_lock); } old = (CFStringRef) CFDictionaryGetValue (static_strings, str); /* Return the existing string pointer if we have one. */ if (NULL != old) return old; GSMutexLock (&static_strings_lock); /* Check again in case another thread added this string to the table while * we were waiting on the mutex. */ old = (CFStringRef) CFDictionaryGetValue (static_strings, str); if (NULL == old) { struct __CFString *new_const_str; new_const_str = CFAllocatorAllocate (NULL, sizeof (struct __CFString), 0); assert (new_const_str); /* Using _CFRuntimeInitStaticInstance() guarantees that any CFRetain or * CFRelease calls on object will be a no-op. */ _CFRuntimeInitStaticInstance (new_const_str, _kCFStringTypeID); new_const_str->_contents = (void *) str; new_const_str->_count = strlen (str); new_const_str->_hash = 0; new_const_str->_deallocator = NULL; CFDictionaryAddValue (static_strings, str, (const void *) new_const_str); old = new_const_str; } GSMutexUnlock (&static_strings_lock); return old; } void CFStringInitialize (void) { _kCFStringTypeID = _CFRuntimeRegisterClass (&CFStringClass); GSMutexInitialize (&static_strings_lock); } void CFShow (CFTypeRef obj) { CFStringRef str; const char *out; char buffer[256]; str = CFCopyDescription (obj); if (str) { out = CFStringGetCStringPtr (str, kCFStringEncodingASCII); if (out == NULL) { if (CFStringGetCString (str, buffer, 256, kCFStringEncodingASCII)) out = buffer; } CFRelease (str); } else { out = NULL; } fprintf (stderr, "%s\n", out); } void CFShowStr (CFStringRef s) { fprintf (stderr, "Length %ld\n", (long) CFStringGetLength (s)); fprintf (stderr, "IsWide %d\n", CFStringIsUnicode (s)); fprintf (stderr, "InlineContents %d\n", CFStringIsInline (s)); fprintf (stderr, "Allocator %p\n", CFGetAllocator (s)); fprintf (stderr, "Mutable %d\n", CFStringIsMutable (s)); fprintf (stderr, "Contents "); CFShow (s); } CFTypeID CFStringGetTypeID (void) { return _kCFStringTypeID; } /* CFStringCreateImmutable function will return an inlined string whenever possible. The contents may or may not be inlined if a NoCopy function is called. With this in mind, CFStringCreateWithBytes will return a string with the content inlined and CFStringCreateWithBytesNoCopy will not have inlined content if, and only if, the input bytes are in one of the internal encodings (ASCII or UTF-16). */ #define CFSTRING_SIZE \ sizeof(struct __CFString) - sizeof(struct __CFRuntimeBase) static CFStringRef CFStringCreateImmutable (CFAllocatorRef alloc, const UInt8 * bytes, CFIndex numBytes, CFStringEncoding encoding, Boolean isExtRep, CFAllocatorRef contentsDealloc, Boolean copy) { struct __CFString *new; UniChar b[BUFFER_SIZE]; UniChar *buffer; UniChar *bufferStart; CFIndex need; CFIndex extra; buffer = b; bufferStart = b; /* Check if we can store this string as ASCII */ if (__CFStringEncodingIsSupersetOfASCII (encoding)) { const UInt8 *s; const UInt8 *limit; s = bytes; limit = s + numBytes; while (s < limit) { if (*s++ > 0x7F) break; } if (s >= limit) encoding = kCFStringEncodingASCII; } if (encoding == kCFStringEncodingASCII) { need = numBytes; extra = numBytes + 1; } else { const UInt8 *src; src = bytes; /* We'll include a loss character for this conversion in case there is an error in the input stream. We dont' want to fail just because someone included an invalid code point/unit. The loss character will be the Unicode replacement character U+FFFD. */ need = GSUnicodeFromEncoding (&buffer, buffer + BUFFER_SIZE, encoding, &src, src + numBytes, 0xFFFD); if (need < 0) /* There is something seriously wrong! */ return NULL; extra = (need + 1) * sizeof (UniChar); } if (!copy) { if (encoding == kCFStringEncodingUTF16) { UniChar c; c = *((const UniChar *) bytes); if (c == kGSUTF16CharacterSwappedByteOrderMark) copy = true; } else if (encoding != kCFStringEncodingASCII) { copy = true; } #if __BIG_ENDIAN__ else if (encoding == kCFStringEncodingUTF16LE) { copy = true; } #else else if (encoding == kCFStringEncodingUTF16BE) { copy = true; } #endif } new = (struct __CFString *) _CFRuntimeCreateInstance (alloc, _kCFStringTypeID, CFSTRING_SIZE + extra, NULL); if (new) { if (contentsDealloc == NULL) contentsDealloc = CFAllocatorGetDefault (); new->_deallocator = CFRetain (contentsDealloc); if (copy) { new->_contents = &(new[1]); if (encoding == kCFStringEncodingASCII) { GSMemoryCopy (new->_contents, bytes, numBytes); } else if (extra <= BUFFER_SIZE) { GSMemoryCopy (new->_contents, bufferStart, need * sizeof (UniChar)); CFStringSetUnicode (new); } else { UniChar *contents; contents = new->_contents; GSUnicodeFromEncoding (&contents, contents + need, encoding, &bytes, bytes + numBytes, 0xFFFD); CFStringSetUnicode (new); } new->_count = need; CFStringSetInline (new); CFStringHasNullByte (new); } else { new->_contents = (void *) bytes; new->_count = encoding == kCFStringEncodingASCII ? numBytes : numBytes / sizeof (UniChar); if (encoding != kCFStringEncodingASCII) CFStringSetUnicode (new); } } return (CFStringRef) new; } CFStringRef CFStringCreateWithBytes (CFAllocatorRef alloc, const UInt8 * bytes, CFIndex numBytes, CFStringEncoding encoding, Boolean isExternalRepresentation) { return CFStringCreateImmutable (alloc, bytes, numBytes, encoding, isExternalRepresentation, NULL, true); } CFStringRef CFStringCreateWithBytesNoCopy (CFAllocatorRef alloc, const UInt8 * bytes, CFIndex numBytes, CFStringEncoding encoding, Boolean isExternalRepresentation, CFAllocatorRef contentsDeallocator) { return CFStringCreateImmutable (alloc, bytes, numBytes, encoding, isExternalRepresentation, contentsDeallocator, false); } CFStringRef CFStringCreateCopy (CFAllocatorRef alloc, CFStringRef str) { if (CF_IS_OBJC (_kCFStringTypeID, str)) { CFIndex length = CFStringGetLength (str); UniChar *buf = (UniChar *) CFAllocatorAllocate (alloc, sizeof (UniChar) * length, 0); CFStringGetCharacters (str, CFRangeMake (0, length), buf); return CFStringCreateWithCharactersNoCopy (alloc, buf, length, alloc); } CFIndex length; CFStringRef new; CFStringEncoding enc; if (alloc == NULL) alloc = CFAllocatorGetDefault (); if (CFGetAllocator (str) == alloc && !CFStringIsMutable (str)) return CFRetain (str); length = CFStringIsUnicode (str) ? str->_count * sizeof (UniChar) : str->_count; enc = CFStringIsUnicode (str) ? kCFStringEncodingUTF16 : kCFStringEncodingASCII; new = CFStringCreateWithBytes (alloc, str->_contents, length, enc, false); return new; } CFStringRef CFStringCreateWithFileSystemRepresentation (CFAllocatorRef alloc, const char *buffer) { /* FIXME: Need to make sure the system encoding will work here. */ return CFStringCreateWithCString (alloc, buffer, CFStringGetSystemEncoding ()); } CFStringRef CFStringCreateFromExternalRepresentation (CFAllocatorRef alloc, CFDataRef data, CFStringEncoding encoding) { const UInt8 *bytes = CFDataGetBytePtr (data); CFIndex numBytes = CFDataGetLength (data); return CFStringCreateWithBytes (alloc, bytes, numBytes, encoding, true); } CFStringRef CFStringCreateWithCharacters (CFAllocatorRef alloc, const UniChar * chars, CFIndex numChars) { return CFStringCreateWithBytes (alloc, (const UInt8 *) chars, numChars * sizeof (UniChar), kCFStringEncodingUnicode, false); } CFStringRef CFStringCreateWithCharactersNoCopy (CFAllocatorRef alloc, const UniChar * chars, CFIndex numChars, CFAllocatorRef contentsDeallocator) { return CFStringCreateWithBytesNoCopy (alloc, (const UInt8 *) chars, numChars * sizeof (UniChar), kCFStringEncodingUnicode, false, contentsDeallocator); } CFStringRef CFStringCreateWithCString (CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding) { CFIndex len = strlen (cStr); return CFStringCreateWithBytes (alloc, (const UInt8 *) cStr, len, encoding, false); } CFStringRef CFStringCreateWithCStringNoCopy (CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding, CFAllocatorRef contentsDeallocator) { CFIndex len = strlen (cStr); return CFStringCreateWithBytesNoCopy (alloc, (const UInt8 *) cStr, len, encoding, false, contentsDeallocator); } CFStringRef CFStringCreateWithFormat (CFAllocatorRef alloc, CFDictionaryRef formatOptions, CFStringRef format, ...) { CFStringRef result; va_list args; va_start (args, format); result = CFStringCreateWithFormatAndArguments (alloc, formatOptions, format, args); va_end (args); return result; } CFStringRef CFStringCreateWithFormatAndArguments (CFAllocatorRef alloc, CFDictionaryRef formatOptions, CFStringRef format, va_list arguments) { Boolean free_fmt_str = false; CFIndex str_len; CFIndex fmt_str_len; UniChar buf[BUFFER_SIZE]; UniChar *str = buf; const UniChar *fmt_str; CFStringRef fmted_str; fmt_str_len = CFStringGetLength (format); fmt_str = CFStringGetCharactersPtr (format); if (fmt_str == 0) { CFRange range; free_fmt_str = true; fmt_str = CFAllocatorAllocate (kCFAllocatorSystemDefault, fmt_str_len * sizeof (UniChar), 0); range = CFRangeMake (0, fmt_str_len); CFStringGetCharacters (format, range, (UniChar *) fmt_str); } str_len = GSUnicodeFormatWithArguments (str, BUFFER_SIZE, formatOptions, fmt_str, fmt_str_len, arguments); if (str_len > BUFFER_SIZE) { /* The buffer was not long enough for the formatted string, so we will * need to allocate a longer buffer and try again. */ str = CFAllocatorAllocate (kCFAllocatorSystemDefault, str_len * sizeof (UniChar), 0); str_len = GSUnicodeFormatWithArguments (str, str_len, formatOptions, fmt_str, fmt_str_len, arguments); } if (str_len < 0) return NULL; fmted_str = CFStringCreateWithCharacters (alloc, (const UniChar *) str, str_len); if (free_fmt_str) CFAllocatorDeallocate (kCFAllocatorSystemDefault, (void *) fmt_str); if (str != buf) CFAllocatorDeallocate (kCFAllocatorSystemDefault, str); return fmted_str; } CFStringRef CFStringCreateWithSubstring (CFAllocatorRef alloc, CFStringRef str, CFRange range) { void *contents; CFIndex len; CFStringEncoding enc; if (CFStringIsUnicode (str)) { enc = kCFStringEncodingUnicode; len = range.length * sizeof (UniChar); contents = ((UniChar *) str->_contents) + range.location; } else { enc = kCFStringEncodingASCII; len = range.length; contents = ((char *) str->_contents) + range.location; } return CFStringCreateWithBytes (alloc, (const UInt8 *) contents, len, enc, false); } CFDataRef CFStringCreateExternalRepresentation (CFAllocatorRef alloc, CFStringRef str, CFStringEncoding encoding, UInt8 lossByte) { UInt8 *buffer; CFRange range; CFIndex converted; CFIndex strLen; CFIndex len; CFIndex usedLen = 0; strLen = CFStringGetLength (str); range = CFRangeMake (0, strLen); converted = CFStringGetBytes (str, range, encoding, lossByte, true, NULL, 0, &len); if (converted == 0) return NULL; len += 1; /* include space for a NULL byte. */ buffer = CFAllocatorAllocate (alloc, len, 0); converted = CFStringGetBytes (str, range, encoding, lossByte, true, buffer, len, &usedLen); if (converted == 0) { CFAllocatorDeallocate (alloc, buffer); return NULL; } return CFDataCreateWithBytesNoCopy (alloc, buffer, usedLen, alloc); } const UniChar * CFStringGetCharactersPtr (CFStringRef str) { if (!CF_IS_OBJC (_kCFStringTypeID, str) && CFStringIsUnicode (str)) return str->_contents; return NULL; } const char * CFStringGetCStringPtr (CFStringRef str, CFStringEncoding enc) { CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, const char *, str, "cStringUsingEncoding:", CFStringConvertEncodingToNSStringEncoding (enc)); return (!CFStringIsUnicode (str) && __CFStringEncodingIsSupersetOfASCII (enc)) ? str-> _contents : NULL; } CFIndex CFStringGetBytes (CFStringRef str, CFRange range, CFStringEncoding enc, UInt8 lossByte, Boolean isExtRep, UInt8 * buffer, CFIndex maxBufLen, CFIndex * usedBufLen) { UInt8 *bufferStart; const UniChar *sUnicode; CFIndex converted; if (CF_IS_OBJC (_kCFStringTypeID, str)) { /* Boolean b; */ uintptr_t opts = 0; if (lossByte != 0) opts |= 1; /* NSStringEncodingConversionAllowLossy */ if (isExtRep != 0) opts |= 2; /*NSStringEncodingConversionExternalRepresentation */ // FIXME: Base's NSString doesn't implement getBytes:... yet! *usedBufLen = 0; return 0; /* CF_OBJC_CALLV (Boolean, b, str, "getBytes:maxLength:usedLength:encoding:options:range:remainingRange:", buffer, maxBufLen, usedBufLen, CFStringConvertEncodingToNSStringEncoding (enc), opts, range, NULL); return b ? *usedBufLen : 0; */ } bufferStart = buffer; sUnicode = CFStringGetCharactersPtr (str); if (sUnicode) { const UniChar *sUnicodeStart; const UniChar *sLimit; sUnicodeStart = sUnicode + range.location; sUnicode = sUnicodeStart; sLimit = sUnicodeStart + range.length; /* It is safe to discard the return value in this case. */ GSUnicodeToEncoding (&buffer, buffer + maxBufLen, enc, &sUnicode, sLimit, lossByte, isExtRep); converted = sUnicode - sUnicodeStart; } else if (__CFStringEncodingIsSupersetOfASCII (enc)) { const char *sCString; sCString = CFStringGetCStringPtr (str, kCFStringEncodingASCII); if (sCString) { sCString += range.location; converted = range.length > maxBufLen ? maxBufLen : range.length; GSMemoryCopy (buffer, sCString, converted); buffer += converted; } else { converted = 0; } } else if (enc == kCFStringEncodingUnicode) { range.length = range.length > (maxBufLen / sizeof (UniChar)) ? maxBufLen / sizeof (UniChar) : range.length; CFStringGetCharacters (str, range, (UniChar *) buffer); buffer += range.length * sizeof (UniChar); converted = range.length; } if (usedBufLen) *usedBufLen = buffer - bufferStart; return converted; /* FIXME */ } void CFStringGetCharacters (CFStringRef str, CFRange range, UniChar * buffer) { CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, void, str, "getCharacters:range:", buffer, range); if (CFStringIsUnicode (str)) { memcpy (buffer, ((UniChar *) str->_contents) + range.location, range.length * sizeof (UniChar)); } else { UInt8 *c; UInt8 *stop; c = str->_contents + range.location; stop = c + range.length; while (c < stop) *buffer++ = *c++; } } Boolean CFStringGetCString (CFStringRef str, char *buffer, CFIndex bufferSize, CFStringEncoding encoding) { CFIndex len = CFStringGetLength (str); CFIndex used; CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, Boolean, str, "getCString:maxLength:encoding:", buffer, bufferSize, CFStringConvertEncodingToNSStringEncoding (encoding)); if (CFStringGetBytes (str, CFRangeMake (0, len), encoding, 0, false, (UInt8 *) buffer, bufferSize, &used) == len && used <= len) { buffer[used] = '\0'; return true; } return false; } Boolean CFStringGetFileSystemRepresentation (CFStringRef string, char *buffer, CFIndex maxBufLen) { /* FIXME */ return CFStringGetCString (string, buffer, maxBufLen, CFStringGetSystemEncoding ()); } UniChar CFStringGetCharacterAtIndex (CFStringRef str, CFIndex idx) { CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, UniChar, str, "characterAtIndex:", idx); return CFStringIsUnicode (str) ? ((UniChar *) str->_contents)[idx] : ((UInt8 *) str->_contents)[idx]; } CFIndex CFStringGetLength (CFStringRef str) { CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, CFIndex, str, "length"); return str->_count; } CFRange CFStringGetRangeOfComposedCharactersAtIndex (CFStringRef str, CFIndex theIndex) { CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, CFRange, str, "rangeOfComposedCharacterSequenceAtIndex:", theIndex); if (CFStringIsUnicode (str)) { CFIndex len = 1; UniChar *characters = ((UniChar *) str->_contents) + theIndex; if (U16_IS_SURROGATE (*characters)) { len = 2; if (U16_IS_SURROGATE_TRAIL (*characters)) theIndex -= 1; } return CFRangeMake (theIndex, len); } return CFRangeMake (theIndex, 1); } UTF32Char CFStringGetLongCharacterForSurrogatePair (UniChar surrogateHigh, UniChar surrogateLow) { return (UTF32Char) U16_GET_SUPPLEMENTARY (surrogateHigh, surrogateLow); } Boolean CFStringGetSurrogatePairForLongCharacter (UTF32Char character, UniChar * surrogates) { if (character > 0x10000) return false; surrogates[0] = U16_LEAD (character); surrogates[1] = U16_TRAIL (character); return true; } Boolean CFStringIsSurrogateHighCharacter (UniChar character) { return (Boolean) U16_IS_LEAD (character); } Boolean CFStringIsSurrogateLowCharacter (UniChar character) { return (Boolean) U16_IS_TRAIL (character); } double CFStringGetDoubleValue (CFStringRef str) { double d; Boolean success; CFNumberFormatterRef fmt; fmt = CFNumberFormatterCreate (NULL, NULL, kCFNumberFormatterDecimalStyle); if (fmt == NULL) return 0.0; success = CFNumberFormatterGetValueFromString (fmt, str, NULL, kCFNumberDoubleType, (void *) &d); CFRelease (fmt); return success ? d : 0.0; } SInt32 CFStringGetIntValue (CFStringRef str) { SInt32 i; Boolean success; CFNumberFormatterRef fmt; fmt = CFNumberFormatterCreate (NULL, NULL, kCFNumberFormatterNoStyle); if (fmt == NULL) return 0; success = CFNumberFormatterGetValueFromString (fmt, str, NULL, kCFNumberSInt32Type, (void *) &i); CFRelease (fmt); return success ? i : 0; } /* CFMutableString functions start here. All mutable string instances are Unicode. This makes it easier to use the ICU functions. */ /* This function is used to grow the size of a CFMutableString buffer. The string's buffer will grow to (newCapacity * sizeof(UniChar)). On return, oldContentBuffer will point to the old data. If this value is not provided, the old content buffer is freed and data will be lost. */ static Boolean CFStringCheckCapacityAndGrow (CFMutableStringRef str, CFIndex newCapacity, void **oldContentBuffer) { void *currentContents; void *newContents; struct __CFMutableString *mStr = (struct __CFMutableString *) str; if (mStr->_capacity >= newCapacity) { if (oldContentBuffer) *oldContentBuffer = str->_contents; return true; } currentContents = mStr->_contents; newContents = CFAllocatorAllocate (mStr->_allocator, (newCapacity * sizeof (UniChar)), 0); if (newContents == NULL) return false; mStr->_contents = newContents; mStr->_capacity = newCapacity; if (oldContentBuffer) *oldContentBuffer = currentContents; else CFAllocatorDeallocate (mStr->_allocator, currentContents); return true; } #define DEFAULT_STRING_CAPACITY 16 #define CFSTRING_INIT_MUTABLE(str) do \ { \ ((CFRuntimeBase *)str)->_flags.info = 0xFF \ & (_kCFStringIsMutable | _kCFStringIsUnicode | _kCFStringHasNullByte); \ } while(0) CFMutableStringRef CFStringCreateMutable (CFAllocatorRef alloc, CFIndex maxLength) { struct __CFMutableString *new; new = (struct __CFMutableString *) _CFRuntimeCreateInstance (alloc, _kCFStringTypeID, sizeof (struct __CFMutableString) - sizeof (CFRuntimeBase), NULL); new->_capacity = maxLength < DEFAULT_STRING_CAPACITY ? DEFAULT_STRING_CAPACITY : maxLength; new->_allocator = alloc ? alloc : CFAllocatorGetDefault (); new->_contents = CFAllocatorAllocate (new->_allocator, new->_capacity * sizeof (UniChar), 0); CFSTRING_INIT_MUTABLE (new); return (CFMutableStringRef) new; } CFMutableStringRef CFStringCreateMutableCopy (CFAllocatorRef alloc, CFIndex maxLength, CFStringRef str) { CFMutableStringRef new; CFStringInlineBuffer buffer; UniChar *contents; CFIndex textLen; CFIndex capacity; CFIndex idx; textLen = CFStringGetLength (str); capacity = textLen; if (maxLength > capacity) capacity = maxLength; new = (CFMutableStringRef) CFStringCreateMutable (alloc, capacity); /* An inline buffer is going to work well here... */ CFStringInitInlineBuffer (str, &buffer, CFRangeMake (0, textLen)); contents = (UniChar *) new->_contents; idx = 0; while (idx < textLen) { UniChar c = CFStringGetCharacterFromInlineBuffer (&buffer, idx++); *(contents++) = c; } new->_count = textLen; CFSTRING_INIT_MUTABLE (new); return new; } CFMutableStringRef CFStringCreateMutableWithExternalCharactersNoCopy (CFAllocatorRef alloc, UniChar * chars, CFIndex numChars, CFIndex capacity, CFAllocatorRef externalCharactersAllocator) { return NULL; /* FIXME */ } void CFStringSetExternalCharactersNoCopy (CFMutableStringRef str, UniChar * chars, CFIndex length, CFIndex capacity) { return; /* FIXME */ } CFIndex CFStringFindAndReplace (CFMutableStringRef str, CFStringRef stringToFind, CFStringRef replacementString, CFRange rangeToSearch, CFOptionFlags compareOptions) { return 0; /* FIXME */ } void CFStringAppend (CFMutableStringRef str, CFStringRef appendString) { CFStringReplace (str, CFRangeMake (CFStringGetLength (str), 0), appendString); } void CFStringAppendCharacters (CFMutableStringRef str, const UniChar * chars, CFIndex numChars) { if (CF_IS_OBJC (_kCFStringTypeID, str)) { // TODO: add a test for this branch CFStringRef wrapped; wrapped = CFStringCreateWithCharactersNoCopy (NULL, chars, numChars, kCFAllocatorNull); CF_OBJC_VOIDCALLV (str, "appendString:", wrapped); CFRelease (wrapped); return; } CFIndex length; void *contents; length = str->_count; if (CFStringCheckCapacityAndGrow (str, (length + numChars), &contents) && contents != str->_contents) { memcpy (str->_contents, contents, length * sizeof (UniChar)); CFAllocatorDeallocate (str->_deallocator, contents); } memcpy ((UniChar *) str->_contents + length, chars, numChars * sizeof (UniChar)); str->_count = length + numChars; } void CFStringAppendCString (CFMutableStringRef str, const char *cStr, CFStringEncoding encoding) { if (CF_IS_OBJC (_kCFStringTypeID, str)) { // TODO: add a test for this branch CFStringRef wrapped; wrapped = CFStringCreateWithCStringNoCopy (NULL, cStr, encoding, kCFAllocatorNull); CF_OBJC_VOIDCALLV (str, "appendString:", wrapped); CFRelease (wrapped); return; } UniChar b[BUFFER_SIZE]; UniChar *buffer; UniChar *bufferStart; const UInt8 *cStrStart; const UInt8 *cStrLimit; CFIndex numChars; buffer = b; bufferStart = b; cStrStart = (const UInt8 *) cStr; cStrLimit = (const UInt8 *) cStr + strlen (cStr); numChars = GSUnicodeFromEncoding (&buffer, buffer + BUFFER_SIZE, encoding, (const UInt8 **) &cStr, cStrLimit, 0); if (numChars <= BUFFER_SIZE) { CFStringAppendCharacters (str, bufferStart, numChars); } else { UniChar *tmp; UniChar *tmpStart; tmp = CFAllocatorAllocate (kCFAllocatorSystemDefault, numChars * sizeof (UniChar), 0); tmpStart = tmp; GSUnicodeFromEncoding (&tmp, tmp + numChars, encoding, (const UInt8 **) &cStrStart, cStrLimit, 0); CFStringAppendCharacters (str, tmpStart, numChars); } } void CFStringAppendFormat (CFMutableStringRef str, CFDictionaryRef options, CFStringRef format, ...) { va_list args; va_start (args, format); CFStringAppendFormatAndArguments (str, options, format, args); va_end (args); } void CFStringAppendFormatAndArguments (CFMutableStringRef str, CFDictionaryRef options, CFStringRef format, va_list args) { Boolean free_fmt_str = false; CFIndex str_len; CFIndex fmt_str_len; UniChar buf[BUFFER_SIZE]; UniChar *fmted_str = buf; const UniChar *fmt_str; fmt_str_len = CFStringGetLength (format); fmt_str = CFStringGetCharactersPtr (format); if (fmt_str == 0) { CFRange range; free_fmt_str = true; fmt_str = CFAllocatorAllocate (kCFAllocatorSystemDefault, fmt_str_len * sizeof (UniChar), 0); range = CFRangeMake (0, fmt_str_len); CFStringGetCharacters (format, range, (UniChar *) fmt_str); } str_len = GSUnicodeFormatWithArguments (fmted_str, BUFFER_SIZE, options, fmt_str, fmt_str_len, args); if (str_len > BUFFER_SIZE) { /* The buffer was not long enough for the formatted string, so we will * need to allocate a longer buffer and try again. */ fmted_str = CFAllocatorAllocate (kCFAllocatorSystemDefault, str_len * sizeof (UniChar), 0); str_len = GSUnicodeFormatWithArguments (fmted_str, str_len, options, fmt_str, fmt_str_len, args); } if (str_len < 0) return; CFStringAppendCharacters (str, (const UniChar *) fmted_str, str_len); if (free_fmt_str) CFAllocatorDeallocate (kCFAllocatorSystemDefault, (void *) fmt_str); if (fmted_str != buf) CFAllocatorDeallocate (kCFAllocatorSystemDefault, str); } void CFStringDelete (CFMutableStringRef str, CFRange range) { CFStringReplace (str, range, CFSTR ("")); } void CFStringInsert (CFMutableStringRef str, CFIndex idx, CFStringRef insertedStr) { CFStringReplace (str, CFRangeMake (idx, 0), insertedStr); } void CFStringPad (CFMutableStringRef str, CFStringRef padString, CFIndex length, CFIndex indexIntoPad) { if (CF_IS_OBJC (_kCFStringTypeID, str)) { // TODO: add a test for this branch CFStringRef padded; CF_OBJC_CALLV (CFStringRef, padded, str, "stringByPaddingToLength:withString:startingAtIndex:", length, padString, indexIntoPad); CF_OBJC_VOIDCALLV (str, "setString:", padded); return; } if (padString == NULL && length < CFStringGetLength (str)) /* truncating */ { ((UniChar *) str->_contents)[length] = 0x0000; str->_count = length; str->_hash = 0; } else { CFIndex padLength; UniChar *padContents; UniChar *contents; UniChar *end; if (!CFStringCheckCapacityAndGrow (str, length, (void **) &contents)) return; if (contents != str->_contents) { memcpy (str->_contents, contents, length * sizeof (UniChar)); CFAllocatorDeallocate (str->_deallocator, contents); } contents = ((UniChar *) str->_contents) + CFStringGetLength (str); end = ((UniChar *) str->_contents) + length; padLength = CFStringGetLength (padString); padContents = CFAllocatorAllocate (NULL, padLength * sizeof (UniChar), 0); CFStringGetCharacters (padString, CFRangeMake (0, padLength), padContents); while (contents < end) { *contents++ = padContents[indexIntoPad++]; if (indexIntoPad == padLength) indexIntoPad = 0; } CFAllocatorDeallocate (NULL, padContents); str->_count = length; str->_hash = 0; } } void CFStringReplace (CFMutableStringRef str, CFRange range, CFStringRef replacement) { CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, void, str, "replaceCharactersInRange:withString:", range, replacement); CFStringInlineBuffer buffer; CFIndex textLength; CFIndex repLength; CFIndex idx; UniChar *contents; textLength = CFStringGetLength (str); repLength = CFStringGetLength (replacement); if (repLength != range.length) { UniChar *moveFrom; UniChar *moveTo; UniChar *oldContents; CFIndex newLength; CFIndex moveLength; newLength = textLength - range.length + repLength; if (!CFStringCheckCapacityAndGrow (str, newLength, (void **) &oldContents)) return; if (oldContents != str->_contents) { memcpy (str->_contents, oldContents, range.location * sizeof (UniChar)); } moveFrom = (oldContents + range.location + range.length); moveTo = (((UniChar *) str->_contents) + range.location + repLength); moveLength = textLength - (range.location + range.length); memmove (moveTo, moveFrom, moveLength * sizeof (UniChar)); if (oldContents != str->_contents) CFAllocatorDeallocate (str->_deallocator, (void *) oldContents); textLength = newLength; } CFStringInitInlineBuffer (replacement, &buffer, CFRangeMake (0, repLength)); contents = (((UniChar *) str->_contents) + range.location); idx = 0; while (idx < repLength) { UniChar c = CFStringGetCharacterFromInlineBuffer (&buffer, idx++); *(contents++) = c; } str->_count = textLength; str->_hash = 0; } void CFStringReplaceAll (CFMutableStringRef theString, CFStringRef replacement) { CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, void, theString, "setString:", replacement); CFStringInlineBuffer buffer; CFIndex textLength; CFIndex idx; UniChar *contents; /* This function is very similar to CFStringReplace() but takes a few shortcuts and should be a little fast if all you need to do is replace the whole string. */ textLength = CFStringGetLength (replacement); if (!CFStringCheckCapacityAndGrow (theString, textLength + 1, NULL)) return; CFStringInitInlineBuffer (replacement, &buffer, CFRangeMake (0, textLength)); contents = (UniChar *) theString->_contents; idx = 0; while (idx < textLength) { UniChar c = CFStringGetCharacterFromInlineBuffer (&buffer, idx++); *(contents++) = c; } theString->_count = textLength; theString->_hash = 0; } void CFStringTrim (CFMutableStringRef str, CFStringRef trimString) { CFStringFindAndReplace (str, trimString, NULL, CFRangeMake (0, CFStringGetLength (str)), kCFCompareAnchored); CFStringFindAndReplace (str, trimString, NULL, CFRangeMake (0, CFStringGetLength (str)), kCFCompareBackwards | kCFCompareAnchored); } void CFStringTrimWhitespace (CFMutableStringRef str) { CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, void, str, "_cfTrimWhitespace"); CFStringInlineBuffer buffer; CFIndex start; CFIndex end; CFIndex textLength; CFIndex newLength; CFIndex idx; UniChar c; UniChar *contents; UniChar *contentsStart; /* I assume that the resulting string will be shorter than the original so no bounds checking is done. */ textLength = CFStringGetLength (str); CFStringInitInlineBuffer (str, &buffer, CFRangeMake (0, textLength)); idx = 0; c = CFStringGetCharacterFromInlineBuffer (&buffer, idx++); while (GSCharacterIsWhitespace (c) && idx < textLength) c = CFStringGetCharacterFromInlineBuffer (&buffer, idx++); start = idx - 1; end = start; while (idx < textLength) { c = CFStringGetCharacterFromInlineBuffer (&buffer, idx++); /* reset the end point */ if (!GSCharacterIsWhitespace (c)) end = idx; } newLength = end - start; contents = (UniChar *) str->_contents; contentsStart = (UniChar *) (contents + start); memmove (contents, contentsStart, newLength * sizeof (UniChar)); str->_count = newLength; str->_hash = 0; } enum { _kCFStringCapitalize, _kCFStringLowercase, _kCFStringUppercase, _kCFStringFold }; static void CFStringCaseMap (CFMutableStringRef str, CFLocaleRef locale, CFOptionFlags flags, CFIndex op) { #if HAVE_UNICODE_USTRING_H char *localeID = NULL; /* FIXME */ const UniChar *oldContents; CFIndex oldContentsLength; CFIndex newLength; int32_t optFlags; UErrorCode err = U_ZERO_ERROR; struct __CFMutableString *mStr = (struct __CFMutableString *) str; oldContents = CFStringGetCharactersPtr (str); oldContentsLength = CFStringGetLength (str); /* Loops a maximum of 2 times, and should never loop more than that. If it does have to go through the loop a 3rd time something is wrong and this whole thing will blow up. */ do { switch (op) { case _kCFStringCapitalize: newLength = u_strToTitle (mStr->_contents, mStr->_capacity, oldContents, oldContentsLength, NULL, localeID, &err); break; case _kCFStringLowercase: newLength = u_strToLower (mStr->_contents, mStr->_capacity, oldContents, oldContentsLength, localeID, &err); break; case _kCFStringUppercase: newLength = u_strToUpper (mStr->_contents, mStr->_capacity, oldContents, oldContentsLength, localeID, &err); break; case _kCFStringFold: optFlags = 0; /* FIXME */ newLength = u_strFoldCase (mStr->_contents, mStr->_capacity, oldContents, oldContentsLength, optFlags, &err); break; default: return; } } while (err == U_BUFFER_OVERFLOW_ERROR && CFStringCheckCapacityAndGrow (str, newLength, (void **) &oldContents)); if (U_FAILURE (err)) return; mStr->_count = newLength; mStr->_hash = 0; if (oldContents != mStr->_contents) CFAllocatorDeallocate (mStr->_allocator, (void *) oldContents); #else /* FIXME */ #endif } void CFStringCapitalize (CFMutableStringRef str, CFLocaleRef locale) { if (CF_IS_OBJC (_kCFStringTypeID, str)) { CFStringRef mod; CF_OBJC_CALLV (CFStringRef, mod, str, "capitalizedString"); CF_OBJC_VOIDCALLV (str, "setString:", mod); CFRelease (mod); } else CFStringCaseMap (str, locale, 0, _kCFStringCapitalize); } void CFStringLowercase (CFMutableStringRef str, CFLocaleRef locale) { if (CF_IS_OBJC (_kCFStringTypeID, str)) { CFStringRef mod; CF_OBJC_CALLV (CFStringRef, mod, str, "lowercaseString"); CF_OBJC_VOIDCALLV (str, "setString:", mod); CFRelease (mod); } else CFStringCaseMap (str, locale, 0, _kCFStringLowercase); } void CFStringUppercase (CFMutableStringRef str, CFLocaleRef locale) { if (CF_IS_OBJC (_kCFStringTypeID, str)) { CFStringRef mod; CF_OBJC_CALLV (CFStringRef, mod, str, "uppercaseString"); CF_OBJC_VOIDCALLV (str, "setString:", mod); CFRelease (mod); } else CFStringCaseMap (str, locale, 0, _kCFStringUppercase); } void CFStringFold (CFMutableStringRef str, CFOptionFlags flags, CFLocaleRef locale) { if (CF_IS_OBJC (_kCFStringTypeID, str)) { /* CFOptionFlags have the same insensitivity values * as NSStringCompareOptions. * CFLocaleRef is toll-free bridged*/ CFStringRef mod; CF_OBJC_CALLV (CFStringRef, mod, str, "stringByFoldingWithOptions:locale:", flags, locale); CF_OBJC_VOIDCALLV (str, "setString:", mod); CFRelease (mod); } else CFStringCaseMap (str, locale, flags, _kCFStringFold); } CF_INLINE const UNormalizer2 * CFToICUNormalizer (CFStringNormalizationForm form, UErrorCode *err) { switch (form) { case kCFStringNormalizationFormD: return unorm2_getNFDInstance(err); case kCFStringNormalizationFormKD: return unorm2_getNFKDInstance(err); case kCFStringNormalizationFormC: return unorm2_getNFCInstance(err); case kCFStringNormalizationFormKC: return unorm2_getNFKCInstance(err); default: return NULL; } } void CFStringNormalize (CFMutableStringRef str, CFStringNormalizationForm theForm) { #if !UCONFIG_NO_NORMALIZATION UniChar *oldContents; CFIndex oldContentsLength; CFIndex newLength; UNormalizationCheckResult checkResult; UErrorCode err = U_ZERO_ERROR; struct __CFMutableString *mStr; CFMutableStringRef objc = NULL; const UNormalizer2 *n2 = CFToICUNormalizer (theForm, &err); if (n2 == NULL || U_FAILURE (err)) return; /* Make sure string isn't already normalized. Use the quick check for speed. We still go through the normalization if the quick check does not return UNORM_YES. */ oldContents = (UniChar *) CFStringGetCharactersPtr (str); oldContentsLength = CFStringGetLength (str); if (oldContents != NULL) { checkResult = unorm2_quickCheck (n2, oldContents, oldContentsLength, &err); if (U_FAILURE (err) || checkResult == UNORM_YES) return; } if (CF_IS_OBJC (_kCFStringTypeID, str)) { objc = str; str = CFStringCreateMutableCopy (kCFAllocatorDefault, 0, objc); } /* unorm_normalize requires that source/dest buffers don't overlap */ mStr = (struct __CFMutableString *) str; oldContents = CFAllocatorAllocate (mStr->_allocator, oldContentsLength * sizeof (UniChar), 0); CFStringGetCharacters (str, CFRangeMake (0, oldContentsLength), oldContents); /* Works just like CFStringCaseMap() above... */ do { newLength = unorm2_normalize (n2, oldContents, oldContentsLength, mStr->_contents, mStr->_capacity, &err); } while (err == U_BUFFER_OVERFLOW_ERROR && CFStringCheckCapacityAndGrow (str, newLength, NULL)); if (U_FAILURE (err)) return; mStr->_count = newLength; if (oldContents != mStr->_contents) CFAllocatorDeallocate (mStr->_allocator, (void *) oldContents); if (objc != NULL) { CF_OBJC_VOIDCALLV (objc, "setString:", str); CFRelease (str); } #else /* FIXME */ #endif } Boolean CFStringTransform (CFMutableStringRef str, CFRange * range, CFStringRef transform, Boolean reverse) { #if !UCONFIG_NO_TRANSLITERATION #define UTRANS_LENGTH 128 struct __CFMutableString *mStr; UniChar transID[UTRANS_LENGTH]; CFIndex idLength; CFIndex newLength; CFIndex start; CFIndex limit; UTransliterator *utrans; UTransDirection dir; UErrorCode err = U_ZERO_ERROR; dir = reverse ? UTRANS_REVERSE : UTRANS_FORWARD; idLength = CFStringGetLength (transform); if (idLength > UTRANS_LENGTH) idLength = UTRANS_LENGTH; CFStringGetCharacters (transform, CFRangeMake (0, idLength), transID); utrans = utrans_openU (transID, idLength, dir, NULL, 0, NULL, &err); if (U_FAILURE (err)) return false; newLength = CFStringGetLength (str); if (range) { start = range->location; limit = range->length + start; } else { start = 0; limit = newLength; } if (CF_IS_OBJC (_kCFStringTypeID, str)) { mStr = (struct __CFMutableString *) CFStringCreateMutableCopy (kCFAllocatorDefault, 0, str); } else { mStr = (struct __CFMutableString *) str; } utrans_transUChars (utrans, mStr->_contents, (int32_t *) & mStr->_count, mStr->_capacity, start, (int32_t *) & limit, &err); utrans_close (utrans); if (((CFMutableStringRef) mStr) != str) /* ObjC case */ { CF_OBJC_VOIDCALLV (str, "setString:", mStr); CFRelease (mStr); } if (U_FAILURE (err)) return false; if (range) range->length = limit; return true; #else return false; #endif } gnustep-corebase-0.2/Source/CFNumberFormatter.c0000644000175000017500000006421014551015633020642 0ustar yavoryavor/* CFNumberFormatter.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: March, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFNumber.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFRuntime.h" #include "GSPrivate.h" #include "CoreFoundation/CFNumberFormatter.h" #if defined(HAVE_UNICODE_UCURR_H) #include #endif #if defined(HAVE_UNICODE_UNUM_H) #include #endif #if defined(HAVE_ICU_H) #include #endif #define BUFFER_SIZE 512 CONST_STRING_DECL(kCFNumberFormatterCurrencyCode, "kCFNumberFormatterCurrencyCode"); CONST_STRING_DECL(kCFNumberFormatterDecimalSeparator, "kCFNumberFormatterDecimalSeparator"); CONST_STRING_DECL(kCFNumberFormatterCurrencyDecimalSeparator, "kCFNumberFormatterCurrencyDecimalSeparator"); CONST_STRING_DECL(kCFNumberFormatterAlwaysShowDecimalSeparator, "kCFNumberFormatterAlwaysShowDecimalSeparator"); CONST_STRING_DECL(kCFNumberFormatterGroupingSeparator, "kCFNumberFormatterGroupingSeparator"); CONST_STRING_DECL(kCFNumberFormatterUseGroupingSeparator, "kCFNumberFormatterUseGroupingSeparator"); CONST_STRING_DECL(kCFNumberFormatterPercentSymbol, "kCFNumberFormatterPercentSymbol"); CONST_STRING_DECL(kCFNumberFormatterZeroSymbol, "kCFNumberFormatterZeroSymbol"); CONST_STRING_DECL(kCFNumberFormatterNaNSymbol, "kCFNumberFormatterNaNSymbol"); CONST_STRING_DECL(kCFNumberFormatterInfinitySymbol, "kCFNumberFormatterInfinitySymbol"); CONST_STRING_DECL(kCFNumberFormatterMinusSign, "kCFNumberFormatterMinusSign"); CONST_STRING_DECL(kCFNumberFormatterPlusSign, "kCFNumberFormatterPlusSign"); CONST_STRING_DECL(kCFNumberFormatterCurrencySymbol, "kCFNumberFormatterCurrencySymbol"); CONST_STRING_DECL(kCFNumberFormatterExponentSymbol, "kCFNumberFormatterExponentSymbol"); CONST_STRING_DECL(kCFNumberFormatterMinIntegerDigits, "kCFNumberFormatterMinIntegerDigits"); CONST_STRING_DECL(kCFNumberFormatterMaxIntegerDigits, "kCFNumberFormatterMaxIntegerDigits"); CONST_STRING_DECL(kCFNumberFormatterMinFractionDigits, "kCFNumberFormatterMinFractionDigits"); CONST_STRING_DECL(kCFNumberFormatterMaxFractionDigits, "kCFNumberFormatterMaxFractionDigits"); CONST_STRING_DECL(kCFNumberFormatterGroupingSize, "kCFNumberFormatterGroupingSize"); CONST_STRING_DECL(kCFNumberFormatterSecondaryGroupingSize, "kCFNumberFormatterSecondaryGroupingSize"); CONST_STRING_DECL(kCFNumberFormatterRoundingMode, "kCFNumberFormatterRoundingMode"); CONST_STRING_DECL(kCFNumberFormatterRoundingIncrement, "kCFNumberFormatterRoundingIncrement"); CONST_STRING_DECL(kCFNumberFormatterFormatWidth, "kCFNumberFormatterFormatWidth"); CONST_STRING_DECL(kCFNumberFormatterPaddingPosition, "kCFNumberFormatterPaddingPosition"); CONST_STRING_DECL(kCFNumberFormatterPaddingCharacter, "kCFNumberFormatterPaddingCharacter"); CONST_STRING_DECL(kCFNumberFormatterDefaultFormat, "kCFNumberFormatterDefaultFormat"); CONST_STRING_DECL(kCFNumberFormatterMultiplier, "kCFNumberFormatterMultiplier"); CONST_STRING_DECL(kCFNumberFormatterPositivePrefix, "kCFNumberFormatterPositivePrefix"); CONST_STRING_DECL(kCFNumberFormatterPositiveSuffix, "kCFNumberFormatterPositiveSuffix"); CONST_STRING_DECL(kCFNumberFormatterNegativePrefix, "kCFNumberFormatterNegativePrefix"); CONST_STRING_DECL(kCFNumberFormatterNegativeSuffix, "kCFNumberFormatterNegativeSuffix"); CONST_STRING_DECL(kCFNumberFormatterPerMillSymbol, "kCFNumberFormatterPerMillSymbol"); CONST_STRING_DECL(kCFNumberFormatterInternationalCurrencySymbol, "kCFNumberFormatterInternationalCurrencySymbol"); CONST_STRING_DECL(kCFNumberFormatterCurrencyGroupingSeparator, "kCFNumberFormatterCurrencyGroupingSeparator"); CONST_STRING_DECL(kCFNumberFormatterIsLenient, "kCFNumberFormatterIsLenient"); CONST_STRING_DECL(kCFNumberFormatterUseSignificantDigits, "kCFNumberFormatterUseSignificantDigits"); CONST_STRING_DECL(kCFNumberFormatterMinSignificantDigits, "kCFNumberFormatterMinSignificantDigits"); CONST_STRING_DECL(kCFNumberFormatterMaxSignificantDigits, "kCFNumberFormatterMaxSignificantDigits"); struct __CFNumberFormatter { CFRuntimeBase _parent; UNumberFormat *_fmt; CFLocaleRef _locale; CFNumberFormatterStyle _style; CFStringRef _defaultFormat; CFStringRef _format; }; static CFTypeID _kCFNumberFormatterTypeID; static CFTypeRef CFNumberFormatterCopy (CFAllocatorRef alloc, CFTypeRef cf) { UErrorCode err = U_ZERO_ERROR; CFNumberFormatterRef o = (CFNumberFormatterRef)cf; struct __CFNumberFormatter *copy = (struct __CFNumberFormatter *)_CFRuntimeCreateInstance (alloc, CFNumberFormatterGetTypeID(), sizeof(struct __CFNumberFormatter) - sizeof(CFRuntimeBase), NULL); copy->_fmt = unum_clone (o->_fmt, &err); if (U_FAILURE(err)) { CFRelease (copy); return NULL; } copy->_locale = CFRetain (o->_locale); copy->_style = o->_style; copy->_defaultFormat = CFRetain (o->_defaultFormat); copy->_format = CFRetain (o->_format); return copy; } static void CFNumberFormatterFinalize (CFTypeRef cf) { struct __CFNumberFormatter *o = (struct __CFNumberFormatter *)cf; unum_close (o->_fmt); CFRelease (o->_defaultFormat); CFRelease (o->_format); } static const CFRuntimeClass CFNumberFormatterClass = { 0, "CFNumberFormatter", NULL, CFNumberFormatterCopy, CFNumberFormatterFinalize, NULL, NULL, NULL, NULL }; void CFNumberFormatterInitialize (void) { _kCFNumberFormatterTypeID = _CFRuntimeRegisterClass(&CFNumberFormatterClass); } static void CFNumberFormatterSetAttribute (CFNumberFormatterRef fmt, int attrib, CFTypeRef num) { int32_t value; double d; switch (attrib) { case UNUM_GROUPING_USED: case UNUM_DECIMAL_ALWAYS_SHOWN: case UNUM_SIGNIFICANT_DIGITS_USED: case UNUM_LENIENT_PARSE: value = (num == kCFBooleanTrue) ? true : false; unum_setAttribute (fmt->_fmt, attrib, value); return; case UNUM_ROUNDING_INCREMENT: CFNumberGetValue (num, kCFNumberDoubleType, &d); unum_setDoubleAttribute (fmt->_fmt, UNUM_ROUNDING_INCREMENT, d); return; default: CFNumberGetValue (num, kCFNumberSInt32Type, &value); unum_setAttribute (fmt->_fmt, attrib, value); return; } } static void CFNumberFormatterSetTextAttribute (CFNumberFormatterRef fmt, int attrib, CFTypeRef str) { int32_t len; UChar ubuffer[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; len = CFStringGetLength (str); if (len > BUFFER_SIZE) len = BUFFER_SIZE; CFStringGetCharacters (str, CFRangeMake(0, len), ubuffer); unum_setTextAttribute (fmt->_fmt, attrib, ubuffer, len, &err); } static void CFNumberFormatterSetSymbol (CFNumberFormatterRef fmt, int symbol, CFTypeRef str) { int32_t len; UChar ubuffer[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; len = CFStringGetLength (str); if (len > BUFFER_SIZE) len = BUFFER_SIZE; CFStringGetCharacters (str, CFRangeMake(0, len), ubuffer); unum_setSymbol (fmt->_fmt, symbol, ubuffer, len, &err); } static CFTypeRef CFNumberFormatterCopyAttribute (CFNumberFormatterRef fmt, int attrib) { int32_t num; double d; switch (attrib) { case UNUM_GROUPING_USED: case UNUM_DECIMAL_ALWAYS_SHOWN: case UNUM_SIGNIFICANT_DIGITS_USED: case UNUM_LENIENT_PARSE: num = unum_getAttribute (fmt->_fmt, attrib); switch (num) { case 0: return kCFBooleanTrue; case 1: return kCFBooleanFalse; } case UNUM_ROUNDING_INCREMENT: d = unum_getDoubleAttribute (fmt->_fmt, attrib); return CFNumberCreate (NULL, kCFNumberDoubleType, (const void*)&d); default: num = unum_getAttribute (fmt->_fmt, attrib); return CFNumberCreate (NULL, kCFNumberSInt32Type, (const void*)&num); } } static CFTypeRef CFNumberFormatterCopyTextAttribute (CFNumberFormatterRef fmt, int attrib) { int32_t len; UChar ubuffer[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; len = unum_getTextAttribute (fmt->_fmt, attrib, ubuffer, BUFFER_SIZE, &err); if (len > BUFFER_SIZE) len = BUFFER_SIZE; return CFStringCreateWithCharacters (NULL, ubuffer, len); } static CFTypeRef CFNumberFormatterCopySymbol (CFNumberFormatterRef fmt, int symbol) { int32_t len; UChar ubuffer[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; len = unum_getSymbol (fmt->_fmt, symbol, ubuffer, BUFFER_SIZE, &err); if (len > BUFFER_SIZE) len = BUFFER_SIZE; return CFStringCreateWithCharacters (NULL, ubuffer, len); } static CFTypeRef CFNumberFormatterCopyDefaultFormat (CFNumberFormatterRef fmt, int attrib) { return CFRetain (fmt->_defaultFormat); } static struct _kCFNumberFormatterProperties { const CFStringRef *prop; int icuProp; void (*set)(CFNumberFormatterRef fmt, int attrib, CFTypeRef value); CFTypeRef (*copy)(CFNumberFormatterRef fmt, int attrib); } _kCFNumberFormatterProperties[] = { { &kCFNumberFormatterDefaultFormat, 0, NULL, CFNumberFormatterCopyDefaultFormat }, { &kCFNumberFormatterCurrencyCode, UNUM_CURRENCY_CODE, CFNumberFormatterSetTextAttribute, CFNumberFormatterCopyTextAttribute }, { &kCFNumberFormatterDecimalSeparator, UNUM_DECIMAL_SEPARATOR_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterCurrencyDecimalSeparator, UNUM_MONETARY_GROUPING_SEPARATOR_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterAlwaysShowDecimalSeparator, UNUM_DECIMAL_ALWAYS_SHOWN, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterGroupingSeparator, UNUM_GROUPING_SEPARATOR_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterUseGroupingSeparator, UNUM_GROUPING_USED, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterPercentSymbol, UNUM_PERCENT_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterZeroSymbol, UNUM_ZERO_DIGIT_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterNaNSymbol, UNUM_NAN_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterInfinitySymbol, UNUM_INFINITY_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterMinusSign, UNUM_MINUS_SIGN_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterPlusSign, UNUM_PLUS_SIGN_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterCurrencySymbol, UNUM_CURRENCY_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterExponentSymbol, UNUM_EXPONENTIAL_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterMinIntegerDigits, UNUM_MIN_INTEGER_DIGITS, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterMaxIntegerDigits, UNUM_MAX_INTEGER_DIGITS, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterMinFractionDigits, UNUM_MIN_FRACTION_DIGITS, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterMaxFractionDigits, UNUM_MAX_FRACTION_DIGITS, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterGroupingSize, UNUM_GROUPING_SIZE, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterSecondaryGroupingSize, UNUM_SECONDARY_GROUPING_SIZE, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterRoundingMode, UNUM_ROUNDING_MODE, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterRoundingIncrement, UNUM_ROUNDING_INCREMENT, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterFormatWidth, UNUM_FORMAT_WIDTH, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterPaddingPosition, UNUM_PADDING_POSITION, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterPaddingCharacter, UNUM_PADDING_CHARACTER, CFNumberFormatterSetTextAttribute, CFNumberFormatterCopyTextAttribute }, { &kCFNumberFormatterDefaultFormat, UNUM_MULTIPLIER, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterMultiplier, UNUM_MULTIPLIER, CFNumberFormatterSetTextAttribute, CFNumberFormatterCopyTextAttribute }, { &kCFNumberFormatterPositivePrefix, UNUM_POSITIVE_PREFIX, CFNumberFormatterSetTextAttribute, CFNumberFormatterCopyTextAttribute }, { &kCFNumberFormatterPositiveSuffix, UNUM_POSITIVE_SUFFIX, CFNumberFormatterSetTextAttribute, CFNumberFormatterCopyTextAttribute }, { &kCFNumberFormatterNegativePrefix, UNUM_NEGATIVE_PREFIX, CFNumberFormatterSetTextAttribute, CFNumberFormatterCopyTextAttribute }, { &kCFNumberFormatterNegativeSuffix, UNUM_NEGATIVE_SUFFIX, CFNumberFormatterSetTextAttribute, CFNumberFormatterCopyTextAttribute }, { &kCFNumberFormatterPerMillSymbol, UNUM_PERMILL_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterInternationalCurrencySymbol, UNUM_INTL_CURRENCY_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterCurrencyGroupingSeparator, UNUM_MONETARY_SEPARATOR_SYMBOL, CFNumberFormatterSetSymbol, CFNumberFormatterCopySymbol }, { &kCFNumberFormatterIsLenient, UNUM_LENIENT_PARSE, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterUseSignificantDigits, UNUM_SIGNIFICANT_DIGITS_USED, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterMinSignificantDigits, UNUM_MIN_SIGNIFICANT_DIGITS, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute }, { &kCFNumberFormatterMaxSignificantDigits, UNUM_MAX_SIGNIFICANT_DIGITS, CFNumberFormatterSetAttribute, CFNumberFormatterCopyAttribute } }; static const CFIndex _kCFNumberFormatterPropertiesSize = sizeof(_kCFNumberFormatterProperties) / sizeof(struct _kCFNumberFormatterProperties); CFNumberFormatterRef CFNumberFormatterCreate (CFAllocatorRef allocator, CFLocaleRef loc, CFNumberFormatterStyle style) { struct __CFNumberFormatter *new; const char *cLocale; char buffer[ULOC_FULLNAME_CAPACITY]; int32_t len; UChar ubuffer[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; if (loc == NULL) loc = CFLocaleGetSystem (); cLocale = CFLocaleGetCStringIdentifier (loc, buffer, ULOC_FULLNAME_CAPACITY); new = (struct __CFNumberFormatter *)_CFRuntimeCreateInstance (allocator, CFNumberFormatterGetTypeID(), sizeof(struct __CFNumberFormatter) - sizeof(CFRuntimeBase), NULL); if (new == NULL) return NULL; /* Good news, UNumberFormatStyle and NS/CFNumberFormatterStyle match. */ new->_fmt = unum_open ((UNumberFormatStyle )style, NULL, 0, cLocale, NULL, &err); if (U_FAILURE(err)) { CFRelease (new); return NULL; } new->_locale = CFRetain(loc); new->_style = style; if (style == kCFNumberFormatterNoStyle) { ubuffer[0] = '#'; new->_defaultFormat = CFStringCreateWithCharacters (allocator, ubuffer, 1); unum_applyPattern (new->_fmt, false, ubuffer, 1, NULL, &err); } else if (style == kCFNumberFormatterSpellOutStyle) { len = unum_getTextAttribute (new->_fmt, UNUM_DEFAULT_RULESET, ubuffer, BUFFER_SIZE, &err); if (len > BUFFER_SIZE) len = BUFFER_SIZE; new->_defaultFormat = CFStringCreateWithCharacters (allocator, ubuffer, len); } else { len = unum_toPattern (new->_fmt, false, ubuffer, BUFFER_SIZE, &err); if (len > BUFFER_SIZE) len = BUFFER_SIZE; new->_defaultFormat = CFStringCreateWithCharacters (allocator, ubuffer, len); } new->_format = CFRetain (new->_defaultFormat); return new; } void CFNumberFormatterSetFormat (CFNumberFormatterRef fmt, CFStringRef formatString) { UniChar buffer[BUFFER_SIZE]; CFIndex len; UErrorCode err = U_ZERO_ERROR; len = CFStringGetLength (formatString); if (len > BUFFER_SIZE) len = BUFFER_SIZE; /* Apple recommends using an in-line buffer if there are a lot of characters. I'll assume this won't be a problem here. */ CFStringGetCharacters (formatString, CFRangeMake(0, len), buffer); unum_applyPattern (fmt->_fmt, false, buffer, len, NULL, &err); if (U_FAILURE(err)) return; if (fmt->_format) CFRelease (fmt->_format); fmt->_format = CFRetain (formatString); } void CFNumberFormatterSetProperty (CFNumberFormatterRef fmt, CFStringRef key, CFTypeRef value) { CFIndex idx; for (idx = 0 ; idx < _kCFNumberFormatterPropertiesSize ; ++idx) { if (key == *(_kCFNumberFormatterProperties[idx].prop)) { (_kCFNumberFormatterProperties[idx].set)(fmt, _kCFNumberFormatterProperties[idx].icuProp, value); return; } } for (idx = 0 ; idx < _kCFNumberFormatterPropertiesSize ; ++idx) { if (CFEqual(key, *(_kCFNumberFormatterProperties[idx].prop))) { (_kCFNumberFormatterProperties[idx].set)(fmt, _kCFNumberFormatterProperties[idx].icuProp, value); return; } } } CFNumberRef CFNumberFormatterCreateNumberFromString (CFAllocatorRef allocator, CFNumberFormatterRef fmt, CFStringRef str, CFRange *rangep, CFOptionFlags options) { CFNumberRef result; CFNumberType type; UInt8 value[sizeof(double)]; /* FIXME: what's the largest value we have? */ type = (options == kCFNumberFormatterParseIntegersOnly) ? kCFNumberSInt64Type : kCFNumberFloat64Type; if (CFNumberFormatterGetValueFromString (fmt, str, rangep, type, value)) result = CFNumberCreate (allocator, type, (const void *)value); else result = NULL; return result; } CFStringRef CFNumberFormatterCreateStringWithNumber (CFAllocatorRef allocator, CFNumberFormatterRef fmt, CFNumberRef number) { UInt8 value[sizeof(double)]; /* FIXME */ CFNumberType type = CFNumberGetType (number); if (CFNumberGetValue (number, type, value)) return CFNumberFormatterCreateStringWithValue (allocator, fmt, type, (const void*)value); return NULL; } CFStringRef CFNumberFormatterCreateStringWithValue (CFAllocatorRef allocator, CFNumberFormatterRef fmt, CFNumberType numberType, const void *valuePtr) { UChar ubuffer[BUFFER_SIZE]; int32_t len; int64_t inum = 0; double dnum = 0.0; UErrorCode err = U_ZERO_ERROR; switch (numberType) { case kCFNumberSInt8Type: inum = (int64_t)*(SInt8*)valuePtr; break; case kCFNumberSInt16Type: inum = (int64_t)*(SInt16*)valuePtr; break; case kCFNumberSInt32Type: inum = (int64_t)*(SInt32*)valuePtr; break; case kCFNumberSInt64Type: inum = (int64_t)*(SInt64*)valuePtr; break; case kCFNumberCharType: inum = (int64_t)*(char*)valuePtr; break; case kCFNumberShortType: inum = (int64_t)*(short*)valuePtr; break; case kCFNumberIntType: inum = (int64_t)*(int*)valuePtr; break; case kCFNumberLongType: inum = (int64_t)*(long*)valuePtr; break; case kCFNumberLongLongType: inum = (int64_t)*(long long*)valuePtr; break; case kCFNumberCFIndexType: inum = (int64_t)*(CFIndex*)valuePtr; break; case kCFNumberNSIntegerType: /* FIXME: This isn't defined in CF, so guess */ inum = (int64_t)*(CFIndex*)valuePtr; break; case kCFNumberFloat32Type: dnum = (double)*(Float32*)valuePtr; break; case kCFNumberFloat64Type: dnum = (double)*(Float64*)valuePtr; break; case kCFNumberFloatType: dnum = (double)*(float*)valuePtr; break; case kCFNumberDoubleType: dnum = *(double*)valuePtr; break; case kCFNumberCGFloatType: /* FIXME: Guess here, too */ dnum = *(double*)valuePtr; break; } switch (numberType) { case kCFNumberSInt8Type: case kCFNumberSInt16Type: case kCFNumberSInt32Type: case kCFNumberSInt64Type: case kCFNumberCharType: case kCFNumberShortType: case kCFNumberIntType: case kCFNumberLongType: case kCFNumberLongLongType: case kCFNumberCFIndexType: case kCFNumberNSIntegerType: len = unum_formatInt64 (fmt->_fmt, inum, ubuffer, BUFFER_SIZE, NULL, &err); break; default: /* must be a float type */ len = unum_formatDouble (fmt->_fmt, dnum, ubuffer, BUFFER_SIZE, NULL, &err); } if (U_FAILURE(err)) return NULL; if (len > BUFFER_SIZE) len = BUFFER_SIZE; return CFStringCreateWithCharacters (allocator, ubuffer, len); } Boolean CFNumberFormatterGetDecimalInfoForCurrencyCode (CFStringRef currencyCode, int32_t *defaultFractionDigits, double *roundingIncrement) { CFIndex len; UChar ubuffer[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; len = CFStringGetLength (currencyCode); if (len > BUFFER_SIZE) len = BUFFER_SIZE; CFStringGetCharacters (currencyCode, CFRangeMake(0, len), ubuffer); *defaultFractionDigits = ucurr_getDefaultFractionDigits (ubuffer, &err); *roundingIncrement = ucurr_getRoundingIncrement (ubuffer, &err); if (U_SUCCESS(err)) return true; return false; } Boolean CFNumberFormatterGetValueFromString (CFNumberFormatterRef fmt, CFStringRef string, CFRange *rangep, CFNumberType numberType, void *valuePtr) { CFRange parseRange; UniChar ubuffer[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; int32_t parsePos; double dresult = 0.0; int64_t iresult = 0; /* Keep compiler happy */ if (rangep) { parseRange = *rangep; } else { parseRange.location = 0; parseRange.length = CFStringGetLength (string); } if (parseRange.length > BUFFER_SIZE) parseRange.length = BUFFER_SIZE; CFStringGetCharacters (string, parseRange, ubuffer); parsePos = 0; switch (numberType) { case kCFNumberSInt8Type: case kCFNumberSInt16Type: case kCFNumberSInt32Type: case kCFNumberSInt64Type: case kCFNumberCharType: case kCFNumberShortType: case kCFNumberIntType: case kCFNumberLongType: case kCFNumberLongLongType: case kCFNumberCFIndexType: case kCFNumberNSIntegerType: iresult = unum_parseInt64 (fmt->_fmt, ubuffer, parseRange.length, &parsePos, &err); break; default: /* must be a float type */ dresult = unum_parseDouble (fmt->_fmt, ubuffer, parseRange.length, &parsePos, &err); } if (U_FAILURE(err)) return false; switch (numberType) { case kCFNumberSInt8Type: *(SInt8*)valuePtr = (SInt8)iresult; break; case kCFNumberSInt16Type: *(SInt16*)valuePtr = (SInt16)iresult; break; case kCFNumberSInt32Type: *(SInt32*)valuePtr = (SInt32)iresult; break; case kCFNumberSInt64Type: *(SInt64*)valuePtr = (SInt64)iresult; break; case kCFNumberCharType: *(char*)valuePtr = (char)iresult; break; case kCFNumberShortType: *(short*)valuePtr = (short)iresult; break; case kCFNumberIntType: *(int*)valuePtr = (int)iresult; break; case kCFNumberLongType: *(long*)valuePtr = (long)iresult; break; case kCFNumberLongLongType: *(long long*)valuePtr = (long long)iresult; break; case kCFNumberCFIndexType: *(CFIndex*)valuePtr = (CFIndex)iresult; break; case kCFNumberNSIntegerType: /* FIXME: This isn't defined in CF, so guess */ *(CFIndex*)valuePtr = (CFIndex)iresult; break; case kCFNumberFloat32Type: *(Float32*)valuePtr = (Float32)dresult; break; case kCFNumberFloat64Type: *(Float64*)valuePtr = (Float64)dresult; break; case kCFNumberFloatType: *(float*)valuePtr = (float)dresult; break; case kCFNumberDoubleType: *(double*)valuePtr = (double)dresult; break; case kCFNumberCGFloatType: /* FIXME: Guess here, too */ *(double*)valuePtr = (double)dresult; break; } if (rangep && parseRange.length != parsePos) { rangep->length = parsePos; return false; } return true; } CFTypeRef CFNumberFormatterCopyProperty (CFNumberFormatterRef fmt, CFStringRef key) { CFIndex idx; for (idx = 0 ; idx < _kCFNumberFormatterPropertiesSize ; ++idx) { if (key == *(_kCFNumberFormatterProperties[idx].prop)) return (_kCFNumberFormatterProperties[idx].copy)(fmt, _kCFNumberFormatterProperties[idx].icuProp); } for (idx = 0 ; idx < _kCFNumberFormatterPropertiesSize ; ++idx) { if (CFEqual(key, *(_kCFNumberFormatterProperties[idx].prop))) return (_kCFNumberFormatterProperties[idx].copy)(fmt, _kCFNumberFormatterProperties[idx].icuProp); } return NULL; } CFStringRef CFNumberFormatterGetFormat (CFNumberFormatterRef fmt) { return (fmt->_format) ? fmt->_format : fmt->_defaultFormat; } CFLocaleRef CFNumberFormatterGetLocale (CFNumberFormatterRef fmt) { return fmt->_locale; } CFNumberFormatterStyle CFNumberFormatterGetStyle (CFNumberFormatterRef fmt) { return fmt->_style; } CFTypeID CFNumberFormatterGetTypeID (void) { return _kCFNumberFormatterTypeID; } gnustep-corebase-0.2/Source/NSCFDictionary.m0000644000175000017500000001163513222706330020104 0ustar yavoryavor/* NSCFDictionary.m Copyright (C) 2013 Free Software Foundation, Inc. Written by: Lubos Dolezel Date: March, 2013 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #import #include "NSCFType.h" #include "CoreFoundation/CFDictionary.h" @interface NSCFDictionary : NSMutableDictionary NSCFTYPE_VARS @end @interface NSDictionary (CoreBaseAdditions) - (CFTypeID) _cfTypeID; - (CFIndex) _cfCountOfValue: (id)value; @end @interface NSMutableDictionary (CoreBaseAdditions) - (void) _cfSetValue: (id)key : (id)value; - (void) _cfReplaceValue: (id)key : (id)value; @end @implementation NSCFDictionary + (void) load { NSCFInitialize (); } + (void) initialize { GSObjCAddClassBehavior (self, [NSCFType class]); } - (id) initWithObjects: (const id[])objects forKeys: (const id[])keys count: (NSUInteger)count { RELEASE(self); self = (NSCFDictionary*) CFDictionaryCreate(kCFAllocatorDefault, (const void **) keys, (const void **) objects, count, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); return self; } - (id) initWithCapacity: (NSUInteger)numItems { RELEASE(self); self = (NSCFDictionary*) CFDictionaryCreateMutable(kCFAllocatorDefault, numItems, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); return self; } - (NSUInteger) count { return CFDictionaryGetCount((CFDictionaryRef) self); } - (NSEnumerator*) keyEnumerator { CFIndex count; const void **keys; NSArray *array; count = CFDictionaryGetCount((CFDictionaryRef) self); keys = (const void**) malloc(sizeof(void*) * count); CFDictionaryGetKeysAndValues((CFDictionaryRef) self, keys, NULL); array = [NSArray arrayWithObjects: (const id*)keys count: count]; free((void*)keys); return [array objectEnumerator]; } - (id) objectForKey: (id)aKey { return (id) CFDictionaryGetValue((CFDictionaryRef) self, aKey); } - (NSEnumerator*) objectEnumerator { CFIndex count; const void **values; NSArray *array; count = CFDictionaryGetCount((CFDictionaryRef) self); values = (const void**) malloc(sizeof(void*) * count); CFDictionaryGetKeysAndValues((CFDictionaryRef) self, NULL, values); array = [NSArray arrayWithObjects: (const id*)values count: count]; free((void*)values); return [array objectEnumerator]; } - (NSUInteger) countByEnumeratingWithState: (NSFastEnumerationState*)state objects: (id[])stackbuf count: (NSUInteger)len { NSEnumerator *enuM = [self keyEnumerator]; return [enuM countByEnumeratingWithState: state objects: stackbuf count: len]; } - (void) setObject: anObject forKey: (id)aKey { CFDictionarySetValue((CFMutableDictionaryRef) self, aKey, anObject); } - (void) removeObjectForKey: (id)aKey { CFDictionaryRemoveValue((CFMutableDictionaryRef) self, aKey); } - (void) removeAllObjects { CFDictionaryRemoveAllValues((CFMutableDictionaryRef) self); } @end @implementation NSDictionary (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFDictionaryGetTypeID(); } - (CFIndex) _cfCountOfValue: (id)value { CFIndex countOfValue = 0; CFIndex i; NSUInteger count; NSArray* array; // TODO: getObjects:andKeys: could be faster (less calls) array = [self allValues]; count = [self count]; for (i = 0; i < count; i++) { if ([[array objectAtIndex: i] isEqual: value]) countOfValue++; } return countOfValue; } @end @implementation NSMutableDictionary (CoreBaseAdditions) - (void) _cfSetValue: (id)key : (id)value { [self removeObjectForKey: key]; [self setObject: value forKey: key]; } - (void) _cfReplaceValue: (id)key : (id)value { if ([self objectForKey: key] != NULL) { [self removeObjectForKey: key]; [self setObject: value forKey: key]; } } @end gnustep-corebase-0.2/Source/NSCFTimeZone.m0000644000175000017500000001246213222706330017530 0ustar yavoryavor/* NSCFTimeZone.m Copyright (C) 2013 Free Software Foundation, Inc. Written by: Lubos Dolezel Date: March, 2013 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #import #include "NSCFType.h" #include "CoreFoundation/CFTimeZone.h" @interface NSCFTimeZone : NSTimeZone NSCFTYPE_VARS @end @interface NSTimeZone (CoreBaseAdditions) - (CFTypeID) _cfTypeID; - (NSString*) _cfCopyAbbreviation: (CFAbsoluteTime)at; - (NSTimeInterval) _cfGetDaylightSavingTimeOffset: (CFAbsoluteTime)at; - (Boolean) _cfIsDaylightSavingTime: (CFAbsoluteTime)at; - (NSTimeInterval) _cfGetSecondsFromGMT: (CFAbsoluteTime)at; - (CFAbsoluteTime) _cfGetNextDaylightSavingTimeTransition: (CFAbsoluteTime)at; @end //#if 0 @implementation NSCFTimeZone + (void) load { NSCFInitialize (); } + (void) initialize { GSObjCAddClassBehavior (self, [NSCFType class]); } - (id)initWithName:(NSString *)tzName data:(NSData *)data { RELEASE(self); if (data != NULL) { self = (NSCFTimeZone*) CFTimeZoneCreate(NULL, (CFStringRef) tzName, (CFDataRef) data); } else { self = (NSCFTimeZone*) CFTimeZoneCreateWithName(NULL, (CFStringRef) tzName, YES); } return self; } - (NSString*) name { return (NSString*) CFTimeZoneGetName((CFTimeZoneRef) self); } - (NSData *)data { return (NSData*) CFTimeZoneGetData((CFTimeZoneRef) self); } - (NSInteger) secondsFromGMTForDate: (NSDate*)aDate { CFAbsoluteTime at = [aDate timeIntervalSince1970] - kCFAbsoluteTimeIntervalSince1970; return CFTimeZoneGetSecondsFromGMT((CFTimeZoneRef) self, at); } - (NSString *)abbreviationForDate:(NSDate *)aDate { NSString *abbr; CFAbsoluteTime at = [aDate timeIntervalSince1970] - kCFAbsoluteTimeIntervalSince1970; abbr = (NSString*) CFTimeZoneCopyAbbreviation((CFTimeZoneRef) self, at); AUTORELEASE(abbr); return abbr; } - (NSString *)localizedName:(NSTimeZoneNameStyle)style locale:(NSLocale *)locale { NSString *str; str = (NSString*) CFTimeZoneCopyLocalizedName((CFTimeZoneRef) self, (CFTimeZoneNameStyle)style, (CFLocaleRef)locale); AUTORELEASE(str); return str; } - (NSDate *)nextDaylightSavingTimeTransitionAfterDate:(NSDate *)aDate { CFAbsoluteTime at; at = [aDate timeIntervalSince1970] - kCFAbsoluteTimeIntervalSince1970; at = CFTimeZoneGetNextDaylightSavingTimeTransition((CFTimeZoneRef) self, at); return [NSDate dateWithTimeIntervalSince1970: at + kCFAbsoluteTimeIntervalSince1970]; } - (BOOL)isDaylightSavingTimeForDate:(NSDate *)aDate { CFAbsoluteTime at; at = [aDate timeIntervalSince1970] - kCFAbsoluteTimeIntervalSince1970; return CFTimeZoneIsDaylightSavingTime((CFTimeZoneRef) self, at); } - (NSTimeInterval)daylightSavingTimeOffsetForDate:(NSDate *)aDate { CFAbsoluteTime at; at = [aDate timeIntervalSince1970] - kCFAbsoluteTimeIntervalSince1970; return CFTimeZoneGetDaylightSavingTimeOffset((CFTimeZoneRef) self, at); } @end //#endif @implementation NSTimeZone (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFTimeZoneGetTypeID(); } - (NSString*) _cfCopyAbbreviation: (CFAbsoluteTime)at { NSString *abbr; NSDate *date; date = [NSDate dateWithTimeIntervalSince1970: at + kCFAbsoluteTimeIntervalSince1970]; abbr = [self abbreviationForDate: date]; RETAIN(abbr); return abbr; } - (NSTimeInterval) _cfGetDaylightSavingTimeOffset: (CFAbsoluteTime)at { NSDate *date; date = [NSDate dateWithTimeIntervalSince1970: at + kCFAbsoluteTimeIntervalSince1970]; return [self daylightSavingTimeOffsetForDate: date]; } - (Boolean) _cfIsDaylightSavingTime: (CFAbsoluteTime)at { NSDate *date; date = [NSDate dateWithTimeIntervalSince1970: at + kCFAbsoluteTimeIntervalSince1970]; return [self isDaylightSavingTimeForDate: date]; } - (NSTimeInterval) _cfGetSecondsFromGMT: (CFAbsoluteTime)at { NSDate *date; date = [NSDate dateWithTimeIntervalSince1970: at + kCFAbsoluteTimeIntervalSince1970]; return (NSTimeInterval) [self secondsFromGMTForDate: date]; } - (CFAbsoluteTime) _cfGetNextDaylightSavingTimeTransition: (CFAbsoluteTime)at { NSDate *date; date = [NSDate dateWithTimeIntervalSince1970: at + kCFAbsoluteTimeIntervalSince1970]; date = [self nextDaylightSavingTimeTransitionAfterDate: date]; return [date timeIntervalSince1970] - kCFAbsoluteTimeIntervalSince1970; } - (BOOL)isEqualToTimeZone:(NSTimeZone *)aTimeZone { return [[self name] isEqual: [aTimeZone name]]; } @end gnustep-corebase-0.2/Source/CFTimeZone.c0000644000175000017500000005265714551015633017274 0ustar yavoryavor/* CFTimeZone.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: April, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFByteOrder.h" #include "CoreFoundation/CFArray.h" #include "CoreFoundation/CFDictionary.h" #include "CoreFoundation/CFData.h" #include "CoreFoundation/CFDate.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFTimeZone.h" #include "CoreFoundation/CFURL.h" #include "CoreFoundation/CFURLAccess.h" #include "CoreFoundation/CFRuntime.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" #include "tzfile.h" #include #include #if defined(HAVE_UNICODE_UCAL_H) #include #endif #if defined(HAVE_ICU_H) #include #endif struct _ttinfo { SInt32 offset; UInt8 isdst; UInt8 abbr_idx; } __attribute__((packed)); typedef struct { SInt32 transition; SInt16 offset; UInt8 isDST; UInt8 abbrevIdx; } TransInfo; struct __CFTimeZone { CFRuntimeBase _parent; CFStringRef _name; /* The Olson name */ CFDataRef _data; CFIndex _abbrevCount; CFStringRef *_abbrevs; CFIndex _transCount; TransInfo *_transitions; }; static CFTypeID _kCFTimeZoneTypeID = 0; static GSMutex _kCFTimeZoneCacheLock; static CFMutableDictionaryRef _kCFTimeZoneCache = NULL; static CFTimeZoneRef _kCFTimeZoneDefault = NULL; static CFTimeZoneRef _kCFTimeZoneSystem = NULL; static CFDictionaryRef _kCFTimeZoneAbbreviationDictionary = NULL; static void CFTimeZoneFinalize (CFTypeRef cf) { CFIndex i; CFAllocatorRef alloc; CFTimeZoneRef tz = (CFTimeZoneRef)cf; alloc = CFGetAllocator (tz); CFRelease (tz->_name); CFRelease (tz->_data); for (i = 0 ; i < tz->_abbrevCount ; ++i) CFRelease (tz->_abbrevs[i]); CFAllocatorDeallocate (alloc, tz->_transitions); } static CFRuntimeClass CFTimeZoneClass = { 0, "CFTimeZone", NULL, NULL, CFTimeZoneFinalize, NULL, NULL, NULL, NULL }; void CFTimeZoneInitialize (void) { _kCFTimeZoneTypeID = _CFRuntimeRegisterClass (&CFTimeZoneClass); GSMutexInitialize (&_kCFTimeZoneCacheLock); } CFTypeID CFTimeZoneGetTypeID (void) { return _kCFTimeZoneTypeID; } #define CFTIMEZONE_SIZE sizeof(struct __CFTimeZone) - sizeof(CFRuntimeBase) CFTimeZoneRef CFTimeZoneCreate (CFAllocatorRef alloc, CFStringRef name, CFDataRef data) { const UInt8 *bytes; const UInt8 *endOfBytes; const struct tzhead *header; SInt32 tzh_timecnt; SInt32 tzh_typecnt; SInt32 tzh_charcnt; UInt32 *tmp; struct __CFTimeZone *new; CFTimeZoneRef old; if (_kCFTimeZoneCache == NULL) { GSMutexLock(&_kCFTimeZoneCacheLock); /* Double check the cache is still NULL. */ if (_kCFTimeZoneCache == NULL) _kCFTimeZoneCache = CFDictionaryCreateMutable ( kCFAllocatorSystemDefault, 0, &kCFCopyStringDictionaryKeyCallBacks, NULL); GSMutexUnlock(&_kCFTimeZoneCacheLock); } /* Verify we haven't created a timezone with this name already. */ old = (CFTimeZoneRef)CFDictionaryGetValue (_kCFTimeZoneCache, name); if (old != NULL) return CFRetain (old); /* Do some basic checks before we try anything else. */ bytes = CFDataGetBytePtr (data); endOfBytes = bytes + CFDataGetLength (data); header = (const struct tzhead*)bytes; bytes += sizeof(struct tzhead); if (bytes > endOfBytes) return NULL; if (memcmp(header->tzh_magic, TZ_MAGIC, 4) != 0) return NULL; tmp = (UInt32*)header->tzh_timecnt; tzh_timecnt = (SInt32)CFSwapInt32BigToHost (*tmp); tmp = (UInt32*)header->tzh_typecnt; tzh_typecnt = (SInt32)CFSwapInt32BigToHost (*tmp); tmp = (UInt32*)header->tzh_charcnt; tzh_charcnt = (SInt32)CFSwapInt32BigToHost (*tmp); /* Make sure we're not above any of the maximums. */ if (tzh_timecnt > TZ_MAX_TIMES || tzh_typecnt > TZ_MAX_TYPES || tzh_charcnt > TZ_MAX_CHARS) return NULL; new = (struct __CFTimeZone*)_CFRuntimeCreateInstance (alloc, _kCFTimeZoneTypeID, CFTIMEZONE_SIZE, 0); if (new) { CFIndex idx; TransInfo *trans; SInt32 *times; UInt8 *typeIdx; struct _ttinfo *types; char *chars; char *charsEnd; CFStringRef abbrevs[TZ_MAX_CHARS / 4]; new->_name = CFStringCreateCopy (alloc, name); new->_data = CFDataCreateCopy (alloc, data); trans = CFAllocatorAllocate (alloc, sizeof(TransInfo) * tzh_timecnt, 0); new->_transitions = trans; times = (SInt32*)bytes; typeIdx = (UInt8*)((sizeof(SInt32) * tzh_timecnt) + bytes); types = (struct _ttinfo*)(typeIdx + (sizeof(UInt8) * tzh_timecnt)); chars = (char*)(((UInt8*)types) + (sizeof(struct _ttinfo) * tzh_typecnt)); charsEnd = chars + tzh_charcnt; /* Transition times and information */ new->_transCount = tzh_timecnt; for (idx = 0 ; idx < tzh_timecnt ; ++idx) { trans->transition = (SInt32)CFSwapInt32BigToHost(*(times++)); trans->offset = (SInt16)((SInt32)CFSwapInt32BigToHost(types[*typeIdx].offset)); trans->isDST = types[*typeIdx].isdst; trans->abbrevIdx = types[*typeIdx].abbr_idx; trans++; typeIdx++; } /* Abbreviations */ idx = 0; while (chars < charsEnd) { abbrevs[idx++] = CFStringCreateWithCString (alloc, chars, kCFStringEncodingASCII); while (*chars != '\0') chars++; chars++; /* Skip '\0' */ } new->_abbrevs = CFAllocatorAllocate (alloc, sizeof(void*) * idx, 0); new->_abbrevCount = idx; for (idx = 0 ; idx < new->_abbrevCount ; ++idx) new->_abbrevs[idx] = abbrevs[idx]; if (header->tzh_version[0] == '2') { /* FIXME: Code for version '2' TZif files */ } GSMutexLock(&_kCFTimeZoneCacheLock); /* Double check another an entry wasn't inserted before we could act. */ old = (CFTimeZoneRef)CFDictionaryGetValue (_kCFTimeZoneCache, name); if (old != NULL) { GSMutexUnlock(&_kCFTimeZoneCacheLock); CFRelease ((CFTimeZoneRef)new); return CFRetain (old); } CFDictionaryAddValue (_kCFTimeZoneCache, name, (const void *)new); old = (CFTimeZoneRef)new; GSMutexUnlock(&_kCFTimeZoneCacheLock); } return old; } struct TZFile { struct tzhead header; SInt32 time; UInt8 type; struct _ttinfo ttinfo; char abbrev[10]; /* 10 = max number of characters, ie 'GMT+01:00\0'. */ } __attribute__((packed)); CFTimeZoneRef CFTimeZoneCreateWithTimeIntervalFromGMT (CFAllocatorRef alloc, CFTimeInterval ti) { CFTimeZoneRef new; struct TZFile tzfile; CFIndex numChars; CFStringRef name; CFDataRef data; char sign; SInt32 sec; SInt32 hour; SInt32 min; sign = (ti < 0) ? '-' : '+'; sec = (SInt32)ti; hour = (ti < 0) ? -sec / 3600 : sec / 3600; sec -= ((ti < 0) ? -hour : hour) * 3600; min = (ti < 0) ? -sec / 60 : sec / 60; memset (&tzfile, 0, sizeof(struct TZFile)); memcpy (tzfile.header.tzh_magic, "TZif", 4); tzfile.header.tzh_timecnt[3] = 1; tzfile.header.tzh_typecnt[3] = 1; tzfile.ttinfo.offset = CFSwapInt32HostToBig((SInt32)ti); numChars = snprintf (tzfile.abbrev, 10, "GMT%c%02d:%02d", sign, hour, min); tzfile.header.tzh_charcnt[3] = numChars; name = CFStringCreateWithCString (alloc, tzfile.abbrev, kCFStringEncodingASCII); data = CFDataCreateWithBytesNoCopy (alloc, (UInt8*)&tzfile, sizeof(struct TZFile) - (10 - numChars), kCFAllocatorNull); new = CFTimeZoneCreate (alloc, name, data); CFRelease (name); CFRelease (data); return new; } CFTimeZoneRef CFTimeZoneCreateWithName (CFAllocatorRef alloc, CFStringRef name, Boolean tryAbbrev) { CFURLRef tzdir; CFURLRef path; CFDataRef data; CFTimeZoneRef new; if (tryAbbrev) { CFDictionaryRef abbrevs; CFStringRef nonAbbrev; abbrevs = CFTimeZoneCopyAbbreviationDictionary (); if (CFDictionaryGetValueIfPresent (abbrevs, name, (const void**)&nonAbbrev)) { name = nonAbbrev; } CFRelease (abbrevs); } tzdir = CFURLCreateWithFileSystemPathRelativeToBase (alloc, CFSTR(TZDIR), kCFURLPOSIXPathStyle, true, NULL); path = CFURLCreateWithFileSystemPathRelativeToBase (alloc, name, kCFURLPOSIXPathStyle, false, tzdir); CFRelease (tzdir); if (CFURLCreateDataAndPropertiesFromResource (alloc, path, &data, NULL, NULL, NULL)) { new = CFTimeZoneCreate (alloc, name, data); CFRelease (data); } else { new = NULL; } CFRelease (path); return new; } CFStringRef CFTimeZoneGetName (CFTimeZoneRef tz) { CF_OBJC_FUNCDISPATCHV(_kCFTimeZoneTypeID, CFStringRef, tz, "name"); return tz->_name; } CFDataRef CFTimeZoneGetData (CFTimeZoneRef tz) { CF_OBJC_FUNCDISPATCHV(_kCFTimeZoneTypeID, CFDataRef, tz, "data"); return tz->_data; } static CFComparisonResult CFTimeZoneComparator (const void *v1, const void *v2, void *ctxt) { TransInfo *ti1 = (TransInfo*)v1; TransInfo *ti2 = (TransInfo*)v2; return (ti1->transition < ti2->transition) ? kCFCompareLessThan : ((ti1->transition == ti2->transition) ? kCFCompareEqualTo : kCFCompareGreaterThan); } CFStringRef CFTimeZoneCopyAbbreviation (CFTimeZoneRef tz, CFAbsoluteTime at) { CF_OBJC_FUNCDISPATCHV(_kCFTimeZoneTypeID, CFStringRef, tz, "_cfCopyAbbreviation:", at); TransInfo tmp; CFIndex idx; tmp.transition = (SInt32)(at + kCFAbsoluteTimeIntervalSince1970); idx = GSBSearch (tz->_transitions, &tmp, CFRangeMake(0, tz->_transCount), sizeof(TransInfo), CFTimeZoneComparator, NULL); return CFRetain (tz->_abbrevs[tz->_transitions[idx].abbrevIdx]); } CFTimeInterval CFTimeZoneGetDaylightSavingTimeOffset (CFTimeZoneRef tz, CFAbsoluteTime at) { CF_OBJC_FUNCDISPATCHV(_kCFTimeZoneTypeID, CFTimeInterval, tz, "_cfGetDaylightSavingTimeOffset:", at); TransInfo tmp; TransInfo *cur; TransInfo *prev; CFIndex idx; CFTimeInterval ret; if (tz->_transCount <= 1) return 0.0; /* No DST, so no DST offset. */ tmp.transition = (SInt32)(at + kCFAbsoluteTimeIntervalSince1970); idx = GSBSearch (tz->_transitions, &tmp, CFRangeMake(0, tz->_transCount), sizeof(TransInfo), CFTimeZoneComparator, NULL); cur = &(tz->_transitions[idx]); idx = idx > 0 ? idx - 1 : idx + 1; prev = &(tz->_transitions[idx]); if (cur->isDST && cur->offset > prev->offset) ret = (CFTimeInterval)(cur->offset - prev->offset); else ret = 0.0; return ret; } Boolean CFTimeZoneIsDaylightSavingTime (CFTimeZoneRef tz, CFAbsoluteTime at) { CF_OBJC_FUNCDISPATCHV(_kCFTimeZoneTypeID, Boolean, tz, "_cfIsDaylightSavingTime:", at); TransInfo tmp; CFIndex idx; tmp.transition = (SInt32)(at + kCFAbsoluteTimeIntervalSince1970); idx = GSBSearch (tz->_transitions, &tmp, CFRangeMake(0, tz->_transCount), sizeof(TransInfo), CFTimeZoneComparator, NULL); return (Boolean)(tz->_transitions[idx].isDST); } CFTimeInterval CFTimeZoneGetSecondsFromGMT (CFTimeZoneRef tz, CFAbsoluteTime at) { CF_OBJC_FUNCDISPATCHV(_kCFTimeZoneTypeID, CFTimeInterval, tz, "_cfGetSecondsFromGMT:", at); TransInfo tmp; CFIndex idx; tmp.transition = (SInt32)(at + kCFAbsoluteTimeIntervalSince1970); idx = GSBSearch (tz->_transitions, &tmp, CFRangeMake(0, tz->_transCount), sizeof(TransInfo), CFTimeZoneComparator, NULL); return (CFTimeInterval)(tz->_transitions[idx].offset); } CFAbsoluteTime CFTimeZoneGetNextDaylightSavingTimeTransition (CFTimeZoneRef tz, CFAbsoluteTime at) { CF_OBJC_FUNCDISPATCHV(_kCFTimeZoneTypeID, CFAbsoluteTime, tz, "_cfGetNextDaylightSavingTimeTransition:", at); TransInfo tmp; CFIndex idx; tmp.transition = (SInt32)(at + kCFAbsoluteTimeIntervalSince1970); idx = GSBSearch (tz->_transitions, &tmp, CFRangeMake(0, tz->_transCount), sizeof(TransInfo), CFTimeZoneComparator, NULL); return (idx + 1 >= tz->_transCount) ? 0.0 : tz->_transitions[idx + 1].transition - kCFAbsoluteTimeIntervalSince1970; } #define BUFFER_SIZE 256 CFStringRef CFTimeZoneCopyLocalizedName (CFTimeZoneRef tz, CFTimeZoneNameStyle style, CFLocaleRef locale) { CF_OBJC_FUNCDISPATCHV_RETAINED(_kCFTimeZoneTypeID, CFStringRef, tz, "localizedName:locale:", style, locale); #if HAVE_ICU UniChar localizedName[BUFFER_SIZE]; UniChar zoneID[BUFFER_SIZE]; char cLocale[ULOC_FULLNAME_CAPACITY]; CFIndex len; UCalendarDisplayNameType ucaltype; UCalendar *ucal; UErrorCode err; CFStringRef ret; len = CFStringGetLength (tz->_name); if (len > BUFFER_SIZE) len = BUFFER_SIZE; CFStringGetCharacters (tz->_name, CFRangeMake(0, len), zoneID); err = U_ZERO_ERROR; ucal = ucal_open (zoneID, len, NULL, UCAL_TRADITIONAL, &err); if (U_FAILURE(err)) return NULL; switch (style) { case kCFTimeZoneNameStyleShortStandard: ucaltype = UCAL_SHORT_STANDARD; break; case kCFTimeZoneNameStyleDaylightSaving: ucaltype = UCAL_DST; break; case kCFTimeZoneNameStyleShortDaylightSaving: ucaltype = UCAL_SHORT_DST; break; default: /* Covers kCFTimeZoneNameStyleStandard */ ucaltype = UCAL_STANDARD; } CFStringGetCString (CFLocaleGetIdentifier(locale), cLocale, ULOC_FULLNAME_CAPACITY, kCFStringEncodingASCII); len = ucal_getTimeZoneDisplayName (ucal, ucaltype, cLocale, localizedName, BUFFER_SIZE, &err); if (len > BUFFER_SIZE) len = BUFFER_SIZE; ret = CFStringCreateWithCharacters (CFGetAllocator(tz), localizedName, len); ucal_close (ucal); return ret; #else return NULL; #endif } CFTimeZoneRef CFTimeZoneCopyDefault (void) { if (_kCFTimeZoneDefault == NULL) { CFTimeZoneRef new; new = CFTimeZoneCopySystem(); /* FIXME */ if (GSAtomicCompareAndSwapPointer(&_kCFTimeZoneDefault, NULL, new) != NULL) CFRelease (new); } return CFRetain (_kCFTimeZoneDefault); } void CFTimeZoneSetDefault (CFTimeZoneRef tz) { CFTimeZoneRef old; old = GSAtomicCompareAndSwapPointer(&_kCFTimeZoneDefault, _kCFTimeZoneDefault, CFRetain (tz)); if (old != NULL) CFRelease (old); } CFTimeZoneRef CFTimeZoneCopySystem (void) { if (_kCFTimeZoneSystem == NULL) { CFTimeZoneRef new; new = CFTimeZoneCreateWithTimeIntervalFromGMT (NULL, 0.0); /* FIXME */ if (GSAtomicCompareAndSwapPointer(&_kCFTimeZoneSystem, NULL, new) != NULL) CFRelease (new); } return CFRetain (_kCFTimeZoneSystem); } void CFTimeZoneResetSystem (void) { if (_kCFTimeZoneSystem != NULL) { CFTimeZoneRef old; old = GSAtomicCompareAndSwapPointer(&_kCFTimeZoneSystem, _kCFTimeZoneSystem, NULL); if (old != NULL) CFRelease (old); } } CFArrayRef CFTimeZoneCopyKnownNames (void) { return NULL; /* FIXME */ } static const char *_kCFTimeZoneAbbreviationKeys[] = { "ACDT", "ACST", "ADT", "AEDT", "AEST", "AFT", "AKDT", "AKST", "AMT", "ART", "AST", "AWDT", "AWST", "AZOST", "AZT", "BDT", "BIOT", "BOT", "BRT", "BST", "BTT", "CAT", "CCT", "CDT", "CEDT", "CEST", "CET", "CHADT", "CHAST", "CLST", "CLT", "COT", "CST", "CT", "CVT", "CXT", "EAST", "EAT", "ECT", "EDT", "EEDT", "EEST", "EET", "EST", "FET", "FJT", "FKST", "FKT", "GALT", "GET", "GFT", "GIT", "GST", "GYT", "HADT", "HAST", "HKT", "HST", "ICT", "IRKT", "IRST", "IST", "JST", "KRAT", "KST", "MAGT", "MDT", "MSD", "MSK", "MST", "MYT", "NDT", "NPT", "NST", "NZDT", "NZST", "PDT", "PETT", "PKT", "PST", "SAMT", "SGT", "SST", "TAHT", "THA", "UYST", "UYT", "VET", "VLAT", "WAT", "WEDT", "WEST", "WET", "YAKT", "YEKT" }; static const char *_kCFTimeZoneAbbreviationValues[] = { /* ACDT */ "Australia/Adelaide", /* ACST */ "Australia/Adelaide", /* ADT */ "America/Halifax", /* AEDT */ "Australia/Sydney", /* AEST */ "Australia/Sydney", /* AFT */ "Asia/Kabul", /* AKDT */ "America/Juneau", /* AKST */ "America/Juneau", /* AMT */ "Asia/Yakutsk", /* ART */ "America/Argentina/Buenos_Aires", /* AST */ "America/Halifax", /* AWDT */ "Australia/Perth", /* AWST */ "Australia/Perth", /* AZOST */ "Atlantic/Azores", /* AZT */ "Asia/Baku", /* BDT */ "Asia/Dhaka", /* BIOT */ "Indian/Chagos", /* BOT */ "America/La_Paz", /* BRT */ "America/Sao_Paulo", /* BST */ "Europe/London", /* BTT */ "Asia/Thimphu", /* CAT */ "Africa/Harare", /* CCT */ "Indian/Cocos", /* CDT */ "America/Chicago", /* CEDT */ "Europe/Paris", /* CEST */ "Europe/Paris", /* CET */ "Europe/Paris", /* CHADT */ "Pacific/Chatham", /* CHAST */ "Pacific/Chatham", /* CLST */ "America/Santiago", /* CLT */ "America/Santiago", /* COT */ "America/Bogota", /* CST */ "America/Chicago", /* CT */ "Asia/Shanghai", /* CVT */ "Atlantic/Cape_Verde", /* CXT */ "Indian/Christmas", /* EAST */ "Pacific/Easter", /* EAT */ "Africa/Addis_Ababa", /* ECT */ "America/Guayaquil", /* EDT */ "America/New_York", /* EEDT */ "Europe/Istanbul", /* EEST */ "Europe/Istanbul", /* EET */ "Europe/Istanbul", /* EST */ "America/New_York", /* FET */ "Europe/Kaliningrad", /* FJT */ "Pacific/Fiji", /* FKST */ "Atlantic/Stanley", /* FKT */ "Atlantic/Stanley", /* GALT */ "Pacific/Galapagos", /* GET */ "Asia/Tbilisi", /* GFT */ "America/Cayenne", /* GIT */ "Pacific/Gambier", /* GST */ "Asia/Dubai", /* GYT */ "America/Guyana", /* HADT */ "America/Adak", /* HAST */ "America/Adak", /* HKT */ "Asia/Hong_Kong", /* HST */ "Pacific/Honolulu", /* ICT */ "Asia/Bangkok", /* IRKT */ " Asia/Irkutsk", /* IRST */ "Asia/Tehran", /* IST */ "Asia/Calcutta", /* JST */ "Asia/Tokyo", /* KRAT */ "Asia/Krasnoyarsk", /* KST */ "Asia/Seoul", /* MAGT */ "Asia/Magadan", /* MDT */ "America/Denver", /* MSD */ "Europe/Moscow", /* MSK */ "Europe/Moscow", /* MST */ "America/Denver", /* MYT */ "Asia/Kuala_Lumpur", /* NDT */ "America/St_Johns", /* NPT */ "Asia/Kathmandu", /* NST */ "America/St_Johns", /* NZDT */ "Pacific/Auckland", /* NZST */ "Pacific/Auckland", /* PDT */ "America/Los_Angeles", /* PETT */ "Asia/Kamchatka", /* PKT */ "Asia/Karachi", /* PST */ "America/Los_Angeles", /* SAMT */ "Europe/Samara", /* SGT */ "Asia/Singapore", /* SST */ "Pacific/Pago_Pago", /* TAHT */ "Pacific/Tahiti", /* THA */ "Asia/Bangkok", /* UYST */ "America/Montevideo", /* UYT */ "America/Montevideo", /* VET */ "America/Caracas", /* VLAT */ "Asia/Vladivostok", /* WAT */ "Africa/Lagos", /* WEDT */ "Europe/Lisbon", /* WEST */ "Europe/Lisbon", /* WET */ "Europe/Lisbon", /* YAKT */ "Asia/Yakutsk", /* YEKT */ "Asia/Yekaterinburg" }; static const CFIndex _kCFTimeZoneAbbreviationsSize = sizeof(_kCFTimeZoneAbbreviationKeys) / sizeof(void*); CFDictionaryRef CFTimeZoneCopyAbbreviationDictionary (void) { if (_kCFTimeZoneAbbreviationDictionary == NULL) { CFIndex i; CFMutableDictionaryRef dict; CFDictionaryRef new; dict = CFDictionaryCreateMutable (NULL, _kCFTimeZoneAbbreviationsSize, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); i = 0; while (i < _kCFTimeZoneAbbreviationsSize) { CFStringRef abbrev; CFStringRef fullname; abbrev = __CFStringMakeConstantString (_kCFTimeZoneAbbreviationKeys[i]); fullname = __CFStringMakeConstantString (_kCFTimeZoneAbbreviationValues[i]); CFDictionaryAddValue (dict, abbrev, fullname); i++; } new = CFDictionaryCreateCopy (NULL, dict); CFRelease (dict); if (GSAtomicCompareAndSwapPointer(&_kCFTimeZoneAbbreviationDictionary, NULL, new) != NULL) CFRelease (new); } return CFRetain (_kCFTimeZoneAbbreviationDictionary); } void CFTimeZoneSetAbbreviationDictionary (CFDictionaryRef dict) { CFDictionaryRef old; old = GSAtomicCompareAndSwapPointer(&_kCFTimeZoneAbbreviationDictionary, _kCFTimeZoneAbbreviationDictionary, CFDictionaryCreateCopy (NULL, dict)); if (old != NULL) CFRelease (old); } gnustep-corebase-0.2/Source/CFBundle.m0000644000175000017500000001470313222706330016746 0ustar yavoryavor/* CFBundle.m Copyright (C) 2011 Free Software Foundation, Inc. Written by: David Chisnall Date: April, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBundle.h" #include #include #include "GSPrivate.h" #if !defined(_WIN32) #include #ifndef RTLD_DEFAULT # define RTLD_DEFAULT ((void *) 0) #endif #endif static CFTypeID _kCFBundleTypeID = 0; CONST_STRING_DECL(kCFBundleInfoDictionaryVersionKey, "CFBundleInfoDictionaryVersion"); CONST_STRING_DECL(kCFBundleExecutableKey, "CFBundleExecutable"); CONST_STRING_DECL(kCFBundleIdentifierKey, "CFBundleIdentifier"); CONST_STRING_DECL(kCFBundleVersionKey, "CFBundleVersion"); CONST_STRING_DECL(kCFBundleNameKey, "CFBundleName"); CONST_STRING_DECL(kCFBundleLocalizationsKey, "CFBundleLocalizations"); @implementation NSBundle (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFBundleGetTypeID(); } @end static const CFRuntimeClass CFBundleClass = { 0, "CFBundle", NULL, NULL, NULL, NULL, NULL, NULL, NULL }; void CFBundleInitialize (void) { _kCFBundleTypeID = _CFRuntimeRegisterClass(&CFBundleClass); } CFTypeID CFBundleGetTypeID (void) { return _kCFBundleTypeID; } CFBundleRef CFBundleCreate(CFAllocatorRef allocator, CFURLRef bundleURL) { NSString *path = [(NSURL*)bundleURL path]; if (nil == path) { return 0; } return (CFBundleRef)[[NSBundle alloc] initWithPath: path]; } void* CFBundleGetFunctionPointerForName(CFBundleRef bundle, CFStringRef functionName) { #if !defined(_WIN32) [(NSBundle*)bundle load]; return dlsym(RTLD_DEFAULT, [(NSString *) functionName UTF8String]); #else return NULL; #endif } void* CFBundleGetDataPointerForName(CFBundleRef bundle, CFStringRef functionName) { #if !defined(_WIN32) [(NSBundle*)bundle load]; return dlsym(RTLD_DEFAULT, [(NSString *) functionName UTF8String]); #else return NULL; #endif } Boolean CFBundlePreflightExecutable(CFBundleRef bundle, CFErrorRef *error) { NSBundle *ns = (NSBundle *) bundle; return [ns preflightAndReturnError: (NSError **)error]; } Boolean CFBundleLoadExecutable(CFBundleRef bundle) { NSBundle *ns = (NSBundle *) bundle; return [ns load]; } Boolean CFBundleLoadExecutableAndReturnError(CFBundleRef bundle, CFErrorRef *error) { NSBundle *ns = (NSBundle *) bundle; return [ns loadAndReturnError: (NSError**) error]; } void CFBundleUnloadExecutable(CFBundleRef bundle) { NSBundle *ns = (NSBundle *) bundle; [ns unload]; } CFBundleRef CFBundleGetMainBundle(void) { return (CFBundleRef) [NSBundle mainBundle]; } CFBundleRef CFBundleGetBundleWithIdentifier(CFStringRef bundleID) { return (CFBundleRef) [NSBundle bundleWithIdentifier: (NSString*)bundleID]; } CFStringRef CFBundleGetIdentifier(CFBundleRef bundle) { NSBundle *ns = (NSBundle *) bundle; return (CFStringRef) [ns bundleIdentifier]; } CFURLRef CFBundleCopyBundleURL(CFBundleRef bundle) { NSBundle *ns = (NSBundle *) bundle; NSURL *url = [ns bundleURL]; [url retain]; return (CFURLRef) url; } CFURLRef CFBundleCopyExecutableURL(CFBundleRef bundle) { NSBundle *ns = (NSBundle *) bundle; NSURL* url; url = [ns executableURL]; [url retain]; return (CFURLRef) url; } CFURLRef CFBundleCopyBuiltInPlugInsURL(CFBundleRef bundle) { NSBundle *ns = (NSBundle *) bundle; NSURL* url; url = [ns builtInPlugInsURL]; [url retain]; return (CFURLRef) url; } CFURLRef CFBundleCopyResourcesDirectoryURL(CFBundleRef bundle) { NSBundle *ns = (NSBundle *) bundle; NSURL* url; url = [ns resourceURL]; [url retain]; return (CFURLRef) url; } CFURLRef CFBundleCopyResourceURL(CFBundleRef bundle, CFStringRef resourceName, CFStringRef resourceType, CFStringRef subDirName) { NSBundle *ns = (NSBundle *) bundle; NSURL *url; url = [ns URLForResource: (NSString *) resourceName withExtension: (NSString *) resourceType subdirectory: (NSString *) subDirName]; [url retain]; return (CFURLRef) url; } CFURLRef CFBundleCopyResourceURLForLocalization(CFBundleRef bundle, CFStringRef resourceName, CFStringRef resourceType, CFStringRef subDirName, CFStringRef localizationName) { NSBundle *ns = (NSBundle *) bundle; NSURL *url; url = [ns URLForResource: (NSString *) resourceName withExtension: (NSString *) resourceType subdirectory: (NSString *) subDirName localization: (NSString *) localizationName]; [url retain]; return (CFURLRef) url; } CFURLRef CFBundleCopyPrivateFrameworksURL(CFBundleRef bundle) { NSBundle *ns = (NSBundle *) bundle; NSURL *url; url = [ns privateFrameworksURL]; [url retain]; return (CFURLRef) url; } CFURLRef CFBundleCopyAuxiliaryExecutableURL(CFBundleRef bundle, CFStringRef executableName) { NSBundle *ns = (NSBundle *) bundle; NSURL *url; url = [ns URLForAuxiliaryExecutable: (NSString *) executableName]; [url retain]; return (CFURLRef) url; } CFDictionaryRef CFBundleGetInfoDictionary(CFBundleRef bundle) { NSBundle *ns = (NSBundle *) bundle; return (CFDictionaryRef) [ns infoDictionary]; } CFDictionaryRef CFBundleGetLocalInfoDictionary(CFBundleRef bundle) { NSBundle *ns = (NSBundle *) bundle; return (CFDictionaryRef) [ns localizedInfoDictionary]; } CFTypeRef CFBundleGetValueForInfoDictionaryKey(CFBundleRef bundle, CFStringRef key) { NSBundle *ns = (NSBundle *) bundle; return [ns objectForInfoDictionaryKey: (NSString *)key]; } gnustep-corebase-0.2/Source/CFBase.c0000644000175000017500000001370113222706330016372 0ustar yavoryavor/* CFBase.c Copyright (C) 2010-2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFRuntime.h" #include "GSPrivate.h" #include #include const double kCFCoreFoundationVersionNumber = 550.13; struct __CFAllocator { CFRuntimeBase _parent; CFAllocatorContext _context; }; /* this will hold the default zone if set with CFAllocatorSetDefault () */ static CFTypeID _kCFAllocatorTypeID = 0; static CFAllocatorRef _kCFDefaultAllocator = NULL; static CFRuntimeClass CFAllocatorClass = { 0, "CFAllocator", NULL, NULL, NULL, NULL, NULL, NULL, NULL }; void CFAllocatorInitialize (void) { _kCFAllocatorTypeID = _CFRuntimeRegisterClass (&CFAllocatorClass); _kCFDefaultAllocator = kCFAllocatorSystemDefault; /* These are already semi-initialized by INIT_CFRUNTIME_BASE() */ GSRuntimeConstantInit (kCFAllocatorSystemDefault, _kCFAllocatorTypeID); GSRuntimeConstantInit (kCFAllocatorMalloc, _kCFAllocatorTypeID); GSRuntimeConstantInit (kCFAllocatorMallocZone, _kCFAllocatorTypeID); GSRuntimeConstantInit (kCFAllocatorNull, _kCFAllocatorTypeID); } static void * malloc_alloc (CFIndex allocSize, CFOptionFlags hint, void *info) { return malloc (allocSize); } static void * malloc_realloc (void *ptr, CFIndex newsize, CFOptionFlags hint, void *info) { return realloc (ptr, newsize); } static void malloc_dealloc (void *ptr, void *info) { free (ptr); } static void * null_alloc (CFIndex allocSize, CFOptionFlags hint, void *info) { return NULL; } static void * null_realloc (void *ptr, CFIndex newsize, CFOptionFlags hint, void *info) { return NULL; } static void null_dealloc (void *ptr, void *info) { } static struct __CFAllocator _kCFAllocatorSystemDefault = { INIT_CFRUNTIME_BASE(), { 0, NULL, NULL, NULL, NULL, malloc_alloc, malloc_realloc, malloc_dealloc, NULL } }; static struct __CFAllocator _kCFAllocatorNull = { INIT_CFRUNTIME_BASE(), { 0, NULL, NULL, NULL, NULL, null_alloc, null_realloc, null_dealloc, NULL } }; CFAllocatorRef kCFAllocatorDefault = NULL; /* Just use the default system allocator everywhere! */ CFAllocatorRef kCFAllocatorSystemDefault = &_kCFAllocatorSystemDefault; CFAllocatorRef kCFAllocatorMalloc = &_kCFAllocatorSystemDefault; CFAllocatorRef kCFAllocatorMallocZone = &_kCFAllocatorSystemDefault; CFAllocatorRef kCFAllocatorNull = &_kCFAllocatorNull; CFAllocatorRef kCFAllocatorUseContext = (CFAllocatorRef)0x01; CFAllocatorRef CFAllocatorCreate(CFAllocatorRef allocator, CFAllocatorContext *context) { struct __CFAllocator *new; if (allocator == kCFAllocatorUseContext) { /* Chicken and egg problem... */ return NULL; /* FIXME */ } else { new = (struct __CFAllocator*)_CFRuntimeCreateInstance (allocator, _kCFAllocatorTypeID, sizeof(struct __CFAllocator) - sizeof(CFRuntimeBase), 0); memcpy (&(new->_context), context, sizeof(CFAllocatorContext)); } return (CFAllocatorRef)new; } void * CFAllocatorAllocate(CFAllocatorRef allocator, CFIndex size, CFOptionFlags hint) { if (NULL == allocator) allocator = _kCFDefaultAllocator; return allocator->_context.allocate(size, hint, allocator->_context.info); } void CFAllocatorDeallocate(CFAllocatorRef allocator, void *ptr) { if (NULL == allocator) allocator = _kCFDefaultAllocator; allocator->_context.deallocate(ptr, allocator->_context.info); } CFIndex CFAllocatorGetPreferredSizeForSize(CFAllocatorRef allocator, CFIndex size, CFOptionFlags hint) { if (allocator == NULL) allocator = _kCFDefaultAllocator; if (allocator->_context.preferredSize) return allocator->_context.preferredSize (size, hint, allocator->_context.info); return size; } void * CFAllocatorReallocate(CFAllocatorRef allocator, void *ptr, CFIndex newsize, CFOptionFlags hint) { if (NULL == allocator) allocator = _kCFDefaultAllocator; return allocator->_context.reallocate(ptr, newsize, hint, allocator->_context.info); } CFAllocatorRef CFAllocatorGetDefault(void) { return _kCFDefaultAllocator; } void CFAllocatorSetDefault(CFAllocatorRef allocator) { CFAllocatorRef current = _kCFDefaultAllocator; if (allocator == NULL) return; CFRetain (allocator); _kCFDefaultAllocator = allocator; CFRelease (current); } void CFAllocatorGetContext(CFAllocatorRef allocator, CFAllocatorContext *context) { memcpy (context, &(allocator->_context), sizeof(CFAllocatorContext)); } CFTypeID CFAllocatorGetTypeID(void) { return _kCFAllocatorTypeID; } static CFTypeID _kCFNullTypeID; static const CFRuntimeClass CFNullClass = { 0, "CFNUll", NULL, NULL, NULL, NULL, NULL, NULL, NULL }; struct __CFNull { CFRuntimeBase _parent; }; static struct __CFNull _kCFNull = { INIT_CFRUNTIME_BASE() }; CFNullRef kCFNull = &_kCFNull; void CFNullInitialize (void) { _kCFNullTypeID = _CFRuntimeRegisterClass (&CFNullClass); _CFRuntimeSetInstanceTypeID (&_kCFNull, _kCFNullTypeID); GSRuntimeConstantInit (kCFNull, _kCFNullTypeID); } CFTypeID CFNullGetTypeID (void) { return _kCFNullTypeID; } gnustep-corebase-0.2/Source/CFCharacterSet.c0000644000175000017500000002622414551015633020101 0ustar yavoryavor/* CFCharacterSet.c Copyright (C) 2012 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFCharacterSet.h" #include "CoreFoundation/CFDictionary.h" #include "CoreFoundation/CFString.h" #include "GSPrivate.h" #if defined(HAVE_UNICODE_USET_H) #include #endif #if defined(HAVE_ICU_H) #include #endif struct __CFCharacterSet { CFRuntimeBase _parent; USet *_uset; }; static CFTypeID _kCFCharacterSetTypeID = 0; static CFMutableDictionaryRef _kCFPredefinedCharacterSets = NULL; static GSMutex _kCFPredefinedCharacterSetLock; static void CFCharacterSetFinalize (CFTypeRef cf) { CFCharacterSetRef cs = (CFCharacterSetRef)cf; uset_close (cs->_uset); } static Boolean CFCharacterSetEqual (CFTypeRef cf1, CFTypeRef cf2) { return uset_equals (((CFCharacterSetRef)cf1)->_uset, ((CFCharacterSetRef)cf2)->_uset); } static CFHashCode CFCharacterSetHash (CFTypeRef cf) { return uset_size (((CFCharacterSetRef)cf)->_uset); } static const CFRuntimeClass CFCharacterSetClass = { 0, "CFCharacterSet", NULL, (CFTypeRef (*)(CFAllocatorRef, CFTypeRef))CFCharacterSetCreateCopy, CFCharacterSetFinalize, CFCharacterSetEqual, CFCharacterSetHash, NULL, NULL }; void CFCharacterSetInitialize (void) { _kCFCharacterSetTypeID = _CFRuntimeRegisterClass (&CFCharacterSetClass); GSMutexInitialize (&_kCFPredefinedCharacterSetLock); } CFTypeID CFCharacterSetGetTypeID (void) { return _kCFCharacterSetTypeID; } #define CFCHARACTERSET_SIZE \ (sizeof(struct __CFCharacterSet) - sizeof(CFRuntimeBase)) CFCharacterSetRef CFCharacterSetCreateCopy (CFAllocatorRef alloc, CFCharacterSetRef set) { struct __CFCharacterSet *new; new = (struct __CFCharacterSet*)_CFRuntimeCreateInstance (alloc, _kCFCharacterSetTypeID, CFCHARACTERSET_SIZE, 0); if (new) { new->_uset = uset_clone (set->_uset); uset_freeze (new->_uset); } return new; } CFCharacterSetRef CFCharacterSetCreateInvertedSet (CFAllocatorRef alloc, CFCharacterSetRef set) { struct __CFCharacterSet *new; new = (struct __CFCharacterSet*)_CFRuntimeCreateInstance (alloc, _kCFCharacterSetTypeID, CFCHARACTERSET_SIZE, 0); if (new) { new->_uset = uset_cloneAsThawed (set->_uset); uset_complement (new->_uset); uset_freeze (new->_uset); } return new; } CFCharacterSetRef CFCharacterSetCreateWithCharactersInRange (CFAllocatorRef alloc, CFRange range) { struct __CFCharacterSet *new; new = (struct __CFCharacterSet*)_CFRuntimeCreateInstance (alloc, _kCFCharacterSetTypeID, CFCHARACTERSET_SIZE, 0); if (new) { new->_uset = uset_open ((UChar32)range.location, (UChar32)(range.location + range.length)); uset_freeze (new->_uset); } return new; } static void USetAddString (USet *set, CFStringRef string) { UniChar *str; CFIndex len; len = CFStringGetLength (string); str = CFAllocatorAllocate (NULL, sizeof(UniChar) * len, 0); CFStringGetCharacters (string, CFRangeMake(0, len), str); uset_addAllCodePoints (set, str, len); CFAllocatorDeallocate (NULL, str); } CFCharacterSetRef CFCharacterSetCreateWithCharactersInString (CFAllocatorRef alloc, CFStringRef string) { struct __CFCharacterSet *new; new = (struct __CFCharacterSet*)_CFRuntimeCreateInstance (alloc, _kCFCharacterSetTypeID, CFCHARACTERSET_SIZE, 0); if (new) { new->_uset = uset_openEmpty (); USetAddString (new->_uset, string); uset_freeze (new->_uset); } return new; } static const UniChar control[] = { '[', '[', ':', 'C', 'c', ':', ']', '[', ':', 'C', 'f', ':', ']', ']' }; static const UniChar whitespace[] = { '[', '[', ':', 'Z', 's', ':', ']', '[', '\\', 'u', '0', '0', '0', '9', ']', ']' }; static const UniChar whitespace_newline[] = { '[', '[', ':', 'Z', ':', ']', '[', '\\', 'u', '0', '0', '0', 'A', '-', '\\', 'u', '0', '0', '0', 'D', ']', '[', '\\', 'u', '0', '0', '8', '5', ']', ']' }; static const UniChar decimal_digit[] = { '[', ':', 'N', ':', ']' }; static const UniChar letter[] = { '[', '[', ':', 'L', ':', ']', '[', ':', 'M', ':', ']', ']' }; static const UniChar lowercase_letter[] = { '[', ':', 'L', 'l', ':', ']' }; static const UniChar uppercase_letter[] = { '[', ':', 'L', 'u', ':', ']' }; static const UniChar non_base[] = { '[', ':', 'M', ':', ']' }; static const UniChar decomposable[] = /* FIXME */ { ' ' }; static const UniChar alpha_numeric[] = { '[', '[', ':', 'L', ':', ']', '[', ':', 'M', ':', ']', '[', ':', 'N', ':', ']', ']' }; static const UniChar punctuation[] = { '[', ':', 'P', ':', ']' }; static const UniChar illegal[] = /* FIXME: Is this right? */ { '[', '[', ':', '^', 'C', ':', ']', '[', ':', '^', 'L', ':', ']', '[', ':', '^', 'M', ':', ']', '[', ':', '^', 'N', ':', ']', '[', ':', '^', 'P', ':', ']', '[', ':', '^', 'S', ':', ']', '[', ':', '^', 'Z', ':', ']', ']' }; static const UniChar capitalized_letter[] = { '[', ':', 'L', 't', ':', ']' }; static const UniChar symbol[] = { '[', ':', 'S', ':', ']' }; static const UniChar newline[] = { '[', '[', '\\', 'u', '0', '0', '0', 'A', '-', '\\', 'u', '0', '0', '0', 'D', ']', '[', '\\', 'u', '0', '0', '8', '5', ']', '[', '\\', 'u', '2', '0', '2', '8', ']', '[', '\\', 'u', '2', '0', '2', '9', ']', ']' }; static const UniChar *predefinedSets[] = { control, whitespace, whitespace_newline, decimal_digit, letter, lowercase_letter, uppercase_letter, non_base, decomposable, alpha_numeric, punctuation, illegal, capitalized_letter, symbol, newline }; static const CFIndex predefinedSetsSize[] = { sizeof(control) / sizeof(UniChar), sizeof(whitespace) / sizeof(UniChar), sizeof(whitespace_newline) / sizeof(UniChar), sizeof(decimal_digit) / sizeof(UniChar), sizeof(letter) / sizeof(UniChar), sizeof(lowercase_letter) / sizeof(UniChar), sizeof(uppercase_letter) / sizeof(UniChar), sizeof(non_base) / sizeof(UniChar), sizeof(decomposable) / sizeof(UniChar), sizeof(alpha_numeric) / sizeof(UniChar), sizeof(punctuation) / sizeof(UniChar), sizeof(illegal) / sizeof(UniChar), sizeof(capitalized_letter) / sizeof(UniChar), sizeof(symbol) / sizeof(UniChar), sizeof(newline) / sizeof(UniChar) }; CFCharacterSetRef CFCharacterSetGetPredefined (CFCharacterSetPredefinedSet setIdentifier) { struct __CFCharacterSet *ret; if (_kCFPredefinedCharacterSets == NULL) { GSMutexLock (&_kCFPredefinedCharacterSetLock); if (_kCFPredefinedCharacterSets == NULL) { /* No need to set callbacks. */ _kCFPredefinedCharacterSets = CFDictionaryCreateMutable (NULL, 15, NULL, &kCFTypeDictionaryValueCallBacks); } GSMutexUnlock (&_kCFPredefinedCharacterSetLock); } ret = (struct __CFCharacterSet*) CFDictionaryGetValue (_kCFPredefinedCharacterSets, (const void*)setIdentifier); if (ret == NULL) { GSMutexLock (&_kCFPredefinedCharacterSetLock); ret = (struct __CFCharacterSet*)_CFRuntimeCreateInstance (NULL, _kCFCharacterSetTypeID, CFCHARACTERSET_SIZE, 0); if (ret) { UErrorCode err = U_ZERO_ERROR; ret->_uset = uset_openPattern (predefinedSets[setIdentifier - 1], predefinedSetsSize[setIdentifier - 1], &err); uset_freeze (ret->_uset); CFDictionaryAddValue (_kCFPredefinedCharacterSets, (const void*)setIdentifier, ret); CFRelease (ret); } GSMutexUnlock (&_kCFPredefinedCharacterSetLock); } return ret; } CFCharacterSetRef CFCharacterSetCreateWithBitmapRepresentation (CFAllocatorRef alloc, CFDataRef data) { return NULL; } CFDataRef CFCharacterSetCreateBitmapRepresentation (CFAllocatorRef alloc, CFCharacterSetRef set) { return NULL; } Boolean CFCharacterSetIsCharacterMember (CFCharacterSetRef set, UniChar c) { return (Boolean)uset_contains (set->_uset, (UChar32)c); } Boolean CFCharacterSetHasMemberInPlane (CFCharacterSetRef set, CFIndex plane) { return false; } Boolean CFCharacterSetIsLongCharacterMember (CFCharacterSetRef set, UTF32Char c) { return (Boolean)uset_contains (set->_uset, (UChar32)c); } Boolean CFCharacterSetIsSupersetOfSet (CFCharacterSetRef set, CFCharacterSetRef otherSet) { return uset_containsAll (set->_uset, otherSet->_uset); } CFMutableCharacterSetRef CFCharacterSetCreateMutable (CFAllocatorRef alloc) { struct __CFCharacterSet *new; new = (struct __CFCharacterSet*)_CFRuntimeCreateInstance (alloc, _kCFCharacterSetTypeID, CFCHARACTERSET_SIZE, 0); if (new) { new->_uset = uset_openEmpty (); } return new; } CFMutableCharacterSetRef CFCharacterSetCreateMutableCopy (CFAllocatorRef alloc, CFCharacterSetRef set) { struct __CFCharacterSet *new; new = (struct __CFCharacterSet*)_CFRuntimeCreateInstance (alloc, _kCFCharacterSetTypeID, CFCHARACTERSET_SIZE, 0); if (new) { new->_uset = uset_cloneAsThawed (set->_uset); } return new; } void CFCharacterSetAddCharactersInRange (CFMutableCharacterSetRef set, CFRange range) { uset_addRange (set->_uset, (UChar32)range.location, (UChar32)(range.location + range.length)); } void CFCharacterSetAddCharactersInString (CFMutableCharacterSetRef set, CFStringRef string) { USetAddString (set->_uset, string); } void CFCharacterSetRemoveCharactersInRange (CFMutableCharacterSetRef set, CFRange range) { uset_removeRange (set->_uset, (UChar32)range.location, (UChar32)(range.location + range.length)); } void CFCharacterSetRemoveCharactersInString (CFMutableCharacterSetRef set, CFStringRef string) { UniChar *str; CFIndex len; len = CFStringGetLength (string); str = CFAllocatorAllocate (NULL, sizeof(UniChar) * len, 0); CFStringGetCharacters (string, CFRangeMake(0, len), str); uset_removeString (set->_uset, str, len); CFAllocatorDeallocate (NULL, str); } void CFCharacterSetIntersect (CFMutableCharacterSetRef set, CFCharacterSetRef otherSet) { uset_retainAll (set->_uset, otherSet->_uset); } void CFCharacterSetInvert (CFMutableCharacterSetRef set) { uset_complement (set->_uset); } void CFCharacterSetUnion (CFMutableCharacterSetRef set, CFCharacterSetRef otherSet) { uset_addAll (set->_uset, otherSet->_uset); } gnustep-corebase-0.2/Source/CFError.c0000644000175000017500000001243313222706330016612 0ustar yavoryavor/* CFError.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: September, 2011 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFError.h" #include "CoreFoundation/CFDictionary.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" CONST_STRING_DECL(kCFErrorDomainPOSIX, "kCFErrorDomainPOSIX"); CONST_STRING_DECL(kCFErrorDomainOSStatus, "kCFErrorDomainOSStatus"); CONST_STRING_DECL(kCFErrorDomainMach, "kCFErrorDomainMach"); CONST_STRING_DECL(kCFErrorDomainCocoa, "kCFErrorDomainCocoa"); CONST_STRING_DECL(kCFErrorLocalizedDescriptionKey, "kCFErrorLocalizedDescriptionKey"); CONST_STRING_DECL(kCFErrorLocalizedFailureReasonKey, "kCFErrorLocalizedFailureReasonKey"); CONST_STRING_DECL(kCFErrorLocalizedRecoverySuggestionKey, "kCFErrorLocalizedRecoverySuggestionKey"); CONST_STRING_DECL(kCFErrorDescriptionKey, "kCFErrorDescriptionKey"); CONST_STRING_DECL(kCFErrorUnderlyingErrorKey, "kCFErrorUnderlyingErrorKey"); struct __CFError { CFRuntimeBase _parent; CFStringRef _domain; CFIndex _code; CFDictionaryRef _userInfo; }; static CFTypeID _kCFErrorTypeID = 0; static void CFErrorFinalize (CFTypeRef cf) { CFErrorRef err = (CFErrorRef)cf; CFRelease (err->_domain); CFRelease (err->_userInfo); } static Boolean CFErrorEqual (CFTypeRef cf1, CFTypeRef cf2) { CFErrorRef err1 = (CFErrorRef)cf1; CFErrorRef err2 = (CFErrorRef)cf2; return err1->_code == err2->_code && CFEqual (err1->_domain, err2->_domain) && CFEqual (err1->_userInfo, err2->_userInfo); } static CFHashCode CFErrorHash (CFTypeRef cf) { return CFHash (((CFErrorRef)cf)->_domain); } static const CFRuntimeClass CFErrorClass = { 0, "CFError", NULL, NULL, CFErrorFinalize, CFErrorEqual, CFErrorHash, NULL, NULL }; void CFErrorInitialize (void) { _kCFErrorTypeID = _CFRuntimeRegisterClass (&CFErrorClass); } CFErrorRef CFErrorCreate (CFAllocatorRef allocator, CFStringRef domain, CFIndex code, CFDictionaryRef userInfo) { struct __CFError *new; if (domain == NULL) return NULL; new = (struct __CFError*)_CFRuntimeCreateInstance (allocator, _kCFErrorTypeID, sizeof(struct __CFError) - sizeof(CFRuntimeBase), 0); if (new) { new->_domain = CFRetain (domain); new->_code = code; if (userInfo != NULL) new->_userInfo = (CFDictionaryRef)CFRetain (userInfo); else new->_userInfo = CFDictionaryCreate(allocator, NULL, NULL, 0, NULL, NULL); } return (CFErrorRef)new; } CFErrorRef CFErrorCreateWithUserInfoKeysAndValues (CFAllocatorRef allocator, CFStringRef domain, CFIndex code, const void *const *userInfoKeys, const void *const *userInfoValues, CFIndex numUserInfoValues) { CFDictionaryRef userInfo = CFDictionaryCreate (allocator, (const void **)userInfoKeys, (const void **)userInfoValues, numUserInfoValues, NULL, NULL); CFErrorRef ret = CFErrorCreate (allocator, domain, code, userInfo); CFRelease (userInfo); return ret; } CFStringRef CFErrorCopyDescription (CFErrorRef err) { CF_OBJC_FUNCDISPATCHV(_kCFErrorTypeID, CFStringRef, err, "localizedDescription"); return CFRetain(CFDictionaryGetValue (err->_userInfo, kCFErrorLocalizedDescriptionKey)); } CFStringRef CFErrorCopyFailureReason (CFErrorRef err) { CF_OBJC_FUNCDISPATCHV(_kCFErrorTypeID, CFStringRef, err, "localizedFailureReason"); return CFRetain(CFDictionaryGetValue (err->_userInfo, kCFErrorLocalizedFailureReasonKey)); } CFStringRef CFErrorCopyRecoverySuggestion (CFErrorRef err) { CF_OBJC_FUNCDISPATCHV(_kCFErrorTypeID, CFStringRef, err, "localizedRecoverySuggestion"); return CFRetain(CFDictionaryGetValue (err->_userInfo, kCFErrorLocalizedRecoverySuggestionKey)); } CFDictionaryRef CFErrorCopyUserInfo (CFErrorRef err) { CF_OBJC_FUNCDISPATCHV(_kCFErrorTypeID, CFDictionaryRef, err, "userInfo"); return CFRetain(err->_userInfo); } CFIndex CFErrorGetCode (CFErrorRef err) { CF_OBJC_FUNCDISPATCHV(_kCFErrorTypeID, CFIndex, err, "code"); return err->_code; } CFStringRef CFErrorGetDomain (CFErrorRef err) { CF_OBJC_FUNCDISPATCHV(_kCFErrorTypeID, CFStringRef, err, "domain"); return err->_domain; } CFTypeID CFErrorGetTypeID (void) { return _kCFErrorTypeID; } gnustep-corebase-0.2/Source/CFStringEncoding.c0000644000175000017500000005532414551015633020451 0ustar yavoryavor/* CFStringEncoding.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: May, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redisibute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is disibuted in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFByteOrder.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFStringEncodingExt.h" #include "GSPrivate.h" #include #include #ifndef _WIN32 #include #endif #if defined(HAVE_UNICODE_UCNV_H) #include #endif #if defined(HAVE_ICU_H) #include #endif static GSMutex _kCFStringEncodingLock; static CFStringEncoding *_kCFStringEncodingList = NULL; static CFStringEncoding _kCFStringSystemEncoding = kCFStringEncodingInvalidId; void CFStringEncodingInitialize (void) { GSMutexInitialize (&_kCFStringEncodingLock); } typedef struct { CFStringEncoding enc; const char *converterName; UInt32 winCodepage; } _str_encoding; /* The values in this table are best guess. */ static _str_encoding str_encoding_table[] = { {kCFStringEncodingMacRoman, "macos-0_2-10.2", 10000}, {kCFStringEncodingMacJapanese, "", 10001}, {kCFStringEncodingMacChineseTrad, "", 10002}, {kCFStringEncodingMacKorean, "", 10003}, {kCFStringEncodingMacArabic, "", 10004}, {kCFStringEncodingMacHebrew, "", 10005}, {kCFStringEncodingMacGreek, "macos-6_2-10.4", 10006}, {kCFStringEncodingMacCyrillic, "macos-7_3-10.2", 10007}, {kCFStringEncodingMacDevanagari, "", 0}, {kCFStringEncodingMacGurmukhi, "", 0}, {kCFStringEncodingMacGujarati, "", 0}, {kCFStringEncodingMacOriya, "", 0}, {kCFStringEncodingMacBengali, "", 0}, {kCFStringEncodingMacTamil, "", 0}, {kCFStringEncodingMacTelugu, "", 0}, {kCFStringEncodingMacKannada, "", 0}, {kCFStringEncodingMacMalayalam, "", 0}, {kCFStringEncodingMacSinhalese, "", 0}, {kCFStringEncodingMacBurmese, "", 0}, {kCFStringEncodingMacKhmer, "", 0}, {kCFStringEncodingMacThai, "", 10021}, {kCFStringEncodingMacLaotian, "", 0}, {kCFStringEncodingMacGeorgian, "", 0}, {kCFStringEncodingMacArmenian, "", 0}, {kCFStringEncodingMacChineseSimp, "", 10008}, {kCFStringEncodingMacTibetan, "", 0}, {kCFStringEncodingMacMongolian, "", 0}, {kCFStringEncodingMacEthiopic, "", 0}, {kCFStringEncodingMacCentralEurRoman, "macos-29-10.2", 10029}, {kCFStringEncodingMacVietnamese, "", 0}, {kCFStringEncodingMacExtArabic, "", 0}, {kCFStringEncodingMacSymbol, "", 0}, {kCFStringEncodingMacDingbats, "", 0}, {kCFStringEncodingMacTurkish, "macos-35-10.2", 10081}, {kCFStringEncodingMacCroatian, "", 10082}, {kCFStringEncodingMacIcelandic, "", 10079}, {kCFStringEncodingMacRomanian, "", 10010}, {kCFStringEncodingMacCeltic, "", 0}, {kCFStringEncodingMacGaelic, "", 0}, {kCFStringEncodingMacFarsi, "", 0}, {kCFStringEncodingMacUkrainian, "", 10017}, {kCFStringEncodingMacInuit, "", 0}, {kCFStringEncodingMacVT100, "", 0}, {kCFStringEncodingMacHFS, "", 0}, {kCFStringEncodingUTF16, "UTF-16", 0}, {kCFStringEncodingUTF7, "UTF-7", 65000}, {kCFStringEncodingUTF8, "UTF-8", 65001}, {kCFStringEncodingUTF16BE, "UTF-16BE", 1201}, {kCFStringEncodingUTF16LE, "UTF-16LE", 1200}, {kCFStringEncodingUTF32, "UTF-32", 0}, {kCFStringEncodingUTF32BE, "UTF-32BE", 12001}, {kCFStringEncodingUTF32LE, "UTF-32LE", 12000}, {kCFStringEncodingISOLatin1, "ISO-8859-1", 28591}, {kCFStringEncodingISOLatin2, "ibm-912_P100-1995", 28592}, {kCFStringEncodingISOLatin3, "ibm-913_P100-2000", 28593}, {kCFStringEncodingISOLatin4, "ibm-914_P100-1995", 28594}, {kCFStringEncodingISOLatinCyrillic, "ibm-915_P100-1995", 28595}, {kCFStringEncodingISOLatinArabic, "ibm-1089_P100-1995", 28596}, {kCFStringEncodingISOLatinGreek, "ibm-9005_X110-2007", 28597}, {kCFStringEncodingISOLatinHebrew, "ibm-5012_P100-1999", 28598}, {kCFStringEncodingISOLatin5, "ibm-920_P100-1995", 28599}, {kCFStringEncodingISOLatin6, "iso-8859_10-1998", 0}, {kCFStringEncodingISOLatinThai, "iso-8859_11-2001", 0}, {kCFStringEncodingISOLatin7, "ibm-921_P100-1995", 28603}, {kCFStringEncodingISOLatin8, "iso-8859_14-1998", 0}, {kCFStringEncodingISOLatin9, "ibm-923_P100-1998", 28605}, {kCFStringEncodingISOLatin10, "iso-8859_16-2001", 0}, {kCFStringEncodingDOSLatinUS, "ibm-437_P100-1995", 437}, {kCFStringEncodingDOSGreek, "ibm-737_P100-1997", 737}, {kCFStringEncodingDOSBalticRim, "ibm-775_P100-1996", 775}, {kCFStringEncodingDOSLatin1, "ibm-850_P100-1995", 850}, {kCFStringEncodingDOSGreek1, "ibm-851_P100-1995", 851}, {kCFStringEncodingDOSLatin2, "ibm-852_P100-1995", 852}, {kCFStringEncodingDOSCyrillic, "ibm-855_P100-1995", 855}, {kCFStringEncodingDOSTurkish, "ibm-857_P100-1995", 857}, {kCFStringEncodingDOSPortuguese, "ibm-860_P100-1995", 860}, {kCFStringEncodingDOSIcelandic, "ibm-861_P100-1995", 861}, {kCFStringEncodingDOSHebrew, "ibm-862_P100-1995", 862}, {kCFStringEncodingDOSCanadianFrench, "ibm-863_P100-1995", 863}, {kCFStringEncodingDOSArabic, "ibm-720_P100-1997", 720}, {kCFStringEncodingDOSNordic, "ibm-865_P100-1995", 865}, {kCFStringEncodingDOSRussian, "ibm-866_P100-1995", 866}, {kCFStringEncodingDOSGreek2, "ibm-869_P100-1995", 869}, {kCFStringEncodingDOSThai, "ibm-874_P100-1995", 874}, {kCFStringEncodingDOSJapanese, "ibm-942_P12A-1999", 932}, {kCFStringEncodingDOSChineseSimplif, "windows-936-2000", 936}, {kCFStringEncodingDOSKorean, "ibm-949_P110-1999", 949}, {kCFStringEncodingDOSChineseTrad, "ibm-950_P110-1999", 950}, {kCFStringEncodingWindowsLatin1, "ibm-5348_P100-1997", 1252}, {kCFStringEncodingWindowsLatin2, "ibm-5346_P100-1998", 1250}, {kCFStringEncodingWindowsCyrillic, "ibm-5347_P100-1998", 1251}, {kCFStringEncodingWindowsGreek, "ibm-5349_P100-1998", 1253}, {kCFStringEncodingWindowsLatin5, "ibm-5350_P100-1998", 1254}, {kCFStringEncodingWindowsHebrew, "ibm-9447_P100-2002", 1255}, {kCFStringEncodingWindowsArabic, "ibm-9448_X100-2005", 1256}, {kCFStringEncodingWindowsBalticRim, "ibm-9449_P100-2002", 1257}, {kCFStringEncodingWindowsVietnamese, "ibm-5354_P100-1998", 1258}, {kCFStringEncodingWindowsKoreanJohab, "", 1361}, {kCFStringEncodingASCII, "US-ASCII", 20127}, {kCFStringEncodingANSEL, "", 0}, {kCFStringEncodingJIS_X0201_76, "ibm-897_P100-1995", 50222}, {kCFStringEncodingJIS_X0208_83, "", 0}, {kCFStringEncodingJIS_X0208_90, "ibm-952_P110-1997", 20932}, {kCFStringEncodingJIS_X0212_90, "ibm-953_P100-2000", 20932}, {kCFStringEncodingJIS_C6226_78, "", 0}, {kCFStringEncodingShiftJIS_X0213, "ibm-943_P15A-2003", 0}, {kCFStringEncodingShiftJIS_X0213_MenKuTen, "", 0}, {kCFStringEncodingGB_2312_80, "ibm-1383_P110-1999", 0}, {kCFStringEncodingGBK_95, "windows-936-2000", 936}, {kCFStringEncodingGB_18030_2000, "gb18030", 54936}, {kCFStringEncodingKSC_5601_87, "ibm-970_P110_P110-2006_U2", 51949}, {kCFStringEncodingKSC_5601_92_Johab, "", 0}, {kCFStringEncodingCNS_11643_92_P1, "", 0}, {kCFStringEncodingCNS_11643_92_P2, "", 0}, {kCFStringEncodingCNS_11643_92_P3, "", 0}, {kCFStringEncodingISO_2022_JP, "ISO_2022,locale=ja,version=0", 50220}, {kCFStringEncodingISO_2022_JP_2, "ISO_2022,locale=ja,version=2", 0}, {kCFStringEncodingISO_2022_JP_1, "ISO_2022,locale=ja,version=1", 50221}, {kCFStringEncodingISO_2022_JP_3, "ISO_2022,locale=ja,version=3", 0}, {kCFStringEncodingISO_2022_CN, "ISO_2022,locale=zh,version=0", 50227}, {kCFStringEncodingISO_2022_CN_EXT, "ISO_2022,locale=zh,version=1", 0}, {kCFStringEncodingISO_2022_KR, "ISO_2022,locale=ko,version=0", 50225}, {kCFStringEncodingEUC_JP, "ibm-33722_P12A_P12A-2004_U2", 51932}, {kCFStringEncodingEUC_CN, "ibm-1383_P110-1999", 51936}, {kCFStringEncodingEUC_TW, "ibm-964_P110-1999", 51950}, {kCFStringEncodingEUC_KR, "ibm-970_P110_P110-2006_U2", 51949}, {kCFStringEncodingShiftJIS, "ibm-943_P15A-2003", 932}, {kCFStringEncodingKOI8_R, "ibm-878_P100-1996", 20866}, {kCFStringEncodingBig5, "windows-950-2000", 950}, {kCFStringEncodingMacRomanLatin1, "", 0}, {kCFStringEncodingHZ_GB_2312, "ibm-1383_P110-1999", 20936}, {kCFStringEncodingBig5_HKSCS_1999, "ibm-1375_P100-2007", 0}, {kCFStringEncodingVISCII, "", 0}, {kCFStringEncodingKOI8_U, "ibm-1168_P100-2002", 21866}, {kCFStringEncodingBig5_E, "", 0}, {kCFStringEncodingUTF7_IMAP, "IMAP-mailbox-name", 0}, {kCFStringEncodingNextStepLatin, "", 0}, {kCFStringEncodingNextStepJapanese, "", 0}, {kCFStringEncodingEBCDIC_US, "ibm-37_P100-1995", 37}, {kCFStringEncodingEBCDIC_CP037, "ibm-37_P100-1995", 37} }; static const CFIndex str_encoding_table_size = sizeof (str_encoding_table) / sizeof (_str_encoding); /* Define this here so we can use it in the NSStringEncoding functions. */ enum { NSASCIIStringEncoding = 1, NSNEXTSTEPStringEncoding = 2, NSJapaneseEUCStringEncoding = 3, NSUTF8StringEncoding = 4, NSISOLatin1StringEncoding = 5, NSSymbolStringEncoding = 6, NSNonLossyASCIIStringEncoding = 7, NSShiftJISStringEncoding = 8, NSISOLatin2StringEncoding = 9, NSUnicodeStringEncoding = 10, NSWindowsCP1251StringEncoding = 11, NSWindowsCP1252StringEncoding = 12, NSWindowsCP1253StringEncoding = 13, NSWindowsCP1254StringEncoding = 14, NSWindowsCP1250StringEncoding = 15, NSISO2022JPStringEncoding = 21, NSMacOSRomanStringEncoding = 30, NSUTF16BigEndianStringEncoding = 0x90000100, NSUTF16LittleEndianStringEncoding = 0x94000100, NSUTF32StringEncoding = 0x8c000100, NSUTF32BigEndianStringEncoding = 0x98000100, NSUTF32LittleEndianStringEncoding = 0x9c000100, }; static CFIndex CFStringEncodingTableIndex (CFStringEncoding encoding) { CFIndex idx = 0; while (idx < str_encoding_table_size && str_encoding_table[idx].enc != encoding) idx++; return idx; } CF_INLINE const char * CFStringICUConverterName (CFStringEncoding encoding) { const char *name; CFIndex idx; idx = CFStringEncodingTableIndex (encoding); name = str_encoding_table[idx].converterName; return name; } static UConverter * GSStringOpenConverter (CFStringEncoding encoding, char lossByte) { const char *converterName; UConverter *cnv; UErrorCode err = U_ZERO_ERROR; converterName = CFStringICUConverterName (encoding); cnv = ucnv_open (converterName, &err); if (U_FAILURE (err)) cnv = NULL; if (lossByte) { /* FIXME: for some reason this is returning U_ILLEGAL_ARGUMENTS_ERROR */ ucnv_setSubstChars (cnv, &lossByte, 1, &err); } else { ucnv_setToUCallBack (cnv, UCNV_TO_U_CALLBACK_STOP, NULL, NULL, NULL, &err); ucnv_setFromUCallBack (cnv, UCNV_FROM_U_CALLBACK_STOP, NULL, NULL, NULL, &err); } return cnv; } CF_INLINE void GSStringCloseConverter (UConverter * cnv) { ucnv_close (cnv); } static CFStringEncoding CFStringConvertStandardNameToEncoding (const char *name, CFIndex length) { #define US_ASCII "US-ASCII" #define UTF_PREFIX "utf-" #define ISO_PREFIX "iso-" #define WIN_PREFIX "windows-" #define CP_PREFIX "cp" #define UTF_LEN sizeof(UTF_PREFIX)-1 #define ISO_LEN sizeof(ISO_PREFIX)-1 #define WIN_LEN sizeof(WIN_PREFIX)-1 #define CP_LEN sizeof(CP_PREFIX)-1 /* FIXME: This isn't a very smart thing to do, but for now it's good enough. */ #if defined(_MSC_VER) #define strncasecmp(a, b, n) lstrcmpiA (a, b) #endif if (length == -1) length = strlen (name); if (strncmp (name, US_ASCII, length) == 0) { return kCFStringEncodingASCII; } else if (strncasecmp (name, UTF_PREFIX, UTF_LEN) == 0) { CFStringEncoding encoding = 0x100; if (strncasecmp (name + UTF_LEN, "8", 1) == 0) return kCFStringEncodingUTF8; else if (strncasecmp (name + UTF_LEN, "7", 1) == 0) return kCFStringEncodingUTF7; if (strncasecmp (name + UTF_LEN, "32", 2) == 0) encoding |= 0x0c000000; if (UTF_LEN + 2 > length) { if (strncasecmp (name + UTF_LEN + 2, "LE", 2) == 0) encoding |= 0x14000000; else if (strncasecmp (name + UTF_LEN + 2, "BE", 2) == 0) encoding |= 0x10000000; } return encoding; } else if (strncasecmp (name, ISO_PREFIX, ISO_LEN) == 0) { if (strncasecmp (name + ISO_LEN, "8859-", 5) == 0) { int num = atoi (name + ISO_LEN + 5); return (num > 16) ? kCFStringEncodingInvalidId : 0x200 + num; } else if (strncasecmp (name + ISO_LEN, "2022-", 5) == 0) { /* FIXME */ } } else if (strncasecmp (name, WIN_PREFIX, WIN_LEN) == 0) { int codepage = atoi (name + WIN_LEN); int idx = 0; while (idx < str_encoding_table_size) { if (str_encoding_table[idx].winCodepage != codepage) return str_encoding_table[idx].enc; ++idx; } } else if (strncasecmp (name, CP_PREFIX, CP_LEN) == 0) { int codepage = atoi (name + CP_LEN); int idx = 0; while (idx < str_encoding_table_size) { if (str_encoding_table[idx].winCodepage != codepage) return str_encoding_table[idx].enc; ++idx; } } else if (strncasecmp (name, "EUC-", sizeof ("EUC-") - 1) == 0) { /* FIXME */ } else if (strncasecmp (name, "macintosh", sizeof ("macintosh") - 1) == 0) { return kCFStringEncodingMacRoman; } return kCFStringEncodingInvalidId; } CFStringRef CFStringConvertEncodingToIANACharSetName (CFStringEncoding encoding) { const char *name; const char *cnvName; UErrorCode err = U_ZERO_ERROR; cnvName = CFStringICUConverterName (encoding); name = ucnv_getStandardName (cnvName, "IANA", &err); if (U_FAILURE (err)) return NULL; /* Using this function here because we don't want to make multiple copies of this string. */ return __CFStringMakeConstantString (name); } unsigned long CFStringConvertEncodingToNSStringEncoding (CFStringEncoding encoding) { switch (encoding) { case kCFStringEncodingASCII: return NSASCIIStringEncoding; case kCFStringEncodingNextStepLatin: return NSNEXTSTEPStringEncoding; case kCFStringEncodingEUC_JP: return NSJapaneseEUCStringEncoding; case kCFStringEncodingUTF8: return NSUTF8StringEncoding; case kCFStringEncodingISOLatin1: return NSISOLatin1StringEncoding; case kCFStringEncodingMacSymbol: return NSSymbolStringEncoding; case kCFStringEncodingNonLossyASCII: return NSNonLossyASCIIStringEncoding; case kCFStringEncodingShiftJIS: return NSShiftJISStringEncoding; case kCFStringEncodingISOLatin2: return NSISOLatin2StringEncoding; case kCFStringEncodingUTF16: return NSUnicodeStringEncoding; case kCFStringEncodingWindowsCyrillic: return NSWindowsCP1251StringEncoding; case kCFStringEncodingWindowsLatin1: return NSWindowsCP1252StringEncoding; case kCFStringEncodingWindowsGreek: return NSWindowsCP1253StringEncoding; case kCFStringEncodingWindowsLatin5: return NSWindowsCP1254StringEncoding; case kCFStringEncodingWindowsLatin2: return NSWindowsCP1250StringEncoding; case kCFStringEncodingISO_2022_JP: return NSISO2022JPStringEncoding; case kCFStringEncodingMacRoman: return NSMacOSRomanStringEncoding; case kCFStringEncodingUTF16BE: return NSUTF16BigEndianStringEncoding; case kCFStringEncodingUTF16LE: return NSUTF16LittleEndianStringEncoding; case kCFStringEncodingUTF32: return NSUTF32StringEncoding; case kCFStringEncodingUTF32BE: return NSUTF32BigEndianStringEncoding; case kCFStringEncodingUTF32LE: return NSUTF32LittleEndianStringEncoding; } return 0; } UInt32 CFStringConvertEncodingToWindowsCodepage (CFStringEncoding encoding) { CFIndex idx = CFStringEncodingTableIndex (encoding); return str_encoding_table[idx].winCodepage; } CFStringEncoding CFStringConvertIANACharSetNameToEncoding (CFStringRef str) { /* We'll start out by checking if it's one of the UTF identifiers, than ISO, Windows codepages, DOS codepages and EUC. Will use strncasecmp because the compare here is not case sensitive. */ char buffer[32]; CFIndex length; if (!CFStringGetCString (str, buffer, 32, kCFStringEncodingASCII)) return kCFStringEncodingInvalidId; length = CFStringGetLength (str); return CFStringConvertStandardNameToEncoding (buffer, length); } CFStringEncoding CFStringConvertNSStringEncodingToEncoding (unsigned long encoding) { switch (encoding) { case NSASCIIStringEncoding: return kCFStringEncodingASCII; case NSNEXTSTEPStringEncoding: return kCFStringEncodingNextStepLatin; case NSJapaneseEUCStringEncoding: return kCFStringEncodingEUC_JP; case NSUTF8StringEncoding: return kCFStringEncodingUTF8; case NSISOLatin1StringEncoding: return kCFStringEncodingISOLatin1; case NSSymbolStringEncoding: return kCFStringEncodingMacSymbol; case NSNonLossyASCIIStringEncoding: return kCFStringEncodingNonLossyASCII; case NSShiftJISStringEncoding: return kCFStringEncodingShiftJIS; case NSISOLatin2StringEncoding: return kCFStringEncodingISOLatin2; case NSUnicodeStringEncoding: return kCFStringEncodingUTF16; case NSWindowsCP1251StringEncoding: return kCFStringEncodingWindowsCyrillic; case NSWindowsCP1252StringEncoding: return kCFStringEncodingWindowsLatin1; case NSWindowsCP1253StringEncoding: return kCFStringEncodingWindowsGreek; case NSWindowsCP1254StringEncoding: return kCFStringEncodingWindowsLatin5; case NSWindowsCP1250StringEncoding: return kCFStringEncodingISOLatin2; case NSISO2022JPStringEncoding: return kCFStringEncodingISO_2022_JP; case NSMacOSRomanStringEncoding: return kCFStringEncodingMacRoman; case NSUTF16BigEndianStringEncoding: return kCFStringEncodingUTF16BE; case NSUTF16LittleEndianStringEncoding: return kCFStringEncodingUTF16LE; case NSUTF32StringEncoding: return kCFStringEncodingUTF32; case NSUTF32BigEndianStringEncoding: return kCFStringEncodingUTF32BE; case NSUTF32LittleEndianStringEncoding: return kCFStringEncodingUTF32LE; } return kCFStringEncodingInvalidId; } CFStringEncoding CFStringConvertWindowsCodepageToEncoding (UInt32 codepage) { CFIndex idx = 0; while (idx < str_encoding_table_size) if (str_encoding_table[idx++].winCodepage == codepage) return str_encoding_table[idx - 1].enc; return kCFStringEncodingInvalidId; } const CFStringEncoding * CFStringGetListOfAvailableEncodings (void) { if (_kCFStringEncodingList == NULL) { GSMutexLock (&_kCFStringEncodingLock); if (_kCFStringEncodingList == NULL) { int32_t count; int32_t idx, pos; const char *name; UErrorCode err = U_ZERO_ERROR; count = ucnv_countAvailable (); _kCFStringEncodingList = CFAllocatorAllocate (NULL, sizeof (CFStringEncoding) * (count + 1), 0); idx = pos = 0; while (idx < count) { name = ucnv_getStandardName (ucnv_getAvailableName (idx), "MIME", &err); if (U_SUCCESS (err) && name != NULL) { _kCFStringEncodingList[pos] = CFStringConvertStandardNameToEncoding (name, -1); ++pos; } ++idx; } _kCFStringEncodingList[pos] = kCFStringEncodingInvalidId; } GSMutexUnlock (&_kCFStringEncodingLock); } return _kCFStringEncodingList; } CFIndex CFStringGetMaximumSizeForEncoding (CFIndex length, CFStringEncoding encoding) { UConverter *cnv; int8_t charSize; switch (encoding) { case kCFStringEncodingUTF16: case kCFStringEncodingUTF16BE: case kCFStringEncodingUTF16LE: charSize = sizeof (UniChar); break; default: cnv = GSStringOpenConverter (encoding, 0); charSize = ucnv_getMaxCharSize (cnv); GSStringCloseConverter (cnv); } return charSize * length; } CFStringEncoding CFStringGetMostCompatibleMacStringEncoding (CFStringEncoding encoding) { return kCFStringEncodingInvalidId; /* FIXME */ } CFStringEncoding CFStringGetSystemEncoding (void) { #if defined(_WIN32) return kCFStringEncodingASCII; #else if (_kCFStringSystemEncoding == kCFStringEncodingInvalidId) { GSMutexLock (&_kCFStringEncodingLock); if (_kCFStringSystemEncoding == kCFStringEncodingInvalidId) { const char *name; const char *defaultName; UErrorCode err = U_ZERO_ERROR; defaultName = ucnv_getDefaultName (); name = ucnv_getStandardName (defaultName, "MIME", &err); if (name != NULL) { _kCFStringSystemEncoding = CFStringConvertStandardNameToEncoding (name, -1); } else { name = ucnv_getStandardName (defaultName, "IANA", &err); if (name != NULL) _kCFStringSystemEncoding = CFStringConvertStandardNameToEncoding (name, -1); else _kCFStringSystemEncoding = kCFStringEncodingInvalidId; } } GSMutexUnlock (&_kCFStringEncodingLock); } return _kCFStringSystemEncoding; #endif } Boolean CFStringIsEncodingAvailable (CFStringEncoding encoding) { const CFStringEncoding *encodings = CFStringGetListOfAvailableEncodings (); while (*encodings != kCFStringEncodingInvalidId) if (*(encodings++) == encoding) return true; return false; } CFStringEncoding CFStringGetFastestEncoding (CFStringRef str) { const UniChar *s = CFStringGetCharactersPtr (str); return s ? kCFStringEncodingUTF16 : kCFStringEncodingASCII; } CFStringEncoding CFStringGetSmallestEncoding (CFStringRef str) { return kCFStringEncodingInvalidId; } CFIndex CFStringGetMaximumSizeOfFileSystemRepresentation (CFStringRef string) { CFIndex length = CFStringGetLength (string); return CFStringGetMaximumSizeForEncoding (length, CFStringGetSystemEncoding ()); } CFStringRef CFStringGetNameOfEncoding (CFStringEncoding encoding) { return NULL; } gnustep-corebase-0.2/Source/CFURLAccess.c0000644000175000017500000003757514551015633017330 0ustar yavoryavor/* CFURLAccess.c Copyright (C) 2012 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: April, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFArray.h" #include "CoreFoundation/CFData.h" #include "CoreFoundation/CFDate.h" #include "CoreFoundation/CFNumber.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFURL.h" #include "CoreFoundation/CFURLAccess.h" #include "GSPrivate.h" #if defined(_WIN32) #include #include #define PATH_MAX MAX_PATH #else #include #include #include #include #include #include #include #ifndef PATH_MAX # ifdef MAXPATHLEN # define PATH_MAX MAXPATHLEN # else # define PATH_MAX 1024 # endif #endif #endif CONST_STRING_DECL (kCFURLFileExists, "kCFURLFileExists"); CONST_STRING_DECL (kCFURLFileDirectoryContents, "kCFURLFileDirectoryContents"); CONST_STRING_DECL (kCFURLFileLength, "kCFURLFileLength"); CONST_STRING_DECL (kCFURLFileLastModificationTime, "kCFURLFileLastModificationTime"); CONST_STRING_DECL (kCFURLFilePOSIXMode, "kCFURLFilePOSIXMode"); CONST_STRING_DECL (kCFURLFileOwnerID, "kCFURLFileOwnerID"); CONST_STRING_DECL (kCFURLHTTPStatusCode, "kCFURLHTTPStatusCode"); CONST_STRING_DECL (kCFURLHTTPStatusLine, "kCFURLHTTPStatusLine"); static Boolean CFFileURLCreateDataAndPropertiesFromResource (CFAllocatorRef alloc, CFURLRef url, CFDataRef * resourceData, CFDictionaryRef * properties, CFArrayRef desiredProperties, SInt32 * errorCode) { #ifdef _WIN32 HANDLE handle; #else int fd; #endif char path[PATH_MAX]; SInt32 error; Boolean exists; CFIndex length; SInt64 modTime; SInt32 mode; SInt32 ownerID; error = 0; exists = false; length = 0; modTime = 0; mode = 0; ownerID = 0; if (!CFURLGetFileSystemRepresentation (url, true, (UInt8 *) path, PATH_MAX)) { if (errorCode) *errorCode = kCFURLUnknownError; return false; } /* We'll check for data first */ #ifdef _WIN32 handle = (void*)CreateFileA( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (handle != INVALID_HANDLE_VALUE) #else fd = open (path, O_RDONLY); if (fd >= 0) #endif // _WIN32 { void *bytes; #ifdef _WIN32 DWORD bytesRead; FILE_STANDARD_INFO finfo = {0}; if (GetFileInformationByHandleEx(handle, FileStandardInfo, &finfo, sizeof(finfo))) { exists = true; length = finfo.EndOfFile.QuadPart; } #else ssize_t bytesRead; struct stat sb; fstat (fd, &sb); /* Might as well gather as much information as we can here */ exists = true; mode = sb.st_mode; ownerID = sb.st_uid; length = sb.st_size; modTime = sb.st_mtime; #endif // _WIN32 if (resourceData) { bytes = CFAllocatorAllocate (alloc, length, 0); #ifdef _WIN32 if (!ReadFile(handle, bytes, length, &bytesRead, NULL)) #else if ((bytesRead = read (fd, bytes, length)) < 0) #endif { error = kCFURLUnknownError; CFAllocatorDeallocate (alloc, bytes); } else { *resourceData = CFDataCreateWithBytesNoCopy (alloc, (const void *)bytes, length, alloc); } } #ifdef _WIN32 CloseHandle(handle); #else close (fd); #endif } else { #ifdef _WIN32 switch (GetLastError()) { case ERROR_ACCESS_DENIED: exists = true; error = kCFURLResourceAccessViolationError; break; case ERROR_FILE_NOT_FOUND: error = kCFURLResourceNotFoundError; break; default: error = kCFURLUnknownError; } #else switch (errno) { case EACCES: exists = true; error = kCFURLResourceAccessViolationError; break; case ENOENT: error = kCFURLResourceNotFoundError; break; default: error = kCFURLUnknownError; } #endif // _WIN32 } /* Now we worry about the properties */ if (properties) { Boolean fetchAll; CFIndex count; CFMutableDictionaryRef props; if (desiredProperties) { fetchAll = false; count = CFArrayGetCount (desiredProperties); } else { fetchAll = true; count = 0; } /* We have a maximum of 6 properties */ props = CFDictionaryCreateMutable (alloc, 6, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); if (fetchAll || CFArrayContainsValue (desiredProperties, CFRangeMake(0, count), kCFURLFileExists)) { CFDictionaryAddValue (props, kCFURLFileExists, exists ? kCFBooleanTrue : kCFBooleanFalse); } if (exists) { if (CFURLHasDirectoryPath (url) && (fetchAll || CFArrayContainsValue (desiredProperties, CFRangeMake(0, count), kCFURLFileDirectoryContents))) { #ifdef _WIN32 #warning Directory enumeration not implemented on Windows #else DIR *dir; struct dirent *entry; dir = opendir (path); if (dir) { CFArrayRef array; CFMutableArrayRef tmp; tmp = CFArrayCreateMutable (alloc, 0,&kCFTypeArrayCallBacks); while ((entry = readdir (dir)) != NULL) { if (strncmp (entry->d_name, ".", 2) != 0 && strncmp (entry->d_name, "..", 3) != 0) { CFStringRef str; str = CFStringCreateWithFileSystemRepresentation ( alloc, entry->d_name); CFArrayAppendValue (tmp, str); CFRelease (str); } } closedir (dir); array = CFArrayCreateCopy (alloc, tmp); CFRelease (tmp); CFDictionaryAddValue (props, kCFURLFileDirectoryContents, array); CFRelease (array); } else { error = kCFURLUnknownError; } #endif // _WIN32 } if (fetchAll || CFArrayContainsValue (desiredProperties, CFRangeMake(0, count), kCFURLFileLength)) { CFNumberRef len; len = CFNumberCreate (alloc, kCFNumberCFIndexType, &length); CFDictionaryAddValue (props, kCFURLFileLength, len); CFRelease (len); } if (fetchAll || CFArrayContainsValue (desiredProperties, CFRangeMake(0, count), kCFURLFileLastModificationTime)) { CFDateRef date; CFAbsoluteTime at; at = ((CFAbsoluteTime)modTime) - kCFAbsoluteTimeIntervalSince1970; date = CFDateCreate (alloc, at); CFDictionaryAddValue (props, kCFURLFileLastModificationTime, date); CFRelease (date); } if (fetchAll || CFArrayContainsValue (desiredProperties, CFRangeMake(0, count), kCFURLFilePOSIXMode)) { CFNumberRef num; num = CFNumberCreate (alloc, kCFNumberSInt32Type, &mode); CFDictionaryAddValue (props, kCFURLFilePOSIXMode, num); CFRelease (num); } if (fetchAll || CFArrayContainsValue (desiredProperties, CFRangeMake(0, count), kCFURLFileOwnerID)) { CFNumberRef num; num = CFNumberCreate (alloc, kCFNumberSInt32Type, &ownerID); CFDictionaryAddValue (props, kCFURLFileOwnerID, num); CFRelease (num); } } *properties = CFDictionaryCreateCopy (alloc, props); CFRelease (props); } if (error < 0) { if (errorCode) *errorCode = error; return false; } return true; } Boolean CFURLCreateDataAndPropertiesFromResource (CFAllocatorRef alloc, CFURLRef url, CFDataRef * resourceData, CFDictionaryRef * properties, CFArrayRef desiredProperties, SInt32 * errorCode) { CFStringRef scheme; SInt32 error; scheme = CFURLCopyScheme (url); if (scheme == NULL) { error = kCFURLImproperArgumentsError; } else if (CFStringCompare (scheme, CFSTR ("file"), 0) == kCFCompareEqualTo) { CFRelease (scheme); return CFFileURLCreateDataAndPropertiesFromResource (alloc, url, resourceData, properties, desiredProperties, errorCode); } else if (CFStringCompare (scheme, CFSTR ("http"), 0) == kCFCompareEqualTo) { /* FIXME */ error = kCFURLUnknownSchemeError; } else { error = kCFURLUnknownSchemeError; } if (scheme) CFRelease (scheme); if (errorCode) *errorCode = error; return false; } CFTypeRef CFURLCreatePropertyFromResource (CFAllocatorRef alloc, CFURLRef url, CFStringRef property, SInt32 * errorCode) { CFDictionaryRef dict; CFArrayRef array; CFTypeRef ret = NULL; array = CFArrayCreate (alloc, (const void **) &property, 1, NULL); if (CFURLCreateDataAndPropertiesFromResource (alloc, url, NULL, &dict, array, errorCode) == true) { ret = CFRetain (CFDictionaryGetValue (dict, property)); CFRelease (dict); } CFRelease (array); return ret; } Boolean CFURLDestroyResource (CFURLRef url, SInt32 * errorCode) { CFStringRef scheme; SInt32 error; scheme = CFURLCopyScheme (url); error = 0; if (scheme == NULL) { error = kCFURLImproperArgumentsError; } else if (CFStringCompare (scheme, CFSTR ("file"), 0) == kCFCompareEqualTo) { char path[PATH_MAX]; if (!CFURLGetFileSystemRepresentation (url, true, (UInt8 *) path, PATH_MAX)) { CFRelease (scheme); if (errorCode) *errorCode = kCFURLUnknownError; return false; } if (CFURLHasDirectoryPath (url)) { #if _WIN32 if (_rmdir(path) < 0) #else if (rmdir (path) < 0) #endif error = kCFURLUnknownError; } else { #if _WIN32 if (DeleteFile(path) == FALSE) #else if (unlink (path) < 0) #endif error = kCFURLUnknownError; } } else if (CFStringCompare (scheme, CFSTR ("http"), 0) == kCFCompareEqualTo) { /* FIXME */ error = kCFURLUnknownSchemeError; } else { error = kCFURLUnknownSchemeError; } if (scheme) CFRelease (scheme); if (error < 0) { if (errorCode) *errorCode = error; return false; } return true; } Boolean CFURLWriteDataAndPropertiesToResource (CFURLRef url, CFDataRef dataToWrite, CFDictionaryRef propertiesToWrite, SInt32 * errorCode) { CFStringRef scheme; SInt32 error; scheme = CFURLCopyScheme (url); error = 0; if (scheme == NULL) { error = kCFURLImproperArgumentsError; } else if (CFStringCompare (scheme, CFSTR ("file"), 0) == kCFCompareEqualTo) { char path[PATH_MAX]; int mode; if (!CFURLGetFileSystemRepresentation (url, true, (UInt8*)path, PATH_MAX)) { CFRelease (scheme); if (errorCode) *errorCode = kCFURLUnknownError; return false; } mode = CFURLHasDirectoryPath (url) ? 0755 : 0644; if (propertiesToWrite) { /* All other properties are going to be disregarded */ CFTypeRef num; if (CFDictionaryGetValueIfPresent (propertiesToWrite, kCFURLFilePOSIXMode, &num)) CFNumberGetValue (num, kCFNumberIntType, &mode); } if (CFURLHasDirectoryPath (url)) { #ifdef _WIN32 if (CreateDirectoryA(path, NULL) == 0) #else if (mkdir (path, mode) < 0) #endif error = kCFURLUnknownError; } else { #ifdef _WIN32 HANDLE handle; DWORD wr; handle = (void*)CreateFileA( path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (handle != INVALID_HANDLE_VALUE) #else int fd; fd = open (path, O_WRONLY | O_TRUNC | O_CREAT, mode); if (fd >= 0) #endif // _WIN32 { if (dataToWrite) { CFIndex length; const void *buf; length = CFDataGetLength (dataToWrite); buf = CFDataGetBytePtr (dataToWrite); if (length > 0) { #ifdef _WIN32 if (!WriteFile(handle, buf, length, &wr, NULL) || wr != length) #else if (write (fd, buf, length) != length) #endif error = kCFURLUnknownError; } } #ifdef _WIN32 CloseHandle(handle); #else close (fd); #endif } else { error = kCFURLUnknownError; } } } else if (CFStringCompare (scheme, CFSTR ("http"), 0) == kCFCompareEqualTo) { /* FIXME */ error = kCFURLUnknownSchemeError; } else { error = kCFURLUnknownSchemeError; } if (scheme) CFRelease (scheme); if (error < 0) { if (errorCode) *errorCode = error; return false; } return true; } gnustep-corebase-0.2/Source/CFArray.c0000644000175000017500000004272213222706330016603 0ustar yavoryavor/* CFArray.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: October, 2011 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFArray.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFString.h" #include "GSCArray.h" #include "GSObjCRuntime.h" #include struct __CFArray { CFRuntimeBase _parent; const CFArrayCallBacks *_callBacks; const void **_contents; CFIndex _count; }; struct __CFMutableArray { CFRuntimeBase _parent; const CFArrayCallBacks *_callBacks; const void **_contents; CFIndex _count; CFIndex _capacity; }; static CFTypeID _kCFArrayTypeID = 0; enum { _kCFArrayIsMutable = (1 << 0) }; CF_INLINE Boolean CFArrayIsMutable (CFArrayRef array) { return ((CFRuntimeBase *) array)->_flags.info & _kCFArrayIsMutable ? true : false; } CF_INLINE void CFArraySetMutable (CFArrayRef array) { ((CFRuntimeBase *) array)->_flags.info |= _kCFArrayIsMutable; } const CFArrayCallBacks kCFTypeArrayCallBacks = { 0, CFTypeRetainCallBack, CFTypeReleaseCallBack, CFCopyDescription, CFEqual }; /* Internal structure in case NULL is passed as the callback */ static CFArrayCallBacks _kCFNullArrayCallBacks = { 0, NULL, NULL, NULL, NULL }; static void CFArrayFinalize (CFTypeRef cf) { CFIndex idx; CFArrayRef array = (CFArrayRef) cf; CFArrayReleaseCallBack release = array->_callBacks->release; CFAllocatorRef alloc = CFGetAllocator (array); if (release) { for (idx = 0; idx < array->_count; ++idx) release (alloc, array->_contents[idx]); } if (CFArrayIsMutable (array)) CFAllocatorDeallocate (alloc, array->_contents); } static Boolean CFArrayEqual (CFTypeRef cf1, CFTypeRef cf2) { CFArrayRef a1 = (CFArrayRef) cf1; CFArrayRef a2 = (CFArrayRef) cf2; if (a1->_count != a2->_count) return false; if (a1->_count > 0) { Boolean result; CFIndex idx; CFArrayEqualCallBack equal = a1->_callBacks->equal; for (idx = 0; idx < a1->_count; ++idx) { result = equal ? equal (a1->_contents[idx], a2->_contents[idx]) : a1->_contents[idx] == a2->_contents[idx]; if (result == false) return false; } } return true; } static CFHashCode CFArrayHash (CFTypeRef cf) { return CFArrayGetCount (cf); } static CFStringRef CFArrayCopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOptions) { CFIndex idx; CFStringRef ret; CFMutableStringRef str; CFArrayRef array = (CFArrayRef) cf; CFArrayCopyDescriptionCallBack copyDesc = array->_callBacks->copyDescription; str = CFStringCreateMutable (NULL, 0); CFStringAppend (str, CFSTR ("{")); if (copyDesc) { for (idx = 0; idx < array->_count; ++idx) { CFStringRef desc = copyDesc (array->_contents[idx]); CFStringAppendFormat (str, formatOptions, CFSTR ("%@, "), desc); CFRelease (desc); } } else { for (idx = 0; idx < array->_count; ++idx) CFStringAppendFormat (str, formatOptions, CFSTR ("%p, "), array->_contents[idx]); } CFStringDelete (str, CFRangeMake (CFStringGetLength (str), 2)); CFStringAppend (str, CFSTR ("}")); ret = CFStringCreateCopy (NULL, str); CFRelease (str); return ret; } static CFRuntimeClass CFArrayClass = { 0, "CFArray", NULL, (CFTypeRef (*)(CFAllocatorRef, CFTypeRef)) CFArrayCreateCopy, CFArrayFinalize, CFArrayEqual, CFArrayHash, CFArrayCopyFormattingDesc, NULL }; void CFArrayInitialize (void) { _kCFArrayTypeID = _CFRuntimeRegisterClass (&CFArrayClass); } #define CFARRAY_SIZE sizeof(struct __CFArray) - sizeof(CFRuntimeBase) CFArrayRef CFArrayCreate (CFAllocatorRef allocator, const void **values, CFIndex numValues, const CFArrayCallBacks * callBacks) { struct __CFArray *new; CFIndex size; CFIndex idx; CFArrayRetainCallBack retain; size = CFARRAY_SIZE + (sizeof (void *) * numValues); new = (struct __CFArray *) _CFRuntimeCreateInstance (allocator, _kCFArrayTypeID, size, 0); if (new) { if (callBacks == NULL) callBacks = &_kCFNullArrayCallBacks; new->_callBacks = callBacks; new->_contents = (const void **) &new[1]; new->_count = numValues; memcpy (new->_contents, values, numValues * sizeof (void *)); retain = callBacks->retain; if (retain) for (idx = 0; idx < numValues; ++idx) retain (allocator, values[idx]); } return (CFArrayRef) new; } CFArrayRef CFArrayCreateCopy (CFAllocatorRef allocator, CFArrayRef array) { if (CF_IS_OBJC (_kCFArrayTypeID, array)) { const void **values; CFIndex count; CFArrayRef copy; count = CFArrayGetCount (array); values = (const void **) CFAllocatorAllocate (allocator, sizeof (const void *) * count, 0); CFArrayGetValues (array, CFRangeMake (0, count), values); copy = CFArrayCreate (allocator, values, count, &kCFTypeArrayCallBacks); CFAllocatorDeallocate (allocator, (void *) values); return copy; } return CFArrayCreate (allocator, array->_contents, array->_count, array->_callBacks); } void CFArrayApplyFunction (CFArrayRef array, CFRange range, CFArrayApplierFunction applier, void *context) { CFIndex i; for (i = range.location; i < range.location + range.length; i++) applier (CFArrayGetValueAtIndex (array, i), context); } CFIndex CFArrayBSearchValues (CFArrayRef array, CFRange range, const void *value, CFComparatorFunction comparator, void *context) { CFIndex min, max, mid; min = range.location; max = range.location + range.length - 1; while (min <= max) { const void *midValue; CFComparisonResult res; mid = (min + max) / 2; midValue = CFArrayGetValueAtIndex (array, mid); res = comparator (midValue, value, context); if (res == kCFCompareEqualTo) { max = mid - 1; break; } else if (res == kCFCompareGreaterThan) { max = mid - 1; } else { min = mid + 1; } } return max + 1; } Boolean CFArrayContainsValue (CFArrayRef array, CFRange range, const void *value) { return (CFArrayGetFirstIndexOfValue (array, range, value) != -1); } CFIndex CFArrayGetCount (CFArrayRef array) { CF_OBJC_FUNCDISPATCHV (_kCFArrayTypeID, CFIndex, array, "count"); return array->_count; } CFIndex CFArrayGetCountOfValue (CFArrayRef array, CFRange range, const void *value) { CFIndex count = 0; CFIndex i; while ((i = CFArrayGetFirstIndexOfValue (array, range, value)) != -1) { count++; range.location = i + 1; range.length = range.length - range.location; } return count; } CFIndex CFArrayGetFirstIndexOfValue (CFArrayRef array, CFRange range, const void *value) { CF_OBJC_FUNCDISPATCHV (_kCFArrayTypeID, CFIndex, array, "indexOfObject:inRange:", value, range); const void **contents; CFIndex idx; CFIndex end; CFArrayEqualCallBack equal; contents = array->_contents; idx = range.location; end = idx + range.length; equal = array->_callBacks->equal; if (equal) { while (idx < end) { if (equal (value, contents[idx])) break; idx++; } } else { while (idx < end) { if (value == contents[idx]) break; idx++; } } if (idx >= end) idx = -1; return idx; } CFIndex CFArrayGetLastIndexOfValue (CFArrayRef array, CFRange range, const void *value) { CFArrayEqualCallBack equal; CFIndex idx; CFIndex start; if (CF_IS_OBJC (_kCFArrayTypeID, array)) equal = kCFTypeArrayCallBacks.equal; else equal = array->_callBacks->equal; start = range.location; idx = start + range.length; if (equal) { while (idx >= start) { if (equal (value, CFArrayGetValueAtIndex (array, idx))) break; --idx; } } else { while (idx >= start) { if (value == CFArrayGetValueAtIndex (array, idx)) break; --idx; } } if (idx < start) idx = -1; return idx; } CFTypeID CFArrayGetTypeID (void) { return _kCFArrayTypeID; } const void * CFArrayGetValueAtIndex (CFArrayRef array, CFIndex idx) { CF_OBJC_FUNCDISPATCHV (_kCFArrayTypeID, const void *, array, "objectAtIndex:", idx); return (array->_contents)[idx]; } void CFArrayGetValues (CFArrayRef array, CFRange range, const void **values) { CF_OBJC_FUNCDISPATCHV (_kCFArrayTypeID, void, array, "getObjects:range:", values, range); memcpy (values, (array->_contents + range.location), range.length * sizeof (const void *)); } #define DEFAULT_ARRAY_CAPACITY 16 #define CFMUTABLEARRAY_SIZE sizeof(struct __CFMutableArray) - sizeof(CFRuntimeBase) CF_INLINE void CFArrayCheckCapacityAndGrow (CFMutableArrayRef array, CFIndex newCapacity) { struct __CFMutableArray *mArray = (struct __CFMutableArray *) array; if (mArray->_capacity < newCapacity) { newCapacity = mArray->_capacity + DEFAULT_ARRAY_CAPACITY; mArray->_contents = CFAllocatorReallocate (CFGetAllocator (mArray), mArray->_contents, (newCapacity * sizeof (const void *)), 0); mArray->_capacity = newCapacity; } } CFMutableArrayRef CFArrayCreateMutable (CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks * callBacks) { struct __CFMutableArray *new; new = (struct __CFMutableArray *) _CFRuntimeCreateInstance (allocator, _kCFArrayTypeID, CFMUTABLEARRAY_SIZE, 0); if (new) { if (callBacks == NULL) callBacks = &_kCFNullArrayCallBacks; new->_callBacks = callBacks; if (capacity < DEFAULT_ARRAY_CAPACITY) capacity = DEFAULT_ARRAY_CAPACITY; new->_contents = CFAllocatorAllocate (allocator, capacity * sizeof (void *), 0); new->_count = 0; new->_capacity = capacity; CFArraySetMutable ((CFArrayRef) new); } return (CFMutableArrayRef) new; } CFMutableArrayRef CFArrayCreateMutableCopy (CFAllocatorRef allocator, CFIndex capacity, CFArrayRef array) { if (CF_IS_OBJC (_kCFArrayTypeID, array)) { const void **values; CFIndex count, i; CFMutableArrayRef copy; count = CFArrayGetCount (array); values = (const void **) CFAllocatorAllocate (allocator, sizeof (const void *) * count, 0); CFArrayGetValues (array, CFRangeMake (0, count), values); if (count > capacity) capacity = count; copy = CFArrayCreateMutable (allocator, capacity, &kCFTypeArrayCallBacks); for (i = 0; i < count; i++) CFArrayAppendValue (copy, values[i]); CFAllocatorDeallocate (allocator, (void *) values); return copy; } CFMutableArrayRef new; const CFArrayCallBacks *callbacks; if (!array) return NULL; if (CF_IS_OBJC (_kCFArrayTypeID, array)) callbacks = &kCFTypeArrayCallBacks; else callbacks = array->_callBacks; new = CFArrayCreateMutable (allocator, capacity, callbacks); if (new) { CFIndex idx; CFIndex count; for (idx = 0, count = CFArrayGetCount (array); idx < count; ++idx) { new->_contents[idx] = callbacks->retain ? callbacks->retain (NULL, CFArrayGetValueAtIndex (array, idx)) : CFArrayGetValueAtIndex (array, idx); } new->_count = count; } return new; } void CFArrayAppendArray (CFMutableArrayRef array, CFArrayRef oArray, CFRange oRange) { CFIndex oLen; const void **values; CF_OBJC_FUNCDISPATCHV (_kCFArrayTypeID, void, array, "replaceObjectsInRange:withObjectsFromArray:range:", CFRangeMake (CFArrayGetCount (array), 0), oArray, oRange); oLen = oRange.length; values = CFAllocatorAllocate (NULL, oLen * sizeof (void *), 0); CFArrayGetValues (oArray, oRange, values); CFArrayReplaceValues (array, CFRangeMake (array->_count, 0), values, oLen); CFAllocatorDeallocate (NULL, values); } void CFArrayAppendValue (CFMutableArrayRef array, const void *value) { CF_OBJC_FUNCDISPATCHV (_kCFArrayTypeID, void, array, "addObject:", value); CFArrayReplaceValues (array, CFRangeMake (array->_count, 0), &value, 1); } void CFArrayExchangeValuesAtIndices (CFMutableArrayRef array, CFIndex idx1, CFIndex idx2) { const void *tmp; CF_OBJC_FUNCDISPATCHV (_kCFArrayTypeID, void, array, "exchangeObjectAtIndex:withObjectAtIndex:", idx1, idx2); tmp = array->_contents[idx1]; array->_contents[idx1] = array->_contents[idx2]; array->_contents[idx2] = tmp; } void CFArrayInsertValueAtIndex (CFMutableArrayRef array, CFIndex idx, const void *value) { CF_OBJC_FUNCDISPATCHV (_kCFArrayTypeID, void, array, "insertObject:AtIndex:", value, idx); CFArrayReplaceValues (array, CFRangeMake (idx, 0), &value, 1); } void CFArrayRemoveAllValues (CFMutableArrayRef array) { CF_OBJC_FUNCDISPATCHV (_kCFArrayTypeID, void, array, "removeAllObjects"); CFArrayReplaceValues (array, CFRangeMake (0, array->_count), NULL, 0); memset (array->_contents, 0, array->_count * sizeof (void *)); } void CFArrayRemoveValueAtIndex (CFMutableArrayRef array, CFIndex idx) { CF_OBJC_FUNCDISPATCHV (_kCFArrayTypeID, void, array, "removeObjectAtIndex:", idx); CFArrayReplaceValues (array, CFRangeMake (idx, 1), NULL, 0); } void CFArrayReplaceValues (CFMutableArrayRef array, CFRange range, const void **newValues, CFIndex newCount) { if (CF_IS_OBJC (_kCFArrayTypeID, array)) { CFArrayRef temp; temp = CFArrayCreate (kCFAllocatorDefault, newValues, newCount, &kCFTypeArrayCallBacks); CF_OBJC_VOIDCALLV (array, "replaceObjectsInRange:withObjectsFromArray:", range, temp); CFRelease (temp); return; } const void **start; const void **end; CFAllocatorRef alloc; start = array->_contents + range.location; end = start + range.length; alloc = CFGetAllocator (array); /* Release values if needed */ if (range.length > 0) { CFArrayReleaseCallBack release = array->_callBacks->release; if (release) { const void **current = start; while (current < end) release (alloc, *(current++)); } array->_count -= range.length; } /* Move remaining values if required */ if (range.length != newCount) { CFIndex newSize; newSize = array->_count - range.length + newCount; CFArrayCheckCapacityAndGrow (array, newSize); memmove (start + newCount, end, (array->_count - range.location + range.length) * sizeof (void *)); } /* Insert new values */ if (newCount > 0) { CFArrayRetainCallBack retain = array->_callBacks->retain; const void **current = start; end = current + newCount; /* New end... */ if (retain) { while (current < end) *(current++) = retain (alloc, *(newValues++)); } else { while (current < end) *(current++) = *(newValues++); } array->_count += newCount; } } void CFArraySetValueAtIndex (CFMutableArrayRef array, CFIndex idx, const void *value) { CF_OBJC_FUNCDISPATCHV (_kCFArrayTypeID, void, array, "replaceObjectAtIndex:withObject:", idx, value); CFArrayReplaceValues (array, CFRangeMake (idx, 1), &value, 1); } void CFArraySortValues (CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) { CF_OBJC_FUNCDISPATCHV (_kCFArrayTypeID, void, array, "sortUsingFunction:context:", comparator, context); GSCArrayQuickSort (array->_contents + range.location, range.length, comparator, context); } gnustep-corebase-0.2/Source/CFTree.c0000644000175000017500000001365313222706330016425 0ustar yavoryavor/* CFTree.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFTree.h" #include static CFTypeID _kCFTreeTypeID = 0; struct __CFTree { CFRuntimeBase parent; CFTreeContext _context; CFTreeRef _parent; CFTreeRef _nextSibling; CFTreeRef _firstChild; CFTreeRef _lastChild; }; static CFTreeContext _kCFNullTreeContext = { 0, NULL, NULL, NULL, NULL }; static void CFTreeFinalize (CFTypeRef cf) { CFTreeRef tree = (CFTreeRef)cf; CFTreeRef child; CFTreeRef tmp; CFTreeReleaseCallBack release; child = tree->_firstChild; while (child) { tmp = child->_nextSibling; CFTreeFinalize (child); /* No need to go through CFRelease(). */ child = tmp; } release = tree->_context.release; if (release) release (tree); } static CFRuntimeClass CFTreeClass = { 0, "CFTree", NULL, NULL, CFTreeFinalize, NULL, NULL, NULL, NULL }; void CFTreeInitialize (void) { _kCFTreeTypeID = _CFRuntimeRegisterClass (&CFTreeClass); } CFTypeID CFTreeGetTypeID (void) { return _kCFTreeTypeID; } #define CFTREE_SIZE (sizeof(struct __CFTree) - sizeof(CFRuntimeBase)) CFTreeRef CFTreeCreate (CFAllocatorRef allocator, const CFTreeContext *context) { CFTreeRef new; new = (CFTreeRef)_CFRuntimeCreateInstance (allocator, _kCFTreeTypeID, CFTREE_SIZE, 0); if (new) { if (context == NULL) context = &_kCFNullTreeContext; memcpy (&new->_context, context, sizeof(CFTreeContext)); } return new; } void CFTreeAppendChild (CFTreeRef tree, CFTreeRef newChild) { CFTreeRetainCallBack retain = newChild->_context.retain; newChild->_parent = tree; if (retain) retain (newChild); if (tree->_firstChild == NULL) { tree->_firstChild = newChild; tree->_lastChild = newChild; } else { tree->_lastChild->_nextSibling = newChild; tree->_lastChild = newChild; } } void CFTreeInsertSibling (CFTreeRef tree, CFTreeRef newSibling) { CFTreeRef parent = tree->_parent; if (parent != NULL && newSibling->_parent == NULL) { CFTreeRetainCallBack retain = newSibling->_context.retain; newSibling->_parent = parent; if (retain) retain (newSibling); if (parent->_lastChild == tree) parent->_lastChild = newSibling; else newSibling->_nextSibling = tree->_nextSibling; tree->_nextSibling = newSibling; } } void CFTreeRemoveAllChildren (CFTreeRef tree) { CFTreeRef child; CFTreeRef tmp; child = tree->_firstChild; while (child) { tmp = child->_nextSibling; CFTreeFinalize (child); child = tmp; } tree->_firstChild = NULL; tree->_lastChild = NULL; } void CFTreePrependChild (CFTreeRef tree, CFTreeRef newChild) { newChild->_parent = tree; newChild->_nextSibling = tree->_firstChild; tree->_firstChild = newChild; if (tree->_lastChild == NULL) tree->_lastChild = NULL; } void CFTreeRemove (CFTreeRef tree) { CFTreeRef child; CFTreeRef previousSibling; previousSibling = NULL; child = tree->_firstChild; while (child != previousSibling) child = child->_nextSibling; if (previousSibling) previousSibling->_nextSibling = tree->_nextSibling; CFTreeFinalize (tree); } void CFTreeSetContext (CFTreeRef tree, const CFTreeContext *context) { if (context == NULL) context = &_kCFNullTreeContext; memcpy (&tree->_context, context, sizeof(CFTreeContext)); } void CFTreeSortChildren (CFTreeRef tree, CFComparatorFunction comp, void *context) { /* FIXME */ } CFTreeRef CFTreeFindRoot (CFTreeRef tree) { while (tree->_parent != NULL) tree = tree->_parent; return tree; } CFTreeRef CFTreeGetChildAtIndex (CFTreeRef tree, CFIndex idx) { CFIndex j; CFTreeRef child; j = 0; child = tree->_firstChild; while (j++ < idx) child = child->_nextSibling; return child; } CFIndex CFTreeGetChildCount (CFTreeRef tree) { CFIndex count; CFTreeRef child; count = 0; child = tree->_firstChild; while (child) { child = child->_nextSibling; ++count; } return count; } void CFTreeGetChildren (CFTreeRef tree, CFTreeRef *children) { CFIndex idx; CFTreeRef child; idx = 0; child = tree->_firstChild; while (child) { children[idx++] = child; child = child->_nextSibling; } } void CFTreeGetContext (CFTreeRef tree, CFTreeContext *context) { memcpy (context, &tree->_context, sizeof(CFTreeContext)); } CFTreeRef CFTreeGetFirstChild (CFTreeRef tree) { return tree->_firstChild; } CFTreeRef CFTreeGetNextSibling (CFTreeRef tree) { return tree->_nextSibling; } CFTreeRef CFTreeGetParent (CFTreeRef tree) { return tree->_parent; } void CFTreeApplyFunctionToChildren (CFTreeRef tree, CFTreeApplierFunction applier, void *context) { CFTreeRef child; child = tree->_firstChild; while (child) { applier (child, context); child = child->_nextSibling; } } gnustep-corebase-0.2/Source/CFStringUtilities.c0000644000175000017500000002417114551015633020672 0ustar yavoryavor/* CFStringUtilities.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: May, 2011 This file is part of GNUstep CoreBase Library. This library is free software; you can redisibute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is disibuted in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFArray.h" #include "CoreFoundation/CFCharacterSet.h" #include "CoreFoundation/CFLocale.h" #include "CoreFoundation/CFString.h" #include "GSPrivate.h" #if defined(HAVE_UNICODE_UCOL_H) #include #endif #if defined(HAVE_UNICODE_ULOC_H) #include #endif #if defined(HAVE_UNICODE_USEARCH_H) #include #endif #if defined(HAVE_ICU_H) #include #endif CF_INLINE UCollator * CFStringICUCollatorOpen (CFStringCompareFlags options, CFLocaleRef loc) { const char *cLocale; char buffer[ULOC_FULLNAME_CAPACITY]; UCollator *ret; UErrorCode err = U_ZERO_ERROR; if (loc != NULL && (options & kCFCompareLocalized)) cLocale = CFLocaleGetCStringIdentifier (loc, buffer, ULOC_FULLNAME_CAPACITY); else cLocale = NULL; ret = ucol_open (cLocale, &err); if (options) { if (options & kCFCompareCaseInsensitive) ucol_setAttribute (ret, UCOL_CASE_LEVEL, UCOL_OFF, &err); if (options & kCFCompareNonliteral) ucol_setAttribute (ret, UCOL_ALTERNATE_HANDLING, UCOL_SHIFTED, &err); if (options & kCFCompareNumerically) ucol_setAttribute (ret, UCOL_NUMERIC_COLLATION, UCOL_ON, &err); if (options & kCFCompareDiacriticInsensitive) ucol_setAttribute (ret, UCOL_NORMALIZATION_MODE, UCOL_ON, &err); /* FIXME if (compareOptions & kCFCompareWidthInsensitive) */ if (options & kCFCompareForcedOrdering) ucol_setAttribute (ret, UCOL_STRENGTH, UCOL_IDENTICAL, &err); } return ret; } CF_INLINE void CFStringICUCollatorClose (UCollator *collator) { ucol_close (collator); } CFRange CFStringFind (CFStringRef str, CFStringRef stringToFind, CFStringCompareFlags compareOptions) { CFRange ret; CFIndex len = CFStringGetLength (str); if (!CFStringFindWithOptionsAndLocale (str, stringToFind, CFRangeMake(0, len), compareOptions, NULL, &ret)) ret = CFRangeMake (kCFNotFound, 0); return ret; } Boolean CFStringFindWithOptions (CFStringRef str, CFStringRef stringToFind, CFRange rangeToSearch, CFStringCompareFlags searchOptions, CFRange *result) { return CFStringFindWithOptionsAndLocale (str, stringToFind, rangeToSearch, searchOptions, NULL, result); } Boolean CFStringFindWithOptionsAndLocale (CFStringRef str, CFStringRef stringToFind, CFRange rangeToSearch, CFStringCompareFlags searchOptions, CFLocaleRef locale, CFRange *result) { UniChar *pattern; UniChar *text; CFIndex patternLength; CFIndex textLength; CFIndex start; CFIndex end; CFAllocatorRef alloc; UCollator *ucol; UStringSearch *usrch; UErrorCode err = U_ZERO_ERROR; if (rangeToSearch.length == 0) return false; alloc = CFAllocatorGetDefault (); textLength = CFStringGetLength (stringToFind); if (textLength == 0) return false; patternLength = rangeToSearch.length; pattern = CFAllocatorAllocate (alloc, patternLength * sizeof(UniChar), 0); CFStringGetCharacters (str, rangeToSearch, pattern); text = CFAllocatorAllocate (alloc, textLength * sizeof(UniChar), 0); CFStringGetCharacters (stringToFind, CFRangeMake(0, textLength), text); ucol = CFStringICUCollatorOpen (searchOptions, locale); usrch = usearch_openFromCollator (text, textLength, pattern, patternLength, ucol, NULL, &err); if (U_FAILURE(err)) return false; /* FIXME: need to handle kCFCompareAnchored */ if (searchOptions & kCFCompareBackwards) { start = usearch_last (usrch, &err); } else { start = usearch_first (usrch, &err); } if (start == USEARCH_DONE) { CFAllocatorDeallocate (alloc, pattern); CFAllocatorDeallocate (alloc, text); return false; } end = usearch_getMatchedLength (usrch); usearch_close (usrch); CFStringICUCollatorClose (ucol); if (result) *result = CFRangeMake (start + rangeToSearch.location, end); CFAllocatorDeallocate (alloc, pattern); CFAllocatorDeallocate (alloc, text); return true; } Boolean CFStringHasPrefix (CFStringRef str, CFStringRef prefix) { CFIndex len = CFStringGetLength (str); return CFStringFindWithOptionsAndLocale (str, prefix, CFRangeMake(0, len), kCFCompareAnchored, NULL, NULL); } Boolean CFStringHasSuffix (CFStringRef str, CFStringRef suffix) { CFIndex len = CFStringGetLength (str); return CFStringFindWithOptionsAndLocale (str, suffix, CFRangeMake(0, len), kCFCompareBackwards | kCFCompareAnchored, NULL, NULL); } CFComparisonResult CFStringCompare (CFStringRef str1, CFStringRef str2, CFStringCompareFlags compareOptions) { CFIndex len = CFStringGetLength (str1); return CFStringCompareWithOptionsAndLocale (str1, str2, CFRangeMake(0, len), compareOptions, NULL); } CFComparisonResult CFStringCompareWithOptions (CFStringRef str1, CFStringRef str2, CFRange rangeToCompare, CFStringCompareFlags compareOptions) { return CFStringCompareWithOptionsAndLocale (str1, str2, rangeToCompare, compareOptions, NULL); } CFComparisonResult CFStringCompareWithOptionsAndLocale (CFStringRef str1, CFStringRef str2, CFRange rangeToCompare, CFStringCompareFlags compareOptions, CFLocaleRef locale) { CFComparisonResult ret; UniChar *string1; UniChar *string2; CFIndex length1; CFIndex length2; CFAllocatorRef alloc; UCollator *ucol; alloc = CFAllocatorGetDefault (); length1 = rangeToCompare.length; string1 = CFAllocatorAllocate (alloc, (length1) * sizeof(UniChar), 0); CFStringGetCharacters (str1, rangeToCompare, string1); length2 = CFStringGetLength (str2); string2 = CFAllocatorAllocate (alloc, (length2) * sizeof(UniChar), 0); CFStringGetCharacters (str2, CFRangeMake(0, length2), string2); ucol = CFStringICUCollatorOpen (compareOptions, locale); ret = (CFComparisonResult)ucol_strcoll (ucol, string2, length2, string1, length1); CFStringICUCollatorClose (ucol); CFAllocatorDeallocate (alloc, string1); CFAllocatorDeallocate (alloc, string2); return ret; } Boolean CFStringFindCharacterFromSet (CFStringRef str, CFCharacterSetRef theSet, CFRange rangeToSearch, CFStringCompareFlags searchOptions, CFRange *result) { /* FIXME: Not really sure how to get this done. Input is welcome. */ return false; } CFStringRef CFStringCreateByCombiningStrings (CFAllocatorRef alloc, CFArrayRef theArray, CFStringRef separatorString) { CFIndex idx; CFIndex count; CFMutableStringRef string; CFStringRef currentString; CFStringRef ret; count = CFArrayGetCount (theArray) - 1; if (count == 0) return NULL; string = CFStringCreateMutable (NULL, 0); idx = 0; while (idx < count) { currentString = (CFStringRef)CFArrayGetValueAtIndex (theArray, idx++); CFStringAppend (string, currentString); CFStringAppend (string, separatorString); } currentString = CFArrayGetValueAtIndex (theArray, idx); CFStringAppend (string, currentString); ret = CFStringCreateCopy (alloc, string); CFRelease (string); return ret; } CFArrayRef CFStringCreateArrayBySeparatingStrings (CFAllocatorRef alloc, CFStringRef str, CFStringRef separator) { /* This is basically a port of -componentsSeparatedByString: */ CFIndex end; CFRange search; CFRange found; CFStringRef tmp; CFArrayRef ret; CFMutableArrayRef array; array = CFArrayCreateMutable (alloc, 0, &kCFTypeArrayCallBacks); search = CFRangeMake (0, CFStringGetLength(str)); end = search.length; while (CFStringFindWithOptions(str, separator, search, 0, &found)) { CFRange current; current = CFRangeMake (search.location, found.location - search.location); tmp = CFStringCreateWithSubstring(alloc, str, current); CFArrayAppendValue (array, tmp); CFRelease (tmp); search = CFRangeMake (found.location + found.length, end - found.location - found.length); } /* Add the last search string range */ tmp = CFStringCreateWithSubstring(alloc, str, search); CFArrayAppendValue (array, tmp); CFRelease (tmp); ret = CFArrayCreateCopy (alloc, array); CFRelease(array); return ret; } CFArrayRef CFStringCreateArrayWithFindResults (CFAllocatorRef alloc, CFStringRef str, CFStringRef stringToFind, CFRange rangeToSearch, CFStringCompareFlags compOpt) { return NULL; /* FIXME */ } /* These next two functions should be very similar. According to Apple's documentation the only different between the two is that ...ParagraphBounds does not stop at Unicode NextLine or LineSeparactor characters. They can probably be implemented using ICU's break iterator. */ void CFStringGetLineBounds (CFStringRef str, CFRange range, CFIndex *lineBeginIndex, CFIndex *lineEndIndex, CFIndex *contentsEndIndex) { return; } void CFStringGetParagraphBounds (CFStringRef string, CFRange range, CFIndex *parBeginIndex, CFIndex *parEndIndex, CFIndex *contentsEndIndex) { return; } gnustep-corebase-0.2/Source/NSCFInputStream.m0000644000175000017500000000366413222706330020255 0ustar yavoryavor/* NSCFInputStream.m Copyright (C) 2014 Free Software Foundation, Inc. Written by: Lubos Dolezel Date: February, 2014 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #include "NSCFType.h" #include "CoreFoundation/CFStream.h" @interface NSCFInputStream : NSInputStream NSCFTYPE_VARS @end @interface NSInputStream (CoreBaseAdditions) - (CFTypeID) _cfTypeID; @end @implementation NSCFInputStream + (void) load { NSCFInitialize (); } + (void) initialize { GSObjCAddClassBehavior (self, [NSCFType class]); } - (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len { return CFReadStreamRead((CFReadStreamRef) self, buffer, len); } - (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)length { const UInt8* buf; CFIndex out; buf = CFReadStreamGetBuffer((CFReadStreamRef) self, *length, &out); *length = out; *buffer = (uint8_t *) buf; return buf != NULL; } - (BOOL)hasBytesAvailable { return CFReadStreamHasBytesAvailable((CFReadStreamRef) self); } @end @implementation NSInputStream (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFReadStreamGetTypeID(); } @end gnustep-corebase-0.2/Source/GSPrivate.h0000644000175000017500000001701114551015633017163 0ustar yavoryavor/* GSPrivate.h Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2011 This file is part of GNUstep CoreBase library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSPRIVATE_H__ #define __GSPRIVATE_H__ #include "config.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFLocale.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFStringEncodingExt.h" #if (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__) # define GS_PRIVATE __attribute__ ((visibility ("hidden"))) #else # define GS_PRIVATE #endif #define UDATE_TO_ABSOLUTETIME(d) \ (((d) / 1000.0) - kCFAbsoluteTimeIntervalSince1970) #define ABSOLUTETIME_TO_UDATE(at) \ (((at) + kCFAbsoluteTimeIntervalSince1970) * 1000.0) #ifdef HAVE_PTHREAD_H #include #endif #if defined(_WIN32) #include #define GSMutex CRITICAL_SECTION #define GSMutexInitialize(x) InitializeCriticalSection(x) #define GSMutexLock(x) EnterCriticalSection(x) #define GSMutexUnlock(x) LeaveCriticalSection(x) #define GSMutexDestroy(x) DeleteCriticalSection(x) #if defined(_WIN64) #define GSAtomicIncrementCFIndex(ptr) \ InterlockedIncrement64((LONGLONG volatile*)(ptr)) #define GSAtomicDecrementCFIndex(ptr) \ InterlockedDecrement64((LONGLONG volatile*)(ptr)) #define GSAtomicCompareAndSwapCFIndex(ptr, oldv, newv) \ InterlockedCompareExchange64((LONGLONG volatile*)(ptr), (newv), (oldv)) #else #define GSAtomicIncrementCFIndex(ptr) \ InterlockedIncrement((LONG volatile*)(ptr)) #define GSAtomicDecrementCFIndex(ptr) \ InterlockedDecrement((LONG volatile*)(ptr)) #define GSAtomicCompareAndSwapCFIndex(ptr, oldv, newv) \ InterlockedCompareExchange((LONG volatile*)(ptr), (newv), (oldv)) #endif /* _WIN64 */ #define GSAtomicCompareAndSwapPointer(ptr, oldv, newv) \ InterlockedCompareExchangePointer((ptr), (newv), (oldv)) #else /* _WIN32 */ #define GSMutex pthread_mutex_t #define GSMutexInitialize(x) pthread_mutex_init(x, NULL) #define GSMutexLock(x) pthread_mutex_lock(x) #define GSMutexUnlock(x) pthread_mutex_unlock(x) #define GSMutexDestroy(x) pthraed_mutex_destroy(x) #if defined(__llvm__) \ || (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) #define GSAtomicIncrementCFIndex(ptr) __sync_add_and_fetch((long*)(ptr), 1) #define GSAtomicDecrementCFIndex(ptr) __sync_sub_and_fetch((long*)(ptr), 1) #define GSAtomicCompareAndSwapCFIndex(ptr, oldv, newv) \ __sync_val_compare_and_swap((long*)(ptr), (long)(oldv), (long)(newv)) #define GSAtomicCompareAndSwapPointer(ptr, oldv, newv) \ __sync_val_compare_and_swap((void**)(ptr), (void*)(oldv), (void*)(newv)) #endif #endif /* _WIN32 */ CFIndex GSBSearch (const void *array, const void *key, CFRange range, CFIndex size, CFComparatorFunction comp, void *ctxt); /* All three of these function are taken from Thomas Wang's website * (http://www.concentric.net/~Ttwang/tech/inthash.htm). As far as I know, * these algorithm are in the public domain. */ CF_INLINE UInt64 GSHashInt64 (UInt64 value) { register UInt64 hash = value; hash = (~hash) + (hash << 21); hash = hash ^ (hash >> 24); hash = (hash + (hash << 3)) + (hash << 8); hash = hash ^ (hash >> 14); hash = (hash + (hash << 2)) + (hash << 4); hash = hash ^ (hash >> 28); hash = hash + (hash << 31); return hash; } CF_INLINE UInt32 GSHashInt32 (UInt32 value) { register UInt32 hash = value; hash = ~hash + (hash << 15); hash = hash ^ (hash >> 12); hash = hash + (hash << 2); hash = hash ^ (hash >> 4); hash = (hash + (hash << 3)) + (hash << 11); hash = hash ^ (hash >> 16); return hash; } CF_INLINE UInt32 GSHashInt64ToInt32 (UInt64 value) { register UInt64 hash = value; hash = (~hash) + (hash << 18); hash = hash ^ (hash >> 31); hash = (hash + (hash << 2)) + (hash << 4); hash = hash ^ (hash >> 11); hash = hash + (hash << 6); hash = hash ^ (hash >> 22); return (UInt32)hash; } CF_INLINE CFHashCode GSHashPointer (const void *value) { #if defined(__LP64__) || defined(_WIN64) /* 64-bit operating systems */ return (CFHashCode)GSHashInt64 ((UInt64)value); #else /* 32-bit operating systems */ return (CFHashCode)GSHashInt32 ((UInt32)value); #endif } CF_INLINE CFHashCode GSHashBytes (const void *bytes, CFIndex length) { CFHashCode ret = 0; if (length > 0) { register CFIndex idx; register const char *p = bytes; for (idx = 0 ; idx < length ; ++idx) ret = (ret << 5) + ret + p[idx]; ret &= 0x0fffffff; if (ret == 0) ret = 0x0fffffff; } else { ret = 0x0ffffffe; } return ret; } struct __CFConstantString { CFRuntimeBase _parent; void *_contents; CFIndex _count; CFHashCode _hash; CFAllocatorRef _deallocator; }; #if defined (_WIN32) #define DLL_EXPORT __declspec(dllexport) #else #define DLL_EXPORT #endif #define CONST_STRING_DECL(var, str) \ static struct __CFConstantString __ ## var ## __ = \ { {0, 0, {1, 0, 0}}, (void*)str, sizeof(str) - 1, 0, NULL }; \ DLL_EXPORT const CFStringRef var = (CFStringRef) & __ ## var ## __; #define CHAR_IS_DIGIT(c) ((c) >= '0' && (c) <= '9') #define CHAR_IS_OCTAL(c) ((c) >= '0' && (c) <= '7') #define CHAR_IS_HEX(c) ((CHAR_IS_DIGIT(c) \ || ((c) >= 'A' && (c) <= 'F') || ((c) >= 'a' && (c) <= 'f'))) #define CHAR_IS_ASCII(c) ((c) < 128) #define CHAR_IS_UPPER_CASE(c) ((c) >= 'A' && (c) <= 'Z') #define CHAR_IS_LOWER_CASE(c) ((c) >= 'a' && (c) <= 'z') #define CHAR_IS_ALPHA(c) (CHAR_IS_UPPER_CASE(c) || CHAR_IS_LOWER_CASE(c)) CF_INLINE Boolean __CFStringEncodingIsSupersetOfASCII (CFStringEncoding encoding) { if (encoding == kCFStringEncodingASCII) return true; switch (encoding & 0xF00) { case 0x100: return encoding == kCFStringEncodingUTF8 ? true : false; case 0x000: /* MacOS codepage */ if (encoding == kCFStringEncodingMacJapanese || encoding == kCFStringEncodingMacArabic || encoding == kCFStringEncodingMacHebrew || encoding == kCFStringEncodingMacUkrainian || encoding == kCFStringEncodingMacSymbol || encoding == kCFStringEncodingMacDingbats) return false; case 0x200: /* ISO-8859-* */ case 0x400: /* DOS codepage */ case 0x500: /* Windows codepage */ return true; } return false; } CF_INLINE CFStringEncoding GSStringGetFileSystemEncoding (void) { #if defined(_WIN32) return kCFStringEncodingUTF16; #else return CFStringGetSystemEncoding (); #endif } const char * CFLocaleGetCStringIdentifier (CFLocaleRef locale, char *buf, CFIndex maxlen); void GSRuntimeConstantInit (CFTypeRef cf, CFTypeID typeID); void GSRuntimeDeallocateInstance (CFTypeRef cf); #define GS_MAX(a,b) (a > b ? a : b) #define GS_MIN(a,b) (a < b ? a : b) #endif /* __GSPRIVATE_H__ */ gnustep-corebase-0.2/Source/NSCFData.m0000644000175000017500000000557113222706330016652 0ustar yavoryavor/* NSCFData.m Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: September, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #import #import #include "NSCFType.h" #include "CoreFoundation/CFData.h" /* NSCFData inherits from NSMutableData and doesn't have any ivars because it is only an ObjC wrapper around CFData. */ @interface NSCFData : NSMutableData NSCFTYPE_VARS @end @interface NSData (CoreBaseAdditions) - (CFTypeID) _cfTypeID; @end @implementation NSCFData + (void) load { NSCFInitialize (); } + (void) initialize { GSObjCAddClassBehavior (self, [NSCFType class]); } - (const void *) bytes { return CFDataGetBytePtr ((CFDataRef) self); } - (NSString *) description { return AUTORELEASE((id) CFCopyDescription(self)); } - (void) getBytes: (void *) buffer range: (NSRange) range { CFDataGetBytes ((CFDataRef) self, CFRangeMake(range.location, range.length), buffer); } - (BOOL) isEqualToData: (NSData *) other { return (BOOL)CFEqual ((CFDataRef) self, other); } - (NSUInteger) length { return (NSUInteger)CFDataGetLength((CFMutableDataRef) self); } - (void) increaseLengthBy: (NSUInteger) extraLength { CFDataIncreaseLength ((CFMutableDataRef) self, (CFIndex)extraLength); } - (void) setLength: (NSUInteger) length { CFDataSetLength ((CFMutableDataRef) self, (CFIndex)length); } - (void *) mutableBytes { return CFDataGetMutableBytePtr ((CFMutableDataRef) self); } - (void) appendBytes: (const void *) buffer length: (NSUInteger) size { CFDataAppendBytes ((CFMutableDataRef) self, buffer, size); } - (void) replaceBytesInRange: (NSRange) range withBytes: (const void *) bytes length: (NSUInteger) length { CFDataReplaceBytes ((CFMutableDataRef) self, CFRangeMake(range.location, range.length), bytes, (CFIndex)length); } @end @implementation NSData (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFDataGetTypeID(); } @end gnustep-corebase-0.2/Source/NSCFLocale.m0000644000175000017500000000563113222706330017175 0ustar yavoryavor/* NSCFLocale.m Copyright (C) 2013 Free Software Foundation, Inc. Written by: Lubos Dolezel Date: March, 2013 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #include "NSCFType.h" #include "CoreFoundation/CFLocale.h" @interface NSCFLocale : NSLocale NSCFTYPE_VARS @end @interface NSLocale (CoreBaseAdditions) - (CFTypeID) _cfTypeID; @end static CFStringRef NSLocaleKeyToCFLocaleKey(id key) { CFStringRef cfKey = NULL; #define CASE(keyName) if([key isEqual: NS##keyName]) cfKey = kCF##keyName; else CASE(LocaleIdentifier) CASE(LocaleLanguageCode) CASE(LocaleCountryCode) CASE(LocaleScriptCode) CASE(LocaleVariantCode) CASE(LocaleExemplarCharacterSet) CASE(LocaleCalendar) CASE(LocaleCollationIdentifier) CASE(LocaleUsesMetricSystem) CASE(LocaleMeasurementSystem) CASE(LocaleDecimalSeparator) CASE(LocaleGroupingSeparator) CASE(LocaleCurrencySymbol) CASE(LocaleCurrencyCode) CASE(LocaleCollatorIdentifier) CASE(LocaleQuotationBeginDelimiterKey) CASE(LocaleQuotationEndDelimiterKey) CASE(LocaleAlternateQuotationBeginDelimiterKey) CASE(LocaleAlternateQuotationEndDelimiterKey); #undef CASE return cfKey; } @implementation NSCFLocale + (void) load { NSCFInitialize (); } + (void) initialize { GSObjCAddClassBehavior (self, [NSCFType class]); } - (id) initWithLocaleIdentifier:(NSString*)string { RELEASE(self); self = (NSCFLocale*) CFLocaleCreate(kCFAllocatorDefault, (CFStringRef) string); return self; } - (NSString*) localeIdentifier { return (NSString*) CFLocaleGetIdentifier((CFLocaleRef) self); } - (id) objectForKey:(id)key { CFStringRef cfKey = NSLocaleKeyToCFLocaleKey(key); return (id) CFLocaleGetValue((CFLocaleRef) self, cfKey); } - (NSString*) displayNameForKey:(id)key value:(id)value { CFStringRef cfKey = NSLocaleKeyToCFLocaleKey(key); return (NSString*) CFLocaleCopyDisplayNameForPropertyValue((CFLocaleRef) self, cfKey, (CFStringRef) value); } @end @implementation NSLocale (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFLocaleGetTypeID(); } @end gnustep-corebase-0.2/Source/GSCArray.h0000644000175000017500000000327713222706330016736 0ustar yavoryavor/* GSCArray.h Copyright (C) 2013 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: July, 2013 This file is part of GNUstep CoreBase library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSCARRAY_H__ #define __GSCARRAY_H__ #include "config.h" #include "CoreFoundation/CFBase.h" #include "GSPrivate.h" GS_PRIVATE void GSCArrayQuickSort (const void **array, CFIndex length, CFComparatorFunction comparator, void *context); GS_PRIVATE void GSCArrayInsertionSort (const void **array, CFIndex length, CFComparatorFunction comparator, void *context); GS_PRIVATE void GSCArrayHeapify (const void **array, CFIndex length, CFComparatorFunction comparator, void *context); GS_PRIVATE CFIndex GSCArrayBSearch (const void **array, const void *key, CFIndex length, CFComparatorFunction comparator, void *context); #endif /* __GSCARRAY_H__ */ gnustep-corebase-0.2/Source/CFXMLParser.c0000644000175000017500000002371513222706330017343 0ustar yavoryavor/* CFXMLParser.c Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFData.h" #include "CoreFoundation/CFDictionary.h" #include "CoreFoundation/CFNumber.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFURL.h" #include "CoreFoundation/CFXMLParser.h" #include "GSPrivate.h" #include #include CONST_STRING_DECL(kCFXMLTreeErrorDescription, "kCFXMLTreeErrorDescription"); CONST_STRING_DECL(kCFXMLTreeErrorLineNumber, "kCFXMLTreeErrorLineNumber"); CONST_STRING_DECL(kCFXMLTreeErrorLocation, "kCFXMLTreeErrorLocation"); CONST_STRING_DECL(kCFXMLTreeErrorStatusCode, "kCFXMLTreeErrorStatusCode"); struct __CFXMLParser { CFRuntimeBase parent; CFXMLParserStatusCode _errorCode; CFStringRef _errorDesc; CFDataRef _data; CFURLRef _dataSrc; CFIndex _nodeVersion; CFXMLParserOptions _options; CFXMLParserCallBacks _callBacks; CFXMLParserContext _context; }; static CFTypeID _kCFXMLParserTypeID = 0; static void CFXMLParserFinalize (CFTypeRef cf) { CFXMLParserRef parser = (CFXMLParserRef)cf; CFRelease (parser->_data); CFRelease (parser->_dataSrc); if (parser->_errorDesc) CFRelease (parser->_errorDesc); } static const CFRuntimeClass CFXMLParserClass = { 0, "CFXMLParser", NULL, NULL, CFXMLParserFinalize, NULL, NULL, NULL, NULL }; void CFXMLParserInitialize (void) { _kCFXMLParserTypeID = _CFRuntimeRegisterClass (&CFXMLParserClass); } CFTypeID CFXMLParserGetTypeID (void) { return _kCFXMLParserTypeID; } void CFXMLParserAbort (CFXMLParserRef parser, CFXMLParserStatusCode errorCode, CFStringRef errorDesc) { parser->_errorCode = errorCode; parser->_errorDesc = CFStringCreateCopy (CFGetAllocator(parser), errorDesc); } CFStringRef CFXMLParserCopyErrorDescription (CFXMLParserRef parser) { return CFRetain (parser->_errorDesc); } #define CFXMLPARSER_SIZE sizeof(struct __CFXMLParser) - sizeof(CFRuntimeBase) CFXMLParserRef CFXMLParserCreate (CFAllocatorRef alloc, CFDataRef xmlData, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes, CFXMLParserCallBacks *callBacks, CFXMLParserContext *context) { struct __CFXMLParser *new; new = (struct __CFXMLParser*)_CFRuntimeCreateInstance (alloc, _kCFXMLParserTypeID, CFXMLPARSER_SIZE, 0); if (new) { new->_errorCode = kCFXMLStatusParseNotBegun; new->_data = CFDataCreateCopy (alloc, xmlData); if (dataSource) new->_dataSrc = CFURLCopyAbsoluteURL (dataSource); new->_nodeVersion = versionOfNodes; new->_options = parseOptions; if (callBacks) memcpy (&new->_callBacks, callBacks, sizeof(CFXMLParserCallBacks)); if (context) { memcpy (&new->_context, context, sizeof(CFXMLParserContext)); if (new->_context.retain) new->_context.retain (new->_context.info); } } return new; } CFXMLParserRef CFXMLParserCreateWithDataFromURL (CFAllocatorRef alloc, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes, CFXMLParserCallBacks *callBacks, CFXMLParserContext *context) { return NULL; } void CFXMLParserGetCallBacks (CFXMLParserRef parser, CFXMLParserCallBacks *callBacks) { } void CFXMLParserGetContext (CFXMLParserRef parser, CFXMLParserContext *context) { } void * CFXMLParserGetDocument (CFXMLParserRef parser) { return NULL; } CFIndex CFXMLParserGetLineNumber (CFXMLParserRef parser) { return 0; } CFIndex CFXMLParserGetLocation (CFXMLParserRef parser) { return 0; } CFURLRef CFXMLParserGetSourceURL (CFXMLParserRef parser) { return NULL; } CFXMLParserStatusCode CFXMLParserGetStatusCode (CFXMLParserRef parser) { return 0; } Boolean CFXMLParserParse (CFXMLParserRef parser) { return false; } static void * CFXMLTreeCreateXMLStructure (CFXMLParserRef parser, CFXMLNodeRef nodeDesc, void *info) { return CFXMLTreeCreateWithNode (info, nodeDesc); } void CFXMLTreeAddChild (CFXMLParserRef parser, void *parent, void *child, void *info) { CFTreeAppendChild (parent, child); } void CFXMLEndXMLStructure (CFXMLParserRef parser, void *xmlType, void *info) { /* xmlType is of type CFXMLTree */ if (CFTreeGetParent(xmlType)) /* Only release if not root */ CFRelease ((CFTypeRef)xmlType); } CFXMLTreeRef CFXMLTreeCreateFromDataWithError (CFAllocatorRef allocator, CFDataRef xmlData, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes, CFDictionaryRef *errorDict) { CFXMLTreeRef new; CFXMLParserRef parser; CFXMLParserCallBacks callBacks; CFXMLParserContext context; callBacks.version = 0; callBacks.createXMLStructure = CFXMLTreeCreateXMLStructure; callBacks.addChild = CFXMLTreeAddChild; callBacks.endXMLStructure = CFXMLEndXMLStructure; callBacks.resolveExternalEntity = NULL; callBacks.handleError = NULL; context.version = 0; context.info = (void*)allocator; context.retain = NULL; context.release = NULL; context.copyDescription = NULL; parser = CFXMLParserCreate (allocator, xmlData, dataSource, parseOptions, versionOfNodes, &callBacks, &context); if (CFXMLParserParse(parser)) { new = (CFXMLTreeRef)CFRetain (CFXMLParserGetDocument (parser)); } else { if (errorDict) { /* Handle error */ CFIndex num; CFTypeRef obj; CFMutableDictionaryRef dict = CFDictionaryCreateMutable (allocator, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); obj = CFXMLParserCopyErrorDescription (parser); if (obj) { CFDictionaryAddValue (dict, kCFXMLTreeErrorDescription, obj); CFRelease (obj); } num = CFXMLParserGetLineNumber (parser); obj = CFNumberCreate (allocator, kCFNumberCFIndexType, &num); if (obj) { CFDictionaryAddValue (dict, kCFXMLTreeErrorLineNumber, obj); CFRelease (obj); } num = CFXMLParserGetLocation (parser); obj = CFNumberCreate (allocator, kCFNumberCFIndexType, &num); if (obj) { CFDictionaryAddValue (dict, kCFXMLTreeErrorLocation, obj); CFRelease (obj); } num = CFXMLParserGetStatusCode (parser); obj = CFNumberCreate (allocator, kCFNumberCFIndexType, &num); if (obj) { CFDictionaryAddValue (dict, kCFXMLTreeErrorStatusCode, obj); CFRelease (obj); } *errorDict = dict; } new = NULL; } CFRelease (parser); return new; } CFXMLTreeRef CFXMLTreeCreateFromData (CFAllocatorRef allocator, CFDataRef xmlData, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes) { return CFXMLTreeCreateFromDataWithError (allocator, xmlData, dataSource, parseOptions, versionOfNodes, NULL); } CFXMLTreeRef CFXMLTreeCreateWithDataFromURL (CFAllocatorRef allocator, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes) { CFXMLTreeRef new; CFXMLParserRef parser; CFXMLParserCallBacks callBacks; CFXMLParserContext context; callBacks.version = 0; callBacks.createXMLStructure = CFXMLTreeCreateXMLStructure; callBacks.addChild = CFXMLTreeAddChild; callBacks.endXMLStructure = CFXMLEndXMLStructure; callBacks.resolveExternalEntity = NULL; callBacks.handleError = NULL; context.version = 0; context.info = (void*)allocator; context.retain = NULL; context.release = NULL; context.copyDescription = NULL; parser = CFXMLParserCreateWithDataFromURL (allocator, dataSource, parseOptions, versionOfNodes, &callBacks, &context); if (CFXMLParserParse(parser)) new = (CFXMLTreeRef)CFRetain (CFXMLParserGetDocument (parser)); else new = NULL; CFRelease (parser); return new; } CFXMLTreeRef CFXMLTreeCreateWithNode (CFAllocatorRef allocator, CFXMLNodeRef node) { CFTreeContext context; context.version = 0; context.info = (void*)node; context.retain = CFRetain; context.release = CFRelease; context.copyDescription = CFCopyDescription; return CFTreeCreate (allocator, &context); } CFXMLNodeRef CFXMLTreeGetNode (CFXMLTreeRef xmlTree) { CFTreeContext context; CFTreeGetContext (xmlTree, &context); return context.info; } CFDataRef CFXMLTreeCreateXMLData (CFAllocatorRef allocator, CFXMLTreeRef xmlTree) { return NULL; } CFStringRef CFXMLCreateStringByEscapingEntities(CFAllocatorRef allocator, CFStringRef string, CFDictionaryRef entitiesDictionary) { return NULL; } CFStringRef CFXMLCreateStringByUnescapingEntities(CFAllocatorRef allocator, CFStringRef string, CFDictionaryRef entitiesDictionary) { return NULL; } gnustep-corebase-0.2/Source/CFDictionary.c0000644000175000017500000002202613222706330017625 0ustar yavoryavor/* CFDictionary.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: November, 2011 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFDictionary.h" #include "CoreFoundation/CFString.h" #include "GSHashTable.h" #include "GSObjCRuntime.h" static CFTypeID _kCFDictionaryTypeID = 0; static void CFDictionaryFinalize (CFTypeRef cf) { GSHashTableFinalize ((GSHashTableRef)cf); } static Boolean CFDictionaryEqual (CFTypeRef cf1, CFTypeRef cf2) { return GSHashTableEqual ((GSHashTableRef)cf1, (GSHashTableRef)cf2); } static CFHashCode CFDictionaryHash (CFTypeRef cf) { return GSHashTableHash ((GSHashTableRef)cf); } static CFStringRef CFDictionaryCopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOptions) { return CFSTR(""); } static CFRuntimeClass CFDictionaryClass = { 0, "CFDictionary", NULL, (CFTypeRef(*)(CFAllocatorRef, CFTypeRef))CFDictionaryCreateCopy, CFDictionaryFinalize, CFDictionaryEqual, CFDictionaryHash, CFDictionaryCopyFormattingDesc, NULL }; void CFDictionaryInitialize (void) { _kCFDictionaryTypeID = _CFRuntimeRegisterClass (&CFDictionaryClass); } const CFDictionaryKeyCallBacks kCFCopyStringDictionaryKeyCallBacks = { 0, (CFTypeRef (*)(CFAllocatorRef, CFTypeRef))CFStringCreateCopy, CFTypeReleaseCallBack, CFCopyDescription, CFEqual, CFHash }; const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks = { 0, CFTypeRetainCallBack, CFTypeReleaseCallBack, CFCopyDescription, CFEqual, CFHash }; const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks = { 0, CFTypeRetainCallBack, CFTypeReleaseCallBack, CFCopyDescription, CFEqual }; CFDictionaryRef CFDictionaryCreate (CFAllocatorRef allocator, const void **keys, const void **values, CFIndex numValues, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks) { return (CFDictionaryRef)GSHashTableCreate (allocator, _kCFDictionaryTypeID, keys, values, numValues, (const GSHashTableKeyCallBacks*)keyCallBacks, (const GSHashTableValueCallBacks*)valueCallBacks); } CFDictionaryRef CFDictionaryCreateCopy (CFAllocatorRef allocator, CFDictionaryRef dict) { if (CF_IS_OBJC(_kCFDictionaryTypeID, dict)) { CFIndex count = CFDictionaryGetCount(dict); const void **values, **keys; CFDictionaryRef copy; keys = (const void **) CFAllocatorAllocate(allocator, sizeof(const void *) * count, 0); values = (const void **) CFAllocatorAllocate(allocator, sizeof(const void *) * count, 0); CFDictionaryGetKeysAndValues(dict, keys, values); copy = CFDictionaryCreate(allocator, keys, values, count, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFAllocatorDeallocate(allocator, keys); CFAllocatorDeallocate(allocator, values); return copy; } return (CFDictionaryRef)GSHashTableCreateCopy (allocator, (GSHashTableRef)dict); } void CFDictionaryApplyFunction (CFDictionaryRef dict, CFDictionaryApplierFunction applier, void *context) { CFIndex i; CFIndex cnt; const void **keys; const void **values; CFAllocatorRef alloc; cnt = CFDictionaryGetCount (dict); alloc = CFGetAllocator(dict); keys = CFAllocatorAllocate (alloc, cnt * 2 * sizeof(void*), 0); values = keys + cnt; CFDictionaryGetKeysAndValues (dict, keys, values); for (i = 0; i < cnt; i++) applier (keys[i], values[i], context); } Boolean CFDictionaryContainsKey (CFDictionaryRef dict, const void *key) { if (CF_IS_OBJC(_kCFDictionaryTypeID, dict)) { void *object; CF_OBJC_CALLV (void*, object, dict, "objectForKey:", key); return object != NULL; } return GSHashTableContainsKey ((GSHashTableRef)dict, key); } Boolean CFDictionaryContainsValue (CFDictionaryRef dict, const void *value) { if (CF_IS_OBJC(_kCFDictionaryTypeID, dict)) return CFDictionaryGetCountOfValue(dict, value) ? true : false; return GSHashTableContainsValue ((GSHashTableRef)dict, value); } CFIndex CFDictionaryGetCount (CFDictionaryRef dict) { CF_OBJC_FUNCDISPATCHV(_kCFDictionaryTypeID, CFIndex, dict, "count"); return GSHashTableGetCount ((GSHashTableRef)dict); } CFIndex CFDictionaryGetCountOfKey (CFDictionaryRef dict, const void *key) { if (CF_IS_OBJC(_kCFDictionaryTypeID, dict)) return CFDictionaryContainsKey(dict, key) ? 1 : 0; return GSHashTableGetCountOfKey ((GSHashTableRef)dict, key); } CFIndex CFDictionaryGetCountOfValue (CFDictionaryRef dict, const void *value) { CF_OBJC_FUNCDISPATCHV(_kCFDictionaryTypeID, Boolean, dict, "_cfCountOfValue:", value); return GSHashTableGetCountOfValue ((GSHashTableRef)dict, value); } void CFDictionaryGetKeysAndValues (CFDictionaryRef dict, const void **keys, const void **values) { CF_OBJC_FUNCDISPATCHV(_kCFDictionaryTypeID, void, dict, "getObjects:andKeys:", values, keys); GSHashTableGetKeysAndValues ((GSHashTableRef)dict, keys, values); } const void * CFDictionaryGetValue (CFDictionaryRef dict, const void *key) { CF_OBJC_FUNCDISPATCHV(_kCFDictionaryTypeID, const void *, dict, "objectForKey:", key); return GSHashTableGetValue ((GSHashTableRef)dict, key); } Boolean CFDictionaryGetValueIfPresent (CFDictionaryRef dict, const void *key, const void **value) { const void *v; v = CFDictionaryGetValue (dict, key); if (v) { if (value) *value = v; return true; } return false; } CFTypeID CFDictionaryGetTypeID (void) { return _kCFDictionaryTypeID; } CFMutableDictionaryRef CFDictionaryCreateMutable (CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks *keyCallBacks, const CFDictionaryValueCallBacks *valueCallBacks) { return (CFMutableDictionaryRef)GSHashTableCreateMutable (allocator, _kCFDictionaryTypeID, capacity, (const GSHashTableKeyCallBacks*)keyCallBacks, (const GSHashTableValueCallBacks*)valueCallBacks); } CFMutableDictionaryRef CFDictionaryCreateMutableCopy (CFAllocatorRef allocator, CFIndex capacity, CFDictionaryRef dict) { if (CF_IS_OBJC(_kCFDictionaryTypeID, dict)) { CFIndex count = CFDictionaryGetCount(dict); const void **values, **keys; CFMutableDictionaryRef copy; CFIndex i; keys = (const void **) CFAllocatorAllocate(allocator, sizeof(const void *) * count, 0); values = (const void **) CFAllocatorAllocate(allocator, sizeof(const void *) * count, 0); if (count > capacity) capacity = count; CFDictionaryGetKeysAndValues(dict, keys, values); copy = CFDictionaryCreateMutable(allocator, capacity, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); for (i = 0; i < count; i++) CFDictionaryAddValue(copy, keys[i], values[i]); CFAllocatorDeallocate(allocator, keys); CFAllocatorDeallocate(allocator, values); return copy; } return (CFMutableDictionaryRef)GSHashTableCreateMutableCopy (allocator, (GSHashTableRef)dict, capacity); } void CFDictionaryAddValue (CFMutableDictionaryRef dict, const void *key, const void *value) { CF_OBJC_FUNCDISPATCHV(_kCFDictionaryTypeID, void, dict, "setObject:forKey:", value, key); GSHashTableAddValue ((GSHashTableRef)dict, key, value); } void CFDictionaryRemoveAllValues (CFMutableDictionaryRef dict) { CF_OBJC_FUNCDISPATCHV(_kCFDictionaryTypeID, void, dict, "removeAllObjects"); GSHashTableRemoveAll ((GSHashTableRef)dict); } void CFDictionaryRemoveValue (CFMutableDictionaryRef dict, const void *key) { CF_OBJC_FUNCDISPATCHV(_kCFDictionaryTypeID, void, dict, "removeObjectForKey:", key); GSHashTableRemoveValue ((GSHashTableRef)dict, key); } void CFDictionaryReplaceValue (CFMutableDictionaryRef dict, const void *key, const void *value) { CF_OBJC_FUNCDISPATCHV(_kCFDictionaryTypeID, void, dict, "_cfReplaceValue::", key, value); GSHashTableReplaceValue ((GSHashTableRef)dict, key, value); } void CFDictionarySetValue (CFMutableDictionaryRef dict, const void *key, const void *value) { CF_OBJC_FUNCDISPATCHV(_kCFDictionaryTypeID, void, dict, "_cfSetValue::", key, value); GSHashTableSetValue ((GSHashTableRef)dict, key, value); } gnustep-corebase-0.2/Source/NSCFString.m0000644000175000017500000003703613222706330017250 0ustar yavoryavor/* NSCFString.m Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: May, 2011 This file is part of CoreBase. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #import #import #import #import #import #import #include "NSCFType.h" #include "CoreFoundation/CFString.h" #include "GSPrivate.h" /* NSCFString inherits from NSMutableString and doesn't have any ivars because it is only an ObjC wrapper around CFString. */ @interface NSCFString : NSMutableString NSCFTYPE_VARS @end @interface NSString (CoreBaseAdditions) - (CFTypeID) _cfTypeID; @end @interface NSMutableString (CoreBaseAdditions) - (void) _cfTrimWhitespace; @end @implementation NSCFString /* Class variables */ static NSStringEncoding *nsencodings = NULL; + (void) load { NSCFInitialize (); } + (void) initialize { GSObjCAddClassBehavior (self, [NSCFType class]); } - (id) initWithBytes: (const void*) bytes length: (NSUInteger) length encoding: (NSStringEncoding) encoding { CFAllocatorRef alloc = kCFAllocatorDefault; CFStringEncoding enc = CFStringConvertNSStringEncodingToEncoding (encoding); RELEASE(self); self = (NSCFString*)CFStringCreateWithBytes (alloc, bytes, length, enc, false); return self; } - (id) initWithBytesNoCopy: (void*) bytes length: (NSUInteger) length encoding: (NSStringEncoding) encoding freeWhenDone: (BOOL) flag { CFAllocatorRef alloc = kCFAllocatorDefault; CFAllocatorRef deallocator = flag ? kCFAllocatorDefault : kCFAllocatorNull; CFStringEncoding enc = CFStringConvertNSStringEncodingToEncoding (encoding); RELEASE(self); self = (NSCFString*)CFStringCreateWithBytesNoCopy (alloc, bytes, length, enc, false, deallocator); return self; } - (id) initWithCharacters: (const unichar*) chars length: (NSUInteger) length { CFAllocatorRef alloc = kCFAllocatorDefault; RELEASE(self); self = (NSCFString*)CFStringCreateWithCharacters (alloc, chars, length); return self; } - (id) initWithCharactersNoCopy: (unichar*) chars length: (NSUInteger) length freeWhenDone: (BOOL) flag { CFAllocatorRef alloc = kCFAllocatorDefault; CFAllocatorRef deallocator = flag ? kCFAllocatorDefault : kCFAllocatorNull; RELEASE(self); self = (NSCFString*)CFStringCreateWithCharactersNoCopy (alloc, chars, length, deallocator); return self; } - (id) initWithString: (NSString*) string { CFAllocatorRef alloc = kCFAllocatorDefault; RELEASE(self); self = (NSCFString*)CFStringCreateWithSubstring (alloc, (CFStringRef) string, CFRangeMake(0, CFStringGetLength((CFStringRef) string))); return self; } /* - (id) initWithFormat: (NSString*) format arguments: (va_list) argList { CFAllocatorRef alloc = kCFAllocatorDefault; RELEASE(self); self = (NSCFString*)CFStringCreateWithFormatAndArguments (alloc, NULL, format, argList); return self; } - (id) initWithFormat: (NSString*) format locale: (id) locale arguments: (va_list) argList { if ([locale isKindOfClass: [NSLocale class]]) return nil; // FIXME RELEASE(self); return (NSCFString*) CFStringCreateWithFormatAndArguments (CFAllocatorGetDefault(), (CFDictionaryRef)locale, format, argList); } */ - (id) initWithData: (NSData*)data encoding: (NSStringEncoding)encoding { CFStringEncoding enc = CFStringConvertNSStringEncodingToEncoding (encoding); CFAllocatorRef alloc = kCFAllocatorDefault; RELEASE(self); self = (NSCFString*) CFStringCreateFromExternalRepresentation (alloc, (CFDataRef)data, enc); return self; } - (NSString*)stringByReplacingOccurrencesOfString: (NSString*)replace withString: (NSString*)by options: (NSStringCompareOptions)opts range: (NSRange)searchRange { // GNUstep's NSString uses GSMutableStringClass here // so we cannot use the base implementation (it would break the bridging) return nil; // FIXME } - (NSString*) stringByReplacingCharactersInRange: (NSRange)aRange withString: (NSString*)by; { // GNUstep's NSString uses GSMutableStringClass here // so we cannot use the base implementation (it would break the bridging) return nil; // FIXME } - (NSUInteger) length { return (NSUInteger)CFStringGetLength ((CFStringRef) self); } - (unichar) characterAtIndex: (NSUInteger) index { return (unichar)CFStringGetCharacterAtIndex ((CFStringRef) self, index); } - (void) getCharacters: (unichar*) buffer range: (NSRange) aRange { CFRange cfRange = CFRangeMake (aRange.location, aRange.length); CFStringGetCharacters ((CFStringRef) self, cfRange, buffer); } - (NSArray*) componentsSeparatedByString: (NSString*) separator { return (NSArray*) CFStringCreateArrayBySeparatingStrings (CFAllocatorGetDefault(), (CFStringRef) self, (CFStringRef) separator); } - (NSRange) rangeOfCharacterFromSet: (NSCharacterSet*) aSet options: (NSUInteger) mask range: (NSRange) aRange { CFRange cfRange = CFRangeMake (aRange.location, aRange.length); CFRange ret; if (!CFStringFindCharacterFromSet ((CFStringRef) self, (CFCharacterSetRef)aSet, cfRange, (CFStringCompareFlags) mask, &ret)) ret = CFRangeMake (kCFNotFound, 0); return NSMakeRange (ret.location, ret.length); } - (NSRange) rangeOfString: (NSString *) aString options: (NSStringCompareOptions) mask range: (NSRange) searchRange locale: (NSLocale *) locale { CFRange cfRange = CFRangeMake (searchRange.location, searchRange.length); CFRange ret; if (!CFStringFindWithOptionsAndLocale ((CFStringRef) self, (CFStringRef) aString, cfRange, (CFStringCompareFlags) mask, (CFLocaleRef) locale, &ret)) ret = CFRangeMake (kCFNotFound, 0); return NSMakeRange (ret.location, ret.length); } /* - (NSArray *) componentsSeparatedByCharactersInSet: (NSCharacterSet *)separator { return nil; // FIXME } - (NSRange) rangeOfComposedCharacterSequencesForRange: (NSRange)range { return NSMakeRange (NSNotFound, 0); // FIXME, even NSString doesn't implement this } - (NSDictionary*) propertyListFromStringsFileFormat { // FIXME ??? return nil; } */ - (NSComparisonResult) compare: (NSString*) string options: (NSUInteger) mask range: (NSRange) compareRange locale: (id) locale { CFRange cfRange = CFRangeMake (compareRange.location, compareRange.length); if (nil != locale && ![locale isKindOfClass: [NSLocale class]]) { locale = [NSLocale currentLocale]; } return (NSComparisonResult) CFStringCompareWithOptionsAndLocale ((CFStringRef) self, (CFStringRef) string, cfRange, (CFStringCompareFlags)mask, (CFLocaleRef) locale); } - (BOOL) hasPrefix: (NSString*) aString { return CFStringHasPrefix ((CFStringRef) self, (CFStringRef) aString); } - (BOOL) hasSuffix: (NSString*) aString { return CFStringHasSuffix ((CFStringRef) self, (CFStringRef) aString); } - (NSString*) capitalizedString { CFMutableStringRef copy; copy = CFStringCreateMutableCopy (NULL, 0, (CFStringRef) self); CFStringCapitalize (copy, NULL); return (NSString*) AUTORELEASE((NSString *) copy); } - (NSString*) lowercaseString { CFMutableStringRef copy; copy = CFStringCreateMutableCopy (NULL, 0, (CFStringRef) self); CFStringLowercase (copy, NULL); return (NSString*)AUTORELEASE((NSString *) copy); } - (NSString*) uppercaseString { CFMutableStringRef copy; copy = CFStringCreateMutableCopy (NULL, 0, (CFStringRef) self); CFStringUppercase (copy, NULL); return (NSString*)AUTORELEASE((NSString *) copy); } - (BOOL) getCString: (char*) buffer maxLength: (NSUInteger) maxLength encoding: (NSStringEncoding) encoding { CFStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (encoding); return (BOOL)CFStringGetCString ((CFStringRef) self, buffer, maxLength, enc); } - (NSUInteger) lengthOfBytesUsingEncoding: (NSStringEncoding) encoding { return [self lengthOfBytesUsingEncoding: encoding]; } - (NSUInteger) maximumLengthOfBytesUsingEncoding: (NSStringEncoding) encoding { CFStringEncoding enc = CFStringConvertNSStringEncodingToEncoding (encoding); return CFStringGetMaximumSizeForEncoding ([self length], enc); } - (NSData*) dataUsingEncoding: (NSStringEncoding) encoding allowLossyConversion: (BOOL) flag { CFStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (encoding); return (NSData*)CFStringCreateExternalRepresentation (NULL, (CFStringRef) self, enc, flag ? '?' : 0); } - (NSStringEncoding) fastestEncoding { CFStringEncoding enc = CFStringGetFastestEncoding ((CFStringRef) self); return CFStringConvertEncodingToNSStringEncoding (enc); } - (NSStringEncoding) smallestEncoding { CFStringEncoding enc = CFStringGetSmallestEncoding ((CFStringRef) self); return CFStringConvertEncodingToNSStringEncoding (enc); } - (BOOL) getFileSystemRepresentation: (char*) buffer maxLength: (NSUInteger) size { return (BOOL) CFStringGetFileSystemRepresentation ((CFStringRef) self, buffer, size); } - (NSString*) substringWithRange: (NSRange) aRange { CFRange cfRange = CFRangeMake (aRange.location, aRange.length); return (NSString*) CFStringCreateWithSubstring (NULL, (CFStringRef) self, cfRange); } + (NSStringEncoding*) availableStringEncodings { if (!nsencodings) { int count = 0, i; const CFStringEncoding* encodings; NSStringEncoding* converted; encodings = CFStringGetListOfAvailableEncodings(); for (i = 0; encodings[i] != 0; i++) count++; converted = (NSStringEncoding*) CFAllocatorAllocate (kCFAllocatorSystemDefault, (count+1) * sizeof(NSStringEncoding), 0); for (i = 0; i < count; i++) converted[i] = CFStringConvertEncodingToNSStringEncoding(encodings[i]); if (GSAtomicCompareAndSwapPointer (&nsencodings, NULL, converted) != NULL) CFAllocatorDeallocate (kCFAllocatorSystemDefault, converted); } return nsencodings; } - (void) getLineStart: (NSUInteger *) startIndex end: (NSUInteger *) lineEndIndex contentsEnd: (NSUInteger *) contentsEndIndex forRange: (NSRange) aRange { CFRange cfRange = CFRangeMake (aRange.location, aRange.length); CFStringGetLineBounds ((CFStringRef) self, cfRange, (CFIndex*)startIndex, (CFIndex*)lineEndIndex, (CFIndex*)contentsEndIndex); } - (NSString*) stringByPaddingToLength: (NSUInteger)newLength withString: (NSString*)padString startingAtIndex: (NSUInteger)padIndex { CFMutableStringRef copy; copy = CFStringCreateMutableCopy(NULL, 0, (CFStringRef) self); CFStringPad(copy, (CFStringRef) padString, newLength, padIndex); return (NSString *) copy; } - (void) getParagraphStart: (NSUInteger *) startPtr end: (NSUInteger *) parEndPtr contentsEnd: (NSUInteger *) contentsEndPtr forRange: (NSRange)range { CFRange cfRange = CFRangeMake (range.location, range.length); CFStringGetParagraphBounds ((CFStringRef) self, cfRange, (CFIndex*)startPtr, (CFIndex*)parEndPtr, (CFIndex*)contentsEndPtr); } - (NSRange) rangeOfComposedCharacterSequencesForRange: (NSRange)range { return NSMakeRange (NSNotFound, 0); // FIXME, even NSString doesn't implement this } // // NSMutableString methods // - (id) initWithCapacity: (NSUInteger)capacity { CFAllocatorRef alloc = kCFAllocatorDefault; RELEASE(self); self = (NSCFString*)CFStringCreateMutable (alloc, capacity); return self; } - (void) appendFormat: (NSString*) format, ... { va_list args; if (format == nil) [NSException raise: NSInvalidArgumentException format: @"format is nil."]; va_start(args, format); CFStringAppendFormatAndArguments ((CFMutableStringRef) self, NULL, (CFStringRef) format, args); va_end (args); } - (void) appendString: (NSString*) aString { CFStringAppend ((CFMutableStringRef) self, (CFStringRef) aString); } - (void) deleteCharactersInRange: (NSRange) range { CFRange cfRange = CFRangeMake (range.location, range.length); CFStringDelete ((CFMutableStringRef) self, cfRange); } - (void) insertString: (NSString*) aString atIndex: (NSUInteger) loc { CFStringInsert ((CFMutableStringRef) self, loc, (CFStringRef) aString); } - (void) replaceCharactersInRange: (NSRange) range withString: (NSString*) aString { CFRange cfRange = CFRangeMake (range.location, range.length); CFStringReplace ((CFMutableStringRef) self, cfRange, (CFStringRef) aString); } - (NSUInteger) replaceOccurrencesOfString: (NSString*) replace withString: (NSString*) by options: (NSUInteger) opts range: (NSRange) searchRange { CFRange cfRange = CFRangeMake (searchRange.location, searchRange.length); if (replace == nil) [NSException raise: NSInvalidArgumentException format: @"Target string is nil."]; if (by == nil) [NSException raise: NSInvalidArgumentException format: @"Replacement is nil."]; /* FIXME: raise exception for out of range */ return CFStringFindAndReplace ((CFMutableStringRef) self, (CFStringRef) replace, (CFStringRef) by, cfRange, (CFOptionFlags)opts); } - (void) setString: (NSString*) aString { CFStringReplaceAll ((CFMutableStringRef) self, (CFStringRef) aString); } @end @implementation NSString (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFStringGetTypeID(); } @end @implementation NSMutableString (CoreBaseAdditions) - (void) _cfTrimWhitespace { NSString* trimmed; trimmed = [self stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; [self setString: trimmed]; [trimmed release]; } @end gnustep-corebase-0.2/Source/GNUmakefile.in0000644000175000017500000000442114551015633017626 0ustar yavoryavorinclude $(GNUSTEP_MAKEFILES)/common.make include ../Version PACKAGE_NAME = gnustep-corebase LIBRARY_NAME = libgnustep-corebase ADDITIONAL_INCLUDE_DIRS = -I../Headers ADDITIONAL_CFLAGS = -DBUILDING_SELF ADDITIONAL_CXXFLAGS = -DBUILDING_SELF ADDITIONAL_OBJCFLAGS = -DBUILDING_SELF libgnustep-corebase_INTERFACE_VERSION = $(MAJOR_VERSION) libgnustep-corebase_C_FILES = \ CFArray.c \ CFAttributedString.c \ CFBag.c \ CFBase.c \ CFBinaryHeap.c \ CFBitVector.c \ CFCalendar.c \ CFCharacterSet.c \ CFData.c \ CFDate.c \ CFDateFormatter.c \ CFDictionary.c \ CFError.c \ CFLocale.c \ CFNumber.c \ CFNumberFormatter.c \ CFPropertyList.c \ CFRunLoop.c \ CFRuntime.c \ CFSet.c \ CFSocket.c \ CFStream.c \ CFString.c \ CFConstantString.c \ CFStringEncoding.c \ CFStringUtilities.c \ CFTimeZone.c \ CFTree.c \ CFURL.c \ CFURLAccess.c \ CFUUID.c \ CFXMLNode.c \ CFXMLParser.c \ GSCArray.c \ GSFunctions.c \ GSHashTable.c \ GSUnicode.c libgnustep-corebase_HEADER_FILES = \ CoreFoundation.h \ CFArray.h \ CFAttributedString.h \ CFAvailability.h \ CFBag.h \ CFBase.h \ CFBinaryHeap.h \ CFBitVector.h \ CFBundle.h \ CFByteOrder.h \ CFCalendar.h \ CFCharacterSet.h \ CFData.h \ CFDate.h \ CFDateFormatter.h \ CFDictionary.h \ CFError.h \ CFLocale.h \ CFNumber.h \ CFNumberFormatter.h \ CFPropertyList.h \ CFRunLoop.h \ CFRuntime.h \ CFSet.h \ CFSocket.h \ CFStream.h \ CFStreamPriv.h \ CFString.h \ CFStringEncodingExt.h \ CFTimeZone.h \ CFTree.h \ CFURL.h \ CFURLAccess.h \ CFUUID.h \ CFXMLNode.h \ CFXMLParser.h \ GSCharacter.h libgnustep-corebase_OBJC_FILES = \ CFBundle.m \ NSCFArray.m \ NSCFData.m \ NSCFError.m \ NSCFString.m \ NSCFSet.m \ NSCFLocale.m \ NSCFNumber.m \ NSCFDictionary.m \ NSCFTimeZone.m \ NSCFInputStream.m \ NSCFOutputStream.m \ NSCFDate.m \ NSCFType.m libgnustep-corebase_LIBRARIES_DEPEND_UPON += @LIBS@ $(FND_LIBS) libgnustep-corebase_HEADER_FILES_DIR = ../Headers/CoreFoundation libgnustep-corebase_HEADER_FILES_INSTALL_DIR = CoreFoundation libgnustep-corebase_NEEDS_GUI = NO ifeq ($(GNUSTEP_TARGET_OS), mingw32) ADDITIONAL_LDFLAGS = -L/mingw/bin endif include $(GNUSTEP_MAKEFILES)/library.make -include Makefile.postamble gnustep-corebase-0.2/Source/GSCArray.c0000644000175000017500000000653413222706330016730 0ustar yavoryavor/* GSCArray.c Copyright (C) 2013 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: July, 2013 This file is part of GNUstep CoreBase library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "GSCArray.h" #define GS_EXCHANGE_VALUES(_v1, _v2) do \ { \ const void *_tmp_; \ _tmp_ = _v1; \ _v1 = _v2; \ _v2 = _tmp_; \ } while (0) void GSCArrayQuickSort (const void **array, CFIndex length, CFComparatorFunction comparator, void *context) { if (length > 16) /* 16 is an arbritrary "small" number */ { const void *value; CFIndex pivot; CFIndex stored; CFIndex idx; pivot = length / 2; value = array[pivot]; GS_EXCHANGE_VALUES (array[pivot], array[length - 1]); for (idx = 0, stored = 0; idx < length; ++idx) { if ((*comparator) (array[idx], value, context) == kCFCompareLessThan) { GS_EXCHANGE_VALUES (array[idx], array[stored]); ++stored; } } GS_EXCHANGE_VALUES (array[stored], array[length - 1]); GSCArrayQuickSort (array, stored - 1, comparator, context); GSCArrayQuickSort (array + stored + 1, length - stored, comparator, context); } GSCArrayInsertionSort (array, length, comparator, context); } void GSCArrayInsertionSort (const void **array, CFIndex length, CFComparatorFunction comparator, void *context) { CFIndex idx; for (idx = 1; idx < length; ++idx) { int hole; const void *value; hole = idx; value = array[hole]; while (hole > 0 && (*comparator) (value, array[hole - 1], context) == kCFCompareLessThan) { array[hole] = array[hole - 1]; --hole; } array[hole] = value; } } CFIndex GSCArrayBSearch (const void **array, const void *key, CFIndex length, CFComparatorFunction comparator, void *context) { CFIndex min; CFIndex mid; CFIndex max; min = 0; max = length; while (min < max) { CFComparisonResult r; mid = (min + max) / 2; r = (*comparator) (key, array[mid], context); if (r == kCFCompareLessThan) { max = mid - 1; break; } else if (r == kCFCompareGreaterThan) { max = mid - 1; } else { min = mid + 1; } } return max + 1; } void GSCArrayHeapify (const void **array, CFIndex length, CFComparatorFunction comparator, void *context) { } gnustep-corebase-0.2/Source/CFBag.c0000644000175000017500000001127713222706330016217 0ustar yavoryavor/* CFBag.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: November, 2011 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFBag.h" #include "CoreFoundation/CFString.h" #include "GSHashTable.h" #include "GSObjCRuntime.h" static CFTypeID _kCFBagTypeID = 0; static void CFBagFinalize (CFTypeRef cf) { GSHashTableFinalize ((GSHashTableRef)cf); } static Boolean CFBagEqual (CFTypeRef cf1, CFTypeRef cf2) { return GSHashTableEqual ((GSHashTableRef)cf1, (GSHashTableRef)cf2); } static CFHashCode CFBagHash (CFTypeRef cf) { return GSHashTableHash ((GSHashTableRef)cf); } static CFStringRef CFBagCopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOptions) { return CFSTR(""); } static CFRuntimeClass CFBagClass = { 0, "CFBag", NULL, (CFTypeRef(*)(CFAllocatorRef, CFTypeRef))CFBagCreateCopy, CFBagFinalize, CFBagEqual, CFBagHash, CFBagCopyFormattingDesc, NULL }; void CFBagInitialize (void) { _kCFBagTypeID = _CFRuntimeRegisterClass (&CFBagClass); } const CFBagCallBacks kCFCopyStringBagCallBacks = { 0, (CFTypeRef (*)(CFAllocatorRef, CFTypeRef))CFStringCreateCopy, CFTypeReleaseCallBack, CFCopyDescription, CFEqual, CFHash }; const CFBagCallBacks kCFTypeBagCallBacks = { 0, CFTypeRetainCallBack, CFTypeReleaseCallBack, CFCopyDescription, CFEqual, CFHash }; CFBagRef CFBagCreate (CFAllocatorRef allocator, const void **values, CFIndex numValues, const CFBagCallBacks *callBacks) { return (CFBagRef)GSHashTableCreate (allocator, _kCFBagTypeID, values, values, numValues, (const GSHashTableKeyCallBacks*)callBacks, NULL); } CFBagRef CFBagCreateCopy (CFAllocatorRef allocator, CFBagRef bag) { return (CFBagRef)GSHashTableCreateCopy (allocator, (GSHashTableRef)bag); } void CFBagApplyFunction (CFBagRef bag, CFBagApplierFunction applier, void *context) { } Boolean CFBagContainsValue (CFBagRef bag, const void *value) { return GSHashTableContainsKey ((GSHashTableRef)bag, value); } CFIndex CFBagGetCount (CFBagRef bag) { return GSHashTableGetCount ((GSHashTableRef)bag); } CFIndex CFBagGetCountOfValue (CFBagRef bag, const void *value) { return GSHashTableGetCountOfKey ((GSHashTableRef)bag, value); } void CFBagGetValues (CFBagRef bag, const void **values) { GSHashTableGetKeysAndValues ((GSHashTableRef)bag, values, NULL); } const void * CFBagGetValue (CFBagRef bag, const void *value) { return GSHashTableGetValue ((GSHashTableRef)bag, value); } Boolean CFBagGetValueIfPresent (CFBagRef bag, const void *candidate, const void **value) { const void *v; v = CFBagGetValue (bag, candidate); if (v) { if (value) *value = v; return true; } return false; } CFTypeID CFBagGetTypeID (void) { return _kCFBagTypeID; } CFMutableBagRef CFBagCreateMutable (CFAllocatorRef allocator, CFIndex capacity, const CFBagCallBacks *callBacks) { return (CFMutableBagRef)GSHashTableCreateMutable (allocator, _kCFBagTypeID, capacity, (const GSHashTableKeyCallBacks*)callBacks, NULL); } CFMutableBagRef CFBagCreateMutableCopy (CFAllocatorRef allocator, CFIndex capacity, CFBagRef bag) { return (CFMutableBagRef)GSHashTableCreateMutableCopy (allocator, (GSHashTableRef)bag, capacity); } void CFBagAddValue (CFMutableBagRef bag, const void *value) { GSHashTableAddValue ((GSHashTableRef)bag, value, value); } void CFBagRemoveAllValues (CFMutableBagRef bag) { GSHashTableRemoveAll ((GSHashTableRef)bag); } void CFBagRemoveValue (CFMutableBagRef bag, const void *value) { GSHashTableRemoveValue ((GSHashTableRef)bag, value); } void CFBagReplaceValue (CFMutableBagRef bag, const void *value) { GSHashTableReplaceValue ((GSHashTableRef)bag, value, value); } void CFBagSetValue (CFMutableBagRef bag, const void *value) { GSHashTableSetValue ((GSHashTableRef)bag, value, value); } gnustep-corebase-0.2/Source/NSCFArray.m0000644000175000017500000000552713222706330017060 0ustar yavoryavor/* NSCFArray.m Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: November, 2011 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #include #include "NSCFType.h" #include "CoreFoundation/CFArray.h" @interface NSCFArray : NSMutableArray NSCFTYPE_VARS @end @interface NSArray (CoreBaseAdditions) - (CFTypeID) _cfTypeID; @end @implementation NSCFArray + (void) load { NSCFInitialize (); } + (void) initialize { GSObjCAddClassBehavior (self, [NSCFType class]); } - (id) initWithObjects:(id)firstObj, ... { RELEASE(self); if (firstObj == nil) { return (NSCFArray*) CFArrayCreate(NULL, NULL, 0, &kCFTypeArrayCallBacks); } /* copy all arguments into a temporary mutable array */ CFMutableArrayRef temp = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks); va_list ap; id obj; va_start(ap, firstObj); CFArrayAppendValue(temp, firstObj); while ((obj = va_arg(ap, id)) != nil) CFArrayAppendValue(temp, obj); va_end(ap); self = (NSCFArray*) CFArrayCreateCopy(NULL, temp); RELEASE((id)temp); return self; } - (NSUInteger) count { return (NSUInteger)CFArrayGetCount ((CFArrayRef)self); } - (id) objectAtIndex: (NSUInteger) index { return (id)CFArrayGetValueAtIndex ((CFArrayRef)self, (CFIndex)index); } -(void) addObject: (id) anObject { CFArrayAppendValue ((CFMutableArrayRef)self, (const void*)anObject); } - (void) replaceObjectAtIndex: (NSUInteger) index withObject: (id) anObject { CFArraySetValueAtIndex ((CFMutableArrayRef)self, (CFIndex)index, (const void*)anObject); } - (void) insertObject: (id) anObject atIndex: (NSUInteger) index { CFArrayInsertValueAtIndex ((CFMutableArrayRef)self, (CFIndex)index, (const void*)anObject); } - (void) removeObjectAtIndex: (NSUInteger) index { CFArrayRemoveValueAtIndex ((CFMutableArrayRef)self, (CFIndex)index); } @end @implementation NSArray (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFArrayGetTypeID(); } @end gnustep-corebase-0.2/Source/GSHashTable.c0000644000175000017500000004725014551015633017407 0ustar yavoryavor/* GSHashTable.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: November, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "GSHashTable.h" #include "GSPrivate.h" #include /* READ THIS FIRST * * GSHashTable uses an open-address scheme with double hashing for * collision resolution. This method has a few drawbacks, such as much * higher memory usage on the worst case, but it is very simple to * implement. This is because, as explained below, we try to keep the * load factor less than 80%, so at least 20% of the memory allocated is * not used. * * One thing that needs to be kept in mind is table load, we * don't want it to go over 80%. The collisions start to get out of * hand at that point. Collisions might also be a problem if the hash * algorithm isn't very good. Some of this is mitigated by using * prime numbers as the hash table size. There are other open addressing * algorithms out there that can handle high load factors more gracefully * than double hashing, but they're also more complicated, like * Cuckoo hashing or Hopscotch hasing. * * The implementation originally used an equation to calculate the next * array size. This became a problem because we were calculating the * table size each time we add or removed an item. Now a lookup table * is used, instead. * * To be as easy as possible on system memory, we rehash not only when * the table load factor gets above 80% but also when it gets below 25%. * This is optimum, but we also want to keep memory usage at a manageable * level. Rehashing to a lower level is only done when removing an object, * though. So we can start with a really large table (high capacity) and * never shrink if we don't remove anything. */ static const GSHashTableKeyCallBacks _kGSNullHashTableKeyCallBacks = { 0, NULL, NULL, NULL, NULL, NULL }; static const GSHashTableValueCallBacks _kGSNullHashTableValueCallBacks = { 0, NULL, NULL, NULL, NULL }; enum { _kGSHashTableMutable = (1 << 0), _kGSHashTableShouldCount = (1 << 1) }; CF_INLINE Boolean GSHashTableIsMutable (GSHashTableRef table) { return ((CFRuntimeBase *) table)->_flags.info & _kGSHashTableMutable ? true : false; } CF_INLINE Boolean GSHashTableShouldCount (GSHashTableRef table) { return ((CFRuntimeBase *) table)->_flags.info & _kGSHashTableShouldCount ? true : false; } CF_INLINE void GSHashTableSetMutable (GSHashTableRef table) { ((CFRuntimeBase *) table)->_flags.info |= _kGSHashTableMutable; } CF_INLINE void GSHashTableSetShouldCount (GSHashTableRef table) { ((CFRuntimeBase *) table)->_flags.info |= _kGSHashTableShouldCount; } typedef enum { _kGSHashTableRetrieve, // retrieval or deletion _kGSHashTableInsert // insertion only } _kGSHashTableOperation; static CFIndex _kGSHashTableBucketCountDeleted = -1; CF_INLINE void GSHashTableAddKeyValuePair (GSHashTableRef table, GSHashTableBucket * bucket, const void *key, const void *value) { GSHashTableRetainCallBack keyRetain = table->_keyCallBacks.retain; GSHashTableRetainCallBack valueRetain = table->_valueCallBacks.retain; CFIndex count = bucket->count; bucket->count = (count == _kGSHashTableBucketCountDeleted) ? 1 : (count + 1); bucket->key = keyRetain ? keyRetain (table->_allocator, key) : key; bucket->value = valueRetain ? valueRetain (table->_allocator, value) : value; } CF_INLINE void GSHashTableReplaceKeyValuePair (GSHashTableRef table, GSHashTableBucket * bucket, const void *key, const void *value) { GSHashTableReleaseCallBack release = table->_valueCallBacks.release; GSHashTableRetainCallBack retain = table->_valueCallBacks.retain; if (release) release (table->_allocator, bucket->value); bucket->value = retain ? retain (table->_allocator, value) : value; } CF_INLINE void GSHashTableRemoveKeyValuePair (GSHashTableRef table, GSHashTableBucket * bucket, CFIndex bucketCountDeleted) { GSHashTableReleaseCallBack keyRelease = table->_keyCallBacks.release; GSHashTableReleaseCallBack valueRelease = table->_valueCallBacks.release; if (keyRelease) keyRelease (table->_allocator, bucket->key); if (valueRelease) valueRelease (table->_allocator, bucket->value); bucket->count = bucketCountDeleted; bucket->key = NULL; bucket->value = NULL; } typedef Boolean (*GSHashTableBucketIsUnoccupiedCallback) (GSHashTableBucket bucket); CF_INLINE Boolean GSHashTableBucketIsUnoccupied(GSHashTableBucket bucket, _kGSHashTableOperation operation) { switch (operation) { case _kGSHashTableRetrieve: return bucket.count == 0; // treat deleted buckets as occupied case _kGSHashTableInsert: return bucket.count <= 0; // treat deleted buckets as unoccupied } #if __has_builtin(__builtin_unreachable) __builtin_unreachable(); #else abort(); #endif } static Boolean GSHashTableEqualPointers (const void *key1, const void *key2) { return key1 == key2; } static GSHashTableBucket * GSHashTableFindBucket (GSHashTableRef table, const void *key, _kGSHashTableOperation operation) { GSHashTableBucket *buckets; CFIndex capacity; CFIndex initialIdx, idx; CFHashCode hash; Boolean matched; GSHashTableHashCallBack fHash = table->_keyCallBacks.hash; GSHashTableEqualCallBack fEqual = table->_keyCallBacks.equal; if (!fEqual) fEqual = GSHashTableEqualPointers; buckets = table->_buckets; capacity = table->_capacity; hash = fHash ? fHash (key) : GSHashPointer (key); initialIdx = idx = hash % capacity; matched = GSHashTableBucketIsUnoccupied(buckets[idx], operation) || (buckets[idx].key && fEqual (key, buckets[idx].key)); if (!matched) { CFHashCode hash2 = 1 + ((hash / capacity) % (capacity - 1)); do { hash += hash2; idx = hash % capacity; matched = GSHashTableBucketIsUnoccupied(buckets[idx], operation) || (buckets[idx].key && fEqual (key, buckets[idx].key)); } while (!matched && idx != initialIdx); } // match should be NULL for _kGSHashTableRetrieve ONLY assert(matched || operation == _kGSHashTableRetrieve); return matched ? &buckets[idx] : NULL; } /* Go as close to INT_MAX as we can. */ static CFIndex _kGSHashTableSizes[] = { 7, 13, 29, 59, 127, 257, 521, 1049, 2099, 4201, 8419, 16843, 33703, 67409, 134837, 269683, 539389, 1078787, 2157587, 4315183, 8630387, 17260781, 34521589, 69043189, 138086407, 276172823, 552345671, 1104691373 }; static CFIndex _kGSHashTableSizesCount = sizeof (_kGSHashTableSizes) / sizeof (CFIndex); /* Calculted 80% of values above. */ static CFIndex _kGSHashTableFilled[] = { 5, 10, 23, 47, 101, 205, 416, 839, 2099, 3360, 6735, 13474, 26962, 53927, 107869, 215746, 431511, 863029, 1726069, 3452146, 6904309, 13808624, 27617271, 55234551, 110469125, 220938258, 441876536, 883753098 }; CF_INLINE CFIndex GSHashTableGetSize (CFIndex min) { CFIndex idx = 0; while (min > _kGSHashTableFilled[idx] && idx < _kGSHashTableSizesCount) ++idx; return _kGSHashTableSizes[idx]; } #define GSHASHTABLE_EXTRA (sizeof(struct GSHashTable) - sizeof(CFRuntimeBase)) #define GET_ARRAY_SIZE(s) ((s) * sizeof(GSHashTableBucket)) GSHashTableRef GSHashTableCreate (CFAllocatorRef alloc, CFTypeID typeID, const void **keys, const void **values, CFIndex numValues, const GSHashTableKeyCallBacks * keyCallBacks, const GSHashTableValueCallBacks * valueCallBacks) { CFIndex arraySize; CFIndex capacity; GSHashTableRef new; capacity = GSHashTableGetSize (numValues); arraySize = GET_ARRAY_SIZE (capacity); new = (GSHashTableRef) _CFRuntimeCreateInstance (alloc, typeID, GSHASHTABLE_EXTRA + arraySize, NULL); if (new) { CFIndex idx; GSHashTableBucket *bucket; new->_allocator = alloc; new->_buckets = (GSHashTableBucket *) & (new[1]); new->_capacity = capacity; if (keyCallBacks == NULL) keyCallBacks = &_kGSNullHashTableKeyCallBacks; if (valueCallBacks == NULL) valueCallBacks = &_kGSNullHashTableValueCallBacks; memcpy (&new->_keyCallBacks, keyCallBacks, sizeof (GSHashTableKeyCallBacks)); memcpy (&new->_valueCallBacks, valueCallBacks, sizeof (GSHashTableValueCallBacks)); if (keys != NULL) { for (idx = 0; idx < numValues; ++idx) { bucket = GSHashTableFindBucket (new, keys[idx], _kGSHashTableInsert); GSHashTableAddKeyValuePair (new, bucket, keys[idx], values[idx]); new->_count += 1; } } } return new; } GSHashTableRef GSHashTableCreateCopy (CFAllocatorRef alloc, GSHashTableRef table) { CFIndex count; GSHashTableRef new; count = GSHashTableGetCount (table); new = GSHashTableCreate (alloc, CFGetTypeID (table), NULL, NULL, count, &table->_keyCallBacks, &table->_valueCallBacks); if (new) { CFIndex idx; GSHashTableBucket *bucket; GSHashTableBucket *buckets = table->_buckets; for (idx = 0; idx < table->_capacity; ++idx) { if (buckets[idx].key) { bucket = GSHashTableFindBucket (new, buckets[idx].key, _kGSHashTableInsert); GSHashTableAddKeyValuePair (new, bucket, buckets[idx].key, buckets[idx].value); new->_count += 1; } } } return new; } void GSHashTableFinalize (GSHashTableRef table) { GSHashTableRemoveAll (table); if (GSHashTableIsMutable (table)) CFAllocatorDeallocate (table->_allocator, table->_buckets); } Boolean GSHashTableEqual (GSHashTableRef table1, GSHashTableRef table2) { if (table1->_count == table2->_count) { GSHashTableBucket *current; GSHashTableBucket *end; GSHashTableBucket *other; GSHashTableEqualCallBack keyEqual; GSHashTableEqualCallBack valueEqual; current = table1->_buckets; end = current + table1->_capacity; keyEqual = table1->_keyCallBacks.equal; valueEqual = table1->_valueCallBacks.equal; if (!keyEqual) keyEqual = GSHashTableEqualPointers; if (!valueEqual) valueEqual = GSHashTableEqualPointers; while (current < end) { if (current->count > 0) { other = GSHashTableFindBucket (table2, current->key, _kGSHashTableRetrieve); if (!other || current->count != other->count || !keyEqual (current->key, other->key) || !valueEqual (current->value, other->value)) return false; } ++current; } return true; } return false; } CFHashCode GSHashTableHash (GSHashTableRef table) { return table->_count; } Boolean GSHashTableContainsKey (GSHashTableRef table, const void *key) { GSHashTableBucket *bucket; bucket = GSHashTableFindBucket (table, key, _kGSHashTableRetrieve); return bucket ? (bucket->count > 0 ? true : false) : false; } Boolean GSHashTableContainsValue (GSHashTableRef table, const void *value) { CFIndex idx; GSHashTableBucket *buckets = table->_buckets; GSHashTableEqualCallBack equal = table->_valueCallBacks.equal; if (!equal) equal = GSHashTableEqualPointers; for (idx = 0; idx < table->_capacity; ++idx) { if (buckets[idx].key) { if (equal (value, buckets[idx].value)) return true; } } return false; } CFIndex GSHashTableGetCount (GSHashTableRef table) { return table->_count; } CFIndex GSHashTableGetCountOfKey (GSHashTableRef table, const void *key) { GSHashTableBucket *bucket; bucket = GSHashTableFindBucket (table, key, _kGSHashTableRetrieve); return bucket ? bucket->count : 0; } CFIndex GSHashTableGetCountOfValue (GSHashTableRef table, const void *value) { CFIndex idx; CFIndex count = 0; GSHashTableBucket *buckets = table->_buckets; GSHashTableEqualCallBack equal = table->_valueCallBacks.equal; if (!equal) equal = GSHashTableEqualPointers; for (idx = 0; idx < table->_capacity; ++idx) { if (buckets[idx].key) { if (equal (value, buckets[idx].value)) count += buckets[idx].count; } } return count; } void GSHashTableGetKeysAndValues (GSHashTableRef table, const void **keys, const void **values) { CFIndex idx; CFIndex j = 0; GSHashTableBucket *buckets = table->_buckets; for (idx = 0; idx < table->_capacity; ++idx) { if (buckets[idx].count > 0) { if (keys) keys[j] = buckets[idx].key; if (values) values[j] = buckets[idx].value; ++j; } } } const void * GSHashTableGetValue (GSHashTableRef table, const void *key) { GSHashTableBucket *bucket; bucket = GSHashTableFindBucket (table, key, _kGSHashTableRetrieve); return bucket ? bucket->value : NULL; } static void GSHashTableRehash (GSHashTableRef table, CFIndex newCapacity) { CFIndex idx; CFIndex oldSize; GSHashTableBucket *bucket; GSHashTableBucket *oldBuckets; oldSize = table->_capacity; oldBuckets = table->_buckets; table->_capacity = newCapacity; table->_buckets = CFAllocatorAllocate (table->_allocator, GET_ARRAY_SIZE (newCapacity), 0); memset (table->_buckets, 0, GET_ARRAY_SIZE (newCapacity)); for (idx = 0; idx < oldSize; ++idx) { if (oldBuckets[idx].key) { bucket = GSHashTableFindBucket (table, oldBuckets[idx].key, _kGSHashTableInsert); GSHashTableAddKeyValuePair (table, bucket, oldBuckets[idx].key, oldBuckets[idx].value); } } CFAllocatorDeallocate (table->_allocator, oldBuckets); } CF_INLINE void GSHashTableGrowIfNeeded (GSHashTableRef table) { CFIndex newSize; if ((newSize = GSHashTableGetSize (table->_count + 1)) > table->_capacity) GSHashTableRehash (table, newSize); } CF_INLINE void GSHashTableShrinkIfNeeded (GSHashTableRef table) { /* Shrink if count is less than half of capacity) */ if (table->_count < (table->_capacity >> 2)) GSHashTableRehash (table, GSHashTableGetSize (table->_count)); } GSHashTableRef GSHashTableCreateMutable (CFAllocatorRef allocator, CFTypeID typeID, CFIndex capacity, const GSHashTableKeyCallBacks * keyCallBacks, const GSHashTableValueCallBacks * valueCallBacks) { GSHashTableRef new; new = (GSHashTableRef) _CFRuntimeCreateInstance (allocator, typeID, GSHASHTABLE_EXTRA, NULL); if (new) { CFIndex arraySize; capacity = GSHashTableGetSize (capacity); arraySize = GET_ARRAY_SIZE (capacity); new->_allocator = allocator; new->_buckets = CFAllocatorAllocate (allocator, arraySize, 0); memset (new->_buckets, 0, arraySize); new->_capacity = capacity; if (keyCallBacks == NULL) keyCallBacks = &_kGSNullHashTableKeyCallBacks; if (valueCallBacks == NULL) valueCallBacks = &_kGSNullHashTableValueCallBacks; memcpy (&new->_keyCallBacks, keyCallBacks, sizeof (GSHashTableKeyCallBacks)); memcpy (&new->_valueCallBacks, valueCallBacks, sizeof (GSHashTableValueCallBacks)); GSHashTableSetMutable (new); } return new; } GSHashTableRef GSHashTableCreateMutableCopy (CFAllocatorRef alloc, GSHashTableRef table, CFIndex capacity) { GSHashTableRef new; if (capacity < table->_count) capacity = table->_count; new = GSHashTableCreateMutable (alloc, CFGetTypeID (table), capacity, &table->_keyCallBacks, &table->_valueCallBacks); if (new) { CFIndex idx; GSHashTableBucket *bucket; GSHashTableBucket *buckets = table->_buckets; for (idx = 0; idx < table->_capacity; ++idx) { if (buckets[idx].key) { bucket = GSHashTableFindBucket (new, buckets[idx].key, _kGSHashTableInsert); GSHashTableAddKeyValuePair (new, bucket, buckets[idx].key, buckets[idx].value); new->_count += 1; } } } return new; } void GSHashTableAddValue (GSHashTableRef table, const void *key, const void *value) { GSHashTableBucket *bucket; GSHashTableGrowIfNeeded (table); bucket = GSHashTableFindBucket (table, key, _kGSHashTableRetrieve); if (!bucket) bucket = GSHashTableFindBucket (table, key, _kGSHashTableInsert); if (bucket->count <= 0) { GSHashTableAddKeyValuePair (table, bucket, key, value); table->_count += 1; } } void GSHashTableReplaceValue (GSHashTableRef table, const void *key, const void *value) { GSHashTableBucket *bucket; bucket = GSHashTableFindBucket (table, key, _kGSHashTableRetrieve); if (bucket && bucket->count > 0) GSHashTableReplaceKeyValuePair (table, bucket, key, value); } void GSHashTableSetValue (GSHashTableRef table, const void *key, const void *value) { GSHashTableBucket *bucket; GSHashTableGrowIfNeeded (table); bucket = GSHashTableFindBucket (table, key, _kGSHashTableRetrieve); if (!bucket) bucket = GSHashTableFindBucket (table, key, _kGSHashTableInsert); if (bucket->count > 0) { GSHashTableReplaceKeyValuePair (table, bucket, key, value); } else { GSHashTableAddKeyValuePair (table, bucket, key, value); table->_count += 1; } } void GSHashTableRemoveAll (GSHashTableRef table) { CFIndex idx; GSHashTableBucket *buckets = table->_buckets; for (idx = 0; idx < table->_capacity; ++idx) { if (buckets[idx].count > 0) GSHashTableRemoveKeyValuePair (table, &buckets[idx], 0); } table->_count = 0; } void GSHashTableRemoveValue (GSHashTableRef table, const void *key) { GSHashTableBucket *bucket; bucket = GSHashTableFindBucket (table, key, _kGSHashTableRetrieve); if (bucket) { if (bucket->count > 1) { bucket->count -= 1; } else if (bucket->count == 1) { GSHashTableRemoveKeyValuePair (table, bucket, _kGSHashTableBucketCountDeleted); table->_count -= 1; } GSHashTableShrinkIfNeeded (table); } } gnustep-corebase-0.2/Source/NSCFError.m0000644000175000017500000000500513222706330017062 0ustar yavoryavor/* NSCFError.m Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: September, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #import #import #include "NSCFType.h" #include "CoreFoundation/CFError.h" @interface NSCFError : NSError NSCFTYPE_VARS @end @interface NSError (CoreBaseAdditions) - (CFTypeID) _cfTypeID; @end @implementation NSCFError + (void) load { NSCFInitialize (); } + (void) initialize { GSObjCAddClassBehavior (self, [NSCFType class]); } - (id) initWithDomain: (NSString*) domain code: (NSInteger) code userInfo: (NSDictionary*) userInfo { RELEASE(self); return (NSCFError*)CFErrorCreate (NULL, (CFStringRef)domain, (CFIndex)code, (CFDictionaryRef)userInfo); } - (NSString *) localizedDescription { return AUTORELEASE((id) CFErrorCopyDescription ((CFErrorRef) self)); } - (NSString *) localizedFailureReason { return AUTORELEASE((id) CFErrorCopyFailureReason ((CFErrorRef) self)); } - (NSArray *) localizedRecoveryOptions { return nil; // FIXME } - (NSString *) localizedRecoverySuggestion { return AUTORELEASE((id) CFErrorCopyRecoverySuggestion ((CFErrorRef) self)); } - (id) recoveryAttempter { return nil; // FIXME } - (NSInteger) code { return (NSInteger)CFErrorGetCode ((CFErrorRef) self); } - (NSString*) domain { return (NSString *) CFErrorGetDomain ((CFErrorRef) self); } - (NSDictionary*) userInfo { return (NSDictionary*)CFErrorCopyUserInfo ((CFErrorRef) self); } @end @implementation NSError (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFErrorGetTypeID(); } @end gnustep-corebase-0.2/Source/CFConstantString.c0000644000175000017500000003311013222706330020474 0ustar yavoryavor/* CFConstantString.c Copyright (C) 2016 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: July, 2016 This file is part of GNUstep CoreBase Library. This library is free software; you can redisibute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is disibuted in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "GSObjCRuntime.h" /* Need the next few includes so we can initialize the string constants */ #include "CoreFoundation/CFError.h" #include "CoreFoundation/CFDateFormatter.h" #include "CoreFoundation/CFLocale.h" #include "CoreFoundation/CFNumberFormatter.h" #include "CoreFoundation/CFRunLoop.h" #include "CoreFoundation/CFStream.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFURLAccess.h" #include "CoreFoundation/CFXMLParser.h" /* WARNING!!! This initialization function must be called after CFStringInitialize(), or else CFStringGetTypeID() will not return a valid type id. */ void CFConstantStringInitialize (void) { CFTypeID _kCFStringTypeID; _kCFStringTypeID = CFStringGetTypeID (); /* Constants defined in CFError.h */ GSRuntimeConstantInit (kCFErrorDomainPOSIX, _kCFStringTypeID); GSRuntimeConstantInit (kCFErrorDomainOSStatus, _kCFStringTypeID); GSRuntimeConstantInit (kCFErrorDomainMach, _kCFStringTypeID); GSRuntimeConstantInit (kCFErrorDomainCocoa, _kCFStringTypeID); GSRuntimeConstantInit (kCFErrorLocalizedDescriptionKey, _kCFStringTypeID); GSRuntimeConstantInit (kCFErrorLocalizedFailureReasonKey, _kCFStringTypeID); GSRuntimeConstantInit (kCFErrorLocalizedRecoverySuggestionKey, _kCFStringTypeID); GSRuntimeConstantInit (kCFErrorDescriptionKey, _kCFStringTypeID); GSRuntimeConstantInit (kCFErrorUnderlyingErrorKey, _kCFStringTypeID); /* Constants defined in CFString.h */ GSRuntimeConstantInit (kCFStringTransformStripCombiningMarks, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformToLatin, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformFullwidthHalfwidth, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformLatinKatakana, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformLatinHiragana, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformHiraganaKatakana, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformMandarinLatin, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformLatinHangul, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformLatinArabic, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformLatinHebrew, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformLatinThai, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformLatinCyrillic, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformLatinGreek, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformToXMLHex, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformToUnicodeName, _kCFStringTypeID); GSRuntimeConstantInit (kCFStringTransformStripDiacritics, _kCFStringTypeID); /* Constants defined in CFLocale.h */ GSRuntimeConstantInit (kCFLocaleMeasurementSystem, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleDecimalSeparator, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleGroupingSeparator, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleCurrencySymbol, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleCurrencyCode, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleIdentifier, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleLanguageCode, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleCountryCode, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleScriptCode, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleVariantCode, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleExemplarCharacterSet, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleCalendarIdentifier, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleCalendar, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleCollationIdentifier, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleUsesMetricSystem, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleCollatorIdentifier, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleQuotationBeginDelimiterKey, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleQuotationEndDelimiterKey, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleAlternateQuotationBeginDelimiterKey, _kCFStringTypeID); GSRuntimeConstantInit (kCFLocaleAlternateQuotationEndDelimiterKey, _kCFStringTypeID); /* Constants defined in CFCalendar.h */ GSRuntimeConstantInit (kCFGregorianCalendar, _kCFStringTypeID); GSRuntimeConstantInit (kCFBuddhistCalendar, _kCFStringTypeID); GSRuntimeConstantInit (kCFChineseCalendar, _kCFStringTypeID); GSRuntimeConstantInit (kCFHebrewCalendar, _kCFStringTypeID); GSRuntimeConstantInit (kCFIslamicCalendar, _kCFStringTypeID); GSRuntimeConstantInit (kCFIslamicCivilCalendar, _kCFStringTypeID); GSRuntimeConstantInit (kCFJapaneseCalendar, _kCFStringTypeID); GSRuntimeConstantInit (kCFRepublicOfChinaCalendar, _kCFStringTypeID); GSRuntimeConstantInit (kCFPersianCalendar, _kCFStringTypeID); GSRuntimeConstantInit (kCFIndianCalendar, _kCFStringTypeID); GSRuntimeConstantInit (kCFISO8601Calendar, _kCFStringTypeID); /* Cosntants defined in CFDataFormatter.h */ GSRuntimeConstantInit (kCFDateFormatterIsLenient, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterTimeZone, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterCalendarName, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterDefaultFormat, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterTwoDigitStartDate, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterDefaultDate, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterCalendar, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterEraSymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterMonthSymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterShortMonthSymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterWeekdaySymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterShortWeekdaySymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterAMSymbol, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterPMSymbol, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterLongEraSymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterVeryShortMonthSymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterStandaloneMonthSymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterShortStandaloneMonthSymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterVeryShortStandaloneMonthSymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterVeryShortWeekdaySymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterStandaloneWeekdaySymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterShortStandaloneWeekdaySymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterVeryShortStandaloneWeekdaySymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterQuarterSymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterShortQuarterSymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterStandaloneQuarterSymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterShortStandaloneQuarterSymbols, _kCFStringTypeID); GSRuntimeConstantInit (kCFDateFormatterGregorianStartDate, _kCFStringTypeID); /* Constants defined in CFNumberFormatter.h */ GSRuntimeConstantInit (kCFNumberFormatterCurrencyCode, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterDecimalSeparator, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterCurrencyDecimalSeparator, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterAlwaysShowDecimalSeparator, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterGroupingSeparator, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterUseGroupingSeparator, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterPercentSymbol, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterZeroSymbol, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterNaNSymbol, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterInfinitySymbol, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterMinusSign, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterPlusSign, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterCurrencySymbol, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterExponentSymbol, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterMinIntegerDigits, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterMaxIntegerDigits, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterMinFractionDigits, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterMaxFractionDigits, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterGroupingSize, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterSecondaryGroupingSize, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterRoundingMode, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterRoundingIncrement, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterFormatWidth, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterPaddingPosition, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterPaddingCharacter, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterDefaultFormat, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterMultiplier, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterPositivePrefix, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterPositiveSuffix, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterNegativePrefix, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterNegativeSuffix, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterPerMillSymbol, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterInternationalCurrencySymbol, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterCurrencyGroupingSeparator, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterIsLenient, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterUseSignificantDigits, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterMinSignificantDigits, _kCFStringTypeID); GSRuntimeConstantInit (kCFNumberFormatterMaxSignificantDigits, _kCFStringTypeID); /* Constants defined in CFRunLoop.h */ GSRuntimeConstantInit (kCFRunLoopCommonModes, _kCFStringTypeID); GSRuntimeConstantInit (kCFRunLoopDefaultMode, _kCFStringTypeID); /* Constants defined in CFStream.h */ GSRuntimeConstantInit (kCFStreamPropertyDataWritten, _kCFStringTypeID); GSRuntimeConstantInit (kCFStreamPropertySocketNativeHandle, _kCFStringTypeID); GSRuntimeConstantInit (kCFStreamPropertySocketRemoteHostName, _kCFStringTypeID); GSRuntimeConstantInit (kCFStreamPropertySocketRemotePortNumber, _kCFStringTypeID); GSRuntimeConstantInit (kCFStreamPropertyAppendToFile, _kCFStringTypeID); GSRuntimeConstantInit (kCFStreamPropertyFileCurrentOffset, _kCFStringTypeID); /* Constants definedin CFXMLParser.h */ GSRuntimeConstantInit (kCFXMLTreeErrorDescription, _kCFStringTypeID); GSRuntimeConstantInit (kCFXMLTreeErrorLineNumber, _kCFStringTypeID); GSRuntimeConstantInit (kCFXMLTreeErrorLocation, _kCFStringTypeID); GSRuntimeConstantInit (kCFXMLTreeErrorStatusCode, _kCFStringTypeID); /* Constants defined in CFURLAccess.h */ GSRuntimeConstantInit (kCFURLFileExists, _kCFStringTypeID); GSRuntimeConstantInit (kCFURLFileDirectoryContents, _kCFStringTypeID); GSRuntimeConstantInit (kCFURLFileLength, _kCFStringTypeID); GSRuntimeConstantInit (kCFURLFileLastModificationTime, _kCFStringTypeID); GSRuntimeConstantInit (kCFURLFilePOSIXMode, _kCFStringTypeID); GSRuntimeConstantInit (kCFURLFileOwnerID, _kCFStringTypeID); GSRuntimeConstantInit (kCFURLHTTPStatusCode, _kCFStringTypeID); GSRuntimeConstantInit (kCFURLHTTPStatusLine, _kCFStringTypeID); } gnustep-corebase-0.2/Source/Makefile.postamble0000644000175000017500000000162413222706330020571 0ustar yavoryavor# # Makefile.postamble # # Project specific makefile rules # # Uncomment the targets you want. # The double colons (::) are important, do not make them single colons # otherwise the normal makefile rules will not be performed. # # Things to do before compiling # before-all:: # Things to do after compiling # after-all:: # Things to do before installing # before-install:: # Things to do after installing # after-install:: # Things to do before uninstalling # before-uninstall:: # Things to do after uninstalling # after-uninstall:: # Things to do before cleaning # before-clean:: # Things to do after cleaning # after-clean:: # Things to do before distcleaning # before-distclean:: # Things to do after distcleaning after-distclean:: @rm -f config.h GNUmakefile ../Headers/CoreFoundation/CFBase.h # Things to do before checking # before-check:: # Things to do after checking # after-check:: gnustep-corebase-0.2/Source/CFBitVector.c0000644000175000017500000002212413222706330017420 0ustar yavoryavor/* CFBitVector.c Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFBitVector.h" #include static CFTypeID _kCFBitVectorTypeID = 0; struct __CFBitVector { CFRuntimeBase _parent; CFIndex _count; CFIndex _byteCount; UInt8 *_bytes; }; enum { _kCFBitVectorIsMutable = (1<<0) }; CF_INLINE Boolean CFBitVectorIsMutable (CFBitVectorRef bv) { return ((CFRuntimeBase *)bv)->_flags.info & _kCFBitVectorIsMutable ? true : false; } CF_INLINE void CFBitVectorSetMutable (CFBitVectorRef bv) { ((CFRuntimeBase *)bv)->_flags.info |= _kCFBitVectorIsMutable; } CF_INLINE CFIndex CFBitVectorGetByteCount (CFIndex numBits) { return (numBits + 7) >> 3; /* (numBits + 7) / 8 */ } static void CFBitVectorFinalize (CFTypeRef cf) { CFBitVectorRef bv = (CFBitVectorRef)cf; if (CFBitVectorIsMutable(bv)) CFAllocatorDeallocate (CFGetAllocator(cf), bv->_bytes); } static Boolean CFBitVectorEqual (CFTypeRef cf1, CFTypeRef cf2) { CFBitVectorRef bv1 = (CFBitVectorRef)cf1; CFBitVectorRef bv2 = (CFBitVectorRef)cf2; if (bv1->_count == bv2->_count) { return memcmp (bv1->_bytes, bv2->_bytes, CFBitVectorGetByteCount(bv1->_count)) == 0 ? true : false; } return false; } static CFHashCode CFBitVectorHash (CFTypeRef cf) { CFBitVectorRef bv = (CFBitVectorRef)cf; return bv->_count; } static CFRuntimeClass CFBitVectorClass = { 0, "CFBitVector", NULL, NULL, CFBitVectorFinalize, CFBitVectorEqual, CFBitVectorHash, NULL, NULL }; void CFBitVectorInitialize (void) { _kCFBitVectorTypeID = _CFRuntimeRegisterClass (&CFBitVectorClass); } CF_INLINE CFIndex CFBitVectorGetByte (CFIndex idx) { return idx >> 3; /* idx / 8 */ } CF_INLINE CFIndex CFBitVectorGetBitIndex (CFIndex idx) { return idx & 7; /* idx % 8 */ } CF_INLINE UInt8 CFBitVectorBitMask (UInt8 mostSig, UInt8 leastSig) { return ((0xFF << (7 - leastSig + mostSig)) >> mostSig); } static void CFBitVectorOperation (CFBitVectorRef bv, CFRange range, UInt8 (*func)(UInt8, UInt8, void*), void *context) { CFIndex curByte; CFIndex endByte; CFIndex startBit; CFIndex endBit; UInt8 mask; Boolean multiByte; curByte = CFBitVectorGetByte (range.location); endByte = CFBitVectorGetByte (range.location + range.length - 1); startBit = CFBitVectorGetBitIndex (range.location); endBit = CFBitVectorGetBitIndex (range.location + range.length - 1); /* First byte */ if (curByte == endByte) { mask = CFBitVectorBitMask (startBit, startBit + endBit); multiByte = false; } else { mask = CFBitVectorBitMask (startBit, 7); multiByte = true; } bv->_bytes[curByte] = func (bv->_bytes[curByte], mask, context); /* Middle bytes */ while (curByte < endByte) { bv->_bytes[curByte] = func (bv->_bytes[curByte], 0xFF, context); ++curByte; } /* Last byte */ if (multiByte) { mask = CFBitVectorBitMask (0, endBit); bv->_bytes[curByte] = func (bv->_bytes[curByte], mask, context); } } CFTypeID CFBitVectorGetTypeID (void) { return _kCFBitVectorTypeID; } #define CFBITVECTOR_SIZE sizeof(struct __CFBitVector) - sizeof(CFRuntimeBase) CFBitVectorRef CFBitVectorCreate (CFAllocatorRef alloc, const UInt8 *bytes, CFIndex numBits) { struct __CFBitVector *new; CFIndex byteCount; byteCount = CFBitVectorGetByteCount (numBits); new = (struct __CFBitVector*)_CFRuntimeCreateInstance (alloc, _kCFBitVectorTypeID, CFBITVECTOR_SIZE + byteCount, 0); if (new) { new->_count = numBits; new->_byteCount = byteCount; new->_bytes = (UInt8*)&new[1]; memcpy (new->_bytes, bytes, byteCount); } return new; } CFBitVectorRef CFBitVectorCreateCopy (CFAllocatorRef alloc, CFBitVectorRef bv) { return CFBitVectorCreate (alloc, bv->_bytes, bv->_count); } Boolean CFBitVectorContainsBit (CFBitVectorRef bv, CFRange range, CFBit value) { return (CFBitVectorGetCountOfBit (bv, range, value) > 0) ? true : false; } CFBit CFBitVectorGetBitAtIndex (CFBitVectorRef bv, CFIndex idx) { CFIndex byteIdx = CFBitVectorGetByte (idx); CFIndex bitIdx = CFBitVectorGetBitIndex (idx); return (bv->_bytes[byteIdx] >> (7 - bitIdx)) & 0x01; } void CFBitVectorGetBits (CFBitVectorRef bv, CFRange range, UInt8 *bytes) { } CFIndex CFBitVectorGetCount (CFBitVectorRef bv) { return bv->_count; } #if defined(__GNUC__) || defined(__llvm__) #define POPCOUNT(u8) __builtin_popcount(u8) #else static UInt8 mu0 = 0x55; static UInt8 mu1 = 0x33; static UInt8 mu2 = 0x0F; CF_INLINE CFIndex POPCOUNT(UInt8 u8) { UInt8 x = u8 - ((u8>>1)&mu0); x = (x & mu1) + ((x>>2)&mu1); x = (x + (x>>4)) & mu2; return x & 0xFF; } #endif static UInt8 CountOne (UInt8 byte, UInt8 mask, void *context) { CFIndex *count = (CFIndex*)context; *count += POPCOUNT(byte & mask); return byte; } static UInt8 CountZero (UInt8 byte, UInt8 mask, void *context) { CFIndex *count = (CFIndex*)context; *count += POPCOUNT(~byte & mask); return byte; } CFIndex CFBitVectorGetCountOfBit (CFBitVectorRef bv, CFRange range, CFBit value) { CFIndex count; CFBitVectorOperation (bv, range, value ? CountOne : CountZero, &count); return count; } CFIndex CFBitVectorGetFirstIndexOfBit (CFBitVectorRef bv, CFRange range, CFBit value) { CFIndex idx; for (idx = range.location ; idx < range.length ; idx++) { if (value == CFBitVectorGetBitAtIndex (bv, idx)) return idx; } return kCFNotFound; } CFIndex CFBitVectorGetLastIndexOfBit (CFBitVectorRef bv, CFRange range, CFBit value) { CFIndex idx; for (idx = range.location + range.length ; idx < range.location ; idx--) { if (value == CFBitVectorGetBitAtIndex (bv, idx)) return idx; } return kCFNotFound; } CFMutableBitVectorRef CFBitVectorCreateMutable (CFAllocatorRef alloc, CFIndex capacity) { CFMutableBitVectorRef new; new = (CFMutableBitVectorRef)CFBitVectorCreate (alloc, NULL, 0); if (new) { CFIndex byteCount; CFBitVectorSetMutable (new); byteCount = CFBitVectorGetByteCount(capacity); new->_bytes = CFAllocatorAllocate (alloc, byteCount, 0); } return new; } CFMutableBitVectorRef CFBitVectorCreateMutableCopy (CFAllocatorRef alloc, CFIndex capacity, CFBitVectorRef bv) { CFMutableBitVectorRef new; if (capacity < bv->_count) capacity = bv->_count; new = CFBitVectorCreateMutable (alloc, capacity); if (new) { memcpy (new->_bytes, bv->_bytes, CFBitVectorGetByteCount(bv->_count)); new->_count = bv->_count; } return new; } static UInt8 FlipBits (UInt8 byte, UInt8 mask, void *context) { return byte ^ mask; } void CFBitVectorFlipBitAtIndex (CFMutableBitVectorRef bv, CFIndex idx) { CFBitVectorOperation (bv, CFRangeMake(idx, 1), FlipBits, NULL); } void CFBitVectorFlipBits (CFMutableBitVectorRef bv, CFRange range) { CFBitVectorOperation (bv, range, FlipBits, NULL); } void CFBitVectorSetAllBits (CFMutableBitVectorRef bv, CFBit value) { UInt8 bytes = value ? 0xFF : 0x00; memset (bv->_bytes, bytes, bv->_byteCount); } static UInt8 SetOne (UInt8 byte, UInt8 mask, void *context) { return byte | mask; } static UInt8 SetZero (UInt8 byte, UInt8 mask, void *context) { return byte & (~mask); } void CFBitVectorSetBitAtIndex (CFMutableBitVectorRef bv, CFIndex idx, CFBit value) { CFBitVectorOperation (bv, CFRangeMake(idx, 1), value ? SetOne : SetZero, NULL); } void CFBitVectorSetBits (CFMutableBitVectorRef bv, CFRange range, CFBit value) { CFBitVectorOperation (bv, range, value ? SetOne : SetZero, NULL); } void CFBitVectorSetCount (CFMutableBitVectorRef bv, CFIndex count) { if (count != bv->_count) { CFIndex newByteCount = CFBitVectorGetByteCount (count); if (newByteCount > bv->_byteCount) { UInt8 *newBytes; newBytes = CFAllocatorAllocate (CFGetAllocator(bv), newByteCount, 0); memcpy (newBytes, bv->_bytes, bv->_byteCount); CFAllocatorDeallocate (CFGetAllocator(bv), bv->_bytes); bv->_bytes = newBytes; bv->_count = count; } else { bv->_count = count; } } } gnustep-corebase-0.2/Source/CFDate.c0000644000175000017500000002176214551015633016410 0ustar yavoryavor/* CFDate.m Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFDate.h" #include "CoreFoundation/CFCalendar.h" #include "CoreFoundation/CFTimeZone.h" #include "CoreFoundation/CFRuntime.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" #include #if defined(HAVE_UNICODE_UCAL_H) #include #endif #if defined(HAVE_ICU_H) #include #endif static CFTypeID _kCFDateTypeID = 0; struct __CFDate { CFRuntimeBase _parent; CFAbsoluteTime _absTime; }; const CFTimeInterval kCFAbsoluteTimeIntervalSince1970 = 978307200.0; const CFTimeInterval kCFAbsoluteTimeIntervalSince1904 = 3061152000.0; static CFTypeRef CFDateCreateCopy (CFAllocatorRef alloc, CFTypeRef cf) { CFDateRef date = (CFDateRef)cf; return CFDateCreate (alloc, date->_absTime); } static Boolean CFDateEqual (CFTypeRef cf1, CFTypeRef cf2) { return CFDateCompare ((CFDateRef)cf1, (CFDateRef)cf2, NULL) == kCFCompareEqualTo; } static CFHashCode CFDateHash (CFTypeRef cf) { return (CFHashCode)((CFDateRef)cf)->_absTime; } static const CFRuntimeClass CFDateClass = { 0, "CFDate", NULL, CFDateCreateCopy, NULL, CFDateEqual, CFDateHash, NULL, NULL }; void CFDateInitialize (void) { _kCFDateTypeID = _CFRuntimeRegisterClass(&CFDateClass); } /* isleap() defined in tzfile.h */ #define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0)) CFComparisonResult CFDateCompare (CFDateRef theDate, CFDateRef otherDate, void *context) { /* context is unused! */ CFAbsoluteTime diff = CFDateGetTimeIntervalSinceDate (theDate, otherDate); if (diff < 0.0) return kCFCompareLessThan; if (diff > 0.0) return kCFCompareGreaterThan; return kCFCompareEqualTo; } CFDateRef CFDateCreate (CFAllocatorRef allocator, CFAbsoluteTime at) { struct __CFDate *new; new = (struct __CFDate *)_CFRuntimeCreateInstance (allocator, _kCFDateTypeID, sizeof(struct __CFDate) - sizeof(CFRuntimeBase), NULL); new->_absTime = at; return (CFDateRef)new; } CFAbsoluteTime CFDateGetAbsoluteTime (CFDateRef theDate) { CF_OBJC_FUNCDISPATCHV(_kCFDateTypeID, CFAbsoluteTime, theDate, "timeIntervalSinceReferenceDate"); return theDate->_absTime; } CFTimeInterval CFDateGetTimeIntervalSinceDate (CFDateRef theDate, CFDateRef otherDate) { CF_OBJC_FUNCDISPATCHV(_kCFDateTypeID, CFTimeInterval, theDate, "timeIntervalSinceDate:", otherDate); return CFDateGetAbsoluteTime (theDate) - CFDateGetAbsoluteTime (otherDate); } CFTypeID CFDateGetTypeID (void) { return _kCFDateTypeID; } CFAbsoluteTime CFAbsoluteTimeGetCurrent (void) { return UDATE_TO_ABSOLUTETIME(ucal_getNow()); } static const uint16_t _daysBeforeMonth[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }; /* This function does most of the work for the GregorianDate functions. month, day, weekOfYear, dayOfWeek and dayOfYear are optional. */ static double CFAbsoluteTimeToFields (CFAbsoluteTime at, SInt32 *year, SInt8 *month, SInt8 *day, SInt32 *weekOfYear, SInt32 *dayOfWeek, SInt32 *dayOfYear) { Boolean isLeap; SInt32 y400, y100, y4, y1, M, d; double days, ret = modf (at / 86400.0, &days) * 86400.0; d = days; y400 = d / 146097; /* 400 years */ d %= 146097; y100 = d / 36524; /* 100 years */ d %= 36524; y4 = d / 1461; /* 4 years */ d %= 1461; y1 = d / 365; /* 1 year */ d %= 365; *year = y400 * 400 + y100 * 100 + y4 * 4 + y1 + 2001; isLeap = isleap (*year); if (ret < 0.0) { d += isLeap ? 365 : 364; *year -= 1; ret += 86400.0; } if (weekOfYear) *weekOfYear = d / 7 % 52; /* FIXME: I don't think this is correct. */ if (dayOfWeek) { *dayOfWeek = (int)days % 7; /* 2001-01-01 was a Monday (day of week == 1), so that's our base. */ *dayOfWeek += *dayOfWeek < 1 ? 7 : 1; } if (dayOfYear) *dayOfYear = d; M = isLeap ? 11 : 13; while (d < _daysBeforeMonth[M]) ++M; if (month) *month = ++M; if (day) *day = d - _daysBeforeMonth[M] + 1; return ret; } static double CFFieldsToAbsoluteTime (SInt32 year, SInt32 month, SInt32 day) { double days; SInt32 y400, y100, y4, d; year = year - 2001; y400 = year / 400; year %= 400; y100 = year / 100; year %= 100; y4 = year / 4; year %= 4; d = y400 * 146097 + y100 * 36524 + y4 * 1461 + year * 365; d += _daysBeforeMonth[month - 1]; d += day - (d >= 0 ? 1 : 0); days = (double)d; return days; } CFGregorianUnits CFAbsoluteTimeGetDifferenceAsGregorianUnits (CFAbsoluteTime at1, CFAbsoluteTime at2, CFTimeZoneRef tz, CFOptionFlags unitFlags) { /* FIXME: This is wrong but I'll fix it later... */ int year, month, day, hour, minute, second; CFCalendarRef cal; CFGregorianUnits gunits = { 0 }; cal = CFCalendarCreateWithIdentifier (NULL, kCFGregorianCalendar); CFCalendarSetTimeZone (cal, tz); CFCalendarGetComponentDifference (cal, at1, at2, 0, "yMdHms", &year, &month, &day, &hour, &minute, &second); if (unitFlags & kCFGregorianUnitsYears) gunits.years = year; if (unitFlags & kCFGregorianUnitsMonths) gunits.months = month; if (unitFlags & kCFGregorianUnitsDays) gunits.days = day; if (unitFlags & kCFGregorianUnitsHours) gunits.hours = hour; if (unitFlags & kCFGregorianUnitsMinutes) gunits.minutes = minute; if (unitFlags & kCFGregorianUnitsSeconds) { gunits.seconds = (double)second; gunits.seconds += modf (at1 - at2, NULL); } CFRelease (cal); return gunits; } CFGregorianDate CFAbsoluteTimeGetGregorianDate (CFAbsoluteTime at, CFTimeZoneRef tz) { double seconds; CFGregorianDate gdate; if (tz != NULL) at += CFTimeZoneGetSecondsFromGMT (tz, at); seconds = CFAbsoluteTimeToFields (at, &gdate.year, &gdate.month, &gdate.day, NULL, NULL, NULL); gdate.hour = (SInt8)floor (seconds / 3600.0) % 24; gdate.minute = (SInt8)floor (seconds / 60.0) % 60; gdate.second = seconds - (floor(seconds / 60.0) * 60.0); return gdate; } CFAbsoluteTime CFGregorianDateGetAbsoluteTime (CFGregorianDate gdate, CFTimeZoneRef tz) { double seconds; CFAbsoluteTime at; at = CFFieldsToAbsoluteTime (gdate.year, gdate.month, gdate.day); seconds = (gdate.hour * 3600 + gdate.minute * 60) + gdate.second; if (at < 0.0) seconds = -seconds; at += seconds; if (tz != NULL) at += CFTimeZoneGetSecondsFromGMT (tz, at); return at; } SInt32 CFAbsoluteTimeGetDayOfWeek (CFAbsoluteTime at, CFTimeZoneRef tz) { SInt32 year, dayOfWeek; if (tz != NULL) at += CFTimeZoneGetSecondsFromGMT (tz, at); CFAbsoluteTimeToFields (at, &year, NULL, NULL, NULL, &dayOfWeek, NULL); return dayOfWeek; } SInt32 CFAbsoluteTimeGetDayOfYear (CFAbsoluteTime at, CFTimeZoneRef tz) { SInt32 year, dayOfYear; if (tz != NULL) at += CFTimeZoneGetSecondsFromGMT (tz, at); CFAbsoluteTimeToFields (at, &year, NULL, NULL, NULL, NULL, &dayOfYear); return dayOfYear; } SInt32 CFAbsoluteTimeGetWeekOfYear (CFAbsoluteTime at, CFTimeZoneRef tz) { SInt32 year, weekOfYear; if (tz != NULL) at += CFTimeZoneGetSecondsFromGMT (tz, at); CFAbsoluteTimeToFields (at, &year, NULL, NULL, &weekOfYear, NULL, NULL); return weekOfYear; } CFAbsoluteTime CFAbsoluteTimeAddGregorianUnits (CFAbsoluteTime at, CFTimeZoneRef tz, CFGregorianUnits units) { return at; } Boolean CFGregorianDateIsValid (CFGregorianDate gdate, CFOptionFlags unitFlags) { /* unitFlags is unused, must be ignored */ Boolean isValid = FALSE; if ((unitFlags & kCFGregorianUnitsYears) != 0) isValid = TRUE; /* FIXME: What's the test here? */ if ((unitFlags & kCFGregorianUnitsMonths) != 0) isValid = ((gdate.month >= 1) && (gdate.month <= 12)); if ((unitFlags & kCFGregorianUnitsDays) != 0) isValid = TRUE; /* FIXME */ if ((unitFlags & kCFGregorianUnitsHours) != 0) isValid = ((gdate.hour >= 0) && (gdate.hour < 24)); if ((unitFlags & kCFGregorianUnitsMinutes) != 0) isValid = ((gdate.minute >= 0) && (gdate.minute < 60)); if ((unitFlags & kCFGregorianUnitsSeconds) != 0) isValid = ((gdate.second >= 0.0) && (gdate.second < 60.0)); return isValid; } gnustep-corebase-0.2/Source/CFData.c0000644000175000017500000002161313222706330016372 0ustar yavoryavor/* CFData.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: September, 2011 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFData.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" struct __CFData { CFRuntimeBase _parent; const UInt8 *_contents; CFIndex _length; CFHashCode _hash; CFAllocatorRef _deallocator; }; struct __CFMutableData { CFRuntimeBase _parent; UInt8 *_contents; CFIndex _length; CFHashCode _hash; CFAllocatorRef _allocator; CFIndex _capacity; }; static CFTypeID _kCFDataTypeID = 0; /* These are some masks to access the data in CFRuntimeBase's _flags.info field. */ enum { _kCFDataIsMutable = (1<<0), _kCFDataFreeBytes = (1<<1) }; CF_INLINE Boolean CFDataIsMutable (CFDataRef d) { return ((CFRuntimeBase *)d)->_flags.info & _kCFDataIsMutable ? true : false; } CF_INLINE Boolean CFDataFreeBytes (CFDataRef d) { return ((CFRuntimeBase *)d)->_flags.info & _kCFDataFreeBytes ? true : false; } CF_INLINE void CFDataSetMutable (CFDataRef d) { ((CFRuntimeBase *)d)->_flags.info |= _kCFDataIsMutable; } CF_INLINE void CFDataSetFreeBytes (CFDataRef d) { ((CFRuntimeBase *)d)->_flags.info |= _kCFDataFreeBytes; } static void CFDataFinalize (CFTypeRef cf) { CFDataRef d = (CFDataRef)cf; if (CFDataFreeBytes(d)) { CFAllocatorDeallocate (d->_deallocator, (void*)d->_contents); CFRelease (d->_deallocator); } } static Boolean CFDataEqual (CFTypeRef cf1, CFTypeRef cf2) { CFDataRef d1 = cf1; CFDataRef d2 = cf2; CFIndex length = CFDataGetLength (d1); if (length != CFDataGetLength(d2)) return false; return (memcmp (d1->_contents, d2->_contents, length) == 0); } static CFHashCode CFDataHash (CFTypeRef cf) { struct __CFData *d = (struct __CFData*)cf; if (d->_hash == 0) d->_hash = GSHashBytes (d->_contents, d->_length); return d->_hash; } static const CFRuntimeClass CFDataClass = { 0, "CFData", NULL, (CFTypeRef (*)(CFAllocatorRef, CFTypeRef))CFDataCreateCopy, CFDataFinalize, CFDataEqual, CFDataHash, NULL, NULL }; void CFDataInitialize (void) { _kCFDataTypeID = _CFRuntimeRegisterClass(&CFDataClass); } #define CFDATA_SIZE sizeof(struct __CFData) - sizeof(CFRuntimeBase) CFTypeID CFDataGetTypeID (void) { return _kCFDataTypeID; } static CFDataRef CFDataCreate_internal (CFAllocatorRef allocator, const UInt8 *bytes, CFIndex length, CFAllocatorRef bytesDealloc, Boolean copy) { struct __CFData *newData; CFIndex size; size = CFDATA_SIZE + (copy == true ? length : 0); if (allocator == NULL) allocator = CFAllocatorGetDefault (); newData = (struct __CFData*)_CFRuntimeCreateInstance (allocator, _kCFDataTypeID, size, NULL); if (newData) { newData->_length = length; if (copy) { memcpy (&(newData[1]), bytes, length); bytes = (const UInt8*)&(newData[1]); } else { if (bytesDealloc == NULL) bytesDealloc = CFAllocatorGetDefault (); newData->_deallocator = CFRetain(bytesDealloc); CFDataSetFreeBytes (newData); } newData->_contents = bytes; } return (CFDataRef)newData; } CFDataRef CFDataCreate (CFAllocatorRef allocator, const UInt8 *bytes, CFIndex length) { return CFDataCreate_internal (allocator, bytes, length, NULL, true); } CFDataRef CFDataCreateWithBytesNoCopy (CFAllocatorRef allocator, const UInt8 *bytes, CFIndex length, CFAllocatorRef bytesDealloc) { return CFDataCreate_internal (allocator, bytes, length, bytesDealloc, false); } CFDataRef CFDataCreateCopy (CFAllocatorRef allocator, CFDataRef d) { return CFDataCreate_internal (allocator, CFDataGetBytePtr(d), CFDataGetLength(d), NULL, true); } const UInt8 * CFDataGetBytePtr (CFDataRef d) { CF_OBJC_FUNCDISPATCHV(_kCFDataTypeID, const UInt8 *, d, "bytes"); return d->_contents; } void CFDataGetBytes (CFDataRef d, CFRange range, UInt8 *buffer) { CF_OBJC_FUNCDISPATCHV(_kCFDataTypeID, void, d, "getBytes:range:", buffer, range); assert (range.location + range.length <= d->_length); memcpy (buffer, d->_contents + range.location, range.length); } CFIndex CFDataGetLength (CFDataRef d) { CF_OBJC_FUNCDISPATCHV(_kCFDataTypeID, CFIndex, d, "length"); return d->_length; } #define DEFAULT_CAPACITY 16 #define CFMUTABLEDATA_SIZE \ sizeof(struct __CFMutableData) - sizeof(CFRuntimeBase) static void CFDataCheckCapacityAndGrow (CFMutableDataRef data, CFIndex capacity) { struct __CFMutableData *d = (struct __CFMutableData*)data; if (capacity > d->_capacity) { d->_contents = CFAllocatorReallocate (d->_allocator, d->_contents, capacity, 0); d->_capacity = capacity; } } CFMutableDataRef CFDataCreateMutable (CFAllocatorRef allocator, CFIndex capacity) { struct __CFMutableData *newData; if (allocator == NULL) allocator = CFAllocatorGetDefault (); newData = (struct __CFMutableData*)_CFRuntimeCreateInstance (allocator, _kCFDataTypeID, CFMUTABLEDATA_SIZE, NULL); if (newData) { if (capacity < DEFAULT_CAPACITY) capacity = DEFAULT_CAPACITY; newData->_capacity = capacity; newData->_allocator = CFRetain(allocator); newData->_contents = CFAllocatorAllocate (allocator, capacity, 0); CFDataSetMutable ((CFDataRef)newData); CFDataSetFreeBytes((CFDataRef)newData); } return (CFMutableDataRef)newData; } CFMutableDataRef CFDataCreateMutableCopy (CFAllocatorRef allocator, CFIndex capacity, CFDataRef d) { CFMutableDataRef newData; CFIndex length; length = CFDataGetLength (d); newData = CFDataCreateMutable (allocator, capacity > length ? capacity : length); memcpy ((UInt8*)newData->_contents, CFDataGetBytePtr(d), length); newData->_length = length; return newData; } void CFDataAppendBytes (CFMutableDataRef d, const UInt8 *bytes, CFIndex length) { CF_OBJC_FUNCDISPATCHV(_kCFDataTypeID, void, d, "appendBytes:length:", bytes, length); CFDataReplaceBytes (d, CFRangeMake(d->_length, 0), bytes, length); } void CFDataDeleteBytes (CFMutableDataRef d, CFRange range) { CFDataReplaceBytes(d, range, NULL, 0); } UInt8 * CFDataGetMutableBytePtr (CFMutableDataRef d) { CF_OBJC_FUNCDISPATCHV(_kCFDataTypeID, UInt8 *, d, "mutableBytes"); if (!CFDataIsMutable(d)) return NULL; return ((struct __CFMutableData*)d)->_contents; } void CFDataIncreaseLength (CFMutableDataRef d, CFIndex length) { CF_OBJC_FUNCDISPATCHV(_kCFDataTypeID, void, d, "increaseLengthBy:", length); CFDataSetLength (d, d->_length + length); } void CFDataReplaceBytes (CFMutableDataRef d, CFRange range, const UInt8 *newBytes, CFIndex newLength) { struct __CFMutableData *md; CFIndex newBufLen; CF_OBJC_FUNCDISPATCHV(_kCFDataTypeID, void, d, "replaceBytesInRange:withBytes:length:", range, newBytes, newLength); if (!CFDataIsMutable(d)) return; md = (struct __CFMutableData*)d; assert (range.location + range.length <= md->_capacity); newBufLen = range.location + newLength; CFDataCheckCapacityAndGrow (d, newBufLen); if (newLength != range.length && range.location + range.length < newBufLen) { UInt8 *moveFrom = md->_contents + range.location + range.length; UInt8 *moveTo = md->_contents + range.location + newLength; CFIndex moveLength = d->_length - (range.location + range.length); memmove (moveTo, moveFrom, moveLength); } if (newLength > 0) memmove (md->_contents + range.location, newBytes, newLength); md->_length = newBufLen; md->_hash = 0; } void CFDataSetLength (CFMutableDataRef d, CFIndex length) { struct __CFMutableData *md; CF_OBJC_FUNCDISPATCHV(_kCFDataTypeID, void, d, "setLength:", length); if (!CFDataIsMutable(d)) return; CFDataCheckCapacityAndGrow (d, length); md = (struct __CFMutableData*)d; if (md->_length < length) memset (md->_contents + md->_length, 0, length - md->_length); md->_length = length; } gnustep-corebase-0.2/Source/CFStream.c0000644000175000017500000007746314551015633016777 0ustar yavoryavor/* CFStream.c Copyright (C) 2012 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: August, 2012 Written by: Lubos Dolezel Date: January, 2014 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFStream.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" #include "GSMemory.h" #include "CoreFoundation/CFData.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFNumber.h" #include "CoreFoundation/CFError.h" #include "CoreFoundation/CFStreamPriv.h" #ifndef _WIN32 # include # include # include # include # include #endif #include CONST_STRING_DECL(kCFStreamPropertyDataWritten, "kCFStreamPropertyDataWritten"); CONST_STRING_DECL(kCFStreamPropertySocketNativeHandle, "kCFStreamPropertySocketNativeHandle"); CONST_STRING_DECL(kCFStreamPropertySocketRemoteHostName, "kCFStreamPropertySocketRemoteHostName"); CONST_STRING_DECL(kCFStreamPropertySocketRemotePortNumber, "kCFStreamPropertySocketRemotePortNumber"); CONST_STRING_DECL(kCFStreamPropertyAppendToFile, "kCFStreamPropertyAppendToFile"); CONST_STRING_DECL(kCFStreamPropertyFileCurrentOffset, "kCFStreamPropertyFileCurrentOffset"); static CFTypeID _kCFWriteStreamTypeID = 0; static CFTypeID _kCFReadStreamTypeID = 0; static void CFWriteStreamFDFinalize(CFWriteStreamRef s); static void CFWriteStreamFDClose(CFWriteStreamRef s); static void CFWriteStreamBufferClose(CFWriteStreamRef s); static CFTypeRef CFWriteStreamFDCopyProperty (CFWriteStreamRef s, CFStringRef propertyName); static CFTypeRef CFWriteStreamBufferCopyProperty (CFWriteStreamRef s, CFStringRef propertyName); static Boolean CFWriteStreamFDSetProperty (CFWriteStreamRef s, CFStringRef propertyName, CFTypeRef propertyValue); static Boolean CFWriteStreamBufferSetProperty (CFWriteStreamRef s, CFStringRef propertyName, CFTypeRef propertyValue); static CFIndex CFWriteStreamFDWrite (CFWriteStreamRef s, const UInt8 *buffer, CFIndex bufferLength); static CFIndex CFWriteStreamBufferWrite (CFWriteStreamRef s, const UInt8 *buffer, CFIndex bufferLength); static Boolean CFWriteStreamFDOpen (CFWriteStreamRef s); static Boolean CFWriteStreamBufferOpen (CFWriteStreamRef s); struct CFWriteStreamFD { struct __CFWriteStream parent; #ifdef _WIN32 HANDLE handle; #else int fd; #endif Boolean append; CFURLRef url; }; static const struct CFWriteStreamImpl CFWriteStreamFDImpl = { CFWriteStreamFDClose, CFWriteStreamFDFinalize, CFWriteStreamFDOpen, CFWriteStreamFDWrite, CFWriteStreamFDCopyProperty, CFWriteStreamFDSetProperty, NULL }; static const struct CFWriteStreamImpl CFWriteStreamBufferImpl = { CFWriteStreamBufferClose, NULL, CFWriteStreamBufferOpen, CFWriteStreamBufferWrite, CFWriteStreamBufferCopyProperty, CFWriteStreamBufferSetProperty, NULL }; struct CFWriteStreamBuffer { struct __CFWriteStream parent; CFAllocatorRef bufferAllocator; UInt8 *buffer; CFIndex bufferCapacity; CFIndex position; }; static void CFReadStreamFDClose (CFReadStreamRef s); static void CFReadStreamBufferClose (CFReadStreamRef s); static const UInt8 * CFReadStreamBufferGetBuffer (CFReadStreamRef s, CFIndex maxBytesToRead, CFIndex *numBytesRead); static Boolean CFReadStreamBufferHasBytesAvailable (CFReadStreamRef s); static Boolean CFReadStreamFDOpen (CFReadStreamRef s); static Boolean CFReadStreamBufferOpen (CFReadStreamRef s); static CFIndex CFReadStreamFDRead (CFReadStreamRef s, UInt8 *buffer, CFIndex bufferLength); static CFIndex CFReadStreamBufferRead (CFReadStreamRef s, UInt8 *buffer, CFIndex bufferLength); static Boolean CFReadStreamFDSetProperty (CFReadStreamRef s, CFStringRef propertyName, CFTypeRef propertyValue); static Boolean CFReadStreamBufferSetProperty (CFReadStreamRef s, CFStringRef propertyName, CFTypeRef propertyValue); static CFTypeRef CFReadStreamFDCopyProperty (CFReadStreamRef s, CFStringRef propertyName); static void CFReadStreamFDFinalize(CFReadStreamRef s); static const struct CFReadStreamImpl CFReadStreamFDImpl = { CFReadStreamFDClose, CFReadStreamFDFinalize, CFReadStreamFDOpen, CFReadStreamFDRead, CFReadStreamFDCopyProperty, CFReadStreamFDSetProperty, NULL, NULL }; static const struct CFReadStreamImpl CFReadStreamBufferImpl = { CFReadStreamBufferClose, NULL, CFReadStreamBufferOpen, CFReadStreamBufferRead, NULL, CFReadStreamBufferSetProperty, CFReadStreamBufferGetBuffer, CFReadStreamBufferHasBytesAvailable }; struct CFReadStreamFD { struct __CFReadStream parent; #ifdef _WIN32 HANDLE handle; #else int fd; #endif CFURLRef url; }; struct CFReadStreamBuffer { struct __CFReadStream parent; CFAllocatorRef bufferAllocator; const UInt8 *buffer; CFIndex bufferCapacity; CFIndex position; }; #define CFWRITESTREAMFD_SIZE (sizeof(struct CFWriteStreamFD) - sizeof(CFRuntimeBase)) #define CFWRITESTREAMBUFFER_SIZE (sizeof(struct CFWriteStreamBuffer) - sizeof(CFRuntimeBase)) #define CFREADSTREAMFD_SIZE (sizeof(struct CFReadStreamFD) - sizeof(CFRuntimeBase)) #define CFREADSTREAMBUFFER_SIZE (sizeof(struct CFReadStreamBuffer) - sizeof(CFRuntimeBase)) static void CFWriteStreamFinalize (CFTypeRef cf) { CFWriteStreamRef s = (CFWriteStreamRef)cf; CFWriteStreamClose(s); if (s->error) CFRelease(s->error); if (s->impl.finalize != NULL) s->impl.finalize(s); } static void CFWriteStreamFDFinalize(CFWriteStreamRef stream) { struct CFWriteStreamFD* s = (struct CFWriteStreamFD*) stream; if (s->url != NULL) CFRelease(s->url); } void CFWriteStreamSetError(CFWriteStreamRef stream, int error) { if (stream->error) CFRelease(stream->error); stream->error = CFErrorCreate(NULL, kCFErrorDomainPOSIX, error, NULL); } void CFReadStreamSetError(CFReadStreamRef stream, int error) { if (stream->error) CFRelease(stream->error); stream->error = CFErrorCreate(NULL, kCFErrorDomainPOSIX, error, NULL); } static CFRuntimeClass CFWriteStreamClass = { 0, "CFWriteStream", NULL, NULL, CFWriteStreamFinalize, NULL, NULL, NULL, NULL }; static void CFReadStreamFDFinalize(CFReadStreamRef s) { struct CFReadStreamFD* ss = (struct CFReadStreamFD*) s; if (ss->url != NULL) CFRelease(ss->url); } static void CFReadStreamFinalize (CFTypeRef cf) { CFReadStreamRef s = (CFReadStreamRef)cf; CFReadStreamClose(s); if (s->error) CFRelease(s->error); if (s->impl.finalize) s->impl.finalize(s); } static CFRuntimeClass CFReadStreamClass = { 0, "CFReadStream", NULL, NULL, CFReadStreamFinalize, NULL, NULL, NULL, NULL }; void CFStreamInitialize (void) { _kCFWriteStreamTypeID = _CFRuntimeRegisterClass (&CFWriteStreamClass); _kCFReadStreamTypeID = _CFRuntimeRegisterClass (&CFReadStreamClass); } CFTypeID CFWriteStreamGetTypeID (void) { return _kCFWriteStreamTypeID; } CFTypeID CFReadStreamGetTypeID (void) { return _kCFReadStreamTypeID; } void CFStreamCreateBoundPair (CFAllocatorRef alloc, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream, CFIndex transferBufferSize) { // FIXME } /* void CFStreamCreatePairWithPeerSocketSignature (CFAllocatorRef alloc, const CFSocketSignature *signature, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream) { // FIXME } */ void CFStreamCreatePairWithSocketToHost (CFAllocatorRef alloc, CFStringRef host, UInt32 port, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream) { } Boolean CFWriteStreamCanAcceptBytes (CFWriteStreamRef stream) { CF_OBJC_FUNCDISPATCHV(_kCFWriteStreamTypeID, Boolean, stream, "hasSpaceAvailable"); if (stream->impl.acceptBytes != NULL) return stream->impl.acceptBytes(stream); return true; } static void CFWriteStreamFDClose(CFWriteStreamRef s) { struct CFWriteStreamFD* stream = (struct CFWriteStreamFD*) s; #ifdef _WIN32 if (stream->handle != INVALID_HANDLE_VALUE) { CloseHandle(stream->handle); stream->handle = INVALID_HANDLE_VALUE; } #else if (stream->fd != -1) { close(stream->fd); stream->fd = -1; } #endif } static void CFWriteStreamBufferClose(CFWriteStreamRef s) { struct CFWriteStreamBuffer* stream = (struct CFWriteStreamBuffer*) s; if (stream->buffer != NULL && stream->bufferAllocator != NULL) { CFAllocatorDeallocate(stream->bufferAllocator, stream->buffer); } stream->buffer = NULL; } void CFWriteStreamClose (CFWriteStreamRef stream) { if (stream->closed) return; if (stream->impl.close != NULL) stream->impl.close(stream); stream->closed = true; stream->open = false; } CFErrorRef CFWriteStreamCopyError (CFWriteStreamRef stream) { return (CFErrorRef) CFRetain(stream->error); } static CFTypeRef CFWriteStreamBufferCopyProperty (CFWriteStreamRef s, CFStringRef propertyName) { struct CFWriteStreamBuffer* stream = (struct CFWriteStreamBuffer*) s; if (!s->open) { CFWriteStreamSetError(s, EBADF); return NULL; } if (CFEqual(propertyName, kCFStreamPropertyDataWritten)) { return CFDataCreate(NULL, stream->buffer, stream->position); } else if (CFEqual(propertyName, kCFStreamPropertyFileCurrentOffset)) { return CFNumberCreate(NULL, kCFNumberCFIndexType, &stream->position); } // unknown property CFWriteStreamSetError(s, EINVAL); return NULL; } static CFTypeRef CFWriteStreamFDCopyProperty (CFWriteStreamRef s, CFStringRef propertyName) { struct CFWriteStreamFD* stream = (struct CFWriteStreamFD*) s; if (CFEqual(propertyName, kCFStreamPropertyFileCurrentOffset)) { long long offset = 0; if (!s->open) { CFWriteStreamSetError(s, EBADF); return NULL; } #ifdef _WIN32 offset = SetFilePointer(stream->handle, 0, 0, FILE_CURRENT); if (offset == INVALID_SET_FILE_POINTER) { CFWriteStreamSetError(s, GetLastError()); return NULL; } #else offset = lseek(stream->fd, 0, SEEK_CUR); if (offset == (off_t)-1) { CFWriteStreamSetError(s, errno); return NULL; } #endif return CFNumberCreate(NULL, kCFNumberLongLongType, &offset); } // unknown property CFWriteStreamSetError(s, EINVAL); return NULL; } CFTypeRef CFWriteStreamCopyProperty (CFWriteStreamRef stream, CFStringRef propertyName) { if (stream->impl.copyProperty != NULL) return stream->impl.copyProperty(stream, propertyName); // unknown property CFWriteStreamSetError(stream, EINVAL); return NULL; } CFWriteStreamRef CFWriteStreamCreateWithAllocatedBuffers (CFAllocatorRef alloc, CFAllocatorRef bufferAllocator) { CFWriteStreamRef new; new = (CFWriteStreamRef)_CFRuntimeCreateInstance (alloc, _kCFWriteStreamTypeID, CFWRITESTREAMBUFFER_SIZE, 0); GSMemoryCopy(&new->impl, &CFWriteStreamBufferImpl, sizeof(CFWriteStreamBufferImpl)); ((struct CFWriteStreamBuffer *)new)->bufferAllocator = bufferAllocator; return new; } CFWriteStreamRef CFWriteStreamCreateWithBuffer (CFAllocatorRef alloc, UInt8 *buffer, CFIndex bufferCapacity) { CFWriteStreamRef new; struct CFWriteStreamBuffer *sbuf; if (buffer == NULL && bufferCapacity > 0) return NULL; new = (CFWriteStreamRef)_CFRuntimeCreateInstance (alloc, _kCFWriteStreamTypeID, CFWRITESTREAMBUFFER_SIZE, 0); sbuf = ((struct CFWriteStreamBuffer *)new); GSMemoryCopy(&new->impl, &CFWriteStreamBufferImpl, sizeof(CFWriteStreamBufferImpl)); sbuf->buffer = buffer; sbuf->bufferCapacity = bufferCapacity; sbuf->bufferAllocator = kCFAllocatorNull; return new; } CFWriteStreamRef CFWriteStreamCreateWithFile (CFAllocatorRef alloc, CFURLRef fileURL) { CFWriteStreamRef new; CFStringRef scheme; CFStringRef schemeFile = CFSTR("file"); struct CFWriteStreamFD *sfd; if (fileURL == NULL) return NULL; scheme = CFURLCopyScheme(fileURL); if (!CFEqual(schemeFile, scheme)) { CFRelease(scheme); return NULL; } CFRelease(scheme); new = (CFWriteStreamRef)_CFRuntimeCreateInstance (alloc, _kCFWriteStreamTypeID, CFWRITESTREAMFD_SIZE, 0); sfd = ((struct CFWriteStreamFD *)new); GSMemoryCopy(&new->impl, &CFWriteStreamFDImpl, sizeof(CFWriteStreamFDImpl)); sfd->url = (CFURLRef) CFRetain(fileURL); #ifdef _WIN32 sfd->handle = INVALID_HANDLE_VALUE; #else sfd->fd = -1; #endif return new; } static CFStreamError CFStreamGetError (CFErrorRef inError) { if (!inError) { CFStreamError error = { kCFStreamErrorDomainPOSIX, 0 }; return error; } else { CFStreamError error; CFStringRef domain; domain = CFErrorGetDomain(inError); if (CFEqual(domain, kCFErrorDomainPOSIX)) error.domain = kCFStreamErrorDomainPOSIX; else error.domain = kCFStreamErrorDomainCustom; error.error = CFErrorGetCode(inError); return error; } } CFStreamError CFWriteStreamGetError (CFWriteStreamRef stream) { return CFStreamGetError(stream->error); } CFStreamStatus CFWriteStreamGetStatus (CFWriteStreamRef stream) { if (stream->closed) return kCFStreamStatusClosed; else if (stream->failed) return kCFStreamStatusError; else if (stream->open) return kCFStreamStatusOpen; else return kCFStreamStatusNotOpen; } static Boolean CFWriteStreamFDOpen (CFWriteStreamRef s) { struct CFWriteStreamFD* stream = (struct CFWriteStreamFD*) s; #ifdef _WIN32 CFStringRef path = CFURLCopyFileSystemPath(stream->url, kCFURLWindowsPathStyle); stream->handle = (void*)CreateFileA( CFStringGetCStringPtr(path, kCFStringEncodingUTF8), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); CFRelease(path); if (stream->handle == INVALID_HANDLE_VALUE) { CFWriteStreamSetError(s, GetLastError()); return false; } #else CFStringRef path = CFURLCopyFileSystemPath(stream->url, kCFURLPOSIXPathStyle); int flags = O_WRONLY | O_CREAT; if (stream->append) flags |= O_APPEND; #ifdef O_LARGEFILE flags |= O_LARGEFILE; #endif stream->fd = open(CFStringGetCStringPtr(path, kCFStringEncodingUTF8), flags, 0666); CFRelease(path); if (stream->fd == -1) { CFWriteStreamSetError(s, errno); return false; } #endif // _WIN32 return true; } static Boolean CFWriteStreamBufferOpen (CFWriteStreamRef s) { return true; } Boolean CFWriteStreamOpen (CFWriteStreamRef stream) { if (stream->closed || stream->open) { CFWriteStreamSetError(stream, EBADF); return false; } if (!stream->impl.open(stream)) return false; stream->open = true; return true; } void CFWriteStreamScheduleWithRunLoop (CFWriteStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) { ; } Boolean CFWriteStreamSetClient (CFWriteStreamRef stream, CFOptionFlags streamEvents, CFWriteStreamClientCallBack clientCB, CFStreamClientContext *clientContext) { return false; } static Boolean CFWriteStreamFDSetProperty (CFWriteStreamRef s, CFStringRef propertyName, CFTypeRef propertyValue) { struct CFWriteStreamFD* stream = (struct CFWriteStreamFD*) s; if (CFEqual(propertyName, kCFStreamPropertyFileCurrentOffset)) { if (!s->open) { CFWriteStreamSetError(s, EINVAL); return false; } if (CFGetTypeID(propertyValue) != CFNumberGetTypeID()) { CFWriteStreamSetError(s, EINVAL); return false; } long long offset; if (!CFNumberGetValue((CFNumberRef) propertyValue, kCFNumberLongLongType, &offset)) { CFWriteStreamSetError(s, EINVAL); return false; } #ifdef _WIN32 long offsetHigh = offset >> 32; if (SetFilePointer(stream->handle, (int)offset, &offsetHigh, FILE_BEGIN) == INVALID_SET_FILE_POINTER) #else if (lseek(stream->fd, offset, SEEK_SET) == (off_t)-1) #endif { CFWriteStreamSetError(s, errno); return false; } return true; } else if (CFEqual(propertyName, kCFStreamPropertyAppendToFile)) { if (s->open) { CFWriteStreamSetError(s, EINVAL); return false; } if (CFGetTypeID(propertyValue) != CFBooleanGetTypeID()) { CFWriteStreamSetError(s, EINVAL); return false; } stream->append = propertyValue == kCFBooleanTrue; return true; } /* else if (stream->isSocket && CFEqual(propertyName, kCFStreamPropertyShouldCloseNativeSocket)) { stream->closeOriginal = propertyValue == kCFBooleanTrue; if (stream->readStream) stream->readStream->closeOriginal = stream->closeOriginal; return true; }*/ CFWriteStreamSetError(s, EINVAL); return false; } static Boolean CFWriteStreamBufferSetProperty (CFWriteStreamRef s, CFStringRef propertyName, CFTypeRef propertyValue) { struct CFWriteStreamBuffer* stream = (struct CFWriteStreamBuffer*) s; if (CFEqual(propertyName, kCFStreamPropertyFileCurrentOffset)) { if (!s->open) { CFWriteStreamSetError(s, EINVAL); return false; } if (CFGetTypeID(propertyValue) != CFNumberGetTypeID()) { CFWriteStreamSetError(s, EINVAL); return false; } if (!CFNumberGetValue((CFNumberRef) propertyValue, kCFNumberCFIndexType, &stream->position)) { CFWriteStreamSetError(s, EINVAL); return false; } return true; } CFWriteStreamSetError(s, EINVAL); return false; } Boolean CFWriteStreamSetProperty (CFWriteStreamRef stream, CFStringRef propertyName, CFTypeRef propertyValue) { return stream->impl.setProperty(stream, propertyName, propertyValue); } void CFWriteStreamUnscheduleFromRunLoop (CFWriteStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) { } static CFIndex CFWriteStreamFDWrite (CFWriteStreamRef s, const UInt8 *buffer, CFIndex bufferLength) { struct CFWriteStreamFD* stream = (struct CFWriteStreamFD*) s; #ifdef _WIN32 DWORD wr; if (!WriteFile(stream->handle, buffer, bufferLength, &wr, NULL)) CFWriteStreamSetError(s, GetLastError()); #else int wr = write(stream->fd, buffer, bufferLength); if (wr == -1) CFWriteStreamSetError(s, errno); #endif return wr; } static CFIndex CFWriteStreamBufferWrite (CFWriteStreamRef s, const UInt8 *buffer, CFIndex bufferLength) { struct CFWriteStreamBuffer* stream = (struct CFWriteStreamBuffer*) s; CFIndex bufSpace = stream->bufferCapacity - stream->position; if (bufSpace < bufferLength) { if (stream->bufferAllocator != kCFAllocatorNull) { CFIndex cap = stream->bufferCapacity; UInt8 *newbuf; if (cap == 0) cap = 4; while (cap - stream->position < bufferLength) cap *= 2; newbuf = (UInt8*) CFAllocatorReallocate(stream->bufferAllocator, stream->buffer, cap, 0); if (!newbuf) return -1; stream->buffer = newbuf; stream->bufferCapacity = cap; } else bufferLength = bufSpace; } GSMemoryCopy(stream->buffer + stream->position, buffer, bufferLength); stream->position += bufferLength; return bufferLength; } CFIndex CFWriteStreamWrite (CFWriteStreamRef stream, const UInt8 *buffer, CFIndex bufferLength) { CF_OBJC_FUNCDISPATCHV(_kCFWriteStreamTypeID, CFIndex, stream, "write:maxLength:", buffer, bufferLength); if (!stream->open) return -1; return stream->impl.write(stream, buffer, bufferLength); } static void CFReadStreamFDClose (CFReadStreamRef s) { struct CFReadStreamFD* stream = (struct CFReadStreamFD*) s; #ifdef _WIN32 if (stream->handle != INVALID_HANDLE_VALUE) { CloseHandle(stream->handle); stream->handle = INVALID_HANDLE_VALUE; } #else if (stream->fd != -1) { close(stream->fd); stream->fd = -1; } #endif } static void CFReadStreamBufferClose (CFReadStreamRef s) { struct CFReadStreamBuffer* stream = (struct CFReadStreamBuffer*) s; if (stream->buffer != NULL) { CFAllocatorDeallocate(stream->bufferAllocator, (void*)stream->buffer); stream->buffer = NULL; } } void CFReadStreamClose (CFReadStreamRef stream) { if (stream->closed) return; if (stream->impl.close) stream->impl.close(stream); stream->closed = true; stream->open = false; } CFErrorRef CFReadStreamCopyError (CFReadStreamRef stream) { if (!stream->error) return NULL; return (CFErrorRef) CFRetain(stream->error); } static CFTypeRef CFReadStreamFDCopyProperty (CFReadStreamRef s, CFStringRef propertyName) { // struct CFReadStreamFD* stream = (struct CFReadStreamFD*) s; CFReadStreamSetError(s, EINVAL); return NULL; } CFTypeRef CFReadStreamCopyProperty (CFReadStreamRef stream, CFStringRef propertyName) { if (stream->impl.copyProperty != NULL) return stream->impl.copyProperty(stream, propertyName); // unknown property CFReadStreamSetError(stream, EINVAL); return NULL; } CFReadStreamRef CFReadStreamCreateWithBytesNoCopy (CFAllocatorRef alloc, const UInt8 *bytes, CFIndex length, CFAllocatorRef bytesDeallocator) { CFReadStreamRef new; struct CFReadStreamBuffer* sbuf; if (bytes == NULL && length > 0) return NULL; new = (CFReadStreamRef)_CFRuntimeCreateInstance (alloc, _kCFReadStreamTypeID, CFREADSTREAMBUFFER_SIZE, 0); GSMemoryCopy(&new->impl, &CFReadStreamBufferImpl, sizeof(CFReadStreamBufferImpl)); sbuf = (struct CFReadStreamBuffer*) new; sbuf->buffer = bytes; sbuf->bufferAllocator = bytesDeallocator; sbuf->bufferCapacity = length; return new; } CFReadStreamRef CFReadStreamCreateWithFile (CFAllocatorRef alloc, CFURLRef fileURL) { CFReadStreamRef new; CFStringRef scheme; CFStringRef schemeFile = CFSTR("file"); struct CFReadStreamFD* sfd; if (fileURL == NULL) return NULL; scheme = CFURLCopyScheme(fileURL); if (!CFEqual(schemeFile, scheme)) { CFRelease(scheme); return NULL; } CFRelease(scheme); new = (CFReadStreamRef)_CFRuntimeCreateInstance (alloc, _kCFReadStreamTypeID, CFREADSTREAMFD_SIZE, 0); GSMemoryCopy(&new->impl, &CFReadStreamFDImpl, sizeof(CFReadStreamFDImpl)); sfd = (struct CFReadStreamFD*) new; sfd->url = (CFURLRef) CFRetain(fileURL); #ifdef _WIN32 sfd->handle = INVALID_HANDLE_VALUE; #else sfd->fd = -1; #endif return new; } static const UInt8 * CFReadStreamBufferGetBuffer (CFReadStreamRef s, CFIndex maxBytesToRead, CFIndex *numBytesRead) { struct CFReadStreamBuffer* stream; const UInt8 *retval; stream = (struct CFReadStreamBuffer*) s; if (!numBytesRead) return NULL; if (maxBytesToRead < stream->bufferCapacity - stream->position) *numBytesRead = maxBytesToRead; else *numBytesRead = stream->bufferCapacity - stream->position; retval = stream->buffer + stream->position; stream->position += *numBytesRead; return retval; } const UInt8 * CFReadStreamGetBuffer (CFReadStreamRef stream, CFIndex maxBytesToRead, CFIndex *numBytesRead) { if (CF_IS_OBJC(_kCFReadStreamTypeID, stream)) { const UInt8* buffer; Boolean rv; *numBytesRead = maxBytesToRead; CF_OBJC_CALLV(Boolean, rv, stream, "getBuffer:length:", &buffer, numBytesRead); if (!rv) buffer = NULL; return buffer; } if (stream->impl.getBuffer == NULL) return NULL; return stream->impl.getBuffer(stream, maxBytesToRead, numBytesRead); } CFStreamError CFReadStreamGetError (CFReadStreamRef stream) { return CFStreamGetError(stream->error); } CFStreamStatus CFReadStreamGetStatus (CFReadStreamRef stream) { if (stream->closed) return kCFStreamStatusClosed; else if (stream->failed) return kCFStreamStatusError; else if (stream->open) return kCFStreamStatusOpen; else return kCFStreamStatusNotOpen; } static Boolean CFReadStreamBufferHasBytesAvailable (CFReadStreamRef s) { struct CFReadStreamBuffer* stream; stream = (struct CFReadStreamBuffer*) s; return stream->bufferCapacity > stream->position; } Boolean CFReadStreamHasBytesAvailable (CFReadStreamRef stream) { CF_OBJC_FUNCDISPATCHV(_kCFReadStreamTypeID, Boolean, stream, "hasBytesAvailable"); if (stream->impl.hasBytes != NULL) return stream->impl.hasBytes(stream); return true; } static Boolean CFReadStreamFDOpen (CFReadStreamRef s) { struct CFReadStreamFD* stream = (struct CFReadStreamFD*) s; #ifdef _WIN32 CFStringRef path = CFURLCopyFileSystemPath(stream->url, kCFURLWindowsPathStyle); stream->handle = (void*)CreateFileA( CFStringGetCStringPtr(path, kCFStringEncodingUTF8), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); CFRelease(path); if (stream->handle == INVALID_HANDLE_VALUE) { CFReadStreamSetError(s, GetLastError()); return false; } #else CFStringRef path = CFURLCopyFileSystemPath(stream->url, kCFURLPOSIXPathStyle); int flags = O_RDONLY; #ifdef O_LARGEFILE flags |= O_LARGEFILE; #endif stream->fd = open(CFStringGetCStringPtr(path, kCFStringEncodingUTF8), flags); CFRelease(path); if (stream->fd == -1) { CFReadStreamSetError(s, errno); return false; } #endif // _WIN32 return true; } static Boolean CFReadStreamBufferOpen (CFReadStreamRef s) { return true; } Boolean CFReadStreamOpen (CFReadStreamRef stream) { if (stream->open || stream->closed) { CFReadStreamSetError(stream, EBADF); return false; } if (!stream->impl.open(stream)) return false; stream->open = true; return true; } static CFIndex CFReadStreamFDRead (CFReadStreamRef s, UInt8 *buffer, CFIndex bufferLength) { struct CFReadStreamFD* stream = (struct CFReadStreamFD*) s; #ifdef _WIN32 DWORD rd; if (!ReadFile(stream->handle, buffer, bufferLength, &rd, NULL)) CFReadStreamSetError(s, GetLastError()); #else int rd = read(stream->fd, buffer, bufferLength); if (rd == -1) CFReadStreamSetError(s, errno); #endif // _WIN32 return rd; } static CFIndex CFReadStreamBufferRead (CFReadStreamRef s, UInt8 *buffer, CFIndex bufferLength) { struct CFReadStreamBuffer* stream = (struct CFReadStreamBuffer*) s; if (stream->position >= stream->bufferCapacity) return 0; if (stream->bufferCapacity - stream->position < bufferLength) bufferLength = stream->bufferCapacity - stream->position; GSMemoryCopy(buffer, stream->buffer + stream->position, bufferLength); stream->position += bufferLength; return bufferLength; } CFIndex CFReadStreamRead (CFReadStreamRef stream, UInt8 *buffer, CFIndex bufferLength) { CF_OBJC_FUNCDISPATCHV (_kCFReadStreamTypeID, CFIndex, stream, "read:maxLength:", buffer, bufferLength); if (!stream->open) { CFReadStreamSetError(stream, EBADF); return -1; } return stream->impl.read(stream, buffer, bufferLength); } void CFReadStreamScheduleWithRunLoop (CFReadStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) { } Boolean CFReadStreamSetClient (CFReadStreamRef stream, CFOptionFlags streamEvents, CFReadStreamClientCallBack clientCB, CFStreamClientContext *clientContext) { return false; } static Boolean CFReadStreamFDSetProperty (CFReadStreamRef s, CFStringRef propertyName, CFTypeRef propertyValue) { struct CFReadStreamFD* stream = (struct CFReadStreamFD*) s; if (CFEqual(propertyName, kCFStreamPropertyFileCurrentOffset)) { if (!s->open) { CFReadStreamSetError(s, EINVAL); return false; } if (CFGetTypeID(propertyValue) != CFNumberGetTypeID()) { CFReadStreamSetError(s, EINVAL); return false; } long long offset; if (!CFNumberGetValue((CFNumberRef) propertyValue, kCFNumberLongLongType, &offset)) { CFReadStreamSetError(s, EINVAL); return false; } #ifdef _WIN32 long offsetHigh = offset >> 32; if (SetFilePointer(stream->handle, (int)offset, &offsetHigh, FILE_BEGIN) == INVALID_SET_FILE_POINTER) #else if (lseek(stream->fd, offset, SEEK_SET) == (off_t)-1) #endif { CFReadStreamSetError(s, errno); return false; } return true; } CFReadStreamSetError(s, EINVAL); return false; } static Boolean CFReadStreamBufferSetProperty (CFReadStreamRef s, CFStringRef propertyName, CFTypeRef propertyValue) { struct CFReadStreamBuffer* stream = (struct CFReadStreamBuffer*) s; if (CFEqual(propertyName, kCFStreamPropertyFileCurrentOffset)) { if (!s->open) { CFReadStreamSetError(s, EINVAL); return false; } if (CFGetTypeID(propertyValue) != CFNumberGetTypeID()) { CFReadStreamSetError(s, EINVAL); return false; } CFIndex offset; if (!CFNumberGetValue((CFNumberRef) propertyValue, kCFNumberCFIndexType, &offset)) { CFReadStreamSetError(s, EINVAL); return false; } stream->position = offset; return true; } CFReadStreamSetError(s, EINVAL); return false; } Boolean CFReadStreamSetProperty (CFReadStreamRef stream, CFStringRef propertyName, CFTypeRef propertyValue) { if (stream->impl.setProperty != NULL) stream->impl.setProperty(stream, propertyName, propertyValue); CFReadStreamSetError(stream, EINVAL); return false; } void CFReadStreamUnscheduleFromRunLoop (CFReadStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode) { } gnustep-corebase-0.2/Source/NSCFOutputStream.m0000644000175000017500000000340013222706330020442 0ustar yavoryavor/* NSCFOutputStream.m Copyright (C) 2014 Free Software Foundation, Inc. Written by: Lubos Dolezel Date: February, 2014 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #include "NSCFType.h" #include "CoreFoundation/CFStream.h" @interface NSCFOutputStream : NSOutputStream NSCFTYPE_VARS @end @interface NSOutputStream (CoreBaseAdditions) - (CFTypeID) _cfTypeID; @end @implementation NSCFOutputStream + (void) load { NSCFInitialize (); } + (void) initialize { GSObjCAddClassBehavior (self, [NSCFType class]); } - (NSInteger)write:(const uint8_t *)buffer maxLength:(NSUInteger)length { return CFWriteStreamWrite((CFWriteStreamRef) self, (const UInt8*) buffer, length); } - (BOOL)hasSpaceAvailable { return CFWriteStreamCanAcceptBytes((CFWriteStreamRef) self); } @end @implementation NSOutputStream (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFWriteStreamGetTypeID(); } @end gnustep-corebase-0.2/Source/CFBinaryHeap.c0000644000175000017500000002314413222706330017544 0ustar yavoryavor/* CFBinaryHeap.c Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFBinaryHeap.h" #include static CFTypeID _kCFBinaryHeapTypeID = 0; static const CFBinaryHeapCallBacks _kCFNullBinaryHeapCallBacks = { 0, NULL, NULL, NULL, NULL }; struct __CFBinaryHeap { CFRuntimeBase _parent; CFBinaryHeapCompareContext _context; const CFBinaryHeapCallBacks *_callBacks; CFIndex _count; CFIndex _capacity; const void **_values; }; static void CFBinaryHeapFinalize (CFTypeRef cf) { CFBinaryHeapRef heap = (CFBinaryHeapRef)cf; CFAllocatorRef allocator = CFGetAllocator(heap); if (heap->_context.release) heap->_context.release (heap->_context.info); if (heap->_callBacks->release) { const void **cur = heap->_values; const void **end = cur + heap->_count; while (cur < end) heap->_callBacks->release (allocator, cur++); } CFAllocatorDeallocate (allocator, (void*)heap->_values); } static Boolean CFBinaryHeapEqual (CFTypeRef cf1, CFTypeRef cf2) { CFBinaryHeapRef heap1 = (CFBinaryHeapRef)cf1; CFBinaryHeapRef heap2 = (CFBinaryHeapRef)cf2; if (heap1->_count != heap2->_count || heap1->_callBacks->compare != heap2->_callBacks->compare || heap1->_context.info != heap2->_context.info) return false; if (heap1->_count > 0) { CFIndex idx; Boolean result; CFBinaryHeapCompareCallBack compare = heap1->_callBacks->compare; for (idx = 0 ; idx < heap1->_count ; ++idx) { if (compare) result = (compare(heap1->_values[idx], heap2->_values[idx], heap1->_context.info) == 0); else result = ((heap1->_values[idx] == heap2->_values[idx]) == false); if (result == false) return false; } } return true; } static CFHashCode CFBinaryHeapHash (CFTypeRef cf) { return (CFHashCode)((CFBinaryHeapRef)cf)->_count; } static CFRuntimeClass CFBinaryHeapClass = { 0, "CFBinaryHeap", NULL, NULL, CFBinaryHeapFinalize, CFBinaryHeapEqual, CFBinaryHeapHash, NULL, NULL }; void CFBinaryHeapInitialize (void) { _kCFBinaryHeapTypeID = _CFRuntimeRegisterClass (&CFBinaryHeapClass); } CFTypeID CFBinaryHeapGetTypeID (void) { return _kCFBinaryHeapTypeID; } CFIndex CFBinaryHeapGetCount (CFBinaryHeapRef heap) { return heap->_count; } void CFBinaryHeapApplyFunction (CFBinaryHeapRef heap, CFBinaryHeapApplierFunction applier, void *context) { CFIndex i; for (i = 0 ; i < heap->_count ; i++) applier(heap->_values[i], context); } #define CFBINARYHEAP_SIZE sizeof(struct __CFBinaryHeap) - sizeof(CFRuntimeBase) #define DEFAULT_HEAP_CAPACITY 15 /* Equivalent to 3 levels */ CFBinaryHeapRef CFBinaryHeapCreate (CFAllocatorRef alloc, CFIndex capacity, const CFBinaryHeapCallBacks *callBacks, const CFBinaryHeapCompareContext *compareContext) { CFBinaryHeapRef new; new = (CFBinaryHeapRef)_CFRuntimeCreateInstance (alloc, _kCFBinaryHeapTypeID, CFBINARYHEAP_SIZE, 0); if (new) { /* Make sure we always have at least 3 complete levels */ if (capacity < DEFAULT_HEAP_CAPACITY) { capacity = DEFAULT_HEAP_CAPACITY; } else { CFIndex tmp = DEFAULT_HEAP_CAPACITY; while (capacity > tmp) tmp = (tmp << 1) + 1; capacity = tmp; } new->_values = CFAllocatorAllocate (alloc, sizeof(void*) * capacity, 0); memset (new->_values, 0, sizeof(void*) * capacity); new->_capacity = capacity; if (callBacks == NULL) callBacks = &_kCFNullBinaryHeapCallBacks; new->_callBacks = callBacks; if (compareContext && compareContext->info) { new->_context.version = compareContext->version; new->_context.info = compareContext->retain ? (void*)compareContext->retain (compareContext->info) : compareContext->info; new->_context.retain = compareContext->retain; new->_context.release = compareContext->release; new->_context.copyDescription = compareContext->copyDescription; } } return new; } CFBinaryHeapRef CFBinaryHeapCreateCopy (CFAllocatorRef alloc, CFIndex capacity, CFBinaryHeapRef heap) { CFBinaryHeapRef ret; ret = CFBinaryHeapCreate (alloc, capacity, heap->_callBacks, &heap->_context); memcpy (ret->_values, heap->_values, sizeof(void*) * heap->_count); ret->_count = heap->_count; return ret; } CF_INLINE void CFBinaryHeapCheckCapacityAndGrow (CFBinaryHeapRef heap) { if (heap->_count == heap->_capacity) { CFIndex newCapacity = (heap->_capacity << 1) + 1; heap->_values = CFAllocatorReallocate (CFGetAllocator(heap), heap->_values, (newCapacity * sizeof(const void *)), 0); heap->_capacity = newCapacity; } } void CFBinaryHeapAddValue (CFBinaryHeapRef heap, const void *value) { CFIndex cur; void *info; CFBinaryHeapCompareCallBack compare; CFBinaryHeapRetainCallBack retain; CFBinaryHeapCheckCapacityAndGrow (heap); compare = heap->_callBacks->compare; info = heap->_context.info; cur = heap->_count; while (cur > 0) { /* Shift down */ CFIndex parent; const void *p; parent = (cur - 1) >> 1; p = heap->_values[parent]; if (compare ? compare(p, value, info) != kCFCompareGreaterThan : p <= value) break; heap->_values[cur] = heap->_values[parent]; cur = parent; } retain = heap->_callBacks->retain; heap->_values[cur] = retain ? retain(CFGetAllocator(heap), value) : value; heap->_count += 1; } Boolean CFBinaryHeapContainsValue (CFBinaryHeapRef heap, const void *value) { CFIndex idx; CFIndex count; CFBinaryHeapCompareCallBack compare; void *info; idx = 0; count = heap->_count; compare = heap->_callBacks->compare; info = heap->_context.info; while (idx < count) { const void *v; v = heap->_values[idx++]; if (compare ? compare(v, value, info) == kCFCompareEqualTo : v == value) return true; } return false; } CFIndex CFBinaryHeapGetCountOfValue (CFBinaryHeapRef heap, const void *value) { CFIndex idx; CFIndex count; CFIndex counter; CFBinaryHeapCompareCallBack compare; void *info; idx = 0; count = heap->_count; counter = 0; compare = heap->_callBacks->compare; info = heap->_context.info; while (idx < count) { const void *v; v = heap->_values[idx++]; if (compare ? compare(v, value, info) == kCFCompareEqualTo : v == value) counter++; } return counter; } const void * CFBinaryHeapGetMinimum (CFBinaryHeapRef heap) { return heap->_values[0]; } Boolean CFBinaryHeapGetMinimumIfPresent (CFBinaryHeapRef heap, const void **value) { if (heap->_count == 0) return false; if (value) *value = heap->_values[0]; return true; } void CFBinaryHeapGetValues (CFBinaryHeapRef heap, const void **values) { CFBinaryHeapRef copy; copy = CFBinaryHeapCreateCopy (NULL, heap->_capacity, heap); while (CFBinaryHeapGetMinimumIfPresent(copy, values)) { values++; CFBinaryHeapRemoveMinimumValue (copy); } CFRelease (copy); } void CFBinaryHeapRemoveAllValues (CFBinaryHeapRef heap) { if (heap->_callBacks->release) { CFAllocatorRef allocator = CFGetAllocator(heap); const void **cur = heap->_values; const void **end = cur + heap->_count; while (cur < end) heap->_callBacks->release (allocator, cur++); } heap->_count = 0; } void CFBinaryHeapRemoveMinimumValue (CFBinaryHeapRef heap) { CFIndex idx; CFIndex child; CFIndex count; CFBinaryHeapReleaseCallBack release; CFBinaryHeapCompareCallBack compare; const void *last; void *info; release = heap->_callBacks->release; if (release) release (CFGetAllocator(heap), heap->_values[0]); count = heap->_count; heap->_count -= 1; compare = heap->_callBacks->compare; info = heap->_context.info; idx = 0; child = 1; /* Initialize to left child */ last = heap->_values[count - 1]; while (child < count) { const void *v; v = heap->_values[child]; if (child + 1 < count) /* Check for a right child */ { const void *right; right = heap->_values[child + 1]; if (compare ? compare(v, right, info) == kCFCompareGreaterThan : v > right) { v = right; child += 1; } } heap->_values[idx] = v; idx = child; child = (idx << 1) + 1; /* Go to left child */ } heap->_values[idx] = last; } gnustep-corebase-0.2/Source/CFXMLNode.c0000644000175000017500000003642413222706330016775 0ustar yavoryavor/* CFXMLNode.c Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFURL.h" #include "CoreFoundation/CFXMLNode.h" #include struct __CFXMLNode { CFRuntimeBase _parent; CFXMLNodeTypeCode _type; CFStringRef _string; CFIndex _version; void *_info; }; static CFTypeID _kCFXMLNodeTypeID = 0; static void CFXMLNodeFinalize (CFTypeRef cf) { CFXMLNodeRef node = (CFXMLNodeRef)cf; switch (node->_type) { case kCFXMLNodeTypeDocument: { CFXMLDocumentInfo *info = (CFXMLDocumentInfo*)node->_info; CFRelease (info->sourceURL); } break; case kCFXMLNodeTypeElement: { CFXMLElementInfo *info = (CFXMLElementInfo*)node->_info; CFRelease (info->attributes); CFRelease (info->attributeOrder); } break; case kCFXMLNodeTypeProcessingInstruction: { CFXMLProcessingInstructionInfo *info = (CFXMLProcessingInstructionInfo*)node->_info; CFRelease (info->dataString); } break; case kCFXMLNodeTypeEntity: { CFXMLEntityInfo *info = (CFXMLEntityInfo*)node->_info; CFRelease (info->replacementText); CFRelease (info->entityID.systemID); CFRelease (info->entityID.publicID); CFRelease (info->notationName); } break; case kCFXMLNodeTypeDocumentType: /* These two have the same structure. */ case kCFXMLNodeTypeNotation: { CFXMLDocumentTypeInfo *info = (CFXMLDocumentTypeInfo*)node->_info; CFRelease (info->externalID.systemID); CFRelease (info->externalID.publicID); } break; case kCFXMLNodeTypeElementTypeDeclaration: { CFXMLElementTypeDeclarationInfo *info = (CFXMLElementTypeDeclarationInfo*)node->_info; CFRelease (info->contentDescription); } break; case kCFXMLNodeTypeAttributeListDeclaration: { CFXMLAttributeListDeclarationInfo *info = (CFXMLAttributeListDeclarationInfo*)node->_info; CFIndex idx; CFIndex num = info->numberOfAttributes; for (idx = 0 ; idx < num ; ++idx) { CFRelease (info->attributes[idx].attributeName); CFRelease (info->attributes[idx].typeString); CFRelease (info->attributes[idx].defaultString); } CFAllocatorDeallocate (CFGetAllocator (node), info->attributes); } break; default: /* Do nothing for everything else */ break; } CFRelease (node->_string); } static Boolean CFXMLNodeEqual (CFTypeRef cf1, CFTypeRef cf2) { CFXMLNodeRef node1 = (CFXMLNodeRef)cf1; CFXMLNodeRef node2 = (CFXMLNodeRef)cf2; if (node1->_type == node2->_type && CFEqual (node1->_string, node2->_string) && node1->_version == node2->_version) { switch (node1->_type) { case kCFXMLNodeTypeDocument: { CFXMLDocumentInfo *doc1 = (CFXMLDocumentInfo*)node1->_info; CFXMLDocumentInfo *doc2 = (CFXMLDocumentInfo*)node2->_info; return CFEqual (doc1->sourceURL, doc2->sourceURL); } case kCFXMLNodeTypeElement: { CFXMLElementInfo *elem1 = (CFXMLElementInfo*)node1->_info; CFXMLElementInfo *elem2 = (CFXMLElementInfo*)node2->_info; return elem1->isEmpty == elem2->isEmpty && CFEqual (elem1->attributes, elem2->attributes); } case kCFXMLNodeTypeProcessingInstruction: { CFXMLProcessingInstructionInfo *proc1 = (CFXMLProcessingInstructionInfo*)node1->_info; CFXMLProcessingInstructionInfo *proc2 = (CFXMLProcessingInstructionInfo*)node2->_info; return CFEqual (proc1->dataString, proc2->dataString); } case kCFXMLNodeTypeEntity: { CFXMLEntityInfo *ent1 = (CFXMLEntityInfo*)node1->_info; CFXMLEntityInfo *ent2 = (CFXMLEntityInfo*)node2->_info; return ent1->entityType == ent2->entityType && CFEqual (ent1->replacementText, ent2->replacementText) && CFEqual (ent1->notationName, ent2->notationName) && CFEqual (ent1->entityID.systemID, ent2->entityID.systemID) && CFEqual (ent1->entityID.publicID, ent2->entityID.publicID); } case kCFXMLNodeTypeEntityReference: { CFXMLEntityReferenceInfo *entRef1 = (CFXMLEntityReferenceInfo*)node1->_info; CFXMLEntityReferenceInfo *entRef2 = (CFXMLEntityReferenceInfo*)node2->_info; return entRef1->entityType == entRef2->entityType; } case kCFXMLNodeTypeDocumentType: /* These two have the same structure. */ case kCFXMLNodeTypeNotation: { CFXMLDocumentTypeInfo *info1 = (CFXMLDocumentTypeInfo*)node1->_info; CFXMLDocumentTypeInfo *info2 = (CFXMLDocumentTypeInfo*)node2->_info; return CFEqual (info1->externalID.systemID, info2->externalID.systemID) && CFEqual (info1->externalID.publicID, info2->externalID.publicID); } case kCFXMLNodeTypeElementTypeDeclaration: { CFXMLElementTypeDeclarationInfo *decl1 = (CFXMLElementTypeDeclarationInfo*)node1->_info; CFXMLElementTypeDeclarationInfo *decl2 = (CFXMLElementTypeDeclarationInfo*)node2->_info; return CFEqual (decl1->contentDescription, decl2->contentDescription); } case kCFXMLNodeTypeAttributeListDeclaration: { CFXMLAttributeListDeclarationInfo *decl1 = (CFXMLAttributeListDeclarationInfo*)node1->_info; CFXMLAttributeListDeclarationInfo *decl2 = (CFXMLAttributeListDeclarationInfo*)node2->_info; CFIndex idx; if (decl1->numberOfAttributes != decl2->numberOfAttributes) return false; for (idx = 0 ; idx < decl1->numberOfAttributes ; ++idx) { if (!CFEqual(decl1->attributes[idx].attributeName, decl2->attributes[idx].attributeName) || !CFEqual(decl1->attributes[idx].typeString, decl2->attributes[idx].typeString) || !CFEqual(decl1->attributes[idx].defaultString, decl2->attributes[idx].defaultString)) return false; } } default: break; } } return false; } static CFHashCode CFXMLNodeHash (CFTypeRef cf) { CFXMLNodeRef node = (CFXMLNodeRef)cf; return (node->_string ? CFHash(node->_string) : 0) + node->_type + node->_version; } static const CFRuntimeClass CFXMLNodeClass = { 0, "CFXMLNode", NULL, NULL, CFXMLNodeFinalize, CFXMLNodeEqual, CFXMLNodeHash, NULL, NULL }; void CFXMLNodeInitialize (void) { _kCFXMLNodeTypeID = _CFRuntimeRegisterClass (&CFXMLNodeClass); } CF_INLINE void CFXMLNodeCopyAdditionalInfo (CFAllocatorRef alloc, void *info, const void *additionalInfoPtr, CFXMLNodeTypeCode xmlType) { switch (xmlType) { case kCFXMLNodeTypeDocument: { CFXMLDocumentInfo *src = (CFXMLDocumentInfo*)additionalInfoPtr; CFXMLDocumentInfo *dest = (CFXMLDocumentInfo*)info; dest->sourceURL = CFRetain (src->sourceURL); dest->encoding = src->encoding; } break; case kCFXMLNodeTypeElement: { CFXMLElementInfo *src = (CFXMLElementInfo*)additionalInfoPtr; CFXMLElementInfo *dest = (CFXMLElementInfo*)info; dest->attributes = src->attributes ? CFDictionaryCreateCopy (alloc, src->attributes) : NULL; dest->attributeOrder = src->attributeOrder ? CFArrayCreateCopy (alloc, src->attributeOrder) : NULL; dest->isEmpty = src->isEmpty; } break; case kCFXMLNodeTypeProcessingInstruction: { CFXMLProcessingInstructionInfo *src = (CFXMLProcessingInstructionInfo*)additionalInfoPtr; CFXMLProcessingInstructionInfo *dest = (CFXMLProcessingInstructionInfo*)info; dest->dataString = src->dataString ? CFStringCreateCopy (alloc, src->dataString) : NULL; } break; case kCFXMLNodeTypeEntity: { CFXMLEntityInfo *src = (CFXMLEntityInfo*)additionalInfoPtr; CFXMLEntityInfo *dest = (CFXMLEntityInfo*)info; dest->entityType = src->entityType; dest->replacementText = src->replacementText ? CFStringCreateCopy (alloc, src->replacementText) : NULL; dest->entityID.systemID = src->entityID.systemID ? CFRetain(src->entityID.systemID) : NULL; dest->entityID.publicID = src->entityID.publicID ? CFStringCreateCopy (alloc, src->entityID.publicID) : NULL; dest->notationName = src->notationName ? CFStringCreateCopy (alloc, src->notationName) : NULL; } break; case kCFXMLNodeTypeEntityReference: { CFXMLEntityReferenceInfo *src = (CFXMLEntityReferenceInfo*)additionalInfoPtr; CFXMLEntityReferenceInfo *dest = (CFXMLEntityReferenceInfo*)info; dest->entityType = src->entityType; } break; case kCFXMLNodeTypeDocumentType: /* These two have the same structure. */ case kCFXMLNodeTypeNotation: { CFXMLDocumentTypeInfo *src = (CFXMLDocumentTypeInfo*)additionalInfoPtr; CFXMLDocumentTypeInfo *dest = (CFXMLDocumentTypeInfo*)info; dest->externalID.systemID = src->externalID.systemID ? CFRetain(src->externalID.systemID) : NULL; dest->externalID.publicID = src->externalID.publicID ? CFStringCreateCopy (alloc, src->externalID.publicID) : NULL; } break; case kCFXMLNodeTypeElementTypeDeclaration: { CFXMLElementTypeDeclarationInfo *src = (CFXMLElementTypeDeclarationInfo*)additionalInfoPtr; CFXMLElementTypeDeclarationInfo *dest = (CFXMLElementTypeDeclarationInfo*)info; dest->contentDescription = src->contentDescription ? CFStringCreateCopy (alloc, src->contentDescription) : NULL; } break; case kCFXMLNodeTypeAttributeListDeclaration: { CFXMLAttributeListDeclarationInfo *src = (CFXMLAttributeListDeclarationInfo*)additionalInfoPtr; CFXMLAttributeListDeclarationInfo *dest = (CFXMLAttributeListDeclarationInfo*)info; CFIndex idx; CFIndex num = src->numberOfAttributes; dest->numberOfAttributes = num; dest->attributes = num > 0 ? CFAllocatorAllocate (alloc, sizeof(CFXMLAttributeDeclarationInfo) * num, 0) : NULL; for (idx = 0 ; idx < num ; ++idx) { dest->attributes[idx].attributeName = CFStringCreateCopy (alloc, src->attributes[idx].attributeName); dest->attributes[idx].typeString = CFStringCreateCopy (alloc, src->attributes[idx].typeString); dest->attributes[idx].defaultString = CFStringCreateCopy (alloc, src->attributes[idx].defaultString); } } break; default: /* Do nothing for everything else */ break; } } CFTypeID CFXMLNodeGetTypeID (void) { return _kCFXMLNodeTypeID; } #define CFXMLNODE_SIZE (sizeof(struct __CFXMLNode) - sizeof(CFRuntimeBase)) CFXMLNodeRef CFXMLNodeCreate (CFAllocatorRef alloc, CFXMLNodeTypeCode xmlType, CFStringRef dataString, const void *additionalInfoPtr, CFIndex version) { struct __CFXMLNode *new; CFIndex additionalInfoSize; switch (xmlType) { case kCFXMLNodeTypeDocument: additionalInfoSize = sizeof(struct CFXMLDocumentInfo); break; case kCFXMLNodeTypeElement: additionalInfoSize = sizeof(struct CFXMLElementInfo); break; case kCFXMLNodeTypeProcessingInstruction: additionalInfoSize = sizeof(struct CFXMLProcessingInstructionInfo); break; case kCFXMLNodeTypeEntity: additionalInfoSize = sizeof(struct CFXMLEntityInfo); break; case kCFXMLNodeTypeEntityReference: additionalInfoSize = sizeof(struct CFXMLEntityReferenceInfo); break; case kCFXMLNodeTypeDocumentType: additionalInfoSize = sizeof(struct CFXMLDocumentTypeInfo); break; case kCFXMLNodeTypeNotation: additionalInfoSize = sizeof(struct CFXMLNotationInfo); break; case kCFXMLNodeTypeElementTypeDeclaration: additionalInfoSize = sizeof(struct CFXMLElementTypeDeclarationInfo); break; case kCFXMLNodeTypeAttributeListDeclaration: additionalInfoSize = sizeof(struct CFXMLAttributeListDeclarationInfo); break; default: additionalInfoSize = 0; } new = (struct __CFXMLNode*)_CFRuntimeCreateInstance (alloc, _kCFXMLNodeTypeID, CFXMLNODE_SIZE + additionalInfoSize, 0); if (new) { new->_type = xmlType; new->_string = dataString ? CFStringCreateCopy (alloc, dataString) : dataString; new->_version = version; if (additionalInfoPtr) { new->_info = (void*)&(new[1]); CFXMLNodeCopyAdditionalInfo (alloc, new->_info, additionalInfoPtr, xmlType); } } return new; } CFXMLNodeRef CFXMLNodeCreateCopy (CFAllocatorRef alloc, CFXMLNodeRef origNode) { return CFXMLNodeCreate (alloc, origNode->_type, origNode->_string, origNode->_info, origNode->_version); } const void * CFXMLNodeGetInfoPtr (CFXMLNodeRef node) { return node->_info; } CFStringRef CFXMLNodeGetString (CFXMLNodeRef node) { return node->_string; } CFXMLNodeTypeCode CFXMLNodeGetTypeCode (CFXMLNodeRef node) { return ((CFRuntimeBase*)node)->_flags.info; } CFIndex CFXMLNodeGetVersion (CFXMLNodeRef node) { return node->_version; } gnustep-corebase-0.2/Source/GSMemory.h0000644000175000017500000000355213222706330017021 0ustar yavoryavor/* GSMemory.h Copyright (C) 2013 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: August, 2013 This file is part of GNUstep CoreBase library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #ifndef GSMEMORY_H #define GSMEMORY_H #include "CoreFoundation/CFBase.h" #if HOST_OS_WINDOWS #include #else #include #endif CF_INLINE void * GSMemoryCopy (void *dst, const void *src, CFIndex len) { #if HOST_OS_WINDOWS CopyMemory (dst, src, len); return dst; #else return memcpy (dst, src, len); #endif } CF_INLINE void * GSMemoryMove (void *dst, const void *src, CFIndex len) { #if HOST_OS_WINDOWS MoveMemory (dst, src, len); return dst; #else return memmove (dst, src, len); #endif } CF_INLINE void * GSMemorySet (void *dst, int c, CFIndex len) { #if HOST_OS_WINDOWS FillMemory (dst, len, c); return dst; #else return memset (dst, c, len); #endif } CF_INLINE void * GSMemoryZero (void *dst, CFIndex len) { #if HOST_OS_WINDOWS ZeroMemory (dst, len); return dst; #else return memset (dst, 0, len); #endif } #endif /* GSMEMORY_H */ gnustep-corebase-0.2/Source/CFDateFormatter.c0000644000175000017500000005205014551015633020266 0ustar yavoryavor/* CFDateFormatter.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFDate.h" #include "CoreFoundation/CFNumber.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFTimeZone.h" #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFDateFormatter.h" #include "GSPrivate.h" #if defined(HAVE_UNICODE_UDAT_H) #include #endif #if defined(HAVE_UNICODE_UDATPG_H) #include #endif #if defined(HAVE_ICU_H) #include #endif #define BUFFER_SIZE 256 CONST_STRING_DECL(kCFDateFormatterIsLenient, "kCFDateFormatterIsLenient"); CONST_STRING_DECL(kCFDateFormatterTimeZone, "kCFDateFormatterTimeZone"); CONST_STRING_DECL(kCFDateFormatterCalendarName, "kCFDateFormatterCalendarName"); CONST_STRING_DECL(kCFDateFormatterDefaultFormat, "kCFDateFormatterDefaultFormat"); CONST_STRING_DECL(kCFDateFormatterTwoDigitStartDate, "kCFDateFormatterTwoDigitStartDate"); CONST_STRING_DECL(kCFDateFormatterDefaultDate, "kCFDateFormatterDefaultDate"); CONST_STRING_DECL(kCFDateFormatterCalendar, "kCFDateFormatterCalendar"); CONST_STRING_DECL(kCFDateFormatterEraSymbols, "kCFDateFormatterEraSymbols"); CONST_STRING_DECL(kCFDateFormatterMonthSymbols, "kCFDateFormatterMonthSymbols"); CONST_STRING_DECL(kCFDateFormatterShortMonthSymbols, "kCFDateFormatterShortMonthSymbols"); CONST_STRING_DECL(kCFDateFormatterWeekdaySymbols, "kCFDateFormatterWeekdaySymbols"); CONST_STRING_DECL(kCFDateFormatterShortWeekdaySymbols, "kCFDateFormatterShortWeekdaySymbols"); CONST_STRING_DECL(kCFDateFormatterAMSymbol, "kCFDateFormatterAMSymbol"); CONST_STRING_DECL(kCFDateFormatterPMSymbol, "kCFDateFormatterPMSymbol"); CONST_STRING_DECL(kCFDateFormatterLongEraSymbols, "kCFDateFormatterLongEraSymbols"); CONST_STRING_DECL(kCFDateFormatterVeryShortMonthSymbols, "kCFDateFormatterVeryShortMonthSymbols"); CONST_STRING_DECL(kCFDateFormatterStandaloneMonthSymbols, "kCFDateFormatterStandaloneMonthSymbols"); CONST_STRING_DECL(kCFDateFormatterShortStandaloneMonthSymbols, "kCFDateFormatterShortStandaloneMonthSymbols"); CONST_STRING_DECL(kCFDateFormatterVeryShortStandaloneMonthSymbols, "kCFDateFormatterVeryShortStandaloneMonthSymbols"); CONST_STRING_DECL(kCFDateFormatterVeryShortWeekdaySymbols, "kCFDateFormatterVeryShortWeekdaySymbols"); CONST_STRING_DECL(kCFDateFormatterStandaloneWeekdaySymbols, "kCFDateFormatterStandaloneWeekdaySymbols"); CONST_STRING_DECL(kCFDateFormatterShortStandaloneWeekdaySymbols, "kCFDateFormatterShortStandaloneWeekdaySymbols"); CONST_STRING_DECL(kCFDateFormatterVeryShortStandaloneWeekdaySymbols, "kCFDateFormatterVeryShortStandaloneWeekdaySymbols"); CONST_STRING_DECL(kCFDateFormatterQuarterSymbols, "kCFDateFormatterQuarterSymbols"); CONST_STRING_DECL(kCFDateFormatterShortQuarterSymbols, "kCFDateFormatterShortQuarterSymbols"); CONST_STRING_DECL(kCFDateFormatterStandaloneQuarterSymbols, "kCFDateFormatterStandaloneQuarterSymbols"); CONST_STRING_DECL(kCFDateFormatterShortStandaloneQuarterSymbols, "kCFDateFormatterShortStandaloneQuarterSymbols"); CONST_STRING_DECL(kCFDateFormatterGregorianStartDate, "kCFDateFormatterGregorianStartDate"); struct __CFDateFormatter { CFRuntimeBase _parent; UDateFormat *_fmt; CFLocaleRef _locale; CFTimeZoneRef _tz; CFDateFormatterStyle _dateStyle; CFDateFormatterStyle _timeStyle; CFStringRef _defaultFormat; CFStringRef _format; }; static CFTypeID _kCFDateFormatterTypeID = 0; static const CFRuntimeClass CFDateFormatterClass = { 0, "CFDateFormatter", NULL, NULL, NULL, NULL, NULL, NULL, NULL }; void CFDateFormatterInitialize (void) { _kCFDateFormatterTypeID = _CFRuntimeRegisterClass(&CFDateFormatterClass); } CF_INLINE UDateFormatStyle CFDataFormatterStyleToUDateFormatStyle (CFDateFormatterStyle style) { UDateFormatStyle us = 0; switch (style) { case kCFDateFormatterNoStyle: us = UDAT_NONE; break; case kCFDateFormatterShortStyle: us = UDAT_SHORT; break; case kCFDateFormatterMediumStyle: us = UDAT_MEDIUM; break; case kCFDateFormatterLongStyle: us = UDAT_LONG; break; case kCFDateFormatterFullStyle: us = UDAT_FULL; break; } return us; } static void CFDateFormatterSetup (CFDateFormatterRef dfmt) { UDateFormatStyle utStyle; UDateFormatStyle udStyle; const char *cLocale; char buffer[ULOC_FULLNAME_CAPACITY]; UniChar uTzID[BUFFER_SIZE]; CFIndex uTzIDLength; UErrorCode err = U_ZERO_ERROR; if (dfmt->_fmt) udat_close (dfmt->_fmt); utStyle = CFDataFormatterStyleToUDateFormatStyle (dfmt->_timeStyle); udStyle = CFDataFormatterStyleToUDateFormatStyle (dfmt->_dateStyle); cLocale = CFLocaleGetCStringIdentifier (dfmt->_locale, buffer, ULOC_FULLNAME_CAPACITY); uTzIDLength = CFStringGetLength (CFTimeZoneGetName(dfmt->_tz)); if (uTzIDLength > BUFFER_SIZE) uTzIDLength = BUFFER_SIZE; CFStringGetCharacters (CFTimeZoneGetName(dfmt->_tz), CFRangeMake(0, uTzIDLength), uTzID); dfmt->_fmt = udat_open (utStyle, udStyle, cLocale, uTzID, uTzIDLength, NULL, 0, &err); if (U_FAILURE(err)) dfmt->_fmt = NULL; } static void CFDateFormatterSetLenient (CFDateFormatterRef fmt, int prop, CFTypeRef value) { udat_setLenient (fmt->_fmt, value == kCFBooleanTrue ? true : false); } static CFTypeRef CFDateFormatterCopyLenient (CFDateFormatterRef fmt, int prop) { return CFRetain(udat_isLenient(fmt->_fmt) ? kCFBooleanTrue : kCFBooleanFalse); } static void CFDateFormatterSetTimeZone (CFDateFormatterRef fmt, int prop, CFTypeRef value) { if (!CFEqual(fmt->_tz, value)) CFRelease (fmt->_tz); fmt->_tz = CFRetain (value); } static CFTypeRef CFDateFormatterCopyTimeZone (CFDateFormatterRef fmt, int prop) { return CFRetain (fmt->_tz); } static void CFDateFormatterSetCalendarName (CFDateFormatterRef fmt, int prop, CFTypeRef value) { CFDictionaryRef dict; CFMutableDictionaryRef mDict; CFStringRef locale; dict = CFLocaleCreateComponentsFromLocaleIdentifier (NULL, CFLocaleGetIdentifier (fmt->_locale)); mDict = CFDictionaryCreateMutableCopy (NULL, 0, dict); CFRelease (dict); CFDictionarySetValue (mDict, kCFLocaleCalendarIdentifier, value); locale = CFLocaleCreateLocaleIdentifierFromComponents (NULL, mDict); CFRelease (fmt->_locale); fmt->_locale = CFLocaleCreate (NULL, locale); CFRelease (locale); CFRelease (mDict); CFDateFormatterSetup (fmt); } static CFTypeRef CFDateFormatterCopyCalendarName (CFDateFormatterRef fmt, int prop) { CFStringRef calendarName; calendarName = CFLocaleGetValue (fmt->_locale, kCFLocaleCalendarIdentifier); return CFRetain(calendarName); } static void CFDateFormatterSetDefaultFormat (CFDateFormatterRef fmt, int prop, CFTypeRef value) { /* Do nothing, this property can't be changed */ } static CFTypeRef CFDateFormatterCopyDefaultFormat (CFDateFormatterRef fmt, int prop) { return CFRetain (fmt->_defaultFormat); } static void CFDateFormatterSetTwoDigitYearStart (CFDateFormatterRef fmt, int prop, CFTypeRef value) { UDate udate = ABSOLUTETIME_TO_UDATE(CFDateGetAbsoluteTime(value)); UErrorCode err = U_ZERO_ERROR; udat_set2DigitYearStart (fmt->_fmt, udate, &err); } static CFTypeRef CFDateFormatterCopyTwoDigitYearStart (CFDateFormatterRef fmt, int prop) { UErrorCode err = U_ZERO_ERROR; CFAbsoluteTime at = UDATE_TO_ABSOLUTETIME(udat_get2DigitYearStart (fmt->_fmt, &err)); return CFDateCreate (NULL, at); } static void CFDateFormatterSetDefaultDate (CFDateFormatterRef fmt, int prop, CFTypeRef value) { } static CFTypeRef CFDateFormatterCopyDefaultDate (CFDateFormatterRef fmt, int prop) { return NULL; } static void CFDateFormatterSetCalendar (CFDateFormatterRef fmt, int prop, CFTypeRef value) { } static CFTypeRef CFDateFormatterCopyCalendar (CFDateFormatterRef fmt, int prop) { return NULL; } static void CFDateFromatterSetSymbolAtIndex (UDateFormat fmt, UDateFormatSymbolType type, CFStringRef value, CFIndex idx) { CFIndex textLength; UniChar text[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; textLength = CFStringGetLength (value); if (textLength > BUFFER_SIZE) textLength = BUFFER_SIZE; CFStringGetCharacters (value, CFRangeMake(0, textLength), text); udat_setSymbols (fmt, type, idx, text, textLength, &err); } static CFStringRef CFDateFormatterCopySymbolAtIndex (UDateFormat fmt, UDateFormatSymbolType type, CFIndex idx) { CFIndex textLength; UniChar text[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; textLength = udat_getSymbols (fmt, type, idx, text, BUFFER_SIZE, &err); if (textLength > BUFFER_SIZE) textLength = BUFFER_SIZE; return CFStringCreateWithCharacters (NULL, text, textLength); } static void CFDateFormatterSetSymbols (CFDateFormatterRef fmt, int prop, CFTypeRef value) { CFIndex idx; CFIndex count; CFArrayRef array = (CFArrayRef)value; count = CFArrayGetCount (array); /* Something's wrong if count != # of symbols in ICU. */ if (count != udat_countSymbols(fmt->_fmt, prop)) return; for (idx = 0 ; idx < count ; ++ idx) { CFDateFromatterSetSymbolAtIndex (fmt->_fmt, prop, CFArrayGetValueAtIndex (array, idx), idx); } } static CFTypeRef CFDateFormatterCopySymbols (CFDateFormatterRef fmt, int prop) { CFIndex idx; CFIndex count; CFStringRef str; CFMutableArrayRef mArray; CFArrayRef ret = NULL; count = udat_countSymbols(fmt->_fmt, prop); mArray = CFArrayCreateMutable (NULL, count, &kCFTypeArrayCallBacks); for (idx = 0 ; idx < count ; ++ idx) { str = CFDateFormatterCopySymbolAtIndex (fmt->_fmt, prop, idx); CFArrayAppendValue (mArray, str); CFRelease (str); } ret = CFArrayCreateCopy (NULL, mArray); CFRelease (mArray); return ret; } static void CFDateFormatterSetAMPMSymbol (CFDateFormatterRef fmt, int idx, CFTypeRef value) { CFDateFromatterSetSymbolAtIndex (fmt->_fmt, UDAT_AM_PMS, value, idx); } static CFTypeRef CFDateFormatterCopyAMPMSymbol (CFDateFormatterRef fmt, int idx) { return CFDateFormatterCopySymbolAtIndex (fmt->_fmt, UDAT_AM_PMS, idx); } static void CFDateFormatterSetGregorianStartDate (CFDateFormatterRef fmt, int prop, CFTypeRef value) { CFAbsoluteTime at; UErrorCode err = U_ZERO_ERROR; UCalendar *ucal = (UCalendar*)udat_getCalendar (fmt->_fmt); at = CFDateGetAbsoluteTime (value); ucal_setGregorianChange (ucal, ABSOLUTETIME_TO_UDATE(at), &err); } static CFTypeRef CFDateFormatterCopyGregorianStartDate (CFDateFormatterRef fmt, int prop) { UDate udate; UErrorCode err = U_ZERO_ERROR; UCalendar *ucal = (UCalendar*)udat_getCalendar (fmt->_fmt); udate = ucal_getGregorianChange (ucal, &err); return CFDateCreate (NULL, UDATE_TO_ABSOLUTETIME(udate)); } static struct _kCFDateFormatterProperties { const CFStringRef *prop; int icuProp; void (*set)(CFDateFormatterRef fmt, int prop, CFTypeRef value); CFTypeRef (*copy)(CFDateFormatterRef fmt, int prop); } _kCFDateFormatterProperties[] = { { &kCFDateFormatterIsLenient, 0, CFDateFormatterSetLenient, CFDateFormatterCopyLenient }, { &kCFDateFormatterTimeZone, 0, CFDateFormatterSetTimeZone, CFDateFormatterCopyTimeZone }, { &kCFDateFormatterCalendarName, 0, CFDateFormatterSetCalendarName, CFDateFormatterCopyCalendarName }, { &kCFDateFormatterDefaultFormat, 0, CFDateFormatterSetDefaultFormat, CFDateFormatterCopyDefaultFormat }, { &kCFDateFormatterTwoDigitStartDate, 0, CFDateFormatterSetTwoDigitYearStart, CFDateFormatterCopyTwoDigitYearStart }, { &kCFDateFormatterDefaultDate, 0, CFDateFormatterSetDefaultDate, CFDateFormatterCopyDefaultDate }, { &kCFDateFormatterCalendar, 0, CFDateFormatterSetCalendar, CFDateFormatterCopyCalendar }, { &kCFDateFormatterEraSymbols, UDAT_ERAS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterMonthSymbols, UDAT_MONTHS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterShortMonthSymbols, UDAT_SHORT_MONTHS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterWeekdaySymbols, UDAT_WEEKDAYS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterShortWeekdaySymbols, UDAT_SHORT_WEEKDAYS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterAMSymbol, 0, CFDateFormatterSetAMPMSymbol, CFDateFormatterCopyAMPMSymbol }, { &kCFDateFormatterPMSymbol, 1, CFDateFormatterSetAMPMSymbol, CFDateFormatterCopyAMPMSymbol }, { &kCFDateFormatterLongEraSymbols, UDAT_ERA_NAMES, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterVeryShortMonthSymbols, UDAT_NARROW_MONTHS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterStandaloneMonthSymbols, UDAT_STANDALONE_MONTHS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterShortStandaloneMonthSymbols, UDAT_STANDALONE_SHORT_MONTHS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterVeryShortStandaloneMonthSymbols, UDAT_STANDALONE_NARROW_MONTHS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterVeryShortWeekdaySymbols, UDAT_NARROW_WEEKDAYS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterStandaloneWeekdaySymbols, UDAT_STANDALONE_WEEKDAYS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterShortStandaloneWeekdaySymbols, UDAT_STANDALONE_SHORT_WEEKDAYS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterVeryShortStandaloneWeekdaySymbols, UDAT_STANDALONE_NARROW_WEEKDAYS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterQuarterSymbols, UDAT_QUARTERS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterShortQuarterSymbols, UDAT_SHORT_QUARTERS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterStandaloneQuarterSymbols, UDAT_STANDALONE_QUARTERS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterShortStandaloneQuarterSymbols, UDAT_STANDALONE_SHORT_QUARTERS, CFDateFormatterSetSymbols, CFDateFormatterCopySymbols }, { &kCFDateFormatterGregorianStartDate, 0, CFDateFormatterSetGregorianStartDate, CFDateFormatterCopyGregorianStartDate } }; static const CFIndex _kCFDateFormatterPropertiesCount = sizeof(_kCFDateFormatterProperties) / sizeof(struct _kCFDateFormatterProperties); #define CFDATEFORMATTER_SIZE \ sizeof(struct __CFDateFormatter) - sizeof(CFRuntimeBase) CFDateFormatterRef CFDateFormatterCreate (CFAllocatorRef alloc, CFLocaleRef locale, CFDateFormatterStyle dateStyle, CFDateFormatterStyle timeStyle) { struct __CFDateFormatter *new; new = (struct __CFDateFormatter*)_CFRuntimeCreateInstance (alloc, _kCFDateFormatterTypeID, CFDATEFORMATTER_SIZE, 0); if (new) { CFIndex formatLength; UniChar format[BUFFER_SIZE]; UErrorCode err = U_ZERO_ERROR; new->_locale = locale ? CFRetain(locale) : CFLocaleCopyCurrent (); new->_tz = CFTimeZoneCopyDefault (); new->_dateStyle = dateStyle; new->_timeStyle = timeStyle; CFDateFormatterSetup (new); formatLength = udat_toPattern (new->_fmt, false, format, BUFFER_SIZE, &err); if (formatLength > BUFFER_SIZE) formatLength = BUFFER_SIZE; new->_defaultFormat = CFStringCreateWithCharacters (alloc, format, formatLength); new->_format = CFRetain (new->_defaultFormat); } return new; } void CFDateFormatterSetFormat (CFDateFormatterRef fmt, CFStringRef formatString) { if (formatString != fmt->_format) CFRelease (fmt->_format); fmt->_format = CFRetain (formatString); } void CFDateFormatterSetProperty (CFDateFormatterRef fmt, CFStringRef key, CFTypeRef value) { CFIndex idx; for (idx = 0 ; idx < _kCFDateFormatterPropertiesCount ; ++idx) { if (key == *(_kCFDateFormatterProperties[idx].prop)) { (_kCFDateFormatterProperties[idx].set)(fmt, _kCFDateFormatterProperties[idx].icuProp, value); return; } } for (idx = 0 ; idx < _kCFDateFormatterPropertiesCount ; ++idx) { if (CFEqual(key, *(_kCFDateFormatterProperties[idx].prop))) { (_kCFDateFormatterProperties[idx].set)(fmt, _kCFDateFormatterProperties[idx].icuProp, value); return; } } } CFDateRef CFDateFormatterCreateDateFromString (CFAllocatorRef alloc, CFDateFormatterRef fmt, CFStringRef string, CFRange *rangep) { CFAbsoluteTime at; if (CFDateFormatterGetAbsoluteTimeFromString (fmt, string, rangep, &at)) return CFDateCreate (alloc, at); return NULL; } Boolean CFDateFormatterGetAbsoluteTimeFromString (CFDateFormatterRef fmt, CFStringRef string, CFRange *rangep, CFAbsoluteTime *atp) { UDate udate; UniChar text[BUFFER_SIZE]; CFRange range; UErrorCode err = U_ZERO_ERROR; int32_t pPos = 0; CFDateFormatterSetup (fmt); if (rangep) range = *rangep; else range = CFRangeMake (0, CFStringGetLength(string)); CFStringGetCharacters (string, range, text); udate = udat_parse (fmt->_fmt, text, range.length, &pPos, &err); if (U_FAILURE(err)) return false; if (rangep) rangep->length = pPos; if (atp) *atp = UDATE_TO_ABSOLUTETIME(udate); return true; } CFStringRef CFDateFormatterCreateStringWithAbsoluteTime (CFAllocatorRef alloc, CFDateFormatterRef fmt, CFAbsoluteTime at) { CFStringRef result; CFIndex length; UniChar string[BUFFER_SIZE]; UDate udate = ABSOLUTETIME_TO_UDATE(at); UErrorCode err = U_ZERO_ERROR; CFDateFormatterSetup (fmt); length = udat_format (fmt->_fmt, udate, string, BUFFER_SIZE, NULL, &err); if (length > BUFFER_SIZE) length = BUFFER_SIZE; if (U_FAILURE(err)) return NULL; result = CFStringCreateWithCharacters (alloc, string, length); return result; } CFStringRef CFDateFormatterCreateStringWithDate (CFAllocatorRef alloc, CFDateFormatterRef fmt, CFDateRef date) { CFAbsoluteTime at = CFDateGetAbsoluteTime (date); return CFDateFormatterCreateStringWithAbsoluteTime (alloc, fmt, at); } CFStringRef CFDateFormatterCreateDateFormatFromTemplate (CFAllocatorRef alloc, CFStringRef templ, CFOptionFlags options, CFLocaleRef loc) { const char *cLocale; char buffer[ULOC_FULLNAME_CAPACITY]; UniChar pat[BUFFER_SIZE]; UniChar skel[BUFFER_SIZE]; CFIndex patLen; CFIndex skelLen; UDateTimePatternGenerator *datpg; UErrorCode err = U_ZERO_ERROR; cLocale = CFLocaleGetCStringIdentifier (loc, buffer, ULOC_FULLNAME_CAPACITY); datpg = udatpg_open (cLocale, &err); if (U_FAILURE(err)) return NULL; if ((patLen = CFStringGetLength(templ)) > BUFFER_SIZE) patLen = BUFFER_SIZE; CFStringGetCharacters(templ, CFRangeMake(0, patLen), pat); skelLen = udatpg_getSkeleton (datpg, pat, patLen, skel, BUFFER_SIZE, &err); if (U_FAILURE(err)) return NULL; patLen = udatpg_getBestPattern (datpg, skel, skelLen, pat, BUFFER_SIZE, &err); udatpg_close (datpg); return CFStringCreateWithCharacters (alloc, pat, patLen); } CFTypeRef CFDateFormatterCopyProperty (CFDateFormatterRef fmt, CFStringRef key) { CFIndex idx; for (idx = 0 ; idx < _kCFDateFormatterPropertiesCount ; ++idx) { if (key == *(_kCFDateFormatterProperties[idx].prop)) return (_kCFDateFormatterProperties[idx].copy)(fmt, _kCFDateFormatterProperties[idx].icuProp); } for (idx = 0 ; idx < _kCFDateFormatterPropertiesCount ; ++idx) { if (CFEqual(key, *(_kCFDateFormatterProperties[idx].prop))) return (_kCFDateFormatterProperties[idx].copy)(fmt, _kCFDateFormatterProperties[idx].icuProp); } return NULL; } CFDateFormatterStyle CFDateFormatterGetDateStyle (CFDateFormatterRef fmt) { return fmt->_dateStyle; } CFStringRef CFDateFormatterGetFormat (CFDateFormatterRef fmt) { return fmt->_format; } CFLocaleRef CFDateFormatterGetLocale (CFDateFormatterRef fmt) { return fmt->_locale; } CFDateFormatterStyle CFDateFormatterGetTimeStyle (CFDateFormatterRef fmt) { return fmt->_timeStyle; } CFTypeID CFDateFormatterGetTypeID (void) { return _kCFDateFormatterTypeID; } gnustep-corebase-0.2/Source/CFSocket.c0000644000175000017500000005433214551015633016762 0ustar yavoryavor/* CFSocket.c Copyright (C) 2012 Free Software Foundation, Inc. Author: Stefan Bidigaray Date: September, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFData.h" #include "CoreFoundation/CFDate.h" #include "CoreFoundation/CFRunLoop.h" #include "CoreFoundation/CFSocket.h" #include "GSPrivate.h" #if HAVE_LIBDISPATCH # include #endif #include #include #if defined(_WIN32) #include #ifdef HAVE_WS2TCPIP_H #include #else typedef int socklen_t; #endif #ifndef EINPROGRESS #define EINPROGRESS WSAEINPROGRESS #endif CF_INLINE int CFSocketGetLastError (void) { return WSAGetLastError (); } #else #include #include #include #include #include #include #include #ifndef INVALID_SOCKET #define INVALID_SOCKET (-1) #endif #define closesocket(x) close(x) CF_INLINE int CFSocketGetLastError (void) { return errno; } #endif struct __CFSocket { CFRuntimeBase parent; GSMutex _lock; CFSocketNativeHandle _socket; CFOptionFlags _opts; CFOptionFlags _cbTypes; CFSocketCallBack _callback; CFSocketContext _ctx; CFDataRef _address; CFDataRef _peerAddress; Boolean _isConnected; Boolean _isListening; CFRunLoopSourceRef _source; #if HAVE_LIBDISPATCH dispatch_source_t _readSource; Boolean _readFired; Boolean _readResumed; dispatch_source_t _writeSource; Boolean _writeFired; Boolean _writeResumed; #endif }; static CFTypeID _kCFSocketTypeID = 0; static CFMutableDictionaryRef _kCFSocketObjects = NULL; static GSMutex _kCFSocketObjectsLock; static void DummyBarrier (void* dummy) { } static void CFSocketFinalize (CFTypeRef cf) { CFSocketRef s = (CFSocketRef)cf; #if HAVE_LIBDISPATCH dispatch_queue_t q = dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_cancel(s->_readSource); dispatch_source_cancel(s->_writeSource); // Wait for source handlers to complete // before we proceed to destruction. dispatch_barrier_sync_f(q, NULL, DummyBarrier); if (s->_source != NULL) CFRelease(s->_source); #endif if (s->_socket != -1) { GSMutexLock (&_kCFSocketObjectsLock); CFDictionaryRemoveValue(_kCFSocketObjects, (void*)(uintptr_t) s->_socket); closesocket (s->_socket); GSMutexUnlock (&_kCFSocketObjectsLock); } if (s->_address) CFRelease (s->_address); if (s->_peerAddress) CFRelease (s->_peerAddress); } static CFRuntimeClass CFSocketClass = { 0, "CFSocket", NULL, NULL, CFSocketFinalize, NULL, NULL, NULL, NULL }; void CFSocketInitialize (void) { _kCFSocketTypeID = _CFRuntimeRegisterClass (&CFSocketClass); GSMutexInitialize (&_kCFSocketObjectsLock); } CFTypeID CFSocketGetTypeID (void) { return _kCFSocketTypeID; } #if HAVE_LIBDISPATCH static void CFSocketDispatchReadEvent(void* p) { CFSocketRef socket = (CFSocketRef) p; CFRunLoopSourceRef src = socket->_source; socket->_readFired = true; if (src != NULL) CFRunLoopSourceSignal(src); } static void CFSocketDispatchWriteEvent(void* p) { CFSocketRef socket = (CFSocketRef) p; CFRunLoopSourceRef src = socket->_source; socket->_writeFired = true; if (src != NULL) CFRunLoopSourceSignal(src); } #endif #define CFSOCKET_SIZE sizeof(struct __CFSocket) - sizeof(CFRuntimeBase) CFSocketRef CFSocketCreateWithNative (CFAllocatorRef alloc, CFSocketNativeHandle sock, CFOptionFlags cbTypes, CFSocketCallBack callback, const CFSocketContext *ctx) { CFSocketRef new = NULL; GSMutexLock (&_kCFSocketObjectsLock); if (_kCFSocketObjects == NULL) { _kCFSocketObjects = CFDictionaryCreateMutable (kCFAllocatorSystemDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks); } if (CFDictionaryGetValueIfPresent (_kCFSocketObjects, (const void*)(uintptr_t)sock, (const void**)&new)) { GSMutexUnlock (&_kCFSocketObjectsLock); CFRetain(new); return new; } if (new == NULL) { new = (CFSocketRef)_CFRuntimeCreateInstance (alloc, _kCFSocketTypeID, CFSOCKET_SIZE, 0); if (new != NULL) { new->_socket = sock; new->_cbTypes = cbTypes; new->_callback = callback; new->_opts = kCFSocketCloseOnInvalidate | kCFSocketAutomaticallyReenableAcceptCallBack | kCFSocketAutomaticallyReenableDataCallBack | kCFSocketAutomaticallyReenableReadCallBack; if (ctx != NULL) { if (ctx->info != NULL) new->_ctx.info = (void*)(ctx->retain ? ctx->retain (ctx->info) : ctx->info); new->_ctx.retain = ctx->retain; new->_ctx.release = ctx->release; new->_ctx.copyDescription = ctx->copyDescription; } CFDictionaryAddValue (_kCFSocketObjects, (const void*)(uintptr_t)sock, new); #if HAVE_LIBDISPATCH dispatch_queue_t q = dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); new->_readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, new->_socket, 0, q); dispatch_set_context(new->_readSource, new); dispatch_source_set_event_handler_f(new->_readSource, CFSocketDispatchReadEvent); new->_writeSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, new->_socket, 0, q); dispatch_set_context(new->_writeSource, new); dispatch_source_set_event_handler_f(new->_writeSource, CFSocketDispatchWriteEvent); #endif } } GSMutexUnlock (&_kCFSocketObjectsLock); return new; } #if defined(_WIN32) static Boolean _kWinsockInitialized = false; #define WINSOCK_MAJOR_VERSION 2 #define WINSOCK_MINOR_VERSION 2 #endif CFSocketRef CFSocketCreate (CFAllocatorRef alloc, SInt32 protocolFamily, SInt32 socketType, SInt32 protocol, CFOptionFlags cbTypes, CFSocketCallBack callback, const CFSocketContext *ctx) { CFSocketRef new = NULL; CFSocketNativeHandle s; #if defined(_WIN32) if (_kWinsockInitialized == false) { WORD winsockVersionRequested; WSADATA winsockData; int winsockErr; _kWinsockInitialized = true; /* High-byte = minor && low-byte = major */ winsockVersionRequested = MAKEWORD(WINSOCK_MAJOR_VERSION, WINSOCK_MINOR_VERSION); winsockErr = WSAStartup (winsockVersionRequested, &winsockData); if (winsockErr != 0) return NULL; if (LOBYTE(winsockData.wVersion) != WINSOCK_MAJOR_VERSION || HIBYTE(winsockData.wVersion) != WINSOCK_MINOR_VERSION) { WSACleanup (); _kWinsockInitialized = false; return NULL; } } #endif s = socket (protocolFamily, socketType, protocol); if (s != INVALID_SOCKET) new = CFSocketCreateWithNative (alloc, s, cbTypes, callback, ctx); return new; } CFSocketRef CFSocketCreateWithSocketSignature (CFAllocatorRef alloc, const CFSocketSignature *sign, CFOptionFlags cbTypes, CFSocketCallBack callback, const CFSocketContext *ctx) { CFSocketRef new; new = CFSocketCreate (alloc, sign->protocolFamily, sign->socketType, sign->protocol, cbTypes, callback, ctx); if (new) { CFSocketError err; err = CFSocketSetAddress (new, sign->address); if (err != kCFSocketSuccess) { CFRelease (new); new = NULL; } } return new; } CFSocketRef CFSocketCreateConnectedToSocketSignature (CFAllocatorRef alloc, const CFSocketSignature *sign, CFOptionFlags cbTypes, CFSocketCallBack callback, const CFSocketContext *ctx, CFTimeInterval timeout) { CFSocketRef new; new = CFSocketCreate (alloc, sign->protocolFamily, sign->socketType, sign->protocol, cbTypes, callback, ctx); if (new) { CFSocketError err; err = CFSocketConnectToAddress (new, sign->address, timeout); if (err != kCFSocketSuccess) { CFRelease (new); new = NULL; } } return new; } CFDataRef CFSocketCopyAddress (CFSocketRef s) { CFDataRef ret = NULL; GSMutexLock (&s->_lock); if (s->_address == NULL) { struct sockaddr addr; socklen_t addrlen; getsockname (s->_socket, &addr, &addrlen); s->_address = CFDataCreate (CFGetAllocator (s), (const UInt8*)&addr, (CFIndex)addrlen); } if (s->_address != NULL) ret = CFRetain (s->_address); GSMutexUnlock (&s->_lock); return ret; } CFDataRef CFSocketCopyPeerAddress (CFSocketRef s) { CFDataRef ret = NULL; GSMutexLock (&s->_lock); if (s->_address == NULL) { struct sockaddr addr; socklen_t addrlen; getpeername (s->_socket, &addr, &addrlen); s->_address = CFDataCreate (CFGetAllocator (s), (const UInt8*)&addr, (CFIndex)addrlen); } if (s->_address != NULL) ret = CFRetain (s->_address); GSMutexUnlock (&s->_lock); return ret; } CFSocketError CFSocketSetAddress (CFSocketRef s, CFDataRef address) { CFSocketNativeHandle sock; struct sockaddr *addr; socklen_t addrlen; int err; if (CFSocketIsValid (s) == false || address == NULL) return kCFSocketError; addr = (struct sockaddr*)CFDataGetBytePtr (address); addrlen = CFDataGetLength (address); if (addr == NULL || addrlen == 0) return kCFSocketError; sock = CFSocketGetNative (s); err = bind (sock, addr, addrlen); if (err == 0) { listen (sock, 1024); s->_isListening = true; return kCFSocketSuccess; } return kCFSocketError; } CFSocketError CFSocketConnectToAddress (CFSocketRef s, CFDataRef address, CFTimeInterval timeout) { CFSocketNativeHandle sock; struct sockaddr *addr; socklen_t addrlen; int err; if (CFSocketIsValid (s) == false || address == NULL) return kCFSocketError; addr = (struct sockaddr*)CFDataGetBytePtr (address); addrlen = CFDataGetLength (address); if (addr == NULL || addrlen == 0) return kCFSocketError; sock = CFSocketGetNative (s); if (timeout < 0.0) { #ifdef _WIN32 unsigned long mode = 1; if (ioctlsocket(sock, FIONBIO, &mode) == SOCKET_ERROR) return kCFSocketError; #else int f; f = fcntl (sock, F_GETFL, 0); f |= O_NONBLOCK; if (fcntl (sock, F_SETFL, f) != 0) return kCFSocketError; #endif } err = connect (sock, addr, addrlen); if (err != 0 && CFSocketGetLastError () == EINPROGRESS) { if (timeout >= 0.0) { struct timeval tv; int count; fd_set writefds[FD_SETSIZE]; tv.tv_sec = (long)floor (timeout); tv.tv_usec = (long)((timeout - floor (timeout)) * 1000000.0); FD_ZERO(writefds); FD_SET(sock, writefds); count = select (sock + 1, NULL, writefds, NULL, &tv); if (count > 0) s->_isConnected = true; else err = -1; } else { err = 0; } } return (err == 0) ? kCFSocketSuccess : kCFSocketError; } void CFSocketGetContext (CFSocketRef s, CFSocketContext *ctx) { *ctx = s->_ctx; } CFSocketNativeHandle CFSocketGetNative (CFSocketRef s) { return s->_socket; } static void CFSocketUpdateDispatchSources (CFSocketRef s) { #if HAVE_LIBDISPATCH # define READ_EVENTS (kCFSocketReadCallBack|kCFSocketAcceptCallBack|kCFSocketDataCallBack) # define WRITE_EVENTS (kCFSocketConnectCallBack|kCFSocketWriteCallBack) if (s->_cbTypes & READ_EVENTS) { if (!s->_readResumed) { dispatch_resume(s->_readSource); s->_readResumed = true; } } else if (s->_readResumed) { dispatch_suspend(s->_readSource); s->_readResumed = false; } if (s->_cbTypes & WRITE_EVENTS) { if (!s->_writeResumed) { dispatch_resume(s->_writeSource); s->_writeResumed = true; } } else if (s->_writeResumed) { dispatch_suspend(s->_writeSource); s->_writeResumed = false; } #endif } void CFSocketDisableCallBacks (CFSocketRef s, CFOptionFlags cbTypes) { s->_cbTypes &= ~cbTypes; CFSocketUpdateDispatchSources(s); } void CFSocketEnableCallBacks (CFSocketRef s, CFOptionFlags cbTypes) { if (s->_isConnected) cbTypes &= ~kCFSocketConnectCallBack; s->_cbTypes |= cbTypes; CFSocketUpdateDispatchSources(s); } CFOptionFlags CFSocketGetSocketFlags (CFSocketRef s) { return s->_opts; } void CFSocketSetSocketFlags (CFSocketRef s, CFOptionFlags flags) { s->_opts = flags; } CFSocketError CFSocketSendData (CFSocketRef s, CFDataRef address, CFDataRef data, CFTimeInterval timeout) { struct sockaddr* addr = NULL; socklen_t len; int err; struct timeval tv; if (CFSocketIsValid (s) == false || address == NULL || data == NULL) return kCFSocketError; tv.tv_sec = (int) floor(timeout); tv.tv_usec = (timeout - tv.tv_sec) * 1000000; err = setsockopt(s->_socket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval)); if (err != 0) return kCFSocketError; if (address != NULL) { addr = (struct sockaddr*) CFDataGetBytePtr(address); len = CFDataGetLength(address); err = sendto(s->_socket, CFDataGetBytePtr(data), 0, CFDataGetLength(data), addr, len); } else { err = send(s->_socket, CFDataGetBytePtr(data), CFDataGetLength(data), 0); } if (err == 0) return kCFSocketSuccess; else if (errno == EAGAIN || errno == EWOULDBLOCK) return kCFSocketTimeout; else return kCFSocketError; } void CFSocketInvalidate (CFSocketRef s) { #if HAVE_LIBDISPATCH if (s->_source != NULL) CFRunLoopSourceInvalidate(s->_source); #endif if (s->_socket != -1 && s->_opts & kCFSocketCloseOnInvalidate) { GSMutexLock (&_kCFSocketObjectsLock); CFDictionaryRemoveValue(_kCFSocketObjects, (void*)(uintptr_t) s->_socket); GSMutexUnlock (&_kCFSocketObjectsLock); closesocket (s->_socket); s->_socket = -1; } } Boolean CFSocketIsValid (CFSocketRef s) { if (s->_source != NULL) return CFRunLoopSourceIsValid(s->_source); // !kCFSocketCloseOnInvalidate case return s->_socket != -1; } #if HAVE_LIBDISPATCH static void CFSocketRLSSchedule (void* p, CFRunLoopRef rl, CFStringRef mode) { CFSocketRef s = (CFSocketRef) p; CFSocketUpdateDispatchSources(s); } static void CFSocketRLSPerform (void* p) { CFSocketRef s = (CFSocketRef) p; if (s->_callback == NULL) return; if (s->_readFired) { if (s->_isListening) { if (s->_cbTypes & kCFSocketAcceptCallBack) { struct sockaddr addr; socklen_t len = sizeof(addr); int err; err = accept (s->_socket, &addr, &len); if (!(s->_opts & kCFSocketAutomaticallyReenableAcceptCallBack)) CFSocketDisableCallBacks(s, kCFSocketAcceptCallBack); if (err != 0) { CFSocketNativeHandle handle = (CFSocketNativeHandle) err; CFDataRef addrData; addrData = CFDataCreate(NULL, (UInt8*) &addr, len); s->_callback(s, kCFSocketAcceptCallBack, addrData, &handle, s->_ctx.info); CFRelease(addrData); } } } if (s->_cbTypes & kCFSocketDataCallBack) { char buffer[512]; int err; CFDataRef data, addrData; struct sockaddr addr; socklen_t len = sizeof(addr); if (!(s->_opts & kCFSocketAutomaticallyReenableDataCallBack)) CFSocketDisableCallBacks(s, kCFSocketDataCallBack); err = recvfrom (s->_socket, buffer, sizeof(buffer), MSG_DONTWAIT, &addr, &len); if (err < 0) err = 0; data = CFDataCreate(NULL, (UInt8*) buffer, err); addrData = CFDataCreate(NULL, (UInt8*) &addr, len); s->_callback(s, kCFSocketDataCallBack, addrData, data, s->_ctx.info); CFRelease(data); CFRelease(addrData); } else if (s->_cbTypes & kCFSocketReadCallBack) { if (!(s->_opts & kCFSocketAutomaticallyReenableReadCallBack)) CFSocketDisableCallBacks(s, kCFSocketReadCallBack); s->_callback(s, kCFSocketReadCallBack, NULL, NULL, s->_ctx.info); } s->_readFired = false; } if (s->_writeFired) { if (!s->_isConnected && s->_cbTypes & kCFSocketConnectCallBack) { SInt32 err; socklen_t len = sizeof(err); int rv = getsockopt(s->_socket, SOL_SOCKET, SO_ERROR, &err, &len); if (rv == -1) err = errno; void* data; if (err != 0) data = &err; else data = NULL; s->_callback(s, kCFSocketConnectCallBack, NULL, data, s->_ctx.info); } else { s->_isConnected = true; if (!(s->_opts & kCFSocketAutomaticallyReenableWriteCallBack)) CFSocketDisableCallBacks(s, kCFSocketWriteCallBack); if (!(s->_opts & kCFSocketLeaveErrors)) { // Clear out last error SInt32 err; socklen_t len = sizeof(err); getsockopt(s->_socket, SOL_SOCKET, SO_ERROR, &err, &len); } s->_callback(s, kCFSocketWriteCallBack, NULL, NULL, s->_ctx.info); } s->_writeFired = false; } } static void CFSocketRLSCancel (void* p, CFRunLoopRef rl, CFStringRef mode) { } #endif CFRunLoopSourceRef CFSocketCreateRunLoopSource (CFAllocatorRef alloc, CFSocketRef s, CFIndex order) { #if HAVE_LIBDISPATCH CFRunLoopSourceRef source; CFRunLoopSourceContext context; if (s->_source != NULL) return (CFRunLoopSourceRef) CFRetain(s->_source); memset(&context, 0, sizeof(context)); context.info = s; context.retain = CFRetain; context.release = CFRelease; context.schedule = CFSocketRLSSchedule; context.cancel = CFSocketRLSCancel; context.perform = CFSocketRLSPerform; source = CFRunLoopSourceCreate(CFGetAllocator(s), order, &context); s->_source = (CFRunLoopSourceRef) CFRetain(source); return source; #else fprintf(stderr, "CFSocketCreateRunLoopSource(): dummy implementation, " "GCD support not enabled\n"); return NULL; #endif } /* "Name server functionality is currently inoperable in OS X." */ CFSocketError CFSocketCopyRegisteredSocketSignature (const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name, CFSocketSignature *sign, CFDataRef *nameServerAddress) { return kCFSocketError; } CFSocketError CFSocketCopyRegisteredValue (const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name, CFPropertyListRef *value, CFDataRef *nameServerAddress) { return kCFSocketError; } UInt16 CFSocketGetDefaultNameRegistryPortNumber (void) { return 0; } CFSocketError CFSocketRegisterSocketSignature (const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name, const CFSocketSignature *sign) { return kCFSocketError; } CFSocketError CFSocketRegisterValue (const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name, CFPropertyListRef value) { return kCFSocketError; } void CFSocketSetDefaultNameRegistryPortNumber (UInt16 port) { return; } CFSocketError CFSocketUnregister (const CFSocketSignature *nameServerSignature, CFTimeInterval timeout, CFStringRef name) { return kCFSocketError; } gnustep-corebase-0.2/Source/tzfile.h0000644000175000017500000001071213222706330016610 0ustar yavoryavor#ifndef TZFILE_H #define TZFILE_H /* ** This file is in the public domain, so clarified as of ** 1996-06-05 by Arthur David Olson. */ /* ** This header is for use ONLY with the time conversion code. ** There is no guarantee that it will remain unchanged, ** or that it will remain at all. ** Do NOT copy it to any system include directory. ** Thank you! */ /* ** Each file begins with. . . */ #define TZ_MAGIC "TZif" struct tzhead { UInt8 tzh_magic[4]; /* TZ_MAGIC */ UInt8 tzh_version[1]; /* '\0' or '2' as of 2005 */ UInt8 tzh_reserved[15]; /* reserved--must be zero */ UInt8 tzh_ttisgmtcnt[4]; /* coded number of trans. time flags */ UInt8 tzh_ttisstdcnt[4]; /* coded number of trans. time flags */ UInt8 tzh_leapcnt[4]; /* coded number of leap seconds */ UInt8 tzh_timecnt[4]; /* coded number of transition times */ UInt8 tzh_typecnt[4]; /* coded number of local time types */ UInt8 tzh_charcnt[4]; /* coded number of abbr. chars */ }; /* ** . . .followed by. . . ** ** tzh_timecnt (char [4])s coded transition times a la time(2) ** tzh_timecnt (unsigned char)s types of local time starting at above ** tzh_typecnt repetitions of ** one (char [4]) coded UTC offset in seconds ** one (unsigned char) used to set tm_isdst ** one (unsigned char) that's an abbreviation list index ** tzh_charcnt (char)s '\0'-terminated zone abbreviations ** tzh_leapcnt repetitions of ** one (char [4]) coded leap second transition times ** one (char [4]) total correction after above ** tzh_ttisstdcnt (char)s indexed by type; if TRUE, transition ** time is standard time, if FALSE, ** transition time is wall clock time ** if absent, transition times are ** assumed to be wall clock time ** tzh_ttisgmtcnt (char)s indexed by type; if TRUE, transition ** time is UTC, if FALSE, ** transition time is local time ** if absent, transition times are ** assumed to be local time */ /* ** If tzh_version is '2' or greater, the above is followed by a second instance ** of tzhead and a second instance of the data in which each coded transition ** time uses 8 rather than 4 chars, ** then a POSIX-TZ-environment-variable-style string for use in handling ** instants after the last transition time stored in the file ** (with nothing between the newlines if there is no POSIX representation for ** such instants). */ /* ** In the current implementation, "tzset()" refuses to deal with files that ** exceed any of the limits below. */ #ifndef TZ_MAX_TIMES #define TZ_MAX_TIMES 1200 #endif /* !defined TZ_MAX_TIMES */ #ifndef TZ_MAX_TYPES #ifndef NOSOLAR #define TZ_MAX_TYPES 256 /* Limited by what (unsigned char)'s can hold */ #endif /* !defined NOSOLAR */ #ifdef NOSOLAR /* ** Must be at least 14 for Europe/Riga as of Jan 12 1995, ** as noted by Earl Chew. */ #define TZ_MAX_TYPES 20 /* Maximum number of local time types */ #endif /* !defined NOSOLAR */ #endif /* !defined TZ_MAX_TYPES */ #ifndef TZ_MAX_CHARS #define TZ_MAX_CHARS 50 /* Maximum number of abbreviation characters */ /* (limited by what unsigned chars can hold) */ #endif /* !defined TZ_MAX_CHARS */ #ifndef TZ_MAX_LEAPS #define TZ_MAX_LEAPS 50 /* Maximum number of leap second corrections */ #endif /* !defined TZ_MAX_LEAPS */ #define SECSPERMIN 60 #define MINSPERHOUR 60 #define HOURSPERDAY 24 #define DAYSPERWEEK 7 #define DAYSPERNYEAR 365 #define DAYSPERLYEAR 366 #define SECSPERHOUR (SECSPERMIN * MINSPERHOUR) #define SECSPERDAY ((long) SECSPERHOUR * HOURSPERDAY) #define MONSPERYEAR 12 #define TM_SUNDAY 0 #define TM_MONDAY 1 #define TM_TUESDAY 2 #define TM_WEDNESDAY 3 #define TM_THURSDAY 4 #define TM_FRIDAY 5 #define TM_SATURDAY 6 #define TM_JANUARY 0 #define TM_FEBRUARY 1 #define TM_MARCH 2 #define TM_APRIL 3 #define TM_MAY 4 #define TM_JUNE 5 #define TM_JULY 6 #define TM_AUGUST 7 #define TM_SEPTEMBER 8 #define TM_OCTOBER 9 #define TM_NOVEMBER 10 #define TM_DECEMBER 11 #define TM_YEAR_BASE 1900 #define EPOCH_YEAR 1970 #define EPOCH_WDAY TM_THURSDAY #define isleap(y) (((y) % 4) == 0 && (((y) % 100) != 0 || ((y) % 400) == 0)) /* ** Since everything in isleap is modulo 400 (or a factor of 400), we know that ** isleap(y) == isleap(y % 400) ** and so ** isleap(a + b) == isleap((a + b) % 400) ** or ** isleap(a + b) == isleap(a % 400 + b % 400) ** This is true even if % means modulo rather than Fortran remainder ** (which is allowed by C89 but not C99). ** We use this to avoid addition overflow problems. */ #define isleap_sum(a, b) isleap((a) % 400 + (b) % 400) #endif /* !defined TZFILE_H */ gnustep-corebase-0.2/Source/GSHashTable.h0000644000175000017500000001152613222706330017404 0ustar yavoryavor/* GSHashTable.h Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: November, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSHASHTABLE__ #define __GSHASHTABLE__ 1 #include "CoreFoundation/CFBase.h" #include "GSPrivate.h" typedef CFStringRef (*GSHashTableCopyDescriptionCallBack) (const void *value); typedef Boolean (*GSHashTableEqualCallBack) (const void *value1, const void *value2); typedef CFHashCode (*GSHashTableHashCallBack) (const void *value); typedef void (*GSHashTableReleaseCallBack) (CFAllocatorRef allocator, const void *value); typedef const void *(*GSHashTableRetainCallBack) (CFAllocatorRef allocator, const void *value); typedef struct GSHashTableKeyCallBacks GSHashTableKeyCallBacks; struct GSHashTableKeyCallBacks { CFIndex version; GSHashTableRetainCallBack retain; GSHashTableReleaseCallBack release; GSHashTableRetainCallBack copyDescrition; GSHashTableEqualCallBack equal; GSHashTableHashCallBack hash; }; typedef struct GSHashTableValueCallBacks GSHashTableValueCallBacks; struct GSHashTableValueCallBacks { CFIndex version; GSHashTableRetainCallBack retain; GSHashTableReleaseCallBack release; GSHashTableRetainCallBack copyDescrition; GSHashTableEqualCallBack equal; }; typedef struct GSHashTableBucket GSHashTableBucket; struct GSHashTableBucket { CFIndex count; const void *key; const void *value; }; typedef struct GSHashTable *GSHashTableRef; struct GSHashTable { CFRuntimeBase _parent; CFAllocatorRef _allocator; CFIndex _capacity; CFIndex _count; CFIndex _total; /* Used for CFBagGetCount() */ GSHashTableKeyCallBacks _keyCallBacks; GSHashTableValueCallBacks _valueCallBacks; struct GSHashTableBucket *_buckets; }; GS_PRIVATE void GSHashTableFinalize (GSHashTableRef table); GS_PRIVATE Boolean GSHashTableEqual (GSHashTableRef table1, GSHashTableRef table2); GS_PRIVATE CFHashCode GSHashTableHash (GSHashTableRef table); GS_PRIVATE GSHashTableRef GSHashTableCreate (CFAllocatorRef alloc, CFTypeID typeID, const void **keys, const void **values, CFIndex count, const GSHashTableKeyCallBacks * keyCallBacks, const GSHashTableValueCallBacks * valueCallBacks); GS_PRIVATE GSHashTableRef GSHashTableCreateCopy (CFAllocatorRef alloc, GSHashTableRef table); GS_PRIVATE Boolean GSHashTableContainsKey (GSHashTableRef table, const void *key); GS_PRIVATE Boolean GSHashTableContainsValue (GSHashTableRef table, const void *value); GS_PRIVATE CFIndex GSHashTableGetCount (GSHashTableRef table); GS_PRIVATE CFIndex GSHashTableGetCountOfKey (GSHashTableRef table, const void *key); GS_PRIVATE CFIndex GSHashTableGetCountOfValue (GSHashTableRef table, const void *value); GS_PRIVATE void GSHashTableGetKeysAndValues (GSHashTableRef table, const void **keys, const void **values); GS_PRIVATE const void *GSHashTableGetValue (GSHashTableRef table, const void *key); GS_PRIVATE GSHashTableRef GSHashTableCreateMutable (CFAllocatorRef allocator, CFTypeID typeID, CFIndex capacity, const GSHashTableKeyCallBacks * keyCallBacks, const GSHashTableValueCallBacks * valueCallBacks); GS_PRIVATE GSHashTableRef GSHashTableCreateMutableCopy (CFAllocatorRef alloc, GSHashTableRef table, CFIndex capacity); GS_PRIVATE void GSHashTableAddValue (GSHashTableRef table, const void *key, const void *value); GS_PRIVATE void GSHashTableReplaceValue (GSHashTableRef table, const void *key, const void *value); GS_PRIVATE void GSHashTableSetValue (GSHashTableRef table, const void *key, const void *value); GS_PRIVATE void GSHashTableRemoveAll (GSHashTableRef table); GS_PRIVATE void GSHashTableRemoveValue (GSHashTableRef table, const void *key); #endif /* __GSHASHTABLE__ */ gnustep-corebase-0.2/Source/GSObjCRuntime.h0000644000175000017500000000776213222706330017741 0ustar yavoryavor/* GSObjCRuntime.h Copyright (C) 2013 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: July, 2013 This file is part of GNUstep CoreBase library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSOBJCRUNTIME_H__ #define __GSOBJCRUNTIME_H__ #include "config.h" #include "CoreFoundation/CFBase.h" #include "GSPrivate.h" GS_PRIVATE const void *CFTypeRetainCallBack (CFAllocatorRef alloc, const void *value); GS_PRIVATE void CFTypeReleaseCallBack (CFAllocatorRef alloc, const void *value); #if HAVE_OBJC_RUNTIME_H #define BOOL OBJC_BOOL #include #undef BOOL extern void **__CFRuntimeObjCClassTable; extern UInt32 __CFRuntimeClassTableCount; CF_INLINE void * __CFISAForTypeID (CFTypeID typeID) { return (__CFRuntimeObjCClassTable && typeID < __CFRuntimeClassTableCount ? __CFRuntimeObjCClassTable[typeID] : NULL); } CF_INLINE Boolean CF_IS_OBJC (CFTypeID typeID, const void *obj) { #if defined(OBJC_SMALL_OBJECT_MASK) return (obj && (((unsigned long)obj & OBJC_SMALL_OBJECT_MASK) != 0 || typeID >= __CFRuntimeClassTableCount || object_getClass ((id) obj) != __CFISAForTypeID (typeID))); #else return (obj && (typeID >= __CFRuntimeClassTableCount || object_getClass ((id) obj) != __CFISAForTypeID (typeID))); #endif } #define CF_OBJC_FUNCDISPATCHV(typeID, rettype, obj, sel, ...) \ do { \ if (CF_IS_OBJC(typeID, obj)) \ { \ rettype (*imp)(id, SEL, ...); \ static SEL s = NULL; \ if (!s) \ s = sel_registerName(sel); \ imp = (rettype (*)(id, SEL, ...)) \ class_getMethodImplementation (object_getClass((id)obj), s); \ return (rettype)imp((id)obj, s, ##__VA_ARGS__); \ } \ } while(0) #define CF_OBJC_FUNCDISPATCHV_RETAINED(typeID, rettype, obj, sel, ...) \ do { \ if (CF_IS_OBJC(typeID, obj)) \ { \ rettype (*imp)(id, SEL, ...); \ static SEL s = NULL; \ if (!s) \ s = sel_registerName(sel); \ imp = (rettype (*)(id, SEL, ...)) \ class_getMethodImplementation (object_getClass((id)obj), s); \ rettype val = imp((id)obj, s, ##__VA_ARGS__); \ if (val != NULL) CFRetain(val); \ return val; \ } \ } while(0) #define CF_OBJC_CALLV(rettype, var, obj, sel, ...) \ do { \ rettype (*imp)(id, SEL, ...); \ static SEL s = NULL; \ if (!s) \ s = sel_registerName(sel); \ imp = (rettype (*)(id, SEL, ...)) \ class_getMethodImplementation (object_getClass((id)obj), s); \ var = imp((id)obj, s, ##__VA_ARGS__); \ } while (0) #define CF_OBJC_VOIDCALLV(obj, sel, ...) \ do { \ void (*imp)(id, SEL, ...); \ static SEL s = NULL; \ if (!s) \ s = sel_registerName(sel); \ imp = (void (*)(id, SEL, ...)) \ class_getMethodImplementation (object_getClass((id)obj), s); \ imp((id)obj, s, ##__VA_ARGS__); \ } while (0) #else #define __CFISAForTypeID(typeID) (NULL) #define CF_IS_OBJC(typeID, obj) (0) #define CF_OBJC_FUNCDISPATCHV(typeID, rettype, obj, sel, ...) #define CF_OBJC_FUNCDISPATCHV_RETAINED(typeID, rettype, obj, sel, ...) #define CF_OBJC_CALLV(rettype, var, obj, sel, ...) #define CF_OBJC_VOIDCALLV(obj, sel, ...) #endif /* HAVE_OBJC_RUNTIME_H */ #endif /* __GSOBJCRUNTIME_H__ */ gnustep-corebase-0.2/Source/NSCFType.h0000644000175000017500000000360413222706330016710 0ustar yavoryavor/* NSCFType.h Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: September, 2011 This file is part of GNUstep CoreBase library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __NSCFTYPE_H__ #define __NSCFTYPE_H__ #import #import #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFRuntime.h" extern void **__CFRuntimeObjCClassTable; void NSCFInitialize (void); CF_INLINE void CFRuntimeBridgeClass (CFTypeID typeID, const char *cls) { __CFRuntimeObjCClassTable[typeID] = (Class)objc_getClass (cls); } CF_INLINE void CFRuntimeSetInstanceISA (CFTypeRef cf, Class cls) { ((CFRuntimeBase *)cf)->_isa = cls; } /* This is NSCFType, the ObjC class that all non-bridged CF types belong to. */ #define NSCFTYPE_VARS { \ /* NSCFType's ivar layout must match CFRuntimeBase. */ \ int16_t _typeID; \ struct \ { \ int16_t ro: 1; \ int16_t unused: 7; \ int16_t reserved: 8; \ } _flags; \ } @interface NSCFType : NSObject NSCFTYPE_VARS - (CFTypeID) _cfTypeID; @end #endif /* __NSCFTYPE_H__ */ gnustep-corebase-0.2/Source/CFRuntime.c0000644000175000017500000003262414551015633017155 0ustar yavoryavor/* CFRuntime.c Copyright (C) 2010-2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFString.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" #include #include #include #include #if HAVE_OBJC_RUNTIME_H #include #endif /* GC stuff... */ Boolean kCFUseCollectableAllocator = false; Boolean (*__CFObjCIsCollectable) (void *) = NULL; /* CFRuntimeClass Table */ CFRuntimeClass **__CFRuntimeClassTable = NULL; void **__CFRuntimeObjCClassTable = NULL; UInt32 __CFRuntimeClassTableCount = 0; UInt32 __CFRuntimeClassTableSize = 1024; /* Initial size */ static GSMutex _kCFRuntimeTableLock; void *NSCFTypeClass = NULL; /******************************/ /* Object header... lifted from base's NSObject.m */ #ifdef ALIGN #undef ALIGN #endif #define ALIGN __alignof__(double) /* * Define a structure to hold information that is held locally * (before the start) in each object. */ struct obj_layout_unpadded { CFAllocatorRef allocator; CFIndex retained; }; #define UNP sizeof(struct obj_layout_unpadded) /* * Now do the REAL version - using the other version to determine * what padding (if any) is required to get the alignment of the * structure correct. */ struct obj_layout { #if !defined(_MSC_VER) char padding[ALIGN - ((UNP % ALIGN) ? (UNP % ALIGN) : ALIGN)]; #endif CFAllocatorRef allocator; CFIndex retained; }; typedef struct obj_layout *obj; /******************************/ /* CFNotATypeClass declaration for index 0 of the class table. */ static CFRuntimeClass CFNotATypeClass = { 0, /* Version */ "CFNotATypeClass", /* Class name */ NULL, NULL, NULL, NULL, NULL, NULL, NULL }; CFTypeID _CFRuntimeRegisterClass (const CFRuntimeClass * const cls) { CFTypeID ret; GSMutexLock (&_kCFRuntimeTableLock); if (__CFRuntimeClassTableCount >= __CFRuntimeClassTableSize) { GSMutexUnlock (&_kCFRuntimeTableLock); return _kCFRuntimeNotATypeID; } __CFRuntimeClassTable[__CFRuntimeClassTableCount] = (CFRuntimeClass *) cls; if (__CFRuntimeObjCClassTable) __CFRuntimeObjCClassTable[__CFRuntimeClassTableCount] = NSCFTypeClass; ret = __CFRuntimeClassTableCount++; GSMutexUnlock (&_kCFRuntimeTableLock); return ret; } const CFRuntimeClass * _CFRuntimeGetClassWithTypeID (CFTypeID typeID) { GSMutexLock (&_kCFRuntimeTableLock); if (typeID > __CFRuntimeClassTableCount) typeID = 0; GSMutexUnlock (&_kCFRuntimeTableLock); return __CFRuntimeClassTable[typeID]; } void _CFRuntimeUnregisterClassWithTypeID (CFTypeID typeID) { GSMutexLock (&_kCFRuntimeTableLock); __CFRuntimeClassTable[typeID] = NULL; GSMutexUnlock (&_kCFRuntimeTableLock); } CFTypeRef _CFRuntimeCreateInstance (CFAllocatorRef allocator, CFTypeID typeID, CFIndex extraBytes, unsigned char *category) { /* category is not used and should be NULL. */ CFIndex instSize; CFRuntimeClass *cls; CFRuntimeBase *new; /* Return NULL if typeID is unknown. */ if (_kCFRuntimeNotATypeID == typeID || typeID > __CFRuntimeClassTableCount) { return NULL; } if (NULL == allocator) allocator = CFAllocatorGetDefault (); instSize = sizeof (struct obj_layout) + sizeof (CFRuntimeBase) + extraBytes; new = (CFRuntimeBase *) CFAllocatorAllocate (allocator, instSize, 0); if (new) { new = memset (new, 0, instSize); ((obj) new)->allocator = allocator; new = (CFRuntimeBase *) & ((obj) new)[1]; new->_isa = __CFRuntimeObjCClassTable ? __CFRuntimeObjCClassTable[typeID] : NULL; new->_typeID = typeID; cls = __CFRuntimeClassTable[typeID]; if (NULL != cls->init) { /* Init instance... */ cls->init (new); } } return new; } void _CFRuntimeSetInstanceTypeID (CFTypeRef cf, CFTypeID typeID) { ((CFRuntimeBase *) cf)->_typeID = typeID; } void _CFRuntimeInitStaticInstance (void *memory, CFTypeID typeID) { CFRuntimeClass *cls; CFRuntimeBase *obj = (CFRuntimeBase *) memory; if (_kCFRuntimeNotATypeID == typeID || typeID >= __CFRuntimeClassTableCount || NULL == memory) { return; } cls = __CFRuntimeClassTable[typeID]; obj->_isa = __CFISAForTypeID (typeID); obj->_flags.ro = 1; obj->_flags.reserved = 0; obj->_flags.info = 0; obj->_typeID = typeID; if (cls->init != NULL) { /* Init instance... */ cls->init (memory); } } CFStringRef CFCopyDescription (CFTypeRef cf) { CFRuntimeClass *cfclass; CFTypeID typeID; if (NULL == cf) return NULL; typeID = CFGetTypeID (cf); CF_OBJC_FUNCDISPATCHV (typeID, CFStringRef, cf, "description"); if (_kCFRuntimeNotATypeID == typeID) return NULL; cfclass = __CFRuntimeClassTable[typeID]; if (NULL != cfclass->copyFormattingDesc) { return cfclass->copyFormattingDesc (cf, NULL); } else { return CFStringCreateWithFormat (NULL, NULL, CFSTR ("<%s: %p>"), cfclass->className, cf); } return NULL; } CFStringRef CFCopyTypeIDDescription (CFTypeID typeID) { CFRuntimeClass *cfclass; if (_kCFRuntimeNotATypeID == typeID || typeID >= __CFRuntimeClassTableCount) return NULL; cfclass = __CFRuntimeClassTable[typeID]; return __CFStringMakeConstantString (cfclass->className); } Boolean CFEqual (CFTypeRef cf1, CFTypeRef cf2) { CFRuntimeClass *cls; CFTypeID tID1, tID2; if (cf1 == cf2) return true; if (cf1 == NULL || cf2 == NULL) return false; /* Can't compare here if either objects are ObjC objects. */ CF_OBJC_FUNCDISPATCHV (CFGetTypeID (cf1), Boolean, cf1, "isEqual:", cf2); CF_OBJC_FUNCDISPATCHV (CFGetTypeID (cf2), Boolean, cf2, "isEqual:", cf1); tID1 = CFGetTypeID (cf1); tID2 = CFGetTypeID (cf2); if (tID1 != tID2) return false; cls = __CFRuntimeClassTable[tID1]; if (NULL != cls->equal) return cls->equal (cf1, cf2); return false; } CFAllocatorRef CFGetAllocator (CFTypeRef cf) { if (CF_IS_OBJC (CFGetTypeID (cf), cf) || ((CFRuntimeBase *) cf)->_flags.ro) return kCFAllocatorSystemDefault; return ((obj) cf)[-1].allocator; } CFIndex CFGetRetainCount (CFTypeRef cf) { CF_OBJC_FUNCDISPATCHV (CFGetTypeID (cf), CFIndex, cf, "retainCount"); if (!((CFRuntimeBase *) cf)->_flags.ro) return ((obj) cf)[-1].retained + 1; return UINT_MAX; } CFTypeID CFGetTypeID (CFTypeRef cf) { if (cf == NULL) return _kCFRuntimeNotATypeID; #if defined(OBJC_SMALL_OBJECT_MASK) CFTypeID typeID = _kCFRuntimeNotATypeID; /* Small objects in ObjC are not valid pointers, hence we must avoid accessing them. */ if (((uintptr_t) cf & OBJC_SMALL_OBJECT_MASK) == 0) typeID = ((CFRuntimeBase *) cf)->_typeID; CF_OBJC_FUNCDISPATCHV (typeID, CFTypeID, cf, "_cfTypeID"); #endif return ((CFRuntimeBase *) cf)->_typeID; } CFHashCode CFHash (CFTypeRef cf) { CFRuntimeClass *cls; CF_OBJC_FUNCDISPATCHV (CFGetTypeID (cf), CFHashCode, cf, "hash"); cls = __CFRuntimeClassTable[CFGetTypeID (cf)]; if (cls->hash) return cls->hash (cf); return (CFHashCode) ((uintptr_t) cf >> 3); } CFTypeRef CFMakeCollectable (CFTypeRef cf) { /* FIXME */ return cf; } void CFRelease (CFTypeRef cf) { #if defined (OBJC_SMALL_OBJECT_MASK) if (((unsigned long)cf & OBJC_SMALL_OBJECT_MASK) == 0) #endif { CF_OBJC_FUNCDISPATCHV (CFGetTypeID (cf), void, cf, "release"); if (!((CFRuntimeBase *) cf)->_flags.ro) { CFIndex result = GSAtomicDecrementCFIndex (&(((obj) cf)[-1].retained)); if (result < 0) { assert (result == -1); GSRuntimeDeallocateInstance (cf); } } } } CFTypeRef CFRetain (CFTypeRef cf) { #if defined (OBJC_SMALL_OBJECT_MASK) if (((unsigned long)cf & OBJC_SMALL_OBJECT_MASK) == 0) #endif { CF_OBJC_FUNCDISPATCHV (CFGetTypeID (cf), CFTypeRef, cf, "retain"); if (!((CFRuntimeBase *) cf)->_flags.ro) { CFIndex result = GSAtomicIncrementCFIndex (&(((obj) cf)[-1].retained)); assert (result < INT_MAX); } } return cf; } CFTypeRef CFAutorelease (CFTypeRef cf) { #if __has_feature(objc_arc) return objc_autoreleaseReturnValue(cf); #else CF_OBJC_CALLV(CFTypeRef, cf, cf, "autorelease"); return cf; #endif } void * _CFBridgingRelease (CFTypeRef cf) { CF_OBJC_CALLV(CFTypeRef, cf, cf, "autorelease"); return (void *)cf; } CFTypeRef _CFBridgingRetain (void *obj) { CF_OBJC_CALLV(void *, obj, obj, "retain"); return (CFTypeRef)obj; } const void * CFTypeRetainCallBack (CFAllocatorRef allocator, const void *value) { return CFRetain (value); } void CFTypeReleaseCallBack (CFAllocatorRef alloc, const void *value) { CFRelease (value); } void GSRuntimeDeallocateInstance (CFTypeRef cf) { CFRuntimeClass *cls; cls = __CFRuntimeClassTable[CFGetTypeID (cf)]; if (cls->finalize) cls->finalize (cf); CFAllocatorDeallocate (CFGetAllocator (cf), (void *) &((obj) cf)[-1]); } static CFTypeRef GSRuntimeConstantTable[512]; static CFIndex GSRuntimeConstantTableSize = 0; void GSRuntimeConstantInit (CFTypeRef cf, CFTypeID typeID) { ((CFRuntimeBase *) cf)->_typeID = typeID; GSRuntimeConstantTable[GSRuntimeConstantTableSize++] = cf; } void GSRuntimeInitializeConstants (void) { CFIndex i; CFTypeID tid; for (i = 0; i < GSRuntimeConstantTableSize; ++i) { tid = ((CFRuntimeBase *) GSRuntimeConstantTable[i])->_typeID; ((CFRuntimeBase *) GSRuntimeConstantTable[i])->_isa = __CFRuntimeObjCClassTable[tid]; } } GS_PRIVATE void CFAllocatorInitialize (void); GS_PRIVATE void CFArrayInitialize (void); GS_PRIVATE void CFAttributedStringInitialize (void); GS_PRIVATE void CFBagInitialize (void); GS_PRIVATE void CFBinaryHeapInitialize (void); GS_PRIVATE void CFBitVectorInitialize (void); GS_PRIVATE void CFBooleanInitialize (void); GS_PRIVATE void CFCalendarInitialize (void); GS_PRIVATE void CFCharacterSetInitialize (void); GS_PRIVATE void CFDataInitialize (void); GS_PRIVATE void CFBundleInitialize (void); GS_PRIVATE void CFDateInitialize (void); GS_PRIVATE void CFDateFormatterInitialize (void); GS_PRIVATE void CFDictionaryInitialize (void); GS_PRIVATE void CFErrorInitialize (void); GS_PRIVATE void CFLocaleInitialize (void); GS_PRIVATE void CFNullInitialize (void); GS_PRIVATE void CFNumberInitialize (void); GS_PRIVATE void CFNumberFormatterInitialize (void); GS_PRIVATE void CFRunLoopInitialize (void); GS_PRIVATE void CFSetInitialize (void); GS_PRIVATE void CFStreamInitialize (void); GS_PRIVATE void CFStringInitialize (void); GS_PRIVATE void CFConstantStringInitialize (void); GS_PRIVATE void CFStringEncodingInitialize (void); GS_PRIVATE void CFTimeZoneInitialize (void); GS_PRIVATE void CFTreeInitialize (void); GS_PRIVATE void CFURLInitialize (void); GS_PRIVATE void CFUUIDInitialize (void); GS_PRIVATE void CFXMLNodeInitialize (void); #if !defined(_MSC_VER) void CFInitialize (void) __attribute__ ((constructor)); #endif static CFIndex CFInitialized = 0; void CFInitialize (void) { /* Only initialize once. */ if (GSAtomicCompareAndSwapCFIndex (&CFInitialized, 0, 1) == 1) return; /* Initialize CFRuntimeClassTable */ __CFRuntimeClassTable = (CFRuntimeClass **) calloc (__CFRuntimeClassTableSize, sizeof (CFRuntimeClass *)); GSMutexInitialize (&_kCFRuntimeTableLock); /* CFNotATypeClass should be at index = 0 */ _CFRuntimeRegisterClass (&CFNotATypeClass); CFAllocatorInitialize (); CFArrayInitialize (); CFAttributedStringInitialize (); CFBagInitialize (); CFBinaryHeapInitialize (); CFBitVectorInitialize (); CFBooleanInitialize (); CFCalendarInitialize (); CFCharacterSetInitialize (); CFDataInitialize (); CFBundleInitialize (); CFDateInitialize (); CFDateFormatterInitialize (); CFDictionaryInitialize (); CFErrorInitialize (); CFLocaleInitialize (); CFNullInitialize (); CFNumberInitialize (); CFNumberFormatterInitialize (); CFSetInitialize (); CFStreamInitialize (); CFStringInitialize (); CFConstantStringInitialize (); /* must be after CFStringIntialize () */ CFStringEncodingInitialize (); CFTimeZoneInitialize (); CFTreeInitialize (); CFURLInitialize (); CFUUIDInitialize (); CFXMLNodeInitialize (); CFRunLoopInitialize (); } #if defined(_MSC_VER) #include WinBOOL DllMain (HINSTANCE hinst, DWORD fdwReason, LPVOID ldvReserved) { if (fdwReason == DLL_PROCESS_ATTACH) { CFInitialize (); } return TRUE; } #endif gnustep-corebase-0.2/Source/CFAttributedString.c0000644000175000017500000005543313222706330021026 0ustar yavoryavor/* CFAttributedString.c Copyright (C) 2012 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: April, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFAttributedString.h" #include "CoreFoundation/CFBag.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFArray.h" #include "CoreFoundation/CFDictionary.h" #include "CoreFoundation/CFString.h" #include "GSPrivate.h" #include "GSObjCRuntime.h" #include static CFTypeID _kCFAttributedStringTypeID = 0; static CFDictionaryRef _kCFAttributedStringBlankAttribute = NULL; static CFMutableBagRef _kCFAttributedStringCache = NULL; static GSMutex _kCFAttributedStringCacheLock; static GSMutex _kCFAttributedStringBlankAttributeLock; typedef struct { CFIndex index; CFDictionaryRef attrib; } Attr; struct __CFAttributedString { CFRuntimeBase parent; CFStringRef _string; Attr *_attribs; CFIndex _attribCount; }; struct __CFMutableAttributedString { CFRuntimeBase parent; CFMutableStringRef _string; Attr *_attribs; CFIndex _attribCount; CFIndex _attribCap; CFIndex _isEditing; }; enum { _kCFAttributedStringIsInline = (1<<0), _kCFAttributedStringIsMutable = (1<<1) }; CF_INLINE Boolean CFAttributedStringIsInline (CFAttributedStringRef str) { return ((CFRuntimeBase *)str)->_flags.info & _kCFAttributedStringIsInline ? true : false; } CF_INLINE Boolean CFAttributedStringIsMutable (CFAttributedStringRef str) { return ((CFRuntimeBase *)str)->_flags.info & _kCFAttributedStringIsMutable ? true : false; } CF_INLINE void CFAttributedStringSetInline (CFAttributedStringRef str) { ((CFRuntimeBase *)str)->_flags.info |= _kCFAttributedStringIsInline; } CF_INLINE void CFAttributedStringSetMutable (CFAttributedStringRef str) { ((CFRuntimeBase *)str)->_flags.info |= _kCFAttributedStringIsMutable; } static CFDictionaryRef CFAttributedStringCacheAttribute (CFDictionaryRef attribs) { CFDictionaryRef cachedAttr = NULL; GSMutexLock (&_kCFAttributedStringCacheLock); if (_kCFAttributedStringCache == NULL) { _kCFAttributedStringCache = CFBagCreateMutable (kCFAllocatorSystemDefault, 0, &kCFTypeBagCallBacks); } else { cachedAttr = CFBagGetValue (_kCFAttributedStringCache, attribs); } if (cachedAttr == NULL) { CFDictionaryRef insert; insert = CFDictionaryCreateCopy (NULL, attribs); CFBagAddValue (_kCFAttributedStringCache, insert); cachedAttr = insert; CFRelease (insert); } GSMutexUnlock (&_kCFAttributedStringCacheLock); return cachedAttr; } static void CFAttributedStringUncacheAttribute (CFDictionaryRef attribs) { GSMutexLock (&_kCFAttributedStringCacheLock); CFBagRemoveValue (_kCFAttributedStringCache, attribs); GSMutexUnlock (&_kCFAttributedStringCacheLock); } static CFDictionaryRef CFAttributedStringGetBlankAttribute (void) { if (_kCFAttributedStringBlankAttribute == NULL) { GSMutexLock (&_kCFAttributedStringBlankAttributeLock); if (_kCFAttributedStringBlankAttribute == NULL) { _kCFAttributedStringBlankAttribute = CFDictionaryCreate (NULL, NULL, NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); /* Cache the blank attribute in case anyone wants to use it. */ CFAttributedStringCacheAttribute (_kCFAttributedStringBlankAttribute); CFRelease (_kCFAttributedStringBlankAttribute); } GSMutexUnlock (&_kCFAttributedStringBlankAttributeLock); } return CFAttributedStringCacheAttribute (_kCFAttributedStringBlankAttribute); } static CFComparisonResult CFAttributedStringCompareAttribute (const void *v1, const void *v2, void *ctxt) { Attr *attr1 = (Attr*)v1; Attr *attr2 = (Attr*)v2; return attr1->index < attr2->index ? kCFCompareLessThan : (attr1->index == attr2->index ? kCFCompareEqualTo : kCFCompareGreaterThan); } static CFIndex CFAttributedStringArrayGetIndex (CFAttributedStringRef str, CFIndex loc, CFRange *effRange) { /* This function does exactly the same things as * CFAttributedStringGetAttributes() but does not check if str is * an ObjC object and returns an index instead of a CFDictionaryRef. */ CFIndex idx; Attr attr; attr.index = loc; idx = GSBSearch (str->_attribs, &attr, CFRangeMake(0, str->_attribCount), sizeof(Attr), CFAttributedStringCompareAttribute, NULL); if (effRange) { CFIndex start; CFIndex end; start = str->_attribs[idx].index; effRange->location = start; if (idx < str->_attribCount - 1) end = str->_attribs[idx + 1].index; else end = CFStringGetLength(str->_string); effRange->length = end - start; } return idx; } static void CFAttributedStringFinalize (CFTypeRef cf) { CFIndex idx; CFAttributedStringRef str = (CFAttributedStringRef)cf; CFRelease (str->_string); for (idx = 0 ; idx < str->_attribCount ; ++idx) CFAttributedStringUncacheAttribute (str->_attribs[idx].attrib); if (!CFAttributedStringIsInline(str)) CFAllocatorDeallocate (CFGetAllocator(str), str->_attribs); } static Boolean CFAttributedStringEqual (CFTypeRef cf1, CFTypeRef cf2) { CFAttributedStringRef str1 = (CFAttributedStringRef)cf1; CFAttributedStringRef str2 = (CFAttributedStringRef)cf2; if (CFEqual (str1->_string, str2->_string) && str1->_attribCount == str2->_attribCount) { CFIndex idx; for (idx = 0 ; idx < str1->_attribCount ; ++idx) if (!CFEqual (str1->_attribs[idx].attrib, str2->_attribs[idx].attrib)) return false; return true; } return false; } static CFHashCode CFAttributedStringHash (CFTypeRef cf) { CFHashCode hash; CFAttributedStringRef str = (CFAttributedStringRef)cf; hash = CFHash (str->_string); hash += str->_attribCount; return hash; } CFRuntimeClass CFAttributedStringClass = { 0, "CFAttributedString", NULL, (CFTypeRef (*)(CFAllocatorRef, CFTypeRef))CFAttributedStringCreateCopy, CFAttributedStringFinalize, CFAttributedStringEqual, CFAttributedStringHash, NULL, NULL }; void CFAttributedStringInitialize (void) { _kCFAttributedStringTypeID = _CFRuntimeRegisterClass (&CFAttributedStringClass); GSMutexInitialize (&_kCFAttributedStringCacheLock); GSMutexInitialize (&_kCFAttributedStringBlankAttributeLock); } CFTypeID CFAttributedStringGetTypeID (void) { return _kCFAttributedStringTypeID; } #define CFATTRIBUTESTRING_SIZE sizeof(CFRuntimeClass) \ - sizeof(struct __CFAttributedString) static CFAttributedStringRef CFAttributedStringCreateInlined (CFAllocatorRef alloc, CFStringRef str, CFIndex count, Attr *attribs) { struct __CFAttributedString *new; new = (struct __CFAttributedString *)_CFRuntimeCreateInstance (alloc, _kCFAttributedStringTypeID, CFATTRIBUTESTRING_SIZE + (sizeof(Attr) * count), 0); if (new) { CFIndex idx; new->_string = CFStringCreateCopy (alloc, str); new->_attribCount = 1; new->_attribs = (Attr*)&new[1]; for (idx = 0 ; idx < count ; ++idx) { new->_attribs[idx].index = idx; new->_attribs[idx].attrib = CFAttributedStringCacheAttribute (attribs[idx].attrib); } CFAttributedStringSetInline (new); } return new; } CFAttributedStringRef CFAttributedStringCreate (CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attribs) { Attr attrib; attrib.index = 0; attrib.attrib = attribs; return CFAttributedStringCreateInlined (alloc, str, 1, &attrib); } CFAttributedStringRef CFAttributedStringCreateCopy (CFAllocatorRef alloc, CFAttributedStringRef str) { if (CF_IS_OBJC(_kCFAttributedStringTypeID, str)) { CFIndex len = CFAttributedStringGetLength (str); return CFAttributedStringCreateWithSubstring (alloc, str, CFRangeMake (0, len)); } return CFAttributedStringCreateInlined (alloc, str->_string, str->_attribCount, str->_attribs); } CFAttributedStringRef CFAttributedStringCreateWithSubstring (CFAllocatorRef alloc, CFAttributedStringRef str, CFRange range) { CFAttributedStringRef new; CFMutableAttributedStringRef tmp; CFRange r; CFIndex cur; tmp = CFAttributedStringCreateMutable (alloc, range.length); /* We do not need to protect this with beging and end editing because * we will be adding attributes in the order they appear. Using * the being/end editing functions would actually slow things down. */ CFAttributedStringReplaceString (tmp, range, CFAttributedStringGetString (str)); cur = range.location; do { CFDictionaryRef attribs; attribs = CFAttributedStringGetAttributes (str, cur, &r); CFAttributedStringSetAttributes (tmp, r, attribs, true); cur = r.location + r.length; } while (cur < range.length); new = CFAttributedStringCreateCopy (alloc, tmp); CFRelease (tmp); return new; } CFIndex CFAttributedStringGetLength (CFAttributedStringRef str) { CF_OBJC_FUNCDISPATCHV (_kCFAttributedStringTypeID, CFIndex, str, "length"); return CFStringGetLength (str->_string); } CFStringRef CFAttributedStringGetString (CFAttributedStringRef str) { CF_OBJC_FUNCDISPATCHV (_kCFAttributedStringTypeID, CFStringRef, str, "string"); return str->_string; } CFTypeRef CFAttributedStringGetAttribute (CFAttributedStringRef str, CFIndex loc, CFStringRef attrName, CFRange *effRange) { CFDictionaryRef attribs; attribs = CFAttributedStringGetAttributes (str, loc, effRange); return CFDictionaryGetValue (attribs, attrName); } CFDictionaryRef CFAttributedStringGetAttributes (CFAttributedStringRef str, CFIndex loc, CFRange *effRange) { CFIndex idx; CF_OBJC_FUNCDISPATCHV (_kCFAttributedStringTypeID, CFDictionaryRef, str, "attributesAtIndex:effectiveRange:", loc, effRange); idx = CFAttributedStringArrayGetIndex (str, loc, effRange); return str->_attribs[idx].attrib; } CFTypeRef CFAttributedStringGetAttributeAndLongestEffectiveRange ( CFAttributedStringRef str, CFIndex loc, CFStringRef attrName, CFRange inRange, CFRange *longestEffRange) { return NULL; /* FIXME */ } CFDictionaryRef CFAttributedStringGetAttributesAndLongestEffectiveRange ( CFAttributedStringRef str, CFIndex loc, CFRange inRange, CFRange *longestEffRange) { return NULL; /* FIXME */ } static void InsertAttributesAtIndex (CFMutableAttributedStringRef str, CFIndex idx, CFIndex strIdx, CFDictionaryRef attrib) { struct __CFMutableAttributedString *working; CFAllocatorRef alloc; const Attr *stop; Attr *prev; Attr *cur; working = (struct __CFMutableAttributedString *)str; alloc = CFGetAllocator (working); if (working->_attribCount == working->_attribCap) { /* Grow */ working->_attribs = CFAllocatorReallocate (alloc, working->_attribs, (working->_attribCap << 1), 0); } /* Move things to the right */ stop = &working->_attribs[idx]; cur = &working->_attribs[working->_attribCount]; prev = cur - 1; while (cur > stop) *cur-- = *prev--; working->_attribCount += 1; /* Insert the new attribute */ cur->index = strIdx; cur->attrib = CFAttributedStringCacheAttribute (attrib); } static void ReplaceAttributesAtIndex (CFMutableAttributedStringRef str, CFIndex idx, CFDictionaryRef repl) { CFAttributedStringUncacheAttribute (str->_attribs[idx].attrib); str->_attribs[idx].attrib = CFAttributedStringCacheAttribute (str->_attribs[idx].attrib); } static void SetAttributesAtIndex (CFMutableAttributedStringRef str, CFIndex idx, CFDictionaryRef repl) { CFMutableDictionaryRef dict; CFIndex count; CFIndex i; const void **keys; const void ** values; dict = CFDictionaryCreateMutableCopy (NULL, 0, str->_attribs[idx].attrib); count = CFDictionaryGetCount (repl); keys = CFAllocatorAllocate (NULL, count * sizeof(void*) * 2, 0); values = keys + count; CFDictionaryGetKeysAndValues (repl, keys, values); for (i = 0 ; i < count ; ++i) CFDictionarySetValue (dict, keys[i], values[i]); CFAttributedStringUncacheAttribute (str->_attribs[idx].attrib); str->_attribs[idx].attrib = CFAttributedStringCacheAttribute (dict); CFAllocatorDeallocate (NULL, keys); CFRelease (dict); } static void RemoveAttributesAtIndex (CFMutableAttributedStringRef str, CFRange range) { if (range.length > 0) { struct __CFMutableAttributedString *working; CFAllocatorRef alloc; const Attr *stop; Attr *next; Attr *cur; working = (struct __CFMutableAttributedString *)str; alloc = CFGetAllocator (working); /* Move things to the left */ cur = &working->_attribs[range.location]; stop = cur + range.length; while (cur < stop) { CFAttributedStringUncacheAttribute (cur->attrib); cur++; } cur = &working->_attribs[range.location]; next = cur + range.length; stop = cur + (working->_attribCount - (range.location + range.length) - 1); while (cur < stop) *cur++ = *next++; working->_attribCount -= range.length; if (working->_attribCount < (working->_attribCap >> 2) && working->_attribCount > 9) { /* Shrink */ working->_attribs = CFAllocatorReallocate (alloc, working->_attribs, (working->_attribCap >> 1), 0); } } } static void CFAttributedStringCoalesce (CFMutableAttributedStringRef str, CFRange range) { struct __CFMutableAttributedString *working; working = (struct __CFMutableAttributedString *)str; if (working->_isEditing == 0) { CFIndex cur; CFIndex end; Attr *array; array = working->_attribs; if (range.location > 0) { if (array[range.location - 1].attrib == array[range.location].attrib) { RemoveAttributesAtIndex (str, CFRangeMake (range.location, 1)); range.length -= 1; } } cur = range.location; end = range.location + range.length; while (cur < end) { if (array[cur - 1].attrib == array[cur].attrib) { RemoveAttributesAtIndex (str, CFRangeMake (cur, 1)); end -= 1; } cur++; } } } #define CFMUTABLEATTRIBUTESTRING_SIZE sizeof(CFRuntimeClass) \ - sizeof(struct __CFMutableAttributedString) CFMutableAttributedStringRef CFAttributedStringCreateMutable (CFAllocatorRef alloc, CFIndex maxLength) { struct __CFMutableAttributedString *new; new = (struct __CFMutableAttributedString*)_CFRuntimeCreateInstance (alloc, _kCFAttributedStringTypeID, CFMUTABLEATTRIBUTESTRING_SIZE, 0); if (new) { new->_string = CFStringCreateMutable (alloc, maxLength); /* Minimum size is 8 */ new->_attribCap = 8; new->_attribs = (Attr*)CFAllocatorAllocate (alloc, sizeof(Attr) * 8, 0); new->_attribCount = 1; new->_attribs[0].index = 0; new->_attribs[0].attrib = CFAttributedStringGetBlankAttribute (); CFAttributedStringSetMutable ((CFAttributedStringRef)new); } return (CFMutableAttributedStringRef)new; } CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy (CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef str) { CFMutableAttributedStringRef new; CFRange r; CFIndex idx; CFIndex cur; CFIndex strLen; new = CFAttributedStringCreateMutable (alloc, maxLength); strLen = CFAttributedStringGetLength (str); CFAttributedStringReplaceString (new, CFRangeMake (0, 0), CFAttributedStringGetString (str)); RemoveAttributesAtIndex (new, CFRangeMake (0, 1)); cur = 0; idx = 0; do { CFDictionaryRef attribs; attribs = CFAttributedStringGetAttributes (str, cur, &r); InsertAttributesAtIndex (new, idx, cur, attribs); cur = r.location + r.length; idx++; } while (cur < strLen); return new; } void CFAttributedStringBeginEditing (CFMutableAttributedStringRef str) { CF_OBJC_FUNCDISPATCHV (_kCFAttributedStringTypeID, void, str, "beginEditing"); ((struct __CFMutableAttributedString *)str)->_isEditing += 1; } void CFAttributedStringEndEditing (CFMutableAttributedStringRef str) { CF_OBJC_FUNCDISPATCHV (_kCFAttributedStringTypeID, void, str, "endEditing"); if ((((struct __CFMutableAttributedString *)str)->_isEditing -= 1) == 0) CFAttributedStringCoalesce (str, CFRangeMake (0, str->_attribCount)); } CFMutableStringRef CFAttributedStringGetMutableString (CFMutableAttributedStringRef str) { CF_OBJC_FUNCDISPATCHV (_kCFAttributedStringTypeID, CFMutableStringRef, str, "mutableString"); return NULL; /* FIXME */ } void CFAttributedStringRemoveAttribute (CFMutableAttributedStringRef str, CFRange range, CFStringRef attrName) { CF_OBJC_FUNCDISPATCHV (_kCFAttributedStringTypeID, void, str, "removeAttribute:range:", attrName, range); if (!CFAttributedStringIsMutable(str)) return; /* FIXME */ } void CFAttributedStringReplaceString (CFMutableAttributedStringRef str, CFRange range, CFStringRef repl) { CFIndex idxS; CFIndex idxE; CFIndex cur; CFIndex moveAmount; CF_OBJC_FUNCDISPATCHV (_kCFAttributedStringTypeID, void, str, "replaceCharactersInRange:withString:", range, repl); if (!CFAttributedStringIsMutable(str)) return; CFStringReplace ((CFMutableStringRef)str->_string, range, repl); idxS = CFAttributedStringArrayGetIndex (str, range.location, NULL); idxE = CFAttributedStringArrayGetIndex (str, range.location + range.length, NULL); RemoveAttributesAtIndex (str, CFRangeMake (idxS, idxE - idxS)); /* Need to move the attributes */ moveAmount = CFStringGetLength (repl) - range.length; cur = idxS + 1; while (cur < str->_attribCount) str->_attribs[cur++].index += moveAmount; CFAttributedStringCoalesce (str, CFRangeMake (idxS, idxE - idxS)); } void CFAttributedStringReplaceAttributedString (CFMutableAttributedStringRef str, CFRange range, CFAttributedStringRef repl) { CF_OBJC_FUNCDISPATCHV (_kCFAttributedStringTypeID, void, str, "replaceCharactersInRange:withAttributeString:", range, repl); if (!CFAttributedStringIsMutable(str)) return; } void CFAttributedStringSetAttribute (CFMutableAttributedStringRef str, CFRange range, CFStringRef attrName, CFTypeRef value) { CFDictionaryRef attrib; CF_OBJC_FUNCDISPATCHV (_kCFAttributedStringTypeID, void, str, "setAttribute:value:range:", attrName, value, range); if (!CFAttributedStringIsMutable(str)) return; attrib = CFDictionaryCreate (NULL, (const void **)&attrName, (const void **)&value, 1, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFAttributedStringSetAttributes (str, range, attrib, false); CFRelease (attrib); } void CFAttributedStringSetAttributes (CFMutableAttributedStringRef str, CFRange range, CFDictionaryRef repl, Boolean clearOtherAttribs) { CFIndex idxS; CFIndex idxE; CFIndex cur; CFRange rS; CFRange rE; CFIndex rangeMax; Attr *array; CF_OBJC_FUNCDISPATCHV (_kCFAttributedStringTypeID, void, str, "setAttributes:range:", repl, range); if (!CFAttributedStringIsMutable(str)) return; array = str->_attribs; rangeMax = range.location + range.length; idxS = CFAttributedStringArrayGetIndex (str, range.location, &rS); idxE = CFAttributedStringArrayGetIndex (str, rangeMax - 1, &rE); cur = idxS; /* Split the last attribute in 2 if new attribute does not fall in a * boundary and the new attributes are different from what's already there. */ if (rE.location + rE.length > rangeMax && !CFEqual (array[idxE].attrib, repl)) InsertAttributesAtIndex (str, idxE + 1, rangeMax, array[idxE].attrib); if (range.location == rS.location) { if (clearOtherAttribs) ReplaceAttributesAtIndex (str, cur, repl); else SetAttributesAtIndex (str, cur, repl); } else if (!CFEqual (array[idxS].attrib, repl)) { /* Only insert a new attribute if the new attribute is different from * the existing attribute */ cur += 1; idxE += 1; InsertAttributesAtIndex (str, cur, range.location, repl); if (!clearOtherAttribs) SetAttributesAtIndex (str, cur, array[idxS].attrib); } cur += 1; if (cur <= idxE) { if (clearOtherAttribs) { RemoveAttributesAtIndex (str, CFRangeMake (cur, idxE - cur + 1)); } else { do { SetAttributesAtIndex (str, cur++, repl); } while (cur <= idxE); } } CFAttributedStringCoalesce (str, CFRangeMake (idxS, cur)); } gnustep-corebase-0.2/Source/CFUUID.c0000644000175000017500000002200213222706330016260 0ustar yavoryavor/* CFUUID.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: May, 2011 This file is part of GNUstep CoreBase Library. This library is free software; you can redisibute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is disibuted in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "CoreFoundation/CFRuntime.h" #include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFSet.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFUUID.h" #include "GSPrivate.h" /* Some of the code in CFUUID is based on Etoile's ETUUID class. Copyright (C) 2007 Yen-Ju Check */ #include #include /* On *BSD and Linux we have a srandomdev() function which seeds the random * number generator with entropy collected from a variety of sources. On other * platforms we don't, so we use some less random data based on the current * time and pid to seed the random number generator. */ #if defined(__FreeBSD__) \ || defined(__OpenBSD__) \ || defined(__DragonFly__) \ || defined(__APPLE__) #define INITRANDOM() srandomdev() #elif defined(_WIN32) #define INITRANDOM() CFsrandomdev() #define UNICODE #include #include BOOLEAN (APIENTRY *RtlGenRandom)(PVOID, ULONG); static void CFsrandomdev (void) { HMODULE lib = LoadLibraryW (L"advapi32.dll"); RtlGenRandom = (BOOLEAN(APIENTRY*)(PVOID,ULONG))GetProcAddress (lib, "SystemFunction036"); } #else #include #include #include #include #define INITRANDOM() CFsrandomdev() #if defined(__linux__) #include #include #include static void CFsrandomdev(void) { int fd; unsigned int seed = 0; size_t len = sizeof(seed); Boolean hasSeed = false; fd = open("/dev/random", O_RDONLY | O_NONBLOCK, 0); if (fd >= 0) { if (errno != EWOULDBLOCK) { if (read(fd, &seed, len) == (ssize_t)len) hasSeed = true; } close(fd); } if (hasSeed == false) { struct timeval tv; gettimeofday(&tv, NULL); seed = ((getpid() << 16) ^ tv.tv_sec ^ tv.tv_usec ^ time(NULL)); } srandom(seed); } #else static void CFsrandomdev(void) { struct timeval tv; unsigned int seed = 0; gettimeofday(&tv, NULL); seed = ((getpid() << 16) ^ tv.tv_sec ^ tv.tv_usec ^ time(NULL)); srandom(seed); } #endif #endif static CFTypeID _kCFUUIDTypeID = 0; static GSMutex _kCFUUIDLock; static CFMutableSetRef _kCFUUIDConstants = NULL; struct __CFUUID { CFRuntimeBase _parent; CFUUIDBytes _bytes; }; static Boolean CFUUIDBytesEqual (const void *b1, const void *b2) { CFUUIDBytes *bytes1 = (CFUUIDBytes*)b1; CFUUIDBytes *bytes2 = (CFUUIDBytes*)b2; if (bytes1->byte0 == bytes2->byte0 && bytes1->byte1 == bytes2->byte1 && bytes1->byte2 == bytes2->byte2 && bytes1->byte3 == bytes2->byte3 && bytes1->byte4 == bytes2->byte4 && bytes1->byte5 == bytes2->byte5 && bytes1->byte6 == bytes2->byte6 && bytes1->byte7 == bytes2->byte7 && bytes1->byte8 == bytes2->byte8 && bytes1->byte9 == bytes2->byte9 && bytes1->byte10 == bytes2->byte10 && bytes1->byte11 == bytes2->byte11 && bytes1->byte12 == bytes2->byte12 && bytes1->byte13 == bytes2->byte13 && bytes1->byte14 == bytes2->byte14 && bytes1->byte15 == bytes2->byte15) return true; return false; } static CFHashCode CFUUIDBytesHash (const void *bytes) { return GSHashBytes (bytes, 16); } static Boolean CFUUIDEqual (CFTypeRef cf1, CFTypeRef cf2) { CFUUIDBytes bytes1 = ((CFUUIDRef)cf1)->_bytes; CFUUIDBytes bytes2 = ((CFUUIDRef)cf2)->_bytes; return CFUUIDBytesEqual (&bytes1, &bytes2); } static CFHashCode CFUUIDHash (CFTypeRef cf) { return GSHashBytes ((const void*)&((CFUUIDRef)cf)->_bytes, 16); } static CFStringRef CFUUIDCopyFormattingDescription (CFTypeRef cf, CFDictionaryRef formatOptions) { return CFUUIDCreateString(NULL, cf); } const CFRuntimeClass CFUUIDClass = { 0, "CFUUID", NULL, /* init */ NULL, /* copy */ NULL, /* dealloc */ CFUUIDEqual, /* equal */ CFUUIDHash, /* hash */ CFUUIDCopyFormattingDescription, /* copyFormattingDesc */ NULL /* copyDebugDesc */ }; void CFUUIDInitialize (void) { INITRANDOM(); _kCFUUIDTypeID = _CFRuntimeRegisterClass (&CFUUIDClass); GSMutexInitialize (&_kCFUUIDLock); } CFUUIDRef CFUUIDCreate (CFAllocatorRef alloc) { CFUUIDBytes bytes; #if defined(_WIN32) RtlGenRandom ((void*)&bytes, sizeof(bytes)); #else CFIndex i; for (i = 0 ; i < 16 ; ++i) { long r = random (); ((UInt8*)&bytes)[i] = (UInt8)r; } #endif /* Set version */ bytes.byte6 &= 0x0F; bytes.byte6 |= 0x40; /* Bit 6 must be 0 and 7 must be 1 */ bytes.byte8 &= 0xBF; return CFUUIDCreateFromUUIDBytes (alloc, bytes); } CFUUIDRef CFUUIDCreateFromString (CFAllocatorRef alloc, CFStringRef uuidStr) { CFUUIDBytes bytes; char data[36]; /* 36 chars */ if (!CFStringGetCString (uuidStr, data, 36, kCFStringEncodingASCII)) return NULL; sscanf (data, "%4hx%4hx-%4hx-%4hx-%4hx-%4hx%4hx%4hx", (UInt16*)&bytes.byte1,(UInt16*)&bytes.byte3, (UInt16*)&bytes.byte5, (UInt16*)&bytes.byte7, (UInt16*)&bytes.byte9, (UInt16*)&bytes.byte11, (UInt16*)&bytes.byte13, (UInt16*)&bytes.byte15); return CFUUIDCreateFromUUIDBytes (alloc, bytes); } CFUUIDRef CFUUIDCreateFromUUIDBytes (CFAllocatorRef alloc, CFUUIDBytes bytes) { struct __CFUUID *new; new = (struct __CFUUID *)_CFRuntimeCreateInstance (alloc, _kCFUUIDTypeID, sizeof(struct __CFUUID) - sizeof(CFRuntimeBase), NULL); if (new) new->_bytes = bytes; return (CFUUIDRef)new; } CFUUIDRef CFUUIDCreateWithBytes (CFAllocatorRef alloc, UInt8 byte0, UInt8 byte1, UInt8 byte2, UInt8 byte3, UInt8 byte4, UInt8 byte5, UInt8 byte6, UInt8 byte7, UInt8 byte8, UInt8 byte9, UInt8 byte10, UInt8 byte11, UInt8 byte12, UInt8 byte13, UInt8 byte14, UInt8 byte15) { CFUUIDBytes uuidBytes; uuidBytes.byte0 = byte0; uuidBytes.byte1 = byte1; uuidBytes.byte2 = byte2; uuidBytes.byte3 = byte3; uuidBytes.byte4 = byte4; uuidBytes.byte5 = byte5; uuidBytes.byte6 = byte6; uuidBytes.byte7 = byte7; uuidBytes.byte8 = byte8; uuidBytes.byte9 = byte9; uuidBytes.byte10 = byte10; uuidBytes.byte11 = byte11; uuidBytes.byte12 = byte12; uuidBytes.byte13 = byte13; uuidBytes.byte14 = byte14; uuidBytes.byte15 = byte15; return CFUUIDCreateFromUUIDBytes (alloc, uuidBytes); } CFStringRef CFUUIDCreateString (CFAllocatorRef alloc, CFUUIDRef uuid) { CFStringRef ret; CFUUIDBytes bytes = uuid->_bytes; ret = CFStringCreateWithFormat (alloc, NULL, CFSTR("%2hhx%2hhx%2hhx%2hhx-" "%2hhx%2hhx-%2hhx%2hhx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx"), bytes.byte0, bytes.byte1, bytes.byte2, bytes.byte3, bytes.byte4, bytes.byte5, bytes.byte6, bytes.byte7, bytes.byte8, bytes.byte9, bytes.byte10, bytes.byte11, bytes.byte12, bytes.byte13, bytes.byte14, bytes.byte15); return ret; } CFUUIDRef CFUUIDGetConstantUUIDWithBytes (CFAllocatorRef alloc, UInt8 byte0, UInt8 byte1, UInt8 byte2, UInt8 byte3, UInt8 byte4, UInt8 byte5, UInt8 byte6, UInt8 byte7, UInt8 byte8, UInt8 byte9, UInt8 byte10, UInt8 byte11, UInt8 byte12, UInt8 byte13, UInt8 byte14, UInt8 byte15) { CFUUIDRef uuid; CFUUIDBytes uuidBytes; CFSetCallBacks cb = {0, NULL, NULL, NULL, CFUUIDBytesEqual, CFUUIDBytesHash}; uuidBytes.byte0 = byte0; uuidBytes.byte1 = byte1; uuidBytes.byte2 = byte2; uuidBytes.byte3 = byte3; uuidBytes.byte4 = byte4; uuidBytes.byte5 = byte5; uuidBytes.byte6 = byte6; uuidBytes.byte7 = byte7; uuidBytes.byte8 = byte8; uuidBytes.byte9 = byte9; uuidBytes.byte10 = byte10; uuidBytes.byte11 = byte11; uuidBytes.byte12 = byte12; uuidBytes.byte13 = byte13; uuidBytes.byte14 = byte14; uuidBytes.byte15 = byte15; GSMutexLock (&_kCFUUIDLock); if (_kCFUUIDConstants == NULL) _kCFUUIDConstants = CFSetCreateMutable (NULL, 0, &cb); if (!CFSetGetValueIfPresent(_kCFUUIDConstants, &uuidBytes, (const void**)&uuid)) { uuid = CFUUIDCreateFromUUIDBytes (NULL, uuidBytes); CFSetAddValue (_kCFUUIDConstants, (const void*)uuid); CFRelease (uuid); } GSMutexUnlock (&_kCFUUIDLock); return uuid; } CFUUIDBytes CFUUIDGetUUIDBytes (CFUUIDRef uuid) { return uuid->_bytes; } CFTypeID CFUUIDGetTypeID (void) { return _kCFUUIDTypeID; } gnustep-corebase-0.2/Source/NSCFDate.m0000644000175000017500000000333613222706330016653 0ustar yavoryavor/* NSCFError.m Copyright (C) 2014 Free Software Foundation, Inc. Written by: Lubos Dolezel Date: May, 2014 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #import #import #include "NSCFType.h" #include "CoreFoundation/CFDate.h" @interface NSCFDate : NSDate NSCFTYPE_VARS @end @interface NSDate (CoreBaseAdditions) - (CFTypeID) _cfTypeID; @end @implementation NSCFDate + (void) load { NSCFInitialize (); } + (void) initialize { GSObjCAddClassBehavior (self, [NSCFType class]); } - (id)initWithTimeIntervalSinceReferenceDate:(NSTimeInterval)seconds { RELEASE(self); return (NSCFDate*) CFDateCreate(NULL, seconds); } - (NSTimeInterval)timeIntervalSinceReferenceDate { return CFDateGetAbsoluteTime((CFDateRef) self); } @end @implementation NSDate (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return CFDateGetTypeID(); } @end gnustep-corebase-0.2/Source/NSCFType.m0000644000175000017500000000657114551015633016730 0ustar yavoryavor/* NSCFType.m Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: March, 2011 This file is part of GNUstep CoreBase library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #import #include "CoreFoundation/CoreFoundation.h" #include "NSCFType.h" #include "GSPrivate.h" extern void CFInitialize (void); extern UInt32 __CFRuntimeClassTableSize; extern UInt32 __CFRuntimeClassTableCount; extern Class NSCFTypeClass; extern void GSRuntimeInitializeConstants (void); void NSCFInitialize (void) { static int requiredClasses = 12; --requiredClasses; if (requiredClasses == 0) { CFIndex i = 0; /* Make sure CoreBase is initialized before bridging */ CFInitialize (); __CFRuntimeObjCClassTable = calloc (__CFRuntimeClassTableSize, sizeof(Class)); while (i < __CFRuntimeClassTableCount) __CFRuntimeObjCClassTable[i++] = NSCFTypeClass; CFRuntimeBridgeClass (CFNullGetTypeID(), "NSNull"); CFRuntimeBridgeClass (CFArrayGetTypeID(), "NSCFArray"); CFRuntimeBridgeClass (CFDataGetTypeID(), "NSCFData"); CFRuntimeBridgeClass (CFErrorGetTypeID(), "NSCFError"); CFRuntimeBridgeClass (CFStringGetTypeID(), "NSCFString"); CFRuntimeBridgeClass (CFSetGetTypeID(), "NSCFSet"); CFRuntimeBridgeClass (CFLocaleGetTypeID(), "NSCFLocale"); CFRuntimeBridgeClass (CFNumberGetTypeID(), "NSCFNumber"); CFRuntimeBridgeClass (CFDictionaryGetTypeID(), "NSCFDictionary"); CFRuntimeBridgeClass (CFTimeZoneGetTypeID(), "NSCFTimeZone"); CFRuntimeBridgeClass (CFReadStreamGetTypeID(), "NSCFInputStream"); CFRuntimeBridgeClass (CFWriteStreamGetTypeID(), "NSCFOutputStream"); CFRuntimeBridgeClass (CFDateGetTypeID(), "NSCFDate"); GSRuntimeInitializeConstants (); } } @interface NSObject (CoreBaseAdditions) - (CFTypeID) _cfTypeID; @end @implementation NSObject (CoreBaseAdditions) - (CFTypeID) _cfTypeID { return _kCFRuntimeNotATypeID; } @end @implementation NSCFType + (void) load { NSCFTypeClass = self; NSCFInitialize (); } - (void) dealloc { GSRuntimeDeallocateInstance (self); } - (id) retain { return (id)CFRetain(self); } - (oneway void) release { CFRelease(self); } - (NSUInteger) retainCount { return CFGetRetainCount (self); } - (BOOL) isEqual: (id) anObject { return (BOOL)CFEqual (self, (CFTypeRef)anObject); } - (CFTypeID) _cfTypeID { /* This is an undocumented method. See: http://www.cocoadev.com/index.pl?HowToCreateTollFreeBridgedClass for more info. */ return (CFTypeID)_typeID; } @end gnustep-corebase-0.2/Source/config.h.in0000644000175000017500000001241014551015633017167 0ustar yavoryavor/* Source/config.h.in. Generated from configure.ac by autoheader. */ /* Define if building universal (internal helper macro) */ #undef AC_APPLE_UNIVERSAL_BUILD /* Define to the architecture's data model. */ #undef DATA_MODEL /* Define ILP32 data model. */ #define DATA_MODEL_ILP32 124484 /* Define LLP64 data model. */ #define DATA_MODEL_LLP64 124488 /* Define LP32 data model. */ #define DATA_MODEL_LP32 122484 /* Define LP64 data model. */ #define DATA_MODEL_LP64 124888 /* Define to 1 if the required libraries and headers for CFRunLoop are present. */ #undef HAVE_CFRUNLOOP_SUPPORT /* Define to 1 if you have the header file. */ #undef HAVE_DISPATCH_DISPATCH_H /* Define to 1 if you have the header file. */ #undef HAVE_FCNTL_H /* Define to 1 if you have International Components for Unicode. */ #undef HAVE_ICU /* Define to 1 if you have the header file. */ #undef HAVE_ICU_H /* Define to 1 if you have the header file. */ #undef HAVE_INTTYPES_H /* Define to 1 if you have the `dispatch' library (-ldispatch). */ #undef HAVE_LIBDISPATCH /* Define to 1 if you have the `m' library (-lm). */ #undef HAVE_LIBM /* Define to 1 if you have the header file. */ #undef HAVE_LIMITS_H /* Define to 1 if you have the header file. */ #undef HAVE_MEMORY_H /* Define to 1 if you have the header file. */ #undef HAVE_OBJC_RUNTIME_H /* Define to 1 if you have the header file. */ #undef HAVE_POLL_H /* Define to 1 if you have the header file. */ #undef HAVE_PTHREAD_H /* Define to 1 if you have the header file. */ #undef HAVE_STDINT_H /* Define to 1 if you have the header file. */ #undef HAVE_STDLIB_H /* Define to 1 if you have the header file. */ #undef HAVE_STRINGS_H /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_STAT_H /* Define to 1 if you have the header file. */ #undef HAVE_SYS_TYPES_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_UCAL_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_UCHAR_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_UCNV_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_UCOL_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_UCURR_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_UDATPG_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_UDAT_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_ULOCDATA_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_ULOC_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_UNORM2_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_UNUM_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_USEARCH_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_USET_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_USTRING_H /* Define to 1 if you have the header file. */ #undef HAVE_UNICODE_UTRANS_H /* Define to 1 if you have the header file. */ #undef HAVE_UNISTD_H /* Define to 1 if you have the header file. */ #undef HAVE_WS2TCPIP_H /* Define to the address where bug reports for this package should be sent. */ #undef PACKAGE_BUGREPORT /* Define to the full name of this package. */ #undef PACKAGE_NAME /* Define to the full name and version of this package. */ #undef PACKAGE_STRING /* Define to the one symbol short name of this package. */ #undef PACKAGE_TARNAME /* Define to the home page for this package. */ #undef PACKAGE_URL /* Define to the version of this package. */ #undef PACKAGE_VERSION /* The size of `char', as computed by sizeof. */ #undef SIZEOF_CHAR /* The size of `double', as computed by sizeof. */ #undef SIZEOF_DOUBLE /* The size of `int', as computed by sizeof. */ #undef SIZEOF_INT /* The size of `long', as computed by sizeof. */ #undef SIZEOF_LONG /* The size of `long double', as computed by sizeof. */ #undef SIZEOF_LONG_DOUBLE /* The size of `long long', as computed by sizeof. */ #undef SIZEOF_LONG_LONG /* The size of `short', as computed by sizeof. */ #undef SIZEOF_SHORT /* The size of `void *', as computed by sizeof. */ #undef SIZEOF_VOID_P /* Define to 1 if you have the ANSI C header files. */ #undef STDC_HEADERS /* Define to the directory contain time zone object files. */ #undef TZDIR /* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most significant byte first (like Motorola and SPARC, unlike Intel). */ #if defined AC_APPLE_UNIVERSAL_BUILD # if defined __BIG_ENDIAN__ # define WORDS_BIGENDIAN 1 # endif #else # ifndef WORDS_BIGENDIAN # undef WORDS_BIGENDIAN # endif #endif /* Define to `__inline__' or `__inline' if that's what the C compiler calls it, or to nothing if 'inline' is not supported under any name. */ #ifndef __cplusplus #undef inline #endif gnustep-corebase-0.2/configure0000755000175000017500000061072214551015633015625 0ustar yavoryavor#! /bin/sh # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.69 for libgnustep-corebase 0.2. # # Report bugs to . # # # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. # # # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # Use a proper internal environment variable to ensure we don't fall # into an infinite loop, continuously re-executing ourselves. if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then _as_can_reexec=no; export _as_can_reexec; # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 as_fn_exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} if test "x$CONFIG_SHELL" = x; then as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST else case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi " as_required="as_fn_return () { (exit \$1); } as_fn_success () { as_fn_return 0; } as_fn_failure () { as_fn_return 1; } as_fn_ret_success () { return 0; } as_fn_ret_failure () { return 1; } exitcode=0 as_fn_success || { exitcode=1; echo as_fn_success failed.; } as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : else exitcode=1; echo positional parameters were not saved. fi test x\$exitcode = x0 || exit 1 test -x / || exit 1" as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 test \$(( 1 + 1 )) = 2 || exit 1" if (eval "$as_required") 2>/dev/null; then : as_have_required=yes else as_have_required=no fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. as_found=: case $as_dir in #( /*) for as_base in sh bash ksh sh5; do # Try only shells that exist, to save several forks. as_shell=$as_dir/$as_base if { test -f "$as_shell" || test -f "$as_shell.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : CONFIG_SHELL=$as_shell as_have_required=yes if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : break 2 fi fi done;; esac as_found=false done $as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : CONFIG_SHELL=$SHELL as_have_required=yes fi; } IFS=$as_save_IFS if test "x$CONFIG_SHELL" != x; then : export CONFIG_SHELL # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV case $- in # (((( *v*x* | *x*v* ) as_opts=-vx ;; *v* ) as_opts=-v ;; *x* ) as_opts=-x ;; * ) as_opts= ;; esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail # out after a failed `exec'. $as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi if test x$as_have_required = xno; then : $as_echo "$0: This script requires a shell more modern than all" $as_echo "$0: the shells that I found on your system." if test x${ZSH_VERSION+set} = xset ; then $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" $as_echo "$0: be upgraded to zsh 4.3.4 or later." else $as_echo "$0: Please tell bug-autoconf@gnu.org and $0: bug-gnustep@gnu.org about your system, including any $0: error possibly output before this message. Then install $0: a modern shell, or manually run the script under such a $0: shell if you do have one." fi exit 1 fi fi fi SHELL=${CONFIG_SHELL-/bin/sh} export SHELL # Unset more variables known to interfere with behavior of common tools. CLICOLOR_FORCE= GREP_OPTIONS= unset CLICOLOR_FORCE GREP_OPTIONS ## --------------------- ## ## M4sh Shell Functions. ## ## --------------------- ## # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits as_lineno_1=$LINENO as_lineno_1a=$LINENO as_lineno_2=$LINENO as_lineno_2a=$LINENO eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= ' <$as_myself | sed ' s/[$]LINENO.*/&-/ t lineno b :lineno N :loop s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ t loop s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } # If we had to re-execute with $CONFIG_SHELL, we're ensured to have # already done that, so ensure we don't try to do so again and fall # in an infinite loop. This has already happened in practice. _as_can_reexec=no; export _as_can_reexec # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). . "./$as_me.lineno" # Exit status is that of the last command. exit } ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. # hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` # # Initializations. # ac_default_prefix=/usr/local ac_clean_files= ac_config_libobj_dir=. LIBOBJS= cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= # Identity of this package. PACKAGE_NAME='libgnustep-corebase' PACKAGE_TARNAME='libgnustep-corebase' PACKAGE_VERSION='0.2' PACKAGE_STRING='libgnustep-corebase 0.2' PACKAGE_BUGREPORT='bug-gnustep@gnu.org' PACKAGE_URL='' ac_unique_file="Source/CFBase.c" # Factoring default headers for most tests. ac_includes_default="\ #include #ifdef HAVE_SYS_TYPES_H # include #endif #ifdef HAVE_SYS_STAT_H # include #endif #ifdef STDC_HEADERS # include # include #else # ifdef HAVE_STDLIB_H # include # endif #endif #ifdef HAVE_STRING_H # if !defined STDC_HEADERS && defined HAVE_MEMORY_H # include # endif # include #endif #ifdef HAVE_STRINGS_H # include #endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif #ifdef HAVE_UNISTD_H # include #endif" ac_subst_vars='LTLIBOBJS LIBOBJS ICU_LIBS ICU_CFLAGS PKG_CONFIG_LIBDIR PKG_CONFIG_PATH PKG_CONFIG GS_UINTPTR_T GS_SINTPTR_T GS_UINT32_T GS_SINT32_T GS_UINT64_T GS_SINT64_T GS_UINT16_T GS_SINT16_T GS_UINT8_T GS_SINT8_T GS_WORDS_BIGENDIAN_DEFINE EGREP GREP ac_ct_OBJC OBJCFLAGS OBJC CPP OBJEXT EXEEXT ac_ct_CC CPPFLAGS LDFLAGS CFLAGS CC target_os target_vendor target_cpu target host_os host_vendor host_cpu host build_os build_vendor build_cpu build target_alias host_alias build_alias LIBS ECHO_T ECHO_N ECHO_C DEFS mandir localedir libdir psdir pdfdir dvidir htmldir infodir docdir oldincludedir includedir runstatedir localstatedir sharedstatedir sysconfdir datadir datarootdir libexecdir sbindir bindir program_transform_name prefix exec_prefix PACKAGE_URL PACKAGE_BUGREPORT PACKAGE_STRING PACKAGE_VERSION PACKAGE_TARNAME PACKAGE_NAME PATH_SEPARATOR SHELL' ac_subst_files='' ac_user_opts=' enable_option_checking enable_cfrunloop with_icu with_gcd with_objc with_zoneinfo ' ac_precious_vars='build_alias host_alias target_alias CC CFLAGS LDFLAGS LIBS CPPFLAGS CPP OBJC OBJCFLAGS PKG_CONFIG PKG_CONFIG_PATH PKG_CONFIG_LIBDIR ICU_CFLAGS ICU_LIBS' # Initialize some variables set by options. ac_init_help= ac_init_version=false ac_unrecognized_opts= ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null exec_prefix=NONE no_create= no_recursion= prefix=NONE program_prefix=NONE program_suffix=NONE program_transform_name=s,x,x, silent= site= srcdir= verbose= x_includes=NONE x_libraries=NONE # Installation directory options. # These are left unexpanded so users can "make install exec_prefix=/foo" # and all the variables that are supposed to be based on exec_prefix # by default will actually change. # Use braces instead of parens because sh, perl, etc. also accept them. # (The list follows the same order as the GNU Coding Standards.) bindir='${exec_prefix}/bin' sbindir='${exec_prefix}/sbin' libexecdir='${exec_prefix}/libexec' datarootdir='${prefix}/share' datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' runstatedir='${localstatedir}/run' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' infodir='${datarootdir}/info' htmldir='${docdir}' dvidir='${docdir}' pdfdir='${docdir}' psdir='${docdir}' libdir='${exec_prefix}/lib' localedir='${datarootdir}/locale' mandir='${datarootdir}/man' ac_prev= ac_dashdash= for ac_option do # If the previous option needs an argument, assign it. if test -n "$ac_prev"; then eval $ac_prev=\$ac_option ac_prev= continue fi case $ac_option in *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; *=) ac_optarg= ;; *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; -bindir | --bindir | --bindi | --bind | --bin | --bi) ac_prev=bindir ;; -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) bindir=$ac_optarg ;; -build | --build | --buil | --bui | --bu) ac_prev=build_alias ;; -build=* | --build=* | --buil=* | --bui=* | --bu=*) build_alias=$ac_optarg ;; -cache-file | --cache-file | --cache-fil | --cache-fi \ | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) ac_prev=cache_file ;; -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) cache_file=$ac_optarg ;; --config-cache | -C) cache_file=config.cache ;; -datadir | --datadir | --datadi | --datad) ac_prev=datadir ;; -datadir=* | --datadir=* | --datadi=* | --datad=*) datadir=$ac_optarg ;; -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ | --dataroo | --dataro | --datar) ac_prev=datarootdir ;; -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) datarootdir=$ac_optarg ;; -disable-* | --disable-*) ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) docdir=$ac_optarg ;; -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) ac_prev=dvidir ;; -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) dvidir=$ac_optarg ;; -enable-* | --enable-*) ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "enable_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ | --exec | --exe | --ex) ac_prev=exec_prefix ;; -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ | --exec=* | --exe=* | --ex=*) exec_prefix=$ac_optarg ;; -gas | --gas | --ga | --g) # Obsolete; use --with-gas. with_gas=yes ;; -help | --help | --hel | --he | -h) ac_init_help=long ;; -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) ac_init_help=recursive ;; -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) ac_init_help=short ;; -host | --host | --hos | --ho) ac_prev=host_alias ;; -host=* | --host=* | --hos=* | --ho=*) host_alias=$ac_optarg ;; -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) ac_prev=htmldir ;; -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ | --ht=*) htmldir=$ac_optarg ;; -includedir | --includedir | --includedi | --included | --include \ | --includ | --inclu | --incl | --inc) ac_prev=includedir ;; -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ | --includ=* | --inclu=* | --incl=* | --inc=*) includedir=$ac_optarg ;; -infodir | --infodir | --infodi | --infod | --info | --inf) ac_prev=infodir ;; -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) infodir=$ac_optarg ;; -libdir | --libdir | --libdi | --libd) ac_prev=libdir ;; -libdir=* | --libdir=* | --libdi=* | --libd=*) libdir=$ac_optarg ;; -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ | --libexe | --libex | --libe) ac_prev=libexecdir ;; -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ | --libexe=* | --libex=* | --libe=*) libexecdir=$ac_optarg ;; -localedir | --localedir | --localedi | --localed | --locale) ac_prev=localedir ;; -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) localedir=$ac_optarg ;; -localstatedir | --localstatedir | --localstatedi | --localstated \ | --localstate | --localstat | --localsta | --localst | --locals) ac_prev=localstatedir ;; -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) localstatedir=$ac_optarg ;; -mandir | --mandir | --mandi | --mand | --man | --ma | --m) ac_prev=mandir ;; -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) mandir=$ac_optarg ;; -nfp | --nfp | --nf) # Obsolete; use --without-fp. with_fp=no ;; -no-create | --no-create | --no-creat | --no-crea | --no-cre \ | --no-cr | --no-c | -n) no_create=yes ;; -no-recursion | --no-recursion | --no-recursio | --no-recursi \ | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) no_recursion=yes ;; -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ | --oldin | --oldi | --old | --ol | --o) ac_prev=oldincludedir ;; -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) oldincludedir=$ac_optarg ;; -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) ac_prev=prefix ;; -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) prefix=$ac_optarg ;; -program-prefix | --program-prefix | --program-prefi | --program-pref \ | --program-pre | --program-pr | --program-p) ac_prev=program_prefix ;; -program-prefix=* | --program-prefix=* | --program-prefi=* \ | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) program_prefix=$ac_optarg ;; -program-suffix | --program-suffix | --program-suffi | --program-suff \ | --program-suf | --program-su | --program-s) ac_prev=program_suffix ;; -program-suffix=* | --program-suffix=* | --program-suffi=* \ | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) program_suffix=$ac_optarg ;; -program-transform-name | --program-transform-name \ | --program-transform-nam | --program-transform-na \ | --program-transform-n | --program-transform- \ | --program-transform | --program-transfor \ | --program-transfo | --program-transf \ | --program-trans | --program-tran \ | --progr-tra | --program-tr | --program-t) ac_prev=program_transform_name ;; -program-transform-name=* | --program-transform-name=* \ | --program-transform-nam=* | --program-transform-na=* \ | --program-transform-n=* | --program-transform-=* \ | --program-transform=* | --program-transfor=* \ | --program-transfo=* | --program-transf=* \ | --program-trans=* | --program-tran=* \ | --progr-tra=* | --program-tr=* | --program-t=*) program_transform_name=$ac_optarg ;; -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) ac_prev=pdfdir ;; -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) pdfdir=$ac_optarg ;; -psdir | --psdir | --psdi | --psd | --ps) ac_prev=psdir ;; -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) psdir=$ac_optarg ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) silent=yes ;; -runstatedir | --runstatedir | --runstatedi | --runstated \ | --runstate | --runstat | --runsta | --runst | --runs \ | --run | --ru | --r) ac_prev=runstatedir ;; -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \ | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \ | --run=* | --ru=* | --r=*) runstatedir=$ac_optarg ;; -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ | --sbi=* | --sb=*) sbindir=$ac_optarg ;; -sharedstatedir | --sharedstatedir | --sharedstatedi \ | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ | --sharedst | --shareds | --shared | --share | --shar \ | --sha | --sh) ac_prev=sharedstatedir ;; -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ | --sha=* | --sh=*) sharedstatedir=$ac_optarg ;; -site | --site | --sit) ac_prev=site ;; -site=* | --site=* | --sit=*) site=$ac_optarg ;; -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) ac_prev=srcdir ;; -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) srcdir=$ac_optarg ;; -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ | --syscon | --sysco | --sysc | --sys | --sy) ac_prev=sysconfdir ;; -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) sysconfdir=$ac_optarg ;; -target | --target | --targe | --targ | --tar | --ta | --t) ac_prev=target_alias ;; -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) target_alias=$ac_optarg ;; -v | -verbose | --verbose | --verbos | --verbo | --verb) verbose=yes ;; -version | --version | --versio | --versi | --vers | -V) ac_init_version=: ;; -with-* | --with-*) ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in *" "with_$ac_useropt" "*) ;; *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" ac_unrecognized_sep=', ';; esac eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. with_x=yes ;; -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ | --x-incl | --x-inc | --x-in | --x-i) ac_prev=x_includes ;; -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) x_includes=$ac_optarg ;; -x-libraries | --x-libraries | --x-librarie | --x-librari \ | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) ac_prev=x_libraries ;; -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; -*) as_fn_error $? "unrecognized option: \`$ac_option' Try \`$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi # Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ libdir localedir mandir runstatedir do eval ac_val=\$$ac_var # Remove trailing slashes. case $ac_val in */ ) ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` eval $ac_var=\$ac_val;; esac # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias host=$host_alias target=$target_alias # FIXME: To remove some day. if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi fi ac_tool_prefix= test -n "$host_alias" && ac_tool_prefix=$host_alias- test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. ac_confdir=`$as_dirname -- "$as_myself" || $as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_myself" : 'X\(//\)[^/]' \| \ X"$as_myself" : 'X\(//\)$' \| \ X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` srcdir=$ac_confdir if test ! -r "$srcdir/$ac_unique_file"; then srcdir=.. fi else ac_srcdir_defaulted=no fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then srcdir=. fi # Remove unnecessary trailing slashes from srcdir. # Double slashes in file names in object file debugging info # mess up M-x gdb in Emacs. case $srcdir in */) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; esac for ac_var in $ac_precious_vars; do eval ac_env_${ac_var}_set=\${${ac_var}+set} eval ac_env_${ac_var}_value=\$${ac_var} eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} eval ac_cv_env_${ac_var}_value=\$${ac_var} done # # Report the --help message. # if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF \`configure' configures libgnustep-corebase 0.2 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... To assign environment variables (e.g., CC, CFLAGS...), specify them as VAR=VALUE. See below for descriptions of some of the useful variables. Defaults for the options are specified in brackets. Configuration: -h, --help display this help and exit --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files --srcdir=DIR find the sources in DIR [configure dir or \`..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify an installation prefix other than \`$ac_default_prefix' using \`--prefix', for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: --bindir=DIR user executables [EPREFIX/bin] --sbindir=DIR system admin executables [EPREFIX/sbin] --libexecdir=DIR program executables [EPREFIX/libexec] --sysconfdir=DIR read-only single-machine data [PREFIX/etc] --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] --localstatedir=DIR modifiable single-machine data [PREFIX/var] --runstatedir=DIR modifiable per-process data [LOCALSTATEDIR/run] --libdir=DIR object code libraries [EPREFIX/lib] --includedir=DIR C header files [PREFIX/include] --oldincludedir=DIR C header files for non-gcc [/usr/include] --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] --datadir=DIR read-only architecture-independent data [DATAROOTDIR] --infodir=DIR info documentation [DATAROOTDIR/info] --localedir=DIR locale-dependent data [DATAROOTDIR/locale] --mandir=DIR man documentation [DATAROOTDIR/man] --docdir=DIR documentation root [DATAROOTDIR/doc/libgnustep-corebase] --htmldir=DIR html documentation [DOCDIR] --dvidir=DIR dvi documentation [DOCDIR] --pdfdir=DIR pdf documentation [DOCDIR] --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] --target=TARGET configure for building compilers for TARGET [HOST] _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in short | recursive ) echo "Configuration of libgnustep-corebase 0.2:";; esac cat <<\_ACEOF Optional Features: --disable-option-checking ignore unrecognized --enable/--with options --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) --enable-FEATURE[=ARG] include FEATURE [ARG=yes] --disable-cfrunloop Disables CFRunLoop support and requiring pthread. Must be passed when building on Windows. Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) --without-icu Disable Internation Components for Unicode. WARNING: Many components will stop working without ICU support! --without-gcd Explicitly compiles without Grand Central Dispatch support. Configure will attempt to find a compatible library, use this option if you do not wish to have the support. The opposite option, --with-gcd, is also supported and should be used if Grand Central Dispatch support is absolutely required. A compatible library will required (http://www.nickhutchinson.me/libdispatch). --without-objc Compiles without support for Objective-C. This option disables the Toll-Free Bridging mechanism. --with-zoneinfo=DIR Directory of the Time zone object files. Some influential environment variables: CC C compiler command CFLAGS C compiler flags LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor OBJC Objective C compiler command OBJCFLAGS Objective C compiler flags PKG_CONFIG path to pkg-config utility PKG_CONFIG_PATH directories to add to pkg-config's search path PKG_CONFIG_LIBDIR path overriding pkg-config's built-in search path ICU_CFLAGS C compiler flags for ICU, overriding pkg-config ICU_LIBS linker flags for ICU, overriding pkg-config Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to . _ACEOF ac_status=$? fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue test -d "$ac_dir" || { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } # Check for guested configure. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive elif test -f "$ac_srcdir/configure"; then echo && $SHELL "$ac_srcdir/configure" --help=recursive else $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF libgnustep-corebase configure 0.2 generated by GNU Autoconf 2.69 Copyright (C) 2012 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi ## ------------------------ ## ## Autoconf initialization. ## ## ------------------------ ## # ac_fn_c_try_compile LINENO # -------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_compile # ac_fn_c_try_cpp LINENO # ---------------------- # Try to preprocess conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_cpp () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_cpp conftest.$ac_ext" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } > conftest.i && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_cpp # ac_fn_objc_try_compile LINENO # ----------------------------- # Try to compile conftest.$ac_ext, and return whether this succeeded. ac_fn_objc_try_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_objc_werror_flag" || test ! -s conftest.err } && test -s conftest.$ac_objext; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_objc_try_compile # ac_fn_c_try_run LINENO # ---------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes # that executables *can* be run. ac_fn_c_try_run () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then : ac_retval=0 else $as_echo "$as_me: program exited with status $ac_status" >&5 $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_run # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES # ------------------------------------------------------- # Tests whether HEADER exists and can be compiled using the include files in # INCLUDES, setting the cache variable VAR accordingly. ac_fn_c_check_header_compile () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : eval "$3=yes" else eval "$3=no" fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_compile # ac_fn_c_compute_int LINENO EXPR VAR INCLUDES # -------------------------------------------- # Tries to find the compile-time value of EXPR in a program that includes # INCLUDES, setting VAR accordingly. Returns whether the value could be # computed ac_fn_c_compute_int () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack if test "$cross_compiling" = yes; then # Depending upon the size, compute the lo and hi bounds. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { static int test_array [1 - 2 * !(($2) >= 0)]; test_array [0] = 0; return test_array [0]; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_lo=0 ac_mid=0 while :; do cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { static int test_array [1 - 2 * !(($2) <= $ac_mid)]; test_array [0] = 0; return test_array [0]; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_hi=$ac_mid; break else as_fn_arith $ac_mid + 1 && ac_lo=$as_val if test $ac_lo -le $ac_mid; then ac_lo= ac_hi= break fi as_fn_arith 2 '*' $ac_mid + 1 && ac_mid=$as_val fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { static int test_array [1 - 2 * !(($2) < 0)]; test_array [0] = 0; return test_array [0]; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_hi=-1 ac_mid=-1 while :; do cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { static int test_array [1 - 2 * !(($2) >= $ac_mid)]; test_array [0] = 0; return test_array [0]; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_lo=$ac_mid; break else as_fn_arith '(' $ac_mid ')' - 1 && ac_hi=$as_val if test $ac_mid -le $ac_hi; then ac_lo= ac_hi= break fi as_fn_arith 2 '*' $ac_mid && ac_mid=$as_val fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done else ac_lo= ac_hi= fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext # Binary search between lo and hi bounds. while test "x$ac_lo" != "x$ac_hi"; do as_fn_arith '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo && ac_mid=$as_val cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int main () { static int test_array [1 - 2 * !(($2) <= $ac_mid)]; test_array [0] = 0; return test_array [0]; ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_hi=$ac_mid else as_fn_arith '(' $ac_mid ')' + 1 && ac_lo=$as_val fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext done case $ac_lo in #(( ?*) eval "$3=\$ac_lo"; ac_retval=0 ;; '') ac_retval=1 ;; esac else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 static long int longval () { return $2; } static unsigned long int ulongval () { return $2; } #include #include int main () { FILE *f = fopen ("conftest.val", "w"); if (! f) return 1; if (($2) < 0) { long int i = longval (); if (i != ($2)) return 1; fprintf (f, "%ld", i); } else { unsigned long int i = ulongval (); if (i != ($2)) return 1; fprintf (f, "%lu", i); } /* Do not output a trailing newline, as this causes \r\n confusion on some platforms. */ return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : echo >>conftest.val; read $3 &5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } else # Is the header compilable? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 $as_echo_n "checking $2 usability... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_header_compiler=yes else ac_header_compiler=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 $as_echo "$ac_header_compiler" >&6; } # Is the header present? { $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 $as_echo_n "checking $2 presence... " >&6; } cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <$2> _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : ac_header_preproc=yes else ac_header_preproc=no fi rm -f conftest.err conftest.i conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } # So? What about this header? case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( yes:no: ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 $as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ;; no:yes:* ) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 $as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 $as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} ( $as_echo "## ---------------------------------- ## ## Report this to bug-gnustep@gnu.org ## ## ---------------------------------- ##" ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_mongrel # ac_fn_c_try_link LINENO # ----------------------- # Try to link conftest.$ac_ext, and return whether this succeeded. ac_fn_c_try_link () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack rm -f conftest.$ac_objext conftest$ac_exeext if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>conftest.err ac_status=$? if test -s conftest.err; then grep -v '^ *+' conftest.err >conftest.er1 cat conftest.er1 >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } && { test -z "$ac_c_werror_flag" || test ! -s conftest.err } && test -s conftest$ac_exeext && { test "$cross_compiling" = yes || test -x conftest$ac_exeext }; then : ac_retval=0 else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_link cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by libgnustep-corebase $as_me 0.2, which was generated by GNU Autoconf 2.69. Invocation command line was $ $0 $@ _ACEOF exec 5>>config.log { cat <<_ASUNAME ## --------- ## ## Platform. ## ## --------- ## hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` uname -m = `(uname -m) 2>/dev/null || echo unknown` uname -r = `(uname -r) 2>/dev/null || echo unknown` uname -s = `(uname -s) 2>/dev/null || echo unknown` uname -v = `(uname -v) 2>/dev/null || echo unknown` /usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` /bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` /bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` /usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` /usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` /bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` /usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` /bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` _ASUNAME as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. $as_echo "PATH: $as_dir" done IFS=$as_save_IFS } >&5 cat >&5 <<_ACEOF ## ----------- ## ## Core tests. ## ## ----------- ## _ACEOF # Keep a trace of the command line. # Strip out --no-create and --no-recursion so they do not pile up. # Strip out --silent because we don't want to record it for future runs. # Also quote any args containing shell meta-characters. # Make two passes to allow for proper duplicate-argument suppression. ac_configure_args= ac_configure_args0= ac_configure_args1= ac_must_keep_next=false for ac_pass in 1 2 do for ac_arg do case $ac_arg in -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else case $ac_arg in *=* | --config-cache | -C | -disable-* | --disable-* \ | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ | -with-* | --with-* | -without-* | --without-* | --x) case "$ac_configure_args0 " in "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; esac ;; -* ) ac_must_keep_next=true ;; esac fi as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done { ac_configure_args0=; unset ac_configure_args0;} { ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there # would cause problems or look ugly. # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? # Save into config.log some information that might help in debugging. { echo $as_echo "## ---------------- ## ## Cache variables. ## ## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( *${as_nl}ac_space=\ *) sed -n \ "s/'\''/'\''\\\\'\'''\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" ;; #( *) sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) echo $as_echo "## ----------------- ## ## Output variables. ## ## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then $as_echo "## ------------------- ## ## File substitutions. ## ## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac $as_echo "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then $as_echo "## ----------- ## ## confdefs.h. ## ## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && $as_echo "$as_me: caught signal $ac_signal" $as_echo "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h $as_echo "/* confdefs.h */" > confdefs.h # Predefined preprocessor variables. cat >>confdefs.h <<_ACEOF #define PACKAGE_NAME "$PACKAGE_NAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_TARNAME "$PACKAGE_TARNAME" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_VERSION "$PACKAGE_VERSION" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_STRING "$PACKAGE_STRING" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" _ACEOF cat >>confdefs.h <<_ACEOF #define PACKAGE_URL "$PACKAGE_URL" _ACEOF # Let the site file select an alternate cache file if it wants to. # Prefer an explicitly selected file to automatically selected ones. ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then # We do not want a PATH search for config.site. case $CONFIG_SITE in #(( -*) ac_site_file1=./$CONFIG_SITE;; */*) ac_site_file1=$CONFIG_SITE;; *) ac_site_file1=./$CONFIG_SITE;; esac elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site else ac_site_file1=$ac_default_prefix/share/config.site ac_site_file2=$ac_default_prefix/etc/config.site fi for ac_site_file in "$ac_site_file1" "$ac_site_file2" do test "x$ac_site_file" = xNONE && continue if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file See \`config.log' for more details" "$LINENO" 5; } fi done if test -r "$cache_file"; then # Some versions of bash will fail to source /dev/null (special files # actually), so we avoid doing that. DJGPP emulates it as a regular file. if test /dev/null != "$cache_file" && test -f "$cache_file"; then { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 $as_echo "$as_me: loading cache $cache_file" >&6;} case $cache_file in [\\/]* | ?:[\\/]* ) . "$cache_file";; *) . "./$cache_file";; esac fi else { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 $as_echo "$as_me: creating cache $cache_file" >&6;} >$cache_file fi # Check that the precious variables saved in the cache have kept the same # value. ac_cache_corrupted=false for ac_var in $ac_precious_vars; do eval ac_old_set=\$ac_cv_env_${ac_var}_set eval ac_new_set=\$ac_env_${ac_var}_set eval ac_old_val=\$ac_cv_env_${ac_var}_value eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 $as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) if test "x$ac_old_val" != "x$ac_new_val"; then # differences in whitespace do not lead to failure. ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 $as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 $as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 $as_echo "$as_me: former value: \`$ac_old_val'" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 $as_echo "$as_me: current value: \`$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. if test "$ac_new_set" = set; then case $ac_new_val in *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; *) ac_arg=$ac_var=$ac_new_val ;; esac case " $ac_configure_args " in *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. *) as_fn_append ac_configure_args " '$ac_arg'" ;; esac fi done if $ac_cache_corrupted; then { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## ## -------------------- ## ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_config_headers="$ac_config_headers Source/config.h" if test -n "$GNUSTEP_MAKEFILES"; then #-------------------------------------------------------------------- # Use config.guess, config.sub and install-sh provided by gnustep-make #-------------------------------------------------------------------- ac_aux_dir= for ac_dir in $GNUSTEP_MAKEFILES "$srcdir"/$GNUSTEP_MAKEFILES; do if test -f "$ac_dir/install-sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install-sh -c" break elif test -f "$ac_dir/install.sh"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/install.sh -c" break elif test -f "$ac_dir/shtool"; then ac_aux_dir=$ac_dir ac_install_sh="$ac_aux_dir/shtool install -c" break fi done if test -z "$ac_aux_dir"; then as_fn_error $? "cannot find install-sh, install.sh, or shtool in $GNUSTEP_MAKEFILES \"$srcdir\"/$GNUSTEP_MAKEFILES" "$LINENO" 5 fi # These three variables are undocumented and unsupported, # and are intended to be withdrawn in a future Autoconf release. # They can cause serious problems if a builder's source tree is in a directory # whose full name contains unusual characters. ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. #-------------------------------------------------------------------- # Determine the host, build, and target systems #-------------------------------------------------------------------- # Make sure we can run config.sub. $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 $as_echo_n "checking build system type... " >&6; } if ${ac_cv_build+:} false; then : $as_echo_n "(cached) " >&6 else ac_build_alias=$build_alias test "x$ac_build_alias" = x && ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` test "x$ac_build_alias" = x && as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 $as_echo "$ac_cv_build" >&6; } case $ac_cv_build in *-*-*) ;; *) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; esac build=$ac_cv_build ac_save_IFS=$IFS; IFS='-' set x $ac_cv_build shift build_cpu=$1 build_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: build_os=$* IFS=$ac_save_IFS case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 $as_echo_n "checking host system type... " >&6; } if ${ac_cv_host+:} false; then : $as_echo_n "(cached) " >&6 else if test "x$host_alias" = x; then ac_cv_host=$ac_cv_build else ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 $as_echo "$ac_cv_host" >&6; } case $ac_cv_host in *-*-*) ;; *) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; esac host=$ac_cv_host ac_save_IFS=$IFS; IFS='-' set x $ac_cv_host shift host_cpu=$1 host_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: host_os=$* IFS=$ac_save_IFS case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking target system type" >&5 $as_echo_n "checking target system type... " >&6; } if ${ac_cv_target+:} false; then : $as_echo_n "(cached) " >&6 else if test "x$target_alias" = x; then ac_cv_target=$ac_cv_host else ac_cv_target=`$SHELL "$ac_aux_dir/config.sub" $target_alias` || as_fn_error $? "$SHELL $ac_aux_dir/config.sub $target_alias failed" "$LINENO" 5 fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_target" >&5 $as_echo "$ac_cv_target" >&6; } case $ac_cv_target in *-*-*) ;; *) as_fn_error $? "invalid value of canonical target" "$LINENO" 5;; esac target=$ac_cv_target ac_save_IFS=$IFS; IFS='-' set x $ac_cv_target shift target_cpu=$1 target_vendor=$2 shift; shift # Remember, the first character of IFS is used to create $*, # except with old shells: target_os=$* IFS=$ac_save_IFS case $target_os in *\ *) target_os=`echo "$target_os" | sed 's/ /-/g'`;; esac # The aliases save the names the user supplied, while $host etc. # will get canonicalized. test -n "$target_alias" && test "$program_prefix$program_suffix$program_transform_name" = \ NONENONEs,x,x, && program_prefix=${target_alias}- fi #-------------------------------------------------------------------- # Find the compiler #-------------------------------------------------------------------- ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" # Try to create an executable without -o first, disregard a.out. # It will help us diagnose broken compilers, and finding out an intuition # of exeext. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 $as_echo_n "checking whether the C compiler works... " >&6; } ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` # The possible output files: ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" ac_rmfiles= for ac_file in $ac_files do case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; * ) ac_rmfiles="$ac_rmfiles $ac_file";; esac done rm -f $ac_rmfiles if { { ac_try="$ac_link_default" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link_default") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. # So ignore a value of `no', otherwise this would lead to `EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. for ac_file in $ac_files '' do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; [ab].out ) # We found the default executable, but exeext='' is most # certainly right. break;; *.* ) if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; then :; else ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not # safe: cross compilers may not add the suffix if given an `-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. break;; * ) break;; esac done test "$ac_cv_exeext" = no && ac_cv_exeext= else ac_file='' fi if test -z "$ac_file"; then : { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables See \`config.log' for more details" "$LINENO" 5; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 $as_echo_n "checking for C compiler default output file name... " >&6; } { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 $as_echo "$ac_file" >&6; } ac_exeext=$ac_cv_exeext rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 $as_echo_n "checking for suffix of executables... " >&6; } if { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : # If both `conftest.exe' and `conftest' are `present' (well, observable) # catch `conftest.exe'. For instance with Cygwin, `ls conftest' will # work properly (i.e., refer to `conftest.exe'), while it won't with # `rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` break;; * ) break;; esac done else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 $as_echo "$ac_cv_exeext" >&6; } rm -f conftest.$ac_ext EXEEXT=$ac_cv_exeext ac_exeext=$EXEEXT cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { FILE *f = fopen ("conftest.out", "w"); return ferror (f) || fclose (f) != 0; ; return 0; } _ACEOF ac_clean_files="$ac_clean_files conftest.out" # Check that the compiler produces executables we can run. If not, either # the compiler is broken, or we cross compile. { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 $as_echo_n "checking whether we are cross compiling... " >&6; } if test "$cross_compiling" != yes; then { { ac_try="$ac_link" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_link") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } if { ac_try='./conftest$ac_cv_exeext' { { case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_try") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; }; then cross_compiling=no else if test "$cross_compiling" = maybe; then cross_compiling=yes else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run C compiled programs. If you meant to cross compile, use \`--host'. See \`config.log' for more details" "$LINENO" 5; } fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 $as_echo "$cross_compiling" >&6; } rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } if ${ac_cv_objext+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF rm -f conftest.o conftest.obj if { { ac_try="$ac_compile" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compile") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then : for ac_file in conftest.o conftest.obj conftest.*; do test -f "$ac_file" || continue; case $ac_file in *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` break;; esac done else $as_echo "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 $as_echo "$ac_cv_objext" >&6; } OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 $as_echo_n "checking how to run the C preprocessor... " >&6; } # On Suns, sometimes $CPP names a directory. if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then if ${ac_cv_prog_CPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" do ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi done ac_cv_prog_CPP=$CPP fi CPP=$ac_cv_prog_CPP else ac_cv_prog_CPP=$CPP fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 $as_echo "$CPP" >&6; } ac_preproc_ok=false for ac_c_preproc_warn_flag in '' yes do # Use a header file that comes with gcc, so configuring glibc # with a fresh cross-compiler works. # Prefer to if __STDC__ is defined, since # exists even on freestanding compilers. # On the NeXT, cc -E runs the code through the compiler's parser, # not just through cpp. "Syntax error" is here to catch this case. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifdef __STDC__ # include #else # include #endif Syntax error _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : else # Broken: fails on valid input. continue fi rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if ac_fn_c_try_cpp "$LINENO"; then : # Broken: success on invalid input. continue else # Passes both tests. ac_preproc_ok=: break fi rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C preprocessor \"$CPP\" fails sanity check See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. set dummy ${ac_tool_prefix}gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_prog_CC"; then ac_ct_CC=$CC # Extract the first word of "gcc", so it can be a program name with args. set dummy gcc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="gcc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi else CC="$ac_cv_prog_CC" fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. set dummy ${ac_tool_prefix}cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="${ac_tool_prefix}cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi fi if test -z "$CC"; then # Extract the first word of "cc", so it can be a program name with args. set dummy cc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then ac_prog_rejected=yes continue fi ac_cv_prog_CC="cc" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS if test $ac_prog_rejected = yes; then # We found a bogon in the path, so make sure we never use it. set dummy $ac_cv_prog_CC shift if test $# != 0; then # We chose a different compiler from the bogus one. # However, it has the same basename, so the bogon will be chosen # first if we set CC to just the basename; use the full file name. shift ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" fi fi fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$CC"; then if test -n "$ac_tool_prefix"; then for ac_prog in cl.exe do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_CC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi CC=$ac_cv_prog_CC if test -n "$CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 $as_echo "$CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$CC" && break done fi if test -z "$CC"; then ac_ct_CC=$CC for ac_prog in cl.exe do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_CC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 $as_echo "$ac_ct_CC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_CC" && break done if test "x$ac_ct_CC" = x; then CC="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac CC=$ac_ct_CC fi fi fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 $as_echo "$ac_cv_c_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GCC=yes else GCC= fi ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes else CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : else ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_c_werror_flag=$ac_save_c_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 $as_echo "$ac_cv_prog_cc_g" >&6; } if test "$ac_test_CFLAGS" = set; then CFLAGS=$ac_save_CFLAGS elif test $ac_cv_prog_cc_g = yes; then if test "$GCC" = yes; then CFLAGS="-g -O2" else CFLAGS="-g" fi else if test "$GCC" = yes; then CFLAGS="-O2" else CFLAGS= fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include struct stat; /* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ struct buf { int x; }; FILE * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; { return p[i]; } static char *f (char * (*g) (char **, int), char **p, ...) { char *s; va_list v; va_start (v,p); s = g (p, va_arg (v,int)); va_end (v); return s; } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not '\xHH' hex character constants. These don't provoke an error unfortunately, instead are silently treated as 'x'. The following induces an error, until -std is added to get proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an array size at least. It's necessary to write '\x00'==0 to get something that's true only with -std. */ int osf4_cc_array ['\x00' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ #define FOO(x) 'x' int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); int argc; char **argv; int main () { return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; ; return 0; } _ACEOF for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" do CC="$ac_save_CC $ac_arg" if ac_fn_c_try_compile "$LINENO"; then : ac_cv_prog_cc_c89=$ac_arg fi rm -f core conftest.err conftest.$ac_objext test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext CC=$ac_save_CC fi # AC_CACHE_VAL case "x$ac_cv_prog_cc_c89" in x) { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 $as_echo "none needed" >&6; } ;; xno) { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 $as_echo "unsupported" >&6; } ;; *) CC="$CC $ac_cv_prog_cc_c89" { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 $as_echo "$ac_cv_prog_cc_c89" >&6; } ;; esac if test "x$ac_cv_prog_cc_c89" != xno; then : fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_ext=m ac_cpp='$OBJCPP $CPPFLAGS' ac_compile='$OBJC -c $OBJCFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$OBJC -o conftest$ac_exeext $OBJCFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_objc_compiler_gnu if test -n "$ac_tool_prefix"; then for ac_prog in gcc objcc objc cc CC do # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_OBJC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OBJC"; then ac_cv_prog_OBJC="$OBJC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_OBJC="$ac_tool_prefix$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi OBJC=$ac_cv_prog_OBJC if test -n "$OBJC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $OBJC" >&5 $as_echo "$OBJC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$OBJC" && break done fi if test -z "$OBJC"; then ac_ct_OBJC=$OBJC for ac_prog in gcc objcc objc cc CC do # Extract the first word of "$ac_prog", so it can be a program name with args. set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_prog_ac_ct_OBJC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OBJC"; then ac_cv_prog_ac_ct_OBJC="$ac_ct_OBJC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_prog_ac_ct_OBJC="$ac_prog" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS fi fi ac_ct_OBJC=$ac_cv_prog_ac_ct_OBJC if test -n "$ac_ct_OBJC"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_OBJC" >&5 $as_echo "$ac_ct_OBJC" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi test -n "$ac_ct_OBJC" && break done if test "x$ac_ct_OBJC" = x; then OBJC="gcc" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac OBJC=$ac_ct_OBJC fi fi # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for Objective C compiler version" >&5 set X $ac_compile ac_compiler=$2 for ac_option in --version -v -V -qversion; do { { ac_try="$ac_compiler $ac_option >&5" case "(($ac_try" in *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; *) ac_try_echo=$ac_try;; esac eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" $as_echo "$ac_try_echo"; } >&5 (eval "$ac_compiler $ac_option >&5") 2>conftest.err ac_status=$? if test -s conftest.err; then sed '10a\ ... rest of stderr output deleted ... 10q' conftest.err >conftest.er1 cat conftest.er1 >&5 fi rm -f conftest.er1 conftest.err $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU Objective C compiler" >&5 $as_echo_n "checking whether we are using the GNU Objective C compiler... " >&6; } if ${ac_cv_objc_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { #ifndef __GNUC__ choke me #endif ; return 0; } _ACEOF if ac_fn_objc_try_compile "$LINENO"; then : ac_compiler_gnu=yes else ac_compiler_gnu=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_cv_objc_compiler_gnu=$ac_compiler_gnu fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objc_compiler_gnu" >&5 $as_echo "$ac_cv_objc_compiler_gnu" >&6; } if test $ac_compiler_gnu = yes; then GOBJC=yes else GOBJC= fi ac_test_OBJCFLAGS=${OBJCFLAGS+set} ac_save_OBJCFLAGS=$OBJCFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $OBJC accepts -g" >&5 $as_echo_n "checking whether $OBJC accepts -g... " >&6; } if ${ac_cv_prog_objc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_objc_werror_flag=$ac_objc_werror_flag ac_objc_werror_flag=yes ac_cv_prog_objc_g=no OBJCFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_objc_try_compile "$LINENO"; then : ac_cv_prog_objc_g=yes else OBJCFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_objc_try_compile "$LINENO"; then : else ac_objc_werror_flag=$ac_save_objc_werror_flag OBJCFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main () { ; return 0; } _ACEOF if ac_fn_objc_try_compile "$LINENO"; then : ac_cv_prog_objc_g=yes fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext ac_objc_werror_flag=$ac_save_objc_werror_flag fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_objc_g" >&5 $as_echo "$ac_cv_prog_objc_g" >&6; } if test "$ac_test_OBJCFLAGS" = set; then OBJCFLAGS=$ac_save_OBJCFLAGS elif test $ac_cv_prog_objc_g = yes; then if test "$GOBJC" = yes; then OBJCFLAGS="-g -O2" else OBJCFLAGS="-g" fi else if test "$GOBJC" = yes; then OBJCFLAGS="-O2" else OBJCFLAGS= fi fi ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu # Check for header files. { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 $as_echo_n "checking for grep that handles long lines and -e... " >&6; } if ${ac_cv_path_GREP+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in grep ggrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_GREP" || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_GREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_GREP=$GREP fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 $as_echo "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 $as_echo_n "checking for egrep... " >&6; } if ${ac_cv_path_EGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then ac_path_EGREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_prog in egrep; do for ac_exec_ext in '' $ac_executable_extensions; do ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" as_fn_executable_p "$ac_path_EGREP" || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 $as_echo_n 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" $as_echo 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_max=$ac_count fi # 10*(2^10) chars as input seems more than enough test $ac_count -gt 10 && break done rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac $ac_path_EGREP_found && break 3 done done done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_EGREP=$EGREP fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 $as_echo "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #include #include int main () { ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_header_stdc=yes else ac_cv_header_stdc=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_header_stdc = yes; then # SunOS 4.x string.h does not declare mem*, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "memchr" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include _ACEOF if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | $EGREP "free" >/dev/null 2>&1; then : else ac_cv_header_stdc=no fi rm -f conftest* fi if test $ac_cv_header_stdc = yes; then # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. if test "$cross_compiling" = yes; then : : else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include #if ((' ' & 0x0FF) == 0x020) # define ISLOWER(c) ('a' <= (c) && (c) <= 'z') # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) #else # define ISLOWER(c) \ (('a' <= (c) && (c) <= 'i') \ || ('j' <= (c) && (c) <= 'r') \ || ('s' <= (c) && (c) <= 'z')) # define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) #endif #define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) int main () { int i; for (i = 0; i < 256; i++) if (XOR (islower (i), ISLOWER (i)) || toupper (i) != TOUPPER (i)) return 2; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : else ac_cv_header_stdc=no fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 $as_echo "$ac_cv_header_stdc" >&6; } if test $ac_cv_header_stdc = yes; then $as_echo "#define STDC_HEADERS 1" >>confdefs.h fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for inline" >&5 $as_echo_n "checking for inline... " >&6; } if ${ac_cv_c_inline+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_c_inline=no for ac_kw in inline __inline__ __inline; do cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifndef __cplusplus typedef int foo_t; static $ac_kw foo_t static_foo () {return 0; } $ac_kw foo_t foo () {return 0; } #endif _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_inline=$ac_kw fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext test "$ac_cv_c_inline" != no && break done fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_inline" >&5 $as_echo "$ac_cv_c_inline" >&6; } case $ac_cv_c_inline in inline | yes) ;; *) case $ac_cv_c_inline in no) ac_val=;; *) ac_val=$ac_cv_c_inline;; esac cat >>confdefs.h <<_ACEOF #ifndef __cplusplus #define inline $ac_val #endif _ACEOF ;; esac # On IRIX 5.3, sys/types and inttypes.h are conflicting. for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ inttypes.h stdint.h unistd.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default " if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF fi done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5 $as_echo_n "checking whether byte ordering is bigendian... " >&6; } if ${ac_cv_c_bigendian+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_c_bigendian=unknown # See if we're dealing with a universal compiler. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #ifndef __APPLE_CC__ not a universal capable compiler #endif typedef int dummy; _ACEOF if ac_fn_c_try_compile "$LINENO"; then : # Check for potential -arch flags. It is not universal unless # there are at least two -arch flags with different values. ac_arch= ac_prev= for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do if test -n "$ac_prev"; then case $ac_word in i?86 | x86_64 | ppc | ppc64) if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then ac_arch=$ac_word else ac_cv_c_bigendian=universal break fi ;; esac ac_prev= elif test "x$ac_word" = "x-arch"; then ac_prev=arch fi done fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext if test $ac_cv_c_bigendian = unknown; then # See if sys/param.h defines the BYTE_ORDER macro. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main () { #if ! (defined BYTE_ORDER && defined BIG_ENDIAN \ && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \ && LITTLE_ENDIAN) bogus endian macros #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : # It does; now see whether it defined to BIG_ENDIAN or not. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include #include int main () { #if BYTE_ORDER != BIG_ENDIAN not big endian #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_bigendian=yes else ac_cv_c_bigendian=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi if test $ac_cv_c_bigendian = unknown; then # See if defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris). cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { #if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN) bogus endian macros #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : # It does; now see whether it defined to _BIG_ENDIAN or not. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include int main () { #ifndef _BIG_ENDIAN not big endian #endif ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : ac_cv_c_bigendian=yes else ac_cv_c_bigendian=no fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi if test $ac_cv_c_bigendian = unknown; then # Compile a test program. if test "$cross_compiling" = yes; then : # Try to guess by grepping values from an object file. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ short int ascii_mm[] = { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; short int ascii_ii[] = { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; int use_ascii (int i) { return ascii_mm[i] + ascii_ii[i]; } short int ebcdic_ii[] = { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; short int ebcdic_mm[] = { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; int use_ebcdic (int i) { return ebcdic_mm[i] + ebcdic_ii[i]; } extern int foo; int main () { return use_ascii (foo) == use_ebcdic (foo); ; return 0; } _ACEOF if ac_fn_c_try_compile "$LINENO"; then : if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then ac_cv_c_bigendian=yes fi if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then if test "$ac_cv_c_bigendian" = unknown; then ac_cv_c_bigendian=no else # finding both strings is unlikely to happen, but who knows? ac_cv_c_bigendian=unknown fi fi fi rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext else cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int main () { /* Are we little or big endian? From Harbison&Steele. */ union { long int l; char c[sizeof (long int)]; } u; u.l = 1; return u.c[sizeof (long int) - 1] == 1; ; return 0; } _ACEOF if ac_fn_c_try_run "$LINENO"; then : ac_cv_c_bigendian=no else ac_cv_c_bigendian=yes fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5 $as_echo "$ac_cv_c_bigendian" >&6; } case $ac_cv_c_bigendian in #( yes) GS_WORDS_BIGENDIAN_DEFINE="#define __BIG_ENDIAN__ 1" ;; #( no) GS_WORDS_BIGENDIAN_DEFINE="#define __LITTLE_ENDIAN__ 1" ;; #( universal) $as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h ;; #( *) as_fn_error $? "Could not determine CPU endianness." "$LINENO" 5 ;; esac # Gather information about the data model so we can define the data types # GS_CHECK_DATA_MODEL # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of char" >&5 $as_echo_n "checking size of char... " >&6; } if ${ac_cv_sizeof_char+:} false; then : $as_echo_n "(cached) " >&6 else if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (char))" "ac_cv_sizeof_char" "$ac_includes_default"; then : else if test "$ac_cv_type_char" = yes; then { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (char) See \`config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_char=0 fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_char" >&5 $as_echo "$ac_cv_sizeof_char" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_CHAR $ac_cv_sizeof_char _ACEOF # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of short" >&5 $as_echo_n "checking size of short... " >&6; } if ${ac_cv_sizeof_short+:} false; then : $as_echo_n "(cached) " >&6 else if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (short))" "ac_cv_sizeof_short" "$ac_includes_default"; then : else if test "$ac_cv_type_short" = yes; then { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (short) See \`config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_short=0 fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_short" >&5 $as_echo "$ac_cv_sizeof_short" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_SHORT $ac_cv_sizeof_short _ACEOF # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of int" >&5 $as_echo_n "checking size of int... " >&6; } if ${ac_cv_sizeof_int+:} false; then : $as_echo_n "(cached) " >&6 else if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (int))" "ac_cv_sizeof_int" "$ac_includes_default"; then : else if test "$ac_cv_type_int" = yes; then { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (int) See \`config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_int=0 fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_int" >&5 $as_echo "$ac_cv_sizeof_int" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_INT $ac_cv_sizeof_int _ACEOF # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long" >&5 $as_echo_n "checking size of long... " >&6; } if ${ac_cv_sizeof_long+:} false; then : $as_echo_n "(cached) " >&6 else if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long))" "ac_cv_sizeof_long" "$ac_includes_default"; then : else if test "$ac_cv_type_long" = yes; then { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (long) See \`config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_long=0 fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long" >&5 $as_echo "$ac_cv_sizeof_long" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_LONG $ac_cv_sizeof_long _ACEOF # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long long" >&5 $as_echo_n "checking size of long long... " >&6; } if ${ac_cv_sizeof_long_long+:} false; then : $as_echo_n "(cached) " >&6 else if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long long))" "ac_cv_sizeof_long_long" "$ac_includes_default"; then : else if test "$ac_cv_type_long_long" = yes; then { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (long long) See \`config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_long_long=0 fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long_long" >&5 $as_echo "$ac_cv_sizeof_long_long" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_LONG_LONG $ac_cv_sizeof_long_long _ACEOF # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of void *" >&5 $as_echo_n "checking size of void *... " >&6; } if ${ac_cv_sizeof_void_p+:} false; then : $as_echo_n "(cached) " >&6 else if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (void *))" "ac_cv_sizeof_void_p" "$ac_includes_default"; then : else if test "$ac_cv_type_void_p" = yes; then { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (void *) See \`config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_void_p=0 fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_void_p" >&5 $as_echo "$ac_cv_sizeof_void_p" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_VOID_P $ac_cv_sizeof_void_p _ACEOF { $as_echo "$as_me:${as_lineno-$LINENO}: checking for data model" >&5 $as_echo_n "checking for data model... " >&6; } if ${gs_cv_c_data_model+:} false; then : $as_echo_n "(cached) " >&6 else _gs_data_model="$ac_cv_sizeof_char$ac_cv_sizeof_short$ac_cv_sizeof_int$ac_cv_sizeof_long$ac_cv_sizeof_long_long$ac_cv_sizeof_void_p" case $_gs_data_model in #( 122484) : gs_cv_c_data_model="LP32" ;; #( 124484) : gs_cv_c_data_model="ILP32" ;; #( 124488) : gs_cv_c_data_model="LLP64" ;; #( 124888) : gs_cv_c_data_model="LP64" ;; #( *) : gs_cv_c_data_model="unknown" ;; esac fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $gs_cv_c_data_model" >&5 $as_echo "$gs_cv_c_data_model" >&6; } cat >>confdefs.h <<_ACEOF #define DATA_MODEL DATA_MODEL_$gs_cv_c_data_model _ACEOF GS_SINT8_T="signed char" GS_UINT8_T="unsigned char" GS_SINT16_T="signed short" GS_UINT16_T="unsigned short" GS_SINT64_T="signed long long" GS_UINT64_T="unsigned long long" case $gs_cv_c_data_model in #( LP32) : GS_SINT32_T="signed long" GS_UINT32_T="unsigned long" GS_SINTPTR_T="signed long" GS_UINTPTR_T="unsigned long" ;; #( ILP32) : GS_SINT32_T="signed int" GS_UINT32_T="unsigned int" GS_SINTPTR_T="signed int" GS_UINTPTR_T="unsigned int" ;; #( LLP64) : GS_SINT32_T="signed int" GS_UINT32_T="unsigned int" GS_SINTPTR_T="signed long long" GS_UINTPTR_T="unsigned long long" ;; #( LP64) : GS_SINT32_T="signed int" GS_UINT32_T="unsigned int" GS_SINTPTR_T="signed long" GS_UINTPTR_T="unsigned long" ;; #( *) : as_fn_error $? "Could not identify the architecture's data model." "$LINENO" 5 ;; esac # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of double" >&5 $as_echo_n "checking size of double... " >&6; } if ${ac_cv_sizeof_double+:} false; then : $as_echo_n "(cached) " >&6 else if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (double))" "ac_cv_sizeof_double" "$ac_includes_default"; then : else if test "$ac_cv_type_double" = yes; then { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (double) See \`config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_double=0 fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_double" >&5 $as_echo "$ac_cv_sizeof_double" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_DOUBLE $ac_cv_sizeof_double _ACEOF # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects # declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of long double" >&5 $as_echo_n "checking size of long double... " >&6; } if ${ac_cv_sizeof_long_double+:} false; then : $as_echo_n "(cached) " >&6 else if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long double))" "ac_cv_sizeof_long_double" "$ac_includes_default"; then : else if test "$ac_cv_type_long_double" = yes; then { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (long double) See \`config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_long_double=0 fi fi fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long_double" >&5 $as_echo "$ac_cv_sizeof_long_double" >&6; } cat >>confdefs.h <<_ACEOF #define SIZEOF_LONG_DOUBLE $ac_cv_sizeof_long_double _ACEOF #-------------------------------------------------------------------- # Check for CFRunLoop support # Android and QNX have pthread in libc instead of libpthread #-------------------------------------------------------------------- # Check whether --enable-cfrunloop was given. if test "${enable_cfrunloop+set}" = set; then : enableval=$enable_cfrunloop; else for ac_header in unistd.h fcntl.h poll.h limits.h pthread.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing pthread_join" >&5 $as_echo_n "checking for library containing pthread_join... " >&6; } if ${ac_cv_search_pthread_join+:} false; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char pthread_join (); int main () { return pthread_join (); ; return 0; } _ACEOF for ac_lib in '' pthread pthreadG32 pthreadVC2; do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_pthread_join=$ac_res fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext if ${ac_cv_search_pthread_join+:} false; then : break fi done if ${ac_cv_search_pthread_join+:} false; then : else ac_cv_search_pthread_join=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_pthread_join" >&5 $as_echo "$ac_cv_search_pthread_join" >&6; } ac_res=$ac_cv_search_pthread_join if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" $as_echo "#define HAVE_CFRUNLOOP_SUPPORT 1" >>confdefs.h else as_fn_error $? "Missing pthread library for CFRunLoop support." "$LINENO" 5 fi else as_fn_error $? "Missing headers for CFRunLoop support." "$LINENO" 5 fi done fi #--- # Check for ICU #--- # Check whether --with-icu was given. if test "${with_icu+set}" = set; then : withval=$with_icu; else with_icu=yes fi if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then if test -n "$ac_tool_prefix"; then # Extract the first word of "${ac_tool_prefix}pkg-config", so it can be a program name with args. set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_PKG_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $PKG_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_PKG_CONFIG="$PKG_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi PKG_CONFIG=$ac_cv_path_PKG_CONFIG if test -n "$PKG_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PKG_CONFIG" >&5 $as_echo "$PKG_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi fi if test -z "$ac_cv_path_PKG_CONFIG"; then ac_pt_PKG_CONFIG=$PKG_CONFIG # Extract the first word of "pkg-config", so it can be a program name with args. set dummy pkg-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } if ${ac_cv_path_ac_pt_PKG_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $ac_pt_PKG_CONFIG in [\\/]* | ?:[\\/]*) ac_cv_path_ac_pt_PKG_CONFIG="$ac_pt_PKG_CONFIG" # Let the user override the test with a path. ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then ac_cv_path_ac_pt_PKG_CONFIG="$as_dir/$ac_word$ac_exec_ext" $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 break 2 fi done done IFS=$as_save_IFS ;; esac fi ac_pt_PKG_CONFIG=$ac_cv_path_ac_pt_PKG_CONFIG if test -n "$ac_pt_PKG_CONFIG"; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_PKG_CONFIG" >&5 $as_echo "$ac_pt_PKG_CONFIG" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } fi if test "x$ac_pt_PKG_CONFIG" = x; then PKG_CONFIG="" else case $cross_compiling:$ac_tool_warned in yes:) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 $as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} ac_tool_warned=yes ;; esac PKG_CONFIG=$ac_pt_PKG_CONFIG fi else PKG_CONFIG="$ac_cv_path_PKG_CONFIG" fi fi if test -n "$PKG_CONFIG"; then _pkg_min_version=0.9.0 { $as_echo "$as_me:${as_lineno-$LINENO}: checking pkg-config is at least version $_pkg_min_version" >&5 $as_echo_n "checking pkg-config is at least version $_pkg_min_version... " >&6; } if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } PKG_CONFIG="" fi fi if test x"with_icu" != xno; then : found_icu=no case $target_os in #( mingw*|windows) : # check for ICU bundled with Windows 10 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for udat_open in -licu" >&5 $as_echo_n "checking for udat_open in -licu... " >&6; } if ${ac_cv_lib_icu_udat_open+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-licu $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char udat_open (); int main () { return udat_open (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_icu_udat_open=yes else ac_cv_lib_icu_udat_open=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_icu_udat_open" >&5 $as_echo "$ac_cv_lib_icu_udat_open" >&6; } if test "x$ac_cv_lib_icu_udat_open" = xyes; then : for ac_header in icu.h do : ac_fn_c_check_header_mongrel "$LINENO" "icu.h" "ac_cv_header_icu_h" "$ac_includes_default" if test "x$ac_cv_header_icu_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_ICU_H 1 _ACEOF found_icu=yes LIBS="$LIBS -licu" { $as_echo "$as_me:${as_lineno-$LINENO}: Using ICU DLL from Windows 10 (requires version 1903)" >&5 $as_echo "$as_me: Using ICU DLL from Windows 10 (requires version 1903)" >&6;} fi done fi ;; #( *) : ;; esac if test $found_icu = no; then : pkg_failed=no { $as_echo "$as_me:${as_lineno-$LINENO}: checking for icu-i18n > 49.0" >&5 $as_echo_n "checking for icu-i18n > 49.0... " >&6; } if test -n "$ICU_CFLAGS"; then pkg_cv_ICU_CFLAGS="$ICU_CFLAGS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"icu-i18n > 49.0\""; } >&5 ($PKG_CONFIG --exists --print-errors "icu-i18n > 49.0") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_ICU_CFLAGS=`$PKG_CONFIG --cflags "icu-i18n > 49.0" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test -n "$ICU_LIBS"; then pkg_cv_ICU_LIBS="$ICU_LIBS" elif test -n "$PKG_CONFIG"; then if test -n "$PKG_CONFIG" && \ { { $as_echo "$as_me:${as_lineno-$LINENO}: \$PKG_CONFIG --exists --print-errors \"icu-i18n > 49.0\""; } >&5 ($PKG_CONFIG --exists --print-errors "icu-i18n > 49.0") 2>&5 ac_status=$? $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; }; then pkg_cv_ICU_LIBS=`$PKG_CONFIG --libs "icu-i18n > 49.0" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes else pkg_failed=yes fi else pkg_failed=untried fi if test $pkg_failed = yes; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi if test $_pkg_short_errors_supported = yes; then ICU_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "icu-i18n > 49.0" 2>&1` else ICU_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "icu-i18n > 49.0" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$ICU_PKG_ERRORS" >&5 as_fn_error $? "Package requirements (icu-i18n > 49.0) were not met: $ICU_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. Alternatively, you may set the environment variables ICU_CFLAGS and ICU_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details." "$LINENO" 5 elif test $pkg_failed = untried; then { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 $as_echo "no" >&6; } { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. Alternatively, you may set the environment variables ICU_CFLAGS and ICU_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. To get pkg-config, see . See \`config.log' for more details" "$LINENO" 5; } else ICU_CFLAGS=$pkg_cv_ICU_CFLAGS ICU_LIBS=$pkg_cv_ICU_LIBS { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } fi LIBS="$LIBS $ICU_LIBS"; CFLAGS="$CFLAGS $ICU_CFLAGS"; INCLUDE_FLAGS="$INCLUDE_FLAGS $ICU_CFLAGS" for ac_header in unicode/ucal.h unicode/uchar.h unicode/ucnv.h unicode/ucol.h unicode/ucurr.h unicode/udat.h unicode/udatpg.h unicode/uloc.h unicode/ulocdata.h unicode/unorm2.h unicode/unum.h unicode/usearch.h unicode/uset.h unicode/ustring.h unicode/utrans.h do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF else as_fn_error $? "Could not find required ICU headers." "$LINENO" 5 fi done fi $as_echo "#define HAVE_ICU 1" >>confdefs.h fi #--- # Check for Grand Central Dispatch (libdispatch) #--- # Check whether --with-gcd was given. if test "${with_gcd+set}" = set; then : withval=$with_gcd; else with_gcd=maybe fi if test "x$with_gcd" != xno; then : for ac_header in dispatch/dispatch.h do : ac_fn_c_check_header_mongrel "$LINENO" "dispatch/dispatch.h" "ac_cv_header_dispatch_dispatch_h" "$ac_includes_default" if test "x$ac_cv_header_dispatch_dispatch_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_DISPATCH_DISPATCH_H 1 _ACEOF { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dispatch_get_main_queue_eventfd_np in -ldispatch" >&5 $as_echo_n "checking for dispatch_get_main_queue_eventfd_np in -ldispatch... " >&6; } if ${ac_cv_lib_dispatch_dispatch_get_main_queue_eventfd_np+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-ldispatch $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char dispatch_get_main_queue_eventfd_np (); int main () { return dispatch_get_main_queue_eventfd_np (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_dispatch_dispatch_get_main_queue_eventfd_np=yes else ac_cv_lib_dispatch_dispatch_get_main_queue_eventfd_np=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dispatch_dispatch_get_main_queue_eventfd_np" >&5 $as_echo "$ac_cv_lib_dispatch_dispatch_get_main_queue_eventfd_np" >&6; } if test "x$ac_cv_lib_dispatch_dispatch_get_main_queue_eventfd_np" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBDISPATCH 1 _ACEOF LIBS="-ldispatch $LIBS" else if test "x$with_gcd" = "xyes"; then : as_fn_error $? "Compatible libdispatch not found for GCD support!" "$LINENO" 5 fi fi else as_fn_error $? "Could not find the Grand Central Dispatch headers." "$LINENO" 5 fi done fi #--- # Check for the Objective-C runtime #--- # Check whether --with-objc was given. if test "${with_objc+set}" = set; then : withval=$with_objc; else with_objc=yes fi if test "x$with_objc" != xno; then : for ac_header in objc/runtime.h do : ac_fn_c_check_header_mongrel "$LINENO" "objc/runtime.h" "ac_cv_header_objc_runtime_h" "$ac_includes_default" if test "x$ac_cv_header_objc_runtime_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_OBJC_RUNTIME_H 1 _ACEOF { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing objc_getClass" >&5 $as_echo_n "checking for library containing objc_getClass... " >&6; } if ${ac_cv_search_objc_getClass+:} false; then : $as_echo_n "(cached) " >&6 else ac_func_search_save_LIBS=$LIBS cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char objc_getClass (); int main () { return objc_getClass (); ; return 0; } _ACEOF for ac_lib in '' objc objc2; do if test -z "$ac_lib"; then ac_res="none required" else ac_res=-l$ac_lib LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi if ac_fn_c_try_link "$LINENO"; then : ac_cv_search_objc_getClass=$ac_res fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext if ${ac_cv_search_objc_getClass+:} false; then : break fi done if ${ac_cv_search_objc_getClass+:} false; then : else ac_cv_search_objc_getClass=no fi rm conftest.$ac_ext LIBS=$ac_func_search_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_objc_getClass" >&5 $as_echo "$ac_cv_search_objc_getClass" >&6; } ac_res=$ac_cv_search_objc_getClass if test "$ac_res" != no; then : test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" else as_fn_error $? "Objective-C library not found! Use --without-objc-bridge to explicitly disable the toll-free bridge or install the Objective-C library." "$LINENO" 5 fi else as_fn_error $? "Could not find the Objective-C runtime header." "$LINENO" 5 fi done fi #--- # Check for zoneinfo directory #--- # Check whether --with-zoneinfo was given. if test "${with_zoneinfo+set}" = set; then : withval=$with_zoneinfo; else with_zoneinfo=no fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking zoneinfo directory" >&5 $as_echo_n "checking zoneinfo directory... " >&6; } if test "x$with_zoneinfo" = xno; then : if test -d "/usr/share/zoneinfo"; then : with_zoneinfo='/usr/share/zoneinfo' elif test -d "/usr/lib/zoneinfo"; then : with_zoneinfo='/usr/lib/zoneinfo' elif test -d "/usr/local/share/zoneinfo"; then : with_zoneinfo='/usr/local/share/zoneinfo' elif test -d "/usr/local/lib/zoneinfo"; then : with_zoneinfo='/usr/local/lib/zoneinfo' elif test -d "/etc/zoneinfo"; then : with_zoneinfo='/etc/zoneinfo' elif test -d "/usr/local/etc/zoneinfo"; then : with_zoneinfo='/usr/local/etc/zoneinfo' fi fi if test "$with_zoneinfo" = "no" || test ! -d "$with_zoneinfo"; then : as_fn_error $? "Please specify a valid zoneinfo directory." "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $with_zoneinfo" >&5 $as_echo "$with_zoneinfo" >&6; } cat >>confdefs.h <<_ACEOF #define TZDIR "$with_zoneinfo" _ACEOF #--- # Check for libm #--- { $as_echo "$as_me:${as_lineno-$LINENO}: checking for modf in -lm" >&5 $as_echo_n "checking for modf in -lm... " >&6; } if ${ac_cv_lib_m_modf+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS LIBS="-lm $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC builtin and then its argument prototype would still apply. */ #ifdef __cplusplus extern "C" #endif char modf (); int main () { return modf (); ; return 0; } _ACEOF if ac_fn_c_try_link "$LINENO"; then : ac_cv_lib_m_modf=yes else ac_cv_lib_m_modf=no fi rm -f core conftest.err conftest.$ac_objext \ conftest$ac_exeext conftest.$ac_ext LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_m_modf" >&5 $as_echo "$ac_cv_lib_m_modf" >&6; } if test "x$ac_cv_lib_m_modf" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBM 1 _ACEOF LIBS="-lm $LIBS" fi #--- # Check for WinSock2 #--- for ac_header in ws2tcpip.h do : ac_fn_c_check_header_mongrel "$LINENO" "ws2tcpip.h" "ac_cv_header_ws2tcpip_h" "$ac_includes_default" if test "x$ac_cv_header_ws2tcpip_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_WS2TCPIP_H 1 _ACEOF fi done ac_config_files="$ac_config_files Source/GNUmakefile Headers/CoreFoundation/CFBase.h" cat >confcache <<\_ACEOF # This file is a shell script that caches the results of configure # tests run on this system so they can be shared between configure # scripts and configure runs, see configure's option --config-cache. # It is not useful on other systems. If it contains results you don't # want to keep, you may remove or edit it. # # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # # `ac_cv_env_foo' variables (set or unset) will be overridden when # loading this file, other *unset* `ac_cv_foo' will be assigned the # following values. _ACEOF # The following way of writing the cache mishandles newlines in values, # but we know of no workaround that is simple, portable, and efficient. # So, we kill variables containing newlines. # Ultrix sh set writes to stderr and can't be redirected directly, # and sets the high bit in the cache file unless we assign to the vars. ( for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do eval ac_val=\$$ac_var case $ac_val in #( *${as_nl}*) case $ac_var in #( *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) # `set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) # `set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | sort ) | sed ' /^ac_cv_env_/b end t clear :clear s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ t end s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then if test "x$cache_file" != "x/dev/null"; then { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} if test ! -f "$cache_file" || test -h "$cache_file"; then cat confcache >"$cache_file" else case $cache_file in #( */* | ?:*) mv -f confcache "$cache_file"$$ && mv -f "$cache_file"$$ "$cache_file" ;; #( *) mv -f confcache "$cache_file" ;; esac fi fi else { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} fi fi rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' ac_i=`$as_echo "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs LTLIBOBJS=$ac_ltlibobjs : "${CONFIG_STATUS=./config.status}" ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 $as_echo "$as_me: creating $CONFIG_STATUS" >&6;} as_write_fail=0 cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. # Compiler output produced by configure, useful for debugging # configure, is in config.log if it exists. debug=false ac_cs_recheck=false ac_cs_silent=false SHELL=\${CONFIG_SHELL-$SHELL} export SHELL _ASEOF cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 ## -------------------- ## ## M4sh Initialization. ## ## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : emulate sh NULLCMD=: # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST else case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; esac fi as_nl=' ' export as_nl # Printing a long string crashes Solaris 7 /usr/bin/printf. as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo # Prefer a ksh shell builtin over an external printf program on Solaris, # but without wasting forks for bash or zsh. if test -z "$BASH_VERSION$ZSH_VERSION" \ && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='print -r --' as_echo_n='print -rn --' elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then as_echo='printf %s\n' as_echo_n='printf %s' else if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' as_echo_n='/usr/ucb/echo -n' else as_echo_body='eval expr "X$1" : "X\\(.*\\)"' as_echo_n_body='eval arg=$1; case $arg in #( *"$as_nl"*) expr "X$arg" : "X\\(.*\\)$as_nl"; arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; esac; expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" ' export as_echo_n_body as_echo_n='sh -c $as_echo_n_body as_echo' fi export as_echo_body as_echo='sh -c $as_echo_body as_echo' fi # The user is always right. if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || PATH_SEPARATOR=';' } fi # IFS # We need space, tab and new line, in precisely that order. Quoting is # there to prevent editors from complaining about space-tab. # (If _AS_PATH_WALK were called with IFS unset, it would disable word # splitting by setting IFS to empty value.) IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS test -z "$as_dir" && as_dir=. test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break done IFS=$as_save_IFS ;; esac # We did not find ourselves, most probably we were run as `sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 exit 1 fi # Unset variables that we do not need and which cause bugs (e.g. in # pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" # suppresses any "Segmentation fault" message there. '((' could # trigger a bug in pdksh 5.2.14. for as_var in BASH_ENV ENV MAIL MAILPATH do eval test x\${$as_var+set} = xset \ && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : done PS1='$ ' PS2='> ' PS4='+ ' # NLS nuisances. LC_ALL=C export LC_ALL LANGUAGE=C export LANGUAGE # CDPATH. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the # script with STATUS, using 1 if that was 0. as_fn_error () { as_status=$1; test $as_status -eq 0 && as_status=1 if test "$4"; then as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. as_fn_set_status () { return $1 } # as_fn_set_status # as_fn_exit STATUS # ----------------- # Exit the shell with STATUS, even in a "trap 0" or "set -e" context. as_fn_exit () { set +e as_fn_set_status $1 exit $1 } # as_fn_exit # as_fn_unset VAR # --------------- # Portably unset VAR. as_fn_unset () { { eval $1=; unset $1;} } as_unset=as_fn_unset # as_fn_append VAR VALUE # ---------------------- # Append the text in VALUE to the end of the definition contained in VAR. Take # advantage of any shell optimizations that allow amortized linear growth over # repeated appends, instead of the typical quadratic growth present in naive # implementations. if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : eval 'as_fn_append () { eval $1+=\$2 }' else as_fn_append () { eval $1=\$$1\$2 } fi # as_fn_append # as_fn_arith ARG... # ------------------ # Perform arithmetic evaluation on the ARGs, and store the result in the # global $as_val. Take advantage of shells that can avoid forks. The arguments # must be portable across $(()) and expr. if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : eval 'as_fn_arith () { as_val=$(( $* )) }' else as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` } fi # as_fn_arith if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr else as_expr=false fi if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then as_basename=basename else as_basename=false fi if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then as_dirname=dirname else as_dirname=false fi as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || $as_echo X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q } /^X\/\(\/\/\)$/{ s//\1/ q } /^X\/\(\/\).*/{ s//\1/ q } s/.*/./; q'` # Avoid depending upon Character Ranges. as_cr_letters='abcdefghijklmnopqrstuvwxyz' as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' as_cr_Letters=$as_cr_letters$as_cr_LETTERS as_cr_digits='0123456789' as_cr_alnum=$as_cr_Letters$as_cr_digits ECHO_C= ECHO_N= ECHO_T= case `echo -n x` in #((((( -n*) case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. xy) ECHO_C='\c';; *) echo `echo ksh88 bug on AIX 6.1` > /dev/null ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir mkdir conf$$.dir 2>/dev/null fi if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. # In both cases, we have to default to `cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then as_ln_s=ln else as_ln_s='cp -pR' fi else as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null # as_fn_mkdir_p # ------------- # Create "$as_dir" as a directory, including parents if necessary. as_fn_mkdir_p () { case $as_dir in #( -*) as_dir=./$as_dir;; esac test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" as_dir=`$as_dirname -- "$as_dir" || $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p if mkdir -p . 2>/dev/null; then as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi # as_fn_executable_p FILE # ----------------------- # Test if FILE is an executable regular file. as_fn_executable_p () { test -f "$1" && test -x "$1" } # as_fn_executable_p as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" # Sed expression to map a string onto a valid variable name. as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" exec 6>&1 ## ----------------------------------- ## ## Main body of $CONFIG_STATUS script. ## ## ----------------------------------- ## _ASEOF test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Save the log message, to keep $0 and so on meaningful, and to # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" This file was extended by libgnustep-corebase $as_me 0.2, which was generated by GNU Autoconf 2.69. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS CONFIG_LINKS = $CONFIG_LINKS CONFIG_COMMANDS = $CONFIG_COMMANDS $ $0 $@ on `(hostname || uname -n) 2>/dev/null | sed 1q` " _ACEOF case $ac_config_files in *" "*) set x $ac_config_files; shift; ac_config_files=$*;; esac case $ac_config_headers in *" "*) set x $ac_config_headers; shift; ac_config_headers=$*;; esac cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 # Files that config.status was made for. config_files="$ac_config_files" config_headers="$ac_config_headers" _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ \`$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. Usage: $0 [OPTION]... [TAG]... -h, --help print this help, then exit -V, --version print version number and configuration settings, then exit --config print configuration, then exit -q, --quiet, --silent do not print progress messages -d, --debug don't remove temporary files --recheck update $as_me by reconfiguring in the same conditions --file=FILE[:TEMPLATE] instantiate the configuration file FILE --header=FILE[:TEMPLATE] instantiate the configuration header FILE Configuration files: $config_files Configuration headers: $config_headers Report bugs to ." _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ libgnustep-corebase config.status 0.2 configured by $0, generated by GNU Autoconf 2.69, with options \\"\$ac_cs_config\\" Copyright (C) 2012 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." ac_pwd='$ac_pwd' srcdir='$srcdir' test -n "\$AWK" || AWK=awk _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # The default lists apply if the user does not specify any file. ac_need_defaults=: while test $# != 0 do case $1 in --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; --*=) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg= ac_shift=: ;; *) ac_option=$1 ac_optarg=$2 ac_shift=shift ;; esac case $ac_option in # Handling of the options. -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) ac_cs_recheck=: ;; --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) $as_echo "$ac_cs_version"; exit ;; --config | --confi | --conf | --con | --co | --c ) $as_echo "$ac_cs_config"; exit ;; --debug | --debu | --deb | --de | --d | -d ) debug=: ;; --file | --fil | --fi | --f ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; --header | --heade | --head | --hea ) $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; esac as_fn_append CONFIG_HEADERS " '$ac_optarg'" ac_need_defaults=false;; --he | --h) # Conflict between --help and --header as_fn_error $? "ambiguous option: \`$1' Try \`$0 --help' for more information.";; --help | --hel | -h ) $as_echo "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ | -silent | --silent | --silen | --sile | --sil | --si | --s) ac_cs_silent=: ;; # This is an error. -*) as_fn_error $? "unrecognized option: \`$1' Try \`$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; esac shift done ac_configure_extra_args= if $ac_cs_silent; then exec 6>/dev/null ac_configure_extra_args="$ac_configure_extra_args --silent" fi _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 if \$ac_cs_recheck; then set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion shift \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 CONFIG_SHELL='$SHELL' export CONFIG_SHELL exec "\$@" fi _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 exec 5>>config.log { echo sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX ## Running $as_me. ## _ASBOX $as_echo "$ac_log" } >&5 _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # Handling of arguments. for ac_config_target in $ac_config_targets do case $ac_config_target in "Source/config.h") CONFIG_HEADERS="$CONFIG_HEADERS Source/config.h" ;; "Source/GNUmakefile") CONFIG_FILES="$CONFIG_FILES Source/GNUmakefile" ;; "Headers/CoreFoundation/CFBase.h") CONFIG_FILES="$CONFIG_FILES Headers/CoreFoundation/CFBase.h" ;; *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done # If the user did not use the arguments to specify the items to instantiate, # then the envvar interface is used. Set only those that are not. # We use the long form for the default assignment because of an extremely # bizarre bug on SunOS 4.1.3. if $ac_need_defaults; then test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers fi # Have a temporary directory for convenience. Make it in the build tree # simply because there is no reason against having it here, and in addition, # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: # after its creation but before its name has been assigned to `$tmp'. $debug || { tmp= ac_tmp= trap 'exit_status=$? : "${ac_tmp:=$tmp}" { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } # Create a (secure) tmp directory for tmp files. { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. # This happens for instance with `./config.status config.h'. if test -n "$CONFIG_FILES"; then ac_cr=`echo X | tr X '\015'` # On cygwin, bash can eat \r inside `` if the user requested igncr. # But we know of no other shell where ac_cr would be empty at this # point, so we can use a bashism as a fallback. if test "x$ac_cr" = x; then eval ac_cr=\$\'\\r\' fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi echo 'BEGIN {' >"$ac_tmp/subs1.awk" && _ACEOF { echo "cat >conf$$subs.awk <<_ACEOF" && echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h s/^/S["/; s/!.*/"]=/ p g s/^[^!]*!// :repl t repl s/'"$ac_delim"'$// t delim :nl h s/\(.\{148\}\)..*/\1/ t more1 s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ p n b repl :more1 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t nl :delim h s/\(.\{148\}\)..*/\1/ t more2 s/["\\]/\\&/g; s/^/"/; s/$/"/ p b :more2 s/["\\]/\\&/g; s/^/"/; s/$/"\\/ p g s/.\{148\}// t delim ' >$CONFIG_STATUS || ac_write_fail=1 rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" } { line = $ 0 nfields = split(line, field, "@") substed = 0 len = length(field[1]) for (i = 2; i < nfields; i++) { key = field[i] keylen = length(key) if (S_is_set[key]) { value = S[key] line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) len += length(value) + length(field[++i]) substed = 1 } else len += 1 + keylen } print line } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF # VPATH may cause trouble with some makes, so we remove sole $(srcdir), # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ h s/// s/^/:/ s/[ ]*$/:/ s/:\$(srcdir):/:/g s/:\${srcdir}:/:/g s/:@srcdir@:/:/g s/^:*// s/:*$// x s/\(=[ ]*\).*/\1/ G s/\n// s/^[^=]*=[ ]*$// }' fi cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 fi # test -n "$CONFIG_FILES" # Set up the scripts for CONFIG_HEADERS section. # No need to generate them if there are no CONFIG_HEADERS. # This happens for instance with `./config.status Makefile'. if test -n "$CONFIG_HEADERS"; then cat >"$ac_tmp/defines.awk" <<\_ACAWK || BEGIN { _ACEOF # Transform confdefs.h into an awk script `defines.awk', embedded as # here-document in config.status, that substitutes the proper values into # config.h.in to produce config.h. # Create a delimiter string that does not exist in confdefs.h, to ease # handling of long lines. ac_delim='%!_!# ' for ac_last_try in false false :; do ac_tt=`sed -n "/$ac_delim/p" confdefs.h` if test -z "$ac_tt"; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi done # For the awk script, D is an array of macro values keyed by name, # likewise P contains macro parameters if any. Preserve backslash # newline sequences. ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* sed -n ' s/.\{148\}/&'"$ac_delim"'/g t rset :rset s/^[ ]*#[ ]*define[ ][ ]*/ / t def d :def s/\\$// t bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3"/p s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p d :bsnl s/["\\]/\\&/g s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ D["\1"]=" \3\\\\\\n"\\/p t cont s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p t cont d :cont n s/.\{148\}/&'"$ac_delim"'/g t clear :clear s/\\$// t bsnlc s/["\\]/\\&/g; s/^/"/; s/$/"/p d :bsnlc s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p b cont ' >$CONFIG_STATUS || ac_write_fail=1 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 for (key in D) D_is_set[key] = 1 FS = "" } /^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { line = \$ 0 split(line, arg, " ") if (arg[1] == "#") { defundef = arg[2] mac1 = arg[3] } else { defundef = substr(arg[1], 2) mac1 = arg[2] } split(mac1, mac2, "(") #) macro = mac2[1] prefix = substr(line, 1, index(line, defundef) - 1) if (D_is_set[macro]) { # Preserve the white space surrounding the "#". print prefix "define", macro P[macro] D[macro] next } else { # Replace #undef with comments. This is necessary, for example, # in the case of _POSIX_SOURCE, which is predefined and required # on some systems where configure will not decide to define it. if (defundef == "undef") { print "/*", prefix defundef, macro, "*/" next } } } { print } _ACAWK _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 fi # test -n "$CONFIG_HEADERS" eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " shift for ac_tag do case $ac_tag in :[FHLC]) ac_mode=$ac_tag; continue;; esac case $ac_mode$ac_tag in :[FHL]*:*);; :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac ac_save_IFS=$IFS IFS=: set x $ac_tag IFS=$ac_save_IFS shift ac_file=$1 shift case $ac_mode in :L) ac_source=$1;; :[FH]) ac_file_inputs= for ac_f do case $ac_f in -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done # Let's still pretend it is `configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' `' by configure.' if test x"$ac_file" != x-; then configure_input="$ac_file. $configure_input" { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 $as_echo "$as_me: creating $ac_file" >&6;} fi # Neutralize special characters interpreted by sed in replacement strings. case $configure_input in #( *\&* | *\|* | *\\* ) ac_sed_conf_input=`$as_echo "$configure_input" | sed 's/[\\\\&|]/\\\\&/g'`;; #( *) ac_sed_conf_input=$configure_input;; esac case $ac_tag in *:-:* | *:-) cat >"$ac_tmp/stdin" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac ac_dir=`$as_dirname -- "$ac_file" || $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$ac_file" : 'X\(//\)[^/]' \| \ X"$ac_file" : 'X\(//\)$' \| \ X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || $as_echo X"$ac_file" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q } /^X\(\/\/\)[^/].*/{ s//\1/ q } /^X\(\/\/\)$/{ s//\1/ q } /^X\(\/\).*/{ s//\1/ q } s/.*/./; q'` as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; esac ;; esac ac_abs_top_builddir=$ac_pwd ac_abs_builddir=$ac_pwd$ac_dir_suffix # for backward compatibility: ac_top_builddir=$ac_top_build_prefix case $srcdir in .) # We are building in place. ac_srcdir=. ac_top_srcdir=$ac_top_builddir_sub ac_abs_top_srcdir=$ac_pwd ;; [\\/]* | ?:[\\/]* ) # Absolute name. ac_srcdir=$srcdir$ac_dir_suffix; ac_top_srcdir=$srcdir ac_abs_top_srcdir=$srcdir ;; *) # Relative name. ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix ac_top_srcdir=$ac_top_build_prefix$srcdir ac_abs_top_srcdir=$ac_pwd/$srcdir ;; esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix case $ac_mode in :F) # # CONFIG_FILE # _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= ac_sed_dataroot=' /datarootdir/ { p q } /@datadir@/p /@docdir@/p /@infodir@/p /@localedir@/p /@mandir@/p' case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 $as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_sed_extra="$ac_vpsub $extrasub _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t s&@builddir@&$ac_builddir&;t t s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$ac_tmp/stdin" case $ac_file in -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; :H) # # CONFIG_HEADER # if test x"$ac_file" != x-; then { $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" } >"$ac_tmp/config.h" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 $as_echo "$as_me: $ac_file is unchanged" >&6;} else rm -f "$ac_file" mv "$ac_tmp/config.h" "$ac_file" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 fi else $as_echo "/* $configure_input */" \ && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ || as_fn_error $? "could not create -" "$LINENO" 5 fi ;; esac done # for ac_tag as_fn_exit 0 _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. # Unfortunately, on DOS this fails, as config.log is still kept open # by configure, so config.status won't be able to write to it; its # output is simply discarded. So we exec the FD to /dev/null, # effectively closing config.log, so it can be properly (re)opened and # appended to by config.status. When coming back to configure, we # need to make the FD available again. if test "$no_create" != yes; then ac_cs_success=: ac_config_status_args= test "$silent" = yes && ac_config_status_args="$ac_config_status_args --quiet" exec 5>/dev/null $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. $ac_cs_success || as_fn_exit 1 fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi gnustep-corebase-0.2/GNUmakefile0000644000175000017500000000147613222706330015763 0ustar yavoryavor ifeq ($(GNUSTEP_MAKEFILES),) GNUSTEP_MAKEFILES := $(shell gnustep-config --variable=GNUSTEP_MAKEFILES 2>/dev/null) ifeq ($(GNUSTEP_MAKEFILES),) $(warning ) $(warning Unable to obtain GNUSTEP_MAKEFILES setting from gnustep-config!) $(warning Perhaps gnustep-make is not properly installed,) $(warning so gnustep-config is not in your PATH.) $(warning ) $(warning Your PATH is currently $(PATH)) $(warning ) endif endif ifeq ($(GNUSTEP_MAKEFILES),) $(error You need to set GNUSTEP_MAKEFILES before compiling!) endif include $(GNUSTEP_MAKEFILES)/common.make PACKAGE_NAME = gnustep-corebase SVN_MODULE_NAME = corebase SVN_BASE_URL = svn+ssh://svn.gna.org/svn/gnustep/libs include ./Version SUBPROJECTS = Source Tests include $(GNUSTEP_MAKEFILES)/aggregate.make -include Makefile.postamble gnustep-corebase-0.2/COPYING0000644000175000017500000007724613222706330014754 0ustar yavoryavor GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. gnustep-corebase-0.2/Tests/0000755000175000017500000000000014661604117015013 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFLocale/0000755000175000017500000000000014661604117016423 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFLocale/values.m0000644000175000017500000000625613222706330020101 0ustar yavoryavor#include "CoreFoundation/CFNumber.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFLocale.h" #include "../CFTesting.h" int main (void) { CFLocaleRef locale; CFTypeRef obj; CFTypeRef exp; locale = CFLocaleCreate (NULL, CFSTR("pt_BR@calendar=gregorian;collation=traditional;currency=BRL")); obj = CFLocaleGetValue (locale, kCFLocaleMeasurementSystem); PASS_CFEQ(obj, CFSTR("Metric"), "'pt_BR' measurement system is 'Metric'"); obj = CFLocaleGetValue (locale, kCFLocaleDecimalSeparator); PASS_CFEQ(obj, CFSTR(","), "Decimal separtor is ','"); obj = CFLocaleGetValue (locale, kCFLocaleGroupingSeparator); PASS_CFEQ(obj, CFSTR("."), "Grouping separator is '.'"); obj = CFLocaleGetValue (locale, kCFLocaleCurrencySymbol); PASS_CFEQ(obj, CFSTR("R$"), "Currency symbol is 'R$'"); obj = CFLocaleGetValue (locale, kCFLocaleCurrencyCode); PASS_CFEQ(obj, CFSTR("BRL"), "Currency code is 'BRL'"); obj = CFLocaleGetValue (locale, kCFLocaleIdentifier); PASS_CFEQ(obj, CFSTR("pt_BR@calendar=gregorian;collation=traditional;currency=BRL"), "Locale identifier is correct"); obj = CFLocaleGetValue (locale, kCFLocaleLanguageCode); PASS_CFEQ(obj, CFSTR("pt"), "Language code is 'pt'"); obj = CFLocaleGetValue (locale, kCFLocaleCountryCode); PASS_CFEQ(obj, CFSTR("BR"), "Country code is 'BR'"); obj = CFLocaleGetValue (locale, kCFLocaleScriptCode); PASS_CF(obj == NULL, "No script code for locale"); obj = CFLocaleGetValue (locale, kCFLocaleVariantCode); PASS_CF(obj == NULL, "No variant code for locale"); obj = CFLocaleGetValue (locale, kCFLocaleCalendarIdentifier); PASS_CFEQ(obj, CFSTR("gregorian"), "Calendar is 'gregorian'"); obj = CFLocaleGetValue (locale, kCFLocaleCalendar); PASS_CFNEQ(obj, kCFNull, "Returns valid CFCalendar"); // FIXME: required CFCalendar obj = CFLocaleGetValue (locale, kCFLocaleCollationIdentifier); PASS_CFEQ(obj, CFSTR("traditional"), "Collation identifier is 'traditional'"); obj = CFLocaleGetValue (locale, kCFLocaleUsesMetricSystem); PASS_CFEQ(obj, kCFBooleanTrue, "Uses metric system"); // FIXME: needs CFBoolean obj = CFLocaleGetValue (locale, kCFLocaleCollatorIdentifier); PASS_CFEQ(obj, NULL, "Collator identifier is NULL"); exp = CFStringCreateWithCString (NULL, "“", kCFStringEncodingUTF8); obj = CFLocaleGetValue (locale, kCFLocaleQuotationBeginDelimiterKey); PASS_CFEQ(obj, exp, "Quotation begin delimiter is correct"); CFRelease (exp); exp = CFStringCreateWithCString (NULL, "”", kCFStringEncodingUTF8); obj = CFLocaleGetValue (locale, kCFLocaleQuotationEndDelimiterKey); PASS_CFEQ(obj, exp, "Quotation end delimiter is correct"); CFRelease (exp); exp = CFStringCreateWithCString (NULL, "‘", kCFStringEncodingUTF8); obj = CFLocaleGetValue (locale, kCFLocaleAlternateQuotationBeginDelimiterKey); PASS_CFEQ(obj, exp, "Alternate quotation begin delimiter is correct"); obj = CFLocaleGetValue (locale, kCFLocaleAlternateQuotationEndDelimiterKey); CFRelease (exp); exp = CFStringCreateWithCString (NULL, "’", kCFStringEncodingUTF8); PASS_CFEQ(obj, exp, "Alternate quotation end delimiter is correct"); CFRelease (exp); CFRelease ((CFTypeRef)locale); return 0; } gnustep-corebase-0.2/Tests/CFLocale/displayvalues.m0000644000175000017500000000252213222706330021457 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "CoreFoundation/CFLocale.h" #include "../CFTesting.h" int main (void) { CFLocaleRef locale; CFStringRef str; locale = CFLocaleCreate (NULL, CFSTR("nb")); str = CFLocaleCopyDisplayNameForPropertyValue (locale, kCFLocaleLanguageCode, CFSTR("pt")); PASS_CFEQ (str, CFSTR("portugisisk"), "Display language is correct"); CFRelease (str); str = CFLocaleCopyDisplayNameForPropertyValue (locale, kCFLocaleCountryCode, CFSTR("BR")); PASS_CFEQ (str, CFSTR("Brasil"), "Display country is correct"); CFRelease (str); str = CFLocaleCopyDisplayNameForPropertyValue (locale, kCFLocaleCalendarIdentifier, CFSTR("gregorian")); PASS_CFEQ (str, CFSTR("gregoriansk kalender"), "Display calendar identifier is correct"); CFRelease (str); str = CFLocaleCopyDisplayNameForPropertyValue (locale, kCFLocaleCollationIdentifier, CFSTR("traditional")); PASS_CFEQ (str, CFSTR("tradisjonell sortering"), "Display collation identifier is correct"); CFRelease (str); return 0; } gnustep-corebase-0.2/Tests/CFLocale/identifier.m0000644000175000017500000000162513222706330020717 0ustar yavoryavor#include "CoreFoundation/CFDictionary.h" #include "CoreFoundation/CFString.h" #include "CoreFoundation/CFLocale.h" #include "../CFTesting.h" int main (void) { CFStringRef str; CFStringRef str2; CFDictionaryRef dict; CFDictionaryRef dict2; str = CFSTR("sr_Latn_RS@collation=phonebook;currency=USD;calendar=greogian"); str = CFLocaleCreateCanonicalLocaleIdentifierFromString (NULL, str); dict = CFLocaleCreateComponentsFromLocaleIdentifier (NULL, str); str2 = CFLocaleCreateLocaleIdentifierFromComponents (NULL, dict); PASS_CFEQ(str, str2, "Locale identifiers are the same"); CFRelease (str); CFRelease (str2); str2 = CFLocaleCreateLocaleIdentifierFromComponents (NULL, dict); dict2 = CFLocaleCreateComponentsFromLocaleIdentifier (NULL, str2); PASS_CFEQ(dict, dict2, "Locale components are the same"); CFRelease (str2); CFRelease (dict); CFRelease (dict2); return 0; } gnustep-corebase-0.2/Tests/CFLocale/TestInfo0000644000175000017500000000000013222706330020057 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFLocale/create.m0000664000175000017500000000152614661604117020052 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "CoreFoundation/CFLocale.h" #include "../CFTesting.h" int main (void) { CFLocaleRef locale; CFLocaleRef locale2; locale = CFLocaleCopyCurrent (); PASS_CF(locale != NULL, "CFLocaleCopyCurrent() returns a value"); CFRelease((CFTypeRef)locale); locale = CFLocaleGetSystem (); PASS_CF(locale != NULL, "CFLocaleCopyCurrent() returns a value"); locale = CFLocaleCreate (NULL, CFSTR("es_ES_PREEURO")); PASS_CF(locale != NULL, "CFLocaleCreate() returns a value"); PASS_CFEQ(CFLocaleGetIdentifier(locale), CFSTR("es_ES@currency=ESP"), "en_ES_PREEURO is stored as es_ES@currency=ESP"); locale2 = CFLocaleCreateCopy (NULL, locale); PASS_CF(locale2 != NULL, "CFLocaleCreateCopy() returns a value"); CFRelease((CFTypeRef)locale); CFRelease((CFTypeRef)locale2); return 0; } gnustep-corebase-0.2/Tests/CFLocale/bridge.m0000664000175000017500000000301014661604117020031 0ustar yavoryavor#import #import #include "CoreFoundation/CFString.h" #include "../CFTesting.h" void testCFonNS(void); void testNSonCF(void); int main(void) { testCFonNS(); testNSonCF(); return 0; } void testCFonNS(void) { NSLocale* locale = [NSLocale currentLocale]; CFLocaleRef cfRef = (CFLocaleRef) locale; PASS_CF(CFStringCompare(CFLocaleGetIdentifier(cfRef), (CFStringRef) [locale localeIdentifier], 0) == 0, "CFLocaleGetIdentifier works"); PASS_CF(CFStringCompare(CFLocaleGetValue(cfRef, kCFLocaleCurrencySymbol), (CFStringRef) [locale objectForKey: NSLocaleCurrencySymbol], 0) == 0, "CFLocaleGetValue works"); PASS_CF(CFStringCompare(CFLocaleCopyDisplayNameForPropertyValue(cfRef, kCFLocaleIdentifier, CFSTR("fr_FR")), (CFStringRef) [locale displayNameForKey: NSLocaleIdentifier value: @"fr_FR"], 0) == 0, "CFLocaleCopyDisplayNameForPropertyValue works"); } void testNSonCF(void) { CFLocaleRef cfRef = CFLocaleCopyCurrent(); NSLocale* locale = (NSLocale*)cfRef; PASS_CF([[(NSLocale*)cfRef localeIdentifier] isEqual:[locale localeIdentifier]] == YES, "-localeIdentifier works"); PASS_CF([[(NSLocale*)cfRef objectForKey:NSLocaleCurrencySymbol] isEqual:[locale objectForKey:NSLocaleCurrencySymbol]] == YES, "-objectForKey: works"); PASS_CF([[(NSLocale*)cfRef displayNameForKey:NSLocaleIdentifier value:@"fr_FR"] isEqual:[locale displayNameForKey:NSLocaleIdentifier value:@"fr_FR"]] == YES, "-displayNameForKey:value: works"); CFRelease(cfRef); } gnustep-corebase-0.2/Tests/CFTesting.h0000664000175000017500000000605614661604117017023 0ustar yavoryavor#include #include #include #define CFTEST_BUFFER_SIZE 1024 #if defined(__OBJC__) && defined(__clang__) && defined(_MSC_VER) /* Work around Clang bug on Windows MSVC when tests contain no * Objective-C constructs: https://bugs.llvm.org/show_bug.cgi?id=49681 */ id __work_around_clang_bug = @"__unused__"; #endif static Boolean testPassed = true; static Boolean testHopeful = false; static void cfpass(int passed, const char *format, ...) __attribute__((unused)) __attribute__ ((format(printf, 2, 3))); static void cfpass(int passed, const char *format, ...) { va_list args; va_start(args, format); if (passed) { fprintf(stderr, "Passed test: "); testPassed = true; } #if !defined(TESTDEV) else if (true == testHopeful) { fprintf(stderr, "Dashed hope: "); testPassed = false; } #endif else { fprintf(stderr, "Failed test: "); testPassed = false; } vfprintf(stderr, format, args); fprintf(stderr, "\n"); va_end(args); #if defined(FAILFAST) if (false == testPassed && false == testHopeful) { exit(1); // Abandon testing now. } #endif } #define PASS_CFEQ(cf1__, cf2__, testFormat__, ...) do \ { \ cfpass((CFEqual((CFTypeRef)(cf1__), (CFTypeRef)(cf2__)) ? true : false), "%s:%d ... " testFormat__, __FILE__, __LINE__, ## __VA_ARGS__); \ if (false == testPassed) \ { \ CFStringRef str1__; \ CFStringRef str2__; \ char expect[CFTEST_BUFFER_SIZE] = {0}; \ char expr[CFTEST_BUFFER_SIZE] = {0}; \ str1__ = CFCopyDescription((CFTypeRef)(cf1__)); \ str2__ = CFCopyDescription((CFTypeRef)(cf2__)); \ CFStringGetCString (str1__, expr, CFTEST_BUFFER_SIZE, \ kCFStringEncodingUTF8); \ CFStringGetCString (str2__, expect, CFTEST_BUFFER_SIZE, \ kCFStringEncodingUTF8); \ CFRelease ((CFTypeRef)str1__); \ CFRelease ((CFTypeRef)str2__); \ fprintf (stderr, "expected %s, but got %s\n", \ expect, \ expr); \ } \ } while (0) #define PASS_CFNEQ(cf1__, cf2__, testFormat__, ...) do \ { \ cfpass((CFEqual((CFTypeRef)(cf1__), (CFTypeRef)(cf2__)) ? false : true), "%s:%d ... " testFormat__, __FILE__, __LINE__, ## __VA_ARGS__); \ if (false == testPassed) \ { \ CFStringRef str1__; \ CFStringRef str2__; \ char expect[CFTEST_BUFFER_SIZE] = {0}; \ char expr[CFTEST_BUFFER_SIZE] = {0}; \ str1__ = CFCopyDescription((CFTypeRef)(cf1__)); \ str2__ = CFCopyDescription((CFTypeRef)(cf2__)); \ CFStringGetCString (str1__, expr, CFTEST_BUFFER_SIZE, \ kCFStringEncodingUTF8); \ CFStringGetCString (str2__, expect, CFTEST_BUFFER_SIZE, \ kCFStringEncodingUTF8); \ CFRelease ((CFTypeRef)str1__); \ CFRelease ((CFTypeRef)str2__); \ fprintf (stderr, "Did not expect %s, got %s\n", \ expect, \ expr); \ } \ } while (0) #define PASS_CF(exp__, testFormat__, ...) do \ { \ cfpass(exp__, "%s:%d ... " testFormat__, __FILE__, __LINE__, ## __VA_ARGS__); \ } while (0) gnustep-corebase-0.2/Tests/CFNumber/0000755000175000017500000000000014661604110016445 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFNumber/TestInfo0000644000175000017500000000000013222706330020110 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFNumber/general.m0000644000175000017500000000346113222706330020243 0ustar yavoryavor#include "CoreFoundation/CFNumber.h" #include "../CFTesting.h" int main (void) { signed int i32 = -5; signed short i16 = 6; signed char i8 = 7; float f = 3.4; Float64 f64; CFNumberRef num1, num2; num1 = CFNumberCreate (NULL, kCFNumberIntType, &i32); PASS_CF(num1 != NULL, "CFNumberCreate() returns non-NULL"); PASS_CF(CFNumberGetType(num1) == kCFNumberSInt32Type, "Integer is converted to SInt32(%d).", (int)CFNumberGetType(num1)); num2 = CFNumberCreate (NULL, kCFNumberCharType, &i8); PASS_CF(CFNumberGetType(num2) == kCFNumberSInt32Type, "Char is converted to SInt32(%d).", (int)CFNumberGetType(num2)); PASS_CF(CFNumberGetValue(num1, kCFNumberSInt8Type, &i8), "Integer converted to SInt8."); PASS_CF(i8 == -5, "SInt32 converted to SInt8 (%d) correctly.", i8); PASS_CF(CFNumberGetValue(num2, kCFNumberSInt32Type, &i32), "Char converted to SInt32."); PASS_CF(i32 == 7, "SInt8 converted to SInt32 (%d)correctly.", i32); CFRelease (num1); CFRelease (num2); num1 = CFNumberCreate (NULL, kCFNumberShortType, &i16); PASS_CF(CFNumberGetType(num1) == kCFNumberSInt32Type, "Short is converted to SInt32(%d).", (int)CFNumberGetType(num1)); num2 = CFNumberCreate (NULL, kCFNumberFloatType, &f); PASS_CF(CFNumberGetType(num2) == kCFNumberFloat64Type, "Float is converted to Float64(%d).", (int)CFNumberGetType(num2)); PASS_CF(CFNumberGetValue(num1, kCFNumberFloatType, &f), "Short converted to float."); PASS_CF(f == 6.0, "Short converted to float (%f) correctly.", f); /* Lossy conversion so returns false... */ PASS_CF(CFNumberGetValue(num2, kCFNumberSInt16Type, &i16) == false, "Float converted to short."); PASS_CF(i16 == 3, "Float converted to short (%d) correctly.", i16); CFRelease (num1); CFRelease (num2); return 0; } gnustep-corebase-0.2/Tests/CFNumber/bridge.m0000644000175000017500000001355014551015633020067 0ustar yavoryavor#import #include "CoreFoundation/CFNumber.h" #include "../CFTesting.h" static signed int sints[] = {INT_MIN, INT_MAX, 0, -1, 1}; static signed short sshorts[] = {SHRT_MIN, SHRT_MAX, 0, -1, 1}; static signed char schars[] = {CHAR_MIN, CHAR_MAX, 0, -1, 1}; static unsigned int uints[] = {UINT_MAX, 0, 1}; static unsigned short ushorts[] = {USHRT_MAX, 0, 1}; static unsigned char uchars[] = {UCHAR_MAX, 0, 1}; static float floats[] = {FLT_MIN, FLT_MAX, FLT_EPSILON, 0, -3.4, 3.4}; static double doubles[] = {DBL_MIN, DBL_MAX, DBL_EPSILON, 0, -3.4, 3.4}; void testNSonCF(void); void testCFonNS(void); int main(void) { testNSonCF(); testCFonNS(); return 0; } void testNSonCF(void) { int i; for (i = 0; i < sizeof(sints)/sizeof(*sints); i++) { signed int in = sints[i]; CFNumberRef cfnum = CFNumberCreate(NULL, kCFNumberIntType, &in); signed int out = [(NSNumber*)cfnum intValue]; PASS_CF(in == out, "-intValue = %d works on CFNumber(kCFNumberIntType) %d", out, in); } for (i = 0; i < sizeof(sshorts)/sizeof(*sshorts); i++) { signed short in = sshorts[i]; CFNumberRef cfnum = CFNumberCreate(NULL, kCFNumberShortType, &in); signed short out = [(NSNumber*)cfnum shortValue]; PASS_CF(in == out, "-shortValue = %d works on CFNumber(kCFNumberShortType) %d", out, in); } for (i = 0; i < sizeof(schars)/sizeof(*schars); i++) { signed char in = schars[i]; CFNumberRef cfnum = CFNumberCreate(NULL, kCFNumberCharType, &in); signed char out = [(NSNumber*)cfnum charValue]; PASS_CF(in == out, "-charValue = %d works on CFNumber(kCFNumberCharType) %d", out, in); } for (i = 0; i < sizeof(uints)/sizeof(*uints); i++) { unsigned int in = uints[i]; CFNumberRef cfnum = CFNumberCreate(NULL, kCFNumberIntType, &in); unsigned int out = [(NSNumber*)cfnum unsignedIntValue]; PASS_CF(in == out, "-unsignedIntValue = %u works on CFNumber(kCFNumberIntType) %u", out, in); } for (i = 0; i < sizeof(ushorts)/sizeof(*ushorts); i++) { unsigned short in = ushorts[i]; CFNumberRef cfnum = CFNumberCreate(NULL, kCFNumberShortType, &in); unsigned short out = [(NSNumber*)cfnum unsignedShortValue]; PASS_CF(in == out, "-unsignedShortValue = %u works on CFNumber(kCFNumberShortType) %u", out, in); } for (i = 0; i < sizeof(uchars)/sizeof(*uchars); i++) { unsigned char in = uchars[i]; CFNumberRef cfnum = CFNumberCreate(NULL, kCFNumberCharType, &in); unsigned char out = [(NSNumber*)cfnum unsignedCharValue]; PASS_CF(in == out, "-unsignedCharValue = %u works on CFNumber(kCFNumberCharType) %u", out, in); } for (i = 0; i < sizeof(floats)/sizeof(*floats); i++) { float in = floats[i]; CFNumberRef cfnum = CFNumberCreate(NULL, kCFNumberFloatType, &in); float out = [(NSNumber*)cfnum floatValue]; PASS_CF(in == out, "-floatValue = %f works on CFNumber(kCFNumberFloatType) %f", out, in); } for (i = 0; i < sizeof(doubles)/sizeof(*doubles); i++) { double in = doubles[i]; CFNumberRef cfnum = CFNumberCreate(NULL, kCFNumberDoubleType, &in); double out = [(NSNumber*)cfnum doubleValue]; PASS_CF(in == out, "-doubleValue = %lf works on CFNumber(kCFNumberDoubleType) %lf", out, in); } } void testCFonNS(void) { int i; for (i = 0; i < sizeof(sints)/sizeof(*sints); i++) { signed int in = sints[i]; signed int out; CFNumberGetValue((CFNumberRef)[NSNumber numberWithInt:in], kCFNumberIntType, &out); PASS_CF(in == out, "CFNumberGetValue(kCFNumberIntType) = %d works on signed NSNumber %d", out, in); } for (i = 0; i < sizeof(sshorts)/sizeof(*sshorts); i++) { signed short in = sshorts[i]; signed short out; CFNumberGetValue((CFNumberRef)[NSNumber numberWithShort:in], kCFNumberShortType, &out); PASS_CF(in == out, "CFNumberGetValue(kCFNumberShortType) = %d works on signed NSNumber %d", out, in); } for (i = 0; i < sizeof(schars)/sizeof(*schars); i++) { signed char in = schars[i]; signed char out; CFNumberGetValue((CFNumberRef)[NSNumber numberWithChar:in], kCFNumberCharType, &out); PASS_CF(in == out, "CFNumberGetValue(kCFNumberCharType) = %d works on signed NSNumber %d", out, in); } for (i = 0; i < sizeof(uints)/sizeof(*uints); i++) { unsigned int in = uints[i]; unsigned int out; CFNumberGetValue((CFNumberRef)[NSNumber numberWithUnsignedInt:in], kCFNumberIntType, &out); PASS_CF(in == out, "CFNumberGetValue(kCFNumberIntType) = %u works on unsigned NSNumber %u", out, in); } for (i = 0; i < sizeof(ushorts)/sizeof(*ushorts); i++) { unsigned short in = ushorts[i]; unsigned short out; CFNumberGetValue((CFNumberRef)[NSNumber numberWithUnsignedShort:in], kCFNumberShortType, &out); PASS_CF(in == out, "CFNumberGetValue(kCFNumberShortType) = %u works on unsigned NSNumber %u", out, in); } for (i = 0; i < sizeof(uchars)/sizeof(*uchars); i++) { unsigned char in = uchars[i]; unsigned char out; CFNumberGetValue((CFNumberRef)[NSNumber numberWithUnsignedChar:in], kCFNumberCharType, &out); PASS_CF(in == out, "CFNumberGetValue(kCFNumberCharType) = %u works on unsigned NSNumber %u", out, in); } for (i = 0; i < sizeof(floats)/sizeof(*floats); i++) { float in = floats[i]; float out; CFNumberGetValue((CFNumberRef)[NSNumber numberWithFloat:in], kCFNumberFloatType, &out); PASS_CF(in == out, "CFNumberGetValue(kCFNumberFloatType) = %f works on NSNumber %f", out, in); } for (i = 0; i < sizeof(doubles)/sizeof(*doubles); i++) { double in = doubles[i]; double out; CFNumberGetValue((CFNumberRef)[NSNumber numberWithDouble:in], kCFNumberDoubleType, &out); PASS_CF(in == out, "CFNumberGetValue(kCFNumberDoubleType) = %lf works on NSNumber %lf", out, in); } } gnustep-corebase-0.2/Tests/CFCalendar/0000755000175000017500000000000014661604107016734 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFCalendar/basic.m0000644000175000017500000000353413222706330020171 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "CoreFoundation/CFDate.h" #include "CoreFoundation/CFCalendar.h" #include "CoreFoundation/CFTimeZone.h" #include "../CFTesting.h" int main (void) { CFCalendarRef cal; CFTimeZoneRef tz; CFAbsoluteTime at = 0.0; CFTimeInterval ti= 0.0; int year, month, hour, minute, second; cal = CFCalendarCreateWithIdentifier (NULL, kCFGregorianCalendar); tz = CFTimeZoneCreateWithTimeIntervalFromGMT (NULL, -3600.0); CFCalendarSetTimeZone (cal, tz); CFRelease (tz); PASS_CF(CFCalendarComposeAbsoluteTime(cal, &at, "yMd", 2011, 7, 8), "Absolute time composed."); testHopeful = true; PASS_CF(at == 331779600.0, "Absolute time composed correctly (%f).", at); testHopeful = false; PASS_CF(CFCalendarDecomposeAbsoluteTime(cal, at, "yMH", &year, &month, &hour), "Absolute time decomposed."); PASS_CF(year == 2011, "Year decomposed correctly."); PASS_CF(month == 7, "Month decomosed correctly."); PASS_CF(hour == 0, "Hour decomposed correctly."); PASS_CF(CFCalendarGetComponentDifference(cal, at, at + 3600.0, 0, "s", &second), "Got component difference."); PASS_CF(second == 3600, "Seconds difference is %d", second); PASS_CF(CFCalendarGetComponentDifference(cal, at, at + 3663.0, kCFCalendarComponentsWrap, "Hms", &hour, &minute, &second), "Got wrapped components difference."); PASS_CF(hour == 1 && minute == 1 && second == 3, "Component difference is %d hour(s), %d minute(s) and %d second(s)", hour, minute, second); PASS_CF(CFCalendarGetTimeRangeOfUnit (cal, kCFCalendarUnitWeekday, 331365601.0, &at, &ti), "Got time range of kCFCalendarUnitWeekday."); PASS_CF(at == 331347600.0, "Got start of weekday (%f).", at); PASS_CF(ti == 86400.0, "Time interval is %d day(s) long (%f).", (int)(ti/86400.0), ti); CFRelease (cal); return 0; } gnustep-corebase-0.2/Tests/CFCalendar/TestInfo0000644000175000017500000000000013222706330020371 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFCalendar/create.m0000644000175000017500000000137013222706330020347 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "CoreFoundation/CFCalendar.h" #include "../CFTesting.h" int main (void) { CFCalendarRef cal; CFLocaleRef locale1, locale2; cal = CFCalendarCreateWithIdentifier (NULL, kCFGregorianCalendar); PASS_CF(cal != NULL, "Calendar created."); PASS_CFEQ(CFCalendarGetIdentifier(cal), kCFGregorianCalendar, "Correct calendar identifier."); CFRelease (cal); cal = CFCalendarCopyCurrent (); PASS_CF(cal != NULL, "CFCalendarCopyCurrent returns a calendar"); locale1 = CFCalendarCopyLocale (cal); locale2 = CFLocaleCopyCurrent (); PASS_CFEQ(locale1, locale2, "Current calendar locale matches current locale."); CFRelease (locale1); CFRelease (locale2); CFRelease (cal); return 0; } gnustep-corebase-0.2/Tests/GNUmakefile0000664000175000017500000000235014661604117017067 0ustar yavoryavorifeq ($(GNUSTEP_MAKEFILES),) GNUSTEP_MAKEFILES := $(shell gnustep-config --variable=GNUSTEP_MAKEFILES 2>/dev/null) ifeq ($(GNUSTEP_MAKEFILES),) $(warning ) $(warning Unable to obtain GNUSTEP_MAKEFILES setting from gnustep-config!) $(warning Perhaps gnustep-make is not properly installed,) $(warning so gnustep-config is not in your PATH.) $(warning ) $(warning Your PATH is currently $(PATH)) $(warning ) endif endif ifeq ($(GNUSTEP_MAKEFILES),) $(error You need to set GNUSTEP_MAKEFILES before compiling!) endif include $(GNUSTEP_MAKEFILES)/common.make all:: @(echo If you want to run the gnustep-corebase testsuite, please type \'make check\') TOP_DIR := $(shell dirname $(CURDIR)) check:: @(\ ADDITIONAL_INCLUDE_DIRS="-I$(TOP_DIR)/Headers";\ ADDITIONAL_LIB_DIRS="-L$(TOP_DIR)/Source/$(GNUSTEP_OBJ_DIR)";\ LD_LIBRARY_PATH="$(TOP_DIR)/Source/$(GNUSTEP_OBJ_DIR):${LD_LIBRARY_PATH}";\ PATH="$(TOP_DIR)/Source/$(GNUSTEP_OBJ_DIR):${PATH}";\ export ADDITIONAL_INCLUDE_DIRS;\ export ADDITIONAL_LIB_DIRS;\ export LD_LIBRARY_PATH;\ export PATH;\ if [ "$(DEBUG)" = "" ]; then \ gnustep-tests;\ else\ gnustep-tests --debug;\ fi;\ ) clean:: gnustep-tests --clean include $(GNUSTEP_MAKEFILES)/rules.makegnustep-corebase-0.2/Tests/CFURLAccess/0000755000175000017500000000000014661604110017001 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFURLAccess/basic.m0000644000175000017500000000535513222706330020247 0ustar yavoryavor#include "CoreFoundation/CFURLAccess.h" #include "CoreFoundation/CFNumber.h" #include "../CFTesting.h" #include const char *test = "test data!\n"; int main (void) { const char *bytes; CFURLRef dir; CFURLRef file1; CFURLRef file2; CFDataRef data; CFDictionaryRef dict; CFArrayRef contents; CFNumberRef num; CFIndex fileLength; CFIndex count; dir = CFURLCreateWithFileSystemPath (NULL, CFSTR("TestDir"), kCFURLPOSIXPathStyle, true); PASS_CF(CFURLWriteDataAndPropertiesToResource (dir, NULL, NULL, NULL), "Directory was successfully created."); file1 = CFURLCreateWithFileSystemPath (NULL, CFSTR("TestDir/file1.txt"), kCFURLPOSIXPathStyle, false); data = CFDataCreate (NULL, (const UInt8*)test, strlen(test)); PASS_CF(CFURLWriteDataAndPropertiesToResource (file1, data, NULL, NULL), "Data was successfully written to test file."); CFRelease (data); file2 = CFURLCreateWithFileSystemPath (NULL, CFSTR("TestDir/file2.txt"), kCFURLPOSIXPathStyle, false); data = CFDataCreate (NULL, NULL, 0); PASS_CF(CFURLWriteDataAndPropertiesToResource (file2, data, NULL, NULL), "Empty file was successfully created."); CFRelease (data); /* Lets try to delete the directory with files inside, this should fail. */ PASS_CF(!CFURLDestroyResource(dir, NULL), "Could not delete directory."); PASS_CF(CFURLCreateDataAndPropertiesFromResource (NULL, file1, &data, &dict, NULL, NULL), "File was successfully read."); num = CFDictionaryGetValue (dict, kCFURLFileLength); CFNumberGetValue (num, kCFNumberCFIndexType, &fileLength); PASS_CF(fileLength == 11, "Properties correctly read."); CFRelease (dict); PASS_CF(CFURLCreateDataAndPropertiesFromResource (NULL, dir, NULL, &dict, NULL, NULL), "Directory was successfully read."); contents = CFDictionaryGetValue (dict, kCFURLFileDirectoryContents); count = CFArrayGetCount (contents); PASS_CF(count == 2, "There are %d items in the directory.", (int)count); PASS_CF(CFArrayContainsValue (contents, CFRangeMake (0, count), CFSTR("file1.txt")), "Directory has file1.txt"); PASS_CF(CFArrayContainsValue (contents, CFRangeMake (0, count), CFSTR("file2.txt")), "Directory has file2.txt"); CFRelease (dict); bytes = (const char*)CFDataGetBytePtr (data); PASS_CF(strncmp (bytes, test, strlen(test)) == 0, "Content read is the same the content that was written."); CFRelease (data); PASS_CF(CFURLDestroyResource(file1, NULL), "File1 was successfully deleted."); PASS_CF(CFURLDestroyResource(file2, NULL), "File2 was successfully deleted."); PASS_CF(CFURLDestroyResource(dir, NULL), "Directory was successfully deleted."); CFRelease (file1); CFRelease (file2); CFRelease (dir); return 0; }gnustep-corebase-0.2/Tests/CFURLAccess/TestInfo0000644000175000017500000000000013222706330020444 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFUUID/0000755000175000017500000000000014661604110015763 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFUUID/TestInfo0000644000175000017500000000000013222706330017426 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFUUID/create.m0000644000175000017500000000120213222706330017376 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "CoreFoundation/CFUUID.h" #include "../CFTesting.h" int main (void) { CFStringRef str; CFUUIDRef uuid1; CFUUIDRef uuid2; uuid1 = CFUUIDCreate (NULL); PASS_CF(uuid1 != NULL, "CFUUIDCreate() returns non-NULL."); if (uuid1 == NULL) return 1; uuid2 = CFUUIDCreateFromUUIDBytes (NULL, CFUUIDGetUUIDBytes(uuid1)); PASS_CFEQ(uuid1, uuid2, "UUID creates with CFUUIDBytes is correct."); CFRelease(uuid2); str = CFUUIDCreateString (NULL, uuid1); PASS_CF(str != NULL, "CFUUIDCreateString() returns non-NULL."); CFRelease (uuid1); CFRelease (str); return 0; } gnustep-corebase-0.2/Tests/CFRunLoop/0000755000175000017500000000000014661604117016622 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFRunLoop/TestInfo0000644000175000017500000000000013222706330020256 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFRunLoop/source.m0000644000175000017500000000451413222706330020274 0ustar yavoryavor#include #include "../CFTesting.h" #include #include CFRunLoopSourceRef rls1 = NULL; CFRunLoopSourceRef rls2 = NULL; pthread_t thread2 = 0; void perform1 (void *info) { SInt32 ret; CFIndex *i = (CFIndex*)info; ret = CFRunLoopRunInMode (CFSTR("another_mode"), 3.0, false); PASS_CF(ret == kCFRunLoopRunTimedOut, "Run loop run in 'another_mode' returned" " '%d'", ret); (*i)++; } void perform2 (void *info) { CFIndex *i = (CFIndex*)info; (*i)++; } void* delay_signal(void* arg) { //CFRunLoopSourceRef src = (CFRunLoopSourceRef) arg; int i; for (i = 0; i < 2; i++) { sleep(1); printf("Signalling!\n"); CFRunLoopSourceSignal(rls1); CFRunLoopSourceSignal(rls2); } return NULL; } void schedule2 (void* info, CFRunLoopRef rl, CFStringRef mode) { if (!thread2) { pthread_create(&thread2, NULL, delay_signal, rls2); } } int main (void) { CFRunLoopRef rl; CFIndex i1 = 0; CFIndex i2 = 0; CFRunLoopSourceContext c1 = { 0 }; CFRunLoopSourceContext c2 = { 0 }; SInt32 ret; rl = CFRunLoopGetMain (); PASS_CF(rl != NULL, "Got main run loop."); c1.info = &i1; // c1.schedule = schedule1; c1.perform = perform1; c2.info = &i2; c2.schedule = schedule2; c2.perform = perform2; rls1 = CFRunLoopSourceCreate (NULL, 0, &c1); PASS_CF(rls1 != NULL, "First run loop source create."); rls2 = CFRunLoopSourceCreate (NULL, 0, &c2); PASS_CF(rls2 != NULL, "Second run loop source create."); CFRunLoopAddSource (rl, rls1, kCFRunLoopDefaultMode); CFRunLoopAddSource (rl, rls2, kCFRunLoopDefaultMode); CFRunLoopAddSource (rl, rls2, CFSTR("another_mode")); ret = CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.0, true); PASS_CF(ret == kCFRunLoopRunHandledSource, "Run loop handled sources. Exit" " code '%d'.", ret); PASS_CF(i1 == 1, "First run loop source was performed %d time(s).", (int)i1); PASS_CF(i2 == 2, "Second run loop source was performed %d time(s).", (int)i2); CFRunLoopRemoveSource (rl, rls2, CFSTR("another_mode")); CFRunLoopSourceInvalidate (rls2); CFRunLoopSourceInvalidate (rls1); ret = CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.0, true); PASS_CF(ret == kCFRunLoopRunFinished, "Run loop handled sources. Exit" " code '%d'.", ret); CFRelease (rls1); CFRelease (rls2); return 0; } gnustep-corebase-0.2/Tests/CFRunLoop/timers.m0000664000175000017500000000363714661604117020316 0ustar yavoryavor#include #include "../CFTesting.h" #include #include int timesTimer1Fired = 0, timesTimer2Fired = 0; void timerCallback(CFRunLoopTimerRef timer, void *info); void timerCallback2(CFRunLoopTimerRef timer, void *info); void* createSecondTimerThread(void* p); int main() { // Test plan: // Create a repeated timer, check if it repeats and invalidate it after 2 repeats. // Asynchronously, while the runloop is waiting, plan another, singleshot timer // to see, if the runloop reschedules correctly. // After all timers are invalid, the runloop should exit. CFRunLoopRef rl; CFRunLoopTimerRef timer1; rl = CFRunLoopGetMain (); PASS_CF(rl != NULL, "Got main run loop."); timer1 = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent() + 1, 1, 0, 0, timerCallback, NULL); CFRunLoopAddTimer(rl, timer1, kCFRunLoopCommonModes); CFRelease(timer1); CFRunLoopRun(); PASS_CF(timesTimer1Fired == 2, "Timer 1 fired twice and loop exited"); return 0; } void timerCallback(CFRunLoopTimerRef timer, void *info) { timesTimer1Fired++; printf("Timer 1 fired...\n"); if (timesTimer1Fired == 1) { pthread_t thread; pthread_create(&thread, NULL, createSecondTimerThread, NULL); } else if (timesTimer1Fired >= 2) CFRunLoopTimerInvalidate(timer); } void timerCallback2(CFRunLoopTimerRef timer, void *info) { printf("Timer 2 fired\n"); PASS_CF(timesTimer1Fired == 1, "Timer 2 fired while timer 1 fired only once"); timesTimer2Fired++; PASS_CF(timesTimer2Fired == 1, "Timer 2 fires only once"); } void* createSecondTimerThread(void* p) { CFRunLoopRef rl = CFRunLoopGetMain (); CFRunLoopTimerRef timer2; while (!CFRunLoopIsWaiting(rl)) usleep(10*1000); timer2 = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent() + 0.25, 0, 0, 0, timerCallback2, NULL); CFRunLoopAddTimer(rl, timer2, kCFRunLoopCommonModes); CFRelease(timer2); return NULL; } gnustep-corebase-0.2/Tests/CFSet/0000755000175000017500000000000013222706330015747 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFSet/objc_bridge.m0000644000175000017500000000127613222706330020364 0ustar yavoryavor#import #import #include "CoreFoundation/CFSet.h" #include "../CFTesting.h" int main (void) { NSSet* nsset = [[NSSet alloc] initWithObjects: @"Hello", @"world", @"!", nil]; CFSetRef copy; PASS_CF ([nsset count] == CFSetGetCount((CFSetRef) nsset), "CFSetGetCount works with an NSSet instance"); PASS_CF ([nsset member: @"world"] == CFSetGetValue((CFSetRef) nsset, @"world"), "CFSetGetValue works with an NSSet instance"); copy = CFSetCreateCopy(NULL, (CFSetRef) nsset); PASS_CF ([nsset count] == CFSetGetCount(copy), "CFSetCreateCopy resulting count matches"); CFRelease((CFSetRef) nsset); CFRelease(copy); return 0; } gnustep-corebase-0.2/Tests/CFRuntime/0000755000175000017500000000000014661604110016640 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFRuntime/runtime.m0000644000175000017500000001000113222706330020470 0ustar yavoryavor#include #include #include #import #include "../CFTesting.h" typedef const struct __GSPoint * GSPointRef; extern GSPointRef kGSPointOrigin; CFTypeID GSPointGetTypeID (void); GSPointRef GSPointCreate (CFAllocatorRef allocator, CFIndex x, CFIndex y); CFIndex GSPointGetX (GSPointRef o); CFIndex GSPointGetY (GSPointRef o); struct __GSPoint { CFRuntimeBase _base; CFIndex x; CFIndex y; }; static Boolean GSPointEqual(CFTypeRef cf1, CFTypeRef cf2) { GSPointRef o1 = (GSPointRef)cf1; GSPointRef o2 = (GSPointRef)cf2; if (o1->x != o2->y) return false; if (o1->x != o2->y) return false; return true; } static CFHashCode GSPointHash(CFTypeRef cf) { GSPointRef o = (GSPointRef)cf; return (CFHashCode)(o->x + o->y); } static CFStringRef GSPointCopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOpts) { GSPointRef o = (GSPointRef)cf; return CFStringCreateWithFormat (CFGetAllocator(cf), formatOpts, CFSTR("(%u, %u)"), o->x, o->x + o->y); } static CFStringRef GSPointCopyDebugDesc (CFTypeRef cf) { GSPointRef o = (GSPointRef)cf; return CFStringCreateWithFormat (CFGetAllocator(cf), NULL, CFSTR(" (%u, %u)"), o, CFGetAllocator(cf), o->x, o->y); } static CFTypeID _kGSPointTypeID = _kCFRuntimeNotATypeID; static CFRuntimeClass _kGSPointClass = { 0, "GSPoint", NULL, // init NULL, // copy NULL, // dealloc GSPointEqual, GSPointHash, GSPointCopyFormattingDesc, GSPointCopyDebugDesc }; struct __GSPoint _kGSPointOrigin = { INIT_CFRUNTIME_BASE(), 0, // X 0 // Y }; GSPointRef kGSPointOrigin = &_kGSPointOrigin; void GSPointInitialize (void) { _kGSPointTypeID = _CFRuntimeRegisterClass(&_kGSPointClass); _CFRuntimeInitStaticInstance ((void *)kGSPointOrigin, _kGSPointTypeID); } CFTypeID GSPointGetTypeID (void) { return _kGSPointTypeID; } GSPointRef GSPointCreate (CFAllocatorRef allocator, CFIndex x, CFIndex y) { struct __GSPoint *new; new = (struct __GSPoint*)_CFRuntimeCreateInstance(allocator, _kGSPointTypeID, sizeof(struct __GSPoint) - sizeof(CFRuntimeBase), NULL); if (NULL == new) return NULL; new->x = x; new->y = y; return (GSPointRef)new; } CFIndex GSPointGetX (GSPointRef o) { return o->x; } CFIndex GSPointGetY (GSPointRef o) { return o->y; } @interface GSPoint : NSObject { // Need to include the NSCFType ivars int16_t _typeID; int16_t _flags; CFIndex _x; CFIndex _y; } - (id) initWithX: (CFIndex)x Y: (CFIndex)y; - (CFIndex) x; - (CFIndex) y; @end @implementation GSPoint - (id) initWithX: (CFIndex)x Y: (CFIndex)y { GSPoint *new; new = (GSPoint*)GSPointCreate(NULL, x, y); RELEASE(self); self = new; return self; } - (CFIndex) x { return _x; } - (CFIndex) y { return _y; } @end int main (void) { GSPointRef pt; GSPoint *bpt; GSPointInitialize (); pt = GSPointCreate (NULL, 0, 0); PASS_CFEQ((CFTypeRef)pt, (CFTypeRef)kGSPointOrigin, "Points are equal"); PASS_CF(CFHash((CFTypeRef)pt) == CFHash((CFTypeRef)kGSPointOrigin), "Points have same hash code."); PASS_CFEQ(CFCopyDescription((CFTypeRef)pt), CFSTR("(0, 0)"), "Description is correct."); PASS_CFEQ(CFCopyTypeIDDescription(GSPointGetTypeID()), CFSTR("GSPoint"), "Type ID description is correct."); // Test the toll-free bridge mechanism bpt = [[GSPoint alloc] initWithX: 0 Y: 0]; PASS_CF(bpt != nil, "-initWithX:Y: returns non-nil"); PASS_CFEQ(pt, bpt, "CF object and ObjC object are the same"); PASS_CFEQ(CFCopyDescription((CFTypeRef)bpt), CFSTR("(0, 0)"), "ObjC returns same description as CF object"); /* START_SET("Retain/Release Tests") RETAIN((id)pt); CFRetain(bpt); CFRelease((CFTypeRef)pt); RELEASE(bpt); END_SET("Retain/Release Tests") */ RELEASE(bpt); CFRelease((CFTypeRef)pt); return 0; } gnustep-corebase-0.2/Tests/CFRuntime/TestInfo0000644000175000017500000000000013222706330020303 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFString/0000755000175000017500000000000014661604117016472 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFString/hash.m0000644000175000017500000000054713222706330017571 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "../CFTesting.h" int main (void) { UniChar uStr[] = { 's', 't', 'r', 0 }; CFStringRef str1 = CFSTR ("str"); CFStringRef str2 = CFStringCreateWithCharacters (NULL, uStr, 3); PASS_CF(CFHash (str1) == CFHash (str2), "Identical ASCII and UTF-16 string hashes match"); CFRelease(str2); return 0; } gnustep-corebase-0.2/Tests/CFString/encodings.m0000644000175000017500000000625313222706330020617 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "../CFTesting.h" #include /* These are all the same text. */ const UInt8 utf8_string[] = { 't', 0xC2, 0xA2, 'e', 0xE2, 0x82, 0xAC, 's', 0xF0, 0xA4, 0xAD, 0xA2, 't', '\0' }; const UInt8 utf8_ext_string[] = { 0xEF, 0xBB, 0xBF, 't', 0xC2, 0xA2, 'e', 0xE2, 0x82, 0xAC, 's', 0xF0, 0xA4, 0xAD, 0xA2, 't', '\0' }; const UniChar utf16_string[] = { 't', 0x00A2, 'e', 0x20AC, 's', 0xD852, 0xDF62, 't', '\0' }; const UniChar utf16_ext_string[] = { 0xFEFF, 't', 0x00A2, 'e', 0x20AC, 's', 0xD852, 0xDF62, 't', '\0' }; const UTF32Char utf32_string[] = { 't', 0x00A2, 'e', 0x20AC, 's', 0xD852, 0xDF62, 't', '\0' }; const UTF32Char utf32_ext_string[] = { 0xFEFF, 't', 0xA2, 'e', 0x20AC, 's', 0x24B62, 't', '\0' }; int main (void) { UInt8 buf1[256]; UInt8 buf2[256]; CFStringRef str_utf8; CFStringRef str_utf16; CFIndex num; CFIndex used1; CFIndex used2; num = CFStringGetMaximumSizeForEncoding (4, kCFStringEncodingUTF16); PASS_CF(num == 8, "Maximum size for 4 UTF-16 characters is 8 bytes."); num = CFStringGetMaximumSizeForEncoding (4, kCFStringEncodingUTF8); PASS_CF(num == 12, "Maximum size for 4 UTF-8 characters is 12 bytes."); str_utf16 = CFStringConvertEncodingToIANACharSetName (kCFStringEncodingUTF16); PASS_CFEQ (str_utf16, CFSTR("UTF-16"), "Correctly converts to IANA Char Set."); CFRelease(str_utf16); str_utf8 = CFStringCreateWithBytes (NULL, utf8_string, sizeof(utf8_string), kCFStringEncodingUTF8, false); str_utf16 = CFStringCreateWithCharacters (NULL, utf16_string, sizeof(utf16_string) / sizeof(UniChar)); PASS_CFEQ (str_utf8, str_utf16, "UTF-8 string is equal to UTF-16 string."); memset (buf1, 0, 256); memset (buf2, 0, 256); used1 = 0; used2 = 0; CFStringGetBytes (str_utf8, CFRangeMake (0, CFStringGetLength(str_utf8)), kCFStringEncodingUTF16, 0, false, buf1, 256, &used1); CFStringGetBytes (str_utf16, CFRangeMake (0, CFStringGetLength(str_utf16)), kCFStringEncodingUTF16, 0, true, buf2, 256, &used2); PASS_CF (used1 == used2, "UTF-16 convesion used the same from buffer."); PASS_CF (memcmp (buf1, utf16_string, used1) == 0, "UTF-16 conversion successful."); PASS_CF (memcmp (buf2, utf16_ext_string, used2) == 0, "External UTF-16 conversion successful."); CFRelease (str_utf8); CFRelease (str_utf16); return 0; } gnustep-corebase-0.2/Tests/CFString/objc_bridge.m0000664000175000017500000000202714661604117021104 0ustar yavoryavor#import #include "CoreFoundation/CFString.h" #include "../CFTesting.h" void refcounting_tests(void); void basic_ops(void); int main (void) { refcounting_tests(); basic_ops(); return 0; } void refcounting_tests(void) { NSString *str; CFStringRef str2; str = (NSString*)CFSTR("test"); PASS_CF ([str retainCount] == UINT_MAX, "Constant string has maximum retain count."); [str release]; PASS_CF ([str retainCount] == UINT_MAX, "Release has no effect of constant string."); str2 = CFStringCreateWithBytes (NULL, "Test2", 6, kCFStringEncodingASCII, 0); [str2 retain]; PASS_CF ([str2 retainCount] == 2, "CFStringRef instances accept -retain method calls"); } void basic_ops(void) { NSString* str = [NSString stringWithString: CFSTR("Hello world!")]; PASS_CF([str isEqual: @"Hello world!"], "NSString stringWithString accepts a CFStringRef"); PASS_CF(CFStringCompare((CFStringRef) str, CFSTR("Hello world!"), 0) == 0, "CFStringCompare accepts an NSString"); [str release]; } gnustep-corebase-0.2/Tests/CFString/format_misc.m0000644000175000017500000000336513222706330021152 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "../CFTesting.h" int main (void) { CFStringRef str1; void *ptr; int num; str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%c%2c%c"), 'r', 'u', 'n'); PASS_CFEQ(str1, CFSTR("r un"), "Characters are formatted correctly"); CFRelease(str1); ptr = (void*)12; str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%p %s"), ptr, "A longer than usual string."); PASS_CFEQ(str1, CFSTR ("0xc A longer than usual string."), "Strings are formatted correctly"); CFRelease(str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%@"), CFSTR("Object test")); PASS_CFEQ(str1, CFSTR("Object test"), "CFString objects are formatted correctly"); CFRelease(str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("1234%n"), &num); PASS_CF(num == 4, "Getting number of bytes written works."); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-8s"), NULL); PASS_CFEQ(str1, CFSTR("(null) "), "Left-aligned, NULL string formatted correctly."); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%8s"), NULL); PASS_CFEQ(str1, CFSTR(" (null)"), "Right-aligned, NULL string formatted correctly."); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%4.2s"), "string"); PASS_CFEQ(str1, CFSTR(" st"), "Truncated string formatted correctly."); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%% %s"), "%"); PASS_CFEQ(str1, CFSTR("% %"), "Percent sign formatted correctly."); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%p"), NULL); PASS_CFEQ(str1, CFSTR("(nil)"), "Percent sign formatted correctly."); CFRelease (str1); return 0; } gnustep-corebase-0.2/Tests/CFString/format_int.m0000644000175000017500000002736213222706330021014 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "../CFTesting.h" int main (void) { CFStringRef str1; str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%x"), 0x321); PASS_CFEQ (str1, CFSTR ("321"), "%%x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%.5x"), 0x321); PASS_CFEQ (str1, CFSTR ("00321"), "%%.5x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%05x"), 0x321); PASS_CFEQ (str1, CFSTR ("00321"), "%%05x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%5.4x"), 0x321); PASS_CFEQ (str1, CFSTR (" 0321"), "%%5.4x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%0#5.4x"), 0x321); PASS_CFEQ (str1, CFSTR ("0x0321"), "%%0#5.4x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%.*X"), 6, 0xabc); PASS_CFEQ (str1, CFSTR ("000ABC"), "%%.*x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%0*X"), 4, 0xabc); PASS_CFEQ (str1, CFSTR ("0ABC"), "%%0*x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%*.*X"), 6, 5, 0xabc); PASS_CFEQ (str1, CFSTR (" 00ABC"), "%%*.*x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%0*.*X"), 6, 5, 0xabc); PASS_CFEQ (str1, CFSTR (" 00ABC"), "%%0*.*x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#08o"), 0321); PASS_CFEQ (str1, CFSTR ("0321 "), "%%-+#08o formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#08d"), -321); PASS_CFEQ (str1, CFSTR ("-321 "), "%%-+#08d formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#08x"), 0x321); PASS_CFEQ (str1, CFSTR ("0x321 "), "%%-+#08x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#08X"), 0x321); PASS_CFEQ (str1, CFSTR ("0X321 "), "%%-+#08X formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#08u"), 321); PASS_CFEQ (str1, CFSTR ("321 "), "%%-+#08u formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#8o"), 0321); PASS_CFEQ (str1, CFSTR ("0321 "), "%%-+#8o formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#8d"), 321); PASS_CFEQ (str1, CFSTR ("+321 "), "%%-+#8d formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#8x"), 0x321); PASS_CFEQ (str1, CFSTR ("0x321 "), "%%-+#8x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#8X"), 0x321); PASS_CFEQ (str1, CFSTR ("0X321 "), "%%-+#8x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#8u"), 321); PASS_CFEQ (str1, CFSTR ("321 "), "%%-+#8u formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#8o"), 0321); PASS_CFEQ (str1, CFSTR ("0321 "), "%%-+#8o formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#8d"), -321); PASS_CFEQ (str1, CFSTR ("-321 "), "%%-+#8d formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#8x"), 0x321); PASS_CFEQ (str1, CFSTR ("0x321 "), "%%-+#8x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#8X"), 0x321); PASS_CFEQ (str1, CFSTR ("0X321 "), "%%-+#8x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+#8u"), 321); PASS_CFEQ (str1, CFSTR ("321 "), "%%-+#8u formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+8o"), 0321); PASS_CFEQ (str1, CFSTR ("321 "), "%%-+8o formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+8d"), 321); PASS_CFEQ (str1, CFSTR ("+321 "), "%%-+8d formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+8x"), 0x321); PASS_CFEQ (str1, CFSTR ("321 "), "%%-+8x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+8X"), 0x321); PASS_CFEQ (str1, CFSTR ("321 "), "%%-+8x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-+8u"), 321); PASS_CFEQ (str1, CFSTR ("321 "), "%%-+8u formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-8o"), 0321); PASS_CFEQ (str1, CFSTR ("321 "), "%%-8o formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-8d"), 321); PASS_CFEQ (str1, CFSTR ("321 "), "%%-8d formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-8x"), 0x321); PASS_CFEQ (str1, CFSTR ("321 "), "%%-8x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-8X"), 0x321); PASS_CFEQ (str1, CFSTR ("321 "), "%%-8x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%-8u"), 321); PASS_CFEQ (str1, CFSTR ("321 "), "%%-8u formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+#08o"), 0321); PASS_CFEQ (str1, CFSTR ("00000321"), "%%+#08o formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+#08d"), 321); PASS_CFEQ (str1, CFSTR ("+0000321"), "%%+#08d formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+#08x"), 0x321); PASS_CFEQ (str1, CFSTR ("0x000321"), "%%+#08x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+#08X"), 0x321); PASS_CFEQ (str1, CFSTR ("0X000321"), "%%+#08X formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+#08u"), 321); PASS_CFEQ (str1, CFSTR ("00000321"), "%%+#08u formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+#8o"), 0321); PASS_CFEQ (str1, CFSTR (" 0321"), "%%+#8o formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+#8d"), -321); PASS_CFEQ (str1, CFSTR (" -321"), "%%+#8d formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+#8x"), 0x321); PASS_CFEQ (str1, CFSTR (" 0x321"), "%%+#8x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+#8X"), 0x321); PASS_CFEQ (str1, CFSTR (" 0X321"), "%%+#8X formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+#8u"), 321); PASS_CFEQ (str1, CFSTR (" 321"), "%%+#8u formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+8o"), 0321); PASS_CFEQ (str1, CFSTR (" 321"), "%%+8o formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+8d"), 321); PASS_CFEQ (str1, CFSTR (" +321"), "%%+8d formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+8x"), 0x321); PASS_CFEQ (str1, CFSTR (" 321"), "%%+8x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+8X"), 0x321); PASS_CFEQ (str1, CFSTR (" 321"), "%%+8X formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%+8u"), 321); PASS_CFEQ (str1, CFSTR (" 321"), "%%+8u formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%#08o"), 0321); PASS_CFEQ (str1, CFSTR ("00000321"), "%%#08o formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%#08d"), 321); PASS_CFEQ (str1, CFSTR ("00000321"), "%%#08d formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%#08x"), 0x321); PASS_CFEQ (str1, CFSTR ("0x000321"), "%%#08x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%#08X"), 0x321); PASS_CFEQ (str1, CFSTR ("0X000321"), "%%#08X formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%#08u"), 321); PASS_CFEQ (str1, CFSTR ("00000321"), "%%#08u formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%#8o"), 0321); PASS_CFEQ (str1, CFSTR (" 0321"), "%%#8o formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%#8d"), 321); PASS_CFEQ (str1, CFSTR (" 321"), "%%#8d formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%#8x"), 0x321); PASS_CFEQ (str1, CFSTR (" 0x321"), "%%#8x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%#8X"), 0x321); PASS_CFEQ (str1, CFSTR (" 0X321"), "%%#8X formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%#8u"), 321); PASS_CFEQ (str1, CFSTR (" 321"), "%%#8u formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%08o"), 0321); PASS_CFEQ (str1, CFSTR ("00000321"), "%%08o formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%08d"), -321); PASS_CFEQ (str1, CFSTR ("-0000321"), "%%08d formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%08x"), 0x321); PASS_CFEQ (str1, CFSTR ("00000321"), "%%08x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%08X"), 0x321); PASS_CFEQ (str1, CFSTR ("00000321"), "%%08X formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%08u"), 321); PASS_CFEQ (str1, CFSTR ("00000321"), "%%08u formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%8o"), 0321); PASS_CFEQ (str1, CFSTR (" 321"), "%%8o formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%8d"), 321); PASS_CFEQ (str1, CFSTR (" 321"), "%%8d formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%8x"), 0x321); PASS_CFEQ (str1, CFSTR (" 321"), "%%8x formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%8X"), 0x321); PASS_CFEQ (str1, CFSTR (" 321"), "%%8X formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%8u"), 321); PASS_CFEQ (str1, CFSTR (" 321"), "%%8u formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%4.2i"), 321); PASS_CFEQ (str1, CFSTR (" 321"), "%%4.2i formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%5.1i"), -321); PASS_CFEQ (str1, CFSTR (" -321"), "%%5.1i formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%i"), -123); PASS_CFEQ (str1, CFSTR ("-123"), "Decimal formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%o"), -123); PASS_CFEQ (str1, CFSTR ("37777777605"), "Negative octal formatted correctly"); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%x"), -123); PASS_CFEQ (str1, CFSTR ("ffffff85"), "Negative hex formatted correctly"); CFRelease (str1); return 0; } gnustep-corebase-0.2/Tests/CFString/objc_bridge_from_cf.m0000664000175000017500000000564114661604117022604 0ustar yavoryavor/* * This file contains tests focused on using CF functions * with non-CF objects */ #import #include "CoreFoundation/CFString.h" #include "../CFTesting.h" void testCaseTransformations(void); void testWhitespace(void); void testPointerAccess(void); void testAppend(void); void testPad(void); void testGetBytes(void); void testEquals(void); int main(void) { testEquals(); testCaseTransformations(); testWhitespace(); testPointerAccess(); testAppend(); testPad(); testGetBytes(); return 0; } void testEquals(void) { NSString* str = @"Hello"; CFStringRef cstr = CFSTR("Hello"); PASS_CF([str isEqual: cstr], "isEqual works #1"); PASS_CF([cstr isEqual: str], "isEqual works #2"); PASS_CF([str hash] == [cstr hash], "hashes are equal"); } void testCaseTransformations(void) { NSMutableString* str = [NSMutableString stringWithCapacity: 0]; [str setString: @"hello world"]; CFStringUppercase((CFMutableStringRef) str, /*CFLocaleGetSystem()*/ NULL); PASS_CF([str isEqual: @"HELLO WORLD"], "CFStringUppercase works"); [str release]; } void testWhitespace(void) { NSMutableString* str = [NSMutableString stringWithCapacity: 0]; [str setString: @"\nHello\tworld \t"]; CFStringTrimWhitespace((CFMutableStringRef) str); PASS_CF([str isEqual: @"Hello\tworld"], "CFStringTrimWhitespace works"); [str release]; } void testPointerAccess(void) { CFStringRef str = (CFStringRef) @"Hello world!"; PASS_CF(strcmp(CFStringGetCStringPtr(str, kCFStringEncodingASCII), "Hello world!") == 0, "CFStringGetCStringPtr works on a Foundation object"); } void testAppend(void) { const UniChar trivialUtf16[] = { ' ', 'w', 'o', 'r', 'l', 'd', '!', 0 }; NSMutableString* str = [NSMutableString stringWithCapacity: 0]; [str setString: @"Hello"]; CFStringAppendCString((CFMutableStringRef) str, " world!", kCFStringEncodingASCII); PASS_CF([str isEqual: @"Hello world!"], "CFStringAppendCString works"); [str setString: @"Hello"]; CFStringAppendCharacters((CFMutableStringRef) str, trivialUtf16, 7); PASS_CF([str isEqual: @"Hello world!"], "CFStringAppendCharacters works"); [str release]; } void testPad(void) { NSMutableString* str = [NSMutableString stringWithCapacity: 0]; [str setString: (NSString*) CFSTR("abcdef")]; CFStringPad((CFMutableStringRef) str, CFSTR("123"), 9, 1); PASS_CF([str isEqual: @"abcdef231"], "CFStringPad works"); [str release]; } void testGetBytes(void) { NSString* str = @"Hello world!"; const UniChar uniStr[] = { 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l' }; UniChar buffer[10]; CFIndex usedLen = -1; CFStringGetBytes((CFStringRef) str, CFRangeMake(1, 9), kCFStringEncodingUnicode, 0, false, (UInt8*) buffer, 9, &usedLen); testHopeful = true; PASS_CF(memcmp(buffer, uniStr, sizeof(UniChar)*9) == 0, "CFStringGetBytes works in simple case"); // TODO: lossByte, ext representation... PASS_CF(usedLen == 9, "CFStringGetBytes returns correct usedLen"); testHopeful = false; } gnustep-corebase-0.2/Tests/CFString/normalize.m0000664000175000017500000000200414661604117020646 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "../CFTesting.h" #import #include int main (void) { // Letter 'Å' UniChar notNormalized[] = { 0x212B, 0 }; UniChar normalized[] = { 0x0041, 0x030A, 0 }; CFMutableStringRef mut; UniChar* processed; NSMutableString* nsmut; mut = CFStringCreateMutable (NULL, 0); CFStringAppendCharacters (mut, notNormalized, 1); CFStringNormalize(mut, kCFStringNormalizationFormD); processed = CFStringGetCharactersPtr(mut); printf("first char: %04x\n", *processed); PASS_CF (memcmp(processed, normalized, 4) == 0, "CFStringNormalize works"); CFRelease(mut); nsmut = [[NSString stringWithCharacters: notNormalized length: 1] mutableCopy]; CFStringNormalize(nsmut, kCFStringNormalizationFormD); PASS_CF ([nsmut length] == 2, "Correct char count"); PASS_CF ([nsmut characterAtIndex: 0] == normalized[0], "CFStringNormalize works on an NSString"); [nsmut release]; return 0; } gnustep-corebase-0.2/Tests/CFString/format_float.m0000644000175000017500000000117613222706330021322 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "../CFTesting.h" #include int main (void) { CFStringRef str1; str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%a %A %f %F %g %G"), -INFINITY, INFINITY, INFINITY, -INFINITY, -INFINITY, INFINITY); PASS_CFEQ (str1, CFSTR ("-inf INF inf -INF -inf INF"), "Formatting infinity works."); CFRelease (str1); str1 = CFStringCreateWithFormat (NULL, NULL, CFSTR("%a %A %f %F %g %G"), -NAN, NAN, NAN, -NAN, -NAN, NAN); PASS_CFEQ (str1, CFSTR ("-nan NAN nan -NAN -nan NAN"), "Formatting not-a-number works."); CFRelease (str1); return 0; } gnustep-corebase-0.2/Tests/CFString/TestInfo0000644000175000017500000000000013222706330020126 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFString/general.m0000644000175000017500000000170013222706330020253 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "../CFTesting.h" int main (void) { CFStringRef str; CFArrayRef array; CFRange found; /* This is used by CFURL. */ array = CFStringCreateArrayBySeparatingStrings (NULL, CFSTR("/usr/local/share/GNUstep/"), CFSTR("/")); PASS_CF(CFArrayGetCount(array) == 6, "There are 6 strings on separated string."); str = CFArrayGetValueAtIndex (array, 1); PASS_CFEQ(str, CFSTR("usr"), "Value at index 1 is 'usr'"); str = CFStringCreateByCombiningStrings (NULL, array, CFSTR("\\")); PASS_CFEQ(str, CFSTR("\\usr\\local\\share\\GNUstep\\"), "Combined string is \\usr\\local\\share\\GNUstep\\"); CFRelease (array); PASS_CF(CFStringFindWithOptions(str, CFSTR("\\"), CFRangeMake(5, 12), 0, &found), "'\\' was found."); PASS_CF(found.location == 10 && found.length == 1, "String has range (%d, %d)", (int)found.location, (int)found.length); CFRelease (str); return 0; }gnustep-corebase-0.2/Tests/CFString/create.m0000644000175000017500000000162513222706330020107 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "../CFTesting.h" int main (void) { CFStringRef str1; CFStringRef str2; CFStringRef string; CFStringRef arrayValues[2]; CFArrayRef array; UniChar ubuffer[] = { 'O', 'K', '!', 0 }; str1 = CFStringCreateWithBytes (NULL, (const UInt8*)"OK", 2, kCFStringEncodingASCII, false); str2 = CFStringCreateWithBytes (NULL, (const UInt8*)ubuffer, 2 * sizeof(UniChar), kCFStringEncodingUTF16, false); PASS_CFEQ(str1, str2, "Unicode and C-string are equal."); arrayValues[0] = str1; arrayValues[1] = str2; array = CFArrayCreate (NULL, (const void **)arrayValues, 2, &kCFTypeArrayCallBacks); string = CFStringCreateByCombiningStrings (NULL, array, CFSTR("! ")); PASS_CFEQ(string, CFSTR("OK! OK"), "Strings were combined successfully."); CFRelease(str1); CFRelease(str2); CFRelease(string); CFRelease(array); return 0; } gnustep-corebase-0.2/Tests/CFString/mutablestring.m0000644000175000017500000000314513222706330021523 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "../CFTesting.h" int main (void) { CFMutableStringRef str1; CFMutableStringRef str2; CFStringRef constant1 = CFSTR("Test string."); CFStringRef constant2 = CFSTR(" test "); str1 = CFStringCreateMutable (NULL, 0); CFStringReplaceAll (str1, constant1); PASS_CFEQ(str1, constant1, "String is replaced correctly."); str2 = CFStringCreateMutableCopy (NULL, CFStringGetLength(str1), str1); CFStringUppercase (str2, NULL); PASS_CFEQ(str2, CFSTR("TEST STRING."), "Uppercase mapping works."); CFStringCapitalize (str2, NULL); PASS_CFEQ(str2, CFSTR("Test String."), "Capitalize mapping works."); CFStringLowercase (str2, NULL); PASS_CFEQ(str2, CFSTR("test string."), "Lowercase mapping works"); CFStringReplace (str2, CFRangeMake(0, CFStringGetLength(str1)), constant1); PASS_CFEQ(str2, constant1, "String is replaced whole."); CFRelease(str1); CFRelease(str2); str1 = CFStringCreateMutable (NULL, 0); CFStringReplaceAll (str1, constant2); CFStringTrimWhitespace (str1); PASS_CFEQ(str1, CFSTR("test"), "String is trimmed correctly."); CFStringReplace (str1, CFRangeMake(1, 2), constant1); PASS_CFEQ(str1, CFSTR("tTest string.t"), "String replacement works"); CFRelease (str1); str1 = CFStringCreateMutable (NULL, 0); CFStringReplaceAll (str1, CFSTR("abcdef")); constant1 = CFSTR("123"); CFStringPad (str1, constant1, 9, 1); PASS_CFEQ(str1, CFSTR("abcdef231"), "Padding works."); CFStringPad (str1, NULL, 3, 0); PASS_CFEQ(str1, CFSTR("abc"), "Truncating works."); CFRelease (str1); return 0; } gnustep-corebase-0.2/Tests/CFString/format_errors.m0000644000175000017500000000107713222706330021531 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "../CFTesting.h" int main (void) { CFStringRef o; o = CFStringCreateWithFormat (NULL, NULL, CFSTR("%z"), "test"); PASS_CF(o == NULL, "Format with invalid spec (%%z) returns NULL."); o = CFStringCreateWithFormat (NULL, NULL, CFSTR("%s %01.2z"), "test", NULL); PASS_CF(o == NULL, "Complex format with invalid spec (%%01.2z) returns NULL."); o = CFStringCreateWithFormat (NULL, NULL, CFSTR("%s %1$s"), "test1", "test2"); PASS_CF(o == NULL, "Specifying only 1 positional parameter returns NULL."); return 0; } gnustep-corebase-0.2/Tests/CFBinaryHeap/0000755000175000017500000000000014661604107017245 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFBinaryHeap/TestInfo0000644000175000017500000000000013222706330020702 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFBinaryHeap/general.m0000644000175000017500000000232113222706330021027 0ustar yavoryavor#include #include "../CFTesting.h" #include #define ARRAY_SIZE 6 const CFIndex array[ARRAY_SIZE] = { 7, 10, 5, 10, 25, 1 }; const CFIndex sorted[ARRAY_SIZE] = { 1, 5, 7, 10, 10, 25 }; int main (void) { CFIndex idx; CFIndex n; CFBinaryHeapRef heap; CFIndex values[ARRAY_SIZE]; heap = CFBinaryHeapCreate (NULL, ARRAY_SIZE, NULL, NULL); PASS_CF(heap != NULL, "Binary heap was created."); for (idx = 0 ; idx < ARRAY_SIZE ; ++idx) CFBinaryHeapAddValue (heap, (const void*)array[idx]); n = CFBinaryHeapGetCount(heap); PASS_CF(n == ARRAY_SIZE, "Binary heap has %d values.", (int)n); PASS_CF(CFBinaryHeapContainsValue(heap, (const void*)5), "Binary heap has value."); n = CFBinaryHeapGetCountOfValue(heap, (const void*)10); PASS_CF(n == 2, "Value 10 appears %d times in binary heap.", (int)n); CFBinaryHeapGetValues (heap, (const void**)values); PASS_CF(memcmp(values, sorted, sizeof(void*) * ARRAY_SIZE) == 0, "All values are in the binary heap."); CFBinaryHeapRemoveMinimumValue (heap); n = (CFIndex)CFBinaryHeapGetMinimum (heap); PASS_CF(n == 5, "Minimum value in binary heap is %d.", (int)n); CFRelease (heap); return 0; }gnustep-corebase-0.2/Tests/CFDateFormatter/0000755000175000017500000000000014661604117017765 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFDateFormatter/basic.m0000664000175000017500000000347414661604117021236 0ustar yavoryavor#include "CoreFoundation/CFDateFormatter.h" #include "CoreFoundation/CFTimeZone.h" #include "../CFTesting.h" int main (void) { CFAbsoluteTime at; CFLocaleRef loc; CFStringRef str; CFDateFormatterRef fmt; CFTimeZoneRef tz; loc = CFLocaleCreate (NULL, CFSTR("de_DE")); fmt = CFDateFormatterCreate (NULL, loc, kCFDateFormatterFullStyle, kCFDateFormatterShortStyle); tz = CFTimeZoneCreateWithTimeIntervalFromGMT (NULL, 3600.0); CFDateFormatterSetProperty (fmt, kCFDateFormatterTimeZone, tz); str = CFDateFormatterGetFormat (fmt); PASS_CFEQ(str, CFSTR("EEEE, d. MMMM y HH:mm"), "Default format for de_DE locale is EEEE, d. MMMM y HH:mm"); str = CFDateFormatterCreateStringWithAbsoluteTime (NULL, fmt, 65.0); PASS_CFEQ(str, CFSTR("Montag, 1. Januar 2001 01:01"), "Absolute time can be formatted using full date style."); CFRelease(str); PASS_CF(CFDateFormatterGetAbsoluteTimeFromString (fmt, CFSTR("Montag, 1. Januar 2011 23:00"), NULL, &at), "Absolute time gotten for 2/1/2003"); PASS_CF(at == 315612000.0, "Absolute time for Montag, 1. Januar 2011 23:00 is %f", at); CFRelease(fmt); fmt = CFDateFormatterCreate (NULL, loc, kCFDateFormatterNoStyle, kCFDateFormatterNoStyle); str = CFDateFormatterCreateStringWithAbsoluteTime (NULL, fmt, 65.0); PASS_CFEQ(str, CFSTR("20010101 12:01 vorm."), "Absolute time can be formatted using no date style."); CFRelease(str); PASS_CF(CFDateFormatterGetAbsoluteTimeFromString (fmt, CFSTR("20050403 02:01 vorm."), NULL, &at), "Absolute time gotten for 20050403 02:01 vorm."); PASS_CF(at == 134186460.0, "Absolute time for 20050403 02:01 vorm. is %f", at); CFRelease(fmt); CFRelease(loc); return 0; }gnustep-corebase-0.2/Tests/CFDateFormatter/TestInfo0000644000175000017500000000000013222706330021421 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFDictionary/0000755000175000017500000000000014661604107017330 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFDictionary/TestInfo0000644000175000017500000000000013222706330020765 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFDictionary/general.m0000644000175000017500000000620414551015633021123 0ustar yavoryavor#include "CoreFoundation/CFDictionary.h" #include "CoreFoundation/CFNumber.h" #include "../CFTesting.h" int main (void) { CFMutableDictionaryRef cfdict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); int keys[] = {48, 33, 39, 44, 47, 56, 59, 54, 58, 71, 63, 61, 77, 64, 68, 60, 65, 70, 73, 84, 82, 75}; int key, value, i; int removeCount, count = sizeof(keys)/sizeof(*keys); CFTypeRef cfkey, cfvalue; for (i = 0; i < count; i++) { key = keys[i]; cfkey = CFNumberCreate (NULL, kCFNumberIntType, &key); cfvalue = CFNumberCreate (NULL, kCFNumberIntType, &i); CFDictionarySetValue(cfdict, cfkey, cfvalue); CFNumberRef cfvalue2 = CFDictionaryGetValue(cfdict, cfkey); PASS_CFEQ(cfvalue, cfvalue2, "set and get values are equal"); CFRelease(cfkey); CFRelease(cfvalue); } key = 57; cfkey = CFNumberCreate (NULL, kCFNumberIntType, &key); PASS_CF(CFDictionaryGetValue(cfdict, cfkey) == NULL, "CFDictionaryGetValue returns NULL for nonexistant key"); CFRelease(cfkey); for (i = 0; i < count; i++) { key = keys[i]; cfkey = CFNumberCreate (NULL, kCFNumberIntType, &key); cfvalue = CFDictionaryGetValue(cfdict, cfkey); PASS_CF(cfvalue != NULL, "CFDictionaryGetValue returns value for existant key %d", key); if (cfvalue) { CFNumberGetValue(cfvalue, kCFNumberIntType, &value); PASS_CF(value == i, "CFDictionaryGetValue returns correct value %d == %d for key %d", value, i, key); } CFRelease(cfkey); } PASS_CF(CFDictionaryGetCount(cfdict) == count, "CFDictionaryGetCount returns correct value"); CFDictionaryRemoveAllValues(cfdict); PASS_CF(CFDictionaryGetCount(cfdict) == 0, "CFDictionaryRemoveAllValues removes all values"); // test large dictionary count = 5000; removeCount = 0; CFStringRef keyFormat = CFSTR("key-%d"); for (i = 0; i < count; i++) { cfkey = CFStringCreateWithFormat(NULL, NULL, keyFormat, i); cfvalue = CFNumberCreate(NULL, kCFNumberIntType, &i); CFDictionarySetValue(cfdict, cfkey, cfvalue); CFRelease(cfkey); CFRelease(cfvalue); // start removing keys while we are adding new ones after filling 1/10 if (i > count/10) { int keyToRemove = removeCount++; cfkey = CFStringCreateWithFormat(NULL, NULL, keyFormat, keyToRemove); cfvalue = CFDictionaryGetValue(cfdict, cfkey); PASS_CF(cfvalue != NULL, "CFDictionaryGetValue returns value for key 'key-%d' to remove", keyToRemove); CFDictionaryRemoveValue(cfdict, cfkey); CFRelease(cfkey); } } for (i = 0; i < count; i++) { cfkey = CFStringCreateWithFormat(NULL, NULL, keyFormat, i); cfvalue = CFDictionaryGetValue(cfdict, cfkey); if (i < removeCount) { PASS_CF(cfvalue == NULL, "CFDictionaryGetValue returns no value for non-existant key 'key-%d': %p", i, cfvalue); } else { CFNumberRef cfvalue2 = CFNumberCreate(NULL, kCFNumberIntType, &i); PASS_CFEQ(cfvalue, cfvalue2, "CFDictionaryGetValue returns correct value for existant key 'key-%d': %p", i, cfvalue); } CFRelease(cfkey); } CFRelease(cfdict); return 0; }gnustep-corebase-0.2/Tests/CFDictionary/bridge.m0000644000175000017500000000746514551015633020754 0ustar yavoryavor#import #import #import #include "CoreFoundation/CFDictionary.h" #include "../CFTesting.h" void testCFonNS(void); void testNSonCF(void); void testLargeDict(void); int main (void) { testCFonNS(); testNSonCF(); testLargeDict(); return 0; } void testCFonNS(void) { NSMutableDictionary* nsdict = [[NSMutableDictionary alloc] initWithCapacity: 4]; CFMutableDictionaryRef cfdict = (CFMutableDictionaryRef) nsdict; CFIndex count; [nsdict setValue: @"A" forKey: @"a"]; [nsdict setValue: @"B" forKey: @"b"]; [nsdict setValue: @"C" forKey: @"c"]; [nsdict setValue: @"D" forKey: @"d"]; count = [nsdict count]; PASS_CF(CFDictionaryGetCount(cfdict) == count, "CFDictionaryGetCount() works on an NSDictionary"); PASS_CF(CFDictionaryGetValue(cfdict, @"b") == [nsdict objectForKey: @"b"], "CFDictionaryGetValue() works on an NSDictionary"); CFDictionaryAddValue(cfdict, @"e", @"E"); PASS_CF(CFDictionaryGetCount(cfdict) == count+1, "CFDictionaryAddValue() added a pair into an NSDictionary"); NSLog(@"dict: %@\n", nsdict); PASS_CF(CFDictionaryGetCountOfKey(cfdict, @"e") == 1, "CFDictionaryGetCountOfKey() works on an NSDictionary (#1)"); PASS_CF(CFDictionaryGetCountOfValue(cfdict, @"E") == 1, "CFDictionaryGetCountOfValue() works on an NSDictionary (#1)"); PASS_CF(CFDictionaryGetCountOfKey(cfdict, @"b") == 1, "CFDictionaryGetCountOfKey() works on an NSDictionary (#2)"); PASS_CF(CFDictionaryGetCountOfValue(cfdict, @"B") == 1, "CFDictionaryGetCountOfValue() works on an NSDictionary (#2)"); CFRelease(cfdict); } void testNSonCF(void) { CFMutableDictionaryRef cfdict = CFDictionaryCreateMutable(NULL, 4, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); NSMutableDictionary* nsdict = (NSMutableDictionary*) cfdict; CFIndex count; CFDictionaryAddValue(cfdict, @"a", @"A"); CFDictionaryAddValue(cfdict, @"b", @"B"); CFDictionaryAddValue(cfdict, @"c", @"C"); CFDictionaryAddValue(cfdict, @"d", @"D"); count = CFDictionaryGetCount(cfdict); PASS_CF([nsdict count] == count, "-count works on a CFDictionary"); PASS_CF(CFDictionaryGetValue(cfdict, @"b") == [nsdict objectForKey: @"b"], "-objectForKey: works on a CFDictionary"); [nsdict setObject: @"E" forKey: @"e"]; PASS_CF([nsdict count] == count+1, "-setObject:forKey: works on a CFDictionary"); PASS_CF([nsdict objectForKey: @"e"] != nil, "-objectForKey: works on a CFDictionary"); [nsdict release]; } void testLargeDict(void) { CFMutableDictionaryRef cfdict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); int count = 5000; int removeCount = 0; for (int i = 0; i < count; i++) { id key = [[NSString alloc] initWithFormat:@"key-%d", i]; id value = [[NSNumber alloc] initWithInt:i]; CFDictionarySetValue(cfdict, (__bridge const void *)key, (__bridge const void *)value); [key release]; [value release]; // start removing keys while we are adding new ones after filling 1/10 if (i > count/10) { id keyToEvict = [[NSString alloc] initWithFormat:@"key-%d", removeCount++]; CFDictionaryRemoveValue(cfdict, (__bridge const void *)(keyToEvict)); [keyToEvict release]; } } for (int i = 0; i < count; i++) { id key = [[NSString alloc] initWithFormat:@"key-%d", i]; void *value = CFDictionaryGetValue(cfdict, (__bridge const void *)key); if (i < removeCount) { PASS_CF(value == NULL, "CFDictionaryGetValue returns no value for non-existant key '%@'", key); } else { PASS_CF(value != NULL, "CFDictionaryGetValue returns value for existant key '%@'", key); } [key release]; } CFRelease(cfdict); } gnustep-corebase-0.2/Tests/CFArray/0000755000175000017500000000000014661604107016301 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFArray/mutablearray.m0000644000175000017500000000265513222706330021150 0ustar yavoryavor#include "CoreFoundation/CFArray.h" #include "../CFTesting.h" #include #define ARRAY_SIZE 5 const CFIndex array[ARRAY_SIZE] = { 5, 2, 3, 4, 1 }; const CFIndex sorted[ARRAY_SIZE+1] = { 1, 2, 3, 4, 5, 7 }; CFComparisonResult comp (const void *val1, const void *val2, void *context) { return val1 == val2 ? kCFCompareEqualTo : (val1 < val2 ? kCFCompareLessThan : kCFCompareGreaterThan); } int main (void) { CFArrayRef a; CFMutableArrayRef ma; CFIndex n; CFIndex len; CFIndex buf[ARRAY_SIZE + 1]; a = CFArrayCreate (NULL, (const void**)&array, ARRAY_SIZE, NULL); PASS_CF(a != NULL, "CFArray created."); ma = CFArrayCreateMutableCopy (NULL, 6, a); PASS_CF(ma != NULL, "CFMutableArray created."); n = 7; CFArrayAppendValue (ma, (const void*)n); len = CFArrayGetCount ((CFArrayRef)ma); PASS_CF(len == ARRAY_SIZE + 1, "CFMutableArray has correct number of values."); CFArraySortValues (ma, CFRangeMake(0, len), comp, NULL); CFArrayGetValues (ma, CFRangeMake(0, len), (const void**)buf); PASS_CF(memcmp(buf, sorted, sizeof(CFIndex) * ARRAY_SIZE) == 0, "Array sorted correctly."); n = CFArrayBSearchValues (ma, CFRangeMake(2, len - 2), (const void*)5, comp, NULL); PASS_CF(n == 4, "Index of number 5 is %d.", (int)n); n = CFArrayBSearchValues (ma, CFRangeMake(0, len), (const void*)6, comp, NULL); PASS_CF(n == 5, "Index of value between values is %d.", (int)n); return 0; } gnustep-corebase-0.2/Tests/CFArray/TestInfo0000644000175000017500000000000013222706330017736 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFArray/create.m0000644000175000017500000000143513222706330017716 0ustar yavoryavor#include "CoreFoundation/CFArray.h" #include "../CFTesting.h" #define ARRAY_SIZE 5 const CFIndex array[ARRAY_SIZE] = { 5, 2, 1, 4, 3 }; int main (void) { CFArrayRef a; CFIndex n; a = CFArrayCreate (NULL, (const void**)&array, ARRAY_SIZE, NULL); PASS_CF(a != NULL, "CFArray created."); n = CFArrayGetCount (a); PASS_CF(n == ARRAY_SIZE, "CFArray has correct number of values."); n = (CFIndex)CFArrayGetCountOfValue (a, CFRangeMake(0, ARRAY_SIZE), (const void*)3); PASS_CF(n == 1, "Found 1 occurence of the %d.", (int)n); n = (CFIndex)CFArrayGetValueAtIndex (a, 1); PASS_CF(n == 2, "Found value at index %d.", (int)n); CFRelease (a); a = CFArrayCreate (NULL, NULL, 0, NULL); PASS_CF(a != NULL, "An array with no values return non-NULL."); return 0; } gnustep-corebase-0.2/Tests/CFArray/bridge.m0000644000175000017500000000434614551015633017720 0ustar yavoryavor#import #import #include "CoreFoundation/CFArray.h" #include "../CFTesting.h" void testNSonCF(void); void testCFonNS(void); int main(void) { testNSonCF(); testCFonNS(); return 0; } void testNSonCF(void) { CFMutableArrayRef cfarray = CFArrayCreateMutable(NULL, 4, &kCFTypeArrayCallBacks); NSMutableArray* nsarray = (NSMutableArray*) cfarray; CFIndex count; CFArrayAppendValue(cfarray, CFSTR("1")); CFArrayAppendValue(cfarray, CFSTR("2")); CFArrayAppendValue(cfarray, CFSTR("3")); CFArrayAppendValue(cfarray, CFSTR("4")); count = CFArrayGetCount(cfarray); PASS_CF([nsarray count] == count, "-count works on a CFArray"); [nsarray addObject: (id)CFSTR("5")]; PASS_CF([nsarray count] == count+1, "-addObject: adds a value into a CFArray"); PASS_CF(CFArrayGetValueAtIndex(cfarray, 1) == [nsarray objectAtIndex: 1], "-objectAtIndex: works on a CFArray (#1)"); PASS_CF(CFArrayGetValueAtIndex(cfarray, 4) == [nsarray objectAtIndex: 4], "-objectAtIndex: works on a CFArray (#2)"); PASS_CF(CFArrayGetFirstIndexOfValue(cfarray, CFRangeMake(0, count+1), @"5") == [nsarray indexOfObject: @"5"], "-indexOfObject: works on a CFArray"); [nsarray release]; } void testCFonNS(void) { NSMutableArray* nsarray = [[NSMutableArray alloc] initWithCapacity: 4]; CFMutableArrayRef cfarray = (CFMutableArrayRef) nsarray; CFIndex count; [nsarray addObject: @"1"]; [nsarray addObject: @"2"]; [nsarray addObject: @"3"]; [nsarray addObject: @"4"]; count = [nsarray count]; PASS_CF(CFArrayGetCount(cfarray) == count, "CFArrayGetCount() works on an NSArray"); CFArrayAppendValue(cfarray, @"5"); PASS_CF(CFArrayGetCount(cfarray) == count+1, "CFArrayAppendValue() adds a value into an NSArray"); PASS_CF(CFArrayGetValueAtIndex(cfarray, 1) == [nsarray objectAtIndex: 1], "CFArrayGetValueAtIndex() works on an NSArray (#1)"); PASS_CF(CFArrayGetValueAtIndex(cfarray, 4) == [nsarray objectAtIndex: 4], "CFArrayGetValueAtIndex() works on an NSArray (#2)"); PASS_CF(CFArrayGetFirstIndexOfValue(cfarray, CFRangeMake(0, count+1), @"5") == [nsarray indexOfObject: @"5"], "CFArrayGetFirstIndexOfValue() works on an NSArray"); CFRelease(cfarray); } gnustep-corebase-0.2/Tests/CFURL/0000755000175000017500000000000014661604110015657 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFURL/escaping.m0000644000175000017500000000263013222706330017626 0ustar yavoryavor#include "CoreFoundation/CFURL.h" #include "../CFTesting.h" int main (void) { CFStringRef str; CFStringRef str2; CFStringRef urlStr = CFSTR("http://www.gnustep.org/Test file.html"); str = CFURLCreateStringByAddingPercentEscapes (NULL, urlStr, NULL, NULL, kCFStringEncodingUTF8); PASS_CFEQ(str, CFSTR("http://www.gnustep.org/Test%20file.html"), "URL string is escaped correctly."); CFRelease (str); str = CFURLCreateStringByAddingPercentEscapes (NULL, urlStr, CFSTR(" "), CFSTR("ep"), kCFStringEncodingUTF8); PASS_CFEQ(str, CFSTR("htt%70://www.gnust%65%70.org/T%65st fil%65.html"), "Correct characters escaped."); str2 = CFURLCreateStringByReplacingPercentEscapes (NULL, str, NULL); PASS_CFEQ(str2, str, "No percent escapes were replaced."); CFRelease (str2); str2 = CFURLCreateStringByReplacingPercentEscapes (NULL, str, CFSTR("")); PASS_CFEQ(str2, urlStr, "Percent escapes replaced correctly."); CFRelease (str); CFRelease (str2); str = CFURLCreateStringByAddingPercentEscapes (NULL, urlStr, NULL, CFSTR("nm/."), kCFStringEncodingUTF8); PASS_CFEQ(str, CFSTR("http:%2F%2Fwww%2Eg%6Eustep%2Eorg%2FTest%20file%2Eht%6Dl"), "Correct characters escaped."); str2 = CFURLCreateStringByReplacingPercentEscapes (NULL, str, CFSTR("")); PASS_CFEQ(str2, urlStr, "Percent escapes replaced correctly."); CFRelease (str); CFRelease (str2); return 0; }gnustep-corebase-0.2/Tests/CFURL/file_system_path.m0000644000175000017500000000466413222706330021405 0ustar yavoryavor#include "CoreFoundation/CFURL.h" #include "../CFTesting.h" int main (void) { CFURLRef url; CFURLRef baseURL; CFStringRef str; url = CFURLCreateWithFileSystemPath (NULL, CFSTR("C:\\WINDOWS"), kCFURLWindowsPathStyle, true); PASS_CF(CFURLCanBeDecomposed(url) == true, "C:\\WINDOWS path can be decomposed"); PASS_CFEQ(CFURLGetString(url), CFSTR("file://localhost/C:/WINDOWS/"), "Windows style path of file URL C:\\WINDOWS is file://localhost/C:/WINDOWS/"); PASS_CF(CFURLCopyResourceSpecifier (url) == NULL, "Resource specifier of C:\\WINDOWS is NULL"); str = CFURLCopyFileSystemPath (url, kCFURLWindowsPathStyle); PASS_CFEQ(str, CFSTR("C:\\WINDOWS"), "File system path is C:\\WINDOWS"); CFRelease (str); str = CFURLCopyPath (url); PASS_CFEQ(str, CFSTR("/C:/WINDOWS/"), "Path is /C:/WINDOWS/"); CFRelease (str); str = CFURLCopyStrictPath (url, NULL); PASS_CFEQ(str, CFSTR("C:/WINDOWS/"), "Strict path is C:/WINDOWS/"); CFRelease (str); CFRelease (url); url = CFURLCreateWithFileSystemPath (NULL, CFSTR("/usr"), kCFURLPOSIXPathStyle, true); PASS_CF(CFURLCanBeDecomposed(url) == true, "/usr path can be decomposed"); PASS_CFEQ(CFURLGetString(url), CFSTR("file://localhost/usr/"), "String for file URL /usr is /usr/"); PASS_CF(CFURLCopyResourceSpecifier (url) == NULL, "Resource Specifier of /usr is NULL"); str = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle); PASS_CFEQ(str, CFSTR("/usr"), "File system path is /usr"); CFRelease (str); str = CFURLCopyPath (url); PASS_CFEQ(str, CFSTR("/usr/"), "Path is /usr/"); CFRelease (str); str = CFURLCopyStrictPath (url, NULL); PASS_CFEQ(str, CFSTR("usr/"), "Strict path is usr/"); CFRelease (str); CFRelease (url); baseURL = CFURLCreateWithFileSystemPath (NULL, CFSTR("/usr"), kCFURLPOSIXPathStyle, true); url = CFURLCreateWithFileSystemPathRelativeToBase (NULL, CFSTR("local/share"), kCFURLPOSIXPathStyle, true, baseURL); PASS_CF(CFURLCanBeDecomposed(url) == true, "local/share path can be decomposed"); str = CFURLGetString (url); PASS_CFEQ(str, CFSTR("local/share/"), "String is local/share/"); str = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle); PASS_CFEQ(str, CFSTR("local/share"), "File system path is not resolved against base"); CFRelease (str); PASS_CF(CFURLHasDirectoryPath(url) == true, "local/share is a directory path."); CFRelease (url); CFRelease (baseURL); return false; }gnustep-corebase-0.2/Tests/CFURL/ref_resolution.m0000644000175000017500000001141413222706330021074 0ustar yavoryavor#include "CoreFoundation/CFURL.h" #include "../CFTesting.h" int main (void) { CFURLRef url; CFURLRef url2; CFURLRef url3; CFStringRef str; url = CFURLCreateWithString (NULL, CFSTR("http://here.and.there/testing/one.html"), NULL); url2 = CFURLCreateWithString (NULL, CFSTR("aaa/bbb/ccc/"), url); CFRelease (url); url = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url), CFSTR("http://here.and.there/testing/aaa/bbb/ccc/"), "Simple relative URL absoluteString works"); str = CFURLCopyPath (url); PASS_CFEQ(str, CFSTR("/testing/aaa/bbb/ccc/"), "Simple relative URL path works"); CFRelease (url); CFRelease (url2); CFRelease (str); url = CFURLCreateWithString (NULL, CFSTR("http://a"), NULL); url2 = CFURLCreateWithString (NULL, CFSTR("../g"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/g"), "../g resolved against http://a is http://a/g"); CFRelease(url); CFRelease(url2); CFRelease(url3); /* Examples from RFC 3986 */ url = CFURLCreateWithString (NULL, CFSTR("http://a/b/c/d;p?q"), NULL); url2 = CFURLCreateWithString (NULL, CFSTR("g:h"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("g:h"), "g:h resolved against http://a/b/c/d;p?q is g:h"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("./g"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/b/c/g"), "./g resolved against http://a/b/c/d;p?q is http://a/b/c/g"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("//g"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://g"), "//g resolved against http://a/b/c/d;p?q is http://g"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("#s"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/b/c/d;p?q#s"), "#s resolved against http://a/b/c/d;p?q is http:/a/b/c/d;p?q#s"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("g;x?y#s"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/b/c/g;x?y#s"), "g;x?y#s resolved against http://a/b/c/d;p?q is http://a/b/c/g;x?y#s"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("../.."), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/"), "../.. resolved against http://a/b/c/d;p?q is http://a/"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("../../g"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/g"), "../../g resolved against http://a/b/c/d;p?q is http://a/g"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("../../../../g"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/g"), "../../../../g resolved against http://a/b/c/d;p?q is http://a/g"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("/./g"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/g"), "/./g resolved against http://a/b/c/d;p?q is http://a/g"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("/../g"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/g"), "/../g resolved against http://a/b/c/d;p?q is http://a/g"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("..g"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/b/c/..g"), "..g resolved against http://a/b/c/d;p?q is http://a/b/c/..g"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("./../g"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/b/g"), "./../g resolved against http://a/b/c/d;p?q is http://a/b/g"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("g;x=1/./y"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/b/c/g;x=1/y"), "g;x=1/./y resolved against http://a/b/c/d;p?q is http://a/b/c/g;x=1/y"); CFRelease(url3); CFRelease(url2); url2 = CFURLCreateWithString (NULL, CFSTR("g?y/../x"), url); url3 = CFURLCopyAbsoluteURL (url2); PASS_CFEQ(CFURLGetString(url3), CFSTR("http://a/b/c/g?y/../x"), "g?y/../x resolved against http://a/b/c/d;p?q is http://a/b/c/g?y/../x"); CFRelease(url3); CFRelease(url2); CFRelease(url); return 0; }gnustep-corebase-0.2/Tests/CFURL/TestInfo0000644000175000017500000000000013222706330017322 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFURL/create.m0000644000175000017500000000744613222706330017312 0ustar yavoryavor#include "CoreFoundation/CFURL.h" #include "../CFTesting.h" int main (void) { CFURLRef url; CFURLRef url2; CFStringRef str; url = CFURLCreateWithString (NULL, CFSTR("http://www.gnustep.org"), NULL); PASS_CF(url != NULL, "URL created."); url2 = CFURLCopyAbsoluteURL (url); PASS_CF(url == url2, "Absolute URL of an absolute URL are the same."); CFRelease (url); CFRelease (url2); url = CFURLCreateWithString (NULL, CFSTR("http://user:password@www.w3.org:5/silly-file-path/"), NULL); PASS_CF(CFURLCanBeDecomposed(url) == true, "http://user:password@www.w3.org:5/silly-file-path/ path can be decomposed"); str = CFURLCopyPath (url); PASS_CFEQ(str, CFSTR("/silly-file-path/"), "Path of " "http://user:password@www.w3.org:5/silly-file-path/ is /silly-file-path/"); CFRelease (str); str = CFURLCopyUserName (url); PASS_CFEQ(str, CFSTR("user"), "User name of " "http://user:password@www.w3.org:5/silly-file-path/ is user"); CFRelease (str); str = CFURLCopyPassword (url); PASS_CFEQ(str, CFSTR("password"), "Password of " "http://user:password@www.w3.org:5/silly-file-path/ is password"); CFRelease (str); str = CFURLCopyResourceSpecifier (url); PASS_CF(str == NULL, "resourceSpecifier of http://www.w3.org/silly-file-path/ is NULL"); url2 = CFURLCreateWithString (NULL, CFSTR("additional/string"), url); PASS_CF(CFURLCanBeDecomposed(url2) == true, "additional/string path can be decomposed since base URL is decomposable"); str = CFURLGetString (url2); PASS_CFEQ(str, CFSTR("additional/string"), "String is additional/string"); str = CFURLCopyPath (url2); PASS_CFEQ(str, CFSTR("additional/string"), "Copied path is not resolved against base."); CFRelease (str); str = CFURLCopyResourceSpecifier (url2); testHopeful = true; PASS_CF(str == NULL, "Resource specifier of relative url is NULL"); testHopeful = false; CFRelease (url); CFRelease (url2); url = CFURLCreateWithString (NULL, CFSTR("http://www.w3.org/silly-file-name?query#fragment"), NULL); PASS_CF(CFURLCanBeDecomposed(url) == true, "http://www.w3.org/silly-file-name?query#fragment path can be decomposed"); str = CFURLCopyScheme (url); PASS_CFEQ(str, CFSTR("http"), "Scheme of http://www.w3.org/silly-file-name is http"); CFRelease (str); str = CFURLCopyHostName (url); PASS_CFEQ(str, CFSTR("www.w3.org"), "Host of http://www.w3.org/silly-file-name is www.w3.org"); CFRelease (str); str = CFURLCopyStrictPath (url, NULL); PASS_CFEQ(str, CFSTR("silly-file-name"), "Strict path of http://www.w3.org/silly-file-name is silly-file-name"); CFRelease (str); str = CFURLCopyResourceSpecifier (url); PASS_CFEQ(str, CFSTR("?query#fragment"), "Resource specifier of http://www.w3.org/silly-file-name?query#fragment is" " ?query#fragment"); CFRelease(str); str = CFURLCopyQueryString (url, NULL); PASS_CFEQ(str, CFSTR("query"), "Query of " "http://www.w3.org/silly-file-name?query#fragment is query"); CFRelease (str); str = CFURLCopyFragment (url, NULL); PASS_CFEQ(str, CFSTR("fragment"), "Fragment of " "http://www.w3.org/silly-file-name?query#fragment is fragment"); CFRelease (str); CFRelease (url); url = CFURLCreateWithString (NULL, CFSTR("http://www.w3.org/silly;type=test"), NULL); str = CFURLCopyParameterString (url, NULL); PASS_CFEQ(str, CFSTR("type=test"), "Parameter string for " "http://www.w3.org/silly;type=test"); CFRelease(str); str = CFURLCopyResourceSpecifier (url); PASS_CFEQ(str, CFSTR(";type=test"), "Resource specifier of http://www.w3.org/silly;type=test is ;test=test."); CFRelease(str); CFRelease(url); url = CFURLCreateWithString (NULL, CFSTR("this isn't a URL"), NULL); PASS_CF(url == NULL, "URL with 'this isn't a URL' returns NULL"); return 0; } gnustep-corebase-0.2/Tests/CFTimeZone/0000755000175000017500000000000014661604110016747 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFTimeZone/basic.m0000644000175000017500000000150513222706330020206 0ustar yavoryavor#include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFTimeZone.h" #include "../CFTesting.h" int main (void) { CFTimeZoneRef tz; CFStringRef str; CFTimeInterval ti; CFAbsoluteTime at; tz = CFTimeZoneCreateWithTimeIntervalFromGMT (NULL, 0.0); PASS_CF(tz != NULL, "CFTimeZone create successfully."); PASS_CFEQ(CFTimeZoneGetName(tz), CFSTR("GMT+00:00"), "CFTimeZone has correct name."); str = CFTimeZoneCopyAbbreviation (tz, 0.0); PASS_CFEQ(str, CFSTR("GMT+00:00"), "Time zone abbreviations are equal."); ti = CFTimeZoneGetSecondsFromGMT (tz, 0.0); PASS_CF(ti == 0.0, "GMT+00:00 offset from GMT is %g", ti); at = CFTimeZoneGetNextDaylightSavingTimeTransition (tz, 0.0); PASS_CF(at == 0.0, "Next transition for GMT+00:00 is %g", at); CFRelease (str); CFRelease (tz); return 0; } gnustep-corebase-0.2/Tests/CFTimeZone/TestInfo0000644000175000017500000000000013222706330020412 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFTimeZone/general.m0000644000175000017500000000344613222706330020550 0ustar yavoryavor#include "CoreFoundation/CFBase.h" #include "CoreFoundation/CFLocale.h" #include "CoreFoundation/CFTimeZone.h" #include "../CFTesting.h" int main (void) { CFTimeZoneRef tz; CFStringRef str; CFLocaleRef loc; CFAbsoluteTime at; CFTimeInterval ti; tz = CFTimeZoneCreateWithName (NULL, CFSTR("CST"), false); PASS_CF(tz == NULL, "Time zone named 'CST' is not found if abbreviations are not searched."); tz = CFTimeZoneCreateWithName (NULL, CFSTR("CST"), true); PASS_CF(tz != NULL, "Time zone named 'CST' was found when abbreviations were searched"); str = CFTimeZoneGetName (tz); PASS_CFEQ(str, CFSTR("America/Chicago"), "Time zone name is 'US/Central'"); CFRelease (str); CFRelease (tz); tz = CFTimeZoneCreateWithName (NULL, CFSTR("Europe/Rome"), false); str = CFTimeZoneGetName (tz); PASS_CFEQ(str, CFSTR("Europe/Rome"), "'Europe/Rome' time zone created."); CFRelease (str); at = CFTimeZoneGetSecondsFromGMT (tz, 1000000.0); PASS_CF(at == 3600.0, "Offset from GMT at 1000000 seconds from absolute epoch is '%f'", at); PASS_CF(CFTimeZoneIsDaylightSavingTime (tz, 1000000.0) == false, "On daylight saving time at 1000000 seconds from absolute epoch."); loc = CFLocaleCreate (NULL, CFSTR("en_GB")); str = CFTimeZoneCopyLocalizedName (tz, kCFTimeZoneNameStyleShortStandard, loc); PASS_CFEQ(str, CFSTR("CET"), "Short standard localized name is correct."); CFRelease (str); CFRelease (loc); ti = CFTimeZoneGetDaylightSavingTimeOffset (tz, 0.0); PASS_CF(ti == 0.0, "Daylight Saving time offset at 0 second from absolute epoch is '%f'.", ti); at = CFTimeZoneGetNextDaylightSavingTimeTransition (tz, 1000000.0); PASS_CF(at == 7174800.0, "Next daylight saving transition is at '%f'.", at); CFRelease (tz); return 0; } gnustep-corebase-0.2/Tests/CFTimeZone/bridge.m0000644000175000017500000000346613222706330020371 0ustar yavoryavor#import #include "CoreFoundation/CFTimeZone.h" #include "../CFTesting.h" void testNSonCF(void); void testCFonNS(void); int main(void) { testNSonCF(); testCFonNS(); return 0; } void testNSonCF(void) { CFTimeZoneRef cftz = CFTimeZoneCopySystem(); NSTimeZone* nstz = (NSTimeZone*) cftz; CFStringRef abbrev; PASS_CFEQ(CFTimeZoneGetName(cftz), [nstz name], "-name works on a CFTimeZone"); PASS_CF(CFTimeZoneGetSecondsFromGMT(cftz, CFAbsoluteTimeGetCurrent()) == [nstz secondsFromGMT], "-secondsFromGMT works on a CFTimeZone"); // TODO: this test is not "stable" enough PASS_CF(CFTimeZoneIsDaylightSavingTime(cftz, CFAbsoluteTimeGetCurrent()) == [nstz isDaylightSavingTime], "-isDaylightSavingTime works on a CFTimeZone"); abbrev = CFTimeZoneCopyAbbreviation(cftz, CFAbsoluteTimeGetCurrent()); PASS_CFEQ(abbrev, [nstz abbreviation], "-abbreviation works on a CFTimeZone"); CFRelease(abbrev); // TODO: test other functions [nstz release]; } void testCFonNS(void) { NSTimeZone* nstz = [NSTimeZone systemTimeZone]; CFTimeZoneRef cftz = (CFTimeZoneRef) nstz; CFStringRef abbrev; PASS_CFEQ([nstz name], CFTimeZoneGetName(cftz), "CFTimeZoneGetName() works on an NSTimeZone"); PASS_CF(CFTimeZoneGetSecondsFromGMT(cftz, CFAbsoluteTimeGetCurrent()) == [nstz secondsFromGMT], "CFTimeZoneGetSecondsFromGMT works on an NSTimeZone"); // TODO: this test is not "stable" enough PASS_CF(CFTimeZoneIsDaylightSavingTime(cftz, CFAbsoluteTimeGetCurrent()) == [nstz isDaylightSavingTime], "CFTimeZoneIsDaylightSavingTime() works on an NSTimeZone"); abbrev = CFTimeZoneCopyAbbreviation(cftz, CFAbsoluteTimeGetCurrent()); PASS_CFEQ([nstz abbreviation], abbrev, "CFTimeZoneCopyAbbreviation() works on an NSTimeZone"); CFRelease(abbrev); } gnustep-corebase-0.2/Tests/CFDate/0000755000175000017500000000000014661604107016100 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFDate/basic.m0000644000175000017500000000107013222706330017326 0ustar yavoryavor#include "CoreFoundation/CFDate.h" #include "../CFTesting.h" int main (void) { CFDateRef date; CFDateRef date2; date = CFDateCreate (NULL, 128.0); PASS_CF(CFDateGetAbsoluteTime(date) == 128.0, "Date created correctly."); date2 = CFDateCreate (NULL, 127.0); PASS_CF(CFDateCompare(date, date2, NULL) == kCFCompareGreaterThan, "First date is greater than second date."); PASS_CF(CFDateGetTimeIntervalSinceDate(date, date2) == 1.0, "First date is one second ahead of second date."); CFRelease (date); CFRelease (date2); return 0; }gnustep-corebase-0.2/Tests/CFDate/TestInfo0000644000175000017500000000000013222706330017535 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFAttributedString/0000755000175000017500000000000014661604107020521 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFAttributedString/mutable.m0000644000175000017500000000555513222706330022333 0ustar yavoryavor#include "CoreFoundation/CFAttributedString.h" #include "../CFTesting.h" int main (void) { const void *keys[3]; const void *values[3]; CFDictionaryRef attrib1; CFDictionaryRef attrib2; CFDictionaryRef attrib3; CFDictionaryRef curAttrib; CFAttributedStringRef str; CFMutableAttributedStringRef mstr; CFRange r; keys[0] = CFSTR("Attrib 1"); values[0] = CFSTR("Attribute"); attrib1 = CFDictionaryCreate (NULL, keys, values, 1, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); str = CFAttributedStringCreate (NULL, CFSTR("This is a string!"), (CFDictionaryRef)attrib1); mstr = CFAttributedStringCreateMutableCopy (NULL, 0, str); PASS_CF(mstr != NULL, "Mutable attributed string was created."); curAttrib = CFAttributedStringGetAttributes (str, 10, &r); PASS_CF(r.location == 0 && r.length == 17, "Attribute range is (%d, %d).", (int)r.location, (int)r.length); PASS_CFEQ (curAttrib, attrib1, "First set of attributes are the same."); /* This will be like a wedge between the previous attribute */ keys[1] = CFSTR("Attrib 2"); values[1] = CFSTR("Another Attribute"); attrib2 = CFDictionaryCreateMutable (NULL, 2, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryAddValue (attrib2, keys[1], values[1]); CFAttributedStringSetAttributes (mstr, CFRangeMake (5, 10), attrib2, false); CFDictionaryAddValue (attrib2, keys[0], values[0]); curAttrib = CFAttributedStringGetAttributes (mstr, 10, &r); PASS_CF(r.location == 5 && r.length == 10, "Attribute range is (%d, %d).", (int)r.location, (int)r.length); PASS_CFEQ (curAttrib, attrib2, "Second set of attributes are the same."); curAttrib = CFAttributedStringGetAttributes (mstr, 16, &r); PASS_CF(r.location == 15 && r.length == 2, "Attribute range is (%d, %d).", (int)r.location, (int)r.length); PASS_CFEQ (curAttrib, attrib1, "Previous attributes are adjusted."); /* This will insert a new attribute and delete the last one */ keys[0] = CFSTR("Attrib 3"); values[0] = CFSTR("attribute #3"); attrib3 = CFDictionaryCreate (NULL, keys, values, 1, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFAttributedStringSetAttributes (mstr, CFRangeMake (10, 7), attrib3, true); curAttrib = CFAttributedStringGetAttributes (mstr, 11, &r); PASS_CF(r.location == 10 && r.length == 7, "Attribute range is (%d, %d).", (int)r.location, (int)r.length); PASS_CFEQ (curAttrib, attrib3, "Third set of attributes are the same."); CFRelease (attrib1); CFRelease (attrib2); CFRelease (attrib3); CFRelease (mstr); CFRelease (str); return 0; } gnustep-corebase-0.2/Tests/CFAttributedString/TestInfo0000644000175000017500000000000013222706330022156 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFAttributedString/general.m0000644000175000017500000000310713222706330022306 0ustar yavoryavor#include "CoreFoundation/CFAttributedString.h" #include "../CFTesting.h" int main (void) { CFAttributedStringRef str; CFAttributedStringRef str2; CFMutableDictionaryRef attribs; CFDictionaryRef attrOut; CFRange r; attribs = CFDictionaryCreateMutable (NULL, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryAddValue (attribs, CFSTR("Attrib 1"), CFSTR("Attribute")); CFDictionaryAddValue (attribs, CFSTR("Attrib 2"), CFSTR("Attribute2")); str = CFAttributedStringCreate (NULL, CFSTR("This is a string!"), (CFDictionaryRef)attribs); PASS_CF(str != NULL && CFEqual(CFAttributedStringGetString(str), CFSTR("This is a string!")) && CFAttributedStringGetLength(str) == 17, "Attributed string was correctly created."); attrOut = CFAttributedStringGetAttributes (str, 2, &r); PASS_CF(r.location == 0 && r.length == 17, "Attribute range is (%d, %d).", (int)r.location, (int)r.length); PASS_CFEQ (attrOut, attribs, "Attributes are the same."); str2 = CFAttributedStringCreateCopy (NULL, str); PASS_CFEQ (str, str2, "Copied attributed string is equal."); attrOut = CFAttributedStringGetAttributes (str, 10, &r); PASS_CF(r.location == 0 && r.length == 17, "Copied attribute range is (%d, %d).", (int)r.location, (int)r.length); PASS_CFEQ (attrOut, attribs, "Copied attributes are the same."); CFRelease (attribs); CFRelease (str); //CFRelease (str2); return 0; } gnustep-corebase-0.2/Tests/CFNumberFormatter/0000755000175000017500000000000014661604117020340 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFNumberFormatter/parse.m0000644000175000017500000000371113222706330021622 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "CoreFoundation/CFLocale.h" #include "CoreFoundation/CFNumber.h" #include "CoreFoundation/CFNumberFormatter.h" #include "../CFTesting.h" int main (void) { CFLocaleRef loc; CFStringRef str; CFNumberFormatterRef nf; SInt8 int_8; SInt16 int_16; SInt32 int_32; SInt64 int_64; double d; CFRange range; loc = CFLocaleCreate (NULL, CFSTR("en_US")); nf = CFNumberFormatterCreate (NULL, loc, kCFNumberFormatterNoStyle); str = CFSTR("16"); PASS_CF(CFNumberFormatterGetValueFromString (nf, str, NULL, kCFNumberSInt8Type, &int_8) == true, "Got SInt8 value"); PASS_CF(int_8 == 16, "SInt8 value is '%d'", (int)int_8); str = CFSTR("300.0"); PASS_CF(CFNumberFormatterGetValueFromString (nf, str, NULL, kCFNumberSInt16Type, &int_16) == true, "Got SInt16 value"); PASS_CF(int_16 == 300, "SInt16 value is '%d'", (int)int_16); CFRelease(nf); nf = CFNumberFormatterCreate (NULL, loc, kCFNumberFormatterCurrencyStyle); str = CFSTR("$68456.50"); PASS_CF(CFNumberFormatterGetValueFromString (nf, str, NULL, kCFNumberSInt32Type, &int_32) == true, "Got SInt32 value"); PASS_CF(int_32 == 68456, "SInt32 value is '%d'", (int)int_32); CFRelease (nf); nf = CFNumberFormatterCreate (NULL, loc, kCFNumberFormatterScientificStyle); str = CFSTR("3.15E+8"); PASS_CF(CFNumberFormatterGetValueFromString (nf, str, NULL, kCFNumberSInt64Type, &int_64) == true, "Got SInt64 value"); PASS_CF(int_64 == 315000000, "SInt64 value is '%lld'", (long long)int_64); CFRelease (nf); nf = CFNumberFormatterCreate (NULL, loc, kCFNumberFormatterPercentStyle); str = CFSTR("123.4%"); range = CFRangeMake (1, 5); PASS_CF(CFNumberFormatterGetValueFromString (nf, str, &range, kCFNumberDoubleType, &d) == true, "Got double value"); PASS_CF(d == 0.234, "Double value is '%g'", d); PASS_CF((range.location == 1 && range.length == 5) , "Parsed complete length"); CFRelease (nf); return 0; } gnustep-corebase-0.2/Tests/CFNumberFormatter/format.m0000664000175000017500000000377414661604117022023 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "CoreFoundation/CFLocale.h" #include "CoreFoundation/CFNumber.h" #include "CoreFoundation/CFNumberFormatter.h" #include "../CFTesting.h" int main (void) { CFNumberRef num; CFLocaleRef loc; CFStringRef str; CFNumberFormatterRef nf; SInt8 int_8; SInt16 int_16; SInt32 int_32; SInt64 int_64; double d; loc = CFLocaleCreate (NULL, CFSTR("en_US")); nf = CFNumberFormatterCreate (NULL, loc, kCFNumberFormatterNoStyle); int_8 = 16; str = CFNumberFormatterCreateStringWithValue (NULL, nf, kCFNumberSInt8Type, &int_8); PASS_CFEQ(str, CFSTR("16"), "SInt8 formatted correctly"); CFRelease (str); num = CFNumberCreate (NULL, kCFNumberSInt8Type, &int_8); CFNumberFormatterSetProperty (nf, kCFNumberFormatterFormatWidth, num); str = CFNumberFormatterCreateStringWithValue (NULL, nf, kCFNumberSInt8Type, &int_8); PASS_CFEQ(str, CFSTR("**************16"), "SInt8 formatted correctly"); CFRelease(nf); nf = CFNumberFormatterCreate (NULL, loc, kCFNumberFormatterCurrencyStyle); int_16 = 300; PASS_CFEQ(CFNumberFormatterCreateStringWithValue (NULL, nf, kCFNumberSInt16Type, &int_16), CFSTR("$300.00"), "SInt16 formatted correctly"); CFRelease(nf); nf = CFNumberFormatterCreate (NULL, loc, kCFNumberFormatterScientificStyle); int_32 = 68456; PASS_CFEQ(CFNumberFormatterCreateStringWithValue (NULL, nf, kCFNumberSInt32Type, &int_32), CFSTR("6.8456E4"), "SInt32 formatted correctly"); CFRelease(nf); nf = CFNumberFormatterCreate (NULL, loc, kCFNumberFormatterDecimalStyle); int_64 = 315000000; PASS_CFEQ(CFNumberFormatterCreateStringWithValue (NULL, nf, kCFNumberSInt64Type, &int_64), CFSTR("315,000,000"), "SInt64 formatted correctly"); CFRelease(nf); nf = CFNumberFormatterCreate (NULL, loc, kCFNumberFormatterPercentStyle); d = 1.234; PASS_CFEQ(CFNumberFormatterCreateStringWithValue (NULL, nf, kCFNumberDoubleType, &d), CFSTR("123%"), "Double formatted correctly"); return 0; } gnustep-corebase-0.2/Tests/CFNumberFormatter/TestInfo0000644000175000017500000000000013222706330021774 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFNumberFormatter/create.m0000644000175000017500000000377713222706330021767 0ustar yavoryavor#include "CoreFoundation/CFString.h" #include "CoreFoundation/CFLocale.h" #include "CoreFoundation/CFNumberFormatter.h" #include "../CFTesting.h" int main (void) { CFNumberFormatterRef fmt; CFLocaleRef locale; CFStringRef str; CFStringRef exp; locale = CFLocaleCreate (NULL, CFSTR("en_GB")); fmt = CFNumberFormatterCreate (NULL, locale, kCFNumberFormatterNoStyle); PASS_CF(fmt != NULL, "CFNumberFormatterCreate() return non-nil"); str = CFNumberFormatterCopyProperty (fmt, kCFNumberFormatterDefaultFormat); PASS_CFEQ(str, CFSTR("#"), "Default no-style format same as cocoa"); CFRelease (fmt); fmt = CFNumberFormatterCreate (NULL, locale, kCFNumberFormatterDecimalStyle); str = CFNumberFormatterCopyProperty (fmt, kCFNumberFormatterDefaultFormat); PASS_CFEQ(str, CFSTR("#,##0.###"), "Default decimal-style format same as cocoa"); CFRelease (fmt); fmt = CFNumberFormatterCreate (NULL, locale, kCFNumberFormatterCurrencyStyle); str = CFNumberFormatterCopyProperty (fmt, kCFNumberFormatterDefaultFormat); exp = CFStringCreateWithCString (NULL, "¤#,##0.00", kCFStringEncodingUTF8); PASS_CFEQ(str, exp, "Default currency-style format same as cocoa"); CFRelease (exp); CFRelease (fmt); fmt = CFNumberFormatterCreate (NULL, locale, kCFNumberFormatterPercentStyle); str = CFNumberFormatterCopyProperty (fmt, kCFNumberFormatterDefaultFormat); PASS_CFEQ(str, CFSTR("#,##0%"), "Default percent-style format same as cocoa"); CFRelease (fmt); fmt = CFNumberFormatterCreate (NULL, locale, kCFNumberFormatterScientificStyle); str = CFNumberFormatterCopyProperty (fmt, kCFNumberFormatterDefaultFormat); PASS_CFEQ(str, CFSTR("#E0"), "Default scientific-style format same as cocoa"); CFRelease (fmt); fmt = CFNumberFormatterCreate (NULL, NULL, kCFNumberFormatterSpellOutStyle); PASS_CF(fmt != NULL, "CFNumberFormatterCreate() return non-nil for system locale"); CFRelease ((CFTypeRef)locale); CFRelease (fmt); return 0; } gnustep-corebase-0.2/Tests/CFTree/0000755000175000017500000000000014661604110016114 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFTree/basic.m0000644000175000017500000000207413222706330017355 0ustar yavoryavor#include "CoreFoundation/CFTree.h" #include "../CFTesting.h" int main (void) { CFTreeRef tree; CFTreeRef child1; CFTreeRef child2; CFTreeRef child3; CFTreeContext ctxt; ctxt.version = 0; ctxt.info = NULL; ctxt.retain = NULL; ctxt.release = NULL; ctxt.copyDescription = NULL; tree = CFTreeCreate (NULL, &ctxt); child1 = CFTreeCreate (NULL, &ctxt); child2 = CFTreeCreate (NULL, &ctxt); child3 = CFTreeCreate (NULL, &ctxt); CFTreeAppendChild (tree, child2); CFTreePrependChild (tree, child1); CFTreeInsertSibling (child2, child3); PASS_CF(CFTreeGetChildCount (tree) == 3, "Tree has three children."); PASS_CF(CFTreeGetParent (child3) == tree, "Parent is the original tree object."); PASS_CF(CFTreeGetFirstChild (tree) == child1, "First child is child1."); PASS_CF(CFTreeGetNextSibling (child1) == child2, "Next sibling for child1 is child2."); PASS_CF(CFTreeGetChildAtIndex (tree, 2) == child3, "Child3 is at index 2"); CFRelease (child1); CFRelease (child2); CFRelease (child3); CFRelease (tree); return 0; } gnustep-corebase-0.2/Tests/CFTree/TestInfo0000644000175000017500000000000013222706330017557 0ustar yavoryavorgnustep-corebase-0.2/Tests/GNUmakefile.super0000664000175000017500000000014714661604117020226 0ustar yavoryavor # Link tests with corebase library ADDITIONAL_OBJC_LIBS += -lgnustep-corebase ADDITIONAL_OBJCFLAGS = gnustep-corebase-0.2/Tests/CFStream/0000755000175000017500000000000014661604110016450 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFStream/write.m0000644000175000017500000000341513222706330017762 0ustar yavoryavor#include "CoreFoundation/CFStream.h" #include "CoreFoundation/CFData.h" #include "../CFTesting.h" #include void BufferTest1(); void BufferTest2(); int main (void) { BufferTest1(); return 0; } void BufferTest1() { CFWriteStreamRef stream; CFDataRef data; const char* test1 = "Hello WorldHelloWorld!!!"; const char* test2 = "Abcdefghijklmn"; stream = CFWriteStreamCreateWithAllocatedBuffers(NULL, NULL); PASS_CF(CFWriteStreamOpen(stream), "CFWriteStreamOpen() succeeds"); PASS_CF(strlen(test1) == CFWriteStreamWrite(stream, test1, strlen(test1)), "CFWriteStreamWrite() writes into buffer"); PASS_CF(strlen(test2) == CFWriteStreamWrite(stream, test2, strlen(test2)), "CFWriteStreamWrite() writes into buffer"); data = CFWriteStreamCopyProperty(stream, kCFStreamPropertyDataWritten); PASS_CF(data != NULL, "CFWriteStreamCopyProperty returns written data"); PASS_CF(strlen(test1)+strlen(test2) == CFDataGetLength(data), "Written data have correct length"); PASS_CF(memcmp(test1, CFDataGetBytePtr(data), strlen(test1)) == 0, "Written data contain correct data"); PASS_CF(memcmp(test2, CFDataGetBytePtr(data) + strlen(test1), strlen(test2)) == 0, "Written data contain correct data"); CFRelease(data); CFRelease(stream); } void BufferTest2() { CFWriteStreamRef stream; UInt8 mybuffer[10]; const char* test1 = "Hello WorldHelloWorld!!!"; stream = CFWriteStreamCreateWithBuffer(NULL, mybuffer, sizeof(mybuffer)); PASS_CF(CFWriteStreamOpen(stream), "CFWriteStreamOpen() succeeds"); PASS_CF(sizeof(mybuffer) == CFWriteStreamWrite(stream, test1, strlen(test1)), "CFWriteStreamWrite() writes into buffer"); PASS_CF(memcmp(test1, mybuffer, sizeof(mybuffer)) == 0, "Written data contain correct data"); CFRelease(stream); } gnustep-corebase-0.2/Tests/CFStream/read.m0000644000175000017500000000163313222706330017543 0ustar yavoryavor#include "CoreFoundation/CFStream.h" #include "../CFTesting.h" #include void BufferTest1(); int main (void) { BufferTest1(); return 0; } void BufferTest1() { CFReadStreamRef stream; const char* data = "lknvidufvbdfuvdvjbfdjkvbfdb jkd eaduyebiub"; UInt8 buf[10]; UInt8 buf2[50]; CFIndex rd; stream = CFReadStreamCreateWithBytesNoCopy(NULL, data, strlen(data), kCFAllocatorNull); PASS_CF(CFReadStreamOpen(stream), "CFReadStreamOpen() succeeds"); PASS_CF(sizeof(buf) == CFReadStreamRead(stream, buf, sizeof(buf)), "CFReadStreamRead() reads data"); PASS_CF(memcmp(buf, data, sizeof(buf)) == 0, "CFReadStreamRead() reads correct data"); rd = CFReadStreamRead(stream, buf2, sizeof(buf2)); PASS_CF(strlen(data) - sizeof(buf) == rd, "CFReadStreamRead() reads data"); PASS_CF(memcmp(buf2, data+sizeof(buf), rd) == 0, "CFReadStreamRead() reads correct data"); CFRelease(stream); } gnustep-corebase-0.2/Tests/CFStream/TestInfo0000644000175000017500000000000013222706330020113 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFData/0000755000175000017500000000000014661604107016074 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFData/basic.m0000644000175000017500000000120713222706330017324 0ustar yavoryavor#include "CoreFoundation/CFData.h" #include "../CFTesting.h" const UInt8 bytes[] = { 0xDE, 0xAD, 0xBA, 0xBA }; int main (void) { CFDataRef data; CFDataRef data2; CFIndex length; UInt8 *copy; data = CFDataCreate (NULL, bytes, sizeof(bytes)); PASS_CF(data != NULL, "Data created."); length = CFDataGetLength (data); copy = CFAllocatorAllocate (NULL, length, 0); CFDataGetBytes (data, CFRangeMake(0, length), copy); data2 = CFDataCreateWithBytesNoCopy (NULL, copy, length, kCFAllocatorDefault); PASS_CFEQ(data, data2, "Copy of data is equal to original."); CFRelease (data); CFRelease (data2); return 0; }gnustep-corebase-0.2/Tests/CFData/TestInfo0000644000175000017500000000000013222706330017531 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFCharacterSet/0000755000175000017500000000000014661604107017573 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFCharacterSet/mutable.m0000644000175000017500000000110313222706330021366 0ustar yavoryavor#include "CoreFoundation/CFCharacterSet.h" #include "../CFTesting.h" int main (void) { CFMutableCharacterSetRef charset; charset = CFCharacterSetCreateMutable (NULL); CFCharacterSetAddCharactersInRange (charset, CFRangeMake(0x20, 0x7F)); PASS_CF(CFCharacterSetIsCharacterMember(charset, 'a'), "Letter 'a' is part of mutable character set."); CFCharacterSetRemoveCharactersInString (charset, CFSTR("a")); PASS_CF(CFCharacterSetIsCharacterMember(charset, 'a') == false, "Letter 'a' was successfully removed from mutable character set."); return 0; }gnustep-corebase-0.2/Tests/CFCharacterSet/basic.m0000644000175000017500000000271513222706330021030 0ustar yavoryavor#include "CoreFoundation/CFCharacterSet.h" #include "../CFTesting.h" int main (void) { CFCharacterSetRef charset; CFCharacterSetRef charset2; charset = CFCharacterSetCreateWithCharactersInRange (NULL, CFRangeMake(0x20, 0x7F)); PASS_CF(CFCharacterSetIsCharacterMember(charset, 'a'), "Letter 'a' is part of character set."); charset2 = CFCharacterSetCreateWithCharactersInString (NULL, CFSTR("abcABC")); PASS_CF(CFCharacterSetIsSupersetOfSet(charset, charset2), "Character set with all ASCII characters is a superset of a charcter set" "including 'abcABC'."); PASS_CF(CFCharacterSetIsSupersetOfSet(charset2, charset) == false, "Characters set with 'abcABC' is not a superset of a character set" "including all ASCII characters"); CFRelease (charset2); charset2 = CFCharacterSetCreateInvertedSet (NULL, charset); PASS_CF(CFCharacterSetIsCharacterMember(charset2, 'a') == false, "Inverted character set does not include letter 'a'."); PASS_CF(CFCharacterSetIsCharacterMember(charset2, 0x00DD), "Inverted character set includes character 0x00DD."); CFRelease (charset); charset = CFCharacterSetGetPredefined (kCFCharacterSetWhitespace); PASS_CF(CFCharacterSetIsCharacterMember(charset, ' ') == true, "Whitespace character set includes ' '."); PASS_CF(CFCharacterSetIsCharacterMember(charset, '5') == false, "Whitespace character set does not includes '5'."); CFRelease (charset); return 0; }gnustep-corebase-0.2/Tests/CFCharacterSet/TestInfo0000644000175000017500000000000013222706330021230 0ustar yavoryavorgnustep-corebase-0.2/Tests/CFPropertyList/0000755000175000017500000000000014661604117017704 5ustar yavoryavorgnustep-corebase-0.2/Tests/CFPropertyList/openstep.m0000664000175000017500000000417714661604117021732 0ustar yavoryavor#include "../CFTesting.h" #include "CoreFoundation/CFPropertyList.h" #include "CoreFoundation/CFDictionary.h" const UInt8 data[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; const UInt8 proplist[] = "\357\273\277{\n" "\tstring = \"Quotable String.\";\n" "\tdata = <0102030405060708090A0B0C0D0E0F>;\n" "\tarray = (\n" "\t\t<0102030405060708090A0B0C0D0E0F>,\n" "\t\t\"Quotable String.\"\n" "\t);\n" "}\n"; int main (void) { CFPropertyListRef plist; CFPropertyListRef readPlist; CFDataRef plData; CFErrorRef err; CFPropertyListFormat fmt; CFIndex count; const void *keys[3]; const void *values[3]; keys[0] = CFSTR ("data"); keys[1] = CFSTR ("string"); keys[2] = CFSTR ("array"); values[0] = CFDataCreate (NULL, data, 15); values[1] = CFSTR ("Quotable String."); values[2] = CFArrayCreate (NULL, values, 2, &kCFTypeArrayCallBacks); plist = CFDictionaryCreate (NULL, keys, values, 3, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); #if GNUSTEP plData = CFPropertyListCreateData (NULL, plist, kCFPropertyListOpenStepFormat, 0, NULL); PASS_CF (memcmp (CFDataGetBytePtr (plData), proplist, CFDataGetLength (plData)) == 0, "OpenStep property list written correctly."); #endif plData = CFDataCreate (NULL, proplist, sizeof (proplist) -1); fmt = 0; err = NULL; readPlist = CFPropertyListCreateWithData (NULL, plData, kCFPropertyListImmutable, &fmt, &err); PASS_CF (err == NULL, "No errors encountered parsing valid property list."); count = CFDictionaryGetCount (readPlist); PASS_CF (count == 3, "Correct number of objects parsed into OpenStep property list."); PASS_CF (CFPropertyListIsValid (readPlist, kCFPropertyListOpenStepFormat), "Valid OpenStep property list returned."); PASS_CFEQ (readPlist, plist, "OpenStep property list read correctly."); CFRelease (plData); CFRelease (readPlist); CFRelease (plist); return 0; } gnustep-corebase-0.2/Tests/CFPropertyList/validate.m0000644000175000017500000000503513222706330021646 0ustar yavoryavor#include #include #include #include #include #include #include "../CFTesting.h" const UInt8 rawdata[] = { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 }; const SInt32 i32 = 10; int main (void) { CFMutableDictionaryRef dict; CFMutableArrayRef array; CFNumberRef num; CFDateRef date; CFDataRef data; date = CFDateCreate (NULL, 1.0); data = CFDataCreate (NULL, rawdata, sizeof(rawdata)); num = CFNumberCreate (NULL, kCFNumberSInt32Type, &i32); dict = CFDictionaryCreateMutable (NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryAddValue (dict, date, data); CFDictionaryAddValue (dict, num, date); PASS_CF(CFPropertyListIsValid (dict, kCFPropertyListXMLFormat_v1_0) == false, "Dictionary with non-CFString keys is not a valid property list."); CFDictionaryRemoveValue (dict, date); CFDictionaryRemoveValue (dict, num); CFDictionaryAddValue (dict, CFSTR("data"), data); CFDictionaryAddValue (dict, CFSTR("date"), date); CFDictionaryAddValue (dict, CFSTR("number"), num); PASS_CF(CFPropertyListIsValid (dict, kCFPropertyListXMLFormat_v1_0), "Dictionary with CFString keys is a valid property list."); PASS_CF(CFPropertyListIsValid (dict, kCFPropertyListOpenStepFormat) == false, "Dictionary with CFDate and CFNumber values is not a valid OpenStep" " property list."); CFDictionaryRemoveValue (dict, CFSTR("date")); CFDictionaryRemoveValue (dict, CFSTR("number")); PASS_CF(CFPropertyListIsValid (dict, kCFPropertyListOpenStepFormat), "Dictionary with CFData only is a valid OpenStep property list."); array = CFArrayCreateMutable (NULL, 0, &kCFTypeArrayCallBacks); CFArrayAppendValue (array, (const void*)date); CFArrayAppendValue (array, (const void*)data); CFArrayAppendValue (array, (const void*)num); CFArrayAppendValue (array, (const void*)dict); PASS_CF(CFPropertyListIsValid (array, kCFPropertyListXMLFormat_v1_0), "Array with CFType objects is a valid XML property list."); CFDictionaryAddValue (dict, CFSTR("array"), array); PASS_CF(CFPropertyListIsValid (dict, kCFPropertyListXMLFormat_v1_0) == false, "Property list with recursion is not a valid property list."); CFRelease (dict); CFRelease (array); CFRelease (data); CFRelease (date); CFRelease (num); return 0; } gnustep-corebase-0.2/Tests/CFPropertyList/TestInfo0000644000175000017500000000000013222706330021340 0ustar yavoryavorgnustep-corebase-0.2/INSTALL0000644000175000017500000000425113222706330014734 0ustar yavoryavor1 Introduction ================ If you are installing this package as part of the GNUstep core packages, read the file GNUstep-HOWTO for more complete instructions on how to install the entire GNUstep package (including this library). GNUstep-HOWTO is located in the gnustep-make package or at `http://www.gnustep.org' This version of gnustep-base requires: * gnustep-make version 2.0.0 or higher * gnustep-base * ICU version 4.0 or higher If you are installing the GNUstep libraries individually, make sure you already have the GNUstep Makefile package (gnustep-make) installed, and you have sourced the makefile script: . $GNUSTEP_SYSTEM_ROOT/Library/Makefiles/GNUstep.sh Quick installation instructions: ./configure make make install 2 Configuration ================= Configuration is performed by running the `configure' program at a shell prompt. You may want to use some of the optional arguments to the `configure' program. Type `configure --help' for a list of these. It is not likely that you will need to use the `--prefix' option, since gnustep-corebase will automatically install in the directory specified by the `GNUSTEP_SYSTEM_LIBRARY' environment variable (specified when you installed gnustep-make). 2.1 ICU Library ----------------- GNUstep's corebase library requires the International Components for Unicode (www.icu-project.org) library. ICU provides GNUstep-corebase the ability to, among other things: * Convert to and/or from Unicode * Locale specific string comparison * Locale specific number and date formatting * Time calculations 3 Compilation =============== To compile this library, type 'make'. After this is complete, type 'make install' (you must be the root user). Some additional options you can use with make are `debug=yes' to make a debugging version of the library and `shared=no' to make a static version of the library. See the gnustep-make package for more information on these options. Copyright (C) 2012 Free Software Foundation Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. gnustep-corebase-0.2/Doxyfile0000644000175000017500000002532113222706330015412 0ustar yavoryavor# Doxyfile 1.8.1.2 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" "). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- DOXYFILE_ENCODING = UTF-8 PROJECT_NAME = "GNUstep CoreBase Library" PROJECT_NUMBER = 0.2 PROJECT_BRIEF = PROJECT_LOGO = OUTPUT_DIRECTORY = Documentation CREATE_SUBDIRS = NO OUTPUT_LANGUAGE = English BRIEF_MEMBER_DESC = YES REPEAT_BRIEF = NO ABBREVIATE_BRIEF = ALWAYS_DETAILED_SEC = NO INLINE_INHERITED_MEMB = NO FULL_PATH_NAMES = YES STRIP_FROM_PATH = STRIP_FROM_INC_PATH = SHORT_NAMES = NO JAVADOC_AUTOBRIEF = NO QT_AUTOBRIEF = NO MULTILINE_CPP_IS_BRIEF = NO INHERIT_DOCS = YES SEPARATE_MEMBER_PAGES = NO TAB_SIZE = 8 ALIASES = "shcmd{1}=\1" TCL_SUBST = OPTIMIZE_OUTPUT_FOR_C = YES OPTIMIZE_OUTPUT_JAVA = NO OPTIMIZE_FOR_FORTRAN = NO OPTIMIZE_OUTPUT_VHDL = NO EXTENSION_MAPPING = MARKDOWN_SUPPORT = YES BUILTIN_STL_SUPPORT = NO CPP_CLI_SUPPORT = NO SIP_SUPPORT = NO IDL_PROPERTY_SUPPORT = YES DISTRIBUTE_GROUP_DOC = NO SUBGROUPING = YES INLINE_GROUPED_CLASSES = NO INLINE_SIMPLE_STRUCTS = YES TYPEDEF_HIDES_STRUCT = YES SYMBOL_CACHE_SIZE = 0 LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- EXTRACT_ALL = NO EXTRACT_PRIVATE = NO EXTRACT_PACKAGE = NO EXTRACT_STATIC = NO EXTRACT_LOCAL_CLASSES = YES EXTRACT_LOCAL_METHODS = NO EXTRACT_ANON_NSPACES = NO HIDE_UNDOC_MEMBERS = NO HIDE_UNDOC_CLASSES = NO HIDE_FRIEND_COMPOUNDS = NO HIDE_IN_BODY_DOCS = NO INTERNAL_DOCS = NO CASE_SENSE_NAMES = YES HIDE_SCOPE_NAMES = NO SHOW_INCLUDE_FILES = YES FORCE_LOCAL_INCLUDES = NO INLINE_INFO = YES SORT_MEMBER_DOCS = NO SORT_BRIEF_DOCS = NO SORT_MEMBERS_CTORS_1ST = NO SORT_GROUP_NAMES = YES SORT_BY_SCOPE_NAME = NO STRICT_PROTO_MATCHING = NO GENERATE_TODOLIST = YES GENERATE_TESTLIST = YES GENERATE_BUGLIST = YES GENERATE_DEPRECATEDLIST= YES ENABLED_SECTIONS = MAX_INITIALIZER_LINES = 30 SHOW_USED_FILES = YES SHOW_FILES = NO SHOW_NAMESPACES = YES FILE_VERSION_FILTER = LAYOUT_FILE = Documentation/DoxygenLayout.xml CITE_BIB_FILES = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- QUIET = YES WARNINGS = YES WARN_IF_UNDOCUMENTED = NO WARN_IF_DOC_ERROR = YES WARN_NO_PARAMDOC = NO WARN_FORMAT = "$file:$line: $text" WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- INPUT = Headers/ \ Documentation/ INPUT_ENCODING = UTF-8 FILE_PATTERNS = *.h \ *.dox RECURSIVE = YES EXCLUDE = EXCLUDE_SYMLINKS = NO EXCLUDE_PATTERNS = .svn EXCLUDE_SYMBOLS = EXAMPLE_PATH = Examples/ EXAMPLE_PATTERNS = EXAMPLE_RECURSIVE = NO IMAGE_PATH = INPUT_FILTER = FILTER_PATTERNS = FILTER_SOURCE_FILES = NO FILTER_SOURCE_PATTERNS = #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- SOURCE_BROWSER = NO INLINE_SOURCES = NO STRIP_CODE_COMMENTS = YES REFERENCED_BY_RELATION = NO REFERENCES_RELATION = NO REFERENCES_LINK_SOURCE = YES USE_HTAGS = NO VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- ALPHABETICAL_INDEX = NO COLS_IN_ALPHA_INDEX = 5 IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- GENERATE_HTML = YES HTML_OUTPUT = html HTML_FILE_EXTENSION = .html HTML_HEADER = HTML_FOOTER = HTML_STYLESHEET = HTML_EXTRA_FILES = HTML_COLORSTYLE_HUE = 220 HTML_COLORSTYLE_SAT = 100 HTML_COLORSTYLE_GAMMA = 80 HTML_TIMESTAMP = YES HTML_DYNAMIC_SECTIONS = YES HTML_INDEX_NUM_ENTRIES = 100 GENERATE_DOCSET = NO DOCSET_FEEDNAME = "Doxygen generated docs" DOCSET_BUNDLE_ID = org.doxygen.Project DOCSET_PUBLISHER_ID = org.doxygen.Publisher DOCSET_PUBLISHER_NAME = Publisher GENERATE_HTMLHELP = NO CHM_FILE = HHC_LOCATION = GENERATE_CHI = NO CHM_INDEX_ENCODING = BINARY_TOC = NO TOC_EXPAND = NO GENERATE_QHP = NO QCH_FILE = QHP_NAMESPACE = org.doxygen.Project QHP_VIRTUAL_FOLDER = doc QHP_CUST_FILTER_NAME = QHP_CUST_FILTER_ATTRS = QHP_SECT_FILTER_ATTRS = QHG_LOCATION = GENERATE_ECLIPSEHELP = NO ECLIPSE_DOC_ID = org.doxygen.Project DISABLE_INDEX = NO GENERATE_TREEVIEW = NO ENUM_VALUES_PER_LINE = 4 TREEVIEW_WIDTH = 250 EXT_LINKS_IN_WINDOW = NO FORMULA_FONTSIZE = 10 FORMULA_TRANSPARENT = YES USE_MATHJAX = NO MATHJAX_RELPATH = http://www.mathjax.org/mathjax MATHJAX_EXTENSIONS = SEARCHENGINE = NO SERVER_BASED_SEARCH = NO #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- GENERATE_LATEX = NO LATEX_OUTPUT = latex LATEX_CMD_NAME = latex MAKEINDEX_CMD_NAME = makeindex COMPACT_LATEX = NO PAPER_TYPE = a4 EXTRA_PACKAGES = LATEX_HEADER = LATEX_FOOTER = PDF_HYPERLINKS = YES USE_PDFLATEX = YES LATEX_BATCHMODE = NO LATEX_HIDE_INDICES = NO LATEX_SOURCE_CODE = NO LATEX_BIB_STYLE = plain #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- GENERATE_RTF = NO RTF_OUTPUT = rtf COMPACT_RTF = NO RTF_HYPERLINKS = NO RTF_STYLESHEET_FILE = RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- GENERATE_MAN = NO MAN_OUTPUT = man MAN_EXTENSION = .3 MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- GENERATE_XML = NO XML_OUTPUT = xml XML_SCHEMA = XML_DTD = XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- GENERATE_PERLMOD = NO PERLMOD_LATEX = NO PERLMOD_PRETTY = YES PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- ENABLE_PREPROCESSING = YES MACRO_EXPANSION = YES EXPAND_ONLY_PREDEF = YES SEARCH_INCLUDES = NO INCLUDE_PATH = INCLUDE_FILE_PATTERNS = *.h PREDEFINED = __has_builtin \ OS_API_VERSION(x,y)=1 \ GS_API_VERSION(x,y)=1 \ CF_INLINE= \ CF_EXPORT= \ CF_EXTERN_C_BEGIN= \ CF_EXTERN_C_END= EXPAND_AS_DEFINED = SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- TAGFILES = GENERATE_TAGFILE = ALLEXTERNALS = NO EXTERNAL_GROUPS = YES PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- CLASS_DIAGRAMS = YES MSCGEN_PATH = HIDE_UNDOC_RELATIONS = YES HAVE_DOT = NO DOT_NUM_THREADS = 0 DOT_FONTNAME = Helvetica DOT_FONTSIZE = 10 DOT_FONTPATH = CLASS_GRAPH = YES COLLABORATION_GRAPH = YES GROUP_GRAPHS = YES UML_LOOK = NO UML_LIMIT_NUM_FIELDS = 10 TEMPLATE_RELATIONS = NO INCLUDE_GRAPH = YES INCLUDED_BY_GRAPH = YES CALL_GRAPH = NO CALLER_GRAPH = NO GRAPHICAL_HIERARCHY = YES DIRECTORY_GRAPH = YES DOT_IMAGE_FORMAT = png INTERACTIVE_SVG = NO DOT_PATH = DOTFILE_DIRS = MSCFILE_DIRS = DOT_GRAPH_MAX_NODES = 50 MAX_DOT_GRAPH_DEPTH = 0 DOT_TRANSPARENT = NO DOT_MULTI_TARGETS = YES GENERATE_LEGEND = YES DOT_CLEANUP = YES gnustep-corebase-0.2/COPYING.LIB0000644000175000017500000005755513222706330015362 0ustar yavoryavor GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. gnustep-corebase-0.2/configure.ac0000644000175000017500000002071714551015633016203 0ustar yavoryavor# -*- Autoconf -*- # Process this file with autoconf to produce a configure script. AC_PREREQ([2.60]) AC_INIT([libgnustep-corebase], [0.2], [bug-gnustep@gnu.org]) AC_CONFIG_SRCDIR([Source/CFBase.c]) AC_CONFIG_HEADERS([Source/config.h]) if test -n "$GNUSTEP_MAKEFILES"; then #-------------------------------------------------------------------- # Use config.guess, config.sub and install-sh provided by gnustep-make #-------------------------------------------------------------------- AC_CONFIG_AUX_DIR($GNUSTEP_MAKEFILES) #-------------------------------------------------------------------- # Determine the host, build, and target systems #-------------------------------------------------------------------- AC_CANONICAL_TARGET([]) fi #-------------------------------------------------------------------- # Find the compiler #-------------------------------------------------------------------- AC_PROG_CPP AC_PROG_CC AC_PROG_OBJC # Check for header files. AC_HEADER_STDC AC_C_INLINE AC_C_BIGENDIAN(AC_SUBST([GS_WORDS_BIGENDIAN_DEFINE], ["#define __BIG_ENDIAN__ 1"]), AC_SUBST([GS_WORDS_BIGENDIAN_DEFINE], ["#define __LITTLE_ENDIAN__ 1"]), AC_MSG_ERROR([Could not determine CPU endianness.])) # Gather information about the data model so we can define the data types m4_define([GS_CHECK_DATA_MODEL], [AC_CHECK_SIZEOF([char]) AC_CHECK_SIZEOF([short]) AC_CHECK_SIZEOF([int]) AC_CHECK_SIZEOF([long]) AC_CHECK_SIZEOF([long long]) AC_CHECK_SIZEOF([void *]) AH_VERBATIM([DATA_MODEL_LP32], [/* Define LP32 data model. */ #define DATA_MODEL_LP32 122484]) AH_VERBATIM([DATA_MODEL_ILP32], [/* Define ILP32 data model. */ #define DATA_MODEL_ILP32 124484]) AH_VERBATIM([DATA_MODEL_LLP64], [/* Define LLP64 data model. */ #define DATA_MODEL_LLP64 124488]) AH_VERBATIM([DATA_MODEL_LP64], [/* Define LP64 data model. */ #define DATA_MODEL_LP64 124888]) AC_CACHE_CHECK([for data model], [gs_cv_c_data_model], [_gs_data_model="$ac_cv_sizeof_char$ac_cv_sizeof_short$ac_cv_sizeof_int$ac_cv_sizeof_long$ac_cv_sizeof_long_long$ac_cv_sizeof_void_p" AS_CASE([$_gs_data_model], [122484], [gs_cv_c_data_model="LP32"], [124484], [gs_cv_c_data_model="ILP32"], [124488], [gs_cv_c_data_model="LLP64"], [124888], [gs_cv_c_data_model="LP64"], [gs_cv_c_data_model="unknown"])]) AC_DEFINE_UNQUOTED([DATA_MODEL], [DATA_MODEL_$gs_cv_c_data_model], [Define to the architecture's data model.]) ]) # GS_CHECK_DATA_MODEL GS_CHECK_DATA_MODEL AC_SUBST([GS_SINT8_T], ["signed char"]) AC_SUBST([GS_UINT8_T], ["unsigned char"]) AC_SUBST([GS_SINT16_T], ["signed short"]) AC_SUBST([GS_UINT16_T], ["unsigned short"]) AC_SUBST([GS_SINT64_T], ["signed long long"]) AC_SUBST([GS_UINT64_T], ["unsigned long long"]) AS_CASE([$gs_cv_c_data_model], [LP32], [AC_SUBST([GS_SINT32_T], ["signed long"]) AC_SUBST([GS_UINT32_T], ["unsigned long"]) AC_SUBST([GS_SINTPTR_T], ["signed long"]) AC_SUBST([GS_UINTPTR_T], ["unsigned long"])], [ILP32], [AC_SUBST([GS_SINT32_T], ["signed int"]) AC_SUBST([GS_UINT32_T], ["unsigned int"]) AC_SUBST([GS_SINTPTR_T], ["signed int"]) AC_SUBST([GS_UINTPTR_T], ["unsigned int"])], [LLP64], [AC_SUBST([GS_SINT32_T], ["signed int"]) AC_SUBST([GS_UINT32_T], ["unsigned int"]) AC_SUBST([GS_SINTPTR_T], ["signed long long"]) AC_SUBST([GS_UINTPTR_T], ["unsigned long long"])], [LP64], [AC_SUBST([GS_SINT32_T], ["signed int"]) AC_SUBST([GS_UINT32_T], ["unsigned int"]) AC_SUBST([GS_SINTPTR_T], ["signed long"]) AC_SUBST([GS_UINTPTR_T], ["unsigned long"])], [AC_MSG_ERROR([Could not identify the architecture's data model.])]) AC_CHECK_SIZEOF([double]) AC_CHECK_SIZEOF([long double]) #-------------------------------------------------------------------- # Check for CFRunLoop support # Android and QNX have pthread in libc instead of libpthread #-------------------------------------------------------------------- AC_ARG_ENABLE(cfrunloop, [--disable-cfrunloop Disables CFRunLoop support and requiring pthread. Must be passed when building on Windows.], [], [AC_CHECK_HEADERS([unistd.h fcntl.h poll.h limits.h pthread.h], [AC_SEARCH_LIBS(pthread_join, [pthread pthreadG32 pthreadVC2], [AC_DEFINE(HAVE_CFRUNLOOP_SUPPORT, 1, [Define to 1 if the required libraries and headers for CFRunLoop are present.])], [AC_MSG_ERROR([Missing pthread library for CFRunLoop support.])])], [AC_MSG_ERROR([Missing headers for CFRunLoop support.])])]) #--- # Check for ICU #--- AC_ARG_WITH([icu], AS_HELP_STRING([--without-icu], [Disable Internation Components for Unicode. WARNING: Many components will stop working without ICU support!]), [], [with_icu=yes]) AS_IF([test x"with_icu" != xno], [found_icu=no AS_CASE([$target_os], [mingw*|windows], [ # check for ICU bundled with Windows 10 AC_CHECK_LIB(icu, udat_open, [AC_CHECK_HEADERS([icu.h], [found_icu=yes LIBS="$LIBS -licu" AC_MSG_NOTICE([Using ICU DLL from Windows 10 (requires version 1903)])])])]) AS_IF([test $found_icu = no], [PKG_CHECK_MODULES([ICU], [icu-i18n > 49.0]) LIBS="$LIBS $ICU_LIBS"; CFLAGS="$CFLAGS $ICU_CFLAGS"; INCLUDE_FLAGS="$INCLUDE_FLAGS $ICU_CFLAGS" AC_CHECK_HEADERS([unicode/ucal.h unicode/uchar.h unicode/ucnv.h unicode/ucol.h unicode/ucurr.h unicode/udat.h unicode/udatpg.h unicode/uloc.h unicode/ulocdata.h unicode/unorm2.h unicode/unum.h unicode/usearch.h unicode/uset.h unicode/ustring.h unicode/utrans.h], [], AC_MSG_ERROR([Could not find required ICU headers.]))]) AC_DEFINE([HAVE_ICU], [1], [Define to 1 if you have International Components for Unicode.])]) #--- # Check for Grand Central Dispatch (libdispatch) #--- AC_ARG_WITH([gcd], [AS_HELP_STRING([--without-gcd], [Explicitly compiles without Grand Central Dispatch support. Configure will attempt to find a compatible library, use this option if you do not wish to have the support. The opposite option, --with-gcd, is also supported and should be used if Grand Central Dispatch support is absolutely required. A compatible library will required (http://www.nickhutchinson.me/libdispatch).])], [], [with_gcd=maybe]) AS_IF([test "x$with_gcd" != xno], AC_CHECK_HEADERS([dispatch/dispatch.h], AC_CHECK_LIB([dispatch], [dispatch_get_main_queue_eventfd_np], , AS_IF([test "x$with_gcd" = "xyes"], AC_MSG_ERROR([Compatible libdispatch not found for GCD support!])) ), AC_MSG_ERROR([Could not find the Grand Central Dispatch headers.]) ) ) #--- # Check for the Objective-C runtime #--- AC_ARG_WITH([objc], [AS_HELP_STRING([--without-objc], [Compiles without support for Objective-C. This option disables the Toll-Free Bridging mechanism.])], [], [with_objc=yes]) AS_IF([test "x$with_objc" != xno], AC_CHECK_HEADERS([objc/runtime.h], AC_SEARCH_LIBS(objc_getClass, [objc objc2], [], AC_MSG_ERROR([Objective-C library not found! Use --without-objc-bridge to explicitly disable the toll-free bridge or install the Objective-C library.])), AC_MSG_ERROR([Could not find the Objective-C runtime header.]))) #--- # Check for zoneinfo directory #--- AC_ARG_WITH([zoneinfo], [AS_HELP_STRING([--with-zoneinfo=DIR], [Directory of the Time zone object files.])], [], [with_zoneinfo=no]) AC_MSG_CHECKING([zoneinfo directory]) AS_IF([test "x$with_zoneinfo" = xno], [AS_IF([test -d "/usr/share/zoneinfo"], [with_zoneinfo='/usr/share/zoneinfo'], [test -d "/usr/lib/zoneinfo"], [with_zoneinfo='/usr/lib/zoneinfo'], [test -d "/usr/local/share/zoneinfo"], [with_zoneinfo='/usr/local/share/zoneinfo'], [test -d "/usr/local/lib/zoneinfo"], [with_zoneinfo='/usr/local/lib/zoneinfo'], [test -d "/etc/zoneinfo"], [with_zoneinfo='/etc/zoneinfo'], [test -d "/usr/local/etc/zoneinfo"], [with_zoneinfo='/usr/local/etc/zoneinfo'])]) AS_IF([test "$with_zoneinfo" = "no" || test ! -d "$with_zoneinfo"], [AC_MSG_ERROR([Please specify a valid zoneinfo directory.])]) AC_MSG_RESULT($with_zoneinfo) AC_DEFINE_UNQUOTED([TZDIR], ["$with_zoneinfo"], [Define to the directory contain time zone object files.]) #--- # Check for libm #--- AC_CHECK_LIB(m, modf) #--- # Check for WinSock2 #--- AC_CHECK_HEADERS(ws2tcpip.h) AC_CONFIG_FILES([Source/GNUmakefile Headers/CoreFoundation/CFBase.h]) AC_OUTPUT gnustep-corebase-0.2/.gitignore0000644000175000017500000000007314551015633015676 0ustar yavoryavorobj *.log *.sum config.* CFBase.h Source/GNUmakefile *.tmp gnustep-corebase-0.2/Makefile.postamble0000644000175000017500000000160213222706330017325 0ustar yavoryavor# # Makefile.postamble # # Project specific makefile rules # # Uncomment the targets you want. # The double colons (::) are important, do not make them single colons # otherwise the normal makefile rules will not be performed. # # Things to do before compiling # before-all:: # Things to do after compiling # after-all:: # Things to do before installing # before-install:: # Things to do after installing # after-install:: # Things to do before uninstalling # before-uninstall:: # Things to do after uninstalling # after-uninstall:: # Things to do before cleaning # before-clean:: # Things to do after cleaning # after-clean:: # Things to do before distcleaning # before-distclean:: # Things to do after distcleaning after-distclean:: @rm -f config.status config.log config.cache # Things to do before checking # before-check:: # Things to do after checking # after-check:: gnustep-corebase-0.2/ANNOUNCE0000644000175000017500000000251413222706330015034 0ustar yavoryavor1 ANNOUNCE ********** This is version 0.1 of CoreBase. 1.1 What is CoreBase? ================= The GNUstep CoreBase Library is a library of general-purpose, non-graphical C objects. For example, it includes types for strings, collections, byte streams, typed coders, invocations, notifications, notification dispatchers, moments in time, network ports, and event loops. It provides functionality that aims to implement the non-graphical portion of Apple's CoreFoundation framework. 1.2 Noteworthy changes ========================================== * Initial release 1.3 How can I get support for this software? ============================================ You may wish to use the GNUstep discussion mailing list for general questions and discussion. Look at the GNUstep Web Pages for more information regarding GNUstep resources `http://www.gnustep.org/' 1.4 Where can you get it? How can you compile it? ================================================== You can download sources and rpms (for some machines) from `ftp://ftp.gnustep.org/pub/gnustep/libs'. 1.5 Where do I send bug reports? ================================ Bug reports can be sent to . 1.6 Obtaining GNU Software ========================== Check out the GNUstep web site. (`http://www.gnustep.org/'), and the GNU web site. (`http://www.gnu.org/') gnustep-corebase-0.2/aclocal.m40000644000175000017500000002524214551015633015553 0ustar yavoryavor# generated automatically by aclocal 1.16.3 -*- Autoconf -*- # Copyright (C) 1996-2020 Free Software Foundation, Inc. # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY, to the extent permitted by law; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])]) # pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*- # serial 12 (pkg-config-0.29.2) dnl Copyright © 2004 Scott James Remnant . dnl Copyright © 2012-2015 Dan Nicholson dnl dnl This program is free software; you can redistribute it and/or modify dnl it under the terms of the GNU General Public License as published by dnl the Free Software Foundation; either version 2 of the License, or dnl (at your option) any later version. dnl dnl This program is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU dnl General Public License for more details. dnl dnl You should have received a copy of the GNU General Public License dnl along with this program; if not, write to the Free Software dnl Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA dnl 02111-1307, USA. dnl dnl As a special exception to the GNU General Public License, if you dnl distribute this file as part of a program that contains a dnl configuration script generated by Autoconf, you may include it under dnl the same distribution terms that you use for the rest of that dnl program. dnl PKG_PREREQ(MIN-VERSION) dnl ----------------------- dnl Since: 0.29 dnl dnl Verify that the version of the pkg-config macros are at least dnl MIN-VERSION. Unlike PKG_PROG_PKG_CONFIG, which checks the user's dnl installed version of pkg-config, this checks the developer's version dnl of pkg.m4 when generating configure. dnl dnl To ensure that this macro is defined, also add: dnl m4_ifndef([PKG_PREREQ], dnl [m4_fatal([must install pkg-config 0.29 or later before running autoconf/autogen])]) dnl dnl See the "Since" comment for each macro you use to see what version dnl of the macros you require. m4_defun([PKG_PREREQ], [m4_define([PKG_MACROS_VERSION], [0.29.2]) m4_if(m4_version_compare(PKG_MACROS_VERSION, [$1]), -1, [m4_fatal([pkg.m4 version $1 or higher is required but ]PKG_MACROS_VERSION[ found])]) ])dnl PKG_PREREQ dnl PKG_PROG_PKG_CONFIG([MIN-VERSION]) dnl ---------------------------------- dnl Since: 0.16 dnl dnl Search for the pkg-config tool and set the PKG_CONFIG variable to dnl first found in the path. Checks that the version of pkg-config found dnl is at least MIN-VERSION. If MIN-VERSION is not specified, 0.9.0 is dnl used since that's the first version where most current features of dnl pkg-config existed. AC_DEFUN([PKG_PROG_PKG_CONFIG], [m4_pattern_forbid([^_?PKG_[A-Z_]+$]) m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$]) m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$]) AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility]) AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path]) AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path]) if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then AC_PATH_TOOL([PKG_CONFIG], [pkg-config]) fi if test -n "$PKG_CONFIG"; then _pkg_min_version=m4_default([$1], [0.9.0]) AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version]) if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) PKG_CONFIG="" fi fi[]dnl ])dnl PKG_PROG_PKG_CONFIG dnl PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) dnl ------------------------------------------------------------------- dnl Since: 0.18 dnl dnl Check to see whether a particular set of modules exists. Similar to dnl PKG_CHECK_MODULES(), but does not set variables or print errors. dnl dnl Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG]) dnl only at the first occurence in configure.ac, so if the first place dnl it's called might be skipped (such as if it is within an "if", you dnl have to call PKG_CHECK_EXISTS manually AC_DEFUN([PKG_CHECK_EXISTS], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl if test -n "$PKG_CONFIG" && \ AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then m4_default([$2], [:]) m4_ifvaln([$3], [else $3])dnl fi]) dnl _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES]) dnl --------------------------------------------- dnl Internal wrapper calling pkg-config via PKG_CONFIG and setting dnl pkg_failed based on the result. m4_define([_PKG_CONFIG], [if test -n "$$1"; then pkg_cv_[]$1="$$1" elif test -n "$PKG_CONFIG"; then PKG_CHECK_EXISTS([$3], [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null` test "x$?" != "x0" && pkg_failed=yes ], [pkg_failed=yes]) else pkg_failed=untried fi[]dnl ])dnl _PKG_CONFIG dnl _PKG_SHORT_ERRORS_SUPPORTED dnl --------------------------- dnl Internal check to see if pkg-config supports short errors. AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED], [AC_REQUIRE([PKG_PROG_PKG_CONFIG]) if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then _pkg_short_errors_supported=yes else _pkg_short_errors_supported=no fi[]dnl ])dnl _PKG_SHORT_ERRORS_SUPPORTED dnl PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND], dnl [ACTION-IF-NOT-FOUND]) dnl -------------------------------------------------------------- dnl Since: 0.4.0 dnl dnl Note that if there is a possibility the first call to dnl PKG_CHECK_MODULES might not happen, you should be sure to include an dnl explicit call to PKG_PROG_PKG_CONFIG in your configure.ac AC_DEFUN([PKG_CHECK_MODULES], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl pkg_failed=no AC_MSG_CHECKING([for $2]) _PKG_CONFIG([$1][_CFLAGS], [cflags], [$2]) _PKG_CONFIG([$1][_LIBS], [libs], [$2]) m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS and $1[]_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details.]) if test $pkg_failed = yes; then AC_MSG_RESULT([no]) _PKG_SHORT_ERRORS_SUPPORTED if test $_pkg_short_errors_supported = yes; then $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1` else $1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1` fi # Put the nasty error message in config.log where it belongs echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD m4_default([$4], [AC_MSG_ERROR( [Package requirements ($2) were not met: $$1_PKG_ERRORS Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. _PKG_TEXT])[]dnl ]) elif test $pkg_failed = untried; then AC_MSG_RESULT([no]) m4_default([$4], [AC_MSG_FAILURE( [The pkg-config script could not be found or is too old. Make sure it is in your PATH or set the PKG_CONFIG environment variable to the full path to pkg-config. _PKG_TEXT To get pkg-config, see .])[]dnl ]) else $1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS $1[]_LIBS=$pkg_cv_[]$1[]_LIBS AC_MSG_RESULT([yes]) $3 fi[]dnl ])dnl PKG_CHECK_MODULES dnl PKG_CHECK_MODULES_STATIC(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND], dnl [ACTION-IF-NOT-FOUND]) dnl --------------------------------------------------------------------- dnl Since: 0.29 dnl dnl Checks for existence of MODULES and gathers its build flags with dnl static libraries enabled. Sets VARIABLE-PREFIX_CFLAGS from --cflags dnl and VARIABLE-PREFIX_LIBS from --libs. dnl dnl Note that if there is a possibility the first call to dnl PKG_CHECK_MODULES_STATIC might not happen, you should be sure to dnl include an explicit call to PKG_PROG_PKG_CONFIG in your dnl configure.ac. AC_DEFUN([PKG_CHECK_MODULES_STATIC], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl _save_PKG_CONFIG=$PKG_CONFIG PKG_CONFIG="$PKG_CONFIG --static" PKG_CHECK_MODULES($@) PKG_CONFIG=$_save_PKG_CONFIG[]dnl ])dnl PKG_CHECK_MODULES_STATIC dnl PKG_INSTALLDIR([DIRECTORY]) dnl ------------------------- dnl Since: 0.27 dnl dnl Substitutes the variable pkgconfigdir as the location where a module dnl should install pkg-config .pc files. By default the directory is dnl $libdir/pkgconfig, but the default can be changed by passing dnl DIRECTORY. The user can override through the --with-pkgconfigdir dnl parameter. AC_DEFUN([PKG_INSTALLDIR], [m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])]) m4_pushdef([pkg_description], [pkg-config installation directory @<:@]pkg_default[@:>@]) AC_ARG_WITH([pkgconfigdir], [AS_HELP_STRING([--with-pkgconfigdir], pkg_description)],, [with_pkgconfigdir=]pkg_default) AC_SUBST([pkgconfigdir], [$with_pkgconfigdir]) m4_popdef([pkg_default]) m4_popdef([pkg_description]) ])dnl PKG_INSTALLDIR dnl PKG_NOARCH_INSTALLDIR([DIRECTORY]) dnl -------------------------------- dnl Since: 0.27 dnl dnl Substitutes the variable noarch_pkgconfigdir as the location where a dnl module should install arch-independent pkg-config .pc files. By dnl default the directory is $datadir/pkgconfig, but the default can be dnl changed by passing DIRECTORY. The user can override through the dnl --with-noarch-pkgconfigdir parameter. AC_DEFUN([PKG_NOARCH_INSTALLDIR], [m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])]) m4_pushdef([pkg_description], [pkg-config arch-independent installation directory @<:@]pkg_default[@:>@]) AC_ARG_WITH([noarch-pkgconfigdir], [AS_HELP_STRING([--with-noarch-pkgconfigdir], pkg_description)],, [with_noarch_pkgconfigdir=]pkg_default) AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir]) m4_popdef([pkg_default]) m4_popdef([pkg_description]) ])dnl PKG_NOARCH_INSTALLDIR dnl PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE, dnl [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND]) dnl ------------------------------------------- dnl Since: 0.28 dnl dnl Retrieves the value of the pkg-config variable for the given module. AC_DEFUN([PKG_CHECK_VAR], [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl _PKG_CONFIG([$1], [variable="][$3]["], [$2]) AS_VAR_COPY([$1], [pkg_cv_][$1]) AS_VAR_IF([$1], [""], [$5], [$4])dnl ])dnl PKG_CHECK_VAR gnustep-corebase-0.2/Headers/0000755000175000017500000000000013222706330015254 5ustar yavoryavorgnustep-corebase-0.2/Headers/CoreFoundation/0000755000175000017500000000000014661613221020177 5ustar yavoryavorgnustep-corebase-0.2/Headers/CoreFoundation/CFDate.h0000644000175000017500000000752313222706330021441 0ustar yavoryavor/* CFDate.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFDATE_H__ #define __COREFOUNDATION_CFDATE_H__ #include CF_EXTERN_C_BEGIN /** \ingroup CFDateRef */ typedef const struct __CFDate *CFDateRef; /** \ingroup CFTimeZoneRef */ typedef const struct __CFTimeZone *CFTimeZoneRef; /** \defgroup TimeUtils Time Utilities \{ */ /** \name Data Types \{ */ typedef double CFTimeInterval; typedef CFTimeInterval CFAbsoluteTime; typedef struct CFGregorianDate CFGregorianDate; struct CFGregorianDate { SInt32 year; SInt8 month; SInt8 day; SInt8 hour; SInt8 minute; double second; }; typedef struct CFGregorianUnits CFGregorianUnits; struct CFGregorianUnits { SInt32 years; SInt32 months; SInt32 days; SInt32 hours; SInt32 minutes; double seconds; }; typedef enum { kCFGregorianUnitsYears = (1 << 0), kCFGregorianUnitsMonths = (1 << 1), kCFGregorianUnitsDays = (1 << 2), kCFGregorianUnitsHours = (1 << 3), kCFGregorianUnitsMinutes = (1 << 4), kCFGregorianUnitsSeconds = (1 << 5), kCFGregorianAllUnits = 0x00FFFFFF } CFGregorianUnitFlags; /** \} */ /** \name Constants \{ */ CF_EXPORT const CFTimeInterval kCFAbsoluteTimeIntervalSince1970; CF_EXPORT const CFTimeInterval kCFAbsoluteTimeIntervalSince1904; /** \} */ /** \name Time Utilities Functions \{ */ CF_EXPORT CFAbsoluteTime CFAbsoluteTimeAddGregorianUnits (CFAbsoluteTime at, CFTimeZoneRef tz, CFGregorianUnits units); CF_EXPORT CFAbsoluteTime CFAbsoluteTimeGetCurrent (void); CF_EXPORT SInt32 CFAbsoluteTimeGetDayOfWeek (CFAbsoluteTime at, CFTimeZoneRef tz); CF_EXPORT SInt32 CFAbsoluteTimeGetDayOfYear (CFAbsoluteTime at, CFTimeZoneRef tz); CF_EXPORT CFGregorianUnits CFAbsoluteTimeGetDifferenceAsGregorianUnits (CFAbsoluteTime at1, CFAbsoluteTime at2, CFTimeZoneRef tz, CFOptionFlags unitFlags); CF_EXPORT CFGregorianDate CFAbsoluteTimeGetGregorianDate (CFAbsoluteTime at, CFTimeZoneRef tz); CF_EXPORT SInt32 CFAbsoluteTimeGetWeekOfYear (CFAbsoluteTime at, CFTimeZoneRef tz); CF_EXPORT CFAbsoluteTime CFGregorianDateGetAbsoluteTime (CFGregorianDate gdate, CFTimeZoneRef tz); CF_EXPORT Boolean CFGregorianDateIsValid (CFGregorianDate gdate, CFOptionFlags unitFlags); /** \} */ /** \} */ /** \defgroup CFDateRef CFData Reference \{ */ /** \name CFDate Functions \{ */ CF_EXPORT CFComparisonResult CFDateCompare (CFDateRef theDate, CFDateRef otherDate, void *context); CF_EXPORT CFDateRef CFDateCreate (CFAllocatorRef allocator, CFAbsoluteTime at); CF_EXPORT CFAbsoluteTime CFDateGetAbsoluteTime (CFDateRef theDate); CF_EXPORT CFTimeInterval CFDateGetTimeIntervalSinceDate (CFDateRef theDate, CFDateRef otherDate); CF_EXPORT CFTypeID CFDateGetTypeID (void); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFDATE_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFXMLNode.h0000644000175000017500000001123113222706330022021 0ustar yavoryavor/* CFXMLNode.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __CFCOREFOUNDATION_CFXMLNODE_H__ #define __CFCOREFOUNDATION_CFXMLNODE_H__ 1 #include #include #include #include #include CF_EXTERN_C_BEGIN /** \defgroup CFXMLNodeRef CFXMLNode Reference (deprecated) \{ */ typedef const struct __CFXMLNode *CFXMLNodeRef; typedef enum { kCFXMLEntityTypeParameter = 0, kCFXMLEntityTypeParsedInternal = 1, kCFXMLEntityTypeParsedExternal = 2, kCFXMLEntityTypeUnparsed = 3, kCFXMLEntityTypeCharacter = 4 } CFXMLEntityTypeCode; enum { kCFXMLNodeCurrentVersion = 1 }; typedef enum { kCFXMLNodeTypeDocument = 1, kCFXMLNodeTypeElement = 2, kCFXMLNodeTypeAttribute = 3, kCFXMLNodeTypeProcessingInstruction = 4, kCFXMLNodeTypeComment = 5, kCFXMLNodeTypeText = 6, kCFXMLNodeTypeCDATASection = 7, kCFXMLNodeTypeDocumentFragment = 8, kCFXMLNodeTypeEntity = 9, kCFXMLNodeTypeEntityReference = 10, kCFXMLNodeTypeDocumentType = 11, kCFXMLNodeTypeWhitespace = 12, kCFXMLNodeTypeNotation = 13, kCFXMLNodeTypeElementTypeDeclaration = 14, kCFXMLNodeTypeAttributeListDeclaration = 15 } CFXMLNodeTypeCode; typedef struct CFXMLExternalID CFXMLExternalID; struct CFXMLExternalID { CFURLRef systemID; CFStringRef publicID; }; typedef struct CFXMLAttributeDeclarationInfo CFXMLAttributeDeclarationInfo; struct CFXMLAttributeDeclarationInfo { CFStringRef attributeName; CFStringRef typeString; CFStringRef defaultString; }; typedef struct CFXMLAttributeListDeclarationInfo CFXMLAttributeListDeclarationInfo; struct CFXMLAttributeListDeclarationInfo { CFIndex numberOfAttributes; CFXMLAttributeDeclarationInfo *attributes; }; typedef struct CFXMLDocumentInfo CFXMLDocumentInfo; struct CFXMLDocumentInfo { CFURLRef sourceURL; CFStringEncoding encoding; }; typedef struct CFXMLDocumentTypeInfo CFXMLDocumentTypeInfo; struct CFXMLDocumentTypeInfo { CFXMLExternalID externalID; }; typedef struct CFXMLElementInfo CFXMLElementInfo; struct CFXMLElementInfo { CFDictionaryRef attributes; CFArrayRef attributeOrder; Boolean isEmpty; }; typedef struct CFXMLElementTypeDeclarationInfo CFXMLElementTypeDeclarationInfo; struct CFXMLElementTypeDeclarationInfo { CFStringRef contentDescription; }; typedef struct CFXMLEntityInfo CFXMLEntityInfo; struct CFXMLEntityInfo { CFXMLEntityTypeCode entityType; CFStringRef replacementText; CFXMLExternalID entityID; CFStringRef notationName; }; typedef struct CFXMLEntityReferenceInfo CFXMLEntityReferenceInfo; struct CFXMLEntityReferenceInfo { CFXMLEntityTypeCode entityType; }; typedef struct CFXMLNotationInfo CFXMLNotationInfo; struct CFXMLNotationInfo { CFXMLExternalID externalID; }; typedef struct CFXMLProcessingInstructionInfo CFXMLProcessingInstructionInfo; struct CFXMLProcessingInstructionInfo { CFStringRef dataString; }; CF_EXPORT CFTypeID CFXMLNodeGetTypeID (void); CF_EXPORT CFXMLNodeRef CFXMLNodeCreate (CFAllocatorRef alloc, CFXMLNodeTypeCode xmlType, CFStringRef dataString, const void *additionalInfoPtr, CFIndex version); CF_EXPORT CFXMLNodeRef CFXMLNodeCreateCopy (CFAllocatorRef alloc, CFXMLNodeRef origNode); CF_EXPORT const void *CFXMLNodeGetInfoPtr (CFXMLNodeRef node); CF_EXPORT CFStringRef CFXMLNodeGetString (CFXMLNodeRef node); CF_EXPORT CFXMLNodeTypeCode CFXMLNodeGetTypeCode (CFXMLNodeRef node); CF_EXPORT CFIndex CFXMLNodeGetVersion (CFXMLNodeRef node); typedef CFTreeRef CFXMLTreeRef; CF_EXPORT CFXMLTreeRef CFXMLTreeCreateWithNode (CFAllocatorRef allocator, CFXMLNodeRef node); CF_EXPORT CFXMLNodeRef CFXMLTreeGetNode (CFXMLTreeRef xmlTree); /** \} */ CF_EXTERN_C_END #endif /* __CFCOREFOUNDATION_CFXMLNODE_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFSocket.h0000644000175000017500000001703113222706330022007 0ustar yavoryavor/* CFSocket.h Copyright (C) 2012 Free Software Foundation, Inc. Author: Stefan Bidigaray Date: September, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFSOCKET_H__ #define __COREFOUNDATION_CFSOCKET_H__ #include #include #include CF_EXTERN_C_BEGIN /** \defgroup CFSocketRef CFSocket Reference \{ */ typedef struct __CFSocket *CFSocketRef; #if defined(_WIN32) #include typedef SOCKET CFSocketNativeHandle; #else typedef int CFSocketNativeHandle; #endif typedef struct CFSocketContext CFSocketContext; struct CFSocketContext { CFIndex version; void *info; CFAllocatorRetainCallBack retain; CFAllocatorReleaseCallBack release; CFAllocatorCopyDescriptionCallBack copyDescription; }; typedef struct CFSocketSignature CFSocketSignature; struct CFSocketSignature { SInt32 protocolFamily; SInt32 socketType; SInt32 protocol; CFDataRef address; }; typedef enum { kCFSocketNoCallBack = 0, kCFSocketReadCallBack = 1, kCFSocketAcceptCallBack = 2, kCFSocketDataCallBack = 3, kCFSocketConnectCallBack = 4 #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) , kCFSocketWriteCallBack = 8 #endif } CFSocketCallBackType; #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) enum { kCFSocketAutomaticallyReenableReadCallBack = 1, kCFSocketAutomaticallyReenableAcceptCallBack = 2, kCFSocketAutomaticallyReenableDataCallBack = 3, kCFSocketAutomaticallyReenableWriteCallBack = 8, #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) kCFSocketLeaveErrors = 64, #endif kCFSocketCloseOnInvalidate = 128 }; #endif typedef enum { kCFSocketSuccess = 0, kCFSocketError = -1, kCFSocketTimeout = -2 } CFSocketError; typedef void (*CFSocketCallBack) (CFSocketRef s, CFSocketCallBackType callbackType, CFDataRef address, const void *data, void *info); /** \} */ /** \defgroup CFSocketUtils Socket Name Server Utilities \{ */ CF_EXPORT const CFStringRef kCFSocketCommandKey; CF_EXPORT const CFStringRef kCFSocketNameKey; CF_EXPORT const CFStringRef kCFSocketValueKey; CF_EXPORT const CFStringRef kCFSocketResultKey; CF_EXPORT const CFStringRef kCFSocketErrorKey; CF_EXPORT const CFStringRef kCFSocketRegisterCommand; CF_EXPORT const CFStringRef kCFSocketRetrieveCommand; /** \} */ CF_EXPORT CFTypeID CFSocketGetTypeID (void); /** \ingroup CFSocketRef \{ */ /** \name Creating Sockets \{ */ CF_EXPORT CFSocketRef CFSocketCreate (CFAllocatorRef allocator, SInt32 protocolFamily, SInt32 socketType, SInt32 protocol, CFOptionFlags callBackTypes, CFSocketCallBack callout, const CFSocketContext * context); CF_EXPORT CFSocketRef CFSocketCreateConnectedToSocketSignature (CFAllocatorRef allocator, const CFSocketSignature * signature, CFOptionFlags callBackTypes, CFSocketCallBack callout, const CFSocketContext * context, CFTimeInterval timeout); CF_EXPORT CFSocketRef CFSocketCreateWithNative (CFAllocatorRef allocator, CFSocketNativeHandle sock, CFOptionFlags callBackTypes, CFSocketCallBack callout, const CFSocketContext * context); CF_EXPORT CFSocketRef CFSocketCreateWithSocketSignature (CFAllocatorRef allocator, const CFSocketSignature * signature, CFOptionFlags callBackTypes, CFSocketCallBack callout, const CFSocketContext * context); /** \} */ /** \name Configuring Sockets \{ */ CF_EXPORT CFDataRef CFSocketCopyAddress (CFSocketRef s); CF_EXPORT CFDataRef CFSocketCopyPeerAddress (CFSocketRef s); CF_EXPORT void CFSocketGetContext (CFSocketRef s, CFSocketContext * context); CF_EXPORT CFSocketNativeHandle CFSocketGetNative (CFSocketRef s); CF_EXPORT CFSocketError CFSocketSetAddress (CFSocketRef s, CFDataRef address); #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) CF_EXPORT void CFSocketDisableCallBacks (CFSocketRef s, CFOptionFlags callBackTypes); CF_EXPORT void CFSocketEnableCallBacks (CFSocketRef s, CFOptionFlags callBackTypes); CF_EXPORT CFOptionFlags CFSocketGetSocketFlags (CFSocketRef s); CF_EXPORT void CFSocketSetSocketFlags (CFSocketRef s, CFOptionFlags flags); #endif /** \} */ /** \name Using Sockets \{ */ CF_EXPORT CFSocketError CFSocketConnectToAddress (CFSocketRef s, CFDataRef address, CFTimeInterval timeout); CF_EXPORT CFRunLoopSourceRef CFSocketCreateRunLoopSource (CFAllocatorRef allocator, CFSocketRef s, CFIndex order); CF_EXPORT void CFSocketInvalidate (CFSocketRef s); CF_EXPORT Boolean CFSocketIsValid (CFSocketRef s); CF_EXPORT CFSocketError CFSocketSendData (CFSocketRef s, CFDataRef address, CFDataRef data, CFTimeInterval timeout); /** \} */ /** \} */ /** \ingroup CFSocketUtils \{ */ CF_EXPORT CFSocketError CFSocketCopyRegisteredSocketSignature (const CFSocketSignature * nameServerSignature, CFTimeInterval timeout, CFStringRef name, CFSocketSignature * signature, CFDataRef * nameServerAddress); CF_EXPORT CFSocketError CFSocketCopyRegisteredValue (const CFSocketSignature * nameServerSignature, CFTimeInterval timeout, CFStringRef name, CFPropertyListRef * value, CFDataRef * nameServerAddress); CF_EXPORT UInt16 CFSocketGetDefaultNameRegistryPortNumber (void); CF_EXPORT CFSocketError CFSocketRegisterSocketSignature (const CFSocketSignature * nameServerSignature, CFTimeInterval timeout, CFStringRef name, const CFSocketSignature * signature); CF_EXPORT CFSocketError CFSocketRegisterValue (const CFSocketSignature * nameServerSignature, CFTimeInterval timeout, CFStringRef name, CFPropertyListRef value); CF_EXPORT void CFSocketSetDefaultNameRegistryPortNumber (UInt16 port); CF_EXPORT CFSocketError CFSocketUnregister (const CFSocketSignature * nameServerSignature, CFTimeInterval timeout, CFStringRef name); /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFSOCKET_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFRunLoop.h0000644000175000017500000002436113222706330022161 0ustar yavoryavor/* CFRunLoop.h Copyright (C) 2012 Free Software Foundation, Inc. Author: Stefan Bidigaray Date: August, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFRUNLOOP_H__ #define __COREFOUNDATION_CFRUNLOOP_H__ #include #include #include #include #include CF_EXTERN_C_BEGIN /** \ingroup CFRunLoopRef */ typedef struct __CFRunLoop *CFRunLoopRef; /** \ingroup CFRunLoopSourceRef */ typedef struct __CFRunLoopSource *CFRunLoopSourceRef; /** \ingroup CFRunLoopObserverRef */ typedef struct __CFRunLoopObserver *CFRunLoopObserverRef; /** \ingroup CFRunLoopTimerRef */ typedef struct __CFRunLoopTimer *CFRunLoopTimerRef; /** \defgroup CFRunLoopRef CFRunLoop Reference \{ */ enum { kCFRunLoopRunFinished = 1, kCFRunLoopRunStopped = 2, kCFRunLoopRunTimedOut = 3, kCFRunLoopRunHandledSource = 4 }; CF_EXPORT const CFStringRef kCFRunLoopCommonModes; CF_EXPORT const CFStringRef kCFRunLoopDefaultMode; #ifndef __APPLE__ /** On non-Darwin platforms, we assume ports to be ordinary pollable file descriptors. */ typedef int mach_port_t; #endif /** \name Getting the CFRunLoop Type ID \{ */ CF_EXPORT CFTypeID CFRunLoopGetTypeID (void); /** \} */ /** \name Getting a Run Loop \{ */ CF_EXPORT CFRunLoopRef CFRunLoopGetCurrent (void); CF_EXPORT CFRunLoopRef CFRunLoopGetMain (void); /** \} */ /** \name Starting and Stopping a Run Loop \{ */ CF_EXPORT void CFRunLoopRun (void); CF_EXPORT SInt32 CFRunLoopRunInMode (CFStringRef mode, CFTimeInterval seconds, Boolean returnAfterSourceHandled); CF_EXPORT void CFRunLoopWakeUp (CFRunLoopRef rl); CF_EXPORT void CFRunLoopStop (CFRunLoopRef rl); CF_EXPORT Boolean CFRunLoopIsWaiting (CFRunLoopRef rl); /** \} */ /** \name Managing Run Loop Modes \{ */ CF_EXPORT void CFRunLoopAddCommonMode (CFRunLoopRef rl, CFStringRef mode); CF_EXPORT CFArrayRef CFRunLoopCopyAllModes (CFRunLoopRef rl); CF_EXPORT CFStringRef CFRunLoopCopyCurrentMode (CFRunLoopRef rl); /** \} */ /** \name Scheduling Blocks \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) DEFINE_BLOCK_TYPE_NO_ARGS (PerformBlockType, void); CF_EXPORT void CFRunLoopPerformBlock (CFRunLoopRef rl, CFTypeRef mode, PerformBlockType block); #endif /** \} */ /** \name Extensions for NSRunLoop \{ */ CF_EXPORT Boolean _CFRunLoopHasAnyValidSources (CFRunLoopRef rl, CFStringRef mode); /** \} */ /** \} */ /** \defgroup CFRunLoopSourceRef CFRunLoopSource Reference \{ */ typedef void (*CFRunLoopCancelCallBack) (void *info, CFRunLoopRef rl, CFStringRef mode); typedef Boolean (*CFRunLoopEqualCallBack) (const void *info1, const void *info2); typedef CFHashCode (*CFRunLoopHashCallBack) (const void *info); typedef mach_port_t (*CFRunLoopGetPortCallBack) (void *info); typedef void *(*CFRunLoopMachPerformCallBack) (void *msg, CFIndex size, CFAllocatorRef alloc, void *info); typedef void (*CFRunLoopPerformCallBack) (void *info); typedef void (*CFRunLoopScheduleCallBack) (void *info, CFRunLoopRef rl, CFStringRef mode); typedef struct CFRunLoopSourceContext CFRunLoopSourceContext; struct CFRunLoopSourceContext { CFIndex version; void *info; CFAllocatorRetainCallBack retain; CFAllocatorReleaseCallBack release; CFAllocatorCopyDescriptionCallBack copyDescription; CFRunLoopEqualCallBack equal; CFRunLoopHashCallBack hash; CFRunLoopScheduleCallBack schedule; CFRunLoopCancelCallBack cancel; CFRunLoopPerformCallBack perform; }; typedef struct CFRunLoopSourceContext1 CFRunLoopSourceContext1; struct CFRunLoopSourceContext1 { CFIndex version; void *info; CFAllocatorRetainCallBack retain; CFAllocatorReleaseCallBack release; CFAllocatorCopyDescriptionCallBack copyDescription; CFRunLoopEqualCallBack equal; CFRunLoopHashCallBack hash; CFRunLoopGetPortCallBack getPort; CFRunLoopMachPerformCallBack perform; }; /** \name Managing Sources \{ */ CF_EXPORT void CFRunLoopAddSource (CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode); CF_EXPORT Boolean CFRunLoopContainsSource (CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode); CF_EXPORT void CFRunLoopRemoveSource (CFRunLoopRef rl, CFRunLoopSourceRef source, CFStringRef mode); CF_EXPORT CFRunLoopSourceRef CFRunLoopSourceCreate (CFAllocatorRef alloc, CFIndex order, CFRunLoopSourceContext * context); CF_EXPORT void CFRunLoopSourceGetContext (CFRunLoopSourceRef source, CFRunLoopSourceContext * context); CF_EXPORT CFIndex CFRunLoopSourceGetOrder (CFRunLoopSourceRef source); CF_EXPORT void CFRunLoopSourceInvalidate (CFRunLoopSourceRef source); CF_EXPORT Boolean CFRunLoopSourceIsValid (CFRunLoopSourceRef source); CF_EXPORT void CFRunLoopSourceSignal (CFRunLoopSourceRef source); /** \} */ /** \name Getting the CFRunLoopSource Type ID \{ */ CF_EXPORT CFTypeID CFRunLoopSourceGetTypeID (void); /** \} */ /** \} */ /** \defgroup CFRunLoopObserverRef CFRunLoopObserver Reference \{ */ enum { kCFRunLoopEntry = (1 << 0), kCFRunLoopBeforeTimers = (1 << 1), kCFRunLoopBeforeSources = (1 << 2), kCFRunLoopBeforeWaiting = (1 << 5), kCFRunLoopAfterWaiting = (1 << 6), kCFRunLoopExit = (1 << 7), kCFRunLoopAllActivities = 0x0FFFFFFFU }; typedef int CFRunLoopActivity; typedef void (*CFRunLoopObserverCallBack) (CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info); typedef struct CFRunLoopObserverContext CFRunLoopObserverContext; struct CFRunLoopObserverContext { CFIndex version; void *info; CFAllocatorRetainCallBack retain; CFAllocatorReleaseCallBack release; CFAllocatorCopyDescriptionCallBack copyDescription; }; /** \name Managing Observers \{ */ CF_EXPORT void CFRunLoopAddObserver (CFRunLoopRef rl, CFRunLoopObserverRef observer, CFStringRef mode); CF_EXPORT Boolean CFRunLoopContainsObserver (CFRunLoopRef rl, CFRunLoopObserverRef observer, CFStringRef mode); CF_EXPORT void CFRunLoopRemoveObserver (CFRunLoopRef rl, CFRunLoopObserverRef observer, CFStringRef mode); CF_EXPORT CFRunLoopObserverRef CFRunLoopObserverCreate (CFAllocatorRef alloc, CFOptionFlags activities, Boolean repeats, CFIndex order, CFRunLoopObserverCallBack callback, CFRunLoopObserverContext * context); CF_EXPORT Boolean CFRunLoopObserverDoesRepeat (CFRunLoopObserverRef observer); CF_EXPORT CFOptionFlags CFRunLoopObserverGetActivities (CFRunLoopObserverRef observer); CF_EXPORT void CFRunLoopObserverGetContext (CFRunLoopObserverRef observer, CFRunLoopObserverContext * context); CF_EXPORT CFIndex CFRunLoopObserverGetOrder (CFRunLoopObserverRef observer); CF_EXPORT void CFRunLoopObserverInvalidate (CFRunLoopObserverRef observer); CF_EXPORT Boolean CFRunLoopObserverIsValid (CFRunLoopObserverRef observer); /** \} */ /** \name Getting the CFRunLoopObserver Type ID \{ */ CF_EXPORT CFTypeID CFRunLoopObserverGetTypeID (void); /** \} */ /** \} */ /** \defgroup CFRunLoopTimerRef CFRunLoopTimer Reference \{ */ typedef void (*CFRunLoopTimerCallBack) (CFRunLoopTimerRef timer, void *info); typedef struct CFRunLoopTimerContext CFRunLoopTimerContext; struct CFRunLoopTimerContext { CFIndex version; void *info; CFAllocatorRetainCallBack retain; CFAllocatorReleaseCallBack release; CFAllocatorCopyDescriptionCallBack copyDescription; }; /** \name Managing Timers \{ */ CF_EXPORT void CFRunLoopAddTimer (CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode); CF_EXPORT CFAbsoluteTime CFRunLoopGetNextTimerFireDate (CFRunLoopRef rl, CFStringRef mode); CF_EXPORT void CFRunLoopRemoveTimer (CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode); CF_EXPORT Boolean CFRunLoopContainsTimer (CFRunLoopRef rl, CFRunLoopTimerRef timer, CFStringRef mode); CF_EXPORT CFRunLoopTimerRef CFRunLoopTimerCreate (CFAllocatorRef alloc, CFAbsoluteTime fireDate, CFTimeInterval interval, CFOptionFlags flags, CFIndex order, CFRunLoopTimerCallBack callback, CFRunLoopTimerContext * context); CF_EXPORT Boolean CFRunLoopTimerDoesRepeat (CFRunLoopTimerRef timer); CF_EXPORT void CFRunLoopTimerGetContext (CFRunLoopTimerRef timer, CFRunLoopTimerContext * context); CF_EXPORT CFTimeInterval CFRunLoopTimerGetInterval (CFRunLoopTimerRef timer); CF_EXPORT CFAbsoluteTime CFRunLoopTimerGetNextFireDate (CFRunLoopTimerRef timer); CF_EXPORT CFIndex CFRunLoopTimerGetOrder (CFRunLoopTimerRef timer); CF_EXPORT void CFRunLoopTimerInvalidate (CFRunLoopTimerRef timer); CF_EXPORT Boolean CFRunLoopTimerIsValid (CFRunLoopTimerRef timer); CF_EXPORT void CFRunLoopTimerSetNextFireDate (CFRunLoopTimerRef timer, CFAbsoluteTime fireDate); /** \} */ /** \name Getting the CFRunLoopTimer Type ID \{ */ CF_EXPORT CFTypeID CFRunLoopTimerGetTypeID (void); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFRUNLOOP_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFDateFormatter.h0000644000175000017500000001464513222706330023330 0ustar yavoryavor/* CFDateFormatter.h Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFDATEFORMATTER_H__ #define __COREFOUNDATION_CFDATEFORMATTER_H__ #include #include #include #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) CF_EXTERN_C_BEGIN /** \defgroup CFDateFormatterRef CFDateFormatter Reference \{ */ typedef struct __CFDateFormatter *CFDateFormatterRef; typedef enum _CFDateFormatterStyle { kCFDateFormatterNoStyle = 0, kCFDateFormatterShortStyle = 1, kCFDateFormatterMediumStyle = 2, kCFDateFormatterLongStyle = 3, kCFDateFormatterFullStyle = 4 } CFDateFormatterStyle; /** \name Constants \{ */ CF_EXPORT const CFStringRef kCFDateFormatterIsLenient; /* CFBoolean */ CF_EXPORT const CFStringRef kCFDateFormatterTimeZone; /* CFTimeZone */ CF_EXPORT const CFStringRef kCFDateFormatterCalendarName; /* CFString */ CF_EXPORT const CFStringRef kCFDateFormatterDefaultFormat; /* CFString */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXPORT const CFStringRef kCFDateFormatterTwoDigitStartDate; /* CFDate */ CF_EXPORT const CFStringRef kCFDateFormatterDefaultDate; /* CFDate */ CF_EXPORT const CFStringRef kCFDateFormatterCalendar; /* CFCalendar */ CF_EXPORT const CFStringRef kCFDateFormatterEraSymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterMonthSymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterShortMonthSymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterWeekdaySymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterShortWeekdaySymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterAMSymbol; /* CFString */ CF_EXPORT const CFStringRef kCFDateFormatterPMSymbol; /* CFString */ #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT const CFStringRef kCFDateFormatterLongEraSymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterVeryShortMonthSymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterStandaloneMonthSymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterShortStandaloneMonthSymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterVeryShortStandaloneMonthSymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterVeryShortWeekdaySymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterStandaloneWeekdaySymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterShortStandaloneWeekdaySymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterVeryShortStandaloneWeekdaySymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterQuarterSymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterShortQuarterSymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterStandaloneQuarterSymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterShortStandaloneQuarterSymbols; /* CFArray */ CF_EXPORT const CFStringRef kCFDateFormatterGregorianStartDate; /* CFDate */ #endif /** \} */ /** \name Creating a Date Formatter */ CF_EXPORT CFDateFormatterRef CFDateFormatterCreate (CFAllocatorRef alloc, CFLocaleRef locale, CFDateFormatterStyle dateStyle, CFDateFormatterStyle timeStyle); /** \} */ /** \name Configuring a Date Formatter \{ */ CF_EXPORT void CFDateFormatterSetFormat (CFDateFormatterRef fmt, CFStringRef formatString); CF_EXPORT void CFDateFormatterSetProperty (CFDateFormatterRef fmt, CFStringRef key, CFTypeRef value); /** \} */ /** \name Parsing Strings \{ */ CF_EXPORT CFDateRef CFDateFormatterCreateDateFromString (CFAllocatorRef alloc, CFDateFormatterRef fmt, CFStringRef string, CFRange * rangep); CF_EXPORT Boolean CFDateFormatterGetAbsoluteTimeFromString (CFDateFormatterRef fmt, CFStringRef string, CFRange * rangep, CFAbsoluteTime * atp); /** \} */ /** \name Creating Strings From Data \{ */ CF_EXPORT CFStringRef CFDateFormatterCreateStringWithAbsoluteTime (CFAllocatorRef alloc, CFDateFormatterRef fmt, CFAbsoluteTime at); CF_EXPORT CFStringRef CFDateFormatterCreateStringWithDate (CFAllocatorRef alloc, CFDateFormatterRef fmt, CFDateRef date); CF_EXPORT CFStringRef CFDateFormatterCreateDateFormatFromTemplate (CFAllocatorRef alloc, CFStringRef templ, CFOptionFlags options, CFLocaleRef locale); /** \} */ /** \name Getting Information About a Date Formatter \{ */ CF_EXPORT CFTypeRef CFDateFormatterCopyProperty (CFDateFormatterRef fmt, CFStringRef key); CF_EXPORT CFDateFormatterStyle CFDateFormatterGetDateStyle (CFDateFormatterRef fmt); CF_EXPORT CFStringRef CFDateFormatterGetFormat (CFDateFormatterRef fmt); CF_EXPORT CFLocaleRef CFDateFormatterGetLocale (CFDateFormatterRef fmt); CF_EXPORT CFDateFormatterStyle CFDateFormatterGetTimeStyle (CFDateFormatterRef fmt); /** \} */ /** \name Getting the CFDateFormatter Type ID \{ */ CF_EXPORT CFTypeID CFDateFormatterGetTypeID (void); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* MAC_OS_X_VERSION_10_3 */ #endif /* __COREFOUNDATION_CFDATEFORMATTER_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFTimeZone.h0000644000175000017500000000644113222706330022314 0ustar yavoryavor/* CFTimeZone.c Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: July, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFTIMEZONE__ #define __COREFOUNDATION_CFTIMEZONE__ 1 #include #include #include #include #include #include CF_EXTERN_C_BEGIN /** \defgroup CFTimeZoneRef CFTimeZone Reference \{ */ CF_EXPORT const CFStringRef kCFTimeZoneSystemTimeZoneDidChangeNotification; #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) typedef enum { kCFTimeZoneNameStyleStandard, kCFTimeZoneNameStyleShortStandard, kCFTimeZoneNameStyleDaylightSaving, kCFTimeZoneNameStyleShortDaylightSaving } CFTimeZoneNameStyle; #endif CF_EXPORT CFTimeZoneRef CFTimeZoneCreateWithName (CFAllocatorRef alloc, CFStringRef name, Boolean tryAbbrev); CF_EXPORT CFTimeZoneRef CFTimeZoneCreateWithTimeIntervalFromGMT (CFAllocatorRef alloc, CFTimeInterval ti); CF_EXPORT CFTimeZoneRef CFTimeZoneCreate (CFAllocatorRef alloc, CFStringRef name, CFDataRef data); CF_EXPORT CFDictionaryRef CFTimeZoneCopyAbbreviationDictionary (void); CF_EXPORT CFStringRef CFTimeZoneCopyAbbreviation (CFTimeZoneRef tz, CFAbsoluteTime at); CF_EXPORT CFTimeZoneRef CFTimeZoneCopyDefault (void); CF_EXPORT CFTimeZoneRef CFTimeZoneCopySystem (void); CF_EXPORT void CFTimeZoneSetDefault (CFTimeZoneRef tz); CF_EXPORT CFArrayRef CFTimeZoneCopyKnownNames (void); CF_EXPORT void CFTimeZoneResetSystem (void); CF_EXPORT void CFTimeZoneSetAbbreviationDictionary (CFDictionaryRef dict); CF_EXPORT CFStringRef CFTimeZoneGetName (CFTimeZoneRef tz); CF_EXPORT CFTimeInterval CFTimeZoneGetSecondsFromGMT (CFTimeZoneRef tz, CFAbsoluteTime at); CF_EXPORT CFDataRef CFTimeZoneGetData (CFTimeZoneRef tz); CF_EXPORT Boolean CFTimeZoneIsDaylightSavingTime (CFTimeZoneRef tz, CFAbsoluteTime at); CF_EXPORT CFTypeID CFTimeZoneGetTypeID (void); #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT CFStringRef CFTimeZoneCopyLocalizedName (CFTimeZoneRef tz, CFTimeZoneNameStyle style, CFLocaleRef locale); CF_EXPORT CFTimeInterval CFTimeZoneGetDaylightSavingTimeOffset (CFTimeZoneRef tz, CFAbsoluteTime at); CF_EXPORT CFAbsoluteTime CFTimeZoneGetNextDaylightSavingTimeTransition (CFTimeZoneRef tz, CFAbsoluteTime at); #endif /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFTIMEZONE__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFBag.h0000644000175000017500000000773413222706330021261 0ustar yavoryavor/* CFBag.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of CoreBase. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFBAG_H__ #define __COREFOUNDATION_CFBAG_H__ #include CF_EXTERN_C_BEGIN /** \ingroup CFBagRef */ typedef const struct __CFBag *CFBagRef; /** \ingroup CFMutableBagRef */ typedef struct __CFBag *CFMutableBagRef; /** \defgroup CFBagRef CFBag Reference \{ */ typedef void (*CFBagApplierFunction) (const void *value, void *context); typedef CFStringRef (*CFBagCopyDescriptionCallBack) (const void *value); typedef Boolean (*CFBagEqualCallBack) (const void *value1, const void *value2); typedef CFHashCode (*CFBagHashCallBack) (const void *value); typedef void (*CFBagReleaseCallBack) (CFAllocatorRef alloc, const void *value); typedef const void *(*CFBagRetainCallBack) (CFAllocatorRef alloc, const void *value); typedef struct CFBagCallBacks CFBagCallBacks; struct CFBagCallBacks { CFIndex version; CFBagRetainCallBack retain; CFBagReleaseCallBack release; CFBagCopyDescriptionCallBack copyDescription; CFBagEqualCallBack equal; CFBagHashCallBack hash; }; CF_EXPORT const CFBagCallBacks kCFCopyStringBagCallBacks; CF_EXPORT const CFBagCallBacks kCFTypeBagCallBacks; /** \name Creating a bag \{ */ CF_EXPORT CFBagRef CFBagCreate (CFAllocatorRef alloc, const void **values, CFIndex numValues, const CFBagCallBacks * callBacks); CF_EXPORT CFBagRef CFBagCreateCopy (CFAllocatorRef alloc, CFBagRef bag); /** \} */ /** \name Examining a dictionary \{ */ CF_EXPORT Boolean CFBagContainsValue (CFBagRef bag, const void *value); CF_EXPORT CFIndex CFBagGetCount (CFBagRef bag); CF_EXPORT CFIndex CFBagGetCountOfValue (CFBagRef bag, const void *value); CF_EXPORT void CFBagGetValues (CFBagRef bag, const void **values); CF_EXPORT const void *CFBagGetValue (CFBagRef bag, const void *value); CF_EXPORT Boolean CFBagGetValueIfPresent (CFBagRef bag, const void *candidate, const void **value); /** \} */ /** \name Applying a funcation to a dictionary \{ */ CF_EXPORT void CFBagApplyFunction (CFBagRef bag, CFBagApplierFunction applier, void *context); /** \} */ /** \name Getting the CFBag type ID \{ */ CF_EXPORT CFTypeID CFBagGetTypeID (void); /** \} */ /** \} */ /** \defgroup CFMutableBagRef CFMutableBag Reference \{ */ /** \name Creating a Mutable Dictionary \{ */ CF_EXPORT CFMutableBagRef CFBagCreateMutable (CFAllocatorRef alloc, CFIndex capacity, const CFBagCallBacks * callBacks); CF_EXPORT CFMutableBagRef CFBagCreateMutableCopy (CFAllocatorRef alloc, CFIndex capacity, CFBagRef bag); /** \} */ /** \name Modifying a Dictionary \{ */ CF_EXPORT void CFBagAddValue (CFMutableBagRef bag, const void *value); CF_EXPORT void CFBagRemoveAllValues (CFMutableBagRef bag); CF_EXPORT void CFBagRemoveValue (CFMutableBagRef bag, const void *value); CF_EXPORT void CFBagReplaceValue (CFMutableBagRef bag, const void *value); CF_EXPORT void CFBagSetValue (CFMutableBagRef bag, const void *value); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFBAG_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFURL.h0000644000175000017500000004237713222706330021234 0ustar yavoryavor/* CFURL.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Eric Wasylishen Date: January, 2010 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFURL_H__ #define __COREFOUNDATION_CFURL_H__ #include #include #include #include #include CF_EXTERN_C_BEGIN /** \defgroup CFURLRef CFURL Reference \{ */ typedef const struct __CFURL *CFURLRef; #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) typedef CFOptionFlags CFURLBookmarkCreationOptions; typedef CFOptionFlags CFURLBookmarkFileCreationOptions; typedef CFOptionFlags CFURLBookmarkResolutionOptions; #endif /** \name Constants \{ */ typedef enum { kCFURLPOSIXPathStyle = 0, kCFURLHFSPathStyle = 1, kCFURLWindowsPathStyle = 2 } CFURLPathStyle; #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) typedef enum { kCFURLComponentScheme = 1, kCFURLComponentNetLocation = 2, kCFURLComponentPath = 3, kCFURLComponentResourceSpecifier = 4, kCFURLComponentUser = 5, kCFURLComponentPassword = 6, kCFURLComponentUserInfo = 7, kCFURLComponentHost = 8, kCFURLComponentPort = 9, kCFURLComponentParameterString = 10, kCFURLComponentQuery = 11, kCFURLComponentFragment = 12 } CFURLComponentType; #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) enum { kCFURLBookmarkCreationPreferFileIDResolutionMask = (1 << 8), kCFURLBookmarkCreationMinimalBookmarkMask = (1 << 9), kCFURLBookmarkCreationSuitableForBookmarkFile = (1 << 10) }; enum { kCFBookmarkResolutionWithoutUIMask = (1 << 8), kCFBookmarkResolutionWithoutMountingMask = (1 << 9) }; /** \} */ /** \name Common File System Resource Keys \{ */ CF_EXPORT const CFStringRef kCFURLNameKey; CF_EXPORT const CFStringRef kCFURLLocalizedNameKey; CF_EXPORT const CFStringRef kCFURLIsRegularFileKey; CF_EXPORT const CFStringRef kCFURLIsDirectoryKey; CF_EXPORT const CFStringRef kCFURLIsSymbolicLinkKey; CF_EXPORT const CFStringRef kCFURLIsVolumeKey; CF_EXPORT const CFStringRef kCFURLIsPackageKey; CF_EXPORT const CFStringRef kCFURLIsSystemImmutableKey; CF_EXPORT const CFStringRef kCFURLIsUserImmutableKey; CF_EXPORT const CFStringRef kCFURLIsHiddenKey; CF_EXPORT const CFStringRef kCFURLHasHiddenExtensionKey; CF_EXPORT const CFStringRef kCFURLCreationDateKey; CF_EXPORT const CFStringRef kCFURLContentAccessDateKey; CF_EXPORT const CFStringRef kCFURLContentModificationDateKey; CF_EXPORT const CFStringRef kCFURLAttributeModificationDateKey; CF_EXPORT const CFStringRef kCFURLLinkCountKey; CF_EXPORT const CFStringRef kCFURLParentDirectoryURLKey; CF_EXPORT const CFStringRef kCFURLVolumeURLKey; CF_EXPORT const CFStringRef kCFURLTypeIdentifierKey; CF_EXPORT const CFStringRef kCFURLLocalizedTypeDescriptionKey; CF_EXPORT const CFStringRef kCFURLLabelNumberKey; CF_EXPORT const CFStringRef kCFURLLabelColorKey; CF_EXPORT const CFStringRef kCFURLLocalizedLabelKey; CF_EXPORT const CFStringRef kCFURLEffectiveIconKey; CF_EXPORT const CFStringRef kCFURLCustomIconKey; #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_7, GS_API_LATEST) CF_EXPORT const CFStringRef kCFURLFileResourceIdentifierKey; CF_EXPORT const CFStringRef kCFURLVolumeIdentifierKey; CF_EXPORT const CFStringRef kCFURLPreferredIOBlockSizeKey; CF_EXPORT const CFStringRef kCFURLIsReadableKey; CF_EXPORT const CFStringRef kCFURLIsWritableKey; CF_EXPORT const CFStringRef kCFURLIsExecutableKey; CF_EXPORT const CFStringRef kCFURLFileSecurityKey; CF_EXPORT const CFStringRef kCFURLFileResourceTypeKey; #endif /** \} */ /** \name File Resource Types \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_7, GS_API_LATEST) CF_EXPORT const CFStringRef kCFURLFileResourceTypeBlockSpecial; CF_EXPORT const CFStringRef kCFURLFileResourceTypeCharacterSpecial; CF_EXPORT const CFStringRef kCFURLFileResourceTypeDirectory; CF_EXPORT const CFStringRef kCFURLFileResourceTypeNamedPipe; CF_EXPORT const CFStringRef kCFURLFileResourceTypeRegular; CF_EXPORT const CFStringRef kCFURLFileResourceTypeSocket; CF_EXPORT const CFStringRef kCFURLFileResourceTypeSymbolicLink; CF_EXPORT const CFStringRef kCFURLFileResourceTypeUnknown; #endif /** \} */ /** \name File Property Keys \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) CF_EXPORT const CFStringRef kCFURLFileAllocatedSizeKey; CF_EXPORT const CFStringRef kCFURLFileSizeKey; CF_EXPORT const CFStringRef kCFURLIsAliasFileKey; #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) CF_EXPORT const CFStringRef kCFURLIsMountTriggerKey; CF_EXPORT const CFStringRef kCFURLTotalFileAllocatedSizeKey; CF_EXPORT const CFStringRef kCFURLTotalFileSizeKey; #endif /** \} */ /** \name Volume Property Keys \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) CF_EXPORT const CFStringRef kCFURLVolumeLocalizedFormatDescriptionKey; CF_EXPORT const CFStringRef kCFURLVolumeTotalCapacityKey; CF_EXPORT const CFStringRef kCFURLVolumeAvailableCapacityKey; CF_EXPORT const CFStringRef kCFURLVolumeResourceCountKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsPersistentIDsKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsSymbolicLinksKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsHardLinksKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsJournalingKey; CF_EXPORT const CFStringRef kCFURLVolumeIsJournalingKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsSparseFilesKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsZeroRunsKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsCaseSensitiveNamesKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsCasePreservedNamesKey; #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_7, GS_API_LATEST) CF_EXPORT const CFStringRef kCFURLVolumeNameKey; CF_EXPORT const CFStringRef kCFURLVolumeLocalizedNameKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsRootDirectoryDatesKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsVolumeSizesKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsRenamingKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsAdvisoryFileLockingKey; CF_EXPORT const CFStringRef kCFURLVolumeSupportsExtendedSecurityKey; CF_EXPORT const CFStringRef kCFURLVolumeIsBrowsableKey; CF_EXPORT const CFStringRef kCFURLVolumeMaximumFileSizeKey; CF_EXPORT const CFStringRef kCFURLVolumeIsEjectableKey; CF_EXPORT const CFStringRef kCFURLVolumeIsRemovableKey; CF_EXPORT const CFStringRef kCFURLVolumeIsInternalKey; CF_EXPORT const CFStringRef kCFURLVolumeIsAutomountedKey; CF_EXPORT const CFStringRef kCFURLVolumeIsLocalKey; CF_EXPORT const CFStringRef kCFURLVolumeIsReadOnlyKey; CF_EXPORT const CFStringRef kCFURLVolumeCreationDateKey; CF_EXPORT const CFStringRef kCFURLVolumeURLForRemountingKey; CF_EXPORT const CFStringRef kCFURLVolumeUUIDStringKey; #endif /** \} */ /** \name CFError userInfo Dictionary Keys \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_7, GS_API_LATEST) CF_EXPORT const CFStringRef kCFURLKeysOfUnsetValuesKey; #endif /** \} */ /** \name Getting the CFURL Type ID \{ */ CF_EXPORT CFTypeID CFURLGetTypeID (void); /** \} */ /** \name Creating a CFURL Object \{ */ CF_EXPORT CFURLRef CFURLCopyAbsoluteURL (CFURLRef relativeURL); #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) CF_EXPORT CFURLRef CFURLCreateAbsoluteURLWithBytes (CFAllocatorRef alloc, const UInt8 * relativeURLBytes, CFIndex length, CFStringEncoding encoding, CFURLRef baseURL, Boolean useCompatibilityMode); #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) CF_EXPORT CFURLRef CFURLCreateByResolvingBookmarkData (CFAllocatorRef alloc, CFDataRef bookmark, CFURLBookmarkResolutionOptions options, CFURLRef relativeToURL, CFArrayRef resourcePropertiesToInclude, Boolean * isStale, CFErrorRef * error); #endif CF_EXPORT CFURLRef CFURLCreateCopyAppendingPathComponent (CFAllocatorRef alloc, CFURLRef url, CFStringRef pathComponent, Boolean isDirectory); CF_EXPORT CFURLRef CFURLCreateCopyAppendingPathExtension (CFAllocatorRef alloc, CFURLRef url, CFStringRef extension); CF_EXPORT CFURLRef CFURLCreateCopyDeletingLastPathComponent (CFAllocatorRef alloc, CFURLRef url); CF_EXPORT CFURLRef CFURLCreateCopyDeletingPathExtension (CFAllocatorRef alloc, CFURLRef url); #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) CF_EXPORT CFURLRef CFURLCreateFilePathURL (CFAllocatorRef allocator, CFURLRef url, CFErrorRef * error); CF_EXPORT CFURLRef CFURLCreateFileReferenceURL (CFAllocatorRef allocator, CFURLRef url, CFErrorRef * error); #endif CF_EXPORT CFURLRef CFURLCreateFromFileSystemRepresentation (CFAllocatorRef alloc, const UInt8 * buffer, CFIndex bufLen, Boolean isDirectory); CF_EXPORT CFURLRef CFURLCreateFromFileSystemRepresentationRelativeToBase (CFAllocatorRef alloc, const UInt8 * buffer, CFIndex bufLen, Boolean isDirectory, CFURLRef baseURL); #if 0 /* No FSRef support */ CF_EXPORT CFURLRef CFURLCreateFromFSRef (CFAllocatorRef alloc, const struct FSRef *fsRef); #endif CF_EXPORT CFURLRef CFURLCreateWithBytes (CFAllocatorRef alloc, const UInt8 * bytes, CFIndex length, CFStringEncoding encoding, CFURLRef baseURL); CF_EXPORT CFURLRef CFURLCreateWithFileSystemPath (CFAllocatorRef allocator, CFStringRef fileSystemPath, CFURLPathStyle style, Boolean isDirectory); CF_EXPORT CFURLRef CFURLCreateWithFileSystemPathRelativeToBase (CFAllocatorRef alloc, CFStringRef filePath, CFURLPathStyle style, Boolean isDirectory, CFURLRef baseURL); CF_EXPORT CFURLRef CFURLCreateWithString (CFAllocatorRef allocator, CFStringRef string, CFURLRef baseURL); /** \} */ /** \name Accessing the Parts of a URL \{ */ CF_EXPORT Boolean CFURLCanBeDecomposed (CFURLRef url); CFStringRef CFURLCopyFileSystemPath (CFURLRef aURL, CFURLPathStyle style); CF_EXPORT CFStringRef CFURLCopyFragment (CFURLRef url, CFStringRef charactersToLeaveEscaped); CF_EXPORT CFStringRef CFURLCopyHostName (CFURLRef url); CF_EXPORT CFStringRef CFURLCopyLastPathComponent (CFURLRef url); CF_EXPORT CFStringRef CFURLCopyNetLocation (CFURLRef url); CF_EXPORT CFStringRef CFURLCopyParameterString (CFURLRef url, CFStringRef charactersToLeaveEscaped); CF_EXPORT CFStringRef CFURLCopyPassword (CFURLRef url); CF_EXPORT CFStringRef CFURLCopyPath (CFURLRef url); CF_EXPORT CFStringRef CFURLCopyPathExtension (CFURLRef url); CF_EXPORT CFStringRef CFURLCopyQueryString (CFURLRef url, CFStringRef charactersToLeaveEscaped); CF_EXPORT CFStringRef CFURLCopyResourceSpecifier (CFURLRef url); CF_EXPORT CFStringRef CFURLCopyScheme (CFURLRef url); CF_EXPORT CFStringRef CFURLCopyStrictPath (CFURLRef url, Boolean * isAbsolute); CF_EXPORT CFStringRef CFURLCopyUserName (CFURLRef url); CF_EXPORT SInt32 CFURLGetPortNumber (CFURLRef url); CF_EXPORT Boolean CFURLHasDirectoryPath (CFURLRef url); /** \} */ /** \name Converting URLs to Other Representations \{ */ CF_EXPORT CFDataRef CFURLCreateData (CFAllocatorRef alloc, CFURLRef url, CFStringEncoding encoding, Boolean escapeWhiteSpace); CF_EXPORT CFStringRef CFURLCreateStringByAddingPercentEscapes (CFAllocatorRef alloc, CFStringRef origString, CFStringRef charactersToLeaveUnescaped, CFStringRef legalURLCharactersToBeEscaped, CFStringEncoding encoding); CF_EXPORT CFStringRef CFURLCreateStringByReplacingPercentEscapes (CFAllocatorRef alloc, CFStringRef origString, CFStringRef charactersToLeaveEscaped); #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) CF_EXPORT CFStringRef CFURLCreateStringByReplacingPercentEscapesUsingEncoding (CFAllocatorRef alloc, CFStringRef origString, CFStringRef charactersToLeaveEscaped, CFStringEncoding encoding); #endif CF_EXPORT Boolean CFURLGetFileSystemRepresentation (CFURLRef url, Boolean resolveAgainstBase, UInt8 * buffer, CFIndex bufLen); #if 0 /* FSRef unsupported */ CF_EXPORT Boolean CFURLGetFSRef (CFURLRef url, struct FSRef *fsRef); #endif CF_EXPORT CFStringRef CFURLGetString (CFURLRef url); /** \} */ /** \name Getting URL Properties \{ */ CF_EXPORT CFURLRef CFURLGetBaseURL (CFURLRef url); #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) CF_EXPORT CFIndex CFURLGetBytes (CFURLRef url, UInt8 * buffer, CFIndex bufLen); CF_EXPORT CFRange CFURLGetByteRangeForComponent (CFURLRef url, CFURLComponentType comp, CFRange * rangeIncludingSeparators); CF_EXPORT Boolean CFURLResourceIsReachable (CFURLRef url, CFErrorRef * error); #endif /** \} */ /** \name Getting and Setting File System Resource Properties \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) CF_EXPORT void CFURLClearResourcePropertyCache (CFURLRef url); CF_EXPORT void CFURLClearResourcePropertyCacheForKey (CFURLRef url, CFStringRef key); CF_EXPORT CFDictionaryRef CFURLCopyResourcePropertiesForKeys (CFURLRef url, CFArrayRef keys, CFErrorRef * error); CF_EXPORT Boolean CFURLCopyResourcePropertyForKey (CFURLRef url, CFStringRef key, void *propertyValueTypeRefPtr, CFErrorRef * error); CF_EXPORT CFDictionaryRef CFURLCreateResourcePropertiesForKeysFromBookmarkData (CFAllocatorRef allocator, CFArrayRef resourcePropertiesToReturn, CFDataRef bookmark); CF_EXPORT CFTypeRef CFURLCreateResourcePropertyForKeyFromBookmarkData (CFAllocatorRef allocator, CFStringRef resourcePropertyKey, CFDataRef bookmark); CF_EXPORT Boolean CFURLSetResourcePropertiesForKeys (CFURLRef url, CFDictionaryRef keyedPropertyValues, CFErrorRef * error); CF_EXPORT Boolean CFURLSetResourcePropertyForKey (CFURLRef url, CFStringRef key, CFTypeRef propertValue, CFErrorRef * error); CF_EXPORT void CFURLSetTemporaryResourcePropertyForKey (CFURLRef url, CFStringRef key, CFTypeRef propertyValue); /** \} */ /** \name Working with Bookmark Data \{ */ CF_EXPORT CFDataRef CFURLCreateBookmarkData (CFAllocatorRef alloc, CFURLRef url, CFURLBookmarkCreationOptions options, CFArrayRef resourcePropertiesToInclude, CFURLRef relativeToURL, CFErrorRef * error); CF_EXPORT CFDataRef CFURLCreateBookmarkDataFromAliasRecord (CFAllocatorRef alloc, CFDataRef aliasRecordDataRef); CF_EXPORT CFDataRef CFURLCreateBookmarkDataFromFile (CFAllocatorRef allocator, CFURLRef fileURL, CFErrorRef * errorRef); CF_EXPORT Boolean CFURLWriteBookmarkDataToFile (CFDataRef bookmarkRef, CFURLRef fileURL, CFURLBookmarkFileCreationOptions options, CFErrorRef * errorRef); #endif /** \} */ /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFURL_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFStringEncodingExt.h0000644000175000017500000001441113222706330024154 0ustar yavoryavor/* CFStringEncodingExt.h Copyright (C) 2009 Stefan Bidigaray Author: Stefan Bidigaray Date: October, 2009 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFSTRINGENCODINGEXT__ #define __COREFOUNDATION_CFSTRINGENCODINGEXT__ 1 #include /* External String Encodings */ enum { kCFStringEncodingMacJapanese = 1, kCFStringEncodingMacChineseTrad = 2, kCFStringEncodingMacKorean = 3, kCFStringEncodingMacArabic = 4, kCFStringEncodingMacHebrew = 5, kCFStringEncodingMacGreek = 6, kCFStringEncodingMacCyrillic = 7, kCFStringEncodingMacDevanagari = 9, kCFStringEncodingMacGurmukhi = 10, kCFStringEncodingMacGujarati = 11, kCFStringEncodingMacOriya = 12, kCFStringEncodingMacBengali = 13, kCFStringEncodingMacTamil = 14, kCFStringEncodingMacTelugu = 15, kCFStringEncodingMacKannada = 16, kCFStringEncodingMacMalayalam = 17, kCFStringEncodingMacSinhalese = 18, kCFStringEncodingMacBurmese = 19, kCFStringEncodingMacKhmer = 20, kCFStringEncodingMacThai = 21, kCFStringEncodingMacLaotian = 22, kCFStringEncodingMacGeorgian = 23, kCFStringEncodingMacArmenian = 24, kCFStringEncodingMacChineseSimp = 25, kCFStringEncodingMacTibetan = 26, kCFStringEncodingMacMongolian = 27, kCFStringEncodingMacEthiopic = 28, kCFStringEncodingMacCentralEurRoman = 29, kCFStringEncodingMacVietnamese = 30, kCFStringEncodingMacExtArabic = 31, kCFStringEncodingMacSymbol = 33, kCFStringEncodingMacDingbats = 34, kCFStringEncodingMacTurkish = 35, kCFStringEncodingMacCroatian = 36, kCFStringEncodingMacIcelandic = 37, kCFStringEncodingMacRomanian = 38, kCFStringEncodingMacCeltic = 39, kCFStringEncodingMacGaelic = 40, kCFStringEncodingMacFarsi = 0x8C, kCFStringEncodingMacUkrainian = 0x98, kCFStringEncodingMacInuit = 0xEC, kCFStringEncodingMacVT100 = 0xFC, kCFStringEncodingMacHFS = 0xFF, kCFStringEncodingISOLatin2 = 0x0202, kCFStringEncodingISOLatin3 = 0x0203, kCFStringEncodingISOLatin4 = 0x0204, kCFStringEncodingISOLatinCyrillic = 0x0205, kCFStringEncodingISOLatinArabic = 0x0206, kCFStringEncodingISOLatinGreek = 0x0207, kCFStringEncodingISOLatinHebrew = 0x0208, kCFStringEncodingISOLatin5 = 0x0209, kCFStringEncodingISOLatin6 = 0x020A, kCFStringEncodingISOLatinThai = 0x020B, kCFStringEncodingISOLatin7 = 0x020D, kCFStringEncodingISOLatin8 = 0x020E, kCFStringEncodingISOLatin9 = 0x020F, kCFStringEncodingISOLatin10 = 0x0210, kCFStringEncodingDOSLatinUS = 0x0400, kCFStringEncodingDOSGreek = 0x0405, kCFStringEncodingDOSBalticRim = 0x0406, kCFStringEncodingDOSLatin1 = 0x0410, kCFStringEncodingDOSGreek1 = 0x0411, kCFStringEncodingDOSLatin2 = 0x0412, kCFStringEncodingDOSCyrillic = 0x0413, kCFStringEncodingDOSTurkish = 0x0414, kCFStringEncodingDOSPortuguese = 0x0415, kCFStringEncodingDOSIcelandic = 0x0416, kCFStringEncodingDOSHebrew = 0x0417, kCFStringEncodingDOSCanadianFrench = 0x0418, kCFStringEncodingDOSArabic = 0x0419, kCFStringEncodingDOSNordic = 0x041A, kCFStringEncodingDOSRussian = 0x041B, kCFStringEncodingDOSGreek2 = 0x041C, kCFStringEncodingDOSThai = 0x041D, kCFStringEncodingDOSJapanese = 0x0420, kCFStringEncodingDOSChineseSimplif = 0x0421, kCFStringEncodingDOSKorean = 0x0422, kCFStringEncodingDOSChineseTrad = 0x0423, kCFStringEncodingWindowsLatin2 = 0x0501, kCFStringEncodingWindowsCyrillic = 0x0502, kCFStringEncodingWindowsGreek = 0x0503, kCFStringEncodingWindowsLatin5 = 0x0504, kCFStringEncodingWindowsHebrew = 0x0505, kCFStringEncodingWindowsArabic = 0x0506, kCFStringEncodingWindowsBalticRim = 0x0507, kCFStringEncodingWindowsVietnamese = 0x0508, kCFStringEncodingWindowsKoreanJohab = 0x0510, kCFStringEncodingANSEL = 0x0601, kCFStringEncodingJIS_X0201_76 = 0x0620, kCFStringEncodingJIS_X0208_83 = 0x0621, kCFStringEncodingJIS_X0208_90 = 0x0622, kCFStringEncodingJIS_X0212_90 = 0x0623, kCFStringEncodingJIS_C6226_78 = 0x0624, kCFStringEncodingShiftJIS_X0213 = 0x0628, kCFStringEncodingShiftJIS_X0213_MenKuTen = 0x0629, kCFStringEncodingGB_2312_80 = 0x0630, kCFStringEncodingGBK_95 = 0x0631, kCFStringEncodingGB_18030_2000 = 0x0632, kCFStringEncodingKSC_5601_87 = 0x0640, kCFStringEncodingKSC_5601_92_Johab = 0x0641, kCFStringEncodingCNS_11643_92_P1 = 0x0651, kCFStringEncodingCNS_11643_92_P2 = 0x0652, kCFStringEncodingCNS_11643_92_P3 = 0x0653, kCFStringEncodingISO_2022_JP = 0x0820, kCFStringEncodingISO_2022_JP_2 = 0x0821, kCFStringEncodingISO_2022_JP_1 = 0x0822, kCFStringEncodingISO_2022_JP_3 = 0x0823, kCFStringEncodingISO_2022_CN = 0x0830, kCFStringEncodingISO_2022_CN_EXT = 0x0831, kCFStringEncodingISO_2022_KR = 0x0840, kCFStringEncodingEUC_JP = 0x0920, kCFStringEncodingEUC_CN = 0x0930, kCFStringEncodingEUC_TW = 0x0931, kCFStringEncodingEUC_KR = 0x0940, kCFStringEncodingShiftJIS = 0x0A01, kCFStringEncodingKOI8_R = 0x0A02, kCFStringEncodingBig5 = 0x0A03, kCFStringEncodingMacRomanLatin1 = 0x0A04, kCFStringEncodingHZ_GB_2312 = 0x0A05, kCFStringEncodingBig5_HKSCS_1999 = 0x0A06, kCFStringEncodingVISCII = 0x0A07, kCFStringEncodingKOI8_U = 0x0A08, kCFStringEncodingBig5_E = 0x0A09, kCFStringEncodingNextStepJapanese = 0x0B02, kCFStringEncodingEBCDIC_US = 0x0C01, kCFStringEncodingEBCDIC_CP037 = 0x0C02, kCFStringEncodingUTF7 = 0x04000100, kCFStringEncodingUTF7_IMAP = 0x0A10, #if MAC_OS_X_VERSION_MIN_ALLOWED <= MAC_OS_X_VERSION_10_2 kCFStringEncodingShiftJIS_X0213_00 = 0x0628 /* Deprecated */ #endif }; #endif /* __COREFOUNDATION_CFSTRINGENCODINGEXT__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFByteOrder.h0000644000175000017500000001502713222706330022461 0ustar yavoryavor/* CFByteOrder.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Eric Wasylishen Date: June, 2010 Most of the code here was copied from NSByteOrder.h in GNUstep-base written by Richard Frith-Macdonald. This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFBYTEORDER_H__ #define __COREFOUNDATION_CFBYTEORDER_H__ 1 #include /** \defgroup CFByteOrderUtils Byte Order Utilities \brief \{ */ /** \name Byte Order Flags \{ Flags that identify the system's byte order. */ typedef enum { CFByteOrderUnknown, /**< Unknown byte order. */ CFByteOrderLittleEndian, /**< Specifies that multi-byte values are stored least-significant byte first. */ CFByteOrderBigEndian /**< Specifies that multi-byte values are stored most-significant byte first. */ } CFByteOrder; /** \} */ typedef UInt32 CFSwappedFloat32; /* Same as GNUstep NSSwappedFloat */ typedef UInt64 CFSwappedFloat64; /* Same as GNUstep NSSwappedDouble */ /** \name Host System Information \{ */ /** Find the byte order of the host computer. \return The byte order of the host system. \see CFByteOrder */ CF_INLINE CFByteOrder CFByteOrderGetCurrent() { #if __BIG_ENDIAN__ return CFByteOrderBigEndian; #else return CFByteOrderLittleEndian; #endif } /** \} */ CF_INLINE UInt16 CFSwapInt16(UInt16 in) { union swap { UInt16 num; UInt8 byt[2]; } dst; union swap *src = (union swap*)∈ dst.byt[0] = src->byt[1]; dst.byt[1] = src->byt[0]; return dst.num; } CF_INLINE UInt32 CFSwapInt32(UInt32 in) { union swap { UInt32 num; UInt8 byt[4]; } dst; union swap *src = (union swap*)∈ dst.byt[0] = src->byt[3]; dst.byt[1] = src->byt[2]; dst.byt[2] = src->byt[1]; dst.byt[3] = src->byt[0]; return dst.num; } CF_INLINE UInt64 CFSwapInt64(UInt64 in) { union swap { UInt64 num; UInt8 byt[8]; } dst; union swap *src = (union swap*)∈ dst.byt[0] = src->byt[7]; dst.byt[1] = src->byt[6]; dst.byt[2] = src->byt[5]; dst.byt[3] = src->byt[4]; dst.byt[4] = src->byt[3]; dst.byt[5] = src->byt[2]; dst.byt[6] = src->byt[1]; dst.byt[7] = src->byt[0]; return dst.num; } #if __BIG_ENDIAN__ CF_INLINE UInt16 CFSwapInt16BigToHost(UInt16 in) { return in; } CF_INLINE UInt16 CFSwapInt16HostToBig(UInt16 in) { return in; } CF_INLINE UInt16 CFSwapInt16HostToLittle(UInt16 in) { return CFSwapInt16(in); } CF_INLINE UInt16 CFSwapInt16LittleToHost(UInt16 in) { return CFSwapInt16(in); } CF_INLINE UInt32 CFSwapInt32BigToHost(UInt32 in) { return in; } CF_INLINE UInt32 CFSwapInt32HostToBig(UInt32 in) { return in; } CF_INLINE UInt32 CFSwapInt32HostToLittle(UInt32 in) { return CFSwapInt32(in); } CF_INLINE UInt32 CFSwapInt32LittleToHost(UInt32 in) { return CFSwapInt32(in); } CF_INLINE UInt64 CFSwapInt64BigToHost(UInt64 in) { return in; } CF_INLINE UInt64 CFSwapInt64HostToBig(UInt64 in) { return in; } CF_INLINE UInt64 CFSwapInt64HostToLittle(UInt64 in) { return CFSwapInt64(in); } CF_INLINE UInt64 CFSwapInt64LittleToHost(UInt64 in) { return CFSwapInt64(in); } #else CF_INLINE UInt16 CFSwapInt16BigToHost(UInt16 in) { return CFSwapInt16(in); } CF_INLINE UInt16 CFSwapInt16HostToBig(UInt16 in) { return CFSwapInt16(in); } CF_INLINE UInt16 CFSwapInt16HostToLittle(UInt16 in) { return in; } CF_INLINE UInt16 CFSwapInt16LittleToHost(UInt16 in) { return in; } CF_INLINE UInt32 CFSwapInt32BigToHost(UInt32 in) { return CFSwapInt32(in); } CF_INLINE UInt32 CFSwapInt32HostToBig(UInt32 in) { return CFSwapInt32(in); } CF_INLINE UInt32 CFSwapInt32HostToLittle(UInt32 in) { return in; } CF_INLINE UInt32 CFSwapInt32LittleToHost(UInt32 in) { return in; } CF_INLINE UInt64 CFSwapInt64BigToHost(UInt64 in) { return CFSwapInt64(in); } CF_INLINE UInt64 CFSwapInt64HostToBig(UInt64 in) { return CFSwapInt64(in); } CF_INLINE UInt64 CFSwapInt64HostToLittle(UInt64 in) { return in; } CF_INLINE UInt64 CFSwapInt64LittleToHost(UInt64 in) { return in; } #endif union dconv { double d; Float64 num; CFSwappedFloat64 sf; }; union fconv { float f; Float32 num; CFSwappedFloat32 sf; }; /** \name Floating Point Function \{ */ CF_INLINE CFSwappedFloat64 CFConvertFloat64HostToSwapped (Float64 in) { union dconv conv; conv.num = in; return CFSwapInt64 (conv.sf); } CF_INLINE Float64 CFConvertFloat64SwappedToHost (CFSwappedFloat64 in) { union dconv conv; conv.sf = CFSwapInt64 (in); return conv.num; } CF_INLINE CFSwappedFloat64 CFConvertDoubleHostToSwapped (double in) { union dconv conv; conv.d = in; return CFSwapInt64 (conv.sf); } CF_INLINE double CFConvertDoubleSwappedToHost(CFSwappedFloat64 in) { union dconv conv; conv.sf = CFSwapInt64 (in); return conv.d; } CF_INLINE CFSwappedFloat32 CFConvertFloat32HostToSwapped(Float32 in) { union fconv conv; conv.num = in; return CFSwapInt32 (conv.sf); } CF_INLINE Float32 CFConvertFloat32SwappedToHost(CFSwappedFloat32 in) { union fconv conv; conv.sf = CFSwapInt32 (in); return conv.num; } CF_INLINE CFSwappedFloat32 CFConvertFloatHostToSwapped(float in) { union fconv conv; conv.f = in; return CFSwapInt32 (conv.sf); } CF_INLINE float CFConvertFloatSwappedToHost(CFSwappedFloat32 in) { union fconv conv; conv.sf = CFSwapInt32 (in); return conv.f; } /** \} */ /** \} */ #endif /* __COREFOUNDATION_CFBYTEORDER_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFArray.h0000644000175000017500000001336513222706330021643 0ustar yavoryavor/* CFArray.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of CoreBase. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFARRAY_H__ #define __COREFOUNDATION_CFARRAY_H__ #include CF_EXTERN_C_BEGIN /** \ingroup CFArrayRef \brief Reference to an immutable array object. */ typedef const struct __CFArray *CFArrayRef; /** \ingroup CFMutableArrayRef \brief Reference to a mutable array object. */ typedef struct __CFArray *CFMutableArrayRef; /** \defgroup CFArrayRef CFArray Reference \brief A CFArray and its mutable type, \ref CFMutableArrayRef "CFMutableArray", are simple, low overhead, ordered containers for objects. \details \#include \{ */ /** \name Callbacks \{ */ typedef void (*CFArrayApplierFunction) (const void *value, void *context); typedef CFStringRef (*CFArrayCopyDescriptionCallBack) (const void *value); typedef void (*CFArrayReleaseCallBack) (CFAllocatorRef allocator, const void *value); typedef const void *(*CFArrayRetainCallBack) (CFAllocatorRef allocator, const void *value); typedef Boolean (*CFArrayEqualCallBack) (const void *value1, const void *value2); /** \} */ /** \brief Structure with CFArray callbacks. */ typedef struct _CFArrayCallBacks CFArrayCallBacks; struct _CFArrayCallBacks { CFIndex version; /**< Structure's version number. Current version is 0. */ CFArrayRetainCallBack retain; /**< The callback used to retain values added to the array. If NULL, values are not retained. */ CFArrayReleaseCallBack release; CFArrayCopyDescriptionCallBack copyDescription; CFArrayEqualCallBack equal; }; /** \name Predefined Callback Structures \{ */ CF_EXPORT const CFArrayCallBacks kCFTypeArrayCallBacks; /** \} */ /** \name Creating an Array \{ */ CF_EXPORT CFArrayRef CFArrayCreate (CFAllocatorRef allocator, const void **values, CFIndex numValues, const CFArrayCallBacks * callBacks); CF_EXPORT CFArrayRef CFArrayCreateCopy (CFAllocatorRef allocator, CFArrayRef theArray); /** \} */ /** \name Examining an Array \{ */ CF_EXPORT CFIndex CFArrayBSearchValues (CFArrayRef theArray, CFRange range, const void *value, CFComparatorFunction comparator, void *context); CF_EXPORT Boolean CFArrayContainsValue (CFArrayRef theArray, CFRange range, const void *value); CF_EXPORT CFIndex CFArrayGetCount (CFArrayRef theArray); CF_EXPORT CFIndex CFArrayGetCountOfValue (CFArrayRef theArray, CFRange range, const void *value); CF_EXPORT CFIndex CFArrayGetFirstIndexOfValue (CFArrayRef theArray, CFRange range, const void *value); CF_EXPORT CFIndex CFArrayGetLastIndexOfValue (CFArrayRef theArray, CFRange range, const void *value); CF_EXPORT void CFArrayGetValues (CFArrayRef theArray, CFRange range, const void **values); CF_EXPORT const void *CFArrayGetValueAtIndex (CFArrayRef theArray, CFIndex idx); /** \} */ /** \name Applying a Function to Elements \{ */ CF_EXPORT void CFArrayApplyFunction (CFArrayRef theArray, CFRange range, CFArrayApplierFunction applier, void *context); /** \} */ /** \name Getting the CFArray Type ID \{ */ CF_EXPORT CFTypeID CFArrayGetTypeID (void); /** \} */ /** \} */ /** \defgroup CFMutableArrayRef CFMutableArray Reference \details \#include \{ */ CF_EXPORT void CFArrayAppendArray (CFMutableArrayRef theArray, CFArrayRef otherArray, CFRange otherRange); CF_EXPORT void CFArrayAppendValue (CFMutableArrayRef theArray, const void *value); CF_EXPORT CFMutableArrayRef CFArrayCreateMutable (CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks * callBacks); CF_EXPORT CFMutableArrayRef CFArrayCreateMutableCopy (CFAllocatorRef allocator, CFIndex capacity, CFArrayRef theArray); CF_EXPORT void CFArrayExchangeValuesAtIndices (CFMutableArrayRef theArray, CFIndex idx1, CFIndex idx2); CF_EXPORT void CFArrayInsertValueAtIndex (CFMutableArrayRef theArray, CFIndex idx, const void *value); CF_EXPORT void CFArrayRemoveAllValues (CFMutableArrayRef theArray); CF_EXPORT void CFArrayRemoveValueAtIndex (CFMutableArrayRef theArray, CFIndex idx); CF_EXPORT void CFArrayReplaceValues (CFMutableArrayRef theArray, CFRange range, const void **newValues, CFIndex newCount); CF_EXPORT void CFArraySetValueAtIndex (CFMutableArrayRef theArray, CFIndex idx, const void *value); CF_EXPORT void CFArraySortValues (CFMutableArrayRef theArray, CFRange range, CFComparatorFunction comparator, void *context); /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFARRAY_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFTree.h0000644000175000017500000000641513222706330021462 0ustar yavoryavor/* CFTree.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __CFCOREFOUNDATION_CFTREE_H__ #define __CFCOREFOUNDATION_CFTREE_H__ #include CF_EXTERN_C_BEGIN /** \defgroup CFTreeRef CFTree Reference \{ */ typedef struct __CFTree *CFTreeRef; typedef void (*CFTreeApplierFunction) (const void *value, void *context); typedef const void *(*CFTreeRetainCallBack) (const void *info); typedef void (*CFTreeReleaseCallBack) (const void *info); typedef CFStringRef (*CFTreeCopyDescriptionCallBack) (const void *info); typedef struct _CFTreeContext CFTreeContext; struct _CFTreeContext { CFIndex version; void *info; CFTreeRetainCallBack retain; CFTreeReleaseCallBack release; CFTreeCopyDescriptionCallBack copyDescription; }; /** \name Creating Trees \{ */ CF_EXPORT CFTreeRef CFTreeCreate (CFAllocatorRef allocator, const CFTreeContext *context); /** \} */ /** \name Modifying a Tree \{ */ CF_EXPORT void CFTreeAppendChild (CFTreeRef tree, CFTreeRef newChild); CF_EXPORT void CFTreeInsertSibling (CFTreeRef tree, CFTreeRef newSibling); CF_EXPORT void CFTreeRemoveAllChildren (CFTreeRef tree); CF_EXPORT void CFTreePrependChild (CFTreeRef tree, CFTreeRef newChild); CF_EXPORT void CFTreeRemove (CFTreeRef tree); CF_EXPORT void CFTreeSetContext (CFTreeRef tree, const CFTreeContext *context); /** \} */ /** \name Sorting a Tree \{ */ CF_EXPORT void CFTreeSortChildren (CFTreeRef tree, CFComparatorFunction comp, void *context); /** \} */ /** \name Examining a Tree \{ */ CF_EXPORT CFTreeRef CFTreeFindRoot (CFTreeRef tree); CF_EXPORT CFTreeRef CFTreeGetChildAtIndex (CFTreeRef tree, CFIndex idx); CF_EXPORT CFIndex CFTreeGetChildCount (CFTreeRef tree); CF_EXPORT void CFTreeGetChildren (CFTreeRef tree, CFTreeRef *children); CF_EXPORT void CFTreeGetContext (CFTreeRef tree, CFTreeContext *context); CF_EXPORT CFTreeRef CFTreeGetFirstChild (CFTreeRef tree); CF_EXPORT CFTreeRef CFTreeGetNextSibling (CFTreeRef tree); CF_EXPORT CFTreeRef CFTreeGetParent (CFTreeRef tree); /** \} */ /** \name Performing an Operation on Tree Elements \{ */ CF_EXPORT void CFTreeApplyFunctionToChildren (CFTreeRef tree, CFTreeApplierFunction applier, void *context); /** \} */ /** \name Getting the Tree Type ID \{ */ CF_EXPORT CFTypeID CFTreeGetTypeID (void); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* __CFCOREFOUNDATION_CFTREE_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFURLAccess.h0000644000175000017500000000565713222706330022356 0ustar yavoryavor/* CFURLAccess.h Copyright (C) 2012 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: April, 2012 This file is part of CoreBase. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFURLACCESS__ #define __COREFOUNDATION_CFURLACCESS__ #include #include #include CF_EXTERN_C_BEGIN /** \defgroup CFURLAccessUtils URL Access Utilities (deprecated) \{ */ /** \name File URL Properties \{ */ CF_EXPORT const CFStringRef kCFURLFileExists; /* CFBoolean */ CF_EXPORT const CFStringRef kCFURLFileDirectoryContents; /* CFArray */ CF_EXPORT const CFStringRef kCFURLFileLength; /* CFNumber */ CF_EXPORT const CFStringRef kCFURLFileLastModificationTime; /* CFDate */ CF_EXPORT const CFStringRef kCFURLFilePOSIXMode; /* CFNumber */ CF_EXPORT const CFStringRef kCFURLFileOwnerID; /* CFNumber */ /** \} */ /** \name HTTP URL Properties \{ */ CF_EXPORT const CFStringRef kCFURLHTTPStatusCode; /*CFNumber */ CF_EXPORT const CFStringRef kCFURLHTTPStatusLine; /* CFString */ /** \} */ /** \name Error Codes \{ */ typedef enum { kCFURLUnknownError = -10, kCFURLUnknownSchemeError = -11, kCFURLResourceNotFoundError = -12, kCFURLResourceAccessViolationError = -13, kCFURLRemoteHostUnavailableError = -14, kCFURLImproperArgumentsError = -15, kCFURLUnknownPropertyKeyError = -16, kCFURLPropertyKeyUnavailableError = -17, kCFURLTimeoutError = -18 } CFURLError; /** \} */ CF_EXPORT Boolean CFURLCreateDataAndPropertiesFromResource (CFAllocatorRef alloc, CFURLRef url, CFDataRef *resourceData, CFDictionaryRef *properties, CFArrayRef desiredProperties, SInt32 *errorCode); CF_EXPORT CFTypeRef CFURLCreatePropertyFromResource (CFAllocatorRef alloc, CFURLRef url, CFStringRef property, SInt32 *errorCode); CF_EXPORT Boolean CFURLDestroyResource (CFURLRef url, SInt32 *errorCode); CF_EXPORT Boolean CFURLWriteDataAndPropertiesToResource (CFURLRef url, CFDataRef dataToWrite, CFDictionaryRef propertiesToWrite, SInt32 *errorCode); /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFURLACCESS__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFBinaryHeap.h0000644000175000017500000000702013222706330022576 0ustar yavoryavor/* CFBinaryHeap.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFBINARYHEAP_H__ #define __COREFOUNDATION_CFBINARYHEAP_H__ #include CF_EXTERN_C_BEGIN /** \defgroup CFBinaryHeapRef CFBinaryHeap Reference \{ */ typedef struct __CFBinaryHeap *CFBinaryHeapRef; typedef void (*CFBinaryHeapApplierFunction) (const void *val, void *context); typedef const void *(*CFBinaryHeapRetainCallBack) (CFAllocatorRef allocator, const void *ptr); typedef void (*CFBinaryHeapReleaseCallBack) (CFAllocatorRef allocator, const void *ptr); typedef CFStringRef (*CFBinaryHeapCopyDescriptionCallBack) (const void *ptr); typedef CFComparisonResult (*CFBinaryHeapCompareCallBack) (const void *ptr1, const void *ptr2, void *info); typedef struct CFBinaryHeapCallBacks CFBinaryHeapCallBacks; struct CFBinaryHeapCallBacks { CFIndex version; CFBinaryHeapRetainCallBack retain; CFBinaryHeapReleaseCallBack release; CFAllocatorCopyDescriptionCallBack copyDescription; CFBinaryHeapCompareCallBack compare; }; typedef struct CFBinaryHeapCompareContext CFBinaryHeapCompareContext; struct CFBinaryHeapCompareContext { CFIndex version; void *info; CFAllocatorRetainCallBack retain; CFAllocatorReleaseCallBack release; CFAllocatorCopyDescriptionCallBack copyDescription; }; CF_EXPORT const CFBinaryHeapCallBacks kCFStringBinaryHeapCallBacks; CF_EXPORT CFBinaryHeapRef CFBinaryHeapCreate (CFAllocatorRef allocator, CFIndex capacity, const CFBinaryHeapCallBacks *callBacks, const CFBinaryHeapCompareContext *compareContext); CF_EXPORT CFBinaryHeapRef CFBinaryHeapCreateCopy (CFAllocatorRef allocator, CFIndex capacity, CFBinaryHeapRef heap); CF_EXPORT void CFBinaryHeapAddValue (CFBinaryHeapRef heap, const void *value); CF_EXPORT void CFBinaryHeapApplyFunction (CFBinaryHeapRef heap, CFBinaryHeapApplierFunction applier, void *context); CF_EXPORT Boolean CFBinaryHeapContainsValue (CFBinaryHeapRef heap, const void *value); CF_EXPORT CFIndex CFBinaryHeapGetCount (CFBinaryHeapRef heap); CF_EXPORT CFIndex CFBinaryHeapGetCountOfValue (CFBinaryHeapRef heap, const void *value); CF_EXPORT const void * CFBinaryHeapGetMinimum (CFBinaryHeapRef heap); CF_EXPORT Boolean CFBinaryHeapGetMinimumIfPresent (CFBinaryHeapRef heap, const void **value); CF_EXPORT void CFBinaryHeapGetValues (CFBinaryHeapRef heap, const void **values); CF_EXPORT void CFBinaryHeapRemoveAllValues (CFBinaryHeapRef heap); CF_EXPORT void CFBinaryHeapRemoveMinimumValue (CFBinaryHeapRef heap); CF_EXPORT CFTypeID CFBinaryHeapGetTypeID (void); /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFBINARYHEAP_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFString.h0000644000175000017500000004251113222706330022026 0ustar yavoryavor/* CFString.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of CoreBase. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFSTRING_H__ #define __COREFOUNDATION_CFSTRING_H__ #include #include #include #include #include #include #include CF_EXTERN_C_BEGIN /** \defgroup CFStringRef CFString Reference \brief The CFString type defines opaque objects representing strings. CFString is "toll-free bridged" to NSString. \{ */ /* * Data Types */ typedef UInt32 CFStringEncoding; /* * Constants */ typedef enum { kCFCompareCaseInsensitive = 1, kCFCompareBackwards = 4, kCFCompareAnchored = 8, kCFCompareNonliteral = 16, kCFCompareLocalized = 32, kCFCompareNumerically = 64, #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) kCFCompareDiacriticInsensitive = 128, kCFCompareWidthInsensitive = 256, kCFCompareForcedOrdering = 512 #endif } CFStringCompareFlags; enum CFStringBuiltInEncodings { kCFStringEncodingMacRoman = 0, kCFStringEncodingWindowsLatin1 = 0x0500, kCFStringEncodingISOLatin1 = 0x0201, kCFStringEncodingNextStepLatin = 0x0B01, kCFStringEncodingASCII = 0x0600, kCFStringEncodingUnicode = 0x0100, kCFStringEncodingUTF8 = 0x08000100, kCFStringEncodingNonLossyASCII = 0x0BFF, #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) kCFStringEncodingUTF16 = 0x0100, kCFStringEncodingUTF16BE = 0x10000100, kCFStringEncodingUTF16LE = 0x14000100, kCFStringEncodingUTF32 = 0x0c000100, kCFStringEncodingUTF32BE = 0x18000100, kCFStringEncodingUTF32LE = 0x1c000100 #endif }; #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) # define kCFStringEncodingInvalidId (0xffffffffU) #endif /** \def CFSTR(x) \brief Creates a constant string object. \note This macro will create the constant string at runtime. */ /* The 'pure' attribute tells the compiler that this function will always return the same result with the same input. If it has any skill, then constant propagation passes will magically make sure that this function is called as few times as possible. */ CF_EXPORT CFStringRef __CFStringMakeConstantString (const char *str) GS_PURE_FUNCTION; #define CFSTR(x) __CFStringMakeConstantString("" x "") /** \name Creating a CFString \{ */ CF_EXPORT CFArrayRef CFStringCreateArrayBySeparatingStrings (CFAllocatorRef alloc, CFStringRef theString, CFStringRef separatorString); CF_EXPORT CFStringRef CFStringCreateByCombiningStrings (CFAllocatorRef alloc, CFArrayRef theArray, CFStringRef separatorString); CF_EXPORT CFStringRef CFStringCreateCopy (CFAllocatorRef alloc, CFStringRef theString); CF_EXPORT CFStringRef CFStringCreateFromExternalRepresentation (CFAllocatorRef alloc, CFDataRef data, CFStringEncoding encoding); CF_EXPORT CFStringRef CFStringCreateWithBytes (CFAllocatorRef alloc, const UInt8 *bytes, CFIndex numBytes, CFStringEncoding encoding, Boolean isExternalRepresentation); CF_EXPORT CFStringRef CFStringCreateWithCharacters (CFAllocatorRef alloc, const UniChar *chars, CFIndex numChars); CF_EXPORT CFStringRef CFStringCreateWithCharactersNoCopy (CFAllocatorRef alloc, const UniChar *chars, CFIndex numChars, CFAllocatorRef contentsDeallocator); CF_EXPORT CFStringRef CFStringCreateWithCString (CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding); CF_EXPORT CFStringRef CFStringCreateWithCStringNoCopy (CFAllocatorRef alloc, const char *cStr, CFStringEncoding encoding, CFAllocatorRef contentsDeallocator); CF_EXPORT CFStringRef CFStringCreateWithFormat (CFAllocatorRef alloc, CFDictionaryRef formatOptions, CFStringRef format, ...); CF_EXPORT CFStringRef CFStringCreateWithFormatAndArguments (CFAllocatorRef alloc, CFDictionaryRef formatOptions, CFStringRef format, va_list arguments); CF_EXPORT CFStringRef CFStringCreateWithSubstring (CFAllocatorRef alloc, CFStringRef str, CFRange range); #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXPORT CFStringRef CFStringCreateWithFileSystemRepresentation (CFAllocatorRef alloc, const char *buffer); #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT CFStringRef CFStringCreateWithBytesNoCopy (CFAllocatorRef alloc, const UInt8 *bytes, CFIndex numBytes, CFStringEncoding encoding, Boolean isExternalReprentation, CFAllocatorRef contentsDeallocator); #endif /** \} */ /** \name Searching CFStrings \{ */ CF_EXPORT CFArrayRef CFStringCreateArrayWithFindResults (CFAllocatorRef alloc, CFStringRef theString, CFStringRef stringToFind, CFRange rangeToSearch, CFStringCompareFlags compareOptions); CF_EXPORT CFRange CFStringFind (CFStringRef theString, CFStringRef stringToFind, CFStringCompareFlags compareOptions); CF_EXPORT Boolean CFStringFindWithOptions (CFStringRef theString, CFStringRef stringToFind, CFRange rangeToSearch, CFStringCompareFlags searchOptions, CFRange *result); CF_EXPORT Boolean CFStringFindWithOptionsAndLocale (CFStringRef theString,CFStringRef stringToFind, CFRange rangeToSearch, CFStringCompareFlags searchOptions, CFLocaleRef locale, CFRange *result); CF_EXPORT void CFStringGetLineBounds (CFStringRef theString, CFRange range, CFIndex *lineBeginIndex, CFIndex *lineEndIndex, CFIndex *contentsEndIndex); #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) CF_EXPORT Boolean CFStringFindCharacterFromSet (CFStringRef theString, CFCharacterSetRef theSet, CFRange rangeToSearch, CFStringCompareFlags searchOptions, CFRange *result); #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT void CFStringGetParagraphBounds (CFStringRef string, CFRange range, CFIndex *parBeginIndex, CFIndex *parEndIndex, CFIndex *contentsEndIndex); #endif /** \} */ /** \name Comparing String \{ */ CF_EXPORT CFComparisonResult CFStringCompare (CFStringRef theString1, CFStringRef theString2, CFStringCompareFlags compareOptions); CF_EXPORT CFComparisonResult CFStringCompareWithOptions (CFStringRef theString1, CFStringRef theString2, CFRange rangeToCOmpare, CFStringCompareFlags compareOptions); CF_EXPORT Boolean CFStringHasPrefix (CFStringRef theString, CFStringRef prefix); CF_EXPORT Boolean CFStringHasSuffix (CFStringRef theString, CFStringRef suffix); #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT CFComparisonResult CFStringCompareWithOptionsAndLocale (CFStringRef theString1, CFStringRef theString2, CFRange rangeToCOmpare, CFStringCompareFlags compareOptions, CFLocaleRef locale); #endif /** \} */ /** \name Accessing Characters \{ */ CF_EXPORT CFDataRef CFStringCreateExternalRepresentation (CFAllocatorRef alloc, CFStringRef theString, CFStringEncoding encoding, UInt8 lossByte); CF_EXPORT CFIndex CFStringGetBytes (CFStringRef theString, CFRange range, CFStringEncoding encoding, UInt8 lossByte, Boolean isExternalRepresentation, UInt8 *buffer, CFIndex maxBufLen, CFIndex *usedBufLen); CF_EXPORT UniChar CFStringGetCharacterAtIndex (CFStringRef theString, CFIndex idx); CF_EXPORT void CFStringGetCharacters (CFStringRef theString, CFRange range, UniChar *buffer); CF_EXPORT const UniChar * CFStringGetCharactersPtr (CFStringRef theString); CF_EXPORT Boolean CFStringGetCString (CFStringRef theString, char *buffer, CFIndex bufferSize, CFStringEncoding encoding); CF_EXPORT const char * CFStringGetCStringPtr (CFStringRef theString, CFStringEncoding encoding); CF_EXPORT CFIndex CFStringGetLength (CFStringRef str); CF_EXPORT CFRange CFStringGetRangeOfComposedCharactersAtIndex (CFStringRef theString, CFIndex theIndex); #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) CF_EXPORT UTF32Char CFStringGetLongCharacterForSurrogatePair (UniChar surrogateHigh, UniChar surrogateLow); CF_EXPORT Boolean CFStringGetSurrogatePairForLongCharacter (UTF32Char character, UniChar *surrogates); CF_EXPORT Boolean CFStringIsSurrogateHighCharacter (UniChar character); CF_EXPORT Boolean CFStringIsSurrogateLowCharacter (UniChar character); #endif /** \} */ /** \name Working with Encodings \{ */ CF_EXPORT CFStringRef CFStringConvertEncodingToIANACharSetName (CFStringEncoding encoding); CF_EXPORT unsigned long CFStringConvertEncodingToNSStringEncoding (CFStringEncoding encoding); UInt32 CFStringConvertEncodingToWindowsCodepage (CFStringEncoding encoding); CF_EXPORT CFStringEncoding CFStringConvertIANACharSetNameToEncoding (CFStringRef theString); CF_EXPORT CFStringEncoding CFStringConvertNSStringEncodingToEncoding (unsigned long encoding); CF_EXPORT CFStringEncoding CFStringConvertWindowsCodepageToEncoding (UInt32 codepage); CF_EXPORT CFStringEncoding CFStringGetFastestEncoding (CFStringRef theString); CF_EXPORT const CFStringEncoding * CFStringGetListOfAvailableEncodings (void); CF_EXPORT CFIndex CFStringGetMaximumSizeForEncoding (CFIndex length, CFStringEncoding encoding); CF_EXPORT CFStringEncoding CFStringGetMostCompatibleMacStringEncoding (CFStringEncoding encoding); CF_EXPORT CFStringRef CFStringGetNameOfEncoding (CFStringEncoding encoding); CF_EXPORT CFStringEncoding CFStringGetSmallestEncoding (CFStringRef theString); CF_EXPORT CFStringEncoding CFStringGetSystemEncoding (void); CF_EXPORT Boolean CFStringIsEncodingAvailable (CFStringEncoding encoding); #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXPORT Boolean CFStringGetFileSystemRepresentation (CFStringRef string, char *buffer, CFIndex maxBufLen); CF_EXPORT CFIndex CFStringGetMaximumSizeOfFileSystemRepresentation (CFStringRef string); #endif /** \} */ /** \name Getting Numeric Values \{ */ CF_EXPORT double CFStringGetDoubleValue (CFStringRef str); CF_EXPORT SInt32 CFStringGetIntValue (CFStringRef str); /** \} */ /** \name Getting String Properties \{ */ CF_EXPORT void CFShow (CFTypeRef obj); CF_EXPORT void CFShowStr (CFStringRef str); CF_EXPORT CFTypeID CFStringGetTypeID (void); /** \} */ /** \name Pascal Strings \{ */ CF_EXPORT CFStringRef CFStringCreateWithPascalString (CFAllocatorRef alloc, ConstStr255Param pStr, CFStringEncoding encoding); CF_EXPORT CFStringRef CFStringCreateWithPascalStringNoCopy (CFAllocatorRef alloc, ConstStr255Param pStr, CFStringEncoding encoding, CFAllocatorRef contentsDeallocate); CF_EXPORT Boolean CFStringGetPascalString (CFStringRef theString, StringPtr buffer, CFIndex bufferSize, CFStringEncoding encoding); CF_EXPORT ConstStringPtr CFStringGetPascalStringPtr (CFStringRef theString, CFStringEncoding encoding); /** \} */ /** \} */ /** \defgroup CFMutableStringRef CFMutableString Reference * \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) typedef enum { kCFStringNormalizationFormD = 0, kCFStringNormalizationFormKD = 1, kCFStringNormalizationFormC = 2, kCFStringNormalizationFormKC = 3 } CFStringNormalizationForm; #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXPORT const CFStringRef kCFStringTransformStripCombiningMarks; CF_EXPORT const CFStringRef kCFStringTransformToLatin; CF_EXPORT const CFStringRef kCFStringTransformFullwidthHalfwidth; CF_EXPORT const CFStringRef kCFStringTransformLatinKatakana; CF_EXPORT const CFStringRef kCFStringTransformLatinHiragana; CF_EXPORT const CFStringRef kCFStringTransformHiraganaKatakana; CF_EXPORT const CFStringRef kCFStringTransformMandarinLatin; CF_EXPORT const CFStringRef kCFStringTransformLatinHangul; CF_EXPORT const CFStringRef kCFStringTransformLatinArabic; CF_EXPORT const CFStringRef kCFStringTransformLatinHebrew; CF_EXPORT const CFStringRef kCFStringTransformLatinThai; CF_EXPORT const CFStringRef kCFStringTransformLatinCyrillic; CF_EXPORT const CFStringRef kCFStringTransformLatinGreek; CF_EXPORT const CFStringRef kCFStringTransformToXMLHex; CF_EXPORT const CFStringRef kCFStringTransformToUnicodeName; #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT const CFStringRef kCFStringTransformStripDiacritics; #endif CF_EXPORT void CFStringAppend (CFMutableStringRef theString, CFStringRef appendedString); CF_EXPORT void CFStringAppendCharacters (CFMutableStringRef theString, const UniChar *chars, CFIndex numChars); CF_EXPORT void CFStringAppendCString (CFMutableStringRef theString, const char *cStr, CFStringEncoding encoding); CF_EXPORT void CFStringAppendFormat (CFMutableStringRef theString, CFDictionaryRef formatOptions, CFStringRef format, ...); CF_EXPORT void CFStringAppendFormatAndArguments (CFMutableStringRef theString, CFDictionaryRef formatOptions, CFStringRef format, va_list arguments); CF_EXPORT void CFStringAppendPascalString (CFMutableStringRef theString, ConstStr255Param pStr, CFStringEncoding encoding); CF_EXPORT void CFStringCapitalize (CFMutableStringRef theString, CFLocaleRef locale); CF_EXPORT CFMutableStringRef CFStringCreateMutable (CFAllocatorRef alloc, CFIndex maxLength); CF_EXPORT CFMutableStringRef CFStringCreateMutableCopy (CFAllocatorRef alloc, CFIndex maxLength, CFStringRef theString); CF_EXPORT CFMutableStringRef CFStringCreateMutableWithExternalCharactersNoCopy (CFAllocatorRef alloc, UniChar *chars, CFIndex numChars, CFIndex capacity, CFAllocatorRef externalCharactersAllocator); CF_EXPORT void CFStringDelete (CFMutableStringRef theString, CFRange range); CF_EXPORT void CFStringInsert (CFMutableStringRef str, CFIndex idx, CFStringRef insertedStr); CF_EXPORT void CFStringLowercase (CFMutableStringRef theString, CFLocaleRef locale); CF_EXPORT void CFStringPad (CFMutableStringRef theString, CFStringRef padString, CFIndex length, CFIndex indexIntoPad); CF_EXPORT void CFStringReplace (CFMutableStringRef theString, CFRange range, CFStringRef replacement); CF_EXPORT void CFStringReplaceAll (CFMutableStringRef theString, CFStringRef replacement); CF_EXPORT void CFStringSetExternalCharactersNoCopy (CFMutableStringRef theString, UniChar *chars, CFIndex length, CFIndex capacity); CF_EXPORT void CFStringTrim (CFMutableStringRef theString, CFStringRef trimString); CF_EXPORT void CFStringTrimWhitespace (CFMutableStringRef theString); CF_EXPORT void CFStringUppercase (CFMutableStringRef theString, CFLocaleRef locale); #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) CF_EXPORT CFIndex CFStringFindAndReplace (CFMutableStringRef theString, CFStringRef stringToFind, CFStringRef replacementString, CFRange rangeToSearch, CFOptionFlags compareOptions); CF_EXPORT void CFStringNormalize (CFMutableStringRef theString, CFStringNormalizationForm theForm); #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXPORT Boolean CFStringTransform (CFMutableStringRef string, CFRange *range, CFStringRef transform, Boolean reverse); #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT void CFStringFold (CFMutableStringRef theString, CFOptionFlags theFlags, CFLocaleRef theLocale); #endif /** \} */ /** \ingroup CFStringRef \name CFStringInlineBuffer \{ */ #define __kCFStringInlineBufferLength 64 struct CFStringInlineBuffer { UniChar buffer[__kCFStringInlineBufferLength]; CFStringRef theString; const UniChar *directBuffer; CFRange rangeToBuffer; CFIndex bufferedRangeStart; CFIndex bufferedRangeEnd; }; typedef struct CFStringInlineBuffer CFStringInlineBuffer; CF_INLINE void CFStringInitInlineBuffer (CFStringRef str, CFStringInlineBuffer *buf, CFRange range) { buf->theString = str; buf->rangeToBuffer = range; buf->directBuffer = CFStringGetCharactersPtr (str); buf->bufferedRangeStart = 0; buf->bufferedRangeEnd = 0; } CF_INLINE UniChar CFStringGetCharacterFromInlineBuffer (CFStringInlineBuffer *buf, CFIndex idx) { if (buf->directBuffer) { if (idx < 0 || idx >= buf->rangeToBuffer.length) return 0; return buf->directBuffer[idx + buf->rangeToBuffer.location]; } else if (idx >= buf->bufferedRangeEnd || idx < buf->bufferedRangeStart) { CFRange range; if (idx < 0 || idx >= buf->rangeToBuffer.length) return 0; /* Use 16 here so it's efficient to go backwards, too */ buf->bufferedRangeStart = idx - 16; if (buf->bufferedRangeStart < 0) buf->bufferedRangeStart = 0; buf->bufferedRangeEnd = buf->bufferedRangeStart + __kCFStringInlineBufferLength; if (buf->bufferedRangeEnd > buf->rangeToBuffer.length) buf->bufferedRangeEnd = buf->rangeToBuffer.length; range = CFRangeMake (buf->rangeToBuffer.location + buf->bufferedRangeStart, buf->bufferedRangeEnd - buf->bufferedRangeStart); CFStringGetCharacters (buf->theString, range, buf->buffer); } return buf->buffer[(idx - buf->bufferedRangeStart)]; } /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFSTRING_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFBitVector.h0000644000175000017500000000657413222706330022472 0ustar yavoryavor/* CFBitVector.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFBITVECTOR_H__ #define __COREFOUNDATION_CFBITVECTOR_H__ #include CF_EXTERN_C_BEGIN /** \ingroup CFBitVectorRef */ typedef const struct __CFBitVector *CFBitVectorRef; /** \ingruop CFMutableBitVectorRef */ typedef struct __CFBitVector *CFMutableBitVectorRef; /** \defgroup CFBitVectorRef CFBitVector Reference \{ */ typedef UInt32 CFBit; /** \name Creating a Bit Vector \{ */ CF_EXPORT CFBitVectorRef CFBitVectorCreate (CFAllocatorRef allocator, const UInt8 *bytes, CFIndex numBits); CF_EXPORT CFBitVectorRef CFBitVectorCreateCopy (CFAllocatorRef allocator, CFBitVectorRef bv); /** \} */ /** \name Getting Information About a Bit Vector \{ */ CF_EXPORT Boolean CFBitVectorContainsBit (CFBitVectorRef bv, CFRange range, CFBit value); CF_EXPORT CFBit CFBitVectorGetBitAtIndex (CFBitVectorRef bv, CFIndex idx); CF_EXPORT void CFBitVectorGetBits (CFBitVectorRef bv, CFRange range, UInt8 *bytes); CF_EXPORT CFIndex CFBitVectorGetCount (CFBitVectorRef bv); CF_EXPORT CFIndex CFBitVectorGetCountOfBit (CFBitVectorRef bv, CFRange range, CFBit value); CF_EXPORT CFIndex CFBitVectorGetFirstIndexOfBit (CFBitVectorRef bv, CFRange range, CFBit value); CF_EXPORT CFIndex CFBitVectorGetLastIndexOfBit (CFBitVectorRef bv, CFRange range, CFBit value); /** \} */ /** \name Getting the CFBitVector Type ID */ CF_EXPORT CFTypeID CFBitVectorGetTypeID (void); /** \} */ /** \} */ /** \defgroup CFMutableBitVectorRef CFMutableBitVector Reference \{ */ /** \name Creating a mutable Bit Vector \{ */ CF_EXPORT CFMutableBitVectorRef CFBitVectorCreateMutable (CFAllocatorRef allocator, CFIndex capacity); CF_EXPORT CFMutableBitVectorRef CFBitVectorCreateMutableCopy (CFAllocatorRef allocator, CFIndex capacity, CFBitVectorRef bv); /** \} */ /** \name Manipulating a Bit Vector \{ */ CF_EXPORT void CFBitVectorFlipBitAtIndex (CFMutableBitVectorRef bv, CFIndex idx); CF_EXPORT void CFBitVectorFlipBits (CFMutableBitVectorRef bv, CFRange range); CF_EXPORT void CFBitVectorSetAllBits (CFMutableBitVectorRef bv, CFBit value); CF_EXPORT void CFBitVectorSetBitAtIndex (CFMutableBitVectorRef bv, CFIndex idx, CFBit value); CF_EXPORT void CFBitVectorSetBits (CFMutableBitVectorRef bv, CFRange range, CFBit value); CF_EXPORT void CFBitVectorSetCount (CFMutableBitVectorRef bv, CFIndex count); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFBITVECTOR_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFData.h0000644000175000017500000000616613222706330021437 0ustar yavoryavor/* CFData.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of CoreBase. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFDATA_H__ #define __COREFOUNDATION_CFDATA_H__ #include CF_EXTERN_C_BEGIN /** \ingroup CFDataRef */ typedef const struct __CFData *CFDataRef; /** \ingroup CFMutableDataRef */ typedef struct __CFData *CFMutableDataRef; /** \defgroup CFDataRef CFData Reference \{ */ /** \name Creating a CFData Object \{ */ CF_EXPORT CFDataRef CFDataCreate (CFAllocatorRef allocator, const UInt8 * bytes, CFIndex length); CF_EXPORT CFDataRef CFDataCreateCopy (CFAllocatorRef allocator, CFDataRef theData); CF_EXPORT CFDataRef CFDataCreateWithBytesNoCopy (CFAllocatorRef allocator, const UInt8 * bytes, CFIndex length, CFAllocatorRef bytesDeallocator); /** \} */ /** \name Examining a CFData Object \{ */ CF_EXPORT const UInt8 *CFDataGetBytePtr (CFDataRef theData); CF_EXPORT void CFDataGetBytes (CFDataRef theData, CFRange range, UInt8 * buffer); CF_EXPORT CFIndex CFDataGetLength (CFDataRef theData); /** \} */ /** \name Getting the CFData Type ID \{ */ CF_EXPORT CFTypeID CFDataGetTypeID (void); /** \} */ /** \} */ /** \defgroup CFMutableDataRef CFMutableData Reference \{ */ /** \name Creating a Mutable Data Object \{ */ CF_EXPORT CFMutableDataRef CFDataCreateMutable (CFAllocatorRef allocator, CFIndex capacity); CF_EXPORT CFMutableDataRef CFDataCreateMutableCopy (CFAllocatorRef allocator, CFIndex capacity, CFDataRef theData); /** \} */ /** \name Accessing Mutable Data \{ */ CF_EXPORT UInt8 *CFDataGetMutableBytePtr (CFMutableDataRef theData); /** \} */ /** \name Modifying a Mutable Data Object \{ */ CF_EXPORT void CFDataAppendBytes (CFMutableDataRef theData, const UInt8 * bytes, CFIndex length); CF_EXPORT void CFDataDeleteBytes (CFMutableDataRef theData, CFRange range); CF_EXPORT void CFDataReplaceBytes (CFMutableDataRef theData, CFRange range, const UInt8 * newBytes, CFIndex newLength); CF_EXPORT void CFDataIncreaseLength (CFMutableDataRef theData, CFIndex extraLength); CF_EXPORT void CFDataSetLength (CFMutableDataRef theData, CFIndex length); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFDATA_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CoreFoundation.h0000644000175000017500000000450313222706330023265 0ustar yavoryavor/* CoreFoundation.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of CoreBase. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_COREFOUNDATION_H__ #define __COREFOUNDATION_COREFOUNDATION_H__ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #endif /* __COREFOUNDATION_COREFOUNDATION_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFCharacterSet.h0000644000175000017500000001137213222706330023131 0ustar yavoryavor/* CFCharacterSet.h Copyright (C) 2012 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFCHARACTERSET_H__ #define __COREFOUNDATION_CFCHARACTERSET_H__ #include #include CF_EXTERN_C_BEGIN /** \ingroup CFCharacterSetRef */ typedef const struct __CFCharacterSet * CFCharacterSetRef; /** \ingroup CFMutableCharacterSetRef */ typedef struct __CFCharacterSet * CFMutableCharacterSetRef; /** \defgroup CFCharacterSetRef CFCharacterSet Reference \{ */ typedef enum { kCFCharacterSetControl = 1, kCFCharacterSetWhitespace, kCFCharacterSetWhitespaceAndNewline, kCFCharacterSetDecimalDigit, kCFCharacterSetLetter, kCFCharacterSetLowercaseLetter, kCFCharacterSetUppercaseLetter, kCFCharacterSetNonBase, kCFCharacterSetDecomposable, kCFCharacterSetAlphaNumeric, kCFCharacterSetPunctuation, #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) kCFCharacterSetCapitalizedLetter = 13, #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) kCFCharacterSetSymbol = 14, #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) kCFCharacterSetNewline = 15, #endif kCFCharacterSetIllegal = 12 } CFCharacterSetPredefinedSet; /** \name Creating Character Sets \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) CF_EXPORT CFCharacterSetRef CFCharacterSetCreateCopy (CFAllocatorRef alloc, CFCharacterSetRef set); #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) CF_EXPORT CFCharacterSetRef CFCharacterSetCreateInvertedSet (CFAllocatorRef alloc, CFCharacterSetRef set); #endif CF_EXPORT CFCharacterSetRef CFCharacterSetCreateWithCharactersInRange (CFAllocatorRef alloc, CFRange range); CF_EXPORT CFCharacterSetRef CFCharacterSetCreateWithCharactersInString (CFAllocatorRef alloc, CFStringRef string); CF_EXPORT CFCharacterSetRef CFCharacterSetCreateWithBitmapRepresentation (CFAllocatorRef alloc, CFDataRef data); /** \} */ /** \name Getting Predefined Character Sets \{ */ CF_EXPORT CFCharacterSetRef CFCharacterSetGetPredefined (CFCharacterSetPredefinedSet setIdentifier); /** \} */ /** \name Querying Character Sets \{ */ CF_EXPORT CFDataRef CFCharacterSetCreateBitmapRepresentation (CFAllocatorRef alloc, CFCharacterSetRef set); CF_EXPORT Boolean CFCharacterSetIsCharacterMember (CFCharacterSetRef set, UniChar c); #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) CF_EXPORT Boolean CFCharacterSetHasMemberInPlane (CFCharacterSetRef set, CFIndex plane); CF_EXPORT Boolean CFCharacterSetIsLongCharacterMember (CFCharacterSetRef set, UTF32Char c); CF_EXPORT Boolean CFCharacterSetIsSupersetOfSet (CFCharacterSetRef set, CFCharacterSetRef otherSet); #endif /** \} */ /** \name Getting the Character Set Type Identifier \{ */ CF_EXPORT CFTypeID CFCharacterSetGetTypeID (void); /** \} */ /** \} */ /** \defgroup CFMutableCharacterSetRef CFMutableCharacterSet Reference \{ */ CF_EXPORT CFMutableCharacterSetRef CFCharacterSetCreateMutable (CFAllocatorRef alloc); CF_EXPORT CFMutableCharacterSetRef CFCharacterSetCreateMutableCopy (CFAllocatorRef alloc, CFCharacterSetRef set); CF_EXPORT void CFCharacterSetAddCharactersInRange (CFMutableCharacterSetRef set, CFRange range); CF_EXPORT void CFCharacterSetAddCharactersInString (CFMutableCharacterSetRef set, CFStringRef string); CF_EXPORT void CFCharacterSetRemoveCharactersInRange (CFMutableCharacterSetRef set, CFRange range); CF_EXPORT void CFCharacterSetRemoveCharactersInString (CFMutableCharacterSetRef set, CFStringRef string); CF_EXPORT void CFCharacterSetIntersect (CFMutableCharacterSetRef set, CFCharacterSetRef otherSet); CF_EXPORT void CFCharacterSetInvert (CFMutableCharacterSetRef set); CF_EXPORT void CFCharacterSetUnion (CFMutableCharacterSetRef set, CFCharacterSetRef otherSet); /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFCHARACTERSET_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFLocale.h0000644000175000017500000001712613222706330021763 0ustar yavoryavor/* CFLocale.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: March, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFLOCALE__ #define __COREFOUNDATION_CFLOCALE__ 1 #include #include #include #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) CF_EXTERN_C_BEGIN /** \defgroup CFLocaleRef CFLocale Reference \brief CFLocale provides basic functionality for language and/or region specific operations. Locale-sensitive operations, such as collation, calendars and capitalization, may use CFLocale objects to provide language and/or region specific functionality. CFLocale is "toll-free bridged" to NSLocale. \{ */ typedef const struct __CFLocale *CFLocaleRef; /** */ enum { kCFLocaleLanguageDirectionUnknown = 0, kCFLocaleLanguageDirectionLeftToRight = 1, kCFLocaleLanguageDirectionRightToLeft = 2, kCFLocaleLanguageDirectionTopToBottom = 3, kCFLocaleLanguageDirectionBottomToTop = 4 }; typedef CFIndex CFLocaleLanguageDirection; /** \name CFLocale Property Keys \{ */ CF_EXPORT const CFStringRef kCFLocaleMeasurementSystem; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleDecimalSeparator; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleGroupingSeparator; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleCurrencySymbol; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleCurrencyCode; /* CFString */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXPORT const CFStringRef kCFLocaleIdentifier; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleLanguageCode; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleCountryCode; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleScriptCode; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleVariantCode; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleExemplarCharacterSet; /* CFCharacterSet */ CF_EXPORT const CFStringRef kCFLocaleCalendarIdentifier; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleCalendar; /* CFCalendar */ CF_EXPORT const CFStringRef kCFLocaleCollationIdentifier; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleUsesMetricSystem; /* CFBoolean */ #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) CF_EXPORT const CFStringRef kCFLocaleCollatorIdentifier; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleQuotationBeginDelimiterKey; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleQuotationEndDelimiterKey; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleAlternateQuotationBeginDelimiterKey; /* CFString */ CF_EXPORT const CFStringRef kCFLocaleAlternateQuotationEndDelimiterKey; /* CFString */ #endif /** \} */ /** \name CFCalendar Identifiers \{ */ CF_EXPORT const CFStringRef kCFGregorianCalendar; #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXPORT const CFStringRef kCFBuddhistCalendar; CF_EXPORT const CFStringRef kCFChineseCalendar; CF_EXPORT const CFStringRef kCFHebrewCalendar; CF_EXPORT const CFStringRef kCFIslamicCalendar; CF_EXPORT const CFStringRef kCFIslamicCivilCalendar; CF_EXPORT const CFStringRef kCFJapaneseCalendar; #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) CF_EXPORT const CFStringRef kCFRepublicOfChinaCalendar; CF_EXPORT const CFStringRef kCFPersianCalendar; CF_EXPORT const CFStringRef kCFIndianCalendar; CF_EXPORT const CFStringRef kCFISO8601Calendar; #endif /** \} */ /** CFLocale Change Notification */ CF_EXPORT const CFStringRef kCFLocaleCurrentLocaleDidChangeNotification; /** \name Creating a Locale \{ */ CF_EXPORT CFLocaleRef CFLocaleCopyCurrent (void); CF_EXPORT CFLocaleRef CFLocaleCreate (CFAllocatorRef allocator, CFStringRef localeIdent); CF_EXPORT CFLocaleRef CFLocaleCreateCopy (CFAllocatorRef allocator, CFLocaleRef locale); CF_EXPORT CFLocaleRef CFLocaleGetSystem (void); /** \} */ /** \name Getting System Locale Information \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXPORT CFArrayRef CFLocaleCopyAvailableLocaleIdentifiers (void); #endif /** \} */ /** \name Getting ISO Information \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXPORT CFArrayRef CFLocaleCopyISOCountryCodes (void); CF_EXPORT CFArrayRef CFLocaleCopyISOLanguageCodes (void); CF_EXPORT CFArrayRef CFLocaleCopyISOCurrencyCodes (void); #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT CFArrayRef CFLocaleCopyCommonISOCurrencyCodes (void); #endif /** \{ */ /** \name Accessing Language Information \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT CFArrayRef CFLocaleCopyPreferredLanguages (void); #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) CF_EXPORT CFLocaleLanguageDirection CFLocaleGetLanguageCharacterDirection (CFStringRef isoLangCode); CF_EXPORT CFLocaleLanguageDirection CFLocaleGetLanguageLineDirection (CFStringRef isoLangCode); #endif /** \} */ /** \name Getting Information About a Locale \{ */ CF_EXPORT CFStringRef CFLocaleCopyDisplayNameForPropertyValue (CFLocaleRef displayLocale, CFStringRef key, CFStringRef value); CF_EXPORT CFTypeRef CFLocaleGetValue (CFLocaleRef locale, CFStringRef key); CF_EXPORT CFStringRef CFLocaleGetIdentifier (CFLocaleRef locale); /** \} */ /** \name Getting and Creating Locale Identifiers \{ */ CF_EXPORT CFStringRef CFLocaleCreateCanonicalLocaleIdentifierFromString (CFAllocatorRef allocator, CFStringRef localeIdent); #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXPORT CFStringRef CFLocaleCreateCanonicalLanguageIdentifierFromString (CFAllocatorRef allocator, CFStringRef localeIdent); CF_EXPORT CFDictionaryRef CFLocaleCreateComponentsFromLocaleIdentifier (CFAllocatorRef allocator, CFStringRef localeIdent); CF_EXPORT CFStringRef CFLocaleCreateLocaleIdentifierFromComponents (CFAllocatorRef allocator, CFDictionaryRef dictionary); #endif /** \} */ /** \name Windows Locale Codes \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) CF_EXPORT CFStringRef CFLocaleCreateLocaleIdentifierFromWindowsLocaleCode (CFAllocatorRef allocator, UInt32 lcid); CF_EXPORT UInt32 CFLocaleGetWindowsLocaleCodeFromLocaleIdentifier (CFStringRef localeIdent); #endif /** \} */ /** \name Getting the CFLocale Type ID \{ */ CF_EXPORT CFTypeID CFLocaleGetTypeID (void); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* OS_API_VERSION >= MAC_OS_X_VERSION_10_3 */ #endif /* __COREFOUNDATION_CFLOCALE__ */ gnustep-corebase-0.2/Headers/CoreFoundation/GSUnicode.h0000644000175000017500000002026613222706330022172 0ustar yavoryavor/* GSUnicode.h Copyright (C) 2014 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: November, 2014 This file is part of GNUstep CoreBase library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSUNICODE_H__ #define __GSUNICODE_H__ 1 #include #include /** @defgroup UnicodeUtils Unicode String Utilities @{ */ /** @name Convert to/from a Unicode String @{ */ /** @brief Convert a string in some external encoding to Unicode (UTF-16). @details This function is used internally to convert to Unicode from the various supported encodings. The function performs checks on both the input and output to verify the results of the conversion is valid UTF-16 data. @note This function always attempts to consume the source buffer s completely. It will only stop if an invalid character and no loss character was provided. Certain encodings, like UTF-7, are stateful and cannot be converted recursively. This differs from the behavior of GSUnicodeToEncoding() and note must be taken. @param[in,out] d Pointer to the address the start of the destination buffer. If NULL or pointing to NULL, will cause the function to perform the conversion but not write any data out. On return, points to memory immediately after where the last byte of data was written out. @param[in] dLimit A pointer to memory immediately after the end of the destination buffer. @param[in] enc Encoding of the data in source buffer. @param[in,out] s Pointer to the first character of the source buffer. This value must not point to NULL or be NULL itself. @param[in] sLimit A pointer to memory immediate after the end of the source buffer. @param[in] loss A substitute character for invalid input. For example, if a UTF-8 input string encodes a surrogate without a pair. A typical character would be U+FFFD (replacement character). Specify a value of 0 if you do not want lossy conversion. @return The amount of UniChar characters required to successfully complete the conversion. Will return -1 if an error is encountered, such as an invalid character and no loss character was provided. If an error occurs, dLen and sLen are still updated and reflect where the error occurred. @see GSUnicodeToEncoding() */ CF_EXPORT CFIndex GSUnicodeFromEncoding (UniChar ** d, const UniChar * const dLimit, CFStringEncoding enc, const UInt8 ** s, const UInt8 * const sLimit, const UTF16Char loss); /** @brief Convert a Unicode string (UTF-16) to some external encoding. @details This function is used internally to convert from Unicode to the various supported encodings. The function performs minimal checks on the input data and will only fail if a code point cannot be converted to the specified encoding and a loss character was not provided. @note This function only attempts to fill the destination buffer d. Only if d or dLen are NULL will this function attempt to consume the source buffer completely. Additionally, in the case when converting to UTF-16 this function does not perform any checks to ensure the input and output are correct. This differs from the behavior of GSUnicodeFromEncoding() and note must be taken. @param[in,out] d Pointer to the address the start of the destination buffer. If NULL or pointing to NULL, will cause the function to perform the conversion but not write any data out. On return, points to memory immediately after where the last byte of data was written out. @param[in] dLimit A pointer to memory immediately after the end of the destination buffer. @param[in] enc Encoding of the data in source buffer. @param[in,out] s Pointer to the first character of the source buffer. This value must not point to NULL or be NULL itself. @param[in] sLimit A pointer to memory immediate after the end of the source buffer. @param[in] loss A substitute character for invalid input. For example, if a UTF-8 input string encodes a surrogate without a pair. A typical character would be '?' (replacement character). Specify a value of 0 if you do not want lossy conversion. @param[in] addBOM If true, adds a byte order mark to the start of the destination buffer. @return The number of successfully converted converted UTF-16 code points. May return -1 if an error is encountered, such as an invalid character and no loss character was provided. @see GSUnicodeFromEncoding () */ CF_EXPORT CFIndex GSUnicodeToEncoding (UInt8 ** d, const UInt8 * const dLimit, CFStringEncoding enc, const UniChar ** s, const UniChar * const sLimit, const char loss, Boolean addBOM); /** @} */ CFIndex GSUnicodeFormatWithArguments (UniChar * __restrict__ s, CFIndex n, CFTypeRef locale, const UniChar * __restrict__ format, CFIndex fmtlen, va_list ap); CFIndex GSUnicodeFormat (UniChar * __restrict__ s, CFIndex n, CFTypeRef locale, const UniChar * __restrict__ format, CFIndex fmtlen, ...); #if 0 /** @name Printf-like Unicode Formatting @{ */ /** @brief Creates an output according to a format per the printf family of functions. @param[in] buffer Output buffer. If NULL, this function returns the number of characters needed. @param[in] size Maximum size of buffer. @param[in] locale This may be a CFDictionaryRef containing locale information or a CFLocaleRef object. Pass NULL for POSIX locale. @param[in] format The formatted string with printf-style specifiers. @return On success, return the number of characters printed, excluding NULL byte. If buffer is not long enough, returns how many characters would be required. @see GSUnicodeFormatWithArguments () */ CF_EXPORT CFIndex GSUnicodeFormat (UniChar * d, UniChar * const dLimit, CFTypeRef locale, const UniChar * f, const UniChar * const fLimit, ...); /** @brief Creates an output according to a format per the printf family of functions. @param[in] buffer Output buffer. If NULL, this function returns the number of characters needed. @param[in] size Maximum size of buffer. @param[in] locale This may be a CFDictionaryRef containing locale information or a CFLocaleRef object. Pass NULL for POSIX locale. @param[in] format The formatted string with printf-style directives. @param[in] arguments The variable argument list of values to be formatted. @return On success, return the number of characters printed, excluding NULL byte. If buffer is not long enough, returns how many characters would be required. @see GSUnicodeFormat() */ CF_EXPORT CFIndex GSUnicodeFormatWithArguments (UniChar * d, UniChar * const dLimit, CFTypeRef locale, const UniChar * f, const UniChar * fLimit, va_list ap); /** @} */ #endif /** @} */ #endif /* __GSUNICODE_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/GSCharacter.h0000644000175000017500000002551113222706330022476 0ustar yavoryavor/* GSCharacter.h Copyright (C) 2014 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: November, 2014 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __GSCHARACTER_H__ #define __GSCHARACTER_H__ 1 #include /** @defgroup CharUtils Character Utilities @{ */ /** @name Unicode Code Point Functions @{ */ /** @brief Determine if a character is an ASCII character (less than 128). @param[in] c Character to test. @return Return true if character is an ASCII character. */ CF_INLINE Boolean GSCharacterIsASCII (const UTF32Char c) { return c < 128; } /** @brief Determine if a character is a whitespace character. @param[in] c Charater to test. @return True if character is whitespace. */ CF_INLINE Boolean GSCharacterIsWhitespace (const UTF32Char c) { return (0x0009 <= c && c <= 0x000D) || (c == 0x0020) || (c == 0x0085) || (c == 0x00A0) || (c == 0x1680) || (0x2000 <= c && c <= 0x200A) || (c == 0x2028) || (c == 0x2029) || (c == 0x202F) || (c == 0x205F) || (c == 0x3000); } /** @brief Determine if character is in one of the supplementary planes. @param[in] c Character to test. @return Returns true if character is in one of the supplementary planes and false if in the Basic Multilingual plane. */ CF_INLINE Boolean GSCharacterIsInSupplementaryPlane (const UTF32Char c) { return c > 0xFFFF; } /** @brief Determine true if character is a surrogate code point. @param[in] c Character to test. @return Returns true if character is a surrogate and false, otherwise. */ CF_INLINE Boolean GSCharacterIsSurrogate (const UTF32Char c) { return (c & 0xFFFFF800) == 0xD800; } /** @brief Determine if character is a leading surrogate code point. @param[in] c Character to test. @return Returns true if character is leading and false, otherwise. */ CF_INLINE Boolean GSCharacterIsLeadSurrogate (const UTF32Char c) { return (c & 0xFFFFFC00) == 0xD800; } /** @brief Determine if character is a trailing surrogate code point. @param[in] c Character to test. @return Returns true if character is trailing and false, otherwise. */ CF_INLINE Boolean GSCharacterIsTrailSurrogate (const UTF32Char c) { return (c & 0xFFFFFC00) == 0xDC00; } /** @} */ /** @name UTF-8 Utilities @{ */ /** @brief The maximum number of UTF-8 code units required to represent the highest Unicode code point. */ #define kGSUTF8CharacterMaximumLength 4 /** @brief Determine the number of trailing bytes for a UTF-8 character based on the leading code unit. @param[in] c Leading code unit to test. @return The number of trailing bytes. */ CF_INLINE CFIndex GSUTF8CharacterTrailBytesCount (const UTF8Char c) { return (c < 0xF5) ? (c >= 0xC0) + (c >= 0xE0) + (c >= 0xF0) : 0; } /** @brief Determines if the specified UTF-8 code unit is a trailing code unit. @param[in] c The code unit to test. @return Returns true if this UTF-8 code unit is a trailing code unit. */ CF_INLINE Boolean GSUTF8CharacterIsTrailing (const UTF8Char c) { return (c & 0xC0) == 0x80; } /** @brief Determine the number of UTF-8 code units required to represent the specified Unicode code point. @param[in] c The Unicode code point to test. @return The number of UTF-8 code units required. */ CF_INLINE CFIndex GSUTF8CharacterLength (const UTF32Char c) { return (c <= 0x10FFFF) ? 1 + (c >= 0x80) + (c >= 0x800) + (c >= 0x10000) : 0; } /** @brief Append the UTF-8 Byte Order Mark to the string buffer. @param[in,out] d A pointer to the current position of the string buffer. This value is updated after a call to the function. @param[in] limit The position just after the end of the buffer. @return True if the function was successful and false, otherwise. */ CF_INLINE CFIndex GSUTF8CharacterAppendByteOrderMark (UTF8Char * d, const UTF8Char * limit) { if ((limit - d) > 3) { d[0] = 0xEF; d[1] = 0xBB; d[2] = 0xBF; } return 3; } /** @brief Determine if a UTF-8 string buffer has a Byte Order Mark. @param[in,out] s A pointer to the current position of the string buffer. This value is updated after a call to the function. @param[in] limit The position just after the end of the buffer. The caller must ensure this parameter is beyond the string buffer pointed to by d. @return True if a Byte Order Mark is found and false, otherwise. */ CF_INLINE Boolean GSUTF8CharacterSkipByteOrderMark (const UTF8Char ** s, const UTF8Char * limit) { const UTF8Char *p; p = *s; if ((limit - p) > 3) { if (*p++ == 0xEF && *p++ == 0xBB && *p++ == 0xBF) { *s = p; return true; } } return false; } /** @brief Append a character to a UTF-8 string buffer. @param[in] d A pointer to the current position of the string buffer. This value is updated after a call to the function. @param[in] limit The position just after the end of the buffer. @param[in] c The Unicode code point to write. @return The amount of code units written to the destination buffer. Will return 0 if c is a surrogate or invalid code point. */ CF_INLINE CFIndex GSUTF8CharacterAppend (UTF8Char * d, const UTF8Char * limit, UTF32Char c) { static const UTF8Char utf8LeadHeader[4] = { 0x00, 0xC0, 0xE0, 0xF0 }; CFIndex l; if (GSCharacterIsSurrogate (c)) return 0; l = GSUTF8CharacterLength (c); if (l && limit - d > l) { switch (l) { case 4: d[3] = (c & 0x3F) | 0x80; c >>= 6; case 3: d[2] = (c & 0x3F) | 0x80; c >>= 6; case 2: d[1] = (c & 0x3F) | 0x80; c >>= 6; case 1: d[0] = c | utf8LeadHeader[l - 1]; } } return l; } /** @brief Get a Unicode code unit from a UTF-8 string buffer. @param[in,out] s A pointer to the current position of the source buffer. This value is updated after a call to the function. @param[in] limit The position just after the end of the buffer. Must be at least *s + 1. @param[out] c On return, the character. @return A valid Unicode code unit. Will return 0 if: -# The UTF-8 code unit is also a 0. -# An invalid code point or code unit is encountered and loss was not specified. */ CF_INLINE CFIndex GSUTF8CharacterGet (const UTF8Char * s, const UTF8Char * limit, UTF32Char *c) { static const UTF32Char utf8LeadMask[4] = { 0x0, 0x1F, 0x0F, 0x07 }; const UTF8Char *start; UTF32Char ch; start = s; ch = *s++; if (ch > 0x7F) { CFIndex trail; trail = GSUTF8CharacterTrailBytesCount (ch); if (limit - s < trail) trail = 0; /* Force an error */ ch &= utf8LeadMask[trail]; switch (trail) { case 3: if (!GSUTF8CharacterIsTrailing (*s)) { s = start; break; } ch = (ch << 6) | (*s++ & 0x3F); case 2: if (!GSUTF8CharacterIsTrailing (*s)) { s = start; break; } ch = (ch << 6) | (*s++ & 0x3F); case 1: if (!GSUTF8CharacterIsTrailing (*s)) { s = start; break; } ch = (ch << 6) | (*s++ & 0x3F); break; case 0: s = start; break; } } *c = ch; return s - start; } /** @} */ /** @name UTF-16 Utilities @{ */ /** @brief The maximum number of UTF-16 code units required to represent the highest Unicode code point. */ #define kGSUTF16CharacterMaximumLength 2 /** @brief The Byte Order Mark for UTF-16 strings. */ #define kGSUTF16CharacterByteOrderMark 0xFEFF /** @brief The swapped Byte Order Mark for UTF-16 strings. */ #define kGSUTF16CharacterSwappedByteOrderMark 0xFFFE /** @brief Append a character to a UTF-16 string buffer. @param[in,out] d A pointer to the current position of the buffer. This value is updated after a call to the function. @param[in] limit The position just after the end of the buffer. @param[in] c The Unicode code point to write. @return True if the functions was successful, and false if there is not enough space left in the string buffer or the code point is invalid. */ CF_INLINE CFIndex GSUTF16CharacterAppend (UTF16Char * d, const UTF16Char * limit, UTF32Char c) { if (c <= 0xFFFF) { if ((limit - d) > 1) *d = c; return 1; } else if (c <= 0x10FFFF) { if ((limit - d) > 2) { d[0] = (c >> 10) + 0xD7C0; d[1] = (c & 0x3FF) + 0xDC00; } return 2; } return 0; } /** @brief Get a Unicode code point from a UTF-16 string buffer. @param[in] s A pointer to the current position of the buffer. This value is updated after a call to the function. @param[in] limit The position just after the end of the buffer. Must be at least *s + 1. @param[out] c On return, the character. @return A valid Unicode code point. Will return 0 if: -# The UTF-16 code unit is also a 0. -# The UTF-16 code unit pointed to by s is not a leading code unit. -# The leading UTF-16 code unit does not have a trailing pair. */ CF_INLINE CFIndex GSUTF16CharacterGet (const UTF16Char * s, const UTF16Char * limit, UTF32Char *c) { const UTF16Char *start; UTF32Char ch; start = s; ch = *s++; if (GSCharacterIsSurrogate (ch)) { if (GSCharacterIsLeadSurrogate (ch) && s < limit && GSCharacterIsTrailSurrogate (*s)) ch = (ch << 10) + (*s++) - ((0xD7C0 << 10) + 0xDC00); else --s; } *c = ch; return s - start; } /** @} */ /** @name UTF-32 Utilities @{ */ /** @brief The Byte Order Mark for UTF-32 strings. */ #define kGSUTF32CharacterByteOrderMark 0x0000FEFF /** @brief The swapped Byte Order Mark for UTF-32 strings. */ #define kGSUTF32CharacterSwappedByteOrderMark 0xFFFE0000 /** @} */ /** @} */ #endif /* __GSCHARACTER_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFBase.h.in0000644000175000017500000003431413222706330022041 0ustar yavoryavor/* CFBase.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFBASE_H__ #define __COREFOUNDATION_CFBASE_H__ /* CoreFoundation defines __LITTLE_ENDIAN__ or __BIG_ENDIAN__ so we'll * do the same here for compatibility. */ #if !defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) @GS_WORDS_BIGENDIAN_DEFINE@ #endif #include #include /* * CoreFoundation types */ typedef @GS_UINT8_T@ Boolean; typedef @GS_UINT8_T@ UInt8; typedef @GS_SINT8_T@ SInt8; typedef @GS_UINT16_T@ UInt16; typedef @GS_SINT16_T@ SInt16; typedef @GS_UINT32_T@ UInt32; typedef @GS_SINT32_T@ SInt32; typedef @GS_UINT64_T@ UInt64; typedef @GS_SINT64_T@ SInt64; typedef SInt32 OSStatus; typedef float Float32; typedef double Float64; typedef UInt16 UniChar; typedef UInt8 *StringPtr; typedef const StringPtr *ConstStringPtr; typedef UInt8 Str255[256]; typedef const Str255 *ConstStr255Param; typedef SInt16 OSErr; typedef SInt16 RegionCode; typedef SInt16 LangCode; typedef SInt16 ScriptCode; typedef UInt32 FourCharCode; #ifndef OSTYPE_DECLARED typedef FourCharCode OSType; #define OSTYPE_DECLARED #endif typedef UInt8 Byte; typedef SInt8 SignedByte; #ifndef UTF32Char /* UTF32Char is also defined in GSConfig.h */ typedef UInt32 UTF32Char; #endif typedef UInt16 UTF16Char; typedef UInt8 UTF8Char; #if !defined(CF_EXTERN_C_BEGIN) #if defined(__cplusplus) #define CF_EXTERN_C_BEGIN extern "C" { #define CF_EXTERN_C_END } #else #define CF_EXTERN_C_BEGIN #define CF_EXTERN_C_END #endif #endif #if defined(_WIN32) #if defined(BUILDING_SELF) #if defined(__cplusplus) #define CF_EXPORT extern "C" __declspec(dllexport) #else #define CF_EXPORT extern __declspec(dllexport) #endif #else #if defined(__cplusplus) #define CF_EXPORT extern "C" __declspec(dllimport) #else #define CF_EXPORT extern __declspec(dllimport) #endif #endif #else #if defined(__cplusplus) #define CF_EXPORT extern "C" #else #define CF_EXPORT extern #endif #endif #if !defined(__bool_true_false_are_defined) #define true 1 #define false 0 #endif #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #if !defined(CF_INLINE) #if defined(__GNUC__) && (__GNUC__ >= 4) #define CF_INLINE static __inline__ __attribute__((always_inline)) #elif defined(__GNUC__) #define CF_INLINE static __inline__ #elif defined(__MWERKS__) || defined(__cplusplus) #define CF_INLINE static inline #elif defined(_MSC_VER) #define CF_INLINE static __inline #elif _WIN32 #define CF_INLINE static __inline__ #else #define CF_INLINE static inline #endif #endif #if defined(__GNUC__) || defined(__llvm__) #define GS_PURE_FUNCTION __attribute__((pure)) #else #define GS_PURE_FUNCTION #endif CF_EXTERN_C_BEGIN /** \defgroup CFTypeRef CFType Reference \{ */ typedef @GS_UINTPTR_T@ CFTypeID; typedef const void *CFTypeRef; /** @} */ /** \defgroup BaseUtils Base Utilities \{ */ /** An integer value to store a hash code. */ typedef @GS_UINTPTR_T@ CFHashCode; /** A bitfield for passing information to functions. Can hold as many bits as a word. */ typedef @GS_UINTPTR_T@ CFOptionFlags; /** A signed integer representing an index, size, length or count. */ typedef @GS_SINTPTR_T@ CFIndex; /** A structure that represents a range of items in a container, such as an array. */ typedef struct CFRange CFRange; struct CFRange { CFIndex location; /**< An integer representing the start location of the range, inclusive. */ CFIndex length; /**< An integer representing the total number of items in the range */ }; /** Creates a CFRange structure. \param location The starting location. \param length The length. \return An initialized CFRange structure. */ CF_INLINE CFRange CFRangeMake (CFIndex location, CFIndex length) { CFRange range; range.location = location; range.length = length; return range; } /* Returned by comparison functions */ typedef enum { kCFCompareLessThan = -1, kCFCompareEqualTo = 0, kCFCompareGreaterThan = 1 } CFComparisonResult; /* Return when a value is not found */ enum { kCFNotFound = -1 }; /* Definition for standard comparison function callback. */ typedef CFComparisonResult (*CFComparatorFunction) (const void *val1, const void *val2, void *context); /* CoreFoundation version numbers */ /** \name Library Version Numbers \{ */ CF_EXPORT const double kCFCoreFoundationVersionNumber; #define kCFCoreFoundationVersionNumber10_0 196.40 #define kCFCoreFoundationVersionNumber10_0_3 196.50 #define kCFCoreFoundationVersionNumber10_1 226.00 #define kCFCoreFoundationVersionNumber10_1_1 226.00 #define kCFCoreFoundationVersionNumber10_1_2 227.20 #define kCFCoreFoundationVersionNumber10_1_3 227.20 #define kCFCoreFoundationVersionNumber10_1_4 227.30 #define kCFCoreFoundationVersionNumber10_2 263.00 #define kCFCoreFoundationVersionNumber10_2_1 263.10 #define kCFCoreFoundationVersionNumber10_2_2 263.10 #define kCFCoreFoundationVersionNumber10_2_3 263.30 #define kCFCoreFoundationVersionNumber10_2_4 263.30 #define kCFCoreFoundationVersionNumber10_2_5 263.50 #define kCFCoreFoundationVersionNumber10_2_6 263.50 #define kCFCoreFoundationVersionNumber10_2_7 263.50 #define kCFCoreFoundationVersionNumber10_2_8 263.50 #define kCFCoreFoundationVersionNumber10_3 299.00 #define kCFCoreFoundationVersionNumber10_3_1 299.00 #define kCFCoreFoundationVersionNumber10_3_2 299.00 #define kCFCoreFoundationVersionNumber10_3_3 299.30 #define kCFCoreFoundationVersionNumber10_3_4 299.31 #define kCFCoreFoundationVersionNumber10_3_5 299.31 #define kCFCoreFoundationVersionNumber10_3_6 299.32 #define kCFCoreFoundationVersionNumber10_3_7 299.33 #define kCFCoreFoundationVersionNumber10_3_8 299.33 #define kCFCoreFoundationVersionNumber10_3_9 299.35 #define kCFCoreFoundationVersionNumber10_4 368.00 #define kCFCoreFoundationVersionNumber10_4_1 368.10 #define kCFCoreFoundationVersionNumber10_4_2 368.11 #define kCFCoreFoundationVersionNumber10_4_3 368.18 #define kCFCoreFoundationVersionNumber10_4_4_Intel 368.26 #define kCFCoreFoundationVersionNumber10_4_4_PowerPC 368.25 #define kCFCoreFoundationVersionNumber10_4_5_Intel 368.26 #define kCFCoreFoundationVersionNumber10_4_5_PowerPC 368.25 #define kCFCoreFoundationVersionNumber10_4_6_Intel 368.26 #define kCFCoreFoundationVersionNumber10_4_6_PowerPC 368.25 #define kCFCoreFoundationVersionNumber10_4_7 368.27 #define kCFCoreFoundationVersionNumber10_4_8 368.27 #define kCFCoreFoundationVersionNumber10_4_9 368.28 #define kCFCoreFoundationVersionNumber10_4_10 368.28 #define kCFCoreFoundationVersionNumber10_4_11 368.31 #define kCFCoreFoundationVersionNumber10_5 476.00 #define kCFCoreFoundationVersionNumber10_5_1 476.00 #define kCFCoreFoundationVersionNumber10_5_2 476.10 #define kCFCoreFoundationVersionNumber10_5_3 476.13 #define kCFCoreFoundationVersionNumber10_5_4 476.14 #define kCFCoreFoundationVersionNumber10_5_5 476.15 #define kCFCoreFoundationVersionNumber10_5_6 476.17 /** \} */ /** \} */ #if __has_feature(attribute_cf_returns_retained) #define CF_RETURNS_RETAINED __attribute__((cf_returns_retained)) #else #define CF_RETURNS_RETAINED #endif #if __has_feature(attribute_cf_returns_not_retained) #define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained)) #else #define CF_RETURNS_NOT_RETAINED #endif /** \ingroup CFPropertyListRef */ typedef CFTypeRef CFPropertyListRef; /** \ingroup CFStringRef */ typedef const struct __CFString *CFStringRef; /** \ingroup CFMutableStringRef */ typedef struct __CFString *CFMutableStringRef; /** \defgroup CFAllocatorRef CFAllocator Reference \brief CFAllocator is an opaque type used to allocate and deallocate memory. \{ */ /** \brief A reference to a CFAllocator object. */ typedef const struct __CFAllocator *CFAllocatorRef; typedef void *(*CFAllocatorAllocateCallBack) (CFIndex allocSize, CFOptionFlags hint, void *info); typedef void (*CFAllocatorDeallocateCallBack) (void *ptr, void *info); typedef void *(*CFAllocatorReallocateCallBack) (void *ptr, CFIndex newsize, CFOptionFlags hint, void *info); typedef CFIndex (*CFAllocatorPreferredSizeCallBack) (CFIndex size, CFOptionFlags hint, void *info); typedef const void *(*CFAllocatorRetainCallBack) (const void *info); typedef void (*CFAllocatorReleaseCallBack) (const void *info); typedef CFStringRef (*CFAllocatorCopyDescriptionCallBack) (const void *info); struct _CFAllocatorContext { CFIndex version; void *info; CFAllocatorRetainCallBack retain; CFAllocatorReleaseCallBack release; CFAllocatorCopyDescriptionCallBack copyDescription; CFAllocatorAllocateCallBack allocate; CFAllocatorReallocateCallBack reallocate; CFAllocatorDeallocateCallBack deallocate; CFAllocatorPreferredSizeCallBack preferredSize; }; typedef struct _CFAllocatorContext CFAllocatorContext; /** The default allocator and is equivalent to NULL. \see CFAllocatorGetDefault() \see CFAllocatorSetDefault() */ CF_EXPORT CFAllocatorRef kCFAllocatorDefault; /** The default system allocator is used internally by GNUstep and is the default allocator if none is been defined. \see CFAllocatorSetDefault() */ CF_EXPORT CFAllocatorRef kCFAllocatorSystemDefault; /** An allocator that uses the system's malloc, realloc and free functions. */ CF_EXPORT CFAllocatorRef kCFAllocatorMalloc; #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) /** Equivalent to kCFAllocatorSystemDefault */ CF_EXPORT CFAllocatorRef kCFAllocatorMallocZone; #endif /** The NULL allocator does perform any operations. Can be passed as a deallocator if you do not want GNUstep to deallocate the data. */ CF_EXPORT CFAllocatorRef kCFAllocatorNull; /** This is a special case allocator directing CFAllocatorCreate() to use the given CFAllocatorContext structure to allocate the new allocator. */ CF_EXPORT CFAllocatorRef kCFAllocatorUseContext; /** Create a new CFAllocator. \param allocator The allocator used to create this allocator or kCFAllocatorUseContext to use the functions in \b context. \param context The new allocator's context functions. \return A new CFAllocator or NULL in case of failure. \see CFAllocatorContext */ CF_EXPORT CFAllocatorRef CFAllocatorCreate (CFAllocatorRef allocator, CFAllocatorContext * context); /** Allocate new memory. \param allocator The CFAllocator to use. \param size The number of bytes to allocate. \param hint Option flags. Currently unused and should be 0. \return Newly allocated memory of NULL in case of failure. \see CFAllocatorDeallocate() */ CF_EXPORT void *CFAllocatorAllocate (CFAllocatorRef allocator, CFIndex size, CFOptionFlags hint); /** Deallocate the memory pointed to by \b ptr. \param allocator The CFAllocator to use. \param ptr A pointer previously allocated by CFAllocatorAllocate(). \see CFAllocatorAllocate() */ CF_EXPORT void CFAllocatorDeallocate (CFAllocatorRef allocator, void *ptr); CF_EXPORT CFIndex CFAllocatorGetPreferredSizeForSize (CFAllocatorRef allocator, CFIndex size, CFOptionFlags hint); CF_EXPORT void *CFAllocatorReallocate (CFAllocatorRef allocator, void *ptr, CFIndex newsize, CFOptionFlags hint); CF_EXPORT CFAllocatorRef CFAllocatorGetDefault (void); CF_EXPORT void CFAllocatorSetDefault (CFAllocatorRef allocator); CF_EXPORT void CFAllocatorGetContext (CFAllocatorRef allocator, CFAllocatorContext * context); CF_EXPORT CFTypeID CFAllocatorGetTypeID (void); /** \} */ /** \ingroup CFTypeRef \{ */ /* These function will be implemented in CFRuntime.c since they require runtime support. */ CF_EXPORT CFStringRef CFCopyDescription (CFTypeRef cf); CF_EXPORT CFStringRef CFCopyTypeIDDescription (CFTypeID typeID); CF_EXPORT Boolean CFEqual (CFTypeRef cf1, CFTypeRef cf2); CF_EXPORT CFAllocatorRef CFGetAllocator (CFTypeRef cf); CF_EXPORT CFIndex CFGetRetainCount (CFTypeRef cf); CF_EXPORT CFTypeID CFGetTypeID (CFTypeRef cf); CF_EXPORT CFHashCode CFHash (CFTypeRef cf); #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXPORT CFTypeRef CFMakeCollectable (CFTypeRef cf); #endif CF_EXPORT void CFRelease (CFTypeRef cf); CF_EXPORT CFTypeRef CFRetain (CFTypeRef cf); CF_EXPORT CFTypeRef CFAutorelease(CFTypeRef arg); #if OS_API_VERSION(MAC_OS_X_VERSION_10_7, GS_API_LATEST) CF_EXPORT void *_CFBridgingRelease (CFTypeRef cf); CF_EXPORT CFTypeRef _CFBridgingRetain (void *obj); #if __has_feature(objc_arc) #define CFBridgingRetain(x) (__bridge_retained CFTypeRef)(x) #define CFBridgingRelease(x) (__bridge_transfer id)(x) #elif __OBJC__ #define CFBridgingRetain(x) _CFBridgingRetain((void *)(x)) #define CFBridgingRelease(x) (id)_CFBridgingRelease((x)) #else #define CFBridgingRetain(x) _CFBridgingRetain((void *)(x)) #define CFBridgingRelease(x) _CFBridgingRelease((x)) #endif #endif /** \} */ /** \defgroup CFNullRef CFNull Reference \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) typedef struct __CFNull *CFNullRef; CF_EXPORT CFNullRef kCFNull; CFTypeID CFNullGetTypeID (void); #endif /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFBASE_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFPropertyList.h0000644000175000017500000001111113222706330023230 0ustar yavoryavor/* CFPropertyList.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFPROPERTYLIST_H__ #define __COREFOUNDATION_CFPROPERTYLIST_H__ #include #include #include #include CF_EXTERN_C_BEGIN /** \defgroup CFPropertyListRef CFPropertyList Reference \{ */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) typedef enum { kCFPropertyListOpenStepFormat = 1, kCFPropertyListXMLFormat_v1_0 = 100, kCFPropertyListBinaryFormat_v1_0 = 200 } CFPropertyListFormat; #endif typedef enum { kCFPropertyListImmutable = 0, kCFPropertyListMutableContainers = 1, kCFPropertyListMutableContainersAndLeaves = 2 } CFPropertyListMutabilityOptions; #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) enum { kCFPropertyListReadCorruptError = 3840, kCFPropertyListReadUnknownVersionError = 3841, kCFPropertyListReadStreamError = 3842, kCFPropertyListWriteStreamError = 3851, }; #endif CF_EXPORT CFPropertyListRef CFPropertyListCreateDeepCopy (CFAllocatorRef allocator, CFPropertyListRef propertyList, CFOptionFlags mutabilityOption); #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) CF_EXPORT CFDataRef CFPropertyListCreateData (CFAllocatorRef allocator, CFPropertyListRef propertyList, CFPropertyListFormat format, CFOptionFlags options, CFErrorRef *error); CF_EXPORT CFPropertyListRef CFPropertyListCreateWithData (CFAllocatorRef allocator, CFDataRef data, CFOptionFlags options, CFPropertyListFormat *format, CFErrorRef *error); CF_EXPORT CFPropertyListRef CFPropertyListCreateWithStream (CFAllocatorRef allocator, CFReadStreamRef stream, CFIndex streamLength, CFOptionFlags options, CFPropertyListFormat *format, CFErrorRef *error); CF_EXPORT CFIndex CFPropertyListWrite (CFPropertyListRef propertyList, CFWriteStreamRef stream, CFPropertyListFormat format, CFOptionFlags options, CFErrorRef *error); #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) CF_EXPORT Boolean CFPropertyListIsValid (CFPropertyListRef plist, CFPropertyListFormat format); #endif /* The following function are marked as obsolete as of 10.6 */ CF_EXPORT CFPropertyListRef CFPropertyListCreateFromXMLData (CFAllocatorRef allocator, CFDataRef xmlData, CFOptionFlags mutabilityOption, CFStringRef *errorString); CF_EXPORT CFDataRef CFPropertyListCreateXMLData (CFAllocatorRef allocator, CFPropertyListRef propertyList); #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) CF_EXPORT CFPropertyListRef CFPropertyListCreateFromStream (CFAllocatorRef allocator, CFReadStreamRef stream, CFIndex streamLength, CFOptionFlags mutabilityOption, CFPropertyListFormat *format, CFStringRef *errorString); CF_EXPORT CFIndex CFPropertyListWriteToStream (CFPropertyListRef propertyList, CFWriteStreamRef stream, CFPropertyListFormat format, CFStringRef *errorString); #endif /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFPROPERTYLIST_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFXMLParser.h0000644000175000017500000002020713222706330022373 0ustar yavoryavor/* CFXMLParser.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: December, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __CFCOREFOUNDATION_CFXMLPARSER_H__ #define __CFCOREFOUNDATION_CFXMLPARSER_H__ #include #include #include #include #include #include CF_EXTERN_C_BEGIN /** \defgroup CFXMLParserRef CFXMLParser Reference (deprecated) \{ */ typedef struct __CFXMLParser *CFXMLParserRef; typedef enum { kCFXMLStatusParseNotBegun = -2, kCFXMLStatusParseInProgress = -1, kCFXMLStatusParseSuccessful = 0, kCFXMLErrorUnexpectedEOF = 1, kCFXMLErrorUnknownEncoding = 2, kCFXMLErrorEncodingConversionFailure = 3, kCFXMLErrorMalformedProcessingInstruction = 4, kCFXMLErrorMalformedDTD = 5, kCFXMLErrorMalformedName = 6, kCFXMLErrorMalformedCDSect = 7, kCFXMLErrorMalformedCloseTag = 8, kCFXMLErrorMalformedStartTag = 9, kCFXMLErrorMalformedDocument = 10, kCFXMLErrorElementlessDocument = 11, kCFXMLErrorMalformedComment = 12, kCFXMLErrorMalformedCharacterReference = 13, kCFXMLErrorMalformedParsedCharacterData = 14, kCFXMLErrorNoData = 15 } CFXMLParserStatusCode; typedef enum { kCFXMLParserValidateDocument = (1 << 0), kCFXMLParserSkipMetaData = (1 << 1), kCFXMLParserReplacePhysicalEntities = (1 << 2), kCFXMLParserSkipWhitespace = (1 << 3), kCFXMLParserResolveExternalEntities = (1 << 4), kCFXMLParserAddImpliedAttributes = (1 << 5), kCFXMLParserAllOptions = 0x00FFFFFF, kCFXMLParserNoOptions = 0 } CFXMLParserOptions; typedef void *(*CFXMLParserCreateXMLStructureCallBack) (CFXMLParserRef parser, CFXMLNodeRef nodeDesc, void *info); typedef void (*CFXMLParserAddChildCallBack) (CFXMLParserRef parser, void *parent, void *child, void *info); typedef void (*CFXMLParserEndXMLStructureCallBack) (CFXMLParserRef parser, void *xmlType, void *info); typedef CFDataRef (*CFXMLParserResolveExternalEntityCallBack) (CFXMLParserRef parser, CFXMLExternalID * extID, void *info); typedef Boolean (*CFXMLParserHandleErrorCallBack) (CFXMLParserRef parser, CFXMLParserStatusCode error, void *info); typedef CFStringRef (*CFXMLParserCopyDescriptionCallBack) (const void *info); typedef void (*CFXMLParserReleaseCallBack) (const void *info); typedef const void *(*CFXMLParserRetainCallBack) (const void *info); typedef struct CFXMLParserCallBacks CFXMLParserCallBacks; struct CFXMLParserCallBacks { CFIndex version; CFXMLParserCreateXMLStructureCallBack createXMLStructure; CFXMLParserAddChildCallBack addChild; CFXMLParserEndXMLStructureCallBack endXMLStructure; CFXMLParserResolveExternalEntityCallBack resolveExternalEntity; CFXMLParserHandleErrorCallBack handleError; }; typedef struct CFXMLParserContext CFXMLParserContext; struct CFXMLParserContext { CFIndex version; void *info; CFXMLParserRetainCallBack retain; CFXMLParserReleaseCallBack release; CFXMLParserCopyDescriptionCallBack copyDescription; }; CF_EXPORT CFTypeID CFXMLParserGetTypeID (void); CF_EXPORT void CFXMLParserAbort (CFXMLParserRef parser, CFXMLParserStatusCode errorCode, CFStringRef errorDescription); CF_EXPORT CFStringRef CFXMLParserCopyErrorDescription (CFXMLParserRef parser); CF_EXPORT CFXMLParserRef CFXMLParserCreate (CFAllocatorRef allocator, CFDataRef xmlData, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes, CFXMLParserCallBacks * callBacks, CFXMLParserContext * context); CF_EXPORT CFXMLParserRef CFXMLParserCreateWithDataFromURL (CFAllocatorRef allocator, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes, CFXMLParserCallBacks * callBacks, CFXMLParserContext * context); CF_EXPORT void CFXMLParserGetCallBacks (CFXMLParserRef parser, CFXMLParserCallBacks * callBacks); CF_EXPORT void CFXMLParserGetContext (CFXMLParserRef parser, CFXMLParserContext * context); CF_EXPORT void *CFXMLParserGetDocument (CFXMLParserRef parser); CF_EXPORT CFIndex CFXMLParserGetLineNumber (CFXMLParserRef parser); CF_EXPORT CFIndex CFXMLParserGetLocation (CFXMLParserRef parser); CF_EXPORT CFURLRef CFXMLParserGetSourceURL (CFXMLParserRef parser); CF_EXPORT CFXMLParserStatusCode CFXMLParserGetStatusCode (CFXMLParserRef parser); CF_EXPORT Boolean CFXMLParserParse (CFXMLParserRef parser); /** \} */ /** \defgroup CFXMLTreeRef CFXMLTree Reference (deprecated) \{ */ CF_EXPORT CFXMLTreeRef CFXMLTreeCreateFromData (CFAllocatorRef allocator, CFDataRef xmlData, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes); CF_EXPORT CFXMLTreeRef CFXMLTreeCreateWithDataFromURL (CFAllocatorRef allocator, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes); CF_EXPORT CFDataRef CFXMLTreeCreateXMLData (CFAllocatorRef allocator, CFXMLTreeRef xmlTree); #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) CF_EXPORT const CFStringRef kCFXMLTreeErrorDescription; CF_EXPORT const CFStringRef kCFXMLTreeErrorLineNumber; CF_EXPORT const CFStringRef kCFXMLTreeErrorLocation; CF_EXPORT const CFStringRef kCFXMLTreeErrorStatusCode; CF_EXPORT CFStringRef CFXMLCreateStringByEscapingEntities (CFAllocatorRef allocator, CFStringRef string, CFDictionaryRef entitiesDictionary); CF_EXPORT CFStringRef CFXMLCreateStringByUnescapingEntities (CFAllocatorRef allocator, CFStringRef string, CFDictionaryRef entitiesDictionary); CF_EXPORT CFXMLTreeRef CFXMLTreeCreateFromDataWithError (CFAllocatorRef allocator, CFDataRef xmlData, CFURLRef dataSource, CFOptionFlags parseOptions, CFIndex versionOfNodes, CFDictionaryRef * errorDict); #endif /* MAC_OS_X_VERSION_10_3 */ /** \} */ CF_EXTERN_C_END #endif /* __CFCOREFOUNDATION_CFXMLPARSER_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFAttributedString.h0000644000175000017500000001237513222706330024063 0ustar yavoryavor/* CFAttributedString.h Copyright (C) 2012 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: April, 2012 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFATTRIBUTEDSTIRNG_H__ #define __COREFOUNDATION_CFATTRIBUTEDSTIRNG_H__ 1 #include #include CF_EXTERN_C_BEGIN /** \ingroup CFAttributedStringRef */ typedef const struct __CFAttributedString *CFAttributedStringRef; /** \ingroup CFMutableAttributedStringRef */ typedef struct __CFAttributedString *CFMutableAttributedStringRef; /** \defgroup CFAttributedStringRef CFAttributedString Reference \{ */ /** \name Creating a CFAttributedString \{ */ CF_EXPORT CFAttributedStringRef CFAttributedStringCreate (CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attribs); CF_EXPORT CFAttributedStringRef CFAttributedStringCreateCopy (CFAllocatorRef alloc, CFAttributedStringRef str); CF_EXPORT CFAttributedStringRef CFAttributedStringCreateWithSubstring (CFAllocatorRef alloc, CFAttributedStringRef str, CFRange range); CF_EXPORT CFIndex CFAttributedStringGetLength (CFAttributedStringRef str); CF_EXPORT CFStringRef CFAttributedStringGetString (CFAttributedStringRef str); /** \} */ /** \name Accessing Attributes \{ */ CF_EXPORT CFTypeRef CFAttributedStringGetAttribute (CFAttributedStringRef str, CFIndex loc, CFStringRef attrName, CFRange * effRange); CF_EXPORT CFDictionaryRef CFAttributedStringGetAttributes (CFAttributedStringRef str, CFIndex loc, CFRange * effRange); CF_EXPORT CFTypeRef CFAttributedStringGetAttributeAndLongestEffectiveRange (CFAttributedStringRef str, CFIndex loc, CFStringRef attrName, CFRange inRange, CFRange * longestEffRange); CF_EXPORT CFDictionaryRef CFAttributedStringGetAttributesAndLongestEffectiveRange (CFAttributedStringRef str, CFIndex loc, CFRange inRange, CFRange * longestEffRange); /** \} */ /** \name Getting Attributed String Properties \{ */ CF_EXPORT CFTypeID CFAttributedStringGetTypeID (void); /** \} */ /** \} */ /** \defgroup CFMutableAttributedStringRef CFMutableAttributedString Reference \{ */ /** \name Creating a CFMutableAttributedString \{ */ CF_EXPORT CFMutableAttributedStringRef CFAttributedStringCreateMutable (CFAllocatorRef alloc, CFIndex maxLength); CF_EXPORT CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy (CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef str); /** \} */ /** \name Modifying a CFMutableAttributedString \{ */ CF_EXPORT void CFAttributedStringBeginEditing (CFMutableAttributedStringRef str); CF_EXPORT void CFAttributedStringEndEditing (CFMutableAttributedStringRef str); CF_EXPORT CFMutableStringRef CFAttributedStringGetMutableString (CFMutableAttributedStringRef str); CF_EXPORT void CFAttributedStringRemoveAttribute (CFMutableAttributedStringRef str, CFRange range, CFStringRef attrName); CF_EXPORT void CFAttributedStringReplaceString (CFMutableAttributedStringRef str, CFRange range, CFStringRef repl); CF_EXPORT void CFAttributedStringReplaceAttributedString (CFMutableAttributedStringRef str, CFRange range, CFAttributedStringRef repl); CF_EXPORT void CFAttributedStringSetAttribute (CFMutableAttributedStringRef str, CFRange range, CFStringRef attrName, CFTypeRef value); CF_EXPORT void CFAttributedStringSetAttributes (CFMutableAttributedStringRef str, CFRange range, CFDictionaryRef repl, Boolean clearOtherAttribs); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFATTRIBUTEDSTIRNG_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFDictionary.h0000644000175000017500000001336213222706330022667 0ustar yavoryavor/* CFDictionary.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFDICTIONARY_H__ #define __COREFOUNDATION_CFDICTIONARY_H__ 1 #include CF_EXTERN_C_BEGIN /** \ingroup CFDictionaryRef */ typedef const struct __CFDictionary *CFDictionaryRef; /** \ingroup CFMutableDictionaryRef */ typedef struct __CFDictionary *CFMutableDictionaryRef; /** \defgroup CFDictionaryRef CFDictionary Reference \{ */ typedef void (*CFDictionaryApplierFunction) (const void *key, const void *value, void *context); typedef CFStringRef (*CFDictionaryCopyDescriptionCallBack) (const void *value); typedef Boolean (*CFDictionaryEqualCallBack) (const void *value1, const void *value2); typedef CFHashCode (*CFDictionaryHashCallBack) (const void *value); typedef void (*CFDictionaryReleaseCallBack) (CFAllocatorRef allocator, const void *value); typedef const void *(*CFDictionaryRetainCallBack) (CFAllocatorRef allocator, const void *value); typedef struct _CFDictionaryKeyCallBacks CFDictionaryKeyCallBacks; struct _CFDictionaryKeyCallBacks { CFIndex version; CFDictionaryRetainCallBack retain; CFDictionaryReleaseCallBack release; CFDictionaryCopyDescriptionCallBack copyDescription; CFDictionaryEqualCallBack equal; CFDictionaryHashCallBack hash; }; typedef struct _CFDictionaryValueCallBacks CFDictionaryValueCallBacks; struct _CFDictionaryValueCallBacks { CFIndex version; CFDictionaryRetainCallBack retain; CFDictionaryReleaseCallBack release; CFDictionaryCopyDescriptionCallBack copyDescription; CFDictionaryEqualCallBack equal; }; CF_EXPORT const CFDictionaryKeyCallBacks kCFCopyStringDictionaryKeyCallBacks; CF_EXPORT const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks; CF_EXPORT const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks; /** \name Creating a dictionary \{ */ CF_EXPORT CFDictionaryRef CFDictionaryCreate (CFAllocatorRef allocator, const void **keys, const void **values, CFIndex numValues, const CFDictionaryKeyCallBacks * keyCallBacks, const CFDictionaryValueCallBacks * valueCallBacks); CF_EXPORT CFDictionaryRef CFDictionaryCreateCopy (CFAllocatorRef allocator, CFDictionaryRef theDict); /** \} */ /** \name Examining a dictionary \{ */ CF_EXPORT Boolean CFDictionaryContainsKey (CFDictionaryRef theDict, const void *key); CF_EXPORT Boolean CFDictionaryContainsValue (CFDictionaryRef theDict, const void *value); CF_EXPORT CFIndex CFDictionaryGetCount (CFDictionaryRef theDict); CF_EXPORT CFIndex CFDictionaryGetCountOfKey (CFDictionaryRef theDict, const void *key); CF_EXPORT CFIndex CFDictionaryGetCountOfValue (CFDictionaryRef theDict, const void *value); CF_EXPORT void CFDictionaryGetKeysAndValues (CFDictionaryRef theDict, const void **keys, const void **values); CF_EXPORT const void *CFDictionaryGetValue (CFDictionaryRef theDict, const void *key); CF_EXPORT Boolean CFDictionaryGetValueIfPresent (CFDictionaryRef theDict, const void *key, const void **value); /** \} */ /** \name Applying a funcation to a dictionary \{ */ CF_EXPORT void CFDictionaryApplyFunction (CFDictionaryRef theDict, CFDictionaryApplierFunction applier, void *context); /** \} */ /** \name Getting the CFDictionary type ID \{ */ CF_EXPORT CFTypeID CFDictionaryGetTypeID (void); /** \} */ /** \} */ /** \defgroup CFMutableDictionaryRef CFMutableDictionary Reference \{ */ /** \name Creating a Mutable Dictionary \{ */ CF_EXPORT CFMutableDictionaryRef CFDictionaryCreateMutable (CFAllocatorRef allocator, CFIndex capacity, const CFDictionaryKeyCallBacks * keyCallBacks, const CFDictionaryValueCallBacks * valueCallBacks); CF_EXPORT CFMutableDictionaryRef CFDictionaryCreateMutableCopy (CFAllocatorRef allocator, CFIndex capacity, CFDictionaryRef theDict); /** \} */ /** \name Modifying a Dictionary \{ */ CF_EXPORT void CFDictionaryAddValue (CFMutableDictionaryRef theDict, const void *key, const void *value); CF_EXPORT void CFDictionaryRemoveAllValues (CFMutableDictionaryRef theDict); CF_EXPORT void CFDictionaryRemoveValue (CFMutableDictionaryRef theDict, const void *key); CF_EXPORT void CFDictionaryReplaceValue (CFMutableDictionaryRef theDict, const void *key, const void *value); CF_EXPORT void CFDictionarySetValue (CFMutableDictionaryRef theDict, const void *key, const void *value); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFDICTIONARY_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFRuntime.h0000644000175000017500000001264613222706330022211 0ustar yavoryavor/* CFRuntime.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of CoreBase. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFRUNTIME_H__ #define __COREFOUNDATION_CFRUNTIME_H__ #include #include #include CF_EXTERN_C_BEGIN /** \defgroup CFRuntimeUtils Runtime Utilities \brief \par Examples: \ref ExampleEXUInt32 \warning The CFRuntime functions are not thread-safe. \{ */ /** \name Garbage Collection \brief Garbage Collection is not supported. All macros and functions relating to GC return false or NULL, but are provided for compatibility. \{ */ CF_EXPORT Boolean kCFUseCollectableAllocator; CF_EXPORT Boolean (*__CFObjCIsCollectable)(void *); #define CF_USING_COLLECTABLE_MEMORY (kCFUseCollectableAllocator) #define CF_IS_COLLECTABLE_ALLOCATOR(allocator) 0 #define CF_IS_COLLECTABLE(obj) 0 /** \} */ enum { _kCFRuntimeNotATypeID = 0 }; enum { _kCFRuntimeScannedObject = (1UL<<0), _kCFRuntimeResourcefulObject = (1UL<<2), _kCFRuntimeCustomRefCount = (1UL<<3) }; typedef struct __CFRuntimeClass CFRuntimeClass; struct __CFRuntimeClass { CFIndex version; const char *className; void (*init)(CFTypeRef cf); CFTypeRef (*copy)(CFAllocatorRef allocator, CFTypeRef cf); #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) void (*finalize)(CFTypeRef cf); #else void (*dealloc)(CFTypeRef cf); #endif Boolean (*equal)(CFTypeRef cf1, CFTypeRef cf2); CFHashCode (*hash)(CFTypeRef cf); CFStringRef (*copyFormattingDesc)(CFTypeRef cf, CFDictionaryRef formatOptions); CFStringRef (*copyDebugDesc)(CFTypeRef cf); #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) #define CF_RECLAIM_AVAILABLE 1 void (*reclaim)(CFTypeRef cf); /* _kCFRuntimeResourcefulObject */ #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_7, GS_API_LATEST) #define CF_REFCOUNT_AVAILABLE 1 UInt32 (*refcount)(intptr_t op, CFTypeRef cf); /* _kCFRuntimeCustomRefCount */ #endif }; /** Registers a new CF class with the runtime. This function locks the class table and so is thread-safe. \param cls A constant CFRuntimeClass. \return The next available CFTypeID or _kCFRuntimeNotATypeID if none are available. \see _CFRuntimeUnregisterClassWithTypeID() */ CF_EXPORT CFTypeID _CFRuntimeRegisterClass (const CFRuntimeClass * const cls); /** Gets the class structure associated with the \a typeID. \param typeID A CFTypeID to look up. \return The CFRuntimeClass for the \b typeID */ CF_EXPORT const CFRuntimeClass * _CFRuntimeGetClassWithTypeID (CFTypeID typeID); /** Unregisters a class. \param typeID The CFTypeID to unregister. \see _CFRuntimeRegisterClass() \warning This function is not thread-safe. */ CF_EXPORT void _CFRuntimeUnregisterClassWithTypeID (CFTypeID typeID); typedef struct __CFRuntimeBase CFRuntimeBase; struct __CFRuntimeBase { void *_isa; /**< The Objective-C class for this object. Used for the Objective-C bridge. For internal use only. */ SInt16 _typeID; struct { SInt16 ro: 1; SInt16 reserved: 7; SInt16 info: 8; } _flags; }; #define INIT_CFRUNTIME_BASE(...) { 0, 0, { 1, 0, 0 } } /** Creates a new CF type instance. \param allocator The CFAllocatorRef to use or NULL for the default allocator. \param typeID The CFTypeID of the class. \param extraBytes The amount of extra bytes over a CFRuntimeBase type needed by this instance. \param category Currently unused, use NULL. \return A newly allocated object. \see CFRetain() \see CFRelease() */ CF_EXPORT CFTypeRef _CFRuntimeCreateInstance (CFAllocatorRef allocator, CFTypeID typeID, CFIndex extraBytes, unsigned char *category); /** Set the CFTypeID for an instance. \param cf The object instance to set the type ID. \param typeID The new CFTypeID. */ CF_EXPORT void _CFRuntimeSetInstanceTypeID (CFTypeRef cf, CFTypeID typeID); /** Initializes a static CF object instance. \param memory A pointer to a static CF object instance. \param typeID The CFTypeID of the instance. */ CF_EXPORT void _CFRuntimeInitStaticInstance (void *memory, CFTypeID typeID); #define CF_HAS_INIT_STATIC_INSTANCE 1 /** \} */ /** \example EXUInt32.h Example of how to create a new CF class. See \ref EXUInt32.c for the implementation details of this simple CF type. */ /** \example EXUInt32.c Example of how to create a new CF class. See \ref EXUInt32.h for the interface details of this simple CF type. */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFRUNTIME_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFNumber.h0000644000175000017500000000616613222706330022016 0ustar yavoryavor/* CFNumber.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFNUMBER_H__ #define __COREFOUNDATION_CFNUMBER_H__ #include CF_EXTERN_C_BEGIN /** \ingroup CFBooleanRef */ typedef const struct __CFBoolean *CFBooleanRef; /** \ingroup CFNumberRef */ typedef const struct __CFNumber *CFNumberRef; /** \defgroup CFBooleanRef CFBoolean Reference \{ */ CF_EXPORT const CFBooleanRef kCFBooleanTrue; CF_EXPORT const CFBooleanRef kCFBooleanFalse; CF_EXPORT CFTypeID CFBooleanGetTypeID (void); CF_EXPORT Boolean CFBooleanGetValue (CFBooleanRef boolean); /** \} */ /** \defgroup CFNumberRef CFNumber Reference \{ */ CF_EXPORT const CFNumberRef kCFNumberNaN; CF_EXPORT const CFNumberRef kCFNumberNegativeInfinity; CF_EXPORT const CFNumberRef kCFNumberPositiveInfinity; typedef enum { kCFNumberSInt8Type = 1, kCFNumberSInt16Type = 2, kCFNumberSInt32Type = 3, kCFNumberSInt64Type = 4, kCFNumberFloat32Type = 5, kCFNumberFloat64Type = 6, kCFNumberCharType = 7, kCFNumberShortType = 8, kCFNumberIntType = 9, kCFNumberLongType = 10, kCFNumberLongLongType = 11, kCFNumberFloatType = 12, kCFNumberDoubleType = 13, kCFNumberCFIndexType = 14, #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) kCFNumberNSIntegerType = 15, kCFNumberCGFloatType = 16, kCFNumberMaxType = 16 #else kCFNumberMaxType = 14 #endif } CFNumberType; /** \name Creating a Number \{ */ CF_EXPORT CFNumberRef CFNumberCreate (CFAllocatorRef allocator, CFNumberType theType, const void *valuePtr); /** \} */ /** \name Getting Information About Numbers \{ */ CF_EXPORT CFIndex CFNumberGetByteSize (CFNumberRef number); CF_EXPORT CFNumberType CFNumberGetType (CFNumberRef number); CF_EXPORT Boolean CFNumberGetValue (CFNumberRef number, CFNumberType theType, void *valuePtr); CF_EXPORT Boolean CFNumberIsFloatType (CFNumberRef number); /** \} */ /** \name Comparing Numbers \{ */ CF_EXPORT CFComparisonResult CFNumberCompare (CFNumberRef number, CFNumberRef otherNumber, void *context); /** \} */ /** \name Getting the CFNumber Type ID \{ */ CF_EXPORT CFTypeID CFNumberGetTypeID (void); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFNUMBER_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFBundle.h0000644000175000017500000000671313222706330021775 0ustar yavoryavor/* CFBundle.h Copyright (C) 2011 Free Software Foundation, Inc. Written by: David Chisnall Date: April, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFBUNDLE__ #define __COREFOUNDATION_CFBUNDLE__ 1 #include #include #include #include CF_EXTERN_C_BEGIN typedef const struct __CFBundle *CFBundleRef; CFTypeID CFBundleGetTypeID (void); CFBundleRef CFBundleCreate(CFAllocatorRef allocator, CFURLRef bundleURL); void* CFBundleGetFunctionPointerForName(CFBundleRef bundle, CFStringRef functionName); void* CFBundleGetDataPointerForName(CFBundleRef bundle, CFStringRef functionName); CFBundleRef CFBundleGetMainBundle(void); CFBundleRef CFBundleGetBundleWithIdentifier(CFStringRef bundleID); Boolean CFBundleLoadExecutable(CFBundleRef bundle); Boolean CFBundleLoadExecutableAndReturnError(CFBundleRef bundle, CFErrorRef *error); Boolean CFBundlePreflightExecutable(CFBundleRef bundle, CFErrorRef *error); void CFBundleUnloadExecutable(CFBundleRef bundle); CFStringRef CFBundleGetIdentifier(CFBundleRef bundle); CFURLRef CFBundleCopyExecutableURL(CFBundleRef bundle); CFURLRef CFBundleCopyBuiltInPlugInsURL(CFBundleRef bundle); CFURLRef CFBundleCopyBundleURL(CFBundleRef bundle); CFURLRef CFBundleCopyResourcesDirectoryURL(CFBundleRef bundle); CFURLRef CFBundleCopyResourceURL(CFBundleRef bundle, CFStringRef resourceName, CFStringRef resourceType, CFStringRef subDirName); CFURLRef CFBundleCopyPrivateFrameworksURL(CFBundleRef bundle); CFURLRef CFBundleCopyAuxiliaryExecutableURL(CFBundleRef bundle, CFStringRef executableName); CFURLRef CFBundleCopyResourceURLForLocalization(CFBundleRef bundle, CFStringRef resourceName, CFStringRef resourceType, CFStringRef subDirName, CFStringRef localizationName); CFDictionaryRef CFBundleGetInfoDictionary(CFBundleRef bundle); CFDictionaryRef CFBundleGetLocalInfoDictionary(CFBundleRef bundle); CFTypeRef CFBundleGetValueForInfoDictionaryKey(CFBundleRef bundle, CFStringRef key); CF_EXPORT const CFStringRef kCFBundleInfoDictionaryVersionKey; CF_EXPORT const CFStringRef kCFBundleExecutableKey; CF_EXPORT const CFStringRef kCFBundleIdentifierKey; CF_EXPORT const CFStringRef kCFBundleVersionKey; CF_EXPORT const CFStringRef kCFBundleNameKey; CF_EXPORT const CFStringRef kCFBundleLocalizationsKey; CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFBUNDLE__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFUUID.h0000644000175000017500000000564313222706330021333 0ustar yavoryavor/* CFUUID.h Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: May, 2011 This file is part of GNUstep CoreBase Library. This library is free software; you can redisibute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is disibuted in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFUUID_H__ #define __COREFOUNDATION_CFUUID_H__ #include CF_EXTERN_C_BEGIN /** \defgroup CFUUIDRef CFUUID Reference \{ */ typedef const struct __CFUUID *CFUUIDRef; typedef struct { UInt8 byte0; UInt8 byte1; UInt8 byte2; UInt8 byte3; UInt8 byte4; UInt8 byte5; UInt8 byte6; UInt8 byte7; UInt8 byte8; UInt8 byte9; UInt8 byte10; UInt8 byte11; UInt8 byte12; UInt8 byte13; UInt8 byte14; UInt8 byte15; } CFUUIDBytes; /** \name Creating CFUUID Objects \{ */ CF_EXPORT CFUUIDRef CFUUIDCreate (CFAllocatorRef alloc); CF_EXPORT CFUUIDRef CFUUIDCreateFromString (CFAllocatorRef alloc, CFStringRef uuidStr); CF_EXPORT CFUUIDRef CFUUIDCreateFromUUIDBytes (CFAllocatorRef alloc, CFUUIDBytes bytes); CF_EXPORT CFUUIDRef CFUUIDCreateWithBytes (CFAllocatorRef alloc, UInt8 byte0, UInt8 byte1, UInt8 byte2, UInt8 byte3, UInt8 byte4, UInt8 byte5, UInt8 byte6, UInt8 byte7, UInt8 byte8, UInt8 byte9, UInt8 byte10, UInt8 byte11, UInt8 byte12, UInt8 byte13, UInt8 byte14, UInt8 byte15); /** \} */ /** \name Getting Information About CFUUID Objects \{ */ CF_EXPORT CFStringRef CFUUIDCreateString (CFAllocatorRef alloc, CFUUIDRef uuid); CF_EXPORT CFUUIDRef CFUUIDGetConstantUUIDWithBytes (CFAllocatorRef alloc, UInt8 byte0, UInt8 byte1, UInt8 byte2, UInt8 byte3, UInt8 byte4, UInt8 byte5, UInt8 byte6, UInt8 byte7, UInt8 byte8, UInt8 byte9, UInt8 byte10, UInt8 byte11, UInt8 byte12, UInt8 byte13, UInt8 byte14, UInt8 byte15); CF_EXPORT CFUUIDBytes CFUUIDGetUUIDBytes (CFUUIDRef uuid); /** \} */ /** \name Getting the CFUUID Type Identifier \{ */ CF_EXPORT CFTypeID CFUUIDGetTypeID (void); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFUUID_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFStream.h0000644000175000017500000002235313222706330022015 0ustar yavoryavor/* CFStream.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFSTREAM_H__ #define __COREFOUNDATION_CFSTREAM_H__ 1 #include #include #include #include #include CF_EXTERN_C_BEGIN #if OS_API_VERSION(MAC_OS_X_VERSION_10_1, GS_API_LATEST) /** \ingroup CFWriteStreamRef */ typedef struct __CFWriteStream *CFWriteStreamRef; /** \ingroup CFReadStreamRef */ typedef struct __CFReadStream *CFReadStreamRef; /** \defgroup CFStreamUtils Stream Utilities \{ */ CF_EXPORT const CFStringRef kCFStreamPropertyDataWritten; CF_EXPORT const CFStringRef kCFStreamPropertySocketNativeHandle; CF_EXPORT const CFStringRef kCFStreamPropertySocketRemoteHostName; CF_EXPORT const CFStringRef kCFStreamPropertySocketRemotePortNumber; #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) CF_EXPORT const CFStringRef kCFStreamPropertyAppendToFile; #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) CF_EXPORT const CFStringRef kCFStreamPropertyFileCurrentOffset; #endif struct CFStreamClientContext { CFIndex version; void *info; CFAllocatorRetainCallBack retain; CFAllocatorReleaseCallBack release; CFAllocatorCopyDescriptionCallBack copyDescription; }; typedef struct CFStreamClientContext CFStreamClientContext; typedef enum { kCFStreamStatusNotOpen = 0, kCFStreamStatusOpening, kCFStreamStatusOpen, kCFStreamStatusReading, kCFStreamStatusWriting, kCFStreamStatusAtEnd, kCFStreamStatusClosed, kCFStreamStatusError } CFStreamStatus; /* Deprecated */ typedef enum { kCFStreamErrorDomainCustom = -1, kCFStreamErrorDomainPOSIX = 1, kCFStreamErrorDomainMacOSStatus } CFStreamErrorDomain; struct _CFStreamError { CFStreamErrorDomain domain; SInt32 error; }; typedef struct _CFStreamError CFStreamError; typedef enum { kCFStreamEventNone = 0, kCFStreamEventOpenCompleted = 1, kCFStreamEventHasBytesAvailable = 2, kCFStreamEventCanAcceptBytes = 4, kCFStreamEventErrorOccurred = 8, kCFStreamEventEndEncountered = 16 } CFStreamEventType; /** \name NSStream functions \{ */ CF_EXPORT void CFStreamCreatePairWithSocketToHost (CFAllocatorRef alloc, CFStringRef host, UInt32 port, CFReadStreamRef * readStream, CFWriteStreamRef * writeStream); #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) CF_EXPORT void CFStreamCreatePairWithPeerSocketSignature (CFAllocatorRef alloc, const CFSocketSignature * signature, CFReadStreamRef * readStream, CFWriteStreamRef * writeStream); #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT void CFStreamCreateBoundPair (CFAllocatorRef alloc, CFReadStreamRef * readStream, CFWriteStreamRef * writeStream, CFIndex transferBufferSize); #endif /** \} */ /** \} */ /** \defgroup CFWriteStreamRef CFWriteStream Reference \{ */ typedef void (*CFWriteStreamClientCallBack) (CFWriteStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo); /** \name Creating a Write Stream \{ */ CF_EXPORT CFWriteStreamRef CFWriteStreamCreateWithAllocatedBuffers (CFAllocatorRef alloc, CFAllocatorRef bufferAllocator); CF_EXPORT CFWriteStreamRef CFWriteStreamCreateWithBuffer (CFAllocatorRef alloc, UInt8 * buffer, CFIndex bufferCapacity); CF_EXPORT CFWriteStreamRef CFWriteStreamCreateWithFile (CFAllocatorRef alloc, CFURLRef fileURL); /** \} */ /** \name Opening and Closing a Write Stream \{ */ CF_EXPORT void CFWriteStreamClose (CFWriteStreamRef stream); CF_EXPORT Boolean CFWriteStreamOpen (CFWriteStreamRef stream); /** \} */ /** \name Writing to a Stream \{ */ CF_EXPORT CFIndex CFWriteStreamWrite (CFWriteStreamRef stream, const UInt8 * buffer, CFIndex bufferLength); /** \} */ /** \name Scheduling a Write Stream \{ */ CF_EXPORT void CFWriteStreamScheduleWithRunLoop (CFWriteStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode); CF_EXPORT void CFWriteStreamUnscheduleFromRunLoop (CFWriteStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode); /** \} */ /** \name Examining Write Stream Properties \{ */ CF_EXPORT Boolean CFWriteStreamCanAcceptBytes (CFWriteStreamRef stream); CF_EXPORT CFTypeRef CFWriteStreamCopyProperty (CFWriteStreamRef stream, CFStringRef propertyName); /** \} */ /* Deprecated function */ CF_EXPORT CFStreamError CFWriteStreamGetError (CFWriteStreamRef stream); CF_EXPORT CFStreamStatus CFWriteStreamGetStatus (CFWriteStreamRef stream); /** \name Setting Write Stream Properties \{ */ CF_EXPORT Boolean CFWriteStreamSetClient (CFWriteStreamRef stream, CFOptionFlags streamEvents, CFWriteStreamClientCallBack clientCB, CFStreamClientContext * clientContext); /** \} */ /** \name Getting the CFWriteStream Type ID \{ */ CF_EXPORT CFTypeID CFWriteStreamGetTypeID (void); /** \} */ /** \} */ /** \defgroup CFReadStreamRef CFReadStream Reference \{ */ typedef void (*CFReadStreamClientCallBack) (CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo); /** \name Creating a Read Stream \{ */ CF_EXPORT CFReadStreamRef CFReadStreamCreateWithBytesNoCopy (CFAllocatorRef alloc, const UInt8 * bytes, CFIndex length, CFAllocatorRef bytesDeallocator); CF_EXPORT CFReadStreamRef CFReadStreamCreateWithFile (CFAllocatorRef alloc, CFURLRef fileURL); /** \} */ /** \name Opening and Closing a Read Stream \{ */ CF_EXPORT void CFReadStreamClose (CFReadStreamRef stream); CF_EXPORT Boolean CFReadStreamOpen (CFReadStreamRef stream); /** \} */ /** \name Reading from a Read Stream \{ */ CF_EXPORT CFIndex CFReadStreamRead (CFReadStreamRef stream, UInt8 * buffer, CFIndex bufferLength); /** \} */ /** \name Scheduling a Read Stream \{ */ CF_EXPORT void CFReadStreamScheduleWithRunLoop (CFReadStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode); CF_EXPORT void CFReadStreamUnscheduleFromRunLoop (CFReadStreamRef stream, CFRunLoopRef runLoop, CFStringRef runLoopMode); /** \} */ /** \name Examining Stream Properties \{ */ CF_EXPORT CFTypeRef CFReadStreamCopyProperty (CFReadStreamRef stream, CFStringRef propertyName); CF_EXPORT const UInt8 *CFReadStreamGetBuffer (CFReadStreamRef stream, CFIndex maxBytesToRead, CFIndex * numBytesRead); /** \} */ /* Deprecated function */ CF_EXPORT CFStreamError CFReadStreamGetError (CFReadStreamRef stream); CF_EXPORT CFStreamStatus CFReadStreamGetStatus (CFReadStreamRef stream); CF_EXPORT Boolean CFReadStreamHasBytesAvailable (CFReadStreamRef stream); /** \name Setting Stream Properties \{ */ CF_EXPORT Boolean CFReadStreamSetClient (CFReadStreamRef stream, CFOptionFlags streamEvents, CFReadStreamClientCallBack clientCB, CFStreamClientContext * clientContext); /** \} */ /** \name Getting the CFReadStream Type ID \{ */ CF_EXPORT CFTypeID CFReadStreamGetTypeID (void); /** \} */ /** \} */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_2, GS_API_LATEST) CF_EXPORT Boolean CFWriteStreamSetProperty (CFWriteStreamRef stream, CFStringRef propertyName, CFTypeRef propertyValue); CF_EXPORT Boolean CFReadStreamSetProperty (CFReadStreamRef stream, CFStringRef propertyName, CFTypeRef propertyValue); #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT CFErrorRef CFWriteStreamCopyError (CFWriteStreamRef stream); CF_EXPORT CFErrorRef CFReadStreamCopyError (CFReadStreamRef stream); #endif #endif /* MAC_OS_X_VERSION_10_1 */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFSTREAM_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFAvailability.h0000644000175000017500000000321413222706330023167 0ustar yavoryavor/* CFAvailability.h Copyright (C) 2017 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: August, 2017 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFAVAILABILITY_H__ #define __COREFOUNDATION_CFAVAILABILITY_H__ /* Compiler features */ #ifndef __has_feature #define __has_feature(x) 0 #endif #ifndef __has_attribute #define __has_attribute(x) 0 #endif #ifndef __has_extension #define __has_extension(x) __has_feature #endif /* CFEnum macro for type definitions */ #if (__cplusplus && __cplusplus >= 201103L) #define CF_ENUM(_type, _name) _type _name; enum : _type #define CF_OPTIONS(_type, _name) _type _name; enum : _type #else #define CF_ENUM(_type, _name) _type _name; enum #define CF_OPTIONS(_type, _name) _type _name; enum #endif #endif /* __COREFOUNDATION_CFAVAILABILITY_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFStreamPriv.h0000644000175000017500000000534613222706330022661 0ustar yavoryavor/* CFStream.h Copyright (C) 2014 Free Software Foundation, Inc. Written by: Lubos Dolezel Date: February, 2014 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFSTREAMPRIV_H__ #define __COREFOUNDATION_CFSTREAMPRIV_H__ 1 #include #include /* * This header file is intended to be used by CFStream implementations, namely * by CFStream itself and CFNetwork. * */ struct CFWriteStreamImpl { void (*close)(CFWriteStreamRef); void (*finalize)(CFWriteStreamRef); Boolean (*open)(CFWriteStreamRef); CFIndex (*write)(CFWriteStreamRef, const UInt8 *, CFIndex); CFTypeRef (*copyProperty)(CFWriteStreamRef, CFStringRef); Boolean (*setProperty)(CFWriteStreamRef, CFStringRef, CFTypeRef); Boolean (*acceptBytes)(CFWriteStreamRef); }; struct __CFWriteStream { CFRuntimeBase parent; struct CFWriteStreamImpl impl; Boolean open, closed, failed; CFErrorRef error; /* callbacks when used with a runloop */ CFOptionFlags streamEvents; CFWriteStreamClientCallBack clientCB; }; struct CFReadStreamImpl { void (*close)(CFReadStreamRef); void (*finalize)(CFReadStreamRef); Boolean (*open)(CFReadStreamRef); CFIndex (*read)(CFReadStreamRef, UInt8 *, CFIndex); CFTypeRef (*copyProperty)(CFReadStreamRef, CFStringRef); Boolean (*setProperty)(CFReadStreamRef, CFStringRef, CFTypeRef); const UInt8* (*getBuffer)(CFReadStreamRef, CFIndex, CFIndex*); Boolean (*hasBytes)(CFReadStreamRef); }; struct __CFReadStream { CFRuntimeBase parent; struct CFReadStreamImpl impl; Boolean open, closed, failed; CFErrorRef error; /* callbacks when used with a runloop */ CFOptionFlags streamEvents; CFReadStreamClientCallBack clientCB; }; #endif gnustep-corebase-0.2/Headers/CoreFoundation/CFError.h0000644000175000017500000000553513222706330021656 0ustar yavoryavor/* CFError.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFERROR_H__ #define __COREFOUNDATION_CFERROR_H__ #include #include CF_EXTERN_C_BEGIN #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) /** \ingroup CFErrorRef */ typedef const struct __CFError * CFErrorRef; /** \defgroup CFErrorRef CFError Reference \{ */ CF_EXPORT const CFStringRef kCFErrorDomainPOSIX; CF_EXPORT const CFStringRef kCFErrorDomainOSStatus; CF_EXPORT const CFStringRef kCFErrorDomainMach; CF_EXPORT const CFStringRef kCFErrorDomainCocoa; CF_EXPORT const CFStringRef kCFErrorLocalizedDescriptionKey; CF_EXPORT const CFStringRef kCFErrorLocalizedFailureReasonKey; CF_EXPORT const CFStringRef kCFErrorLocalizedRecoverySuggestionKey; CF_EXPORT const CFStringRef kCFErrorDescriptionKey; CF_EXPORT const CFStringRef kCFErrorUnderlyingErrorKey; /** \name Creating a CFError \{ */ CF_EXPORT CFErrorRef CFErrorCreate (CFAllocatorRef allocator, CFStringRef domain, CFIndex code, CFDictionaryRef userInfo); CF_EXPORT CFErrorRef CFErrorCreateWithUserInfoKeysAndValues (CFAllocatorRef allocator, CFStringRef domain, CFIndex code, const void *const *userInfoKeys, const void *const *userInfoValues, CFIndex numUserInfoValues); /** \} */ /** \name Getting Information About an Error \{ */ CF_EXPORT CFStringRef CFErrorGetDomain (CFErrorRef err); CF_EXPORT CFIndex CFErrorGetCode (CFErrorRef err); CF_EXPORT CFDictionaryRef CFErrorCopyUserInfo (CFErrorRef err); CF_EXPORT CFStringRef CFErrorCopyDescription (CFErrorRef err); CF_EXPORT CFStringRef CFErrorCopyFailureReason (CFErrorRef err); CF_EXPORT CFStringRef CFErrorCopyRecoverySuggestion (CFErrorRef err); /** \} */ /** \name Getting the CFError Type ID \{ */ CF_EXPORT CFTypeID CFErrorGetTypeID (void); /** \} */ /** \} */ #endif /* MAC_OS_X_VERSION_10_5 */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFERROR_H__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFCalendar.h0000644000175000017500000001157113222706330022273 0ustar yavoryavor/* CFCalendar.h Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: March, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFCALENDAR__ #define __COREFOUNDATION_CFCALENDAR__ 1 #include #include #include #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXTERN_C_BEGIN /** \defgroup CFCalendarRef CFCalendar Reference \{ */ /** CFCalendar is "toll-free bridged" to NSCalendar. */ typedef struct __CFCalendar *CFCalendarRef; typedef enum { kCFCalendarUnitEra = (1UL << 1), kCFCalendarUnitYear = (1UL << 2), kCFCalendarUnitMonth = (1UL << 3), kCFCalendarUnitDay = (1UL << 4), kCFCalendarUnitHour = (1UL << 5), kCFCalendarUnitMinute = (1UL << 6), kCFCalendarUnitSecond = (1UL << 7), kCFCalendarUnitWeek = (1UL << 8), kCFCalendarUnitWeekday = (1UL << 9), kCFCalendarUnitWeekdayOrdinal = (1UL << 10), #if OS_API_VERSION(MAC_OS_X_VERSION_10_6, GS_API_LATEST) kCFCalendarUnitQuarter = (1UL << 11), #endif } CFCalendarUnit; enum { kCFCalendarComponentsWrap = (1UL << 0) }; /** \name Creating a Calendar \{ */ CF_EXPORT CFCalendarRef CFCalendarCopyCurrent (void); CF_EXPORT CFCalendarRef CFCalendarCreateWithIdentifier (CFAllocatorRef allocator, CFStringRef ident); /** \} */ /** \name Calendrical Calculations \{ */ CF_EXPORT Boolean CFCalendarAddComponents (CFCalendarRef cal, CFAbsoluteTime * at, CFOptionFlags options, const char *componentDesc, ...); CF_EXPORT Boolean CFCalendarComposeAbsoluteTime (CFCalendarRef cal, CFAbsoluteTime * at, const char *componentDesc, ...); CF_EXPORT Boolean CFCalendarDecomposeAbsoluteTime (CFCalendarRef cal, CFAbsoluteTime at, const char *componentDesc, ...); CF_EXPORT Boolean CFCalendarGetComponentDifference (CFCalendarRef cal, CFAbsoluteTime startinAT, CFAbsoluteTime resultAT, CFOptionFlags options, const char *componentDesc, ...); /** \} */ /** \name Getting Ranges of Units \{ */ CF_EXPORT CFRange CFCalendarGetRangeOfUnit (CFCalendarRef cal, CFCalendarUnit smallerUnit, CFCalendarUnit biggerUnit, CFAbsoluteTime at); CF_EXPORT CFIndex CFCalendarGetOrdinalityOfUnit (CFCalendarRef cal, CFCalendarUnit smallerUnit, CFCalendarUnit biggerUnit, CFAbsoluteTime at); CF_EXPORT CFRange CFCalendarGetMaximumRangeOfUnit (CFCalendarRef cal, CFCalendarUnit unit); CF_EXPORT CFRange CFCalendarGetMinimumRangeOfUnit (CFCalendarRef cal, CFCalendarUnit unit); #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT Boolean CFCalendarGetTimeRangeOfUnit (CFCalendarRef cal, CFCalendarUnit unit, CFAbsoluteTime at, CFAbsoluteTime * startp, CFTimeInterval * tip); #endif /** \} */ /** \name Getting and Setting the Time Zone \{ */ CF_EXPORT CFTimeZoneRef CFCalendarCopyTimeZone (CFCalendarRef cal); CF_EXPORT void CFCalendarSetTimeZone (CFCalendarRef cal, CFTimeZoneRef tz); /** \} */ /** \name Getting the Identifier \{ */ CF_EXPORT CFStringRef CFCalendarGetIdentifier (CFCalendarRef cal); /** \} */ /** \name Getting and Setting the Locale \{ */ CF_EXPORT CFLocaleRef CFCalendarCopyLocale (CFCalendarRef cal); CF_EXPORT void CFCalendarSetLocale (CFCalendarRef cal, CFLocaleRef locale); /** \} */ /** \name Getting and Setting Day Information \{ */ CF_EXPORT CFIndex CFCalendarGetFirstWeekday (CFCalendarRef cal); CF_EXPORT void CFCalendarSetFirstWeekday (CFCalendarRef cal, CFIndex wkdy); CF_EXPORT CFIndex CFCalendarGetMinimumDaysInFirstWeek (CFCalendarRef cal); CF_EXPORT void CFCalendarSetMinimumDaysInFirstWeek (CFCalendarRef cal, CFIndex mwd); /** \} */ /** \name Getting the Type ID \{ */ CF_EXPORT CFTypeID CFCalendarGetTypeID (void); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* MAC_OS_X_VERSION_10_4 */ #endif /* __COREFOUNDATION_CFCALENDAR__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFNumberFormatter.h0000644000175000017500000001675313222706330023705 0ustar yavoryavor/* CFNumberFormatter.h Copyright (C) 2011 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: March, 2011 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFNUMBERFORMATTER__ #define __COREFOUNDATION_CFNUMBERFORMATTER__ 1 #include #include #include #if OS_API_VERSION(MAC_OS_X_VERSION_10_3, GS_API_LATEST) CF_EXTERN_C_BEGIN /** \defgroup CFNumberFormatterRef CFNUmberFormatter Reference \brief CFNumberFormatter can be used to format and parse CFStrings into numbers. Unlike other Core Foundation types with similar names to Cocoa classes CFNumberFormatter is @b not "toll-free bridged" to NSNumberFormatter. \{ */ typedef struct __CFNumberFormatter *CFNumberFormatterRef; typedef CFOptionFlags CFNumberFormatterOptionFlags; enum { kCFNumberFormatterParseIntegersOnly = 1 }; typedef CFIndex CFNumberFormatterPadPosition; enum { kCFNumberFormatterPadBeforePrefix = 0, kCFNumberFormatterPadAfterPrefix = 1, kCFNumberFormatterPadBeforeSuffix = 2, kCFNumberFormatterPadAfterSuffix = 3 }; typedef enum { kCFNumberFormatterRoundCeiling = 0, kCFNumberFormatterRoundFloor = 1, kCFNumberFormatterRoundDown = 2, kCFNumberFormatterRoundUp = 3, kCFNumberFormatterRoundHalfEven = 4, kCFNumberFormatterRoundHalfDown = 5, kCFNumberFormatterRoundHalfUp = 6 } CFNumberFormatterRoundingMode; typedef enum { kCFNumberFormatterNoStyle = 0, kCFNumberFormatterDecimalStyle = 1, kCFNumberFormatterCurrencyStyle = 2, kCFNumberFormatterPercentStyle = 3, kCFNumberFormatterScientificStyle = 4, kCFNumberFormatterSpellOutStyle = 5 } CFNumberFormatterStyle; CF_EXPORT const CFStringRef kCFNumberFormatterCurrencyCode; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterDecimalSeparator; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterCurrencyDecimalSeparator; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterAlwaysShowDecimalSeparator; /* CFBoolean */ CF_EXPORT const CFStringRef kCFNumberFormatterGroupingSeparator; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterUseGroupingSeparator; /* CFBoolean */ CF_EXPORT const CFStringRef kCFNumberFormatterPercentSymbol; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterZeroSymbol; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterNaNSymbol; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterInfinitySymbol; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterMinusSign; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterPlusSign; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterCurrencySymbol; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterExponentSymbol; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterMinIntegerDigits; /* CFNumber */ CF_EXPORT const CFStringRef kCFNumberFormatterMaxIntegerDigits; /* CFNumber */ CF_EXPORT const CFStringRef kCFNumberFormatterMinFractionDigits; /* CFNumber */ CF_EXPORT const CFStringRef kCFNumberFormatterMaxFractionDigits; /* CFNumber */ CF_EXPORT const CFStringRef kCFNumberFormatterGroupingSize; /* CFNumber */ CF_EXPORT const CFStringRef kCFNumberFormatterSecondaryGroupingSize; /* CFNumber */ CF_EXPORT const CFStringRef kCFNumberFormatterRoundingMode; /* CFNumber */ CF_EXPORT const CFStringRef kCFNumberFormatterRoundingIncrement; /* CFNumber */ CF_EXPORT const CFStringRef kCFNumberFormatterFormatWidth; /* CFNumber */ CF_EXPORT const CFStringRef kCFNumberFormatterPaddingPosition; /* CFNumber */ CF_EXPORT const CFStringRef kCFNumberFormatterPaddingCharacter; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterDefaultFormat; /* CFString */ #if OS_API_VERSION(MAC_OS_X_VERSION_10_4, GS_API_LATEST) CF_EXPORT const CFStringRef kCFNumberFormatterMultiplier; /* CFNumber */ CF_EXPORT const CFStringRef kCFNumberFormatterPositivePrefix; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterPositiveSuffix; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterNegativePrefix; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterNegativeSuffix; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterPerMillSymbol; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterInternationalCurrencySymbol; /* CFString */ #endif #if OS_API_VERSION(MAC_OS_X_VERSION_10_5, GS_API_LATEST) CF_EXPORT const CFStringRef kCFNumberFormatterCurrencyGroupingSeparator; /* CFString */ CF_EXPORT const CFStringRef kCFNumberFormatterIsLenient; /* CFBoolean */ CF_EXPORT const CFStringRef kCFNumberFormatterUseSignificantDigits; /* CFBoolean */ CF_EXPORT const CFStringRef kCFNumberFormatterMinSignificantDigits; /* CFNumber */ CF_EXPORT const CFStringRef kCFNumberFormatterMaxSignificantDigits; /* CFNumber */ #endif /* * Creating a Number Formatter */ CF_EXPORT CFNumberFormatterRef CFNumberFormatterCreate (CFAllocatorRef allocator, CFLocaleRef locale, CFNumberFormatterStyle style); /* * Configuring a Number Formatter */ CF_EXPORT void CFNumberFormatterSetFormat (CFNumberFormatterRef formatter, CFStringRef formatString); CF_EXPORT void CFNumberFormatterSetProperty (CFNumberFormatterRef formatter, CFStringRef key, CFTypeRef value); /* * Formatting Values */ CF_EXPORT CFNumberRef CFNumberFormatterCreateNumberFromString (CFAllocatorRef allocator, CFNumberFormatterRef formatter, CFStringRef string, CFRange *rangep, CFOptionFlags options); CF_EXPORT CFStringRef CFNumberFormatterCreateStringWithNumber (CFAllocatorRef allocator, CFNumberFormatterRef formatter, CFNumberRef number); CF_EXPORT CFStringRef CFNumberFormatterCreateStringWithValue (CFAllocatorRef allocator, CFNumberFormatterRef formatter, CFNumberType numberType, const void *valuePtr); CF_EXPORT Boolean CFNumberFormatterGetDecimalInfoForCurrencyCode (CFStringRef currencyCode, SInt32 *defaultFractionDigits, double *roundingIncrement); CF_EXPORT Boolean CFNumberFormatterGetValueFromString (CFNumberFormatterRef formatter, CFStringRef string, CFRange *rangep, CFNumberType numberType, void *valuePtr); /* * Examining a Number Formatter */ CF_EXPORT CFTypeRef CFNumberFormatterCopyProperty (CFNumberFormatterRef formatter, CFStringRef key); CF_EXPORT CFStringRef CFNumberFormatterGetFormat (CFNumberFormatterRef formatter); CF_EXPORT CFLocaleRef CFNumberFormatterGetLocale (CFNumberFormatterRef formatter); CF_EXPORT CFNumberFormatterStyle CFNumberFormatterGetStyle (CFNumberFormatterRef formatter); /* * Getting the CFNumberFormatter Type ID */ CF_EXPORT CFTypeID CFNumberFormatterGetTypeID (void); /** \} */ CF_EXTERN_C_END #endif /* MAC_OS_X_VERSION_10_3 */ #endif /* __COREFOUNDATION_CFNUMBERFORMATTER__ */ gnustep-corebase-0.2/Headers/CoreFoundation/CFSet.h0000644000175000017500000000770213222706330021316 0ustar yavoryavor/* CFSet.h Copyright (C) 2010 Free Software Foundation, Inc. Written by: Stefan Bidigaray Date: January, 2010 This file is part of the GNUstep CoreBase Library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; see the file COPYING.LIB. If not, see or write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef __COREFOUNDATION_CFSET_H__ #define __COREFOUNDATION_CFSET_H__ 1 #include CF_EXTERN_C_BEGIN /** \ingroup CFSetRef */ typedef const struct __CFSet *CFSetRef; /** \ingroup CFMutableSetRef */ typedef struct __CFSet *CFMutableSetRef; /** \defgroup CFSetRef CFSet Reference \{ */ typedef void (*CFSetApplierFunction) (const void *value, void *context); typedef CFStringRef (*CFSetCopyDescriptionCallBack) (const void *value); typedef Boolean (*CFSetEqualCallBack) (const void *value1, const void *value2); typedef CFHashCode (*CFSetHashCallBack) (const void *value); typedef void (*CFSetReleaseCallBack) (CFAllocatorRef alloc, const void *value); typedef const void *(*CFSetRetainCallBack) (CFAllocatorRef alloc, const void *value); typedef struct CFSetCallBacks CFSetCallBacks; struct CFSetCallBacks { CFIndex version; CFSetRetainCallBack retain; CFSetReleaseCallBack release; CFSetCopyDescriptionCallBack copyDescription; CFSetEqualCallBack equal; CFSetHashCallBack hash; }; CF_EXPORT const CFSetCallBacks kCFCopyStringSetCallBacks; CF_EXPORT const CFSetCallBacks kCFTypeSetCallBacks; /** \name Creating a set */ CF_EXPORT CFSetRef CFSetCreate (CFAllocatorRef alloc, const void **values, CFIndex numValues, const CFSetCallBacks * callBacks); CF_EXPORT CFSetRef CFSetCreateCopy (CFAllocatorRef alloc, CFSetRef set); /** \} */ /** \name Examining a set \{ */ CF_EXPORT Boolean CFSetContainsValue (CFSetRef set, const void *value); CF_EXPORT CFIndex CFSetGetCount (CFSetRef set); CF_EXPORT CFIndex CFSetGetCountOfValue (CFSetRef set, const void *value); CF_EXPORT void CFSetGetValues (CFSetRef set, const void **values); CF_EXPORT const void *CFSetGetValue (CFSetRef set, const void *value); CF_EXPORT Boolean CFSetGetValueIfPresent (CFSetRef set, const void *candidate, const void **value); /** \} */ /** \name Applying a funcation to a set \{ */ CF_EXPORT void CFSetApplyFunction (CFSetRef set, CFSetApplierFunction applier, void *context); /** \} */ /** \name Getting the CFSet type ID \{ */ CF_EXPORT CFTypeID CFSetGetTypeID (void); /** \} */ /** \} */ /** \defgroup CFMutableSetRef CFMutableSet Reference \{ */ /** \name Creating a Mutable Set \{ */ CF_EXPORT CFMutableSetRef CFSetCreateMutable (CFAllocatorRef alloc, CFIndex capacity, const CFSetCallBacks * callBacks); CF_EXPORT CFMutableSetRef CFSetCreateMutableCopy (CFAllocatorRef alloc, CFIndex capacity, CFSetRef set); /** \} */ /** \name Modifying a Set \{ */ CF_EXPORT void CFSetAddValue (CFMutableSetRef set, const void *value); CF_EXPORT void CFSetRemoveAllValues (CFMutableSetRef set); CF_EXPORT void CFSetRemoveValue (CFMutableSetRef set, const void *value); CF_EXPORT void CFSetReplaceValue (CFMutableSetRef set, const void *value); CF_EXPORT void CFSetSetValue (CFMutableSetRef set, const void *value); /** \} */ /** \} */ CF_EXTERN_C_END #endif /* __COREFOUNDATION_CFSET_H__ */ gnustep-corebase-0.2/README0000644000175000017500000000356113222706330014566 0ustar yavoryavor1 README ******** The GNUstep CoreBase Library is a library of general-purpose, non-graphical C objects. For example, it includes types for strings, collections, byte streams, typed coders, invocations, notifications, notification dispatchers, moments in time, network ports, and event loops. It provides functionality that aims to implement the non-graphical portion of Apple's CoreFoundation framework. 1.1 Initial reading =================== The files `INSTALL' or `GNUstep-HOWTO' (from the web site) gives instructions for installing the library. 1.2 License =========== The GNUstep libraries and library resources are covered under the GNU Lesser General Public License. This means you can use these libraries in any program (even non-free programs). If you distribute the libraries along with your program, you must make the improvements you have made to the libraries freely available. You should read the COPYING.LIB file for more information. All files in the 'Source', 'Headers' directories are covered under the GNU LGPL. GNUstep test programs, and other files are covered under the GNU General Public License. This means if you make changes to these programs, you cannot charge a fee, other than distribution fees, for others to use the program. You should read the COPYING file for more information. All files in the 'Test', directory is covered under the GPL. 1.3 How can you help? ===================== * Give us feedback! Tell us what you like; tell us what you think could be better. Please log bug reports on the GNUstep project page `http://savannah.gnu.org/bugs/?group=gnustep' or send bug reports to . Happy hacking! Copyright (C) 2005 Free Software Foundation Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved.