Index: Doxyfile
==================================================================
--- Doxyfile
+++ Doxyfile
@@ -4,10 +4,11 @@
FILE_PATTERNS = *.h *.m
HTML_OUTPUT = .
GENERATE_LATEX = NO
HIDE_UNDOC_CLASSES = YES
HIDE_UNDOC_MEMBERS = YES
+TYPEDEF_HIDES_STRUCT = YES
PREDEFINED = __OBJC__ \
DOXYGEN \
OF_BOXABLE \
OF_CONSUMED \
OF_DESIGNATED_INITIALIZER \
Index: README.md
==================================================================
--- README.md
+++ README.md
@@ -159,19 +159,19 @@
$ clang="clang -isysroot $(xcrun --sdk iphoneos --show-sdk-path)"
$ export OBJC="$clang -arch armv7 -arch arm64"
$ export OBJCPP="$clang -arch armv7 -E"
$ export IPHONEOS_DEPLOYMENT_TARGET="9.0"
- $ ./configure --prefix=/usr/local/ios --host=arm-apple-darwin
+ $ ./configure --prefix=/usr/local/ios --host=arm64-apple-darwin
To build for the iOS simulator, use something like this:
$ clang="clang -isysroot $(xcrun --sdk iphonesimulator --show-sdk-path)"
$ export OBJC="$clang -arch i386 -arch x86_64"
$ export OBJCPP="$clang -arch i386 -E"
$ export IPHONEOS_DEPLOYMENT_TARGET="9.0"
- $ ./configure --prefix=/usr/local/iossim --host=i386-apple-darwin
+ $ ./configure --prefix=/usr/local/iossim --host=x86_64-apple-darwin
Using the macOS or iOS framework in Xcode
To use the macOS framework in Xcode, you need to add the `.framework`s to
your project and add the following flags to `Other C Flags`:
@@ -315,11 +315,11 @@
This creates a file `MyFirstApp.m`. The `-[applicationDidFinishLaunching]`
method is called as soon as ObjFW finished all initialization. Use this as
the entry point to your own code. For example, you could add the following
line there to create a "Hello World":
- [of_stdout writeLine: @"Hello World!"];
+ [OFStdOut writeLine: @"Hello World!"];
You can compile your new app using `objfw-compile`:
$ objfw-compile -o MyFirstApp MyFirstApp.m
Index: generators/unicode/TableGenerator.h
==================================================================
--- generators/unicode/TableGenerator.h
+++ generators/unicode/TableGenerator.h
@@ -20,31 +20,31 @@
@interface TableGenerator: OFObject
{
OFHTTPClient *_HTTPClient;
- of_unichar_t _uppercaseTable[0x110000];
- of_unichar_t _lowercaseTable[0x110000];
- of_unichar_t _titlecaseTable[0x110000];
- of_unichar_t _casefoldingTable[0x110000];
+ OFUnichar _uppercaseTable[0x110000];
+ OFUnichar _lowercaseTable[0x110000];
+ OFUnichar _titlecaseTable[0x110000];
+ OFUnichar _caseFoldingTable[0x110000];
OFString *_decompositionTable[0x110000];
OFString *_decompositionCompatTable[0x110000];
char _uppercaseTableUsed[0x1100];
char _lowercaseTableUsed[0x1100];
char _titlecaseTableUsed[0x1100];
- char _casefoldingTableUsed[0x1100];
+ char _caseFoldingTableUsed[0x1100];
char _decompositionTableUsed[0x1100];
char _decompositionCompatTableUsed[0x1100];
size_t _uppercaseTableSize;
size_t _lowercaseTableSize;
size_t _titlecaseTableSize;
- size_t _casefoldingTableSize;
+ size_t _caseFoldingTableSize;
size_t _decompositionTableSize;
size_t _decompositionCompatTableSize;
enum {
- STATE_UNICODE_DATA,
- STATE_CASE_FOLDING
+ stateUnicodeData,
+ stateCaseFolding
} _state;
}
- (void)parseUnicodeData: (OFHTTPResponse *)response;
- (void)parseCaseFolding: (OFHTTPResponse *)response;
Index: generators/unicode/TableGenerator.m
==================================================================
--- generators/unicode/TableGenerator.m
+++ generators/unicode/TableGenerator.m
@@ -30,14 +30,14 @@
#import "OFOutOfRangeException.h"
#import "TableGenerator.h"
#import "copyright.h"
-#define UNICODE_DATA_URL \
- @"http://www.unicode.org/Public/UNIDATA/UnicodeData.txt"
-#define CASE_FOLDING_URL \
- @"http://www.unicode.org/Public/UNIDATA/CaseFolding.txt"
+static OFString *const unicodeDataURL =
+ @"http://www.unicode.org/Public/UNIDATA/UnicodeData.txt";
+static OFString *const caseFoldingURL =
+ @"http://www.unicode.org/Public/UNIDATA/CaseFolding.txt";
OF_APPLICATION_DELEGATE(TableGenerator)
@implementation TableGenerator
- (instancetype)init
@@ -49,11 +49,11 @@
_HTTPClient.delegate = self;
_uppercaseTableSize = SIZE_MAX;
_lowercaseTableSize = SIZE_MAX;
_titlecaseTableSize = SIZE_MAX;
- _casefoldingTableSize = SIZE_MAX;
+ _caseFoldingTableSize = SIZE_MAX;
_decompositionTableSize = SIZE_MAX;
_decompositionCompatTableSize = SIZE_MAX;
} @catch (id e) {
@throw e;
[self release];
@@ -64,14 +64,14 @@
- (void)applicationDidFinishLaunching
{
OFHTTPRequest *request;
- [of_stdout writeString: @"Downloading UnicodeData.txt…"];
- _state = STATE_UNICODE_DATA;
+ [OFStdOut writeString: @"Downloading UnicodeData.txt…"];
+ _state = stateUnicodeData;
request = [OFHTTPRequest requestWithURL:
- [OFURL URLWithString: UNICODE_DATA_URL]];
+ [OFURL URLWithString: unicodeDataURL]];
[_HTTPClient asyncPerformRequest: request];
}
- (void)client: (OFHTTPClient *)client
didPerformRequest: (OFHTTPRequest *)request
@@ -79,17 +79,17 @@
exception: (id)exception
{
if (exception != nil)
@throw exception;
- [of_stdout writeLine: @" done"];
+ [OFStdOut writeLine: @" done"];
switch (_state) {
- case STATE_UNICODE_DATA:
+ case stateUnicodeData:
[self parseUnicodeData: response];
break;
- case STATE_CASE_FOLDING:
+ case stateCaseFolding:
[self parseCaseFolding: response];
break;
}
}
@@ -96,39 +96,39 @@
- (void)parseUnicodeData: (OFHTTPResponse *)response
{
OFString *line;
OFHTTPRequest *request;
- [of_stdout writeString: @"Parsing UnicodeData.txt…"];
+ [OFStdOut writeString: @"Parsing UnicodeData.txt…"];
while ((line = [response readLine]) != nil) {
void *pool2;
OFArray OF_GENERIC(OFString *) *components;
- of_unichar_t codePoint;
+ OFUnichar codePoint;
if (line.length == 0)
continue;
pool2 = objc_autoreleasePoolPush();
components = [line componentsSeparatedByString: @";"];
if (components.count != 15) {
- of_log(@"Invalid line: %@\n", line);
+ OFLog(@"Invalid line: %@\n", line);
[OFApplication terminateWithStatus: 1];
}
- codePoint = (of_unichar_t)[[components objectAtIndex: 0]
+ codePoint = (OFUnichar)[[components objectAtIndex: 0]
unsignedLongLongValueWithBase: 16];
if (codePoint > 0x10FFFF)
@throw [OFOutOfRangeException exception];
- _uppercaseTable[codePoint] = (of_unichar_t)[[components
+ _uppercaseTable[codePoint] = (OFUnichar)[[components
objectAtIndex: 12] unsignedLongLongValueWithBase: 16];
- _lowercaseTable[codePoint] = (of_unichar_t)[[components
+ _lowercaseTable[codePoint] = (OFUnichar)[[components
objectAtIndex: 13] unsignedLongLongValueWithBase: 16];
- _titlecaseTable[codePoint] = (of_unichar_t)[[components
+ _titlecaseTable[codePoint] = (OFUnichar)[[components
objectAtIndex: 14] unsignedLongLongValueWithBase: 16];
if ([[components objectAtIndex: 5] length] > 0) {
OFArray *decomposed = [[components objectAtIndex: 5]
componentsSeparatedByString: @" "];
@@ -135,18 +135,18 @@
bool compat = false;
OFMutableString *string;
if ([decomposed.firstObject hasPrefix: @"<"]) {
decomposed = [decomposed objectsInRange:
- of_range(1, decomposed.count - 1)];
+ OFRangeMake(1, decomposed.count - 1)];
compat = true;
}
string = [OFMutableString string];
for (OFString *character in decomposed) {
- of_unichar_t unichar = (of_unichar_t)[character
+ OFUnichar unichar = (OFUnichar)[character
unsignedLongLongValueWithBase: 16];
[string appendCharacters: &unichar
length: 1];
}
@@ -162,58 +162,58 @@
}
[self applyDecompositionRecursivelyForTable: _decompositionTable];
[self applyDecompositionRecursivelyForTable: _decompositionCompatTable];
- [of_stdout writeLine: @" done"];
+ [OFStdOut writeLine: @" done"];
- [of_stdout writeString: @"Downloading CaseFolding.txt…"];
- _state = STATE_CASE_FOLDING;
+ [OFStdOut writeString: @"Downloading CaseFolding.txt…"];
+ _state = stateCaseFolding;
request = [OFHTTPRequest requestWithURL:
- [OFURL URLWithString: CASE_FOLDING_URL]];
+ [OFURL URLWithString: caseFoldingURL]];
[_HTTPClient asyncPerformRequest: request];
}
- (void)parseCaseFolding: (OFHTTPResponse *)response
{
OFString *line;
- [of_stdout writeString: @"Parsing CaseFolding.txt…"];
+ [OFStdOut writeString: @"Parsing CaseFolding.txt…"];
while ((line = [response readLine]) != nil) {
void *pool2;
OFArray OF_GENERIC(OFString *) *components;
- of_unichar_t codePoint;
+ OFUnichar codePoint;
if (line.length == 0 || [line hasPrefix: @"#"])
continue;
pool2 = objc_autoreleasePoolPush();
components = [line componentsSeparatedByString: @"; "];
if (components.count != 4) {
- of_log(@"Invalid line: %s\n", line);
+ OFLog(@"Invalid line: %s\n", line);
[OFApplication terminateWithStatus: 1];
}
if (![[components objectAtIndex: 1] isEqual: @"S"] &&
![[components objectAtIndex: 1] isEqual: @"C"])
continue;
- codePoint = (of_unichar_t)[[components objectAtIndex: 0]
+ codePoint = (OFUnichar)[[components objectAtIndex: 0]
unsignedLongLongValueWithBase: 16];
if (codePoint > 0x10FFFF)
@throw [OFOutOfRangeException exception];
- _casefoldingTable[codePoint] = (of_unichar_t)[[components
+ _caseFoldingTable[codePoint] = (OFUnichar)[[components
objectAtIndex: 2] unsignedLongLongValueWithBase: 16];
objc_autoreleasePoolPop(pool2);
}
- [of_stdout writeLine: @" done"];
+ [OFStdOut writeLine: @" done"];
[self writeFiles];
}
- (void)applyDecompositionRecursivelyForTable: (OFString *[0x110000])table
@@ -221,13 +221,13 @@
bool done;
do {
done = true;
- for (of_unichar_t i = 0; i < 0x110000; i++) {
+ for (OFUnichar i = 0; i < 0x110000; i++) {
void *pool;
- const of_unichar_t *characters;
+ const OFUnichar *characters;
size_t length;
OFMutableString *replacement;
bool changed = false;
if (table[i] == nil)
@@ -270,19 +270,19 @@
- (void)writeFiles
{
OFURL *URL;
- [of_stdout writeString: @"Writing files…"];
+ [OFStdOut writeString: @"Writing files…"];
URL = [OFURL fileURLWithPath: @"../../src/unicode.m"];
[self writeTablesToFile: URL.fileSystemRepresentation];
URL = [OFURL fileURLWithPath: @"../../src/unicode.h"];
[self writeHeaderToFile: URL.fileSystemRepresentation];
- [of_stdout writeLine: @" done"];
+ [OFStdOut writeLine: @" done"];
[OFApplication terminate];
}
- (void)writeTablesToFile: (OFString *)path
@@ -293,19 +293,19 @@
[file writeString: COPYRIGHT
@"#include \"config.h\"\n"
@"\n"
@"#import \"OFString.h\"\n\n"
- @"static const of_unichar_t emptyPage[0x100] = { 0 };\n"
+ @"static const OFUnichar emptyPage[0x100] = { 0 };\n"
@"static const char *emptyDecompositionPage[0x100] = { NULL };\n"
@"\n"];
/* Write uppercasePage%u */
- for (of_unichar_t i = 0; i < 0x110000; i += 0x100) {
+ for (OFUnichar i = 0; i < 0x110000; i += 0x100) {
bool isEmpty = true;
- for (of_unichar_t j = i; j < i + 0x100; j++) {
+ for (OFUnichar j = i; j < i + 0x100; j++) {
if (_uppercaseTable[j] != 0) {
isEmpty = false;
_uppercaseTableSize = i >> 8;
_uppercaseTableUsed[_uppercaseTableSize] = 1;
break;
@@ -313,15 +313,15 @@
}
if (!isEmpty) {
void *pool2 = objc_autoreleasePoolPush();
- [file writeFormat: @"static const of_unichar_t "
+ [file writeFormat: @"static const OFUnichar "
@"uppercasePage%u[0x100] = {\n",
i >> 8];
- for (of_unichar_t j = i; j < i + 0x100; j += 8)
+ for (OFUnichar j = i; j < i + 0x100; j += 8)
[file writeFormat:
@"\t%u, %u, %u, %u, %u, %u, %u, %u,\n",
_uppercaseTable[j],
_uppercaseTable[j + 1],
_uppercaseTable[j + 2],
@@ -336,14 +336,14 @@
objc_autoreleasePoolPop(pool2);
}
}
/* Write lowercasePage%u */
- for (of_unichar_t i = 0; i < 0x110000; i += 0x100) {
+ for (OFUnichar i = 0; i < 0x110000; i += 0x100) {
bool isEmpty = true;
- for (of_unichar_t j = i; j < i + 0x100; j++) {
+ for (OFUnichar j = i; j < i + 0x100; j++) {
if (_lowercaseTable[j] != 0) {
isEmpty = false;
_lowercaseTableSize = i >> 8;
_lowercaseTableUsed[_lowercaseTableSize] = 1;
break;
@@ -351,15 +351,15 @@
}
if (!isEmpty) {
void *pool2 = objc_autoreleasePoolPush();
- [file writeFormat: @"static const of_unichar_t "
+ [file writeFormat: @"static const OFUnichar "
@"lowercasePage%u[0x100] = {\n",
i >> 8];
- for (of_unichar_t j = i; j < i + 0x100; j += 8)
+ for (OFUnichar j = i; j < i + 0x100; j += 8)
[file writeFormat:
@"\t%u, %u, %u, %u, %u, %u, %u, %u,\n",
_lowercaseTable[j],
_lowercaseTable[j + 1],
_lowercaseTable[j + 2],
@@ -374,18 +374,18 @@
objc_autoreleasePoolPop(pool2);
}
}
/* Write titlecasePage%u if it does NOT match uppercasePage%u */
- for (of_unichar_t i = 0; i < 0x110000; i += 0x100) {
+ for (OFUnichar i = 0; i < 0x110000; i += 0x100) {
bool isEmpty = true;
- for (of_unichar_t j = i; j < i + 0x100; j++) {
+ for (OFUnichar j = i; j < i + 0x100; j++) {
if (_titlecaseTable[j] != 0) {
isEmpty = !memcmp(_uppercaseTable + i,
_titlecaseTable + i,
- 256 * sizeof(of_unichar_t));
+ 256 * sizeof(OFUnichar));
_titlecaseTableSize = i >> 8;
_titlecaseTableUsed[_titlecaseTableSize] =
(isEmpty ? 2 : 1);
break;
}
@@ -392,15 +392,15 @@
}
if (!isEmpty) {
void *pool2 = objc_autoreleasePoolPush();
- [file writeFormat: @"static const of_unichar_t "
+ [file writeFormat: @"static const OFUnichar "
@"titlecasePage%u[0x100] = {\n",
i >> 8];
- for (of_unichar_t j = i; j < i + 0x100; j += 8)
+ for (OFUnichar j = i; j < i + 0x100; j += 8)
[file writeFormat:
@"\t%u, %u, %u, %u, %u, %u, %u, %u,\n",
_titlecaseTable[j],
_titlecaseTable[j + 1],
_titlecaseTable[j + 2],
@@ -414,56 +414,56 @@
objc_autoreleasePoolPop(pool2);
}
}
- /* Write casefoldingPage%u if it does NOT match lowercasePage%u */
- for (of_unichar_t i = 0; i < 0x110000; i += 0x100) {
+ /* Write caseFoldingPage%u if it does NOT match lowercasePage%u */
+ for (OFUnichar i = 0; i < 0x110000; i += 0x100) {
bool isEmpty = true;
- for (of_unichar_t j = i; j < i + 0x100; j++) {
- if (_casefoldingTable[j] != 0) {
+ for (OFUnichar j = i; j < i + 0x100; j++) {
+ if (_caseFoldingTable[j] != 0) {
isEmpty = !memcmp(_lowercaseTable + i,
- _casefoldingTable + i,
- 256 * sizeof(of_unichar_t));
- _casefoldingTableSize = i >> 8;
- _casefoldingTableUsed[_casefoldingTableSize] =
+ _caseFoldingTable + i,
+ 256 * sizeof(OFUnichar));
+ _caseFoldingTableSize = i >> 8;
+ _caseFoldingTableUsed[_caseFoldingTableSize] =
(isEmpty ? 2 : 1);
break;
}
}
if (!isEmpty) {
void *pool2 = objc_autoreleasePoolPush();
- [file writeFormat: @"static const of_unichar_t "
- @"casefoldingPage%u[0x100] = {\n",
+ [file writeFormat: @"static const OFUnichar "
+ @"caseFoldingPage%u[0x100] = {\n",
i >> 8];
- for (of_unichar_t j = i; j < i + 0x100; j += 8)
+ for (OFUnichar j = i; j < i + 0x100; j += 8)
[file writeFormat:
@"\t%u, %u, %u, %u, %u, %u, %u, %u,\n",
- _casefoldingTable[j],
- _casefoldingTable[j + 1],
- _casefoldingTable[j + 2],
- _casefoldingTable[j + 3],
- _casefoldingTable[j + 4],
- _casefoldingTable[j + 5],
- _casefoldingTable[j + 6],
- _casefoldingTable[j + 7]];
+ _caseFoldingTable[j],
+ _caseFoldingTable[j + 1],
+ _caseFoldingTable[j + 2],
+ _caseFoldingTable[j + 3],
+ _caseFoldingTable[j + 4],
+ _caseFoldingTable[j + 5],
+ _caseFoldingTable[j + 6],
+ _caseFoldingTable[j + 7]];
[file writeString: @"};\n\n"];
objc_autoreleasePoolPop(pool2);
}
}
/* Write decompositionPage%u */
- for (of_unichar_t i = 0; i < 0x110000; i += 0x100) {
+ for (OFUnichar i = 0; i < 0x110000; i += 0x100) {
bool isEmpty = true;
- for (of_unichar_t j = i; j < i + 0x100; j++) {
+ for (OFUnichar j = i; j < i + 0x100; j++) {
if (_decompositionTable[j] != nil) {
isEmpty = false;
_decompositionTableSize = i >> 8;
_decompositionTableUsed[
_decompositionTableSize] = 1;
@@ -476,11 +476,11 @@
[file writeFormat: @"static const char *const "
@"decompositionPage%u[0x100] = {\n",
i >> 8];
- for (of_unichar_t j = i; j < i + 0x100; j++) {
+ for (OFUnichar j = i; j < i + 0x100; j++) {
if ((j - i) % 2 == 0)
[file writeString: @"\t"];
else
[file writeString: @" "];
@@ -510,14 +510,14 @@
objc_autoreleasePoolPop(pool2);
}
}
/* Write decompCompatPage%u if it does NOT match decompositionPage%u */
- for (of_unichar_t i = 0; i < 0x110000; i += 0x100) {
+ for (OFUnichar i = 0; i < 0x110000; i += 0x100) {
bool isEmpty = true;
- for (of_unichar_t j = i; j < i + 0x100; j++) {
+ for (OFUnichar j = i; j < i + 0x100; j++) {
if (_decompositionCompatTable[j] != 0) {
/*
* We bulk-compare pointers via memcmp here.
* This is safe, as we always set the same
* pointer in both tables if both are the same.
@@ -539,11 +539,11 @@
[file writeFormat: @"static const char *const "
@"decompCompatPage%u[0x100] = {\n",
i >> 8];
- for (of_unichar_t j = i; j < i + 0x100; j++) {
+ for (OFUnichar j = i; j < i + 0x100; j++) {
if ((j - i) % 2 == 0)
[file writeString: @"\t"];
else
[file writeString: @" "];
@@ -581,20 +581,20 @@
* But from now on, we need the size.
*/
_uppercaseTableSize++;
_lowercaseTableSize++;
_titlecaseTableSize++;
- _casefoldingTableSize++;
+ _caseFoldingTableSize++;
_decompositionTableSize++;
_decompositionCompatTableSize++;
- /* Write of_unicode_uppercase_table */
- [file writeFormat: @"const of_unichar_t *const "
- @"of_unicode_uppercase_table[0x%X] = {\n\t",
+ /* Write OFUnicodeUppercaseTable */
+ [file writeFormat: @"const OFUnichar *const "
+ @"OFUnicodeUppercaseTable[0x%X] = {\n\t",
_uppercaseTableSize];
- for (of_unichar_t i = 0; i < _uppercaseTableSize; i++) {
+ for (OFUnichar i = 0; i < _uppercaseTableSize; i++) {
if (_uppercaseTableUsed[i])
[file writeFormat: @"uppercasePage%u", i];
else
[file writeString: @"emptyPage"];
@@ -606,16 +606,16 @@
}
}
[file writeString: @"\n};\n\n"];
- /* Write of_unicode_lowercase_table */
- [file writeFormat: @"const of_unichar_t *const "
- @"of_unicode_lowercase_table[0x%X] = {\n\t",
+ /* Write OFUnicodeLowercaseTable */
+ [file writeFormat: @"const OFUnichar *const "
+ @"OFUnicodeLowercaseTable[0x%X] = {\n\t",
_lowercaseTableSize];
- for (of_unichar_t i = 0; i < _lowercaseTableSize; i++) {
+ for (OFUnichar i = 0; i < _lowercaseTableSize; i++) {
if (_lowercaseTableUsed[i])
[file writeFormat: @"lowercasePage%u", i];
else
[file writeString: @"emptyPage"];
@@ -627,16 +627,16 @@
}
}
[file writeString: @"\n};\n\n"];
- /* Write of_unicode_titlecase_table */
- [file writeFormat: @"const of_unichar_t *const "
- @"of_unicode_titlecase_table[0x%X] = {\n\t",
+ /* Write OFUnicodeTitlecaseTable */
+ [file writeFormat: @"const OFUnichar *const "
+ @"OFUnicodeTitlecaseTable[0x%X] = {\n\t",
_titlecaseTableSize];
- for (of_unichar_t i = 0; i < _titlecaseTableSize; i++) {
+ for (OFUnichar i = 0; i < _titlecaseTableSize; i++) {
if (_titlecaseTableUsed[i] == 1)
[file writeFormat: @"titlecasePage%u", i];
else if (_titlecaseTableUsed[i] == 2)
[file writeFormat: @"uppercasePage%u", i];
else
@@ -650,39 +650,39 @@
}
}
[file writeString: @"\n};\n\n"];
- /* Write of_unicode_casefolding_table */
- [file writeFormat: @"const of_unichar_t *const "
- @"of_unicode_casefolding_table[0x%X] = {\n\t",
- _casefoldingTableSize];
-
- for (of_unichar_t i = 0; i < _casefoldingTableSize; i++) {
- if (_casefoldingTableUsed[i] == 1)
- [file writeFormat: @"casefoldingPage%u", i];
- else if (_casefoldingTableUsed[i] == 2)
+ /* Write OFUnicodeCaseFoldingTable */
+ [file writeFormat: @"const OFUnichar *const "
+ @"OFUnicodeCaseFoldingTable[0x%X] = {\n\t",
+ _caseFoldingTableSize];
+
+ for (OFUnichar i = 0; i < _caseFoldingTableSize; i++) {
+ if (_caseFoldingTableUsed[i] == 1)
+ [file writeFormat: @"caseFoldingPage%u", i];
+ else if (_caseFoldingTableUsed[i] == 2)
[file writeFormat: @"lowercasePage%u", i];
else
[file writeString: @"emptyPage"];
- if (i + 1 < _casefoldingTableSize) {
+ if (i + 1 < _caseFoldingTableSize) {
if ((i + 1) % 3 == 0)
[file writeString: @",\n\t"];
else
[file writeString: @", "];
}
}
[file writeString: @"\n};\n\n"];
- /* Write of_unicode_decomposition_table */
+ /* Write OFUnicodeDecompositionTable */
[file writeFormat: @"const char *const "
- @"*of_unicode_decomposition_table[0x%X] = {\n\t",
+ @"*OFUnicodeDecompositionTable[0x%X] = {\n\t",
_decompositionTableSize];
- for (of_unichar_t i = 0; i < _decompositionTableSize; i++) {
+ for (OFUnichar i = 0; i < _decompositionTableSize; i++) {
if (_decompositionTableUsed[i])
[file writeFormat: @"decompositionPage%u", i];
else
[file writeString: @"emptyDecompositionPage"];
@@ -694,17 +694,17 @@
}
}
[file writeString: @"\n};\n\n"];
- /* Write of_unicode_decomposition_compat_table */
+ /* Write OFUnicodeDecompositionCompatTable */
[file writeFormat: @"const char *const "
- @"*of_unicode_decomposition_compat_table[0x%X] = {"
+ @"*OFUnicodeDecompositionCompatTable[0x%X] = {"
@"\n\t",
_decompositionCompatTableSize];
- for (of_unichar_t i = 0; i < _decompositionCompatTableSize; i++) {
+ for (OFUnichar i = 0; i < _decompositionCompatTableSize; i++) {
if (_decompositionCompatTableUsed[i] == 1)
[file writeFormat: @"decompCompatPage%u", i];
else if (_decompositionCompatTableUsed[i] == 2)
[file writeFormat: @"decompositionPage%u", i];
else
@@ -731,44 +731,40 @@
[file writeString: COPYRIGHT
@"#import \"OFString.h\"\n\n"];
[file writeFormat:
- @"#define OF_UNICODE_UPPERCASE_TABLE_SIZE 0x%X\n"
- @"#define OF_UNICODE_LOWERCASE_TABLE_SIZE 0x%X\n"
- @"#define OF_UNICODE_TITLECASE_TABLE_SIZE 0x%X\n"
- @"#define OF_UNICODE_CASEFOLDING_TABLE_SIZE 0x%X\n"
- @"#define OF_UNICODE_DECOMPOSITION_TABLE_SIZE 0x%X\n"
- @"#define OF_UNICODE_DECOMPOSITION_COMPAT_TABLE_SIZE 0x%X\n\n",
+ @"#define OFUnicodeUppercaseTableSize 0x%X\n"
+ @"#define OFUnicodeLowercaseTableSize 0x%X\n"
+ @"#define OFUnicodeTitlecaseTableSize 0x%X\n"
+ @"#define OFUnicodeCaseFoldingTableSize 0x%X\n"
+ @"#define OFUnicodeDecompositionTableSize 0x%X\n"
+ @"#define OFUnicodeDecompositionCompatTableSize 0x%X\n\n",
_uppercaseTableSize, _lowercaseTableSize, _titlecaseTableSize,
- _casefoldingTableSize, _decompositionTableSize,
+ _caseFoldingTableSize, _decompositionTableSize,
_decompositionCompatTableSize];
[file writeString:
@"#ifdef __cplusplus\n"
@"extern \"C\" {\n"
@"#endif\n"
- @"extern const of_unichar_t *const _Nonnull\n"
- @" of_unicode_uppercase_table["
- @"OF_UNICODE_UPPERCASE_TABLE_SIZE];\n"
- @"extern const of_unichar_t *const _Nonnull\n"
- @" of_unicode_lowercase_table["
- @"OF_UNICODE_LOWERCASE_TABLE_SIZE];\n"
- @"extern const of_unichar_t *const _Nonnull\n"
- @" of_unicode_titlecase_table["
- @"OF_UNICODE_TITLECASE_TABLE_SIZE];\n"
- @"extern const of_unichar_t *const _Nonnull\n"
- @" of_unicode_casefolding_table["
- @"OF_UNICODE_CASEFOLDING_TABLE_SIZE];\n"
- @"extern const char *const _Nullable *const _Nonnull\n"
- @" of_unicode_decomposition_table["
- @"OF_UNICODE_DECOMPOSITION_TABLE_SIZE];\n"
- @"extern const char *const _Nullable *const _Nonnull\n"
- @" of_unicode_decomposition_compat_table["
- @"OF_UNICODE_DECOMPOSITION_COMPAT_TABLE_SIZE];\n"
+ @"extern const OFUnichar *const _Nonnull\n"
+ @" OFUnicodeUppercaseTable[OFUnicodeUppercaseTableSize];\n"
+ @"extern const OFUnichar *const _Nonnull\n"
+ @" OFUnicodeLowercaseTable[OFUnicodeLowercaseTableSize];\n"
+ @"extern const OFUnichar *const _Nonnull\n"
+ @" OFUnicodeTitlecaseTable[OFUnicodeTitlecaseTableSize];\n"
+ @"extern const OFUnichar *const _Nonnull\n"
+ @" OFUnicodeCaseFoldingTable[OFUnicodeCaseFoldingTableSize];\n"
+ @"extern const char *const _Nullable *const _Nonnull\n"
+ @" OFUnicodeDecompositionTable["
+ @"OFUnicodeDecompositionTableSize];\n"
+ @"extern const char *const _Nullable *const _Nonnull\n"
+ @" OFUnicodeDecompositionCompatTable["
+ @"OFUnicodeDecompositionCompatTableSize];\n"
@"#ifdef __cplusplus\n"
@"}\n"
@"#endif\n"];
objc_autoreleasePoolPop(pool);
}
@end
Index: src/Makefile
==================================================================
--- src/Makefile
+++ src/Makefile
@@ -8,13 +8,17 @@
STATIC_LIB = ${OBJFW_STATIC_LIB}
FRAMEWORK = ${OBJFW_FRAMEWORK}
LIB_MAJOR = ${OBJFW_LIB_MAJOR}
LIB_MINOR = ${OBJFW_LIB_MINOR}
-SRCS = OFApplication.m \
+SRCS = OFASPrintF.m \
+ OFApplication.m \
OFArray.m \
+ OFBase64.m \
OFBlock.m \
+ OFCRC16.m \
+ OFCRC32.m \
OFCharacterSet.m \
OFColor.m \
OFConstantString.m \
OFCountedSet.m \
OFData.m \
@@ -24,19 +28,20 @@
OFDictionary.m \
OFEnumerator.m \
OFFileManager.m \
OFGZIPStream.m \
OFHMAC.m \
+ OFHuffmanTree.m \
OFInflate64Stream.m \
OFInflateStream.m \
OFInvocation.m \
OFLHAArchive.m \
OFLHAArchiveEntry.m \
OFList.m \
OFLocale.m \
- OFMapTable.m \
OFMD5Hash.m \
+ OFMapTable.m \
OFMessagePackExtension.m \
OFMethodSignature.m \
OFMutableArray.m \
OFMutableData.m \
OFMutableDictionary.m \
@@ -51,27 +56,31 @@
OFNull.m \
OFNumber.m \
OFObject.m \
OFObject+KeyValueCoding.m \
OFObject+Serialization.m \
+ OFOnce.m \
OFOptionsParser.m \
+ OFPBKDF2.m \
OFPair.m \
OFRIPEMD160Hash.m \
OFRunLoop.m \
- OFSandbox.m \
- OFSecureData.m \
- OFSeekableStream.m \
- OFSet.m \
OFSHA1Hash.m \
OFSHA224Hash.m \
OFSHA224Or256Hash.m \
OFSHA256Hash.m \
OFSHA384Hash.m \
OFSHA384Or512Hash.m \
OFSHA512Hash.m \
+ OFScrypt.m \
+ OFSecureData.m \
+ OFSeekableStream.m \
+ OFSerialization.m \
+ OFSet.m \
OFSortedList.m \
OFStdIOStream.m \
+ OFStrPTime.m \
OFStream.m \
OFString.m \
OFString+CryptographicHashing.m \
OFString+JSONParsing.m \
OFString+PropertyListParsing.m \
@@ -96,23 +105,13 @@
OFXMLElement.m \
OFXMLElement+Serialization.m \
OFXMLElementBuilder.m \
OFXMLNode.m \
OFXMLParser.m \
- OFXMLProcessingInstructions.m \
+ OFXMLProcessingInstruction.m \
OFZIPArchive.m \
OFZIPArchiveEntry.m \
- base64.m \
- crc16.m \
- crc32.m \
- huffman_tree.m \
- of_asprintf.m \
- of_strptime.m \
- once.m \
- pbkdf2.m \
- scrypt.m \
- ${UNICODE_M} \
${USE_SRCS_FILES} \
${USE_SRCS_PLUGINS} \
${USE_SRCS_SOCKETS} \
${USE_SRCS_THREADS} \
${USE_SRCS_WINDOWS}
@@ -135,45 +134,43 @@
OFHTTPCookieManager.m \
OFHTTPRequest.m \
OFHTTPResponse.m \
OFHTTPServer.m \
OFSequencedPacketSocket.m \
+ OFSocket.m \
OFStreamSocket.m \
OFTCPSocket.m \
OFUDPSocket.m \
- socket.m \
${USE_SRCS_IPX}
SRCS_THREADS = OFCondition.m \
OFMutex.m \
+ OFPlainCondition.m \
+ OFPlainMutex.m \
+ OFPlainThread.m \
OFRecursiveMutex.m \
- OFThreadPool.m \
- condition.m \
- mutex.m \
- thread.m \
- tlskey.m
+ OFTLSKey.m \
+ OFThreadPool.m
SRCS_WINDOWS = OFWin32ConsoleStdIOStream.m \
OFWindowsRegistryKey.m
-INCLUDES_ATOMIC = atomic.h \
- atomic_builtins.h \
- atomic_no_threads.h \
- atomic_osatomic.h \
- atomic_powerpc.h \
- atomic_sync_builtins.h \
- atomic_x86.h
+INCLUDES_ATOMIC = OFAtomic.h \
+ OFAtomic_builtins.h \
+ OFAtomic_no_threads.h \
+ OFAtomic_osatomic.h \
+ OFAtomic_powerpc.h \
+ OFAtomic_sync_builtins.h \
+ OFAtomic_x86.h
INCLUDES := ${SRCS:.m=.h} \
OFCollection.h \
OFCryptographicHash.h \
OFJSONRepresentation.h \
OFKernelEventObserver.h \
OFKeyValueCoding.h \
OFLocking.h \
OFMessagePackRepresentation.h \
- OFSerialization.h \
OFTLSSocket.h \
ObjFW.h \
- block.h \
macros.h \
objfw-defs.h \
platform.h \
${USE_INCLUDES_ATOMIC}
@@ -180,11 +177,10 @@
SRCS += OFAdjacentArray.m \
OFAdjacentSubarray.m \
OFBitSetCharacterSet.m \
OFBytesValue.m \
OFCountedMapTableSet.m \
- OFDimensionValue.m \
OFInvertedCharacterSet.m \
OFLHADecompressingStream.m \
OFMapTableDictionary.m \
OFMapTableSet.m \
OFMutableAdjacentArray.m \
@@ -194,16 +190,19 @@
OFNonretainedObjectValue.m \
OFPointValue.m \
OFPointerValue.m \
OFRangeCharacterSet.m \
OFRangeValue.m \
- OFRectangleValue.m \
+ OFRectValue.m \
+ OFSandbox.m \
+ OFSizeValue.m \
OFSubarray.m \
OFUTF8String.m \
${LIBBASES_M} \
${RUNTIME_AUTORELEASE_M} \
- ${RUNTIME_INSTANCE_M}
+ ${RUNTIME_INSTANCE_M} \
+ ${UNICODE_M}
SRCS_FILES += OFFileURLHandler.m \
OFINIFileSettings.m
SRCS_SOCKETS += OFDNSResolverSettings.m \
OFHTTPURLHandler.m \
OFHostAddressResolver.m \
ADDED src/OFASPrintF.h
Index: src/OFASPrintF.h
==================================================================
--- src/OFASPrintF.h
+++ src/OFASPrintF.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#ifndef __STDC_LIMIT_MACROS
+# define __STDC_LIMIT_MACROS
+#endif
+#ifndef __STDC_CONSTANT_MACROS
+# define __STDC_CONSTANT_MACROS
+#endif
+
+#include
+
+#import "macros.h"
+
+OF_ASSUME_NONNULL_BEGIN
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern int OFVASPrintF(
+ char *_Nullable *_Nonnull, const char *_Nonnull, va_list);
+#ifdef __cplusplus
+}
+#endif
+
+OF_ASSUME_NONNULL_END
ADDED src/OFASPrintF.m
Index: src/OFASPrintF.m
==================================================================
--- src/OFASPrintF.m
+++ src/OFASPrintF.m
@@ -0,0 +1,783 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#include
+#include
+#include
+#include
+#include
+
+#ifdef HAVE_WCHAR_H
+# include
+#endif
+
+#ifdef HAVE_ASPRINTF_L
+# include
+#endif
+#ifdef HAVE_XLOCALE_H
+# include
+#endif
+
+#ifdef OF_HAVE_SYS_TYPES_H
+# include
+#endif
+
+#import "OFString.h"
+#import "OFLocale.h"
+
+#import "OFInitializationFailedException.h"
+
+#define maxSubformatLen 64
+
+#ifndef HAVE_ASPRINTF
+/*
+ * (v)asprintf might be declared, but HAVE_ASPRINTF not defined because
+ * configure determined it is broken. In this case, we must make sure there is
+ * no name clash.
+ */
+# define asprintf asprintf_
+# define vasprintf vasprintf_
+#endif
+
+struct context {
+ const char *format;
+ size_t formatLen;
+ char subformat[maxSubformatLen + 1];
+ size_t subformatLen;
+ va_list arguments;
+ char *buffer;
+ size_t bufferLen;
+ size_t i, last;
+ enum {
+ stateString,
+ stateFormatFlags,
+ stateFormatFieldWidth,
+ stateFormatLengthModifier,
+ stateFormatConversionSpecifier
+ } state;
+ enum {
+ lengthModifierNone,
+ lengthModifierHH,
+ lengthModifierH,
+ lengthModifierL,
+ lengthModifierLL,
+ lengthModifierJ,
+ lengthModifierZ,
+ lengthModifierT,
+ lengthModifierCapitalL
+ } lengthModifier;
+ bool useLocale;
+};
+
+#ifdef HAVE_ASPRINTF_L
+static locale_t cLocale;
+
+OF_CONSTRUCTOR()
+{
+ if ((cLocale = newlocale(LC_ALL_MASK, "C", NULL)) == NULL)
+ @throw [OFInitializationFailedException exception];
+}
+#endif
+
+#ifndef HAVE_ASPRINTF
+static int
+vasprintf(char **string, const char *format, va_list arguments)
+{
+ int length;
+ size_t bufferLength = 128;
+
+ *string = NULL;
+
+ for (;;) {
+ free(*string);
+
+ if ((*string = malloc(bufferLength)) == NULL)
+ return -1;
+
+ length = vsnprintf(*string, bufferLength - 1, format,
+ arguments);
+
+ if (length >= 0 && (size_t)length < bufferLength - 1)
+ break;
+
+ if (bufferLength > INT_MAX / 2) {
+ free(*string);
+ return -1;
+ }
+
+ bufferLength <<= 1;
+ }
+
+ if (length > 0 && (size_t)length != bufferLength - 1) {
+ char *resized = realloc(*string, length + 1);
+
+ /* Ignore if making it smaller failed. */
+ if (resized != NULL)
+ *string = resized;
+ }
+
+ return length;
+}
+
+static int
+asprintf(char **string, const char *format, ...)
+{
+ int ret;
+ va_list arguments;
+
+ va_start(arguments, format);
+ ret = vasprintf(string, format, arguments);
+ va_end(arguments);
+
+ return ret;
+}
+#endif
+
+static bool
+appendString(struct context *ctx, const char *append, size_t appendLen)
+{
+ char *newBuf;
+
+ if (appendLen == 0)
+ return true;
+
+ if ((newBuf = realloc(ctx->buffer,
+ ctx->bufferLen + appendLen + 1)) == NULL)
+ return false;
+
+ memcpy(newBuf + ctx->bufferLen, append, appendLen);
+
+ ctx->buffer = newBuf;
+ ctx->bufferLen += appendLen;
+
+ return true;
+}
+
+static bool
+appendSubformat(struct context *ctx, const char *subformat,
+ size_t subformatLen)
+{
+ if (ctx->subformatLen + subformatLen > maxSubformatLen)
+ return false;
+
+ memcpy(ctx->subformat + ctx->subformatLen, subformat, subformatLen);
+ ctx->subformatLen += subformatLen;
+ ctx->subformat[ctx->subformatLen] = 0;
+
+ return true;
+}
+
+static bool
+stringState(struct context *ctx)
+{
+ if (ctx->format[ctx->i] == '%') {
+ if (ctx->i > 0)
+ if (!appendString(ctx, ctx->format + ctx->last,
+ ctx->i - ctx->last))
+ return false;
+
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
+ return false;
+
+ ctx->last = ctx->i + 1;
+ ctx->state = stateFormatFlags;
+ }
+
+ return true;
+}
+
+static bool
+formatFlagsState(struct context *ctx)
+{
+ switch (ctx->format[ctx->i]) {
+ case '-':
+ case '+':
+ case ' ':
+ case '#':
+ case '0':
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
+ return false;
+
+ break;
+ case ',':
+ /* ObjFW extension: Use decimal point from locale */
+ ctx->useLocale = true;
+ break;
+ default:
+ ctx->state = stateFormatFieldWidth;
+ ctx->i--;
+
+ break;
+ }
+
+ return true;
+}
+
+static bool
+formatFieldWidthState(struct context *ctx)
+{
+ if ((ctx->format[ctx->i] >= '0' && ctx->format[ctx->i] <= '9') ||
+ ctx->format[ctx->i] == '*' || ctx->format[ctx->i] == '.') {
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
+ return false;
+ } else {
+ ctx->state = stateFormatLengthModifier;
+ ctx->i--;
+ }
+
+ return true;
+}
+
+static bool
+formatLengthModifierState(struct context *ctx)
+{
+ /* Only one allowed */
+ switch (ctx->format[ctx->i]) {
+ case 'h': /* and also hh */
+ if (ctx->formatLen > ctx->i + 1 &&
+ ctx->format[ctx->i + 1] == 'h') {
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 2))
+ return false;
+
+ ctx->i++;
+ ctx->lengthModifier = lengthModifierHH;
+ } else {
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
+ return false;
+
+ ctx->lengthModifier = lengthModifierH;
+ }
+
+ break;
+ case 'l': /* and also ll */
+ if (ctx->formatLen > ctx->i + 1 &&
+ ctx->format[ctx->i + 1] == 'l') {
+#ifndef OF_WINDOWS
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 2))
+ return false;
+#else
+ if (!appendSubformat(ctx, "I64", 3))
+ return false;
+#endif
+
+ ctx->i++;
+ ctx->lengthModifier = lengthModifierLL;
+ } else {
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
+ return false;
+
+ ctx->lengthModifier = lengthModifierL;
+ }
+
+ break;
+ case 'j':
+#if defined(OF_WINDOWS)
+ if (!appendSubformat(ctx, "I64", 3))
+ return false;
+#elif defined(_NEWLIB_VERSION) || defined(OF_HPUX)
+ if (!appendSubformat(ctx, "ll", 2))
+ return false;
+#else
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
+ return false;
+#endif
+
+ ctx->lengthModifier = lengthModifierJ;
+
+ break;
+ case 'z':
+#if defined(OF_WINDOWS)
+ if (sizeof(size_t) == 8)
+ if (!appendSubformat(ctx, "I64", 3))
+ return false;
+#elif defined(_NEWLIB_VERSION) || defined(OF_HPUX)
+ if (!appendSubformat(ctx, "l", 1))
+ return false;
+#else
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
+ return false;
+#endif
+
+ ctx->lengthModifier = lengthModifierZ;
+
+ break;
+ case 't':
+#if defined(OF_WINDOWS)
+ if (sizeof(ptrdiff_t) == 8)
+ if (!appendSubformat(ctx, "I64", 3))
+ return false;
+#elif defined(_NEWLIB_VERSION) || defined(OF_HPUX)
+ if (!appendSubformat(ctx, "l", 1))
+ return false;
+#else
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
+ return false;
+#endif
+
+ ctx->lengthModifier = lengthModifierT;
+
+ break;
+ case 'L':
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
+ return false;
+
+ ctx->lengthModifier = lengthModifierCapitalL;
+
+ break;
+#ifdef OF_WINDOWS
+ case 'I': /* win32 strangeness (I64 instead of ll or j) */
+ if (ctx->formatLen > ctx->i + 2 &&
+ ctx->format[ctx->i + 1] == '6' &&
+ ctx->format[ctx->i + 2] == '4') {
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 3))
+ return false;
+
+ ctx->i += 2;
+ ctx->lengthModifier = lengthModifierLL;
+ } else
+ ctx->i--;
+
+ break;
+#endif
+#ifdef OF_IOS
+ case 'q': /* iOS uses this for PRI?64 */
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
+ return false;
+
+ ctx->lengthModifier = lengthModifierLL;
+
+ break;
+#endif
+ default:
+ ctx->i--;
+
+ break;
+ }
+
+ ctx->state = stateFormatConversionSpecifier;
+ return true;
+}
+
+static bool
+formatConversionSpecifierState(struct context *ctx)
+{
+ char *tmp = NULL;
+ int tmpLen = 0;
+#ifndef HAVE_ASPRINTF_L
+ OFString *point;
+#endif
+
+ if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
+ return false;
+
+ switch (ctx->format[ctx->i]) {
+ case '@':
+ if (ctx->lengthModifier != lengthModifierNone)
+ return false;
+
+ ctx->subformat[ctx->subformatLen - 1] = 's';
+
+ @try {
+ id object;
+
+ if ((object = va_arg(ctx->arguments, id)) != nil) {
+ void *pool = objc_autoreleasePoolPush();
+
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ [object description].UTF8String);
+
+ objc_autoreleasePoolPop(pool);
+ } else
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ "(nil)");
+ } @catch (id e) {
+ free(ctx->buffer);
+ @throw e;
+ }
+
+ break;
+ case 'C':
+ if (ctx->lengthModifier != lengthModifierNone)
+ return false;
+
+ ctx->subformat[ctx->subformatLen - 1] = 's';
+
+ {
+ char buffer[5];
+ size_t len = OFUTF8StringEncode(
+ va_arg(ctx->arguments, OFUnichar), buffer);
+
+ if (len == 0)
+ return false;
+
+ buffer[len] = 0;
+ tmpLen = asprintf(&tmp, ctx->subformat, buffer);
+ }
+
+ break;
+ case 'S':
+ if (ctx->lengthModifier != lengthModifierNone)
+ return false;
+
+ ctx->subformat[ctx->subformatLen - 1] = 's';
+
+ {
+ const OFUnichar *arg =
+ va_arg(ctx->arguments, const OFUnichar *);
+ size_t j, len = OFUTF32StringLength(arg);
+ char *buffer;
+
+ if (SIZE_MAX / 4 < len || (SIZE_MAX / 4) - len < 1)
+ return false;
+
+ if ((buffer = malloc((len * 4) + 1)) == NULL)
+ return false;
+
+ j = 0;
+ for (size_t i = 0; i < len; i++) {
+ size_t clen = OFUTF8StringEncode(arg[i],
+ buffer + j);
+
+ if (clen == 0) {
+ free(buffer);
+ return false;
+ }
+
+ j += clen;
+ }
+ buffer[j] = 0;
+
+ tmpLen = asprintf(&tmp, ctx->subformat, buffer);
+
+ free(buffer);
+ }
+
+ break;
+ case 'd':
+ case 'i':
+ switch (ctx->lengthModifier) {
+ case lengthModifierNone:
+ case lengthModifierHH:
+ case lengthModifierH:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, int));
+ break;
+ case lengthModifierL:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, long));
+ break;
+ case lengthModifierLL:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, long long));
+ break;
+ case lengthModifierJ:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, intmax_t));
+ break;
+ case lengthModifierZ:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, ssize_t));
+ break;
+ case lengthModifierT:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, ptrdiff_t));
+ break;
+ default:
+ return false;
+ }
+
+ break;
+ case 'o':
+ case 'u':
+ case 'x':
+ case 'X':
+ switch (ctx->lengthModifier) {
+ case lengthModifierNone:
+ case lengthModifierHH:
+ case lengthModifierH:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, unsigned int));
+ break;
+ case lengthModifierL:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, unsigned long));
+ break;
+ case lengthModifierLL:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, unsigned long long));
+ break;
+ case lengthModifierJ:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, uintmax_t));
+ break;
+ case lengthModifierZ:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, size_t));
+ break;
+ case lengthModifierT:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, ptrdiff_t));
+ break;
+ default:
+ return false;
+ }
+
+ break;
+ case 'f':
+ case 'F':
+ case 'e':
+ case 'E':
+ case 'g':
+ case 'G':
+ case 'a':
+ case 'A':
+ switch (ctx->lengthModifier) {
+ case lengthModifierNone:
+ case lengthModifierL:
+#ifdef HAVE_ASPRINTF_L
+ if (!ctx->useLocale)
+ tmpLen = asprintf_l(&tmp, cLocale,
+ ctx->subformat,
+ va_arg(ctx->arguments, double));
+ else
+#endif
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, double));
+ break;
+ case lengthModifierCapitalL:
+#ifdef HAVE_ASPRINTF_L
+ if (!ctx->useLocale)
+ tmpLen = asprintf_l(&tmp, cLocale,
+ ctx->subformat,
+ va_arg(ctx->arguments, long double));
+ else
+#endif
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, long double));
+ break;
+ default:
+ return false;
+ }
+
+#ifndef HAVE_ASPRINTF_L
+ if (tmpLen == -1)
+ return false;
+
+ /*
+ * If there's no asprintf_l, we have no other choice than to
+ * use this ugly hack to replace the locale's decimal point
+ * back to ".".
+ */
+ point = [OFLocale decimalPoint];
+
+ if (!ctx->useLocale && point != nil && ![point isEqual: @"."]) {
+ void *pool = objc_autoreleasePoolPush();
+ char *tmp2;
+
+ @try {
+ OFMutableString *tmpStr = [OFMutableString
+ stringWithUTF8String: tmp
+ length: tmpLen];
+ [tmpStr replaceOccurrencesOfString: point
+ withString: @"."];
+
+ if (tmpStr.UTF8StringLength > INT_MAX)
+ return false;
+
+ tmpLen = (int)tmpStr.UTF8StringLength;
+ tmp2 = malloc(tmpLen);
+ memcpy(tmp2, tmpStr.UTF8String, tmpLen);
+ } @finally {
+ free(tmp);
+ objc_autoreleasePoolPop(pool);
+ }
+
+ tmp = tmp2;
+ }
+#endif
+
+ break;
+ case 'c':
+ switch (ctx->lengthModifier) {
+ case lengthModifierNone:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, int));
+ break;
+ case lengthModifierL:
+#ifdef HAVE_WCHAR_H
+# if WINT_MAX >= INT_MAX
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, wint_t));
+# else
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, int));
+# endif
+ break;
+#endif
+ default:
+ return false;
+ }
+
+ break;
+ case 's':
+ switch (ctx->lengthModifier) {
+ case lengthModifierNone:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, const char *));
+ break;
+#ifdef HAVE_WCHAR_T
+ case lengthModifierL:
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, const wchar_t *));
+ break;
+#endif
+ default:
+ return false;
+ }
+
+ break;
+ case 'p':
+ if (ctx->lengthModifier != lengthModifierNone)
+ return false;
+
+ tmpLen = asprintf(&tmp, ctx->subformat,
+ va_arg(ctx->arguments, void *));
+
+ break;
+ case 'n':
+ switch (ctx->lengthModifier) {
+ case lengthModifierNone:
+ *va_arg(ctx->arguments, int *) = (int)ctx->bufferLen;
+ break;
+ case lengthModifierHH:
+ *va_arg(ctx->arguments, signed char *) =
+ (signed char)ctx->bufferLen;
+ break;
+ case lengthModifierH:
+ *va_arg(ctx->arguments, short *) =
+ (short)ctx->bufferLen;
+ break;
+ case lengthModifierL:
+ *va_arg(ctx->arguments, long *) =
+ (long)ctx->bufferLen;
+ break;
+ case lengthModifierLL:
+ *va_arg(ctx->arguments, long long *) =
+ (long long)ctx->bufferLen;
+ break;
+ case lengthModifierJ:
+ *va_arg(ctx->arguments, intmax_t *) =
+ (intmax_t)ctx->bufferLen;
+ break;
+ case lengthModifierZ:
+ *va_arg(ctx->arguments, size_t *) =
+ (size_t)ctx->bufferLen;
+ break;
+ case lengthModifierT:
+ *va_arg(ctx->arguments, ptrdiff_t *) =
+ (ptrdiff_t)ctx->bufferLen;
+ break;
+ default:
+ return false;
+ }
+
+ break;
+ case '%':
+ if (ctx->lengthModifier != lengthModifierNone)
+ return false;
+
+ if (!appendString(ctx, "%", 1))
+ return false;
+
+ break;
+ default:
+ return false;
+ }
+
+ if (tmpLen == -1)
+ return false;
+
+ if (tmp != NULL) {
+ if (!appendString(ctx, tmp, tmpLen)) {
+ free(tmp);
+ return false;
+ }
+
+ free(tmp);
+ }
+
+ memset(ctx->subformat, 0, maxSubformatLen);
+ ctx->subformatLen = 0;
+ ctx->lengthModifier = lengthModifierNone;
+ ctx->useLocale = false;
+
+ ctx->last = ctx->i + 1;
+ ctx->state = stateString;
+
+ return true;
+}
+
+static bool (*states[])(struct context *) = {
+ stringState,
+ formatFlagsState,
+ formatFieldWidthState,
+ formatLengthModifierState,
+ formatConversionSpecifierState
+};
+
+int
+OFVASPrintF(char **string, const char *format, va_list arguments)
+{
+ struct context ctx;
+
+ ctx.format = format;
+ ctx.formatLen = strlen(format);
+ memset(ctx.subformat, 0, maxSubformatLen + 1);
+ ctx.subformatLen = 0;
+ va_copy(ctx.arguments, arguments);
+ ctx.bufferLen = 0;
+ ctx.last = 0;
+ ctx.state = stateString;
+ ctx.lengthModifier = lengthModifierNone;
+ ctx.useLocale = false;
+
+ if ((ctx.buffer = malloc(1)) == NULL)
+ return -1;
+
+ for (ctx.i = 0; ctx.i < ctx.formatLen; ctx.i++) {
+ if (!states[ctx.state](&ctx)) {
+ free(ctx.buffer);
+ return -1;
+ }
+ }
+
+ if (ctx.state != stateString) {
+ free(ctx.buffer);
+ return -1;
+ }
+
+ if (!appendString(&ctx, ctx.format + ctx.last,
+ ctx.formatLen - ctx.last)) {
+ free(ctx.buffer);
+ return -1;
+ }
+
+ ctx.buffer[ctx.bufferLen] = 0;
+
+ *string = ctx.buffer;
+ return (ctx.bufferLen <= INT_MAX ? (int)ctx.bufferLen : -1);
+}
Index: src/OFAdjacentArray.m
==================================================================
--- src/OFAdjacentArray.m
+++ src/OFAdjacentArray.m
@@ -160,15 +160,15 @@
@try {
void *pool = objc_autoreleasePoolPush();
if ((![element.name isEqual: @"OFArray"] &&
![element.name isEqual: @"OFMutableArray"]) ||
- ![element.namespace isEqual: OF_SERIALIZATION_NS])
+ ![element.namespace isEqual: OFSerializationNS])
@throw [OFInvalidArgumentException exception];
for (OFXMLElement *child in
- [element elementsForNamespace: OF_SERIALIZATION_NS]) {
+ [element elementsForNamespace: OFSerializationNS]) {
void *pool2 = objc_autoreleasePoolPush();
id object;
object = child.objectByDeserializing;
[_array addItem: &object];
@@ -204,11 +204,11 @@
- (id)objectAtIndexedSubscript: (size_t)idx
{
return *((id *)[_array itemAtIndex: idx]);
}
-- (void)getObjects: (id *)buffer inRange: (of_range_t)range
+- (void)getObjects: (id *)buffer inRange: (OFRange)range
{
id const *objects = _array.items;
size_t count = _array.count;
if (range.length > SIZE_MAX - range.location ||
@@ -223,42 +223,42 @@
{
id const *objects;
size_t count;
if (object == nil)
- return OF_NOT_FOUND;
+ return OFNotFound;
objects = _array.items;
count = _array.count;
for (size_t i = 0; i < count; i++)
if ([objects[i] isEqual: object])
return i;
- return OF_NOT_FOUND;
+ return OFNotFound;
}
- (size_t)indexOfObjectIdenticalTo: (id)object
{
id const *objects;
size_t count;
if (object == nil)
- return OF_NOT_FOUND;
+ return OFNotFound;
objects = _array.items;
count = _array.count;
for (size_t i = 0; i < count; i++)
if (objects[i] == object)
return i;
- return OF_NOT_FOUND;
+ return OFNotFound;
}
-- (OFArray *)objectsInRange: (of_range_t)range
+- (OFArray *)objectsInRange: (OFRange)range
{
if (range.length > SIZE_MAX - range.location ||
range.location + range.length > _array.count)
@throw [OFOutOfRangeException exception];
@@ -302,23 +302,23 @@
- (unsigned long)hash
{
id const *objects = _array.items;
size_t count = _array.count;
- uint32_t hash;
+ unsigned long hash;
- OF_HASH_INIT(hash);
+ OFHashInit(&hash);
for (size_t i = 0; i < count; i++)
- OF_HASH_ADD_HASH(hash, [objects[i] hash]);
+ OFHashAddHash(&hash, [objects[i] hash]);
- OF_HASH_FINALIZE(hash);
+ OFHashFinalize(&hash);
return hash;
}
-- (int)countByEnumeratingWithState: (of_fast_enumeration_state_t *)state
+- (int)countByEnumeratingWithState: (OFFastEnumerationState *)state
objects: (id *)objects
count: (int)count_
{
size_t count = _array.count;
@@ -340,11 +340,11 @@
return (int)count;
}
#ifdef OF_HAVE_BLOCKS
-- (void)enumerateObjectsUsingBlock: (of_array_enumeration_block_t)block
+- (void)enumerateObjectsUsingBlock: (OFArrayEnumerationBlock)block
{
id const *objects = _array.items;
size_t count = _array.count;
bool stop = false;
Index: src/OFAdjacentSubarray.m
==================================================================
--- src/OFAdjacentSubarray.m
+++ src/OFAdjacentSubarray.m
@@ -51,15 +51,15 @@
return true;
}
#ifdef OF_HAVE_BLOCKS
-- (void)enumerateObjectsUsingBlock: (of_array_enumeration_block_t)block
+- (void)enumerateObjectsUsingBlock: (OFArrayEnumerationBlock)block
{
id const *objects = self.objects;
bool stop = false;
for (size_t i = 0; i < _range.length && !stop; i++)
block(objects[i], i, &stop);
}
#endif
@end
Index: src/OFApplication.h
==================================================================
--- src/OFApplication.h
+++ src/OFApplication.h
@@ -50,16 +50,16 @@
* [OFApplication terminate];
* }
* @end
* @endcode
*/
-#define OF_APPLICATION_DELEGATE(class_) \
- int \
- main(int argc, char *argv[]) \
- { \
- return of_application_main(&argc, &argv, \
- (class_ *)[[class_ alloc] init]); \
+#define OF_APPLICATION_DELEGATE(class_) \
+ int \
+ main(int argc, char *argv[]) \
+ { \
+ return OFApplicationMain(&argc, &argv, \
+ (class_ *)[[class_ alloc] init]); \
}
#ifdef OF_HAVE_PLEDGE
# define OF_HAVE_SANDBOX
#endif
@@ -198,18 +198,11 @@
*/
@property OF_NULLABLE_PROPERTY (assign, nonatomic)
id delegate;
#ifdef OF_HAVE_SANDBOX
-/**
- * @brief The sandbox currently active for this application.
- */
@property OF_NULLABLE_PROPERTY (readonly, nonatomic) OFSandbox *activeSandbox;
-
-/**
- * @brief The sandbox currently active for child processes of this application.
- */
@property OF_NULLABLE_PROPERTY (readonly, nonatomic)
OFSandbox *activeSandboxForChildProcesses;
#endif
/**
@@ -251,41 +244,12 @@
* @param status The status with which the application will terminate
*/
+ (void)terminateWithStatus: (int)status OF_NO_RETURN;
#ifdef OF_HAVE_SANDBOX
-/**
- * @brief Activates the specified sandbox for the application.
- *
- * This is only available if `OF_HAVE_SANDBOX` is defined.
- *
- * @warning If you allow `exec()`, but do not call
- * @ref activateSandboxForChildProcesses:, an `exec()`'d process does
- * not have its permissions restricted!
- *
- * @note Once a sandbox has been activated, you cannot activate a different
- * sandbox. You can however change the active sandbox and reactivate it.
- *
- * @param sandbox The sandbox to activate
- */
-+ (void)activateSandbox: (OFSandbox *)sandbox;
-
-/**
- * @brief Activates the specified sandbox for child processes of the
- * application.
- *
- * This is only available if `OF_HAVE_SANDBOX` is defined.
- *
- * `unveiledPaths` on the sandbox must *not* be empty, otherwise an
- * @ref OFInvalidArgumentException is raised.
- *
- * @note Once a sandbox has been activated, you cannot activate a different
- * sandbox. You can however change the active sandbox and reactivate it.
- *
- * @param sandbox The sandbox to activate
- */
-+ (void)activateSandboxForChildProcesses: (OFSandbox *)sandbox;
++ (void)of_activateSandbox: (OFSandbox *)sandbox;
++ (void)of_activateSandboxForChildProcesses: (OFSandbox *)sandbox;
#endif
- (instancetype)init OF_UNAVAILABLE;
/**
@@ -308,49 +272,20 @@
* @param status The status with which the application will terminate
*/
- (void)terminateWithStatus: (int)status OF_NO_RETURN;
#ifdef OF_HAVE_SANDBOX
-/**
- * @brief Activates the specified sandbox for the application.
- *
- * This is only available if `OF_HAVE_SANDBOX` is defined.
- *
- * @warning If you allow `exec()`, but do not call
- * @ref activateSandboxForChildProcesses:, an `exec()`'d process does
- * not have its permissions restricted!
- *
- * @note Once a sandbox has been activated, you cannot activate a different
- * sandbox. You can however change the active sandbox and reactivate it.
- *
- * @param sandbox The sandbox to activate
- */
-- (void)activateSandbox: (OFSandbox *)sandbox;
-
-/**
- * @brief Activates the specified sandbox for child processes of the
- * application.
- *
- * This is only available if `OF_HAVE_SANDBOX` is defined.
- *
- * `unveiledPaths` on the sandbox must *not* be empty, otherwise an
- * @ref OFInvalidArgumentException is raised.
- *
- * @note Once a sandbox has been activated, you cannot activate a different
- * sandbox. You can however change the active sandbox and reactivate it.
- *
- * @param sandbox The sandbox to activate
- */
-- (void)activateSandboxForChildProcesses: (OFSandbox *)sandbox;
+- (void)of_activateSandbox: (OFSandbox *)sandbox;
+- (void)of_activateSandboxForChildProcesses: (OFSandbox *)sandbox;
#endif
@end
#ifdef __cplusplus
extern "C" {
#endif
-extern int of_application_main(int *_Nonnull,
- char *_Nullable *_Nonnull[_Nonnull], id );
+extern int OFApplicationMain(int *_Nonnull, char *_Nullable *_Nonnull[_Nonnull],
+ id );
#ifdef __cplusplus
}
#endif
OF_ASSUME_NONNULL_END
Index: src/OFApplication.m
==================================================================
--- src/OFApplication.m
+++ src/OFApplication.m
@@ -92,17 +92,16 @@
[delegate release];
#if defined(OF_HAVE_THREADS) && defined(OF_HAVE_SOCKETS) && \
defined(OF_AMIGAOS) && !defined(OF_MORPHOS)
- of_socket_deinit();
+ OFSocketDeinit();
#endif
}
int
-of_application_main(int *argc, char **argv[],
- id delegate)
+OFApplicationMain(int *argc, char **argv[], id delegate)
{
#ifdef OF_WINDOWS
wchar_t **wargv, **wenvp;
int wargc, si = 0;
#endif
@@ -194,18 +193,18 @@
OF_UNREACHABLE
#endif
}
#ifdef OF_HAVE_SANDBOX
-+ (void)activateSandbox: (OFSandbox *)sandbox
-{
- [app activateSandbox: sandbox];
-}
-
-+ (void)activateSandboxForChildProcesses: (OFSandbox *)sandbox
-{
- [app activateSandboxForChildProcesses: sandbox];
++ (void)of_activateSandbox: (OFSandbox *)sandbox
+{
+ [app of_activateSandbox: sandbox];
+}
+
++ (void)of_activateSandboxForChildProcesses: (OFSandbox *)sandbox
+{
+ [app of_activateSandboxForChildProcesses: sandbox];
}
#endif
- (instancetype)init
{
@@ -221,19 +220,19 @@
atexit(atexitHandler);
#if defined(OF_WINDOWS)
if ([OFSystemInfo isWindowsNT]) {
- of_char16_t *env, *env0;
+ OFChar16 *env, *env0;
env = env0 = GetEnvironmentStringsW();
while (*env != 0) {
void *pool = objc_autoreleasePoolPush();
OFString *tmp, *key, *value;
size_t length, pos;
- length = of_string_utf16_length(env);
+ length = OFUTF16StringLength(env);
tmp = [OFString stringWithUTF16String: env
length: length];
env += length + 1;
/*
@@ -245,11 +244,11 @@
objc_autoreleasePoolPop(pool);
continue;
}
pos = [tmp rangeOfString: @"="].location;
- if (pos == OF_NOT_FOUND) {
+ if (pos == OFNotFound) {
fprintf(stderr,
"Warning: Invalid environment "
"variable: %s\n", tmp.UTF8String);
continue;
}
@@ -287,11 +286,11 @@
objc_autoreleasePoolPop(pool);
continue;
}
pos = [tmp rangeOfString: @"="].location;
- if (pos == OF_NOT_FOUND) {
+ if (pos == OFNotFound) {
fprintf(stderr,
"Warning: Invalid environment "
"variable: %s\n", tmp.UTF8String);
continue;
}
@@ -308,11 +307,11 @@
#elif defined(OF_AMIGAOS)
void *pool = objc_autoreleasePoolPush();
OFFileManager *fileManager = [OFFileManager defaultManager];
OFArray *envContents =
[fileManager contentsOfDirectoryAtPath: @"ENV:"];
- const of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
struct Process *proc;
struct LocalVar *firstLocalVar;
for (OFString *name in envContents) {
void *pool2 = objc_autoreleasePoolPush();
@@ -374,12 +373,11 @@
# else
char **env = *_NSGetEnviron();
# endif
if (env != NULL) {
- const of_string_encoding_t encoding =
- [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
for (; *env != NULL; env++) {
void *pool = objc_autoreleasePoolPush();
OFString *key, *value;
char *sep;
@@ -466,11 +464,11 @@
- (void)of_setArgumentCount: (int *)argc andArgumentValues: (char ***)argv
{
void *pool = objc_autoreleasePoolPush();
OFMutableArray *arguments;
- of_string_encoding_t encoding;
+ OFStringEncoding encoding;
_argc = argc;
_argv = argv;
encoding = [OFLocale encoding];
@@ -601,16 +599,16 @@
OF_UNREACHABLE
}
#ifdef OF_HAVE_SANDBOX
-- (void)activateSandbox: (OFSandbox *)sandbox
+- (void)of_activateSandbox: (OFSandbox *)sandbox
{
# ifdef OF_HAVE_PLEDGE
void *pool = objc_autoreleasePoolPush();
- of_string_encoding_t encoding = [OFLocale encoding];
- OFArray OF_GENERIC(of_sandbox_unveil_path_t) *unveiledPaths;
+ OFStringEncoding encoding = [OFLocale encoding];
+ OFArray OF_GENERIC(OFSandboxUnveilPath) *unveiledPaths;
size_t unveiledPathsCount;
const char *promises;
if (_activeSandbox != nil && sandbox != _activeSandbox)
@throw [OFInvalidArgumentException exception];
@@ -618,11 +616,11 @@
unveiledPaths = sandbox.unveiledPaths;
unveiledPathsCount = unveiledPaths.count;
for (size_t i = sandbox->_unveiledPathsIndex;
i < unveiledPathsCount; i++) {
- of_sandbox_unveil_path_t unveiledPath =
+ OFSandboxUnveilPath unveiledPath =
[unveiledPaths objectAtIndex: i];
OFString *path = unveiledPath.firstObject;
OFString *permissions = unveiledPath.secondObject;
if (path == nil || permissions == nil)
@@ -646,11 +644,11 @@
if (_activeSandbox == nil)
_activeSandbox = [sandbox retain];
# endif
}
-- (void)activateSandboxForChildProcesses: (OFSandbox *)sandbox
+- (void)of_activateSandboxForChildProcesses: (OFSandbox *)sandbox
{
# ifdef OF_HAVE_PLEDGE
void *pool = objc_autoreleasePoolPush();
const char *promises;
Index: src/OFArray.h
==================================================================
--- src/OFArray.h
+++ src/OFArray.h
@@ -33,14 +33,29 @@
/** @file */
@class OFString;
-enum {
- OF_ARRAY_SKIP_EMPTY = 1,
- OF_ARRAY_SORT_DESCENDING = 2
-};
+/**
+ * @brief Options for joining the objects of an array.
+ *
+ * This is a bit mask.
+ */
+typedef enum {
+ /** Skip empty components */
+ OFArraySkipEmptyComponents = 1
+} OFArrayJoinOptions;
+
+/**
+ * @brief Options for sorting an array.
+ *
+ * This is a bit mask.
+ */
+typedef enum {
+ /** Sort the array descending */
+ OFArraySortDescending = 1
+} OFArraySortOptions;
#ifdef OF_HAVE_BLOCKS
/**
* @brief A block for enumerating an OFArray.
*
@@ -47,39 +62,38 @@
* @param object The current object
* @param index The index of the current object
* @param stop A pointer to a variable that can be set to true to stop the
* enumeration
*/
-typedef void (^of_array_enumeration_block_t)(id object, size_t index,
- bool *stop);
+typedef void (^OFArrayEnumerationBlock)(id object, size_t index, bool *stop);
/**
* @brief A block for filtering an OFArray.
*
* @param object The object to inspect
* @param index The index of the object to inspect
* @return Whether the object should be in the filtered array
*/
-typedef bool (^of_array_filter_block_t)(id object, size_t index);
+typedef bool (^OFArrayFilterBlock)(id object, size_t index);
/**
* @brief A block for mapping objects to objects in an OFArray.
*
* @param object The object to map
* @param index The index of the object to map
* @return The object to map to
*/
-typedef id _Nonnull (^of_array_map_block_t)(id object, size_t index);
+typedef id _Nonnull (^OFArrayMapBlock)(id object, size_t index);
/**
* @brief A block for folding an OFArray.
*
* @param left The object to which the object has been folded so far
* @param right The object that should be added to the left object
* @return The left and right side folded into one object
*/
-typedef id _Nullable (^of_array_fold_block_t)(id _Nullable left, id right);
+typedef id _Nullable (^OFArrayFoldBlock)(id _Nullable left, id right);
#endif
/**
* @class OFArray OFArray.h ObjFW/OFArray.h
*
@@ -268,29 +282,29 @@
*
* @param buffer The buffer to copy the objects to
* @param range The range to copy
*/
- (void)getObjects: (ObjectType __unsafe_unretained _Nonnull *_Nonnull)buffer
- inRange: (of_range_t)range;
+ inRange: (OFRange)range;
/**
* @brief Returns the index of the first object that is equivalent to the
- * specified object or `OF_NOT_FOUND` if it was not found.
+ * specified object or `OFNotFound` if it was not found.
*
* @param object The object whose index is returned
* @return The index of the first object equivalent to the specified object
- * or `OF_NOT_FOUND` if it was not found
+ * or `OFNotFound` if it was not found
*/
- (size_t)indexOfObject: (ObjectType)object;
/**
* @brief Returns the index of the first object that has the same address as the
- * specified object or `OF_NOT_FOUND` if it was not found.
+ * specified object or `OFNotFound` if it was not found.
*
* @param object The object whose index is returned
* @return The index of the first object that has the same address as
- * the specified object or `OF_NOT_FOUND` if it was not found
+ * the specified object or `OFNotFound` if it was not found
*/
- (size_t)indexOfObjectIdenticalTo: (ObjectType)object;
/**
* @brief Checks whether the array contains an object equal to the specified
@@ -315,11 +329,11 @@
* @brief Returns the objects in the specified range as a new OFArray.
*
* @param range The range for the subarray
* @return The subarray as a new autoreleased OFArray
*/
-- (OFArray OF_GENERIC(ObjectType) *)objectsInRange: (of_range_t)range;
+- (OFArray OF_GENERIC(ObjectType) *)objectsInRange: (OFRange)range;
/**
* @brief Creates a string by joining all objects of the array.
*
* @param separator The string with which the objects should be joined
@@ -329,19 +343,15 @@
/**
* @brief Creates a string by joining all objects of the array.
*
* @param separator The string with which the objects should be joined
- * @param options Options according to which the objects should be joined.@n
- * Possible values are:
- * Value | Description
- * ----------------------|----------------------
- * `OF_ARRAY_SKIP_EMPTY` | Skip empty components
+ * @param options Options according to which the objects should be joined
* @return A string containing all objects joined by the separator
*/
- (OFString *)componentsJoinedByString: (OFString *)separator
- options: (int)options;
+ options: (OFArrayJoinOptions)options;
/**
* @brief Creates a string by calling the selector on all objects of the array
* and joining the strings returned by calling the selector.
*
@@ -356,20 +366,16 @@
* @brief Creates a string by calling the selector on all objects of the array
* and joining the strings returned by calling the selector.
*
* @param separator The string with which the objects should be joined
* @param selector The selector to perform on the objects
- * @param options Options according to which the objects should be joined.@n
- * Possible values are:
- * Value | Description
- * ----------------------|----------------------
- * `OF_ARRAY_SKIP_EMPTY` | Skip empty components
+ * @param options Options according to which the objects should be joined
* @return A string containing all objects joined by the separator
*/
- (OFString *)componentsJoinedByString: (OFString *)separator
usingSelector: (SEL)selector
- options: (int)options;
+ options: (OFArrayJoinOptions)options;
/**
* @brief Performs the specified selector on all objects in the array.
*
* @param selector The selector to perform on all objects in the array
@@ -391,36 +397,29 @@
* @brief Returns a copy of the array sorted using the specified selector and
* options.
*
* @param selector The selector to use to sort the array. It's signature
* should be the same as that of -[compare:].
- * @param options The options to use when sorting the array.@n
- * Possible values are:
- * Value | Description
- * ---------------------------|-------------------------
- * `OF_ARRAY_SORT_DESCENDING` | Sort in descending order
+ * @param options The options to use when sorting the array
* @return A sorted copy of the array
*/
-- (OFArray OF_GENERIC(ObjectType) *)sortedArrayUsingSelector: (SEL)selector
- options: (int)options;
+- (OFArray OF_GENERIC(ObjectType) *)
+ sortedArrayUsingSelector: (SEL)selector
+ options: (OFArraySortOptions)options;
#ifdef OF_HAVE_BLOCKS
/**
* @brief Returns a copy of the array sorted using the specified selector and
* options.
*
* @param comparator The comparator to use to sort the array
- * @param options The options to use when sorting the array.@n
- * Possible values are:
- * Value | Description
- * ---------------------------|-------------------------
- * `OF_ARRAY_SORT_DESCENDING` | Sort in descending order
+ * @param options The options to use when sorting the array
* @return A sorted copy of the array
*/
- (OFArray OF_GENERIC(ObjectType) *)
- sortedArrayUsingComparator: (of_comparator_t)comparator
- options: (int)options;
+ sortedArrayUsingComparator: (OFComparator)comparator
+ options: (OFArraySortOptions)options;
#endif
/**
* @brief Creates a new array with the specified object added.
*
@@ -450,19 +449,19 @@
/**
* @brief Executes a block for each object.
*
* @param block The block to execute for each object
*/
-- (void)enumerateObjectsUsingBlock: (of_array_enumeration_block_t)block;
+- (void)enumerateObjectsUsingBlock: (OFArrayEnumerationBlock)block;
/**
* @brief Creates a new array, mapping each object using the specified block.
*
* @param block A block which maps an object for each object
* @return A new, autoreleased OFArray
*/
-- (OFArray *)mappedArrayUsingBlock: (of_array_map_block_t)block;
+- (OFArray *)mappedArrayUsingBlock: (OFArrayMapBlock)block;
/**
* @brief Creates a new array, only containing the objects for which the block
* returns true.
*
@@ -469,11 +468,11 @@
* @param block A block which determines if the object should be in the new
* array
* @return A new, autoreleased OFArray
*/
- (OFArray OF_GENERIC(ObjectType) *)filteredArrayUsingBlock:
- (of_array_filter_block_t)block;
+ (OFArrayFilterBlock)block;
/**
* @brief Folds the array to a single object using the specified block.
*
* If the array is empty, it will return `nil`.
@@ -487,11 +486,11 @@
*
* @param block A block which folds two objects into one, which is called for
* all objects except the first
* @return The array folded to a single object
*/
-- (nullable id)foldUsingBlock: (of_array_fold_block_t)block;
+- (nullable id)foldUsingBlock: (OFArrayFoldBlock)block;
#endif
#if !defined(OF_HAVE_GENERICS) && !defined(DOXYGEN)
# undef ObjectType
#endif
@end
Index: src/OFArray.m
==================================================================
--- src/OFArray.m
+++ src/OFArray.m
@@ -36,12 +36,13 @@
static struct {
Class isa;
} placeholder;
@interface OFArray ()
-- (OFString *)of_JSONRepresentationWithOptions: (int)options
- depth: (size_t)depth;
+- (OFString *)
+ of_JSONRepresentationWithOptions: (OFJSONRepresentationOptions)options
+ depth: (size_t)depth;
@end
@interface OFPlaceholderArray: OFArray
@end
@@ -226,30 +227,30 @@
- (size_t)count
{
OF_UNRECOGNIZED_SELECTOR
}
-- (void)getObjects: (id *)buffer inRange: (of_range_t)range
+- (void)getObjects: (id *)buffer inRange: (OFRange)range
{
for (size_t i = 0; i < range.length; i++)
buffer[i] = [self objectAtIndex: range.location + i];
}
- (id const *)objects
{
size_t count = self.count;
- id *buffer = of_alloc(count, sizeof(id));
+ id *buffer = OFAllocMemory(count, sizeof(id));
@try {
- [self getObjects: buffer inRange: of_range(0, count)];
+ [self getObjects: buffer inRange: OFRangeMake(0, count)];
return [[OFData dataWithItemsNoCopy: buffer
count: count
itemSize: sizeof(id)
freeWhenDone: true] items];
} @catch (id e) {
- free(buffer);
+ OFFreeMemory(buffer);
@throw e;
}
}
- (id)copy
@@ -304,47 +305,47 @@
- (size_t)indexOfObject: (id)object
{
size_t i = 0;
if (object == nil)
- return OF_NOT_FOUND;
+ return OFNotFound;
for (id objectIter in self) {
if ([objectIter isEqual: object])
return i;
i++;
}
- return OF_NOT_FOUND;
+ return OFNotFound;
}
- (size_t)indexOfObjectIdenticalTo: (id)object
{
size_t i = 0;
if (object == nil)
- return OF_NOT_FOUND;
+ return OFNotFound;
for (id objectIter in self) {
if (objectIter == object)
return i;
i++;
}
- return OF_NOT_FOUND;
+ return OFNotFound;
}
- (bool)containsObject: (id)object
{
- return ([self indexOfObject: object] != OF_NOT_FOUND);
+ return ([self indexOfObject: object] != OFNotFound);
}
- (bool)containsObjectIdenticalTo: (id)object
{
- return ([self indexOfObjectIdenticalTo: object] != OF_NOT_FOUND);
+ return ([self indexOfObjectIdenticalTo: object] != OFNotFound);
}
- (id)firstObject
{
if (self.count > 0)
@@ -361,11 +362,11 @@
return [self objectAtIndex: count - 1];
return nil;
}
-- (OFArray *)objectsInRange: (of_range_t)range
+- (OFArray *)objectsInRange: (OFRange)range
{
OFArray *ret;
id *buffer;
if (range.length > SIZE_MAX - range.location ||
@@ -373,17 +374,17 @@
@throw [OFOutOfRangeException exception];
if (![self isKindOfClass: [OFMutableArray class]])
return [OFSubarray arrayWithArray: self range: range];
- buffer = of_alloc(range.length, sizeof(*buffer));
+ buffer = OFAllocMemory(range.length, sizeof(*buffer));
@try {
[self getObjects: buffer inRange: range];
ret = [OFArray arrayWithObjects: buffer count: range.length];
} @finally {
- free(buffer);
+ OFFreeMemory(buffer);
}
return ret;
}
@@ -393,11 +394,11 @@
usingSelector: @selector(description)
options: 0];
}
- (OFString *)componentsJoinedByString: (OFString *)separator
- options: (int)options
+ options: (OFArrayJoinOptions)options
{
return [self componentsJoinedByString: separator
usingSelector: @selector(description)
options: options];
}
@@ -410,11 +411,11 @@
options: 0];
}
- (OFString *)componentsJoinedByString: (OFString *)separator
usingSelector: (SEL)selector
- options: (int)options
+ options: (OFArrayJoinOptions)options
{
OFMutableString *ret;
if (separator == nil)
@throw [OFInvalidArgumentException exception];
@@ -432,11 +433,11 @@
return component;
}
ret = [OFMutableString string];
- if (options & OF_ARRAY_SKIP_EMPTY) {
+ if (options & OFArraySkipEmptyComponents) {
for (id object in self) {
void *pool = objc_autoreleasePoolPush();
OFString *component =
[object performSelector: selector];
@@ -505,18 +506,18 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
+ unsigned long hash;
- OF_HASH_INIT(hash);
+ OFHashInit(&hash);
for (id object in self)
- OF_HASH_ADD_HASH(hash, [object hash]);
+ OFHashAddHash(&hash, [object hash]);
- OF_HASH_FINALIZE(hash);
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -551,14 +552,14 @@
void *pool = objc_autoreleasePoolPush();
OFXMLElement *element;
if ([self isKindOfClass: [OFMutableArray class]])
element = [OFXMLElement elementWithName: @"OFMutableArray"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
else
element = [OFXMLElement elementWithName: @"OFArray"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
for (id object in self) {
void *pool2 = objc_autoreleasePoolPush();
[element addChild: object.XMLElementBySerializing];
@@ -576,23 +577,25 @@
- (OFString *)JSONRepresentation
{
return [self of_JSONRepresentationWithOptions: 0 depth: 0];
}
-- (OFString *)JSONRepresentationWithOptions: (int)options
+- (OFString *)JSONRepresentationWithOptions:
+ (OFJSONRepresentationOptions)options
{
return [self of_JSONRepresentationWithOptions: options depth: 0];
}
-- (OFString *)of_JSONRepresentationWithOptions: (int)options
- depth: (size_t)depth
+- (OFString *)
+ of_JSONRepresentationWithOptions: (OFJSONRepresentationOptions)options
+ depth: (size_t)depth
{
OFMutableString *JSON = [OFMutableString stringWithString: @"["];
void *pool = objc_autoreleasePoolPush();
size_t i, count = self.count;
- if (options & OF_JSON_REPRESENTATION_PRETTY) {
+ if (options & OFJSONRepresentationOptionPretty) {
OFMutableString *indentation = [OFMutableString string];
for (i = 0; i < depth; i++)
[indentation appendString: @"\t"];
@@ -653,17 +656,17 @@
if (count <= 15) {
uint8_t tmp = 0x90 | ((uint8_t)count & 0xF);
[data addItem: &tmp];
} else if (count <= UINT16_MAX) {
uint8_t type = 0xDC;
- uint16_t tmp = OF_BSWAP16_IF_LE((uint16_t)count);
+ uint16_t tmp = OFToBigEndian16((uint16_t)count);
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else if (count <= UINT32_MAX) {
uint8_t type = 0xDD;
- uint32_t tmp = OF_BSWAP32_IF_LE((uint32_t)count);
+ uint32_t tmp = OFToBigEndian32((uint32_t)count);
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else
@throw [OFOutOfRangeException exception];
@@ -712,21 +715,21 @@
[new makeImmutable];
return new;
}
- (OFArray *)sortedArrayUsingSelector: (SEL)selector
- options: (int)options
+ options: (OFArraySortOptions)options
{
OFMutableArray *new = [[self mutableCopy] autorelease];
[new sortUsingSelector: selector options: options];
[new makeImmutable];
return new;
}
#ifdef OF_HAVE_BLOCKS
-- (OFArray *)sortedArrayUsingComparator: (of_comparator_t)comparator
- options: (int)options
+- (OFArray *)sortedArrayUsingComparator: (OFComparator)comparator
+ options: (OFArraySortOptions)options
{
OFMutableArray *new = [[self mutableCopy] autorelease];
[new sortUsingComparator: comparator options: options];
[new makeImmutable];
return new;
@@ -739,15 +742,15 @@
[new reverse];
[new makeImmutable];
return new;
}
-- (int)countByEnumeratingWithState: (of_fast_enumeration_state_t *)state
+- (int)countByEnumeratingWithState: (OFFastEnumerationState *)state
objects: (id *)objects
count: (int)count
{
- of_range_t range = of_range(state->state, count);
+ OFRange range = OFRangeMake(state->state, count);
if (range.length > SIZE_MAX - range.location)
@throw [OFOutOfRangeException exception];
if (range.location + range.length > self.count)
@@ -770,11 +773,11 @@
return [[[OFArrayEnumerator alloc] initWithArray: self
mutationsPtr: NULL] autorelease];
}
#ifdef OF_HAVE_BLOCKS
-- (void)enumerateObjectsUsingBlock: (of_array_enumeration_block_t)block
+- (void)enumerateObjectsUsingBlock: (OFArrayEnumerationBlock)block
{
size_t i = 0;
bool stop = false;
for (id object in self) {
@@ -816,35 +819,35 @@
[ret makeImmutable];
return ret;
}
#ifdef OF_HAVE_BLOCKS
-- (OFArray *)mappedArrayUsingBlock: (of_array_map_block_t)block
+- (OFArray *)mappedArrayUsingBlock: (OFArrayMapBlock)block
{
OFArray *ret;
size_t count = self.count;
- id *tmp = of_alloc(count, sizeof(id));
+ id *tmp = OFAllocMemory(count, sizeof(id));
@try {
[self enumerateObjectsUsingBlock: ^ (id object, size_t idx,
bool *stop) {
tmp[idx] = block(object, idx);
}];
ret = [OFArray arrayWithObjects: tmp count: count];
} @finally {
- free(tmp);
+ OFFreeMemory(tmp);
}
return ret;
}
-- (OFArray *)filteredArrayUsingBlock: (of_array_filter_block_t)block
+- (OFArray *)filteredArrayUsingBlock: (OFArrayFilterBlock)block
{
OFArray *ret;
size_t count = self.count;
- id *tmp = of_alloc(count, sizeof(id));
+ id *tmp = OFAllocMemory(count, sizeof(id));
@try {
__block size_t i = 0;
[self enumerateObjectsUsingBlock: ^ (id object, size_t idx,
@@ -853,17 +856,17 @@
tmp[i++] = object;
}];
ret = [OFArray arrayWithObjects: tmp count: i];
} @finally {
- free(tmp);
+ OFFreeMemory(tmp);
}
return ret;
}
-- (id)foldUsingBlock: (of_array_fold_block_t)block
+- (id)foldUsingBlock: (OFArrayFoldBlock)block
{
size_t count = self.count;
__block id current;
if (count == 0)
ADDED src/OFAtomic.h
Index: src/OFAtomic.h
==================================================================
--- src/OFAtomic.h
+++ src/OFAtomic.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include
+
+#import "macros.h"
+
+#ifndef OF_HAVE_ATOMIC_OPS
+# error No atomic operations available!
+#endif
+
+#if !defined(OF_HAVE_THREADS)
+# import "OFAtomic_no_threads.h"
+#elif (defined(OF_X86_64) || defined(OF_X86)) && defined(__GNUC__)
+# import "OFAtomic_x86.h"
+#elif defined(OF_POWERPC) && defined(__GNUC__) && !defined(__APPLE_CC__) && \
+ !defined(OF_AIX)
+# import "OFAtomic_powerpc.h"
+#elif defined(OF_HAVE_ATOMIC_BUILTINS)
+# import "OFAtomic_builtins.h"
+#elif defined(OF_HAVE_SYNC_BUILTINS)
+# import "OFAtomic_sync_builtins.h"
+#elif defined(OF_HAVE_OSATOMIC)
+# import "OFAtomic_osatomic.h"
+#else
+# error No atomic operations available!
+#endif
ADDED src/OFAtomic_builtins.h
Index: src/OFAtomic_builtins.h
==================================================================
--- src/OFAtomic_builtins.h
+++ src/OFAtomic_builtins.h
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+static OF_INLINE int
+OFAtomicIntAdd(volatile int *_Nonnull p, int i)
+{
+ return __atomic_add_fetch(p, i, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Add(volatile int32_t *_Nonnull p, int32_t i)
+{
+ return __atomic_add_fetch(p, i, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE void *_Nullable
+OFAtomicPointerAdd(void *volatile _Nullable *_Nonnull p, intptr_t i)
+{
+ return __atomic_add_fetch(p, i, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE int
+OFAtomicIntSubtract(volatile int *_Nonnull p, int i)
+{
+ return __atomic_sub_fetch(p, i, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Subtract(volatile int32_t *_Nonnull p, int32_t i)
+{
+ return __atomic_sub_fetch(p, i, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE void *_Nullable
+OFAtomicPointerSubtract(void *volatile _Nullable *_Nonnull p, intptr_t i)
+{
+ return __atomic_sub_fetch(p, i, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE int
+OFAtomicIntIncrease(volatile int *_Nonnull p)
+{
+ return __atomic_add_fetch(p, 1, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Increase(volatile int32_t *_Nonnull p)
+{
+ return __atomic_add_fetch(p, 1, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE int
+OFAtomicIntDecrease(volatile int *_Nonnull p)
+{
+ return __atomic_sub_fetch(p, 1, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Decrease(volatile int32_t *_Nonnull p)
+{
+ return __atomic_sub_fetch(p, 1, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntOr(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ return __atomic_or_fetch(p, i, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32Or(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ return __atomic_or_fetch(p, i, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntAnd(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ return __atomic_and_fetch(p, i, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32And(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ return __atomic_and_fetch(p, i, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntXor(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ return __atomic_xor_fetch(p, i, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32Xor(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ return __atomic_xor_fetch(p, i, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE bool
+OFAtomicIntCompareAndSwap(volatile int *_Nonnull p, int o, int n)
+{
+ return __atomic_compare_exchange(p, &o, &n, false,
+ __ATOMIC_RELAXED, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE bool
+OFAtomicInt32CompareAndSwap(volatile int32_t *_Nonnull p, int32_t o, int32_t n)
+{
+ return __atomic_compare_exchange(p, &o, &n, false,
+ __ATOMIC_RELAXED, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE bool
+OFAtomicPointerCompareAndSwap(void *volatile _Nullable *_Nonnull p,
+ void *_Nullable o, void *_Nullable n)
+{
+ return __atomic_compare_exchange(p, &o, &n, false,
+ __ATOMIC_RELAXED, __ATOMIC_RELAXED);
+}
+
+static OF_INLINE void
+OFMemoryBarrier(void)
+{
+ __atomic_thread_fence(__ATOMIC_SEQ_CST);
+}
+
+static OF_INLINE void
+OFAcquireMemoryBarrier(void)
+{
+ __atomic_thread_fence(__ATOMIC_ACQUIRE);
+}
+
+static OF_INLINE void
+OFReleaseMemoryBarrier(void)
+{
+ __atomic_thread_fence(__ATOMIC_RELEASE);
+}
ADDED src/OFAtomic_no_threads.h
Index: src/OFAtomic_no_threads.h
==================================================================
--- src/OFAtomic_no_threads.h
+++ src/OFAtomic_no_threads.h
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+static OF_INLINE int
+OFAtomicIntAdd(volatile int *_Nonnull p, int i)
+{
+ return (*p += i);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Add(volatile int32_t *_Nonnull p, int32_t i)
+{
+ return (*p += i);
+}
+
+static OF_INLINE void *_Nullable
+OFAtomicPointerAdd(void *volatile _Nullable *_Nonnull p, intptr_t i)
+{
+ return (*(char *volatile *)p += i);
+}
+
+static OF_INLINE int
+OFAtomicIntSubtract(volatile int *_Nonnull p, int i)
+{
+ return (*p -= i);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Subtract(volatile int32_t *_Nonnull p, int32_t i)
+{
+ return (*p -= i);
+}
+
+static OF_INLINE void *_Nullable
+OFAtomicPointerSubtract(void *volatile _Nullable *_Nonnull p, intptr_t i)
+{
+ return (*(char *volatile *)p -= i);
+}
+
+static OF_INLINE int
+OFAtomicIntIncrease(volatile int *_Nonnull p)
+{
+ return ++*p;
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Increase(volatile int32_t *_Nonnull p)
+{
+ return ++*p;
+}
+
+static OF_INLINE int
+OFAtomicIntDecrease(volatile int *_Nonnull p)
+{
+ return --*p;
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Decrease(volatile int32_t *_Nonnull p)
+{
+ return --*p;
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntOr(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ return (*p |= i);
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32Or(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ return (*p |= i);
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntAnd(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ return (*p &= i);
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32And(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ return (*p &= i);
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntXor(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ return (*p ^= i);
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32Xor(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ return (*p ^= i);
+}
+
+static OF_INLINE bool
+OFAtomicIntCompareAndSwap(volatile int *_Nonnull p, int o, int n)
+{
+ if (*p == o) {
+ *p = n;
+ return true;
+ }
+
+ return false;
+}
+
+static OF_INLINE bool
+OFAtomicInt32CompareAndSwap(volatile int32_t *_Nonnull p, int32_t o, int32_t n)
+{
+ if (*p == o) {
+ *p = n;
+ return true;
+ }
+
+ return false;
+}
+
+static OF_INLINE bool
+OFAtomicPointerCompareAndSwap(void *volatile _Nullable *_Nonnull p,
+ void *_Nullable o, void *_Nullable n)
+{
+ if (*p == o) {
+ *p = n;
+ return true;
+ }
+
+ return false;
+}
+
+static OF_INLINE void
+OFMemoryBarrier(void)
+{
+ /* nop */
+}
+
+static OF_INLINE void
+OFAcquireMemoryBarrier(void)
+{
+ /* nop */
+}
+
+static OF_INLINE void
+OFReleaseMemoryBarrier(void)
+{
+ /* nop */
+}
ADDED src/OFAtomic_osatomic.h
Index: src/OFAtomic_osatomic.h
==================================================================
--- src/OFAtomic_osatomic.h
+++ src/OFAtomic_osatomic.h
@@ -0,0 +1,157 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include
+
+static OF_INLINE int
+OFAtomicIntAdd(volatile int *_Nonnull p, int i)
+{
+ return OSAtomicAdd32(i, p);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Add(volatile int32_t *_Nonnull p, int32_t i)
+{
+ return OSAtomicAdd32(i, p);
+}
+
+static OF_INLINE void *_Nullable
+OFAtomicPointerAdd(void *volatile _Nullable *_Nonnull p, intptr_t i)
+{
+#ifdef __LP64__
+ return (void *)OSAtomicAdd64(i, (int64_t *)p);
+#else
+ return (void *)OSAtomicAdd32(i, (int32_t *)p);
+#endif
+}
+
+static OF_INLINE int
+OFAtomicIntSubtract(volatile int *_Nonnull p, int i)
+{
+ return OSAtomicAdd32(-i, p);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Subtract(volatile int32_t *_Nonnull p, int32_t i)
+{
+ return OSAtomicAdd32(-i, p);
+}
+
+static OF_INLINE void *_Nullable
+OFAtomicPointerSubtract(void *volatile _Nullable *_Nonnull p, intptr_t i)
+{
+#ifdef __LP64__
+ return (void *)OSAtomicAdd64(-i, (int64_t *)p);
+#else
+ return (void *)OSAtomicAdd32(-i, (int32_t *)p);
+#endif
+}
+
+static OF_INLINE int
+OFAtomicIntIncrease(volatile int *_Nonnull p)
+{
+ return OSAtomicIncrement32(p);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Increase(volatile int32_t *_Nonnull p)
+{
+ return OSAtomicIncrement32(p);
+}
+
+static OF_INLINE int
+OFAtomicIntDecrease(volatile int *_Nonnull p)
+{
+ return OSAtomicDecrement32(p);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Decrease(volatile int32_t *_Nonnull p)
+{
+ return OSAtomicDecrement32(p);
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntOr(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ return OSAtomicOr32(i, p);
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32Or(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ return OSAtomicOr32(i, p);
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntAnd(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ return OSAtomicAnd32(i, p);
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32And(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ return OSAtomicAnd32(i, p);
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntXor(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ return OSAtomicXor32(i, p);
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32Xor(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ return OSAtomicXor32(i, p);
+}
+
+static OF_INLINE bool
+OFAtomicIntCompareAndSwap(volatile int *_Nonnull p, int o, int n)
+{
+ return OSAtomicCompareAndSwapInt(o, n, p);
+}
+
+static OF_INLINE bool
+OFAtomicInt32CompareAndSwap(volatile int32_t *_Nonnull p, int32_t o, int32_t n)
+{
+ return OSAtomicCompareAndSwap32(o, n, p);
+}
+
+static OF_INLINE bool
+OFAtomicPointerCompareAndSwap(void *volatile _Nullable *_Nonnull p,
+ void *_Nullable o, void *_Nullable n)
+{
+ return OSAtomicCompareAndSwapPtr(o, n, p);
+}
+
+static OF_INLINE void
+OFMemoryBarrier(void)
+{
+ OSMemoryBarrier();
+}
+
+static OF_INLINE void
+OFAcquireMemoryBarrier(void)
+{
+ OSMemoryBarrier();
+}
+
+static OF_INLINE void
+OFReleaseMemoryBarrier(void)
+{
+ OSMemoryBarrier();
+}
ADDED src/OFAtomic_powerpc.h
Index: src/OFAtomic_powerpc.h
==================================================================
--- src/OFAtomic_powerpc.h
+++ src/OFAtomic_powerpc.h
@@ -0,0 +1,397 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+static OF_INLINE int
+OFAtomicIntAdd(volatile int *_Nonnull p, int i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %2\n\t"
+ "add %0, %0, %1\n\t"
+ "stwcx. %0, 0, %2\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(i), "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Add(volatile int32_t *_Nonnull p, int32_t i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %2\n\t"
+ "add %0, %0, %1\n\t"
+ "stwcx. %0, 0, %2\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(i), "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE void *_Nullable
+OFAtomicPointerAdd(void *volatile _Nullable *_Nonnull p, intptr_t i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %2\n\t"
+ "add %0, %0, %1\n\t"
+ "stwcx. %0, 0, %2\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(i), "r"(p)
+ : "cc", "memory"
+ );
+
+ return (void *)i;
+}
+
+static OF_INLINE int
+OFAtomicIntSubtract(volatile int *_Nonnull p, int i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %2\n\t"
+ "sub %0, %0, %1\n\t"
+ "stwcx. %0, 0, %2\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(i), "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Subtract(volatile int32_t *_Nonnull p, int32_t i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %2\n\t"
+ "sub %0, %0, %1\n\t"
+ "stwcx. %0, 0, %2\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(i), "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE void *_Nullable
+OFAtomicPointerSubtract(void *volatile _Nullable *_Nonnull p, intptr_t i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %2\n\t"
+ "sub %0, %0, %1\n\t"
+ "stwcx. %0, 0, %2\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(i), "r"(p)
+ : "cc", "memory"
+ );
+
+ return (void *)i;
+}
+
+static OF_INLINE int
+OFAtomicIntIncrease(volatile int *_Nonnull p)
+{
+ int i;
+
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %1\n\t"
+ "addi %0, %0, 1\n\t"
+ "stwcx. %0, 0, %1\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Increase(volatile int32_t *_Nonnull p)
+{
+ int32_t i;
+
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %1\n\t"
+ "addi %0, %0, 1\n\t"
+ "stwcx. %0, 0, %1\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE int
+OFAtomicIntDecrease(volatile int *_Nonnull p)
+{
+ int i;
+
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %1\n\t"
+ "subi %0, %0, 1\n\t"
+ "stwcx. %0, 0, %1\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Decrease(volatile int32_t *_Nonnull p)
+{
+ int32_t i;
+
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %1\n\t"
+ "subi %0, %0, 1\n\t"
+ "stwcx. %0, 0, %1\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntOr(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %2\n\t"
+ "or %0, %0, %1\n\t"
+ "stwcx. %0, 0, %2\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(i), "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32Or(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %2\n\t"
+ "or %0, %0, %1\n\t"
+ "stwcx. %0, 0, %2\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(i), "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntAnd(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %2\n\t"
+ "and %0, %0, %1\n\t"
+ "stwcx. %0, 0, %2\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(i), "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32And(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %2\n\t"
+ "and %0, %0, %1\n\t"
+ "stwcx. %0, 0, %2\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(i), "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntXor(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %2\n\t"
+ "xor %0, %0, %1\n\t"
+ "stwcx. %0, 0, %2\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(i), "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32Xor(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %2\n\t"
+ "xor %0, %0, %1\n\t"
+ "stwcx. %0, 0, %2\n\t"
+ "bne- 0b"
+ : "=&r"(i)
+ : "r"(i), "r"(p)
+ : "cc", "memory"
+ );
+
+ return i;
+}
+
+static OF_INLINE bool
+OFAtomicIntCompAndSwap(volatile int *_Nonnull p, int o, int n)
+{
+ int r;
+
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %3\n\t"
+ "cmpw %0, %1\n\t"
+ "bne 1f\n\t"
+ "stwcx. %2, 0, %3\n\t"
+ "bne- 0b\n\t"
+ "li %0, 1\n\t"
+ "b 2f\n\t"
+ "1:\n\t"
+ "stwcx. %0, 0, %3\n\t"
+ "li %0, 0\n\t"
+ "2:"
+ : "=&r"(r)
+ : "r"(o), "r"(n), "r"(p)
+ : "cc", "memory"
+ );
+
+ return r;
+}
+
+static OF_INLINE bool
+OFAtomicInt32CompareAndSwap(volatile int32_t *_Nonnull p, int32_t o, int32_t n)
+{
+ int r;
+
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %3\n\t"
+ "cmpw %0, %1\n\t"
+ "bne 1f\n\t"
+ "stwcx. %2, 0, %3\n\t"
+ "bne- 0b\n\t"
+ "li %0, 1\n\t"
+ "b 2f\n\t"
+ "1:\n\t"
+ "stwcx. %0, 0, %3\n\t"
+ "li %0, 0\n\t"
+ "2:"
+ : "=&r"(r)
+ : "r"(o), "r"(n), "r"(p)
+ : "cc", "memory"
+ );
+
+ return r;
+}
+
+static OF_INLINE bool
+OFAtomicPointerCompareAndSwap(void *volatile _Nullable *_Nonnull p,
+ void *_Nullable o, void *_Nullable n)
+{
+ int r;
+
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "lwarx %0, 0, %3\n\t"
+ "cmpw %0, %1\n\t"
+ "bne 1f\n\t"
+ "stwcx. %2, 0, %3\n\t"
+ "bne- 0b\n\t"
+ "li %0, 1\n\t"
+ "b 2f\n\t"
+ "1:\n\t"
+ "stwcx. %0, 0, %3\n\t"
+ "li %0, 0\n\t"
+ "2:"
+ : "=&r"(r)
+ : "r"(o), "r"(n), "r"(p)
+ : "cc", "memory"
+ );
+
+ return r;
+}
+
+static OF_INLINE void
+OFMemoryBarrier(void)
+{
+ __asm__ __volatile__ (
+ ".long 0x7C2004AC /* lwsync */" ::: "memory"
+ );
+}
+
+static OF_INLINE void
+OFAcquireMemoryBarrier(void)
+{
+ __asm__ __volatile__ (
+ ".long 0x7C2004AC /* lwsync */" ::: "memory"
+ );
+}
+
+static OF_INLINE void
+OFReleaseMemoryBarrier(void)
+{
+ __asm__ __volatile__ (
+ ".long 0x7C2004AC /* lwsync */" ::: "memory"
+ );
+}
ADDED src/OFAtomic_sync_builtins.h
Index: src/OFAtomic_sync_builtins.h
==================================================================
--- src/OFAtomic_sync_builtins.h
+++ src/OFAtomic_sync_builtins.h
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+static OF_INLINE int
+OFAtomicIntAdd(volatile int *_Nonnull p, int i)
+{
+ return __sync_add_and_fetch(p, i);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Add(volatile int32_t *_Nonnull p, int32_t i)
+{
+ return __sync_add_and_fetch(p, i);
+}
+
+static OF_INLINE void *_Nullable
+OFAtomicPointerAdd(void *volatile _Nullable *_Nonnull p, intptr_t i)
+{
+ return __sync_add_and_fetch(p, (void *)i);
+}
+
+static OF_INLINE int
+OFAtomicIntSubtract(volatile int *_Nonnull p, int i)
+{
+ return __sync_sub_and_fetch(p, i);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Subtract(volatile int32_t *_Nonnull p, int32_t i)
+{
+ return __sync_sub_and_fetch(p, i);
+}
+
+static OF_INLINE void *_Nullable
+OFAtomicPointerSubtract(void *volatile _Nullable *_Nonnull p, intptr_t i)
+{
+ return __sync_sub_and_fetch(p, (void *)i);
+}
+
+static OF_INLINE int
+OFAtomicIntIncrease(volatile int *_Nonnull p)
+{
+ return __sync_add_and_fetch(p, 1);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Increase(volatile int32_t *_Nonnull p)
+{
+ return __sync_add_and_fetch(p, 1);
+}
+
+static OF_INLINE int
+OFAtomicIntDecrease(volatile int *_Nonnull p)
+{
+ return __sync_sub_and_fetch(p, 1);
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Decrease(volatile int32_t *_Nonnull p)
+{
+ return __sync_sub_and_fetch(p, 1);
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntOr(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ return __sync_or_and_fetch(p, i);
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32Or(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ return __sync_or_and_fetch(p, i);
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntAnd(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ return __sync_and_and_fetch(p, i);
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32And(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ return __sync_and_and_fetch(p, i);
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntXor(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ return __sync_xor_and_fetch(p, i);
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32Xor(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ return __sync_xor_and_fetch(p, i);
+}
+
+static OF_INLINE bool
+OFAtomicIntCompareAndSwap(volatile int *_Nonnull p, int o, int n)
+{
+ return __sync_bool_compare_and_swap(p, o, n);
+}
+
+static OF_INLINE bool
+OFAtomicInt32CompAndSwap(volatile int32_t *_Nonnull p, int32_t o, int32_t n)
+{
+ return __sync_bool_compare_and_swap(p, o, n);
+}
+
+static OF_INLINE bool
+OFAtomicPointerCompareAndSwap(void *volatile _Nullable *_Nonnull p,
+ void *_Nullable o, void *_Nullable n)
+{
+ return __sync_bool_compare_and_swap(p, o, n);
+}
+
+static OF_INLINE void
+OFMemoryBarrier(void)
+{
+ __sync_synchronize();
+}
+
+static OF_INLINE void
+OFAcquireMemoryBarrier(void)
+{
+ __sync_synchronize();
+}
+
+static OF_INLINE void
+OFReleaseMemoryBarrier(void)
+{
+ __sync_synchronize();
+}
ADDED src/OFAtomic_x86.h
Index: src/OFAtomic_x86.h
==================================================================
--- src/OFAtomic_x86.h
+++ src/OFAtomic_x86.h
@@ -0,0 +1,502 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+OF_ASSUME_NONNULL_BEGIN
+
+static OF_INLINE int
+OFAtomicIntAdd(volatile int *_Nonnull p, int i)
+{
+ if (sizeof(int) == 4)
+ __asm__ __volatile__ (
+ "lock\n\t"
+ "xaddl %0, %2\n\t"
+ "addl %1, %0"
+ : "+&r"(i)
+ : "r"(i), "m"(*p)
+ );
+#ifdef OF_X86_64
+ else if (sizeof(int) == 8)
+ __asm__ __volatile__ (
+ "lock\n\t"
+ "xaddq %0, %2\n\t"
+ "addq %1, %0"
+ : "+&r"(i)
+ : "r"(i), "m"(*p)
+ );
+#endif
+ else
+ abort();
+
+ return i;
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Add(volatile int32_t *_Nonnull p, int32_t i)
+{
+ __asm__ __volatile__ (
+ "lock\n\t"
+ "xaddl %0, %2\n\t"
+ "addl %1, %0"
+ : "+&r"(i)
+ : "r"(i), "m"(*p)
+ );
+
+ return i;
+}
+
+static OF_INLINE void *_Nullable
+OFAtomicPointerAdd(void *volatile _Nullable *_Nonnull p, intptr_t i)
+{
+#if defined(OF_X86_64)
+ __asm__ __volatile__ (
+ "lock\n\t"
+ "xaddq %0, %2\n\t"
+ "addq %1, %0"
+ : "+&r"(i)
+ : "r"(i), "m"(*p)
+ );
+
+ return (void *)i;
+#elif defined(OF_X86)
+ __asm__ __volatile__ (
+ "lock\n\t"
+ "xaddl %0, %2\n\t"
+ "addl %1, %0"
+ : "+&r"(i)
+ : "r"(i), "m"(*p)
+ );
+
+ return (void *)i;
+#endif
+}
+
+static OF_INLINE int
+OFAtomicIntSubtract(volatile int *_Nonnull p, int i)
+{
+ if (sizeof(int) == 4)
+ __asm__ __volatile__ (
+ "negl %0\n\t"
+ "lock\n\t"
+ "xaddl %0, %2\n\t"
+ "subl %1, %0"
+ : "+&r"(i)
+ : "r"(i), "m"(*p)
+ );
+#ifdef OF_X86_64
+ else if (sizeof(int) == 8)
+ __asm__ __volatile__ (
+ "negq %0\n\t"
+ "lock\n\t"
+ "xaddq %0, %2\n\t"
+ "subq %1, %0"
+ : "+&r"(i)
+ : "r"(i), "m"(*p)
+ );
+#endif
+ else
+ abort();
+
+ return i;
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Subtract(volatile int32_t *_Nonnull p, int32_t i)
+{
+ __asm__ __volatile__ (
+ "negl %0\n\t"
+ "lock\n\t"
+ "xaddl %0, %2\n\t"
+ "subl %1, %0"
+ : "+&r"(i)
+ : "r"(i), "m"(*p)
+ );
+
+ return i;
+}
+
+static OF_INLINE void *_Nullable
+OFAtomicPointerSubtract(void *volatile _Nullable *_Nonnull p, intptr_t i)
+{
+#if defined(OF_X86_64)
+ __asm__ __volatile__ (
+ "negq %0\n\t"
+ "lock\n\t"
+ "xaddq %0, %2\n\t"
+ "subq %1, %0"
+ : "+&r"(i)
+ : "r"(i), "m"(*p)
+ );
+
+ return (void *)i;
+#elif defined(OF_X86)
+ __asm__ __volatile__ (
+ "negl %0\n\t"
+ "lock\n\t"
+ "xaddl %0, %2\n\t"
+ "subl %1, %0"
+ : "+&r"(i)
+ : "r"(i), "m"(*p)
+ );
+
+ return (void *)i;
+#endif
+}
+
+static OF_INLINE int
+OFAtomicIntIncrease(volatile int *_Nonnull p)
+{
+ int i;
+
+ if (sizeof(int) == 4)
+ __asm__ __volatile__ (
+ "xorl %0, %0\n\t"
+ "incl %0\n\t"
+ "lock\n\t"
+ "xaddl %0, %1\n\t"
+ "incl %0"
+ : "=&r"(i)
+ : "m"(*p)
+ );
+#ifdef OF_X86_64
+ else if (sizeof(int) == 8)
+ __asm__ __volatile__ (
+ "xorq %0, %0\n\t"
+ "incq %0\n\t"
+ "lock\n\t"
+ "xaddq %0, %1\n\t"
+ "incq %0"
+ : "=&r"(i)
+ : "m"(*p)
+ );
+#endif
+ else
+ abort();
+
+ return i;
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Increase(volatile int32_t *_Nonnull p)
+{
+ int32_t i;
+
+ __asm__ __volatile__ (
+ "xorl %0, %0\n\t"
+ "incl %0\n\t"
+ "lock\n\t"
+ "xaddl %0, %1\n\t"
+ "incl %0"
+ : "=&r"(i)
+ : "m"(*p)
+ );
+
+ return i;
+}
+
+static OF_INLINE int
+OFAtomicIntDecrease(volatile int *_Nonnull p)
+{
+ int i;
+
+ if (sizeof(int) == 4)
+ __asm__ __volatile__ (
+ "xorl %0, %0\n\t"
+ "decl %0\n\t"
+ "lock\n\t"
+ "xaddl %0, %1\n\t"
+ "decl %0"
+ : "=&r"(i)
+ : "m"(*p)
+ );
+#ifdef OF_X86_64
+ else if (sizeof(int) == 8)
+ __asm__ __volatile__ (
+ "xorq %0, %0\n\t"
+ "decq %0\n\t"
+ "lock\n\t"
+ "xaddq %0, %1\n\t"
+ "decq %0"
+ : "=&r"(i)
+ : "m"(*p)
+ );
+#endif
+ else
+ abort();
+
+ return i;
+}
+
+static OF_INLINE int32_t
+OFAtomicInt32Decrease(volatile int32_t *_Nonnull p)
+{
+ int32_t i;
+
+ __asm__ __volatile__ (
+ "xorl %0, %0\n\t"
+ "decl %0\n\t"
+ "lock\n\t"
+ "xaddl %0, %1\n\t"
+ "decl %0"
+ : "=&r"(i)
+ : "m"(*p)
+ );
+
+ return i;
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntOr(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ if (sizeof(int) == 4)
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "movl %2, %0\n\t"
+ "movl %0, %%eax\n\t"
+ "orl %1, %0\n\t"
+ "lock\n\t"
+ "cmpxchg %0, %2\n\t"
+ "jne 0b"
+ : "=&r"(i)
+ : "r"(i), "m"(*p)
+ : "eax", "cc"
+ );
+#ifdef OF_X86_64
+ else if (sizeof(int) == 8)
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "movq %2, %0\n\t"
+ "movq %0, %%rax\n\t"
+ "orq %1, %0\n\t"
+ "lock\n\t"
+ "cmpxchg %0, %2\n\t"
+ "jne 0b"
+ : "=&r"(i)
+ : "r"(i), "m"(*p)
+ : "rax", "cc"
+ );
+#endif
+ else
+ abort();
+
+ return i;
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32Or(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "movl %2, %0\n\t"
+ "movl %0, %%eax\n\t"
+ "orl %1, %0\n\t"
+ "lock\n\t"
+ "cmpxchg %0, %2\n\t"
+ "jne 0b"
+ : "=&r"(i)
+ : "r"(i), "m"(*p)
+ : "eax", "cc"
+ );
+
+ return i;
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntAnd(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ if (sizeof(int) == 4)
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "movl %2, %0\n\t"
+ "movl %0, %%eax\n\t"
+ "andl %1, %0\n\t"
+ "lock\n\t"
+ "cmpxchg %0, %2\n\t"
+ "jne 0b"
+ : "=&r"(i)
+ : "r"(i), "m"(*p)
+ : "eax", "cc"
+ );
+#ifdef OF_X86_64
+ else if (sizeof(int) == 8)
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "movq %2, %0\n\t"
+ "movq %0, %%rax\n\t"
+ "andq %1, %0\n\t"
+ "lock\n\t"
+ "cmpxchg %0, %2\n\t"
+ "jne 0b"
+ : "=&r"(i)
+ : "r"(i), "m"(*p)
+ : "rax", "cc"
+ );
+#endif
+ else
+ abort();
+
+ return i;
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32And(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "movl %2, %0\n\t"
+ "movl %0, %%eax\n\t"
+ "andl %1, %0\n\t"
+ "lock\n\t"
+ "cmpxchg %0, %2\n\t"
+ "jne 0b"
+ : "=&r"(i)
+ : "r"(i), "m"(*p)
+ : "eax", "cc"
+ );
+
+ return i;
+}
+
+static OF_INLINE unsigned int
+OFAtomicIntXor(volatile unsigned int *_Nonnull p, unsigned int i)
+{
+ if (sizeof(int) == 4)
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "movl %2, %0\n\t"
+ "movl %0, %%eax\n\t"
+ "xorl %1, %0\n\t"
+ "lock\n\t"
+ "cmpxchg %0, %2\n\t"
+ "jne 0b"
+ : "=&r"(i)
+ : "r"(i), "m"(*p)
+ : "eax", "cc"
+ );
+#ifdef OF_X86_64
+ else if (sizeof(int) == 8)
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "movq %2, %0\n\t"
+ "movq %0, %%rax\n\t"
+ "xorq %1, %0\n\t"
+ "lock\n\t"
+ "cmpxchg %0, %2\n\t"
+ "jne 0b"
+ : "=&r"(i)
+ : "r"(i), "m"(*p)
+ : "rax", "cc"
+ );
+#endif
+ else
+ abort();
+
+ return i;
+}
+
+static OF_INLINE uint32_t
+OFAtomicInt32Xor(volatile uint32_t *_Nonnull p, uint32_t i)
+{
+ __asm__ __volatile__ (
+ "0:\n\t"
+ "movl %2, %0\n\t"
+ "movl %0, %%eax\n\t"
+ "xorl %1, %0\n\t"
+ "lock\n\t"
+ "cmpxchgl %0, %2\n\t"
+ "jne 0b"
+ : "=&r"(i)
+ : "r"(i), "m"(*p)
+ : "eax", "cc"
+ );
+
+ return i;
+}
+
+static OF_INLINE bool
+OFAtomicIntCompareAndSwap(volatile int *_Nonnull p, int o, int n)
+{
+ int r;
+
+ __asm__ __volatile__ (
+ "lock\n\t"
+ "cmpxchg %2, %3\n\t"
+ "sete %b0\n\t"
+ "movzbl %b0, %0"
+ : "=&d"(r), "+a"(o) /* use d instead of r to avoid a gcc bug */
+ : "r"(n), "m"(*p)
+ : "cc"
+ );
+
+ return r;
+}
+
+static OF_INLINE bool
+OFAtomicInt32CompareAndSwap(volatile int32_t *_Nonnull p, int32_t o, int32_t n)
+{
+ int r;
+
+ __asm__ __volatile__ (
+ "lock\n\t"
+ "cmpxchg %2, %3\n\t"
+ "sete %b0\n\t"
+ "movzbl %b0, %0"
+ : "=&d"(r), "+a"(o) /* use d instead of r to avoid a gcc bug */
+ : "r"(n), "m"(*p)
+ : "cc"
+ );
+
+ return r;
+}
+
+static OF_INLINE bool
+OFAtomicPointerCompareAndSwap(void *volatile _Nullable *_Nonnull p,
+ void *_Nullable o, void *_Nullable n)
+{
+ int r;
+
+ __asm__ __volatile__ (
+ "lock\n\t"
+ "cmpxchg %2, %3\n\t"
+ "sete %b0\n\t"
+ "movzbl %b0, %0"
+ : "=&d"(r), "+a"(o) /* use d instead of r to avoid a gcc bug */
+ : "r"(n), "m"(*p)
+ : "cc"
+ );
+
+ return r;
+}
+
+static OF_INLINE void
+OFMemoryBarrier(void)
+{
+ __asm__ __volatile__ (
+ "mfence" ::: "memory"
+ );
+}
+
+static OF_INLINE void
+OFAcquireMemoryBarrier(void)
+{
+ __asm__ __volatile__ ("" ::: "memory");
+}
+
+static OF_INLINE void
+OFReleaseMemoryBarrier(void)
+{
+ __asm__ __volatile__ ("" ::: "memory");
+}
+
+OF_ASSUME_NONNULL_END
ADDED src/OFBase64.h
Index: src/OFBase64.h
==================================================================
--- src/OFBase64.h
+++ src/OFBase64.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#ifndef __STDC_LIMIT_MACROS
+# define __STDC_LIMIT_MACROS
+#endif
+#ifndef __STDC_CONSTANT_MACROS
+# define __STDC_CONSTANT_MACROS
+#endif
+
+#import "macros.h"
+
+OF_ASSUME_NONNULL_BEGIN
+
+@class OFString;
+@class OFMutableData;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern OFString *OFBase64Encode(const void *, size_t);
+extern bool OFBase64Decode(OFMutableData *, const char *, size_t);
+#ifdef __cplusplus
+}
+#endif
+
+OF_ASSUME_NONNULL_END
ADDED src/OFBase64.m
Index: src/OFBase64.m
==================================================================
--- src/OFBase64.m
+++ src/OFBase64.m
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#import "OFBase64.h"
+#import "OFString.h"
+#import "OFData.h"
+
+static const unsigned char encodeTable[64] = {
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
+ 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b',
+ 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
+ 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
+ '4', '5', '6', '7', '8', '9', '+', '/'
+};
+
+static const signed char decodeTable[128] = {
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
+ 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 1, 2,
+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
+ 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30,
+ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
+ 48, 49, 50, 51, -1, -1, -1, -1, -1
+};
+
+OFString *
+OFBase64Encode(const void *data, size_t length)
+{
+ OFMutableString *ret = [OFMutableString string];
+ uint8_t *buffer = (uint8_t *)data;
+ size_t i;
+ uint8_t rest;
+ char tb[4];
+ uint32_t sb;
+
+ rest = length % 3;
+
+ for (i = 0; i < length - rest; i += 3) {
+ sb = (buffer[i] << 16) | (buffer[i + 1] << 8) | buffer[i + 2];
+
+ tb[0] = encodeTable[(sb & 0xFC0000) >> 18];
+ tb[1] = encodeTable[(sb & 0x03F000) >> 12];
+ tb[2] = encodeTable[(sb & 0x000FC0) >> 6];
+ tb[3] = encodeTable[sb & 0x00003F];
+
+ [ret appendCString: tb
+ encoding: OFStringEncodingASCII
+ length: 4];
+ }
+
+ switch (rest) {
+ case 1:
+ tb[0] = encodeTable[buffer[i] >> 2];
+ tb[1] = encodeTable[(buffer[i] & 3) << 4];
+ tb[2] = tb[3] = '=';
+
+ [ret appendCString: tb
+ encoding: OFStringEncodingASCII
+ length: 4];
+
+ break;
+ case 2:
+ sb = (buffer[i] << 16) | (buffer[i + 1] << 8);
+
+ tb[0] = encodeTable[(sb & 0xFC0000) >> 18];
+ tb[1] = encodeTable[(sb & 0x03F000) >> 12];
+ tb[2] = encodeTable[(sb & 0x000FC0) >> 6];
+ tb[3] = '=';
+
+ [ret appendCString: tb
+ encoding: OFStringEncodingASCII
+ length: 4];
+
+ break;
+ }
+
+ [ret makeImmutable];
+
+ return ret;
+}
+
+bool
+OFBase64Decode(OFMutableData *data, const char *string, size_t length)
+{
+ const uint8_t *buffer = (const uint8_t *)string;
+ size_t i;
+
+ if ((length & 3) != 0)
+ return false;
+
+ if (data.itemSize != 1)
+ return false;
+
+ for (i = 0; i < length; i += 4) {
+ uint32_t sb = 0;
+ uint8_t count = 3;
+ char db[3];
+ int8_t tmp;
+
+ if (buffer[i] > 0x7F || buffer[i + 1] > 0x7F ||
+ buffer[i + 2] > 0x7F || buffer[i + 3] > 0x7F)
+ return false;
+
+ if (buffer[i] == '=' || buffer[i + 1] == '=' ||
+ (buffer[i + 2] == '=' && buffer[i + 3] != '='))
+ return false;
+
+ if (buffer[i + 2] == '=')
+ count--;
+ if (buffer[i + 3] == '=')
+ count--;
+
+ if ((tmp = decodeTable[buffer[i]]) == -1)
+ return false;
+
+ sb |= tmp << 18;
+
+ if ((tmp = decodeTable[buffer[i + 1]]) == -1)
+ return false;
+
+ sb |= tmp << 12;
+
+ if ((tmp = decodeTable[buffer[i + 2]]) == -1)
+ return false;
+
+ sb |= tmp << 6;
+
+ if ((tmp = decodeTable[buffer[i + 3]]) == -1)
+ return false;
+
+ sb |= tmp;
+
+ db[0] = (sb & 0xFF0000) >> 16;
+ db[1] = (sb & 0x00FF00) >> 8;
+ db[2] = sb & 0x0000FF;
+
+ [data addItems: db count: count];
+ }
+
+ return true;
+}
Index: src/OFBitSetCharacterSet.m
==================================================================
--- src/OFBitSetCharacterSet.m
+++ src/OFBitSetCharacterSet.m
@@ -30,33 +30,33 @@
{
self = [super init];
@try {
void *pool = objc_autoreleasePoolPush();
- const of_unichar_t *characters = string.characters;
+ const OFUnichar *characters = string.characters;
size_t length = string.length;
for (size_t i = 0; i < length; i++) {
- of_unichar_t c = characters[i];
+ OFUnichar c = characters[i];
if (c / CHAR_BIT >= _size) {
size_t newSize;
if (UINT32_MAX - c < 1)
@throw [OFOutOfRangeException
exception];
- newSize = OF_ROUND_UP_POW2(CHAR_BIT, c + 1) /
+ newSize = OFRoundUpToPowerOf2(CHAR_BIT, c + 1) /
CHAR_BIT;
- _bitset = of_realloc(_bitset, newSize, 1);
+ _bitset = OFResizeMemory(_bitset, newSize, 1);
memset(_bitset + _size, '\0', newSize - _size);
_size = newSize;
}
- of_bitset_set(_bitset, c);
+ OFBitsetSet(_bitset, c);
}
objc_autoreleasePoolPop(pool);
} @catch (id e) {
[self release];
@@ -66,18 +66,18 @@
return self;
}
- (void)dealloc
{
- free(_bitset);
+ OFFreeMemory(_bitset);
[super dealloc];
}
-- (bool)characterIsMember: (of_unichar_t)character
+- (bool)characterIsMember: (OFUnichar)character
{
if (character / CHAR_BIT >= _size)
return false;
- return of_bitset_isset(_bitset, character);
+ return OFBitsetIsSet(_bitset, character);
}
@end
Index: src/OFBlock.h
==================================================================
--- src/OFBlock.h
+++ src/OFBlock.h
@@ -13,12 +13,10 @@
* file.
*/
#import "OFObject.h"
-#import "block.h"
-
OF_ASSUME_NONNULL_BEGIN
/**
* @class OFBlock OFBlock.h ObjFW/OFBlock.h
*
@@ -38,7 +36,39 @@
@end
OF_SUBCLASSING_RESTRICTED
@interface OFMallocBlock: OFBlock
@end
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern void *_Block_copy(const void *);
+extern void _Block_release(const void *);
+
+# if defined(OF_WINDOWS) && \
+ (defined(OF_NO_SHARED) || defined(OF_COMPILING_OBJFW))
+/*
+ * Clang has implicit declarations for these, but they are dllimport. When
+ * compiling ObjFW itself or using it as a static library, these need to be
+ * dllexport. Interestingly, this still works when using it as a shared library.
+ */
+extern __declspec(dllexport) struct objc_class _NSConcreteStackBlock;
+extern __declspec(dllexport) struct objc_class _NSConcreteGlobalBlock;
+extern __declspec(dllexport) void _Block_object_assign(void *, const void *,
+ const int);
+extern __declspec(dllexport) void _Block_object_dispose(const void *,
+ const int);
+# endif
+#ifdef __cplusplus
+}
+#endif
+
+#ifndef Block_copy
+# define Block_copy(...) \
+ ((__typeof__(__VA_ARGS__))_Block_copy((const void *)(__VA_ARGS__)))
+#endif
+#ifndef Block_release
+# define Block_release(...) _Block_release((const void *)(__VA_ARGS__))
+#endif
OF_ASSUME_NONNULL_END
Index: src/OFBlock.m
==================================================================
--- src/OFBlock.m
+++ src/OFBlock.m
@@ -18,50 +18,62 @@
#include
#include
#include
#import "OFBlock.h"
+#ifdef OF_HAVE_ATOMIC_OPS
+# import "OFAtomic.h"
+#endif
+#ifdef OF_HAVE_THREADS
+# import "OFPlainMutex.h"
+#endif
#import "OFAllocFailedException.h"
#import "OFInitializationFailedException.h"
#if defined(OF_OBJFW_RUNTIME)
# import "runtime/private.h"
#endif
-#ifdef OF_HAVE_ATOMIC_OPS
-# import "atomic.h"
-#endif
-#ifdef OF_HAVE_THREADS
-# import "mutex.h"
-#endif
-
-typedef struct of_block_byref_t of_block_byref_t;
-struct of_block_byref_t {
+struct Block {
+ Class isa;
+ int flags;
+ int reserved;
+ void (*invoke)(void *block, ...);
+ struct {
+ unsigned long reserved;
+ unsigned long size;
+ void (*_Nullable copyHelper)(void *dest, void *src);
+ void (*_Nullable disposeHelper)(void *src);
+ const char *signature;
+ } *descriptor;
+};
+
+struct Byref {
Class isa;
- of_block_byref_t *forwarding;
+ struct Byref *forwarding;
int flags;
int size;
- void (*byref_keep)(void *dest, void *src);
- void (*byref_dispose)(void *);
-};
-
-enum {
- OF_BLOCK_HAS_COPY_DISPOSE = (1 << 25),
- OF_BLOCK_HAS_CTOR = (1 << 26),
- OF_BLOCK_IS_GLOBAL = (1 << 28),
- OF_BLOCK_HAS_STRET = (1 << 29),
- OF_BLOCK_HAS_SIGNATURE = (1 << 30)
-};
-#define OF_BLOCK_REFCOUNT_MASK 0xFFFF
-
-enum {
- OF_BLOCK_FIELD_IS_OBJECT = 3,
- OF_BLOCK_FIELD_IS_BLOCK = 7,
- OF_BLOCK_FIELD_IS_BYREF = 8,
- OF_BLOCK_FIELD_IS_WEAK = 16,
- OF_BLOCK_BYREF_CALLER = 128
+ void (*keepByref)(void *dest, void *src);
+ void (*disposeByref)(void *);
+};
+
+enum {
+ OFBlockHasCopyDispose = (1 << 25),
+ OFBlockHasCtor = (1 << 26),
+ OFBlockIsGlobal = (1 << 28),
+ OFBlockHasStret = (1 << 29),
+ OFBlockHasSignature = (1 << 30)
+};
+#define OFBlockRefCountMask 0xFFFF
+
+enum {
+ OFBlockFieldIsObject = 3,
+ OFBlockFieldIsBlock = 7,
+ OFBlockFieldIsByref = 8,
+ OFBlockFieldIsWeak = 16,
+ OFBlockByrefCaller = 128
};
@protocol RetainRelease
- (instancetype)retain;
- (void)release;
@@ -74,11 +86,11 @@
sizeof(_NSConcreteStackBlock_metaclass), NULL, NULL
};
struct objc_class _NSConcreteStackBlock = {
&_NSConcreteStackBlock_metaclass, (Class)(void *)"OFBlock",
- "OFStackBlock", 8, OBJC_CLASS_INFO_CLASS, sizeof(of_block_literal_t),
+ "OFStackBlock", 8, OBJC_CLASS_INFO_CLASS, sizeof(struct Block),
NULL, NULL
};
static struct objc_class _NSConcreteGlobalBlock_metaclass = {
Nil, Nil, "OFGlobalBlock", 8, OBJC_CLASS_INFO_METACLASS,
@@ -85,11 +97,11 @@
sizeof(_NSConcreteGlobalBlock_metaclass), NULL, NULL
};
struct objc_class _NSConcreteGlobalBlock = {
&_NSConcreteGlobalBlock_metaclass, (Class)(void *)"OFBlock",
- "OFGlobalBlock", 8, OBJC_CLASS_INFO_CLASS, sizeof(of_block_literal_t),
+ "OFGlobalBlock", 8, OBJC_CLASS_INFO_CLASS, sizeof(struct Block),
NULL, NULL
};
static struct objc_class _NSConcreteMallocBlock_metaclass = {
Nil, Nil, "OFMallocBlock", 8, OBJC_CLASS_INFO_METACLASS,
@@ -96,11 +108,11 @@
sizeof(_NSConcreteMallocBlock_metaclass), NULL, NULL
};
struct objc_class _NSConcreteMallocBlock = {
&_NSConcreteMallocBlock_metaclass, (Class)(void *)"OFBlock",
- "OFMallocBlock", 8, OBJC_CLASS_INFO_CLASS, sizeof(of_block_literal_t),
+ "OFMallocBlock", 8, OBJC_CLASS_INFO_CLASS, sizeof(struct Block),
NULL, NULL
};
static struct {
unsigned long unknown;
@@ -152,23 +164,23 @@
static struct {
Class isa;
} alloc_failed_exception;
#ifndef OF_HAVE_ATOMIC_OPS
-# define NUM_SPINLOCKS 8 /* needs to be a power of 2 */
-# define SPINLOCK_HASH(p) ((uintptr_t)p >> 4) & (NUM_SPINLOCKS - 1)
-static of_spinlock_t blockSpinlocks[NUM_SPINLOCKS];
-static of_spinlock_t byrefSpinlocks[NUM_SPINLOCKS];
+# define numSpinlocks 8 /* needs to be a power of 2 */
+# define SPINLOCK_HASH(p) ((uintptr_t)p >> 4) & (numSpinlocks - 1)
+static OFSpinlock blockSpinlocks[numSpinlocks];
+static OFSpinlock byrefSpinlocks[numSpinlocks];
#endif
void *
_Block_copy(const void *block_)
{
- of_block_literal_t *block = (of_block_literal_t *)block_;
+ struct Block *block = (struct Block *)block_;
if ([(id)block isMemberOfClass: (Class)&_NSConcreteStackBlock]) {
- of_block_literal_t *copy;
+ struct Block *copy;
if ((copy = malloc(block->descriptor->size)) == NULL) {
alloc_failed_exception.isa =
[OFAllocFailedException class];
@throw (OFAllocFailedException *)
@@ -177,198 +189,196 @@
memcpy(copy, block, block->descriptor->size);
object_setClass((id)copy, (Class)&_NSConcreteMallocBlock);
copy->flags++;
- if (block->flags & OF_BLOCK_HAS_COPY_DISPOSE)
- block->descriptor->copy_helper(copy, block);
+ if (block->flags & OFBlockHasCopyDispose)
+ block->descriptor->copyHelper(copy, block);
return copy;
}
if ([(id)block isMemberOfClass: (Class)&_NSConcreteMallocBlock]) {
#ifdef OF_HAVE_ATOMIC_OPS
- of_atomic_int_inc(&block->flags);
+ OFAtomicIntIncrease(&block->flags);
#else
unsigned hash = SPINLOCK_HASH(block);
- OF_ENSURE(of_spinlock_lock(&blockSpinlocks[hash]) == 0);
+ OFEnsure(OFSpinlockLock(&blockSpinlocks[hash]) == 0);
block->flags++;
- OF_ENSURE(of_spinlock_unlock(&blockSpinlocks[hash]) == 0);
+ OFEnsure(OFSpinlockUnlock(&blockSpinlocks[hash]) == 0);
#endif
}
return block;
}
void
_Block_release(const void *block_)
{
- of_block_literal_t *block = (of_block_literal_t *)block_;
+ struct Block *block = (struct Block *)block_;
if (object_getClass((id)block) != (Class)&_NSConcreteMallocBlock)
return;
#ifdef OF_HAVE_ATOMIC_OPS
- if ((of_atomic_int_dec(&block->flags) & OF_BLOCK_REFCOUNT_MASK) == 0) {
- if (block->flags & OF_BLOCK_HAS_COPY_DISPOSE)
- block->descriptor->dispose_helper(block);
+ if ((OFAtomicIntDecrease(&block->flags) & OFBlockRefCountMask) == 0) {
+ if (block->flags & OFBlockHasCopyDispose)
+ block->descriptor->disposeHelper(block);
free(block);
}
#else
unsigned hash = SPINLOCK_HASH(block);
- OF_ENSURE(of_spinlock_lock(&blockSpinlocks[hash]) == 0);
- if ((--block->flags & OF_BLOCK_REFCOUNT_MASK) == 0) {
- OF_ENSURE(of_spinlock_unlock(&blockSpinlocks[hash]) == 0);
+ OFEnsure(OFSpinlockLock(&blockSpinlocks[hash]) == 0);
+ if ((--block->flags & OFBlockRefCountMask) == 0) {
+ OFEnsure(OFSpinlockUnlock(&blockSpinlocks[hash]) == 0);
- if (block->flags & OF_BLOCK_HAS_COPY_DISPOSE)
- block->descriptor->dispose_helper(block);
+ if (block->flags & OFBlockHasCopyDispose)
+ block->descriptor->disposeHelper(block);
free(block);
return;
}
- OF_ENSURE(of_spinlock_unlock(&blockSpinlocks[hash]) == 0);
+ OFEnsure(OFSpinlockUnlock(&blockSpinlocks[hash]) == 0);
#endif
}
void
_Block_object_assign(void *dst_, const void *src_, const int flags_)
{
- int flags = flags_ & (OF_BLOCK_FIELD_IS_BLOCK |
- OF_BLOCK_FIELD_IS_OBJECT | OF_BLOCK_FIELD_IS_BYREF);
+ int flags = flags_ & (OFBlockFieldIsBlock | OFBlockFieldIsObject |
+ OFBlockFieldIsByref);
if (src_ == NULL)
return;
switch (flags) {
- case OF_BLOCK_FIELD_IS_BLOCK:
- *(of_block_literal_t **)dst_ = _Block_copy(src_);
+ case OFBlockFieldIsBlock:
+ *(struct Block **)dst_ = _Block_copy(src_);
break;
- case OF_BLOCK_FIELD_IS_OBJECT:
- if (!(flags_ & OF_BLOCK_BYREF_CALLER))
+ case OFBlockFieldIsObject:
+ if (!(flags_ & OFBlockByrefCaller))
*(id *)dst_ = [(id)src_ retain];
break;
- case OF_BLOCK_FIELD_IS_BYREF:;
- of_block_byref_t *src = (of_block_byref_t *)src_;
- of_block_byref_t **dst = (of_block_byref_t **)dst_;
+ case OFBlockFieldIsByref:;
+ struct Byref *src = (struct Byref *)src_;
+ struct Byref **dst = (struct Byref **)dst_;
src = src->forwarding;
- if ((src->flags & OF_BLOCK_REFCOUNT_MASK) == 0) {
+ if ((src->flags & OFBlockRefCountMask) == 0) {
if ((*dst = malloc(src->size)) == NULL) {
alloc_failed_exception.isa =
[OFAllocFailedException class];
@throw (OFAllocFailedException *)
&alloc_failed_exception;
}
memcpy(*dst, src, src->size);
(*dst)->flags =
- ((*dst)->flags & ~OF_BLOCK_REFCOUNT_MASK) | 1;
+ ((*dst)->flags & ~OFBlockRefCountMask) | 1;
(*dst)->forwarding = *dst;
- if (src->flags & OF_BLOCK_HAS_COPY_DISPOSE)
- src->byref_keep(*dst, src);
+ if (src->flags & OFBlockHasCopyDispose)
+ src->keepByref(*dst, src);
#ifdef OF_HAVE_ATOMIC_OPS
- if (!of_atomic_ptr_cmpswap((void **)&src->forwarding,
- src, *dst)) {
- src->byref_dispose(*dst);
+ if (!OFAtomicPointerCompareAndSwap(
+ (void **)&src->forwarding, src, *dst)) {
+ src->disposeByref(*dst);
free(*dst);
*dst = src->forwarding;
}
#else
unsigned hash = SPINLOCK_HASH(src);
- OF_ENSURE(of_spinlock_lock(&byrefSpinlocks[hash]) == 0);
+ OFEnsure(OFSpinlockLock(&byrefSpinlocks[hash]) == 0);
if (src->forwarding == src)
src->forwarding = *dst;
else {
- src->byref_dispose(*dst);
+ src->disposeByref(*dst);
free(*dst);
*dst = src->forwarding;
}
- OF_ENSURE(
- of_spinlock_unlock(&byrefSpinlocks[hash]) == 0);
+ OFEnsure(OFSpinlockUnlock(&byrefSpinlocks[hash]) == 0);
#endif
} else
*dst = src;
#ifdef OF_HAVE_ATOMIC_OPS
- of_atomic_int_inc(&(*dst)->flags);
+ OFAtomicIntIncrease(&(*dst)->flags);
#else
unsigned hash = SPINLOCK_HASH(*dst);
- OF_ENSURE(of_spinlock_lock(&byrefSpinlocks[hash]) == 0);
+ OFEnsure(OFSpinlockLock(&byrefSpinlocks[hash]) == 0);
(*dst)->flags++;
- OF_ENSURE(of_spinlock_unlock(&byrefSpinlocks[hash]) == 0);
+ OFEnsure(OFSpinlockUnlock(&byrefSpinlocks[hash]) == 0);
#endif
break;
}
}
void
_Block_object_dispose(const void *object_, const int flags_)
{
- const int flags = flags_ & (OF_BLOCK_FIELD_IS_BLOCK |
- OF_BLOCK_FIELD_IS_OBJECT | OF_BLOCK_FIELD_IS_BYREF);
+ const int flags = flags_ & (OFBlockFieldIsBlock | OFBlockFieldIsObject |
+ OFBlockFieldIsByref);
if (object_ == NULL)
return;
switch (flags) {
- case OF_BLOCK_FIELD_IS_BLOCK:
+ case OFBlockFieldIsBlock:
_Block_release(object_);
break;
- case OF_BLOCK_FIELD_IS_OBJECT:
- if (!(flags_ & OF_BLOCK_BYREF_CALLER))
+ case OFBlockFieldIsObject:
+ if (!(flags_ & OFBlockByrefCaller))
[(id)object_ release];
break;
- case OF_BLOCK_FIELD_IS_BYREF:;
- of_block_byref_t *object = (of_block_byref_t *)object_;
+ case OFBlockFieldIsByref:;
+ struct Byref *object = (struct Byref *)object_;
object = object->forwarding;
#ifdef OF_HAVE_ATOMIC_OPS
- if ((of_atomic_int_dec(&object->flags) &
- OF_BLOCK_REFCOUNT_MASK) == 0) {
- if (object->flags & OF_BLOCK_HAS_COPY_DISPOSE)
- object->byref_dispose(object);
+ if ((OFAtomicIntDecrease(&object->flags) &
+ OFBlockRefCountMask) == 0) {
+ if (object->flags & OFBlockHasCopyDispose)
+ object->disposeByref(object);
free(object);
}
#else
unsigned hash = SPINLOCK_HASH(object);
- OF_ENSURE(of_spinlock_lock(&byrefSpinlocks[hash]) == 0);
- if ((--object->flags & OF_BLOCK_REFCOUNT_MASK) == 0) {
- OF_ENSURE(
- of_spinlock_unlock(&byrefSpinlocks[hash]) == 0);
+ OFEnsure(OFSpinlockLock(&byrefSpinlocks[hash]) == 0);
+ if ((--object->flags & OFBlockRefCountMask) == 0) {
+ OFEnsure(OFSpinlockUnlock(&byrefSpinlocks[hash]) == 0);
- if (object->flags & OF_BLOCK_HAS_COPY_DISPOSE)
- object->byref_dispose(object);
+ if (object->flags & OFBlockHasCopyDispose)
+ object->disposeByref(object);
free(object);
}
- OF_ENSURE(of_spinlock_unlock(&byrefSpinlocks[hash]) == 0);
+ OFEnsure(OFSpinlockUnlock(&byrefSpinlocks[hash]) == 0);
#endif
break;
}
}
@implementation OFBlock
+ (void)load
{
#ifndef OF_HAVE_ATOMIC_OPS
- for (size_t i = 0; i < NUM_SPINLOCKS; i++)
- if (of_spinlock_new(&blockSpinlocks[i]) != 0 ||
- of_spinlock_new(&byrefSpinlocks[i]) != 0)
+ for (size_t i = 0; i < numSpinlocks; i++)
+ if (OFSpinlockNew(&blockSpinlocks[i]) != 0 ||
+ OFSpinlockNew(&byrefSpinlocks[i]) != 0)
@throw [OFInitializationFailedException
exceptionWithClass: self];
#endif
#ifdef OF_APPLE_RUNTIME
@@ -461,14 +471,13 @@
}
- (unsigned int)retainCount
{
if ([self isMemberOfClass: (Class)&_NSConcreteMallocBlock])
- return ((of_block_literal_t *)self)->flags &
- OF_BLOCK_REFCOUNT_MASK;
+ return ((struct Block *)self)->flags & OFBlockRefCountMask;
- return OF_RETAIN_COUNT_MAX;
+ return OFMaxRetainCount;
}
- (void)release
{
if ([self isMemberOfClass: (Class)&_NSConcreteMallocBlock])
Index: src/OFBytesValue.m
==================================================================
--- src/OFBytesValue.m
+++ src/OFBytesValue.m
@@ -25,13 +25,13 @@
objCType: (const char *)objCType
{
self = [super init];
@try {
- _size = of_sizeof_type_encoding(objCType);
+ _size = OFSizeOfTypeEncoding(objCType);
_objCType = objCType;
- _bytes = of_alloc(1, _size);
+ _bytes = OFAllocMemory(1, _size);
memcpy(_bytes, bytes, _size);
} @catch (id e) {
[self release];
@throw e;
@@ -40,11 +40,11 @@
return self;
}
- (void)dealloc
{
- free(_bytes);
+ OFFreeMemory(_bytes);
[super dealloc];
}
- (void)getValue: (void *)value size: (size_t)size
ADDED src/OFCRC16.h
Index: src/OFCRC16.h
==================================================================
--- src/OFCRC16.h
+++ src/OFCRC16.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#ifndef __STDC_LIMIT_MACROS
+# define __STDC_LIMIT_MACROS
+#endif
+#ifndef __STDC_CONSTANT_MACROS
+# define __STDC_CONSTANT_MACROS
+#endif
+
+#import "macros.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern uint16_t OFCRC16(uint16_t crc, const void *_Nonnull bytes,
+ size_t length);
+#ifdef __cplusplus
+}
+#endif
ADDED src/OFCRC16.m
Index: src/OFCRC16.m
==================================================================
--- src/OFCRC16.m
+++ src/OFCRC16.m
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#import "OFCRC16.h"
+
+static const uint16_t CRC16Magic = 0xA001;
+
+uint16_t
+OFCRC16(uint16_t CRC, const void *bytes_, size_t length)
+{
+ const unsigned char *bytes = bytes_;
+
+ for (size_t i = 0; i < length; i++) {
+ CRC ^= bytes[i];
+
+ for (uint8_t j = 0; j < 8; j++)
+ CRC = (CRC >> 1) ^ (CRC16Magic & (~(CRC & 1) + 1));
+ }
+
+ return CRC;
+}
ADDED src/OFCRC32.h
Index: src/OFCRC32.h
==================================================================
--- src/OFCRC32.h
+++ src/OFCRC32.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#ifndef __STDC_LIMIT_MACROS
+# define __STDC_LIMIT_MACROS
+#endif
+#ifndef __STDC_CONSTANT_MACROS
+# define __STDC_CONSTANT_MACROS
+#endif
+
+#import "macros.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern uint32_t OFCRC32(uint32_t crc, const void *_Nonnull bytes,
+ size_t length);
+#ifdef __cplusplus
+}
+#endif
ADDED src/OFCRC32.m
Index: src/OFCRC32.m
==================================================================
--- src/OFCRC32.m
+++ src/OFCRC32.m
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#import "OFCRC32.h"
+
+static const uint32_t CRC32Magic = 0xEDB88320;
+
+uint32_t
+OFCRC32(uint32_t CRC, const void *bytes_, size_t length)
+{
+ const unsigned char *bytes = bytes_;
+
+ for (size_t i = 0; i < length; i++) {
+ CRC ^= bytes[i];
+
+ for (uint8_t j = 0; j < 8; j++)
+ CRC = (CRC >> 1) ^ (CRC32Magic & (~(CRC & 1) + 1));
+ }
+
+ return CRC;
+}
Index: src/OFCharacterSet.h
==================================================================
--- src/OFCharacterSet.h
+++ src/OFCharacterSet.h
@@ -54,11 +54,11 @@
* range.
*
* @param range The range of characters for the character set
* @return A new OFCharacterSet
*/
-+ (instancetype)characterSetWithRange: (of_range_t)range;
++ (instancetype)characterSetWithRange: (OFRange)range;
/**
* @brief A character set containing all Unicode characters in the category
* `Zs` plus CHARACTER TABULATION (U+0009).
*/
@@ -78,19 +78,19 @@
* the specified range.
*
* @param range The range of characters for the character set
* @return An initialized OFCharacterSet
*/
-- (instancetype)initWithRange: (of_range_t)range;
+- (instancetype)initWithRange: (OFRange)range;
/**
* @brief Returns whether the specified character is a member of the character
* set.
*
* @param character The character that is checked for being a member of the
* character set
* @return Whether the specified character is a member of the character set.
*/
-- (bool)characterIsMember: (of_unichar_t)character;
+- (bool)characterIsMember: (OFUnichar)character;
@end
OF_ASSUME_NONNULL_END
Index: src/OFCharacterSet.m
==================================================================
--- src/OFCharacterSet.m
+++ src/OFCharacterSet.m
@@ -16,14 +16,13 @@
#include "config.h"
#import "OFCharacterSet.h"
#import "OFBitSetCharacterSet.h"
#import "OFInvertedCharacterSet.h"
+#import "OFOnce.h"
#import "OFRangeCharacterSet.h"
-#import "once.h"
-
@interface OFPlaceholderCharacterSet: OFCharacterSet
@end
@interface OFWhitespaceCharacterSet: OFCharacterSet
@end
@@ -50,11 +49,11 @@
{
return (id)[[OFBitSetCharacterSet alloc]
initWithCharactersInString: characters];
}
-- (instancetype)initWithRange: (of_range_t)range
+- (instancetype)initWithRange: (OFRange)range
{
return (id)[[OFRangeCharacterSet alloc] initWithRange: range];
}
- (instancetype)retain
@@ -98,19 +97,19 @@
{
return [[[self alloc] initWithCharactersInString: characters]
autorelease];
}
-+ (instancetype)characterSetWithRange: (of_range_t)range
++ (instancetype)characterSetWithRange: (OFRange)range
{
return [[[self alloc] initWithRange: range] autorelease];
}
+ (OFCharacterSet *)whitespaceCharacterSet
{
- static of_once_t onceControl = OF_ONCE_INIT;
- of_once(&onceControl, initWhitespaceCharacterSet);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, initWhitespaceCharacterSet);
return whitespaceCharacterSet;
}
- (instancetype)init
@@ -132,16 +131,16 @@
- (instancetype)initWithCharactersInString: (OFString *)characters
{
OF_INVALID_INIT_METHOD
}
-- (instancetype)initWithRange: (of_range_t)range
+- (instancetype)initWithRange: (OFRange)range
{
OF_INVALID_INIT_METHOD
}
-- (bool)characterIsMember: (of_unichar_t)character
+- (bool)characterIsMember: (OFUnichar)character
{
OF_UNRECOGNIZED_SELECTOR
}
- (OFCharacterSet *)invertedSet
@@ -166,14 +165,14 @@
{
}
- (unsigned int)retainCount
{
- return OF_RETAIN_COUNT_MAX;
+ return OFMaxRetainCount;
}
-- (bool)characterIsMember: (of_unichar_t)character
+- (bool)characterIsMember: (OFUnichar)character
{
switch (character) {
case 0x0009:
case 0x0020:
case 0x00A0:
Index: src/OFColor.m
==================================================================
--- src/OFColor.m
+++ src/OFColor.m
@@ -14,34 +14,33 @@
*/
#include "config.h"
#import "OFColor.h"
-
-#import "once.h"
+#import "OFOnce.h"
#import "OFInvalidArgumentException.h"
@implementation OFColor
-#define PREDEFINED_COLOR(name, r, g, b) \
- static OFColor *name##Color = nil; \
- \
- static void \
- initPredefinedColor_##name(void) \
- { \
- name##Color = [[OFColor alloc] initWithRed: r \
- green: g \
- blue: b \
- alpha: 1]; \
- } \
- \
- + (OFColor *)name \
- { \
- static of_once_t onceControl = OF_ONCE_INIT; \
- of_once(&onceControl, initPredefinedColor_##name); \
- \
- return name##Color; \
+#define PREDEFINED_COLOR(name, redValue, greenValue, blueValue) \
+ static OFColor *name##Color = nil; \
+ \
+ static void \
+ initPredefinedColor_##name(void) \
+ { \
+ name##Color = [[OFColor alloc] initWithRed: redValue \
+ green: greenValue \
+ blue: blueValue \
+ alpha: 1]; \
+ } \
+ \
+ + (OFColor *)name \
+ { \
+ static OFOnceControl onceControl = OFOnceControlInitValue; \
+ OFOnce(&onceControl, initPredefinedColor_##name); \
+ \
+ return name##Color; \
}
PREDEFINED_COLOR(black, 0.00f, 0.00f, 0.00f)
PREDEFINED_COLOR(silver, 0.75f, 0.75f, 0.75f)
PREDEFINED_COLOR(grey, 0.50f, 0.50f, 0.50f)
@@ -120,32 +119,32 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
+ unsigned long hash;
float tmp;
- OF_HASH_INIT(hash);
-
- tmp = OF_BSWAP_FLOAT_IF_LE(_red);
- for (uint_fast8_t i = 0; i < sizeof(float); i++)
- OF_HASH_ADD(hash, ((char *)&tmp)[i]);
-
- tmp = OF_BSWAP_FLOAT_IF_LE(_green);
- for (uint_fast8_t i = 0; i < sizeof(float); i++)
- OF_HASH_ADD(hash, ((char *)&tmp)[i]);
-
- tmp = OF_BSWAP_FLOAT_IF_LE(_blue);
- for (uint_fast8_t i = 0; i < sizeof(float); i++)
- OF_HASH_ADD(hash, ((char *)&tmp)[i]);
-
- tmp = OF_BSWAP_FLOAT_IF_LE(_alpha);
- for (uint_fast8_t i = 0; i < sizeof(float); i++)
- OF_HASH_ADD(hash, ((char *)&tmp)[i]);
-
- OF_HASH_FINALIZE(hash);
+ OFHashInit(&hash);
+
+ tmp = OFToLittleEndianFloat(_red);
+ for (uint_fast8_t i = 0; i < sizeof(float); i++)
+ OFHashAdd(&hash, ((char *)&tmp)[i]);
+
+ tmp = OFToLittleEndianFloat(_green);
+ for (uint_fast8_t i = 0; i < sizeof(float); i++)
+ OFHashAdd(&hash, ((char *)&tmp)[i]);
+
+ tmp = OFToLittleEndianFloat(_blue);
+ for (uint_fast8_t i = 0; i < sizeof(float); i++)
+ OFHashAdd(&hash, ((char *)&tmp)[i]);
+
+ tmp = OFToLittleEndianFloat(_alpha);
+ for (uint_fast8_t i = 0; i < sizeof(float); i++)
+ OFHashAdd(&hash, ((char *)&tmp)[i]);
+
+ OFHashFinalize(&hash);
return hash;
}
- (void)getRed: (float *)red
Index: src/OFCondition.h
==================================================================
--- src/OFCondition.h
+++ src/OFCondition.h
@@ -12,12 +12,11 @@
* LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
* file.
*/
#import "OFMutex.h"
-
-#import "condition.h"
+#import "OFPlainCondition.h"
OF_ASSUME_NONNULL_BEGIN
@class OFDate;
@@ -27,11 +26,11 @@
* @brief A class implementing a condition variable for thread synchronization.
*/
OF_SUBCLASSING_RESTRICTED
@interface OFCondition: OFMutex
{
- of_condition_t _condition;
+ OFPlainCondition _condition;
bool _conditionInitialized;
}
/**
* @brief Creates a new condition.
@@ -70,11 +69,11 @@
* to check the condition again after @ref waitForTimeInterval: returned!
*
* @param timeInterval The time interval until the timeout is reached
* @return Whether the condition has been signaled
*/
-- (bool)waitForTimeInterval: (of_time_interval_t)timeInterval;
+- (bool)waitForTimeInterval: (OFTimeInterval)timeInterval;
#ifdef OF_AMIGAOS
/**
* @brief Blocks the current thread until another thread calls @ref signal,
* @ref broadcast, the timeout is reached or an Exec Signal is received.
@@ -84,11 +83,11 @@
* @param timeInterval The time interval until the timeout is reached
* @param signalMask A pointer to a signal mask of Exec Signals to receive.
* This is modified and set to the mask of signals received.
* @return Whether the condition has been signaled or a signal received
*/
-- (bool)waitForTimeInterval: (of_time_interval_t)timeInterval
+- (bool)waitForTimeInterval: (OFTimeInterval)timeInterval
orExecSignal: (ULONG *)signalMask;
#endif
/**
* @brief Blocks the current thread until another thread calls @ref signal,
Index: src/OFCondition.m
==================================================================
--- src/OFCondition.m
+++ src/OFCondition.m
@@ -34,11 +34,11 @@
- (instancetype)init
{
self = [super init];
- if (of_condition_new(&_condition) != 0) {
+ if (OFPlainConditionNew(&_condition) != 0) {
Class c = self.class;
[self release];
@throw [OFInitializationFailedException exceptionWithClass: c];
}
@@ -48,14 +48,14 @@
}
- (void)dealloc
{
if (_conditionInitialized) {
- int error = of_condition_free(&_condition);
+ int error = OFPlainConditionFree(&_condition);
if (error != 0) {
- OF_ENSURE(error == EBUSY);
+ OFEnsure(error == EBUSY);
@throw [OFConditionStillWaitingException
exceptionWithCondition: self];
}
}
@@ -63,11 +63,11 @@
[super dealloc];
}
- (void)wait
{
- int error = of_condition_wait(&_condition, &_mutex);
+ int error = OFPlainConditionWait(&_condition, &_mutex);
if (error != 0)
@throw [OFConditionWaitFailedException
exceptionWithCondition: self
errNo: error];
@@ -74,23 +74,24 @@
}
#ifdef OF_AMIGAOS
- (void)waitForConditionOrExecSignal: (ULONG *)signalMask
{
- int error = of_condition_wait_or_signal(&_condition, &_mutex,
+ int error = OFPlainConditionWaitOrExecSignal(&_condition, &_mutex,
signalMask);
if (error != 0)
@throw [OFConditionWaitFailedException
exceptionWithCondition: self
errNo: error];
}
#endif
-- (bool)waitForTimeInterval: (of_time_interval_t)timeInterval
+- (bool)waitForTimeInterval: (OFTimeInterval)timeInterval
{
- int error = of_condition_timed_wait(&_condition, &_mutex, timeInterval);
+ int error = OFPlainConditionTimedWait(&_condition, &_mutex,
+ timeInterval);
if (error == ETIMEDOUT)
return false;
if (error != 0)
@@ -100,14 +101,14 @@
return true;
}
#ifdef OF_AMIGAOS
-- (bool)waitForTimeInterval: (of_time_interval_t)timeInterval
+- (bool)waitForTimeInterval: (OFTimeInterval)timeInterval
orExecSignal: (ULONG *)signalMask
{
- int error = of_condition_timed_wait_or_signal(&_condition, &_mutex,
+ int error = OFPlainConditionTimedWaitExecOrSignal(&_condition, &_mutex,
timeInterval, signalMask);
if (error == ETIMEDOUT)
return false;
@@ -133,23 +134,23 @@
}
#endif
- (void)signal
{
- int error = of_condition_signal(&_condition);
+ int error = OFPlainConditionSignal(&_condition);
if (error != 0)
@throw [OFConditionSignalFailedException
exceptionWithCondition: self
errNo: error];
}
- (void)broadcast
{
- int error = of_condition_broadcast(&_condition);
+ int error = OFPlainConditionBroadcast(&_condition);
if (error != 0)
@throw [OFConditionBroadcastFailedException
exceptionWithCondition: self
errNo: error];
}
@end
Index: src/OFConstantString.m
==================================================================
--- src/OFConstantString.m
+++ src/OFConstantString.m
@@ -62,11 +62,11 @@
return self;
}
- (unsigned int)retainCount
{
- return OF_RETAIN_COUNT_MAX;
+ return OFMaxRetainCount;
}
- (void)release
{
}
@@ -104,26 +104,26 @@
}
- (void)finishInitialization
{
@synchronized (self) {
- struct of_string_utf8_ivars *ivars;
+ struct OFUTF8StringIvars *ivars;
if ([self isMemberOfClass: [OFConstantUTF8String class]])
return;
- ivars = of_alloc_zeroed(1, sizeof(*ivars));
+ ivars = OFAllocZeroedMemory(1, sizeof(*ivars));
ivars->cString = _cString;
ivars->cStringLength = _cStringLength;
- switch (of_string_utf8_check(ivars->cString,
- ivars->cStringLength, &ivars->length)) {
+ switch (OFUTF8StringCheck(ivars->cString, ivars->cStringLength,
+ &ivars->length)) {
case 1:
ivars->isUTF8 = true;
break;
case -1:
- free(ivars);
+ OFFreeMemory(ivars);
@throw [OFInvalidEncodingException exception];
}
_cString = (char *)ivars;
object_setClass(self, [OFConstantUTF8String class]);
@@ -145,11 +145,11 @@
return self;
}
- (unsigned int)retainCount
{
- return OF_RETAIN_COUNT_MAX;
+ return OFMaxRetainCount;
}
- (void)release
{
}
@@ -177,11 +177,11 @@
[self finishInitialization];
return [self mutableCopy];
}
/* From protocol OFComparing, but overridden in OFString */
-- (of_comparison_result_t)compare: (OFString *)string
+- (OFComparisonResult)compare: (OFString *)string
{
[self finishInitialization];
return [self compare: string];
}
@@ -211,19 +211,19 @@
return self.UTF8String;
}
- (size_t)getCString: (char *)cString_
maxLength: (size_t)maxLength
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
[self finishInitialization];
return [self getCString: cString_
maxLength: maxLength
encoding: encoding];
}
-- (const char *)cStringWithEncoding: (of_string_encoding_t)encoding
+- (const char *)cStringWithEncoding: (OFStringEncoding)encoding
{
[self finishInitialization];
return [self cStringWithEncoding: encoding];
}
@@ -237,49 +237,50 @@
{
[self finishInitialization];
return self.UTF8StringLength;
}
-- (size_t)cStringLengthWithEncoding: (of_string_encoding_t)encoding
+- (size_t)cStringLengthWithEncoding: (OFStringEncoding)encoding
{
[self finishInitialization];
return [self cStringLengthWithEncoding: encoding];
}
-- (of_comparison_result_t)caseInsensitiveCompare: (OFString *)string
+- (OFComparisonResult)caseInsensitiveCompare: (OFString *)string
{
[self finishInitialization];
return [self caseInsensitiveCompare: string];
}
-- (of_unichar_t)characterAtIndex: (size_t)idx
+- (OFUnichar)characterAtIndex: (size_t)idx
{
[self finishInitialization];
return [self characterAtIndex: idx];
}
-- (void)getCharacters: (of_unichar_t *)buffer inRange: (of_range_t)range
+- (void)getCharacters: (OFUnichar *)buffer inRange: (OFRange)range
{
[self finishInitialization];
[self getCharacters: buffer inRange: range];
}
-- (of_range_t)rangeOfString: (OFString *)string
+- (OFRange)rangeOfString: (OFString *)string
{
[self finishInitialization];
return [self rangeOfString: string];
}
-- (of_range_t)rangeOfString: (OFString *)string options: (int)options
+- (OFRange)rangeOfString: (OFString *)string
+ options: (OFStringSearchOptions)options
{
[self finishInitialization];
return [self rangeOfString: string options: options];
}
-- (of_range_t)rangeOfString: (OFString *)string
- options: (int)options
- range: (of_range_t)range
+- (OFRange)rangeOfString: (OFString *)string
+ options: (OFStringSearchOptions)options
+ range: (OFRange)range
{
[self finishInitialization];
return [self rangeOfString: string options: options range: range];
}
@@ -288,19 +289,19 @@
[self finishInitialization];
return [self indexOfCharacterFromSet: characterSet];
}
- (size_t)indexOfCharacterFromSet: (OFCharacterSet *)characterSet
- options: (int)options
+ options: (OFStringSearchOptions)options
{
[self finishInitialization];
return [self indexOfCharacterFromSet: characterSet options: options];
}
- (size_t)indexOfCharacterFromSet: (OFCharacterSet *)characterSet
- options: (int)options
- range: (of_range_t)range
+ options: (OFStringSearchOptions)options
+ range: (OFRange)range
{
[self finishInitialization];
return [self indexOfCharacterFromSet: characterSet
options: options
range: range];
@@ -322,11 +323,11 @@
{
[self finishInitialization];
return [self substringToIndex: idx];
}
-- (OFString *)substringWithRange: (of_range_t)range
+- (OFString *)substringWithRange: (OFRange)range
{
[self finishInitialization];
return [self substringWithRange: range];
}
@@ -364,11 +365,11 @@
}
- (OFString *)stringByReplacingOccurrencesOfString: (OFString *)string
withString: (OFString *)replacement
options: (int)options
- range: (of_range_t)range
+ range: (OFRange)range
{
[self finishInitialization];
return [self stringByReplacingOccurrencesOfString: string
withString: replacement
options: options
@@ -428,11 +429,11 @@
[self finishInitialization];
return [self componentsSeparatedByString: delimiter];
}
- (OFArray *)componentsSeparatedByString: (OFString *)delimiter
- options: (int)options
+ options: (OFStringSeparationOptions)options
{
[self finishInitialization];
return [self componentsSeparatedByString: delimiter options: options];
}
@@ -443,11 +444,11 @@
return [self componentsSeparatedByCharactersInSet: characterSet];
}
- (OFArray *)
componentsSeparatedByCharactersInSet: (OFCharacterSet *)characterSet
- options: (int)options
+ options: (OFStringSeparationOptions)options
{
[self finishInitialization];
return [self componentsSeparatedByCharactersInSet: characterSet
options: options];
}
@@ -504,23 +505,23 @@
{
[self finishInitialization];
return self.doubleValue;
}
-- (const of_unichar_t *)characters
+- (const OFUnichar *)characters
{
[self finishInitialization];
return self.characters;
}
-- (const of_char16_t *)UTF16String
+- (const OFChar16 *)UTF16String
{
[self finishInitialization];
return self.UTF16String;
}
-- (const of_char16_t *)UTF16StringWithByteOrder: (of_byte_order_t)byteOrder
+- (const OFChar16 *)UTF16StringWithByteOrder: (OFByteOrder)byteOrder
{
[self finishInitialization];
return [self UTF16StringWithByteOrder: byteOrder];
}
@@ -528,23 +529,23 @@
{
[self finishInitialization];
return self.UTF16StringLength;
}
-- (const of_char32_t *)UTF32String
+- (const OFChar32 *)UTF32String
{
[self finishInitialization];
return self.UTF32String;
}
-- (const of_char32_t *)UTF32StringWithByteOrder: (of_byte_order_t)byteOrder
+- (const OFChar32 *)UTF32StringWithByteOrder: (OFByteOrder)byteOrder
{
[self finishInitialization];
return [self UTF32StringWithByteOrder: byteOrder];
}
-- (OFData *)dataWithEncoding: (of_string_encoding_t)encoding
+- (OFData *)dataWithEncoding: (OFStringEncoding)encoding
{
[self finishInitialization];
return [self dataWithEncoding: encoding];
}
@@ -575,11 +576,11 @@
{
[self finishInitialization];
[self writeToFile: path];
}
-- (void)writeToFile: (OFString *)path encoding: (of_string_encoding_t)encoding
+- (void)writeToFile: (OFString *)path encoding: (OFStringEncoding)encoding
{
[self finishInitialization];
[self writeToFile: path encoding: encoding];
}
#endif
@@ -588,19 +589,19 @@
{
[self finishInitialization];
[self writeToURL: URL];
}
-- (void)writeToURL: (OFURL *)URL encoding: (of_string_encoding_t)encoding
+- (void)writeToURL: (OFURL *)URL encoding: (OFStringEncoding)encoding
{
[self finishInitialization];
[self writeToURL: URL encoding: encoding];
}
#ifdef OF_HAVE_BLOCKS
-- (void)enumerateLinesUsingBlock: (of_string_line_enumeration_block_t)block
+- (void)enumerateLinesUsingBlock: (OFStringLineEnumerationBlock)block
{
[self finishInitialization];
[self enumerateLinesUsingBlock: block];
}
#endif
@end
Index: src/OFCountedMapTableSet.m
==================================================================
--- src/OFCountedMapTableSet.m
+++ src/OFCountedMapTableSet.m
@@ -123,23 +123,23 @@
@try {
void *pool = objc_autoreleasePoolPush();
if (![element.name isEqual: @"OFCountedSet"] ||
- ![element.namespace isEqual: OF_SERIALIZATION_NS])
+ ![element.namespace isEqual: OFSerializationNS])
@throw [OFInvalidArgumentException exception];
for (OFXMLElement *objectElement in
[element elementsForName: @"object"
- namespace: OF_SERIALIZATION_NS]) {
+ namespace: OFSerializationNS]) {
void *pool2 = objc_autoreleasePoolPush();
OFXMLElement *object;
OFXMLAttribute *countAttribute;
unsigned long long count;
object = [objectElement elementsForNamespace:
- OF_SERIALIZATION_NS].firstObject;
+ OFSerializationNS].firstObject;
countAttribute =
[objectElement attributeForName: @"count"];
if (object == nil || countAttribute == nil)
@throw [OFInvalidFormatException exception];
@@ -167,12 +167,11 @@
{
return (size_t)(uintptr_t)[_mapTable objectForKey: object];
}
#ifdef OF_HAVE_BLOCKS
-- (void)enumerateObjectsAndCountUsingBlock:
- (of_counted_set_enumeration_block_t)block
+- (void)enumerateObjectsAndCountUsingBlock: (OFCountedSetEnumerationBlock)block
{
@try {
[_mapTable enumerateKeysAndObjectsUsingBlock:
^ (void *key, void *object, bool *stop) {
block(key, (size_t)(uintptr_t)object, stop);
Index: src/OFCountedSet.h
==================================================================
--- src/OFCountedSet.h
+++ src/OFCountedSet.h
@@ -26,11 +26,11 @@
* @param object The current object
* @param count The count of the object
* @param stop A pointer to a variable that can be set to true to stop the
* enumeration
*/
-typedef void (^of_counted_set_enumeration_block_t)(id object, size_t count,
+typedef void (^OFCountedSetEnumerationBlock)(id object, size_t count,
bool *stop);
#endif
/**
* @class OFCountedSet OFCountedSet.h ObjFW/OFCountedSet.h
@@ -57,14 +57,13 @@
/**
* @brief Executes a block for each object in the set.
*
* @param block The block to execute for each object in the set
*/
-- (void)enumerateObjectsAndCountUsingBlock:
- (of_counted_set_enumeration_block_t)block;
+- (void)enumerateObjectsAndCountUsingBlock: (OFCountedSetEnumerationBlock)block;
#endif
#if !defined(OF_HAVE_GENERICS) && !defined(DOXYGEN)
# undef ObjectType
#endif
@end
OF_ASSUME_NONNULL_END
Index: src/OFCountedSet.m
==================================================================
--- src/OFCountedSet.m
+++ src/OFCountedSet.m
@@ -181,11 +181,11 @@
{
void *pool = objc_autoreleasePoolPush();
OFXMLElement *element;
element = [OFXMLElement elementWithName: @"OFCountedSet"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
for (id object in self) {
void *pool2 = objc_autoreleasePoolPush();
OFXMLElement *objectElement;
@@ -195,11 +195,11 @@
[OFString stringWithFormat: @"%zu",
[self countForObject: object]];
objectElement = [OFXMLElement
elementWithName: @"object"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
[objectElement addAttributeWithName: @"count"
stringValue: count];
[objectElement addChild: object.XMLElementBySerializing];
[element addChild: objectElement];
@@ -212,12 +212,11 @@
return [element autorelease];
}
#ifdef OF_HAVE_BLOCKS
-- (void)enumerateObjectsAndCountUsingBlock:
- (of_counted_set_enumeration_block_t)block
+- (void)enumerateObjectsAndCountUsingBlock: (OFCountedSetEnumerationBlock)block
{
[self enumerateObjectsUsingBlock: ^ (id object, bool *stop) {
block(object, [self countForObject: object], stop);
}];
}
Index: src/OFDNSQuery.h
==================================================================
--- src/OFDNSQuery.h
+++ src/OFDNSQuery.h
@@ -26,12 +26,12 @@
* @brief A class representing a DNS query.
*/
@interface OFDNSQuery: OFObject
{
OFString *_domainName;
- of_dns_class_t _DNSClass;
- of_dns_record_type_t _recordType;
+ OFDNSClass _DNSClass;
+ OFDNSRecordType _recordType;
OF_RESERVE_IVARS(OFDNSQuery, 4)
}
/**
* @brief The domain name of the query.
@@ -39,16 +39,16 @@
@property (readonly, nonatomic) OFString *domainName;
/**
* @brief The DNS class of the query.
*/
-@property (readonly, nonatomic) of_dns_class_t DNSClass;
+@property (readonly, nonatomic) OFDNSClass DNSClass;
/**
* @brief The record type of the query.
*/
-@property (readonly, nonatomic) of_dns_record_type_t recordType;
+@property (readonly, nonatomic) OFDNSRecordType recordType;
/**
* @brief Creates a new, autoreleased OFDNSQuery.
*
* @param domainName The domain name to query
@@ -55,12 +55,12 @@
* @param DNSClass The DNS class of the query
* @param recordType The record type of the query
* @return A new, autoreleased OFDNSQuery
*/
+ (instancetype)queryWithDomainName: (OFString *)domainName
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType;
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType;
/**
* @brief Initializes an already allocated OFDNSQuery.
*
* @param domainName The domain name to query
@@ -67,13 +67,13 @@
* @param DNSClass The DNS class of the query
* @param recordType The record type of the query
* @return An initialized OFDNSQuery
*/
- (instancetype)initWithDomainName: (OFString *)domainName
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
OF_DESIGNATED_INITIALIZER;
- (instancetype)init OF_UNAVAILABLE;
@end
OF_ASSUME_NONNULL_END
Index: src/OFDNSQuery.m
==================================================================
--- src/OFDNSQuery.m
+++ src/OFDNSQuery.m
@@ -21,21 +21,21 @@
@implementation OFDNSQuery
@synthesize domainName = _domainName, DNSClass = _DNSClass;
@synthesize recordType = _recordType;
+ (instancetype)queryWithDomainName: (OFString *)domainName
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
{
return [[[self alloc] initWithDomainName: domainName
DNSClass: DNSClass
recordType: recordType] autorelease];
}
- (instancetype)initWithDomainName: (OFString *)domainName
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
{
self = [super init];
@try {
void *pool = objc_autoreleasePoolPush();
@@ -91,17 +91,17 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
+ unsigned long hash;
- OF_HASH_INIT(hash);
- OF_HASH_ADD_HASH(hash, _domainName.hash);
- OF_HASH_ADD(hash, _DNSClass);
- OF_HASH_ADD(hash, _recordType);
- OF_HASH_FINALIZE(hash);
+ OFHashInit(&hash);
+ OFHashAddHash(&hash, _domainName.hash);
+ OFHashAdd(&hash, _DNSClass);
+ OFHashAdd(&hash, _recordType);
+ OFHashFinalize(&hash);
return hash;
}
- (id)copy
@@ -110,9 +110,9 @@
}
- (OFString *)description
{
return [OFString stringWithFormat: @"<%@ %@ %@ %@>",
- self.className, _domainName, of_dns_class_to_string(_DNSClass),
- of_dns_record_type_to_string(_recordType)];
+ self.className, _domainName, OFDNSClassName(_DNSClass),
+ OFDNSRecordTypeName(_recordType)];
}
@end
Index: src/OFDNSResolver.h
==================================================================
--- src/OFDNSResolver.h
+++ src/OFDNSResolver.h
@@ -20,11 +20,11 @@
#import "OFRunLoop.h"
#import "OFString.h"
OF_ASSUME_NONNULL_BEGIN
-#define OF_DNS_RESOLVER_BUFFER_LENGTH 512
+#define OFDNSResolverBufferLength 512
@class OFArray OF_GENERIC(ObjectType);
@class OFDNSResolver;
@class OFDNSResolverContext;
@class OFDNSResolverSettings;
@@ -34,41 +34,41 @@
@class OFNumber;
@class OFTCPSocket;
@class OFUDPSocket;
/**
- * @enum of_dns_resolver_error_t OFDNSResolver.h ObjFW/OFDNSResolver.h
+ * @enum OFDNSResolverErrorCode OFDNSResolver.h ObjFW/OFDNSResolver.h
*
* @brief An enum describing why resolving a host failed.
*/
-typedef enum of_dns_resolver_error_t {
+typedef enum {
/** An unknown error */
- OF_DNS_RESOLVER_ERROR_UNKNOWN,
+ OFDNSResolverErrorCodeUnknown,
/** The query timed out */
- OF_DNS_RESOLVER_ERROR_TIMEOUT,
+ OFDNSResolverErrorCodeTimeout,
/** The query was canceled */
- OF_DNS_RESOLVER_ERROR_CANCELED,
+ OFDNSResolverErrorCodeCanceled,
/**
* No result for the specified host with the specified type and class.
*
* This is only used in situations where this is an error, e.g. when
* trying to connect to a host.
*/
- OF_DNS_RESOLVER_ERROR_NO_RESULT,
+ OFDNSResolverErrorCodeNoResult,
/** The server considered the query to be malformed */
- OF_DNS_RESOLVER_ERROR_SERVER_INVALID_FORMAT,
+ OFDNSResolverErrorCodeServerInvalidFormat,
/** The server was unable to process due to an internal error */
- OF_DNS_RESOLVER_ERROR_SERVER_FAILURE,
+ OFDNSResolverErrorCodeServerFailure,
/** The server returned an error that the domain does not exist */
- OF_DNS_RESOLVER_ERROR_SERVER_NAME_ERROR,
+ OFDNSResolverErrorCodeServerNameError,
/** The server does not have support for the requested query */
- OF_DNS_RESOLVER_ERROR_SERVER_NOT_IMPLEMENTED,
+ OFDNSResolverErrorCodeServerNotImplemented,
/** The server refused the query */
- OF_DNS_RESOLVER_ERROR_SERVER_REFUSED,
+ OFDNSResolverErrorCodeServerRefused,
/** There was no name server to query */
- OF_DNS_RESOLVER_ERROR_NO_NAME_SERVER
-} of_dns_resolver_error_t;
+ OFDNSResolverErrorCodeNoNameServer
+} OFDNSResolverErrorCode;
/**
* @protocol OFDNSResolverQueryDelegate OFDNSResolver.h ObjFW/OFDNSResolver.h
*
* @brief A delegate for performed DNS queries.
@@ -99,11 +99,11 @@
* @brief This method is called when a DNS resolver resolved a host to
* addresses.
*
* @param resolver The acting resolver
* @param host The host the resolver resolved
- * @param addresses OFData containing several of_socket_address_t
+ * @param addresses OFData containing several OFSocketAddress
* @param exception The exception that occurred during resolving, or nil on
* success
*/
- (void)resolver: (OFDNSResolver *)resolver
didResolveHost: (OFString *)host
@@ -127,11 +127,11 @@
OFDNSResolverSettings *_settings;
OFUDPSocket *_IPv4Socket;
#ifdef OF_HAVE_IPV6
OFUDPSocket *_IPv6Socket;
#endif
- char _buffer[OF_DNS_RESOLVER_BUFFER_LENGTH];
+ char _buffer[OFDNSResolverBufferLength];
OFMutableDictionary OF_GENERIC(OFNumber *, OFDNSResolverContext *)
*_queries;
OFMutableDictionary OF_GENERIC(OFTCPSocket *, OFDNSResolverContext *)
*_TCPQueries;
}
@@ -163,11 +163,11 @@
/**
* @brief The timeout, in seconds, after which the next name server should be
* tried.
*/
-@property (nonatomic) of_time_interval_t timeout;
+@property (nonatomic) OFTimeInterval timeout;
/**
* @brief The number of attempts before giving up to resolve a host.
*
* Trying all name servers once is considered a single attempt.
@@ -187,11 +187,11 @@
/**
* @brief The interval in seconds in which the config should be reloaded.
*
* Setting this to 0 disables config reloading.
*/
-@property (nonatomic) of_time_interval_t configReloadInterval;
+@property (nonatomic) OFTimeInterval configReloadInterval;
/**
* @brief Creates a new, autoreleased OFDNSResolver.
*/
+ (instancetype)resolver;
@@ -216,11 +216,11 @@
* @param query The query to perform
* @param runLoopMode The run loop mode in which to resolve
* @param delegate The delegate to use for callbacks
*/
- (void)asyncPerformQuery: (OFDNSQuery *)query
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ runLoopMode: (OFRunLoopMode)runLoopMode
delegate: (id )delegate;
/**
* @brief Asynchronously resolves the specified host to socket addresses.
*
@@ -236,11 +236,11 @@
* @param host The host to resolve
* @param addressFamily The desired socket address family
* @param delegate The delegate to use for callbacks
*/
- (void)asyncResolveAddressesForHost: (OFString *)host
- addressFamily: (of_socket_address_family_t)addressFamily
+ addressFamily: (OFSocketAddressFamily)addressFamily
delegate: (id )delegate;
/**
* @brief Asynchronously resolves the specified host to socket addresses.
*
@@ -248,26 +248,26 @@
* @param addressFamily The desired socket address family
* @param runLoopMode The run loop mode in which to resolve
* @param delegate The delegate to use for callbacks
*/
- (void)asyncResolveAddressesForHost: (OFString *)host
- addressFamily: (of_socket_address_family_t)addressFamily
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ addressFamily: (OFSocketAddressFamily)addressFamily
+ runLoopMode: (OFRunLoopMode)runLoopMode
delegate: (id )delegate;
/**
* @brief Synchronously resolves the specified host to socket addresses.
*
* @param host The host to resolve
* @param addressFamily The desired socket address family
- * @return OFData containing several of_socket_address_t
+ * @return OFData containing several OFSocketAddress
*/
- (OFData *)resolveAddressesForHost: (OFString *)host
- addressFamily: (of_socket_address_family_t)addressFamily;
+ addressFamily: (OFSocketAddressFamily)addressFamily;
/**
* @brief Closes all sockets and cancels all ongoing queries.
*/
- (void)close;
@end
OF_ASSUME_NONNULL_END
Index: src/OFDNSResolver.m
==================================================================
--- src/OFDNSResolver.m
+++ src/OFDNSResolver.m
@@ -44,22 +44,20 @@
#ifndef SOCK_DNS
# define SOCK_DNS 0
#endif
-#define BUFFER_LENGTH OF_DNS_RESOLVER_BUFFER_LENGTH
-#define MAX_DNS_RESPONSE_LENGTH 65536
+static const size_t bufferLength = OFDNSResolverBufferLength;
+static const size_t maxDNSResponseLength = 65536;
/*
* RFC 1035 doesn't specify if pointers to pointers are allowed, and if so how
* many. Since it's unspecified, we have to assume that it might happen, but we
* also want to limit it to avoid DoS. Limiting it to 16 levels of pointers and
* immediately rejecting pointers to itself seems like a fair balance.
*/
-#define MAX_ALLOWED_POINTERS 16
-
-#define CNAME_RECURSION 3
+static const uint_fast8_t maxAllowedPointers = 16;
@interface OFDNSResolver ()
- (void)of_contextTimedOut: (OFDNSResolverContext *)context;
@end
@@ -72,11 +70,11 @@
OFDNSResolverSettings *_settings;
size_t _nameServersIndex;
unsigned int _attempt;
id _delegate;
OFData *_queryData;
- of_socket_address_t _usedNameServer;
+ OFSocketAddress _usedNameServer;
OFTCPSocket *_TCPSocket;
OFMutableData *_TCPQueryData;
void *_TCPBuffer;
size_t _responseLength;
OFTimer *_cancelTimer;
@@ -166,70 +164,70 @@
return [components componentsJoinedByString: @"."];
}
static OF_KINDOF(OFDNSResourceRecord *)
-parseResourceRecord(OFString *name, of_dns_class_t DNSClass,
- of_dns_record_type_t recordType, uint32_t TTL, const unsigned char *buffer,
+parseResourceRecord(OFString *name, OFDNSClass DNSClass,
+ OFDNSRecordType recordType, uint32_t TTL, const unsigned char *buffer,
size_t length, size_t i, uint16_t dataLength)
{
- if (recordType == OF_DNS_RECORD_TYPE_A && DNSClass == OF_DNS_CLASS_IN) {
- of_socket_address_t address;
+ if (recordType == OFDNSRecordTypeA && DNSClass == OFDNSClassIN) {
+ OFSocketAddress address;
if (dataLength != 4)
@throw [OFInvalidServerReplyException exception];
memset(&address, 0, sizeof(address));
- address.family = OF_SOCKET_ADDRESS_FAMILY_IPV4;
+ address.family = OFSocketAddressFamilyIPv4;
address.length = sizeof(address.sockaddr.in);
address.sockaddr.in.sin_family = AF_INET;
memcpy(&address.sockaddr.in.sin_addr.s_addr, buffer + i, 4);
return [[[OFADNSResourceRecord alloc]
initWithName: name
address: &address
TTL: TTL] autorelease];
- } else if (recordType == OF_DNS_RECORD_TYPE_NS) {
+ } else if (recordType == OFDNSRecordTypeNS) {
size_t j = i;
OFString *authoritativeHost = parseName(buffer, length, &j,
- MAX_ALLOWED_POINTERS);
+ maxAllowedPointers);
if (j != i + dataLength)
@throw [OFInvalidServerReplyException exception];
return [[[OFNSDNSResourceRecord alloc]
initWithName: name
DNSClass: DNSClass
authoritativeHost: authoritativeHost
TTL: TTL] autorelease];
- } else if (recordType == OF_DNS_RECORD_TYPE_CNAME) {
+ } else if (recordType == OFDNSRecordTypeCNAME) {
size_t j = i;
OFString *alias = parseName(buffer, length, &j,
- MAX_ALLOWED_POINTERS);
+ maxAllowedPointers);
if (j != i + dataLength)
@throw [OFInvalidServerReplyException exception];
return [[[OFCNAMEDNSResourceRecord alloc]
initWithName: name
DNSClass: DNSClass
alias: alias
TTL: TTL] autorelease];
- } else if (recordType == OF_DNS_RECORD_TYPE_SOA) {
+ } else if (recordType == OFDNSRecordTypeSOA) {
size_t j = i;
OFString *primaryNameServer = parseName(buffer, length, &j,
- MAX_ALLOWED_POINTERS);
+ maxAllowedPointers);
OFString *responsiblePerson;
uint32_t serialNumber, refreshInterval, retryInterval;
uint32_t expirationInterval, minTTL;
if (j > i + dataLength)
@throw [OFInvalidServerReplyException exception];
responsiblePerson = parseName(buffer, length, &j,
- MAX_ALLOWED_POINTERS);
+ maxAllowedPointers);
if (dataLength - (j - i) != 20)
@throw [OFInvalidServerReplyException exception];
serialNumber = (buffer[j] << 24) | (buffer[j + 1] << 16) |
@@ -254,24 +252,24 @@
refreshInterval: refreshInterval
retryInterval: retryInterval
expirationInterval: expirationInterval
minTTL: minTTL
TTL: TTL] autorelease];
- } else if (recordType == OF_DNS_RECORD_TYPE_PTR) {
+ } else if (recordType == OFDNSRecordTypePTR) {
size_t j = i;
OFString *domainName = parseName(buffer, length, &j,
- MAX_ALLOWED_POINTERS);
+ maxAllowedPointers);
if (j != i + dataLength)
@throw [OFInvalidServerReplyException exception];
return [[[OFPTRDNSResourceRecord alloc]
initWithName: name
DNSClass: DNSClass
domainName: domainName
TTL: TTL] autorelease];
- } else if (recordType == OF_DNS_RECORD_TYPE_HINFO) {
+ } else if (recordType == OFDNSRecordTypeHINFO) {
size_t j = i;
OFString *CPU = parseString(buffer, length, &j);
OFString *OS;
if (j > i + dataLength)
@@ -286,11 +284,11 @@
initWithName: name
DNSClass: DNSClass
CPU: CPU
OS: OS
TTL: TTL] autorelease];
- } else if (recordType == OF_DNS_RECORD_TYPE_MX) {
+ } else if (recordType == OFDNSRecordTypeMX) {
uint16_t preference;
size_t j;
OFString *mailExchange;
if (dataLength < 2)
@@ -298,11 +296,11 @@
preference = (buffer[i] << 8) | buffer[i + 1];
j = i + 2;
mailExchange = parseName(buffer, length, &j,
- MAX_ALLOWED_POINTERS);
+ maxAllowedPointers);
if (j != i + dataLength)
@throw [OFInvalidServerReplyException exception];
return [[[OFMXDNSResourceRecord alloc]
@@ -309,11 +307,11 @@
initWithName: name
DNSClass: DNSClass
preference: preference
mailExchange: mailExchange
TTL: TTL] autorelease];
- } else if (recordType == OF_DNS_RECORD_TYPE_TXT) {
+ } else if (recordType == OFDNSRecordTypeTXT) {
OFMutableArray *textStrings = [OFMutableArray array];
while (dataLength > 0) {
uint_fast8_t stringLength = buffer[i++];
dataLength--;
@@ -335,21 +333,21 @@
return [[[OFTXTDNSResourceRecord alloc]
initWithName: name
DNSClass: DNSClass
textStrings: textStrings
TTL: TTL] autorelease];
- } else if (recordType == OF_DNS_RECORD_TYPE_RP) {
+ } else if (recordType == OFDNSRecordTypeRP) {
size_t j = i;
OFString *mailbox = parseName(buffer, length, &j,
- MAX_ALLOWED_POINTERS);
+ maxAllowedPointers);
OFString *TXTDomainName;
if (j > i + dataLength)
@throw [OFInvalidServerReplyException exception];
TXTDomainName = parseName(buffer, length, &j,
- MAX_ALLOWED_POINTERS);
+ maxAllowedPointers);
if (j != i + dataLength)
@throw [OFInvalidServerReplyException exception];
return [[[OFRPDNSResourceRecord alloc]
@@ -356,19 +354,19 @@
initWithName: name
DNSClass: DNSClass
mailbox: mailbox
TXTDomainName: TXTDomainName
TTL: TTL] autorelease];
- } else if (recordType == OF_DNS_RECORD_TYPE_AAAA &&
- DNSClass == OF_DNS_CLASS_IN) {
- of_socket_address_t address;
+ } else if (recordType == OFDNSRecordTypeAAAA &&
+ DNSClass == OFDNSClassIN) {
+ OFSocketAddress address;
if (dataLength != 16)
@throw [OFInvalidServerReplyException exception];
memset(&address, 0, sizeof(address));
- address.family = OF_SOCKET_ADDRESS_FAMILY_IPV6;
+ address.family = OFSocketAddressFamilyIPv6;
address.length = sizeof(address.sockaddr.in6);
#ifdef AF_INET6
address.sockaddr.in6.sin6_family = AF_INET6;
#else
@@ -378,12 +376,12 @@
return [[[OFAAAADNSResourceRecord alloc]
initWithName: name
address: &address
TTL: TTL] autorelease];
- } else if (recordType == OF_DNS_RECORD_TYPE_SRV &&
- DNSClass == OF_DNS_CLASS_IN) {
+ } else if (recordType == OFDNSRecordTypeSRV &&
+ DNSClass == OFDNSClassIN) {
uint16_t priority, weight, port;
size_t j;
OFString *target;
if (dataLength < 6)
@@ -392,11 +390,11 @@
priority = (buffer[i] << 8) | buffer[i + 1];
weight = (buffer[i + 2] << 8) | buffer[i + 3];
port = (buffer[i + 4] << 8) | buffer[i + 5];
j = i + 6;
- target = parseName(buffer, length, &j, MAX_ALLOWED_POINTERS);
+ target = parseName(buffer, length, &j, maxAllowedPointers);
if (j != i + dataLength)
@throw [OFInvalidServerReplyException exception];
return [[[OFSRVDNSResourceRecord alloc]
@@ -422,13 +420,13 @@
OFEnumerator OF_GENERIC(OFMutableArray *) *objectEnumerator;
OFMutableArray *array;
for (uint_fast16_t j = 0; j < count; j++) {
OFString *name = parseName(buffer, length, i,
- MAX_ALLOWED_POINTERS);
- of_dns_class_t DNSClass;
- of_dns_record_type_t recordType;
+ maxAllowedPointers);
+ OFDNSClass DNSClass;
+ OFDNSRecordType recordType;
uint32_t TTL;
uint16_t dataLength;
OFDNSResourceRecord *record;
if (*i + 10 > length)
@@ -488,17 +486,17 @@
queryData = [OFMutableData dataWithCapacity: 512];
/* Header */
- tmp = OF_BSWAP16_IF_LE(_ID.unsignedShortValue);
+ tmp = OFToBigEndian16(_ID.unsignedShortValue);
[queryData addItems: &tmp count: 2];
/* RD */
- tmp = OF_BSWAP16_IF_LE(1u << 8);
+ tmp = OFToBigEndian16(1u << 8);
[queryData addItems: &tmp count: 2];
/* QDCOUNT */
- tmp = OF_BSWAP16_IF_LE(1);
+ tmp = OFToBigEndian16(1);
[queryData addItems: &tmp count: 2];
/* ANCOUNT, NSCOUNT and ARCOUNT */
[queryData increaseCountBy: 6];
/* Question */
@@ -517,14 +515,14 @@
[queryData addItems: component.UTF8String
count: length];
}
/* QTYPE */
- tmp = OF_BSWAP16_IF_LE(_query.recordType);
+ tmp = OFToBigEndian16(_query.recordType);
[queryData addItems: &tmp count: 2];
/* QCLASS */
- tmp = OF_BSWAP16_IF_LE(_query.DNSClass);
+ tmp = OFToBigEndian16(_query.DNSClass);
[queryData addItems: &tmp count: 2];
[queryData makeImmutable];
_queryData = [queryData copy];
@@ -544,11 +542,11 @@
[_settings release];
[_delegate release];
[_queryData release];
[_TCPSocket release];
[_TCPQueryData release];
- free(_TCPBuffer);
+ OFFreeMemory(_TCPBuffer);
[_cancelTimer release];
[super dealloc];
}
@end
@@ -558,11 +556,11 @@
+ (void)initialize
{
if (self != [OFDNSResolver class])
return;
- if (!of_socket_init())
+ if (!OFSocketInit())
@throw [OFInitializationFailedException
exceptionWithClass: self];
}
#endif
@@ -645,16 +643,16 @@
OFArray *old = _settings->_searchDomains;
_settings->_searchDomains = [searchDomains copy];
[old release];
}
-- (of_time_interval_t)timeout
+- (OFTimeInterval)timeout
{
return _settings->_timeout;
}
-- (void)setTimeout: (of_time_interval_t)timeout
+- (void)setTimeout: (OFTimeInterval)timeout
{
_settings->_timeout = timeout;
}
- (unsigned int)maxAttempts
@@ -687,22 +685,22 @@
- (void)setUsesTCP: (bool)usesTCP
{
_settings->_usesTCP = usesTCP;
}
-- (of_time_interval_t)configReloadInterval
+- (OFTimeInterval)configReloadInterval
{
return _settings->_configReloadInterval;
}
-- (void)setConfigReloadInterval: (of_time_interval_t)configReloadInterval
+- (void)setConfigReloadInterval: (OFTimeInterval)configReloadInterval
{
_settings->_configReloadInterval = configReloadInterval;
}
- (void)of_sendQueryForContext: (OFDNSResolverContext *)context
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ runLoopMode: (OFRunLoopMode)runLoopMode
{
OFUDPSocket *sock;
OFString *nameServer;
[_queries setObject: context forKey: context->_ID];
@@ -723,11 +721,11 @@
nameServer = [context->_settings->_nameServers
objectAtIndex: context->_nameServersIndex];
if (context->_settings->_usesTCP) {
- OF_ENSURE(context->_TCPSocket == nil);
+ OFEnsure(context->_TCPSocket == nil);
context->_TCPSocket = [[OFTCPSocket alloc] init];
[_TCPQueries setObject: context forKey: context->_TCPSocket];
context->_TCPSocket.delegate = self;
@@ -735,18 +733,18 @@
port: 53
runLoopMode: runLoopMode];
return;
}
- context->_usedNameServer = of_socket_address_parse_ip(nameServer, 53);
+ context->_usedNameServer = OFSocketAddressParseIP(nameServer, 53);
switch (context->_usedNameServer.family) {
#ifdef OF_HAVE_IPV6
- case OF_SOCKET_ADDRESS_FAMILY_IPV6:
+ case OFSocketAddressFamilyIPv6:
if (_IPv6Socket == nil) {
- of_socket_address_t address =
- of_socket_address_parse_ip(@"::", 0);
+ OFSocketAddress address =
+ OFSocketAddressParseIPv6(@"::", 0);
_IPv6Socket = [[OFUDPSocket alloc] init];
[_IPv6Socket of_bindToAddress: &address
extraType: SOCK_DNS];
_IPv6Socket.canBlock = false;
@@ -754,14 +752,14 @@
}
sock = _IPv6Socket;
break;
#endif
- case OF_SOCKET_ADDRESS_FAMILY_IPV4:
+ case OFSocketAddressFamilyIPv4:
if (_IPv4Socket == nil) {
- of_socket_address_t address =
- of_socket_address_parse_ip(@"0.0.0.0", 0);
+ OFSocketAddress address =
+ OFSocketAddressParseIPv4(@"0.0.0.0", 0);
_IPv4Socket = [[OFUDPSocket alloc] init];
[_IPv4Socket of_bindToAddress: &address
extraType: SOCK_DNS];
_IPv4Socket.canBlock = false;
@@ -776,42 +774,42 @@
[sock asyncSendData: context->_queryData
receiver: &context->_usedNameServer
runLoopMode: runLoopMode];
[sock asyncReceiveIntoBuffer: _buffer
- length: BUFFER_LENGTH
+ length: bufferLength
runLoopMode: runLoopMode];
}
- (void)asyncPerformQuery: (OFDNSQuery *)query
delegate: (id )delegate
{
[self asyncPerformQuery: query
- runLoopMode: of_run_loop_mode_default
+ runLoopMode: OFDefaultRunLoopMode
delegate: delegate];
}
- (void)asyncPerformQuery: (OFDNSQuery *)query
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ runLoopMode: (OFRunLoopMode)runLoopMode
delegate: (id )delegate
{
void *pool = objc_autoreleasePoolPush();
OFNumber *ID;
OFDNSResolverContext *context;
/* Random, unused ID */
do {
- ID = [OFNumber numberWithUnsignedShort: of_random16()];
+ ID = [OFNumber numberWithUnsignedShort: OFRandom16()];
} while ([_queries objectForKey: ID] != nil);
if (query.domainName.UTF8StringLength > 253)
@throw [OFOutOfRangeException exception];
if (_settings->_nameServers.count == 0) {
id exception = [OFDNSQueryFailedException
exceptionWithQuery: query
- error: OF_DNS_RESOLVER_ERROR_NO_NAME_SERVER];
+ errorCode: OFDNSResolverErrorCodeNoNameServer];
[delegate resolver: self
didPerformQuery: query
response: nil
exception: exception];
return;
@@ -827,11 +825,11 @@
objc_autoreleasePoolPop(pool);
}
- (void)of_contextTimedOut: (OFDNSResolverContext *)context
{
- of_run_loop_mode_t runLoopMode = [OFRunLoop currentRunLoop].currentMode;
+ OFRunLoopMode runLoopMode = [OFRunLoop currentRunLoop].currentMode;
OFDNSQueryFailedException *exception;
if (context->_TCPSocket != nil) {
context->_TCPSocket.delegate = nil;
[context->_TCPSocket cancelAsyncRequests];
@@ -861,29 +859,29 @@
/*
* Cancel any pending queries, to avoid a send being still pending and
* trying to access the query once it no longer exists.
*/
[_IPv4Socket cancelAsyncRequests];
- [_IPv4Socket asyncReceiveIntoBuffer: _buffer length: BUFFER_LENGTH];
+ [_IPv4Socket asyncReceiveIntoBuffer: _buffer length: bufferLength];
#ifdef OF_HAVE_IPV6
[_IPv6Socket cancelAsyncRequests];
- [_IPv6Socket asyncReceiveIntoBuffer: _buffer length: BUFFER_LENGTH];
+ [_IPv6Socket asyncReceiveIntoBuffer: _buffer length: bufferLength];
#endif
exception = [OFDNSQueryFailedException
exceptionWithQuery: context->_query
- error: OF_DNS_RESOLVER_ERROR_TIMEOUT];
+ errorCode: OFDNSResolverErrorCodeTimeout];
[context->_delegate resolver: self
didPerformQuery: context->_query
response: nil
exception: exception];
}
- (bool)of_handleResponseBuffer: (unsigned char *)buffer
length: (size_t)length
- sender: (const of_socket_address_t *)sender
+ sender: (const OFSocketAddress *)sender
{
OFDictionary *answerRecords = nil, *authorityRecords = nil;
OFDictionary *additionalRecords = nil;
OFDNSResponse *response = nil;
id exception = nil;
@@ -901,20 +899,20 @@
return true;
if (context->_TCPSocket != nil) {
if ([_TCPQueries objectForKey: context->_TCPSocket] != context)
return true;
- } else if (!of_socket_address_equal(sender, &context->_usedNameServer))
+ } else if (!OFSocketAddressEqual(sender, &context->_usedNameServer))
return true;
[context->_cancelTimer invalidate];
[context->_cancelTimer release];
context->_cancelTimer = nil;
[_queries removeObjectForKey: ID];
@try {
- of_dns_resolver_error_t error = 0;
+ OFDNSResolverErrorCode errorCode = 0;
bool tryNextNameServer = false;
const unsigned char *queryDataBuffer;
size_t i;
uint16_t numQuestions, numAnswers, numAuthorityRecords;
uint16_t numAdditionalRecords;
@@ -936,11 +934,11 @@
if ((buffer[2] & 0x78) != (queryDataBuffer[2] & 0x78))
@throw [OFInvalidServerReplyException exception];
/* TC */
if (buffer[2] & 0x02) {
- of_run_loop_mode_t runLoopMode;
+ OFRunLoopMode runLoopMode;
if (context->_settings->_usesTCP)
@throw [OFTruncatedDataException exception];
context->_settings->_usesTCP = true;
@@ -953,37 +951,37 @@
/* RCODE */
switch (buffer[3] & 0x0F) {
case 0:
break;
case 1:
- error = OF_DNS_RESOLVER_ERROR_SERVER_INVALID_FORMAT;
+ errorCode = OFDNSResolverErrorCodeServerInvalidFormat;
break;
case 2:
- error = OF_DNS_RESOLVER_ERROR_SERVER_FAILURE;
+ errorCode = OFDNSResolverErrorCodeServerFailure;
tryNextNameServer = true;
break;
case 3:
- error = OF_DNS_RESOLVER_ERROR_SERVER_NAME_ERROR;
+ errorCode = OFDNSResolverErrorCodeServerNameError;
break;
case 4:
- error = OF_DNS_RESOLVER_ERROR_SERVER_NOT_IMPLEMENTED;
+ errorCode = OFDNSResolverErrorCodeServerNotImplemented;
tryNextNameServer = true;
break;
case 5:
- error = OF_DNS_RESOLVER_ERROR_SERVER_REFUSED;
+ errorCode = OFDNSResolverErrorCodeServerRefused;
tryNextNameServer = true;
break;
default:
- error = OF_DNS_RESOLVER_ERROR_UNKNOWN;
+ errorCode = OFDNSResolverErrorCodeUnknown;
tryNextNameServer = true;
break;
}
if (tryNextNameServer) {
if (context->_nameServersIndex + 1 <
context->_settings->_nameServers.count) {
- of_run_loop_mode_t runLoopMode =
+ OFRunLoopMode runLoopMode =
[OFRunLoop currentRunLoop].currentMode;
context->_nameServersIndex++;
[self of_sendQueryForContext: context
@@ -993,11 +991,11 @@
}
if (buffer[3] & 0x0F)
@throw [OFDNSQueryFailedException
exceptionWithQuery: context->_query
- error: error];
+ errorCode: errorCode];
numQuestions = (buffer[4] << 8) | buffer[5];
numAnswers = (buffer[6] << 8) | buffer[7];
numAuthorityRecords = (buffer[8] << 8) | buffer[9];
numAdditionalRecords = (buffer[10] << 8) | buffer[11];
@@ -1009,11 +1007,11 @@
* query.
*
* TODO: Compare to our query, just in case?
*/
for (uint_fast16_t j = 0; j < numQuestions; j++) {
- parseName(buffer, length, &i, MAX_ALLOWED_POINTERS);
+ parseName(buffer, length, &i, maxAllowedPointers);
i += 4;
}
answerRecords = parseSection(buffer, length, &i, numAnswers);
authorityRecords = parseSection(buffer, length, &i,
@@ -1041,11 +1039,11 @@
}
- (bool)socket: (OFDatagramSocket *)sock
didReceiveIntoBuffer: (void *)buffer
length: (size_t)length
- sender: (const of_socket_address_t *)sender
+ sender: (const OFSocketAddress *)sender
exception: (id)exception
{
if (exception != nil)
return true;
@@ -1059,11 +1057,11 @@
port: (uint16_t)port
exception: (id)exception
{
OFDNSResolverContext *context = [_TCPQueries objectForKey: sock];
- OF_ENSURE(context != nil);
+ OFEnsure(context != nil);
if (exception != nil) {
/*
* TODO: Handle error immediately instead of waiting for the
* timer to try the next nameserver or to retry.
@@ -1083,11 +1081,11 @@
@throw [OFOutOfRangeException exception];
context->_TCPQueryData = [[OFMutableData alloc]
initWithCapacity: queryDataCount + 2];
- tmp = OF_BSWAP16_IF_LE(queryDataCount);
+ tmp = OFToBigEndian16(queryDataCount);
[context->_TCPQueryData addItems: &tmp count: sizeof(tmp)];
[context->_TCPQueryData addItems: context->_queryData.items
count: queryDataCount];
}
@@ -1100,11 +1098,11 @@
exception: (id)exception
{
OFTCPSocket *sock = (OFTCPSocket *)stream;
OFDNSResolverContext *context = [_TCPQueries objectForKey: sock];
- OF_ENSURE(context != nil);
+ OFEnsure(context != nil);
if (exception != nil) {
/*
* TODO: Handle error immediately instead of waiting for the
* timer to try the next nameserver or to retry.
@@ -1115,11 +1113,11 @@
context->_responseLength = 0;
return nil;
}
if (context->_TCPBuffer == nil)
- context->_TCPBuffer = of_alloc(MAX_DNS_RESPONSE_LENGTH, 1);
+ context->_TCPBuffer = OFAllocMemory(maxDNSResponseLength, 1);
[sock asyncReadIntoBuffer: context->_TCPBuffer exactLength: 2];
return nil;
}
@@ -1129,11 +1127,11 @@
exception: (id)exception
{
OFTCPSocket *sock = (OFTCPSocket *)stream;
OFDNSResolverContext *context = [_TCPQueries objectForKey: sock];
- OF_ENSURE(context != nil);
+ OFEnsure(context != nil);
if (exception != nil) {
/*
* TODO: Handle error immediately instead of waiting for the
* timer to try the next nameserver or to retry.
@@ -1142,15 +1140,15 @@
}
if (context->_responseLength == 0) {
unsigned char *ucBuffer = buffer;
- OF_ENSURE(length == 2);
+ OFEnsure(length == 2);
context->_responseLength = (ucBuffer[0] << 8) | ucBuffer[1];
- if (context->_responseLength > MAX_DNS_RESPONSE_LENGTH)
+ if (context->_responseLength > maxDNSResponseLength)
@throw [OFOutOfRangeException exception];
if (context->_responseLength == 0)
goto done;
@@ -1179,28 +1177,28 @@
- (void)asyncResolveAddressesForHost: (OFString *)host
delegate: (id )delegate
{
[self asyncResolveAddressesForHost: host
- addressFamily: OF_SOCKET_ADDRESS_FAMILY_ANY
- runLoopMode: of_run_loop_mode_default
+ addressFamily: OFSocketAddressFamilyAny
+ runLoopMode: OFDefaultRunLoopMode
delegate: delegate];
}
- (void)asyncResolveAddressesForHost: (OFString *)host
- addressFamily: (of_socket_address_family_t)addressFamily
+ addressFamily: (OFSocketAddressFamily)addressFamily
delegate: (id )delegate
{
[self asyncResolveAddressesForHost: host
addressFamily: addressFamily
- runLoopMode: of_run_loop_mode_default
+ runLoopMode: OFDefaultRunLoopMode
delegate: delegate];
}
- (void)asyncResolveAddressesForHost: (OFString *)host
- addressFamily: (of_socket_address_family_t)addressFamily
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ addressFamily: (OFSocketAddressFamily)addressFamily
+ runLoopMode: (OFRunLoopMode)runLoopMode
delegate: (id )delegate
{
void *pool = objc_autoreleasePoolPush();
OFHostAddressResolver *resolver = [[[OFHostAddressResolver alloc]
initWithHost: host
@@ -1214,11 +1212,11 @@
objc_autoreleasePoolPop(pool);
}
- (OFData *)resolveAddressesForHost: (OFString *)host
- addressFamily: (of_socket_address_family_t)addressFamily
+ addressFamily: (OFSocketAddressFamily)addressFamily
{
void *pool = objc_autoreleasePoolPush();
OFHostAddressResolver *resolver = [[[OFHostAddressResolver alloc]
initWithHost: host
addressFamily: addressFamily
@@ -1255,11 +1253,11 @@
while ((context = [enumerator nextObject]) != nil) {
OFDNSQueryFailedException *exception;
exception = [OFDNSQueryFailedException
exceptionWithQuery: context->_query
- error: OF_DNS_RESOLVER_ERROR_CANCELED];
+ errorCode: OFDNSResolverErrorCodeCanceled];
[context->_delegate resolver: self
didPerformQuery: context->_query
response: nil
exception: exception];
Index: src/OFDNSResolverSettings.h
==================================================================
--- src/OFDNSResolverSettings.h
+++ src/OFDNSResolverSettings.h
@@ -27,17 +27,17 @@
OFDictionary OF_GENERIC(OFString *, OFArray OF_GENERIC(OFString *) *)
*_staticHosts;
OFArray OF_GENERIC(OFString *) *_nameServers;
OFString *_Nullable _localDomain;
OFArray OF_GENERIC(OFString *) *_searchDomains;
- of_time_interval_t _timeout;
+ OFTimeInterval _timeout;
unsigned int _maxAttempts, _minNumberOfDotsInAbsoluteName;
bool _usesTCP;
- of_time_interval_t _configReloadInterval;
+ OFTimeInterval _configReloadInterval;
@protected
OFDate *_lastConfigReload;
}
- (void)reload;
@end
OF_ASSUME_NONNULL_END
Index: src/OFDNSResolverSettings.m
==================================================================
--- src/OFDNSResolverSettings.m
+++ src/OFDNSResolverSettings.m
@@ -22,10 +22,11 @@
#import "OFCharacterSet.h"
#import "OFDate.h"
#import "OFDictionary.h"
#import "OFFile.h"
#import "OFLocale.h"
+#import "OFSocket+Private.h"
#import "OFString.h"
#ifdef OF_WINDOWS
# import "OFWindowsRegistryKey.h"
#endif
@@ -51,12 +52,10 @@
# include
# include
# include
#endif
-#import "socket_helpers.h"
-
#if defined(OF_HAIKU)
# define HOSTS_PATH @"/system/settings/network/hosts"
# define RESOLV_CONF_PATH @"/system/settings/network/resolv.conf"
#elif defined(OF_AMIGAOS4)
# define HOSTS_PATH @"DEVS:Internet/hosts"
@@ -74,11 +73,11 @@
{
if (hostname == nil)
return nil;
@try {
- of_socket_address_parse_ip(hostname, 0);
+ OFSocketAddressParseIP(hostname, 0);
/*
* If we are still here, the host name is a valid IP address.
* We can't use that as local domain.
*/
@@ -85,11 +84,11 @@
return nil;
} @catch (OFInvalidFormatException *e) {
/* Not an IP address -> we can use it if it contains a dot. */
size_t pos = [hostname rangeOfString: @"."].location;
- if (pos == OF_NOT_FOUND)
+ if (pos == OFNotFound)
return nil;
return [hostname substringFromIndex: pos + 1];
}
}
@@ -173,11 +172,11 @@
parseNetStackArray(OFString *string)
{
if (![string hasPrefix: @"["] || ![string hasSuffix: @"]"])
return nil;
- string = [string substringWithRange: of_range(1, string.length - 2)];
+ string = [string substringWithRange: OFRangeMake(1, string.length - 2)];
return [string componentsSeparatedByString: @"|"];
}
#endif
@@ -265,23 +264,23 @@
OFArray *components, *hosts;
size_t pos;
OFString *address;
pos = [line rangeOfString: @"#"].location;
- if (pos != OF_NOT_FOUND)
+ if (pos != OFNotFound)
line = [line substringToIndex: pos];
components = [line
componentsSeparatedByCharactersInSet: whitespaceCharacterSet
- options: OF_STRING_SKIP_EMPTY];
+ options: OFStringSkipEmptyComponents];
if (components.count < 2)
continue;
address = components.firstObject;
hosts = [components objectsInRange:
- of_range(1, components.count - 1)];
+ OFRangeMake(1, components.count - 1)];
for (OFString *host in hosts) {
OFMutableArray *addresses =
[staticHosts objectForKey: host];
@@ -366,25 +365,25 @@
size_t pos;
OFArray *components, *arguments;
OFString *option;
pos = [line indexOfCharacterFromSet: commentCharacters];
- if (pos != OF_NOT_FOUND)
+ if (pos != OFNotFound)
line = [line substringToIndex: pos];
components = [line
componentsSeparatedByCharactersInSet: whitespaceCharacterSet
- options: OF_STRING_SKIP_EMPTY];
+ options: OFStringSkipEmptyComponents];
if (components.count < 2) {
objc_autoreleasePoolPop(pool2);
continue;
}
option = components.firstObject;
arguments = [components objectsInRange:
- of_range(1, components.count - 1)];
+ OFRangeMake(1, components.count - 1)];
if ([option isEqual: @"nameserver"]) {
if (arguments.count != 1) {
objc_autoreleasePoolPop(pool2);
continue;
@@ -420,11 +419,11 @@
#endif
#ifdef OF_WINDOWS
- (void)obtainWindowsSystemConfig
{
- of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
OFMutableArray *nameServers;
/*
* We need more space than FIXED_INFO in case we have more than one
* name server, but we also want it to be properly aligned, meaning we
* can't just get a buffer of bytes. Thus, we just get space for 8.
@@ -479,11 +478,11 @@
if (components.count < 2)
continue;
address = components.firstObject;
hosts = [components objectsInRange:
- of_range(1, components.count - 1)];
+ OFRangeMake(1, components.count - 1)];
for (OFString *host in hosts) {
OFMutableArray *addresses =
[staticHosts objectForKey: host];
@@ -507,11 +506,11 @@
#ifdef OF_AMIGAOS4
- (void)obtainAmigaOS4SystemConfig
{
OFMutableArray *nameServers = [OFMutableArray array];
- of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
struct List *nameServerList = ObtainDomainNameServerList();
char buffer[MAXHOSTNAMELEN];
if (nameServerList == NULL)
@throw [OFOutOfMemoryException exception];
@@ -572,11 +571,11 @@
*/
if (optLen < sizeof(buffer.entries))
return;
for (uint_fast8_t i = 0; i < 2; i++) {
- uint32_t ip = OF_BSWAP32_IF_LE(buffer.entries[i].ip.s_addr);
+ uint32_t ip = OFFromBigEndian32(buffer.entries[i].ip.s_addr);
if (ip == 0)
continue;
[nameServers addObject: [OFString stringWithFormat:
Index: src/OFDNSResourceRecord.h
==================================================================
--- src/OFDNSResourceRecord.h
+++ src/OFDNSResourceRecord.h
@@ -12,14 +12,13 @@
* LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
* file.
*/
#import "OFObject.h"
+#import "OFSocket.h"
#import "OFString.h"
-#import "socket.h"
-
OF_ASSUME_NONNULL_BEGIN
/** @file */
@class OFArray OF_GENERIC(ObjectType);
@@ -28,55 +27,55 @@
/**
* @brief The DNS class.
*/
typedef enum {
/** IN */
- OF_DNS_CLASS_IN = 1,
+ OFDNSClassIN = 1,
/** Any class. Only for queries. */
- OF_DNS_CLASS_ANY = 255,
-} of_dns_class_t;
+ OFDNSClassAny = 255,
+} OFDNSClass;
/**
* @brief The type of a DNS resource record.
*/
typedef enum {
/** A */
- OF_DNS_RECORD_TYPE_A = 1,
+ OFDNSRecordTypeA = 1,
/** NS */
- OF_DNS_RECORD_TYPE_NS = 2,
+ OFDNSRecordTypeNS = 2,
/** CNAME */
- OF_DNS_RECORD_TYPE_CNAME = 5,
+ OFDNSRecordTypeCNAME = 5,
/** SOA */
- OF_DNS_RECORD_TYPE_SOA = 6,
+ OFDNSRecordTypeSOA = 6,
/** PTR */
- OF_DNS_RECORD_TYPE_PTR = 12,
+ OFDNSRecordTypePTR = 12,
/** HINFO */
- OF_DNS_RECORD_TYPE_HINFO = 13,
+ OFDNSRecordTypeHINFO = 13,
/** MX */
- OF_DNS_RECORD_TYPE_MX = 15,
+ OFDNSRecordTypeMX = 15,
/** TXT */
- OF_DNS_RECORD_TYPE_TXT = 16,
+ OFDNSRecordTypeTXT = 16,
/** RP */
- OF_DNS_RECORD_TYPE_RP = 17,
+ OFDNSRecordTypeRP = 17,
/** AAAA */
- OF_DNS_RECORD_TYPE_AAAA = 28,
+ OFDNSRecordTypeAAAA = 28,
/** SRV */
- OF_DNS_RECORD_TYPE_SRV = 33,
+ OFDNSRecordTypeSRV = 33,
/** All types. Only for queries. */
- OF_DNS_RECORD_TYPE_ALL = 255,
-} of_dns_record_type_t;
+ OFDNSRecordTypeAll = 255,
+} OFDNSRecordType;
/**
* @class OFDNSResourceRecord OFDNSResourceRecord.h ObjFW/OFDNSResourceRecord.h
*
* @brief A class representing a DNS resource record.
*/
@interface OFDNSResourceRecord: OFObject
{
OFString *_name;
- of_dns_class_t _DNSClass;
- of_dns_record_type_t _recordType;
+ OFDNSClass _DNSClass;
+ OFDNSRecordType _recordType;
uint32_t _TTL;
OF_RESERVE_IVARS(OFDNSResourceRecord, 4)
}
/**
@@ -85,16 +84,16 @@
@property (readonly, nonatomic) OFString *name;
/**
* @brief The DNS class.
*/
-@property (readonly, nonatomic) of_dns_class_t DNSClass;
+@property (readonly, nonatomic) OFDNSClass DNSClass;
/**
* @brief The resource record type code.
*/
-@property (readonly, nonatomic) of_dns_record_type_t recordType;
+@property (readonly, nonatomic) OFDNSRecordType recordType;
/**
* @brief The number of seconds after which the resource record should be
* discarded from the cache.
*/
@@ -109,12 +108,12 @@
* @param recordType The type code for the resource record
* @param TTL The time to live for the resource record
* @return An initialized OFDNSResourceRecord
*/
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL OF_DESIGNATED_INITIALIZER;
@end
/**
* @class OFADNSResourceRecord OFDNSResourceRecord.h ObjFW/OFDNSResourceRecord.h
@@ -122,21 +121,21 @@
* @brief A class representing an A DNS resource record.
*/
OF_SUBCLASSING_RESTRICTED
@interface OFADNSResourceRecord: OFDNSResourceRecord
{
- of_socket_address_t _address;
+ OFSocketAddress _address;
}
/**
* @brief The IPv4 address of the resource record.
*/
-@property (readonly, nonatomic) const of_socket_address_t *address;
+@property (readonly, nonatomic) const OFSocketAddress *address;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFADNSResourceRecord with the
* specified name, class, address and time to live.
@@ -145,11 +144,11 @@
* @param address The address for the resource record
* @param TTL The time to live for the resource record
* @return An initialized OFADNSResourceRecord
*/
- (instancetype)initWithName: (OFString *)name
- address: (const of_socket_address_t *)address
+ address: (const OFSocketAddress *)address
TTL: (uint32_t)TTL OF_DESIGNATED_INITIALIZER;
@end
/**
* @class OFAAAADNSResourceRecord \
@@ -158,21 +157,21 @@
* @brief A class represenging a DNS resource record.
*/
OF_SUBCLASSING_RESTRICTED
@interface OFAAAADNSResourceRecord: OFDNSResourceRecord
{
- of_socket_address_t _address;
+ OFSocketAddress _address;
}
/**
* @brief The IPv6 address of the resource record.
*/
-@property (readonly, nonatomic) const of_socket_address_t *address;
+@property (readonly, nonatomic) const OFSocketAddress *address;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFAAAADNSResourceRecord with the
* specified name, class, address and time to live.
@@ -181,11 +180,11 @@
* @param address The address for the resource record
* @param TTL The time to live for the resource record
* @return An initialized OFAAAADNSResourceRecord
*/
- (instancetype)initWithName: (OFString *)name
- address: (const of_socket_address_t *)address
+ address: (const OFSocketAddress *)address
TTL: (uint32_t)TTL OF_DESIGNATED_INITIALIZER;
@end
/**
* @class OFCNAMEDNSResourceRecord \
@@ -203,12 +202,12 @@
* @brief The alias of the resource record.
*/
@property (readonly, nonatomic) OFString *alias;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFCNAMEDNSResourceRecord with the
* specified name, class, alias and time to live.
@@ -218,11 +217,11 @@
* @param alias The alias for the resource record
* @param TTL The time to live for the resource record
* @return An initialized OFCNAMEDNSResourceRecord
*/
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
alias: (OFString *)alias
TTL: (uint32_t)TTL OF_DESIGNATED_INITIALIZER;
@end
/**
@@ -246,12 +245,12 @@
* @brief The OS of the host info of the resource record.
*/
@property (readonly, nonatomic) OFString *OS;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFHINFODNSResourceRecord with the
* specified name, class, domain name and time to live.
@@ -262,11 +261,11 @@
* @param OS The OS of the host info for the resource record
* @param TTL The time to live for the resource record
* @return An initialized OFHINFODNSResourceRecord
*/
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
CPU: (OFString *)CPU
OS: (OFString *)OS
TTL: (uint32_t)TTL OF_DESIGNATED_INITIALIZER;
@end
@@ -292,12 +291,12 @@
* @brief The mail exchange of the resource record.
*/
@property (readonly, nonatomic) OFString *mailExchange;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFMXDNSResourceRecord with the
* specified name, class, preference, mail exchange and time to live.
@@ -308,11 +307,11 @@
* @param mailExchange The mail exchange for the resource record
* @param TTL The time to live for the resource record
* @return An initialized OFMXDNSResourceRecord
*/
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
preference: (uint16_t)preference
mailExchange: (OFString *)mailExchange
TTL: (uint32_t)TTL OF_DESIGNATED_INITIALIZER;
@end
@@ -332,12 +331,12 @@
* @brief The authoritative host of the resource record.
*/
@property (readonly, nonatomic) OFString *authoritativeHost;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFNSDNSResourceRecord with the
* specified name, class, authoritative host and time to live.
@@ -347,11 +346,11 @@
* @param authoritativeHost The authoritative host for the resource record
* @param TTL The time to live for the resource record
* @return An initialized OFNSDNSResourceRecord
*/
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
authoritativeHost: (OFString *)authoritativeHost
TTL: (uint32_t)TTL OF_DESIGNATED_INITIALIZER;
@end
/**
@@ -370,12 +369,12 @@
* @brief The domain name of the resource record.
*/
@property (readonly, nonatomic) OFString *domainName;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFPTRDNSResourceRecord with the
* specified name, class, domain name and time to live.
@@ -385,11 +384,11 @@
* @param domainName The domain name for the resource record
* @param TTL The time to live for the resource record
* @return An initialized OFPTRDNSResourceRecord
*/
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
domainName: (OFString *)domainName
TTL: (uint32_t)TTL OF_DESIGNATED_INITIALIZER;
@end
/**
@@ -414,12 +413,12 @@
* person of the resource record.
*/
@property (readonly, nonatomic) OFString *TXTDomainName;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFRPDNSResourceRecord with the
* specified name, class, alias and time to live.
@@ -431,11 +430,11 @@
* the responsible person of the resource record
* @param TTL The time to live for the resource record
* @return An initialized OFRPDNSResourceRecord
*/
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
mailbox: (OFString *)mailbox
TXTDomainName: (OFString *)TXTDomainName
TTL: (uint32_t)TTL OF_DESIGNATED_INITIALIZER;
@end
@@ -487,12 +486,12 @@
* @brief The minimum TTL of the zone.
*/
@property (readonly, nonatomic) uint32_t minTTL;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFSOADNSResourceRecord with the
* specified name, class, text data and time to live.
@@ -508,11 +507,11 @@
* @param minTTL The minimum TTL of the zone
* @param TTL The time to live for the resource record
* @return An initialized OFSOADNSResourceRecord
*/
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
primaryNameServer: (OFString *)primaryNameServer
responsiblePerson: (OFString *)responsiblePerson
serialNumber: (uint32_t)serialNumber
refreshInterval: (uint32_t)refreshInterval
retryInterval: (uint32_t)retryInterval
@@ -554,12 +553,12 @@
* @brief The port on the target of the resource record.
*/
@property (readonly, nonatomic) uint16_t port;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFSRVDNSResourceRecord with the
* specified name, class, preference, mail exchange and time to live.
@@ -596,12 +595,12 @@
* @brief The text of the resource record.
*/
@property (readonly, nonatomic) OFArray OF_GENERIC(OFData *) *textStrings;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFTXTDNSResourceRecord with the
* specified name, class, text data and time to live.
@@ -611,23 +610,22 @@
* @param textStrings An array of text strings for the resource record
* @param TTL The time to live for the resource record
* @return An initialized OFTXTDNSResourceRecord
*/
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
textStrings: (OFArray OF_GENERIC(OFData *) *)textStrings
TTL: (uint32_t)TTL OF_DESIGNATED_INITIALIZER;
@end
#ifdef __cplusplus
extern "C" {
#endif
-extern OFString *_Nonnull of_dns_class_to_string(of_dns_class_t DNSClass);
-extern OFString *_Nonnull of_dns_record_type_to_string(
- of_dns_record_type_t recordType);
-extern of_dns_class_t of_dns_class_parse(OFString *_Nonnull string);
-extern of_dns_record_type_t of_dns_record_type_parse(OFString *_Nonnull string);
+extern OFString *_Nonnull OFDNSClassName(OFDNSClass DNSClass);
+extern OFString *_Nonnull OFDNSRecordTypeName(OFDNSRecordType recordType);
+extern OFDNSClass OFDNSClassParseName(OFString *_Nonnull string);
+extern OFDNSRecordType OFDNSRecordTypeParseName(OFString *_Nonnull string);
#ifdef __cplusplus
}
#endif
OF_ASSUME_NONNULL_END
Index: src/OFDNSResourceRecord.m
==================================================================
--- src/OFDNSResourceRecord.m
+++ src/OFDNSResourceRecord.m
@@ -21,67 +21,68 @@
#import "OFInvalidArgumentException.h"
#import "OFInvalidFormatException.h"
OFString *
-of_dns_class_to_string(of_dns_class_t DNSClass)
+OFDNSClassName(OFDNSClass DNSClass)
{
switch (DNSClass) {
- case OF_DNS_CLASS_IN:
+ case OFDNSClassIN:
return @"IN";
- case OF_DNS_CLASS_ANY:
+ case OFDNSClassAny:
return @"any";
default:
return [OFString stringWithFormat: @"%u", DNSClass];
}
}
OFString *
-of_dns_record_type_to_string(of_dns_record_type_t recordType)
+OFDNSRecordTypeName(OFDNSRecordType recordType)
{
switch (recordType) {
- case OF_DNS_RECORD_TYPE_A:
+ case OFDNSRecordTypeA:
return @"A";
- case OF_DNS_RECORD_TYPE_NS:
+ case OFDNSRecordTypeNS:
return @"NS";
- case OF_DNS_RECORD_TYPE_CNAME:
+ case OFDNSRecordTypeCNAME:
return @"CNAME";
- case OF_DNS_RECORD_TYPE_SOA:
+ case OFDNSRecordTypeSOA:
return @"SOA";
- case OF_DNS_RECORD_TYPE_PTR:
+ case OFDNSRecordTypePTR:
return @"PTR";
- case OF_DNS_RECORD_TYPE_HINFO:
+ case OFDNSRecordTypeHINFO:
return @"HINFO";
- case OF_DNS_RECORD_TYPE_MX:
+ case OFDNSRecordTypeMX:
return @"MX";
- case OF_DNS_RECORD_TYPE_TXT:
+ case OFDNSRecordTypeTXT:
return @"TXT";
- case OF_DNS_RECORD_TYPE_RP:
+ case OFDNSRecordTypeRP:
return @"RP";
- case OF_DNS_RECORD_TYPE_AAAA:
+ case OFDNSRecordTypeAAAA:
return @"AAAA";
- case OF_DNS_RECORD_TYPE_SRV:
+ case OFDNSRecordTypeSRV:
return @"SRV";
- case OF_DNS_RECORD_TYPE_ALL:
+ case OFDNSRecordTypeAll:
return @"all";
default:
return [OFString stringWithFormat: @"%u", recordType];
}
}
-of_dns_class_t of_dns_class_parse(OFString *string)
+OFDNSClass
+OFDNSClassParseName(OFString *string)
{
void *pool = objc_autoreleasePoolPush();
- of_dns_class_t DNSClass;
+ OFDNSClass DNSClass;
string = string.uppercaseString;
if ([string isEqual: @"IN"])
- DNSClass = OF_DNS_CLASS_IN;
+ DNSClass = OFDNSClassIN;
else {
@try {
- DNSClass = (of_dns_class_t)
+ DNSClass = (OFDNSClass)
[string unsignedLongLongValueWithBase: 0];
} @catch (OFInvalidFormatException *e) {
@throw [OFInvalidArgumentException exception];
}
}
@@ -89,44 +90,45 @@
objc_autoreleasePoolPop(pool);
return DNSClass;
}
-of_dns_record_type_t of_dns_record_type_parse(OFString *string)
+OFDNSRecordType
+OFDNSRecordTypeParseName(OFString *string)
{
void *pool = objc_autoreleasePoolPush();
- of_dns_record_type_t recordType;
+ OFDNSRecordType recordType;
string = string.uppercaseString;
if ([string isEqual: @"A"])
- recordType = OF_DNS_RECORD_TYPE_A;
+ recordType = OFDNSRecordTypeA;
else if ([string isEqual: @"NS"])
- recordType = OF_DNS_RECORD_TYPE_NS;
+ recordType = OFDNSRecordTypeNS;
else if ([string isEqual: @"CNAME"])
- recordType = OF_DNS_RECORD_TYPE_CNAME;
+ recordType = OFDNSRecordTypeCNAME;
else if ([string isEqual: @"SOA"])
- recordType = OF_DNS_RECORD_TYPE_SOA;
+ recordType = OFDNSRecordTypeSOA;
else if ([string isEqual: @"PTR"])
- recordType = OF_DNS_RECORD_TYPE_PTR;
+ recordType = OFDNSRecordTypePTR;
else if ([string isEqual: @"HINFO"])
- recordType = OF_DNS_RECORD_TYPE_HINFO;
+ recordType = OFDNSRecordTypeHINFO;
else if ([string isEqual: @"MX"])
- recordType = OF_DNS_RECORD_TYPE_MX;
+ recordType = OFDNSRecordTypeMX;
else if ([string isEqual: @"TXT"])
- recordType = OF_DNS_RECORD_TYPE_TXT;
+ recordType = OFDNSRecordTypeTXT;
else if ([string isEqual: @"RP"])
- recordType = OF_DNS_RECORD_TYPE_RP;
+ recordType = OFDNSRecordTypeRP;
else if ([string isEqual: @"AAAA"])
- recordType = OF_DNS_RECORD_TYPE_AAAA;
+ recordType = OFDNSRecordTypeAAAA;
else if ([string isEqual: @"SRV"])
- recordType = OF_DNS_RECORD_TYPE_SRV;
+ recordType = OFDNSRecordTypeSRV;
else if ([string isEqual: @"ALL"])
- recordType = OF_DNS_RECORD_TYPE_ALL;
+ recordType = OFDNSRecordTypeAll;
else {
@try {
- recordType = (of_dns_record_type_t)
+ recordType = (OFDNSRecordType)
[string unsignedLongLongValueWithBase: 0];
} @catch (OFInvalidFormatException *e) {
@throw [OFInvalidArgumentException exception];
}
}
@@ -139,12 +141,12 @@
@implementation OFDNSResourceRecord
@synthesize name = _name, DNSClass = _DNSClass, recordType = _recordType;
@synthesize TTL = _TTL;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL
{
self = [super init];
@try {
@@ -179,39 +181,39 @@
@"\tName = %@\n"
@"\tClass = %@\n"
@"\tType = %@\n"
@"\tTTL = %" PRIu32 "\n"
@">",
- self.className, _name, of_dns_class_to_string(_DNSClass),
- of_dns_record_type_to_string(_recordType), _TTL];
+ self.className, _name, OFDNSClassName(_DNSClass),
+ OFDNSRecordTypeName(_recordType), _TTL];
}
@end
@implementation OFADNSResourceRecord
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL
{
OF_INVALID_INIT_METHOD
}
- (instancetype)initWithName: (OFString *)name
- address: (const of_socket_address_t *)address
+ address: (const OFSocketAddress *)address
TTL: (uint32_t)TTL
{
self = [super initWithName: name
- DNSClass: OF_DNS_CLASS_IN
- recordType: OF_DNS_RECORD_TYPE_A
+ DNSClass: OFDNSClassIN
+ recordType: OFDNSRecordTypeA
TTL: TTL];
_address = *address;
return self;
}
-- (const of_socket_address_t *)address
+- (const OFSocketAddress *)address
{
return &_address;
}
- (bool)isEqual: (id)object
@@ -233,30 +235,30 @@
return false;
if (record->_recordType != _recordType)
return false;
- if (!of_socket_address_equal(&record->_address, &_address))
+ if (!OFSocketAddressEqual(&record->_address, &_address))
return false;
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD_HASH(hash, _name.hash);
- OF_HASH_ADD(hash, _DNSClass >> 8);
- OF_HASH_ADD(hash, _DNSClass);
- OF_HASH_ADD(hash, _recordType >> 8);
- OF_HASH_ADD(hash, _recordType);
- OF_HASH_ADD_HASH(hash, of_socket_address_hash(&_address));
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAddHash(&hash, _name.hash);
+ OFHashAdd(&hash, _DNSClass >> 8);
+ OFHashAdd(&hash, _DNSClass);
+ OFHashAdd(&hash, _recordType >> 8);
+ OFHashAdd(&hash, _recordType);
+ OFHashAddHash(&hash, OFSocketAddressHash(&_address));
+
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -265,39 +267,38 @@
@"<%@:\n"
@"\tName = %@\n"
@"\tAddress = %@\n"
@"\tTTL = %" PRIu32 "\n"
@">",
- self.className, _name,
- of_socket_address_ip_string(&_address, NULL), _TTL];
+ self.className, _name, OFSocketAddressString(&_address), _TTL];
}
@end
@implementation OFAAAADNSResourceRecord
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL
{
OF_INVALID_INIT_METHOD
}
- (instancetype)initWithName: (OFString *)name
- address: (const of_socket_address_t *)address
+ address: (const OFSocketAddress *)address
TTL: (uint32_t)TTL
{
self = [super initWithName: name
- DNSClass: OF_DNS_CLASS_IN
- recordType: OF_DNS_RECORD_TYPE_AAAA
+ DNSClass: OFDNSClassIN
+ recordType: OFDNSRecordTypeAAAA
TTL: TTL];
_address = *address;
return self;
}
-- (const of_socket_address_t *)address
+- (const OFSocketAddress *)address
{
return &_address;
}
- (bool)isEqual: (id)object
@@ -319,30 +320,30 @@
return false;
if (record->_recordType != _recordType)
return false;
- if (!of_socket_address_equal(&record->_address, &_address))
+ if (!OFSocketAddressEqual(&record->_address, &_address))
return false;
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD_HASH(hash, _name.hash);
- OF_HASH_ADD(hash, _DNSClass >> 8);
- OF_HASH_ADD(hash, _DNSClass);
- OF_HASH_ADD(hash, _recordType >> 8);
- OF_HASH_ADD(hash, _recordType);
- OF_HASH_ADD_HASH(hash, of_socket_address_hash(&_address));
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAddHash(&hash, _name.hash);
+ OFHashAdd(&hash, _DNSClass >> 8);
+ OFHashAdd(&hash, _DNSClass);
+ OFHashAdd(&hash, _recordType >> 8);
+ OFHashAdd(&hash, _recordType);
+ OFHashAddHash(&hash, OFSocketAddressHash(&_address));
+
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -351,34 +352,33 @@
@"<%@:\n"
@"\tName = %@\n"
@"\tAddress = %@\n"
@"\tTTL = %" PRIu32 "\n"
@">",
- self.className, _name,
- of_socket_address_ip_string(&_address, NULL), _TTL];
+ self.className, _name, OFSocketAddressString(&_address), _TTL];
}
@end
@implementation OFCNAMEDNSResourceRecord
@synthesize alias = _alias;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL
{
OF_INVALID_INIT_METHOD
}
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
alias: (OFString *)alias
TTL: (uint32_t)TTL
{
self = [super initWithName: name
DNSClass: DNSClass
- recordType: OF_DNS_RECORD_TYPE_CNAME
+ recordType: OFDNSRecordTypeCNAME
TTL: TTL];
@try {
_alias = [alias copy];
} @catch (id e) {
@@ -423,22 +423,22 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD_HASH(hash, _name.hash);
- OF_HASH_ADD(hash, _DNSClass >> 8);
- OF_HASH_ADD(hash, _DNSClass);
- OF_HASH_ADD(hash, _recordType >> 8);
- OF_HASH_ADD(hash, _recordType);
- OF_HASH_ADD_HASH(hash, _alias.hash);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAddHash(&hash, _name.hash);
+ OFHashAdd(&hash, _DNSClass >> 8);
+ OFHashAdd(&hash, _DNSClass);
+ OFHashAdd(&hash, _recordType >> 8);
+ OFHashAdd(&hash, _recordType);
+ OFHashAddHash(&hash, _alias.hash);
+
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -448,35 +448,34 @@
@"\tName = %@\n"
@"\tClass = %@\n"
@"\tAlias = %@\n"
@"\tTTL = %" PRIu32 "\n"
@">",
- self.className, _name, of_dns_class_to_string(_DNSClass), _alias,
- _TTL];
+ self.className, _name, OFDNSClassName(_DNSClass), _alias, _TTL];
}
@end
@implementation OFHINFODNSResourceRecord
@synthesize CPU = _CPU, OS = _OS;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL
{
OF_INVALID_INIT_METHOD
}
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
CPU: (OFString *)CPU
OS: (OFString *)OS
TTL: (uint32_t)TTL
{
self = [super initWithName: name
DNSClass: DNSClass
- recordType: OF_DNS_RECORD_TYPE_HINFO
+ recordType: OFDNSRecordTypeHINFO
TTL: TTL];
@try {
_CPU = [CPU copy];
_OS = [OS copy];
@@ -526,23 +525,23 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD_HASH(hash, _name.hash);
- OF_HASH_ADD(hash, _DNSClass >> 8);
- OF_HASH_ADD(hash, _DNSClass);
- OF_HASH_ADD(hash, _recordType >> 8);
- OF_HASH_ADD(hash, _recordType);
- OF_HASH_ADD_HASH(hash, _CPU.hash);
- OF_HASH_ADD_HASH(hash, _OS.hash);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAddHash(&hash, _name.hash);
+ OFHashAdd(&hash, _DNSClass >> 8);
+ OFHashAdd(&hash, _DNSClass);
+ OFHashAdd(&hash, _recordType >> 8);
+ OFHashAdd(&hash, _recordType);
+ OFHashAddHash(&hash, _CPU.hash);
+ OFHashAddHash(&hash, _OS.hash);
+
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -553,35 +552,34 @@
@"\tClass = %@\n"
@"\tCPU = %@\n"
@"\tOS = %@\n"
@"\tTTL = %" PRIu32 "\n"
@">",
- self.className, _name, of_dns_class_to_string(_DNSClass), _CPU, _OS,
- _TTL];
+ self.className, _name, OFDNSClassName(_DNSClass), _CPU, _OS, _TTL];
}
@end
@implementation OFMXDNSResourceRecord
@synthesize preference = _preference, mailExchange = _mailExchange;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL
{
OF_INVALID_INIT_METHOD
}
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
preference: (uint16_t)preference
mailExchange: (OFString *)mailExchange
TTL: (uint32_t)TTL
{
self = [super initWithName: name
DNSClass: DNSClass
- recordType: OF_DNS_RECORD_TYPE_MX
+ recordType: OFDNSRecordTypeMX
TTL: TTL];
@try {
_preference = preference;
_mailExchange = [mailExchange copy];
@@ -631,24 +629,24 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD_HASH(hash, _name.hash);
- OF_HASH_ADD(hash, _DNSClass >> 8);
- OF_HASH_ADD(hash, _DNSClass);
- OF_HASH_ADD(hash, _recordType >> 8);
- OF_HASH_ADD(hash, _recordType);
- OF_HASH_ADD(hash, _preference >> 8);
- OF_HASH_ADD(hash, _preference);
- OF_HASH_ADD_HASH(hash, _mailExchange.hash);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAddHash(&hash, _name.hash);
+ OFHashAdd(&hash, _DNSClass >> 8);
+ OFHashAdd(&hash, _DNSClass);
+ OFHashAdd(&hash, _recordType >> 8);
+ OFHashAdd(&hash, _recordType);
+ OFHashAdd(&hash, _preference >> 8);
+ OFHashAdd(&hash, _preference);
+ OFHashAddHash(&hash, _mailExchange.hash);
+
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -659,34 +657,34 @@
@"\tClass = %@\n"
@"\tPreference = %" PRIu16 "\n"
@"\tMail Exchange = %@\n"
@"\tTTL = %" PRIu32 "\n"
@">",
- self.className, _name, of_dns_class_to_string(_DNSClass),
- _preference, _mailExchange, _TTL];
+ self.className, _name, OFDNSClassName(_DNSClass), _preference,
+ _mailExchange, _TTL];
}
@end
@implementation OFNSDNSResourceRecord
@synthesize authoritativeHost = _authoritativeHost;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL
{
OF_INVALID_INIT_METHOD
}
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
authoritativeHost: (OFString *)authoritativeHost
TTL: (uint32_t)TTL
{
self = [super initWithName: name
DNSClass: DNSClass
- recordType: OF_DNS_RECORD_TYPE_NS
+ recordType: OFDNSRecordTypeNS
TTL: TTL];
@try {
_authoritativeHost = [authoritativeHost copy];
} @catch (id e) {
@@ -732,22 +730,22 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD_HASH(hash, _name.hash);
- OF_HASH_ADD(hash, _DNSClass >> 8);
- OF_HASH_ADD(hash, _DNSClass);
- OF_HASH_ADD(hash, _recordType >> 8);
- OF_HASH_ADD(hash, _recordType);
- OF_HASH_ADD_HASH(hash, _authoritativeHost.hash);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAddHash(&hash, _name.hash);
+ OFHashAdd(&hash, _DNSClass >> 8);
+ OFHashAdd(&hash, _DNSClass);
+ OFHashAdd(&hash, _recordType >> 8);
+ OFHashAdd(&hash, _recordType);
+ OFHashAddHash(&hash, _authoritativeHost.hash);
+
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -757,34 +755,34 @@
@"\tName = %@\n"
@"\tClass = %@\n"
@"\tAuthoritative Host = %@\n"
@"\tTTL = %" PRIu32 "\n"
@">",
- self.className, _name, of_dns_class_to_string(_DNSClass),
+ self.className, _name, OFDNSClassName(_DNSClass),
_authoritativeHost, _TTL];
}
@end
@implementation OFPTRDNSResourceRecord
@synthesize domainName = _domainName;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL
{
OF_INVALID_INIT_METHOD
}
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
domainName: (OFString *)domainName
TTL: (uint32_t)TTL
{
self = [super initWithName: name
DNSClass: DNSClass
- recordType: OF_DNS_RECORD_TYPE_PTR
+ recordType: OFDNSRecordTypePTR
TTL: TTL];
@try {
_domainName = [domainName copy];
} @catch (id e) {
@@ -830,22 +828,22 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD_HASH(hash, _name.hash);
- OF_HASH_ADD(hash, _DNSClass >> 8);
- OF_HASH_ADD(hash, _DNSClass);
- OF_HASH_ADD(hash, _recordType >> 8);
- OF_HASH_ADD(hash, _recordType);
- OF_HASH_ADD_HASH(hash, _domainName.hash);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAddHash(&hash, _name.hash);
+ OFHashAdd(&hash, _DNSClass >> 8);
+ OFHashAdd(&hash, _DNSClass);
+ OFHashAdd(&hash, _recordType >> 8);
+ OFHashAdd(&hash, _recordType);
+ OFHashAddHash(&hash, _domainName.hash);
+
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -855,35 +853,35 @@
@"\tName = %@\n"
@"\tClass = %@\n"
@"\tDomain Name = %@\n"
@"\tTTL = %" PRIu32 "\n"
@">",
- self.className, _name, of_dns_class_to_string(_DNSClass),
- _domainName, _TTL];
+ self.className, _name, OFDNSClassName(_DNSClass), _domainName,
+ _TTL];
}
@end
@implementation OFRPDNSResourceRecord
@synthesize mailbox = _mailbox, TXTDomainName = _TXTDomainName;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL
{
OF_INVALID_INIT_METHOD
}
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
mailbox: (OFString *)mailbox
TXTDomainName: (OFString *)TXTDomainName
TTL: (uint32_t)TTL
{
self = [super initWithName: name
DNSClass: DNSClass
- recordType: OF_DNS_RECORD_TYPE_RP
+ recordType: OFDNSRecordTypeRP
TTL: TTL];
@try {
_mailbox = [mailbox copy];
_TXTDomainName = [TXTDomainName copy];
@@ -935,23 +933,23 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD_HASH(hash, _name.hash);
- OF_HASH_ADD(hash, _DNSClass >> 8);
- OF_HASH_ADD(hash, _DNSClass);
- OF_HASH_ADD(hash, _recordType >> 8);
- OF_HASH_ADD(hash, _recordType);
- OF_HASH_ADD_HASH(hash, _mailbox.hash);
- OF_HASH_ADD_HASH(hash, _TXTDomainName.hash);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAddHash(&hash, _name.hash);
+ OFHashAdd(&hash, _DNSClass >> 8);
+ OFHashAdd(&hash, _DNSClass);
+ OFHashAdd(&hash, _recordType >> 8);
+ OFHashAdd(&hash, _recordType);
+ OFHashAddHash(&hash, _mailbox.hash);
+ OFHashAddHash(&hash, _TXTDomainName.hash);
+
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -962,11 +960,11 @@
@"\tClass = %@\n"
@"\tMailbox = %@\n"
@"\tTXT Domain Name = %@\n"
@"\tTTL = %" PRIu32 "\n"
@">",
- self.className, _name, of_dns_class_to_string(_DNSClass), _mailbox,
+ self.className, _name, OFDNSClassName(_DNSClass), _mailbox,
_TXTDomainName, _TTL];
}
@end
@implementation OFSOADNSResourceRecord
@@ -975,19 +973,19 @@
@synthesize serialNumber = _serialNumber, refreshInterval = _refreshInterval;
@synthesize retryInterval = _retryInterval;
@synthesize expirationInterval = _expirationInterval, minTTL = _minTTL;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL
{
OF_INVALID_INIT_METHOD
}
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
primaryNameServer: (OFString *)primaryNameServer
responsiblePerson: (OFString *)responsiblePerson
serialNumber: (uint32_t)serialNumber
refreshInterval: (uint32_t)refreshInterval
retryInterval: (uint32_t)retryInterval
@@ -995,11 +993,11 @@
minTTL: (uint32_t)minTTL
TTL: (uint32_t)TTL
{
self = [super initWithName: name
DNSClass: DNSClass
- recordType: OF_DNS_RECORD_TYPE_SOA
+ recordType: OFDNSRecordTypeSOA
TTL: TTL];
@try {
_primaryNameServer = [primaryNameServer copy];
_responsiblePerson = [responsiblePerson copy];
@@ -1071,43 +1069,43 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD_HASH(hash, _name.hash);
- OF_HASH_ADD(hash, _DNSClass >> 8);
- OF_HASH_ADD(hash, _DNSClass);
- OF_HASH_ADD(hash, _recordType >> 8);
- OF_HASH_ADD(hash, _recordType);
- OF_HASH_ADD_HASH(hash, _primaryNameServer.hash);
- OF_HASH_ADD_HASH(hash, _responsiblePerson.hash);
- OF_HASH_ADD(hash, _serialNumber >> 24);
- OF_HASH_ADD(hash, _serialNumber >> 16);
- OF_HASH_ADD(hash, _serialNumber >> 8);
- OF_HASH_ADD(hash, _serialNumber);
- OF_HASH_ADD(hash, _refreshInterval >> 24);
- OF_HASH_ADD(hash, _refreshInterval >> 16);
- OF_HASH_ADD(hash, _refreshInterval >> 8);
- OF_HASH_ADD(hash, _refreshInterval);
- OF_HASH_ADD(hash, _retryInterval >> 24);
- OF_HASH_ADD(hash, _retryInterval >> 16);
- OF_HASH_ADD(hash, _retryInterval >> 8);
- OF_HASH_ADD(hash, _retryInterval);
- OF_HASH_ADD(hash, _expirationInterval >> 24);
- OF_HASH_ADD(hash, _expirationInterval >> 16);
- OF_HASH_ADD(hash, _expirationInterval >> 8);
- OF_HASH_ADD(hash, _expirationInterval);
- OF_HASH_ADD(hash, _minTTL >> 24);
- OF_HASH_ADD(hash, _minTTL >> 16);
- OF_HASH_ADD(hash, _minTTL >> 8);
- OF_HASH_ADD(hash, _minTTL);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAddHash(&hash, _name.hash);
+ OFHashAdd(&hash, _DNSClass >> 8);
+ OFHashAdd(&hash, _DNSClass);
+ OFHashAdd(&hash, _recordType >> 8);
+ OFHashAdd(&hash, _recordType);
+ OFHashAddHash(&hash, _primaryNameServer.hash);
+ OFHashAddHash(&hash, _responsiblePerson.hash);
+ OFHashAdd(&hash, _serialNumber >> 24);
+ OFHashAdd(&hash, _serialNumber >> 16);
+ OFHashAdd(&hash, _serialNumber >> 8);
+ OFHashAdd(&hash, _serialNumber);
+ OFHashAdd(&hash, _refreshInterval >> 24);
+ OFHashAdd(&hash, _refreshInterval >> 16);
+ OFHashAdd(&hash, _refreshInterval >> 8);
+ OFHashAdd(&hash, _refreshInterval);
+ OFHashAdd(&hash, _retryInterval >> 24);
+ OFHashAdd(&hash, _retryInterval >> 16);
+ OFHashAdd(&hash, _retryInterval >> 8);
+ OFHashAdd(&hash, _retryInterval);
+ OFHashAdd(&hash, _expirationInterval >> 24);
+ OFHashAdd(&hash, _expirationInterval >> 16);
+ OFHashAdd(&hash, _expirationInterval >> 8);
+ OFHashAdd(&hash, _expirationInterval);
+ OFHashAdd(&hash, _minTTL >> 24);
+ OFHashAdd(&hash, _minTTL >> 16);
+ OFHashAdd(&hash, _minTTL >> 8);
+ OFHashAdd(&hash, _minTTL);
+
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -1123,11 +1121,11 @@
@"\tRetry Interval = %" PRIu32 "\n"
@"\tExpiration Interval = %" PRIu32 "\n"
@"\tMinimum TTL = %" PRIu32 "\n"
@"\tTTL = %" PRIu32 "\n"
@">",
- self.className, _name, of_dns_class_to_string(_DNSClass),
+ self.className, _name, OFDNSClassName(_DNSClass),
_primaryNameServer, _responsiblePerson, _serialNumber,
_refreshInterval, _retryInterval, _expirationInterval, _minTTL,
_TTL];
}
@end
@@ -1135,12 +1133,12 @@
@implementation OFSRVDNSResourceRecord
@synthesize priority = _priority, weight = _weight, target = _target;
@synthesize port = _port;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL
{
OF_INVALID_INIT_METHOD
}
@@ -1150,12 +1148,12 @@
target: (OFString *)target
port: (uint16_t)port
TTL: (uint32_t)TTL
{
self = [super initWithName: name
- DNSClass: OF_DNS_CLASS_IN
- recordType: OF_DNS_RECORD_TYPE_SRV
+ DNSClass: OFDNSClassIN
+ recordType: OFDNSRecordTypeSRV
TTL: TTL];
@try {
_priority = priority;
_weight = weight;
@@ -1212,28 +1210,28 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD_HASH(hash, _name.hash);
- OF_HASH_ADD(hash, _DNSClass >> 8);
- OF_HASH_ADD(hash, _DNSClass);
- OF_HASH_ADD(hash, _recordType >> 8);
- OF_HASH_ADD(hash, _recordType);
- OF_HASH_ADD(hash, _priority >> 8);
- OF_HASH_ADD(hash, _priority);
- OF_HASH_ADD(hash, _weight >> 8);
- OF_HASH_ADD(hash, _weight);
- OF_HASH_ADD_HASH(hash, _target.hash);
- OF_HASH_ADD(hash, _port >> 8);
- OF_HASH_ADD(hash, _port);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAddHash(&hash, _name.hash);
+ OFHashAdd(&hash, _DNSClass >> 8);
+ OFHashAdd(&hash, _DNSClass);
+ OFHashAdd(&hash, _recordType >> 8);
+ OFHashAdd(&hash, _recordType);
+ OFHashAdd(&hash, _priority >> 8);
+ OFHashAdd(&hash, _priority);
+ OFHashAdd(&hash, _weight >> 8);
+ OFHashAdd(&hash, _weight);
+ OFHashAddHash(&hash, _target.hash);
+ OFHashAdd(&hash, _port >> 8);
+ OFHashAdd(&hash, _port);
+
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -1253,25 +1251,25 @@
@implementation OFTXTDNSResourceRecord
@synthesize textStrings = _textStrings;
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
- recordType: (of_dns_record_type_t)recordType
+ DNSClass: (OFDNSClass)DNSClass
+ recordType: (OFDNSRecordType)recordType
TTL: (uint32_t)TTL
{
OF_INVALID_INIT_METHOD
}
- (instancetype)initWithName: (OFString *)name
- DNSClass: (of_dns_class_t)DNSClass
+ DNSClass: (OFDNSClass)DNSClass
textStrings: (OFArray OF_GENERIC(OFData *) *)textStrings
TTL: (uint32_t)TTL
{
self = [super initWithName: name
DNSClass: DNSClass
- recordType: OF_DNS_RECORD_TYPE_TXT
+ recordType: OFDNSRecordTypeTXT
TTL: TTL];
@try {
_textStrings = [textStrings copy];
} @catch (id e) {
@@ -1317,22 +1315,22 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD_HASH(hash, _name.hash);
- OF_HASH_ADD(hash, _DNSClass >> 8);
- OF_HASH_ADD(hash, _DNSClass);
- OF_HASH_ADD(hash, _recordType >> 8);
- OF_HASH_ADD(hash, _recordType);
- OF_HASH_ADD_HASH(hash, _textStrings.hash);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAddHash(&hash, _name.hash);
+ OFHashAdd(&hash, _DNSClass >> 8);
+ OFHashAdd(&hash, _DNSClass);
+ OFHashAdd(&hash, _recordType >> 8);
+ OFHashAdd(&hash, _recordType);
+ OFHashAddHash(&hash, _textStrings.hash);
+
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -1373,15 +1371,14 @@
@"\tName = %@\n"
@"\tClass = %@\n"
@"\tText strings = %@\n"
@"\tTTL = %" PRIu32 "\n"
@">",
- self.className, _name, of_dns_class_to_string(_DNSClass), text,
- _TTL];
+ self.className, _name, OFDNSClassName(_DNSClass), text, _TTL];
[ret retain];
objc_autoreleasePoolPop(pool);
return [ret autorelease];
}
@end
Index: src/OFDNSResponse.h
==================================================================
--- src/OFDNSResponse.h
+++ src/OFDNSResponse.h
@@ -20,23 +20,22 @@
@class OFArray OF_GENERIC(ObjectType);
@class OFDictionary OF_GENERIC(KeyType, ObjectType);
typedef OFDictionary OF_GENERIC(OFString *, OFArray OF_GENERIC(
- OF_KINDOF(OFDNSResourceRecord *)) *) *of_dns_response_records_t;
+ OF_KINDOF(OFDNSResourceRecord *)) *) *OFDNSResponseRecords;
/**
* @class OFDNSResponse OFDNSResponse.h ObjFW/OFDNSResponse.h
*
* @brief A class storing a response from @ref OFDNSResolver.
*/
@interface OFDNSResponse: OFObject
{
OFString *_domainName;
- of_dns_response_records_t _answerRecords;
- of_dns_response_records_t _authorityRecords;
- of_dns_response_records_t _additionalRecords;
+ OFDNSResponseRecords _answerRecords, _authorityRecords;
+ OFDNSResponseRecords _additionalRecords;
OF_RESERVE_IVARS(OFDNSResponse, 4)
}
/**
* @brief The domain name of the response.
@@ -47,27 +46,27 @@
* @brief The answer records of the response.
*
* This is a dictionary with the key being the domain name and the value being
* an array of @ref OFDNSResourceRecord.
*/
-@property (readonly, nonatomic) of_dns_response_records_t answerRecords;
+@property (readonly, nonatomic) OFDNSResponseRecords answerRecords;
/**
* @brief The authority records of the response.
*
* This is a dictionary with the key being the domain name and the value being
* an array of @ref OFDNSResourceRecord.
*/
-@property (readonly, nonatomic) of_dns_response_records_t authorityRecords;
+@property (readonly, nonatomic) OFDNSResponseRecords authorityRecords;
/**
* @brief The additional records of the response.
*
* This is a dictionary with the key being the domain name and the value being
* an array of @ref OFDNSResourceRecord.
*/
-@property (readonly, nonatomic) of_dns_response_records_t additionalRecords;
+@property (readonly, nonatomic) OFDNSResponseRecords additionalRecords;
/**
* @brief Creates a new, autoreleased OFDNSResponse.
*
* @param domainName The domain name the response is for
@@ -74,15 +73,14 @@
* @param answerRecords The answer records of the response
* @param authorityRecords The authority records of the response
* @param additionalRecords The additional records of the response
* @return A new, autoreleased OFDNSResponse
*/
-+ (instancetype)
- responseWithDomainName: (OFString *)domainName
- answerRecords: (of_dns_response_records_t)answerRecords
- authorityRecords: (of_dns_response_records_t)authorityRecords
- additionalRecords: (of_dns_response_records_t)additionalRecords;
++ (instancetype)responseWithDomainName: (OFString *)domainName
+ answerRecords: (OFDNSResponseRecords)answerRecords
+ authorityRecords: (OFDNSResponseRecords)authorityRecords
+ additionalRecords: (OFDNSResponseRecords)additionalRecords;
/**
* @brief Initializes an already allocated OFDNSResponse.
*
* @param domainName The domain name the response is for
@@ -89,16 +87,15 @@
* @param answerRecords The answer records of the response
* @param authorityRecords The authority records of the response
* @param additionalRecords The additional records of the response
* @return An initialized OFDNSResponse
*/
-- (instancetype)
- initWithDomainName: (OFString *)domainName
- answerRecords: (of_dns_response_records_t)answerRecords
- authorityRecords: (of_dns_response_records_t)authorityRecords
- additionalRecords: (of_dns_response_records_t)additionalRecords
+- (instancetype)initWithDomainName: (OFString *)domainName
+ answerRecords: (OFDNSResponseRecords)answerRecords
+ authorityRecords: (OFDNSResponseRecords)authorityRecords
+ additionalRecords: (OFDNSResponseRecords)additionalRecords
OF_DESIGNATED_INITIALIZER;
- (instancetype)init OF_UNAVAILABLE;
@end
OF_ASSUME_NONNULL_END
Index: src/OFDNSResponse.m
==================================================================
--- src/OFDNSResponse.m
+++ src/OFDNSResponse.m
@@ -22,27 +22,26 @@
@implementation OFDNSResponse
@synthesize domainName = _domainName, answerRecords = _answerRecords;
@synthesize authorityRecords = _authorityRecords;
@synthesize additionalRecords = _additionalRecords;
-+ (instancetype)
- responseWithDomainName: (OFString *)domainName
- answerRecords: (of_dns_response_records_t)answerRecords
- authorityRecords: (of_dns_response_records_t)authorityRecords
- additionalRecords: (of_dns_response_records_t)additionalRecords
++ (instancetype)responseWithDomainName: (OFString *)domainName
+ answerRecords: (OFDNSResponseRecords)answerRecords
+ authorityRecords: (OFDNSResponseRecords)authorityRecords
+ additionalRecords: (OFDNSResponseRecords)additionalRecords
{
return [[[self alloc]
initWithDomainName: domainName
answerRecords: answerRecords
authorityRecords: authorityRecords
additionalRecords: additionalRecords] autorelease];
}
- (instancetype)initWithDomainName: (OFString *)domainName
- answerRecords: (of_dns_response_records_t)answerRecords
- authorityRecords: (of_dns_response_records_t)authorityRecords
- additionalRecords: (of_dns_response_records_t)additionalRecords
+ answerRecords: (OFDNSResponseRecords)answerRecords
+ authorityRecords: (OFDNSResponseRecords)authorityRecords
+ additionalRecords: (OFDNSResponseRecords)additionalRecords
{
self = [super init];
@try {
_domainName = [domainName copy];
@@ -100,18 +99,18 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
- OF_HASH_ADD_HASH(hash, _domainName.hash);
- OF_HASH_ADD_HASH(hash, [_answerRecords hash]);
- OF_HASH_ADD_HASH(hash, [_authorityRecords hash]);
- OF_HASH_ADD_HASH(hash, [_additionalRecords hash]);
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+ OFHashAddHash(&hash, _domainName.hash);
+ OFHashAddHash(&hash, [_answerRecords hash]);
+ OFHashAddHash(&hash, [_authorityRecords hash]);
+ OFHashAddHash(&hash, [_additionalRecords hash]);
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
Index: src/OFData+CryptographicHashing.m
==================================================================
--- src/OFData+CryptographicHashing.m
+++ src/OFData+CryptographicHashing.m
@@ -54,11 +54,11 @@
}
objc_autoreleasePoolPop(pool);
return [OFString stringWithCString: cString
- encoding: OF_STRING_ENCODING_ASCII
+ encoding: OFStringEncodingASCII
length: digestSize * 2];
}
- (OFString *)stringByMD5Hashing
{
Index: src/OFData+MessagePackParsing.m
==================================================================
--- src/OFData+MessagePackParsing.m
+++ src/OFData+MessagePackParsing.m
@@ -132,19 +132,19 @@
switch (data.count) {
case 4: {
uint32_t timestamp;
memcpy(×tamp, data.items, 4);
- timestamp = OF_BSWAP32_IF_LE(timestamp);
+ timestamp = OFFromBigEndian32(timestamp);
return [OFDate dateWithTimeIntervalSince1970: timestamp];
}
case 8: {
uint64_t combined;
memcpy(&combined, data.items, 8);
- combined = OF_BSWAP64_IF_LE(combined);
+ combined = OFFromBigEndian64(combined);
return [OFDate dateWithTimeIntervalSince1970:
(double)(combined & 0x3FFFFFFFF) +
(double)(combined >> 34) / 1000000000];
}
@@ -153,12 +153,12 @@
int64_t seconds;
memcpy(&nanoseconds, data.items, 4);
memcpy(&seconds, (char *)data.items + 4, 8);
- nanoseconds = OF_BSWAP32_IF_LE(nanoseconds);
- seconds = OF_BSWAP64_IF_LE(seconds);
+ nanoseconds = OFFromBigEndian32(nanoseconds);
+ seconds = OFFromBigEndian64(seconds);
return [OFDate dateWithTimeIntervalSince1970:
(double)seconds + (double)nanoseconds / 1000000000];
}
default:
@@ -285,21 +285,21 @@
if (length < 5)
@throw [OFTruncatedDataException exception];
memcpy(&f, buffer + 1, 4);
- *object = [OFNumber numberWithFloat: OF_BSWAP_FLOAT_IF_LE(f)];
+ *object = [OFNumber numberWithFloat: OFFromBigEndianFloat(f)];
return 5;
case 0xCB:; /* float 64 */
double d;
if (length < 9)
@throw [OFTruncatedDataException exception];
memcpy(&d, buffer + 1, 8);
- *object = [OFNumber numberWithDouble: OF_BSWAP_DOUBLE_IF_LE(d)];
+ *object = [OFNumber numberWithDouble: OFFromBigEndianDouble(d)];
return 9;
/* nil */
case 0xC0:
*object = [OFNull null];
return 1;
Index: src/OFData.h
==================================================================
--- src/OFData.h
+++ src/OFData.h
@@ -14,19 +14,27 @@
*/
#import "OFObject.h"
#import "OFSerialization.h"
#import "OFMessagePackRepresentation.h"
+
+/*! @file */
OF_ASSUME_NONNULL_BEGIN
@class OFString;
@class OFURL;
-enum {
- OF_DATA_SEARCH_BACKWARDS = 1
-};
+/**
+ * @brief Options for searching in data.
+ *
+ * This is a bit mask.
+ */
+typedef enum {
+ /** Search backwards in the data */
+ OFDataSearchBackwards = 1
+} OFDataSearchOptions;
/**
* @class OFData OFData.h ObjFW/OFData.h
*
* @brief A class for storing arbitrary data in an array.
@@ -274,11 +282,11 @@
* @brief Compares the data to other data.
*
* @param data Data to compare the data to
* @return The result of the comparison
*/
-- (of_comparison_result_t)compare: (OFData *)data;
+- (OFComparisonResult)compare: (OFData *)data;
/**
* @brief Returns a specific item of the OFData.
*
* @param index The number of the item to return
@@ -290,28 +298,24 @@
* @brief Returns the data in the specified range as a new OFData.
*
* @param range The range of the data for the new OFData
* @return The data in the specified range as a new OFData
*/
-- (OFData *)subdataWithRange: (of_range_t)range;
+- (OFData *)subdataWithRange: (OFRange)range;
/**
* @brief Returns the range of the data.
*
* @param data The data to search for
- * @param options Options modifying search behavior.@n
- * Possible values are:
- * Value | Description
- * ---------------------------|-----------------------------
- * `OF_DATA_SEARCH_BACKWARDS` | Search backwards in the data
+ * @param options Options modifying search behavior
* @param range The range in which to search
* @return The range of the first occurrence of the data or a range with
- * `OF_NOT_FOUND` as start position if it was not found.
+ * `OFNotFound` as start position if it was not found.
*/
-- (of_range_t)rangeOfData: (OFData *)data
- options: (int)options
- range: (of_range_t)range;
+- (OFRange)rangeOfData: (OFData *)data
+ options: (OFDataSearchOptions)options
+ range: (OFRange)range;
#ifdef OF_HAVE_FILES
/**
* @brief Writes the OFData into the specified file.
*
Index: src/OFData.m
==================================================================
--- src/OFData.m
+++ src/OFData.m
@@ -18,10 +18,11 @@
#include
#include
#include
#import "OFData.h"
+#import "OFBase64.h"
#import "OFDictionary.h"
#ifdef OF_HAVE_FILES
# import "OFFile.h"
# import "OFFileManager.h"
#endif
@@ -38,12 +39,10 @@
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"
#import "OFTruncatedDataException.h"
#import "OFUnsupportedProtocolException.h"
-#import "base64.h"
-
/* References for static linking */
void
_references_to_categories_of_OFData(void)
{
_OFData_CryptographicHashing_reference = 1;
@@ -123,11 +122,11 @@
@try {
if (itemSize == 0)
@throw [OFInvalidArgumentException exception];
- _items = of_alloc(count, itemSize);
+ _items = OFAllocMemory(count, itemSize);
_count = count;
_itemSize = itemSize;
_freeWhenDone = true;
memcpy(_items, items, count * itemSize);
@@ -187,19 +186,19 @@
# if ULLONG_MAX > SIZE_MAX
if (size > SIZE_MAX)
@throw [OFOutOfRangeException exception];
# endif
- buffer = of_alloc((size_t)size, 1);
+ buffer = OFAllocMemory((size_t)size, 1);
file = [[OFFile alloc] initWithPath: path mode: @"r"];
@try {
[file readIntoBuffer: buffer exactLength: (size_t)size];
} @finally {
[file release];
}
} @catch (id e) {
- free(buffer);
+ OFFreeMemory(buffer);
[self release];
@throw e;
}
@@ -206,11 +205,11 @@
@try {
self = [self initWithItemsNoCopy: buffer
count: (size_t)size
freeWhenDone: true];
} @catch (id e) {
- free(buffer);
+ OFFreeMemory(buffer);
@throw e;
}
return self;
}
@@ -236,11 +235,11 @@
_count = 0;
_itemSize = 1;
_freeWhenDone = true;
pageSize = [OFSystemInfo pageSize];
- buffer = of_alloc(1, pageSize);
+ buffer = OFAllocMemory(1, pageSize);
@try {
while (!stream.atEndOfStream) {
size_t length = [stream
readIntoBuffer: buffer
@@ -248,16 +247,17 @@
if (SIZE_MAX - _count < length)
@throw [OFOutOfRangeException
exception];
- _items = of_realloc(_items, _count + length, 1);
+ _items = OFResizeMemory(_items,
+ _count + length, 1);
memcpy(_items + _count, buffer, length);
_count += length;
}
} @finally {
- free(buffer);
+ OFFreeMemory(buffer);
}
objc_autoreleasePoolPop(pool);
} @catch (id e) {
[self release];
@@ -271,25 +271,24 @@
{
self = [super init];
@try {
size_t count = [string
- cStringLengthWithEncoding: OF_STRING_ENCODING_ASCII];
+ cStringLengthWithEncoding: OFStringEncodingASCII];
const char *cString;
if (count % 2 != 0)
@throw [OFInvalidFormatException exception];
count /= 2;
- _items = of_alloc(count, 1);
+ _items = OFAllocMemory(count, 1);
_count = count;
_itemSize = 1;
_freeWhenDone = true;
- cString = [string
- cStringWithEncoding: OF_STRING_ENCODING_ASCII];
+ cString = [string cStringWithEncoding: OFStringEncodingASCII];
for (size_t i = 0; i < count; i++) {
uint8_t c1 = cString[2 * i];
uint8_t c2 = cString[2 * i + 1];
uint8_t byte;
@@ -332,14 +331,13 @@
}
self = [(OFMutableData *)self initWithCapacity: string.length / 3];
@try {
- if (!of_base64_decode((OFMutableData *)self,
- [string cStringWithEncoding: OF_STRING_ENCODING_ASCII],
- [string cStringLengthWithEncoding:
- OF_STRING_ENCODING_ASCII]))
+ if (!OFBase64Decode((OFMutableData *)self,
+ [string cStringWithEncoding: OFStringEncodingASCII],
+ [string cStringLengthWithEncoding: OFStringEncodingASCII]))
@throw [OFInvalidFormatException exception];
} @catch (id e) {
[self release];
@throw e;
}
@@ -355,11 +353,11 @@
void *pool = objc_autoreleasePoolPush();
OFString *stringValue;
@try {
if (![element.name isEqual: self.className] ||
- ![element.namespace isEqual: OF_SERIALIZATION_NS])
+ ![element.namespace isEqual: OFSerializationNS])
@throw [OFInvalidArgumentException exception];
stringValue = element.stringValue;
} @catch (id e) {
[self release];
@@ -374,11 +372,11 @@
}
- (void)dealloc
{
if (_freeWhenDone)
- free(_items);
+ OFFreeMemory(_items);
[_parentData release];
[super dealloc];
}
@@ -447,11 +445,11 @@
return false;
return true;
}
-- (of_comparison_result_t)compare: (OFData *)data
+- (OFComparisonResult)compare: (OFData *)data
{
int comparison;
size_t count, minCount;
if (![data isKindOfClass: [OFData class]])
@@ -464,38 +462,38 @@
minCount = (_count > count ? count : _count);
if ((comparison = memcmp(_items, data.items,
minCount * _itemSize)) == 0) {
if (_count > count)
- return OF_ORDERED_DESCENDING;
+ return OFOrderedDescending;
if (_count < count)
- return OF_ORDERED_ASCENDING;
+ return OFOrderedAscending;
- return OF_ORDERED_SAME;
+ return OFOrderedSame;
}
if (comparison > 0)
- return OF_ORDERED_DESCENDING;
+ return OFOrderedDescending;
else
- return OF_ORDERED_ASCENDING;
+ return OFOrderedAscending;
}
- (unsigned long)hash
{
- uint32_t hash;
+ unsigned long hash;
- OF_HASH_INIT(hash);
+ OFHashInit(&hash);
for (size_t i = 0; i < _count * _itemSize; i++)
- OF_HASH_ADD(hash, ((uint8_t *)_items)[i]);
+ OFHashAdd(&hash, ((uint8_t *)_items)[i]);
- OF_HASH_FINALIZE(hash);
+ OFHashFinalize(&hash);
return hash;
}
-- (OFData *)subdataWithRange: (of_range_t)range
+- (OFData *)subdataWithRange: (OFRange)range
{
OFData *ret;
if (range.length > SIZE_MAX - range.location ||
range.location + range.length > _count)
@@ -540,16 +538,16 @@
return ret;
}
- (OFString *)stringByBase64Encoding
{
- return of_base64_encode(_items, _count * _itemSize);
+ return OFBase64Encode(_items, _count * _itemSize);
}
-- (of_range_t)rangeOfData: (OFData *)data
- options: (int)options
- range: (of_range_t)range
+- (OFRange)rangeOfData: (OFData *)data
+ options: (OFDataSearchOptions)options
+ range: (OFRange)range
{
const char *search;
size_t searchLength;
if (range.length > SIZE_MAX - range.location ||
@@ -558,22 +556,22 @@
if (data == nil || data.itemSize != _itemSize)
@throw [OFInvalidArgumentException exception];
if ((searchLength = data.count) == 0)
- return of_range(0, 0);
+ return OFRangeMake(0, 0);
if (searchLength > range.length)
- return of_range(OF_NOT_FOUND, 0);
+ return OFRangeMake(OFNotFound, 0);
search = data.items;
- if (options & OF_DATA_SEARCH_BACKWARDS) {
+ if (options & OFDataSearchBackwards) {
for (size_t i = range.length - searchLength;; i--) {
if (memcmp(_items + i * _itemSize, search,
searchLength * _itemSize) == 0)
- return of_range(i, searchLength);
+ return OFRangeMake(i, searchLength);
/* No match and we're at the last item */
if (i == 0)
break;
}
@@ -580,14 +578,14 @@
} else {
for (size_t i = range.location;
i <= range.length - searchLength; i++)
if (memcmp(_items + i * _itemSize, search,
searchLength * _itemSize) == 0)
- return of_range(i, searchLength);
+ return OFRangeMake(i, searchLength);
}
- return of_range(OF_NOT_FOUND, 0);
+ return OFRangeMake(OFNotFound, 0);
}
#ifdef OF_HAVE_FILES
- (void)writeToFile: (OFString *)path
{
@@ -622,12 +620,12 @@
@throw [OFInvalidArgumentException exception];
pool = objc_autoreleasePoolPush();
element = [OFXMLElement
elementWithName: self.className
- namespace: OF_SERIALIZATION_NS
- stringValue: of_base64_encode(_items, _count * _itemSize)];
+ namespace: OFSerializationNS
+ stringValue: OFBase64Encode(_items, _count * _itemSize)];
[element retain];
objc_autoreleasePoolPop(pool);
@@ -648,18 +646,18 @@
data = [OFMutableData dataWithCapacity: _count + 2];
[data addItem: &type];
[data addItem: &tmp];
} else if (_count <= UINT16_MAX) {
uint8_t type = 0xC5;
- uint16_t tmp = OF_BSWAP16_IF_LE((uint16_t)_count);
+ uint16_t tmp = OFToBigEndian16((uint16_t)_count);
data = [OFMutableData dataWithCapacity: _count + 3];
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else if (_count <= UINT32_MAX) {
uint8_t type = 0xC6;
- uint32_t tmp = OF_BSWAP32_IF_LE((uint32_t)_count);
+ uint32_t tmp = OFToBigEndian32((uint32_t)_count);
data = [OFMutableData dataWithCapacity: _count + 5];
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else
Index: src/OFDatagramSocket.h
==================================================================
--- src/OFDatagramSocket.h
+++ src/OFDatagramSocket.h
@@ -14,12 +14,11 @@
*/
#import "OFObject.h"
#import "OFKernelEventObserver.h"
#import "OFRunLoop.h"
-
-#import "socket.h"
+#import "OFSocket.h"
OF_ASSUME_NONNULL_BEGIN
/** @file */
@@ -34,13 +33,12 @@
* @param sender The address of the sender of the packet
* @param exception An exception which occurred while receiving or `nil` on
* success
* @return A bool whether the same block should be used for the next receive
*/
-typedef bool (^of_datagram_socket_async_receive_block_t)(
- size_t length, const of_socket_address_t *_Nonnull sender,
- id _Nullable exception);
+typedef bool (^OFDatagramSocketAsyncReceiveBlock)(size_t length,
+ const OFSocketAddress *_Nonnull sender, id _Nullable exception);
/**
* @brief A block which is called when a packet has been sent.
*
* @param data The data which was sent
@@ -47,12 +45,12 @@
* @param receiver The receiver for the packet
* @param exception An exception which occurred while reading or `nil` on
* success
* @return The data to repeat the send with or nil if it should not repeat
*/
-typedef OFData *_Nullable (^of_datagram_socket_async_send_data_block_t)(
- OFData *_Nonnull data, const of_socket_address_t *_Nonnull receiver,
+typedef OFData *_Nullable (^OFDatagramSocketAsyncSendDataBlock)(
+ OFData *_Nonnull data, const OFSocketAddress *_Nonnull receiver,
id _Nullable exception);
#endif
/**
* @protocol OFDatagramSocketDelegate OFDatagramSocket.h \
@@ -74,11 +72,11 @@
* @return A bool whether the same block should be used for the next receive
*/
- (bool)socket: (OFDatagramSocket *)socket
didReceiveIntoBuffer: (void *)buffer
length: (size_t)length
- sender: (const of_socket_address_t *_Nonnull)sender
+ sender: (const OFSocketAddress *_Nonnull)sender
exception: (nullable id)exception;
/**
* @brief This method is called when a packet has been sent.
*
@@ -88,11 +86,11 @@
* @param exception An exception that occurred while sending, or nil on success
* @return The data to repeat the send with or nil if it should not repeat
*/
- (nullable OFData *)socket: (OFDatagramSocket *)socket
didSendData: (OFData *)data
- receiver: (const of_socket_address_t *_Nonnull)receiver
+ receiver: (const OFSocketAddress *_Nonnull)receiver
exception: (nullable id)exception;
@end
/**
* @class OFDatagramSocket OFDatagramSocket.h ObjFW/OFDatagramSocket.h
@@ -107,11 +105,11 @@
* was called to create one "instance" for every thread!
*/
@interface OFDatagramSocket: OFObject
{
- of_socket_t _socket;
+ OFSocketHandle _socket;
bool _canBlock;
#ifdef OF_WII
bool _canSendToBroadcastAddresses;
#endif
id _Nullable _delegate;
@@ -151,17 +149,17 @@
*
* If the buffer is too small, the datagram is truncated.
*
* @param buffer The buffer to write the datagram to
* @param length The length of the buffer
- * @param sender A pointer to an @ref of_socket_address_t, which will be set to
- * the address of the sender
+ * @param sender A pointer to an @ref OFSocketAddress, which will be set to the
+ * address of the sender
* @return The length of the received datagram
*/
- (size_t)receiveIntoBuffer: (void *)buffer
length: (size_t)length
- sender: (of_socket_address_t *)sender;
+ sender: (OFSocketAddress *)sender;
/**
* @brief Asynchronously receives a datagram and stores it into the specified
* buffer.
*
@@ -182,11 +180,11 @@
* @param length The length of the buffer
* @param runLoopMode The run loop mode in which to perform the async receive
*/
- (void)asyncReceiveIntoBuffer: (void *)buffer
length: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode;
+ runLoopMode: (OFRunLoopMode)runLoopMode;
#ifdef OF_HAVE_BLOCKS
/**
* @brief Asynchronously receives a datagram and stores it into the specified
* buffer.
@@ -202,11 +200,11 @@
* the datagram received next, you need to return false from the
* method.
*/
- (void)asyncReceiveIntoBuffer: (void *)buffer
length: (size_t)length
- block: (of_datagram_socket_async_receive_block_t)block;
+ block: (OFDatagramSocketAsyncReceiveBlock)block;
/**
* @brief Asynchronously receives a datagram and stores it into the specified
* buffer.
*
@@ -222,78 +220,78 @@
* the datagram received next, you need to return false from the
* method.
*/
- (void)asyncReceiveIntoBuffer: (void *)buffer
length: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_datagram_socket_async_receive_block_t)block;
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFDatagramSocketAsyncReceiveBlock)block;
#endif
/**
* @brief Sends the specified datagram to the specified address.
*
* @param buffer The buffer to send as a datagram
* @param length The length of the buffer
- * @param receiver A pointer to an @ref of_socket_address_t to which the
- * datagram should be sent
+ * @param receiver A pointer to an @ref OFSocketAddress to which the datagram
+ * should be sent
*/
- (void)sendBuffer: (const void *)buffer
length: (size_t)length
- receiver: (const of_socket_address_t *)receiver;
+ receiver: (const OFSocketAddress *)receiver;
/**
* @brief Asynchronously sends the specified datagram to the specified address.
*
* @param data The data to send as a datagram
- * @param receiver A pointer to an @ref of_socket_address_t to which the
- * datagram should be sent. The receiver is copied.
+ * @param receiver A pointer to an @ref OFSocketAddress to which the datagram
+ * should be sent. The receiver is copied.
*/
- (void)asyncSendData: (OFData *)data
- receiver: (const of_socket_address_t *)receiver;
+ receiver: (const OFSocketAddress *)receiver;
/**
* @brief Asynchronously sends the specified datagram to the specified address.
*
* @param data The data to send as a datagram
- * @param receiver A pointer to an @ref of_socket_address_t to which the
- * datagram should be sent. The receiver is copied.
+ * @param receiver A pointer to an @ref OFSocketAddress to which the datgram
+ * should be sent. The receiver is copied.
* @param runLoopMode The run loop mode in which to perform the async send
*/
- (void)asyncSendData: (OFData *)data
- receiver: (const of_socket_address_t *)receiver
- runLoopMode: (of_run_loop_mode_t)runLoopMode;
+ receiver: (const OFSocketAddress *)receiver
+ runLoopMode: (OFRunLoopMode)runLoopMode;
#ifdef OF_HAVE_BLOCKS
/**
* @brief Asynchronously sends the specified datagram to the specified address.
*
* @param data The data to send as a datagram
- * @param receiver A pointer to an @ref of_socket_address_t to which the
- * datagram should be sent. The receiver is copied.
+ * @param receiver A pointer to an @ref OFSocketAddress to which the datagram
+ * should be sent. The receiver is copied.
* @param block The block to call when the packet has been sent. It should
* return the data for the next send with the same callback or nil
* if it should not repeat.
*/
- (void)asyncSendData: (OFData *)data
- receiver: (const of_socket_address_t *)receiver
- block: (of_datagram_socket_async_send_data_block_t)block;
+ receiver: (const OFSocketAddress *)receiver
+ block: (OFDatagramSocketAsyncSendDataBlock)block;
/**
* @brief Asynchronously sends the specified datagram to the specified address.
*
* @param data The data to send as a datagram
- * @param receiver A pointer to an @ref of_socket_address_t to which the
- * datagram should be sent. The receiver is copied.
+ * @param receiver A pointer to an @ref OFSocketAddress to which the datagram
+ * should be sent. The receiver is copied.
* @param runLoopMode The run loop mode in which to perform the async send
* @param block The block to call when the packet has been sent. It should
* return the data for the next send with the same callback or nil
* if it should not repeat.
*/
- (void)asyncSendData: (OFData *)data
- receiver: (const of_socket_address_t *)receiver
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_datagram_socket_async_send_data_block_t)block;
+ receiver: (const OFSocketAddress *)receiver
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFDatagramSocketAsyncSendDataBlock)block;
#endif
/**
* @brief Cancels all pending asynchronous requests on the socket.
*/
Index: src/OFDatagramSocket.m
==================================================================
--- src/OFDatagramSocket.m
+++ src/OFDatagramSocket.m
@@ -26,12 +26,14 @@
# include
#endif
#import "OFDatagramSocket.h"
#import "OFData.h"
-#import "OFRunLoop+Private.h"
#import "OFRunLoop.h"
+#import "OFRunLoop+Private.h"
+#import "OFSocket.h"
+#import "OFSocket+Private.h"
#import "OFGetOptionFailedException.h"
#import "OFInitializationFailedException.h"
#import "OFNotOpenException.h"
#import "OFOutOfRangeException.h"
@@ -38,22 +40,19 @@
#import "OFReadFailedException.h"
#import "OFSetOptionFailedException.h"
#import "OFSetOptionFailedException.h"
#import "OFWriteFailedException.h"
-#import "socket.h"
-#import "socket_helpers.h"
-
@implementation OFDatagramSocket
@synthesize delegate = _delegate;
+ (void)initialize
{
if (self != [OFDatagramSocket class])
return;
- if (!of_socket_init())
+ if (!OFSocketInit())
@throw [OFInitializationFailedException
exceptionWithClass: self];
}
+ (instancetype)socket
@@ -69,11 +68,11 @@
if (self.class == [OFDatagramSocket class]) {
[self doesNotRecognizeSelector: _cmd];
abort();
}
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
_canBlock = true;
} @catch (id e) {
[self release];
@throw e;
}
@@ -81,11 +80,11 @@
return self;
}
- (void)dealloc
{
- if (_socket != INVALID_SOCKET)
+ if (_socket != OFInvalidSocketHandle)
[self close];
[super dealloc];
}
@@ -122,11 +121,11 @@
u_long v = canBlock;
if (ioctlsocket(_socket, FIONBIO, &v) == SOCKET_ERROR)
@throw [OFSetOptionFailedException
exceptionWithObject: self
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
_canBlock = canBlock;
#else
OF_UNRECOGNIZED_SELECTOR
#endif
@@ -138,11 +137,11 @@
if (setsockopt(_socket, SOL_SOCKET, SO_BROADCAST,
(char *)&v, (socklen_t)sizeof(v)) != 0)
@throw [OFSetOptionFailedException
exceptionWithObject: self
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
#ifdef OF_WII
_canSendToBroadcastAddresses = canSendToBroadcastAddresses;
#endif
}
@@ -155,25 +154,25 @@
if (getsockopt(_socket, SOL_SOCKET, SO_BROADCAST,
(char *)&v, &len) != 0 || len != sizeof(v))
@throw [OFGetOptionFailedException
exceptionWithObject: self
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
return v;
#else
return _canSendToBroadcastAddresses;
#endif
}
- (size_t)receiveIntoBuffer: (void *)buffer
length: (size_t)length
- sender: (of_socket_address_t *)sender
+ sender: (OFSocketAddress *)sender
{
ssize_t ret;
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
@throw [OFNotOpenException exceptionWithObject: self];
sender->length = (socklen_t)sizeof(sender->sockaddr);
#ifndef OF_WINDOWS
@@ -180,39 +179,39 @@
if ((ret = recvfrom(_socket, buffer, length, 0,
&sender->sockaddr.sockaddr, &sender->length)) < 0)
@throw [OFReadFailedException
exceptionWithObject: self
requestedLength: length
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
#else
if (length > INT_MAX)
@throw [OFOutOfRangeException exception];
if ((ret = recvfrom(_socket, buffer, (int)length, 0,
&sender->sockaddr.sockaddr, &sender->length)) < 0)
@throw [OFReadFailedException
exceptionWithObject: self
requestedLength: length
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
#endif
switch (sender->sockaddr.sockaddr.sa_family) {
case AF_INET:
- sender->family = OF_SOCKET_ADDRESS_FAMILY_IPV4;
+ sender->family = OFSocketAddressFamilyIPv4;
break;
#ifdef OF_HAVE_IPV6
case AF_INET6:
- sender->family = OF_SOCKET_ADDRESS_FAMILY_IPV6;
+ sender->family = OFSocketAddressFamilyIPv6;
break;
#endif
#ifdef OF_HAVE_IPX
case AF_IPX:
- sender->family = OF_SOCKET_ADDRESS_FAMILY_IPX;
+ sender->family = OFSocketAddressFamilyIPX;
break;
#endif
default:
- sender->family = OF_SOCKET_ADDRESS_FAMILY_UNKNOWN;
+ sender->family = OFSocketAddressFamilyUnknown;
break;
}
return ret;
}
@@ -219,16 +218,16 @@
- (void)asyncReceiveIntoBuffer: (void *)buffer length: (size_t)length
{
[self asyncReceiveIntoBuffer: buffer
length: length
- runLoopMode: of_run_loop_mode_default];
+ runLoopMode: OFDefaultRunLoopMode];
}
- (void)asyncReceiveIntoBuffer: (void *)buffer
length: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ runLoopMode: (OFRunLoopMode)runLoopMode
{
[OFRunLoop of_addAsyncReceiveForDatagramSocket: self
buffer: buffer
length: length
mode: runLoopMode
@@ -239,22 +238,22 @@
}
#ifdef OF_HAVE_BLOCKS
- (void)asyncReceiveIntoBuffer: (void *)buffer
length: (size_t)length
- block: (of_datagram_socket_async_receive_block_t)block
+ block: (OFDatagramSocketAsyncReceiveBlock)block
{
[self asyncReceiveIntoBuffer: buffer
length: length
- runLoopMode: of_run_loop_mode_default
+ runLoopMode: OFDefaultRunLoopMode
block: block];
}
- (void)asyncReceiveIntoBuffer: (void *)buffer
length: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_datagram_socket_async_receive_block_t)block
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFDatagramSocketAsyncReceiveBlock)block
{
[OFRunLoop of_addAsyncReceiveForDatagramSocket: self
buffer: buffer
length: length
mode: runLoopMode
@@ -263,13 +262,13 @@
}
#endif
- (void)sendBuffer: (const void *)buffer
length: (size_t)length
- receiver: (const of_socket_address_t *)receiver
+ receiver: (const OFSocketAddress *)receiver
{
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
@throw [OFNotOpenException exceptionWithObject: self];
#ifndef OF_WINDOWS
ssize_t bytesWritten;
@@ -281,11 +280,11 @@
receiver->length)) < 0)
@throw [OFWriteFailedException
exceptionWithObject: self
requestedLength: length
bytesWritten: 0
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
#else
int bytesWritten;
if (length > INT_MAX)
@throw [OFOutOfRangeException exception];
@@ -294,11 +293,11 @@
&receiver->sockaddr.sockaddr, receiver->length)) < 0)
@throw [OFWriteFailedException
exceptionWithObject: self
requestedLength: length
bytesWritten: 0
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
#endif
if ((size_t)bytesWritten != length)
@throw [OFWriteFailedException exceptionWithObject: self
requestedLength: length
@@ -305,20 +304,20 @@
bytesWritten: bytesWritten
errNo: 0];
}
- (void)asyncSendData: (OFData *)data
- receiver: (const of_socket_address_t *)receiver
+ receiver: (const OFSocketAddress *)receiver
{
[self asyncSendData: data
receiver: receiver
- runLoopMode: of_run_loop_mode_default];
+ runLoopMode: OFDefaultRunLoopMode];
}
- (void)asyncSendData: (OFData *)data
- receiver: (const of_socket_address_t *)receiver
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ receiver: (const OFSocketAddress *)receiver
+ runLoopMode: (OFRunLoopMode)runLoopMode
{
[OFRunLoop of_addAsyncSendForDatagramSocket: self
data: data
receiver: receiver
mode: runLoopMode
@@ -328,23 +327,23 @@
delegate: _delegate];
}
#ifdef OF_HAVE_BLOCKS
- (void)asyncSendData: (OFData *)data
- receiver: (const of_socket_address_t *)receiver
- block: (of_datagram_socket_async_send_data_block_t)block
+ receiver: (const OFSocketAddress *)receiver
+ block: (OFDatagramSocketAsyncSendDataBlock)block
{
[self asyncSendData: data
receiver: receiver
- runLoopMode: of_run_loop_mode_default
+ runLoopMode: OFDefaultRunLoopMode
block: block];
}
- (void)asyncSendData: (OFData *)data
- receiver: (const of_socket_address_t *)receiver
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_datagram_socket_async_send_data_block_t)block
+ receiver: (const OFSocketAddress *)receiver
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFDatagramSocketAsyncSendDataBlock)block
{
[OFRunLoop of_addAsyncSendForDatagramSocket: self
data: data
receiver: receiver
mode: runLoopMode
@@ -354,19 +353,19 @@
#endif
- (void)cancelAsyncRequests
{
[OFRunLoop of_cancelAsyncRequestsForObject: self
- mode: of_run_loop_mode_default];
+ mode: OFDefaultRunLoopMode];
}
- (int)fileDescriptorForReading
{
#ifndef OF_WINDOWS
return _socket;
#else
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
return -1;
if (_socket > INT_MAX)
@throw [OFOutOfRangeException exception];
@@ -377,11 +376,11 @@
- (int)fileDescriptorForWriting
{
#ifndef OF_WINDOWS
return _socket;
#else
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
return -1;
if (_socket > INT_MAX)
@throw [OFOutOfRangeException exception];
@@ -389,12 +388,12 @@
#endif
}
- (void)close
{
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
@throw [OFNotOpenException exceptionWithObject: self];
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
}
@end
Index: src/OFDate.h
==================================================================
--- src/OFDate.h
+++ src/OFDate.h
@@ -31,11 +31,11 @@
OF_SUBCLASSING_RESTRICTED
#endif
@interface OFDate: OFObject
{
- of_time_interval_t _seconds;
+ OFTimeInterval _seconds;
}
#ifdef OF_HAVE_CLASS_PROPERTIES
@property (class, readonly, nonatomic) OFDate *distantFuture;
@property (class, readonly, nonatomic) OFDate *distantPast;
@@ -122,16 +122,16 @@
@property (readonly, nonatomic) unsigned short localDayOfYear;
/**
* @brief The seconds since 1970-01-01T00:00:00Z.
*/
-@property (readonly, nonatomic) of_time_interval_t timeIntervalSince1970;
+@property (readonly, nonatomic) OFTimeInterval timeIntervalSince1970;
/**
* @brief The seconds the date is in the future.
*/
-@property (readonly, nonatomic) of_time_interval_t timeIntervalSinceNow;
+@property (readonly, nonatomic) OFTimeInterval timeIntervalSinceNow;
/**
* @brief Creates a new OFDate with the current date and time.
*
* @return A new, autoreleased OFDate with the current date and time
@@ -143,19 +143,19 @@
* 1970-01-01T00:00:00Z.
*
* @param seconds The seconds since 1970-01-01T00:00:00Z
* @return A new, autoreleased OFDate with the specified date and time
*/
-+ (instancetype)dateWithTimeIntervalSince1970: (of_time_interval_t)seconds;
++ (instancetype)dateWithTimeIntervalSince1970: (OFTimeInterval)seconds;
/**
* @brief Creates a new OFDate with the specified date and time since now.
*
* @param seconds The seconds since now
* @return A new, autoreleased OFDate with the specified date and time
*/
-+ (instancetype)dateWithTimeIntervalSinceNow: (of_time_interval_t)seconds;
++ (instancetype)dateWithTimeIntervalSinceNow: (OFTimeInterval)seconds;
/**
* @brief Creates a new OFDate with the specified string in the specified
* format.
*
@@ -215,21 +215,21 @@
* time since 1970-01-01T00:00:00Z.
*
* @param seconds The seconds since 1970-01-01T00:00:00Z
* @return An initialized OFDate with the specified date and time
*/
-- (instancetype)initWithTimeIntervalSince1970: (of_time_interval_t)seconds
+- (instancetype)initWithTimeIntervalSince1970: (OFTimeInterval)seconds
OF_DESIGNATED_INITIALIZER;
/**
* @brief Initializes an already allocated OFDate with the specified date and
* time since now.
*
* @param seconds The seconds since now
* @return An initialized OFDate with the specified date and time
*/
-- (instancetype)initWithTimeIntervalSinceNow: (of_time_interval_t)seconds;
+- (instancetype)initWithTimeIntervalSinceNow: (OFTimeInterval)seconds;
/**
* @brief Initializes an already allocated OFDate with the specified string in
* the specified format.
*
@@ -271,11 +271,11 @@
* @brief Compares the date to another date.
*
* @param date The date to compare the date to
* @return The result of the comparison
*/
-- (of_comparison_result_t)compare: (OFDate *)date;
+- (OFComparisonResult)compare: (OFDate *)date;
/**
* @brief Creates a string of the date with the specified format.
*
* See the man page for `strftime` for information on the format.
@@ -319,17 +319,17 @@
* @brief Returns the seconds the receiver is after the date.
*
* @param otherDate Date date to generate the difference with receiver
* @return The seconds the receiver is after the date.
*/
-- (of_time_interval_t)timeIntervalSinceDate: (OFDate *)otherDate;
+- (OFTimeInterval)timeIntervalSinceDate: (OFDate *)otherDate;
/**
* @brief Creates a new date with the specified time interval added.
*
* @param seconds The seconds after the date
* @return A new, autoreleased OFDate
*/
-- (OFDate *)dateByAddingTimeInterval: (of_time_interval_t)seconds;
+- (OFDate *)dateByAddingTimeInterval: (OFTimeInterval)seconds;
@end
OF_ASSUME_NONNULL_END
Index: src/OFDate.m
==================================================================
--- src/OFDate.m
+++ src/OFDate.m
@@ -28,10 +28,11 @@
#import "OFDictionary.h"
#import "OFMessagePackExtension.h"
#ifdef OF_HAVE_THREADS
# import "OFMutex.h"
#endif
+#import "OFStrPTime.h"
#import "OFString.h"
#import "OFSystemInfo.h"
#import "OFXMLElement.h"
#import "OFInitializationFailedException.h"
@@ -38,12 +39,10 @@
#import "OFInvalidArgumentException.h"
#import "OFInvalidFormatException.h"
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"
-#import "of_strptime.h"
-
#ifdef OF_AMIGAOS_M68K
/* amiga-gcc does not have trunc() */
# define trunc(x) ((int64_t)(x))
#endif
@@ -89,20 +88,20 @@
{
distantPast = [[OFDateSingleton alloc]
initWithTimeIntervalSince1970: -62167219200.0];
}
-static of_time_interval_t
+static OFTimeInterval
now(void)
{
struct timeval tv;
- of_time_interval_t seconds;
+ OFTimeInterval seconds;
- OF_ENSURE(gettimeofday(&tv, NULL) == 0);
+ OFEnsure(gettimeofday(&tv, NULL) == 0);
seconds = tv.tv_sec;
- seconds += (of_time_interval_t)tv.tv_usec / 1000000;
+ seconds += (OFTimeInterval)tv.tv_usec / 1000000;
return seconds;
}
#if (!defined(HAVE_GMTIME_R) || !defined(HAVE_LOCALTIME_R)) && \
@@ -115,16 +114,16 @@
[mutex release];
}
#endif
#ifdef OF_WINDOWS
-static __time64_t (*func__mktime64)(struct tm *);
+static __time64_t (*_mktime64FuncPtr)(struct tm *);
#endif
#ifdef HAVE_GMTIME_R
# define GMTIME_RET(field) \
- of_time_interval_t timeInterval = self.timeIntervalSince1970; \
+ OFTimeInterval timeInterval = self.timeIntervalSince1970; \
time_t seconds = (time_t)timeInterval; \
struct tm tm; \
\
if (seconds != trunc(timeInterval)) \
@throw [OFOutOfRangeException exception]; \
@@ -132,11 +131,11 @@
if (gmtime_r(&seconds, &tm) == NULL) \
@throw [OFOutOfRangeException exception]; \
\
return tm.field;
# define LOCALTIME_RET(field) \
- of_time_interval_t timeInterval = self.timeIntervalSince1970; \
+ OFTimeInterval timeInterval = self.timeIntervalSince1970; \
time_t seconds = (time_t)timeInterval; \
struct tm tm; \
\
if (seconds != trunc(timeInterval)) \
@throw [OFOutOfRangeException exception]; \
@@ -146,11 +145,11 @@
\
return tm.field;
#else
# ifdef OF_HAVE_THREADS
# define GMTIME_RET(field) \
- of_time_interval_t timeInterval = self.timeIntervalSince1970; \
+ OFTimeInterval timeInterval = self.timeIntervalSince1970; \
time_t seconds = (time_t)timeInterval; \
struct tm *tm; \
\
if (seconds != trunc(timeInterval)) \
@throw [OFOutOfRangeException exception]; \
@@ -164,11 +163,11 @@
return tm->field; \
} @finally { \
[mutex unlock]; \
}
# define LOCALTIME_RET(field) \
- of_time_interval_t timeInterval = self.timeIntervalSince1970; \
+ OFTimeInterval timeInterval = self.timeIntervalSince1970; \
time_t seconds = (time_t)timeInterval; \
struct tm *tm; \
\
if (seconds != trunc(timeInterval)) \
@throw [OFOutOfRangeException exception]; \
@@ -183,11 +182,11 @@
} @finally { \
[mutex unlock]; \
}
# else
# define GMTIME_RET(field) \
- of_time_interval_t timeInterval = self.timeIntervalSince1970; \
+ OFTimeInterval timeInterval = self.timeIntervalSince1970; \
time_t seconds = (time_t)timeInterval; \
struct tm *tm; \
\
if (seconds != trunc(timeInterval)) \
@throw [OFOutOfRangeException exception]; \
@@ -195,11 +194,11 @@
if ((tm = gmtime(&seconds)) == NULL) \
@throw [OFOutOfRangeException exception]; \
\
return tm->field;
# define LOCALTIME_RET(field) \
- of_time_interval_t timeInterval = self.timeIntervalSince1970; \
+ OFTimeInterval timeInterval = self.timeIntervalSince1970; \
time_t seconds = (time_t)timeInterval; \
struct tm *tm; \
\
if (seconds != trunc(timeInterval)) \
@throw [OFOutOfRangeException exception]; \
@@ -275,11 +274,11 @@
{
}
- (unsigned int)retainCount
{
- return OF_RETAIN_COUNT_MAX;
+ return OFMaxRetainCount;
}
@end
@implementation OFDatePlaceholder
#ifdef __clang__
@@ -286,24 +285,24 @@
/* We intentionally don't call into super, so silence the warning. */
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunknown-pragmas"
# pragma clang diagnostic ignored "-Wobjc-designated-initializers"
#endif
-- (instancetype)initWithTimeIntervalSince1970: (of_time_interval_t)seconds
+- (instancetype)initWithTimeIntervalSince1970: (OFTimeInterval)seconds
{
#if defined(OF_OBJFW_RUNTIME) && UINTPTR_MAX == UINT64_MAX
uint64_t value;
#endif
if (seconds == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, initZeroDate);
+ static OFOnceControl once = OFOnceControlInitValue;
+ OFOnce(&once, initZeroDate);
return (id)zeroDate;
}
#if defined(OF_OBJFW_RUNTIME) && UINTPTR_MAX == UINT64_MAX
- value = OF_BSWAP64_IF_LE(OF_DOUBLE_TO_INT_RAW(OF_BSWAP_DOUBLE_IF_LE(
+ value = OFFromBigEndian64(OFDoubleToRawUInt64(OFToBigEndianDouble(
seconds)));
/* Almost all dates fall into this range. */
if (value & (UINT64_C(4) << 60)) {
id ret = objc_createTaggedPointer(dateTag,
@@ -321,17 +320,17 @@
#endif
@end
#if defined(OF_OBJFW_RUNTIME) && UINTPTR_MAX == UINT64_MAX
@implementation OFTaggedPointerDate
-- (of_time_interval_t)timeIntervalSince1970
+- (OFTimeInterval)timeIntervalSince1970
{
uint64_t value = (uint64_t)object_getTaggedPointerValue(self);
value |= UINT64_C(4) << 60;
- return OF_BSWAP_DOUBLE_IF_LE(OF_INT_TO_DOUBLE_RAW(OF_BSWAP64_IF_LE(
+ return OFFromBigEndianDouble(OFRawUInt64ToDouble(OFToBigEndian64(
value)));
}
@end
#endif
@@ -353,11 +352,11 @@
atexit(releaseMutex);
#endif
#ifdef OF_WINDOWS
if ((module = LoadLibrary("msvcrt.dll")) != NULL)
- func__mktime64 = (__time64_t (*)(struct tm *))
+ _mktime64FuncPtr = (__time64_t (*)(struct tm *))
GetProcAddress(module, "_mktime64");
#endif
#if defined(OF_OBJFW_RUNTIME) && UINTPTR_MAX == UINT64_MAX
dateTag = objc_registerTaggedPointerClass([OFTaggedPointerDate class]);
@@ -380,17 +379,17 @@
+ (instancetype)date
{
return [[[self alloc] init] autorelease];
}
-+ (instancetype)dateWithTimeIntervalSince1970: (of_time_interval_t)seconds
++ (instancetype)dateWithTimeIntervalSince1970: (OFTimeInterval)seconds
{
return [[[self alloc]
initWithTimeIntervalSince1970: seconds] autorelease];
}
-+ (instancetype)dateWithTimeIntervalSinceNow: (of_time_interval_t)seconds
++ (instancetype)dateWithTimeIntervalSinceNow: (OFTimeInterval)seconds
{
return [[[self alloc]
initWithTimeIntervalSinceNow: seconds] autorelease];
}
@@ -408,37 +407,37 @@
format: format] autorelease];
}
+ (instancetype)distantFuture
{
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, initDistantFuture);
+ static OFOnceControl once = OFOnceControlInitValue;
+ OFOnce(&once, initDistantFuture);
return distantFuture;
}
+ (instancetype)distantPast
{
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, initDistantPast);
+ static OFOnceControl once = OFOnceControlInitValue;
+ OFOnce(&once, initDistantPast);
return distantPast;
}
- (instancetype)init
{
return [self initWithTimeIntervalSince1970: now()];
}
-- (instancetype)initWithTimeIntervalSince1970: (of_time_interval_t)seconds
+- (instancetype)initWithTimeIntervalSince1970: (OFTimeInterval)seconds
{
self = [super init];
_seconds = seconds;
return self;
}
-- (instancetype)initWithTimeIntervalSinceNow: (of_time_interval_t)seconds
+- (instancetype)initWithTimeIntervalSinceNow: (OFTimeInterval)seconds
{
return [self initWithTimeIntervalSince1970: now() + seconds];
}
- (instancetype)initWithDateString: (OFString *)string
@@ -447,11 +446,11 @@
void *pool = objc_autoreleasePoolPush();
const char *UTF8String = string.UTF8String;
struct tm tm = { .tm_isdst = -1 };
short tz = 0;
- if (of_strptime(UTF8String, format.UTF8String, &tm, &tz) !=
+ if (OFStrPTime(UTF8String, format.UTF8String, &tm, &tz) !=
UTF8String + string.UTF8StringLength)
@throw [OFInvalidFormatException exception];
objc_autoreleasePoolPop(pool);
@@ -463,25 +462,25 @@
{
void *pool = objc_autoreleasePoolPush();
const char *UTF8String = string.UTF8String;
struct tm tm = { .tm_isdst = -1 };
/*
- * of_strptime() can never set this to SHRT_MAX, no matter what is
+ * OFStrPTime() can never set this to SHRT_MAX, no matter what is
* passed to it, so this is a safe way to figure out if the date
* contains a time zone.
*/
short tz = SHRT_MAX;
- of_time_interval_t seconds;
+ OFTimeInterval seconds;
- if (of_strptime(UTF8String, format.UTF8String, &tm, &tz) !=
+ if (OFStrPTime(UTF8String, format.UTF8String, &tm, &tz) !=
UTF8String + string.UTF8StringLength)
@throw [OFInvalidFormatException exception];
if (tz == SHRT_MAX) {
#ifdef OF_WINDOWS
- if (func__mktime64 != NULL) {
- if ((seconds = func__mktime64(&tm)) == -1)
+ if (_mktime64FuncPtr != NULL) {
+ if ((seconds = _mktime64FuncPtr(&tm)) == -1)
@throw [OFInvalidFormatException exception];
} else {
#endif
if ((seconds = mktime(&tm)) == -1)
@throw [OFInvalidFormatException exception];
@@ -496,27 +495,27 @@
return [self initWithTimeIntervalSince1970: seconds];
}
- (instancetype)initWithSerialization: (OFXMLElement *)element
{
- of_time_interval_t seconds;
+ OFTimeInterval seconds;
@try {
void *pool = objc_autoreleasePoolPush();
unsigned long long value;
if (![element.name isEqual: @"OFDate"] ||
- ![element.namespace isEqual: OF_SERIALIZATION_NS])
+ ![element.namespace isEqual: OFSerializationNS])
@throw [OFInvalidArgumentException exception];
value = [element unsignedLongLongValueWithBase: 16];
if (value > UINT64_MAX)
@throw [OFOutOfRangeException exception];
- seconds = OF_BSWAP_DOUBLE_IF_LE(OF_INT_TO_DOUBLE_RAW(
- OF_BSWAP64_IF_LE(value)));
+ seconds = OFFromBigEndianDouble(OFRawUInt64ToDouble(
+ OFToBigEndian64(value)));
objc_autoreleasePoolPop(pool);
} @catch (id e) {
[self release];
@throw e;
@@ -543,41 +542,41 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
+ unsigned long hash;
double tmp;
- OF_HASH_INIT(hash);
+ OFHashInit(&hash);
- tmp = OF_BSWAP_DOUBLE_IF_BE(self.timeIntervalSince1970);
+ tmp = OFToLittleEndianDouble(self.timeIntervalSince1970);
for (size_t i = 0; i < sizeof(double); i++)
- OF_HASH_ADD(hash, ((char *)&tmp)[i]);
+ OFHashAdd(&hash, ((char *)&tmp)[i]);
- OF_HASH_FINALIZE(hash);
+ OFHashFinalize(&hash);
return hash;
}
- (id)copy
{
return [self retain];
}
-- (of_comparison_result_t)compare: (OFDate *)date
+- (OFComparisonResult)compare: (OFDate *)date
{
if (![date isKindOfClass: [OFDate class]])
@throw [OFInvalidArgumentException exception];
if (self.timeIntervalSince1970 < date.timeIntervalSince1970)
- return OF_ORDERED_ASCENDING;
+ return OFOrderedAscending;
if (self.timeIntervalSince1970 > date.timeIntervalSince1970)
- return OF_ORDERED_DESCENDING;
+ return OFOrderedDescending;
- return OF_ORDERED_SAME;
+ return OFOrderedSame;
}
- (OFString *)description
{
return [self dateStringWithFormat: @"%Y-%m-%dT%H:%M:%SZ"];
@@ -587,14 +586,14 @@
{
void *pool = objc_autoreleasePoolPush();
OFXMLElement *element;
element = [OFXMLElement elementWithName: @"OFDate"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
element.stringValue = [OFString stringWithFormat: @"%016" PRIx64,
- OF_BSWAP64_IF_LE(OF_DOUBLE_TO_INT_RAW(OF_BSWAP_DOUBLE_IF_LE(
+ OFFromBigEndian64(OFDoubleToRawUInt64(OFToBigEndianDouble(
self.timeIntervalSince1970)))];
[element retain];
objc_autoreleasePoolPop(pool);
@@ -603,11 +602,11 @@
}
- (OFData *)messagePackRepresentation
{
void *pool = objc_autoreleasePoolPush();
- of_time_interval_t timeInterval = self.timeIntervalSince1970;
+ OFTimeInterval timeInterval = self.timeIntervalSince1970;
int64_t seconds = (int64_t)timeInterval;
uint32_t nanoseconds =
(uint32_t)((timeInterval - trunc(timeInterval)) * 1000000000);
OFData *ret;
@@ -614,11 +613,11 @@
if (seconds >= 0 && seconds < 0x400000000) {
if (seconds <= UINT32_MAX && nanoseconds == 0) {
uint32_t seconds32 = (uint32_t)seconds;
OFData *data;
- seconds32 = OF_BSWAP32_IF_LE(seconds32);
+ seconds32 = OFToBigEndian32(seconds32);
data = [OFData dataWithItems: &seconds32
count: sizeof(seconds32)];
ret = [[OFMessagePackExtension
extensionWithType: -1
@@ -626,11 +625,11 @@
} else {
uint64_t combined = ((uint64_t)nanoseconds << 34) |
(uint64_t)seconds;
OFData *data;
- combined = OF_BSWAP64_IF_LE(combined);
+ combined = OFToBigEndian64(combined);
data = [OFData dataWithItems: &combined
count: sizeof(combined)];
ret = [[OFMessagePackExtension
extensionWithType: -1
@@ -637,13 +636,13 @@
data: data] messagePackRepresentation];
}
} else {
OFMutableData *data = [OFMutableData dataWithCapacity: 12];
- nanoseconds = OF_BSWAP32_IF_LE(nanoseconds);
+ nanoseconds = OFToBigEndian32(nanoseconds);
[data addItems: &nanoseconds count: sizeof(nanoseconds)];
- seconds = OF_BSWAP64_IF_LE(seconds);
+ seconds = OFToBigEndian64(seconds);
[data addItems: &seconds count: sizeof(seconds)];
ret = [[OFMessagePackExtension
extensionWithType: -1
data: data] messagePackRepresentation];
@@ -656,11 +655,11 @@
return [ret autorelease];
}
- (unsigned long)microsecond
{
- of_time_interval_t timeInterval = self.timeIntervalSince1970;
+ OFTimeInterval timeInterval = self.timeIntervalSince1970;
return (unsigned long)((timeInterval - trunc(timeInterval)) * 1000000);
}
- (unsigned char)second
@@ -739,11 +738,11 @@
}
- (OFString *)dateStringWithFormat: (OFConstantString *)format
{
OFString *ret;
- of_time_interval_t timeInterval = self.timeIntervalSince1970;
+ OFTimeInterval timeInterval = self.timeIntervalSince1970;
time_t seconds = (time_t)timeInterval;
struct tm tm;
size_t pageSize;
#ifndef OF_WINDOWS
char *buffer;
@@ -775,11 +774,11 @@
}
# endif
#endif
pageSize = [OFSystemInfo pageSize];
- buffer = of_alloc(1, pageSize);
+ buffer = OFAllocMemory(1, pageSize);
@try {
#ifndef OF_WINDOWS
if (strftime(buffer, pageSize, format.UTF8String, &tm) == 0)
@throw [OFOutOfRangeException exception];
@@ -790,20 +789,20 @@
@throw [OFOutOfRangeException exception];
ret = [OFString stringWithUTF16String: buffer];
#endif
} @finally {
- free(buffer);
+ OFFreeMemory(buffer);
}
return ret;
}
- (OFString *)localDateStringWithFormat: (OFConstantString *)format
{
OFString *ret;
- of_time_interval_t timeInterval = self.timeIntervalSince1970;
+ OFTimeInterval timeInterval = self.timeIntervalSince1970;
time_t seconds = (time_t)timeInterval;
struct tm tm;
size_t pageSize;
#ifndef OF_WINDOWS
char *buffer;
@@ -835,11 +834,11 @@
}
# endif
#endif
pageSize = [OFSystemInfo pageSize];
- buffer = of_alloc(1, pageSize);
+ buffer = OFAllocMemory(1, pageSize);
@try {
#ifndef OF_WINDOWS
if (strftime(buffer, pageSize, format.UTF8String, &tm) == 0)
@throw [OFOutOfRangeException exception];
@@ -850,11 +849,11 @@
@throw [OFOutOfRangeException exception];
ret = [OFString stringWithUTF16String: buffer];
#endif
} @finally {
- free(buffer);
+ OFFreeMemory(buffer);
}
return ret;
}
@@ -861,11 +860,11 @@
- (OFDate *)earlierDate: (OFDate *)otherDate
{
if (otherDate == nil)
return self;
- if ([self compare: otherDate] == OF_ORDERED_DESCENDING)
+ if ([self compare: otherDate] == OFOrderedDescending)
return otherDate;
return self;
}
@@ -872,40 +871,40 @@
- (OFDate *)laterDate: (OFDate *)otherDate
{
if (otherDate == nil)
return self;
- if ([self compare: otherDate] == OF_ORDERED_ASCENDING)
+ if ([self compare: otherDate] == OFOrderedAscending)
return otherDate;
return self;
}
-- (of_time_interval_t)timeIntervalSince1970
+- (OFTimeInterval)timeIntervalSince1970
{
return _seconds;
}
-- (of_time_interval_t)timeIntervalSinceDate: (OFDate *)otherDate
+- (OFTimeInterval)timeIntervalSinceDate: (OFDate *)otherDate
{
return self.timeIntervalSince1970 - otherDate.timeIntervalSince1970;
}
-- (of_time_interval_t)timeIntervalSinceNow
+- (OFTimeInterval)timeIntervalSinceNow
{
struct timeval t;
- of_time_interval_t seconds;
+ OFTimeInterval seconds;
- OF_ENSURE(gettimeofday(&t, NULL) == 0);
+ OFEnsure(gettimeofday(&t, NULL) == 0);
seconds = t.tv_sec;
- seconds += (of_time_interval_t)t.tv_usec / 1000000;
+ seconds += (OFTimeInterval)t.tv_usec / 1000000;
return self.timeIntervalSince1970 - seconds;
}
-- (OFDate *)dateByAddingTimeInterval: (of_time_interval_t)seconds
+- (OFDate *)dateByAddingTimeInterval: (OFTimeInterval)seconds
{
return [OFDate dateWithTimeIntervalSince1970:
self.timeIntervalSince1970 + seconds];
}
@end
Index: src/OFDictionary.h
==================================================================
--- src/OFDictionary.h
+++ src/OFDictionary.h
@@ -32,14 +32,13 @@
OF_ASSUME_NONNULL_BEGIN
@class OFArray OF_GENERIC(ObjectType);
#ifdef OF_HAVE_BLOCKS
-typedef void (^of_dictionary_enumeration_block_t)(id key, id object,
- bool *stop);
-typedef bool (^of_dictionary_filter_block_t)(id key, id object);
-typedef id _Nonnull (^of_dictionary_map_block_t)(id key, id object);
+typedef void (^OFDictionaryEnumerationBlock)(id key, id object, bool *stop);
+typedef bool (^OFDictionaryFilterBlock)(id key, id object);
+typedef id _Nonnull (^OFDictionaryMapBlock)(id key, id object);
#endif
/**
* @class OFDictionary OFDictionary.h ObjFW/OFDictionary.h
*
@@ -270,33 +269,32 @@
/**
* @brief Executes a block for each key / object pair.
*
* @param block The block to execute for each key / object pair.
*/
-- (void)enumerateKeysAndObjectsUsingBlock:
- (of_dictionary_enumeration_block_t)block;
+- (void)enumerateKeysAndObjectsUsingBlock: (OFDictionaryEnumerationBlock)block;
/**
* @brief Creates a new dictionary, mapping each object using the specified
* block.
*
* @param block A block which maps an object for each object
* @return A new autoreleased OFDictionary
*/
-- (OFDictionary OF_GENERIC(KeyType, id) *)mappedDictionaryUsingBlock:
- (of_dictionary_map_block_t)block;
+- (OFDictionary OF_GENERIC(KeyType, id) *)
+ mappedDictionaryUsingBlock: (OFDictionaryMapBlock)block;
/**
* @brief Creates a new dictionary, only containing the objects for which the
* block returns true.
*
* @param block A block which determines if the object should be in the new
* dictionary
* @return A new autoreleased OFDictionary
*/
-- (OFDictionary OF_GENERIC(KeyType, ObjectType) *)filteredDictionaryUsingBlock:
- (of_dictionary_filter_block_t)block;
+- (OFDictionary OF_GENERIC(KeyType, ObjectType) *)
+ filteredDictionaryUsingBlock: (OFDictionaryFilterBlock)block;
#endif
#if !defined(OF_HAVE_GENERICS) && !defined(DOXYGEN)
# undef KeyType
# undef ObjectType
#endif
Index: src/OFDictionary.m
==================================================================
--- src/OFDictionary.m
+++ src/OFDictionary.m
@@ -37,12 +37,13 @@
} placeholder;
static OFCharacterSet *URLQueryPartAllowedCharacterSet = nil;
@interface OFDictionary ()
-- (OFString *)of_JSONRepresentationWithOptions: (int)options
- depth: (size_t)depth;
+- (OFString *)
+ of_JSONRepresentationWithOptions: (OFJSONRepresentationOptions)options
+ depth: (size_t)depth;
@end
@interface OFDictionaryPlaceholder: OFDictionary
@end
@@ -169,16 +170,16 @@
{
}
- (unsigned int)retainCount
{
- return OF_RETAIN_COUNT_MAX;
+ return OFMaxRetainCount;
}
-- (bool)characterIsMember: (of_unichar_t)character
+- (bool)characterIsMember: (OFUnichar)character
{
- if (character < CHAR_MAX && of_ascii_isalnum(character))
+ if (character < CHAR_MAX && OFASCIIIsAlnum(character))
return true;
switch (character) {
case '-':
case '.':
@@ -505,11 +506,11 @@
{
return [[[OFDictionaryObjectEnumerator alloc]
initWithDictionary: self] autorelease];
}
-- (int)countByEnumeratingWithState: (of_fast_enumeration_state_t *)state
+- (int)countByEnumeratingWithState: (OFFastEnumerationState *)state
objects: (id *)objects
count: (int)count
{
OFEnumerator *enumerator;
int i;
@@ -535,12 +536,11 @@
return i;
}
#ifdef OF_HAVE_BLOCKS
-- (void)enumerateKeysAndObjectsUsingBlock:
- (of_dictionary_enumeration_block_t)block
+- (void)enumerateKeysAndObjectsUsingBlock: (OFDictionaryEnumerationBlock)block
{
bool stop = false;
for (id key in self) {
block(key, [self objectForKey: key], &stop);
@@ -548,11 +548,11 @@
if (stop)
break;
}
}
-- (OFDictionary *)mappedDictionaryUsingBlock: (of_dictionary_map_block_t)block
+- (OFDictionary *)mappedDictionaryUsingBlock: (OFDictionaryMapBlock)block
{
OFMutableDictionary *new = [OFMutableDictionary dictionary];
[self enumerateKeysAndObjectsUsingBlock: ^ (id key, id object,
bool *stop) {
@@ -562,12 +562,11 @@
[new makeImmutable];
return new;
}
-- (OFDictionary *)filteredDictionaryUsingBlock:
- (of_dictionary_filter_block_t)block
+- (OFDictionary *)filteredDictionaryUsingBlock: (OFDictionaryFilterBlock)block
{
OFMutableDictionary *new = [OFMutableDictionary dictionary];
[self enumerateKeysAndObjectsUsingBlock: ^ (id key, id object,
bool *stop) {
@@ -679,14 +678,14 @@
OFEnumerator *keyEnumerator, *objectEnumerator;
id key, object;
if ([self isKindOfClass: [OFMutableDictionary class]])
element = [OFXMLElement elementWithName: @"OFMutableDictionary"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
else
element = [OFXMLElement elementWithName: @"OFDictionary"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
keyEnumerator = [self keyEnumerator];
objectEnumerator = [self objectEnumerator];
while ((key = [keyEnumerator nextObject]) != nil &&
(object = [objectEnumerator nextObject]) != nil) {
@@ -693,16 +692,16 @@
void *pool2 = objc_autoreleasePoolPush();
OFXMLElement *keyElement, *objectElement;
keyElement = [OFXMLElement
elementWithName: @"key"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
[keyElement addChild: key.XMLElementBySerializing];
objectElement = [OFXMLElement
elementWithName: @"object"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
[objectElement addChild: object.XMLElementBySerializing];
[element addChild: keyElement];
[element addChild: objectElement];
@@ -719,26 +718,28 @@
- (OFString *)JSONRepresentation
{
return [self of_JSONRepresentationWithOptions: 0 depth: 0];
}
-- (OFString *)JSONRepresentationWithOptions: (int)options
+- (OFString *)JSONRepresentationWithOptions:
+ (OFJSONRepresentationOptions)options
{
return [self of_JSONRepresentationWithOptions: options depth: 0];
}
-- (OFString *)of_JSONRepresentationWithOptions: (int)options
- depth: (size_t)depth
+- (OFString *)
+ of_JSONRepresentationWithOptions: (OFJSONRepresentationOptions)options
+ depth: (size_t)depth
{
OFMutableString *JSON = [OFMutableString stringWithString: @"{"];
void *pool = objc_autoreleasePoolPush();
OFEnumerator *keyEnumerator = [self keyEnumerator];
OFEnumerator *objectEnumerator = [self objectEnumerator];
size_t i, count = self.count;
id key, object;
- if (options & OF_JSON_REPRESENTATION_PRETTY) {
+ if (options & OFJSONRepresentationOptionPretty) {
OFMutableString *indentation = [OFMutableString string];
for (i = 0; i < depth; i++)
[indentation appendString: @"\t"];
@@ -747,11 +748,11 @@
i = 0;
while ((key = [keyEnumerator nextObject]) != nil &&
(object = [objectEnumerator nextObject]) != nil) {
void *pool2 = objc_autoreleasePoolPush();
int identifierOptions =
- options | OF_JSON_REPRESENTATION_IDENTIFIER;
+ options | OFJSONRepresentationOptionIsIdentifier;
if (![key isKindOfClass: [OFString class]])
@throw [OFInvalidArgumentException exception];
[JSON appendString: indentation];
@@ -777,11 +778,11 @@
i = 0;
while ((key = [keyEnumerator nextObject]) != nil &&
(object = [objectEnumerator nextObject]) != nil) {
void *pool2 = objc_autoreleasePoolPush();
int identifierOptions =
- options | OF_JSON_REPRESENTATION_IDENTIFIER;
+ options | OFJSONRepresentationOptionIsIdentifier;
if (![key isKindOfClass: [OFString class]])
@throw [OFInvalidArgumentException exception];
[JSON appendString: [key
@@ -821,17 +822,17 @@
if (count <= 15) {
uint8_t tmp = 0x80 | ((uint8_t)count & 0xF);
[data addItem: &tmp];
} else if (count <= UINT16_MAX) {
uint8_t type = 0xDE;
- uint16_t tmp = OF_BSWAP16_IF_LE((uint16_t)count);
+ uint16_t tmp = OFToBigEndian16((uint16_t)count);
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else if (count <= UINT32_MAX) {
uint8_t type = 0xDF;
- uint32_t tmp = OF_BSWAP32_IF_LE((uint32_t)count);
+ uint32_t tmp = OFToBigEndian32((uint32_t)count);
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else
@throw [OFOutOfRangeException exception];
DELETED src/OFDimensionValue.h
Index: src/OFDimensionValue.h
==================================================================
--- src/OFDimensionValue.h
+++ src/OFDimensionValue.h
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) 2008-2021 Jonathan Schleifer
- *
- * All rights reserved.
- *
- * This file is part of ObjFW. It may be distributed under the terms of the
- * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
- * the packaging of this file.
- *
- * Alternatively, it may be distributed under the terms of the GNU General
- * Public License, either version 2 or 3, which can be found in the file
- * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
- * file.
- */
-
-#import "OFValue.h"
-
-OF_ASSUME_NONNULL_BEGIN
-
-@interface OFDimensionValue: OFValue
-{
- of_dimension_t _dimension;
-}
-@end
-
-OF_ASSUME_NONNULL_END
DELETED src/OFDimensionValue.m
Index: src/OFDimensionValue.m
==================================================================
--- src/OFDimensionValue.m
+++ src/OFDimensionValue.m
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2008-2021 Jonathan Schleifer
- *
- * All rights reserved.
- *
- * This file is part of ObjFW. It may be distributed under the terms of the
- * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
- * the packaging of this file.
- *
- * Alternatively, it may be distributed under the terms of the GNU General
- * Public License, either version 2 or 3, which can be found in the file
- * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
- * file.
- */
-
-#import "OFDimensionValue.h"
-#import "OFMethodSignature.h"
-#import "OFString.h"
-
-#import "OFOutOfRangeException.h"
-
-@implementation OFDimensionValue
-@synthesize dimensionValue = _dimension;
-
-- (instancetype)initWithDimension: (of_dimension_t)dimension
-{
- self = [super init];
-
- _dimension = dimension;
-
- return self;
-}
-
-- (const char *)objCType
-{
- return @encode(of_dimension_t);
-}
-
-- (void)getValue: (void *)value size: (size_t)size
-{
- if (size != sizeof(_dimension))
- @throw [OFOutOfRangeException exception];
-
- memcpy(value, &_dimension, sizeof(_dimension));
-}
-
-- (OFString *)description
-{
- return [OFString stringWithFormat:
- @"",
- _dimension.width, _dimension.height];
-}
-@end
Index: src/OFEnumerator.h
==================================================================
--- src/OFEnumerator.h
+++ src/OFEnumerator.h
@@ -44,15 +44,15 @@
*
* We need this bad check to see if we already imported Cocoa, which defines
* this as well.
*/
/**
- * @struct of_fast_enumeration_state_t OFEnumerator.h ObjFW/OFEnumerator.h
+ * @struct OFFastEnumerationState OFEnumerator.h ObjFW/OFEnumerator.h
*
* @brief State information for fast enumerations.
*/
-#define of_fast_enumeration_state_t NSFastEnumerationState
+#define OFFastEnumerationState NSFastEnumerationState
#ifndef NSINTEGER_DEFINED
typedef struct {
/** Arbitrary state information for the enumeration */
unsigned long state;
/** Pointer to a C array of objects to return */
@@ -59,11 +59,11 @@
id __unsafe_unretained _Nullable *_Nullable itemsPtr;
/** Arbitrary state information to detect mutations */
unsigned long *_Nullable mutationsPtr;
/** Additional arbitrary state information */
unsigned long extra[5];
-} of_fast_enumeration_state_t;
+} OFFastEnumerationState;
#endif
/**
* @protocol OFFastEnumeration OFEnumerator.h ObjFW/OFEnumerator.h
*
@@ -81,11 +81,11 @@
* @param objects A pointer to an array where to put the objects
* @param count The number of objects that can be stored at objects
* @return The number of objects returned in objects or 0 when the enumeration
* finished.
*/
-- (int)countByEnumeratingWithState: (of_fast_enumeration_state_t *)state
+- (int)countByEnumeratingWithState: (OFFastEnumerationState *)state
objects: (id __unsafe_unretained _Nonnull *_Nonnull)
objects
count: (int)count;
@end
Index: src/OFEnumerator.m
==================================================================
--- src/OFEnumerator.m
+++ src/OFEnumerator.m
@@ -55,11 +55,11 @@
objc_autoreleasePoolPop(pool);
return ret;
}
-- (int)countByEnumeratingWithState: (of_fast_enumeration_state_t *)state
+- (int)countByEnumeratingWithState: (OFFastEnumerationState *)state
objects: (id *)objects
count: (int)count
{
int i;
Index: src/OFEpollKernelEventObserver.m
==================================================================
--- src/OFEpollKernelEventObserver.m
+++ src/OFEpollKernelEventObserver.m
@@ -31,13 +31,13 @@
#import "OFNull.h"
#import "OFInitializationFailedException.h"
#import "OFObserveFailedException.h"
-#define EVENTLIST_SIZE 64
+#define eventListSize 64
-static const of_map_table_functions_t mapFunctions = { NULL };
+static const OFMapTableFunctions mapFunctions = { NULL };
@implementation OFEpollKernelEventObserver
- (instancetype)init
{
self = [super init];
@@ -185,20 +185,20 @@
events: EPOLLOUT];
[super removeObjectForWriting: object];
}
-- (void)observeForTimeInterval: (of_time_interval_t)timeInterval
+- (void)observeForTimeInterval: (OFTimeInterval)timeInterval
{
OFNull *nullObject = [OFNull null];
- struct epoll_event eventList[EVENTLIST_SIZE];
+ struct epoll_event eventList[eventListSize];
int events;
if ([self of_processReadBuffers])
return;
- events = epoll_wait(_epfd, eventList, EVENTLIST_SIZE,
+ events = epoll_wait(_epfd, eventList, eventListSize,
(timeInterval != -1 ? timeInterval * 1000 : -1));
if (events < 0)
@throw [OFObserveFailedException exceptionWithObserver: self
errNo: errno];
@@ -207,11 +207,11 @@
if (eventList[i].events & EPOLLIN) {
void *pool = objc_autoreleasePoolPush();
if (eventList[i].data.ptr == nullObject) {
char buffer;
- OF_ENSURE(read(_cancelFD[0], &buffer, 1) == 1);
+ OFEnsure(read(_cancelFD[0], &buffer, 1) == 1);
continue;
}
if ([_delegate respondsToSelector:
@selector(objectIsReadyForReading:)])
Index: src/OFFile.h
==================================================================
--- src/OFFile.h
+++ src/OFFile.h
@@ -16,15 +16,15 @@
#import "OFSeekableStream.h"
#import "OFKernelEventObserver.h"
#ifndef OF_AMIGAOS
# define OF_FILE_HANDLE_IS_FD
-# define OF_INVALID_FILE_HANDLE (-1)
-typedef int of_file_handle_t;
+typedef int OFFileHandle;
+static const OFFileHandle OFInvalidFileHandle = -1;
#else
-# define OF_INVALID_FILE_HANDLE NULL
-typedef struct of_file_handle *of_file_handle_t;
+typedef struct _OFFileHandle *OFFileHandle;
+static const OFFileHandle OFInvalidFileHandle = NULL;
#endif
OF_ASSUME_NONNULL_BEGIN
@class OFURL;
@@ -38,11 +38,11 @@
@interface OFFile: OFSeekableStream
#ifdef OF_FILE_HANDLE_IS_FD
#endif
{
- of_file_handle_t _handle;
+ OFFileHandle _handle;
bool _atEndOfStream;
}
/**
* @brief Creates a new OFFile with the specified path and mode.
@@ -91,11 +91,11 @@
* @param handle A native file handle. If OF_FILE_HANDLE_IS_FD is defined, this
* is a file descriptor. The handle is closed when the OFFile
* object is deallocated!
* @return A new autoreleased OFFile
*/
-+ (instancetype)fileWithHandle: (of_file_handle_t)handle;
++ (instancetype)fileWithHandle: (OFFileHandle)handle;
- (instancetype)init OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFFile.
@@ -151,10 +151,9 @@
* @param handle A native file handle. If OF_FILE_HANDLE_IS_FD is defined, this
* is a file descriptor. The handle is closed when the OFFile
* object is deallocated!
* @return An initialized OFFile
*/
-- (instancetype)initWithHandle: (of_file_handle_t)handle
- OF_DESIGNATED_INITIALIZER;
+- (instancetype)initWithHandle: (OFFileHandle)handle OF_DESIGNATED_INITIALIZER;
@end
OF_ASSUME_NONNULL_END
Index: src/OFFile.m
==================================================================
--- src/OFFile.m
+++ src/OFFile.m
@@ -77,18 +77,18 @@
#endif
#ifndef OF_AMIGAOS
# define closeHandle(h) close(h)
#else
-static struct of_file_handle {
- of_file_handle_t previous, next;
+static struct _OFFileHandle
+ struct _OFFileHandle *previous, *next;
BPTR handle;
bool append;
} *firstHandle = NULL;
static void
-closeHandle(of_file_handle_t handle)
+closeHandle(OFFileHandle handle)
{
Close(handle->handle);
if (handle->previous != NULL)
handle->previous->next = handle->next;
@@ -96,16 +96,16 @@
handle->next->previous = handle->previous;
if (firstHandle == handle)
firstHandle = handle->next;
- free(handle);
+ OFFreeMemory(handle);
}
OF_DESTRUCTOR()
{
- for (of_file_handle_t iter = firstHandle; iter != NULL;
+ for (OFFileHandle iter = firstHandle; iter != NULL;
iter = iter->next)
Close(iter->handle);
}
#endif
@@ -190,11 +190,11 @@
+ (instancetype)fileWithURL: (OFURL *)URL mode: (OFString *)mode
{
return [[[self alloc] initWithURL: URL mode: mode] autorelease];
}
-+ (instancetype)fileWithHandle: (of_file_handle_t)handle
++ (instancetype)fileWithHandle: (OFFileHandle)handle
{
return [[[self alloc] initWithHandle: handle] autorelease];
}
- (instancetype)init
@@ -202,11 +202,11 @@
OF_INVALID_INIT_METHOD
}
- (instancetype)initWithPath: (OFString *)path mode: (OFString *)mode
{
- of_file_handle_t handle;
+ OFFileHandle handle;
@try {
void *pool = objc_autoreleasePoolPush();
int flags;
@@ -236,11 +236,11 @@
@throw [OFOpenItemFailedException
exceptionWithPath: path
mode: mode
errNo: errno];
#else
- handle = of_alloc(1, sizeof(*handle));
+ handle = OFAllocMemory(1, sizeof(*handle));
@try {
if ((flags = parseMode(mode.UTF8String,
&handle->append)) == -1)
@throw [OFInvalidArgumentException exception];
@@ -298,11 +298,11 @@
if (firstHandle != NULL)
firstHandle->previous = handle;
firstHandle = handle;
} @catch (id e) {
- free(handle);
+ OFFreeMemory(handle);
@throw e;
}
#endif
objc_autoreleasePoolPop(pool);
@@ -338,11 +338,11 @@
objc_autoreleasePoolPop(pool);
return self;
}
-- (instancetype)initWithHandle: (of_file_handle_t)handle
+- (instancetype)initWithHandle: (OFFileHandle)handle
{
self = [super init];
_handle = handle;
@@ -349,21 +349,21 @@
return self;
}
- (bool)lowlevelIsAtEndOfStream
{
- if (_handle == OF_INVALID_FILE_HANDLE)
+ if (_handle == OFInvalidFileHandle)
@throw [OFNotOpenException exceptionWithObject: self];
return _atEndOfStream;
}
- (size_t)lowlevelReadIntoBuffer: (void *)buffer length: (size_t)length
{
ssize_t ret;
- if (_handle == OF_INVALID_FILE_HANDLE)
+ if (_handle == OFInvalidFileHandle)
@throw [OFNotOpenException exceptionWithObject: self];
#if defined(OF_WINDOWS)
if (length > UINT_MAX)
@throw [OFOutOfRangeException exception];
@@ -393,11 +393,11 @@
return ret;
}
- (size_t)lowlevelWriteBuffer: (const void *)buffer length: (size_t)length
{
- if (_handle == OF_INVALID_FILE_HANDLE)
+ if (_handle == OFInvalidFileHandle)
@throw [OFNotOpenException exceptionWithObject: self];
#if defined(OF_WINDOWS)
int bytesWritten;
@@ -449,15 +449,15 @@
#endif
return (size_t)bytesWritten;
}
-- (of_offset_t)lowlevelSeekToOffset: (of_offset_t)offset whence: (int)whence
+- (OFFileOffset)lowlevelSeekToOffset: (OFFileOffset)offset whence: (int)whence
{
- of_offset_t ret;
+ OFFileOffset ret;
- if (_handle == OF_INVALID_FILE_HANDLE)
+ if (_handle == OFInvalidFileHandle)
@throw [OFNotOpenException exceptionWithObject: self];
#ifndef OF_AMIGAOS
# if defined(OF_WINDOWS)
ret = _lseeki64(_handle, offset, whence);
@@ -523,22 +523,22 @@
}
#endif
- (void)close
{
- if (_handle == OF_INVALID_FILE_HANDLE)
+ if (_handle == OFInvalidFileHandle)
@throw [OFNotOpenException exceptionWithObject: self];
closeHandle(_handle);
- _handle = OF_INVALID_FILE_HANDLE;
+ _handle = OFInvalidFileHandle;
[super close];
}
- (void)dealloc
{
- if (_handle != OF_INVALID_FILE_HANDLE)
+ if (_handle != OFInvalidFileHandle)
[self close];
[super dealloc];
}
@end
Index: src/OFFileManager.h
==================================================================
--- src/OFFileManager.h
+++ src/OFFileManager.h
@@ -44,57 +44,57 @@
/**
* @brief A key for a file attribute in the file attributes dictionary.
*
* Possible keys for file URLs are:
*
- * * @ref of_file_attribute_key_size
- * * @ref of_file_attribute_key_type
- * * @ref of_file_attribute_key_posix_permissions
- * * @ref of_file_attribute_key_posix_uid
- * * @ref of_file_attribute_key_posix_gid
- * * @ref of_file_attribute_key_owner
- * * @ref of_file_attribute_key_group
- * * @ref of_file_attribute_key_last_access_date
- * * @ref of_file_attribute_key_modification_date
- * * @ref of_file_attribute_key_status_change_date
- * * @ref of_file_attribute_key_creation_date
- * * @ref of_file_attribute_key_symbolic_link_destination
+ * * @ref OFFileSize
+ * * @ref OFFileType
+ * * @ref OFFilePOSIXPermissions
+ * * @ref OFFileOwnerAccountID
+ * * @ref OFFileGroupOwnerAccountID
+ * * @ref OFFileOwnerAccountName
+ * * @ref OFFileGroupOwnerAccountName
+ * * @ref OFFileLastAccessDate
+ * * @ref OFFileModificationDate
+ * * @ref OFFileStatusChangeDate
+ * * @ref OFFileCreationDate
+ * * @ref OFFileSymbolicLinkDestination
*
* Other URL schemes might not have all keys and might have keys not listed.
*/
-typedef OFConstantString *of_file_attribute_key_t;
+typedef OFConstantString *OFFileAttributeKey;
/**
* @brief The type of a file.
*
* Possibles values for file URLs are:
*
- * * @ref of_file_type_regular
- * * @ref of_file_type_directory
- * * @ref of_file_type_symbolic_link
- * * @ref of_file_type_fifo
- * * @ref of_file_type_character_special
- * * @ref of_file_type_block_special
- * * @ref of_file_type_socket
+ * * @ref OFFileTypeRegular
+ * * @ref OFFileTypeDirectory
+ * * @ref OFFileTypeSymbolicLink
+ * * @ref OFFileTypeFIFO
+ * * @ref OFFileTypeCharacterSpecial
+ * * @ref OFFileTypeBlockSpecial
+ * * @ref OFFileTypeSocket
+ * * @ref OFFileTypeUnknown
*
* Other URL schemes might not have all types and might have types not listed.
*/
-typedef OFConstantString *of_file_type_t;
-
-/**
- * @brief A dictionary mapping keys of type @ref of_file_attribute_key_t
- * to their attribute values.
- */
-typedef OFDictionary OF_GENERIC(of_file_attribute_key_t, id)
- *of_file_attributes_t;
-
-/**
- * @brief A mutable dictionary mapping keys of type
- * @ref of_file_attribute_key_t to their attribute values.
- */
-typedef OFMutableDictionary OF_GENERIC(of_file_attribute_key_t, id)
- *of_mutable_file_attributes_t;
+typedef OFConstantString *OFFileAttributeType;
+
+/**
+ * @brief A dictionary mapping keys of type @ref OFFileAttributeKey to their
+ * attribute values.
+ */
+typedef OFDictionary OF_GENERIC(OFFileAttributeKey, id) *OFFileAttributes;
+
+/**
+ * @brief A mutable dictionary mapping keys of type @ref OFFileAttributeKey to
+ * their attribute values.
+ */
+typedef OFMutableDictionary OF_GENERIC(OFFileAttributeKey, id)
+ *OFMutableFileAttributes;
#ifdef __cplusplus
extern "C" {
#endif
/**
@@ -101,137 +101,145 @@
* @brief The size of the file as an @ref OFNumber.
*
* For convenience, a category on @ref OFDictionary is provided to access this
* via @ref OFDictionary#fileSize.
*/
-extern const of_file_attribute_key_t of_file_attribute_key_size;
+extern const OFFileAttributeKey OFFileSize;
/**
* @brief The type of the file.
*
- * The corresponding value is of type @ref of_file_type_t.
+ * The corresponding value is of type @ref OFFileAttributeType.
*
* For convenience, a category on @ref OFDictionary is provided to access this
* via @ref OFDictionary#fileType.
*/
-extern const of_file_attribute_key_t of_file_attribute_key_type;
+extern const OFFileAttributeKey OFFileType;
/**
* @brief The POSIX permissions of the file as an @ref OFNumber.
*
* For convenience, a category on @ref OFDictionary is provided to access this
* via @ref OFDictionary#filePOSIXPermissions.
*/
-extern const of_file_attribute_key_t of_file_attribute_key_posix_permissions;
-
-/**
- * @brief The POSIX UID of the file as an @ref OFNumber.
- *
- * For convenience, a category on @ref OFDictionary is provided to access this
- * via @ref OFDictionary#filePOSIXUID.
- */
-extern const of_file_attribute_key_t of_file_attribute_key_posix_uid;
-
-/**
- * @brief The POSIX GID of the file as an @ref OFNumber.
- *
- * For convenience, a category on @ref OFDictionary is provided to access this
- * via @ref OFDictionary#filePOSIXGID.
- */
-extern const of_file_attribute_key_t of_file_attribute_key_posix_gid;
-
-/**
- * @brief The owner of the file as an OFString.
- *
- * For convenience, a category on @ref OFDictionary is provided to access this
- * via @ref OFDictionary#fileOwner.
- */
-extern const of_file_attribute_key_t of_file_attribute_key_owner;
-
-/**
- * @brief The group of the file as an OFString.
- *
- * For convenience, a category on @ref OFDictionary is provided to access this
- * via @ref OFDictionary#fileGroup.
- */
-extern const of_file_attribute_key_t of_file_attribute_key_group;
+extern const OFFileAttributeKey OFFilePOSIXPermissions;
+
+/**
+ * @brief The account ID of the owner of the file as an @ref OFNumber.
+ *
+ * For convenience, a category on @ref OFDictionary is provided to access this
+ * via @ref OFDictionary#fileOwnerAccountID.
+ */
+extern const OFFileAttributeKey OFFileOwnerAccountID;
+
+/**
+ * @brief The account ID of the group owner of the file as an @ref OFNumber.
+ *
+ * For convenience, a category on @ref OFDictionary is provided to access this
+ * via @ref OFDictionary#fileGroupOwnerAccountID.
+ */
+extern const OFFileAttributeKey OFFileGroupOwnerAccountID;
+
+/**
+ * @brief The account name of the owner of the file as an OFString.
+ *
+ * For convenience, a category on @ref OFDictionary is provided to access this
+ * via @ref OFDictionary#fileOwnerAccountName.
+ */
+extern const OFFileAttributeKey OFFileOwnerAccountName;
+
+/**
+ * @brief The account name of the group owner of the file as an OFString.
+ *
+ * For convenience, a category on @ref OFDictionary is provided to access this
+ * via @ref OFDictionary#fileGroupOwnerAccountName.
+ */
+extern const OFFileAttributeKey OFFileGroupOwnerAccountName;
/**
* @brief The last access date of the file as an @ref OFDate.
*
* For convenience, a category on @ref OFDictionary is provided to access this
* via @ref OFDictionary#fileLastAccessDate.
*/
-extern const of_file_attribute_key_t of_file_attribute_key_last_access_date;
+extern const OFFileAttributeKey OFFileLastAccessDate;
/**
* @brief The last modification date of the file as an @ref OFDate.
*
* For convenience, a category on @ref OFDictionary is provided to access this
* via @ref OFDictionary#fileModificationDate.
*/
-extern const of_file_attribute_key_t of_file_attribute_key_modification_date;
+extern const OFFileAttributeKey OFFileModificationDate;
/**
* @brief The last status change date of the file as an @ref OFDate.
*
* For convenience, a category on @ref OFDictionary is provided to access this
* via @ref OFDictionary#fileStatusChangeDate.
*/
-extern const of_file_attribute_key_t of_file_attribute_key_status_change_date;
+extern const OFFileAttributeKey OFFileStatusChangeDate;
/**
* @brief The creation date of the file as an @ref OFDate.
*
* For convenience, a category on @ref OFDictionary is provided to access this
* via @ref OFDictionary#fileCreationDate.
*/
-extern const of_file_attribute_key_t of_file_attribute_key_creation_date;
+extern const OFFileAttributeKey OFFileCreationDate;
/**
* @brief The destination of a symbolic link as an OFString.
*
* For convenience, a category on @ref OFDictionary is provided to access this
* via @ref OFDictionary#fileSymbolicLinkDestination.
*/
-extern const of_file_attribute_key_t
- of_file_attribute_key_symbolic_link_destination;
+extern const OFFileAttributeKey OFFileSymbolicLinkDestination;
/**
* @brief A regular file.
*/
-extern const of_file_type_t of_file_type_regular;
+extern const OFFileAttributeType OFFileTypeRegular;
/**
* @brief A directory.
*/
-extern const of_file_type_t of_file_type_directory;
+extern const OFFileAttributeType OFFileTypeDirectory;
/**
* @brief A symbolic link.
*/
-extern const of_file_type_t of_file_type_symbolic_link;
+extern const OFFileAttributeType OFFileTypeSymbolicLink;
/**
* @brief A FIFO.
*/
-extern const of_file_type_t of_file_type_fifo;
+extern const OFFileAttributeType OFFileTypeFIFO;
/**
* @brief A character special file.
*/
-extern const of_file_type_t of_file_type_character_special;
+extern const OFFileAttributeType OFFileTypeCharacterSpecial;
/**
* @brief A block special file.
*/
-extern const of_file_type_t of_file_type_block_special;
+extern const OFFileAttributeType OFFileTypeBlockSpecial;
/**
* @brief A socket.
*/
-extern const of_file_type_t of_file_type_socket;
+extern const OFFileAttributeType OFFileTypeSocket;
+
+/**
+ * @brief An unknown file type.
+ *
+ * This is different from not having an @ref OFFileType at all in that it means
+ * that retrieving file types is supported, but the particular file type is
+ * unknown.
+ */
+extern const OFFileAttributeType OFFileTypeUnknown;
#ifdef __cplusplus
}
#endif
/**
@@ -269,23 +277,23 @@
/**
* @brief Returns the attributes for the item at the specified path.
*
* @param path The path to return the attributes for
* @return A dictionary of attributes for the specified path, with the keys of
- * type @ref of_file_attribute_key_t
+ * type @ref OFFileAttributeKey
*/
-- (of_file_attributes_t)attributesOfItemAtPath: (OFString *)path;
+- (OFFileAttributes)attributesOfItemAtPath: (OFString *)path;
#endif
/**
* @brief Returns the attributes for the item at the specified URL.
*
* @param URL The URL to return the attributes for
* @return A dictionary of attributes for the specified URL, with the keys of
- * type @ref of_file_attribute_key_t
+ * type @ref OFFileAttributeKey
*/
-- (of_file_attributes_t)attributesOfItemAtURL: (OFURL *)URL;
+- (OFFileAttributes)attributesOfItemAtURL: (OFURL *)URL;
#ifdef OF_HAVE_FILES
/**
* @brief Sets the attributes for the item at the specified path.
*
@@ -292,11 +300,11 @@
* All attributes not part of the dictionary are left unchanged.
*
* @param attributes The attributes to set for the specified path
* @param path The path of the item to set the attributes for
*/
-- (void)setAttributes: (of_file_attributes_t)attributes
+- (void)setAttributes: (OFFileAttributes)attributes
ofItemAtPath: (OFString *)path;
#endif
/**
* @brief Sets the attributes for the item at the specified URL.
@@ -304,12 +312,11 @@
* All attributes not part of the dictionary are left unchanged.
*
* @param attributes The attributes to set for the specified URL
* @param URL The URL of the item to set the attributes for
*/
-- (void)setAttributes: (of_file_attributes_t)attributes
- ofItemAtURL: (OFURL *)URL;
+- (void)setAttributes: (OFFileAttributes)attributes ofItemAtURL: (OFURL *)URL;
#ifdef OF_HAVE_FILES
/**
* @brief Checks whether a file exists at the specified path.
*
@@ -564,95 +571,90 @@
withDestinationPath: (OFString *)target;
@end
@interface OFDictionary (FileAttributes)
/**
- * @brief The @ref of_file_attribute_key_size key from the dictionary.
+ * @brief The @ref OFFileSize key from the dictionary.
*
* Raises an @ref OFUndefinedKeyException if the key is missing.
*/
@property (readonly, nonatomic) unsigned long long fileSize;
/**
- * @brief The @ref of_file_attribute_key_type key from the dictionary.
+ * @brief The @ref OFFileType key from the dictionary.
*
* Raises an @ref OFUndefinedKeyException if the key is missing.
*/
-@property (readonly, nonatomic) of_file_type_t fileType;
+@property (readonly, nonatomic) OFFileAttributeType fileType;
/**
- * @brief The @ref of_file_attribute_key_posix_permissions key from the
- * dictionary.
+ * @brief The @ref OFFilePOSIXPermissions key from the dictionary.
*
* Raises an @ref OFUndefinedKeyException if the key is missing.
*/
@property (readonly, nonatomic) unsigned long filePOSIXPermissions;
/**
- * @brief The @ref of_file_attribute_key_posix_uid key from the dictionary.
- *
- * Raises an @ref OFUndefinedKeyException if the key is missing.
- */
-@property (readonly, nonatomic) unsigned long filePOSIXUID;
-
-/**
- * @brief The @ref of_file_attribute_key_posix_gid key from the dictionary.
- *
- * Raises an @ref OFUndefinedKeyException if the key is missing.
- */
-@property (readonly, nonatomic) unsigned long filePOSIXGID;
-
-/**
- * @brief The @ref of_file_attribute_key_owner key from the dictionary.
- *
- * Raises an @ref OFUndefinedKeyException if the key is missing.
- */
-@property (readonly, nonatomic) OFString *fileOwner;
-
-/**
- * @brief The @ref of_file_attribute_key_group key from the dictionary.
- *
- * Raises an @ref OFUndefinedKeyException if the key is missing.
- */
-@property (readonly, nonatomic) OFString *fileGroup;
-
-/**
- * @brief The @ref of_file_attribute_key_last_access_date key from the
- * dictionary.
+ * @brief The @ref OFFileOwnerAccountID key from the dictionary.
+ *
+ * Raises an @ref OFUndefinedKeyException if the key is missing.
+ */
+@property (readonly, nonatomic) unsigned long fileOwnerAccountID;
+
+/**
+ * @brief The @ref OFFileGroupOwnerAccountID key from the dictionary.
+ *
+ * Raises an @ref OFUndefinedKeyException if the key is missing.
+ */
+@property (readonly, nonatomic) unsigned long fileGroupOwnerAccountID;
+
+/**
+ * @brief The @ref OFFileOwnerAccountName key from the dictionary.
+ *
+ * Raises an @ref OFUndefinedKeyException if the key is missing.
+ */
+@property (readonly, nonatomic) OFString *fileOwnerAccountName;
+
+/**
+ * @brief The @ref OFFileGroupOwnerAccountName key from the dictionary.
+ *
+ * Raises an @ref OFUndefinedKeyException if the key is missing.
+ */
+@property (readonly, nonatomic) OFString *fileGroupOwnerAccountName;
+
+/**
+ * @brief The @ref OFFileLastAccessDate key from the dictionary.
*
* Raises an @ref OFUndefinedKeyException if the key is missing.
*/
@property (readonly, nonatomic) OFDate *fileLastAccessDate;
/**
- * @brief The @ref of_file_attribute_key_modification_date key from the
- * dictionary.
+ * @brief The @ref OFFileModificationDate key from the dictionary.
*
* Raises an @ref OFUndefinedKeyException if the key is missing.
*/
@property (readonly, nonatomic) OFDate *fileModificationDate;
/**
- * @brief The @ref of_file_attribute_key_status_change_date key from the
- * dictionary.
+ * @brief The @ref OFFileStatusChangeDate key from the dictionary.
*
* Raises an @ref OFUndefinedKeyException if the key is missing.
*/
@property (readonly, nonatomic) OFDate *fileStatusChangeDate;
/**
- * @brief The @ref of_file_attribute_key_creation_date key from the dictionary.
+ * @brief The @ref OFFileCreationDate key from the dictionary.
*
* Raises an @ref OFUndefinedKeyException if the key is missing.
*/
@property (readonly, nonatomic) OFDate *fileCreationDate;
/**
- * @brief The @ref of_file_attribute_key_symbolic_link_destination key from the
- * dictionary.
+ * @brief The @ref OFFileSymbolicLinkDestination key from the dictionary.
*
* Raises an @ref OFUndefinedKeyException if the key is missing.
*/
@property (readonly, nonatomic) OFString *fileSymbolicLinkDestination;
@end
OF_ASSUME_NONNULL_END
Index: src/OFFileManager.m
==================================================================
--- src/OFFileManager.m
+++ src/OFFileManager.m
@@ -69,43 +69,35 @@
#endif
@interface OFDefaultFileManager: OFFileManager
@end
-const of_file_attribute_key_t of_file_attribute_key_size =
- @"of_file_attribute_key_size";
-const of_file_attribute_key_t of_file_attribute_key_type =
- @"of_file_attribute_key_type";
-const of_file_attribute_key_t of_file_attribute_key_posix_permissions =
- @"of_file_attribute_key_posix_permissions";
-const of_file_attribute_key_t of_file_attribute_key_posix_uid =
- @"of_file_attribute_key_posix_uid";
-const of_file_attribute_key_t of_file_attribute_key_posix_gid =
- @"of_file_attribute_key_posix_gid";
-const of_file_attribute_key_t of_file_attribute_key_owner =
- @"of_file_attribute_key_owner";
-const of_file_attribute_key_t of_file_attribute_key_group =
- @"of_file_attribute_key_group";
-const of_file_attribute_key_t of_file_attribute_key_last_access_date =
- @"of_file_attribute_key_last_access_date";
-const of_file_attribute_key_t of_file_attribute_key_modification_date =
- @"of_file_attribute_key_modification_date";
-const of_file_attribute_key_t of_file_attribute_key_status_change_date =
- @"of_file_attribute_key_status_change_date";
-const of_file_attribute_key_t of_file_attribute_key_creation_date =
- @"of_file_attribute_key_creation_date";
-const of_file_attribute_key_t of_file_attribute_key_symbolic_link_destination =
- @"of_file_attribute_key_symbolic_link_destination";
-
-const of_file_type_t of_file_type_regular = @"of_file_type_regular";
-const of_file_type_t of_file_type_directory = @"of_file_type_directory";
-const of_file_type_t of_file_type_symbolic_link = @"of_file_type_symbolic_link";
-const of_file_type_t of_file_type_fifo = @"of_file_type_fifo";
-const of_file_type_t of_file_type_character_special =
- @"of_file_type_character_special";
-const of_file_type_t of_file_type_block_special = @"of_file_type_block_special";
-const of_file_type_t of_file_type_socket = @"of_file_type_socket";
+const OFFileAttributeKey OFFileSize = @"OFFileSize";
+const OFFileAttributeKey OFFileType = @"OFFileType";
+const OFFileAttributeKey OFFilePOSIXPermissions = @"OFFilePOSIXPermissions";
+const OFFileAttributeKey OFFileOwnerAccountID = @"OFFileOwnerAccountID";
+const OFFileAttributeKey OFFileGroupOwnerAccountID =
+ @"OFFileGroupOwnerAccountID";
+const OFFileAttributeKey OFFileOwnerAccountName = @"OFFileOwnerAccountName";
+const OFFileAttributeKey OFFileGroupOwnerAccountName =
+ @"OFFileGroupOwnerAccountName";
+const OFFileAttributeKey OFFileLastAccessDate = @"OFFileLastAccessDate";
+const OFFileAttributeKey OFFileModificationDate = @"OFFileModificationDate";
+const OFFileAttributeKey OFFileStatusChangeDate = @"OFFileStatusChangeDate";
+const OFFileAttributeKey OFFileCreationDate = @"OFFileCreationDate";
+const OFFileAttributeKey OFFileSymbolicLinkDestination =
+ @"OFFileSymbolicLinkDestination";
+
+const OFFileAttributeType OFFileTypeRegular = @"OFFileTypeRegular";
+const OFFileAttributeType OFFileTypeDirectory = @"OFFileTypeDirectory";
+const OFFileAttributeType OFFileTypeSymbolicLink = @"OFFileTypeSymbolicLink";
+const OFFileAttributeType OFFileTypeFIFO = @"OFFileTypeFIFO";
+const OFFileAttributeType OFFileTypeCharacterSpecial =
+ @"OFFileTypeCharacterSpecial";
+const OFFileAttributeType OFFileTypeBlockSpecial = @"OFFileTypeBlockSpecial";
+const OFFileAttributeType OFFileTypeSocket = @"OFFileTypeSocket";
+const OFFileAttributeType OFFileTypeUnknown = @"OFFileTypeUnknown";
#ifdef OF_AMIGAOS4
# define CurrentDir(lock) SetCurrentDir(lock)
#endif
@@ -121,12 +113,11 @@
UnLock(CurrentDir(originalDirLock));
}
#endif
static id
-attributeForKeyOrException(of_file_attributes_t attributes,
- of_file_attribute_key_t key)
+attributeForKeyOrException(OFFileAttributes attributes, OFFileAttributeKey key)
{
id object = [attributes objectForKey: key];
if (object == nil)
@throw [OFUndefinedKeyException exceptionWithObject: attributes
@@ -229,11 +220,11 @@
objc_autoreleasePoolPop(pool);
return [ret autorelease];
}
#endif
-- (of_file_attributes_t)attributesOfItemAtURL: (OFURL *)URL
+- (OFFileAttributes)attributesOfItemAtURL: (OFURL *)URL
{
OFURLHandler *URLHandler;
if (URL == nil)
@throw [OFInvalidArgumentException exception];
@@ -243,14 +234,14 @@
return [URLHandler attributesOfItemAtURL: URL];
}
#ifdef OF_HAVE_FILES
-- (of_file_attributes_t)attributesOfItemAtPath: (OFString *)path
+- (OFFileAttributes)attributesOfItemAtPath: (OFString *)path
{
void *pool = objc_autoreleasePoolPush();
- of_file_attributes_t ret;
+ OFFileAttributes ret;
ret = [self attributesOfItemAtURL: [OFURL fileURLWithPath: path]];
[ret retain];
@@ -258,12 +249,11 @@
return [ret autorelease];
}
#endif
-- (void)setAttributes: (of_file_attributes_t)attributes
- ofItemAtURL: (OFURL *)URL
+- (void)setAttributes: (OFFileAttributes)attributes ofItemAtURL: (OFURL *)URL
{
OFURLHandler *URLHandler;
if (URL == nil)
@throw [OFInvalidArgumentException exception];
@@ -273,11 +263,11 @@
[URLHandler setAttributes: attributes ofItemAtURL: URL];
}
#ifdef OF_HAVE_FILES
-- (void)setAttributes: (of_file_attributes_t)attributes
+- (void)setAttributes: (OFFileAttributes)attributes
ofItemAtPath: (OFString *)path
{
void *pool = objc_autoreleasePoolPush();
[self setAttributes: attributes
ofItemAtURL: [OFURL fileURLWithPath: path]];
@@ -567,12 +557,12 @@
- (void)copyItemAtURL: (OFURL *)source toURL: (OFURL *)destination
{
void *pool;
OFURLHandler *URLHandler;
- of_file_attributes_t attributes;
- of_file_type_t type;
+ OFFileAttributes attributes;
+ OFFileAttributeType type;
if (source == nil || destination == nil)
@throw [OFInvalidArgumentException exception];
pool = objc_autoreleasePoolPush();
@@ -599,22 +589,21 @@
errNo: e.errNo];
}
type = attributes.fileType;
- if ([type isEqual: of_file_type_directory]) {
+ if ([type isEqual: OFFileTypeDirectory]) {
OFArray OF_GENERIC(OFURL *) *contents;
@try {
[self createDirectoryAtURL: destination];
@try {
- of_file_attribute_key_t key =
- of_file_attribute_key_posix_permissions;
+ OFFileAttributeKey key = OFFilePOSIXPermissions;
OFNumber *permissions =
[attributes objectForKey: key];
- of_file_attributes_t destinationAttributes;
+ OFFileAttributes destinationAttributes;
if (permissions != nil) {
destinationAttributes = [OFDictionary
dictionaryWithObject: permissions
forKey: key];
@@ -650,17 +639,17 @@
[self copyItemAtURL: item toURL: destinationURL];
objc_autoreleasePoolPop(pool2);
}
- } else if ([type isEqual: of_file_type_regular]) {
+ } else if ([type isEqual: OFFileTypeRegular]) {
size_t pageSize = [OFSystemInfo pageSize];
OFStream *sourceStream = nil;
OFStream *destinationStream = nil;
char *buffer;
- buffer = of_alloc(1, pageSize);
+ buffer = OFAllocMemory(1, pageSize);
@try {
sourceStream = [[OFURLHandler handlerForURL: source]
openItemAtURL: source
mode: @"r"];
destinationStream = [[OFURLHandler handlerForURL:
@@ -676,15 +665,14 @@
[destinationStream writeBuffer: buffer
length: length];
}
@try {
- of_file_attribute_key_t key =
- of_file_attribute_key_posix_permissions;
+ OFFileAttributeKey key = OFFilePOSIXPermissions;
OFNumber *permissions = [attributes
objectForKey: key];
- of_file_attributes_t destinationAttributes;
+ OFFileAttributes destinationAttributes;
if (permissions != nil) {
destinationAttributes = [OFDictionary
dictionaryWithObject: permissions
forKey: key];
@@ -709,13 +697,13 @@
@throw e;
} @finally {
[sourceStream close];
[destinationStream close];
- free(buffer);
+ OFFreeMemory(buffer);
}
- } else if ([type isEqual: of_file_type_symbolic_link]) {
+ } else if ([type isEqual: OFFileTypeSymbolicLink]) {
@try {
OFString *linkDestination =
attributes.fileSymbolicLinkDestination;
[self createSymbolicLinkAtURL: destination
@@ -905,79 +893,74 @@
{
}
- (unsigned int)retainCount
{
- return OF_RETAIN_COUNT_MAX;
+ return OFMaxRetainCount;
}
@end
@implementation OFDictionary (FileAttributes)
- (unsigned long long)fileSize
{
- return [attributeForKeyOrException(self, of_file_attribute_key_size)
+ return [attributeForKeyOrException(self, OFFileSize)
unsignedLongLongValue];
}
-- (of_file_type_t)fileType
+- (OFFileAttributeType)fileType
{
- return attributeForKeyOrException(self, of_file_attribute_key_type);
+ return attributeForKeyOrException(self, OFFileType);
}
- (unsigned long)filePOSIXPermissions
{
return [attributeForKeyOrException(self,
- of_file_attribute_key_posix_permissions) unsignedLongValue];
-}
-
-- (unsigned long)filePOSIXUID
-{
- return [attributeForKeyOrException(self,
- of_file_attribute_key_posix_uid) unsignedLongValue];
-}
-
-- (unsigned long)filePOSIXGID
-{
- return [attributeForKeyOrException(self,
- of_file_attribute_key_posix_gid) unsignedLongValue];
-}
-
-- (OFString *)fileOwner
-{
- return attributeForKeyOrException(self, of_file_attribute_key_owner);
-}
-
-- (OFString *)fileGroup
-{
- return attributeForKeyOrException(self, of_file_attribute_key_group);
+ OFFilePOSIXPermissions) unsignedLongValue];
+}
+
+- (unsigned long)fileOwnerAccountID
+{
+ return [attributeForKeyOrException(self,
+ OFFileOwnerAccountID) unsignedLongValue];
+}
+
+- (unsigned long)fileGroupOwnerAccountID
+{
+ return [attributeForKeyOrException(self,
+ OFFileGroupOwnerAccountID) unsignedLongValue];
+}
+
+- (OFString *)fileOwnerAccountName
+{
+ return attributeForKeyOrException(self, OFFileOwnerAccountName);
+}
+
+- (OFString *)fileGroupOwnerAccountName
+{
+ return attributeForKeyOrException(self, OFFileGroupOwnerAccountName);
}
- (OFDate *)fileLastAccessDate
{
- return attributeForKeyOrException(self,
- of_file_attribute_key_last_access_date);
+ return attributeForKeyOrException(self, OFFileLastAccessDate);
}
- (OFDate *)fileModificationDate
{
- return attributeForKeyOrException(self,
- of_file_attribute_key_modification_date);
+ return attributeForKeyOrException(self, OFFileModificationDate);
}
- (OFDate *)fileStatusChangeDate
{
- return attributeForKeyOrException(self,
- of_file_attribute_key_status_change_date);
+ return attributeForKeyOrException(self, OFFileStatusChangeDate);
}
- (OFDate *)fileCreationDate
{
- return attributeForKeyOrException(self,
- of_file_attribute_key_creation_date);
+ return attributeForKeyOrException(self, OFFileCreationDate);
}
- (OFString *)fileSymbolicLinkDestination
{
- return attributeForKeyOrException(self,
- of_file_attribute_key_symbolic_link_destination);
+ return attributeForKeyOrException(self, OFFileSymbolicLinkDestination);
}
@end
Index: src/OFFileURLHandler.m
==================================================================
--- src/OFFileURLHandler.m
+++ src/OFFileURLHandler.m
@@ -85,23 +85,23 @@
# endif
#endif
#if defined(OF_WINDOWS) || defined(OF_AMIGAOS)
typedef struct {
- of_offset_t st_size;
+ OFFileOffset st_size;
unsigned int st_mode;
- of_time_interval_t st_atime, st_mtime, st_ctime;
+ OFTimeInterval st_atime, st_mtime, st_ctime;
# ifdef OF_WINDOWS
# define HAVE_STRUCT_STAT_ST_BIRTHTIME
- of_time_interval_t st_birthtime;
+ OFTimeInterval st_birthtime;
DWORD fileAttributes;
# endif
-} of_stat_t;
+} Stat;
#elif defined(HAVE_STAT64)
-typedef struct stat64 of_stat_t;
+typedef struct stat64 Stat;
#else
-typedef struct stat of_stat_t;
+typedef struct stat Stat;
#endif
#ifdef OF_WINDOWS
# define S_IFLNK 0x10000
# define S_ISLNK(mode) (mode & S_IFLNK)
@@ -125,18 +125,18 @@
[readdirMutex release];
}
#endif
#ifdef OF_WINDOWS
-static int (*func__wutime64)(const wchar_t *, struct __utimbuf64 *);
-static WINAPI BOOLEAN (*func_CreateSymbolicLinkW)(LPCWSTR, LPCWSTR, DWORD);
-static WINAPI BOOLEAN (*func_CreateHardLinkW)(LPCWSTR, LPCWSTR,
+static int (*_wutime64FuncPtr)(const wchar_t *, struct __utimbuf64 *);
+static WINAPI BOOLEAN (*createSymbolicLinkWFuncPtr)(LPCWSTR, LPCWSTR, DWORD);
+static WINAPI BOOLEAN (*createHardLinkWFuncPtr)(LPCWSTR, LPCWSTR,
LPSECURITY_ATTRIBUTES);
#endif
#ifdef OF_WINDOWS
-static of_time_interval_t
+static OFTimeInterval
filetimeToTimeInterval(const FILETIME *filetime)
{
return (double)((int64_t)filetime->dwHighDateTime << 32 |
filetime->dwLowDateTime) / 10000000.0 - 11644473600.0;
}
@@ -194,11 +194,11 @@
}
}
#endif
static int
-of_stat(OFString *path, of_stat_t *buffer)
+statWrapper(OFString *path, Stat *buffer)
{
#if defined(OF_WINDOWS)
WIN32_FILE_ATTRIBUTE_DATA data;
bool success;
@@ -260,11 +260,11 @@
# ifdef OF_AMIGAOS4
struct ExamineData *ed;
# else
struct FileInfoBlock fib;
# endif
- of_time_interval_t timeInterval;
+ OFTimeInterval timeInterval;
struct Locale *locale;
struct DateStamp *date;
if ((lock = Lock([path cStringWithEncoding: [OFLocale encoding]],
SHARED_LOCK)) == 0)
@@ -313,11 +313,11 @@
# else
date = &fib.fib_Date;
# endif
timeInterval += date->ds_Days * 86400.0;
timeInterval += date->ds_Minute * 60.0;
- timeInterval += date->ds_Tick / (of_time_interval_t)TICKS_PER_SECOND;
+ timeInterval += date->ds_Tick / (OFTimeInterval)TICKS_PER_SECOND;
buffer->st_atime = buffer->st_mtime = buffer->st_ctime = timeInterval;
# ifdef OF_AMIGAOS4
FreeDosObject(DOS_EXAMINEDATA, ed);
@@ -337,11 +337,11 @@
return 0;
#endif
}
static int
-of_lstat(OFString *path, of_stat_t *buffer)
+lstatWrapper(OFString *path, Stat *buffer)
{
#if defined(HAVE_LSTAT) && !defined(OF_WINDOWS) && !defined(OF_AMIGAOS) && \
!defined(OF_NINTENDO_3DS) && !defined(OF_WII)
# ifdef HAVE_LSTAT64
if (lstat64([path cStringWithEncoding: [OFLocale encoding]],
@@ -352,104 +352,101 @@
return errno;
# endif
return 0;
#else
- return of_stat(path, buffer);
+ return statWrapper(path, buffer);
#endif
}
static void
-setTypeAttribute(of_mutable_file_attributes_t attributes, of_stat_t *s)
+setTypeAttribute(OFMutableFileAttributes attributes, Stat *s)
{
if (S_ISREG(s->st_mode))
- [attributes setObject: of_file_type_regular
- forKey: of_file_attribute_key_type];
+ [attributes setObject: OFFileTypeRegular forKey: OFFileType];
else if (S_ISDIR(s->st_mode))
- [attributes setObject: of_file_type_directory
- forKey: of_file_attribute_key_type];
+ [attributes setObject: OFFileTypeDirectory forKey: OFFileType];
#ifdef S_ISLNK
else if (S_ISLNK(s->st_mode))
- [attributes setObject: of_file_type_symbolic_link
- forKey: of_file_attribute_key_type];
+ [attributes setObject: OFFileTypeSymbolicLink
+ forKey: OFFileType];
#endif
#ifdef S_ISFIFO
else if (S_ISFIFO(s->st_mode))
- [attributes setObject: of_file_type_fifo
- forKey: of_file_attribute_key_type];
+ [attributes setObject: OFFileTypeFIFO forKey: OFFileType];
#endif
#ifdef S_ISCHR
else if (S_ISCHR(s->st_mode))
- [attributes setObject: of_file_type_character_special
- forKey: of_file_attribute_key_type];
+ [attributes setObject: OFFileTypeCharacterSpecial
+ forKey: OFFileType];
#endif
#ifdef S_ISBLK
else if (S_ISBLK(s->st_mode))
- [attributes setObject: of_file_type_block_special
- forKey: of_file_attribute_key_type];
+ [attributes setObject: OFFileTypeBlockSpecial
+ forKey: OFFileType];
#endif
#ifdef S_ISSOCK
else if (S_ISSOCK(s->st_mode))
- [attributes setObject: of_file_type_socket
- forKey: of_file_attribute_key_type];
+ [attributes setObject: OFFileTypeSocket forKey: OFFileType];
#endif
+ else
+ [attributes setObject: OFFileTypeUnknown forKey: OFFileType];
}
static void
-setDateAttributes(of_mutable_file_attributes_t attributes, of_stat_t *s)
+setDateAttributes(OFMutableFileAttributes attributes, Stat *s)
{
/* FIXME: We could be more precise on some OSes */
[attributes
setObject: [OFDate dateWithTimeIntervalSince1970: s->st_atime]
- forKey: of_file_attribute_key_last_access_date];
+ forKey: OFFileLastAccessDate];
[attributes
setObject: [OFDate dateWithTimeIntervalSince1970: s->st_mtime]
- forKey: of_file_attribute_key_modification_date];
+ forKey: OFFileModificationDate];
[attributes
setObject: [OFDate dateWithTimeIntervalSince1970: s->st_ctime]
- forKey: of_file_attribute_key_status_change_date];
+ forKey: OFFileStatusChangeDate];
#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
[attributes
setObject: [OFDate dateWithTimeIntervalSince1970: s->st_birthtime]
- forKey: of_file_attribute_key_creation_date];
+ forKey: OFFileCreationDate];
#endif
}
static void
-setOwnerAndGroupAttributes(of_mutable_file_attributes_t attributes,
- of_stat_t *s)
+setOwnerAndGroupAttributes(OFMutableFileAttributes attributes, Stat *s)
{
#ifdef OF_FILE_MANAGER_SUPPORTS_OWNER
[attributes setObject: [NSNumber numberWithUnsignedLong: s->st_uid]
- forKey: of_file_attribute_key_posix_uid];
+ forKey: OFFileOwnerAccountID];
[attributes setObject: [NSNumber numberWithUnsignedLong: s->st_gid]
- forKey: of_file_attribute_key_posix_gid];
+ forKey: OFFileGroupOwnerAccountID];
# ifdef OF_HAVE_THREADS
[passwdMutex lock];
@try {
# endif
- of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
struct passwd *passwd = getpwuid(s->st_uid);
struct group *group_ = getgrgid(s->st_gid);
if (passwd != NULL) {
OFString *owner = [OFString
stringWithCString: passwd->pw_name
encoding: encoding];
[attributes setObject: owner
- forKey: of_file_attribute_key_owner];
+ forKey: OFFileOwnerAccountName];
}
if (group_ != NULL) {
OFString *group = [OFString
stringWithCString: group_->gr_name
encoding: encoding];
[attributes setObject: group
- forKey: of_file_attribute_key_group];
+ forKey: OFFileGroupOwnerAccountName];
}
# ifdef OF_HAVE_THREADS
} @finally {
[passwdMutex unlock];
}
@@ -457,20 +454,19 @@
#endif
}
#ifdef OF_FILE_MANAGER_SUPPORTS_SYMLINKS
static void
-setSymbolicLinkDestinationAttribute(of_mutable_file_attributes_t attributes,
+setSymbolicLinkDestinationAttribute(OFMutableFileAttributes attributes,
OFURL *URL)
{
OFString *path = URL.fileSystemRepresentation;
# ifndef OF_WINDOWS
- of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
char destinationC[PATH_MAX];
ssize_t length;
OFString *destination;
- of_file_attribute_key_t key;
length = readlink([path cStringWithEncoding: encoding], destinationC,
PATH_MAX);
if (length < 0)
@@ -480,17 +476,17 @@
destination = [OFString stringWithCString: destinationC
encoding: encoding
length: length];
- key = of_file_attribute_key_symbolic_link_destination;
- [attributes setObject: destination forKey: key];
+ [attributes setObject: destination
+ forKey: OFFileSymbolicLinkDestination];
# else
HANDLE handle;
OFString *destination;
- if (func_CreateSymbolicLinkW == NULL)
+ if (createSymbolicLinkWFuncPtr == NULL)
return;
if ((handle = CreateFileW(path.UTF16String, 0, (FILE_SHARE_READ |
FILE_SHARE_WRITE), NULL, OPEN_EXISTING,
FILE_FLAG_OPEN_REPARSE_POINT, NULL)) == INVALID_HANDLE_VALUE)
@@ -503,11 +499,10 @@
char bytes[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
REPARSE_DATA_BUFFER data;
} buffer;
DWORD size;
wchar_t *tmp;
- of_file_attribute_key_t key;
if (!DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, NULL, 0,
buffer.bytes, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &size,
NULL))
@throw [OFRetrieveItemAttributesFailedException
@@ -526,14 +521,14 @@
destination = [OFString
stringWithUTF16String: tmp
length: slrb.SubstituteNameLength /
sizeof(wchar_t)];
- [attributes setObject: of_file_type_symbolic_link
- forKey: of_file_attribute_key_type];
- key = of_file_attribute_key_symbolic_link_destination;
- [attributes setObject: destination forKey: key];
+ [attributes setObject: OFFileTypeSymbolicLink
+ forKey: OFFileType];
+ [attributes setObject: destination
+ forKey: OFFileSymbolicLinkDestination];
# undef slrb
} @finally {
CloseHandle(handle);
}
# endif
@@ -559,18 +554,18 @@
atexit(releaseReaddirMutex);
#endif
#ifdef OF_WINDOWS
if ((module = LoadLibrary("msvcrt.dll")) != NULL)
- func__wutime64 = (int (*)(const wchar_t *,
+ _wutime64FuncPtr = (int (*)(const wchar_t *,
struct __utimbuf64 *))GetProcAddress(module, "_wutime64");
if ((module = LoadLibrary("kernel32.dll")) != NULL) {
- func_CreateSymbolicLinkW =
+ createSymbolicLinkWFuncPtr =
(WINAPI BOOLEAN (*)(LPCWSTR, LPCWSTR, DWORD))
GetProcAddress(module, "CreateSymbolicLinkW");
- func_CreateHardLinkW =
+ createHardLinkWFuncPtr =
(WINAPI BOOLEAN (*)(LPCWSTR, LPCWSTR,
LPSECURITY_ATTRIBUTES))
GetProcAddress(module, "CreateHardLinkW");
}
#endif
@@ -582,13 +577,13 @@
[OFFile class];
}
+ (bool)of_directoryExistsAtPath: (OFString *)path
{
- of_stat_t s;
+ Stat s;
- if (of_stat(path, &s) != 0)
+ if (statWrapper(path, &s) != 0)
return false;
return S_ISDIR(s.st_mode);
}
@@ -602,41 +597,41 @@
objc_autoreleasePoolPop(pool);
return [file autorelease];
}
-- (of_file_attributes_t)attributesOfItemAtURL: (OFURL *)URL
+- (OFFileAttributes)attributesOfItemAtURL: (OFURL *)URL
{
- of_mutable_file_attributes_t ret = [OFMutableDictionary dictionary];
+ OFMutableFileAttributes ret = [OFMutableDictionary dictionary];
void *pool = objc_autoreleasePoolPush();
OFString *path;
int error;
- of_stat_t s;
+ Stat s;
if (URL == nil)
@throw [OFInvalidArgumentException exception];
if (![[URL scheme] isEqual: _scheme])
@throw [OFInvalidArgumentException exception];
path = URL.fileSystemRepresentation;
- if ((error = of_lstat(path, &s)) != 0)
+ if ((error = lstatWrapper(path, &s)) != 0)
@throw [OFRetrieveItemAttributesFailedException
exceptionWithURL: URL
errNo: error];
if (s.st_size < 0)
@throw [OFOutOfRangeException exception];
[ret setObject: [NSNumber numberWithUnsignedLongLong: s.st_size]
- forKey: of_file_attribute_key_size];
+ forKey: OFFileSize];
setTypeAttribute(ret, &s);
[ret setObject: [NSNumber numberWithUnsignedLong: s.st_mode]
- forKey: of_file_attribute_key_posix_permissions];
+ forKey: OFFilePOSIXPermissions];
setOwnerAndGroupAttributes(ret, &s);
setDateAttributes(ret, &s);
#ifdef OF_FILE_MANAGER_SUPPORTS_SYMLINKS
@@ -650,32 +645,31 @@
}
- (void)of_setLastAccessDate: (OFDate *)lastAccessDate
andModificationDate: (OFDate *)modificationDate
ofItemAtURL: (OFURL *)URL
- attributes: (of_file_attributes_t)attributes OF_DIRECT
+ attributes: (OFFileAttributes)attributes OF_DIRECT
{
OFString *path = URL.fileSystemRepresentation;
- of_file_attribute_key_t attributeKey = (modificationDate != nil
- ? of_file_attribute_key_modification_date
- : of_file_attribute_key_last_access_date);
+ OFFileAttributeKey attributeKey = (modificationDate != nil
+ ? OFFileModificationDate : OFFileLastAccessDate);
if (lastAccessDate == nil)
lastAccessDate = modificationDate;
if (modificationDate == nil)
modificationDate = lastAccessDate;
#if defined(OF_WINDOWS)
- if (func__wutime64 != NULL) {
+ if (_wutime64FuncPtr != NULL) {
struct __utimbuf64 times = {
.actime =
(__time64_t)lastAccessDate.timeIntervalSince1970,
.modtime =
(__time64_t)modificationDate.timeIntervalSince1970
};
- if (func__wutime64([path UTF16String], ×) != 0)
+ if (_wutime64FuncPtr([path UTF16String], ×) != 0)
@throw [OFSetItemAttributesFailedException
exceptionWithURL: URL
attributes: attributes
failedAttribute: attributeKey
errNo: errno];
@@ -701,11 +695,11 @@
failedAttribute: attributeKey
errNo: errno];
}
#elif defined(OF_AMIGAOS)
/* AmigaOS does not support access time. */
- of_time_interval_t modificationTime =
+ OFTimeInterval modificationTime =
modificationDate.timeIntervalSince1970;
struct Locale *locale;
struct DateStamp date;
modificationTime -= 252460800; /* 1978-01-01 */
@@ -737,13 +731,12 @@
exceptionWithURL: URL
attributes: attributes
failedAttribute: attributeKey
errNo: retrieveError()];
#else
- of_time_interval_t lastAccessTime =
- lastAccessDate.timeIntervalSince1970;
- of_time_interval_t modificationTime =
+ OFTimeInterval lastAccessTime = lastAccessDate.timeIntervalSince1970;
+ OFTimeInterval modificationTime =
modificationDate.timeIntervalSince1970;
struct timeval times[2] = {
{
.tv_sec = (time_t)lastAccessTime,
.tv_usec =
@@ -765,11 +758,11 @@
#endif
}
- (void)of_setPOSIXPermissions: (OFNumber *)permissions
ofItemAtURL: (OFURL *)URL
- attributes: (of_file_attributes_t)attributes OF_DIRECT
+ attributes: (OFFileAttributes)attributes OF_DIRECT
{
#ifdef OF_FILE_MANAGER_SUPPORTS_PERMISSIONS
mode_t mode = (mode_t)permissions.unsignedLongValue;
OFString *path = URL.fileSystemRepresentation;
int status;
@@ -784,28 +777,28 @@
if (status != 0)
@throw [OFSetItemAttributesFailedException
exceptionWithURL: URL
attributes: attributes
- failedAttribute: of_file_attribute_key_posix_permissions
+ failedAttribute: OFFilePOSIXPermissions
errNo: errno];
#else
OF_UNRECOGNIZED_SELECTOR
#endif
}
-- (void)of_setOwner: (OFString *)owner
- andGroup: (OFString *)group
- ofItemAtURL: (OFURL *)URL
- attributeKey: (of_file_attribute_key_t)attributeKey
- attributes: (of_file_attributes_t)attributes OF_DIRECT
+- (void)of_setOwnerAccountName: (OFString *)owner
+ andGroupOwnerAccountName: (OFString *)group
+ ofItemAtURL: (OFURL *)URL
+ attributeKey: (OFFileAttributeKey)attributeKey
+ attributes: (OFFileAttributes)attributes OF_DIRECT
{
#ifdef OF_FILE_MANAGER_SUPPORTS_OWNER
OFString *path = URL.fileSystemRepresentation;
uid_t uid = -1;
gid_t gid = -1;
- of_string_encoding_t encoding;
+ OFStringEncoding encoding;
if (owner == nil && group == nil)
@throw [OFInvalidArgumentException exception];
encoding = [OFLocale encoding];
@@ -856,17 +849,16 @@
#else
OF_UNRECOGNIZED_SELECTOR
#endif
}
-- (void)setAttributes: (of_file_attributes_t)attributes
- ofItemAtURL: (OFURL *)URL
+- (void)setAttributes: (OFFileAttributes)attributes ofItemAtURL: (OFURL *)URL
{
void *pool = objc_autoreleasePoolPush();
- OFEnumerator OF_GENERIC(of_file_attribute_key_t) *keyEnumerator;
+ OFEnumerator OF_GENERIC(OFFileAttributeKey) *keyEnumerator;
OFEnumerator *objectEnumerator;
- of_file_attribute_key_t key;
+ OFFileAttributeKey key;
id object;
OFDate *lastAccessDate, *modificationDate;
if (URL == nil)
@throw [OFInvalidArgumentException exception];
@@ -877,39 +869,37 @@
keyEnumerator = [attributes keyEnumerator];
objectEnumerator = [attributes objectEnumerator];
while ((key = [keyEnumerator nextObject]) != nil &&
(object = [objectEnumerator nextObject]) != nil) {
- if ([key isEqual: of_file_attribute_key_modification_date] ||
- [key isEqual: of_file_attribute_key_last_access_date])
+ if ([key isEqual: OFFileModificationDate] ||
+ [key isEqual: OFFileLastAccessDate])
continue;
- else if ([key isEqual: of_file_attribute_key_posix_permissions])
+ else if ([key isEqual: OFFilePOSIXPermissions])
[self of_setPOSIXPermissions: object
ofItemAtURL: URL
attributes: attributes];
- else if ([key isEqual: of_file_attribute_key_owner])
- [self of_setOwner: object
- andGroup: nil
- ofItemAtURL: URL
- attributeKey: key
- attributes: attributes];
- else if ([key isEqual: of_file_attribute_key_group])
- [self of_setOwner: nil
- andGroup: object
- ofItemAtURL: URL
- attributeKey: key
- attributes: attributes];
+ else if ([key isEqual: OFFileOwnerAccountName])
+ [self of_setOwnerAccountName: object
+ andGroupOwnerAccountName: nil
+ ofItemAtURL: URL
+ attributeKey: key
+ attributes: attributes];
+ else if ([key isEqual: OFFileGroupOwnerAccountName])
+ [self of_setOwnerAccountName: nil
+ andGroupOwnerAccountName: object
+ ofItemAtURL: URL
+ attributeKey: key
+ attributes: attributes];
else
@throw [OFNotImplementedException
exceptionWithSelector: _cmd
object: self];
}
- lastAccessDate = [attributes
- objectForKey: of_file_attribute_key_last_access_date];
- modificationDate = [attributes
- objectForKey: of_file_attribute_key_modification_date];
+ lastAccessDate = [attributes objectForKey: OFFileLastAccessDate];
+ modificationDate = [attributes objectForKey: OFFileModificationDate];
if (lastAccessDate != nil || modificationDate != nil)
[self of_setLastAccessDate: lastAccessDate
andModificationDate: modificationDate
ofItemAtURL: URL
@@ -919,20 +909,20 @@
}
- (bool)fileExistsAtURL: (OFURL *)URL
{
void *pool = objc_autoreleasePoolPush();
- of_stat_t s;
+ Stat s;
bool ret;
if (URL == nil)
@throw [OFInvalidArgumentException exception];
if (![URL.scheme isEqual: _scheme])
@throw [OFInvalidArgumentException exception];
- if (of_stat(URL.fileSystemRepresentation, &s) != 0) {
+ if (statWrapper(URL.fileSystemRepresentation, &s) != 0) {
objc_autoreleasePoolPop(pool);
return false;
}
ret = S_ISREG(s.st_mode);
@@ -943,20 +933,20 @@
}
- (bool)directoryExistsAtURL: (OFURL *)URL
{
void *pool = objc_autoreleasePoolPush();
- of_stat_t s;
+ Stat s;
bool ret;
if (URL == nil)
@throw [OFInvalidArgumentException exception];
if (![URL.scheme isEqual: _scheme])
@throw [OFInvalidArgumentException exception];
- if (of_stat(URL.fileSystemRepresentation, &s) != 0) {
+ if (statWrapper(URL.fileSystemRepresentation, &s) != 0) {
objc_autoreleasePoolPop(pool);
return false;
}
ret = S_ISDIR(s.st_mode);
@@ -1066,11 +1056,11 @@
errNo: retrieveError()];
} @finally {
FindClose(handle);
}
} else {
- of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
WIN32_FIND_DATA fd;
if ((handle = FindFirstFileA(
[path cStringWithEncoding: encoding], &fd)) ==
INVALID_HANDLE_VALUE)
@@ -1106,11 +1096,11 @@
} @finally {
FindClose(handle);
}
}
#elif defined(OF_AMIGAOS)
- of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
BPTR lock;
if ((lock = Lock([path cStringWithEncoding: encoding],
SHARED_LOCK)) == 0)
@throw [OFOpenItemFailedException
@@ -1176,11 +1166,11 @@
errNo: retrieveError()];
} @finally {
UnLock(lock);
}
#else
- of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
DIR *dir;
if ((dir = opendir([path cStringWithEncoding: encoding])) == NULL)
@throw [OFOpenItemFailedException exceptionWithURL: URL
mode: nil
errNo: errno];
@@ -1255,21 +1245,21 @@
- (void)removeItemAtURL: (OFURL *)URL
{
void *pool = objc_autoreleasePoolPush();
OFString *path;
int error;
- of_stat_t s;
+ Stat s;
if (URL == nil)
@throw [OFInvalidArgumentException exception];
if (![URL.scheme isEqual: _scheme])
@throw [OFInvalidArgumentException exception];
path = URL.fileSystemRepresentation;
- if ((error = of_lstat(path, &s)) != 0)
+ if ((error = lstatWrapper(path, &s)) != 0)
@throw [OFRemoveItemFailedException exceptionWithURL: URL
errNo: error];
if (S_ISDIR(s.st_mode)) {
OFArray OF_GENERIC(OFURL *) *contents;
@@ -1358,24 +1348,24 @@
sourcePath = source.fileSystemRepresentation;
destinationPath = destination.fileSystemRepresentation;
# ifndef OF_WINDOWS
- of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
if (link([sourcePath cStringWithEncoding: encoding],
[destinationPath cStringWithEncoding: encoding]) != 0)
@throw [OFLinkFailedException
exceptionWithSourceURL: source
destinationURL: destination
errNo: errno];
# else
- if (func_CreateHardLinkW == NULL)
+ if (createHardLinkWFuncPtr == NULL)
@throw [OFNotImplementedException exceptionWithSelector: _cmd
object: self];
- if (!func_CreateHardLinkW(destinationPath.UTF16String,
+ if (!createHardLinkWFuncPtr(destinationPath.UTF16String,
sourcePath.UTF16String, NULL))
@throw [OFLinkFailedException
exceptionWithSourceURL: source
destinationURL: destination
errNo: retrieveError()];
@@ -1399,24 +1389,25 @@
@throw [OFInvalidArgumentException exception];
path = URL.fileSystemRepresentation;
# ifndef OF_WINDOWS
- of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
if (symlink([target cStringWithEncoding: encoding],
[path cStringWithEncoding: encoding]) != 0)
@throw [OFCreateSymbolicLinkFailedException
exceptionWithURL: URL
target: target
errNo: errno];
# else
- if (func_CreateSymbolicLinkW == NULL)
+ if (createSymbolicLinkWFuncPtr == NULL)
@throw [OFNotImplementedException exceptionWithSelector: _cmd
object: self];
- if (!func_CreateSymbolicLinkW(path.UTF16String, target.UTF16String, 0))
+ if (!createSymbolicLinkWFuncPtr(path.UTF16String, target.UTF16String,
+ 0))
@throw [OFCreateSymbolicLinkFailedException
exceptionWithURL: URL
target: target
errNo: retrieveError()];
# endif
@@ -1440,11 +1431,11 @@
errNo: EEXIST];
pool = objc_autoreleasePoolPush();
#ifdef OF_AMIGAOS
- of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
if (!Rename([source.fileSystemRepresentation
cStringWithEncoding: encoding],
[destination.fileSystemRepresentation
cStringWithEncoding: encoding]))
@@ -1459,11 +1450,11 @@
if ([OFSystemInfo isWindowsNT])
status = _wrename(source.fileSystemRepresentation.UTF16String,
destination.fileSystemRepresentation.UTF16String);
else {
# endif
- of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
status = rename([source.fileSystemRepresentation
cStringWithEncoding: encoding],
[destination.fileSystemRepresentation
cStringWithEncoding: encoding]);
Index: src/OFGZIPStream.h
==================================================================
--- src/OFGZIPStream.h
+++ src/OFGZIPStream.h
@@ -18,10 +18,31 @@
@class OFInflateStream;
OF_ASSUME_NONNULL_BEGIN
+/**
+ * @brief The operating system on which compressed the data.
+ */
+typedef enum {
+ OFGZIPStreamOperatingSystemFAT = 0,
+ OFGZIPStreamOperatingSystemAmiga = 1,
+ OFGZIPStreamOperatingSystemVMS = 2,
+ OFGZIPStreamOperatingSystemUNIX = 3,
+ OFGZIPStreamOperatingSystemVM_CMS = 4,
+ OFGZIPStreamOperatingSystemAtariTOS = 5,
+ OFGZIPStreamOperatingSystemHPFS = 6,
+ OFGZIPStreamOperatingSystemMacintosh = 7,
+ OFGZIPStreamOperatingSystemZSystem = 8,
+ OFGZIPStreamOperatingSystemCPM = 9,
+ OFGZIPStreamOperatingSystemTOPS20 = 10,
+ OFGZIPStreamOperatingSystemNTFS = 11,
+ OFGZIPStreamOperatingSystemQDO = 12,
+ OFGZIPStreamOperatingSystemAcornRISCOS = 13,
+ OFGZIPStreamOperatingSystemUnknown = 255
+} OFGZIPStreamOperatingSystem;
+
/**
* @class OFGZIPStream OFGZIPStream.h ObjFW/OFGZIPStream.h
*
* @brief A class that handles GZIP compression and decompression transparently
* for an underlying stream.
@@ -29,52 +50,36 @@
OF_SUBCLASSING_RESTRICTED
@interface OFGZIPStream: OFStream
{
OFStream *_stream;
OFInflateStream *_Nullable _inflateStream;
- enum of_gzip_stream_state {
- OF_GZIP_STREAM_ID1,
- OF_GZIP_STREAM_ID2,
- OF_GZIP_STREAM_COMPRESSION_METHOD,
- OF_GZIP_STREAM_FLAGS,
- OF_GZIP_STREAM_MODIFICATION_TIME,
- OF_GZIP_STREAM_EXTRA_FLAGS,
- OF_GZIP_STREAM_OPERATING_SYSTEM,
- OF_GZIP_STREAM_EXTRA_LENGTH,
- OF_GZIP_STREAM_EXTRA,
- OF_GZIP_STREAM_NAME,
- OF_GZIP_STREAM_COMMENT,
- OF_GZIP_STREAM_HEADER_CRC16,
- OF_GZIP_STREAM_DATA,
- OF_GZIP_STREAM_CRC32,
- OF_GZIP_STREAM_UNCOMPRESSED_SIZE
+ enum {
+ OFGZIPStreamStateID1,
+ OFGZIPStreamStateID2,
+ OFGZIPStreamStateCompressionMethod,
+ OFGZIPStreamStateFlags,
+ OFGZIPStreamStateModificationDate,
+ OFGZIPStreamStateExtraFlags,
+ OFGZIPStreamStateOperatingSystem,
+ OFGZIPStreamStateExtraLength,
+ OFGZIPStreamStateExtra,
+ OFGZIPStreamStateName,
+ OFGZIPStreamStateComment,
+ OFGZIPStreamStateHeaderCRC16,
+ OFGZIPStreamStateData,
+ OFGZIPStreamStateCRC32,
+ OFGZIPStreamStateUncompressedSize
} _state;
- enum of_gzip_stream_flags {
- OF_GZIP_STREAM_FLAG_TEXT = 0x01,
- OF_GZIP_STREAM_FLAG_HEADER_CRC16 = 0x02,
- OF_GZIP_STREAM_FLAG_EXTRA = 0x04,
- OF_GZIP_STREAM_FLAG_NAME = 0x08,
- OF_GZIP_STREAM_FLAG_COMMENT = 0x10
+ enum {
+ OFGZIPStreamFlagText = 0x01,
+ OFGZIPStreamFlagHeaderCRC16 = 0x02,
+ OFGZIPStreamFlagExtra = 0x04,
+ OFGZIPStreamFlagName = 0x08,
+ OFGZIPStreamFlagComment = 0x10
} _flags;
uint8_t _extraFlags;
- enum of_gzip_stream_operating_system {
- OF_GZIP_STREAM_OPERATING_SYSTEM_FAT = 0,
- OF_GZIP_STREAM_OPERATING_SYSTEM_AMIGA = 1,
- OF_GZIP_STREAM_OPERATING_SYSTEM_VMS = 2,
- OF_GZIP_STREAM_OPERATING_SYSTEM_UNIX = 3,
- OF_GZIP_STREAM_OPERATING_SYSTEM_VM_CMS = 4,
- OF_GZIP_STREAM_OPERATING_SYSTEM_ATARI_TOS = 5,
- OF_GZIP_STREAM_OPERATING_SYSTEM_HPFS = 6,
- OF_GZIP_STREAM_OPERATING_SYSTEM_MACINTOSH = 7,
- OF_GZIP_STREAM_OPERATING_SYSTEM_Z_SYSTEM = 8,
- OF_GZIP_STREAM_OPERATING_SYSTEM_CP_M = 9,
- OF_GZIP_STREAM_OPERATING_SYSTEM_TOPS_20 = 10,
- OF_GZIP_STREAM_OPERATING_SYSTEM_NTFS = 11,
- OF_GZIP_STREAM_OPERATING_SYSTEM_QDO = 12,
- OF_GZIP_STREAM_OPERATING_SYSTEM_ACORN_RISC_OS = 13,
- OF_GZIP_STREAM_OPERATING_SYSTEM_UNKNOWN = 255
- } _operatingSystemMadeOn;
+ OFGZIPStreamOperatingSystem _operatingSystemMadeOn;
size_t _bytesRead;
uint8_t _buffer[4];
OFDate *_Nullable _modificationDate;
uint16_t _extraLength;
uint32_t _CRC32, _uncompressedSize;
@@ -85,11 +90,11 @@
*
* This property is only guaranteed to be available once @ref atEndOfStream is
* true.
*/
@property (readonly, nonatomic)
- enum of_gzip_stream_operating_system operatingSystemMadeOn;
+ OFGZIPStreamOperatingSystem operatingSystemMadeOn;
/**
* @brief The modification date of the original file.
*
* This property is only guaranteed to be available once @ref atEndOfStream is
Index: src/OFGZIPStream.m
==================================================================
--- src/OFGZIPStream.m
+++ src/OFGZIPStream.m
@@ -14,14 +14,13 @@
*/
#include "config.h"
#import "OFGZIPStream.h"
-#import "OFInflateStream.h"
+#import "OFCRC32.h"
#import "OFDate.h"
-
-#import "crc32.h"
+#import "OFInflateStream.h"
#import "OFChecksumMismatchException.h"
#import "OFInvalidFormatException.h"
#import "OFNotImplementedException.h"
#import "OFNotOpenException.h"
@@ -50,12 +49,11 @@
@throw [OFNotImplementedException
exceptionWithSelector: _cmd
object: nil];
_stream = [stream retain];
- _operatingSystemMadeOn =
- OF_GZIP_STREAM_OPERATING_SYSTEM_UNKNOWN;
+ _operatingSystemMadeOn = OFGZIPStreamOperatingSystemUnknown;
_CRC32 = ~0;
} @catch (id e) {
[self release];
@throw e;
}
@@ -82,39 +80,39 @@
for (;;) {
uint8_t byte;
uint32_t CRC32, uncompressedSize;
if (_stream.atEndOfStream) {
- if (_state != OF_GZIP_STREAM_ID1)
+ if (_state != OFGZIPStreamStateID1)
@throw [OFTruncatedDataException exception];
return 0;
}
switch (_state) {
- case OF_GZIP_STREAM_ID1:
- case OF_GZIP_STREAM_ID2:
- case OF_GZIP_STREAM_COMPRESSION_METHOD:
+ case OFGZIPStreamStateID1:
+ case OFGZIPStreamStateID2:
+ case OFGZIPStreamStateCompressionMethod:
if ([_stream readIntoBuffer: &byte length: 1] < 1)
return 0;
- if ((_state == OF_GZIP_STREAM_ID1 && byte != 0x1F) ||
- (_state == OF_GZIP_STREAM_ID2 && byte != 0x8B) ||
- (_state == OF_GZIP_STREAM_COMPRESSION_METHOD &&
+ if ((_state == OFGZIPStreamStateID1 && byte != 0x1F) ||
+ (_state == OFGZIPStreamStateID2 && byte != 0x8B) ||
+ (_state == OFGZIPStreamStateCompressionMethod &&
byte != 8))
@throw [OFInvalidFormatException exception];
_state++;
break;
- case OF_GZIP_STREAM_FLAGS:
+ case OFGZIPStreamStateFlags:
if ([_stream readIntoBuffer: &byte length: 1] < 1)
return 0;
_flags = byte;
_state++;
break;
- case OF_GZIP_STREAM_MODIFICATION_TIME:
+ case OFGZIPStreamStateModificationDate:
_bytesRead += [_stream
readIntoBuffer: _buffer + _bytesRead
length: 4 - _bytesRead];
if (_bytesRead < 4)
@@ -129,26 +127,26 @@
(_buffer[1] << 8) | _buffer[0]];
_bytesRead = 0;
_state++;
break;
- case OF_GZIP_STREAM_EXTRA_FLAGS:
+ case OFGZIPStreamStateExtraFlags:
if ([_stream readIntoBuffer: &byte length: 1] < 1)
return 0;
_extraFlags = byte;
_state++;
break;
- case OF_GZIP_STREAM_OPERATING_SYSTEM:
+ case OFGZIPStreamStateOperatingSystem:
if ([_stream readIntoBuffer: &byte length: 1] < 1)
return 0;
_operatingSystemMadeOn = byte;
_state++;
break;
- case OF_GZIP_STREAM_EXTRA_LENGTH:
- if (!(_flags & OF_GZIP_STREAM_FLAG_EXTRA)) {
+ case OFGZIPStreamStateExtraLength:
+ if (!(_flags & OFGZIPStreamFlagExtra)) {
_state += 2;
break;
}
_bytesRead += [_stream
@@ -160,11 +158,11 @@
_extraLength = (_buffer[1] << 8) | _buffer[0];
_bytesRead = 0;
_state++;
break;
- case OF_GZIP_STREAM_EXTRA:
+ case OFGZIPStreamStateExtra:
{
char tmp[512];
size_t toRead = _extraLength - _bytesRead;
if (toRead > 512)
@@ -178,12 +176,12 @@
return 0;
_bytesRead = 0;
_state++;
break;
- case OF_GZIP_STREAM_NAME:
- if (!(_flags & OF_GZIP_STREAM_FLAG_NAME)) {
+ case OFGZIPStreamStateName:
+ if (!(_flags & OFGZIPStreamFlagName)) {
_state++;
break;
}
do {
@@ -192,12 +190,12 @@
return 0;
} while (byte != 0);
_state++;
break;
- case OF_GZIP_STREAM_COMMENT:
- if (!(_flags & OF_GZIP_STREAM_FLAG_COMMENT)) {
+ case OFGZIPStreamStateComment:
+ if (!(_flags & OFGZIPStreamFlagComment)) {
_state++;
break;
}
do {
@@ -206,12 +204,12 @@
return 0;
} while (byte != 0);
_state++;
break;
- case OF_GZIP_STREAM_HEADER_CRC16:
- if (!(_flags & OF_GZIP_STREAM_FLAG_HEADER_CRC16)) {
+ case OFGZIPStreamStateHeaderCRC16:
+ if (!(_flags & OFGZIPStreamFlagHeaderCRC16)) {
_state++;
break;
}
_bytesRead += [_stream
@@ -228,21 +226,21 @@
*/
_bytesRead = 0;
_state++;
break;
- case OF_GZIP_STREAM_DATA:
+ case OFGZIPStreamStateData:
if (_inflateStream == nil)
_inflateStream = [[OFInflateStream alloc]
initWithStream: _stream];
if (!_inflateStream.atEndOfStream) {
size_t bytesRead = [_inflateStream
readIntoBuffer: buffer
length: length];
- _CRC32 = of_crc32(_CRC32, buffer, bytesRead);
+ _CRC32 = OFCRC32(_CRC32, buffer, bytesRead);
_uncompressedSize += bytesRead;
return bytesRead;
}
@@ -249,11 +247,11 @@
[_inflateStream release];
_inflateStream = nil;
_state++;
break;
- case OF_GZIP_STREAM_CRC32:
+ case OFGZIPStreamStateCRC32:
_bytesRead += [_stream readIntoBuffer: _buffer
length: 4 - _bytesRead];
if (_bytesRead < 4)
return 0;
@@ -273,11 +271,11 @@
_bytesRead = 0;
_CRC32 = ~0;
_state++;
break;
- case OF_GZIP_STREAM_UNCOMPRESSED_SIZE:
+ case OFGZIPStreamStateUncompressedSize:
_bytesRead += [_stream readIntoBuffer: _buffer
length: 4 - _bytesRead];
uncompressedSize = ((uint32_t)_buffer[3] << 24) |
(_buffer[2] << 16) | (_buffer[1] << 8) | _buffer[0];
@@ -292,11 +290,11 @@
expectedChecksum: expected];
}
_bytesRead = 0;
_uncompressedSize = 0;
- _state = OF_GZIP_STREAM_ID1;
+ _state = OFGZIPStreamStateID1;
break;
}
}
}
@@ -308,11 +306,11 @@
return _stream.atEndOfStream;
}
- (bool)hasDataInReadBuffer
{
- if (_state == OF_GZIP_STREAM_DATA)
+ if (_state == OFGZIPStreamStateData)
return (super.hasDataInReadBuffer ||
_inflateStream.hasDataInReadBuffer);
return (super.hasDataInReadBuffer || _stream.hasDataInReadBuffer);
}
Index: src/OFHTTPClient.m
==================================================================
--- src/OFHTTPClient.m
+++ src/OFHTTPClient.m
@@ -26,10 +26,11 @@
#import "OFHTTPRequest.h"
#import "OFHTTPResponse.h"
#import "OFKernelEventObserver.h"
#import "OFNumber.h"
#import "OFRunLoop.h"
+#import "OFSocket+Private.h"
#import "OFString.h"
#import "OFTCPSocket.h"
#import "OFURL.h"
#import "OFAlreadyConnectedException.h"
@@ -45,13 +46,11 @@
#import "OFTruncatedDataException.h"
#import "OFUnsupportedProtocolException.h"
#import "OFUnsupportedVersionException.h"
#import "OFWriteFailedException.h"
-#import "socket_helpers.h"
-
-#define REDIRECTS_DEFAULT 10
+static const unsigned int defaultRedirects = 10;
OF_DIRECT_MEMBERS
@interface OFHTTPClientRequestHandler: OFObject
{
@public
@@ -114,11 +113,11 @@
static OFString *
constructRequestString(OFHTTPRequest *request)
{
void *pool = objc_autoreleasePoolPush();
- of_http_request_method_t method = request.method;
+ OFHTTPRequestMethod method = request.method;
OFURL *URL = request.URL;
OFString *path;
OFString *user = URL.user, *password = URL.password;
OFMutableString *requestString;
OFMutableDictionary OF_GENERIC(OFString *, OFString *) *headers;
@@ -130,11 +129,11 @@
path = URL.URLEncodedPath;
else
path = @"/";
requestString = [OFMutableString stringWithFormat:
- @"%s %@", of_http_request_method_to_string(method), path];
+ @"%s %@", OFHTTPRequestMethodName(method), path];
if (URL.query != nil) {
[requestString appendString: @"?"];
[requestString appendString: URL.URLEncodedQuery];
}
@@ -217,37 +216,36 @@
{
unsigned char *str = (unsigned char *)str_;
bool firstLetter = true;
while (*str != '\0') {
- if (!of_ascii_isalpha(*str)) {
+ if (!OFASCIIIsAlpha(*str)) {
firstLetter = true;
str++;
continue;
}
*str = (firstLetter
- ? of_ascii_toupper(*str)
- : of_ascii_tolower(*str));
+ ? OFASCIIToUpper(*str) : OFASCIIToLower(*str));
firstLetter = false;
str++;
}
}
static bool
-defaultShouldFollow(of_http_request_method_t method, short statusCode)
+defaultShouldFollow(OFHTTPRequestMethod method, short statusCode)
{
bool follow;
/*
* 301, 302 and 307 should only redirect with user confirmation if the
* request method is not GET or HEAD. Asking the delegate and getting
* true returned is considered user confirmation.
*/
- if (method == OF_HTTP_REQUEST_METHOD_GET ||
- method == OF_HTTP_REQUEST_METHOD_HEAD)
+ if (method == OFHTTPRequestMethodGet ||
+ method == OFHTTPRequestMethodHead)
follow = true;
/* 303 should always be redirected and converted to a GET request. */
else if (statusCode == 303)
follow = true;
else
@@ -319,11 +317,11 @@
else
keepAlive = true;
} else {
if (connectionHeader != nil)
keepAlive = ([connectionHeader caseInsensitiveCompare:
- @"keep-alive"] == OF_ORDERED_SAME);
+ @"keep-alive"] == OFOrderedSame);
else
keepAlive = false;
}
if (keepAlive) {
@@ -330,11 +328,11 @@
response.of_keepAlive = true;
_client->_socket = [sock retain];
_client->_lastURL = [URL copy];
_client->_lastWasHEAD =
- (_request.method == OF_HTTP_REQUEST_METHOD_HEAD);
+ (_request.method == OFHTTPRequestMethodHead);
_client->_lastResponse = [response retain];
}
if (_redirects > 0 && (_status == 301 || _status == 302 ||
_status == 303 || _status == 307) &&
@@ -346,20 +344,20 @@
newURL = [OFURL URLWithString: location
relativeToURL: URL];
newURLScheme = newURL.scheme;
if ([newURLScheme caseInsensitiveCompare: @"http"] !=
- OF_ORDERED_SAME &&
+ OFOrderedSame &&
[newURLScheme caseInsensitiveCompare: @"https"] !=
- OF_ORDERED_SAME)
+ OFOrderedSame)
follow = false;
if (!_client->_allowsInsecureRedirects &&
[URL.scheme caseInsensitiveCompare: @"https"] ==
- OF_ORDERED_SAME &&
+ OFOrderedSame &&
[newURLScheme caseInsensitiveCompare: @"http"] ==
- OF_ORDERED_SAME)
+ OFOrderedSame)
follow = false;
if (follow && [_client->_delegate respondsToSelector: @selector(
client:shouldFollowRedirect:statusCode:request:response:)])
follow = [_client->_delegate client: _client
@@ -399,11 +397,11 @@
if ([key hasPrefix: @"Content-"] ||
[key hasPrefix: @"Transfer-"])
[newHeaders
removeObjectForKey: key];
- newRequest.method = OF_HTTP_REQUEST_METHOD_GET;
+ newRequest.method = OFHTTPRequestMethodGet;
}
newRequest.URL = newURL;
newRequest.headers = newHeaders;
@@ -458,27 +456,26 @@
if (![line hasPrefix: @"HTTP/"] || line.length < 9 ||
[line characterAtIndex: 8] != ' ')
@throw [OFInvalidServerReplyException exception];
- _version = [[line substringWithRange: of_range(5, 3)] copy];
+ _version = [[line substringWithRange: OFRangeMake(5, 3)] copy];
if (![_version isEqual: @"1.0"] && ![_version isEqual: @"1.1"])
@throw [OFUnsupportedVersionException
exceptionWithVersion: _version];
- status = [line substringWithRange: of_range(9, 3)].longLongValue;
+ status = [line substringWithRange: OFRangeMake(9, 3)].longLongValue;
if (status < 0 || status > 599)
@throw [OFInvalidServerReplyException exception];
_status = (short)status;
return true;
}
-- (bool)handleServerHeader: (OFString *)line
- socket: (OFTCPSocket *)sock
+- (bool)handleServerHeader: (OFString *)line socket: (OFTCPSocket *)sock
{
OFString *key, *value, *old;
const char *lineC, *tmp;
char *keyC;
@@ -507,20 +504,20 @@
lineC = line.UTF8String;
if ((tmp = strchr(lineC, ':')) == NULL)
@throw [OFInvalidServerReplyException exception];
- keyC = of_alloc(tmp - lineC + 1, 1);
+ keyC = OFAllocMemory(tmp - lineC + 1, 1);
memcpy(keyC, lineC, tmp - lineC);
keyC[tmp - lineC] = '\0';
normalizeKey(keyC);
@try {
key = [OFString stringWithUTF8StringNoCopy: keyC
freeWhenDone: true];
} @catch (id e) {
- free(keyC);
+ OFFreeMemory(keyC);
@throw e;
}
do {
tmp++;
@@ -567,11 +564,11 @@
return ret;
}
- (OFString *)stream: (OFStream *)stream
didWriteString: (OFString *)string
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
bytesWritten: (size_t)bytesWritten
exception: (id)exception
{
OFDictionary OF_GENERIC(OFString *, OFString *) *headers;
bool chunked;
@@ -699,16 +696,16 @@
OFNumber *URLPort;
[_client close];
if ([URL.scheme caseInsensitiveCompare: @"https"] ==
- OF_ORDERED_SAME) {
- if (of_tls_socket_class == Nil)
+ OFOrderedSame) {
+ if (OFTLSSocketClass == Nil)
@throw [OFUnsupportedProtocolException
exceptionWithURL: URL];
- sock = [[[of_tls_socket_class alloc] init] autorelease];
+ sock = [[[OFTLSSocketClass alloc] init] autorelease];
port = 443;
} else {
sock = [OFTCPSocket socket];
port = 80;
}
@@ -995,19 +992,19 @@
if (line == nil)
return 0;
pos = [line rangeOfString: @";"].location;
- if (pos != OF_NOT_FOUND)
+ if (pos != OFNotFound)
line = [line substringToIndex: pos];
if (line.length < 1) {
/*
* We have read the empty string because the socket is
* at end of stream.
*/
- if (_socket.atEndOfStream && pos == OF_NOT_FOUND)
+ if (_socket.atEndOfStream && pos == OFNotFound)
@throw [OFTruncatedDataException exception];
else
@throw [OFInvalidServerReplyException
exception];
}
@@ -1206,11 +1203,11 @@
[super dealloc];
}
- (OFHTTPResponse *)performRequest: (OFHTTPRequest *)request
{
- return [self performRequest: request redirects: REDIRECTS_DEFAULT];
+ return [self performRequest: request redirects: defaultRedirects];
}
- (OFHTTPResponse *)performRequest: (OFHTTPRequest *)request
redirects: (unsigned int)redirects
{
@@ -1228,22 +1225,22 @@
return [response autorelease];
}
- (void)asyncPerformRequest: (OFHTTPRequest *)request
{
- [self asyncPerformRequest: request redirects: REDIRECTS_DEFAULT];
+ [self asyncPerformRequest: request redirects: defaultRedirects];
}
- (void)asyncPerformRequest: (OFHTTPRequest *)request
redirects: (unsigned int)redirects
{
void *pool = objc_autoreleasePoolPush();
OFURL *URL = request.URL;
OFString *scheme = URL.scheme;
- if ([scheme caseInsensitiveCompare: @"http"] != OF_ORDERED_SAME &&
- [scheme caseInsensitiveCompare: @"https"] != OF_ORDERED_SAME)
+ if ([scheme caseInsensitiveCompare: @"http"] != OFOrderedSame &&
+ [scheme caseInsensitiveCompare: @"https"] != OFOrderedSame)
@throw [OFUnsupportedProtocolException exceptionWithURL: URL];
if (_inProgress)
/* TODO: Find a better exception */
@throw [OFAlreadyConnectedException exception];
Index: src/OFHTTPCookie.m
==================================================================
--- src/OFHTTPCookie.m
+++ src/OFHTTPCookie.m
@@ -66,117 +66,117 @@
{
OFMutableArray OF_GENERIC(OFHTTPCookie *) *ret = [OFMutableArray array];
void *pool = objc_autoreleasePoolPush();
OFString *string = [headerFields objectForKey: @"Set-Cookie"];
OFString *domain = URL.host;
- const of_unichar_t *characters = string.characters;
- size_t length = string.length, last = 0;
- enum {
- STATE_PRE_NAME,
- STATE_NAME,
- STATE_EXPECT_VALUE,
- STATE_VALUE,
- STATE_QUOTED_VALUE,
- STATE_POST_QUOTED_VALUE,
- STATE_PRE_ATTR_NAME,
- STATE_ATTR_NAME,
- STATE_ATTR_VALUE
- } state = STATE_PRE_NAME;
- OFString *name = nil, *value = nil;
-
- for (size_t i = 0; i < length; i++) {
- switch (state) {
- case STATE_PRE_NAME:
- if (characters[i] != ' ') {
- state = STATE_NAME;
- last = i;
- i--;
- }
- break;
- case STATE_NAME:
- if (characters[i] == '=') {
- name = [string substringWithRange:
- of_range(last, i - last)];
- state = STATE_EXPECT_VALUE;
- }
- break;
- case STATE_EXPECT_VALUE:
- if (characters[i] == '"') {
- state = STATE_QUOTED_VALUE;
- last = i + 1;
- } else {
- state = STATE_VALUE;
- last = i;
- }
-
- i--;
- break;
- case STATE_VALUE:
- if (characters[i] == ';' || characters[i] == ',') {
- value = [string substringWithRange:
- of_range(last, i - last)];
-
- [ret addObject:
- [OFHTTPCookie cookieWithName: name
- value: value
- domain: domain]];
-
- state = (characters[i] == ';'
- ? STATE_PRE_ATTR_NAME : STATE_PRE_NAME);
- }
- break;
- case STATE_QUOTED_VALUE:
- if (characters[i] == '"') {
- value = [string substringWithRange:
- of_range(last, i - last)];
- [ret addObject:
- [OFHTTPCookie cookieWithName: name
- value: value
- domain: domain]];
-
- state = STATE_POST_QUOTED_VALUE;
- }
- break;
- case STATE_POST_QUOTED_VALUE:
- if (characters[i] == ';')
- state = STATE_PRE_ATTR_NAME;
- else if (characters[i] == ',')
- state = STATE_PRE_NAME;
- else
- @throw [OFInvalidFormatException exception];
-
- break;
- case STATE_PRE_ATTR_NAME:
- if (characters[i] != ' ') {
- state = STATE_ATTR_NAME;
- last = i;
- i--;
- }
- break;
- case STATE_ATTR_NAME:
- if (characters[i] == '=') {
- name = [string substringWithRange:
- of_range(last, i - last)];
-
- state = STATE_ATTR_VALUE;
- last = i + 1;
- } else if (characters[i] == ';' ||
- characters[i] == ',') {
- name = [string substringWithRange:
- of_range(last, i - last)];
-
- handleAttribute(ret.lastObject, name, nil);
-
- state = (characters[i] == ';'
- ? STATE_PRE_ATTR_NAME : STATE_PRE_NAME);
- }
-
- break;
- case STATE_ATTR_VALUE:
- if (characters[i] == ';' || characters[i] == ',') {
- value = [string substringWithRange:
- of_range(last, i - last)];
+ const OFUnichar *characters = string.characters;
+ size_t length = string.length, last = 0;
+ enum {
+ statePreName,
+ stateName,
+ stateExpectValue,
+ stateValue,
+ stateQuotedValue,
+ statePostQuotedValue,
+ statePreAttrName,
+ stateAttrName,
+ stateAttrValue
+ } state = statePreName;
+ OFString *name = nil, *value = nil;
+
+ for (size_t i = 0; i < length; i++) {
+ switch (state) {
+ case statePreName:
+ if (characters[i] != ' ') {
+ state = stateName;
+ last = i;
+ i--;
+ }
+ break;
+ case stateName:
+ if (characters[i] == '=') {
+ name = [string substringWithRange:
+ OFRangeMake(last, i - last)];
+ state = stateExpectValue;
+ }
+ break;
+ case stateExpectValue:
+ if (characters[i] == '"') {
+ state = stateQuotedValue;
+ last = i + 1;
+ } else {
+ state = stateValue;
+ last = i;
+ }
+
+ i--;
+ break;
+ case stateValue:
+ if (characters[i] == ';' || characters[i] == ',') {
+ value = [string substringWithRange:
+ OFRangeMake(last, i - last)];
+
+ [ret addObject:
+ [OFHTTPCookie cookieWithName: name
+ value: value
+ domain: domain]];
+
+ state = (characters[i] == ';'
+ ? statePreAttrName : statePreName);
+ }
+ break;
+ case stateQuotedValue:
+ if (characters[i] == '"') {
+ value = [string substringWithRange:
+ OFRangeMake(last, i - last)];
+ [ret addObject:
+ [OFHTTPCookie cookieWithName: name
+ value: value
+ domain: domain]];
+
+ state = statePostQuotedValue;
+ }
+ break;
+ case statePostQuotedValue:
+ if (characters[i] == ';')
+ state = statePreAttrName;
+ else if (characters[i] == ',')
+ state = statePreName;
+ else
+ @throw [OFInvalidFormatException exception];
+
+ break;
+ case statePreAttrName:
+ if (characters[i] != ' ') {
+ state = stateAttrName;
+ last = i;
+ i--;
+ }
+ break;
+ case stateAttrName:
+ if (characters[i] == '=') {
+ name = [string substringWithRange:
+ OFRangeMake(last, i - last)];
+
+ state = stateAttrValue;
+ last = i + 1;
+ } else if (characters[i] == ';' ||
+ characters[i] == ',') {
+ name = [string substringWithRange:
+ OFRangeMake(last, i - last)];
+
+ handleAttribute(ret.lastObject, name, nil);
+
+ state = (characters[i] == ';'
+ ? statePreAttrName : statePreName);
+ }
+
+ break;
+ case stateAttrValue:
+ if (characters[i] == ';' || characters[i] == ',') {
+ value = [string substringWithRange:
+ OFRangeMake(last, i - last)];
/*
* Expires often contains a comma, even though
* the comma is used as a separator for
* concatenating headers as per RFC 2616,
@@ -183,11 +183,11 @@
* meaning RFC 6265 contradicts RFC 2616.
* Solve this by special casing this.
*/
if (characters[i] == ',' &&
[name caseInsensitiveCompare: @"expires"] ==
- OF_ORDERED_SAME && value.length == 3 &&
+ OFOrderedSame && value.length == 3 &&
([value isEqual: @"Mon"] ||
[value isEqual: @"Tue"] ||
[value isEqual: @"Wed"] ||
[value isEqual: @"Thu"] ||
[value isEqual: @"Fri"] ||
@@ -196,49 +196,49 @@
break;
handleAttribute(ret.lastObject, name, value);
state = (characters[i] == ';'
- ? STATE_PRE_ATTR_NAME : STATE_PRE_NAME);
+ ? statePreAttrName : statePreName);
}
break;
}
}
switch (state) {
- case STATE_PRE_NAME:
- case STATE_POST_QUOTED_VALUE:
- case STATE_PRE_ATTR_NAME:
+ case statePreName:
+ case statePostQuotedValue:
+ case statePreAttrName:
break;
- case STATE_NAME:
- case STATE_QUOTED_VALUE:
+ case stateName:
+ case stateQuotedValue:
@throw [OFInvalidFormatException exception];
break;
- case STATE_VALUE:
+ case stateValue:
value = [string substringWithRange:
- of_range(last, length - last)];
+ OFRangeMake(last, length - last)];
[ret addObject: [OFHTTPCookie cookieWithName: name
value: value
domain: domain]];
break;
/* We end up here if the cookie is just foo= */
- case STATE_EXPECT_VALUE:
+ case stateExpectValue:
[ret addObject: [OFHTTPCookie cookieWithName: name
value: @""
domain: domain]];
break;
- case STATE_ATTR_NAME:
+ case stateAttrName:
if (last != length) {
name = [string substringWithRange:
- of_range(last, length - last)];
+ OFRangeMake(last, length - last)];
handleAttribute(ret.lastObject, name, nil);
}
break;
- case STATE_ATTR_VALUE:
+ case stateAttrValue:
value = [string substringWithRange:
- of_range(last, length - last)];
+ OFRangeMake(last, length - last)];
handleAttribute(ret.lastObject, name, value);
break;
}
@@ -361,22 +361,22 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
- OF_HASH_ADD_HASH(hash, _name.hash);
- OF_HASH_ADD_HASH(hash, _value.hash);
- OF_HASH_ADD_HASH(hash, _domain.hash);
- OF_HASH_ADD_HASH(hash, _path.hash);
- OF_HASH_ADD_HASH(hash, _expires.hash);
- OF_HASH_ADD(hash, _secure);
- OF_HASH_ADD(hash, _HTTPOnly);
- OF_HASH_ADD_HASH(hash, _extensions.hash);
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+ OFHashAddHash(&hash, _name.hash);
+ OFHashAddHash(&hash, _value.hash);
+ OFHashAddHash(&hash, _domain.hash);
+ OFHashAddHash(&hash, _path.hash);
+ OFHashAddHash(&hash, _expires.hash);
+ OFHashAdd(&hash, _secure);
+ OFHashAdd(&hash, _HTTPOnly);
+ OFHashAddHash(&hash, _extensions.hash);
+ OFHashFinalize(&hash);
return hash;
}
- (id)copy
Index: src/OFHTTPCookieManager.m
==================================================================
--- src/OFHTTPCookieManager.m
+++ src/OFHTTPCookieManager.m
@@ -61,11 +61,11 @@
if (![cookie.path hasPrefix: @"/"])
cookie.path = @"/";
if (cookie.secure &&
- [URL.scheme caseInsensitiveCompare: @"https"] != OF_ORDERED_SAME) {
+ [URL.scheme caseInsensitiveCompare: @"https"] != OFOrderedSame) {
objc_autoreleasePoolPop(pool);
return;
}
cookieDomain = cookie.domain.lowercaseString;
@@ -119,11 +119,11 @@
expires = cookie.expires;
if (expires != nil && expires.timeIntervalSinceNow <= 0)
continue;
if (cookie.secure && [URL.scheme caseInsensitiveCompare:
- @"https"] != OF_ORDERED_SAME)
+ @"https"] != OFOrderedSame)
continue;
pool = objc_autoreleasePoolPush();
cookieDomain = cookie.domain.lowercaseString;
Index: src/OFHTTPRequest.h
==================================================================
--- src/OFHTTPRequest.h
+++ src/OFHTTPRequest.h
@@ -12,14 +12,13 @@
* LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
* file.
*/
#import "OFObject.h"
+#import "OFSocket.h"
#import "OFString.h"
-#import "socket.h"
-
OF_ASSUME_NONNULL_BEGIN
@class OFURL;
@class OFDictionary OF_GENERIC(KeyType, ObjectType);
@class OFData;
@@ -30,54 +29,51 @@
/**
* @brief The type of an HTTP request.
*/
typedef enum {
/** OPTIONS */
- OF_HTTP_REQUEST_METHOD_OPTIONS,
+ OFHTTPRequestMethodOptions,
/** GET */
- OF_HTTP_REQUEST_METHOD_GET,
+ OFHTTPRequestMethodGet,
/** HEAD */
- OF_HTTP_REQUEST_METHOD_HEAD,
+ OFHTTPRequestMethodHead,
/** POST */
- OF_HTTP_REQUEST_METHOD_POST,
+ OFHTTPRequestMethodPost,
/** PUT */
- OF_HTTP_REQUEST_METHOD_PUT,
+ OFHTTPRequestMethodPut,
/** DELETE */
- OF_HTTP_REQUEST_METHOD_DELETE,
+ OFHTTPRequestMethodDelete,
/** TRACE */
- OF_HTTP_REQUEST_METHOD_TRACE,
+ OFHTTPRequestMethodTrace,
/** CONNECT */
- OF_HTTP_REQUEST_METHOD_CONNECT
-} of_http_request_method_t;
+ OFHTTPRequestMethodConnect
+} OFHTTPRequestMethod;
/**
- * @struct of_http_request_protocol_version_t \
- * OFHTTPRequest.h ObjFW/OFHTTPRequest.h
+ * @struct OFHTTPRequestProtocolVersion OFHTTPRequest.h ObjFW/OFHTTPRequest.h
*
* @brief The HTTP version of the HTTP request.
*/
-struct OF_BOXABLE of_http_request_protocol_version_t {
+typedef struct OF_BOXABLE {
/** The major of the HTTP version */
unsigned char major;
/** The minor of the HTTP version */
unsigned char minor;
-};
-typedef struct of_http_request_protocol_version_t
- of_http_request_protocol_version_t;
+} OFHTTPRequestProtocolVersion;
/**
* @class OFHTTPRequest OFHTTPRequest.h ObjFW/OFHTTPRequest.h
*
* @brief A class for storing HTTP requests.
*/
@interface OFHTTPRequest: OFObject
{
OFURL *_URL;
- of_http_request_method_t _method;
- of_http_request_protocol_version_t _protocolVersion;
+ OFHTTPRequestMethod _method;
+ OFHTTPRequestProtocolVersion _protocolVersion;
OFDictionary OF_GENERIC(OFString *, OFString *) *_Nullable _headers;
- of_socket_address_t _remoteAddress;
+ OFSocketAddress _remoteAddress;
bool _hasRemoteAddress;
OF_RESERVE_IVARS(OFHTTPRequest, 4)
}
/**
@@ -86,21 +82,21 @@
@property (copy, nonatomic) OFURL *URL;
/**
* @brief The protocol version of the HTTP request.
*/
-@property (nonatomic) of_http_request_protocol_version_t protocolVersion;
+@property (nonatomic) OFHTTPRequestProtocolVersion protocolVersion;
/**
* @brief The protocol version of the HTTP request as a string.
*/
@property (copy, nonatomic) OFString *protocolVersionString;
/**
* @brief The request method of the HTTP request.
*/
-@property (nonatomic) of_http_request_method_t method;
+@property (nonatomic) OFHTTPRequestMethod method;
/**
* @brief The headers for the HTTP request.
*/
@property OF_NULLABLE_PROPERTY (copy, nonatomic)
@@ -109,12 +105,11 @@
/**
* @brief The remote address from which the request originates.
*
* @note The setter creates a copy of the remote address.
*/
-@property OF_NULLABLE_PROPERTY (nonatomic)
- const of_socket_address_t *remoteAddress;
+@property OF_NULLABLE_PROPERTY (nonatomic) const OFSocketAddress *remoteAddress;
/**
* @brief Creates a new OFHTTPRequest.
*
* @return A new, autoreleased OFHTTPRequest
@@ -145,21 +140,20 @@
* @brief Returns a C string describing the specified request method.
*
* @param method The request method which should be described as a C string
* @return A C string describing the specified request method
*/
-extern const char *_Nullable of_http_request_method_to_string(
- of_http_request_method_t method);
+extern const char *_Nullable OFHTTPRequestMethodName(
+ OFHTTPRequestMethod method);
/**
* @brief Returns the request method for the specified string.
*
* @param string The string for which the request method should be returned
* @return The request method for the specified string
*/
-extern of_http_request_method_t of_http_request_method_from_string(
- OFString *string);
+extern OFHTTPRequestMethod OFHTTPRequestMethodParseName(OFString *string);
#ifdef __cplusplus
}
#endif
OF_ASSUME_NONNULL_END
Index: src/OFHTTPRequest.m
==================================================================
--- src/OFHTTPRequest.m
+++ src/OFHTTPRequest.m
@@ -28,53 +28,53 @@
#import "OFInvalidFormatException.h"
#import "OFOutOfRangeException.h"
#import "OFUnsupportedVersionException.h"
const char *
-of_http_request_method_to_string(of_http_request_method_t method)
+OFHTTPRequestMethodName(OFHTTPRequestMethod method)
{
switch (method) {
- case OF_HTTP_REQUEST_METHOD_OPTIONS:
+ case OFHTTPRequestMethodOptions:
return "OPTIONS";
- case OF_HTTP_REQUEST_METHOD_GET:
+ case OFHTTPRequestMethodGet:
return "GET";
- case OF_HTTP_REQUEST_METHOD_HEAD:
+ case OFHTTPRequestMethodHead:
return "HEAD";
- case OF_HTTP_REQUEST_METHOD_POST:
+ case OFHTTPRequestMethodPost:
return "POST";
- case OF_HTTP_REQUEST_METHOD_PUT:
+ case OFHTTPRequestMethodPut:
return "PUT";
- case OF_HTTP_REQUEST_METHOD_DELETE:
+ case OFHTTPRequestMethodDelete:
return "DELETE";
- case OF_HTTP_REQUEST_METHOD_TRACE:
+ case OFHTTPRequestMethodTrace:
return "TRACE";
- case OF_HTTP_REQUEST_METHOD_CONNECT:
+ case OFHTTPRequestMethodConnect:
return "CONNECT";
}
return NULL;
}
-of_http_request_method_t
-of_http_request_method_from_string(OFString *string)
+OFHTTPRequestMethod
+OFHTTPRequestMethodParseName(OFString *string)
{
if ([string isEqual: @"OPTIONS"])
- return OF_HTTP_REQUEST_METHOD_OPTIONS;
+ return OFHTTPRequestMethodOptions;
if ([string isEqual: @"GET"])
- return OF_HTTP_REQUEST_METHOD_GET;
+ return OFHTTPRequestMethodGet;
if ([string isEqual: @"HEAD"])
- return OF_HTTP_REQUEST_METHOD_HEAD;
+ return OFHTTPRequestMethodHead;
if ([string isEqual: @"POST"])
- return OF_HTTP_REQUEST_METHOD_POST;
+ return OFHTTPRequestMethodPost;
if ([string isEqual: @"PUT"])
- return OF_HTTP_REQUEST_METHOD_PUT;
+ return OFHTTPRequestMethodPut;
if ([string isEqual: @"DELETE"])
- return OF_HTTP_REQUEST_METHOD_DELETE;
+ return OFHTTPRequestMethodDelete;
if ([string isEqual: @"TRACE"])
- return OF_HTTP_REQUEST_METHOD_TRACE;
+ return OFHTTPRequestMethodTrace;
if ([string isEqual: @"CONNECT"])
- return OF_HTTP_REQUEST_METHOD_CONNECT;
+ return OFHTTPRequestMethodConnect;
@throw [OFInvalidArgumentException exception];
}
@implementation OFHTTPRequest
@@ -92,11 +92,11 @@
- (instancetype)init
{
self = [super init];
- _method = OF_HTTP_REQUEST_METHOD_GET;
+ _method = OFHTTPRequestMethodGet;
_protocolVersion.major = 1;
_protocolVersion.minor = 1;
return self;
}
@@ -121,19 +121,19 @@
[_headers release];
[super dealloc];
}
-- (void)setRemoteAddress: (const of_socket_address_t *)remoteAddress
+- (void)setRemoteAddress: (const OFSocketAddress *)remoteAddress
{
_hasRemoteAddress = (remoteAddress != NULL);
if (_hasRemoteAddress)
_remoteAddress = *remoteAddress;
}
-- (const of_socket_address_t *)remoteAddress
+- (const OFSocketAddress *)remoteAddress
{
if (_hasRemoteAddress)
return &_remoteAddress;
return NULL;
@@ -175,36 +175,36 @@
![request->_URL isEqual: _URL] ||
![request->_headers isEqual: _headers])
return false;
if (request.remoteAddress != self.remoteAddress &&
- !of_socket_address_equal(request.remoteAddress, self.remoteAddress))
+ !OFSocketAddressEqual(request.remoteAddress, self.remoteAddress))
return false;
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD(hash, _method);
- OF_HASH_ADD(hash, _protocolVersion.major);
- OF_HASH_ADD(hash, _protocolVersion.minor);
- OF_HASH_ADD_HASH(hash, _URL.hash);
- OF_HASH_ADD_HASH(hash, _headers.hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAdd(&hash, _method);
+ OFHashAdd(&hash, _protocolVersion.major);
+ OFHashAdd(&hash, _protocolVersion.minor);
+ OFHashAddHash(&hash, _URL.hash);
+ OFHashAddHash(&hash, _headers.hash);
if (_hasRemoteAddress)
- OF_HASH_ADD_HASH(hash, of_socket_address_hash(&_remoteAddress));
+ OFHashAddHash(&hash, OFSocketAddressHash(&_remoteAddress));
- OF_HASH_FINALIZE(hash);
+ OFHashFinalize(&hash);
return hash;
}
-- (void)setProtocolVersion: (of_http_request_protocol_version_t)protocolVersion
+- (void)setProtocolVersion: (OFHTTPRequestProtocolVersion)protocolVersion
{
if (protocolVersion.major != 1 || protocolVersion.minor > 1)
@throw [OFUnsupportedVersionException exceptionWithVersion:
[OFString stringWithFormat: @"%hhu.%hhu",
protocolVersion.major,
@@ -211,21 +211,21 @@
protocolVersion.minor]];
_protocolVersion = protocolVersion;
}
-- (of_http_request_protocol_version_t)protocolVersion
+- (OFHTTPRequestProtocolVersion)protocolVersion
{
return _protocolVersion;
}
- (void)setProtocolVersionString: (OFString *)string
{
void *pool = objc_autoreleasePoolPush();
OFArray *components = [string componentsSeparatedByString: @"."];
unsigned long long major, minor;
- of_http_request_protocol_version_t protocolVersion;
+ OFHTTPRequestProtocolVersion protocolVersion;
if (components.count != 2)
@throw [OFInvalidFormatException exception];
major = [components.firstObject unsignedLongLongValue];
@@ -250,20 +250,19 @@
}
- (OFString *)description
{
void *pool = objc_autoreleasePoolPush();
- const char *method = of_http_request_method_to_string(_method);
+ const char *method = OFHTTPRequestMethodName(_method);
OFString *indentedHeaders, *remoteAddress, *ret;
indentedHeaders = [_headers.description
stringByReplacingOccurrencesOfString: @"\n"
withString: @"\n\t"];
if (_hasRemoteAddress)
- remoteAddress =
- of_socket_address_ip_string(&_remoteAddress, NULL);
+ remoteAddress = OFSocketAddressString(&_remoteAddress);
else
remoteAddress = nil;
ret = [[OFString alloc] initWithFormat:
@"<%@:\n\tURL = %@\n"
Index: src/OFHTTPResponse.h
==================================================================
--- src/OFHTTPResponse.h
+++ src/OFHTTPResponse.h
@@ -26,20 +26,20 @@
*
* @brief A class for representing an HTTP request reply as a stream.
*/
@interface OFHTTPResponse: OFStream
{
- of_http_request_protocol_version_t _protocolVersion;
+ OFHTTPRequestProtocolVersion _protocolVersion;
short _statusCode;
OFDictionary OF_GENERIC(OFString *, OFString *) *_headers;
OF_RESERVE_IVARS(OFHTTPResponse, 4)
}
/**
* @brief The protocol version of the HTTP request reply.
*/
-@property (nonatomic) of_http_request_protocol_version_t protocolVersion;
+@property (nonatomic) OFHTTPRequestProtocolVersion protocolVersion;
/**
* @brief The protocol version of the HTTP request reply as a string.
*/
@property (copy, nonatomic) OFString *protocolVersionString;
@@ -64,11 +64,11 @@
* @brief Returns the reply as a string, trying to detect the encoding and
* falling back to the specified encoding if not detectable.
*
* @return The reply as a string
*/
-- (OFString *)stringWithEncoding: (of_string_encoding_t)encoding;
+- (OFString *)stringWithEncoding: (OFStringEncoding)encoding;
@end
#ifdef __cplusplus
extern "C" {
#endif
@@ -76,11 +76,11 @@
* @brief Returns a description string for the specified HTTP status code.
*
* @param code The HTTP status code to return a description string for
* @return A description string for the specified HTTP status code
*/
-extern OFString *_Nonnull of_http_status_code_to_string(short code);
+extern OFString *_Nonnull OFHTTPStatusCodeString(short code);
#ifdef __cplusplus
}
#endif
OF_ASSUME_NONNULL_END
Index: src/OFHTTPResponse.m
==================================================================
--- src/OFHTTPResponse.m
+++ src/OFHTTPResponse.m
@@ -26,11 +26,11 @@
#import "OFOutOfRangeException.h"
#import "OFTruncatedDataException.h"
#import "OFUnsupportedVersionException.h"
OFString *
-of_http_status_code_to_string(short code)
+OFHTTPStatusCodeString(short code)
{
switch (code) {
case 100:
return @"Continue";
case 101:
@@ -114,64 +114,64 @@
default:
return @"(unknown)";
}
}
-static of_string_encoding_t
+static OFStringEncoding
encodingForContentType(OFString *contentType)
{
const char *UTF8String = contentType.UTF8String;
size_t last, length = contentType.UTF8StringLength;
enum {
- STATE_TYPE,
- STATE_BEFORE_PARAM_NAME,
- STATE_PARAM_NAME,
- STATE_PARAM_VALUE_OR_QUOTE,
- STATE_PARAM_VALUE,
- STATE_PARAM_QUOTED_VALUE,
- STATE_AFTER_PARAM_VALUE
- } state = STATE_TYPE;
+ stateType,
+ stateBeforeParamName,
+ stateParamName,
+ stateParamValueOrQuote,
+ stateParamValue,
+ stateParamQuotedValue,
+ stateAfterParamValue
+ } state = stateType;
OFString *name = nil, *value = nil, *charset = nil;
- of_string_encoding_t ret;
+ OFStringEncoding ret;
last = 0;
for (size_t i = 0; i < length; i++) {
switch (state) {
- case STATE_TYPE:
+ case stateType:
if (UTF8String[i] == ';') {
- state = STATE_BEFORE_PARAM_NAME;
+ state = stateBeforeParamName;
last = i + 1;
}
break;
- case STATE_BEFORE_PARAM_NAME:
+ case stateBeforeParamName:
if (UTF8String[i] == ' ')
last = i + 1;
else {
- state = STATE_PARAM_NAME;
+ state = stateParamName;
i--;
}
break;
- case STATE_PARAM_NAME:
+ case stateParamName:
if (UTF8String[i] == '=') {
name = [OFString
stringWithUTF8String: UTF8String + last
length: i - last];
- state = STATE_PARAM_VALUE_OR_QUOTE;
+ state = stateParamValueOrQuote;
last = i + 1;
}
break;
- case STATE_PARAM_VALUE_OR_QUOTE:
+ case stateParamValueOrQuote:
if (UTF8String[i] == '"') {
- state = STATE_PARAM_QUOTED_VALUE;
+ state = stateParamQuotedValue;
last = i + 1;
} else {
- state = STATE_PARAM_VALUE;
+ state = stateParamValue;
i--;
}
break;
- case STATE_PARAM_VALUE:
+ case stateParamValue:
if (UTF8String[i] == ';') {
value = [OFString
stringWithUTF8String: UTF8String + last
length: i - last];
value =
@@ -178,48 +178,48 @@
value.stringByDeletingTrailingWhitespaces;
if ([name isEqual: @"charset"])
charset = value;
- state = STATE_BEFORE_PARAM_NAME;
+ state = stateBeforeParamName;
last = i + 1;
}
break;
- case STATE_PARAM_QUOTED_VALUE:
+ case stateParamQuotedValue:
if (UTF8String[i] == '"') {
value = [OFString
stringWithUTF8String: UTF8String + last
length: i - last];
if ([name isEqual: @"charset"])
charset = value;
- state = STATE_AFTER_PARAM_VALUE;
+ state = stateAfterParamValue;
}
break;
- case STATE_AFTER_PARAM_VALUE:
+ case stateAfterParamValue:
if (UTF8String[i] == ';') {
- state = STATE_BEFORE_PARAM_NAME;
+ state = stateBeforeParamName;
last = i + 1;
} else if (UTF8String[i] != ' ')
- return OF_STRING_ENCODING_AUTODETECT;
+ return OFStringEncodingAutodetect;
break;
}
}
- if (state == STATE_PARAM_VALUE) {
+ if (state == stateParamValue) {
value = [OFString stringWithUTF8String: UTF8String + last
length: length - last];
value = value.stringByDeletingTrailingWhitespaces;
if ([name isEqual: @"charset"])
charset = value;
}
@try {
- ret = of_string_parse_encoding(charset);
+ ret = OFStringEncodingParseName(charset);
} @catch (OFInvalidArgumentException *e) {
- ret = OF_STRING_ENCODING_AUTODETECT;
+ ret = OFStringEncodingAutodetect;
}
return ret;
}
@@ -247,11 +247,11 @@
[_headers release];
[super dealloc];
}
-- (void)setProtocolVersion: (of_http_request_protocol_version_t)protocolVersion
+- (void)setProtocolVersion: (OFHTTPRequestProtocolVersion)protocolVersion
{
if (protocolVersion.major != 1 || protocolVersion.minor > 1)
@throw [OFUnsupportedVersionException exceptionWithVersion:
[OFString stringWithFormat: @"%hhu.%hhu",
protocolVersion.major,
@@ -258,21 +258,21 @@
protocolVersion.minor]];
_protocolVersion = protocolVersion;
}
-- (of_http_request_protocol_version_t)protocolVersion
+- (OFHTTPRequestProtocolVersion)protocolVersion
{
return _protocolVersion;
}
- (void)setProtocolVersionString: (OFString *)string
{
void *pool = objc_autoreleasePoolPush();
OFArray *components = [string componentsSeparatedByString: @"."];
unsigned long long major, minor;
- of_http_request_protocol_version_t protocolVersion;
+ OFHTTPRequestProtocolVersion protocolVersion;
if (components.count != 2)
@throw [OFInvalidFormatException exception];
major = [components.firstObject unsignedLongLongValue];
@@ -296,25 +296,25 @@
_protocolVersion.minor];
}
- (OFString *)string
{
- return [self stringWithEncoding: OF_STRING_ENCODING_AUTODETECT];
+ return [self stringWithEncoding: OFStringEncodingAutodetect];
}
-- (OFString *)stringWithEncoding: (of_string_encoding_t)encoding
+- (OFString *)stringWithEncoding: (OFStringEncoding)encoding
{
void *pool = objc_autoreleasePoolPush();
OFString *contentType, *contentLengthString, *ret;
OFData *data;
- if (encoding == OF_STRING_ENCODING_AUTODETECT &&
+ if (encoding == OFStringEncodingAutodetect &&
(contentType = [_headers objectForKey: @"Content-Type"]) != nil)
encoding = encodingForContentType(contentType);
- if (encoding == OF_STRING_ENCODING_AUTODETECT)
- encoding = OF_STRING_ENCODING_UTF_8;
+ if (encoding == OFStringEncodingAutodetect)
+ encoding = OFStringEncodingUTF8;
data = [self readDataUntilEndOfStream];
contentLengthString = [_headers objectForKey: @"Content-Length"];
if (contentLengthString != nil) {
Index: src/OFHTTPServer.m
==================================================================
--- src/OFHTTPServer.m
+++ src/OFHTTPServer.m
@@ -24,10 +24,11 @@
#import "OFDate.h"
#import "OFDictionary.h"
#import "OFHTTPRequest.h"
#import "OFHTTPResponse.h"
#import "OFNumber.h"
+#import "OFSocket+Private.h"
#import "OFTCPSocket.h"
#import "OFTLSSocket.h"
#import "OFThread.h"
#import "OFTimer.h"
#import "OFURL.h"
@@ -41,14 +42,10 @@
#import "OFOutOfRangeException.h"
#import "OFTruncatedDataException.h"
#import "OFUnsupportedProtocolException.h"
#import "OFWriteFailedException.h"
-#import "socket_helpers.h"
-
-#define BUFFER_SIZE 1024
-
/*
* FIXME: Key normalization replaces headers like "DNT" with "Dnt".
* FIXME: Errors are not reported to the user.
*/
@@ -75,16 +72,16 @@
@public
OFStreamSocket *_socket;
OFHTTPServer *_server;
OFTimer *_timer;
enum {
- AWAITING_PROLOG,
- PARSING_HEADERS,
- SEND_RESPONSE
+ stateAwaitingProlog,
+ stateParsingHeaders,
+ stateSendResponse
} _state;
uint8_t _HTTPMinorVersion;
- of_http_request_method_t _method;
+ OFHTTPRequestMethod _method;
OFString *_host, *_path;
uint16_t _port;
OFMutableDictionary *_headers;
size_t _contentLength;
OFStream *_requestBody;
@@ -120,38 +117,33 @@
#endif
static OF_INLINE OFString *
normalizedKey(OFString *key)
{
- char *cString = of_strdup(key.UTF8String);
+ char *cString = OFStrDup(key.UTF8String);
unsigned char *tmp = (unsigned char *)cString;
bool firstLetter = true;
- if (cString == NULL)
- @throw [OFOutOfMemoryException
- exceptionWithRequestedSize: strlen(key.UTF8String)];
-
while (*tmp != '\0') {
- if (!of_ascii_isalpha(*tmp)) {
+ if (!OFASCIIIsAlpha(*tmp)) {
firstLetter = true;
tmp++;
continue;
}
*tmp = (firstLetter
- ? of_ascii_toupper(*tmp)
- : of_ascii_tolower(*tmp));
+ ? OFASCIIToUpper(*tmp) : OFASCIIToLower(*tmp));
firstLetter = false;
tmp++;
}
@try {
return [OFString stringWithUTF8StringNoCopy: cString
freeWhenDone: true];
} @catch (id e) {
- free(cString);
+ OFFreeMemory(cString);
@throw e;
}
}
@implementation OFHTTPServerResponse
@@ -187,11 +179,11 @@
OFEnumerator *keyEnumerator, *valueEnumerator;
OFString *key, *value;
[_socket writeFormat: @"HTTP/%@ %hd %@\r\n",
self.protocolVersionString, _statusCode,
- of_http_status_code_to_string(_statusCode)];
+ OFHTTPStatusCodeString(_statusCode)];
headers = [[_headers mutableCopy] autorelease];
if ([headers objectForKey: @"Date"] == nil) {
OFString *date = [[OFDate date]
@@ -296,11 +288,11 @@
scheduledTimerWithTimeInterval: 10
target: _socket
selector: @selector(
cancelAsyncRequests)
repeats: false] retain];
- _state = AWAITING_PROLOG;
+ _state = stateAwaitingProlog;
} @catch (id e) {
[self release];
@throw e;
}
@@ -330,22 +322,22 @@
if (line == nil || exception != nil)
return false;
@try {
switch (_state) {
- case AWAITING_PROLOG:
+ case stateAwaitingProlog:
return [self parseProlog: line];
- case PARSING_HEADERS:
+ case stateParsingHeaders:
return [self parseHeaders: line];
default:
return false;
}
} @catch (OFWriteFailedException *e) {
return false;
}
- OF_ENSURE(0);
+ OFEnsure(0);
}
- (bool)parseProlog: (OFString *)line
{
OFString *method;
@@ -352,12 +344,12 @@
OFMutableString *path;
size_t pos;
@try {
OFString *version = [line
- substringWithRange: of_range(line.length - 9, 9)];
- of_unichar_t tmp;
+ substringWithRange: OFRangeMake(line.length - 9, 9)];
+ OFUnichar tmp;
if (![version hasPrefix: @" HTTP/1."])
return [self sendErrorAndClose: 505];
tmp = [version characterAtIndex: 8];
@@ -368,22 +360,22 @@
} @catch (OFOutOfRangeException *e) {
return [self sendErrorAndClose: 400];
}
pos = [line rangeOfString: @" "].location;
- if (pos == OF_NOT_FOUND)
+ if (pos == OFNotFound)
return [self sendErrorAndClose: 400];
method = [line substringToIndex: pos];
@try {
- _method = of_http_request_method_from_string(method);
+ _method = OFHTTPRequestMethodParseName(method);
} @catch (OFInvalidArgumentException *e) {
return [self sendErrorAndClose: 405];
}
@try {
- of_range_t range = of_range(pos + 1, line.length - pos - 10);
+ OFRange range = OFRangeMake(pos + 1, line.length - pos - 10);
path = [[[line substringWithRange:
range] mutableCopy] autorelease];
} @catch (OFOutOfRangeException *e) {
return [self sendErrorAndClose: 400];
@@ -395,11 +387,11 @@
if (![path hasPrefix: @"/"])
return [self sendErrorAndClose: 400];
_headers = [[OFMutableDictionary alloc] init];
_path = [path copy];
- _state = PARSING_HEADERS;
+ _state = stateParsingHeaders;
return true;
}
- (bool)parseHeaders: (OFString *)line
@@ -437,18 +429,18 @@
[_timer invalidate];
[_timer release];
_timer = nil;
}
- _state = SEND_RESPONSE;
+ _state = stateSendResponse;
[self createResponse];
return false;
}
pos = [line rangeOfString: @":"].location;
- if (pos == OF_NOT_FOUND)
+ if (pos == OFNotFound)
return [self sendErrorAndClose: 400];
key = [line substringToIndex: pos];
value = [line substringFromIndex: pos + 1];
@@ -460,15 +452,14 @@
value = [old stringByAppendingFormat: @",%@", value];
[_headers setObject: value forKey: key];
if ([key isEqual: @"Host"]) {
- pos = [value
- rangeOfString: @":"
- options: OF_STRING_SEARCH_BACKWARDS].location;
+ pos = [value rangeOfString: @":"
+ options: OFStringSearchBackwards].location;
- if (pos != OF_NOT_FOUND) {
+ if (pos != OFNotFound) {
[_host release];
_host = [[value substringToIndex: pos] retain];
@try {
unsigned long long portTmp =
@@ -498,12 +489,11 @@
dateStringWithFormat: @"%a, %d %b %Y %H:%M:%S GMT"];
[_socket writeFormat: @"HTTP/1.1 %hd %@\r\n"
@"Date: %@\r\n"
@"Server: %@\r\n"
@"\r\n",
- statusCode,
- of_http_status_code_to_string(statusCode),
+ statusCode, OFHTTPStatusCodeString(statusCode),
date, _server.name];
return false;
}
- (void)createResponse
@@ -533,11 +523,11 @@
URL.scheme = @"http";
URL.host = _host;
if (_port != 80)
URL.port = [OFNumber numberWithUnsignedShort: _port];
- if ((pos = [_path rangeOfString: @"?"].location) != OF_NOT_FOUND) {
+ if ((pos = [_path rangeOfString: @"?"].location) != OFNotFound) {
OFString *path, *query;
path = [_path substringToIndex: pos];
query = [_path substringFromIndex: pos + 1];
@@ -549,11 +539,11 @@
[URL makeImmutable];
request = [OFHTTPRequest requestWithURL: URL];
request.method = _method;
request.protocolVersion =
- (of_http_request_protocol_version_t){ 1, _HTTPMinorVersion };
+ (OFHTTPRequestProtocolVersion){ 1, _HTTPMinorVersion };
request.headers = _headers;
request.remoteAddress = _socket.remoteAddress;
response = [[[OFHTTPServerResponse alloc]
initWithSocket: _socket
@@ -692,19 +682,19 @@
if (line == nil)
return 0;
pos = [line rangeOfString: @";"].location;
- if (pos != OF_NOT_FOUND)
+ if (pos != OFNotFound)
line = [line substringToIndex: pos];
if (line.length < 1) {
/*
* We have read the empty string because the socket is
* at end of stream.
*/
- if (_socket.atEndOfStream && pos == OF_NOT_FOUND)
+ if (_socket.atEndOfStream && pos == OFNotFound)
@throw [OFTruncatedDataException exception];
else
@throw [OFInvalidFormatException exception];
}
@@ -907,14 +897,14 @@
@throw [OFAlreadyConnectedException exception];
if (_usesTLS) {
OFTCPSocket *TLSSocket;
- if (of_tls_socket_class == Nil)
+ if (OFTLSSocketClass == Nil)
@throw [OFUnsupportedProtocolException exception];
- TLSSocket = [[of_tls_socket_class alloc] init];
+ TLSSocket = [[OFTLSSocketClass alloc] init];
_listeningSocket = TLSSocket;
TLSSocket.certificateFile = _certificateFile;
TLSSocket.privateKeyFile = _privateKeyFile;
TLSSocket.privateKeyPassphrase = _privateKeyPassphrase;
Index: src/OFHostAddressResolver.h
==================================================================
--- src/OFHostAddressResolver.h
+++ src/OFHostAddressResolver.h
@@ -14,12 +14,11 @@
*/
#import "OFObject.h"
#import "OFDNSResolver.h"
#import "OFRunLoop.h"
-
-#import "socket.h"
+#import "OFSocket.h"
OF_ASSUME_NONNULL_BEGIN
@class OFDNSResolverSettings;
@class OFDNSResourceRecord;
@@ -28,27 +27,27 @@
@class OFString;
@interface OFHostAddressResolver: OFObject
{
OFString *_host;
- of_socket_address_family_t _addressFamily;
+ OFSocketAddressFamily _addressFamily;
OFDNSResolver *_resolver;
OFDNSResolverSettings *_settings;
- of_run_loop_mode_t _Nullable _runLoopMode;
+ OFRunLoopMode _Nullable _runLoopMode;
id _Nullable _delegate;
bool _isFQDN;
size_t _searchDomainIndex;
unsigned int _numExpectedResponses;
OFMutableData *_addresses;
}
- (instancetype)initWithHost: (OFString *)host
- addressFamily: (of_socket_address_family_t)addressFamily
+ addressFamily: (OFSocketAddressFamily)addressFamily
resolver: (OFDNSResolver *)resolver
settings: (OFDNSResolverSettings *)settings
- runLoopMode: (nullable of_run_loop_mode_t)runLoopMode
+ runLoopMode: (nullable OFRunLoopMode)runLoopMode
delegate: (nullable id )delegate;
- (void)asyncResolve;
- (OFData *)resolve;
@end
OF_ASSUME_NONNULL_END
Index: src/OFHostAddressResolver.m
==================================================================
--- src/OFHostAddressResolver.m
+++ src/OFHostAddressResolver.m
@@ -38,12 +38,12 @@
OFData *_addresses;
id _exception;
}
@end
-static const of_run_loop_mode_t resolveRunLoopMode =
- @"of_host_address_resolver_resolve_mode";
+static const OFRunLoopMode resolveRunLoopMode =
+ @"OFHostAddressResolverResolveRunLoopMode";
static bool
isFQDN(OFString *host, unsigned int minNumberOfDotsInAbsoluteName)
{
const char *UTF8String;
@@ -64,24 +64,23 @@
return (dots >= minNumberOfDotsInAbsoluteName);
}
static bool
addressForRecord(OF_KINDOF(OFDNSResourceRecord *) record,
- const of_socket_address_t **address,
- of_socket_address_family_t addressFamily)
+ const OFSocketAddress **address, OFSocketAddressFamily addressFamily)
{
switch ([record recordType]) {
#ifdef OF_HAVE_IPV6
- case OF_DNS_RECORD_TYPE_AAAA:
- if (addressFamily != OF_SOCKET_ADDRESS_FAMILY_IPV6 &&
- addressFamily != OF_SOCKET_ADDRESS_FAMILY_ANY)
+ case OFDNSRecordTypeAAAA:
+ if (addressFamily != OFSocketAddressFamilyIPv6 &&
+ addressFamily != OFSocketAddressFamilyAny)
return false;
break;
#endif
- case OF_DNS_RECORD_TYPE_A:
- if (addressFamily != OF_SOCKET_ADDRESS_FAMILY_IPV4 &&
- addressFamily != OF_SOCKET_ADDRESS_FAMILY_ANY)
+ case OFDNSRecordTypeA:
+ if (addressFamily != OFSocketAddressFamilyIPv4 &&
+ addressFamily != OFSocketAddressFamilyAny)
return false;
break;
default:
return false;
}
@@ -89,11 +88,11 @@
*address = [record address];
return true;
}
static void
-callDelegateInMode(of_run_loop_mode_t runLoopMode,
+callDelegateInMode(OFRunLoopMode runLoopMode,
id delegate, OFDNSResolver *resolver,
OFString *host, OFData *addresses, id exception)
{
SEL selector = @selector(resolver:didResolveHost:addresses:exception:);
@@ -112,14 +111,14 @@
}
}
@implementation OFHostAddressResolver: OFObject
- (instancetype)initWithHost: (OFString *)host
- addressFamily: (of_socket_address_family_t)addressFamily
+ addressFamily: (OFSocketAddressFamily)addressFamily
resolver: (OFDNSResolver *)resolver
settings: (OFDNSResolverSettings *)settings
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ runLoopMode: (OFRunLoopMode)runLoopMode
delegate: (id )delegate
{
self = [super init];
@try {
@@ -161,29 +160,29 @@
_host, searchDomain];
} else
domainName = _host;
#ifdef OF_HAVE_IPV6
- if (_addressFamily == OF_SOCKET_ADDRESS_FAMILY_IPV6 ||
- _addressFamily == OF_SOCKET_ADDRESS_FAMILY_ANY) {
+ if (_addressFamily == OFSocketAddressFamilyIPv6 ||
+ _addressFamily == OFSocketAddressFamilyAny) {
OFDNSQuery *query = [OFDNSQuery
queryWithDomainName: domainName
- DNSClass: OF_DNS_CLASS_IN
- recordType: OF_DNS_RECORD_TYPE_AAAA];
+ DNSClass: OFDNSClassIN
+ recordType: OFDNSRecordTypeAAAA];
_numExpectedResponses++;
[_resolver asyncPerformQuery: query
runLoopMode: _runLoopMode
delegate: self];
}
#endif
- if (_addressFamily == OF_SOCKET_ADDRESS_FAMILY_IPV4 ||
- _addressFamily == OF_SOCKET_ADDRESS_FAMILY_ANY) {
+ if (_addressFamily == OFSocketAddressFamilyIPv4 ||
+ _addressFamily == OFSocketAddressFamilyAny) {
OFDNSQuery *query = [OFDNSQuery
queryWithDomainName: domainName
- DNSClass: OF_DNS_CLASS_IN
- recordType: OF_DNS_RECORD_TYPE_A];
+ DNSClass: OFDNSClassIN
+ recordType: OFDNSRecordTypeA];
_numExpectedResponses++;
[_resolver asyncPerformQuery: query
runLoopMode: _runLoopMode
delegate: self];
}
@@ -195,37 +194,37 @@
exception: (id)exception
{
_numExpectedResponses--;
if ([exception isKindOfClass: [OFDNSQueryFailedException class]] &&
- [exception error] == OF_DNS_RESOLVER_ERROR_SERVER_NAME_ERROR &&
+ [exception errorCode] == OFDNSResolverErrorCodeServerNameError &&
!_isFQDN && _numExpectedResponses == 0 && _addresses.count == 0 &&
_searchDomainIndex + 1 < _settings->_searchDomains.count) {
_searchDomainIndex++;
[self sendQueries];
return;
}
for (OF_KINDOF(OFDNSResourceRecord *) record in
[response.answerRecords objectForKey: query.domainName]) {
- const of_socket_address_t *address = NULL;
+ const OFSocketAddress *address = NULL;
OFDNSQuery *CNAMEQuery;
- if ([record DNSClass] != OF_DNS_CLASS_IN)
+ if ([record DNSClass] != OFDNSClassIN)
continue;
if (addressForRecord(record, &address, _addressFamily)) {
[_addresses addItem: address];
continue;
}
- if ([record recordType] != OF_DNS_RECORD_TYPE_CNAME)
+ if ([record recordType] != OFDNSRecordTypeCNAME)
continue;
/* FIXME: Check if it's already in answers */
CNAMEQuery = [OFDNSQuery queryWithDomainName: [record alias]
- DNSClass: OF_DNS_CLASS_IN
+ DNSClass: OFDNSClassIN
recordType: query.recordType];
_numExpectedResponses++;
[_resolver asyncPerformQuery: CNAMEQuery
runLoopMode: _runLoopMode
delegate: self];
@@ -243,17 +242,17 @@
if ([exception isKindOfClass:
[OFDNSQueryFailedException class]])
exception = [OFResolveHostFailedException
exceptionWithHost: _host
addressFamily: _addressFamily
- error: [exception error]];
+ errorCode: [exception errorCode]];
if (exception == nil)
exception = [OFResolveHostFailedException
exceptionWithHost: _host
addressFamily: _addressFamily
- error: OF_DNS_RESOLVER_ERROR_NO_RESULT];
+ errorCode: OFDNSResolverErrorCodeNoResult];
} else
exception = nil;
if ([_delegate respondsToSelector:
@selector(resolver:didResolveHost:addresses:exception:)])
@@ -267,17 +266,16 @@
{
void *pool = objc_autoreleasePoolPush();
OFArray OF_GENERIC(OFString *) *aliases;
@try {
- of_socket_address_t address =
- of_socket_address_parse_ip(_host, 0);
+ OFSocketAddress address = OFSocketAddressParseIP(_host, 0);
OFData *addresses = nil;
id exception = nil;
if (_addressFamily == address.family ||
- _addressFamily == OF_SOCKET_ADDRESS_FAMILY_ANY)
+ _addressFamily == OFSocketAddressFamilyAny)
addresses = [OFData dataWithItems: &address
count: 1
itemSize: sizeof(address)];
else
exception = [OFInvalidArgumentException exception];
@@ -290,24 +288,24 @@
} @catch (OFInvalidFormatException *e) {
}
if ((aliases = [_settings->_staticHosts objectForKey: _host]) != nil) {
OFMutableData *addresses = [OFMutableData
- dataWithItemSize: sizeof(of_socket_address_t)];
+ dataWithItemSize: sizeof(OFSocketAddress)];
id exception = nil;
for (OFString *alias in aliases) {
- of_socket_address_t address;
+ OFSocketAddress address;
@try {
- address = of_socket_address_parse_ip(alias, 0);
+ address = OFSocketAddressParseIP(alias, 0);
} @catch (OFInvalidFormatException *e) {
continue;
}
if (_addressFamily != address.family &&
- _addressFamily != OF_SOCKET_ADDRESS_FAMILY_ANY)
+ _addressFamily != OFSocketAddressFamilyAny)
continue;
[addresses addItem: &address];
}
@@ -316,11 +314,11 @@
if (addresses.count == 0) {
addresses = nil;
exception = [OFResolveHostFailedException
exceptionWithHost: _host
addressFamily: _addressFamily
- error: OF_DNS_RESOLVER_ERROR_NO_RESULT];
+ errorCode: OFDNSResolverErrorCodeNoResult];
}
callDelegateInMode(_runLoopMode, _delegate, _resolver, _host,
addresses, exception);
@@ -328,11 +326,11 @@
return;
}
_isFQDN = isFQDN(_host, _settings->_minNumberOfDotsInAbsoluteName);
_addresses = [[OFMutableData alloc]
- initWithItemSize: sizeof(of_socket_address_t)];
+ initWithItemSize: sizeof(OFSocketAddress)];
[self sendQueries];
objc_autoreleasePoolPop(pool);
}
ADDED src/OFHuffmanTree.h
Index: src/OFHuffmanTree.h
==================================================================
--- src/OFHuffmanTree.h
+++ src/OFHuffmanTree.h
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include
+#include
+
+#import "macros.h"
+
+#import "OFInvalidFormatException.h"
+
+OF_ASSUME_NONNULL_BEGIN
+
+typedef struct _OFHuffmanTree {
+ struct _OFHuffmanTree *_Nullable leaves[2];
+ uint16_t value;
+} *OFHuffmanTree;
+
+/* Inlined for performance. */
+static OF_INLINE bool
+OFHuffmanTreeWalk(id _Nullable stream,
+ bool (*bitReader)(id _Nullable, uint16_t *_Nonnull, uint8_t),
+ OFHuffmanTree _Nonnull *_Nonnull tree, uint16_t *_Nonnull value)
+{
+ OFHuffmanTree iter = *tree;
+ uint16_t bits;
+
+ while (iter->value == 0xFFFF) {
+ if OF_UNLIKELY (!bitReader(stream, &bits, 1)) {
+ *tree = iter;
+ return false;
+ }
+
+ if OF_UNLIKELY (iter->leaves[bits] == NULL)
+ @throw [OFInvalidFormatException exception];
+
+ iter = iter->leaves[bits];
+ }
+
+ *value = iter->value;
+ return true;
+}
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern OFHuffmanTree _Nonnull OFHuffmanTreeNew(uint8_t lengths[_Nonnull],
+ uint16_t count);
+extern OFHuffmanTree _Nonnull OFHuffmanTreeNewSingle(uint16_t value);
+extern void OFHuffmanTreeFree(OFHuffmanTree _Nonnull tree);
+#ifdef __cplusplus
+}
+#endif
+
+OF_ASSUME_NONNULL_END
ADDED src/OFHuffmanTree.m
Index: src/OFHuffmanTree.m
==================================================================
--- src/OFHuffmanTree.m
+++ src/OFHuffmanTree.m
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#include
+#include
+
+#import "OFHuffmanTree.h"
+
+#import "OFInvalidFormatException.h"
+#import "OFOutOfMemoryException.h"
+
+static OFHuffmanTree
+newTree(void)
+{
+ OFHuffmanTree tree;
+
+ tree = OFAllocMemory(1, sizeof(*tree));
+ tree->leaves[0] = tree->leaves[1] = NULL;
+ tree->value = 0xFFFF;
+
+ return tree;
+}
+
+static void
+treeInsert(OFHuffmanTree tree, uint16_t code, uint8_t length, uint16_t value)
+{
+ while (length > 0) {
+ uint8_t bit;
+
+ length--;
+ bit = (code & (1u << length)) >> length;
+
+ if (tree->leaves[bit] == NULL)
+ tree->leaves[bit] = newTree();
+
+ tree = tree->leaves[bit];
+ }
+
+ tree->value = value;
+}
+
+OFHuffmanTree
+OFHuffmanTreeNew(uint8_t lengths[], uint16_t count)
+{
+ OFHuffmanTree tree;
+ uint16_t *lengthCount = NULL;
+ uint16_t code, maxCode = 0, *nextCode = NULL;
+ uint_fast8_t maxBit = 0;
+
+ @try {
+ for (uint16_t i = 0; i < count; i++) {
+ uint_fast8_t length = lengths[i];
+
+ if OF_UNLIKELY (length > maxBit) {
+ lengthCount = OFResizeMemory(lengthCount,
+ length + 1, sizeof(uint16_t));
+ nextCode = OFResizeMemory(nextCode,
+ length + 1, sizeof(uint16_t));
+
+ for (uint_fast8_t j = maxBit + 1; j <= length;
+ j++) {
+ lengthCount[j] = 0;
+ nextCode[j] = 0;
+ }
+
+ maxBit = length;
+ }
+
+ if (length > 0) {
+ lengthCount[length]++;
+ maxCode = i;
+ }
+ }
+
+ code = 0;
+ for (size_t i = 1; i <= maxBit; i++) {
+ code = (code + lengthCount[i - 1]) << 1;
+ nextCode[i] = code;
+ }
+
+ tree = newTree();
+
+ for (uint16_t i = 0; i <= maxCode; i++) {
+ uint8_t length = lengths[i];
+
+ if (length > 0)
+ treeInsert(tree, nextCode[length]++, length, i);
+ }
+ } @finally {
+ OFFreeMemory(lengthCount);
+ OFFreeMemory(nextCode);
+ }
+
+ return tree;
+}
+
+OFHuffmanTree
+OFHuffmanTreeNewSingle(uint16_t value)
+{
+ OFHuffmanTree tree = newTree();
+
+ tree->value = value;
+
+ return tree;
+}
+
+void
+OFHuffmanTreeFree(OFHuffmanTree tree)
+{
+ for (uint_fast8_t i = 0; i < 2; i++)
+ if OF_LIKELY (tree->leaves[i] != NULL)
+ OFHuffmanTreeFree(tree->leaves[i]);
+
+ OFFreeMemory(tree);
+}
Index: src/OFINICategory+Private.h
==================================================================
--- src/OFINICategory+Private.h
+++ src/OFINICategory+Private.h
@@ -23,10 +23,10 @@
OF_DIRECT_MEMBERS
@interface OFINICategory ()
- (instancetype)of_initWithName: (OFString *)name OF_METHOD_FAMILY(init);
- (void)of_parseLine: (OFString *)line;
- (bool)of_writeToStream: (OFStream *)stream
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
first: (bool)first;
@end
OF_ASSUME_NONNULL_END
Index: src/OFINICategory.h
==================================================================
--- src/OFINICategory.h
+++ src/OFINICategory.h
@@ -138,22 +138,22 @@
- (OFArray OF_GENERIC(OFString *) *)stringArrayForKey: (OFString *)key;
/**
* @brief Sets the value of the specified key to the specified string.
*
- * If the specified key is a multi-key (see @ref stringValuesForKey:), the
- * value of the first key/value pair found is changed.
+ * If the specified key is a multi-key (see @ref stringArrayForKey:), the value
+ * of the first key/value pair found is changed.
*
* @param string The string to which the key should be set
* @param key The key for which the new value should be set
*/
- (void)setString: (OFString *)string forKey: (OFString *)key;
/**
* @brief Sets the value of the specified key to the specified long long.
*
- * If the specified key is a multi-key (see @ref stringValuesForKey:), the value
+ * If the specified key is a multi-key (see @ref stringArrayForKey:), the value
* of the first key/value pair found is changed.
*
* @param longLong The long long to which the key should be set
* @param key The key for which the new value should be set
*/
@@ -160,33 +160,33 @@
- (void)setLongLong: (long long)longLong forKey: (OFString *)key;
/**
* @brief Sets the value of the specified key to the specified bool.
*
- * If the specified key is a multi-key (see @ref stringValuesForKey:), the
- * value of the first key/value pair found is changed.
+ * If the specified key is a multi-key (see @ref stringArrayForKey:), the value
+ * of the first key/value pair found is changed.
*
* @param bool_ The bool to which the key should be set
* @param key The key for which the new value should be set
*/
- (void)setBool: (bool)bool_ forKey: (OFString *)key;
/**
* @brief Sets the value of the specified key to the specified float.
*
- * If the specified key is a multi-key (see @ref stringValuesForKey:), the
- * value of the first key/value pair found is changed.
+ * If the specified key is a multi-key (see @ref stringArrayForKey:), the value
+ * of the first key/value pair found is changed.
*
* @param float_ The float to which the key should be set
* @param key The key for which the new value should be set
*/
- (void)setFloat: (float)float_ forKey: (OFString *)key;
/**
* @brief Sets the value of the specified key to the specified double.
*
- * If the specified key is a multi-key (see @ref stringValuesForKey:), the value
+ * If the specified key is a multi-key (see @ref stringArrayForKey:), the value
* of the first key/value pair found is changed.
*
* @param double_ The double to which the key should be set
* @param key The key for which the new value should be set
*/
@@ -208,14 +208,14 @@
forKey: (OFString *)key;
/**
* @brief Removes the value for the specified key
*
- * If the specified key is a multi-key (see @ref stringValuesForKey:), all
+ * If the specified key is a multi-key (see @ref stringArrayForKey:), all
* key/value pairs matching the specified key are removed.
*
* @param key The key of the value to remove
*/
- (void)removeValueForKey: (OFString *)key;
@end
OF_ASSUME_NONNULL_END
Index: src/OFINICategory.m
==================================================================
--- src/OFINICategory.m
+++ src/OFINICategory.m
@@ -72,11 +72,11 @@
OFMutableString *mutableString;
if (![string hasPrefix: @"\""] || ![string hasSuffix: @"\""])
return string;
- string = [string substringWithRange: of_range(1, string.length - 2)];
+ string = [string substringWithRange: OFRangeMake(1, string.length - 2)];
mutableString = [[string mutableCopy] autorelease];
[mutableString replaceOccurrencesOfString: @"\\f" withString: @"\f"];
[mutableString replaceOccurrencesOfString: @"\\r" withString: @"\r"];
[mutableString replaceOccurrencesOfString: @"\\n" withString: @"\n"];
@@ -154,11 +154,11 @@
OFINICategoryPair *pair =
[[[OFINICategoryPair alloc] init] autorelease];
OFString *key, *value;
size_t pos;
- if ((pos = [line rangeOfString: @"="].location) == OF_NOT_FOUND)
+ if ((pos = [line rangeOfString: @"="].location) == OFNotFound)
@throw [OFInvalidFormatException exception];
key = unescapeString([line substringToIndex: pos]
.stringByDeletingEnclosingWhitespaces);
value = unescapeString([line substringFromIndex: pos + 1]
@@ -466,11 +466,11 @@
objc_autoreleasePoolPop(pool);
}
- (bool)of_writeToStream: (OFStream *)stream
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
first: (bool)first
{
if (_lines.count == 0)
return false;
Index: src/OFINIFile.h
==================================================================
--- src/OFINIFile.h
+++ src/OFINIFile.h
@@ -54,11 +54,11 @@
* @param encoding The encoding of the specified file
*
* @return A new, autoreleased OFINIFile with the contents of the specified file
*/
+ (instancetype)fileWithPath: (OFString *)path
- encoding: (of_string_encoding_t)encoding;
+ encoding: (OFStringEncoding)encoding;
- (instancetype)init OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFINIFile with the contents of the
@@ -78,11 +78,11 @@
* @param encoding The encoding of the specified file
*
* @return An initialized OFINIFile with the contents of the specified file
*/
- (instancetype)initWithPath: (OFString *)path
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
OF_DESIGNATED_INITIALIZER;
/**
* @brief Returns an @ref OFINICategory for the category with the specified
* name.
@@ -106,9 +106,9 @@
* encoding.
*
* @param path The path of the file to write to
* @param encoding The encoding to use
*/
-- (void)writeToFile: (OFString *)path encoding: (of_string_encoding_t)encoding;
+- (void)writeToFile: (OFString *)path encoding: (OFStringEncoding)encoding;
@end
OF_ASSUME_NONNULL_END
Index: src/OFINIFile.m
==================================================================
--- src/OFINIFile.m
+++ src/OFINIFile.m
@@ -27,21 +27,21 @@
#import "OFInvalidFormatException.h"
#import "OFOpenItemFailedException.h"
OF_DIRECT_MEMBERS
@interface OFINIFile ()
-- (void)of_parseFile: (OFString *)path encoding: (of_string_encoding_t)encoding;
+- (void)of_parseFile: (OFString *)path encoding: (OFStringEncoding)encoding;
@end
static bool
isWhitespaceLine(OFString *line)
{
const char *cString = line.UTF8String;
size_t length = line.UTF8StringLength;
for (size_t i = 0; i < length; i++)
- if (!of_ascii_isspace(cString[i]))
+ if (!OFASCIIIsSpace(cString[i]))
return false;
return true;
}
@@ -52,11 +52,11 @@
{
return [[[self alloc] initWithPath: path] autorelease];
}
+ (instancetype)fileWithPath: (OFString *)path
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
return [[[self alloc] initWithPath: path
encoding: encoding] autorelease];
}
@@ -65,15 +65,15 @@
OF_INVALID_INIT_METHOD
}
- (instancetype)initWithPath: (OFString *)path
{
- return [self initWithPath: path encoding: OF_STRING_ENCODING_UTF_8];
+ return [self initWithPath: path encoding: OFStringEncodingUTF8];
}
- (instancetype)initWithPath: (OFString *)path
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
self = [super init];
@try {
_categories = [[OFMutableArray alloc] init];
@@ -109,11 +109,11 @@
objc_autoreleasePoolPop(pool);
return category;
}
-- (void)of_parseFile: (OFString *)path encoding: (of_string_encoding_t)encoding
+- (void)of_parseFile: (OFString *)path encoding: (OFStringEncoding)encoding
{
void *pool = objc_autoreleasePoolPush();
OFFile *file;
OFINICategory *category = nil;
OFString *line;
@@ -137,11 +137,11 @@
if (![line hasSuffix: @"]"])
@throw [OFInvalidFormatException exception];
categoryName = [line substringWithRange:
- of_range(1, line.length - 2)];
+ OFRangeMake(1, line.length - 2)];
category = [[[OFINICategory alloc]
of_initWithName: categoryName] autorelease];
[_categories addObject: category];
} else {
if (category == nil)
@@ -154,14 +154,14 @@
objc_autoreleasePoolPop(pool);
}
- (void)writeToFile: (OFString *)path
{
- [self writeToFile: path encoding: OF_STRING_ENCODING_UTF_8];
+ [self writeToFile: path encoding: OFStringEncodingUTF8];
}
-- (void)writeToFile: (OFString *)path encoding: (of_string_encoding_t)encoding
+- (void)writeToFile: (OFString *)path encoding: (OFStringEncoding)encoding
{
void *pool = objc_autoreleasePoolPush();
OFFile *file = [OFFile fileWithPath: path mode: @"w"];
bool first = true;
Index: src/OFINIFileSettings.m
==================================================================
--- src/OFINIFileSettings.m
+++ src/OFINIFileSettings.m
@@ -55,13 +55,13 @@
- (void)of_getCategory: (OFString **)category
andKey: (OFString **)key
forPath: (OFString *)path OF_DIRECT
{
size_t pos = [path rangeOfString: @"."
- options: OF_STRING_SEARCH_BACKWARDS].location;
+ options: OFStringSearchBackwards].location;
- if (pos == OF_NOT_FOUND) {
+ if (pos == OFNotFound) {
*category = @"";
*key = path;
return;
}
Index: src/OFIPSocketAsyncConnector.h
==================================================================
--- src/OFIPSocketAsyncConnector.h
+++ src/OFIPSocketAsyncConnector.h
@@ -18,13 +18,13 @@
#import "OFRunLoop+Private.h"
OF_ASSUME_NONNULL_BEGIN
@protocol OFIPSocketAsyncConnecting
-- (bool)of_createSocketForAddress: (const of_socket_address_t *)address
+- (bool)of_createSocketForAddress: (const OFSocketAddress *)address
errNo: (int *)errNo;
-- (bool)of_connectSocketToAddress: (const of_socket_address_t *)address
+- (bool)of_connectSocketToAddress: (const OFSocketAddress *)address
errNo: (int *)errNo;
- (void)of_closeSocket;
@end
@interface OFIPSocketAsyncConnector: OFObject = _socketAddresses.count) {
_exception = [[OFConnectionFailedException alloc]
initWithHost: _host
@@ -222,15 +221,14 @@
[self tryNextAddressWithRunLoopMode:
[OFRunLoop currentRunLoop].currentMode];
}
-- (void)startWithRunLoopMode: (of_run_loop_mode_t)runLoopMode
+- (void)startWithRunLoopMode: (OFRunLoopMode)runLoopMode
{
@try {
- of_socket_address_t address =
- of_socket_address_parse_ip(_host, _port);
+ OFSocketAddress address = OFSocketAddressParseIP(_host, _port);
_socketAddresses = [[OFData alloc]
initWithItems: &address
count: 1
itemSize: sizeof(address)];
@@ -240,10 +238,10 @@
} @catch (OFInvalidFormatException *e) {
}
[[OFThread DNSResolver]
asyncResolveAddressesForHost: _host
- addressFamily: OF_SOCKET_ADDRESS_FAMILY_ANY
+ addressFamily: OFSocketAddressFamilyAny
runLoopMode: runLoopMode
delegate: self];
}
@end
Index: src/OFIPXSocket.h
==================================================================
--- src/OFIPXSocket.h
+++ src/OFIPXSocket.h
@@ -30,15 +30,15 @@
/**
* @class OFIPXSocket OFIPXSocket.h ObjFW/OFIPXSocket.h
*
* @brief A class which provides methods to create and use IPX sockets.
*
- * Addresses are of type @ref of_socket_address_t. You can use
- * @ref of_socket_address_ipx to create an address or
- * @ref of_socket_address_get_ipx_network to get the IPX network,
- * @ref of_socket_address_get_ipx_node to get the IPX node and
- * @ref of_socket_address_get_port to get the port (sometimes also called
+ * Addresses are of type @ref OFSocketAddress. You can use
+ * @ref OFSocketAddressMakeIPX to create an address or
+ * @ref OFSocketAddressIPXNetwork to get the IPX network,
+ * @ref OFSocketAddressIPXNode to get the IPX node and
+ * @ref OFSocketAddressPort to get the port (sometimes also called
* socket number).
*
* @warning Even though the OFCopying protocol is implemented, it does *not*
* return an independent copy of the socket, but instead retains it.
* This is so that the socket can be used as a key for a dictionary,
@@ -70,10 +70,9 @@
* @param port The port (sometimes called socket number) to bind to. 0 means to
* pick one and return it.
* @param packetType The packet type to use on the socket
* @return The address on which this socket can be reached
*/
-- (of_socket_address_t)bindToPort: (uint16_t)port
- packetType: (uint8_t)packetType;
+- (OFSocketAddress)bindToPort: (uint16_t)port packetType: (uint8_t)packetType;
@end
OF_ASSUME_NONNULL_END
Index: src/OFIPXSocket.m
==================================================================
--- src/OFIPXSocket.m
+++ src/OFIPXSocket.m
@@ -20,88 +20,86 @@
#ifdef HAVE_FCNTL_H
# include
#endif
#import "OFIPXSocket.h"
+#import "OFSocket.h"
+#import "OFSocket+Private.h"
#import "OFAlreadyConnectedException.h"
#import "OFBindFailedException.h"
-#import "socket.h"
-#import "socket_helpers.h"
-
@implementation OFIPXSocket
@dynamic delegate;
-- (of_socket_address_t)bindToPort: (uint16_t)port
- packetType: (uint8_t)packetType
+- (OFSocketAddress)bindToPort: (uint16_t)port packetType: (uint8_t)packetType
{
const unsigned char zeroNode[IPX_NODE_LEN] = { 0 };
- of_socket_address_t address;
+ OFSocketAddress address;
int protocol = 0;
#if SOCK_CLOEXEC == 0 && defined(HAVE_FCNTL_H) && defined(FD_CLOEXEC)
int flags;
#endif
- if (_socket != INVALID_SOCKET)
+ if (_socket != OFInvalidSocketHandle)
@throw [OFAlreadyConnectedException exceptionWithSocket: self];
- address = of_socket_address_ipx(zeroNode, 0, port);
+ address = OFSocketAddressMakeIPX(zeroNode, 0, port);
#ifdef OF_WINDOWS
protocol = NSPROTO_IPX + packetType;
#else
_packetType = address.sockaddr.ipx.sipx_type = packetType;
#endif
if ((_socket = socket(address.sockaddr.sockaddr.sa_family,
- SOCK_DGRAM | SOCK_CLOEXEC, protocol)) == INVALID_SOCKET)
+ SOCK_DGRAM | SOCK_CLOEXEC, protocol)) == OFInvalidSocketHandle)
@throw [OFBindFailedException
exceptionWithPort: port
packetType: packetType
socket: self
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
_canBlock = true;
#if SOCK_CLOEXEC == 0 && defined(HAVE_FCNTL_H) && defined(FD_CLOEXEC)
if ((flags = fcntl(_socket, F_GETFD, 0)) != -1)
fcntl(_socket, F_SETFD, flags | FD_CLOEXEC);
#endif
if (bind(_socket, &address.sockaddr.sockaddr, address.length) != 0) {
- int errNo = of_socket_errno();
+ int errNo = OFSocketErrNo();
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
@throw [OFBindFailedException exceptionWithPort: port
packetType: packetType
socket: self
errNo: errNo];
}
memset(&address, 0, sizeof(address));
- address.family = OF_SOCKET_ADDRESS_FAMILY_IPX;
+ address.family = OFSocketAddressFamilyIPX;
address.length = (socklen_t)sizeof(address.sockaddr);
- if (of_getsockname(_socket, &address.sockaddr.sockaddr,
+ if (OFGetSockName(_socket, &address.sockaddr.sockaddr,
&address.length) != 0) {
- int errNo = of_socket_errno();
+ int errNo = OFSocketErrNo();
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
@throw [OFBindFailedException exceptionWithPort: port
packetType: packetType
socket: self
errNo: errNo];
}
if (address.sockaddr.sockaddr.sa_family != AF_IPX) {
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
@throw [OFBindFailedException exceptionWithPort: port
packetType: packetType
socket: self
errNo: EAFNOSUPPORT];
@@ -111,19 +109,19 @@
}
#ifndef OF_WINDOWS
- (void)sendBuffer: (const void *)buffer
length: (size_t)length
- receiver: (const of_socket_address_t *)receiver
+ receiver: (const OFSocketAddress *)receiver
{
- of_socket_address_t fixedReceiver;
+ OFSocketAddress fixedReceiver;
memcpy(&fixedReceiver, receiver, sizeof(fixedReceiver));
/* If it's not IPX, no fix-up needed - it will fail anyway. */
- if (fixedReceiver.family == OF_SOCKET_ADDRESS_FAMILY_IPX)
+ if (fixedReceiver.family == OFSocketAddressFamilyIPX)
fixedReceiver.sockaddr.ipx.sipx_type = _packetType;
[super sendBuffer: buffer length: length receiver: &fixedReceiver];
}
#endif
@end
Index: src/OFInflate64Stream.h
==================================================================
--- src/OFInflate64Stream.h
+++ src/OFInflate64Stream.h
@@ -12,15 +12,16 @@
* LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
* file.
*/
#import "OFStream.h"
+#import "OFHuffmanTree.h"
#import "OFKernelEventObserver.h"
OF_ASSUME_NONNULL_BEGIN
-#define OF_INFLATE64_STREAM_BUFFER_SIZE 4096
+#define OFInflate64StreamBufferSize 4096
/**
* @class OFInflate64Stream OFInflate64Stream.h ObjFW/OFInflate64Stream.h
*
* @note This class only conforms to OFReadyForReadingObserving if the
@@ -31,11 +32,11 @@
*/
OF_SUBCLASSING_RESTRICTED
@interface OFInflate64Stream: OFStream
{
OFStream *_stream;
- unsigned char _buffer[OF_INFLATE64_STREAM_BUFFER_SIZE];
+ unsigned char _buffer[OFInflate64StreamBufferSize];
uint16_t _bufferIndex, _bufferLength;
uint8_t _byte;
uint8_t _bitIndex, _savedBitsLength;
uint16_t _savedBits;
unsigned char *_Nullable _slidingWindow;
@@ -48,23 +49,23 @@
} uncompressedHeader;
struct {
uint16_t position, length;
} uncompressed;
struct {
- struct of_huffman_tree *_Nullable litLenTree;
- struct of_huffman_tree *_Nullable distTree;
- struct of_huffman_tree *_Nullable codeLenTree;
- struct of_huffman_tree *_Nullable treeIter;
+ OFHuffmanTree _Nullable litLenTree;
+ OFHuffmanTree _Nullable distTree;
+ OFHuffmanTree _Nullable codeLenTree;
+ OFHuffmanTree _Nullable treeIter;
uint8_t *_Nullable lengths;
uint16_t receivedCount;
uint8_t value, litLenCodesCount, distCodesCount;
uint8_t codeLenCodesCount;
} huffmanTree;
struct {
- struct of_huffman_tree *_Nullable litLenTree;
- struct of_huffman_tree *_Nullable distTree;
- struct of_huffman_tree *_Nullable treeIter;
+ OFHuffmanTree _Nullable litLenTree;
+ OFHuffmanTree _Nullable distTree;
+ OFHuffmanTree _Nullable treeIter;
int state;
uint16_t value, length, distance, extraBits;
} huffman;
} _context;
bool _inLastBlock, _atEndOfStream;
Index: src/OFInflateStream.h
==================================================================
--- src/OFInflateStream.h
+++ src/OFInflateStream.h
@@ -12,15 +12,16 @@
* LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
* file.
*/
#import "OFStream.h"
+#import "OFHuffmanTree.h"
#import "OFKernelEventObserver.h"
OF_ASSUME_NONNULL_BEGIN
-#define OF_INFLATE_STREAM_BUFFER_SIZE 4096
+#define OFInflateStreamBufferSize 4096
/**
* @class OFInflateStream OFInflateStream.h ObjFW/OFInflateStream.h
*
* @note This class only conforms to OFReadyForReadingObserving if the
@@ -31,11 +32,11 @@
*/
OF_SUBCLASSING_RESTRICTED
@interface OFInflateStream: OFStream
{
OFStream *_stream;
- unsigned char _buffer[OF_INFLATE_STREAM_BUFFER_SIZE];
+ unsigned char _buffer[OFInflateStreamBufferSize];
uint16_t _bufferIndex, _bufferLength;
uint8_t _byte;
uint8_t _bitIndex, _savedBitsLength;
uint16_t _savedBits;
unsigned char *_Nullable _slidingWindow;
@@ -48,23 +49,23 @@
} uncompressedHeader;
struct {
uint16_t position, length;
} uncompressed;
struct {
- struct of_huffman_tree *_Nullable litLenTree;
- struct of_huffman_tree *_Nullable distTree;
- struct of_huffman_tree *_Nullable codeLenTree;
- struct of_huffman_tree *_Nullable treeIter;
+ OFHuffmanTree _Nullable litLenTree;
+ OFHuffmanTree _Nullable distTree;
+ OFHuffmanTree _Nullable codeLenTree;
+ OFHuffmanTree _Nullable treeIter;
uint8_t *_Nullable lengths;
uint16_t receivedCount;
uint8_t value, litLenCodesCount, distCodesCount;
uint8_t codeLenCodesCount;
} huffmanTree;
struct {
- struct of_huffman_tree *_Nullable litLenTree;
- struct of_huffman_tree *_Nullable distTree;
- struct of_huffman_tree *_Nullable treeIter;
+ OFHuffmanTree _Nullable litLenTree;
+ OFHuffmanTree _Nullable distTree;
+ OFHuffmanTree _Nullable treeIter;
int state;
uint16_t value, length, distance, extraBits;
} huffman;
} _context;
bool _inLastBlock, _atEndOfStream;
Index: src/OFInflateStream.m
==================================================================
--- src/OFInflateStream.m
+++ src/OFInflateStream.m
@@ -24,39 +24,38 @@
# import "OFInflateStream.h"
#else
# import "OFInflate64Stream.h"
# define OFInflateStream OFInflate64Stream
#endif
-
-#import "huffman_tree.h"
+#import "OFHuffmanTree.h"
#import "OFInitializationFailedException.h"
#import "OFInvalidFormatException.h"
#import "OFNotOpenException.h"
#import "OFOutOfMemoryException.h"
#ifndef OF_INFLATE64_STREAM_M
-# define BUFFER_SIZE OF_INFLATE_STREAM_BUFFER_SIZE
+# define bufferSize OFInflateStreamBufferSize
#else
-# define BUFFER_SIZE OF_INFLATE64_STREAM_BUFFER_SIZE
+# define bufferSize OFInflate64StreamBufferSize
#endif
-enum state {
- BLOCK_HEADER,
- UNCOMPRESSED_BLOCK_HEADER,
- UNCOMPRESSED_BLOCK,
- HUFFMAN_TREE,
- HUFFMAN_BLOCK
+enum State {
+ stateBlockHeader,
+ stateUncompressedBlockHeader,
+ stateUncompressedBlock,
+ stateHuffmanTree,
+ stateHuffmanBlock
};
-enum huffman_state {
- WRITE_VALUE,
- AWAIT_CODE,
- AWAIT_LENGTH_EXTRA_BITS,
- AWAIT_DISTANCE,
- AWAIT_DISTANCE_EXTRA_BITS,
- PROCESS_PAIR
+enum HuffmanState {
+ huffmanStateWriteValue,
+ huffmanStateAwaitCode,
+ huffmanStateAwaitLengthExtraBits,
+ huffmanStateAwaitDistance,
+ huffmanStateAwaitDistanceExtraBits,
+ huffmanStateProcessPair
};
#ifndef OF_INFLATE64_STREAM_M
static const uint8_t numDistanceCodes = 30;
static const uint8_t lengthCodes[29] = {
@@ -98,11 +97,11 @@
};
#endif
static const uint8_t codeLengthsOrder[19] = {
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
};
-static struct of_huffman_tree *fixedLitLenTree, *fixedDistTree;
+static OFHuffmanTree fixedLitLenTree, fixedDistTree;
@implementation OFInflateStream
static OF_INLINE bool
tryReadBits(OFInflateStream *stream, uint16_t *bits, uint8_t count)
{
@@ -117,11 +116,11 @@
stream->_byte =
stream->_buffer[stream->_bufferIndex++];
else {
size_t length = [stream->_stream
readIntoBuffer: stream->_buffer
- length: BUFFER_SIZE];
+ length: bufferSize];
if OF_UNLIKELY (length < 1) {
stream->_savedBits = ret;
stream->_savedBitsLength = i;
return false;
@@ -159,16 +158,16 @@
for (uint16_t i = 256; i <= 279; i++)
lengths[i] = 7;
for (uint16_t i = 280; i <= 287; i++)
lengths[i] = 8;
- fixedLitLenTree = of_huffman_tree_construct(lengths, 288);
+ fixedLitLenTree = OFHuffmanTreeNew(lengths, 288);
for (uint16_t i = 0; i <= 31; i++)
lengths[i] = 5;
- fixedDistTree = of_huffman_tree_construct(lengths, 32);
+ fixedDistTree = OFHuffmanTreeNew(lengths, 32);
}
+ (instancetype)streamWithStream: (OFStream *)stream
{
return [[[self alloc] initWithStream: stream] autorelease];
@@ -192,11 +191,11 @@
#ifdef OF_INFLATE64_STREAM_M
_slidingWindowMask = 0xFFFF;
#else
_slidingWindowMask = 0x7FFF;
#endif
- _slidingWindow = of_alloc_zeroed(_slidingWindowMask + 1, 1);
+ _slidingWindow = OFAllocZeroedMemory(_slidingWindowMask + 1, 1);
} @catch (id e) {
[self release];
@throw e;
}
@@ -206,25 +205,24 @@
- (void)dealloc
{
if (_stream != nil)
[self close];
- free(_slidingWindow);
+ OFFreeMemory(_slidingWindow);
- if (_state == HUFFMAN_TREE) {
- free(_context.huffmanTree.lengths);
+ if (_state == stateHuffmanTree) {
+ OFFreeMemory(_context.huffmanTree.lengths);
if (_context.huffmanTree.codeLenTree != NULL)
- of_huffman_tree_release(
- _context.huffmanTree.codeLenTree);
+ OFHuffmanTreeFree(_context.huffmanTree.codeLenTree);
}
- if (_state == HUFFMAN_TREE || _state == HUFFMAN_BLOCK) {
+ if (_state == stateHuffmanTree || _state == stateHuffmanBlock) {
if (_context.huffman.litLenTree != fixedLitLenTree)
- of_huffman_tree_release(_context.huffman.litLenTree);
+ OFHuffmanTreeFree(_context.huffman.litLenTree);
if (_context.huffman.distTree != fixedDistTree)
- of_huffman_tree_release(_context.huffman.distTree);
+ OFHuffmanTreeFree(_context.huffman.distTree);
}
[super dealloc];
}
@@ -242,12 +240,12 @@
if (_atEndOfStream)
return 0;
start:
- switch ((enum state)_state) {
- case BLOCK_HEADER:
+ switch ((enum State)_state) {
+ case stateBlockHeader:
if OF_UNLIKELY (_inLastBlock) {
[_stream unreadFromBuffer: _buffer + _bufferIndex
length: _bufferLength -
_bufferIndex];
_bufferIndex = _bufferLength = 0;
@@ -261,24 +259,24 @@
_inLastBlock = (bits & 1);
switch (bits >> 1) {
case 0: /* No compression */
- _state = UNCOMPRESSED_BLOCK_HEADER;
+ _state = stateUncompressedBlockHeader;
_bitIndex = 8;
_context.uncompressedHeader.position = 0;
memset(_context.uncompressedHeader.length, 0, 4);
break;
case 1: /* Fixed Huffman */
- _state = HUFFMAN_BLOCK;
- _context.huffman.state = AWAIT_CODE;
+ _state = stateHuffmanBlock;
+ _context.huffman.state = huffmanStateAwaitCode;
_context.huffman.litLenTree = fixedLitLenTree;
_context.huffman.distTree = fixedDistTree;
_context.huffman.treeIter = fixedLitLenTree;
break;
case 2: /* Dynamic Huffman */
- _state = HUFFMAN_TREE;
+ _state = stateHuffmanTree;
_context.huffmanTree.lengths = NULL;
_context.huffmanTree.receivedCount = 0;
_context.huffmanTree.value = 0xFE;
_context.huffmanTree.litLenCodesCount = 0xFF;
_context.huffmanTree.distCodesCount = 0xFF;
@@ -287,11 +285,11 @@
default:
@throw [OFInvalidFormatException exception];
}
goto start;
- case UNCOMPRESSED_BLOCK_HEADER:
+ case stateUncompressedBlockHeader:
#define CTX _context.uncompressedHeader
/* FIXME: This can be done more efficiently than unreading */
[_stream unreadFromBuffer: _buffer + _bufferIndex
length: _bufferLength - _bufferIndex];
_bufferIndex = _bufferLength = 0;
@@ -305,11 +303,11 @@
if OF_UNLIKELY ((CTX.length[0] | (CTX.length[1] << 8)) !=
(uint16_t)~(CTX.length[2] | (CTX.length[3] << 8)))
@throw [OFInvalidFormatException exception];
- _state = UNCOMPRESSED_BLOCK;
+ _state = stateUncompressedBlock;
/*
* Do not reorder! _context.uncompressed.position and
* _context.uncompressedHeader.length overlap!
*/
@@ -317,11 +315,11 @@
CTX.length[0] | (CTX.length[1] << 8);
_context.uncompressed.position = 0;
goto start;
#undef CTX
- case UNCOMPRESSED_BLOCK:
+ case stateUncompressedBlock:
#define CTX _context.uncompressed
if OF_UNLIKELY (length == 0)
return bytesWritten;
tmp = (length < (size_t)CTX.length - CTX.position
@@ -343,15 +341,15 @@
length -= tmp;
bytesWritten += tmp;
CTX.position += tmp;
if OF_UNLIKELY (CTX.position == CTX.length)
- _state = BLOCK_HEADER;
+ _state = stateBlockHeader;
goto start;
#undef CTX
- case HUFFMAN_TREE:
+ case stateHuffmanTree:
#define CTX _context.huffmanTree
if OF_LIKELY (CTX.value == 0xFE) {
if OF_LIKELY (CTX.litLenCodesCount == 0xFF) {
if OF_UNLIKELY (!tryReadBits(self, &bits, 5))
return bytesWritten;
@@ -376,11 +374,11 @@
CTX.codeLenCodesCount = bits;
}
if OF_LIKELY (CTX.lengths == NULL)
- CTX.lengths = of_alloc_zeroed(19, 1);
+ CTX.lengths = OFAllocZeroedMemory(19, 1);
for (uint16_t i = CTX.receivedCount;
i < CTX.codeLenCodesCount + 4; i++) {
if OF_UNLIKELY (!tryReadBits(self, &bits, 3)) {
CTX.receivedCount = i;
@@ -388,30 +386,29 @@
}
CTX.lengths[codeLengthsOrder[i]] = bits;
}
- CTX.codeLenTree = of_huffman_tree_construct(
- CTX.lengths, 19);
+ CTX.codeLenTree = OFHuffmanTreeNew(CTX.lengths, 19);
CTX.treeIter = CTX.codeLenTree;
- free(CTX.lengths);
+ OFFreeMemory(CTX.lengths);
CTX.lengths = NULL;
CTX.receivedCount = 0;
CTX.value = 0xFF;
}
if OF_LIKELY (CTX.lengths == NULL)
- CTX.lengths = of_alloc(
+ CTX.lengths = OFAllocMemory(
CTX.litLenCodesCount + CTX.distCodesCount + 258, 1);
for (uint16_t i = CTX.receivedCount;
i < CTX.litLenCodesCount + CTX.distCodesCount + 258;) {
uint8_t j, count;
if OF_LIKELY (CTX.value == 0xFF) {
- if OF_UNLIKELY (!of_huffman_tree_walk(self,
+ if OF_UNLIKELY (!OFHuffmanTreeWalk(self,
tryReadBits, &CTX.treeIter, &value)) {
CTX.receivedCount = i;
return bytesWritten;
}
@@ -474,38 +471,38 @@
CTX.lengths[i++] = value;
CTX.value = 0xFF;
}
- of_huffman_tree_release(CTX.codeLenTree);
+ OFHuffmanTreeFree(CTX.codeLenTree);
CTX.codeLenTree = NULL;
- CTX.litLenTree = of_huffman_tree_construct(CTX.lengths,
+ CTX.litLenTree = OFHuffmanTreeNew(CTX.lengths,
CTX.litLenCodesCount + 257);
- CTX.distTree = of_huffman_tree_construct(
+ CTX.distTree = OFHuffmanTreeNew(
CTX.lengths + CTX.litLenCodesCount + 257,
CTX.distCodesCount + 1);
- free(CTX.lengths);
+ OFFreeMemory(CTX.lengths);
/*
* litLenTree and distTree are at the same location in
* _context.huffman and _context.huffmanTree, thus no need to
* set them.
*/
- _state = HUFFMAN_BLOCK;
- _context.huffman.state = AWAIT_CODE;
+ _state = stateHuffmanBlock;
+ _context.huffman.state = huffmanStateAwaitCode;
_context.huffman.treeIter = CTX.litLenTree;
goto start;
#undef CTX
- case HUFFMAN_BLOCK:
+ case stateHuffmanBlock:
#define CTX _context.huffman
for (;;) {
uint8_t extraBits, lengthCodeIndex;
- if OF_UNLIKELY (CTX.state == WRITE_VALUE) {
+ if OF_UNLIKELY (CTX.state == huffmanStateWriteValue) {
if OF_UNLIKELY (length == 0)
return bytesWritten;
buffer[bytesWritten++] = CTX.value;
length--;
@@ -513,28 +510,29 @@
_slidingWindow[_slidingWindowIndex] = CTX.value;
_slidingWindowIndex =
(_slidingWindowIndex + 1) &
_slidingWindowMask;
- CTX.state = AWAIT_CODE;
+ CTX.state = huffmanStateAwaitCode;
CTX.treeIter = CTX.litLenTree;
}
- if OF_UNLIKELY (CTX.state == AWAIT_LENGTH_EXTRA_BITS) {
+ if OF_UNLIKELY (CTX.state ==
+ huffmanStateAwaitLengthExtraBits) {
if OF_UNLIKELY (!tryReadBits(self, &bits,
CTX.extraBits))
return bytesWritten;
CTX.length += bits;
- CTX.state = AWAIT_DISTANCE;
+ CTX.state = huffmanStateAwaitDistance;
CTX.treeIter = CTX.distTree;
}
/* Distance of length distance pair */
- if (CTX.state == AWAIT_DISTANCE) {
- if OF_UNLIKELY (!of_huffman_tree_walk(self,
+ if (CTX.state == huffmanStateAwaitDistance) {
+ if OF_UNLIKELY (!OFHuffmanTreeWalk(self,
tryReadBits, &CTX.treeIter, &value))
return bytesWritten;
if OF_UNLIKELY (value >= numDistanceCodes)
@throw [OFInvalidFormatException
@@ -544,32 +542,34 @@
extraBits = distanceExtraBits[value];
if (extraBits > 0) {
if OF_UNLIKELY (!tryReadBits(self,
&bits, extraBits)) {
- CTX.state =
- AWAIT_DISTANCE_EXTRA_BITS;
+#define HSADEB huffmanStateAwaitDistanceExtraBits
+ CTX.state = HSADEB;
+#undef HSADEB
CTX.extraBits = extraBits;
return bytesWritten;
}
CTX.distance += bits;
}
- CTX.state = PROCESS_PAIR;
- } else if (CTX.state == AWAIT_DISTANCE_EXTRA_BITS) {
+ CTX.state = huffmanStateProcessPair;
+ } else if (CTX.state ==
+ huffmanStateAwaitDistanceExtraBits) {
if OF_UNLIKELY (!tryReadBits(self, &bits,
CTX.extraBits))
return bytesWritten;
CTX.distance += bits;
- CTX.state = PROCESS_PAIR;
+ CTX.state = huffmanStateProcessPair;
}
/* Length distance pair */
- if (CTX.state == PROCESS_PAIR) {
+ if (CTX.state == huffmanStateProcessPair) {
for (uint_fast16_t j = 0; j < CTX.length; j++) {
uint16_t idx;
if OF_UNLIKELY (length == 0) {
CTX.length -= j;
@@ -588,33 +588,33 @@
_slidingWindowIndex =
(_slidingWindowIndex + 1) &
_slidingWindowMask;
}
- CTX.state = AWAIT_CODE;
+ CTX.state = huffmanStateAwaitCode;
CTX.treeIter = CTX.litLenTree;
}
- if OF_UNLIKELY (!of_huffman_tree_walk(self, tryReadBits,
+ if OF_UNLIKELY (!OFHuffmanTreeWalk(self, tryReadBits,
&CTX.treeIter, &value))
return bytesWritten;
/* End of block */
if OF_UNLIKELY (value == 256) {
if (CTX.litLenTree != fixedLitLenTree)
- of_huffman_tree_release(CTX.litLenTree);
+ OFHuffmanTreeFree(CTX.litLenTree);
if (CTX.distTree != fixedDistTree)
- of_huffman_tree_release(CTX.distTree);
+ OFHuffmanTreeFree(CTX.distTree);
- _state = BLOCK_HEADER;
+ _state = stateBlockHeader;
goto start;
}
/* Literal byte */
if OF_LIKELY (value < 256) {
if OF_UNLIKELY (length == 0) {
- CTX.state = WRITE_VALUE;
+ CTX.state = huffmanStateWriteValue;
CTX.value = value;
return bytesWritten;
}
buffer[bytesWritten++] = value;
@@ -639,19 +639,20 @@
if (extraBits > 0) {
if OF_UNLIKELY (!tryReadBits(self, &bits,
extraBits)) {
CTX.extraBits = extraBits;
- CTX.state = AWAIT_LENGTH_EXTRA_BITS;
+ CTX.state =
+ huffmanStateAwaitLengthExtraBits;
return bytesWritten;
}
CTX.length += bits;
}
CTX.treeIter = CTX.distTree;
- CTX.state = AWAIT_DISTANCE;
+ CTX.state = huffmanStateAwaitDistance;
}
break;
#undef CTX
}
Index: src/OFInvertedCharacterSet.h
==================================================================
--- src/OFInvertedCharacterSet.h
+++ src/OFInvertedCharacterSet.h
@@ -18,12 +18,12 @@
OF_ASSUME_NONNULL_BEGIN
@interface OFInvertedCharacterSet: OFCharacterSet
{
OFCharacterSet *_characterSet;
- bool (*_characterIsMember)(id, SEL, of_unichar_t);
+ bool (*_characterIsMember)(id, SEL, OFUnichar);
}
- (instancetype)initWithCharacterSet: (OFCharacterSet *)characterSet;
@end
OF_ASSUME_NONNULL_END
Index: src/OFInvertedCharacterSet.m
==================================================================
--- src/OFInvertedCharacterSet.m
+++ src/OFInvertedCharacterSet.m
@@ -30,11 +30,11 @@
{
self = [super init];
@try {
_characterSet = [characterSet retain];
- _characterIsMember = (bool (*)(id, SEL, of_unichar_t))
+ _characterIsMember = (bool (*)(id, SEL, OFUnichar))
[_characterSet methodForSelector:
@selector(characterIsMember:)];
} @catch (id e) {
[self release];
@throw e;
@@ -48,11 +48,11 @@
[_characterSet release];
[super dealloc];
}
-- (bool)characterIsMember: (of_unichar_t)character
+- (bool)characterIsMember: (OFUnichar)character
{
return !_characterIsMember(_characterSet, @selector(characterIsMember:),
character);
}
Index: src/OFInvocation.m
==================================================================
--- src/OFInvocation.m
+++ src/OFInvocation.m
@@ -21,11 +21,11 @@
#import "OFArray.h"
#import "OFData.h"
#import "OFMethodSignature.h"
#ifdef OF_INVOCATION_CAN_INVOKE
-extern void of_invocation_invoke(OFInvocation *);
+extern void OFInvocationInvoke(OFInvocation *);
#endif
@implementation OFInvocation
@synthesize methodSignature = _methodSignature;
@@ -50,20 +50,20 @@
for (size_t i = 0; i < numberOfArguments; i++) {
OFMutableData *data;
typeEncoding = [_methodSignature
argumentTypeAtIndex: i];
- typeSize = of_sizeof_type_encoding(typeEncoding);
+ typeSize = OFSizeOfTypeEncoding(typeEncoding);
data = [OFMutableData dataWithItemSize: typeSize
capacity: 1];
[data increaseCountBy: 1];
[_arguments addObject: data];
}
typeEncoding = _methodSignature.methodReturnType;
- typeSize = of_sizeof_type_encoding(typeEncoding);
+ typeSize = OFSizeOfTypeEncoding(typeEncoding);
if (typeSize > 0) {
_returnValue = [[OFMutableData alloc]
initWithItemSize: typeSize
capacity: 1];
@@ -111,9 +111,9 @@
}
#ifdef OF_INVOCATION_CAN_INVOKE
- (void)invoke
{
- of_invocation_invoke(self);
+ OFInvocationInvoke(self);
}
#endif
@end
Index: src/OFJSONRepresentation.h
==================================================================
--- src/OFJSONRepresentation.h
+++ src/OFJSONRepresentation.h
@@ -17,15 +17,20 @@
@class OFString;
OF_ASSUME_NONNULL_BEGIN
-enum {
- OF_JSON_REPRESENTATION_PRETTY = 0x01,
- OF_JSON_REPRESENTATION_JSON5 = 0x02,
- OF_JSON_REPRESENTATION_IDENTIFIER = 0x10
-};
+/**
+ * @brief Options to change the behavior when creating a JSON representation.
+ */
+typedef enum {
+ /** Optimize for readability */
+ OFJSONRepresentationOptionPretty = 0x01,
+ /** Generate JSON5 */
+ OFJSONRepresentationOptionJSON5 = 0x02,
+ OFJSONRepresentationOptionIsIdentifier = 0x10
+} OFJSONRepresentationOptions;
/**
* @protocol OFJSONRepresentation
* OFJSONRepresentation.h ObjFW/OFJSONRepresentation.h
*
@@ -43,18 +48,13 @@
@property (readonly, nonatomic) OFString *JSONRepresentation;
/**
* @brief Returns the JSON representation of the object as a string.
*
- * @param options The options to use when creating a JSON representation.@n
- * Possible values are:
- * Value | Description
- * --------------------------------|-------------------------
- * `OF_JSON_REPRESENTATION_PRETTY` | Optimize for readability
- * `OF_JSON_REPRESENTATION_JSON5` | Generate JSON5
- *
+ * @param options The options to use when creating a JSON representation
* @return The JSON representation of the object as a string
*/
-- (OFString *)JSONRepresentationWithOptions: (int)options;
+- (OFString *)JSONRepresentationWithOptions:
+ (OFJSONRepresentationOptions)options;
@end
OF_ASSUME_NONNULL_END
Index: src/OFKernelEventObserver.h
==================================================================
--- src/OFKernelEventObserver.h
+++ src/OFKernelEventObserver.h
@@ -12,13 +12,12 @@
* LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
* file.
*/
#import "OFObject.h"
-
#ifdef OF_HAVE_SOCKETS
-# import "socket.h"
+# import "OFSocket.h"
#endif
#ifdef OF_AMIGAOS
# include
# include
@@ -126,11 +125,11 @@
struct Task *_waitingTask;
ULONG _cancelSignal;
#elif defined(OF_HAVE_PIPE)
int _cancelFD[2];
#else
- of_socket_t _cancelFD[2];
+ OFSocketHandle _cancelFD[2];
struct sockaddr_in _cancelAddr;
#endif
#ifdef OF_AMIGAOS
ULONG _execSignalMask;
#endif
@@ -211,11 +210,11 @@
* @brief Observes all objects until an event happens on an object or the
* timeout is reached.
*
* @param timeInterval The time to wait for an event, in seconds
*/
-- (void)observeForTimeInterval: (of_time_interval_t)timeInterval;
+- (void)observeForTimeInterval: (OFTimeInterval)timeInterval;
/**
* @brief Observes all objects until an event happens on an object or the
* specified date is reached.
*
Index: src/OFKernelEventObserver.m
==================================================================
--- src/OFKernelEventObserver.m
+++ src/OFKernelEventObserver.m
@@ -21,48 +21,38 @@
#import "OFKernelEventObserver.h"
#import "OFArray.h"
#import "OFData.h"
#import "OFDate.h"
-#import "OFStream.h"
-#import "OFStream+Private.h"
-#ifndef OF_HAVE_PIPE
-# import "OFStreamSocket.h"
+#ifdef HAVE_EPOLL
+# import "OFEpollKernelEventObserver.h"
#endif
-
#ifdef HAVE_KQUEUE
# import "OFKqueueKernelEventObserver.h"
#endif
-#ifdef HAVE_EPOLL
-# import "OFEpollKernelEventObserver.h"
-#endif
#ifdef HAVE_POLL
# import "OFPollKernelEventObserver.h"
#endif
#ifdef HAVE_SELECT
# import "OFSelectKernelEventObserver.h"
#endif
+#import "OFSocket.h"
+#import "OFSocket+Private.h"
+#import "OFStream.h"
+#import "OFStream+Private.h"
+#ifndef OF_HAVE_PIPE
+# import "OFStreamSocket.h"
+#endif
#import "OFInitializationFailedException.h"
#import "OFInvalidArgumentException.h"
#import "OFOutOfRangeException.h"
-#import "socket.h"
-#import "socket_helpers.h"
-
#ifdef OF_AMIGAOS
# include
#endif
-enum {
- QUEUE_ADD = 0,
- QUEUE_REMOVE = 1,
- QUEUE_READ = 0,
- QUEUE_WRITE = 2
-};
-#define QUEUE_ACTION (QUEUE_ADD | QUEUE_REMOVE)
-
@implementation OFKernelEventObserver
@synthesize delegate = _delegate;
#ifdef OF_AMIGAOS
@synthesize execSignalMask = _execSignalMask;
#endif
@@ -70,11 +60,11 @@
+ (void)initialize
{
if (self != [OFKernelEventObserver class])
return;
- if (!of_socket_init())
+ if (!OFSocketInit())
@throw [OFInitializationFailedException
exceptionWithClass: self];
}
+ (instancetype)observer
@@ -118,11 +108,11 @@
@throw [OFInitializationFailedException
exceptionWithClass: self.class];
#elif !defined(OF_AMIGAOS)
_cancelFD[0] = _cancelFD[1] = socket(AF_INET, SOCK_DGRAM, 0);
- if (_cancelFD[0] == INVALID_SOCKET)
+ if (_cancelFD[0] == OFInvalidSocketHandle)
@throw [OFInitializationFailedException
exceptionWithClass: self.class];
_cancelAddr.sin_family = AF_INET;
_cancelAddr.sin_port = 0;
@@ -136,11 +126,11 @@
sizeof(_cancelAddr)) != 0)
@throw [OFInitializationFailedException
exceptionWithClass: self.class];
cancelAddrLen = sizeof(_cancelAddr);
- if (of_getsockname(_cancelFD[0],
+ if (OFGetSockName(_cancelFD[0],
(struct sockaddr *)&_cancelAddr, &cancelAddrLen) != 0)
@throw [OFInitializationFailedException
exceptionWithClass: self.class];
# else
for (;;) {
@@ -148,19 +138,19 @@
int ret;
while (rnd < 1024)
rnd = (uint16_t)rand();
- _cancelAddr.sin_port = OF_BSWAP16_IF_LE(rnd);
+ _cancelAddr.sin_port = OFToBigEndian16(rnd);
ret = bind(_cancelFD[0],
(struct sockaddr *)&_cancelAddr,
sizeof(_cancelAddr));
if (ret == 0)
break;
- if (of_socket_errno() != EADDRINUSE)
+ if (OFSocketErrNo() != EADDRINUSE)
@throw [OFInitializationFailedException
exceptionWithClass: self.class];
}
# endif
#endif
@@ -243,11 +233,11 @@
- (void)observe
{
[self observeForTimeInterval: -1];
}
-- (void)observeForTimeInterval: (of_time_interval_t)timeInterval
+- (void)observeForTimeInterval: (OFTimeInterval)timeInterval
{
OF_UNRECOGNIZED_SELECTOR
}
- (void)observeUntilDate: (OFDate *)date
@@ -265,15 +255,15 @@
_waitingTask = NULL;
}
Permit();
#elif defined(OF_HAVE_PIPE)
- OF_ENSURE(write(_cancelFD[1], "", 1) > 0);
+ OFEnsure(write(_cancelFD[1], "", 1) > 0);
#elif defined(OF_WII)
- OF_ENSURE(sendto(_cancelFD[1], "", 1, 0,
+ OFEnsure(sendto(_cancelFD[1], "", 1, 0,
(struct sockaddr *)&_cancelAddr, 8) > 0);
#else
- OF_ENSURE(sendto(_cancelFD[1], (void *)"", 1, 0,
+ OFEnsure(sendto(_cancelFD[1], (void *)"", 1, 0,
(struct sockaddr *)&_cancelAddr, sizeof(_cancelAddr)) > 0);
#endif
}
@end
Index: src/OFKqueueKernelEventObserver.m
==================================================================
--- src/OFKqueueKernelEventObserver.m
+++ src/OFKqueueKernelEventObserver.m
@@ -32,11 +32,11 @@
#import "OFInitializationFailedException.h"
#import "OFObserveFailedException.h"
#import "OFOutOfRangeException.h"
-#define EVENTLIST_SIZE 64
+#define eventListSize 64
@implementation OFKqueueKernelEventObserver
- (instancetype)init
{
self = [super init];
@@ -151,23 +151,23 @@
errNo: errno];
[super removeObjectForWriting: object];
}
-- (void)observeForTimeInterval: (of_time_interval_t)timeInterval
+- (void)observeForTimeInterval: (OFTimeInterval)timeInterval
{
struct timespec timeout;
- struct kevent eventList[EVENTLIST_SIZE];
+ struct kevent eventList[eventListSize];
int events;
if ([self of_processReadBuffers])
return;
timeout.tv_sec = (time_t)timeInterval;
timeout.tv_nsec = (long)((timeInterval - timeout.tv_sec) * 1000000000);
- events = kevent(_kernelQueue, NULL, 0, eventList, EVENTLIST_SIZE,
+ events = kevent(_kernelQueue, NULL, 0, eventList, eventListSize,
(timeInterval != -1 ? &timeout : NULL));
if (events < 0)
@throw [OFObserveFailedException exceptionWithObserver: self
errNo: errno];
@@ -182,11 +182,11 @@
if (eventList[i].ident == (uintptr_t)_cancelFD[0]) {
char buffer;
assert(eventList[i].filter == EVFILT_READ);
- OF_ENSURE(read(_cancelFD[0], &buffer, 1) == 1);
+ OFEnsure(read(_cancelFD[0], &buffer, 1) == 1);
continue;
}
pool = objc_autoreleasePoolPush();
Index: src/OFLHAArchive.h
==================================================================
--- src/OFLHAArchive.h
+++ src/OFLHAArchive.h
@@ -29,23 +29,19 @@
*/
OF_SUBCLASSING_RESTRICTED
@interface OFLHAArchive: OFObject
{
OFStream *_stream;
- enum {
- OF_LHA_ARCHIVE_MODE_READ,
- OF_LHA_ARCHIVE_MODE_WRITE,
- OF_LHA_ARCHIVE_MODE_APPEND
- } _mode;
- of_string_encoding_t _encoding;
+ uint_least8_t _mode;
+ OFStringEncoding _encoding;
OFStream *_Nullable _lastReturnedStream;
}
/**
* @brief The encoding to use for the archive. Defaults to ISO 8859-1.
*/
-@property (nonatomic) of_string_encoding_t encoding;
+@property (nonatomic) OFStringEncoding encoding;
/**
* @brief A stream for reading the current entry.
*
* @note This is only available in read mode.
Index: src/OFLHAArchive.m
==================================================================
--- src/OFLHAArchive.m
+++ src/OFLHAArchive.m
@@ -16,27 +16,32 @@
#include "config.h"
#import "OFLHAArchive.h"
#import "OFLHAArchiveEntry.h"
#import "OFLHAArchiveEntry+Private.h"
+#import "OFCRC16.h"
#ifdef OF_HAVE_FILES
# import "OFFile.h"
#endif
#import "OFLHADecompressingStream.h"
#import "OFStream.h"
#import "OFSeekableStream.h"
#import "OFString.h"
-#import "crc16.h"
-
#import "OFChecksumMismatchException.h"
#import "OFInvalidArgumentException.h"
#import "OFNotImplementedException.h"
#import "OFNotOpenException.h"
#import "OFOutOfRangeException.h"
#import "OFTruncatedDataException.h"
#import "OFWriteFailedException.h"
+
+enum {
+ modeRead,
+ modeWrite,
+ modeAppend
+};
OF_DIRECT_MEMBERS
@interface OFLHAArchiveFileReadStream: OFStream
{
OFStream *_stream, *_decompressedStream;
@@ -53,20 +58,20 @@
OF_DIRECT_MEMBERS
@interface OFLHAArchiveFileWriteStream: OFStream
{
OFMutableLHAArchiveEntry *_entry;
- of_string_encoding_t _encoding;
+ OFStringEncoding _encoding;
OFSeekableStream *_stream;
- of_offset_t _headerOffset;
+ OFFileOffset _headerOffset;
uint32_t _bytesWritten;
uint16_t _CRC16;
}
- (instancetype)of_initWithStream: (OFSeekableStream *)stream
entry: (OFLHAArchiveEntry *)entry
- encoding: (of_string_encoding_t)encoding;
+ encoding: (OFStringEncoding)encoding;
@end
@implementation OFLHAArchive
@synthesize encoding = _encoding;
@@ -93,28 +98,27 @@
@try {
_stream = [stream retain];
if ([mode isEqual: @"r"])
- _mode = OF_LHA_ARCHIVE_MODE_READ;
+ _mode = modeRead;
else if ([mode isEqual: @"w"])
- _mode = OF_LHA_ARCHIVE_MODE_WRITE;
+ _mode = modeWrite;
else if ([mode isEqual: @"a"])
- _mode = OF_LHA_ARCHIVE_MODE_APPEND;
+ _mode = modeAppend;
else
@throw [OFInvalidArgumentException exception];
- if ((_mode == OF_LHA_ARCHIVE_MODE_WRITE ||
- _mode == OF_LHA_ARCHIVE_MODE_APPEND) &&
+ if ((_mode == modeWrite || _mode == modeAppend) &&
![_stream isKindOfClass: [OFSeekableStream class]])
@throw [OFInvalidArgumentException exception];
- if (_mode == OF_LHA_ARCHIVE_MODE_APPEND)
+ if (_mode == modeAppend)
[(OFSeekableStream *)_stream seekToOffset: 0
whence: SEEK_END];
- _encoding = OF_STRING_ENCODING_ISO_8859_1;
+ _encoding = OFStringEncodingISO8859_1;
} @catch (id e) {
[self release];
@throw e;
}
@@ -153,11 +157,11 @@
{
OFLHAArchiveEntry *entry;
char header[21];
size_t headerLen;
- if (_mode != OF_LHA_ARCHIVE_MODE_READ)
+ if (_mode != modeRead)
@throw [OFInvalidArgumentException exception];
[(OFLHAArchiveFileReadStream *)_lastReturnedStream of_skip];
@try {
[_lastReturnedStream close];
@@ -194,11 +198,11 @@
return entry;
}
- (OFStream *)streamForReadingCurrentEntry
{
- if (_mode != OF_LHA_ARCHIVE_MODE_READ)
+ if (_mode != modeRead)
@throw [OFInvalidArgumentException exception];
if (_lastReturnedStream == nil)
@throw [OFInvalidArgumentException exception];
@@ -208,12 +212,11 @@
- (OFStream *)streamForWritingEntry: (OFLHAArchiveEntry *)entry
{
OFString *compressionMethod;
- if (_mode != OF_LHA_ARCHIVE_MODE_WRITE &&
- _mode != OF_LHA_ARCHIVE_MODE_APPEND)
+ if (_mode != modeWrite && _mode != modeAppend)
@throw [OFInvalidArgumentException exception];
compressionMethod = entry.compressionMethod;
if (![compressionMethod isEqual: @"-lh0-"] &&
@@ -333,11 +336,11 @@
length = _toRead;
ret = [_decompressedStream readIntoBuffer: buffer length: length];
_toRead -= ret;
- _CRC16 = of_crc16(_CRC16, buffer, ret);
+ _CRC16 = OFCRC16(_CRC16, buffer, ret);
if (_toRead == 0) {
_atEndOfStream = true;
if (_CRC16 != _entry.CRC16) {
@@ -393,12 +396,12 @@
stream = _stream;
}
if ([stream isKindOfClass: [OFSeekableStream class]] &&
- (sizeof(of_offset_t) > 4 || toRead < INT32_MAX))
- [(OFSeekableStream *)stream seekToOffset: (of_offset_t)toRead
+ (sizeof(OFFileOffset) > 4 || toRead < INT32_MAX))
+ [(OFSeekableStream *)stream seekToOffset: (OFFileOffset)toRead
whence: SEEK_CUR];
else {
while (toRead > 0) {
char buffer[512];
size_t min = toRead;
@@ -432,11 +435,11 @@
@end
@implementation OFLHAArchiveFileWriteStream
- (instancetype)of_initWithStream: (OFSeekableStream *)stream
entry: (OFLHAArchiveEntry *)entry
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
self = [super init];
@try {
_entry = [entry mutableCopy];
@@ -481,17 +484,17 @@
@try {
bytesWritten = (uint32_t)[_stream writeBuffer: buffer
length: length];
} @catch (OFWriteFailedException *e) {
_bytesWritten += e.bytesWritten;
- _CRC16 = of_crc16(_CRC16, buffer, e.bytesWritten);
+ _CRC16 = OFCRC16(_CRC16, buffer, e.bytesWritten);
@throw e;
}
_bytesWritten += (uint32_t)bytesWritten;
- _CRC16 = of_crc16(_CRC16, buffer, bytesWritten);
+ _CRC16 = OFCRC16(_CRC16, buffer, bytesWritten);
return bytesWritten;
}
- (bool)lowlevelIsAtEndOfStream
@@ -508,11 +511,11 @@
.fileDescriptorForWriting;
}
- (void)close
{
- of_offset_t offset;
+ OFFileOffset offset;
if (_stream == nil)
@throw [OFNotOpenException exceptionWithObject: self];
_entry.uncompressedSize = _bytesWritten;
Index: src/OFLHAArchiveEntry+Private.h
==================================================================
--- src/OFLHAArchiveEntry+Private.h
+++ src/OFLHAArchiveEntry+Private.h
@@ -19,12 +19,12 @@
OF_DIRECT_MEMBERS
@interface OFLHAArchiveEntry ()
- (instancetype)of_initWithHeader: (char [_Nonnull 21])header
stream: (OFStream *)stream
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
OF_METHOD_FAMILY(init);
- (void)of_writeToStream: (OFStream *)stream
- encoding: (of_string_encoding_t)encoding;
+ encoding: (OFStringEncoding)encoding;
@end
OF_ASSUME_NONNULL_END
Index: src/OFLHAArchiveEntry.m
==================================================================
--- src/OFLHAArchiveEntry.m
+++ src/OFLHAArchiveEntry.m
@@ -18,18 +18,17 @@
#include
#import "OFLHAArchiveEntry.h"
#import "OFLHAArchiveEntry+Private.h"
#import "OFArray.h"
+#import "OFCRC16.h"
#import "OFData.h"
#import "OFDate.h"
#import "OFNumber.h"
#import "OFStream.h"
#import "OFString.h"
-#import "crc16.h"
-
#import "OFInvalidArgumentException.h"
#import "OFInvalidFormatException.h"
#import "OFOutOfRangeException.h"
#import "OFUnsupportedVersionException.h"
@@ -53,11 +52,11 @@
format: @"%Y-%m-%d %H:%M:%S"];
}
static void
parseFileNameExtension(OFLHAArchiveEntry *entry, OFData *extension,
- of_string_encoding_t encoding)
+ OFStringEncoding encoding)
{
[entry->_fileName release];
entry->_fileName = nil;
entry->_fileName = [[OFString alloc]
@@ -66,11 +65,11 @@
length: [extension count] - 1];
}
static void
parseDirectoryNameExtension(OFLHAArchiveEntry *entry, OFData *extension,
- of_string_encoding_t encoding)
+ OFStringEncoding encoding)
{
void *pool = objc_autoreleasePoolPush();
OFMutableData *data = [[extension mutableCopy] autorelease];
char *items = data.mutableItems;
size_t count = data.count;
@@ -97,11 +96,11 @@
objc_autoreleasePoolPop(pool);
}
static void
parseCommentExtension(OFLHAArchiveEntry *entry, OFData *extension,
- of_string_encoding_t encoding)
+ OFStringEncoding encoding)
{
[entry->_fileComment release];
entry->_fileComment = nil;
entry->_fileComment = [[OFString alloc]
@@ -110,40 +109,40 @@
length: extension.count - 1];
}
static void
parsePermissionsExtension(OFLHAArchiveEntry *entry, OFData *extension,
- of_string_encoding_t encoding)
+ OFStringEncoding encoding)
{
uint16_t mode;
if (extension.count != 3)
@throw [OFInvalidFormatException exception];
memcpy(&mode, (char *)extension.items + 1, 2);
- mode = OF_BSWAP16_IF_BE(mode);
+ mode = OFFromLittleEndian16(mode);
[entry->_mode release];
entry->_mode = nil;
entry->_mode = [[OFNumber alloc] initWithUnsignedShort: mode];
}
static void
parseGIDUIDExtension(OFLHAArchiveEntry *entry, OFData *extension,
- of_string_encoding_t encoding)
+ OFStringEncoding encoding)
{
uint16_t UID, GID;
if (extension.count != 5)
@throw [OFInvalidFormatException exception];
memcpy(&GID, (char *)extension.items + 1, 2);
- GID = OF_BSWAP16_IF_BE(GID);
+ GID = OFFromLittleEndian16(GID);
memcpy(&UID, (char *)extension.items + 3, 2);
- UID = OF_BSWAP16_IF_BE(UID);
+ UID = OFFromLittleEndian16(UID);
[entry->_GID release];
entry->_GID = nil;
[entry->_UID release];
@@ -153,11 +152,11 @@
entry->_UID = [[OFNumber alloc] initWithUnsignedShort: UID];
}
static void
parseGroupExtension(OFLHAArchiveEntry *entry, OFData *extension,
- of_string_encoding_t encoding)
+ OFStringEncoding encoding)
{
[entry->_group release];
entry->_group = nil;
entry->_group = [[OFString alloc]
@@ -166,11 +165,11 @@
length: extension.count - 1];
}
static void
parseOwnerExtension(OFLHAArchiveEntry *entry, OFData *extension,
- of_string_encoding_t encoding)
+ OFStringEncoding encoding)
{
[entry->_owner release];
entry->_owner = nil;
entry->_owner = [[OFString alloc]
@@ -179,19 +178,19 @@
length: extension.count - 1];
}
static void
parseModificationDateExtension(OFLHAArchiveEntry *entry, OFData *extension,
- of_string_encoding_t encoding)
+ OFStringEncoding encoding)
{
uint32_t modificationDate;
if (extension.count != 5)
@throw [OFInvalidFormatException exception];
memcpy(&modificationDate, (char *)extension.items + 1, 4);
- modificationDate = OF_BSWAP32_IF_BE(modificationDate);
+ modificationDate = OFFromLittleEndian32(modificationDate);
[entry->_modificationDate release];
entry->_modificationDate = nil;
entry->_modificationDate = [[OFDate alloc]
@@ -198,13 +197,13 @@
initWithTimeIntervalSince1970: modificationDate];
}
static bool
parseExtension(OFLHAArchiveEntry *entry, OFData *extension,
- of_string_encoding_t encoding, bool allowFileName)
+ OFStringEncoding encoding, bool allowFileName)
{
- void (*function)(OFLHAArchiveEntry *, OFData *, of_string_encoding_t) =
+ void (*function)(OFLHAArchiveEntry *, OFData *, OFStringEncoding) =
NULL;
switch (*(char *)[extension itemAtIndex: 0]) {
case 0x01:
if (allowFileName)
@@ -240,11 +239,11 @@
return true;
}
static void
readExtensions(OFLHAArchiveEntry *entry, OFStream *stream,
- of_string_encoding_t encoding, bool allowFileName)
+ OFStringEncoding encoding, bool allowFileName)
{
uint16_t size;
while ((size = [stream readLittleEndianInt16]) > 0) {
OFData *extension;
@@ -265,12 +264,11 @@
}
}
}
static void
-getFileNameAndDirectoryName(OFLHAArchiveEntry *entry,
- of_string_encoding_t encoding,
+getFileNameAndDirectoryName(OFLHAArchiveEntry *entry, OFStringEncoding encoding,
const char **fileName, size_t *fileNameLength,
const char **directoryName, size_t *directoryNameLength)
{
OFMutableData *data;
char *cString;
@@ -331,30 +329,30 @@
return self;
}
- (instancetype)of_initWithHeader: (char [21])header
stream: (OFStream *)stream
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
self = [super init];
@try {
uint32_t date;
_compressionMethod = [[OFString alloc]
initWithCString: header + 2
- encoding: OF_STRING_ENCODING_ASCII
+ encoding: OFStringEncodingASCII
length: 5];
memcpy(&_compressedSize, header + 7, 4);
- _compressedSize = OF_BSWAP32_IF_BE(_compressedSize);
+ _compressedSize = OFFromLittleEndian32(_compressedSize);
memcpy(&_uncompressedSize, header + 11, 4);
- _uncompressedSize = OF_BSWAP32_IF_BE(_uncompressedSize);
+ _uncompressedSize = OFFromLittleEndian32(_uncompressedSize);
memcpy(&date, header + 15, 4);
- date = OF_BSWAP32_IF_BE(date);
+ date = OFFromLittleEndian32(date);
_headerLevel = header[20];
_extensions = [[OFMutableArray alloc] init];
switch (_headerLevel) {
@@ -553,11 +551,11 @@
{
return _extensions;
}
- (void)of_writeToStream: (OFStream *)stream
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
void *pool = objc_autoreleasePoolPush();
OFMutableData *data = [OFMutableData dataWithCapacity: 24];
const char *fileName, *directoryName;
size_t fileNameLength, directoryNameLength;
@@ -564,11 +562,11 @@
uint16_t tmp16;
uint32_t tmp32;
size_t headerSize;
if ([_compressionMethod cStringLengthWithEncoding:
- OF_STRING_ENCODING_ASCII] != 5)
+ OFStringEncodingASCII] != 5)
@throw [OFInvalidArgumentException exception];
getFileNameAndDirectoryName(self, encoding, &fileName, &fileNameLength,
&directoryName, &directoryNameLength);
@@ -578,48 +576,48 @@
/* Length. Filled in after we're done. */
[data increaseCountBy: 2];
[data addItems: [_compressionMethod
- cStringWithEncoding: OF_STRING_ENCODING_ASCII]
+ cStringWithEncoding: OFStringEncodingASCII]
count: 5];
- tmp32 = OF_BSWAP32_IF_BE(_compressedSize);
+ tmp32 = OFToLittleEndian32(_compressedSize);
[data addItems: &tmp32 count: sizeof(tmp32)];
- tmp32 = OF_BSWAP32_IF_BE(_uncompressedSize);
+ tmp32 = OFToLittleEndian32(_uncompressedSize);
[data addItems: &tmp32 count: sizeof(tmp32)];
- tmp32 = OF_BSWAP32_IF_BE((uint32_t)_date.timeIntervalSince1970);
+ tmp32 = OFToLittleEndian32((uint32_t)_date.timeIntervalSince1970);
[data addItems: &tmp32 count: sizeof(tmp32)];
/* Reserved */
[data increaseCountBy: 1];
/* Header level */
[data addItem: "\x02"];
/* CRC16 */
- tmp16 = OF_BSWAP16_IF_BE(_CRC16);
+ tmp16 = OFToLittleEndian16(_CRC16);
[data addItems: &tmp16 count: sizeof(tmp16)];
/* Operating system identifier */
[data addItem: "U"];
/* Common header. Contains CRC16, which is written at the end. */
- tmp16 = OF_BSWAP16_IF_BE(5);
+ tmp16 = OFToLittleEndian16(5);
[data addItems: &tmp16 count: sizeof(tmp16)];
[data addItem: "\x00"];
[data increaseCountBy: 2];
- tmp16 = OF_BSWAP16_IF_BE((uint16_t)fileNameLength + 3);
+ tmp16 = OFToLittleEndian16((uint16_t)fileNameLength + 3);
[data addItems: &tmp16 count: sizeof(tmp16)];
[data addItem: "\x01"];
[data addItems: fileName count: fileNameLength];
if (directoryNameLength > 0) {
- tmp16 = OF_BSWAP16_IF_BE((uint16_t)directoryNameLength + 3);
+ tmp16 = OFToLittleEndian16((uint16_t)directoryNameLength + 3);
[data addItems: &tmp16 count: sizeof(tmp16)];
[data addItem: "\x02"];
[data addItems: directoryName count: directoryNameLength];
}
@@ -628,38 +626,38 @@
[_fileComment cStringLengthWithEncoding: encoding];
if (fileCommentLength > UINT16_MAX - 3)
@throw [OFOutOfRangeException exception];
- tmp16 = OF_BSWAP16_IF_BE((uint16_t)fileCommentLength + 3);
+ tmp16 = OFToLittleEndian16((uint16_t)fileCommentLength + 3);
[data addItems: &tmp16 count: sizeof(tmp16)];
[data addItem: "\x3F"];
[data addItems: [_fileComment cStringWithEncoding: encoding]
count: fileCommentLength];
}
if (_mode != nil) {
- tmp16 = OF_BSWAP16_IF_BE(5);
+ tmp16 = OFToLittleEndian16(5);
[data addItems: &tmp16 count: sizeof(tmp16)];
[data addItem: "\x50"];
- tmp16 = OF_BSWAP16_IF_BE(_mode.unsignedShortValue);
+ tmp16 = OFToLittleEndian16(_mode.unsignedShortValue);
[data addItems: &tmp16 count: sizeof(tmp16)];
}
if (_UID != nil || _GID != nil) {
if (_UID == nil || _GID == nil)
@throw [OFInvalidArgumentException exception];
- tmp16 = OF_BSWAP16_IF_BE(7);
+ tmp16 = OFToLittleEndian16(7);
[data addItems: &tmp16 count: sizeof(tmp16)];
[data addItem: "\x51"];
- tmp16 = OF_BSWAP16_IF_BE(_GID.unsignedShortValue);
+ tmp16 = OFToLittleEndian16(_GID.unsignedShortValue);
[data addItems: &tmp16 count: sizeof(tmp16)];
- tmp16 = OF_BSWAP16_IF_BE(_UID.unsignedShortValue);
+ tmp16 = OFToLittleEndian16(_UID.unsignedShortValue);
[data addItems: &tmp16 count: sizeof(tmp16)];
}
if (_group != nil) {
size_t groupLength =
@@ -666,11 +664,11 @@
[_group cStringLengthWithEncoding: encoding];
if (groupLength > UINT16_MAX - 3)
@throw [OFOutOfRangeException exception];
- tmp16 = OF_BSWAP16_IF_BE((uint16_t)groupLength + 3);
+ tmp16 = OFToLittleEndian16((uint16_t)groupLength + 3);
[data addItems: &tmp16 count: sizeof(tmp16)];
[data addItem: "\x52"];
[data addItems: [_group cStringWithEncoding: encoding]
count: groupLength];
}
@@ -680,23 +678,23 @@
[_owner cStringLengthWithEncoding: encoding];
if (ownerLength > UINT16_MAX - 3)
@throw [OFOutOfRangeException exception];
- tmp16 = OF_BSWAP16_IF_BE((uint16_t)ownerLength + 3);
+ tmp16 = OFToLittleEndian16((uint16_t)ownerLength + 3);
[data addItems: &tmp16 count: sizeof(tmp16)];
[data addItem: "\x53"];
[data addItems: [_owner cStringWithEncoding: encoding]
count: ownerLength];
}
if (_modificationDate != nil) {
- tmp16 = OF_BSWAP16_IF_BE(7);
+ tmp16 = OFToLittleEndian16(7);
[data addItems: &tmp16 count: sizeof(tmp16)];
[data addItem: "\x54"];
- tmp32 = OF_BSWAP32_IF_BE(
+ tmp32 = OFToLittleEndian32(
(uint32_t)_modificationDate.timeIntervalSince1970);
[data addItems: &tmp32 count: sizeof(tmp32)];
}
for (OFData *extension in _extensions) {
@@ -706,11 +704,11 @@
@throw [OFInvalidArgumentException exception];
if (extensionLength > UINT16_MAX - 2)
@throw [OFOutOfRangeException exception];
- tmp16 = OF_BSWAP16_IF_BE((uint16_t)extensionLength + 2);
+ tmp16 = OFToLittleEndian16((uint16_t)extensionLength + 2);
[data addItems: &tmp16 count: sizeof(tmp16)];
[data addItems: extension.items count: extension.count];
}
/* Zero-length extension to terminate */
@@ -720,15 +718,15 @@
if (headerSize > UINT16_MAX)
@throw [OFOutOfRangeException exception];
/* Now fill in the size and CRC16 for the entire header */
- tmp16 = OF_BSWAP16_IF_BE(headerSize);
+ tmp16 = OFToLittleEndian16(headerSize);
memcpy([data mutableItemAtIndex: 0], &tmp16, sizeof(tmp16));
- tmp16 = of_crc16(0, data.items, data.count);
- tmp16 = OF_BSWAP16_IF_BE(tmp16);
+ tmp16 = OFCRC16(0, data.items, data.count);
+ tmp16 = OFToLittleEndian16(tmp16);
memcpy([data mutableItemAtIndex: 27], &tmp16, sizeof(tmp16));
[stream writeData: data];
objc_autoreleasePoolPop(pool);
Index: src/OFLHADecompressingStream.h
==================================================================
--- src/OFLHADecompressingStream.h
+++ src/OFLHADecompressingStream.h
@@ -12,32 +12,35 @@
* LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
* file.
*/
#import "OFStream.h"
+#import "OFHuffmanTree.h"
OF_ASSUME_NONNULL_BEGIN
-#define OF_LHA_DECOMPRESSING_STREAM_BUFFER_SIZE 4096
+#define OFLHADecompressingStreamBufferSize 4096
OF_DIRECT_MEMBERS
@interface OFLHADecompressingStream: OFStream
{
OFStream *_stream;
uint8_t _distanceBits, _dictionaryBits;
- unsigned char _buffer[OF_LHA_DECOMPRESSING_STREAM_BUFFER_SIZE];
+ unsigned char _buffer[OFLHADecompressingStreamBufferSize];
uint32_t _bytesConsumed;
uint16_t _bufferIndex, _bufferLength;
uint8_t _byte;
uint8_t _bitIndex, _savedBitsLength;
uint16_t _savedBits;
unsigned char *_slidingWindow;
uint32_t _slidingWindowIndex, _slidingWindowMask;
int _state;
uint16_t _symbolsLeft;
- struct of_huffman_tree *_Nullable _codeLenTree, *_Nullable _litLenTree;
- struct of_huffman_tree *_Nullable _distTree, *_Nullable _treeIter;
+ OFHuffmanTree _Nullable _codeLenTree;
+ OFHuffmanTree _Nullable _litLenTree;
+ OFHuffmanTree _Nullable _distTree;
+ OFHuffmanTree _Nullable _treeIter;
uint16_t _codesCount, _codesReceived;
bool _currentIsExtendedLength, _skip;
uint8_t *_Nullable _codesLengths;
uint16_t _length;
uint32_t _distance;
Index: src/OFLHADecompressingStream.m
==================================================================
--- src/OFLHADecompressingStream.m
+++ src/OFLHADecompressingStream.m
@@ -18,30 +18,30 @@
#include
#import "OFLHADecompressingStream.h"
#import "OFKernelEventObserver.h"
-#import "huffman_tree.h"
+#import "OFHuffmanTree.h"
#import "OFInvalidFormatException.h"
#import "OFNotOpenException.h"
-enum state {
- STATE_BLOCK_HEADER,
- STATE_CODE_LEN_CODES_COUNT,
- STATE_CODE_LEN_TREE,
- STATE_CODE_LEN_TREE_SINGLE,
- STATE_LITLEN_CODES_COUNT,
- STATE_LITLEN_TREE,
- STATE_LITLEN_TREE_SINGLE,
- STATE_DIST_CODES_COUNT,
- STATE_DIST_TREE,
- STATE_DIST_TREE_SINGLE,
- STATE_BLOCK_LITLEN,
- STATE_BLOCK_DIST_LENGTH,
- STATE_BLOCK_DIST_LENGTH_EXTRA,
- STATE_BLOCK_LEN_DIST_PAIR
+enum State {
+ stateBlockHeader,
+ stateCodeLenCodesCount,
+ stateCodeLenTree,
+ stateCodeLenTreeSingle,
+ stateLitLenCodesCount,
+ stateLitLenTree,
+ stateLitLenTreeSingle,
+ stateDistCodesCount,
+ stateDistTree,
+ stateDistTreeSingle,
+ stateBlockLitLen,
+ stateBlockDistLength,
+ stateBlockDistLengthExtra,
+ stateBlockLenDistPair
};
@implementation OFLHADecompressingStream
@synthesize bytesConsumed = _bytesConsumed;
@@ -58,11 +58,11 @@
stream->_bufferLength)
stream->_byte =
stream->_buffer[stream->_bufferIndex++];
else {
const size_t bufferLength =
- OF_LHA_DECOMPRESSING_STREAM_BUFFER_SIZE;
+ OFLHADecompressingStreamBufferSize;
size_t length = [stream->_stream
readIntoBuffer: stream->_buffer
length: bufferLength];
stream->_bytesConsumed += (uint32_t)length;
@@ -106,11 +106,11 @@
_distanceBits = distanceBits;
_dictionaryBits = dictionaryBits;
_slidingWindowMask = (1u << dictionaryBits) - 1;
- _slidingWindow = of_alloc(_slidingWindowMask + 1, 1);
+ _slidingWindow = OFAllocMemory(_slidingWindowMask + 1, 1);
memset(_slidingWindow, ' ', _slidingWindowMask + 1);
} @catch (id e) {
[self release];
@throw e;
}
@@ -121,20 +121,20 @@
- (void)dealloc
{
if (_stream != nil)
[self close];
- free(_slidingWindow);
+ OFFreeMemory(_slidingWindow);
if (_codeLenTree != NULL)
- of_huffman_tree_release(_codeLenTree);
+ OFHuffmanTreeFree(_codeLenTree);
if (_litLenTree != NULL)
- of_huffman_tree_release(_litLenTree);
+ OFHuffmanTreeFree(_litLenTree);
if (_distTree != NULL)
- of_huffman_tree_release(_distTree);
+ OFHuffmanTreeFree(_distTree);
- free(_codesLengths);
+ OFFreeMemory(_codesLengths);
[super dealloc];
}
- (size_t)lowlevelReadIntoBuffer: (void *)buffer_
@@ -146,43 +146,43 @@
if (_stream == nil)
@throw [OFNotOpenException exceptionWithObject: self];
if (_stream.atEndOfStream && _bufferLength - _bufferIndex == 0 &&
- _state == STATE_BLOCK_HEADER)
+ _state == stateBlockHeader)
return 0;
start:
- switch ((enum state)_state) {
- case STATE_BLOCK_HEADER:
+ switch ((enum State)_state) {
+ case stateBlockHeader:
if OF_UNLIKELY (!tryReadBits(self, &bits, 16))
return bytesWritten;
_symbolsLeft = bits;
- _state = STATE_CODE_LEN_CODES_COUNT;
+ _state = stateCodeLenCodesCount;
goto start;
- case STATE_CODE_LEN_CODES_COUNT:
+ case stateCodeLenCodesCount:
if OF_UNLIKELY (!tryReadBits(self, &bits, 5))
return bytesWritten;
if OF_UNLIKELY (bits > 20)
@throw [OFInvalidFormatException exception];
if OF_UNLIKELY (bits == 0) {
- _state = STATE_CODE_LEN_TREE_SINGLE;
+ _state = stateCodeLenTreeSingle;
goto start;
}
_codesCount = bits;
_codesReceived = 0;
- _codesLengths = of_alloc_zeroed(bits, 1);
+ _codesLengths = OFAllocZeroedMemory(bits, 1);
_skip = true;
- _state = STATE_CODE_LEN_TREE;
+ _state = stateCodeLenTree;
goto start;
- case STATE_CODE_LEN_TREE:
+ case stateCodeLenTree:
while (_codesReceived < _codesCount) {
if OF_UNLIKELY (_currentIsExtendedLength) {
if OF_UNLIKELY (!tryReadBits(self, &bits, 1))
return bytesWritten;
@@ -222,49 +222,48 @@
continue;
} else
_codesReceived++;
}
- _codeLenTree = of_huffman_tree_construct(_codesLengths,
- _codesCount);
- free(_codesLengths);
+ _codeLenTree = OFHuffmanTreeNew(_codesLengths, _codesCount);
+ OFFreeMemory(_codesLengths);
_codesLengths = NULL;
- _state = STATE_LITLEN_CODES_COUNT;
+ _state = stateLitLenCodesCount;
goto start;
- case STATE_CODE_LEN_TREE_SINGLE:
+ case stateCodeLenTreeSingle:
if OF_UNLIKELY (!tryReadBits(self, &bits, 5))
return bytesWritten;
- _codeLenTree = of_huffman_tree_construct_single(bits);
+ _codeLenTree = OFHuffmanTreeNewSingle(bits);
- _state = STATE_LITLEN_CODES_COUNT;
+ _state = stateLitLenCodesCount;
goto start;
- case STATE_LITLEN_CODES_COUNT:
+ case stateLitLenCodesCount:
if OF_UNLIKELY (!tryReadBits(self, &bits, 9))
return bytesWritten;
if OF_UNLIKELY (bits > 510)
@throw [OFInvalidFormatException exception];
if OF_UNLIKELY (bits == 0) {
- of_huffman_tree_release(_codeLenTree);
+ OFHuffmanTreeFree(_codeLenTree);
_codeLenTree = NULL;
- _state = STATE_LITLEN_TREE_SINGLE;
+ _state = stateLitLenTreeSingle;
goto start;
}
_codesCount = bits;
_codesReceived = 0;
- _codesLengths = of_alloc_zeroed(bits, 1);
+ _codesLengths = OFAllocZeroedMemory(bits, 1);
_skip = false;
_treeIter = _codeLenTree;
- _state = STATE_LITLEN_TREE;
+ _state = stateLitLenTree;
goto start;
- case STATE_LITLEN_TREE:
+ case stateLitLenTree:
while (_codesReceived < _codesCount) {
if OF_UNLIKELY (_skip) {
uint16_t skipCount;
switch (_codesLengths[_codesReceived]) {
@@ -284,11 +283,11 @@
return bytesWritten;
skipCount = bits + 20;
break;
default:
- OF_ENSURE(0);
+ OFEnsure(0);
}
if OF_UNLIKELY (_codesReceived + skipCount >
_codesCount)
@throw [OFInvalidFormatException
@@ -299,12 +298,12 @@
_skip = false;
continue;
}
- if (!of_huffman_tree_walk(self, tryReadBits,
- &_treeIter, &value))
+ if (!OFHuffmanTreeWalk(self, tryReadBits, &_treeIter,
+ &value))
return bytesWritten;
_treeIter = _codeLenTree;
if (value < 3) {
@@ -312,48 +311,47 @@
_skip = true;
} else
_codesLengths[_codesReceived++] = value - 2;
}
- _litLenTree = of_huffman_tree_construct(_codesLengths,
- _codesCount);
- free(_codesLengths);
+ _litLenTree = OFHuffmanTreeNew(_codesLengths, _codesCount);
+ OFFreeMemory(_codesLengths);
_codesLengths = NULL;
- of_huffman_tree_release(_codeLenTree);
+ OFHuffmanTreeFree(_codeLenTree);
_codeLenTree = NULL;
- _state = STATE_DIST_CODES_COUNT;
+ _state = stateDistCodesCount;
goto start;
- case STATE_LITLEN_TREE_SINGLE:
+ case stateLitLenTreeSingle:
if OF_UNLIKELY (!tryReadBits(self, &bits, 9))
return bytesWritten;
- _litLenTree = of_huffman_tree_construct_single(bits);
+ _litLenTree = OFHuffmanTreeNewSingle(bits);
- _state = STATE_DIST_CODES_COUNT;
+ _state = stateDistCodesCount;
goto start;
- case STATE_DIST_CODES_COUNT:
+ case stateDistCodesCount:
if OF_UNLIKELY (!tryReadBits(self, &bits, _distanceBits))
return bytesWritten;
if OF_UNLIKELY (bits > _dictionaryBits)
@throw [OFInvalidFormatException exception];
if OF_UNLIKELY (bits == 0) {
- _state = STATE_DIST_TREE_SINGLE;
+ _state = stateDistTreeSingle;
goto start;
}
_codesCount = bits;
_codesReceived = 0;
- _codesLengths = of_alloc_zeroed(bits, 1);
+ _codesLengths = OFAllocZeroedMemory(bits, 1);
_treeIter = _codeLenTree;
- _state = STATE_DIST_TREE;
+ _state = stateDistTree;
goto start;
- case STATE_DIST_TREE:
+ case stateDistTree:
while (_codesReceived < _codesCount) {
if OF_UNLIKELY (_currentIsExtendedLength) {
if OF_UNLIKELY (!tryReadBits(self, &bits, 1))
return bytesWritten;
@@ -377,34 +375,33 @@
continue;
} else
_codesReceived++;
}
- _distTree = of_huffman_tree_construct(_codesLengths,
- _codesCount);
- free(_codesLengths);
+ _distTree = OFHuffmanTreeNew(_codesLengths, _codesCount);
+ OFFreeMemory(_codesLengths);
_codesLengths = NULL;
_treeIter = _litLenTree;
- _state = STATE_BLOCK_LITLEN;
+ _state = stateBlockLitLen;
goto start;
- case STATE_DIST_TREE_SINGLE:
+ case stateDistTreeSingle:
if OF_UNLIKELY (!tryReadBits(self, &bits, _distanceBits))
return bytesWritten;
- _distTree = of_huffman_tree_construct_single(bits);
+ _distTree = OFHuffmanTreeNewSingle(bits);
_treeIter = _litLenTree;
- _state = STATE_BLOCK_LITLEN;
+ _state = stateBlockLitLen;
goto start;
- case STATE_BLOCK_LITLEN:
+ case stateBlockLitLen:
if OF_UNLIKELY (_symbolsLeft == 0) {
- of_huffman_tree_release(_litLenTree);
- of_huffman_tree_release(_distTree);
+ OFHuffmanTreeFree(_litLenTree);
+ OFHuffmanTreeFree(_distTree);
_litLenTree = _distTree = NULL;
- _state = STATE_BLOCK_HEADER;
+ _state = stateBlockHeader;
/*
* We must return here, as there is no indication
* whether this was the last block. Whoever called this
* method needs to check if everything has been read
@@ -425,11 +422,11 @@
}
if OF_UNLIKELY (length == 0)
return bytesWritten;
- if OF_UNLIKELY (!of_huffman_tree_walk(self, tryReadBits,
+ if OF_UNLIKELY (!OFHuffmanTreeWalk(self, tryReadBits,
&_treeIter, &value))
return bytesWritten;
if OF_LIKELY (value < 256) {
buffer[bytesWritten++] = value;
@@ -442,34 +439,33 @@
_symbolsLeft--;
_treeIter = _litLenTree;
} else {
_length = value - 253;
_treeIter = _distTree;
- _state = STATE_BLOCK_DIST_LENGTH;
+ _state = stateBlockDistLength;
}
goto start;
- case STATE_BLOCK_DIST_LENGTH:
- if OF_UNLIKELY (!of_huffman_tree_walk(self, tryReadBits,
+ case stateBlockDistLength:
+ if OF_UNLIKELY (!OFHuffmanTreeWalk(self, tryReadBits,
&_treeIter, &value))
return bytesWritten;
_distance = value;
_state = (value < 2
- ? STATE_BLOCK_LEN_DIST_PAIR
- : STATE_BLOCK_DIST_LENGTH_EXTRA);
+ ? stateBlockLenDistPair : stateBlockDistLengthExtra);
goto start;
- case STATE_BLOCK_DIST_LENGTH_EXTRA:
+ case stateBlockDistLengthExtra:
if OF_UNLIKELY (!tryReadBits(self, &bits, _distance - 1))
return bytesWritten;
_distance = bits + (1u << (_distance - 1));
- _state = STATE_BLOCK_LEN_DIST_PAIR;
+ _state = stateBlockLenDistPair;
goto start;
- case STATE_BLOCK_LEN_DIST_PAIR:
+ case stateBlockLenDistPair:
for (uint_fast16_t i = 0; i < _length; i++) {
uint32_t idx;
if OF_UNLIKELY (length == 0) {
_length -= i;
@@ -489,11 +485,11 @@
}
_symbolsLeft--;
_treeIter = _litLenTree;
- _state = STATE_BLOCK_LITLEN;
+ _state = stateBlockLitLen;
goto start;
}
OF_UNREACHABLE
}
@@ -502,11 +498,11 @@
{
if (_stream == nil)
@throw [OFNotOpenException exceptionWithObject: self];
return (_stream.atEndOfStream &&
- _bufferLength - _bufferIndex == 0 && _state == STATE_BLOCK_HEADER);
+ _bufferLength - _bufferIndex == 0 && _state == stateBlockHeader);
}
- (int)fileDescriptorForReading
{
return ((id )_stream)
Index: src/OFList.h
==================================================================
--- src/OFList.h
+++ src/OFList.h
@@ -18,27 +18,65 @@
#import "OFEnumerator.h"
#import "OFSerialization.h"
OF_ASSUME_NONNULL_BEGIN
-typedef struct of_list_object_t of_list_object_t;
+/** @file */
+
+/*
+ * Make clang's -Wdocumentation shut about about using @struct on someting it
+ * thinks is not a struct. Doxygen requires it this way.
+ */
+#ifdef __clang__
+# pragma clang diagnostic push
+# pragma clang diagnostic ignored "-Wdocumentation"
+#endif
/**
- * @struct of_list_object_t OFList.h ObjFW/OFList.h
+ * @struct OFListItem OFList.h ObjFW/OFList.h
+ *
+ * @brief A list item.
+ *
+ * See @ref OFListItemNext, @ref OFListItemPrevious and @ref OFListItemObject.
+ */
+typedef struct _OFListItem *OFListItem;
+#ifdef __clang__
+# pragma clang diagnostic pop
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+/*!
+ * @brief Returns the next list item of the list item.
+ *
+ * @param listItem The list item for which the next list item should be returned
+ * @return The next list item of the list item
+ */
+OFListItem OFListItemNext(OFListItem _Nonnull listItem);
+
+/*!
+ * @brief Returns the previous list item of the list item.
+ *
+ * @param listItem The list item for which the previous list item should be
+ * returned
+ * @return The previous list item of the list item
+ */
+OFListItem OFListItemPrevious(OFListItem _Nonnull listItem);
+
+/*!
+ * @brief Returns the object of the list item.
*
- * @brief A list object.
+ * @warning The returned object is not retained and autoreleased - this is the
+ * caller's responsibility!
*
- * A struct that contains a pointer to the next list object, the previous list
- * object and the object.
+ * @param listItem The list item for which the object should be returned
+ * @return The object of the list item
*/
-struct of_list_object_t {
- /** A pointer to the next list object in the list */
- of_list_object_t *_Nullable next;
- /** A pointer to the previous list object in the list */
- of_list_object_t *_Nullable previous;
- /** The object for the list object */
- id __unsafe_unretained object;
-};
+id OFListItemObject(OFListItem _Nonnull listItem);
+#ifdef __cplusplus
+}
+#endif
/**
* @class OFList OFList.h ObjFW/OFList.h
*
* @brief A class which provides easy to use double-linked lists.
@@ -47,22 +85,21 @@
OFSerialization>
#if !defined(OF_HAVE_GENERICS) && !defined(DOXYGEN)
# define ObjectType id
#endif
{
- of_list_object_t *_Nullable _firstListObject;
- of_list_object_t *_Nullable _lastListObject;
+ OFListItem _Nullable _firstListItem;
+ OFListItem _Nullable _lastListItem;
size_t _count;
- unsigned long _mutations;
+ unsigned long _mutations;
OF_RESERVE_IVARS(OFList, 4)
}
/**
* @brief The first list object of the list.
*/
-@property OF_NULLABLE_PROPERTY (readonly, nonatomic)
- of_list_object_t *firstListObject;
+@property OF_NULLABLE_PROPERTY (readonly, nonatomic) OFListItem firstListItem;
/**
* @brief The first object of the list or `nil`.
*
* @warning The returned object is *not* retained and autoreleased for
@@ -71,12 +108,11 @@
@property OF_NULLABLE_PROPERTY (readonly, nonatomic) ObjectType firstObject;
/**
* @brief The last list object of the list.
*/
-@property OF_NULLABLE_PROPERTY (readonly, nonatomic)
- of_list_object_t *lastListObject;
+@property OF_NULLABLE_PROPERTY (readonly, nonatomic) OFListItem lastListItem;
/**
* @brief The last object of the list or `nil`.
*
* @warning The returned object is *not* retained and autoreleased for
@@ -93,58 +129,58 @@
/**
* @brief Appends an object to the list.
*
* @param object The object to append
- * @return An of_list_object_t, needed to identify the object inside the list.
+ * @return An OFListItem, needed to identify the object inside the list.
* For example, if you want to remove an object from the list, you need
- * its of_list_object_t.
+ * its OFListItem.
*/
-- (of_list_object_t *)appendObject: (ObjectType)object;
+- (OFListItem)appendObject: (ObjectType)object;
/**
* @brief Prepends an object to the list.
*
* @param object The object to prepend
- * @return An of_list_object_t, needed to identify the object inside the list.
+ * @return An OFListItem, needed to identify the object inside the list.
* For example, if you want to remove an object from the list, you need
- * its of_list_object_t.
+ * its OFListItem.
*/
-- (of_list_object_t *)prependObject: (ObjectType)object;
+- (OFListItem)prependObject: (ObjectType)object;
/**
* @brief Inserts an object before another list object.
*
* @param object The object to insert
- * @param listObject The of_list_object_t of the object before which it should
- * be inserted
- * @return An of_list_object_t, needed to identify the object inside the list.
+ * @param listItem The OFListItem of the object before which it should be
+ * inserted
+ * @return An OFListItem, needed to identify the object inside the list.
* For example, if you want to remove an object from the list, you need
- * its of_list_object_t.
+ * its OFListItem.
*/
-- (of_list_object_t *)insertObject: (ObjectType)object
- beforeListObject: (of_list_object_t *)listObject;
+- (OFListItem)insertObject: (ObjectType)object
+ beforeListItem: (OFListItem)listItem;
/**
* @brief Inserts an object after another list object.
*
* @param object The object to insert
- * @param listObject The of_list_object_t of the object after which it should be
+ * @param listItem The OFListItem of the object after which it should be
* inserted
- * @return An of_list_object_t, needed to identify the object inside the list.
+ * @return An OFListItem, needed to identify the object inside the list.
* For example, if you want to remove an object from the list, you need
- * its of_list_object_t.
+ * its OFListItem.
*/
-- (of_list_object_t *)insertObject: (ObjectType)object
- afterListObject: (of_list_object_t *)listObject;
+- (OFListItem)insertObject: (ObjectType)object
+ afterListItem: (OFListItem)listItem;
/**
* @brief Removes the object with the specified list object from the list.
*
- * @param listObject The list object returned by append / prepend
+ * @param listItem The list object returned by append / prepend
*/
-- (void)removeListObject: (of_list_object_t *)listObject;
+- (void)removeListItem: (OFListItem)listItem;
/**
* @brief Checks whether the list contains an object equal to the specified
* object.
*
Index: src/OFList.m
==================================================================
--- src/OFList.m
+++ src/OFList.m
@@ -23,27 +23,49 @@
#import "OFXMLElement.h"
#import "OFArray.h"
#import "OFEnumerationMutationException.h"
#import "OFInvalidArgumentException.h"
+
+struct _OFListItem {
+ struct _OFListItem *previous, *next;
+ id object;
+};
OF_DIRECT_MEMBERS
@interface OFListEnumerator: OFEnumerator
{
OFList *_list;
- of_list_object_t *_Nullable _current;
+ OFListItem _Nullable _current;
unsigned long _mutations;
unsigned long *_Nullable _mutationsPtr;
}
- (instancetype)initWithList: (OFList *)list
mutationsPointer: (unsigned long *)mutationsPtr;
@end
+
+OFListItem
+OFListItemNext(OFListItem listItem)
+{
+ return listItem->next;
+}
+
+OFListItem
+OFListItemPrevious(OFListItem listItem)
+{
+ return listItem->previous;
+}
+
+id
+OFListItemObject(OFListItem listItem)
+{
+ return listItem->object;
+}
@implementation OFList
-@synthesize firstListObject = _firstListObject;
-@synthesize lastListObject = _lastListObject;
+@synthesize firstListItem = _firstListItem, lastListItem = _lastListItem;
+ (instancetype)list
{
return [[[self alloc] init] autorelease];
}
@@ -54,15 +76,15 @@
@try {
void *pool = objc_autoreleasePoolPush();
if (![element.name isEqual: self.className] ||
- ![element.namespace isEqual: OF_SERIALIZATION_NS])
+ ![element.namespace isEqual: OFSerializationNS])
@throw [OFInvalidArgumentException exception];
for (OFXMLElement *child in
- [element elementsForNamespace: OF_SERIALIZATION_NS]) {
+ [element elementsForNamespace: OFSerializationNS]) {
void *pool2 = objc_autoreleasePoolPush();
[self appendObject: child.objectByDeserializing];
objc_autoreleasePoolPop(pool2);
@@ -77,142 +99,135 @@
return self;
}
- (void)dealloc
{
- of_list_object_t *next;
+ OFListItem next;
- for (of_list_object_t *iter = _firstListObject;
- iter != NULL; iter = next) {
+ for (OFListItem iter = _firstListItem; iter != NULL; iter = next) {
[iter->object release];
next = iter->next;
- free(iter);
+ OFFreeMemory(iter);
}
[super dealloc];
}
-- (of_list_object_t *)appendObject: (id)object
-{
- of_list_object_t *listObject;
-
- listObject = of_alloc(1, sizeof(of_list_object_t));
- listObject->object = [object retain];
- listObject->next = NULL;
- listObject->previous = _lastListObject;
-
- if (_lastListObject != NULL)
- _lastListObject->next = listObject;
-
- _lastListObject = listObject;
-
- if (_firstListObject == NULL)
- _firstListObject = listObject;
-
- _count++;
- _mutations++;
-
- return listObject;
-}
-
-- (of_list_object_t *)prependObject: (id)object
-{
- of_list_object_t *listObject;
-
- listObject = of_alloc(1, sizeof(of_list_object_t));
- listObject->object = [object retain];
- listObject->next = _firstListObject;
- listObject->previous = NULL;
-
- if (_firstListObject != NULL)
- _firstListObject->previous = listObject;
-
- _firstListObject = listObject;
- if (_lastListObject == NULL)
- _lastListObject = listObject;
-
- _count++;
- _mutations++;
-
- return listObject;
-}
-
-- (of_list_object_t *)insertObject: (id)object
- beforeListObject: (of_list_object_t *)listObject
-{
- of_list_object_t *newListObject;
-
- newListObject = of_alloc(1, sizeof(of_list_object_t));
- newListObject->object = [object retain];
- newListObject->next = listObject;
- newListObject->previous = listObject->previous;
-
- if (listObject->previous != NULL)
- listObject->previous->next = newListObject;
-
- listObject->previous = newListObject;
-
- if (listObject == _firstListObject)
- _firstListObject = newListObject;
-
- _count++;
- _mutations++;
-
- return newListObject;
-}
-
-- (of_list_object_t *)insertObject: (id)object
- afterListObject: (of_list_object_t *)listObject
-{
- of_list_object_t *newListObject;
-
- newListObject = of_alloc(1, sizeof(of_list_object_t));
- newListObject->object = [object retain];
- newListObject->next = listObject->next;
- newListObject->previous = listObject;
-
- if (listObject->next != NULL)
- listObject->next->previous = newListObject;
-
- listObject->next = newListObject;
-
- if (listObject == _lastListObject)
- _lastListObject = newListObject;
-
- _count++;
- _mutations++;
-
- return newListObject;
-}
-
-- (void)removeListObject: (of_list_object_t *)listObject
-{
- if (listObject->previous != NULL)
- listObject->previous->next = listObject->next;
- if (listObject->next != NULL)
- listObject->next->previous = listObject->previous;
-
- if (_firstListObject == listObject)
- _firstListObject = listObject->next;
- if (_lastListObject == listObject)
- _lastListObject = listObject->previous;
-
- _count--;
- _mutations++;
-
- [listObject->object release];
- free(listObject);
-}
-
-- (id)firstObject
-{
- return (_firstListObject != NULL ? _firstListObject->object : nil);
-}
-
-- (id)lastObject
-{
- return (_lastListObject != NULL ? _lastListObject->object : nil);
+- (OFListItem)appendObject: (id)object
+{
+ OFListItem listItem = OFAllocMemory(1, sizeof(*listItem));
+
+ listItem->object = [object retain];
+ listItem->next = NULL;
+ listItem->previous = _lastListItem;
+
+ if (_lastListItem != NULL)
+ _lastListItem->next = listItem;
+
+ _lastListItem = listItem;
+
+ if (_firstListItem == NULL)
+ _firstListItem = listItem;
+
+ _count++;
+ _mutations++;
+
+ return listItem;
+}
+
+- (OFListItem)prependObject: (id)object
+{
+ OFListItem listItem = OFAllocMemory(1, sizeof(*listItem));
+
+ listItem->object = [object retain];
+ listItem->next = _firstListItem;
+ listItem->previous = NULL;
+
+ if (_firstListItem != NULL)
+ _firstListItem->previous = listItem;
+
+ _firstListItem = listItem;
+ if (_lastListItem == NULL)
+ _lastListItem = listItem;
+
+ _count++;
+ _mutations++;
+
+ return listItem;
+}
+
+- (OFListItem)insertObject: (id)object beforeListItem: (OFListItem)listItem
+{
+ OFListItem newListItem = OFAllocMemory(1, sizeof(*newListItem));
+
+ newListItem->object = [object retain];
+ newListItem->next = listItem;
+ newListItem->previous = listItem->previous;
+
+ if (listItem->previous != NULL)
+ listItem->previous->next = newListItem;
+
+ listItem->previous = newListItem;
+
+ if (listItem == _firstListItem)
+ _firstListItem = newListItem;
+
+ _count++;
+ _mutations++;
+
+ return newListItem;
+}
+
+- (OFListItem)insertObject: (id)object afterListItem: (OFListItem)listItem
+{
+ OFListItem newListItem = OFAllocMemory(1, sizeof(*newListItem));
+
+ newListItem->object = [object retain];
+ newListItem->next = listItem->next;
+ newListItem->previous = listItem;
+
+ if (listItem->next != NULL)
+ listItem->next->previous = newListItem;
+
+ listItem->next = newListItem;
+
+ if (listItem == _lastListItem)
+ _lastListItem = newListItem;
+
+ _count++;
+ _mutations++;
+
+ return newListItem;
+}
+
+- (void)removeListItem: (OFListItem)listItem
+{
+ if (listItem->previous != NULL)
+ listItem->previous->next = listItem->next;
+ if (listItem->next != NULL)
+ listItem->next->previous = listItem->previous;
+
+ if (_firstListItem == listItem)
+ _firstListItem = listItem->next;
+ if (_lastListItem == listItem)
+ _lastListItem = listItem->previous;
+
+ _count--;
+ _mutations++;
+
+ [listItem->object release];
+ OFFreeMemory(listItem);
+}
+
+- (id)firstObject
+{
+ return (_firstListItem != NULL ? _firstListItem->object : nil);
+}
+
+- (id)lastObject
+{
+ return (_lastListItem != NULL ? _lastListItem->object : nil);
}
- (size_t)count
{
return _count;
@@ -219,11 +234,11 @@
}
- (bool)isEqual: (id)object
{
OFList *list;
- of_list_object_t *iter, *iter2;
+ OFListItem iter, iter2;
if (object == self)
return true;
if (![object isKindOfClass: [OFList class]])
@@ -232,11 +247,11 @@
list = object;
if (list.count != _count)
return false;
- for (iter = _firstListObject, iter2 = list.firstListObject;
+ for (iter = _firstListItem, iter2 = list.firstListItem;
iter != NULL && iter2 != NULL;
iter = iter->next, iter2 = iter2->next)
if (![iter->object isEqual: iter2->object])
return false;
@@ -249,12 +264,11 @@
- (bool)containsObject: (id)object
{
if (_count == 0)
return false;
- for (of_list_object_t *iter = _firstListObject;
- iter != NULL; iter = iter->next)
+ for (OFListItem iter = _firstListItem; iter != NULL; iter = iter->next)
if ([iter->object isEqual: object])
return true;
return false;
}
@@ -262,80 +276,74 @@
- (bool)containsObjectIdenticalTo: (id)object
{
if (_count == 0)
return false;
- for (of_list_object_t *iter = _firstListObject;
- iter != NULL; iter = iter->next)
+ for (OFListItem iter = _firstListItem; iter != NULL; iter = iter->next)
if (iter->object == object)
return true;
return false;
}
- (void)removeAllObjects
{
- of_list_object_t *next;
+ OFListItem next;
_mutations++;
- for (of_list_object_t *iter = _firstListObject;
- iter != NULL; iter = next) {
+ for (OFListItem iter = _firstListItem; iter != NULL; iter = next) {
[iter->object release];
next = iter->next;
- free(iter);
+ OFFreeMemory(iter);
}
- _firstListObject = _lastListObject = NULL;
+ _firstListItem = _lastListItem = NULL;
}
- (id)copy
{
OFList *copy = [[[self class] alloc] init];
- of_list_object_t *listObject, *previous;
-
- listObject = NULL;
- previous = NULL;
+ OFListItem listItem = NULL, previous = NULL;
@try {
- for (of_list_object_t *iter = _firstListObject;
+ for (OFListItem iter = _firstListItem;
iter != NULL; iter = iter->next) {
- listObject = of_alloc(1, sizeof(of_list_object_t));
- listObject->object = [iter->object retain];
- listObject->next = NULL;
- listObject->previous = previous;
+ listItem = OFAllocMemory(1, sizeof(*listItem));
+ listItem->object = [iter->object retain];
+ listItem->next = NULL;
+ listItem->previous = previous;
- if (copy->_firstListObject == NULL)
- copy->_firstListObject = listObject;
+ if (copy->_firstListItem == NULL)
+ copy->_firstListItem = listItem;
if (previous != NULL)
- previous->next = listObject;
+ previous->next = listItem;
copy->_count++;
- previous = listObject;
+ previous = listItem;
}
} @catch (id e) {
[copy release];
@throw e;
}
- copy->_lastListObject = listObject;
+ copy->_lastListItem = listItem;
return copy;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- for (of_list_object_t *iter = _firstListObject;
- iter != NULL; iter = iter->next)
- OF_HASH_ADD_HASH(hash, [iter->object hash]);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ for (OFListItem iter = _firstListItem; iter != NULL; iter = iter->next)
+ OFHashAddHash(&hash, [iter->object hash]);
+
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -345,11 +353,11 @@
if (_count == 0)
return @"[]";
ret = [OFMutableString stringWithString: @"[\n"];
- for (of_list_object_t *iter = _firstListObject;
+ for (OFListItem iter = _firstListItem;
iter != NULL; iter = iter->next) {
void *pool = objc_autoreleasePoolPush();
[ret appendString: [iter->object description]];
@@ -368,13 +376,13 @@
- (OFXMLElement *)XMLElementBySerializing
{
OFXMLElement *element =
[OFXMLElement elementWithName: self.className
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
- for (of_list_object_t *iter = _firstListObject;
+ for (OFListItem iter = _firstListItem;
iter != NULL; iter = iter->next) {
void *pool = objc_autoreleasePoolPush();
[element addChild: [iter->object XMLElementBySerializing]];
@@ -382,35 +390,35 @@
}
return element;
}
-- (int)countByEnumeratingWithState: (of_fast_enumeration_state_t *)state
+- (int)countByEnumeratingWithState: (OFFastEnumerationState *)state
objects: (id *)objects
count: (int)count
{
- of_list_object_t *listObject;
+ OFListItem listItem;
- memcpy(&listObject, state->extra, sizeof(listObject));
+ memcpy(&listItem, state->extra, sizeof(listItem));
state->itemsPtr = objects;
state->mutationsPtr = &_mutations;
if (state->state == 0) {
- listObject = _firstListObject;
+ listItem = _firstListItem;
state->state = 1;
}
for (int i = 0; i < count; i++) {
- if (listObject == NULL)
+ if (listItem == NULL)
return i;
- objects[i] = listObject->object;
- listObject = listObject->next;
+ objects[i] = listItem->object;
+ listItem = listItem->next;
}
- memcpy(state->extra, &listObject, sizeof(listObject));
+ memcpy(state->extra, &listItem, sizeof(listItem));
return count;
}
- (OFEnumerator *)objectEnumerator
@@ -426,11 +434,11 @@
mutationsPointer: (unsigned long *)mutationsPtr
{
self = [super init];
_list = [list retain];
- _current = _list.firstListObject;
+ _current = _list.firstListItem;
_mutations = *mutationsPtr;
_mutationsPtr = mutationsPtr;
return self;
}
Index: src/OFLocale.h
==================================================================
--- src/OFLocale.h
+++ src/OFLocale.h
@@ -43,21 +43,21 @@
*/
OF_SUBCLASSING_RESTRICTED
@interface OFLocale: OFObject
{
OFString *_Nullable _language, *_Nullable _territory;
- of_string_encoding_t _encoding;
+ OFStringEncoding _encoding;
OFString *_decimalPoint;
OFMutableArray OF_GENERIC(OFDictionary OF_GENERIC(OFString *, id) *)
*_localizedStrings;
}
#ifdef OF_HAVE_CLASS_PROPERTIES
@property (class, readonly, nullable, nonatomic) OFLocale *currentLocale;
@property (class, readonly, nullable, nonatomic) OFString *language;
@property (class, readonly, nullable, nonatomic) OFString *territory;
-@property (class, readonly, nonatomic) of_string_encoding_t encoding;
+@property (class, readonly, nonatomic) OFStringEncoding encoding;
@property (class, readonly, nullable, nonatomic) OFString *decimalPoint;
#endif
/**
* @brief The language of the locale for messages.
@@ -79,11 +79,11 @@
* This is useful to encode strings correctly for passing them to operating
* system calls.
*
* If the native 8-bit encoding is unknown, UTF-8 is assumed.
*/
-@property (readonly, nonatomic) of_string_encoding_t encoding;
+@property (readonly, nonatomic) OFStringEncoding encoding;
/**
* @brief The decimal point of the system's locale.
*/
@property (readonly, nonatomic) OFString *decimalPoint;
@@ -125,11 +125,11 @@
*
* If the native 8-bit encoding is unknown, UTF-8 is assumed.
*
* @return The native 8-bit string encoding for the locale
*/
-+ (of_string_encoding_t)encoding;
++ (OFStringEncoding)encoding;
/**
* @brief Returns the decimal point of the system's locale.
*
* @return The decimal point of the system's locale
Index: src/OFLocale.m
==================================================================
--- src/OFLocale.m
+++ src/OFLocale.m
@@ -37,18 +37,17 @@
static OFLocale *currentLocale = nil;
static OFDictionary *operatorPrecedences = nil;
#ifndef OF_AMIGAOS
static void
-parseLocale(char *locale, of_string_encoding_t *encoding,
+parseLocale(char *locale, OFStringEncoding *encoding,
OFString **language, OFString **territory)
{
- if ((locale = of_strdup(locale)) == NULL)
- return;
+ locale = OFStrDup(locale);
@try {
- const of_string_encoding_t enc = OF_STRING_ENCODING_ASCII;
+ OFStringEncoding enc = OFStringEncodingASCII;
char *tmp;
/* We don't care for extras behind the @ */
if ((tmp = strrchr(locale, '@')) != NULL)
*tmp = '\0';
@@ -57,11 +56,11 @@
if ((tmp = strrchr(locale, '.')) != NULL) {
*tmp++ = '\0';
@try {
if (encoding != NULL)
- *encoding = of_string_parse_encoding(
+ *encoding = OFStringEncodingParseName(
[OFString stringWithCString: tmp
encoding: enc]);
} @catch (OFInvalidArgumentException *e) {
}
}
@@ -77,11 +76,11 @@
if (language != NULL)
*language = [OFString stringWithCString: locale
encoding: enc];
} @finally {
- free(locale);
+ OFFreeMemory(locale);
}
}
#endif
static bool
@@ -106,13 +105,13 @@
/* Substitute variables and convert to RPN first */
tokens = [OFMutableArray array];
operators = [OFMutableArray array];
for (OFString *token in [condition
componentsSeparatedByString: @" "
- options: OF_STRING_SKIP_EMPTY]) {
+ options: OFStringSkipEmptyComponents]) {
unsigned precedence;
- of_unichar_t c;
+ OFUnichar c;
if ([token isEqual: @"("]) {
[operators addObject: @"("];
continue;
}
@@ -195,20 +194,20 @@
else if ([token isEqual: @"!="])
var = [OFNumber numberWithBool:
![first isEqual: second]];
else if ([token isEqual: @"<"])
var = [OFNumber numberWithBool: [first
- compare: second] == OF_ORDERED_ASCENDING];
+ compare: second] == OFOrderedAscending];
else if ([token isEqual: @"<="])
var = [OFNumber numberWithBool: [first
- compare: second] != OF_ORDERED_DESCENDING];
+ compare: second] != OFOrderedDescending];
else if ([token isEqual: @">"])
var = [OFNumber numberWithBool: [first
- compare: second] == OF_ORDERED_DESCENDING];
+ compare: second] == OFOrderedDescending];
else if ([token isEqual: @">="])
var = [OFNumber numberWithBool: [first
- compare: second] != OF_ORDERED_ASCENDING];
+ compare: second] != OFOrderedAscending];
else if ([token isEqual: @"+"])
var = [OFNumber numberWithDouble:
[first doubleValue] + [second doubleValue]];
else if ([token isEqual: @"%"])
var = [OFNumber numberWithLongLong:
@@ -219,11 +218,11 @@
[first boolValue] && [second boolValue]];
else if ([token isEqual: @"||"])
var = [OFNumber numberWithBool:
[first boolValue] || [second boolValue]];
else
- OF_ENSURE(0);
+ OFEnsure(0);
[stack replaceObjectAtIndex: stackSize - 2
withObject: var];
[stack removeLastObject];
} else if (precedence == 1) {
@@ -236,11 +235,11 @@
else if ([token isEqual: @"is_real"])
var = [OFNumber numberWithBool:
([first doubleValue] !=
[first longLongValue])];
else
- OF_ENSURE(0);
+ OFEnsure(0);
[stack replaceObjectAtIndex: stackSize - 1
withObject: var];
} else
[stack addObject: token];
@@ -349,11 +348,11 @@
+ (OFString *)territory
{
return currentLocale.territory;
}
-+ (of_string_encoding_t)encoding
++ (OFStringEncoding)encoding
{
return currentLocale.encoding;
}
+ (OFString *)decimalPoint
@@ -378,11 +377,11 @@
if (currentLocale != nil)
@throw [OFInitializationFailedException
exceptionWithClass: self.class];
- _encoding = OF_STRING_ENCODING_UTF_8;
+ _encoding = OFStringEncodingUTF8;
_decimalPoint = @".";
_localizedStrings = [[OFMutableArray alloc] init];
if ((locale = setlocale(LC_ALL, "")) != NULL)
_decimalPoint = [[OFString alloc]
@@ -422,21 +421,21 @@
# elif defined(OF_AMIGAOS4)
if (GetVar("Charset", buffer, sizeof(buffer), 0) > 0) {
# else
if (0) {
# endif
- of_string_encoding_t ASCII = OF_STRING_ENCODING_ASCII;
+ OFStringEncoding ASCII = OFStringEncodingASCII;
@try {
- _encoding = of_string_parse_encoding(
+ _encoding = OFStringEncodingForName(
[OFString stringWithCString: buffer
encoding: ASCII]);
} @catch (OFInvalidArgumentException *e) {
- _encoding = OF_STRING_ENCODING_ISO_8859_1;
+ _encoding = OFStringEncodingISO8859_1;
}
} else
- _encoding = OF_STRING_ENCODING_ISO_8859_1;
+ _encoding = OFStringEncodingISO8859_1;
/*
* Get it via localeconv() instead of from the Locale struct,
* to make sure we and printf etc. have the same expectations.
*/
@@ -455,11 +454,11 @@
@try {
uint32_t territory;
size_t length;
territory =
- OF_BSWAP32_IF_LE(locale->loc_CountryCode);
+ OFToBigEndian32(locale->loc_CountryCode);
for (length = 0; length < 4; length++)
if (((char *)&territory)[length] == 0)
break;
Index: src/OFMD5Hash.h
==================================================================
--- src/OFMD5Hash.h
+++ src/OFMD5Hash.h
@@ -26,14 +26,14 @@
*/
OF_SUBCLASSING_RESTRICTED
@interface OFMD5Hash: OFObject
{
OFSecureData *_iVarsData;
- struct of_md5_hash_ivars {
+ struct {
uint32_t state[4];
uint64_t bits;
- union of_md5_hash_buffer {
+ union {
unsigned char bytes[64];
uint32_t words[16];
} buffer;
size_t bufferLength;
} *_iVars;
Index: src/OFMD5Hash.m
==================================================================
--- src/OFMD5Hash.m
+++ src/OFMD5Hash.m
@@ -21,12 +21,12 @@
#import "OFSecureData.h"
#import "OFHashAlreadyCalculatedException.h"
#import "OFOutOfRangeException.h"
-#define DIGEST_SIZE 16
-#define BLOCK_SIZE 64
+static const size_t digestSize = 16;
+static const size_t blockSize = 64;
OF_DIRECT_MEMBERS
@interface OFMD5Hash ()
- (void)of_resetState;
@end
@@ -73,11 +73,11 @@
static OF_INLINE void
byteSwapVectorIfBE(uint32_t *vector, uint_fast8_t length)
{
#ifdef OF_BIG_ENDIAN
for (uint_fast8_t i = 0; i < length; i++)
- vector[i] = OF_BSWAP32(vector[i]);
+ vector[i] = OFByteSwap32(vector[i]);
#endif
}
static void
processBlock(uint32_t *state, uint32_t *buffer)
@@ -90,20 +90,21 @@
new[2] = state[2];
new[3] = state[3];
byteSwapVectorIfBE(buffer, 16);
-#define LOOP_BODY(f) \
- { \
- uint32_t tmp = new[3]; \
- tmp = new[3]; \
- new[0] += f(new[1], new[2], new[3]) + \
- buffer[wordOrder[i]] + table[i]; \
- new[3] = new[2]; \
- new[2] = new[1]; \
- new[1] += OF_ROL(new[0], rotateBits[(i % 4) + (i / 16) * 4]); \
- new[0] = tmp;\
+#define LOOP_BODY(f) \
+ { \
+ uint32_t tmp = new[3]; \
+ tmp = new[3]; \
+ new[0] += f(new[1], new[2], new[3]) + \
+ buffer[wordOrder[i]] + table[i]; \
+ new[3] = new[2]; \
+ new[2] = new[1]; \
+ new[1] += OFRotateLeft(new[0], \
+ rotateBits[(i % 4) + (i / 16) * 4]); \
+ new[0] = tmp; \
}
for (; i < 16; i++)
LOOP_BODY(F)
for (; i < 32; i++)
@@ -125,16 +126,16 @@
@synthesize calculated = _calculated;
@synthesize allowsSwappableMemory = _allowsSwappableMemory;
+ (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
+ (size_t)blockSize
{
- return BLOCK_SIZE;
+ return blockSize;
}
+ (instancetype)hashWithAllowsSwappableMemory: (bool)allowsSwappableMemory
{
return [[[self alloc] initWithAllowsSwappableMemory:
@@ -178,16 +179,16 @@
[super dealloc];
}
- (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
- (size_t)blockSize
{
- return BLOCK_SIZE;
+ return blockSize;
}
- (id)copy
{
OFMD5Hash *copy = [[OFMD5Hash alloc] of_init];
@@ -245,25 +246,25 @@
{
if (_calculated)
return (const unsigned char *)_iVars->state;
_iVars->buffer.bytes[_iVars->bufferLength] = 0x80;
- of_explicit_memset(_iVars->buffer.bytes + _iVars->bufferLength + 1, 0,
+ OFZeroMemory(_iVars->buffer.bytes + _iVars->bufferLength + 1,
64 - _iVars->bufferLength - 1);
if (_iVars->bufferLength >= 56) {
processBlock(_iVars->state, _iVars->buffer.words);
- of_explicit_memset(_iVars->buffer.bytes, 0, 64);
+ OFZeroMemory(_iVars->buffer.bytes, 64);
}
_iVars->buffer.words[14] =
- OF_BSWAP32_IF_BE((uint32_t)(_iVars->bits & 0xFFFFFFFF));
+ OFToLittleEndian32((uint32_t)(_iVars->bits & 0xFFFFFFFF));
_iVars->buffer.words[15] =
- OF_BSWAP32_IF_BE((uint32_t)(_iVars->bits >> 32));
+ OFToLittleEndian32((uint32_t)(_iVars->bits >> 32));
processBlock(_iVars->state, _iVars->buffer.words);
- of_explicit_memset(&_iVars->buffer, 0, sizeof(_iVars->buffer));
+ OFZeroMemory(&_iVars->buffer, sizeof(_iVars->buffer));
byteSwapVectorIfBE(_iVars->state, 4);
_calculated = true;
return (const unsigned char *)_iVars->state;
}
@@ -270,10 +271,10 @@
- (void)reset
{
[self of_resetState];
_iVars->bits = 0;
- of_explicit_memset(&_iVars->buffer, 0, sizeof(_iVars->buffer));
+ OFZeroMemory(&_iVars->buffer, sizeof(_iVars->buffer));
_iVars->bufferLength = 0;
_calculated = false;
}
@end
Index: src/OFMapTable.h
==================================================================
--- src/OFMapTable.h
+++ src/OFMapTable.h
@@ -19,26 +19,25 @@
OF_ASSUME_NONNULL_BEGIN
/** @file */
/**
- * @struct of_map_table_functions_t OFMapTable.h ObjFW/OFMapTable.h
+ * @struct OFMapTableFunctions OFMapTable.h ObjFW/OFMapTable.h
*
* @brief A struct describing the functions to be used by the map table.
*/
-struct of_map_table_functions_t {
+typedef struct {
/** The function to retain keys / objects */
void *_Nullable (*_Nullable retain)(void *_Nullable object);
/** The function to release keys / objects */
void (*_Nullable release)(void *_Nullable object);
/** The function to hash keys */
unsigned long (*_Nullable hash)(void *_Nullable object);
/** The function to compare keys / objects */
bool (*_Nullable equal)(void *_Nullable object1,
void *_Nullable object2);
-};
-typedef struct of_map_table_functions_t of_map_table_functions_t;
+} OFMapTableFunctions;
#ifdef OF_HAVE_BLOCKS
/**
* @brief A block for enumerating an OFMapTable.
*
@@ -45,21 +44,21 @@
* @param key The current key
* @param object The current object
* @param stop A pointer to a variable that can be set to true to stop the
* enumeration
*/
-typedef void (^of_map_table_enumeration_block_t)(void *_Nullable key,
+typedef void (^OFMapTableEnumerationBlock)(void *_Nullable key,
void *_Nullable object, bool *stop);
/**
* @brief A block for replacing objects in an OFMapTable.
*
* @param key The key of the object to replace
* @param object The object to replace
* @return The object to replace the object with
*/
-typedef void *_Nullable (^of_map_table_replace_block_t)(void *_Nullable key,
+typedef void *_Nullable (^OFMapTableReplaceBlock)(void *_Nullable key,
void *_Nullable object);
#endif
@class OFMapTableEnumerator;
@@ -70,26 +69,26 @@
* and objects should be retained, released, compared and hashed.
*/
OF_SUBCLASSING_RESTRICTED
@interface OFMapTable: OFObject
{
- of_map_table_functions_t _keyFunctions, _objectFunctions;
- struct of_map_table_bucket *_Nonnull *_Nullable _buckets;
+ OFMapTableFunctions _keyFunctions, _objectFunctions;
+ struct OFMapTableBucket *_Nonnull *_Nullable _buckets;
unsigned long _count, _capacity;
unsigned char _rotate;
unsigned long _mutations;
}
/**
* @brief The key functions used by the map table.
*/
-@property (readonly, nonatomic) of_map_table_functions_t keyFunctions;
+@property (readonly, nonatomic) OFMapTableFunctions keyFunctions;
/**
* @brief The object functions used by the map table.
*/
-@property (readonly, nonatomic) of_map_table_functions_t objectFunctions;
+@property (readonly, nonatomic) OFMapTableFunctions objectFunctions;
/**
* @brief The number of objects in the map table.
*/
@property (readonly, nonatomic) size_t count;
@@ -99,13 +98,12 @@
*
* @param keyFunctions A structure of functions for handling keys
* @param objectFunctions A structure of functions for handling objects
* @return A new autoreleased OFMapTable
*/
-+ (instancetype)mapTableWithKeyFunctions: (of_map_table_functions_t)keyFunctions
- objectFunctions: (of_map_table_functions_t)
- objectFunctions;
++ (instancetype)mapTableWithKeyFunctions: (OFMapTableFunctions)keyFunctions
+ objectFunctions: (OFMapTableFunctions)objectFunctions;
/**
* @brief Creates a new OFMapTable with the specified key functions, object
* functions and capacity.
*
@@ -113,13 +111,12 @@
* @param objectFunctions A structure of functions for handling objects
* @param capacity A hint about the count of elements expected to be in the map
* table
* @return A new autoreleased OFMapTable
*/
-+ (instancetype)mapTableWithKeyFunctions: (of_map_table_functions_t)keyFunctions
- objectFunctions: (of_map_table_functions_t)
- objectFunctions
++ (instancetype)mapTableWithKeyFunctions: (OFMapTableFunctions)keyFunctions
+ objectFunctions: (OFMapTableFunctions)objectFunctions
capacity: (size_t)capacity;
- (instancetype)init OF_UNAVAILABLE;
/**
@@ -128,12 +125,12 @@
*
* @param keyFunctions A structure of functions for handling keys
* @param objectFunctions A structure of functions for handling objects
* @return An initialized OFMapTable
*/
-- (instancetype)initWithKeyFunctions: (of_map_table_functions_t)keyFunctions
- objectFunctions: (of_map_table_functions_t)objectFunctions;
+- (instancetype)initWithKeyFunctions: (OFMapTableFunctions)keyFunctions
+ objectFunctions: (OFMapTableFunctions)objectFunctions;
/**
* @brief Initializes an already allocated OFMapTable with the specified key
* functions, object functions and capacity.
*
@@ -141,12 +138,12 @@
* @param objectFunctions A structure of functions for handling objects
* @param capacity A hint about the count of elements expected to be in the map
* table
* @return An initialized OFMapTable
*/
-- (instancetype)initWithKeyFunctions: (of_map_table_functions_t)keyFunctions
- objectFunctions: (of_map_table_functions_t)objectFunctions
+- (instancetype)initWithKeyFunctions: (OFMapTableFunctions)keyFunctions
+ objectFunctions: (OFMapTableFunctions)objectFunctions
capacity: (size_t)capacity
OF_DESIGNATED_INITIALIZER;
/**
* @brief Returns the object for the given key or NULL if the key was not found.
@@ -215,19 +212,18 @@
/**
* @brief Executes a block for each key / object pair.
*
* @param block The block to execute for each key / object pair.
*/
-- (void)enumerateKeysAndObjectsUsingBlock:
- (of_map_table_enumeration_block_t)block;
+- (void)enumerateKeysAndObjectsUsingBlock: (OFMapTableEnumerationBlock)block;
/**
* @brief Replaces each object with the object returned by the block.
*
* @param block The block which returns a new object for each object
*/
-- (void)replaceObjectsUsingBlock: (of_map_table_replace_block_t)block;
+- (void)replaceObjectsUsingBlock: (OFMapTableReplaceBlock)block;
#endif
@end
/**
* @class OFMapTableEnumerator OFMapTable.h ObjFW/OFMapTable.h
@@ -236,11 +232,11 @@
* keys or objects.
*/
@interface OFMapTableEnumerator: OFObject
{
OFMapTable *_mapTable;
- struct of_map_table_bucket *_Nonnull *_Nullable _buckets;
+ struct OFMapTableBucket *_Nonnull *_Nullable _buckets;
unsigned long _capacity, _mutations, *_Nullable _mutationsPtr;
unsigned long _position;
}
- (instancetype)init OF_UNAVAILABLE;
Index: src/OFMapTable.m
==================================================================
--- src/OFMapTable.m
+++ src/OFMapTable.m
@@ -26,17 +26,19 @@
#import "OFEnumerationMutationException.h"
#import "OFInvalidArgumentException.h"
#import "OFOutOfRangeException.h"
-#define MIN_CAPACITY 16
+extern unsigned long OFHashSeed;
-struct of_map_table_bucket {
+static const unsigned long minCapacity = 16;
+
+struct OFMapTableBucket {
void *key, *object;
unsigned long hash;
};
-static struct of_map_table_bucket deleted = { 0 };
+static struct OFMapTableBucket deletedBucket = { 0 };
static void *
defaultRetain(void *object)
{
return object;
@@ -60,11 +62,11 @@
}
OF_DIRECT_MEMBERS
@interface OFMapTableEnumerator ()
- (instancetype)of_initWithMapTable: (OFMapTable *)mapTable
- buckets: (struct of_map_table_bucket **)buckets
+ buckets: (struct OFMapTableBucket **)buckets
capacity: (unsigned long)capacity
mutationsPointer: (unsigned long *)mutationsPtr
OF_METHOD_FAMILY(init);
@end
@@ -75,22 +77,20 @@
@end
@implementation OFMapTable
@synthesize keyFunctions = _keyFunctions, objectFunctions = _objectFunctions;
-+ (instancetype)mapTableWithKeyFunctions: (of_map_table_functions_t)keyFunctions
- objectFunctions: (of_map_table_functions_t)
- objectFunctions
++ (instancetype)mapTableWithKeyFunctions: (OFMapTableFunctions)keyFunctions
+ objectFunctions: (OFMapTableFunctions)objectFunctions
{
return [[[self alloc]
initWithKeyFunctions: keyFunctions
objectFunctions: objectFunctions] autorelease];
}
-+ (instancetype)mapTableWithKeyFunctions: (of_map_table_functions_t)keyFunctions
- objectFunctions: (of_map_table_functions_t)
- objectFunctions
++ (instancetype)mapTableWithKeyFunctions: (OFMapTableFunctions)keyFunctions
+ objectFunctions: (OFMapTableFunctions)objectFunctions
capacity: (size_t)capacity
{
return [[[self alloc]
initWithKeyFunctions: keyFunctions
objectFunctions: objectFunctions
@@ -100,20 +100,20 @@
- (instancetype)init
{
OF_INVALID_INIT_METHOD
}
-- (instancetype)initWithKeyFunctions: (of_map_table_functions_t)keyFunctions
- objectFunctions: (of_map_table_functions_t)objectFunctions
+- (instancetype)initWithKeyFunctions: (OFMapTableFunctions)keyFunctions
+ objectFunctions: (OFMapTableFunctions)objectFunctions
{
return [self initWithKeyFunctions: keyFunctions
objectFunctions: objectFunctions
capacity: 0];
}
-- (instancetype)initWithKeyFunctions: (of_map_table_functions_t)keyFunctions
- objectFunctions: (of_map_table_functions_t)objectFunctions
+- (instancetype)initWithKeyFunctions: (OFMapTableFunctions)keyFunctions
+ objectFunctions: (OFMapTableFunctions)objectFunctions
capacity: (size_t)capacity
{
self = [super init];
@try {
@@ -149,17 +149,17 @@
if (capacity * 8 / _capacity >= 6)
if (_capacity <= ULONG_MAX / 2)
_capacity *= 2;
- if (_capacity < MIN_CAPACITY)
- _capacity = MIN_CAPACITY;
+ if (_capacity < minCapacity)
+ _capacity = minCapacity;
- _buckets = of_alloc_zeroed(_capacity, sizeof(*_buckets));
+ _buckets = OFAllocZeroedMemory(_capacity, sizeof(*_buckets));
- if (of_hash_seed != 0)
- _rotate = of_random16() & 31;
+ if (OFHashSeed != 0)
+ _rotate = OFRandom16() & 31;
} @catch (id e) {
[self release];
@throw e;
}
@@ -167,28 +167,28 @@
}
- (void)dealloc
{
for (unsigned long i = 0; i < _capacity; i++) {
- if (_buckets[i] != NULL && _buckets[i] != &deleted) {
+ if (_buckets[i] != NULL && _buckets[i] != &deletedBucket) {
_keyFunctions.release(_buckets[i]->key);
_objectFunctions.release(_buckets[i]->object);
- free(_buckets[i]);
+ OFFreeMemory(_buckets[i]);
}
}
- free(_buckets);
+ OFFreeMemory(_buckets);
[super dealloc];
}
static void
resizeForCount(OFMapTable *self, unsigned long count)
{
unsigned long fullness, capacity;
- struct of_map_table_bucket **buckets;
+ struct OFMapTableBucket **buckets;
if (count > ULONG_MAX / sizeof(*self->_buckets) ||
count > ULONG_MAX / 8)
@throw [OFOutOfRangeException exception];
@@ -207,18 +207,18 @@
/*
* Don't downsize if we have an initial capacity or if we would fall
* below the minimum capacity.
*/
if ((capacity < self->_capacity && count > self->_count) ||
- capacity < MIN_CAPACITY)
+ capacity < minCapacity)
return;
- buckets = of_alloc_zeroed(capacity, sizeof(*buckets));
+ buckets = OFAllocZeroedMemory(capacity, sizeof(*buckets));
for (unsigned long i = 0; i < self->_capacity; i++) {
if (self->_buckets[i] != NULL &&
- self->_buckets[i] != &deleted) {
+ self->_buckets[i] != &deletedBucket) {
unsigned long j, last;
last = capacity;
for (j = self->_buckets[i]->hash & (capacity - 1);
@@ -237,11 +237,11 @@
buckets[j] = self->_buckets[i];
}
}
- free(self->_buckets);
+ OFFreeMemory(self->_buckets);
self->_buckets = buckets;
self->_capacity = capacity;
}
static void
@@ -252,16 +252,16 @@
void *old;
if (key == NULL || object == NULL)
@throw [OFInvalidArgumentException exception];
- hash = OF_ROL(hash, self->_rotate);
+ hash = OFRotateLeft(hash, self->_rotate);
last = self->_capacity;
for (i = hash & (self->_capacity - 1);
i < last && self->_buckets[i] != NULL; i++) {
- if (self->_buckets[i] == &deleted)
+ if (self->_buckets[i] == &deletedBucket)
continue;
if (self->_keyFunctions.equal(self->_buckets[i]->key, key))
break;
}
@@ -269,11 +269,11 @@
/* In case the last bucket is already used */
if (i >= last) {
last = hash & (self->_capacity - 1);
for (i = 0; i < last && self->_buckets[i] != NULL; i++) {
- if (self->_buckets[i] == &deleted)
+ if (self->_buckets[i] == &deletedBucket)
continue;
if (self->_keyFunctions.equal(
self->_buckets[i]->key, key))
break;
@@ -280,48 +280,48 @@
}
}
/* Key not in map table */
if (i >= last || self->_buckets[i] == NULL ||
- self->_buckets[i] == &deleted ||
+ self->_buckets[i] == &deletedBucket ||
!self->_keyFunctions.equal(self->_buckets[i]->key, key)) {
- struct of_map_table_bucket *bucket;
+ struct OFMapTableBucket *bucket;
resizeForCount(self, self->_count + 1);
self->_mutations++;
last = self->_capacity;
for (i = hash & (self->_capacity - 1); i < last &&
- self->_buckets[i] != NULL && self->_buckets[i] != &deleted;
- i++);
+ self->_buckets[i] != NULL &&
+ self->_buckets[i] != &deletedBucket; i++);
/* In case the last bucket is already used */
if (i >= last) {
last = hash & (self->_capacity - 1);
for (i = 0; i < last && self->_buckets[i] != NULL &&
- self->_buckets[i] != &deleted; i++);
+ self->_buckets[i] != &deletedBucket; i++);
}
if (i >= last)
@throw [OFOutOfRangeException exception];
- bucket = of_alloc(1, sizeof(*bucket));
+ bucket = OFAllocMemory(1, sizeof(*bucket));
@try {
bucket->key = self->_keyFunctions.retain(key);
} @catch (id e) {
- free(bucket);
+ OFFreeMemory(bucket);
@throw e;
}
@try {
bucket->object = self->_objectFunctions.retain(object);
} @catch (id e) {
self->_keyFunctions.release(bucket->key);
- free(bucket);
+ OFFreeMemory(bucket);
@throw e;
}
bucket->hash = hash;
@@ -352,11 +352,11 @@
mapTable->_keyFunctions.equal != _keyFunctions.equal ||
mapTable->_objectFunctions.equal != _objectFunctions.equal)
return false;
for (unsigned long i = 0; i < _capacity; i++) {
- if (_buckets[i] != NULL && _buckets[i] != &deleted) {
+ if (_buckets[i] != NULL && _buckets[i] != &deletedBucket) {
void *objectIter =
[mapTable objectForKey: _buckets[i]->key];
if (!_objectFunctions.equal(objectIter,
_buckets[i]->object))
@@ -370,12 +370,12 @@
- (unsigned long)hash
{
unsigned long hash = 0;
for (unsigned long i = 0; i < _capacity; i++) {
- if (_buckets[i] != NULL && _buckets[i] != &deleted) {
- hash ^= OF_ROR(_buckets[i]->hash, _rotate);
+ if (_buckets[i] != NULL && _buckets[i] != &deletedBucket) {
+ hash ^= OFRotateRight(_buckets[i]->hash, _rotate);
hash ^= _objectFunctions.hash(_buckets[i]->object);
}
}
return hash;
@@ -388,14 +388,15 @@
objectFunctions: _objectFunctions
capacity: _capacity];
@try {
for (unsigned long i = 0; i < _capacity; i++)
- if (_buckets[i] != NULL && _buckets[i] != &deleted)
+ if (_buckets[i] != NULL &&
+ _buckets[i] != &deletedBucket)
setObject(copy, _buckets[i]->key,
_buckets[i]->object,
- OF_ROR(_buckets[i]->hash, _rotate));
+ OFRotateRight(_buckets[i]->hash, _rotate));
} @catch (id e) {
[copy release];
@throw e;
}
@@ -412,15 +413,15 @@
unsigned long i, hash, last;
if (key == NULL)
@throw [OFInvalidArgumentException exception];
- hash = OF_ROL(_keyFunctions.hash(key), _rotate);
+ hash = OFRotateLeft(_keyFunctions.hash(key), _rotate);
last = _capacity;
for (i = hash & (_capacity - 1); i < last && _buckets[i] != NULL; i++) {
- if (_buckets[i] == &deleted)
+ if (_buckets[i] == &deletedBucket)
continue;
if (_keyFunctions.equal(_buckets[i]->key, key))
return _buckets[i]->object;
}
@@ -430,11 +431,11 @@
/* In case the last bucket is already used */
last = hash & (_capacity - 1);
for (i = 0; i < last && _buckets[i] != NULL; i++) {
- if (_buckets[i] == &deleted)
+ if (_buckets[i] == &deletedBucket)
continue;
if (_keyFunctions.equal(_buckets[i]->key, key))
return _buckets[i]->object;
}
@@ -452,25 +453,25 @@
unsigned long i, hash, last;
if (key == NULL)
@throw [OFInvalidArgumentException exception];
- hash = OF_ROL(_keyFunctions.hash(key), _rotate);
+ hash = OFRotateLeft(_keyFunctions.hash(key), _rotate);
last = _capacity;
for (i = hash & (_capacity - 1); i < last && _buckets[i] != NULL; i++) {
- if (_buckets[i] == &deleted)
+ if (_buckets[i] == &deletedBucket)
continue;
if (_keyFunctions.equal(_buckets[i]->key, key)) {
_mutations++;
_keyFunctions.release(_buckets[i]->key);
_objectFunctions.release(_buckets[i]->object);
- free(_buckets[i]);
- _buckets[i] = &deleted;
+ OFFreeMemory(_buckets[i]);
+ _buckets[i] = &deletedBucket;
_count--;
resizeForCount(self, _count);
return;
@@ -482,19 +483,19 @@
/* In case the last bucket is already used */
last = hash & (_capacity - 1);
for (i = 0; i < last && _buckets[i] != NULL; i++) {
- if (_buckets[i] == &deleted)
+ if (_buckets[i] == &deletedBucket)
continue;
if (_keyFunctions.equal(_buckets[i]->key, key)) {
_keyFunctions.release(_buckets[i]->key);
_objectFunctions.release(_buckets[i]->object);
- free(_buckets[i]);
- _buckets[i] = &deleted;
+ OFFreeMemory(_buckets[i]);
+ _buckets[i] = &deletedBucket;
_count--;
_mutations++;
resizeForCount(self, _count);
@@ -505,42 +506,42 @@
- (void)removeAllObjects
{
for (unsigned long i = 0; i < _capacity; i++) {
if (_buckets[i] != NULL) {
- if (_buckets[i] == &deleted) {
+ if (_buckets[i] == &deletedBucket) {
_buckets[i] = NULL;
continue;
}
_keyFunctions.release(_buckets[i]->key);
_objectFunctions.release(_buckets[i]->object);
- free(_buckets[i]);
+ OFFreeMemory(_buckets[i]);
_buckets[i] = NULL;
}
}
_count = 0;
- _capacity = MIN_CAPACITY;
- _buckets = of_realloc(_buckets, _capacity, sizeof(*_buckets));
+ _capacity = minCapacity;
+ _buckets = OFResizeMemory(_buckets, _capacity, sizeof(*_buckets));
/*
* Get a new random value for _rotate, so that it is not less secure
* than creating a new hash map.
*/
- if (of_hash_seed != 0)
- _rotate = of_random16() & 31;
+ if (OFHashSeed != 0)
+ _rotate = OFRandom16() & 31;
}
- (bool)containsObject: (void *)object
{
if (object == NULL || _count == 0)
return false;
for (unsigned long i = 0; i < _capacity; i++)
- if (_buckets[i] != NULL && _buckets[i] != &deleted)
+ if (_buckets[i] != NULL && _buckets[i] != &deletedBucket)
if (_objectFunctions.equal(_buckets[i]->object, object))
return true;
return false;
}
@@ -549,11 +550,11 @@
{
if (object == NULL || _count == 0)
return false;
for (unsigned long i = 0; i < _capacity; i++)
- if (_buckets[i] != NULL && _buckets[i] != &deleted)
+ if (_buckets[i] != NULL && _buckets[i] != &deletedBucket)
if (_buckets[i]->object == object)
return true;
return false;
}
@@ -574,20 +575,20 @@
buckets: _buckets
capacity: _capacity
mutationsPointer: &_mutations] autorelease];
}
-- (int)countByEnumeratingWithState: (of_fast_enumeration_state_t *)state
+- (int)countByEnumeratingWithState: (OFFastEnumerationState *)state
objects: (id *)objects
count: (int)count
{
unsigned long j = state->state;
int i;
for (i = 0; i < count; i++) {
for (; j < _capacity && (_buckets[j] == NULL ||
- _buckets[j] == &deleted); j++);
+ _buckets[j] == &deletedBucket); j++);
if (j < _capacity) {
objects[i] = _buckets[j]->key;
j++;
} else
@@ -600,36 +601,35 @@
return i;
}
#ifdef OF_HAVE_BLOCKS
-- (void)enumerateKeysAndObjectsUsingBlock:
- (of_map_table_enumeration_block_t)block
+- (void)enumerateKeysAndObjectsUsingBlock: (OFMapTableEnumerationBlock)block
{
bool stop = false;
unsigned long mutations = _mutations;
for (size_t i = 0; i < _capacity && !stop; i++) {
if (_mutations != mutations)
@throw [OFEnumerationMutationException
exceptionWithObject: self];
- if (_buckets[i] != NULL && _buckets[i] != &deleted)
+ if (_buckets[i] != NULL && _buckets[i] != &deletedBucket)
block(_buckets[i]->key, _buckets[i]->object, &stop);
}
}
-- (void)replaceObjectsUsingBlock: (of_map_table_replace_block_t)block
+- (void)replaceObjectsUsingBlock: (OFMapTableReplaceBlock)block
{
unsigned long mutations = _mutations;
for (size_t i = 0; i < _capacity; i++) {
if (_mutations != mutations)
@throw [OFEnumerationMutationException
exceptionWithObject: self];
- if (_buckets[i] != NULL && _buckets[i] != &deleted) {
+ if (_buckets[i] != NULL && _buckets[i] != &deletedBucket) {
void *new;
new = block(_buckets[i]->key, _buckets[i]->object);
if (new == NULL)
@throw [OFInvalidArgumentException exception];
@@ -650,11 +650,11 @@
{
OF_INVALID_INIT_METHOD
}
- (instancetype)of_initWithMapTable: (OFMapTable *)mapTable
- buckets: (struct of_map_table_bucket **)buckets
+ buckets: (struct OFMapTableBucket **)buckets
capacity: (unsigned long)capacity
mutationsPointer: (unsigned long *)mutationsPtr
{
self = [super init];
@@ -686,11 +686,11 @@
if (*_mutationsPtr != _mutations)
@throw [OFEnumerationMutationException
exceptionWithObject: _mapTable];
for (; _position < _capacity && (_buckets[_position] == NULL ||
- _buckets[_position] == &deleted); _position++);
+ _buckets[_position] == &deletedBucket); _position++);
if (_position < _capacity)
return &_buckets[_position++]->key;
else
return NULL;
@@ -703,11 +703,11 @@
if (*_mutationsPtr != _mutations)
@throw [OFEnumerationMutationException
exceptionWithObject: _mapTable];
for (; _position < _capacity && (_buckets[_position] == NULL ||
- _buckets[_position] == &deleted); _position++);
+ _buckets[_position] == &deletedBucket); _position++);
if (_position < _capacity)
return &_buckets[_position++]->object;
else
return NULL;
Index: src/OFMapTableDictionary.m
==================================================================
--- src/OFMapTableDictionary.m
+++ src/OFMapTableDictionary.m
@@ -57,17 +57,17 @@
equal(void *object1, void *object2)
{
return [(id)object1 isEqual: (id)object2];
}
-static const of_map_table_functions_t keyFunctions = {
+static const OFMapTableFunctions keyFunctions = {
.retain = copy,
.release = release,
.hash = hash,
.equal = equal
};
-static const of_map_table_functions_t objectFunctions = {
+static const OFMapTableFunctions objectFunctions = {
.retain = retain,
.release = release,
.hash = hash,
.equal = equal
};
@@ -241,13 +241,13 @@
OFArray *keys, *objects;
OFEnumerator *keyEnumerator, *objectEnumerator;
OFXMLElement *keyElement, *objectElement;
keys = [element elementsForName: @"key"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
objects = [element elementsForName: @"object"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
if (keys.count != objects.count)
@throw [OFInvalidFormatException exception];
_mapTable = [[OFMapTable alloc]
@@ -261,13 +261,13 @@
(objectElement = [objectEnumerator nextObject]) != nil) {
void *pool2 = objc_autoreleasePoolPush();
OFXMLElement *key, *object;
key = [keyElement elementsForNamespace:
- OF_SERIALIZATION_NS].firstObject;
+ OFSerializationNS].firstObject;
object = [objectElement elementsForNamespace:
- OF_SERIALIZATION_NS].firstObject;
+ OFSerializationNS].firstObject;
if (key == nil || object == nil)
@throw [OFInvalidFormatException exception];
[_mapTable setObject: object.objectByDeserializing
@@ -333,11 +333,11 @@
OFArray *ret;
id *keys;
size_t count;
count = _mapTable.count;
- keys = of_alloc(count, sizeof(*keys));
+ keys = OFAllocMemory(count, sizeof(*keys));
@try {
void *pool = objc_autoreleasePoolPush();
OFMapTableEnumerator *enumerator;
void **keyPtr;
@@ -353,11 +353,11 @@
objc_autoreleasePoolPop(pool);
ret = [OFArray arrayWithObjects: keys count: count];
} @finally {
- free(keys);
+ OFFreeMemory(keys);
}
return ret;
}
@@ -366,11 +366,11 @@
OFArray *ret;
id *objects;
size_t count;
count = _mapTable.count;
- objects = of_alloc(count, sizeof(*objects));
+ objects = OFAllocMemory(count, sizeof(*objects));
@try {
void *pool = objc_autoreleasePoolPush();
OFMapTableEnumerator *enumerator;
void **objectPtr;
@@ -386,11 +386,11 @@
objc_autoreleasePoolPop(pool);
ret = [OFArray arrayWithObjects: objects count: count];
} @finally {
- free(objects);
+ OFFreeMemory(objects);
}
return ret;
}
@@ -406,22 +406,21 @@
return [[[OFMapTableEnumeratorWrapper alloc]
initWithEnumerator: [_mapTable objectEnumerator]
object: self] autorelease];
}
-- (int)countByEnumeratingWithState: (of_fast_enumeration_state_t *)state
+- (int)countByEnumeratingWithState: (OFFastEnumerationState *)state
objects: (id *)objects
count: (int)count
{
return [_mapTable countByEnumeratingWithState: state
objects: objects
count: count];
}
#ifdef OF_HAVE_BLOCKS
-- (void)enumerateKeysAndObjectsUsingBlock:
- (of_dictionary_enumeration_block_t)block
+- (void)enumerateKeysAndObjectsUsingBlock: (OFDictionaryEnumerationBlock)block
{
@try {
[_mapTable enumerateKeysAndObjectsUsingBlock:
^ (void *key, void *object, bool *stop) {
block(key, object, stop);
Index: src/OFMapTableSet.m
==================================================================
--- src/OFMapTableSet.m
+++ src/OFMapTableSet.m
@@ -49,17 +49,17 @@
equal(void *object1, void *object2)
{
return [(id)object1 isEqual: (id)object2];
}
-static const of_map_table_functions_t keyFunctions = {
+static const OFMapTableFunctions keyFunctions = {
.retain = retain,
.release = release,
.hash = hash,
.equal = equal
};
-static const of_map_table_functions_t objectFunctions = { NULL };
+static const OFMapTableFunctions objectFunctions = { NULL };
@implementation OFMapTableSet
- (instancetype)init
{
return [self initWithCapacity: 0];
@@ -188,15 +188,15 @@
@try {
void *pool = objc_autoreleasePoolPush();
if ((![element.name isEqual: @"OFSet"] &&
![element.name isEqual: @"OFMutableSet"]) ||
- ![element.namespace isEqual: OF_SERIALIZATION_NS])
+ ![element.namespace isEqual: OFSerializationNS])
@throw [OFInvalidArgumentException exception];
for (OFXMLElement *child in
- [element elementsForNamespace: OF_SERIALIZATION_NS]) {
+ [element elementsForNamespace: OFSerializationNS]) {
void *pool2 = objc_autoreleasePoolPush();
[_mapTable setObject: (void *)1
forKey: [child objectByDeserializing]];
@@ -274,21 +274,21 @@
return [[[OFMapTableEnumeratorWrapper alloc]
initWithEnumerator: [_mapTable keyEnumerator]
object: self] autorelease];
}
-- (int)countByEnumeratingWithState: (of_fast_enumeration_state_t *)state
+- (int)countByEnumeratingWithState: (OFFastEnumerationState *)state
objects: (id *)objects
count: (int)count
{
return [_mapTable countByEnumeratingWithState: state
objects: objects
count: count];
}
#ifdef OF_HAVE_BLOCKS
-- (void)enumerateObjectsUsingBlock: (of_set_enumeration_block_t)block
+- (void)enumerateObjectsUsingBlock: (OFSetEnumerationBlock)block
{
@try {
[_mapTable enumerateKeysAndObjectsUsingBlock:
^ (void *key, void *object, bool *stop) {
block(key, stop);
Index: src/OFMessagePackExtension.m
==================================================================
--- src/OFMessagePackExtension.m
+++ src/OFMessagePackExtension.m
@@ -118,11 +118,11 @@
ret = [OFMutableData dataWithCapacity: count + 4];
prefix = 0xC8;
[ret addItem: &prefix];
- length = OF_BSWAP16_IF_LE((uint16_t)count);
+ length = OFToBigEndian16((uint16_t)count);
[ret addItems: &length count: 2];
[ret addItem: &_type];
} else {
uint32_t length;
@@ -130,11 +130,11 @@
ret = [OFMutableData dataWithCapacity: count + 6];
prefix = 0xC9;
[ret addItem: &prefix];
- length = OF_BSWAP32_IF_LE((uint32_t)count);
+ length = OFToBigEndian32((uint32_t)count);
[ret addItems: &length count: 4];
[ret addItem: &_type];
}
@@ -168,22 +168,22 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD(hash, (uint8_t)_type);
- OF_HASH_ADD_HASH(hash, _data.hash);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAdd(&hash, (uint8_t)_type);
+ OFHashAddHash(&hash, _data.hash);
+
+ OFHashFinalize(&hash);
return hash;
}
- (id)copy
{
return [self retain];
}
@end
Index: src/OFMethodSignature.h
==================================================================
--- src/OFMethodSignature.h
+++ src/OFMethodSignature.h
@@ -92,19 +92,19 @@
* @brief Returns the size for the specified type encoding.
*
* @param type The type encoding to return the size for
* @return The size for the specified type encoding
*/
-extern size_t of_sizeof_type_encoding(const char *type);
+extern size_t OFSizeOfTypeEncoding(const char *type);
/**
* @brief Returns the alignment for the specified type encoding.
*
* @param type The type encoding to return the alignment for
* @return The alignment for the specified type encoding
*/
-extern size_t of_alignof_type_encoding(const char *type);
+extern size_t OFAlignmentOfTypeEncoding(const char *type);
#ifdef __cplusplus
}
#endif
OF_ASSUME_NONNULL_END
Index: src/OFMethodSignature.m
==================================================================
--- src/OFMethodSignature.m
+++ src/OFMethodSignature.m
@@ -25,43 +25,44 @@
#import "OFInvalidFormatException.h"
#import "OFOutOfRangeException.h"
#import "macros.h"
-static size_t alignofEncoding(const char **type, size_t *length, bool inStruct);
-static size_t sizeofEncoding(const char **type, size_t *length);
+static size_t alignmentOfEncoding(const char **type, size_t *length,
+ bool inStruct);
+static size_t sizeOfEncoding(const char **type, size_t *length);
static size_t
-alignofArray(const char **type, size_t *length)
+alignmentOfArray(const char **type, size_t *length)
{
- size_t align;
+ size_t alignment;
assert(*length > 0);
(*type)++;
(*length)--;
- while (*length > 0 && of_ascii_isdigit(**type)) {
+ while (*length > 0 && OFASCIIIsDigit(**type)) {
(*type)++;
(*length)--;
}
- align = alignofEncoding(type, length, true);
+ alignment = alignmentOfEncoding(type, length, true);
if (*length == 0 || **type != ']')
@throw [OFInvalidFormatException exception];
(*type)++;
(*length)--;
- return align;
+ return alignment;
}
static size_t
-alignofStruct(const char **type, size_t *length)
+alignmentOfStruct(const char **type, size_t *length)
{
- size_t align = 0;
+ size_t alignment = 0;
#if defined(OF_POWERPC) && defined(OF_MACOS)
bool first = true;
#endif
assert(*length > 0);
@@ -81,36 +82,36 @@
/* Skip '=' */
(*type)++;
(*length)--;
while (*length > 0 && **type != '}') {
- size_t fieldAlign = alignofEncoding(type, length, true);
+ size_t fieldAlignment = alignmentOfEncoding(type, length, true);
#if defined(OF_POWERPC) && defined(OF_MACOS)
- if (!first && fieldAlign > 4)
- fieldAlign = 4;
+ if (!first && fieldAlignment > 4)
+ fieldAlignment = 4;
first = false;
#endif
- if (fieldAlign > align)
- align = fieldAlign;
+ if (fieldAlignment > alignment)
+ alignment = fieldAlignment;
}
if (*length == 0 || **type != '}')
@throw [OFInvalidFormatException exception];
(*type)++;
(*length)--;
- return align;
+ return alignment;
}
static size_t
-alignofUnion(const char **type, size_t *length)
+alignmentOfUnion(const char **type, size_t *length)
{
- size_t align = 0;
+ size_t alignment = 0;
assert(*length > 0);
(*type)++;
(*length)--;
@@ -127,29 +128,29 @@
/* Skip '=' */
(*type)++;
(*length)--;
while (*length > 0 && **type != ')') {
- size_t fieldAlign = alignofEncoding(type, length, true);
+ size_t fieldAlignment = alignmentOfEncoding(type, length, true);
- if (fieldAlign > align)
- align = fieldAlign;
+ if (fieldAlignment > alignment)
+ alignment = fieldAlignment;
}
if (*length == 0 || **type != ')')
@throw [OFInvalidFormatException exception];
(*type)++;
(*length)--;
- return align;
+ return alignment;
}
static size_t
-alignofEncoding(const char **type, size_t *length, bool inStruct)
+alignmentOfEncoding(const char **type, size_t *length, bool inStruct)
{
- size_t align;
+ size_t alignment;
if (*length == 0)
@throw [OFInvalidFormatException exception];
if (**type == 'r') {
@@ -161,87 +162,87 @@
}
switch (**type) {
case 'c':
case 'C':
- align = OF_ALIGNOF(char);
+ alignment = OF_ALIGNOF(char);
break;
case 'i':
case 'I':
- align = OF_ALIGNOF(int);
+ alignment = OF_ALIGNOF(int);
break;
case 's':
case 'S':
- align = OF_ALIGNOF(short);
+ alignment = OF_ALIGNOF(short);
break;
case 'l':
case 'L':
- align = OF_ALIGNOF(long);
+ alignment = OF_ALIGNOF(long);
break;
case 'q':
case 'Q':
#if defined(OF_X86) && !defined(OF_WINDOWS)
if (inStruct)
- align = 4;
+ alignment = 4;
else
#endif
- align = OF_ALIGNOF(long long);
+ alignment = OF_ALIGNOF(long long);
break;
#ifdef __SIZEOF_INT128__
case 't':
case 'T':
- align = __extension__ OF_ALIGNOF(__int128);
+ alignment = __extension__ OF_ALIGNOF(__int128);
break;
#endif
case 'f':
- align = OF_ALIGNOF(float);
+ alignment = OF_ALIGNOF(float);
break;
case 'd':
#if defined(OF_X86) && !defined(OF_WINDOWS)
if (inStruct)
- align = 4;
+ alignment = 4;
else
#endif
- align = OF_ALIGNOF(double);
+ alignment = OF_ALIGNOF(double);
break;
case 'D':
#if defined(OF_X86) && !defined(OF_WINDOWS)
if (inStruct)
- align = 4;
+ alignment = 4;
else
#endif
- align = OF_ALIGNOF(long double);
+ alignment = OF_ALIGNOF(long double);
break;
case 'B':
- align = OF_ALIGNOF(_Bool);
+ alignment = OF_ALIGNOF(_Bool);
break;
case 'v':
- align = 0;
+ alignment = 0;
break;
case '*':
- align = OF_ALIGNOF(char *);
+ alignment = OF_ALIGNOF(char *);
break;
case '@':
- align = OF_ALIGNOF(id);
+ alignment = OF_ALIGNOF(id);
break;
case '#':
- align = OF_ALIGNOF(Class);
+ alignment = OF_ALIGNOF(Class);
break;
case ':':
- align = OF_ALIGNOF(SEL);
+ alignment = OF_ALIGNOF(SEL);
break;
case '[':
- return alignofArray(type, length);
+ return alignmentOfArray(type, length);
case '{':
- return alignofStruct(type, length);
+ return alignmentOfStruct(type, length);
case '(':
- return alignofUnion(type, length);
+ return alignmentOfUnion(type, length);
case '^':
/* Just to skip over the rest */
(*type)++;
(*length)--;
- alignofEncoding(type, length, false);
+ alignmentOfEncoding(type, length, false);
return OF_ALIGNOF(void *);
#ifndef __STDC_NO_COMPLEX__
case 'j':
(*type)++;
@@ -250,22 +251,22 @@
if (*length == 0)
@throw [OFInvalidFormatException exception];
switch (**type) {
case 'f':
- align = OF_ALIGNOF(float _Complex);
+ alignment = OF_ALIGNOF(float _Complex);
break;
case 'd':
# if defined(OF_X86) && !defined(OF_WINDOWS)
if (inStruct)
- align = 4;
+ alignment = 4;
else
# endif
- align = OF_ALIGNOF(double _Complex);
+ alignment = OF_ALIGNOF(double _Complex);
break;
case 'D':
- align = OF_ALIGNOF(long double _Complex);
+ alignment = OF_ALIGNOF(long double _Complex);
break;
default:
@throw [OFInvalidFormatException exception];
}
@@ -276,35 +277,35 @@
}
(*type)++;
(*length)--;
- return align;
+ return alignment;
}
static size_t
-sizeofArray(const char **type, size_t *length)
+sizeOfArray(const char **type, size_t *length)
{
size_t count = 0;
size_t size;
assert(*length > 0);
(*type)++;
(*length)--;
- while (*length > 0 && of_ascii_isdigit(**type)) {
+ while (*length > 0 && OFASCIIIsDigit(**type)) {
count = count * 10 + **type - '0';
(*type)++;
(*length)--;
}
if (count == 0)
@throw [OFInvalidFormatException exception];
- size = sizeofEncoding(type, length);
+ size = sizeOfEncoding(type, length);
if (*length == 0 || **type != ']')
@throw [OFInvalidFormatException exception];
(*type)++;
@@ -315,16 +316,16 @@
return count * size;
}
static size_t
-sizeofStruct(const char **type, size_t *length)
+sizeOfStruct(const char **type, size_t *length)
{
size_t size = 0;
const char *typeCopy = *type;
size_t lengthCopy = *length;
- size_t alignment = alignofStruct(&typeCopy, &lengthCopy);
+ size_t alignment = alignmentOfStruct(&typeCopy, &lengthCopy);
#if defined(OF_POWERPC) && defined(OF_MACOS)
bool first = true;
#endif
assert(*length > 0);
@@ -344,26 +345,28 @@
/* Skip '=' */
(*type)++;
(*length)--;
while (*length > 0 && **type != '}') {
- size_t fieldSize, fieldAlign;
+ size_t fieldSize, fieldAlignment;
typeCopy = *type;
lengthCopy = *length;
- fieldSize = sizeofEncoding(type, length);
- fieldAlign = alignofEncoding(&typeCopy, &lengthCopy, true);
+ fieldSize = sizeOfEncoding(type, length);
+ fieldAlignment = alignmentOfEncoding(&typeCopy, &lengthCopy,
+ true);
#if defined(OF_POWERPC) && defined(OF_MACOS)
- if (!first && fieldAlign > 4)
- fieldAlign = 4;
+ if (!first && fieldAlignment > 4)
+ fieldAlignment = 4;
first = false;
#endif
- if (size % fieldAlign != 0) {
- size_t padding = fieldAlign - (size % fieldAlign);
+ if (size % fieldAlignment != 0) {
+ size_t padding =
+ fieldAlignment - (size % fieldAlignment);
if (SIZE_MAX - size < padding)
@throw [OFOutOfRangeException exception];
size += padding;
@@ -392,11 +395,11 @@
return size;
}
static size_t
-sizeofUnion(const char **type, size_t *length)
+sizeOfUnion(const char **type, size_t *length)
{
size_t size = 0;
assert(*length > 0);
@@ -415,11 +418,11 @@
/* Skip '=' */
(*type)++;
(*length)--;
while (*length > 0 && **type != ')') {
- size_t fieldSize = sizeofEncoding(type, length);
+ size_t fieldSize = sizeOfEncoding(type, length);
if (fieldSize > size)
size = fieldSize;
}
@@ -431,11 +434,11 @@
return size;
}
static size_t
-sizeofEncoding(const char **type, size_t *length)
+sizeOfEncoding(const char **type, size_t *length)
{
size_t size;
if (*length == 0)
@throw [OFInvalidFormatException exception];
@@ -501,20 +504,20 @@
break;
case ':':
size = sizeof(SEL);
break;
case '[':
- return sizeofArray(type, length);
+ return sizeOfArray(type, length);
case '{':
- return sizeofStruct(type, length);
+ return sizeOfStruct(type, length);
case '(':
- return sizeofUnion(type, length);
+ return sizeOfUnion(type, length);
case '^':
/* Just to skip over the rest */
(*type)++;
(*length)--;
- sizeofEncoding(type, length);
+ sizeOfEncoding(type, length);
return sizeof(void *);
#ifndef __STDC_NO_COMPLEX__
case 'j':
(*type)++;
@@ -548,26 +551,26 @@
return size;
}
size_t
-of_sizeof_type_encoding(const char *type)
+OFSizeOfTypeEncoding(const char *type)
{
size_t length = strlen(type);
- size_t ret = sizeofEncoding(&type, &length);
+ size_t ret = sizeOfEncoding(&type, &length);
if (length > 0)
@throw [OFInvalidFormatException exception];
return ret;
}
size_t
-of_alignof_type_encoding(const char *type)
+OFAlignmentOfTypeEncoding(const char *type)
{
size_t length = strlen(type);
- size_t ret = alignofEncoding(&type, &length, false);
+ size_t ret = alignmentOfEncoding(&type, &length, false);
if (length > 0)
@throw [OFInvalidFormatException exception];
return ret;
@@ -593,21 +596,21 @@
length = strlen(types);
if (length == 0)
@throw [OFInvalidFormatException exception];
- _types = of_alloc(length + 1, 1);
+ _types = OFAllocMemory(length + 1, 1);
memcpy(_types, types, length);
_typesPointers = [[OFMutableData alloc]
initWithItemSize: sizeof(char *)];
_offsets = [[OFMutableData alloc]
initWithItemSize: sizeof(size_t)];
last = _types;
for (size_t i = 0; i < length; i++) {
- if (of_ascii_isdigit(_types[i])) {
+ if (OFASCIIIsDigit(_types[i])) {
size_t offset = _types[i] - '0';
if (last == _types + i)
@throw [OFInvalidFormatException
exception];
@@ -615,11 +618,11 @@
_types[i] = '\0';
[_typesPointers addItem: &last];
i++;
for (; i < length &&
- of_ascii_isdigit(_types[i]); i++)
+ OFASCIIIsDigit(_types[i]); i++)
offset = offset * 10 + _types[i] - '0';
[_offsets addItem: &offset];
last = _types + i;
@@ -667,11 +670,11 @@
return self;
}
- (void)dealloc
{
- free(_types);
+ OFFreeMemory(_types);
[_typesPointers release];
[_offsets release];
[super dealloc];
}
Index: src/OFMutableAdjacentArray.m
==================================================================
--- src/OFMutableAdjacentArray.m
+++ src/OFMutableAdjacentArray.m
@@ -221,31 +221,31 @@
[objects[i] release];
[_array removeAllItems];
}
-- (void)removeObjectsInRange: (of_range_t)range
+- (void)removeObjectsInRange: (OFRange)range
{
id const *objects = _array.items;
size_t count = _array.count;
id *copy;
if (range.length > SIZE_MAX - range.location ||
range.location >= count || range.length > count - range.location)
@throw [OFOutOfRangeException exception];
- copy = of_alloc(range.length, sizeof(*copy));
+ copy = OFAllocMemory(range.length, sizeof(*copy));
memcpy(copy, objects + range.location, range.length * sizeof(id));
@try {
[_array removeItemsInRange: range];
_mutations++;
for (size_t i = 0; i < range.length; i++)
[copy[i] release];
} @finally {
- free(copy);
+ OFFreeMemory(copy);
}
}
- (void)removeLastObject
{
@@ -291,11 +291,11 @@
objects[i] = objects[j];
objects[j] = tmp;
}
}
-- (int)countByEnumeratingWithState: (of_fast_enumeration_state_t *)state
+- (int)countByEnumeratingWithState: (OFFastEnumerationState *)state
objects: (id *)objects
count: (int)count_
{
size_t count = _array.count;
@@ -328,11 +328,11 @@
initWithArray: self
mutationsPtr: &_mutations] autorelease];
}
#ifdef OF_HAVE_BLOCKS
-- (void)enumerateObjectsUsingBlock: (of_array_enumeration_block_t)block
+- (void)enumerateObjectsUsingBlock: (OFArrayEnumerationBlock)block
{
id const *objects = _array.items;
size_t count = _array.count;
bool stop = false;
unsigned long mutations = _mutations;
@@ -344,11 +344,11 @@
block(objects[i], i, &stop);
}
}
-- (void)replaceObjectsUsingBlock: (of_array_replace_block_t)block
+- (void)replaceObjectsUsingBlock: (OFArrayReplaceBlock)block
{
id *objects = _array.mutableItems;
size_t count = _array.count;
unsigned long mutations = _mutations;
Index: src/OFMutableArray.h
==================================================================
--- src/OFMutableArray.h
+++ src/OFMutableArray.h
@@ -25,11 +25,11 @@
*
* @param object The object to replace
* @param index The index of the object to replace
* @return The object to replace the object with
*/
-typedef id _Nonnull (^of_array_replace_block_t)(id object, size_t index);
+typedef id _Nonnull (^OFArrayReplaceBlock)(id object, size_t index);
#endif
/**
* @class OFMutableArray OFArray.h ObjFW/OFArray.h
*
@@ -157,11 +157,11 @@
/**
* @brief Removes the object in the specified range.
*
* @param range The range of the objects to remove
*/
-- (void)removeObjectsInRange: (of_range_t)range;
+- (void)removeObjectsInRange: (OFRange)range;
/**
* @brief Removes the last object.
*/
- (void)removeLastObject;
@@ -175,11 +175,11 @@
/**
* @brief Replaces each object with the object returned by the block.
*
* @param block The block which returns a new object for each object
*/
-- (void)replaceObjectsUsingBlock: (of_array_replace_block_t)block;
+- (void)replaceObjectsUsingBlock: (OFArrayReplaceBlock)block;
#endif
/**
* @brief Exchange the objects at the specified indices.
*
@@ -196,30 +196,23 @@
/**
* @brief Sorts the array using the specified selector and options.
*
* @param selector The selector to use to sort the array. It's signature
* should be the same as that of -[compare:].
- * @param options The options to use when sorting the array.@n
- * Possible values are:
- * Value | Description
- * ---------------------------|-------------------------
- * `OF_ARRAY_SORT_DESCENDING` | Sort in descending order
+ * @param options The options to use when sorting the array
*/
-- (void)sortUsingSelector: (SEL)selector options: (int)options;
+- (void)sortUsingSelector: (SEL)selector options: (OFArraySortOptions)options;
#ifdef OF_HAVE_BLOCKS
/**
* @brief Sorts the array using the specified comparator and options.
*
* @param comparator The comparator to use to sort the array
- * @param options The options to use when sorting the array.@n
- * Possible values are:
- * Value | Description
- * ---------------------------|-------------------------
- * `OF_ARRAY_SORT_DESCENDING` | Sort in descending order
+ * @param options The options to use when sorting the array
*/
-- (void)sortUsingComparator: (of_comparator_t)comparator options: (int)options;
+- (void)sortUsingComparator: (OFComparator)comparator
+ options: (OFArraySortOptions)options;
#endif
/**
* @brief Reverts the order of the objects in the array.
*/
Index: src/OFMutableArray.m
==================================================================
--- src/OFMutableArray.m
+++ src/OFMutableArray.m
@@ -32,32 +32,32 @@
} placeholder;
@interface OFMutableArrayPlaceholder: OFMutableArray
@end
-static of_comparison_result_t
+static OFComparisonResult
compare(id left, id right, SEL selector)
{
- of_comparison_result_t (*comparator)(id, SEL, id) =
- (of_comparison_result_t (*)(id, SEL, id))
+ OFComparisonResult (*comparator)(id, SEL, id) =
+ (OFComparisonResult (*)(id, SEL, id))
[left methodForSelector: selector];
return comparator(left, selector, right);
}
static void
quicksort(OFMutableArray *array, size_t left, size_t right, SEL selector,
- int options)
+ OFArraySortOptions options)
{
- of_comparison_result_t ascending, descending;
+ OFComparisonResult ascending, descending;
- if (options & OF_ARRAY_SORT_DESCENDING) {
- ascending = OF_ORDERED_DESCENDING;
- descending = OF_ORDERED_ASCENDING;
+ if (options & OFArraySortDescending) {
+ ascending = OFOrderedDescending;
+ descending = OFOrderedAscending;
} else {
- ascending = OF_ORDERED_ASCENDING;
- descending = OF_ORDERED_DESCENDING;
+ ascending = OFOrderedAscending;
+ descending = OFOrderedDescending;
}
while (left < right) {
size_t i = left;
size_t j = right - 1;
@@ -90,20 +90,20 @@
}
#ifdef OF_HAVE_BLOCKS
static void
quicksortWithBlock(OFMutableArray *array, size_t left, size_t right,
- of_comparator_t comparator, int options)
+ OFComparator comparator, OFArraySortOptions options)
{
- of_comparison_result_t ascending, descending;
+ OFComparisonResult ascending, descending;
- if (options & OF_ARRAY_SORT_DESCENDING) {
- ascending = OF_ORDERED_DESCENDING;
- descending = OF_ORDERED_ASCENDING;
+ if (options & OFArraySortDescending) {
+ ascending = OFOrderedDescending;
+ descending = OFOrderedAscending;
} else {
- ascending = OF_ORDERED_ASCENDING;
- descending = OF_ORDERED_DESCENDING;
+ ascending = OFOrderedAscending;
+ descending = OFOrderedDescending;
}
while (left < right) {
size_t i = left;
size_t j = right - 1;
@@ -360,11 +360,11 @@
return;
}
}
}
-- (void)removeObjectsInRange: (of_range_t)range
+- (void)removeObjectsInRange: (OFRange)range
{
for (size_t i = 0; i < range.length; i++)
[self removeObjectAtIndex: range.location];
}
@@ -378,15 +378,15 @@
[self removeObjectAtIndex: count - 1];
}
- (void)removeAllObjects
{
- [self removeObjectsInRange: of_range(0, self.count)];
+ [self removeObjectsInRange: OFRangeMake(0, self.count)];
}
#ifdef OF_HAVE_BLOCKS
-- (void)replaceObjectsUsingBlock: (of_array_replace_block_t)block
+- (void)replaceObjectsUsingBlock: (OFArrayReplaceBlock)block
{
[self enumerateObjectsUsingBlock: ^ (id object, size_t idx,
bool *stop) {
id new = block(object, idx);
@@ -414,11 +414,11 @@
{
[self sortUsingSelector: @selector(compare:) options: 0];
}
- (void)sortUsingSelector: (SEL)selector
- options: (int)options
+ options: (OFArraySortOptions)options
{
size_t count = self.count;
if (count == 0 || count == 1)
return;
@@ -425,11 +425,12 @@
quicksort(self, 0, count - 1, selector, options);
}
#ifdef OF_HAVE_BLOCKS
-- (void)sortUsingComparator: (of_comparator_t)comparator options: (int)options
+- (void)sortUsingComparator: (OFComparator)comparator
+ options: (OFArraySortOptions)options
{
size_t count = self.count;
if (count == 0 || count == 1)
return;
Index: src/OFMutableData.h
==================================================================
--- src/OFMutableData.h
+++ src/OFMutableData.h
@@ -188,11 +188,11 @@
/**
* @brief Removes the specified amount of items at the specified index.
*
* @param range The range of items to remove
*/
-- (void)removeItemsInRange: (of_range_t)range;
+- (void)removeItemsInRange: (OFRange)range;
/**
* @brief Removes the last item.
*/
- (void)removeLastItem;
Index: src/OFMutableData.m
==================================================================
--- src/OFMutableData.m
+++ src/OFMutableData.m
@@ -88,11 +88,11 @@
@try {
if (itemSize == 0)
@throw [OFInvalidArgumentException exception];
- _items = of_alloc(capacity, itemSize);
+ _items = OFAllocMemory(capacity, itemSize);
_itemSize = itemSize;
_capacity = capacity;
_freeWhenDone = true;
} @catch (id e) {
[self release];
@@ -119,11 +119,11 @@
freeWhenDone: (bool)freeWhenDone
{
self = [self initWithItems: items count: count itemSize: itemSize];
if (freeWhenDone)
- free(items);
+ OFFreeMemory(items);
return self;
}
- (instancetype)initWithStringRepresentation: (OFString *)string
@@ -162,11 +162,11 @@
return NULL;
return _items + (_count - 1) * _itemSize;
}
-- (OFData *)subdataWithRange: (of_range_t)range
+- (OFData *)subdataWithRange: (OFRange)range
{
if (range.length > SIZE_MAX - range.location ||
range.location + range.length > _count)
@throw [OFOutOfRangeException exception];
@@ -179,11 +179,11 @@
{
if (SIZE_MAX - _count < 1)
@throw [OFOutOfRangeException exception];
if (_count + 1 > _capacity) {
- _items = of_realloc(_items, _count + 1, _itemSize);
+ _items = OFResizeMemory(_items, _count + 1, _itemSize);
_capacity = _count + 1;
}
memcpy(_items + _count * _itemSize, item, _itemSize);
@@ -199,11 +199,11 @@
{
if (count > SIZE_MAX - _count)
@throw [OFOutOfRangeException exception];
if (_count + count > _capacity) {
- _items = of_realloc(_items, _count + count, _itemSize);
+ _items = OFResizeMemory(_items, _count + count, _itemSize);
_capacity = _count + count;
}
memcpy(_items + _count * _itemSize, items, count * _itemSize);
_count += count;
@@ -215,11 +215,11 @@
{
if (count > SIZE_MAX - _count || idx > _count)
@throw [OFOutOfRangeException exception];
if (_count + count > _capacity) {
- _items = of_realloc(_items, _count + count, _itemSize);
+ _items = OFResizeMemory(_items, _count + count, _itemSize);
_capacity = _count + count;
}
memmove(_items + (idx + count) * _itemSize, _items + idx * _itemSize,
(_count - idx) * _itemSize);
@@ -232,24 +232,24 @@
{
if (count > SIZE_MAX - _count)
@throw [OFOutOfRangeException exception];
if (_count + count > _capacity) {
- _items = of_realloc(_items, _count + count, _itemSize);
+ _items = OFResizeMemory(_items, _count + count, _itemSize);
_capacity = _count + count;
}
memset(_items + _count * _itemSize, '\0', count * _itemSize);
_count += count;
}
- (void)removeItemAtIndex: (size_t)idx
{
- [self removeItemsInRange: of_range(idx, 1)];
+ [self removeItemsInRange: OFRangeMake(idx, 1)];
}
-- (void)removeItemsInRange: (of_range_t)range
+- (void)removeItemsInRange: (OFRange)range
{
if (range.length > SIZE_MAX - range.location ||
range.location + range.length > _count)
@throw [OFOutOfRangeException exception];
@@ -257,11 +257,11 @@
_items + (range.location + range.length) * _itemSize,
(_count - range.location - range.length) * _itemSize);
_count -= range.length;
@try {
- _items = of_realloc(_items, _count, _itemSize);
+ _items = OFResizeMemory(_items, _count, _itemSize);
_capacity = _count;
} @catch (OFOutOfMemoryException *e) {
/* We don't really care, as we only made it smaller */
}
}
@@ -271,20 +271,20 @@
if (_count == 0)
return;
_count--;
@try {
- _items = of_realloc(_items, _count, _itemSize);
+ _items = OFResizeMemory(_items, _count, _itemSize);
_capacity = _count;
} @catch (OFOutOfMemoryException *e) {
/* We don't care, as we only made it smaller */
}
}
- (void)removeAllItems
{
- free(_items);
+ OFFreeMemory(_items);
_items = NULL;
_count = 0;
_capacity = 0;
}
@@ -297,15 +297,15 @@
- (void)makeImmutable
{
if (_capacity != _count) {
@try {
- _items = of_realloc(_items, _count, _itemSize);
+ _items = OFResizeMemory(_items, _count, _itemSize);
_capacity = _count;
} @catch (OFOutOfMemoryException *e) {
/* We don't care, as we only made it smaller */
}
}
object_setClass(self, [OFData class]);
}
@end
Index: src/OFMutableDictionary.h
==================================================================
--- src/OFMutableDictionary.h
+++ src/OFMutableDictionary.h
@@ -25,11 +25,11 @@
*
* @param key The key of the object to replace
* @param object The object to replace
* @return The object to replace the object with
*/
-typedef id _Nonnull (^of_dictionary_replace_block_t)(id key, id object);
+typedef id _Nonnull (^OFDictionaryReplaceBlock)(id key, id object);
#endif
/**
* @class OFMutableDictionary OFDictionary.h ObjFW/OFDictionary.h
*
@@ -110,11 +110,11 @@
/**
* @brief Replaces each object with the object returned by the block.
*
* @param block The block which returns a new object for each object
*/
-- (void)replaceObjectsUsingBlock: (of_dictionary_replace_block_t)block;
+- (void)replaceObjectsUsingBlock: (OFDictionaryReplaceBlock)block;
#endif
/**
* @brief Converts the mutable dictionary to an immutable dictionary.
*/
Index: src/OFMutableDictionary.m
==================================================================
--- src/OFMutableDictionary.m
+++ src/OFMutableDictionary.m
@@ -199,11 +199,11 @@
objc_autoreleasePoolPop(pool);
}
#ifdef OF_HAVE_BLOCKS
-- (void)replaceObjectsUsingBlock: (of_dictionary_replace_block_t)block
+- (void)replaceObjectsUsingBlock: (OFDictionaryReplaceBlock)block
{
[self enumerateKeysAndObjectsUsingBlock: ^ (id key, id object,
bool *stop) {
id new = block(key, object);
Index: src/OFMutableMapTableDictionary.m
==================================================================
--- src/OFMutableMapTableDictionary.m
+++ src/OFMutableMapTableDictionary.m
@@ -45,11 +45,11 @@
{
[_mapTable removeAllObjects];
}
#ifdef OF_HAVE_BLOCKS
-- (void)replaceObjectsUsingBlock: (of_dictionary_replace_block_t)block
+- (void)replaceObjectsUsingBlock: (OFDictionaryReplaceBlock)block
{
@try {
[_mapTable replaceObjectsUsingBlock:
^ void *(void *key, void *object) {
return block(key, object);
Index: src/OFMutableSet.m
==================================================================
--- src/OFMutableSet.m
+++ src/OFMutableSet.m
@@ -166,11 +166,11 @@
{
void *pool = objc_autoreleasePoolPush();
size_t count = self.count;
id *cArray;
- cArray = of_alloc(count, sizeof(id));
+ cArray = OFAllocMemory(count, sizeof(id));
@try {
size_t i;
i = 0;
for (id object in self) {
@@ -180,11 +180,11 @@
for (i = 0; i < count; i++)
if (![set containsObject: cArray[i]])
[self removeObject: cArray[i]];
} @finally {
- free(cArray);
+ OFFreeMemory(cArray);
}
objc_autoreleasePoolPop(pool);
}
Index: src/OFMutableString.h
==================================================================
--- src/OFMutableString.h
+++ src/OFMutableString.h
@@ -31,11 +31,11 @@
* @brief Sets the character at the specified index.
*
* @param character The character to set
* @param index The index where to set the character
*/
-- (void)setCharacter: (of_unichar_t)character atIndex: (size_t)index;
+- (void)setCharacter: (OFUnichar)character atIndex: (size_t)index;
/**
* @brief Appends another OFString to the OFMutableString.
*
* @param string An OFString to append
@@ -46,12 +46,11 @@
* @brief Appends the specified characters to the OFMutableString.
*
* @param characters An array of characters to append
* @param length The length of the array of characters
*/
-- (void)appendCharacters: (const of_unichar_t *)characters
- length: (size_t)length;
+- (void)appendCharacters: (const OFUnichar *)characters length: (size_t)length;
/**
* @brief Appends a UTF-8 encoded C string to the OFMutableString.
*
* @param UTF8String A UTF-8 encoded C string to append
@@ -73,11 +72,11 @@
*
* @param cString A C string to append
* @param encoding The encoding of the C string
*/
- (void)appendCString: (const char *)cString
- encoding: (of_string_encoding_t)encoding;
+ encoding: (OFStringEncoding)encoding;
/**
* @brief Appends a C string with the specified encoding and length to the
* OFMutableString.
*
@@ -84,30 +83,30 @@
* @param cString A C string to append
* @param encoding The encoding of the C string
* @param cStringLength The length of the UTF-8 encoded C string
*/
- (void)appendCString: (const char *)cString
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
length: (size_t)cStringLength;
/**
* @brief Appends a formatted string to the OFMutableString.
*
* See `printf` for the format syntax. As an addition, `%@` is available as
- * format specifier for objects, `%C` for `of_unichar_t` and `%S` for
- * `const of_unichar_t *`.
+ * format specifier for objects, `%C` for `OFUnichar` and `%S` for
+ * `const OFUnichar *`.
*
* @param format A format string which generates the string to append
*/
- (void)appendFormat: (OFConstantString *)format, ...;
/**
* @brief Appends a formatted string to the OFMutableString.
*
* See printf for the format syntax. As an addition, `%@` is available as
- * format specifier for objects, `%C` for `of_unichar_t` and `%S` for
- * `const of_unichar_t *`.
+ * format specifier for objects, `%C` for `OFUnichar` and `%S` for
+ * `const OFUnichar *`.
*
* @param format A format string which generates the string to append
* @param arguments The arguments used in the format string
*/
- (void)appendFormat: (OFConstantString *)format arguments: (va_list)arguments;
@@ -154,19 +153,19 @@
/**
* @brief Deletes the characters at the specified range.
*
* @param range The range of the characters which should be removed
*/
-- (void)deleteCharactersInRange: (of_range_t)range;
+- (void)deleteCharactersInRange: (OFRange)range;
/**
* @brief Replaces the characters at the specified range.
*
* @param range The range of the characters which should be replaced
* @param replacement The string to the replace the characters with
*/
-- (void)replaceCharactersInRange: (of_range_t)range
+- (void)replaceCharactersInRange: (OFRange)range
withString: (OFString *)replacement;
/**
* @brief Replaces all occurrences of a string with another string.
*
@@ -187,11 +186,11 @@
* @param range The range in which the string should be replaced
*/
- (void)replaceOccurrencesOfString: (OFString *)string
withString: (OFString *)replacement
options: (int)options
- range: (of_range_t)range;
+ range: (OFRange)range;
/**
* @brief Deletes all whitespaces at the beginning of the string.
*/
- (void)deleteLeadingWhitespaces;
Index: src/OFMutableString.m
==================================================================
--- src/OFMutableString.m
+++ src/OFMutableString.m
@@ -18,17 +18,17 @@
#include
#include
#include
#import "OFString.h"
+#import "OFASPrintF.h"
#import "OFMutableUTF8String.h"
#import "OFInvalidArgumentException.h"
#import "OFInvalidFormatException.h"
#import "OFOutOfRangeException.h"
-#import "of_asprintf.h"
#import "unicode.h"
static struct {
Class isa;
} placeholder;
@@ -54,18 +54,18 @@
initWithUTF8String: UTF8String
length: UTF8StringLength];
}
- (instancetype)initWithCString: (const char *)cString
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
return (id)[[OFMutableUTF8String alloc] initWithCString: cString
encoding: encoding];
}
- (instancetype)initWithCString: (const char *)cString
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
length: (size_t)cStringLength
{
return (id)[[OFMutableUTF8String alloc] initWithCString: cString
encoding: encoding
length: cStringLength];
@@ -74,67 +74,67 @@
- (instancetype)initWithString: (OFString *)string
{
return (id)[[OFMutableUTF8String alloc] initWithString: string];
}
-- (instancetype)initWithCharacters: (const of_unichar_t *)characters
+- (instancetype)initWithCharacters: (const OFUnichar *)characters
length: (size_t)length
{
return (id)[[OFMutableUTF8String alloc] initWithCharacters: characters
length: length];
}
-- (instancetype)initWithUTF16String: (const of_char16_t *)string
+- (instancetype)initWithUTF16String: (const OFChar16 *)string
{
return (id)[[OFMutableUTF8String alloc] initWithUTF16String: string];
}
-- (instancetype)initWithUTF16String: (const of_char16_t *)string
+- (instancetype)initWithUTF16String: (const OFChar16 *)string
length: (size_t)length
{
return (id)[[OFMutableUTF8String alloc] initWithUTF16String: string
length: length];
}
-- (instancetype)initWithUTF16String: (const of_char16_t *)string
- byteOrder: (of_byte_order_t)byteOrder
+- (instancetype)initWithUTF16String: (const OFChar16 *)string
+ byteOrder: (OFByteOrder)byteOrder
{
return (id)[[OFMutableUTF8String alloc] initWithUTF16String: string
byteOrder: byteOrder];
}
-- (instancetype)initWithUTF16String: (const of_char16_t *)string
+- (instancetype)initWithUTF16String: (const OFChar16 *)string
length: (size_t)length
- byteOrder: (of_byte_order_t)byteOrder
+ byteOrder: (OFByteOrder)byteOrder
{
return (id)[[OFMutableUTF8String alloc] initWithUTF16String: string
length: length
byteOrder: byteOrder];
}
-- (instancetype)initWithUTF32String: (const of_char32_t *)string
+- (instancetype)initWithUTF32String: (const OFChar32 *)string
{
return (id)[[OFMutableUTF8String alloc] initWithUTF32String: string];
}
-- (instancetype)initWithUTF32String: (const of_char32_t *)string
+- (instancetype)initWithUTF32String: (const OFChar32 *)string
length: (size_t)length
{
return (id)[[OFMutableUTF8String alloc] initWithUTF32String: string
length: length];
}
-- (instancetype)initWithUTF32String: (const of_char32_t *)string
- byteOrder: (of_byte_order_t)byteOrder
+- (instancetype)initWithUTF32String: (const OFChar32 *)string
+ byteOrder: (OFByteOrder)byteOrder
{
return (id)[[OFMutableUTF8String alloc] initWithUTF32String: string
byteOrder: byteOrder];
}
-- (instancetype)initWithUTF32String: (const of_char32_t *)string
+- (instancetype)initWithUTF32String: (const OFChar32 *)string
length: (size_t)length
- byteOrder: (of_byte_order_t)byteOrder
+ byteOrder: (OFByteOrder)byteOrder
{
return (id)[[OFMutableUTF8String alloc] initWithUTF32String: string
length: length
byteOrder: byteOrder];
}
@@ -164,11 +164,11 @@
{
return (id)[[OFMutableUTF8String alloc] initWithContentsOfFile: path];
}
- (instancetype)initWithContentsOfFile: (OFString *)path
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
return (id)[[OFMutableUTF8String alloc]
initWithContentsOfFile: path
encoding: encoding];
}
@@ -178,11 +178,11 @@
{
return (id)[[OFMutableUTF8String alloc] initWithContentsOfURL: URL];
}
- (instancetype)initWithContentsOfURL: (OFURL *)URL
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
return (id)[[OFMutableUTF8String alloc]
initWithContentsOfURL: URL
encoding: encoding];
}
@@ -226,24 +226,24 @@
return [super alloc];
}
#ifdef OF_HAVE_UNICODE_TABLES
-- (void)of_convertWithWordStartTable: (const of_unichar_t *const [])startTable
- wordMiddleTable: (const of_unichar_t *const [])middleTable
+- (void)of_convertWithWordStartTable: (const OFUnichar *const [])startTable
+ wordMiddleTable: (const OFUnichar *const [])middleTable
wordStartTableSize: (size_t)startTableSize
wordMiddleTableSize: (size_t)middleTableSize
{
void *pool = objc_autoreleasePoolPush();
- const of_unichar_t *characters = self.characters;
+ const OFUnichar *characters = self.characters;
size_t length = self.length;
bool isStart = true;
for (size_t i = 0; i < length; i++) {
- const of_unichar_t *const *table;
+ const OFUnichar *const *table;
size_t tableSize;
- of_unichar_t c = characters[i];
+ OFUnichar c = characters[i];
if (isStart) {
table = startTable;
tableSize = middleTableSize;
} else {
@@ -252,11 +252,11 @@
}
if (c >> 8 < tableSize && table[c >> 8][c & 0xFF])
[self setCharacter: table[c >> 8][c & 0xFF] atIndex: i];
- isStart = of_ascii_isspace(c);
+ isStart = OFASCIIIsSpace(c);
}
objc_autoreleasePoolPop(pool);
}
#else
@@ -263,44 +263,44 @@
static void
convert(OFMutableString *self, char (*startFunction)(char),
char (*middleFunction)(char))
{
void *pool = objc_autoreleasePoolPush();
- const of_unichar_t *characters = self.characters;
+ const OFUnichar *characters = self.characters;
size_t length = self.length;
bool isStart = true;
for (size_t i = 0; i < length; i++) {
char (*function)(char) =
(isStart ? startFunction : middleFunction);
- of_unichar_t c = characters[i];
+ OFUnichar c = characters[i];
if (c <= 0x7F)
[self setCharacter: (int)function(c) atIndex: i];
- isStart = of_ascii_isspace(c);
+ isStart = OFASCIIIsSpace(c);
}
objc_autoreleasePoolPop(pool);
}
#endif
-- (void)setCharacter: (of_unichar_t)character atIndex: (size_t)idx
+- (void)setCharacter: (OFUnichar)character atIndex: (size_t)idx
{
void *pool = objc_autoreleasePoolPush();
OFString *string =
[OFString stringWithCharacters: &character length: 1];
- [self replaceCharactersInRange: of_range(idx, 1) withString: string];
+ [self replaceCharactersInRange: OFRangeMake(idx, 1) withString: string];
objc_autoreleasePoolPop(pool);
}
- (void)appendString: (OFString *)string
{
[self insertString: string atIndex: self.length];
}
-- (void)appendCharacters: (const of_unichar_t *)characters
+- (void)appendCharacters: (const OFUnichar *)characters
length: (size_t)length
{
void *pool = objc_autoreleasePoolPush();
[self appendString: [OFString stringWithCharacters: characters
length: length]];
@@ -322,20 +322,20 @@
length: UTF8StringLength]];
objc_autoreleasePoolPop(pool);
}
- (void)appendCString: (const char *)cString
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
void *pool = objc_autoreleasePoolPush();
[self appendString: [OFString stringWithCString: cString
encoding: encoding]];
objc_autoreleasePoolPop(pool);
}
- (void)appendCString: (const char *)cString
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
length: (size_t)cStringLength
{
void *pool = objc_autoreleasePoolPush();
[self appendString: [OFString stringWithCString: cString
encoding: encoding
@@ -359,11 +359,11 @@
int UTF8StringLength;
if (format == nil)
@throw [OFInvalidArgumentException exception];
- if ((UTF8StringLength = of_vasprintf(&UTF8String, format.UTF8String,
+ if ((UTF8StringLength = OFVASPrintF(&UTF8String, format.UTF8String,
arguments)) == -1)
@throw [OFInvalidFormatException exception];
@try {
[self appendUTF8String: UTF8String length: UTF8StringLength];
@@ -380,68 +380,68 @@
- (void)reverse
{
size_t i, j, length = self.length;
for (i = 0, j = length - 1; i < length / 2; i++, j--) {
- of_unichar_t tmp = [self characterAtIndex: j];
+ OFUnichar tmp = [self characterAtIndex: j];
[self setCharacter: [self characterAtIndex: i] atIndex: j];
[self setCharacter: tmp atIndex: i];
}
}
#ifdef OF_HAVE_UNICODE_TABLES
- (void)uppercase
{
- [self of_convertWithWordStartTable: of_unicode_uppercase_table
- wordMiddleTable: of_unicode_uppercase_table
- wordStartTableSize: OF_UNICODE_UPPERCASE_TABLE_SIZE
- wordMiddleTableSize: OF_UNICODE_UPPERCASE_TABLE_SIZE];
+ [self of_convertWithWordStartTable: OFUnicodeUppercaseTable
+ wordMiddleTable: OFUnicodeUppercaseTable
+ wordStartTableSize: OFUnicodeUppercaseTableSize
+ wordMiddleTableSize: OFUnicodeUppercaseTableSize];
}
- (void)lowercase
{
- [self of_convertWithWordStartTable: of_unicode_lowercase_table
- wordMiddleTable: of_unicode_lowercase_table
- wordStartTableSize: OF_UNICODE_LOWERCASE_TABLE_SIZE
- wordMiddleTableSize: OF_UNICODE_LOWERCASE_TABLE_SIZE];
+ [self of_convertWithWordStartTable: OFUnicodeLowercaseTable
+ wordMiddleTable: OFUnicodeLowercaseTable
+ wordStartTableSize: OFUnicodeLowercaseTableSize
+ wordMiddleTableSize: OFUnicodeLowercaseTableSize];
}
- (void)capitalize
{
- [self of_convertWithWordStartTable: of_unicode_titlecase_table
- wordMiddleTable: of_unicode_lowercase_table
- wordStartTableSize: OF_UNICODE_TITLECASE_TABLE_SIZE
- wordMiddleTableSize: OF_UNICODE_LOWERCASE_TABLE_SIZE];
+ [self of_convertWithWordStartTable: OFUnicodeTitlecaseTable
+ wordMiddleTable: OFUnicodeLowercaseTable
+ wordStartTableSize: OFUnicodeTitlecaseTableSize
+ wordMiddleTableSize: OFUnicodeLowercaseTableSize];
}
#else
- (void)uppercase
{
- convert(self, of_ascii_toupper, of_ascii_toupper);
+ convert(self, OFASCIIToUpper, OFASCIIToUpper);
}
- (void)lowercase
{
- convert(self, of_ascii_tolower, of_ascii_tolower);
+ convert(self, OFASCIIToLower, OFASCIIToLower);
}
- (void)capitalize
{
- convert(self, of_ascii_toupper, of_ascii_tolower);
+ convert(self, OFASCIIToUpper, OFASCIIToLower);
}
#endif
- (void)insertString: (OFString *)string atIndex: (size_t)idx
{
- [self replaceCharactersInRange: of_range(idx, 0) withString: string];
+ [self replaceCharactersInRange: OFRangeMake(idx, 0) withString: string];
}
-- (void)deleteCharactersInRange: (of_range_t)range
+- (void)deleteCharactersInRange: (OFRange)range
{
[self replaceCharactersInRange: range withString: @""];
}
-- (void)replaceCharactersInRange: (of_range_t)range
+- (void)replaceCharactersInRange: (OFRange)range
withString: (OFString *)replacement
{
OF_UNRECOGNIZED_SELECTOR
}
@@ -449,21 +449,21 @@
withString: (OFString *)replacement
{
[self replaceOccurrencesOfString: string
withString: replacement
options: 0
- range: of_range(0, self.length)];
+ range: OFRangeMake(0, self.length)];
}
- (void)replaceOccurrencesOfString: (OFString *)string
withString: (OFString *)replacement
options: (int)options
- range: (of_range_t)range
+ range: (OFRange)range
{
void *pool = objc_autoreleasePoolPush(), *pool2;
- const of_unichar_t *characters;
- const of_unichar_t *searchCharacters = string.characters;
+ const OFUnichar *characters;
+ const OFUnichar *searchCharacters = string.characters;
size_t searchLength = string.length;
size_t replacementLength = replacement.length;
if (string == nil || replacement == nil)
@throw [OFInvalidArgumentException exception];
@@ -480,14 +480,14 @@
pool2 = objc_autoreleasePoolPush();
characters = self.characters;
for (size_t i = range.location; i <= range.length - searchLength; i++) {
if (memcmp(characters + i, searchCharacters,
- searchLength * sizeof(of_unichar_t)) != 0)
+ searchLength * sizeof(OFUnichar)) != 0)
continue;
- [self replaceCharactersInRange: of_range(i, searchLength)
+ [self replaceCharactersInRange: OFRangeMake(i, searchLength)
withString: replacement];
range.length -= searchLength;
range.length += replacementLength;
@@ -503,29 +503,29 @@
}
- (void)deleteLeadingWhitespaces
{
void *pool = objc_autoreleasePoolPush();
- const of_unichar_t *characters = self.characters;
+ const OFUnichar *characters = self.characters;
size_t i, length = self.length;
for (i = 0; i < length; i++) {
- of_unichar_t c = characters[i];
+ OFUnichar c = characters[i];
- if (!of_ascii_isspace(c))
+ if (!OFASCIIIsSpace(c))
break;
}
objc_autoreleasePoolPop(pool);
- [self deleteCharactersInRange: of_range(0, i)];
+ [self deleteCharactersInRange: OFRangeMake(0, i)];
}
- (void)deleteTrailingWhitespaces
{
void *pool;
- const of_unichar_t *characters, *p;
+ const OFUnichar *characters, *p;
size_t length, d;
length = self.length;
if (length == 0)
@@ -534,19 +534,19 @@
pool = objc_autoreleasePoolPush();
characters = self.characters;
d = 0;
for (p = characters + length - 1; p >= characters; p--) {
- if (!of_ascii_isspace(*p))
+ if (!OFASCIIIsSpace(*p))
break;
d++;
}
objc_autoreleasePoolPop(pool);
- [self deleteCharactersInRange: of_range(length - d, d)];
+ [self deleteCharactersInRange: OFRangeMake(length - d, d)];
}
- (void)deleteEnclosingWhitespaces
{
[self deleteLeadingWhitespaces];
Index: src/OFMutableTarArchiveEntry.h
==================================================================
--- src/OFMutableTarArchiveEntry.h
+++ src/OFMutableTarArchiveEntry.h
@@ -59,13 +59,13 @@
@property (readwrite, retain, nonatomic) OFDate *modificationDate;
/**
* @brief The type of the archive entry.
*
- * See @ref of_tar_archive_entry_type_t.
+ * See @ref OFTarArchiveEntryType.
*/
-@property (readwrite, nonatomic) of_tar_archive_entry_type_t type;
+@property (readwrite, nonatomic) OFTarArchiveEntryType type;
/**
* @brief The file name of the target (for a hard link or symbolic link).
*/
@property OF_NULLABLE_PROPERTY (readwrite, copy, nonatomic)
Index: src/OFMutableTarArchiveEntry.m
==================================================================
--- src/OFMutableTarArchiveEntry.m
+++ src/OFMutableTarArchiveEntry.m
@@ -64,11 +64,11 @@
OFDate *old = _modificationDate;
_modificationDate = [modificationDate retain];
[old release];
}
-- (void)setType: (of_tar_archive_entry_type_t)type
+- (void)setType: (OFTarArchiveEntryType)type
{
_type = type;
}
- (void)setTargetFileName: (OFString *)targetFileName
Index: src/OFMutableURL.m
==================================================================
--- src/OFMutableURL.m
+++ src/OFMutableURL.m
@@ -24,12 +24,10 @@
#import "OFNumber.h"
#import "OFString.h"
#import "OFInvalidFormatException.h"
-extern void of_url_verify_escaped(OFString *, OFCharacterSet *);
-
@implementation OFMutableURL
@dynamic scheme, URLEncodedScheme, host, URLEncodedHost, port, user;
@dynamic URLEncodedUser, password, URLEncodedPassword, path, URLEncodedPath;
@dynamic pathComponents, query, URLEncodedQuery, queryDictionary, fragment;
@dynamic URLEncodedFragment;
@@ -55,11 +53,11 @@
- (void)setURLEncodedScheme: (OFString *)URLEncodedScheme
{
OFString *old;
if (URLEncodedScheme != nil)
- of_url_verify_escaped(URLEncodedScheme,
+ OFURLVerifyIsEscaped(URLEncodedScheme,
[OFCharacterSet URLSchemeAllowedCharacterSet]);
old = _URLEncodedScheme;
_URLEncodedScheme = [URLEncodedScheme copy];
[old release];
@@ -68,11 +66,11 @@
- (void)setHost: (OFString *)host
{
void *pool = objc_autoreleasePoolPush();
OFString *old = _URLEncodedHost;
- if (of_url_is_ipv6_host(host))
+ if (OFURLIsIPv6Host(host))
_URLEncodedHost = [[OFString alloc]
initWithFormat: @"[%@]", host];
else
_URLEncodedHost = [[host
stringByURLEncodingWithAllowedCharacters:
@@ -87,15 +85,15 @@
{
OFString *old;
if ([URLEncodedHost hasPrefix: @"["] &&
[URLEncodedHost hasSuffix: @"]"]) {
- if (!of_url_is_ipv6_host([URLEncodedHost substringWithRange:
- of_range(1, URLEncodedHost.length - 2)]))
+ if (!OFURLIsIPv6Host([URLEncodedHost substringWithRange:
+ OFRangeMake(1, URLEncodedHost.length - 2)]))
@throw [OFInvalidFormatException exception];
} else if (URLEncodedHost != nil)
- of_url_verify_escaped(URLEncodedHost,
+ OFURLVerifyIsEscaped(URLEncodedHost,
[OFCharacterSet URLHostAllowedCharacterSet]);
old = _URLEncodedHost;
_URLEncodedHost = [URLEncodedHost copy];
[old release];
@@ -124,11 +122,11 @@
- (void)setURLEncodedUser: (OFString *)URLEncodedUser
{
OFString *old;
if (URLEncodedUser != nil)
- of_url_verify_escaped(URLEncodedUser,
+ OFURLVerifyIsEscaped(URLEncodedUser,
[OFCharacterSet URLUserAllowedCharacterSet]);
old = _URLEncodedUser;
_URLEncodedUser = [URLEncodedUser copy];
[old release];
@@ -151,11 +149,11 @@
- (void)setURLEncodedPassword: (OFString *)URLEncodedPassword
{
OFString *old;
if (URLEncodedPassword != nil)
- of_url_verify_escaped(URLEncodedPassword,
+ OFURLVerifyIsEscaped(URLEncodedPassword,
[OFCharacterSet URLPasswordAllowedCharacterSet]);
old = _URLEncodedPassword;
_URLEncodedPassword = [URLEncodedPassword copy];
[old release];
@@ -177,11 +175,11 @@
- (void)setURLEncodedPath: (OFString *)URLEncodedPath
{
OFString *old;
if (URLEncodedPath != nil)
- of_url_verify_escaped(URLEncodedPath,
+ OFURLVerifyIsEscaped(URLEncodedPath,
[OFCharacterSet URLPathAllowedCharacterSet]);
old = _URLEncodedPath;
_URLEncodedPath = [URLEncodedPath copy];
[old release];
@@ -223,11 +221,11 @@
- (void)setURLEncodedQuery: (OFString *)URLEncodedQuery
{
OFString *old;
if (URLEncodedQuery != nil)
- of_url_verify_escaped(URLEncodedQuery,
+ OFURLVerifyIsEscaped(URLEncodedQuery,
[OFCharacterSet URLQueryAllowedCharacterSet]);
old = _URLEncodedQuery;
_URLEncodedQuery = [URLEncodedQuery copy];
[old release];
@@ -291,11 +289,11 @@
- (void)setURLEncodedFragment: (OFString *)URLEncodedFragment
{
OFString *old;
if (URLEncodedFragment != nil)
- of_url_verify_escaped(URLEncodedFragment,
+ OFURLVerifyIsEscaped(URLEncodedFragment,
[OFCharacterSet URLFragmentAllowedCharacterSet]);
old = _URLEncodedFragment;
_URLEncodedFragment = [URLEncodedFragment copy];
[old release];
@@ -402,11 +400,11 @@
}
if ([current isEqual: @".."] && parent != nil &&
![parent isEqual: @".."]) {
[array removeObjectsInRange:
- of_range(i - 1, 2)];
+ OFRangeMake(i - 1, 2)];
done = false;
break;
}
}
Index: src/OFMutableUTF8String.h
==================================================================
--- src/OFMutableUTF8String.h
+++ src/OFMutableUTF8String.h
@@ -18,11 +18,11 @@
OF_ASSUME_NONNULL_BEGIN
@interface OFMutableUTF8String: OFMutableString
{
- struct of_string_utf8_ivars *restrict _s;
- struct of_string_utf8_ivars _storage;
+ struct OFUTF8StringIvars *restrict _s;
+ struct OFUTF8StringIvars _storage;
}
@end
OF_ASSUME_NONNULL_END
Index: src/OFMutableUTF8String.m
==================================================================
--- src/OFMutableUTF8String.m
+++ src/OFMutableUTF8String.m
@@ -19,20 +19,20 @@
#include
#include
#include
#import "OFMutableUTF8String.h"
+#import "OFASPrintF.h"
#import "OFString.h"
#import "OFUTF8String.h"
#import "OFInvalidArgumentException.h"
#import "OFInvalidEncodingException.h"
#import "OFInvalidFormatException.h"
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"
-#import "of_asprintf.h"
#import "unicode.h"
@implementation OFMutableUTF8String
+ (void)initialize
{
@@ -44,11 +44,11 @@
freeWhenDone: (bool)freeWhenDone
{
self = [self initWithUTF8String: UTF8String];
if (freeWhenDone)
- free(UTF8String);
+ OFFreeMemory(UTF8String);
return self;
}
- (instancetype)initWithUTF8StringNoCopy: (char *)UTF8String
@@ -56,60 +56,60 @@
freeWhenDone: (bool)freeWhenDone
{
self = [self initWithUTF8String: UTF8String length: UTF8StringLength];
if (freeWhenDone)
- free(UTF8String);
+ OFFreeMemory(UTF8String);
return self;
}
#ifdef OF_HAVE_UNICODE_TABLES
-- (void)of_convertWithWordStartTable: (const of_unichar_t *const [])startTable
- wordMiddleTable: (const of_unichar_t *const [])middleTable
+- (void)of_convertWithWordStartTable: (const OFUnichar *const [])startTable
+ wordMiddleTable: (const OFUnichar *const [])middleTable
wordStartTableSize: (size_t)startTableSize
wordMiddleTableSize: (size_t)middleTableSize
{
- of_unichar_t *unicodeString;
+ OFUnichar *unicodeString;
size_t unicodeLen, newCStringLength;
size_t i, j;
char *newCString;
bool isStart = true;
if (!_s->isUTF8) {
uint8_t t;
- const of_unichar_t *const *table;
+ const OFUnichar *const *table;
assert(startTableSize >= 1 && middleTableSize >= 1);
- _s->hashed = false;
+ _s->hasHash = false;
for (i = 0; i < _s->cStringLength; i++) {
if (isStart)
table = startTable;
else
table = middleTable;
- isStart = of_ascii_isspace(_s->cString[i]);
+ isStart = OFASCIIIsSpace(_s->cString[i]);
if ((t = table[0][(uint8_t)_s->cString[i]]) != 0)
_s->cString[i] = t;
}
return;
}
unicodeLen = self.length;
- unicodeString = of_alloc(unicodeLen, sizeof(of_unichar_t));
+ unicodeString = OFAllocMemory(unicodeLen, sizeof(OFUnichar));
i = j = 0;
newCStringLength = 0;
while (i < _s->cStringLength) {
- const of_unichar_t *const *table;
+ const OFUnichar *const *table;
size_t tableSize;
- of_unichar_t c;
+ OFUnichar c;
ssize_t cLen;
if (isStart) {
table = startTable;
tableSize = middleTableSize;
@@ -116,22 +116,22 @@
} else {
table = middleTable;
tableSize = middleTableSize;
}
- cLen = of_string_utf8_decode(_s->cString + i,
+ cLen = OFUTF8StringDecode(_s->cString + i,
_s->cStringLength - i, &c);
if (cLen <= 0 || c > 0x10FFFF) {
- free(unicodeString);
+ OFFreeMemory(unicodeString);
@throw [OFInvalidEncodingException exception];
}
- isStart = of_ascii_isspace(c);
+ isStart = OFASCIIIsSpace(c);
if (c >> 8 < tableSize) {
- of_unichar_t tc = table[c >> 8][c & 0xFF];
+ OFUnichar tc = table[c >> 8][c & 0xFF];
if (tc)
c = tc;
}
unicodeString[j++] = c;
@@ -143,44 +143,44 @@
else if (c < 0x10000)
newCStringLength += 3;
else if (c < 0x110000)
newCStringLength += 4;
else {
- free(unicodeString);
+ OFFreeMemory(unicodeString);
@throw [OFInvalidEncodingException exception];
}
i += cLen;
}
@try {
- newCString = of_alloc(newCStringLength + 1, 1);
+ newCString = OFAllocMemory(newCStringLength + 1, 1);
} @catch (id e) {
- free(unicodeString);
+ OFFreeMemory(unicodeString);
@throw e;
}
j = 0;
for (i = 0; i < unicodeLen; i++) {
size_t d;
- if ((d = of_string_utf8_encode(unicodeString[i],
+ if ((d = OFUTF8StringEncode(unicodeString[i],
newCString + j)) == 0) {
- free(unicodeString);
- free(newCString);
+ OFFreeMemory(unicodeString);
+ OFFreeMemory(newCString);
@throw [OFInvalidEncodingException exception];
}
j += d;
}
assert(j == newCStringLength);
newCString[j] = 0;
- free(unicodeString);
+ OFFreeMemory(unicodeString);
- free(_s->cString);
- _s->hashed = false;
+ OFFreeMemory(_s->cString);
+ _s->hasHash = false;
_s->cString = newCString;
_s->cStringLength = newCStringLength;
/*
* Even though cStringLength can change, length cannot, therefore no
@@ -187,44 +187,44 @@
* need to change it.
*/
}
#endif
-- (void)setCharacter: (of_unichar_t)character atIndex: (size_t)idx
+- (void)setCharacter: (OFUnichar)character atIndex: (size_t)idx
{
char buffer[4];
- of_unichar_t c;
+ OFUnichar c;
size_t lenNew;
ssize_t lenOld;
if (_s->isUTF8)
- idx = of_string_utf8_get_position(_s->cString, idx,
+ idx = OFUTF8StringIndexToPosition(_s->cString, idx,
_s->cStringLength);
if (idx >= _s->cStringLength)
@throw [OFOutOfRangeException exception];
/* Shortcut if old and new character both are ASCII */
if (character < 0x80 && !(_s->cString[idx] & 0x80)) {
- _s->hashed = false;
+ _s->hasHash = false;
_s->cString[idx] = character;
return;
}
- if ((lenNew = of_string_utf8_encode(character, buffer)) == 0)
+ if ((lenNew = OFUTF8StringEncode(character, buffer)) == 0)
@throw [OFInvalidEncodingException exception];
- if ((lenOld = of_string_utf8_decode(_s->cString + idx,
+ if ((lenOld = OFUTF8StringDecode(_s->cString + idx,
_s->cStringLength - idx, &c)) <= 0)
@throw [OFInvalidEncodingException exception];
- _s->hashed = false;
+ _s->hasHash = false;
if (lenNew == (size_t)lenOld)
memcpy(_s->cString + idx, buffer, lenNew);
else if (lenNew > (size_t)lenOld) {
- _s->cString = of_realloc(_s->cString,
+ _s->cString = OFResizeMemory(_s->cString,
_s->cStringLength - lenOld + lenNew + 1, 1);
memmove(_s->cString + idx + lenNew, _s->cString + idx + lenOld,
_s->cStringLength - idx - lenOld);
memcpy(_s->cString + idx, buffer, lenNew);
@@ -246,11 +246,11 @@
if (character >= 0x80)
_s->isUTF8 = true;
@try {
- _s->cString = of_realloc(_s->cString,
+ _s->cString = OFResizeMemory(_s->cString,
_s->cStringLength + 1, 1);
} @catch (OFOutOfMemoryException *e) {
/* We don't really care, as we only made it smaller */
}
}
@@ -265,20 +265,20 @@
memcmp(UTF8String, "\xEF\xBB\xBF", 3) == 0) {
UTF8String += 3;
UTF8StringLength -= 3;
}
- switch (of_string_utf8_check(UTF8String, UTF8StringLength, &length)) {
+ switch (OFUTF8StringCheck(UTF8String, UTF8StringLength, &length)) {
case 1:
_s->isUTF8 = true;
break;
case -1:
@throw [OFInvalidEncodingException exception];
}
- _s->hashed = false;
- _s->cString = of_realloc(_s->cString,
+ _s->hasHash = false;
+ _s->cString = OFResizeMemory(_s->cString,
_s->cStringLength + UTF8StringLength + 1, 1);
memcpy(_s->cString + _s->cStringLength, UTF8String,
UTF8StringLength + 1);
_s->cStringLength += UTF8StringLength;
@@ -294,20 +294,20 @@
memcmp(UTF8String, "\xEF\xBB\xBF", 3) == 0) {
UTF8String += 3;
UTF8StringLength -= 3;
}
- switch (of_string_utf8_check(UTF8String, UTF8StringLength, &length)) {
+ switch (OFUTF8StringCheck(UTF8String, UTF8StringLength, &length)) {
case 1:
_s->isUTF8 = true;
break;
case -1:
@throw [OFInvalidEncodingException exception];
}
- _s->hashed = false;
- _s->cString = of_realloc(_s->cString,
+ _s->hasHash = false;
+ _s->cString = OFResizeMemory(_s->cString,
_s->cStringLength + UTF8StringLength + 1, 1);
memcpy(_s->cString + _s->cStringLength, UTF8String, UTF8StringLength);
_s->cStringLength += UTF8StringLength;
_s->length += length;
@@ -314,22 +314,22 @@
_s->cString[_s->cStringLength] = 0;
}
- (void)appendCString: (const char *)cString
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
[self appendCString: cString
encoding: encoding
length: strlen(cString)];
}
- (void)appendCString: (const char *)cString
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
length: (size_t)cStringLength
{
- if (encoding == OF_STRING_ENCODING_UTF_8)
+ if (encoding == OFStringEncodingUTF8)
[self appendUTF8String: cString length: cStringLength];
else {
void *pool = objc_autoreleasePoolPush();
[self appendString:
@@ -348,12 +348,12 @@
if (string == nil)
@throw [OFInvalidArgumentException exception];
UTF8StringLength = string.UTF8StringLength;
- _s->hashed = false;
- _s->cString = of_realloc(_s->cString,
+ _s->hasHash = false;
+ _s->cString = OFResizeMemory(_s->cString,
_s->cStringLength + UTF8StringLength + 1, 1);
memcpy(_s->cString + _s->cStringLength, string.UTF8String,
UTF8StringLength);
_s->cStringLength += UTF8StringLength;
@@ -367,22 +367,20 @@
_s->isUTF8 = true;
} else
_s->isUTF8 = true;
}
-- (void)appendCharacters: (const of_unichar_t *)characters
- length: (size_t)length
+- (void)appendCharacters: (const OFUnichar *)characters length: (size_t)length
{
- char *tmp = of_alloc((length * 4) + 1, 1);
+ char *tmp = OFAllocMemory((length * 4) + 1, 1);
@try {
size_t j = 0;
bool isUTF8 = false;
for (size_t i = 0; i < length; i++) {
- size_t len = of_string_utf8_encode(characters[i],
- tmp + j);
+ size_t len = OFUTF8StringEncode(characters[i], tmp + j);
if (len == 0)
@throw [OFInvalidEncodingException exception];
if (len > 1)
@@ -391,22 +389,22 @@
j += len;
}
tmp[j] = '\0';
- _s->hashed = false;
- _s->cString = of_realloc(_s->cString,
+ _s->hasHash = false;
+ _s->cString = OFResizeMemory(_s->cString,
_s->cStringLength + j + 1, 1);
memcpy(_s->cString + _s->cStringLength, tmp, j + 1);
_s->cStringLength += j;
_s->length += length;
if (isUTF8)
_s->isUTF8 = true;
} @finally {
- free(tmp);
+ OFFreeMemory(tmp);
}
}
- (void)appendFormat: (OFConstantString *)format arguments: (va_list)arguments
{
@@ -414,11 +412,11 @@
int UTF8StringLength;
if (format == nil)
@throw [OFInvalidArgumentException exception];
- if ((UTF8StringLength = of_vasprintf(&UTF8String, format.UTF8String,
+ if ((UTF8StringLength = OFVASPrintF(&UTF8String, format.UTF8String,
arguments)) == -1)
@throw [OFInvalidFormatException exception];
@try {
[self appendUTF8String: UTF8String length: UTF8StringLength];
@@ -429,11 +427,11 @@
- (void)reverse
{
size_t i, j;
- _s->hashed = false;
+ _s->hasHash = false;
/* We reverse all bytes and restore UTF-8 later, if necessary */
for (i = 0, j = _s->cStringLength - 1; i < _s->cStringLength / 2;
i++, j--) {
_s->cString[i] ^= _s->cString[j];
@@ -513,16 +511,16 @@
if (idx > _s->length)
@throw [OFOutOfRangeException exception];
if (_s->isUTF8)
- idx = of_string_utf8_get_position(_s->cString, idx,
+ idx = OFUTF8StringIndexToPosition(_s->cString, idx,
_s->cStringLength);
newCStringLength = _s->cStringLength + string.UTF8StringLength;
- _s->hashed = false;
- _s->cString = of_realloc(_s->cString, newCStringLength + 1, 1);
+ _s->hasHash = false;
+ _s->cString = OFResizeMemory(_s->cString, newCStringLength + 1, 1);
memmove(_s->cString + idx + string.UTF8StringLength,
_s->cString + idx, _s->cStringLength - idx);
memcpy(_s->cString + idx, string.UTF8String,
string.UTF8StringLength);
@@ -537,40 +535,41 @@
_s->isUTF8 = true;
} else
_s->isUTF8 = true;
}
-- (void)deleteCharactersInRange: (of_range_t)range
+- (void)deleteCharactersInRange: (OFRange)range
{
size_t start = range.location;
size_t end = range.location + range.length;
if (range.length > SIZE_MAX - range.location || end > _s->length)
@throw [OFOutOfRangeException exception];
if (_s->isUTF8) {
- start = of_string_utf8_get_position(_s->cString, start,
+ start = OFUTF8StringIndexToPosition(_s->cString, start,
_s->cStringLength);
- end = of_string_utf8_get_position(_s->cString, end,
+ end = OFUTF8StringIndexToPosition(_s->cString, end,
_s->cStringLength);
}
memmove(_s->cString + start, _s->cString + end,
_s->cStringLength - end);
- _s->hashed = false;
+ _s->hasHash = false;
_s->length -= range.length;
_s->cStringLength -= end - start;
_s->cString[_s->cStringLength] = 0;
@try {
- _s->cString = of_realloc(_s->cString, _s->cStringLength + 1, 1);
+ _s->cString = OFResizeMemory(_s->cString, _s->cStringLength + 1,
+ 1);
} @catch (OFOutOfMemoryException *e) {
/* We don't really care, as we only made it smaller */
}
}
-- (void)replaceCharactersInRange: (of_range_t)range
+- (void)replaceCharactersInRange: (OFRange)range
withString: (OFString *)replacement
{
size_t start = range.location;
size_t end = range.location + range.length;
size_t newCStringLength, newLength;
@@ -582,19 +581,19 @@
@throw [OFOutOfRangeException exception];
newLength = _s->length - range.length + replacement.length;
if (_s->isUTF8) {
- start = of_string_utf8_get_position(_s->cString, start,
+ start = OFUTF8StringIndexToPosition(_s->cString, start,
_s->cStringLength);
- end = of_string_utf8_get_position(_s->cString, end,
+ end = OFUTF8StringIndexToPosition(_s->cString, end,
_s->cStringLength);
}
newCStringLength = _s->cStringLength - (end - start) +
replacement.UTF8StringLength;
- _s->hashed = false;
+ _s->hasHash = false;
/*
* If the new string is bigger, we need to resize it first so we can
* memmove() the rest of the string to the end.
*
@@ -601,11 +600,12 @@
* We must not resize the string if the new string is smaller, because
* then we can't memmove() the rest of the string forward as the rest is
* lost due to the resize!
*/
if (newCStringLength > _s->cStringLength)
- _s->cString = of_realloc(_s->cString, newCStringLength + 1, 1);
+ _s->cString = OFResizeMemory(_s->cString, newCStringLength + 1,
+ 1);
memmove(_s->cString + start + replacement.UTF8StringLength,
_s->cString + end, _s->cStringLength - end);
memcpy(_s->cString + start, replacement.UTF8String,
replacement.UTF8StringLength);
@@ -614,11 +614,12 @@
/*
* If the new string is smaller, we can safely resize it now as we're
* done with memmove().
*/
if (newCStringLength < _s->cStringLength)
- _s->cString = of_realloc(_s->cString, newCStringLength + 1, 1);
+ _s->cString = OFResizeMemory(_s->cString, newCStringLength + 1,
+ 1);
_s->cStringLength = newCStringLength;
_s->length = newLength;
if ([replacement isKindOfClass: [OFUTF8String class]] ||
@@ -630,11 +631,11 @@
}
- (void)replaceOccurrencesOfString: (OFString *)string
withString: (OFString *)replacement
options: (int)options
- range: (of_range_t)range
+ range: (OFRange)range
{
const char *searchString = string.UTF8String;
const char *replacementString = replacement.UTF8String;
size_t searchLength = string.UTF8StringLength;
size_t replacementLength = replacement.UTF8StringLength;
@@ -647,13 +648,13 @@
if (range.length > SIZE_MAX - range.location ||
range.location + range.length > self.length)
@throw [OFOutOfRangeException exception];
if (_s->isUTF8) {
- range.location = of_string_utf8_get_position(_s->cString,
+ range.location = OFUTF8StringIndexToPosition(_s->cString,
range.location, _s->cStringLength);
- range.length = of_string_utf8_get_position(
+ range.length = OFUTF8StringIndexToPosition(
_s->cString + range.location, range.length,
_s->cStringLength - range.location);
}
if (string.UTF8StringLength > range.length)
@@ -667,15 +668,15 @@
for (size_t i = range.location; i <= range.length - searchLength; i++) {
if (memcmp(_s->cString + i, searchString, searchLength) != 0)
continue;
@try {
- newCString = of_realloc(newCString,
+ newCString = OFResizeMemory(newCString,
newCStringLength + i - last + replacementLength + 1,
1);
} @catch (id e) {
- free(newCString);
+ OFFreeMemory(newCString);
@throw e;
}
memcpy(newCString + newCStringLength, _s->cString + last,
i - last);
memcpy(newCString + newCStringLength + i - last,
@@ -687,23 +688,23 @@
i += searchLength - 1;
last = i + 1;
}
@try {
- newCString = of_realloc(newCString,
+ newCString = OFResizeMemory(newCString,
newCStringLength + _s->cStringLength - last + 1, 1);
} @catch (id e) {
- free(newCString);
+ OFFreeMemory(newCString);
@throw e;
}
memcpy(newCString + newCStringLength, _s->cString + last,
_s->cStringLength - last);
newCStringLength += _s->cStringLength - last;
newCString[newCStringLength] = 0;
- free(_s->cString);
- _s->hashed = false;
+ OFFreeMemory(_s->cString);
+ _s->hasHash = false;
_s->cString = newCString;
_s->cStringLength = newCStringLength;
_s->length = newLength;
if ([replacement isKindOfClass: [OFUTF8String class]] ||
@@ -717,22 +718,23 @@
- (void)deleteLeadingWhitespaces
{
size_t i;
for (i = 0; i < _s->cStringLength; i++)
- if (!of_ascii_isspace(_s->cString[i]))
+ if (!OFASCIIIsSpace(_s->cString[i]))
break;
- _s->hashed = false;
+ _s->hasHash = false;
_s->cStringLength -= i;
_s->length -= i;
memmove(_s->cString, _s->cString + i, _s->cStringLength);
_s->cString[_s->cStringLength] = '\0';
@try {
- _s->cString = of_realloc(_s->cString, _s->cStringLength + 1, 1);
+ _s->cString = OFResizeMemory(_s->cString, _s->cStringLength + 1,
+ 1);
} @catch (OFOutOfMemoryException *e) {
/* We don't really care, as we only made it smaller */
}
}
@@ -739,15 +741,15 @@
- (void)deleteTrailingWhitespaces
{
size_t d;
char *p;
- _s->hashed = false;
+ _s->hasHash = false;
d = 0;
for (p = _s->cString + _s->cStringLength - 1; p >= _s->cString; p--) {
- if (!of_ascii_isspace(*p))
+ if (!OFASCIIIsSpace(*p))
break;
*p = '\0';
d++;
}
@@ -754,11 +756,12 @@
_s->cStringLength -= d;
_s->length -= d;
@try {
- _s->cString = of_realloc(_s->cString, _s->cStringLength + 1, 1);
+ _s->cString = OFResizeMemory(_s->cString, _s->cStringLength + 1,
+ 1);
} @catch (OFOutOfMemoryException *e) {
/* We don't really care, as we only made it smaller */
}
}
@@ -765,15 +768,15 @@
- (void)deleteEnclosingWhitespaces
{
size_t d, i;
char *p;
- _s->hashed = false;
+ _s->hasHash = false;
d = 0;
for (p = _s->cString + _s->cStringLength - 1; p >= _s->cString; p--) {
- if (!of_ascii_isspace(*p))
+ if (!OFASCIIIsSpace(*p))
break;
*p = '\0';
d++;
}
@@ -780,21 +783,22 @@
_s->cStringLength -= d;
_s->length -= d;
for (i = 0; i < _s->cStringLength; i++)
- if (!of_ascii_isspace(_s->cString[i]))
+ if (!OFASCIIIsSpace(_s->cString[i]))
break;
_s->cStringLength -= i;
_s->length -= i;
memmove(_s->cString, _s->cString + i, _s->cStringLength);
_s->cString[_s->cStringLength] = '\0';
@try {
- _s->cString = of_realloc(_s->cString, _s->cStringLength + 1, 1);
+ _s->cString = OFResizeMemory(_s->cString, _s->cStringLength + 1,
+ 1);
} @catch (OFOutOfMemoryException *e) {
/* We don't really care, as we only made it smaller */
}
}
Index: src/OFMutableZIPArchiveEntry.h
==================================================================
--- src/OFMutableZIPArchiveEntry.h
+++ src/OFMutableZIPArchiveEntry.h
@@ -50,22 +50,24 @@
/**
* @brief The version which made the entry.
*
* The lower 8 bits are the ZIP specification version.@n
* The upper 8 bits are the attribute compatibility.
- * See @ref of_zip_archive_entry_attribute_compatibility.
+ * See @ref OFZIPArchiveEntryAttributeCompatibility.
*/
-@property (readwrite, nonatomic) uint16_t versionMadeBy;
+@property (readwrite, nonatomic)
+ OFZIPArchiveEntryAttributeCompatibility versionMadeBy;
/**
* @brief The minimum version required to extract the file.
*
* The lower 8 bits are the ZIP specification version.@n
* The upper 8 bits are the attribute compatibility.
- * See @ref of_zip_archive_entry_attribute_compatibility.
+ * See @ref OFZIPArchiveEntryAttributeCompatibility.
*/
-@property (readwrite, nonatomic) uint16_t minVersionNeeded;
+@property (readwrite, nonatomic)
+ OFZIPArchiveEntryAttributeCompatibility minVersionNeeded;
/**
* @brief The last modification date of the entry's file.
*
* @note Due to limitations of the ZIP format, this has only 2 second precision.
@@ -74,19 +76,20 @@
/**
* @brief The compression method of the entry.
*
* Supported values are:
- * Value | Description
- * --------------------------------------------------|---------------
- * OF_ZIP_ARCHIVE_ENTRY_COMPRESSION_METHOD_NONE | No compression
- * OF_ZIP_ARCHIVE_ENTRY_COMPRESSION_METHOD_DEFLATE | Deflate
- * OF_ZIP_ARCHIVE_ENTRY_COMPRESSION_METHOD_DEFLATE64 | Deflate64
+ * Value | Description
+ * --------------------------------------------|---------------
+ * OFZIPArchiveEntryCompressionMethodNone | No compression
+ * OFZIPArchiveEntryCompressionMethodDeflate | Deflate
+ * OFZIPArchiveEntryCompressionMethodDeflate64 | Deflate64
*
* Other values may be returned, but the file cannot be extracted then.
*/
-@property (readwrite, nonatomic) uint16_t compressionMethod;
+@property (readwrite, nonatomic)
+ OFZIPArchiveEntryCompressionMethod compressionMethod;
/**
* @brief The compressed size of the entry's file.
*/
@property (readwrite, nonatomic) uint64_t compressedSize;
Index: src/OFMutableZIPArchiveEntry.m
==================================================================
--- src/OFMutableZIPArchiveEntry.m
+++ src/OFMutableZIPArchiveEntry.m
@@ -83,16 +83,18 @@
[old release];
objc_autoreleasePoolPop(pool);
}
-- (void)setVersionMadeBy: (uint16_t)versionMadeBy
+- (void)setVersionMadeBy:
+ (OFZIPArchiveEntryAttributeCompatibility)versionMadeBy
{
_versionMadeBy = versionMadeBy;
}
-- (void)setMinVersionNeeded: (uint16_t)minVersionNeeded
+- (void)setMinVersionNeeded:
+ (OFZIPArchiveEntryAttributeCompatibility)minVersionNeeded
{
_minVersionNeeded = minVersionNeeded;
}
- (void)setModificationDate: (OFDate *)date
@@ -106,11 +108,12 @@
((date.localMinute & 0x3F) << 5) | ((date.second >> 1) & 0x0F);
objc_autoreleasePoolPop(pool);
}
-- (void)setCompressionMethod: (uint16_t)compressionMethod
+- (void)setCompressionMethod:
+ (OFZIPArchiveEntryCompressionMethod)compressionMethod
{
_compressionMethod = compressionMethod;
}
- (void)setCompressedSize: (uint64_t)compressedSize
Index: src/OFMutex.h
==================================================================
--- src/OFMutex.h
+++ src/OFMutex.h
@@ -13,12 +13,11 @@
* file.
*/
#import "OFObject.h"
#import "OFLocking.h"
-
-#import "mutex.h"
+#import "OFPlainMutex.h"
OF_ASSUME_NONNULL_BEGIN
/**
* @class OFMutex OFMutex.h ObjFW/OFMutex.h
@@ -25,11 +24,11 @@
*
* @brief A class for creating mutual exclusions.
*/
@interface OFMutex: OFObject
{
- of_mutex_t _mutex;
+ OFPlainMutex _mutex;
bool _initialized;
OFString *_Nullable _name;
OF_RESERVE_IVARS(OFMutex, 4)
}
Index: src/OFMutex.m
==================================================================
--- src/OFMutex.m
+++ src/OFMutex.m
@@ -35,11 +35,11 @@
- (instancetype)init
{
self = [super init];
- if (of_mutex_new(&_mutex) != 0) {
+ if (OFPlainMutexNew(&_mutex) != 0) {
Class c = self.class;
[self release];
@throw [OFInitializationFailedException exceptionWithClass: c];
}
@@ -49,14 +49,14 @@
}
- (void)dealloc
{
if (_initialized) {
- int error = of_mutex_free(&_mutex);
+ int error = OFPlainMutexFree(&_mutex);
if (error != 0) {
- OF_ENSURE(error == EBUSY);
+ OFEnsure(error == EBUSY);
@throw [OFStillLockedException exceptionWithLock: self];
}
}
@@ -65,20 +65,20 @@
[super dealloc];
}
- (void)lock
{
- int error = of_mutex_lock(&_mutex);
+ int error = OFPlainMutexLock(&_mutex);
if (error != 0)
@throw [OFLockFailedException exceptionWithLock: self
errNo: error];
}
- (bool)tryLock
{
- int error = of_mutex_trylock(&_mutex);
+ int error = OFPlainMutexTryLock(&_mutex);
if (error != 0) {
if (error == EBUSY)
return false;
else
@@ -89,11 +89,11 @@
return true;
}
- (void)unlock
{
- int error = of_mutex_unlock(&_mutex);
+ int error = OFPlainMutexUnlock(&_mutex);
if (error != 0)
@throw [OFUnlockFailedException exceptionWithLock: self
errNo: error];
}
Index: src/OFNonretainedObjectValue.h
==================================================================
--- src/OFNonretainedObjectValue.h
+++ src/OFNonretainedObjectValue.h
@@ -19,8 +19,10 @@
@interface OFNonretainedObjectValue: OFValue
{
id _object;
}
+
+- (instancetype)initWithNonretainedObject: (id)object;
@end
OF_ASSUME_NONNULL_END
Index: src/OFNull.m
==================================================================
--- src/OFNull.m
+++ src/OFNull.m
@@ -21,12 +21,13 @@
#import "OFData.h"
#import "OFInvalidArgumentException.h"
@interface OFNull ()
-- (OFString *)of_JSONRepresentationWithOptions: (int)options
- depth: (size_t)depth;
+- (OFString *)
+ of_JSONRepresentationWithOptions: (OFJSONRepresentationOptions)options
+ depth: (size_t)depth;
@end
static OFNull *null = nil;
@implementation OFNull
@@ -47,11 +48,11 @@
[self release];
pool = objc_autoreleasePoolPush();
if (![element.name isEqual: self.className] ||
- ![element.namespace isEqual: OF_SERIALIZATION_NS])
+ ![element.namespace isEqual: OFSerializationNS])
@throw [OFInvalidArgumentException exception];
objc_autoreleasePoolPop(pool);
return [OFNull null];
@@ -71,11 +72,11 @@
{
void *pool = objc_autoreleasePoolPush();
OFXMLElement *element;
element = [OFXMLElement elementWithName: self.className
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
[element retain];
objc_autoreleasePoolPop(pool);
@@ -85,16 +86,18 @@
- (OFString *)JSONRepresentation
{
return [self of_JSONRepresentationWithOptions: 0 depth: 0];
}
-- (OFString *)JSONRepresentationWithOptions: (int)options
+- (OFString *)JSONRepresentationWithOptions:
+ (OFJSONRepresentationOptions)options
{
return [self of_JSONRepresentationWithOptions: options depth: 0];
}
-- (OFString *)of_JSONRepresentationWithOptions: (int)options
+- (OFString *)
+ of_JSONRepresentationWithOptions: (OFJSONRepresentationOptions)options
depth: (size_t)depth
{
return @"null";
}
@@ -118,13 +121,13 @@
{
}
- (unsigned int)retainCount
{
- return OF_RETAIN_COUNT_MAX;
+ return OFMaxRetainCount;
}
- (void)dealloc
{
OF_DEALLOC_UNSUPPORTED
}
@end
Index: src/OFNumber.h
==================================================================
--- src/OFNumber.h
+++ src/OFNumber.h
@@ -44,11 +44,11 @@
OF_SUBCLASSING_RESTRICTED
#endif
@interface OFNumber: OFValue
{
- union of_number_value {
+ union {
double float_;
long long signed_;
unsigned long long unsigned_;
} _value;
const char *_typeEncoding;
@@ -127,14 +127,14 @@
#ifdef OF_HAVE_UNAVAILABLE
+ (instancetype)valueWithBytes: (const void *)bytes
objCType: (const char *)objCType OF_UNAVAILABLE;
+ (instancetype)valueWithPointer: (const void *)pointer OF_UNAVAILABLE;
+ (instancetype)valueWithNonretainedObject: (id)object OF_UNAVAILABLE;
-+ (instancetype)valueWithRange: (of_range_t)range OF_UNAVAILABLE;
-+ (instancetype)valueWithPoint: (of_point_t)point OF_UNAVAILABLE;
-+ (instancetype)valueWithDimension: (of_dimension_t)dimension OF_UNAVAILABLE;
-+ (instancetype)valueWithRectangle: (of_rectangle_t)rectangle OF_UNAVAILABLE;
++ (instancetype)valueWithRange: (OFRange)range OF_UNAVAILABLE;
++ (instancetype)valueWithPoint: (OFPoint)point OF_UNAVAILABLE;
++ (instancetype)valueWithSize: (OFSize)size OF_UNAVAILABLE;
++ (instancetype)valueWithRect: (OFRect)rect OF_UNAVAILABLE;
#endif
/**
* @brief Creates a new OFNumber with the specified `bool`.
*
@@ -241,16 +241,10 @@
- (instancetype)init OF_UNAVAILABLE;
#ifdef OF_HAVE_UNAVAILABLE
- (instancetype)initWithBytes: (const void *)bytes
objCType: (const char *)objCType OF_UNAVAILABLE;
-- (instancetype)initWithPointer: (const void *)pointer OF_UNAVAILABLE;
-- (instancetype)initWithNonretainedObject: (id)object OF_UNAVAILABLE;
-- (instancetype)initWithRange: (of_range_t)range OF_UNAVAILABLE;
-- (instancetype)initWithPoint: (of_point_t)point OF_UNAVAILABLE;
-- (instancetype)initWithDimension: (of_dimension_t)dimension OF_UNAVAILABLE;
-- (instancetype)initWithRectangle: (of_rectangle_t)rectangle OF_UNAVAILABLE;
#endif
/**
* @brief Initializes an already allocated OFNumber with the specified `bool`.
*
@@ -366,14 +360,14 @@
* @brief Compares the number to another number.
*
* @param number The number to compare the number to
* @return The result of the comparison
*/
-- (of_comparison_result_t)compare: (OFNumber *)number;
+- (OFComparisonResult)compare: (OFNumber *)number;
@end
OF_ASSUME_NONNULL_END
#if !defined(NSINTEGER_DEFINED) && !__has_feature(modules)
/* Required for number literals to work */
@compatibility_alias NSNumber OFNumber;
#endif
Index: src/OFNumber.m
==================================================================
--- src/OFNumber.m
+++ src/OFNumber.m
@@ -29,35 +29,36 @@
#import "OFInvalidFormatException.h"
#import "OFOutOfRangeException.h"
@interface OFNumber ()
+ (instancetype)of_alloc;
-- (OFString *)of_JSONRepresentationWithOptions: (int)options
- depth: (size_t)depth;
+- (OFString *)
+ of_JSONRepresentationWithOptions: (OFJSONRepresentationOptions)options
+ depth: (size_t)depth;
@end
@interface OFNumberPlaceholder: OFNumber
@end
@interface OFNumberSingleton: OFNumber
@end
#ifdef OF_OBJFW_RUNTIME
-enum {
- TAG_CHAR,
- TAG_SHORT,
- TAG_INT,
- TAG_LONG,
- TAG_LONG_LONG,
- TAG_UNSIGNED_CHAR,
- TAG_UNSIGNED_SHORT,
- TAG_UNSIGNED_INT,
- TAG_UNSIGNED_LONG,
- TAG_UNSIGNED_LONG_LONG,
+enum Tag {
+ tagChar,
+ tagShort,
+ tagInt,
+ tagLong,
+ tagLongLong,
+ tagUnsignedChar,
+ tagUnsignedShort,
+ tagUnsignedInt,
+ tagUnsignedLong,
+ tagUnsignedLongLong,
};
-# define TAG_BITS 4
-# define TAG_MASK 0xF
+static const uint_fast8_t tagBits = 4;
+static const uintptr_t tagMask = 0xF;
@interface OFTaggedPointerNumber: OFNumberSingleton
@end
#endif
@@ -148,16 +149,16 @@
@implementation OFNumberPlaceholder
- (instancetype)initWithBool: (bool)value
{
if (value) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, trueNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, trueNumberInit);
return (id)trueNumber;
} else {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, falseNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, falseNumberInit);
return (id)falseNumber;
}
}
#ifdef __clang__
@@ -165,17 +166,17 @@
# pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare"
#endif
- (instancetype)initWithChar: (signed char)value
{
if (value == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, charZeroNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, charZeroNumberInit);
return (id)charZeroNumber;
#ifdef OF_OBJFW_RUNTIME
- } else if ((unsigned char)value <= (UINTPTR_MAX >> TAG_BITS)) {
+ } else if ((unsigned char)value <= (UINTPTR_MAX >> tagBits)) {
id ret = objc_createTaggedPointer(numberTag,
- ((uintptr_t)(unsigned char)value << TAG_BITS) | TAG_CHAR);
+ ((uintptr_t)(unsigned char)value << tagBits) | tagChar);
if (ret != nil)
return ret;
#endif
}
@@ -184,17 +185,17 @@
}
- (instancetype)initWithShort: (short)value
{
if (value == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, shortZeroNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, shortZeroNumberInit);
return (id)shortZeroNumber;
#ifdef OF_OBJFW_RUNTIME
- } else if ((unsigned short)value <= (UINTPTR_MAX >> TAG_BITS)) {
+ } else if ((unsigned short)value <= (UINTPTR_MAX >> tagBits)) {
id ret = objc_createTaggedPointer(numberTag,
- ((uintptr_t)(unsigned short)value << TAG_BITS) | TAG_SHORT);
+ ((uintptr_t)(unsigned short)value << tagBits) | tagShort);
if (ret != nil)
return ret;
#endif
}
@@ -203,17 +204,17 @@
}
- (instancetype)initWithInt: (int)value
{
if (value == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, intZeroNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, intZeroNumberInit);
return (id)intZeroNumber;
#ifdef OF_OBJFW_RUNTIME
- } else if ((unsigned int)value <= (UINTPTR_MAX >> TAG_BITS)) {
+ } else if ((unsigned int)value <= (UINTPTR_MAX >> tagBits)) {
id ret = objc_createTaggedPointer(numberTag,
- ((uintptr_t)(unsigned int)value << TAG_BITS) | TAG_INT);
+ ((uintptr_t)(unsigned int)value << tagBits) | tagInt);
if (ret != nil)
return ret;
#endif
}
@@ -222,17 +223,17 @@
}
- (instancetype)initWithLong: (long)value
{
if (value == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, longZeroNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, longZeroNumberInit);
return (id)longZeroNumber;
#ifdef OF_OBJFW_RUNTIME
- } else if ((unsigned long)value <= (UINTPTR_MAX >> TAG_BITS)) {
+ } else if ((unsigned long)value <= (UINTPTR_MAX >> tagBits)) {
id ret = objc_createTaggedPointer(numberTag,
- ((uintptr_t)(unsigned long)value << TAG_BITS) | TAG_LONG);
+ ((uintptr_t)(unsigned long)value << tagBits) | tagLong);
if (ret != nil)
return ret;
#endif
}
@@ -241,18 +242,18 @@
}
- (instancetype)initWithLongLong: (long long)value
{
if (value == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, longLongZeroNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, longLongZeroNumberInit);
return (id)longLongZeroNumber;
#ifdef OF_OBJFW_RUNTIME
- } else if ((unsigned long long)value <= (UINTPTR_MAX >> TAG_BITS)) {
+ } else if ((unsigned long long)value <= (UINTPTR_MAX >> tagBits)) {
id ret = objc_createTaggedPointer(numberTag,
- ((uintptr_t)(unsigned long long)value << TAG_BITS) |
- TAG_LONG_LONG);
+ ((uintptr_t)(unsigned long long)value << tagBits) |
+ tagLongLong);
if (ret != nil)
return ret;
#endif
}
@@ -261,17 +262,17 @@
}
- (instancetype)initWithUnsignedChar: (unsigned char)value
{
if (value == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, unsignedCharZeroNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, unsignedCharZeroNumberInit);
return (id)unsignedCharZeroNumber;
#ifdef OF_OBJFW_RUNTIME
- } else if (value <= (UINTPTR_MAX >> TAG_BITS)) {
+ } else if (value <= (UINTPTR_MAX >> tagBits)) {
id ret = objc_createTaggedPointer(numberTag,
- ((uintptr_t)value << TAG_BITS) | TAG_UNSIGNED_CHAR);
+ ((uintptr_t)value << tagBits) | tagUnsignedChar);
if (ret != nil)
return ret;
#endif
}
@@ -280,17 +281,17 @@
}
- (instancetype)initWithUnsignedShort: (unsigned short)value
{
if (value == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, unsignedShortZeroNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, unsignedShortZeroNumberInit);
return (id)unsignedShortZeroNumber;
#ifdef OF_OBJFW_RUNTIME
- } else if (value <= (UINTPTR_MAX >> TAG_BITS)) {
+ } else if (value <= (UINTPTR_MAX >> tagBits)) {
id ret = objc_createTaggedPointer(numberTag,
- ((uintptr_t)value << TAG_BITS) | TAG_UNSIGNED_SHORT);
+ ((uintptr_t)value << tagBits) | tagUnsignedShort);
if (ret != nil)
return ret;
#endif
}
@@ -299,17 +300,17 @@
}
- (instancetype)initWithUnsignedInt: (unsigned int)value
{
if (value == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, unsignedIntZeroNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, unsignedIntZeroNumberInit);
return (id)unsignedIntZeroNumber;
#ifdef OF_OBJFW_RUNTIME
- } else if (value <= (UINTPTR_MAX >> TAG_BITS)) {
+ } else if (value <= (UINTPTR_MAX >> tagBits)) {
id ret = objc_createTaggedPointer(numberTag,
- ((uintptr_t)value << TAG_BITS) | TAG_UNSIGNED_INT);
+ ((uintptr_t)value << tagBits) | tagUnsignedInt);
if (ret != nil)
return ret;
#endif
}
@@ -318,17 +319,17 @@
}
- (instancetype)initWithUnsignedLong: (unsigned long)value
{
if (value == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, unsignedLongZeroNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, unsignedLongZeroNumberInit);
return (id)unsignedLongZeroNumber;
#ifdef OF_OBJFW_RUNTIME
- } else if (value <= (UINTPTR_MAX >> TAG_BITS)) {
+ } else if (value <= (UINTPTR_MAX >> tagBits)) {
id ret = objc_createTaggedPointer(numberTag,
- ((uintptr_t)value << TAG_BITS) | TAG_UNSIGNED_LONG);
+ ((uintptr_t)value << tagBits) | tagUnsignedLong);
if (ret != nil)
return ret;
#endif
}
@@ -337,17 +338,17 @@
}
- (instancetype)initWithUnsignedLongLong: (unsigned long long)value
{
if (value == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, unsignedLongLongZeroNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, unsignedLongLongZeroNumberInit);
return (id)unsignedLongLongZeroNumber;
#ifdef OF_OBJFW_RUNTIME
- } else if (value <= (UINTPTR_MAX >> TAG_BITS)) {
+ } else if (value <= (UINTPTR_MAX >> tagBits)) {
id ret = objc_createTaggedPointer(numberTag,
- ((uintptr_t)value << TAG_BITS) | TAG_UNSIGNED_LONG_LONG);
+ ((uintptr_t)value << tagBits) | tagUnsignedLongLong);
if (ret != nil)
return ret;
#endif
}
@@ -356,23 +357,23 @@
}
- (instancetype)initWithFloat: (float)value
{
if (value == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, floatZeroNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, floatZeroNumberInit);
return (id)floatZeroNumber;
}
return (id)[[OFNumber of_alloc] initWithFloat: value];
}
- (instancetype)initWithDouble: (double)value
{
if (value == 0) {
- static of_once_t once = OF_ONCE_INIT;
- of_once(&once, doubleZeroNumberInit);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, doubleZeroNumberInit);
return (id)doubleZeroNumber;
}
return (id)[[OFNumber of_alloc] initWithDouble: value];
}
@@ -401,72 +402,72 @@
{
}
- (unsigned int)retainCount
{
- return OF_RETAIN_COUNT_MAX;
+ return OFMaxRetainCount;
}
@end
#ifdef OF_OBJFW_RUNTIME
@implementation OFTaggedPointerNumber
- (const char *)objCType
{
uintptr_t value = object_getTaggedPointerValue(self);
- switch (value & TAG_MASK) {
- case TAG_CHAR:
+ switch (value & tagMask) {
+ case tagChar:
return @encode(signed char);
- case TAG_SHORT:
+ case tagShort:
return @encode(short);
- case TAG_INT:
+ case tagInt:
return @encode(int);
- case TAG_LONG:
+ case tagLong:
return @encode(long);
- case TAG_LONG_LONG:
+ case tagLongLong:
return @encode(long long);
- case TAG_UNSIGNED_CHAR:
+ case tagUnsignedChar:
return @encode(unsigned char);
- case TAG_UNSIGNED_SHORT:
+ case tagUnsignedShort:
return @encode(unsigned short);
- case TAG_UNSIGNED_INT:
+ case tagUnsignedInt:
return @encode(unsigned int);
- case TAG_UNSIGNED_LONG:
+ case tagUnsignedLong:
return @encode(unsigned long);
- case TAG_UNSIGNED_LONG_LONG:
+ case tagUnsignedLongLong:
return @encode(unsigned long long);
default:
@throw [OFInvalidArgumentException exception];
}
}
-# define RETURN_VALUE \
- uintptr_t value = object_getTaggedPointerValue(self); \
- \
- switch (value & TAG_MASK) { \
- case TAG_CHAR: \
- return (signed char)(unsigned char)(value >> TAG_BITS); \
- case TAG_SHORT: \
- return (short)(unsigned short)(value >> TAG_BITS); \
- case TAG_INT: \
- return (int)(unsigned int)(value >> TAG_BITS); \
- case TAG_LONG: \
- return (long)(unsigned long)(value >> TAG_BITS); \
- case TAG_LONG_LONG: \
- return (long long)(unsigned long long)(value >> TAG_BITS); \
- case TAG_UNSIGNED_CHAR: \
- return (unsigned char)(value >> TAG_BITS); \
- case TAG_UNSIGNED_SHORT: \
- return (unsigned short)(value >> TAG_BITS); \
- case TAG_UNSIGNED_INT: \
- return (unsigned int)(value >> TAG_BITS); \
- case TAG_UNSIGNED_LONG: \
- return (unsigned long)(value >> TAG_BITS); \
- case TAG_UNSIGNED_LONG_LONG: \
- return (unsigned long long)(value >> TAG_BITS); \
- default: \
- @throw [OFInvalidArgumentException exception]; \
+# define RETURN_VALUE \
+ uintptr_t value = object_getTaggedPointerValue(self); \
+ \
+ switch (value & tagMask) { \
+ case tagChar: \
+ return (signed char)(unsigned char)(value >> tagBits); \
+ case tagShort: \
+ return (short)(unsigned short)(value >> tagBits); \
+ case tagInt: \
+ return (int)(unsigned int)(value >> tagBits); \
+ case tagLong: \
+ return (long)(unsigned long)(value >> tagBits); \
+ case tagLongLong: \
+ return (long long)(unsigned long long)(value >> tagBits); \
+ case tagUnsignedChar: \
+ return (unsigned char)(value >> tagBits); \
+ case tagUnsignedShort: \
+ return (unsigned short)(value >> tagBits); \
+ case tagUnsignedInt: \
+ return (unsigned int)(value >> tagBits); \
+ case tagUnsignedLong: \
+ return (unsigned long)(value >> tagBits); \
+ case tagUnsignedLongLong: \
+ return (unsigned long long)(value >> tagBits); \
+ default: \
+ @throw [OFInvalidArgumentException exception]; \
}
- (long long)longLongValue
{
RETURN_VALUE
}
@@ -748,11 +749,11 @@
@try {
void *pool = objc_autoreleasePoolPush();
OFString *typeString;
if (![element.name isEqual: @"OFNumber"] ||
- ![element.namespace isEqual: OF_SERIALIZATION_NS])
+ ![element.namespace isEqual: OFSerializationNS])
@throw [OFInvalidArgumentException exception];
typeString = [element attributeForName: @"type"].stringValue;
if ([typeString isEqual: @"bool"]) {
@@ -768,12 +769,12 @@
[element unsignedLongLongValueWithBase: 16];
if (value > UINT64_MAX)
@throw [OFOutOfRangeException exception];
- self = [self initWithDouble: OF_BSWAP_DOUBLE_IF_LE(
- OF_INT_TO_DOUBLE_RAW(OF_BSWAP64_IF_LE(value)))];
+ self = [self initWithDouble: OFFromBigEndianDouble(
+ OFRawUInt64ToDouble(OFToBigEndian64(value)))];
} else if ([typeString isEqual: @"signed"])
self = [self initWithLongLong: element.longLongValue];
else if ([typeString isEqual: @"unsigned"])
self = [self initWithUnsignedLongLong:
element.unsignedLongLongValue];
@@ -940,75 +941,75 @@
return (number.longLongValue == self.longLongValue);
return (number.unsignedLongLongValue == self.unsignedLongLongValue);
}
-- (of_comparison_result_t)compare: (OFNumber *)number
+- (OFComparisonResult)compare: (OFNumber *)number
{
if (![number isKindOfClass: [OFNumber class]])
@throw [OFInvalidArgumentException exception];
if (isFloat(self) || isFloat(number)) {
double double1 = self.doubleValue;
double double2 = number.doubleValue;
if (double1 > double2)
- return OF_ORDERED_DESCENDING;
+ return OFOrderedDescending;
if (double1 < double2)
- return OF_ORDERED_ASCENDING;
+ return OFOrderedAscending;
- return OF_ORDERED_SAME;
+ return OFOrderedSame;
} else if (isSigned(self) || isSigned(number)) {
long long int1 = self.longLongValue;
long long int2 = number.longLongValue;
if (int1 > int2)
- return OF_ORDERED_DESCENDING;
+ return OFOrderedDescending;
if (int1 < int2)
- return OF_ORDERED_ASCENDING;
+ return OFOrderedAscending;
- return OF_ORDERED_SAME;
+ return OFOrderedSame;
} else {
unsigned long long uint1 = self.unsignedLongLongValue;
unsigned long long uint2 = number.unsignedLongLongValue;
if (uint1 > uint2)
- return OF_ORDERED_DESCENDING;
+ return OFOrderedDescending;
if (uint1 < uint2)
- return OF_ORDERED_ASCENDING;
+ return OFOrderedAscending;
- return OF_ORDERED_SAME;
+ return OFOrderedSame;
}
}
- (unsigned long)hash
{
- uint32_t hash;
+ unsigned long hash;
- OF_HASH_INIT(hash);
+ OFHashInit(&hash);
if (isFloat(self)) {
double d;
if (isnan(self.doubleValue))
return 0;
- d = OF_BSWAP_DOUBLE_IF_BE(self.doubleValue);
+ d = OFToLittleEndianDouble(self.doubleValue);
for (uint_fast8_t i = 0; i < sizeof(double); i++)
- OF_HASH_ADD(hash, ((char *)&d)[i]);
+ OFHashAdd(&hash, ((char *)&d)[i]);
} else if (isSigned(self) || isUnsigned(self)) {
unsigned long long value = self.unsignedLongLongValue;
while (value != 0) {
- OF_HASH_ADD(hash, value & 0xFF);
+ OFHashAdd(&hash, value & 0xFF);
value >>= 8;
}
} else
@throw [OFInvalidFormatException exception];
- OF_HASH_FINALIZE(hash);
+ OFHashFinalize(&hash);
return hash;
}
- (id)copy
@@ -1040,20 +1041,20 @@
{
void *pool = objc_autoreleasePoolPush();
OFXMLElement *element;
element = [OFXMLElement elementWithName: @"OFNumber"
- namespace: OF_SERIALIZATION_NS
+ namespace: OFSerializationNS
stringValue: self.description];
if (*self.objCType == 'B')
[element addAttributeWithName: @"type" stringValue: @"bool"];
else if (isFloat(self)) {
[element addAttributeWithName: @"type" stringValue: @"float"];
element.stringValue = [OFString
stringWithFormat: @"%016" PRIx64,
- OF_BSWAP64_IF_LE(OF_DOUBLE_TO_INT_RAW(OF_BSWAP_DOUBLE_IF_LE(
+ OFFromBigEndian64(OFDoubleToRawUInt64(OFToBigEndianDouble(
self.doubleValue)))];
} else if (isSigned(self))
[element addAttributeWithName: @"type" stringValue: @"signed"];
else if (isUnsigned(self))
[element addAttributeWithName: @"type"
@@ -1071,26 +1072,28 @@
- (OFString *)JSONRepresentation
{
return [self of_JSONRepresentationWithOptions: 0 depth: 0];
}
-- (OFString *)JSONRepresentationWithOptions: (int)options
+- (OFString *)JSONRepresentationWithOptions:
+ (OFJSONRepresentationOptions)options
{
return [self of_JSONRepresentationWithOptions: options depth: 0];
}
-- (OFString *)of_JSONRepresentationWithOptions: (int)options
- depth: (size_t)depth
+- (OFString *)
+ of_JSONRepresentationWithOptions: (OFJSONRepresentationOptions)options
+ depth: (size_t)depth
{
double doubleValue;
if (*self.objCType == 'B')
return (self.boolValue ? @"true" : @"false");
doubleValue = self.doubleValue;
if (isinf(doubleValue)) {
- if (options & OF_JSON_REPRESENTATION_JSON5) {
+ if (options & OFJSONRepresentationOptionJSON5) {
if (doubleValue > 0)
return @"Infinity";
else
return @"-Infinity";
} else
@@ -1108,18 +1111,18 @@
if (*typeEncoding == 'B') {
uint8_t type = (self.boolValue ? 0xC3 : 0xC2);
data = [OFMutableData dataWithItems: &type count: 1];
} else if (*typeEncoding == 'f') {
uint8_t type = 0xCA;
- float tmp = OF_BSWAP_FLOAT_IF_LE(self.floatValue);
+ float tmp = OFToBigEndianFloat(self.floatValue);
data = [OFMutableData dataWithCapacity: 5];
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else if (*typeEncoding == 'd') {
uint8_t type = 0xCB;
- double tmp = OF_BSWAP_DOUBLE_IF_LE(self.doubleValue);
+ double tmp = OFToBigEndianDouble(self.doubleValue);
data = [OFMutableData dataWithCapacity: 9];
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else if (isSigned(self)) {
@@ -1136,25 +1139,25 @@
data = [OFMutableData dataWithCapacity: 2];
[data addItem: &type];
[data addItem: &tmp];
} else if (value >= INT16_MIN && value <= INT16_MAX) {
uint8_t type = 0xD1;
- int16_t tmp = OF_BSWAP16_IF_LE((int16_t)value);
+ int16_t tmp = OFToBigEndian16((int16_t)value);
data = [OFMutableData dataWithCapacity: 3];
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else if (value >= INT32_MIN && value <= INT32_MAX) {
uint8_t type = 0xD2;
- int32_t tmp = OF_BSWAP32_IF_LE((int32_t)value);
+ int32_t tmp = OFToBigEndian32((int32_t)value);
data = [OFMutableData dataWithCapacity: 5];
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else if (value >= INT64_MIN && value <= INT64_MAX) {
uint8_t type = 0xD3;
- int64_t tmp = OF_BSWAP64_IF_LE((int64_t)value);
+ int64_t tmp = OFToBigEndian64((int64_t)value);
data = [OFMutableData dataWithCapacity: 9];
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else
@@ -1172,25 +1175,25 @@
data = [OFMutableData dataWithCapacity: 2];
[data addItem: &type];
[data addItem: &tmp];
} else if (value <= UINT16_MAX) {
uint8_t type = 0xCD;
- uint16_t tmp = OF_BSWAP16_IF_LE((uint16_t)value);
+ uint16_t tmp = OFToBigEndian16((uint16_t)value);
data = [OFMutableData dataWithCapacity: 3];
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else if (value <= UINT32_MAX) {
uint8_t type = 0xCE;
- uint32_t tmp = OF_BSWAP32_IF_LE((uint32_t)value);
+ uint32_t tmp = OFToBigEndian32((uint32_t)value);
data = [OFMutableData dataWithCapacity: 5];
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else if (value <= UINT64_MAX) {
uint8_t type = 0xCF;
- uint64_t tmp = OF_BSWAP64_IF_LE((uint64_t)value);
+ uint64_t tmp = OFToBigEndian64((uint64_t)value);
data = [OFMutableData dataWithCapacity: 9];
[data addItem: &type];
[data addItems: &tmp count: sizeof(tmp)];
} else
Index: src/OFObject+KeyValueCoding.m
==================================================================
--- src/OFObject+KeyValueCoding.m
+++ src/OFObject+KeyValueCoding.m
@@ -46,21 +46,21 @@
if ((keyLength = key.UTF8StringLength) < 1) {
objc_autoreleasePoolPop(pool);
return [self valueForUndefinedKey: key];
}
- name = of_alloc(keyLength + 3, 1);
+ name = OFAllocMemory(keyLength + 3, 1);
@try {
memcpy(name, "is", 2);
memcpy(name + 2, key.UTF8String, keyLength);
name[keyLength + 2] = '\0';
- name[2] = of_ascii_toupper(name[2]);
+ name[2] = OFASCIIToUpper(name[2]);
selector = sel_registerName(name);
} @finally {
- free(name);
+ OFFreeMemory(name);
}
methodSignature = [self methodSignatureForSelector: selector];
if (methodSignature == NULL) {
@@ -155,21 +155,21 @@
objc_autoreleasePoolPop(pool);
[self setValue: value forUndefinedKey: key];
return;
}
- name = of_alloc(keyLength + 5, 1);
+ name = OFAllocMemory(keyLength + 5, 1);
@try {
memcpy(name, "set", 3);
memcpy(name + 3, key.UTF8String, keyLength);
memcpy(name + keyLength + 3, ":", 2);
- name[3] = of_ascii_toupper(name[3]);
+ name[3] = OFASCIIToUpper(name[3]);
selector = sel_registerName(name);
} @finally {
- free(name);
+ OFFreeMemory(name);
}
methodSignature = [self methodSignatureForSelector: selector];
if (methodSignature == nil ||
Index: src/OFObject+Serialization.m
==================================================================
--- src/OFObject+Serialization.m
+++ src/OFObject+Serialization.m
@@ -40,11 +40,11 @@
pool = objc_autoreleasePoolPush();
element = ((id )self).XMLElementBySerializing;
root = [OFXMLElement elementWithName: @"serialization"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
[root addAttributeWithName: @"version" stringValue: @"1"];
[root addChild: element];
ret = [@"\n"
stringByAppendingString: [root XMLStringWithIndentation: 2]];
Index: src/OFObject.h
==================================================================
--- src/OFObject.h
+++ src/OFObject.h
@@ -28,13 +28,13 @@
#include
#include
#include
#include
-#include "block.h"
#include "macros.h"
-#include "once.h"
+
+#include "OFOnce.h"
/*
* Some versions of MinGW require to be included before
* . Do this here to make sure this is always done in the correct
* order, even if another header includes just .
@@ -54,63 +54,67 @@
/**
* @brief A result of a comparison.
*/
typedef enum {
/** The left object is smaller than the right */
- OF_ORDERED_ASCENDING = -1,
+ OFOrderedAscending = -1,
/** Both objects are equal */
- OF_ORDERED_SAME = 0,
+ OFOrderedSame = 0,
/** The left object is bigger than the right */
- OF_ORDERED_DESCENDING = 1
-} of_comparison_result_t;
+ OFOrderedDescending = 1
+} OFComparisonResult;
#ifdef OF_HAVE_BLOCKS
/**
* @brief A comparator to compare two objects.
*
* @param left The left object
* @param right The right object
* @return The order of the objects
*/
-typedef of_comparison_result_t (^of_comparator_t)(id _Nonnull left,
- id _Nonnull right);
+typedef OFComparisonResult (^OFComparator)(id _Nonnull left, id _Nonnull right);
#endif
/**
- * @brief An enum for storing endianess.
+ * @brief An enum for representing endianess.
*/
typedef enum {
/** Most significant byte first (big endian) */
- OF_BYTE_ORDER_BIG_ENDIAN,
+ OFByteOrderBigEndian,
/** Least significant byte first (little endian) */
- OF_BYTE_ORDER_LITTLE_ENDIAN
-} of_byte_order_t;
+ OFByteOrderLittleEndian,
+ /** Native byte order of the system */
+#ifdef OF_BIG_ENDIAN
+ OFByteOrderNative = OFByteOrderBigEndian
+#else
+ OFByteOrderNative = OFByteOrderLittleEndian
+#endif
+} OFByteOrder;
/**
- * @struct of_range_t OFObject.h ObjFW/OFObject.h
+ * @struct OFRange OFObject.h ObjFW/OFObject.h
*
* @brief A range.
*/
-struct OF_BOXABLE of_range_t {
+typedef struct OF_BOXABLE {
/** The start of the range */
size_t location;
/** The length of the range */
size_t length;
-};
-typedef struct of_range_t of_range_t;
+} OFRange;
/**
- * @brief Creates a new of_range_t.
+ * @brief Creates a new OFRange.
*
* @param start The starting index of the range
* @param length The length of the range
- * @return An of_range with the specified start and length
+ * @return An OFRangeith the specified start and length
*/
-static OF_INLINE of_range_t OF_CONST_FUNC
-of_range(size_t start, size_t length)
+static OF_INLINE OFRange OF_CONST_FUNC
+OFRangeMake(size_t start, size_t length)
{
- of_range_t range = { start, length };
+ OFRange range = { start, length };
return range;
}
/**
@@ -119,11 +123,11 @@
* @param range1 The first range for the comparison
* @param range2 The second range for the comparison
* @return Whether the two ranges are equal
*/
static OF_INLINE bool
-of_range_equal(of_range_t range1, of_range_t range2)
+OFRangeEqual(OFRange range1, OFRange range2)
{
if (range1.location != range2.location)
return false;
if (range1.length != range2.length)
@@ -133,36 +137,35 @@
}
/**
* @brief A time interval in seconds.
*/
-typedef double of_time_interval_t;
+typedef double OFTimeInterval;
/**
- * @struct of_point_t OFObject.h ObjFW/OFObject.h
+ * @struct OFPoint OFObject.h ObjFW/OFObject.h
*
* @brief A point.
*/
-struct OF_BOXABLE of_point_t {
+typedef struct OF_BOXABLE {
/** The x coordinate of the point */
float x;
/** The y coordinate of the point */
float y;
-};
-typedef struct of_point_t of_point_t;
+} OFPoint;
/**
- * @brief Creates a new of_point_t.
+ * @brief Creates a new OFPoint.
*
* @param x The x coordinate of the point
* @param y The x coordinate of the point
- * @return An of_point_t with the specified coordinates
+ * @return An OFPoint with the specified coordinates
*/
-static OF_INLINE of_point_t OF_CONST_FUNC
-of_point(float x, float y)
+static OF_INLINE OFPoint OF_CONST_FUNC
+OFPointMake(float x, float y)
{
- of_point_t point = { x, y };
+ OFPoint point = { x, y };
return point;
}
/**
@@ -171,11 +174,11 @@
* @param point1 The first point for the comparison
* @param point2 The second point for the comparison
* @return Whether the two points are equal
*/
static OF_INLINE bool
-of_point_equal(of_point_t point1, of_point_t point2)
+OFPointEqual(OFPoint point1, OFPoint point2)
{
if (point1.x != point2.x)
return false;
if (point1.y != point2.y)
@@ -183,107 +186,157 @@
return true;
}
/**
- * @struct of_dimension_t OFObject.h ObjFW/OFObject.h
+ * @struct OFSize OFObject.h ObjFW/OFObject.h
*
- * @brief A dimension.
+ * @brief A size.
*/
-struct OF_BOXABLE of_dimension_t {
- /** The width of the dimension */
+typedef struct OF_BOXABLE {
+ /** The width of the size */
float width;
- /** The height of the dimension */
+ /** The height of the size */
float height;
-};
-typedef struct of_dimension_t of_dimension_t;
-
-/**
- * @brief Creates a new of_dimension_t.
- *
- * @param width The width of the dimension
- * @param height The height of the dimension
- * @return An of_dimension_t with the specified width and height
- */
-static OF_INLINE of_dimension_t OF_CONST_FUNC
-of_dimension(float width, float height)
-{
- of_dimension_t dimension = { width, height };
-
- return dimension;
-}
-
-/**
- * @brief Returns whether the two dimensions are equal.
- *
- * @param dimension1 The first dimension for the comparison
- * @param dimension2 The second dimension for the comparison
- * @return Whether the two dimensions are equal
+} OFSize;
+
+/**
+ * @brief Creates a new OFSize.
+ *
+ * @param width The width of the size
+ * @param height The height of the size
+ * @return An OFSize with the specified width and height
+ */
+static OF_INLINE OFSize OF_CONST_FUNC
+OFSizeMake(float width, float height)
+{
+ OFSize size = { width, height };
+
+ return size;
+}
+
+/**
+ * @brief Returns whether the two sizes are equal.
+ *
+ * @param size1 The first size for the comparison
+ * @param size2 The second size for the comparison
+ * @return Whether the two sizes are equal
+ */
+static OF_INLINE bool
+OFSizeEqual(OFSize size1, OFSize size2)
+{
+ if (size1.width != size2.width)
+ return false;
+
+ if (size1.height != size2.height)
+ return false;
+
+ return true;
+}
+
+/**
+ * @struct OFRect OFObject.h ObjFW/OFObject.h
+ *
+ * @brief A rectangle.
+ */
+typedef struct OF_BOXABLE {
+ /** The point from where the rectangle originates */
+ OFPoint origin;
+ /** The size of the rectangle */
+ OFSize size;
+} OFRect;
+
+/**
+ * @brief Creates a new OFRect.
+ *
+ * @param x The x coordinate of the top left corner of the rectangle
+ * @param y The y coordinate of the top left corner of the rectangle
+ * @param width The width of the rectangle
+ * @param height The height of the rectangle
+ * @return An OFRect with the specified origin and size
+ */
+static OF_INLINE OFRect OF_CONST_FUNC
+OFRectMake(float x, float y, float width, float height)
+{
+ OFRect rect = {
+ OFPointMake(x, y),
+ OFSizeMake(width, height)
+ };
+
+ return rect;
+}
+
+/**
+ * @brief Returns whether the two rectangles are equal.
+ *
+ * @param rect1 The first rectangle for the comparison
+ * @param rect2 The second rectangle for the comparison
+ * @return Whether the two rectangles are equal
*/
static OF_INLINE bool
-of_dimension_equal(of_dimension_t dimension1, of_dimension_t dimension2)
+OFRectEqual(OFRect rect1, OFRect rect2)
{
- if (dimension1.width != dimension2.width)
+ if (!OFPointEqual(rect1.origin, rect2.origin))
return false;
- if (dimension1.height != dimension2.height)
+ if (!OFSizeEqual(rect1.size, rect2.size))
return false;
return true;
}
/**
- * @struct of_rectangle_t OFObject.h ObjFW/OFObject.h
- *
- * @brief A rectangle.
- */
-struct OF_BOXABLE of_rectangle_t {
- /** The point from where the rectangle originates */
- of_point_t origin;
- /** The size of the rectangle */
- of_dimension_t size;
-};
-typedef struct of_rectangle_t of_rectangle_t;
-
-/**
- * @brief Creates a new of_rectangle_t.
- *
- * @param x The x coordinate of the top left corner of the rectangle
- * @param y The y coordinate of the top left corner of the rectangle
- * @param width The width of the rectangle
- * @param height The height of the rectangle
- * @return An of_rectangle_t with the specified origin and size
- */
-static OF_INLINE of_rectangle_t OF_CONST_FUNC
-of_rectangle(float x, float y, float width, float height)
-{
- of_rectangle_t rectangle = {
- of_point(x, y),
- of_dimension(width, height)
- };
-
- return rectangle;
-}
-
-/**
- * @brief Returns whether the two rectangles are equal.
- *
- * @param rectangle1 The first rectangle for the comparison
- * @param rectangle2 The second rectangle for the comparison
- * @return Whether the two rectangles are equal
- */
-static OF_INLINE bool
-of_rectangle_equal(of_rectangle_t rectangle1, of_rectangle_t rectangle2)
-{
- if (!of_point_equal(rectangle1.origin, rectangle2.origin))
- return false;
-
- if (!of_dimension_equal(rectangle1.size, rectangle2.size))
- return false;
-
- return true;
-}
+ * @brief Adds the specified byte to the hash.
+ *
+ * @param hash A pointer to a hash to add the byte to
+ * @param byte The byte to add to the hash
+ */
+static OF_INLINE void
+OFHashAdd(unsigned long *_Nonnull hash, unsigned char byte)
+{
+ uint32_t tmp = (uint32_t)*hash;
+
+ tmp += byte;
+ tmp += tmp << 10;
+ tmp ^= tmp >> 6;
+
+ *hash = tmp;
+}
+
+/**
+ * @brief Adds the specified hash to the hash.
+ *
+ * @param hash A pointer to a hash to add the hash to
+ * @param otherHash The hash to add to the hash
+ */
+static OF_INLINE void
+OFHashAddHash(unsigned long *_Nonnull hash, unsigned long otherHash)
+{
+ OFHashAdd(hash, (otherHash >> 24) & 0xFF);
+ OFHashAdd(hash, (otherHash >> 16) & 0xFF);
+ OFHashAdd(hash, (otherHash >> 8) & 0xFF);
+ OFHashAdd(hash, otherHash & 0xFF);
+}
+
+/**
+ * @brief Finalizes the specified hash.
+ *
+ * @param hash A pointer to the hash to finalize
+ */
+static OF_INLINE void
+OFHashFinalize(unsigned long *_Nonnull hash)
+{
+ uint32_t tmp = (uint32_t)*hash;
+
+ tmp += tmp << 3;
+ tmp ^= tmp >> 11;
+ tmp += tmp << 15;
+
+ *hash = tmp;
+}
+
+static const size_t OFNotFound = SIZE_MAX;
#ifdef __OBJC__
@class OFMethodSignature;
@class OFString;
@class OFThread;
@@ -816,11 +869,11 @@
* @brief Performs the specified selector after the specified delay.
*
* @param selector The selector to perform
* @param delay The delay after which the selector will be performed
*/
-- (void)performSelector: (SEL)selector afterDelay: (of_time_interval_t)delay;
+- (void)performSelector: (SEL)selector afterDelay: (OFTimeInterval)delay;
/**
* @brief Performs the specified selector with the specified object after the
* specified delay.
*
@@ -829,11 +882,11 @@
* selector
* @param delay The delay after which the selector will be performed
*/
- (void)performSelector: (SEL)selector
withObject: (nullable id)object
- afterDelay: (of_time_interval_t)delay;
+ afterDelay: (OFTimeInterval)delay;
/**
* @brief Performs the specified selector with the specified objects after the
* specified delay.
*
@@ -845,11 +898,11 @@
* @param delay The delay after which the selector will be performed
*/
- (void)performSelector: (SEL)selector
withObject: (nullable id)object1
withObject: (nullable id)object2
- afterDelay: (of_time_interval_t)delay;
+ afterDelay: (OFTimeInterval)delay;
/**
* @brief Performs the specified selector with the specified objects after the
* specified delay.
*
@@ -864,11 +917,11 @@
*/
- (void)performSelector: (SEL)selector
withObject: (nullable id)object1
withObject: (nullable id)object2
withObject: (nullable id)object3
- afterDelay: (of_time_interval_t)delay;
+ afterDelay: (OFTimeInterval)delay;
/**
* @brief Performs the specified selector with the specified objects after the
* specified delay.
*
@@ -886,11 +939,11 @@
- (void)performSelector: (SEL)selector
withObject: (nullable id)object1
withObject: (nullable id)object2
withObject: (nullable id)object3
withObject: (nullable id)object4
- afterDelay: (of_time_interval_t)delay;
+ afterDelay: (OFTimeInterval)delay;
# ifdef OF_HAVE_THREADS
/**
* @brief Performs the specified selector on the specified thread.
*
@@ -1067,11 +1120,11 @@
* @param thread The thread on which to perform the selector
* @param delay The delay after which the selector will be performed
*/
- (void)performSelector: (SEL)selector
onThread: (OFThread *)thread
- afterDelay: (of_time_interval_t)delay;
+ afterDelay: (OFTimeInterval)delay;
/**
* @brief Performs the specified selector on the specified thread with the
* specified object after the specified delay.
*
@@ -1082,11 +1135,11 @@
* @param delay The delay after which the selector will be performed
*/
- (void)performSelector: (SEL)selector
onThread: (OFThread *)thread
withObject: (nullable id)object
- afterDelay: (of_time_interval_t)delay;
+ afterDelay: (OFTimeInterval)delay;
/**
* @brief Performs the specified selector on the specified thread with the
* specified objects after the specified delay.
*
@@ -1100,11 +1153,11 @@
*/
- (void)performSelector: (SEL)selector
onThread: (OFThread *)thread
withObject: (nullable id)object1
withObject: (nullable id)object2
- afterDelay: (of_time_interval_t)delay;
+ afterDelay: (OFTimeInterval)delay;
/**
* @brief Performs the specified selector on the specified thread with the
* specified objects after the specified delay.
*
@@ -1121,11 +1174,11 @@
- (void)performSelector: (SEL)selector
onThread: (OFThread *)thread
withObject: (nullable id)object1
withObject: (nullable id)object2
withObject: (nullable id)object3
- afterDelay: (of_time_interval_t)delay;
+ afterDelay: (OFTimeInterval)delay;
/**
* @brief Performs the specified selector on the specified thread with the
* specified objects after the specified delay.
*
@@ -1145,11 +1198,11 @@
onThread: (OFThread *)thread
withObject: (nullable id)object1
withObject: (nullable id)object2
withObject: (nullable id)object3
withObject: (nullable id)object4
- afterDelay: (of_time_interval_t)delay;
+ afterDelay: (OFTimeInterval)delay;
# endif
/**
* @brief This method is called when @ref resolveClassMethod: or
* @ref resolveInstanceMethod: returned false. It should return a target
@@ -1225,11 +1278,11 @@
* @brief Compares the object to another object.
*
* @param object An object to compare the object to
* @return The result of the comparison
*/
-- (of_comparison_result_t)compare: (id )object;
+- (OFComparisonResult)compare: (id )object;
@end
#endif
#ifdef __cplusplus
extern "C" {
@@ -1236,44 +1289,44 @@
#endif
/**
* @brief Allocates memory for the specified number of items of the specified
* size.
*
- * To free the allocated memory, use `free()`.
+ * To free the allocated memory, use @ref OFFreeMemory.
*
* Throws @ref OFOutOfMemoryException if allocating failed and
* @ref OFOutOfRangeException if the requested size exceeds the address space.
*
* @param count The number of items to allocate
* @param size The size of each item to allocate
* @return A pointer to the allocated memory. May return NULL if the specified
* size or count is 0.
*/
-extern void *_Nullable of_alloc(size_t count, size_t size)
+extern void *_Nullable OFAllocMemory(size_t count, size_t size)
OF_WARN_UNUSED_RESULT;
/**
* @brief Allocates memory for the specified number of items of the specified
* size and initializes it with zeros.
*
- * To free the allocated memory, use `free()`.
+ * To free the allocated memory, use @ref OFFreeMemory.
*
* Throws @ref OFOutOfMemoryException if allocating failed and
* @ref OFOutOfRangeException if the requested size exceeds the address space.
*
* @param size The size of each item to allocate
* @param count The number of items to allocate
* @return A pointer to the allocated memory. May return NULL if the specified
* size or count is 0.
*/
-extern void *_Nullable of_alloc_zeroed(size_t count, size_t size)
+extern void *_Nullable OFAllocZeroedMemory(size_t count, size_t size)
OF_WARN_UNUSED_RESULT;
/**
* @brief Resizes memory to the specified number of items of the specified size.
*
- * To free the allocated memory, use `free()`.
+ * To free the allocated memory, use @ref OFFreeMemory.
*
* If the pointer is NULL, this is equivalent to allocating memory.
* If the size or number of items is 0, this is equivalent to freeing memory.
*
* Throws @ref OFOutOfMemoryException if allocating failed and
@@ -1282,37 +1335,71 @@
* @param pointer A pointer to the already allocated memory
* @param size The size of each item to resize to
* @param count The number of items to resize to
* @return A pointer to the resized memory chunk
*/
-extern void *_Nullable of_realloc(void *_Nullable pointer, size_t count,
+extern void *_Nullable OFResizeMemory(void *_Nullable pointer, size_t count,
size_t size) OF_WARN_UNUSED_RESULT;
+/**
+ * @brief Frees memory allocated by @ref OFAllocMemory, @ref OFAllocZeroedMemory
+ * or @ref OFResizeMemory.
+ *
+ * @param pointer A pointer to the memory to free or nil (passing nil ooes
+ * nothing)
+ */
+extern void OFFreeMemory(void *_Nullable pointer);
+
#ifdef OF_APPLE_RUNTIME
extern void *_Null_unspecified objc_autoreleasePoolPush(void);
extern void objc_autoreleasePoolPop(void *_Null_unspecified pool);
# ifndef __OBJC2__
extern id _Nullable objc_constructInstance(Class _Nullable class_,
void *_Nullable bytes);
extern void *_Nullable objc_destructInstance(id _Nullable object);
# endif
#endif
-extern id of_alloc_object(Class class_, size_t extraSize,
- size_t extraAlignment, void *_Nullable *_Nullable extra);
-extern void OF_NO_RETURN_FUNC of_method_not_found(id self, SEL _cmd);
-extern uint32_t of_hash_seed;
-/* These do *NOT* provide cryptographically secure randomness! */
-extern uint16_t of_random16(void);
-extern uint32_t of_random32(void);
-extern uint64_t of_random64(void);
+extern id OFAllocObject(Class class_, size_t extraSize, size_t extraAlignment,
+ void *_Nullable *_Nullable extra);
+extern void OF_NO_RETURN_FUNC OFMethodNotFound(id self, SEL _cmd);
+
+/**
+ * @brief Returns 16 bit or non-cryptographical randomness.
+ *
+ * @return 16 bit or non-cryptographical randomness
+ */
+extern uint16_t OFRandom16(void);
+
+/**
+ * @brief Returns 32 bit or non-cryptographical randomness.
+ *
+ * @return 32 bit or non-cryptographical randomness
+ */
+extern uint32_t OFRandom32(void);
+
+/**
+ * @brief Returns 64 bit or non-cryptographical randomness.
+ *
+ * @return 64 bit or non-cryptographical randomness
+ */
+extern uint64_t OFRandom64(void);
+
+/**
+ * @brief Initializes the specified hash.
+ *
+ * @param hash A pointer to the hash to initialize
+ */
+extern void OFHashInit(unsigned long *_Nonnull hash);
#ifdef __cplusplus
}
#endif
OF_ASSUME_NONNULL_END
+
+#include "OFBlock.h"
#ifdef __OBJC__
# import "OFObject+KeyValueCoding.h"
# import "OFObject+Serialization.h"
#endif
#endif
Index: src/OFObject.m
==================================================================
--- src/OFObject.m
+++ src/OFObject.m
@@ -29,13 +29,20 @@
# include
#endif
#import "OFObject.h"
#import "OFArray.h"
+#ifdef OF_HAVE_ATOMIC_OPS
+# import "OFAtomic.h"
+#endif
#import "OFLocale.h"
#import "OFMethodSignature.h"
#import "OFRunLoop.h"
+#if !defined(OF_HAVE_ATOMIC_OPS) && defined(OF_HAVE_THREADS)
+# import "OFPlainMutex.h" /* For OFSpinlock */
+#endif
+#import "OFString.h"
#import "OFThread.h"
#import "OFTimer.h"
#import "OFAllocFailedException.h"
#import "OFEnumerationMutationException.h"
@@ -58,48 +65,40 @@
#ifdef OF_AMIGAOS
# include
#endif
-#import "OFString.h"
-
-#if defined(OF_HAVE_ATOMIC_OPS)
-# import "atomic.h"
-#elif defined(OF_HAVE_THREADS)
-# import "mutex.h"
-#endif
-
#ifdef OF_APPLE_RUNTIME
extern id _Nullable _objc_rootAutorelease(id _Nullable object);
#endif
#if defined(OF_HAVE_FORWARDING_TARGET_FOR_SELECTOR)
-extern id of_forward(id, SEL, ...);
-extern struct stret of_forward_stret(id, SEL, ...);
+extern id OFForward(id, SEL, ...);
+extern struct stret OFForward_stret(id, SEL, ...);
#else
-# define of_forward of_method_not_found
-# define of_forward_stret of_method_not_found_stret
+# define OFForward OFMethodNotFound
+# define OFForward_stret OFMethodNotFound_stret
#endif
-struct pre_ivar {
+struct PreIvars {
int retainCount;
#if !defined(OF_HAVE_ATOMIC_OPS) && !defined(OF_AMIGAOS)
- of_spinlock_t retainCountSpinlock;
+ OFSpinlock retainCountSpinlock;
#endif
};
-#define PRE_IVARS_ALIGN ((sizeof(struct pre_ivar) + \
+#define PRE_IVARS_ALIGN ((sizeof(struct PreIvars) + \
(OF_BIGGEST_ALIGNMENT - 1)) & ~(OF_BIGGEST_ALIGNMENT - 1))
-#define PRE_IVARS ((struct pre_ivar *)(void *)((char *)self - PRE_IVARS_ALIGN))
+#define PRE_IVARS ((struct PreIvars *)(void *)((char *)self - PRE_IVARS_ALIGN))
static struct {
Class isa;
} allocFailedException;
-uint32_t of_hash_seed;
+unsigned long OFHashSeed;
void *
-of_alloc(size_t count, size_t size)
+OFAllocMemory(size_t count, size_t size)
{
void *pointer;
if OF_UNLIKELY (count == 0 || size == 0)
return NULL;
@@ -113,11 +112,11 @@
return pointer;
}
void *
-of_alloc_zeroed(size_t count, size_t size)
+OFAllocZeroedMemory(size_t count, size_t size)
{
void *pointer;
if OF_UNLIKELY (count == 0 || size == 0)
return NULL;
@@ -132,11 +131,11 @@
return pointer;
}
void *
-of_realloc(void *pointer, size_t count, size_t size)
+OFResizeMemory(void *pointer, size_t count, size_t size)
{
if OF_UNLIKELY (count == 0 || size == 0)
return NULL;
if OF_UNLIKELY (count > SIZE_MAX / size)
@@ -146,10 +145,16 @@
@throw [OFOutOfMemoryException
exceptionWithRequestedSize: size];
return pointer;
}
+
+void
+OFFreeMemory(void *pointer)
+{
+ free(pointer);
+}
#if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_GETRANDOM)
static void
initRandom(void)
{
@@ -164,50 +169,49 @@
# endif
}
#endif
uint16_t
-of_random16(void)
+OFRandom16(void)
{
#if defined(HAVE_ARC4RANDOM)
return arc4random();
#elif defined(HAVE_GETRANDOM)
uint16_t buffer;
- OF_ENSURE(getrandom(&buffer, sizeof(buffer), 0) == sizeof(buffer));
+ OFEnsure(getrandom(&buffer, sizeof(buffer), 0) == sizeof(buffer));
return buffer;
#else
- static of_once_t onceControl = OF_ONCE_INIT;
-
- of_once(&onceControl, initRandom);
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, initRandom);
# ifdef HAVE_RANDOM
return random() & 0xFFFF;
# else
return rand() & 0xFFFF;
# endif
#endif
}
uint32_t
-of_random32(void)
+OFRandom32(void)
{
#if defined(HAVE_ARC4RANDOM)
return arc4random();
#elif defined(HAVE_GETRANDOM)
uint32_t buffer;
- OF_ENSURE(getrandom(&buffer, sizeof(buffer), 0) == sizeof(buffer));
+ OFEnsure(getrandom(&buffer, sizeof(buffer), 0) == sizeof(buffer));
return buffer;
#else
- return ((uint32_t)of_random16() << 16) | of_random16();
+ return ((uint32_t)OFRandom16() << 16) | OFRandom16();
#endif
}
uint64_t
-of_random64(void)
+OFRandom64(void)
{
#if defined(HAVE_ARC4RANDOM_BUF)
uint64_t buffer;
arc4random_buf(&buffer, sizeof(buffer));
@@ -214,17 +218,23 @@
return buffer;
#elif defined(HAVE_GETRANDOM)
uint64_t buffer;
- OF_ENSURE(getrandom(&buffer, sizeof(buffer), 0) == sizeof(buffer));
+ OFEnsure(getrandom(&buffer, sizeof(buffer), 0) == sizeof(buffer));
return buffer;
#else
- return ((uint64_t)of_random32() << 32) | of_random32();
+ return ((uint64_t)OFRandom32() << 32) | OFRandom32();
#endif
}
+
+void
+OFHashInit(unsigned long *hash)
+{
+ *hash = OFHashSeed;
+}
static const char *
typeEncodingForSelector(Class class, SEL selector)
{
Method method;
@@ -239,11 +249,11 @@
static void
uncaughtExceptionHandler(id exception)
{
OFString *description = [exception description];
OFArray *backtrace = nil;
- of_string_encoding_t encoding = [OFLocale encoding];
+ OFStringEncoding encoding = [OFLocale encoding];
fprintf(stderr, "\nRuntime error: Unhandled exception:\n%s\n",
[description cStringWithEncoding: encoding]);
if ([exception respondsToSelector: @selector(backtrace)])
@@ -264,11 +274,11 @@
{
@throw [OFEnumerationMutationException exceptionWithObject: object];
}
void OF_NO_RETURN_FUNC
-of_method_not_found(id object, SEL selector)
+OFMethodNotFound(id object, SEL selector)
{
[object doesNotRecognizeSelector: selector];
/*
* Just in case doesNotRecognizeSelector: returned, even though it must
@@ -278,17 +288,17 @@
OF_UNREACHABLE
}
void OF_NO_RETURN_FUNC
-of_method_not_found_stret(void *stret, id object, SEL selector)
+OFMethodNotFound_stret(void *stret, id object, SEL selector)
{
- of_method_not_found(object, selector);
+ OFMethodNotFound(object, selector);
}
id
-of_alloc_object(Class class, size_t extraSize, size_t extraAlignment,
+OFAllocObject(Class class, size_t extraSize, size_t extraAlignment,
void **extra)
{
OFObject *instance;
size_t instanceSize;
@@ -304,15 +314,15 @@
if OF_UNLIKELY (instance == nil) {
allocFailedException.isa = [OFAllocFailedException class];
@throw (id)&allocFailedException;
}
- ((struct pre_ivar *)instance)->retainCount = 1;
+ ((struct PreIvars *)instance)->retainCount = 1;
#if !defined(OF_HAVE_ATOMIC_OPS) && !defined(OF_AMIGAOS)
- if OF_UNLIKELY (of_spinlock_new(
- &((struct pre_ivar *)instance)->retainCountSpinlock) != 0) {
+ if OF_UNLIKELY (OFSpinlockNew(
+ &((struct PreIvars *)instance)->retainCountSpinlock) != 0) {
free(instance);
@throw [OFInitializationFailedException
exceptionWithClass: class];
}
#endif
@@ -361,25 +371,25 @@
*
* Unfortunately, there is no way to check if a forward handler has
* already been set, so this is the best we can do.
*/
if (dlsym(RTLD_DEFAULT, "NSFoundationVersionNumber") == NULL)
- objc_setForwardHandler((void *)&of_forward,
- (void *)&of_forward_stret);
+ objc_setForwardHandler((void *)&OFForward,
+ (void *)&OFForward_stret);
#else
- objc_setForwardHandler((IMP)&of_forward, (IMP)&of_forward_stret);
+ objc_setForwardHandler((IMP)&OFForward, (IMP)&OFForward_stret);
#endif
objc_setEnumerationMutationHandler(enumerationMutationHandler);
do {
- of_hash_seed = of_random32();
- } while (of_hash_seed == 0);
+ OFHashSeed = OFRandom32();
+ } while (OFHashSeed == 0);
#ifdef OF_OBJFW_RUNTIME
objc_setTaggedPointerSecret(sizeof(uintptr_t) == 4
- ? (uintptr_t)of_random32() : (uintptr_t)of_random64());
+ ? (uintptr_t)OFRandom32() : (uintptr_t)OFRandom64());
#endif
}
+ (void)unload
{
@@ -389,11 +399,11 @@
{
}
+ (instancetype)alloc
{
- return of_alloc_object(self, 0, 0, NULL);
+ return OFAllocObject(self, 0, 0, NULL);
}
+ (instancetype)new
{
return [[self alloc] init];
@@ -405,11 +415,11 @@
}
+ (OFString *)className
{
return [OFString stringWithCString: class_getName(self)
- encoding: OF_STRING_ENCODING_ASCII];
+ encoding: OFStringEncodingASCII];
}
+ (bool)isSubclassOfClass: (Class)class
{
for (Class iter = self; iter != Nil; iter = class_getSuperclass(iter))
@@ -560,11 +570,11 @@
}
- (OFString *)className
{
return [OFString stringWithCString: object_getClassName(self)
- encoding: OF_STRING_ENCODING_ASCII];
+ encoding: OFStringEncodingASCII];
}
- (bool)isKindOfClass: (Class)class
{
for (Class iter = object_getClass(self); iter != Nil;
@@ -663,11 +673,11 @@
#endif
return imp(self, selector, object1, object2, object3, object4);
}
-- (void)performSelector: (SEL)selector afterDelay: (of_time_interval_t)delay
+- (void)performSelector: (SEL)selector afterDelay: (OFTimeInterval)delay
{
void *pool = objc_autoreleasePoolPush();
[OFTimer scheduledTimerWithTimeInterval: delay
target: self
@@ -677,11 +687,11 @@
objc_autoreleasePoolPop(pool);
}
- (void)performSelector: (SEL)selector
withObject: (id)object
- afterDelay: (of_time_interval_t)delay
+ afterDelay: (OFTimeInterval)delay
{
void *pool = objc_autoreleasePoolPush();
[OFTimer scheduledTimerWithTimeInterval: delay
target: self
@@ -693,11 +703,11 @@
}
- (void)performSelector: (SEL)selector
withObject: (id)object1
withObject: (id)object2
- afterDelay: (of_time_interval_t)delay
+ afterDelay: (OFTimeInterval)delay
{
void *pool = objc_autoreleasePoolPush();
[OFTimer scheduledTimerWithTimeInterval: delay
target: self
@@ -711,11 +721,11 @@
- (void)performSelector: (SEL)selector
withObject: (id)object1
withObject: (id)object2
withObject: (id)object3
- afterDelay: (of_time_interval_t)delay
+ afterDelay: (OFTimeInterval)delay
{
void *pool = objc_autoreleasePoolPush();
[OFTimer scheduledTimerWithTimeInterval: delay
target: self
@@ -731,11 +741,11 @@
- (void)performSelector: (SEL)selector
withObject: (id)object1
withObject: (id)object2
withObject: (id)object3
withObject: (id)object4
- afterDelay: (of_time_interval_t)delay
+ afterDelay: (OFTimeInterval)delay
{
void *pool = objc_autoreleasePoolPush();
[OFTimer scheduledTimerWithTimeInterval: delay
target: self
@@ -955,11 +965,11 @@
objc_autoreleasePoolPop(pool);
}
- (void)performSelector: (SEL)selector
onThread: (OFThread *)thread
- afterDelay: (of_time_interval_t)delay
+ afterDelay: (OFTimeInterval)delay
{
void *pool = objc_autoreleasePoolPush();
[thread.runLoop addTimer: [OFTimer timerWithTimeInterval: delay
target: self
@@ -970,11 +980,11 @@
}
- (void)performSelector: (SEL)selector
onThread: (OFThread *)thread
withObject: (id)object
- afterDelay: (of_time_interval_t)delay
+ afterDelay: (OFTimeInterval)delay
{
void *pool = objc_autoreleasePoolPush();
[thread.runLoop addTimer: [OFTimer timerWithTimeInterval: delay
target: self
@@ -987,11 +997,11 @@
- (void)performSelector: (SEL)selector
onThread: (OFThread *)thread
withObject: (id)object1
withObject: (id)object2
- afterDelay: (of_time_interval_t)delay
+ afterDelay: (OFTimeInterval)delay
{
void *pool = objc_autoreleasePoolPush();
[thread.runLoop addTimer: [OFTimer timerWithTimeInterval: delay
target: self
@@ -1006,11 +1016,11 @@
- (void)performSelector: (SEL)selector
onThread: (OFThread *)thread
withObject: (id)object1
withObject: (id)object2
withObject: (id)object3
- afterDelay: (of_time_interval_t)delay
+ afterDelay: (OFTimeInterval)delay
{
void *pool = objc_autoreleasePoolPush();
[thread.runLoop addTimer: [OFTimer timerWithTimeInterval: delay
target: self
@@ -1027,11 +1037,11 @@
onThread: (OFThread *)thread
withObject: (id)object1
withObject: (id)object2
withObject: (id)object3
withObject: (id)object4
- afterDelay: (of_time_interval_t)delay
+ afterDelay: (OFTimeInterval)delay
{
void *pool = objc_autoreleasePoolPush();
[thread.runLoop addTimer: [OFTimer timerWithTimeInterval: delay
target: self
@@ -1063,20 +1073,20 @@
}
- (unsigned long)hash
{
uintptr_t ptr = (uintptr_t)self;
- uint32_t hash;
+ unsigned long hash;
- OF_HASH_INIT(hash);
+ OFHashInit(&hash);
for (size_t i = 0; i < sizeof(ptr); i++) {
- OF_HASH_ADD(hash, ptr & 0xFF);
+ OFHashAdd(&hash, ptr & 0xFF);
ptr >>= 8;
}
- OF_HASH_FINALIZE(hash);
+ OFHashFinalize(&hash);
return hash;
}
- (OFString *)description
@@ -1098,11 +1108,11 @@
}
- (instancetype)retain
{
#if defined(OF_HAVE_ATOMIC_OPS)
- of_atomic_int_inc(&PRE_IVARS->retainCount);
+ OFAtomicIntIncrease(&PRE_IVARS->retainCount);
#elif defined(OF_AMIGAOS)
/*
* On AmigaOS, we can only have one CPU. As increasing a variable is a
* single instruction on M68K, we don't need Forbid() / Permit() on
* M68K.
@@ -1113,13 +1123,13 @@
PRE_IVARS->retainCount++;
# ifndef OF_AMIGAOS_M68K
Permit();
# endif
#else
- OF_ENSURE(of_spinlock_lock(&PRE_IVARS->retainCountSpinlock) == 0);
+ OFEnsure(OFSpinlockLock(&PRE_IVARS->retainCountSpinlock) == 0);
PRE_IVARS->retainCount++;
- OF_ENSURE(of_spinlock_unlock(&PRE_IVARS->retainCountSpinlock) == 0);
+ OFEnsure(OFSpinlockUnlock(&PRE_IVARS->retainCountSpinlock) == 0);
#endif
return self;
}
@@ -1130,14 +1140,14 @@
}
- (void)release
{
#if defined(OF_HAVE_ATOMIC_OPS)
- of_memory_barrier_release();
+ OFReleaseMemoryBarrier();
- if (of_atomic_int_dec(&PRE_IVARS->retainCount) <= 0) {
- of_memory_barrier_acquire();
+ if (OFAtomicIntDecrease(&PRE_IVARS->retainCount) <= 0) {
+ OFAcquireMemoryBarrier();
[self dealloc];
}
#elif defined(OF_AMIGAOS)
int retainCount;
@@ -1149,13 +1159,13 @@
if (retainCount == 0)
[self dealloc];
#else
int retainCount;
- OF_ENSURE(of_spinlock_lock(&PRE_IVARS->retainCountSpinlock) == 0);
+ OFEnsure(OFSpinlockLock(&PRE_IVARS->retainCountSpinlock) == 0);
retainCount = --PRE_IVARS->retainCount;
- OF_ENSURE(of_spinlock_unlock(&PRE_IVARS->retainCountSpinlock) == 0);
+ OFEnsure(OFSpinlockUnlock(&PRE_IVARS->retainCountSpinlock) == 0);
if (retainCount == 0)
[self dealloc];
#endif
}
@@ -1231,11 +1241,11 @@
return self;
}
+ (unsigned int)retainCount
{
- return OF_RETAIN_COUNT_MAX;
+ return OFMaxRetainCount;
}
+ (void)release
{
}
ADDED src/OFOnce.h
Index: src/OFOnce.h
==================================================================
--- src/OFOnce.h
+++ src/OFOnce.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "objfw-defs.h"
+
+#include "platform.h"
+
+#if defined(OF_HAVE_PTHREADS)
+# include
+typedef pthread_once_t OFOnceControl;
+# define OFOnceControlInitValue PTHREAD_ONCE_INIT
+#elif defined(OF_HAVE_ATOMIC_OPS)
+typedef volatile int OFOnceControl;
+# define OFOnceControlInitValue 0
+#elif defined(OF_AMIGAOS) || !defined(OF_HAVE_THREADS)
+typedef int OFOnceControl;
+# define OFOnceControlInitValue 0
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern void OFOnce(OFOnceControl *control, void (*func)(void));
+#ifdef __cplusplus
+}
+#endif
ADDED src/OFOnce.m
Index: src/OFOnce.m
==================================================================
--- src/OFOnce.m
+++ src/OFOnce.m
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#include
+
+#import "OFOnce.h"
+#if defined(OF_HAVE_THREADS) && defined(OF_HAVE_ATOMIC_OPS)
+# import "OFAtomic.h"
+# import "OFPlainMutex.h"
+#endif
+
+#ifdef OF_AMIGAOS
+# include
+#endif
+
+void
+OFOnce(OFOnceControl *control, void (*func)(void))
+{
+#if !defined(OF_HAVE_THREADS)
+ if (*control == 0) {
+ func();
+ *control = 1;
+ }
+#elif defined(OF_HAVE_PTHREADS)
+ pthread_once(control, func);
+#elif defined(OF_HAVE_ATOMIC_OPS)
+ /* Avoid atomic operations in case it's already done. */
+ if (*control == 2)
+ return;
+
+ if (OFAtomicIntCompareAndSwap(control, 0, 1)) {
+ func();
+
+ OFMemoryBarrier();
+
+ OFAtomicIntIncrease(control);
+ } else
+ while (*control == 1)
+ OFYieldThread();
+#elif defined(OF_AMIGAOS)
+ bool run = false;
+
+ /* Avoid Forbid() in case it's already done. */
+ if (*control == 2)
+ return;
+
+ Forbid();
+
+ switch (*control) {
+ case 0:
+ *control = 1;
+ run = true;
+ break;
+ case 1:
+ while (*control == 1) {
+ Permit();
+ Forbid();
+ }
+ }
+
+ Permit();
+
+ if (run) {
+ func();
+ *control = 2;
+ }
+#else
+# error No OFOnce available
+#endif
+}
Index: src/OFOptionsParser.h
==================================================================
--- src/OFOptionsParser.h
+++ src/OFOptionsParser.h
@@ -19,17 +19,17 @@
@class OFMapTable;
OF_ASSUME_NONNULL_BEGIN
/**
- * @struct of_options_parser_option_t OFOptionsParser.h ObjFW/OFOptionsParser.h
+ * @struct OFOptionsParserOption OFOptionsParser.h ObjFW/OFOptionsParser.h
*
* @brief An option which can be parsed by an @ref OFOptionsParser.
*/
-struct of_options_parser_option_t {
+typedef struct {
/** The short version (e.g. `-v`) of the option or `\0` for none. */
- of_unichar_t shortOption;
+ OFUnichar shortOption;
/**
* The long version (e.g. `--verbose`) of the option or `nil` for none.
*/
OFString *__unsafe_unretained _Nullable longOption;
@@ -55,26 +55,25 @@
/**
* An optional pointer to an `OFString *` that is set to the
* argument specified for the option or `nil` for no argument.
*/
OFString *__autoreleasing _Nullable *_Nullable argumentPtr;
-};
-typedef struct of_options_parser_option_t of_options_parser_option_t;
+} OFOptionsParserOption;
/**
* @class OFOptionsParser OFOptionsParser.h ObjFW/OFOptionsParser.h
*
* @brief A class for parsing the program options specified on the command line.
*/
OF_SUBCLASSING_RESTRICTED
@interface OFOptionsParser: OFObject
{
- of_options_parser_option_t *_options;
+ OFOptionsParserOption *_options;
OFMapTable *_longOptions;
OFArray OF_GENERIC(OFString *) *_arguments;
size_t _index, _subIndex;
- of_unichar_t _lastOption;
+ OFUnichar _lastOption;
OFString *_Nullable _lastLongOption, *_Nullable _argument;
bool _done;
}
/**
@@ -83,11 +82,11 @@
* If @ref nextOption returned `?` or `:`, this returns the option which was
* unknown or for which the argument was missing.@n
* If this returns `-`, the last option is only available as a long option (see
* lastLongOption).
*/
-@property (readonly, nonatomic) of_unichar_t lastOption;
+@property (readonly, nonatomic) OFUnichar lastOption;
/**
* @brief The long option for the last parsed option, or `nil` if the last
* parsed option was not passed as a long option by the user.
*
@@ -117,31 +116,31 @@
OFArray OF_GENERIC(OFString *) *remainingArguments;
/**
* @brief Creates a new OFOptionsParser which accepts the specified options.
*
- * @param options An array of @ref of_options_parser_option_t specifying all
+ * @param options An array of @ref OFOptionsParserOption specifying all
* accepted options, terminated with an option whose short
* option is `\0` and long option is `nil`.
*
* @return A new, autoreleased OFOptionsParser
*/
-+ (instancetype)parserWithOptions: (const of_options_parser_option_t *)options;
++ (instancetype)parserWithOptions: (const OFOptionsParserOption *)options;
- (instancetype)init OF_UNAVAILABLE;
/**
* @brief Initializes an already allocated OFOptionsParser so that it accepts
* the specified options.
*
- * @param options An array of @ref of_options_parser_option_t specifying all
+ * @param options An array of @ref OFOptionsParserOption specifying all
* accepted options, terminated with an option whose short
* option is `\0` and long option is `nil`.
*
* @return An initialized OFOptionsParser
*/
-- (instancetype)initWithOptions: (const of_options_parser_option_t *)options
+- (instancetype)initWithOptions: (const OFOptionsParserOption *)options
OF_DESIGNATED_INITIALIZER;
/**
* @brief Returns the next option.
*
@@ -158,9 +157,9 @@
* make sure all options have been parsed, even if you only rely on the
* optional pointers specified and don't do any parsing yourself.
*
* @return The next option
*/
-- (of_unichar_t)nextOption;
+- (OFUnichar)nextOption;
@end
OF_ASSUME_NONNULL_END
Index: src/OFOptionsParser.m
==================================================================
--- src/OFOptionsParser.m
+++ src/OFOptionsParser.m
@@ -36,33 +36,33 @@
@implementation OFOptionsParser
@synthesize lastOption = _lastOption, lastLongOption = _lastLongOption;
@synthesize argument = _argument;
-+ (instancetype)parserWithOptions: (const of_options_parser_option_t *)options
++ (instancetype)parserWithOptions: (const OFOptionsParserOption *)options
{
return [[[self alloc] initWithOptions: options] autorelease];
}
- (instancetype)init
{
OF_INVALID_INIT_METHOD
}
-- (instancetype)initWithOptions: (const of_options_parser_option_t *)options
+- (instancetype)initWithOptions: (const OFOptionsParserOption *)options
{
self = [super init];
@try {
size_t count = 0;
- const of_options_parser_option_t *iter;
- of_options_parser_option_t *iter2;
- const of_map_table_functions_t keyFunctions = {
+ const OFOptionsParserOption *iter;
+ OFOptionsParserOption *iter2;
+ const OFMapTableFunctions keyFunctions = {
.hash = stringHash,
.equal = stringEqual
};
- const of_map_table_functions_t objectFunctions = { NULL };
+ const OFMapTableFunctions objectFunctions = { NULL };
/* Count, sanity check, initialize pointers */
for (iter = options;
iter->shortOption != '\0' || iter->longOption != nil;
iter++) {
@@ -82,11 +82,11 @@
*iter->argumentPtr = nil;
count++;
}
- _options = of_alloc(count + 1, sizeof(*_options));
+ _options = OFAllocMemory(count + 1, sizeof(*_options));
_longOptions = [[OFMapTable alloc]
initWithKeyFunctions: keyFunctions
objectFunctions: objectFunctions];
for (iter = options, iter2 = _options;
@@ -139,27 +139,27 @@
}
- (void)dealloc
{
if (_options != NULL)
- for (of_options_parser_option_t *iter = _options;
+ for (OFOptionsParserOption *iter = _options;
iter->shortOption != '\0' || iter->longOption != nil;
iter++)
[iter->longOption release];
- free(_options);
+ OFFreeMemory(_options);
[_longOptions release];
[_arguments release];
[_argument release];
[super dealloc];
}
-- (of_unichar_t)nextOption
+- (OFUnichar)nextOption
{
- of_options_parser_option_t *iter;
+ OFOptionsParserOption *iter;
OFString *argument;
if (_done || _index >= _arguments.count)
return '\0';
@@ -184,24 +184,24 @@
}
if ([argument hasPrefix: @"--"]) {
void *pool = objc_autoreleasePoolPush();
size_t pos;
- of_options_parser_option_t *option;
+ OFOptionsParserOption *option;
_lastOption = '-';
_index++;
if ((pos = [argument rangeOfString: @"="].location) !=
- OF_NOT_FOUND)
+ OFNotFound)
_argument = [[argument
substringFromIndex: pos + 1] copy];
else
pos = argument.length;
_lastLongOption = [[argument substringWithRange:
- of_range(2, pos - 2)] copy];
+ OFRangeMake(2, pos - 2)] copy];
objc_autoreleasePoolPop(pool);
option = [_longOptions objectForKey: _lastLongOption];
if (option == NULL)
@@ -269,8 +269,8 @@
}
- (OFArray *)remainingArguments
{
return [_arguments objectsInRange:
- of_range(_index, _arguments.count - _index)];
+ OFRangeMake(_index, _arguments.count - _index)];
}
@end
ADDED src/OFPBKDF2.h
Index: src/OFPBKDF2.h
==================================================================
--- src/OFPBKDF2.h
+++ src/OFPBKDF2.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#ifndef __STDC_LIMIT_MACROS
+# define __STDC_LIMIT_MACROS
+#endif
+#ifndef __STDC_CONSTANT_MACROS
+# define __STDC_CONSTANT_MACROS
+#endif
+
+#import "macros.h"
+
+OF_ASSUME_NONNULL_BEGIN
+
+/** @file */
+
+@class OFHMAC;
+
+/**
+ * @brief The parameters for @ref OFPBKDF2.
+ */
+typedef struct {
+ /** @brief The HMAC to use to derive a key. */
+ __unsafe_unretained OFHMAC *HMAC;
+ /** @brief The number of iterations to perform. */
+ size_t iterations;
+ /** @brief The salt to derive a key with. */
+ const unsigned char *salt;
+ /** @brief The length of the salt. */
+ size_t saltLength;
+ /** @brief The password to derive a key from. */
+ const char *password;
+ /** @brief The length of the password. */
+ size_t passwordLength;
+ /** @brief The buffer to write the key to. */
+ unsigned char *key;
+ /**
+ * @brief The desired length for the derived key.
+ *
+ * @ref key needs to have enough storage.
+ */
+ size_t keyLength;
+ /** @brief Whether data may be stored in swappable memory. */
+ bool allowsSwappableMemory;
+} OFPBKDF2Parameters;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+/**
+ * @brief Derives a key from a password and a salt using PBKDF2.
+ *
+ * @note This will call @ref OFHMAC::reset on the `HMAC` first, making it
+ * possible to reuse the `HMAC`, but also meaning all previous results
+ * from the `HMAC` get invalidated if they have not been copied.
+ *
+ * @param param The parameters to use
+ */
+extern void OFPBKDF2(OFPBKDF2Parameters param);
+#ifdef __cplusplus
+}
+#endif
+
+OF_ASSUME_NONNULL_END
ADDED src/OFPBKDF2.m
Index: src/OFPBKDF2.m
==================================================================
--- src/OFPBKDF2.m
+++ src/OFPBKDF2.m
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#include
+
+#import "OFPBKDF2.h"
+#import "OFHMAC.h"
+#import "OFSecureData.h"
+
+#import "OFInvalidArgumentException.h"
+#import "OFOutOfMemoryException.h"
+#import "OFOutOfRangeException.h"
+
+void
+OFPBKDF2(OFPBKDF2Parameters param)
+{
+ void *pool = objc_autoreleasePoolPush();
+ size_t blocks, digestSize = param.HMAC.digestSize;
+ OFSecureData *buffer = [OFSecureData
+ dataWithCount: digestSize
+ allowsSwappableMemory: param.allowsSwappableMemory];
+ OFSecureData *digest = [OFSecureData
+ dataWithCount: digestSize
+ allowsSwappableMemory: param.allowsSwappableMemory];
+ unsigned char *bufferItems = buffer.mutableItems;
+ unsigned char *digestItems = digest.mutableItems;
+ OFSecureData *extendedSalt;
+ unsigned char *extendedSaltItems;
+
+ if (param.HMAC == nil || param.iterations == 0 || param.salt == NULL ||
+ param.password == NULL || param.key == NULL || param.keyLength == 0)
+ @throw [OFInvalidArgumentException exception];
+
+ blocks = param.keyLength / digestSize;
+ if (param.keyLength % digestSize != 0)
+ blocks++;
+
+ if (param.saltLength > SIZE_MAX - 4 || blocks > UINT32_MAX)
+ @throw [OFOutOfRangeException exception];
+
+ extendedSalt = [OFSecureData
+ dataWithCount: param.saltLength + 4
+ allowsSwappableMemory: param.allowsSwappableMemory];
+ extendedSaltItems = extendedSalt.mutableItems;
+
+ @try {
+ uint32_t i = OFToBigEndian32(1);
+
+ [param.HMAC setKey: param.password
+ length: param.passwordLength];
+
+ memcpy(extendedSaltItems, param.salt, param.saltLength);
+
+ while (param.keyLength > 0) {
+ size_t length;
+
+ memcpy(extendedSaltItems + param.saltLength, &i, 4);
+
+ [param.HMAC reset];
+ [param.HMAC updateWithBuffer: extendedSaltItems
+ length: param.saltLength + 4];
+ memcpy(bufferItems, param.HMAC.digest, digestSize);
+ memcpy(digestItems, param.HMAC.digest, digestSize);
+
+ for (size_t j = 1; j < param.iterations; j++) {
+ [param.HMAC reset];
+ [param.HMAC updateWithBuffer: digestItems
+ length: digestSize];
+ memcpy(digestItems, param.HMAC.digest,
+ digestSize);
+
+ for (size_t k = 0; k < digestSize; k++)
+ bufferItems[k] ^= digestItems[k];
+ }
+
+ length = digestSize;
+ if (length > param.keyLength)
+ length = param.keyLength;
+
+ memcpy(param.key, bufferItems, length);
+ param.key += length;
+ param.keyLength -= length;
+
+ i = OFToBigEndian32(OFFromBigEndian32(i) + 1);
+ }
+ } @catch (id e) {
+ [extendedSalt zero];
+ [buffer zero];
+ [digest zero];
+
+ @throw e;
+ } @finally {
+ [param.HMAC zero];
+ }
+
+ objc_autoreleasePoolPop(pool);
+}
Index: src/OFPair.m
==================================================================
--- src/OFPair.m
+++ src/OFPair.m
@@ -83,18 +83,18 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD_HASH(hash, [_firstObject hash]);
- OF_HASH_ADD_HASH(hash, [_secondObject hash]);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAddHash(&hash, [_firstObject hash]);
+ OFHashAddHash(&hash, [_secondObject hash]);
+
+ OFHashFinalize(&hash);
return hash;
}
- (id)copy
ADDED src/OFPlainCondition.h
Index: src/OFPlainCondition.h
==================================================================
--- src/OFPlainCondition.h
+++ src/OFPlainCondition.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "objfw-defs.h"
+
+#include "platform.h"
+
+#if !defined(OF_HAVE_THREADS) || \
+ (!defined(OF_HAVE_PTHREADS) && !defined(OF_WINDOWS) && !defined(OF_AMIGAOS))
+# error No conditions available!
+#endif
+
+/* For OFTimeInterval */
+#import "OFObject.h"
+#import "OFPlainMutex.h"
+
+#if defined(OF_HAVE_PTHREADS)
+# include
+typedef pthread_cond_t OFPlainCondition;
+#elif defined(OF_WINDOWS)
+# include
+typedef struct {
+ HANDLE event;
+ volatile int count;
+} OFPlainCondition;
+#elif defined(OF_AMIGAOS)
+# include
+typedef struct {
+ struct OFPlainConditionWaitingTask {
+ struct Task *task;
+ unsigned char sigBit;
+ struct OFPlainConditionWaitingTask *next;
+ } *waitingTasks;
+} OFPlainCondition;
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern int OFPlainConditionNew(OFPlainCondition *condition);
+extern int OFPlainConditionSignal(OFPlainCondition *condition);
+extern int OFPlainConditionBroadcast(OFPlainCondition *condition);
+extern int OFPlainConditionWait(OFPlainCondition *condition,
+ OFPlainMutex *mutex);
+extern int OFPlainConditionTimedWait(OFPlainCondition *condition,
+ OFPlainMutex *mutex, OFTimeInterval timeout);
+#ifdef OF_AMIGAOS
+extern int OFPlainConditionWaitOrExecSignal(OFPlainCondition *condition,
+ OFPlainMutex *mutex, ULONG *signalMask);
+extern int OFPlainConditionTimedWaitOrExecSignal(OFPlainCondition *condition,
+ OFPlainMutex *mutex, OFTimeInterval timeout, ULONG *signalMask);
+#endif
+extern int OFPlainConditionFree(OFPlainCondition *condition);
+#ifdef __cplusplus
+}
+#endif
ADDED src/OFPlainCondition.m
Index: src/OFPlainCondition.m
==================================================================
--- src/OFPlainCondition.m
+++ src/OFPlainCondition.m
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#include "platform.h"
+
+#if defined(OF_HAVE_PTHREADS)
+# include "platform/posix/OFPlainCondition.m"
+#elif defined(OF_WINDOWS)
+# include "platform/windows/OFPlainCondition.m"
+#elif defined(OF_AMIGAOS)
+# include "platform/amiga/OFPlainCondition.m"
+#endif
ADDED src/OFPlainMutex.h
Index: src/OFPlainMutex.h
==================================================================
--- src/OFPlainMutex.h
+++ src/OFPlainMutex.h
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "objfw-defs.h"
+
+#include
+
+#include "platform.h"
+
+#if !defined(OF_HAVE_THREADS) || \
+ (!defined(OF_HAVE_PTHREADS) && !defined(OF_WINDOWS) && !defined(OF_AMIGAOS))
+# error No mutexes available!
+#endif
+
+#import "macros.h"
+
+#if defined(OF_HAVE_PTHREADS)
+# include
+typedef pthread_mutex_t OFPlainMutex;
+#elif defined(OF_WINDOWS)
+# include
+typedef CRITICAL_SECTION OFPlainMutex;
+#elif defined(OF_AMIGAOS)
+# include
+typedef struct SignalSemaphore OFPlainMutex;
+#endif
+
+#if defined(OF_HAVE_ATOMIC_OPS)
+# import "OFAtomic.h"
+typedef volatile int OFSpinlock;
+#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
+typedef pthread_spinlock_t OFSpinlock;
+#else
+typedef OFPlainMutex OFSpinlock;
+#endif
+
+#ifdef OF_HAVE_SCHED_YIELD
+# include
+#endif
+
+#if defined(OF_HAVE_RECURSIVE_PTHREAD_MUTEXES) || defined(OF_WINDOWS) || \
+ defined(OF_AMIGAOS)
+# define OFPlainRecursiveMutex OFPlainMutex
+#else
+# import "OFTLSKey.h"
+typedef struct {
+ OFPlainMutex mutex;
+ OFTLSKey count;
+} OFPlainRecursiveMutex;
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern int OFPlainMutexNew(OFPlainMutex *mutex);
+extern int OFPlainMutexLock(OFPlainMutex *mutex);
+extern int OFPlainMutexTryLock(OFPlainMutex *mutex);
+extern int OFPlainMutexUnlock(OFPlainMutex *mutex);
+extern int OFPlainMutexFree(OFPlainMutex *mutex);
+extern int OFPlainRecursiveMutexNew(OFPlainRecursiveMutex *rmutex);
+extern int OFPlainRecursiveMutexLock(OFPlainRecursiveMutex *rmutex);
+extern int OFPlainRecursiveMutexTryLock(OFPlainRecursiveMutex *rmutex);
+extern int OFPlainRecursiveMutexUnlock(OFPlainRecursiveMutex *rmutex);
+extern int OFPlainRecursiveMutexFree(OFPlainRecursiveMutex *rmutex);
+#ifdef __cplusplus
+}
+#endif
+
+/* Spinlocks are inlined for performance. */
+
+static OF_INLINE void
+OFYieldThread(void)
+{
+#if defined(OF_HAVE_SCHED_YIELD)
+ sched_yield();
+#elif defined(OF_WINDOWS)
+ Sleep(0);
+#endif
+}
+
+static OF_INLINE int
+OFSpinlockNew(OFSpinlock *spinlock)
+{
+#if defined(OF_HAVE_ATOMIC_OPS)
+ *spinlock = 0;
+ return 0;
+#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
+ return pthread_spin_init(spinlock, 0);
+#else
+ return OFPlainMutexNew(spinlock);
+#endif
+}
+
+static OF_INLINE int
+OFSpinlockTryLock(OFSpinlock *spinlock)
+{
+#if defined(OF_HAVE_ATOMIC_OPS)
+ if (OFAtomicIntCompareAndSwap(spinlock, 0, 1)) {
+ OFAcquireMemoryBarrier();
+ return 0;
+ }
+
+ return EBUSY;
+#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
+ return pthread_spin_trylock(spinlock);
+#else
+ return OFPlainMutexTryLock(spinlock);
+#endif
+}
+
+static OF_INLINE int
+OFSpinlockLock(OFSpinlock *spinlock)
+{
+#if defined(OF_HAVE_ATOMIC_OPS)
+ size_t i;
+
+ for (i = 0; i < 10; i++)
+ if (OFSpinlockTryLock(spinlock) == 0)
+ return 0;
+
+ while (OFSpinlockTryLock(spinlock) == EBUSY)
+ OFYieldThread();
+
+ return 0;
+#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
+ return pthread_spin_lock(spinlock);
+#else
+ return OFPlainMutexLock(spinlock);
+#endif
+}
+
+static OF_INLINE int
+OFSpinlockUnlock(OFSpinlock *spinlock)
+{
+#if defined(OF_HAVE_ATOMIC_OPS)
+ bool ret = OFAtomicIntCompareAndSwap(spinlock, 1, 0);
+
+ OFReleaseMemoryBarrier();
+
+ return (ret ? 0 : EINVAL);
+#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
+ return pthread_spin_unlock(spinlock);
+#else
+ return OFPlainMutexUnlock(spinlock);
+#endif
+}
+
+static OF_INLINE int
+OFSpinlockFree(OFSpinlock *spinlock)
+{
+#if defined(OF_HAVE_ATOMIC_OPS)
+ return 0;
+#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
+ return pthread_spin_destroy(spinlock);
+#else
+ return OFPlainMutexFree(spinlock);
+#endif
+}
ADDED src/OFPlainMutex.m
Index: src/OFPlainMutex.m
==================================================================
--- src/OFPlainMutex.m
+++ src/OFPlainMutex.m
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#include "platform.h"
+
+#if defined(OF_HAVE_PTHREADS)
+# include "platform/posix/OFPlainMutex.m"
+#elif defined(OF_WINDOWS)
+# include "platform/windows/OFPlainMutex.m"
+#elif defined(OF_AMIGAOS)
+# include "platform/amiga/OFPlainMutex.m"
+#endif
ADDED src/OFPlainThread.h
Index: src/OFPlainThread.h
==================================================================
--- src/OFPlainThread.h
+++ src/OFPlainThread.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "objfw-defs.h"
+
+#include "platform.h"
+
+#if !defined(OF_HAVE_THREADS) || \
+ (!defined(OF_HAVE_PTHREADS) && !defined(OF_WINDOWS) && !defined(OF_AMIGAOS))
+# error No threads available!
+#endif
+
+#import "macros.h"
+
+#if defined(OF_HAVE_PTHREADS)
+# include
+typedef pthread_t OFPlainThread;
+#elif defined(OF_WINDOWS)
+# include
+typedef HANDLE OFPlainThread;
+#elif defined(OF_AMIGAOS)
+# include
+# include
+typedef struct {
+ struct Task *task;
+ void (*function)(id);
+ id object;
+ struct SignalSemaphore semaphore;
+ struct Task *joinTask;
+ unsigned char joinSigBit;
+ bool detached, done;
+} *OFPlainThread;
+#endif
+
+typedef struct {
+ float priority;
+ size_t stackSize;
+} OFPlainThreadAttributes;
+
+#if defined(OF_HAVE_PTHREADS)
+static OF_INLINE OFPlainThread
+OFCurrentPlainThread(void)
+{
+ return pthread_self();
+}
+
+static OF_INLINE bool
+OFPlainThreadIsCurrent(OFPlainThread thread)
+{
+ return pthread_equal(thread, pthread_self());
+}
+#elif defined(OF_WINDOWS)
+static OF_INLINE OFPlainThread
+OFCurrentPlainThread(void)
+{
+ return GetCurrentThread();
+}
+
+static OF_INLINE bool
+OFPlainThreadIsCurrent(OFPlainThread thread)
+{
+ return (thread == GetCurrentThread());
+}
+#elif defined(OF_AMIGAOS)
+extern OFPlainThread OFCurrentPlainThread(void);
+
+static OF_INLINE bool
+OFPlainThreadIsCurrent(OFPlainThread thread)
+{
+ return (thread->thread == FindTask(NULL));
+}
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern int OFPlainThreadAttributesInit(OFPlainThreadAttributes *attr);
+extern int OFPlainThreadNew(OFPlainThread *thread, const char *name,
+ void (*function)(id), id object, const OFPlainThreadAttributes *attr);
+extern void OFSetThreadName(const char *name);
+extern int OFPlainThreadJoin(OFPlainThread thread);
+extern int OFPlainThreadDetach(OFPlainThread thread);
+#ifdef __cplusplus
+}
+#endif
ADDED src/OFPlainThread.m
Index: src/OFPlainThread.m
==================================================================
--- src/OFPlainThread.m
+++ src/OFPlainThread.m
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#include "platform.h"
+
+#if defined(OF_HAVE_PTHREADS)
+# include "platform/posix/OFPlainThread.m"
+#elif defined(OF_WINDOWS)
+# include "platform/windows/OFPlainThread.m"
+#elif defined(OF_AMIGAOS)
+# include "platform/amiga/OFPlainThread.m"
+#endif
Index: src/OFPlugin.h
==================================================================
--- src/OFPlugin.h
+++ src/OFPlugin.h
@@ -17,30 +17,40 @@
@class OFString;
#ifndef OF_WINDOWS
# include
-# define OF_RTLD_LAZY RTLD_LAZY
-# define OF_RTLD_NOW RTLD_NOW
-typedef void *of_plugin_handle_t;
+typedef void *OFPluginHandle;
+
+typedef enum {
+ OFDLOpenFlagLazy = RTLD_LAZY,
+ OFDLOpenFlagNow = RTLD_NOW
+} OFDLOpenFlags;
#else
# include
-# define OF_RTLD_LAZY 0
-# define OF_RTLD_NOW 0
-typedef HMODULE of_plugin_handle_t;
+typedef HMODULE OFPluginHandle;
+
+typedef enum {
+ OFDLOpenFlagLazy = 0,
+ OFDLOpenFlagNow = 0
+} OFDLOpenFlags;
#endif
OF_ASSUME_NONNULL_BEGIN
/**
* @class OFPlugin OFPlugin.h ObjFW/OFPlugin.h
*
* @brief Provides a system for loading plugins at runtime.
+ *
+ * A plugin must subclass @ref OFPlugin and have a global function called
+ * `OFPluginInit`, which returns an instance of the @ref OFPlugin subclass and
+ * takes no parameters.
*/
@interface OFPlugin: OFObject
{
- of_plugin_handle_t _pluginHandle;
+ OFPluginHandle _pluginHandle;
OF_RESERVE_IVARS(OFPlugin, 4)
}
/**
* @brief Loads a plugin from a file.
@@ -52,14 +62,14 @@
@end
#ifdef __cplusplus
extern "C" {
#endif
-extern of_plugin_handle_t of_dlopen(OFString *path, int flags);
-extern void *of_dlsym(of_plugin_handle_t handle, const char *symbol);
-extern OFString *_Nullable of_dlerror(void);
-extern void of_dlclose(of_plugin_handle_t handle);
+extern OFPluginHandle OFDLOpen(OFString *path, OFDLOpenFlags flags);
+extern void *OFDLSym(OFPluginHandle handle, const char *symbol);
+extern OFString *_Nullable OFDLError(void);
+extern void OFDLClose(OFPluginHandle handle);
#ifdef __cplusplus
}
#endif
OF_ASSUME_NONNULL_END
Index: src/OFPlugin.m
==================================================================
--- src/OFPlugin.m
+++ src/OFPlugin.m
@@ -28,14 +28,14 @@
#import "OFSystemInfo.h"
#import "OFInitializationFailedException.h"
#import "OFLoadPluginFailedException.h"
-typedef OFPlugin *(*init_plugin_t)(void);
+typedef OFPlugin *(*PluginInit)(void);
-of_plugin_handle_t
-of_dlopen(OFString *path, int flags)
+OFPluginHandle
+OFDLOpen(OFString *path, OFDLOpenFlags flags)
{
#ifndef OF_WINDOWS
return dlopen([path cStringWithEncoding: [OFLocale encoding]], flags);
#else
if (path == nil)
@@ -48,31 +48,31 @@
[path cStringWithEncoding: [OFLocale encoding]]);
#endif
}
void *
-of_dlsym(of_plugin_handle_t handle, const char *symbol)
+OFDLSym(OFPluginHandle handle, const char *symbol)
{
#ifndef OF_WINDOWS
return dlsym(handle, symbol);
#else
return (void *)(uintptr_t)GetProcAddress(handle, symbol);
#endif
}
void
-of_dlclose(of_plugin_handle_t handle)
+OFDLClose(OFPluginHandle handle)
{
#ifndef OF_WINDOWS
dlclose(handle);
#else
FreeLibrary(handle);
#endif
}
OFString *
-of_dlerror(void)
+OFDLError(void)
{
#ifndef OF_WINDOWS
return [OFString stringWithCString: dlerror()
encoding: [OFLocale encoding]];
#else
@@ -82,12 +82,12 @@
@implementation OFPlugin
+ (id)pluginWithPath: (OFString *)path
{
void *pool = objc_autoreleasePoolPush();
- of_plugin_handle_t handle;
- init_plugin_t initPlugin;
+ OFPluginHandle handle;
+ PluginInit initPlugin;
OFPlugin *plugin;
#if defined(OF_MACOS)
path = [path stringByAppendingFormat: @".bundle/Contents/MacOS/%@",
path.lastPathComponent];
@@ -96,20 +96,20 @@
path.lastPathComponent];
#else
path = [path stringByAppendingString: @PLUGIN_SUFFIX];
#endif
- if ((handle = of_dlopen(path, OF_RTLD_LAZY)) == NULL)
+ if ((handle = OFDLOpen(path, OFDLOpenFlagLazy)) == NULL)
@throw [OFLoadPluginFailedException
exceptionWithPath: path
- error: of_dlerror()];
+ error: OFDLError()];
objc_autoreleasePoolPop(pool);
- initPlugin = (init_plugin_t)(uintptr_t)of_dlsym(handle, "init_plugin");
- if (initPlugin == (init_plugin_t)0 || (plugin = initPlugin()) == nil) {
- of_dlclose(handle);
+ initPlugin = (PluginInit)(uintptr_t)OFDLSym(handle, "OFPluginInit");
+ if (initPlugin == (PluginInit)0 || (plugin = initPlugin()) == nil) {
+ OFDLClose(handle);
@throw [OFInitializationFailedException
exceptionWithClass: self];
}
plugin->_pluginHandle = handle;
@@ -132,12 +132,12 @@
return [super init];
}
- (void)dealloc
{
- of_plugin_handle_t h = _pluginHandle;
+ OFPluginHandle h = _pluginHandle;
[super dealloc];
- of_dlclose(h);
+ OFDLClose(h);
}
@end
Index: src/OFPointValue.h
==================================================================
--- src/OFPointValue.h
+++ src/OFPointValue.h
@@ -17,10 +17,12 @@
OF_ASSUME_NONNULL_BEGIN
@interface OFPointValue: OFValue
{
- of_point_t _point;
+ OFPoint _point;
}
+
+- (instancetype)initWithPoint: (OFPoint)point;
@end
OF_ASSUME_NONNULL_END
Index: src/OFPointValue.m
==================================================================
--- src/OFPointValue.m
+++ src/OFPointValue.m
@@ -20,11 +20,11 @@
#import "OFOutOfRangeException.h"
@implementation OFPointValue
@synthesize pointValue = _point;
-- (instancetype)initWithPoint: (of_point_t)point
+- (instancetype)initWithPoint: (OFPoint)point
{
self = [super init];
_point = point;
@@ -31,11 +31,11 @@
return self;
}
- (const char *)objCType
{
- return @encode(of_point_t);
+ return @encode(OFPoint);
}
- (void)getValue: (void *)value size: (size_t)size
{
if (size != sizeof(_point))
@@ -45,8 +45,8 @@
}
- (OFString *)description
{
return [OFString stringWithFormat:
- @"", _point.x, _point.y];
+ @"", _point.x, _point.y];
}
@end
Index: src/OFPointerValue.h
==================================================================
--- src/OFPointerValue.h
+++ src/OFPointerValue.h
@@ -19,8 +19,10 @@
@interface OFPointerValue: OFValue
{
void *_pointer;
}
+
+- (instancetype)initWithPointer: (const void *)pointer;
@end
OF_ASSUME_NONNULL_END
Index: src/OFPollKernelEventObserver.m
==================================================================
--- src/OFPollKernelEventObserver.m
+++ src/OFPollKernelEventObserver.m
@@ -24,16 +24,15 @@
# include
#endif
#import "OFPollKernelEventObserver.h"
#import "OFData.h"
+#import "OFSocket+Private.h"
#import "OFObserveFailedException.h"
#import "OFOutOfRangeException.h"
-#import "socket_helpers.h"
-
#ifdef OF_WII
# define pollfd pollsd
# define fd socket
#endif
@@ -48,11 +47,11 @@
_FDs = [[OFMutableData alloc] initWithItemSize:
sizeof(struct pollfd)];
[_FDs addItem: &p];
_maxFD = _cancelFD[0];
- _FDToObject = of_alloc((size_t)_maxFD + 1, sizeof(id));
+ _FDToObject = OFAllocMemory((size_t)_maxFD + 1, sizeof(id));
} @catch (id e) {
[self release];
@throw e;
}
@@ -60,11 +59,11 @@
}
- (void)dealloc
{
[_FDs release];
- free(_FDToObject);
+ OFFreeMemory(_FDToObject);
[super dealloc];
}
static void
@@ -93,11 +92,11 @@
if (!found) {
struct pollfd p = { fd, events, 0 };
if (fd > self->_maxFD) {
self->_maxFD = fd;
- self->_FDToObject = of_realloc(self->_FDToObject,
+ self->_FDToObject = OFResizeMemory(self->_FDToObject,
(size_t)self->_maxFD + 1, sizeof(id));
}
self->_FDToObject[fd] = object;
[self->_FDs addItem: &p];
@@ -160,11 +159,11 @@
removeObject(self, object, object.fileDescriptorForWriting, POLLOUT);
[super removeObjectForWriting: object];
}
-- (void)observeForTimeInterval: (of_time_interval_t)timeInterval
+- (void)observeForTimeInterval: (OFTimeInterval)timeInterval
{
void *pool;
struct pollfd *FDs;
int events;
size_t nFDs;
@@ -197,14 +196,14 @@
if (FDs[i].fd == _cancelFD[0]) {
char buffer;
#ifdef OF_HAVE_PIPE
- OF_ENSURE(read(_cancelFD[0], &buffer, 1) == 1);
+ OFEnsure(read(_cancelFD[0], &buffer, 1) == 1);
#else
- OF_ENSURE(recvfrom(_cancelFD[0], &buffer, 1,
- 0, NULL, NULL) == 1);
+ OFEnsure(recvfrom(_cancelFD[0], &buffer, 1, 0,
+ NULL, NULL) == 1);
#endif
FDs[i].revents = 0;
continue;
}
Index: src/OFRIPEMD160Hash.h
==================================================================
--- src/OFRIPEMD160Hash.h
+++ src/OFRIPEMD160Hash.h
@@ -26,14 +26,14 @@
*/
OF_SUBCLASSING_RESTRICTED
@interface OFRIPEMD160Hash: OFObject
{
OFSecureData *_iVarsData;
- struct of_ripemd160_hash_ivars {
+ struct {
uint32_t state[5];
uint64_t bits;
- union of_ripemd160_hash_buffer {
+ union {
unsigned char bytes[64];
uint32_t words[16];
} buffer;
size_t bufferLength;
} *_iVars;
Index: src/OFRIPEMD160Hash.m
==================================================================
--- src/OFRIPEMD160Hash.m
+++ src/OFRIPEMD160Hash.m
@@ -21,12 +21,12 @@
#import "OFSecureData.h"
#import "OFHashAlreadyCalculatedException.h"
#import "OFOutOfRangeException.h"
-#define DIGEST_SIZE 20
-#define BLOCK_SIZE 64
+static const size_t digestSize = 20;
+static const size_t blockSize = 64;
OF_DIRECT_MEMBERS
@interface OFRIPEMD160Hash ()
- (void)of_resetState;
@end
@@ -69,11 +69,11 @@
static OF_INLINE void
byteSwapVectorIfBE(uint32_t *vector, uint_fast8_t length)
{
#ifdef OF_BIG_ENDIAN
for (uint_fast8_t i = 0; i < length; i++)
- vector[i] = OF_BSWAP32(vector[i]);
+ vector[i] = OFByteSwap32(vector[i]);
#endif
}
static void
processBlock(uint32_t *state, uint32_t *buffer)
@@ -87,33 +87,33 @@
new[3] = new2[3] = state[3];
new[4] = new2[4] = state[4];
byteSwapVectorIfBE(buffer, 16);
-#define LOOP_BODY(f, g, k, k2) \
- { \
- uint32_t tmp; \
- \
- tmp = new[0] + f(new[1], new[2], new[3]) + \
- buffer[wordOrder[i]] + k; \
- tmp = OF_ROL(tmp, rotateBits[i]) + new[4]; \
- \
- new[0] = new[4]; \
- new[4] = new[3]; \
- new[3] = OF_ROL(new[2], 10); \
- new[2] = new[1]; \
- new[1] = tmp; \
- \
- tmp = new2[0] + g(new2[1], new2[2], new2[3]) + \
- buffer[wordOrder2[i]] + k2; \
- tmp = OF_ROL(tmp, rotateBits2[i]) + new2[4]; \
- \
- new2[0] = new2[4]; \
- new2[4] = new2[3]; \
- new2[3] = OF_ROL(new2[2], 10); \
- new2[2] = new2[1]; \
- new2[1] = tmp; \
+#define LOOP_BODY(f, g, k, k2) \
+ { \
+ uint32_t tmp; \
+ \
+ tmp = new[0] + f(new[1], new[2], new[3]) + \
+ buffer[wordOrder[i]] + k; \
+ tmp = OFRotateLeft(tmp, rotateBits[i]) + new[4]; \
+ \
+ new[0] = new[4]; \
+ new[4] = new[3]; \
+ new[3] = OFRotateLeft(new[2], 10); \
+ new[2] = new[1]; \
+ new[1] = tmp; \
+ \
+ tmp = new2[0] + g(new2[1], new2[2], new2[3]) + \
+ buffer[wordOrder2[i]] + k2; \
+ tmp = OFRotateLeft(tmp, rotateBits2[i]) + new2[4]; \
+ \
+ new2[0] = new2[4]; \
+ new2[4] = new2[3]; \
+ new2[3] = OFRotateLeft(new2[2], 10); \
+ new2[2] = new2[1]; \
+ new2[1] = tmp; \
}
for (; i < 16; i++)
LOOP_BODY(F, J, 0x00000000, 0x50A28BE6)
for (; i < 32; i++)
@@ -139,16 +139,16 @@
@synthesize calculated = _calculated;
@synthesize allowsSwappableMemory = _allowsSwappableMemory;
+ (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
+ (size_t)blockSize
{
- return BLOCK_SIZE;
+ return blockSize;
}
+ (instancetype)hashWithAllowsSwappableMemory: (bool)allowsSwappableMemory
{
return [[[self alloc] initWithAllowsSwappableMemory:
@@ -192,16 +192,16 @@
[super dealloc];
}
- (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
- (size_t)blockSize
{
- return BLOCK_SIZE;
+ return blockSize;
}
- (id)copy
{
OFRIPEMD160Hash *copy = [[OFRIPEMD160Hash alloc] of_init];
@@ -260,25 +260,25 @@
{
if (_calculated)
return (const unsigned char *)_iVars->state;
_iVars->buffer.bytes[_iVars->bufferLength] = 0x80;
- of_explicit_memset(_iVars->buffer.bytes + _iVars->bufferLength + 1, 0,
+ OFZeroMemory(_iVars->buffer.bytes + _iVars->bufferLength + 1,
64 - _iVars->bufferLength - 1);
if (_iVars->bufferLength >= 56) {
processBlock(_iVars->state, _iVars->buffer.words);
- of_explicit_memset(_iVars->buffer.bytes, 0, 64);
+ OFZeroMemory(_iVars->buffer.bytes, 64);
}
_iVars->buffer.words[14] =
- OF_BSWAP32_IF_BE((uint32_t)(_iVars->bits & 0xFFFFFFFF));
+ OFToLittleEndian32((uint32_t)(_iVars->bits & 0xFFFFFFFF));
_iVars->buffer.words[15] =
- OF_BSWAP32_IF_BE((uint32_t)(_iVars->bits >> 32));
+ OFToLittleEndian32((uint32_t)(_iVars->bits >> 32));
processBlock(_iVars->state, _iVars->buffer.words);
- of_explicit_memset(&_iVars->buffer, 0, sizeof(_iVars->buffer));
+ OFZeroMemory(&_iVars->buffer, sizeof(_iVars->buffer));
byteSwapVectorIfBE(_iVars->state, 5);
_calculated = true;
return (const unsigned char *)_iVars->state;
}
@@ -285,10 +285,10 @@
- (void)reset
{
[self of_resetState];
_iVars->bits = 0;
- of_explicit_memset(&_iVars->buffer, 0, sizeof(_iVars->buffer));
+ OFZeroMemory(&_iVars->buffer, sizeof(_iVars->buffer));
_iVars->bufferLength = 0;
_calculated = false;
}
@end
Index: src/OFRangeCharacterSet.h
==================================================================
--- src/OFRangeCharacterSet.h
+++ src/OFRangeCharacterSet.h
@@ -17,10 +17,10 @@
OF_ASSUME_NONNULL_BEGIN
@interface OFRangeCharacterSet: OFCharacterSet
{
- of_range_t _range;
+ OFRange _range;
}
@end
OF_ASSUME_NONNULL_END
Index: src/OFRangeCharacterSet.m
==================================================================
--- src/OFRangeCharacterSet.m
+++ src/OFRangeCharacterSet.m
@@ -24,11 +24,11 @@
- (instancetype)init
{
OF_INVALID_INIT_METHOD
}
-- (instancetype)initWithRange: (of_range_t)range
+- (instancetype)initWithRange: (OFRange)range
{
self = [super init];
@try {
if (SIZE_MAX - range.location < range.length)
@@ -41,11 +41,11 @@
}
return self;
}
-- (bool)characterIsMember: (of_unichar_t)character
+- (bool)characterIsMember: (OFUnichar)character
{
return (character >= _range.location &&
character < _range.location + _range.length);
}
@end
Index: src/OFRangeValue.h
==================================================================
--- src/OFRangeValue.h
+++ src/OFRangeValue.h
@@ -17,10 +17,12 @@
OF_ASSUME_NONNULL_BEGIN
@interface OFRangeValue: OFValue
{
- of_range_t _range;
+ OFRange _range;
}
+
+- (instancetype)initWithRange: (OFRange)range;
@end
OF_ASSUME_NONNULL_END
Index: src/OFRangeValue.m
==================================================================
--- src/OFRangeValue.m
+++ src/OFRangeValue.m
@@ -20,11 +20,11 @@
#import "OFOutOfRangeException.h"
@implementation OFRangeValue
@synthesize rangeValue = _range;
-- (instancetype)initWithRange: (of_range_t)range
+- (instancetype)initWithRange: (OFRange)range
{
self = [super init];
_range = range;
@@ -31,11 +31,11 @@
return self;
}
- (const char *)objCType
{
- return @encode(of_range_t);
+ return @encode(OFRange);
}
- (void)getValue: (void *)value size: (size_t)size
{
if (size != sizeof(_range))
@@ -45,9 +45,9 @@
}
- (OFString *)description
{
return [OFString stringWithFormat:
- @"",
+ @"",
_range.location, _range.length];
}
@end
ADDED src/OFRectValue.h
Index: src/OFRectValue.h
==================================================================
--- src/OFRectValue.h
+++ src/OFRectValue.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#import "OFValue.h"
+
+OF_ASSUME_NONNULL_BEGIN
+
+@interface OFRectValue: OFValue
+{
+ OFRect _rect;
+}
+
+- (instancetype)initWithRect: (OFRect)rect;
+@end
+
+OF_ASSUME_NONNULL_END
ADDED src/OFRectValue.m
Index: src/OFRectValue.m
==================================================================
--- src/OFRectValue.m
+++ src/OFRectValue.m
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#import "OFRectValue.h"
+#import "OFMethodSignature.h"
+#import "OFString.h"
+
+#import "OFOutOfRangeException.h"
+
+@implementation OFRectValue
+@synthesize rectValue = _rect;
+
+- (instancetype)initWithRect: (OFRect)rect
+{
+ self = [super init];
+
+ _rect = rect;
+
+ return self;
+}
+
+- (const char *)objCType
+{
+ return @encode(OFRect);
+}
+
+- (void)getValue: (void *)value size: (size_t)size
+{
+ if (size != sizeof(_rect))
+ @throw [OFOutOfRangeException exception];
+
+ memcpy(value, &_rect, sizeof(_rect));
+}
+
+- (OFString *)description
+{
+ return [OFString stringWithFormat:
+ @"",
+ _rect.origin.x, _rect.origin.y,
+ _rect.size.width, _rect.size.height];
+}
+@end
DELETED src/OFRectangleValue.h
Index: src/OFRectangleValue.h
==================================================================
--- src/OFRectangleValue.h
+++ src/OFRectangleValue.h
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) 2008-2021 Jonathan Schleifer
- *
- * All rights reserved.
- *
- * This file is part of ObjFW. It may be distributed under the terms of the
- * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
- * the packaging of this file.
- *
- * Alternatively, it may be distributed under the terms of the GNU General
- * Public License, either version 2 or 3, which can be found in the file
- * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
- * file.
- */
-
-#import "OFValue.h"
-
-OF_ASSUME_NONNULL_BEGIN
-
-@interface OFRectangleValue: OFValue
-{
- of_rectangle_t _rectangle;
-}
-@end
-
-OF_ASSUME_NONNULL_END
DELETED src/OFRectangleValue.m
Index: src/OFRectangleValue.m
==================================================================
--- src/OFRectangleValue.m
+++ src/OFRectangleValue.m
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2008-2021 Jonathan Schleifer
- *
- * All rights reserved.
- *
- * This file is part of ObjFW. It may be distributed under the terms of the
- * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
- * the packaging of this file.
- *
- * Alternatively, it may be distributed under the terms of the GNU General
- * Public License, either version 2 or 3, which can be found in the file
- * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
- * file.
- */
-
-#import "OFRectangleValue.h"
-#import "OFMethodSignature.h"
-#import "OFString.h"
-
-#import "OFOutOfRangeException.h"
-
-@implementation OFRectangleValue
-@synthesize rectangleValue = _rectangle;
-
-- (instancetype)initWithRectangle: (of_rectangle_t)rectangle
-{
- self = [super init];
-
- _rectangle = rectangle;
-
- return self;
-}
-
-- (const char *)objCType
-{
- return @encode(of_rectangle_t);
-}
-
-- (void)getValue: (void *)value size: (size_t)size
-{
- if (size != sizeof(_rectangle))
- @throw [OFOutOfRangeException exception];
-
- memcpy(value, &_rectangle, sizeof(_rectangle));
-}
-
-- (OFString *)description
-{
- return [OFString stringWithFormat:
- @"",
- _rectangle.origin.x, _rectangle.origin.y,
- _rectangle.size.width, _rectangle.size.height];
-}
-@end
Index: src/OFRecursiveMutex.h
==================================================================
--- src/OFRecursiveMutex.h
+++ src/OFRecursiveMutex.h
@@ -13,12 +13,11 @@
* file.
*/
#import "OFObject.h"
#import "OFLocking.h"
-
-#import "mutex.h"
+#import "OFPlainMutex.h"
OF_ASSUME_NONNULL_BEGIN
/**
* @class OFRecursiveMutex OFRecursiveMutex.h ObjFW/OFRecursiveMutex.h
@@ -27,11 +26,11 @@
* recursively.
*/
OF_SUBCLASSING_RESTRICTED
@interface OFRecursiveMutex: OFObject
{
- of_rmutex_t _rmutex;
+ OFPlainRecursiveMutex _rmutex;
bool _initialized;
OFString *_Nullable _name;
}
/**
Index: src/OFRecursiveMutex.m
==================================================================
--- src/OFRecursiveMutex.m
+++ src/OFRecursiveMutex.m
@@ -35,11 +35,11 @@
- (instancetype)init
{
self = [super init];
- if (of_rmutex_new(&_rmutex) != 0) {
+ if (OFPlainRecursiveMutexNew(&_rmutex) != 0) {
Class c = self.class;
[self release];
@throw [OFInitializationFailedException exceptionWithClass: c];
}
@@ -49,14 +49,14 @@
}
- (void)dealloc
{
if (_initialized) {
- int error = of_rmutex_free(&_rmutex);
+ int error = OFPlainRecursiveMutexFree(&_rmutex);
if (error != 0) {
- OF_ENSURE(error == EBUSY);
+ OFEnsure(error == EBUSY);
@throw [OFStillLockedException exceptionWithLock: self];
}
}
@@ -65,20 +65,20 @@
[super dealloc];
}
- (void)lock
{
- int error = of_rmutex_lock(&_rmutex);
+ int error = OFPlainRecursiveMutexLock(&_rmutex);
if (error != 0)
@throw [OFLockFailedException exceptionWithLock: self
errNo: error];
}
- (bool)tryLock
{
- int error = of_rmutex_trylock(&_rmutex);
+ int error = OFPlainRecursiveMutexTryLock(&_rmutex);
if (error != 0) {
if (error == EBUSY)
return false;
else
@@ -89,11 +89,11 @@
return true;
}
- (void)unlock
{
- int error = of_rmutex_unlock(&_rmutex);
+ int error = OFPlainRecursiveMutexUnlock(&_rmutex);
if (error != 0)
@throw [OFUnlockFailedException exceptionWithLock: self
errNo: error];
}
Index: src/OFRunLoop+Private.h
==================================================================
--- src/OFRunLoop+Private.h
+++ src/OFRunLoop+Private.h
@@ -37,98 +37,92 @@
#ifdef OF_HAVE_SOCKETS
+ (void)of_addAsyncReadForStream: (OFStream *)
stream
buffer: (void *)buffer
length: (size_t)length
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (nullable of_stream_async_read_block_t)block
+ block: (nullable OFStreamAsyncReadBlock)block
# endif
delegate: (nullable id )delegate;
+ (void)of_addAsyncReadForStream: (OFStream *)
stream
buffer: (void *)buffer
exactLength: (size_t)length
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (nullable of_stream_async_read_block_t)block
+ block: (nullable OFStreamAsyncReadBlock)block
# endif
delegate: (nullable id )delegate;
+ (void)of_addAsyncReadLineForStream: (OFStream *)
stream
- encoding: (of_string_encoding_t)encoding
- mode: (of_run_loop_mode_t)mode
+ encoding: (OFStringEncoding)encoding
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (nullable
- of_stream_async_read_line_block_t)
- block
+ block: (nullable OFStreamAsyncReadLineBlock)block
# endif
delegate: (nullable id )delegate;
+ (void)of_addAsyncWriteForStream: (OFStream *)
stream
data: (OFData *)data
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (nullable of_stream_async_write_data_block_t)
- block
+ block: (nullable OFStreamAsyncWriteDataBlock)block
# endif
delegate: (nullable id )delegate;
+ (void)of_addAsyncWriteForStream: (OFStream *)
stream
string: (OFString *)string
- encoding: (of_string_encoding_t)encoding
- mode: (of_run_loop_mode_t)mode
+ encoding: (OFStringEncoding)encoding
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (nullable
- of_stream_async_write_string_block_t)
- block
+ block: (nullable OFStreamAsyncWriteStringBlock)block
# endif
delegate: (nullable id )delegate;
# if !defined(OF_WII) && !defined(OF_NINTENDO_3DS)
+ (void)of_addAsyncConnectForSocket: (id)socket
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
delegate: (id )delegate;
# endif
+ (void)of_addAsyncAcceptForSocket: (id)socket
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
block: (nullable id)block
delegate: (nullable id)delegate;
+ (void)of_addAsyncReceiveForDatagramSocket: (OFDatagramSocket *)socket
buffer: (void *)buffer
length: (size_t)length
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (nullable of_datagram_socket_async_receive_block_t)block
+ block: (nullable OFDatagramSocketAsyncReceiveBlock)block
# endif
delegate: (nullable id ) delegate;
+ (void)of_addAsyncSendForDatagramSocket: (OFDatagramSocket *)socket
data: (OFData *)data
- receiver: (const of_socket_address_t *)receiver
- mode: (of_run_loop_mode_t)mode
+ receiver: (const OFSocketAddress *)receiver
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (nullable of_datagram_socket_async_send_data_block_t)block
+ block: (nullable OFDatagramSocketAsyncSendDataBlock)block
# endif
delegate: (nullable id )delegate;
+ (void)of_addAsyncReceiveForSequencedPacketSocket:
(OFSequencedPacketSocket *)socket
buffer: (void *)buffer
length: (size_t)length
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (nullable of_sequenced_packet_socket_async_receive_block_t)block
+ block: (nullable OFSequencedPacketSocketAsyncReceiveBlock)block
# endif
delegate: (nullable id ) delegate;
+ (void)of_addAsyncSendForSequencedPacketSocket:
(OFSequencedPacketSocket *)socket
data: (OFData *)data
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (nullable of_sequenced_packet_socket_async_send_data_block_t)block
+ block: (nullable OFSequencedPacketSocketAsyncSendDataBlock)block
# endif
delegate: (nullable id )delegate;
-+ (void)of_cancelAsyncRequestsForObject: (id)object
- mode: (of_run_loop_mode_t)mode;
++ (void)of_cancelAsyncRequestsForObject: (id)object mode: (OFRunLoopMode)mode;
#endif
-- (void)of_removeTimer: (OFTimer *)timer forMode: (of_run_loop_mode_t)mode;
+- (void)of_removeTimer: (OFTimer *)timer forMode: (OFRunLoopMode)mode;
@end
OF_ASSUME_NONNULL_END
Index: src/OFRunLoop.h
==================================================================
--- src/OFRunLoop.h
+++ src/OFRunLoop.h
@@ -37,19 +37,19 @@
@class OFDate;
/**
* @brief A mode for an OFRunLoop.
*/
-typedef OFConstantString *of_run_loop_mode_t;
+typedef OFConstantString *OFRunLoopMode;
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief The default mode for an OFRunLoop.
*/
-extern const of_run_loop_mode_t of_run_loop_mode_default;
+extern const OFRunLoopMode OFDefaultRunLoopMode;
#ifdef __cplusplus
}
#endif
/**
@@ -62,20 +62,19 @@
{
OFMutableDictionary *_states;
#ifdef OF_HAVE_THREADS
OFMutex *_statesMutex;
#endif
- of_run_loop_mode_t _Nullable _currentMode;
+ OFRunLoopMode _Nullable _currentMode;
volatile bool _stop;
}
#ifdef OF_HAVE_CLASS_PROPERTIES
@property (class, readonly, nullable, nonatomic) OFRunLoop *mainRunLoop;
@property (class, readonly, nullable, nonatomic) OFRunLoop *currentRunLoop;
#endif
-@property OF_NULLABLE_PROPERTY (readonly, nonatomic)
- of_run_loop_mode_t currentMode;
+@property OF_NULLABLE_PROPERTY (readonly, nonatomic) OFRunLoopMode currentMode;
/**
* @brief Returns the run loop for the main thread.
*
* @return The run loop for the main thread
@@ -100,11 +99,11 @@
* @brief Adds an OFTimer to the run loop for the specified mode.
*
* @param timer The timer to add
* @param mode The run loop mode in which to run the timer
*/
-- (void)addTimer: (OFTimer *)timer forMode: (of_run_loop_mode_t)mode;
+- (void)addTimer: (OFTimer *)timer forMode: (OFRunLoopMode)mode;
#ifdef OF_AMIGAOS
/**
* @brief Adds an Exec Signal to the run loop.
*
@@ -135,11 +134,11 @@
* @param selector The selector to call on the target when the signal was
* received. The selector must have one parameter for the ULONG
* of the signal that was received.
*/
- (void)addExecSignal: (ULONG)signal
- forMode: (of_run_loop_mode_t)mode
+ forMode: (OFRunLoopMode)mode
target: (id)target
selector: (SEL)selector;
/**
* @brief Removes the specified Exec Signal with the specified target and
@@ -161,11 +160,11 @@
* @param mode The run loop mode to which the signal was added
* @param target The target which was specified when adding the signal
* @param selector The selector which was specified when adding the signal
*/
- (void)removeExecSignal: (ULONG)signal
- forMode: (of_run_loop_mode_t)mode
+ forMode: (OFRunLoopMode)mode
target: (id)target
selector: (SEL)selector;
#endif
/**
@@ -185,16 +184,15 @@
* deadline is reached.
*
* @param mode The mode in which to run the run loop
* @param deadline The date until which the run loop should run at the longest
*/
-- (void)runMode: (of_run_loop_mode_t)mode
- beforeDate: (nullable OFDate *)deadline;
+- (void)runMode: (OFRunLoopMode)mode beforeDate: (nullable OFDate *)deadline;
/**
* @brief Stops the run loop. If there is still an operation being executed, it
* is finished before the run loop stops.
*/
- (void)stop;
@end
OF_ASSUME_NONNULL_END
Index: src/OFRunLoop.m
==================================================================
--- src/OFRunLoop.m
+++ src/OFRunLoop.m
@@ -41,11 +41,11 @@
#import "OFTimer+Private.h"
#import "OFDate.h"
#import "OFObserveFailedException.h"
-const of_run_loop_mode_t of_run_loop_mode_default = @"of_run_loop_mode_default";
+const OFRunLoopMode OFDefaultRunLoopMode = @"OFDefaultRunLoopMode";
static OFRunLoop *mainRunLoop = nil;
@interface OFRunLoopState: OFObject
#ifdef OF_HAVE_SOCKETS
@@ -88,11 +88,11 @@
@interface OFRunLoopReadQueueItem: OFRunLoopQueueItem
{
@public
# ifdef OF_HAVE_BLOCKS
- of_stream_async_read_block_t _block;
+ OFStreamAsyncReadBlock _block;
# endif
void *_buffer;
size_t _length;
}
@end
@@ -99,11 +99,11 @@
@interface OFRunLoopExactReadQueueItem: OFRunLoopQueueItem
{
@public
# ifdef OF_HAVE_BLOCKS
- of_stream_async_read_block_t _block;
+ OFStreamAsyncReadBlock _block;
# endif
void *_buffer;
size_t _exactLength, _readLength;
}
@end
@@ -110,21 +110,21 @@
@interface OFRunLoopReadLineQueueItem: OFRunLoopQueueItem
{
@public
# ifdef OF_HAVE_BLOCKS
- of_stream_async_read_line_block_t _block;
+ OFStreamAsyncReadLineBlock _block;
# endif
- of_string_encoding_t _encoding;
+ OFStringEncoding _encoding;
}
@end
@interface OFRunLoopWriteDataQueueItem: OFRunLoopQueueItem
{
@public
# ifdef OF_HAVE_BLOCKS
- of_stream_async_write_data_block_t _block;
+ OFStreamAsyncWriteDataBlock _block;
# endif
OFData *_data;
size_t _writtenLength;
}
@end
@@ -131,14 +131,14 @@
@interface OFRunLoopWriteStringQueueItem: OFRunLoopQueueItem
{
@public
# ifdef OF_HAVE_BLOCKS
- of_stream_async_write_string_block_t _block;
+ OFStreamAsyncWriteStringBlock _block;
# endif
OFString *_string;
- of_string_encoding_t _encoding;
+ OFStringEncoding _encoding;
size_t _writtenLength;
}
@end
# if !defined(OF_WII) && !defined(OF_NINTENDO_3DS)
@@ -157,11 +157,11 @@
@interface OFRunLoopDatagramReceiveQueueItem: OFRunLoopQueueItem
{
@public
# ifdef OF_HAVE_BLOCKS
- of_datagram_socket_async_receive_block_t _block;
+ OFDatagramSocketAsyncReceiveBlock _block;
# endif
void *_buffer;
size_t _length;
}
@end
@@ -168,22 +168,22 @@
@interface OFRunLoopDatagramSendQueueItem: OFRunLoopQueueItem
{
@public
# ifdef OF_HAVE_BLOCKS
- of_datagram_socket_async_send_data_block_t _block;
+ OFDatagramSocketAsyncSendDataBlock _block;
# endif
OFData *_data;
- of_socket_address_t _receiver;
+ OFSocketAddress _receiver;
}
@end
@interface OFRunLoopPacketReceiveQueueItem: OFRunLoopQueueItem
{
@public
# ifdef OF_HAVE_BLOCKS
- of_sequenced_packet_socket_async_receive_block_t _block;
+ OFSequencedPacketSocketAsyncReceiveBlock _block;
# endif
void *_buffer;
size_t _length;
}
@end
@@ -190,11 +190,11 @@
@interface OFRunLoopPacketSendQueueItem: OFRunLoopQueueItem
{
@public
# ifdef OF_HAVE_BLOCKS
- of_sequenced_packet_socket_async_send_data_block_t _block;
+ OFSequencedPacketSocketAsyncSendDataBlock _block;
# endif
OFData *_data;
}
@end
#endif
@@ -274,27 +274,28 @@
assert(queue != nil);
@try {
if (![queue.firstObject handleObject: object]) {
- of_list_object_t *listObject = queue.firstListObject;
+ OFListItem listItem = queue.firstListItem;
/*
* The handler might have called -[cancelAsyncRequests]
* so that our queue is now empty, in which case we
* should do nothing.
*/
- if (listObject != NULL) {
+ if (listItem != NULL) {
/*
* Make sure we keep the target until after we
* are done removing the object. The reason for
* this is that the target might call
* -[cancelAsyncRequests] in its dealloc.
*/
- [[listObject->object retain] autorelease];
+ [[OFListItemObject(listItem) retain]
+ autorelease];
- [queue removeListObject: listObject];
+ [queue removeListItem: listItem];
if (queue.count == 0) {
[_kernelEventObserver
removeObjectForReading: object];
[_readQueues
@@ -317,27 +318,28 @@
assert(queue != nil);
@try {
if (![queue.firstObject handleObject: object]) {
- of_list_object_t *listObject = queue.firstListObject;
+ OFListItem listItem = queue.firstListItem;
/*
* The handler might have called -[cancelAsyncRequests]
* so that our queue is now empty, in which case we
* should do nothing.
*/
- if (listObject != NULL) {
+ if (listItem != NULL) {
/*
* Make sure we keep the target until after we
* are done removing the object. The reason for
* this is that the target might call
* -[cancelAsyncRequests] in its dealloc.
*/
- [[listObject->object retain] autorelease];
+ [[OFListItemObject(listItem) retain]
+ autorelease];
- [queue removeListObject: listObject];
+ [queue removeListItem: listItem];
if (queue.count == 0) {
[_kernelEventObserver
removeObjectForWriting: object];
[_writeQueues
@@ -752,19 +754,18 @@
}
# ifdef OF_HAVE_BLOCKS
if (_block != NULL) {
if ([object isKindOfClass: [OFStreamSocket class]])
- return ((of_stream_socket_async_accept_block_t)
- _block)(acceptedSocket, exception);
+ return ((OFStreamSocketAsyncAcceptBlock)_block)(
+ acceptedSocket, exception);
else if ([object isKindOfClass:
[OFSequencedPacketSocket class]])
- return
- ((of_sequenced_packet_socket_async_accept_block_t)
+ return ((OFSequencedPacketSocketAsyncAcceptBlock)
_block)(acceptedSocket, exception);
else
- OF_ENSURE(0);
+ OFEnsure(0);
} else {
# endif
if (![_delegate respondsToSelector:
@selector(socket:didAcceptSocket:exception:)])
return false;
@@ -789,11 +790,11 @@
@implementation OFRunLoopDatagramReceiveQueueItem
- (bool)handleObject: (id)object
{
size_t length;
- of_socket_address_t address;
+ OFSocketAddress address;
id exception = nil;
@try {
length = [object receiveIntoBuffer: _buffer
length: _length
@@ -1015,11 +1016,11 @@
{
mainRunLoop = [runLoop retain];
}
static OFRunLoopState *
-stateForMode(OFRunLoop *self, of_run_loop_mode_t mode, bool create)
+stateForMode(OFRunLoop *self, OFRunLoopMode mode, bool create)
{
OFRunLoopState *state;
#ifdef OF_HAVE_THREADS
[self->_statesMutex lock];
@@ -1086,13 +1087,13 @@
+ (void)of_addAsyncReadForStream: (OFStream *)
stream
buffer: (void *)buffer
length: (size_t)length
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (of_stream_async_read_block_t)block
+ block: (OFStreamAsyncReadBlock)block
# endif
delegate: (id )delegate
{
NEW_READ(OFRunLoopReadQueueItem, stream, mode)
@@ -1108,13 +1109,13 @@
+ (void)of_addAsyncReadForStream: (OFStream *)
stream
buffer: (void *)buffer
exactLength: (size_t)exactLength
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (of_stream_async_read_block_t)block
+ block: (OFStreamAsyncReadBlock)block
# endif
delegate: (id )delegate
{
NEW_READ(OFRunLoopExactReadQueueItem, stream, mode)
@@ -1128,14 +1129,14 @@
QUEUE_ITEM
}
+ (void)of_addAsyncReadLineForStream: (OFStream *)
stream
- encoding: (of_string_encoding_t)encoding
- mode: (of_run_loop_mode_t)mode
+ encoding: (OFStringEncoding)encoding
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (of_stream_async_read_line_block_t)block
+ block: (OFStreamAsyncReadLineBlock)block
# endif
delegate: (id )delegate
{
NEW_READ(OFRunLoopReadLineQueueItem, stream, mode)
@@ -1149,13 +1150,13 @@
}
+ (void)of_addAsyncWriteForStream: (OFStream *)
stream
data: (OFData *)data
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (of_stream_async_write_data_block_t)block
+ block: (OFStreamAsyncWriteDataBlock)block
# endif
delegate: (id )delegate
{
NEW_WRITE(OFRunLoopWriteDataQueueItem, stream, mode)
@@ -1169,14 +1170,14 @@
}
+ (void)of_addAsyncWriteForStream: (OFStream *)
stream
string: (OFString *)string
- encoding: (of_string_encoding_t)encoding
- mode: (of_run_loop_mode_t)mode
+ encoding: (OFStringEncoding)encoding
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (of_stream_async_write_string_block_t)block
+ block: (OFStreamAsyncWriteStringBlock)block
# endif
delegate: (id )delegate
{
NEW_WRITE(OFRunLoopWriteStringQueueItem, stream, mode)
@@ -1190,11 +1191,11 @@
QUEUE_ITEM
}
# if !defined(OF_WII) && !defined(OF_NINTENDO_3DS)
+ (void)of_addAsyncConnectForSocket: (id)sock
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
delegate: (id )delegate
{
NEW_WRITE(OFRunLoopConnectQueueItem, sock, mode)
queueItem->_delegate = [delegate retain];
@@ -1202,11 +1203,11 @@
QUEUE_ITEM
}
# endif
+ (void)of_addAsyncAcceptForSocket: (id)sock
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
block: (id)block
delegate: (id)delegate
{
NEW_READ(OFRunLoopAcceptQueueItem, sock, mode)
@@ -1219,13 +1220,13 @@
}
+ (void)of_addAsyncReceiveForDatagramSocket: (OFDatagramSocket *)sock
buffer: (void *)buffer
length: (size_t)length
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (of_datagram_socket_async_receive_block_t)block
+ block: (OFDatagramSocketAsyncReceiveBlock)block
# endif
delegate: (id )delegate
{
NEW_READ(OFRunLoopDatagramReceiveQueueItem, sock, mode)
@@ -1239,14 +1240,14 @@
QUEUE_ITEM
}
+ (void)of_addAsyncSendForDatagramSocket: (OFDatagramSocket *)sock
data: (OFData *)data
- receiver: (const of_socket_address_t *)receiver
- mode: (of_run_loop_mode_t)mode
+ receiver: (const OFSocketAddress *)receiver
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (of_datagram_socket_async_send_data_block_t)block
+ block: (OFDatagramSocketAsyncSendDataBlock)block
# endif
delegate: (id )delegate
{
NEW_WRITE(OFRunLoopDatagramSendQueueItem, sock, mode)
@@ -1262,13 +1263,13 @@
+ (void)of_addAsyncReceiveForSequencedPacketSocket: (OFSequencedPacketSocket *)
sock
buffer: (void *)buffer
length: (size_t)length
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (of_sequenced_packet_socket_async_receive_block_t)block
+ block: (OFSequencedPacketSocketAsyncReceiveBlock)block
# endif
delegate: (id )delegate
{
NEW_READ(OFRunLoopPacketReceiveQueueItem, sock, mode)
@@ -1282,13 +1283,13 @@
QUEUE_ITEM
}
+ (void)of_addAsyncSendForSequencedPacketSocket: (OFSequencedPacketSocket *)sock
data: (OFData *)data
- mode: (of_run_loop_mode_t)mode
+ mode: (OFRunLoopMode)mode
# ifdef OF_HAVE_BLOCKS
- block: (of_sequenced_packet_socket_async_send_data_block_t)block
+ block: (OFSequencedPacketSocketAsyncSendDataBlock)block
# endif
delegate: (id )delegate
{
NEW_WRITE(OFRunLoopPacketSendQueueItem, sock, mode)
@@ -1302,12 +1303,11 @@
}
# undef NEW_READ
# undef NEW_WRITE
# undef QUEUE_ITEM
-+ (void)of_cancelAsyncRequestsForObject: (id)object
- mode: (of_run_loop_mode_t)mode
++ (void)of_cancelAsyncRequestsForObject: (id)object mode: (OFRunLoopMode)mode
{
void *pool = objc_autoreleasePoolPush();
OFRunLoop *runLoop = [self currentRunLoop];
OFRunLoopState *state = stateForMode(runLoop, mode, false);
OFList *queue;
@@ -1354,12 +1354,11 @@
_states = [[OFMutableDictionary alloc] init];
state = [[OFRunLoopState alloc] init];
@try {
- [_states setObject: state
- forKey: of_run_loop_mode_default];
+ [_states setObject: state forKey: OFDefaultRunLoopMode];
} @finally {
[state release];
}
#ifdef OF_HAVE_THREADS
@@ -1383,14 +1382,14 @@
[super dealloc];
}
- (void)addTimer: (OFTimer *)timer
{
- [self addTimer: timer forMode: of_run_loop_mode_default];
+ [self addTimer: timer forMode: OFDefaultRunLoopMode];
}
-- (void)addTimer: (OFTimer *)timer forMode: (of_run_loop_mode_t)mode
+- (void)addTimer: (OFTimer *)timer forMode: (OFRunLoopMode)mode
{
OFRunLoopState *state = stateForMode(self, mode, true);
#ifdef OF_HAVE_THREADS
[state->_timersQueueMutex lock];
@@ -1410,11 +1409,11 @@
#elif defined(OF_HAVE_THREADS)
[state->_condition signal];
#endif
}
-- (void)of_removeTimer: (OFTimer *)timer forMode: (of_run_loop_mode_t)mode
+- (void)of_removeTimer: (OFTimer *)timer forMode: (OFRunLoopMode)mode
{
OFRunLoopState *state = stateForMode(self, mode, false);
if (state == nil)
return;
@@ -1421,16 +1420,14 @@
#ifdef OF_HAVE_THREADS
[state->_timersQueueMutex lock];
@try {
#endif
- of_list_object_t *iter;
-
- for (iter = state->_timersQueue.firstListObject; iter != NULL;
- iter = iter->next) {
- if ([iter->object isEqual: timer]) {
- [state->_timersQueue removeListObject: iter];
+ for (OFListItem iter = state->_timersQueue.firstListItem;
+ iter != NULL; iter = OFListItemNext(iter)) {
+ if ([OFListItemObject(iter) isEqual: timer]) {
+ [state->_timersQueue removeListItem: iter];
break;
}
}
#ifdef OF_HAVE_THREADS
} @finally {
@@ -1441,17 +1438,17 @@
#ifdef OF_AMIGAOS
- (void)addExecSignal: (ULONG)signal target: (id)target selector: (SEL)selector
{
[self addExecSignal: signal
- forMode: of_run_loop_mode_default
+ forMode: OFDefaultRunLoopMode
target: target
selector: selector];
}
- (void)addExecSignal: (ULONG)signal
- forMode: (of_run_loop_mode_t)mode
+ forMode: (OFRunLoopMode)mode
target: (id)target
selector: (SEL)selector
{
OFRunLoopState *state = stateForMode(self, mode, true);
@@ -1484,17 +1481,17 @@
- (void)removeExecSignal: (ULONG)signal
target: (id)target
selector: (SEL)selector
{
[self removeExecSignal: signal
- forMode: of_run_loop_mode_default
+ forMode: OFDefaultRunLoopMode
target: target
selector: selector];
}
- (void)removeExecSignal: (ULONG)signal
- forMode: (of_run_loop_mode_t)mode
+ forMode: (OFRunLoopMode)mode
target: (id)target
selector: (SEL)selector
{
OFRunLoopState *state = stateForMode(self, mode, false);
@@ -1554,17 +1551,17 @@
{
_stop = false;
while (!_stop &&
(deadline == nil || deadline.timeIntervalSinceNow >= 0))
- [self runMode: of_run_loop_mode_default beforeDate: deadline];
+ [self runMode: OFDefaultRunLoopMode beforeDate: deadline];
}
-- (void)runMode: (of_run_loop_mode_t)mode beforeDate: (OFDate *)deadline
+- (void)runMode: (OFRunLoopMode)mode beforeDate: (OFDate *)deadline
{
void *pool = objc_autoreleasePoolPush();
- of_run_loop_mode_t previousMode = _currentMode;
+ OFRunLoopMode previousMode = _currentMode;
OFRunLoopState *state = stateForMode(self, mode, false);
if (state == nil)
return;
@@ -1580,20 +1577,21 @@
#ifdef OF_HAVE_THREADS
[state->_timersQueueMutex lock];
@try {
#endif
- of_list_object_t *listObject =
- state->_timersQueue.firstListObject;
+ OFListItem listItem =
+ state->_timersQueue.firstListItem;
- if (listObject != NULL && [listObject->object
- fireDate].timeIntervalSinceNow <= 0) {
- timer = [[listObject->object
+ if (listItem != NULL &&
+ [OFListItemObject(listItem) fireDate]
+ .timeIntervalSinceNow <= 0) {
+ timer = [[OFListItemObject(listItem)
retain] autorelease];
[state->_timersQueue
- removeListObject: listObject];
+ removeListItem: listItem];
[timer of_setInRunLoop: nil mode: nil];
} else
break;
#ifdef OF_HAVE_THREADS
@@ -1620,11 +1618,11 @@
}
#endif
/* Watch for I/O events until the next timer is due */
if (nextTimer != nil || deadline != nil) {
- of_time_interval_t timeout;
+ OFTimeInterval timeout;
if (nextTimer != nil && deadline == nil)
timeout = nextTimer.timeIntervalSinceNow;
else if (nextTimer == nil && deadline != nil)
timeout = deadline.timeIntervalSinceNow;
@@ -1694,12 +1692,11 @@
}
}
- (void)stop
{
- OFRunLoopState *state =
- stateForMode(self, of_run_loop_mode_default, false);
+ OFRunLoopState *state = stateForMode(self, OFDefaultRunLoopMode, false);
_stop = true;
if (state == nil)
return;
Index: src/OFSHA1Hash.h
==================================================================
--- src/OFSHA1Hash.h
+++ src/OFSHA1Hash.h
@@ -26,14 +26,14 @@
*/
OF_SUBCLASSING_RESTRICTED
@interface OFSHA1Hash: OFObject
{
OFSecureData *_iVarsData;
- struct of_sha1_hash_ivars {
+ struct {
uint32_t state[5];
uint64_t bits;
- union of_sha1_hash_buffer {
+ union {
unsigned char bytes[64];
uint32_t words[80];
} buffer;
size_t bufferLength;
} *_iVars;
Index: src/OFSHA1Hash.m
==================================================================
--- src/OFSHA1Hash.m
+++ src/OFSHA1Hash.m
@@ -21,12 +21,12 @@
#import "OFSecureData.h"
#import "OFHashAlreadyCalculatedException.h"
#import "OFOutOfRangeException.h"
-#define DIGEST_SIZE 20
-#define BLOCK_SIZE 64
+static const size_t digestSize = 20;
+static const size_t blockSize = 64;
OF_DIRECT_MEMBERS
@interface OFSHA1Hash ()
- (void)of_resetState;
@end
@@ -39,11 +39,11 @@
static OF_INLINE void
byteSwapVectorIfLE(uint32_t *vector, uint_fast8_t length)
{
#ifndef OF_BIG_ENDIAN
for (uint_fast8_t i = 0; i < length; i++)
- vector[i] = OF_BSWAP32(vector[i]);
+ vector[i] = OFByteSwap32(vector[i]);
#endif
}
static void
processBlock(uint32_t *state, uint32_t *buffer)
@@ -60,21 +60,21 @@
byteSwapVectorIfLE(buffer, 16);
for (i = 16; i < 80; i++) {
uint32_t tmp = buffer[i - 3] ^ buffer[i - 8] ^
buffer[i - 14] ^ buffer[i - 16];
- buffer[i] = OF_ROL(tmp, 1);
+ buffer[i] = OFRotateLeft(tmp, 1);
}
#define LOOP_BODY(f, k) \
{ \
- uint32_t tmp = OF_ROL(new[0], 5) + \
+ uint32_t tmp = OFRotateLeft(new[0], 5) + \
f(new[0], new[1], new[2], new[3]) + \
new[4] + k + buffer[i]; \
new[4] = new[3]; \
new[3] = new[2]; \
- new[2] = OF_ROL(new[1], 30); \
+ new[2] = OFRotateLeft(new[1], 30); \
new[1] = new[0]; \
new[0] = tmp; \
}
for (i = 0; i < 20; i++)
@@ -99,16 +99,16 @@
@synthesize calculated = _calculated;
@synthesize allowsSwappableMemory = _allowsSwappableMemory;
+ (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
+ (size_t)blockSize
{
- return BLOCK_SIZE;
+ return blockSize;
}
+ (instancetype)hashWithAllowsSwappableMemory: (bool)allowsSwappableMemory
{
return [[[self alloc] initWithAllowsSwappableMemory:
@@ -152,16 +152,16 @@
[super dealloc];
}
- (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
- (size_t)blockSize
{
- return BLOCK_SIZE;
+ return blockSize;
}
- (id)copy
{
OFSHA1Hash *copy = [[OFSHA1Hash alloc] of_init];
@@ -220,25 +220,25 @@
{
if (_calculated)
return (const unsigned char *)_iVars->state;
_iVars->buffer.bytes[_iVars->bufferLength] = 0x80;
- of_explicit_memset(_iVars->buffer.bytes + _iVars->bufferLength + 1, 0,
+ OFZeroMemory(_iVars->buffer.bytes + _iVars->bufferLength + 1,
64 - _iVars->bufferLength - 1);
if (_iVars->bufferLength >= 56) {
processBlock(_iVars->state, _iVars->buffer.words);
- of_explicit_memset(_iVars->buffer.bytes, 0, 64);
+ OFZeroMemory(_iVars->buffer.bytes, 64);
}
_iVars->buffer.words[14] =
- OF_BSWAP32_IF_LE((uint32_t)(_iVars->bits >> 32));
+ OFToBigEndian32((uint32_t)(_iVars->bits >> 32));
_iVars->buffer.words[15] =
- OF_BSWAP32_IF_LE((uint32_t)(_iVars->bits & 0xFFFFFFFF));
+ OFToBigEndian32((uint32_t)(_iVars->bits & 0xFFFFFFFF));
processBlock(_iVars->state, _iVars->buffer.words);
- of_explicit_memset(&_iVars->buffer, 0, sizeof(_iVars->buffer));
+ OFZeroMemory(&_iVars->buffer, sizeof(_iVars->buffer));
byteSwapVectorIfLE(_iVars->state, 5);
_calculated = true;
return (const unsigned char *)_iVars->state;
}
@@ -245,10 +245,10 @@
- (void)reset
{
[self of_resetState];
_iVars->bits = 0;
- of_explicit_memset(&_iVars->buffer, 0, sizeof(_iVars->buffer));
+ OFZeroMemory(&_iVars->buffer, sizeof(_iVars->buffer));
_iVars->bufferLength = 0;
_calculated = false;
}
@end
Index: src/OFSHA224Hash.m
==================================================================
--- src/OFSHA224Hash.m
+++ src/OFSHA224Hash.m
@@ -15,21 +15,21 @@
#include "config.h"
#import "OFSHA224Hash.h"
-#define DIGEST_SIZE 28
+static const size_t digestSize = 28;
@implementation OFSHA224Hash
+ (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
- (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
- (void)of_resetState
{
_iVars->state[0] = 0xC1059ED8;
Index: src/OFSHA224Or256Hash.h
==================================================================
--- src/OFSHA224Or256Hash.h
+++ src/OFSHA224Or256Hash.h
@@ -27,14 +27,14 @@
@interface OFSHA224Or256Hash: OFObject
{
@private
OFSecureData *_iVarsData;
@protected
- struct of_sha224_or_256_hash_ivars {
+ struct {
uint32_t state[8];
uint64_t bits;
- union of_sha224_or_256_hash_buffer {
+ union {
unsigned char bytes[64];
uint32_t words[64];
} buffer;
size_t bufferLength;
} *_iVars;
Index: src/OFSHA224Or256Hash.m
==================================================================
--- src/OFSHA224Or256Hash.m
+++ src/OFSHA224Or256Hash.m
@@ -22,11 +22,11 @@
#import "OFSecureData.h"
#import "OFHashAlreadyCalculatedException.h"
#import "OFOutOfRangeException.h"
-#define BLOCK_SIZE 64
+static const size_t blockSize = 64;
@interface OFSHA224Or256Hash ()
- (void)of_resetState;
@end
@@ -52,11 +52,11 @@
static OF_INLINE void
byteSwapVectorIfLE(uint32_t *vector, uint_fast8_t length)
{
#ifndef OF_BIG_ENDIAN
for (uint_fast8_t i = 0; i < length; i++)
- vector[i] = OF_BSWAP32(vector[i]);
+ vector[i] = OFByteSwap32(vector[i]);
#endif
}
static void
processBlock(uint32_t *state, uint32_t *buffer)
@@ -77,24 +77,24 @@
for (i = 16; i < 64; i++) {
uint32_t tmp;
tmp = buffer[i - 2];
- buffer[i] = (OF_ROR(tmp, 17) ^ OF_ROR(tmp, 19) ^ (tmp >> 10)) +
- buffer[i - 7];
+ buffer[i] = (OFRotateRight(tmp, 17) ^ OFRotateRight(tmp, 19) ^
+ (tmp >> 10)) + buffer[i - 7];
tmp = buffer[i - 15];
- buffer[i] += (OF_ROR(tmp, 7) ^ OF_ROR(tmp, 18) ^ (tmp >> 3)) +
- buffer[i - 16];
+ buffer[i] += (OFRotateRight(tmp, 7) ^ OFRotateRight(tmp, 18) ^
+ (tmp >> 3)) + buffer[i - 16];
}
for (i = 0; i < 64; i++) {
- uint32_t tmp1 = new[7] + (OF_ROR(new[4], 6) ^
- OF_ROR(new[4], 11) ^ OF_ROR(new[4], 25)) +
+ uint32_t tmp1 = new[7] + (OFRotateRight(new[4], 6) ^
+ OFRotateRight(new[4], 11) ^ OFRotateRight(new[4], 25)) +
((new[4] & (new[5] ^ new[6])) ^ new[6]) +
table[i] + buffer[i];
- uint32_t tmp2 = (OF_ROR(new[0], 2) ^ OF_ROR(new[0], 13) ^
- OF_ROR(new[0], 22)) +
+ uint32_t tmp2 = (OFRotateRight(new[0], 2) ^
+ OFRotateRight(new[0], 13) ^ OFRotateRight(new[0], 22)) +
((new[0] & (new[1] | new[2])) | (new[1] & new[2]));
new[7] = new[6];
new[6] = new[5];
new[5] = new[4];
@@ -124,11 +124,11 @@
OF_UNRECOGNIZED_SELECTOR
}
+ (size_t)blockSize
{
- return BLOCK_SIZE;
+ return blockSize;
}
+ (instancetype)hashWithAllowsSwappableMemory: (bool)allowsSwappableMemory
{
return [[[self alloc] initWithAllowsSwappableMemory:
@@ -182,11 +182,11 @@
OF_UNRECOGNIZED_SELECTOR
}
- (size_t)blockSize
{
- return BLOCK_SIZE;
+ return blockSize;
}
- (id)copy
{
OFSHA224Or256Hash *copy = [[[self class] alloc] of_init];
@@ -236,25 +236,25 @@
{
if (_calculated)
return (const unsigned char *)_iVars->state;
_iVars->buffer.bytes[_iVars->bufferLength] = 0x80;
- of_explicit_memset(_iVars->buffer.bytes + _iVars->bufferLength + 1, 0,
+ OFZeroMemory(_iVars->buffer.bytes + _iVars->bufferLength + 1,
64 - _iVars->bufferLength - 1);
if (_iVars->bufferLength >= 56) {
processBlock(_iVars->state, _iVars->buffer.words);
- of_explicit_memset(_iVars->buffer.bytes, 0, 64);
+ OFZeroMemory(_iVars->buffer.bytes, 64);
}
_iVars->buffer.words[14] =
- OF_BSWAP32_IF_LE((uint32_t)(_iVars->bits >> 32));
+ OFToBigEndian32((uint32_t)(_iVars->bits >> 32));
_iVars->buffer.words[15] =
- OF_BSWAP32_IF_LE((uint32_t)(_iVars->bits & 0xFFFFFFFF));
+ OFToBigEndian32((uint32_t)(_iVars->bits & 0xFFFFFFFF));
processBlock(_iVars->state, _iVars->buffer.words);
- of_explicit_memset(&_iVars->buffer, 0, sizeof(_iVars->buffer));
+ OFZeroMemory(&_iVars->buffer, sizeof(_iVars->buffer));
byteSwapVectorIfLE(_iVars->state, 8);
_calculated = true;
return (const unsigned char *)_iVars->state;
}
@@ -261,15 +261,15 @@
- (void)reset
{
[self of_resetState];
_iVars->bits = 0;
- of_explicit_memset(&_iVars->buffer, 0, sizeof(_iVars->buffer));
+ OFZeroMemory(&_iVars->buffer, sizeof(_iVars->buffer));
_iVars->bufferLength = 0;
_calculated = false;
}
- (void)of_resetState
{
OF_UNRECOGNIZED_SELECTOR
}
@end
Index: src/OFSHA256Hash.m
==================================================================
--- src/OFSHA256Hash.m
+++ src/OFSHA256Hash.m
@@ -15,21 +15,21 @@
#include "config.h"
#import "OFSHA256Hash.h"
-#define DIGEST_SIZE 32
+static const size_t digestSize = 32;
@implementation OFSHA256Hash
+ (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
- (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
- (void)of_resetState
{
_iVars->state[0] = 0x6A09E667;
Index: src/OFSHA384Hash.m
==================================================================
--- src/OFSHA384Hash.m
+++ src/OFSHA384Hash.m
@@ -15,21 +15,21 @@
#include "config.h"
#import "OFSHA384Hash.h"
-#define DIGEST_SIZE 48
+static const size_t digestSize = 48;
@implementation OFSHA384Hash
+ (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
- (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
- (void)of_resetState
{
_iVars->state[0] = 0xCBBB9D5DC1059ED8;
Index: src/OFSHA384Or512Hash.h
==================================================================
--- src/OFSHA384Or512Hash.h
+++ src/OFSHA384Or512Hash.h
@@ -27,14 +27,14 @@
@interface OFSHA384Or512Hash: OFObject
{
@private
OFSecureData *_iVarsData;
@protected
- struct of_sha384_or_512_hash_ivars {
+ struct {
uint64_t state[8];
uint64_t bits[2];
- union of_sha384_or_512_hash_buffer {
+ union {
unsigned char bytes[128];
uint64_t words[80];
} buffer;
size_t bufferLength;
} *_iVars;
Index: src/OFSHA384Or512Hash.m
==================================================================
--- src/OFSHA384Or512Hash.m
+++ src/OFSHA384Or512Hash.m
@@ -22,11 +22,11 @@
#import "OFSecureData.h"
#import "OFHashAlreadyCalculatedException.h"
#import "OFOutOfRangeException.h"
-#define BLOCK_SIZE 128
+static const size_t blockSize = 128;
@interface OFSHA384Or512Hash ()
- (void)of_resetState;
@end
@@ -63,11 +63,11 @@
static OF_INLINE void
byteSwapVectorIfLE(uint64_t *vector, uint_fast8_t length)
{
#ifndef OF_BIG_ENDIAN
for (uint_fast8_t i = 0; i < length; i++)
- vector[i] = OF_BSWAP64(vector[i]);
+ vector[i] = OFByteSwap64(vector[i]);
#endif
}
static void
processBlock(uint64_t *state, uint64_t *buffer)
@@ -88,24 +88,24 @@
for (i = 16; i < 80; i++) {
uint64_t tmp;
tmp = buffer[i - 2];
- buffer[i] = (OF_ROR(tmp, 19) ^ OF_ROR(tmp, 61) ^ (tmp >> 6)) +
- buffer[i - 7];
+ buffer[i] = (OFRotateRight(tmp, 19) ^ OFRotateRight(tmp, 61) ^
+ (tmp >> 6)) + buffer[i - 7];
tmp = buffer[i - 15];
- buffer[i] += (OF_ROR(tmp, 1) ^ OF_ROR(tmp, 8) ^ (tmp >> 7)) +
- buffer[i - 16];
+ buffer[i] += (OFRotateRight(tmp, 1) ^ OFRotateRight(tmp, 8) ^
+ (tmp >> 7)) + buffer[i - 16];
}
for (i = 0; i < 80; i++) {
- uint64_t tmp1 = new[7] + (OF_ROR(new[4], 14) ^
- OF_ROR(new[4], 18) ^ OF_ROR(new[4], 41)) +
+ uint64_t tmp1 = new[7] + (OFRotateRight(new[4], 14) ^
+ OFRotateRight(new[4], 18) ^ OFRotateRight(new[4], 41)) +
((new[4] & (new[5] ^ new[6])) ^ new[6]) +
table[i] + buffer[i];
- uint64_t tmp2 = (OF_ROR(new[0], 28) ^ OF_ROR(new[0], 34) ^
- OF_ROR(new[0], 39)) +
+ uint64_t tmp2 = (OFRotateRight(new[0], 28) ^
+ OFRotateRight(new[0], 34) ^ OFRotateRight(new[0], 39)) +
((new[0] & (new[1] | new[2])) | (new[1] & new[2]));
new[7] = new[6];
new[6] = new[5];
new[5] = new[4];
@@ -135,11 +135,11 @@
OF_UNRECOGNIZED_SELECTOR
}
+ (size_t)blockSize
{
- return BLOCK_SIZE;
+ return blockSize;
}
+ (instancetype)hashWithAllowsSwappableMemory: (bool)allowsSwappableMemory
{
return [[[self alloc] initWithAllowsSwappableMemory:
@@ -193,11 +193,11 @@
OF_UNRECOGNIZED_SELECTOR
}
- (size_t)blockSize
{
- return BLOCK_SIZE;
+ return blockSize;
}
- (id)copy
{
OFSHA384Or512Hash *copy = [[[self class] alloc] of_init];
@@ -249,38 +249,38 @@
{
if (_calculated)
return (const unsigned char *)_iVars->state;
_iVars->buffer.bytes[_iVars->bufferLength] = 0x80;
- of_explicit_memset(_iVars->buffer.bytes + _iVars->bufferLength + 1, 0,
+ OFZeroMemory(_iVars->buffer.bytes + _iVars->bufferLength + 1,
128 - _iVars->bufferLength - 1);
if (_iVars->bufferLength >= 112) {
processBlock(_iVars->state, _iVars->buffer.words);
- of_explicit_memset(_iVars->buffer.bytes, 0, 128);
+ OFZeroMemory(_iVars->buffer.bytes, 128);
}
- _iVars->buffer.words[14] = OF_BSWAP64_IF_LE(_iVars->bits[1]);
- _iVars->buffer.words[15] = OF_BSWAP64_IF_LE(_iVars->bits[0]);
+ _iVars->buffer.words[14] = OFToBigEndian64(_iVars->bits[1]);
+ _iVars->buffer.words[15] = OFToBigEndian64(_iVars->bits[0]);
processBlock(_iVars->state, _iVars->buffer.words);
- of_explicit_memset(&_iVars->buffer, 0, sizeof(_iVars->buffer));
+ OFZeroMemory(&_iVars->buffer, sizeof(_iVars->buffer));
byteSwapVectorIfLE(_iVars->state, 8);
_calculated = true;
return (const unsigned char *)_iVars->state;
}
- (void)reset
{
[self of_resetState];
- of_explicit_memset(_iVars->bits, 0, sizeof(_iVars->bits));
- of_explicit_memset(&_iVars->buffer, 0, sizeof(_iVars->buffer));
+ OFZeroMemory(_iVars->bits, sizeof(_iVars->bits));
+ OFZeroMemory(&_iVars->buffer, sizeof(_iVars->buffer));
_iVars->bufferLength = 0;
_calculated = false;
}
- (void)of_resetState
{
OF_UNRECOGNIZED_SELECTOR
}
@end
Index: src/OFSHA512Hash.m
==================================================================
--- src/OFSHA512Hash.m
+++ src/OFSHA512Hash.m
@@ -15,21 +15,21 @@
#include "config.h"
#import "OFSHA512Hash.h"
-#define DIGEST_SIZE 64
+static const size_t digestSize = 64;
@implementation OFSHA512Hash
+ (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
- (size_t)digestSize
{
- return DIGEST_SIZE;
+ return digestSize;
}
- (void)of_resetState
{
_iVars->state[0] = 0x6A09E667F3BCC908;
Index: src/OFSPXSocket.h
==================================================================
--- src/OFSPXSocket.h
+++ src/OFSPXSocket.h
@@ -28,11 +28,11 @@
* @brief A block which is called when the socket connected.
*
* @param exception An exception which occurred while connecting the socket or
* `nil` on success
*/
-typedef void (^of_spx_socket_async_connect_block_t)(id _Nullable exception);
+typedef void (^OFSPXSocketAsyncConnectBlock)(id _Nullable exception);
#endif
/**
* @protocol OFSPXSocketDelegate OFSPXSocket.h ObjFW/OFSPXSocket.h
*
@@ -116,11 +116,11 @@
* @param runLoopMode The run loop mode in which to perform the async connect
*/
- (void)asyncConnectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
- runLoopMode: (of_run_loop_mode_t)runLoopMode;
+ runLoopMode: (OFRunLoopMode)runLoopMode;
#ifdef OF_HAVE_BLOCKS
/**
* @brief Asynchronously connect the OFSPXSocket to the specified destination.
*
@@ -131,11 +131,11 @@
* @param block The block to execute once the connection has been established
*/
- (void)asyncConnectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
- block: (of_spx_socket_async_connect_block_t)block;
+ block: (OFSPXSocketAsyncConnectBlock)block;
/**
* @brief Asynchronously connect the OFSPXSocket to the specified destination.
*
* @param node The node to connect to
@@ -146,20 +146,20 @@
* @param block The block to execute once the connection has been established
*/
- (void)asyncConnectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_spx_socket_async_connect_block_t)block;
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFSPXSocketAsyncConnectBlock)block;
#endif
/**
* @brief Bind the socket to the specified network, node and port.
*
* @param port The port (sometimes called socket number) to bind to. 0 means to
* pick one and return it.
* @return The address on which this socket can be reached
*/
-- (of_socket_address_t)bindToPort: (uint16_t)port;
+- (OFSocketAddress)bindToPort: (uint16_t)port;
@end
OF_ASSUME_NONNULL_END
Index: src/OFSPXSocket.m
==================================================================
--- src/OFSPXSocket.m
+++ src/OFSPXSocket.m
@@ -18,29 +18,28 @@
#include
#import "OFSPXSocket.h"
#import "OFRunLoop.h"
#import "OFRunLoop+Private.h"
+#import "OFSocket.h"
+#import "OFSocket+Private.h"
#import "OFAlreadyConnectedException.h"
#import "OFBindFailedException.h"
#import "OFConnectionFailedException.h"
#import "OFNotOpenException.h"
-#import "socket.h"
-#import "socket_helpers.h"
-
#ifndef NSPROTO_SPX
# define NSPROTO_SPX 0
#endif
-#define SPX_PACKET_TYPE 5
+static const uint8_t SPXPacketType = 5;
@interface OFSPXSocket ()
-- (int)of_createSocketForAddress: (const of_socket_address_t *)address
+- (int)of_createSocketForAddress: (const OFSocketAddress *)address
errNo: (int *)errNo;
-- (bool)of_connectSocketToAddress: (const of_socket_address_t *)address
+- (bool)of_connectSocketToAddress: (const OFSocketAddress *)address
errNo: (int *)errNo;
- (void)of_closeSocket;
@end
OF_DIRECT_MEMBERS
@@ -49,32 +48,32 @@
OFSPXSocket *_socket;
unsigned char _node[IPX_NODE_LEN];
uint32_t _network;
uint16_t _port;
#ifdef OF_HAVE_BLOCKS
- of_spx_socket_async_connect_block_t _block;
+ OFSPXSocketAsyncConnectBlock _block;
#endif
}
- (instancetype)initWithSocket: (OFSPXSocket *)socket
node: (unsigned char [IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
#ifdef OF_HAVE_BLOCKS
- block: (of_spx_socket_async_connect_block_t)block
+ block: (OFSPXSocketAsyncConnectBlock)block
#endif
;
-- (void)startWithRunLoopMode: (of_run_loop_mode_t)runLoopMode;
+- (void)startWithRunLoopMode: (OFRunLoopMode)runLoopMode;
@end
@implementation OFSPXSocketAsyncConnectDelegate
- (instancetype)initWithSocket: (OFSPXSocket *)sock
node: (unsigned char [IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
#ifdef OF_HAVE_BLOCKS
- block: (of_spx_socket_async_connect_block_t)block
+ block: (OFSPXSocketAsyncConnectBlock)block
#endif
{
self = [super init];
@try {
@@ -101,14 +100,14 @@
#endif
[super dealloc];
}
-- (void)startWithRunLoopMode: (of_run_loop_mode_t)runLoopMode
+- (void)startWithRunLoopMode: (OFRunLoopMode)runLoopMode
{
- of_socket_address_t address =
- of_socket_address_ipx(_node, _network, _port);
+ OFSocketAddress address =
+ OFSocketAddressMakeIPX(_node, _network, _port);
id exception = nil;
int errNo;
if (![_socket of_createSocketForAddress: &address errNo: &errNo]) {
exception = [self of_connectionFailedExceptionForErrNo: errNo];
@@ -172,23 +171,24 @@
@end
@implementation OFSPXSocket
@dynamic delegate;
-- (int)of_createSocketForAddress: (const of_socket_address_t *)address
+- (int)of_createSocketForAddress: (const OFSocketAddress *)address
errNo: (int *)errNo
{
#if SOCK_CLOEXEC == 0 && defined(HAVE_FCNTL) && defined(FD_CLOEXEC)
int flags;
#endif
- if (_socket != INVALID_SOCKET)
+ if (_socket != OFInvalidSocketHandle)
@throw [OFAlreadyConnectedException exceptionWithSocket: self];
if ((_socket = socket(address->sockaddr.ipx.sipx_family,
- SOCK_SEQPACKET | SOCK_CLOEXEC, NSPROTO_SPX)) == INVALID_SOCKET) {
- *errNo = of_socket_errno();
+ SOCK_SEQPACKET | SOCK_CLOEXEC, NSPROTO_SPX)) ==
+ OFInvalidSocketHandle) {
+ *errNo = OFSocketErrNo();
return false;
}
#if SOCK_CLOEXEC == 0 && defined(HAVE_FCNTL) && defined(FD_CLOEXEC)
if ((flags = fcntl(_socket, F_GETFD, 0)) != -1)
@@ -196,37 +196,36 @@
#endif
return true;
}
-- (bool)of_connectSocketToAddress: (const of_socket_address_t *)address
+- (bool)of_connectSocketToAddress: (const OFSocketAddress *)address
errNo: (int *)errNo
{
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
@throw [OFNotOpenException exceptionWithObject: self];
if (connect(_socket, &address->sockaddr.sockaddr,
address->length) != 0) {
- *errNo = of_socket_errno();
+ *errNo = OFSocketErrNo();
return false;
}
return true;
}
- (void)of_closeSocket
{
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
}
- (void)connectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
{
- of_socket_address_t address =
- of_socket_address_ipx(node, network, port);
+ OFSocketAddress address = OFSocketAddressMakeIPX(node, network, port);
int errNo;
if (![self of_createSocketForAddress: &address errNo: &errNo])
@throw [OFConnectionFailedException
exceptionWithNode: node
@@ -252,17 +251,17 @@
port: (uint16_t)port
{
[self asyncConnectToNode: node
network: network
port: port
- runLoopMode: of_run_loop_mode_default];
+ runLoopMode: OFDefaultRunLoopMode];
}
- (void)asyncConnectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ runLoopMode: (OFRunLoopMode)runLoopMode
{
void *pool = objc_autoreleasePoolPush();
[[[[OFSPXSocketAsyncConnectDelegate alloc]
initWithSocket: self
@@ -279,24 +278,24 @@
#ifdef OF_HAVE_BLOCKS
- (void)asyncConnectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
- block: (of_spx_socket_async_connect_block_t)block
+ block: (OFSPXSocketAsyncConnectBlock)block
{
[self asyncConnectToNode: node
network: network
port: port
- runLoopMode: of_run_loop_mode_default
+ runLoopMode: OFDefaultRunLoopMode
block: block];
}
- (void)asyncConnectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_spx_socket_async_connect_block_t)block
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFSPXSocketAsyncConnectBlock)block
{
void *pool = objc_autoreleasePoolPush();
[[[[OFSPXSocketAsyncConnectDelegate alloc]
initWithSocket: self
@@ -308,75 +307,76 @@
objc_autoreleasePoolPop(pool);
}
#endif
-- (of_socket_address_t)bindToPort: (uint16_t)port
+- (OFSocketAddress)bindToPort: (uint16_t)port
{
const unsigned char zeroNode[IPX_NODE_LEN] = { 0 };
- of_socket_address_t address;
+ OFSocketAddress address;
#if SOCK_CLOEXEC == 0 && defined(HAVE_FCNTL_H) && defined(FD_CLOEXEC)
int flags;
#endif
- if (_socket != INVALID_SOCKET)
+ if (_socket != OFInvalidSocketHandle)
@throw [OFAlreadyConnectedException exceptionWithSocket: self];
- address = of_socket_address_ipx(zeroNode, 0, port);
+ address = OFSocketAddressMakeIPX(zeroNode, 0, port);
if ((_socket = socket(address.sockaddr.sockaddr.sa_family,
- SOCK_SEQPACKET | SOCK_CLOEXEC, NSPROTO_SPX)) == INVALID_SOCKET)
+ SOCK_SEQPACKET | SOCK_CLOEXEC, NSPROTO_SPX)) ==
+ OFInvalidSocketHandle)
@throw [OFBindFailedException
exceptionWithPort: port
- packetType: SPX_PACKET_TYPE
+ packetType: SPXPacketType
socket: self
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
_canBlock = true;
#if SOCK_CLOEXEC == 0 && defined(HAVE_FCNTL_H) && defined(FD_CLOEXEC)
if ((flags = fcntl(_socket, F_GETFD, 0)) != -1)
fcntl(_socket, F_SETFD, flags | FD_CLOEXEC);
#endif
if (bind(_socket, &address.sockaddr.sockaddr, address.length) != 0) {
- int errNo = of_socket_errno();
+ int errNo = OFSocketErrNo();
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
@throw [OFBindFailedException exceptionWithPort: port
- packetType: SPX_PACKET_TYPE
+ packetType: SPXPacketType
socket: self
errNo: errNo];
}
memset(&address, 0, sizeof(address));
- address.family = OF_SOCKET_ADDRESS_FAMILY_IPX;
+ address.family = OFSocketAddressFamilyIPX;
address.length = (socklen_t)sizeof(address.sockaddr);
- if (of_getsockname(_socket, &address.sockaddr.sockaddr,
+ if (OFGetSockName(_socket, &address.sockaddr.sockaddr,
&address.length) != 0) {
- int errNo = of_socket_errno();
+ int errNo = OFSocketErrNo();
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
@throw [OFBindFailedException exceptionWithPort: port
- packetType: SPX_PACKET_TYPE
+ packetType: SPXPacketType
socket: self
errNo: errNo];
}
if (address.sockaddr.sockaddr.sa_family != AF_IPX) {
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
@throw [OFBindFailedException exceptionWithPort: port
- packetType: SPX_PACKET_TYPE
+ packetType: SPXPacketType
socket: self
errNo: EAFNOSUPPORT];
}
return address;
}
@end
Index: src/OFSPXStreamSocket.h
==================================================================
--- src/OFSPXStreamSocket.h
+++ src/OFSPXStreamSocket.h
@@ -28,12 +28,11 @@
* @brief A block which is called when the socket connected.
*
* @param exception An exception which occurred while connecting the socket or
* `nil` on success
*/
-typedef void (^of_spx_stream_socket_async_connect_block_t)(
- id _Nullable exception);
+typedef void (^OFSPXStreamSocketAsyncConnectBlock)(id _Nullable exception);
#endif
/**
* @protocol OFSPXStreamSocketDelegate OFSPXStreamSocket.h \
* ObjFW/OFSPXStreamSocket.h
@@ -120,11 +119,11 @@
* @param runLoopMode The run loop mode in which to perform the async connect
*/
- (void)asyncConnectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
- runLoopMode: (of_run_loop_mode_t)runLoopMode;
+ runLoopMode: (OFRunLoopMode)runLoopMode;
#ifdef OF_HAVE_BLOCKS
/**
* @brief Asynchronously connect the OFSPXStreamSocket to the specified
* destination.
@@ -136,11 +135,11 @@
* @param block The block to execute once the connection has been established
*/
- (void)asyncConnectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
- block: (of_spx_stream_socket_async_connect_block_t)block;
+ block: (OFSPXStreamSocketAsyncConnectBlock)block;
/**
* @brief Asynchronously connect the OFSPXStreamSocket to the specified
* destination.
*
@@ -152,20 +151,20 @@
* @param block The block to execute once the connection has been established
*/
- (void)asyncConnectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_spx_stream_socket_async_connect_block_t)block;
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFSPXStreamSocketAsyncConnectBlock)block;
#endif
/**
* @brief Bind the socket to the specified network, node and port.
*
* @param port The port (sometimes called socket number) to bind to. 0 means to
* pick one and return it.
* @return The address on which this socket can be reached
*/
-- (of_socket_address_t)bindToPort: (uint16_t)port;
+- (OFSocketAddress)bindToPort: (uint16_t)port;
@end
OF_ASSUME_NONNULL_END
Index: src/OFSPXStreamSocket.m
==================================================================
--- src/OFSPXStreamSocket.m
+++ src/OFSPXStreamSocket.m
@@ -18,29 +18,28 @@
#include
#import "OFSPXStreamSocket.h"
#import "OFRunLoop.h"
#import "OFRunLoop+Private.h"
+#import "OFSocket.h"
+#import "OFSocket+Private.h"
#import "OFAlreadyConnectedException.h"
#import "OFBindFailedException.h"
#import "OFConnectionFailedException.h"
#import "OFNotOpenException.h"
-#import "socket.h"
-#import "socket_helpers.h"
-
#ifndef NSPROTO_SPX
# define NSPROTO_SPX 0
#endif
-#define SPX_PACKET_TYPE 5
+static const uint8_t SPXPacketType = 5;
@interface OFSPXStreamSocket ()
-- (int)of_createSocketForAddress: (const of_socket_address_t *)address
+- (int)of_createSocketForAddress: (const OFSocketAddress *)address
errNo: (int *)errNo;
-- (bool)of_connectSocketToAddress: (const of_socket_address_t *)address
+- (bool)of_connectSocketToAddress: (const OFSocketAddress *)address
errNo: (int *)errNo;
- (void)of_closeSocket;
@end
OF_DIRECT_MEMBERS
@@ -50,34 +49,32 @@
OFSPXStreamSocket *_socket;
unsigned char _node[IPX_NODE_LEN];
uint32_t _network;
uint16_t _port;
#ifdef OF_HAVE_BLOCKS
- of_spx_stream_socket_async_connect_block_t _block;
+ OFSPXStreamSocketAsyncConnectBlock _block;
#endif
}
- (instancetype)initWithSocket: (OFSPXStreamSocket *)socket
node: (unsigned char [IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
#ifdef OF_HAVE_BLOCKS
- block: (of_spx_stream_socket_async_connect_block_t)
- block
+ block: (OFSPXStreamSocketAsyncConnectBlock)block
#endif
;
-- (void)startWithRunLoopMode: (of_run_loop_mode_t)runLoopMode;
+- (void)startWithRunLoopMode: (OFRunLoopMode)runLoopMode;
@end
@implementation OFSPXStreamSocketAsyncConnectDelegate
- (instancetype)initWithSocket: (OFSPXStreamSocket *)sock
node: (unsigned char [IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
#ifdef OF_HAVE_BLOCKS
- block: (of_spx_stream_socket_async_connect_block_t)
- block
+ block: (OFSPXStreamSocketAsyncConnectBlock)block
#endif
{
self = [super init];
@try {
@@ -104,14 +101,14 @@
#endif
[super dealloc];
}
-- (void)startWithRunLoopMode: (of_run_loop_mode_t)runLoopMode
+- (void)startWithRunLoopMode: (OFRunLoopMode)runLoopMode
{
- of_socket_address_t address =
- of_socket_address_ipx(_node, _network, _port);
+ OFSocketAddress address =
+ OFSocketAddressMakeIPX(_node, _network, _port);
id exception = nil;
int errNo;
if (![_socket of_createSocketForAddress: &address errNo: &errNo]) {
exception = [self of_connectionFailedExceptionForErrNo: errNo];
@@ -176,23 +173,24 @@
@end
@implementation OFSPXStreamSocket
@dynamic delegate;
-- (int)of_createSocketForAddress: (const of_socket_address_t *)address
+- (int)of_createSocketForAddress: (const OFSocketAddress *)address
errNo: (int *)errNo
{
#if SOCK_CLOEXEC == 0 && defined(HAVE_FCNTL) && defined(FD_CLOEXEC)
int flags;
#endif
- if (_socket != INVALID_SOCKET)
+ if (_socket != OFInvalidSocketHandle)
@throw [OFAlreadyConnectedException exceptionWithSocket: self];
if ((_socket = socket(address->sockaddr.ipx.sipx_family,
- SOCK_SEQPACKET | SOCK_CLOEXEC, NSPROTO_SPX)) == INVALID_SOCKET) {
- *errNo = of_socket_errno();
+ SOCK_SEQPACKET | SOCK_CLOEXEC, NSPROTO_SPX)) ==
+ OFInvalidSocketHandle) {
+ *errNo = OFSocketErrNo();
return false;
}
#if SOCK_CLOEXEC == 0 && defined(HAVE_FCNTL) && defined(FD_CLOEXEC)
if ((flags = fcntl(_socket, F_GETFD, 0)) != -1)
@@ -200,37 +198,36 @@
#endif
return true;
}
-- (bool)of_connectSocketToAddress: (const of_socket_address_t *)address
+- (bool)of_connectSocketToAddress: (const OFSocketAddress *)address
errNo: (int *)errNo
{
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
@throw [OFNotOpenException exceptionWithObject: self];
if (connect(_socket, &address->sockaddr.sockaddr,
address->length) != 0) {
- *errNo = of_socket_errno();
+ *errNo = OFSocketErrNo();
return false;
}
return true;
}
- (void)of_closeSocket
{
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
}
- (void)connectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
{
- of_socket_address_t address =
- of_socket_address_ipx(node, network, port);
+ OFSocketAddress address = OFSocketAddressMakeIPX(node, network, port);
int errNo;
if (![self of_createSocketForAddress: &address errNo: &errNo])
@throw [OFConnectionFailedException
exceptionWithNode: node
@@ -256,17 +253,17 @@
port: (uint16_t)port
{
[self asyncConnectToNode: node
network: network
port: port
- runLoopMode: of_run_loop_mode_default];
+ runLoopMode: OFDefaultRunLoopMode];
}
- (void)asyncConnectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ runLoopMode: (OFRunLoopMode)runLoopMode
{
void *pool = objc_autoreleasePoolPush();
[[[[OFSPXStreamSocketAsyncConnectDelegate alloc]
initWithSocket: self
@@ -283,24 +280,24 @@
#ifdef OF_HAVE_BLOCKS
- (void)asyncConnectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
- block: (of_spx_stream_socket_async_connect_block_t)block
+ block: (OFSPXStreamSocketAsyncConnectBlock)block
{
[self asyncConnectToNode: node
network: network
port: port
- runLoopMode: of_run_loop_mode_default
+ runLoopMode: OFDefaultRunLoopMode
block: block];
}
- (void)asyncConnectToNode: (unsigned char [_Nonnull IPX_NODE_LEN])node
network: (uint32_t)network
port: (uint16_t)port
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_spx_stream_socket_async_connect_block_t)block
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFSPXStreamSocketAsyncConnectBlock)block
{
void *pool = objc_autoreleasePoolPush();
[[[[OFSPXStreamSocketAsyncConnectDelegate alloc]
initWithSocket: self
@@ -312,75 +309,75 @@
objc_autoreleasePoolPop(pool);
}
#endif
-- (of_socket_address_t)bindToPort: (uint16_t)port
+- (OFSocketAddress)bindToPort: (uint16_t)port
{
const unsigned char zeroNode[IPX_NODE_LEN] = { 0 };
- of_socket_address_t address;
+ OFSocketAddress address;
#if SOCK_CLOEXEC == 0 && defined(HAVE_FCNTL_H) && defined(FD_CLOEXEC)
int flags;
#endif
- if (_socket != INVALID_SOCKET)
+ if (_socket != OFInvalidSocketHandle)
@throw [OFAlreadyConnectedException exceptionWithSocket: self];
- address = of_socket_address_ipx(zeroNode, 0, port);
+ address = OFSocketAddressMakeIPX(zeroNode, 0, port);
if ((_socket = socket(address.sockaddr.sockaddr.sa_family,
- SOCK_STREAM | SOCK_CLOEXEC, NSPROTO_SPX)) == INVALID_SOCKET)
+ SOCK_STREAM | SOCK_CLOEXEC, NSPROTO_SPX)) == OFInvalidSocketHandle)
@throw [OFBindFailedException
exceptionWithPort: port
- packetType: SPX_PACKET_TYPE
+ packetType: SPXPacketType
socket: self
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
_canBlock = true;
#if SOCK_CLOEXEC == 0 && defined(HAVE_FCNTL_H) && defined(FD_CLOEXEC)
if ((flags = fcntl(_socket, F_GETFD, 0)) != -1)
fcntl(_socket, F_SETFD, flags | FD_CLOEXEC);
#endif
if (bind(_socket, &address.sockaddr.sockaddr, address.length) != 0) {
- int errNo = of_socket_errno();
+ int errNo = OFSocketErrNo();
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
@throw [OFBindFailedException exceptionWithPort: port
- packetType: SPX_PACKET_TYPE
+ packetType: SPXPacketType
socket: self
errNo: errNo];
}
memset(&address, 0, sizeof(address));
- address.family = OF_SOCKET_ADDRESS_FAMILY_IPX;
+ address.family = OFSocketAddressFamilyIPX;
address.length = (socklen_t)sizeof(address.sockaddr);
- if (of_getsockname(_socket, &address.sockaddr.sockaddr,
+ if (OFGetSockName(_socket, &address.sockaddr.sockaddr,
&address.length) != 0) {
- int errNo = of_socket_errno();
+ int errNo = OFSocketErrNo();
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
@throw [OFBindFailedException exceptionWithPort: port
- packetType: SPX_PACKET_TYPE
+ packetType: SPXPacketType
socket: self
errNo: errNo];
}
if (address.sockaddr.sockaddr.sa_family != AF_IPX) {
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
@throw [OFBindFailedException exceptionWithPort: port
- packetType: SPX_PACKET_TYPE
+ packetType: SPXPacketType
socket: self
errNo: EAFNOSUPPORT];
}
return address;
}
@end
Index: src/OFSandbox.h
==================================================================
--- src/OFSandbox.h
+++ src/OFSandbox.h
@@ -15,27 +15,16 @@
#import "OFObject.h"
OF_ASSUME_NONNULL_BEGIN
-/** @file */
-
@class OFArray OF_GENERIC(ObjectType);
@class OFMutableArray OF_GENERIC(ObjectType);
@class OFPair OF_GENERIC(FirstType, SecondType);
-/**
- * @brief An @ref OFPair for a path to unveil, with the first string being the
- * path and the second the permissions.
- */
-typedef OFPair OF_GENERIC(OFString *, OFString *) *of_sandbox_unveil_path_t;
-
-/**
- * @class OFSandbox OFSandbox.h ObjFW/OFSandbox.h
- *
- * @brief A class which describes a sandbox for the application.
- */
+typedef OFPair OF_GENERIC(OFString *, OFString *) *OFSandboxUnveilPath;
+
@interface OFSandbox: OFObject
{
unsigned int _allowsStdIO: 1;
unsigned int _allowsReadingFiles: 1;
unsigned int _allowsWritingFiles: 1;
@@ -64,203 +53,52 @@
unsigned int _allowsPF: 1;
unsigned int _allowsAudio: 1;
unsigned int _allowsBPF: 1;
unsigned int _allowsUnveil: 1;
unsigned int _returnsErrors: 1;
- OFMutableArray OF_GENERIC(of_sandbox_unveil_path_t) *_unveiledPaths;
+ OFMutableArray OF_GENERIC(OFSandboxUnveilPath) *_unveiledPaths;
@public
size_t _unveiledPathsIndex;
OF_RESERVE_IVARS(OFSandbox, 4)
}
-/**
- * @brief Allows IO operations on previously allocated file descriptors.
- */
@property (nonatomic) bool allowsStdIO;
-
-/**
- * @brief Allows read access to the file system.
- */
@property (nonatomic) bool allowsReadingFiles;
-
-/**
- * @brief Allows write access to the file system.
- */
@property (nonatomic) bool allowsWritingFiles;
-
-/**
- * @brief Allows creating files in the file system.
- */
@property (nonatomic) bool allowsCreatingFiles;
-
-/**
- * @brief Allows creating special files in the file system.
- */
@property (nonatomic) bool allowsCreatingSpecialFiles;
-
-/**
- * @brief Allows creating, reading and writing temporary files in `/tmp`.
- */
@property (nonatomic) bool allowsTemporaryFiles;
-
-/**
- * @brief Allows using IP sockets.
- */
@property (nonatomic) bool allowsIPSockets;
-
-/**
- * @brief Allows multicast sockets.
- */
@property (nonatomic) bool allowsMulticastSockets;
-
-/**
- * @brief Allows explicit changes to file attributes.
- */
@property (nonatomic) bool allowsChangingFileAttributes;
-
-/**
- * @brief Allows changing ownership of files.
- */
@property (nonatomic) bool allowsFileOwnerChanges;
-
-/**
- * @brief Allows file locks.
- */
@property (nonatomic) bool allowsFileLocks;
-
-/**
- * @brief Allows UNIX sockets.
- */
@property (nonatomic) bool allowsUNIXSockets;
-
-/**
- * @brief Allows syscalls necessary for DNS lookups.
- */
@property (nonatomic) bool allowsDNS;
-
-/**
- * @brief Allows to look up users and groups.
- */
@property (nonatomic) bool allowsUserDatabaseReading;
-
-/**
- * @brief Allows sending file descriptors via sendmsg().
- */
@property (nonatomic) bool allowsFileDescriptorSending;
-
-/**
- * @brief Allows receiving file descriptors via recvmsg().
- */
@property (nonatomic) bool allowsFileDescriptorReceiving;
-
-/**
- * @brief Allows MTIOCGET and MTIOCTOP operations on tape devices.
- */
@property (nonatomic) bool allowsTape;
-
-/**
- * @brief Allows read-write operations and ioctls on the TTY.
- */
@property (nonatomic) bool allowsTTY;
-
-/**
- * @brief Allows various process relationshop operations.
- */
@property (nonatomic) bool allowsProcessOperations;
-
-/**
- * @brief Allows execve().
- */
@property (nonatomic) bool allowsExec;
-
-/**
- * @brief Allows PROT_EXEC for `mmap()` and `mprotect()`.
- */
@property (nonatomic) bool allowsProtExec;
-
-/**
- * @brief Allows `settime()`.
- */
@property (nonatomic) bool allowsSetTime;
-
-/**
- * @brief Allows introspection of processes on the system.
- */
@property (nonatomic) bool allowsPS;
-
-/**
- * @brief Allows introspection of the system's virtual memory.
- */
@property (nonatomic) bool allowsVMInfo;
-
-/**
- * @brief Allows changing the rights of process, for example the UID.
- */
@property (nonatomic) bool allowsChangingProcessRights;
-
-/**
- * @brief Allows certain ioctls on the PF device.
- */
@property (nonatomic) bool allowsPF;
-
-/**
- * @brief Allows certain ioctls on audio devices.
- */
@property (nonatomic) bool allowsAudio;
-
-/**
- * @brief Allows BIOCGSTATS to collect statistics from a BPF device.
- */
@property (nonatomic) bool allowsBPF;
-
-/**
- * @brief Allows unveiling more paths.
- */
@property (nonatomic) bool allowsUnveil;
-
-/**
- * @brief Returns errors instead of killing the process.
- */
@property (nonatomic) bool returnsErrors;
-
#ifdef OF_HAVE_PLEDGE
-/**
- * The string for OpenBSD's pledge() call.
- *
- * @warning Only available on systems with the pledge() call!
- */
@property (readonly, nonatomic) OFString *pledgeString;
#endif
-
-/**
- * @brief A list of unveiled paths.
- */
-@property (readonly, nonatomic)
- OFArray OF_GENERIC(of_sandbox_unveil_path_t) *unveiledPaths;
-
-/**
- * @brief Create a new, autorelease OFSandbox.
- */
-+ (instancetype)sandbox;
-
-/**
- * @brief "Unveils" the specified path, meaning that it becomes visible from
- * the sandbox with the specified permissions.
- *
- * @param path The path to unveil
- * @param permissions The permissions for the path. The following permissions
- * can be combined:
- * Permission | Description
- * -----------|--------------------
- * r | Make the path available for reading, like
- * | @ref allowsReadingFiles
- * w | Make the path available for writing, like
- * | @ref allowsWritingFiles
- * x | Make the path available for executing, like
- * | @ref allowsExec
- * c | Make the path available for creation and
- * | deletion, like @ref allowsCreatingFiles
- */
+@property (readonly, nonatomic)
+ OFArray OF_GENERIC(OFSandboxUnveilPath) *unveiledPaths;
+
++ (instancetype)sandbox;
- (void)unveilPath: (OFString *)path permissions: (OFString *)permissions;
@end
OF_ASSUME_NONNULL_END
Index: src/OFSandbox.m
==================================================================
--- src/OFSandbox.m
+++ src/OFSandbox.m
@@ -467,46 +467,46 @@
return true;
}
- (unsigned long)hash
{
- uint32_t hash;
-
- OF_HASH_INIT(hash);
-
- OF_HASH_ADD(hash, _allowsStdIO);
- OF_HASH_ADD(hash, _allowsReadingFiles);
- OF_HASH_ADD(hash, _allowsWritingFiles);
- OF_HASH_ADD(hash, _allowsCreatingFiles);
- OF_HASH_ADD(hash, _allowsCreatingSpecialFiles);
- OF_HASH_ADD(hash, _allowsTemporaryFiles);
- OF_HASH_ADD(hash, _allowsIPSockets);
- OF_HASH_ADD(hash, _allowsMulticastSockets);
- OF_HASH_ADD(hash, _allowsChangingFileAttributes);
- OF_HASH_ADD(hash, _allowsFileOwnerChanges);
- OF_HASH_ADD(hash, _allowsFileLocks);
- OF_HASH_ADD(hash, _allowsUNIXSockets);
- OF_HASH_ADD(hash, _allowsDNS);
- OF_HASH_ADD(hash, _allowsUserDatabaseReading);
- OF_HASH_ADD(hash, _allowsFileDescriptorSending);
- OF_HASH_ADD(hash, _allowsFileDescriptorReceiving);
- OF_HASH_ADD(hash, _allowsTape);
- OF_HASH_ADD(hash, _allowsTTY);
- OF_HASH_ADD(hash, _allowsProcessOperations);
- OF_HASH_ADD(hash, _allowsExec);
- OF_HASH_ADD(hash, _allowsProtExec);
- OF_HASH_ADD(hash, _allowsSetTime);
- OF_HASH_ADD(hash, _allowsPS);
- OF_HASH_ADD(hash, _allowsVMInfo);
- OF_HASH_ADD(hash, _allowsChangingProcessRights);
- OF_HASH_ADD(hash, _allowsPF);
- OF_HASH_ADD(hash, _allowsAudio);
- OF_HASH_ADD(hash, _allowsBPF);
- OF_HASH_ADD(hash, _allowsUnveil);
- OF_HASH_ADD(hash, _returnsErrors);
-
- OF_HASH_FINALIZE(hash);
+ unsigned long hash;
+
+ OFHashInit(&hash);
+
+ OFHashAdd(&hash, _allowsStdIO);
+ OFHashAdd(&hash, _allowsReadingFiles);
+ OFHashAdd(&hash, _allowsWritingFiles);
+ OFHashAdd(&hash, _allowsCreatingFiles);
+ OFHashAdd(&hash, _allowsCreatingSpecialFiles);
+ OFHashAdd(&hash, _allowsTemporaryFiles);
+ OFHashAdd(&hash, _allowsIPSockets);
+ OFHashAdd(&hash, _allowsMulticastSockets);
+ OFHashAdd(&hash, _allowsChangingFileAttributes);
+ OFHashAdd(&hash, _allowsFileOwnerChanges);
+ OFHashAdd(&hash, _allowsFileLocks);
+ OFHashAdd(&hash, _allowsUNIXSockets);
+ OFHashAdd(&hash, _allowsDNS);
+ OFHashAdd(&hash, _allowsUserDatabaseReading);
+ OFHashAdd(&hash, _allowsFileDescriptorSending);
+ OFHashAdd(&hash, _allowsFileDescriptorReceiving);
+ OFHashAdd(&hash, _allowsTape);
+ OFHashAdd(&hash, _allowsTTY);
+ OFHashAdd(&hash, _allowsProcessOperations);
+ OFHashAdd(&hash, _allowsExec);
+ OFHashAdd(&hash, _allowsProtExec);
+ OFHashAdd(&hash, _allowsSetTime);
+ OFHashAdd(&hash, _allowsPS);
+ OFHashAdd(&hash, _allowsVMInfo);
+ OFHashAdd(&hash, _allowsChangingProcessRights);
+ OFHashAdd(&hash, _allowsPF);
+ OFHashAdd(&hash, _allowsAudio);
+ OFHashAdd(&hash, _allowsBPF);
+ OFHashAdd(&hash, _allowsUnveil);
+ OFHashAdd(&hash, _returnsErrors);
+
+ OFHashFinalize(&hash);
return hash;
}
#ifdef OF_HAVE_PLEDGE
@@ -595,10 +595,10 @@
secondObject: permissions]];
objc_autoreleasePoolPop(pool);
}
-- (OFArray OF_GENERIC(of_sandbox_unveil_path_t) *)unveiledPaths
+- (OFArray OF_GENERIC(OFSandboxUnveilPath) *)unveiledPaths
{
return [[_unveiledPaths copy] autorelease];
}
@end
ADDED src/OFScrypt.h
Index: src/OFScrypt.h
==================================================================
--- src/OFScrypt.h
+++ src/OFScrypt.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#ifndef __STDC_LIMIT_MACROS
+# define __STDC_LIMIT_MACROS
+#endif
+#ifndef __STDC_CONSTANT_MACROS
+# define __STDC_CONSTANT_MACROS
+#endif
+
+#import "macros.h"
+
+OF_ASSUME_NONNULL_BEGIN
+
+/** @file */
+
+@class OFHMAC;
+
+/**
+ * @brief The parameters for @ref OFScrypt.
+ */
+typedef struct {
+ /** @brief The block size to use. */
+ size_t blockSize;
+ /** @brief The CPU/memory cost factor to use. */
+ size_t costFactor;
+ /** @brief The parallelization to use. */
+ size_t parallelization;
+ /** @brief The salt to derive a key with. */
+ const unsigned char *salt;
+ /** @brief The length of the salt. */
+ size_t saltLength;
+ /** @brief The password to derive a key from. */
+ const char *password;
+ /** @brief The length of the password. */
+ size_t passwordLength;
+ /** @brief The buffer to write the key to. */
+ unsigned char *key;
+ /**
+ * @brief The desired length for the derived key.
+ *
+ * @ref key needs to have enough storage.
+ */
+ size_t keyLength;
+ /** @brief Whether data may be stored in swappable memory. */
+ bool allowsSwappableMemory;
+} OFScryptParameters;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern void OFSalsa20_8Core(uint32_t buffer[_Nonnull 16]);
+extern void OFScryptBlockMix(uint32_t *output, const uint32_t *input,
+ size_t blockSize);
+extern void OFScryptROMix(uint32_t *buffer, size_t blockSize,
+ size_t costFactor, uint32_t *tmp);
+
+/**
+ * @brief Derives a key from a password and a salt using scrypt.
+ *
+ * @param param The parameters to use
+ */
+extern void OFScrypt(OFScryptParameters param);
+#ifdef __cplusplus
+}
+#endif
+
+OF_ASSUME_NONNULL_END
ADDED src/OFScrypt.m
Index: src/OFScrypt.m
==================================================================
--- src/OFScrypt.m
+++ src/OFScrypt.m
@@ -0,0 +1,219 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#import "OFHMAC.h"
+#import "OFSHA256Hash.h"
+#import "OFSecureData.h"
+
+#import "OFInvalidArgumentException.h"
+#import "OFOutOfMemoryException.h"
+#import "OFOutOfRangeException.h"
+
+#import "OFScrypt.h"
+#import "OFPBKDF2.h"
+
+void
+OFSalsa20_8Core(uint32_t buffer[16])
+{
+ uint32_t tmp[16];
+
+ for (uint_fast8_t i = 0; i < 16; i++)
+ tmp[i] = OFToLittleEndian32(buffer[i]);
+
+ for (uint_fast8_t i = 0; i < 8; i += 2) {
+ tmp[ 4] ^= OFRotateLeft(tmp[ 0] + tmp[12], 7);
+ tmp[ 8] ^= OFRotateLeft(tmp[ 4] + tmp[ 0], 9);
+ tmp[12] ^= OFRotateLeft(tmp[ 8] + tmp[ 4], 13);
+ tmp[ 0] ^= OFRotateLeft(tmp[12] + tmp[ 8], 18);
+ tmp[ 9] ^= OFRotateLeft(tmp[ 5] + tmp[ 1], 7);
+ tmp[13] ^= OFRotateLeft(tmp[ 9] + tmp[ 5], 9);
+ tmp[ 1] ^= OFRotateLeft(tmp[13] + tmp[ 9], 13);
+ tmp[ 5] ^= OFRotateLeft(tmp[ 1] + tmp[13], 18);
+ tmp[14] ^= OFRotateLeft(tmp[10] + tmp[ 6], 7);
+ tmp[ 2] ^= OFRotateLeft(tmp[14] + tmp[10], 9);
+ tmp[ 6] ^= OFRotateLeft(tmp[ 2] + tmp[14], 13);
+ tmp[10] ^= OFRotateLeft(tmp[ 6] + tmp[ 2], 18);
+ tmp[ 3] ^= OFRotateLeft(tmp[15] + tmp[11], 7);
+ tmp[ 7] ^= OFRotateLeft(tmp[ 3] + tmp[15], 9);
+ tmp[11] ^= OFRotateLeft(tmp[ 7] + tmp[ 3], 13);
+ tmp[15] ^= OFRotateLeft(tmp[11] + tmp[ 7], 18);
+ tmp[ 1] ^= OFRotateLeft(tmp[ 0] + tmp[ 3], 7);
+ tmp[ 2] ^= OFRotateLeft(tmp[ 1] + tmp[ 0], 9);
+ tmp[ 3] ^= OFRotateLeft(tmp[ 2] + tmp[ 1], 13);
+ tmp[ 0] ^= OFRotateLeft(tmp[ 3] + tmp[ 2], 18);
+ tmp[ 6] ^= OFRotateLeft(tmp[ 5] + tmp[ 4], 7);
+ tmp[ 7] ^= OFRotateLeft(tmp[ 6] + tmp[ 5], 9);
+ tmp[ 4] ^= OFRotateLeft(tmp[ 7] + tmp[ 6], 13);
+ tmp[ 5] ^= OFRotateLeft(tmp[ 4] + tmp[ 7], 18);
+ tmp[11] ^= OFRotateLeft(tmp[10] + tmp[ 9], 7);
+ tmp[ 8] ^= OFRotateLeft(tmp[11] + tmp[10], 9);
+ tmp[ 9] ^= OFRotateLeft(tmp[ 8] + tmp[11], 13);
+ tmp[10] ^= OFRotateLeft(tmp[ 9] + tmp[ 8], 18);
+ tmp[12] ^= OFRotateLeft(tmp[15] + tmp[14], 7);
+ tmp[13] ^= OFRotateLeft(tmp[12] + tmp[15], 9);
+ tmp[14] ^= OFRotateLeft(tmp[13] + tmp[12], 13);
+ tmp[15] ^= OFRotateLeft(tmp[14] + tmp[13], 18);
+ }
+
+ for (uint_fast8_t i = 0; i < 16; i++)
+ buffer[i] = OFToLittleEndian32(OFFromLittleEndian32(buffer[i]) +
+ tmp[i]);
+
+ OFZeroMemory(tmp, sizeof(tmp));
+}
+
+void
+OFScryptBlockMix(uint32_t *output, const uint32_t *input, size_t blockSize)
+{
+ uint32_t tmp[16];
+
+ /* Check defined here and executed in OFScrypt() */
+#define OVERFLOW_CHECK_1 \
+ if (param.blockSize > SIZE_MAX / 2 || \
+ 2 * param.blockSize - 1 > SIZE_MAX / 16) \
+ @throw [OFOutOfRangeException exception];
+
+ memcpy(tmp, input + (2 * blockSize - 1) * 16, 64);
+
+ for (size_t i = 0; i < 2 * blockSize; i++) {
+ for (size_t j = 0; j < 16; j++)
+ tmp[j] ^= input[i * 16 + j];
+
+ OFSalsa20_8Core(tmp);
+
+ /*
+ * Even indices are stored in the first half and odd ones in
+ * the second.
+ */
+ memcpy(output + ((i / 2) + (i & 1) * blockSize) * 16, tmp, 64);
+ }
+
+ OFZeroMemory(tmp, sizeof(tmp));
+}
+
+void
+OFScryptROMix(uint32_t *buffer, size_t blockSize, size_t costFactor,
+ uint32_t *tmp)
+{
+ /* Check defined here and executed in OFScrypt() */
+#define OVERFLOW_CHECK_2 \
+ if (param.blockSize > SIZE_MAX / 128 / param.costFactor) \
+ @throw [OFOutOfRangeException exception];
+
+ uint32_t *tmp2 = tmp + 32 * blockSize;
+
+ memcpy(tmp, buffer, 128 * blockSize);
+
+ for (size_t i = 0; i < costFactor; i++) {
+ memcpy(tmp2 + i * 32 * blockSize, tmp, 128 * blockSize);
+ OFScryptBlockMix(tmp, tmp2 + i * 32 * blockSize, blockSize);
+ }
+
+ for (size_t i = 0; i < costFactor; i++) {
+ uint32_t j = OFFromLittleEndian32(
+ tmp[(2 * blockSize - 1) * 16]) & (costFactor - 1);
+
+ for (size_t k = 0; k < 32 * blockSize; k++)
+ tmp[k] ^= tmp2[j * 32 * blockSize + k];
+
+ OFScryptBlockMix(buffer, tmp, blockSize);
+
+ if (i < costFactor - 1)
+ memcpy(tmp, buffer, 128 * blockSize);
+ }
+}
+
+void
+OFScrypt(OFScryptParameters param)
+{
+ OFSecureData *tmp = nil, *buffer = nil;
+ OFHMAC *HMAC = nil;
+
+ if (param.blockSize == 0 || param.costFactor <= 1 ||
+ (param.costFactor & (param.costFactor - 1)) != 0 ||
+ param.parallelization == 0)
+ @throw [OFInvalidArgumentException exception];
+
+ /*
+ * These are defined by the functions above. They are defined there so
+ * that the check is next to the code and easy to verify, but actually
+ * checked here for performance.
+ */
+ OVERFLOW_CHECK_1
+ OVERFLOW_CHECK_2
+
+ @try {
+ uint32_t *tmpItems, *bufferItems;
+
+ if (param.costFactor > SIZE_MAX - 1 ||
+ (param.costFactor + 1) > SIZE_MAX / 128)
+ @throw [OFOutOfRangeException exception];
+
+ tmp = [[OFSecureData alloc]
+ initWithCount: (param.costFactor + 1) * 128
+ itemSize: param.blockSize
+ allowsSwappableMemory: param.allowsSwappableMemory];
+ tmpItems = tmp.mutableItems;
+
+ if (param.parallelization > SIZE_MAX / 128)
+ @throw [OFOutOfRangeException exception];
+
+ buffer = [[OFSecureData alloc]
+ initWithCount: param.parallelization * 128
+ itemSize: param.blockSize
+ allowsSwappableMemory: param.allowsSwappableMemory];
+ bufferItems = buffer.mutableItems;
+
+ HMAC = [[OFHMAC alloc]
+ initWithHashClass: [OFSHA256Hash class]
+ allowsSwappableMemory: param.allowsSwappableMemory];
+
+ OFPBKDF2((OFPBKDF2Parameters){
+ .HMAC = HMAC,
+ .iterations = 1,
+ .salt = param.salt,
+ .saltLength = param.saltLength,
+ .password = param.password,
+ .passwordLength = param.passwordLength,
+ .key = (unsigned char *)bufferItems,
+ .keyLength = param.parallelization * 128 *
+ param.blockSize,
+ .allowsSwappableMemory = param.allowsSwappableMemory
+ });
+
+ for (size_t i = 0; i < param.parallelization; i++)
+ OFScryptROMix(bufferItems + i * 32 * param.blockSize,
+ param.blockSize, param.costFactor, tmpItems);
+
+ OFPBKDF2((OFPBKDF2Parameters){
+ .HMAC = HMAC,
+ .iterations = 1,
+ .salt = (unsigned char *)bufferItems,
+ .saltLength = param.parallelization * 128 *
+ param.blockSize,
+ .password = param.password,
+ .passwordLength = param.passwordLength,
+ .key = param.key,
+ .keyLength = param.keyLength,
+ .allowsSwappableMemory = param.allowsSwappableMemory
+ });
+ } @finally {
+ [tmp release];
+ [buffer release];
+ [HMAC release];
+ }
+}
Index: src/OFSecureData.m
==================================================================
--- src/OFSecureData.m
+++ src/OFSecureData.m
@@ -23,24 +23,23 @@
#endif
#import "OFSecureData.h"
#import "OFString.h"
#import "OFSystemInfo.h"
+#ifdef OF_HAVE_THREADS
+# import "OFTLSKey.h"
+#endif
#import "OFInitializationFailedException.h"
#import "OFInvalidArgumentException.h"
#import "OFNotImplementedException.h"
#import "OFOutOfMemoryException.h"
#import "OFOutOfRangeException.h"
-#ifdef OF_HAVE_THREADS
-# import "tlskey.h"
-#endif
-
-#define CHUNK_SIZE 16
-
#if defined(HAVE_MMAP) && defined(HAVE_MLOCK) && defined(MAP_ANON)
+static const size_t chunkSize = 16;
+
struct page {
struct page *next, *previous;
void *map;
unsigned char *page;
};
@@ -49,12 +48,12 @@
static thread_local struct page *firstPage = NULL;
static thread_local struct page *lastPage = NULL;
static thread_local struct page **preallocatedPages = NULL;
static thread_local size_t numPreallocatedPages = 0;
# elif defined(OF_HAVE_THREADS)
-static of_tlskey_t firstPageKey, lastPageKey;
-static of_tlskey_t preallocatedPagesKey, numPreallocatedPagesKey;
+static OFTLSKey firstPageKey, lastPageKey;
+static OFTLSKey preallocatedPagesKey, numPreallocatedPagesKey;
# else
static struct page *firstPage = NULL;
static struct page *lastPage = NULL;
static struct page **preallocatedPages = NULL;
static size_t numPreallocatedPages = 0;
@@ -97,68 +96,68 @@
static struct page *
addPage(bool allowPreallocated)
{
size_t pageSize = [OFSystemInfo pageSize];
- size_t mapSize = OF_ROUND_UP_POW2(CHAR_BIT, pageSize / CHUNK_SIZE) /
+ size_t mapSize = OFRoundUpToPowerOf2(CHAR_BIT, pageSize / chunkSize) /
CHAR_BIT;
struct page *page;
# if !defined(OF_HAVE_COMPILER_TLS) && defined(OF_HAVE_THREADS)
struct page *lastPage;
# endif
if (allowPreallocated) {
# if !defined(OF_HAVE_COMPILER_TLS) && defined(OF_HAVE_THREADS)
uintptr_t numPreallocatedPages =
- (uintptr_t)of_tlskey_get(numPreallocatedPagesKey);
+ (uintptr_t)OFTLSKeyGet(numPreallocatedPagesKey);
# endif
if (numPreallocatedPages > 0) {
# if !defined(OF_HAVE_COMPILER_TLS) && defined(OF_HAVE_THREADS)
struct page **preallocatedPages =
- of_tlskey_get(preallocatedPagesKey);
+ OFTLSKeyGet(preallocatedPagesKey);
# endif
numPreallocatedPages--;
# if !defined(OF_HAVE_COMPILER_TLS) && defined(OF_HAVE_THREADS)
- OF_ENSURE(of_tlskey_set(numPreallocatedPagesKey,
+ OFEnsure(OFTLSKeySet(numPreallocatedPagesKey,
(void *)numPreallocatedPages) == 0);
# endif
page = preallocatedPages[numPreallocatedPages];
if (numPreallocatedPages == 0) {
- free(preallocatedPages);
+ OFFreeMemory(preallocatedPages);
preallocatedPages = NULL;
# if !defined(OF_HAVE_COMPILER_TLS) && defined(OF_HAVE_THREADS)
- OF_ENSURE(of_tlskey_set(preallocatedPagesKey,
+ OFEnsure(OFTLSKeySet(preallocatedPagesKey,
preallocatedPages) == 0);
# endif
}
return page;
}
}
- page = of_alloc(1, sizeof(*page));
+ page = OFAllocMemory(1, sizeof(*page));
@try {
- page->map = of_alloc_zeroed(1, mapSize);
+ page->map = OFAllocZeroedMemory(1, mapSize);
} @catch (id e) {
- free(page);
+ OFFreeMemory(page);
@throw e;
}
@try {
page->page = mapPages(1);
} @catch (id e) {
- free(page->map);
- free(page);
+ OFFreeMemory(page->map);
+ OFFreeMemory(page);
@throw e;
}
- of_explicit_memset(page->page, 0, pageSize);
+ OFZeroMemory(page->page, pageSize);
# if !defined(OF_HAVE_COMPILER_TLS) && defined(OF_HAVE_THREADS)
- lastPage = of_tlskey_get(lastPageKey);
+ lastPage = OFTLSKeyGet(lastPageKey);
# endif
page->previous = lastPage;
page->next = NULL;
@@ -169,14 +168,14 @@
lastPage = page;
if (firstPage == NULL)
firstPage = page;
# else
- OF_ENSURE(of_tlskey_set(lastPageKey, page) == 0);
+ OFEnsure(OFTLSKeySet(lastPageKey, page) == 0);
- if (of_tlskey_get(firstPageKey) == NULL)
- OF_ENSURE(of_tlskey_set(firstPageKey, page) == 0);
+ if (OFTLSKeyGet(firstPageKey) == NULL)
+ OFEnsure(OFTLSKeySet(firstPageKey, page) == 0);
# endif
return page;
}
@@ -183,19 +182,19 @@
static void
removePageIfEmpty(struct page *page)
{
unsigned char *map = page->map;
size_t pageSize = [OFSystemInfo pageSize];
- size_t mapSize = OF_ROUND_UP_POW2(CHAR_BIT, pageSize / CHUNK_SIZE) /
+ size_t mapSize = OFRoundUpToPowerOf2(CHAR_BIT, pageSize / chunkSize) /
CHAR_BIT;
for (size_t i = 0; i < mapSize; i++)
if (map[i] != 0)
return;
unmapPages(page->page, 1);
- free(page->map);
+ OFFreeMemory(page->map);
if (page->previous != NULL)
page->previous->next = page->next;
if (page->next != NULL)
page->next->previous = page->previous;
@@ -204,31 +203,31 @@
if (firstPage == page)
firstPage = page->next;
if (lastPage == page)
lastPage = page->previous;
# else
- if (of_tlskey_get(firstPageKey) == page)
- OF_ENSURE(of_tlskey_set(firstPageKey, page->next) == 0);
- if (of_tlskey_get(lastPageKey) == page)
- OF_ENSURE(of_tlskey_set(lastPageKey, page->previous) == 0);
+ if (OFTLSKeyGet(firstPageKey) == page)
+ OFEnsure(OFTLSKeySet(firstPageKey, page->next) == 0);
+ if (OFTLSKeyGet(lastPageKey) == page)
+ OFEnsure(OFTLSKeySet(lastPageKey, page->previous) == 0);
# endif
- free(page);
+ OFFreeMemory(page);
}
static void *
allocateMemory(struct page *page, size_t bytes)
{
size_t chunks, chunksLeft, pageSize, i, firstChunk;
- bytes = OF_ROUND_UP_POW2(CHUNK_SIZE, bytes);
- chunks = chunksLeft = bytes / CHUNK_SIZE;
+ bytes = OFRoundUpToPowerOf2(chunkSize, bytes);
+ chunks = chunksLeft = bytes / chunkSize;
firstChunk = 0;
pageSize = [OFSystemInfo pageSize];
- for (i = 0; i < pageSize / CHUNK_SIZE; i++) {
- if (of_bitset_isset(page->map, i)) {
+ for (i = 0; i < pageSize / chunkSize; i++) {
+ if (OFBitsetIsSet(page->map, i)) {
chunksLeft = chunks;
firstChunk = i + 1;
continue;
}
@@ -236,13 +235,13 @@
break;
}
if (chunksLeft == 0) {
for (size_t j = firstChunk; j < firstChunk + chunks; j++)
- of_bitset_set(page->map, j);
+ OFBitsetSet(page->map, j);
- return page->page + (CHUNK_SIZE * firstChunk);
+ return page->page + (chunkSize * firstChunk);
}
return NULL;
}
@@ -249,18 +248,18 @@
static void
freeMemory(struct page *page, void *pointer, size_t bytes)
{
size_t chunks, chunkIndex;
- bytes = OF_ROUND_UP_POW2(CHUNK_SIZE, bytes);
- chunks = bytes / CHUNK_SIZE;
- chunkIndex = ((uintptr_t)pointer - (uintptr_t)page->page) / CHUNK_SIZE;
+ bytes = OFRoundUpToPowerOf2(chunkSize, bytes);
+ chunks = bytes / chunkSize;
+ chunkIndex = ((uintptr_t)pointer - (uintptr_t)page->page) / chunkSize;
- of_explicit_memset(pointer, 0, bytes);
+ OFZeroMemory(pointer, bytes);
for (size_t i = 0; i < chunks; i++)
- of_bitset_clear(page->map, chunkIndex + i);
+ OFBitsetClear(page->map, chunkIndex + i);
}
#endif
@implementation OFSecureData
@synthesize allowsSwappableMemory = _allowsSwappableMemory;
@@ -270,54 +269,53 @@
+ (void)initialize
{
if (self != [OFSecureData class])
return;
- if (of_tlskey_new(&firstPageKey) != 0 ||
- of_tlskey_new(&lastPageKey) != 0 ||
- of_tlskey_new(&preallocatedPagesKey) != 0 ||
- of_tlskey_new(&numPreallocatedPagesKey) != 0)
+ if (OFTLSKeyNew(&firstPageKey) != 0 || OFTLSKeyNew(&lastPageKey) != 0 ||
+ OFTLSKeyNew(&preallocatedPagesKey) != 0 ||
+ OFTLSKeyNew(&numPreallocatedPagesKey) != 0)
@throw [OFInitializationFailedException
exceptionWithClass: self];
}
#endif
+ (void)preallocateUnswappableMemoryWithSize: (size_t)size
{
#if defined(HAVE_MMAP) && defined(HAVE_MLOCK) && defined(MAP_ANON)
size_t pageSize = [OFSystemInfo pageSize];
- size_t numPages = OF_ROUND_UP_POW2(pageSize, size) / pageSize;
+ size_t numPages = OFRoundUpToPowerOf2(pageSize, size) / pageSize;
# if !defined(OF_HAVE_COMPILER_TLS) && defined(OF_HAVE_THREADS)
- struct page **preallocatedPages = of_tlskey_get(preallocatedPagesKey);
+ struct page **preallocatedPages = OFTLSKeyGet(preallocatedPagesKey);
size_t numPreallocatedPages;
# endif
size_t i;
if (preallocatedPages != NULL)
@throw [OFInvalidArgumentException exception];
- preallocatedPages = of_alloc_zeroed(numPages, sizeof(struct page));
+ preallocatedPages = OFAllocZeroedMemory(numPages, sizeof(struct page));
# if !defined(OF_HAVE_COMPILER_TLS) && defined(OF_HAVE_THREADS)
- OF_ENSURE(of_tlskey_set(preallocatedPagesKey, preallocatedPages) == 0);
+ OFEnsure(OFTLSKeySet(preallocatedPagesKey, preallocatedPages) == 0);
# endif
@try {
for (i = 0; i < numPages; i++)
preallocatedPages[i] = addPage(false);
} @catch (id e) {
for (size_t j = 0; j < i; j++)
removePageIfEmpty(preallocatedPages[j]);
- free(preallocatedPages);
+ OFFreeMemory(preallocatedPages);
preallocatedPages = NULL;
@throw e;
}
numPreallocatedPages = numPages;
# if !defined(OF_HAVE_COMPILER_TLS) && defined(OF_HAVE_THREADS)
- OF_ENSURE(of_tlskey_set(numPreallocatedPagesKey,
+ OFEnsure(OFTLSKeySet(numPreallocatedPagesKey,
(void *)(uintptr_t)numPreallocatedPages) == 0);
# endif
#else
@throw [OFNotImplementedException exceptionWithSelector: _cmd
object: self];
@@ -414,20 +412,20 @@
if (count > SIZE_MAX / itemSize)
@throw [OFOutOfRangeException exception];
if (allowsSwappableMemory) {
- _items = of_alloc(count, itemSize);
+ _items = OFAllocMemory(count, itemSize);
_freeWhenDone = true;
memset(_items, 0, count * itemSize);
#if defined(HAVE_MMAP) && defined(HAVE_MLOCK) && defined(MAP_ANON)
} else if (count * itemSize >= pageSize)
- _items = mapPages(OF_ROUND_UP_POW2(pageSize,
+ _items = mapPages(OFRoundUpToPowerOf2(pageSize,
count * itemSize) / pageSize);
else {
# if !defined(OF_HAVE_COMPILER_TLS) && defined(OF_HAVE_THREADS)
- struct page *lastPage = of_tlskey_get(lastPageKey);
+ struct page *lastPage = OFTLSKeyGet(lastPageKey);
# endif
for (struct page *page = lastPage; page != NULL;
page = page->previous) {
_items = allocateMemory(page, count * itemSize);
@@ -529,11 +527,11 @@
if (!_allowsSwappableMemory) {
size_t pageSize = [OFSystemInfo pageSize];
if (_count * _itemSize > pageSize)
unmapPages(_items,
- OF_ROUND_UP_POW2(pageSize, _count * _itemSize) /
+ OFRoundUpToPowerOf2(pageSize, _count * _itemSize) /
pageSize);
else if (_page != NULL) {
if (_items != NULL)
freeMemory(_page, _items, _count * _itemSize);
@@ -558,11 +556,11 @@
return _items + idx * _itemSize;
}
- (void)zero
{
- of_explicit_memset(_items, 0, _count * _itemSize);
+ OFZeroMemory(_items, _count * _itemSize);
}
- (id)copy
{
OFSecureData *copy = [[OFSecureData alloc]
Index: src/OFSeekableStream.h
==================================================================
--- src/OFSeekableStream.h
+++ src/OFSeekableStream.h
@@ -29,19 +29,19 @@
#import "OFStream.h"
OF_ASSUME_NONNULL_BEGIN
#if defined(OF_WINDOWS)
-typedef __int64 of_offset_t;
+typedef __int64 OFFileOffset;
#elif defined(OF_ANDROID)
-typedef long long of_offset_t;
+typedef long long OFFileOffset;
#elif defined(OF_MORPHOS)
-typedef signed long long of_offset_t;
+typedef signed long long OFFileOffset;
#elif defined(OF_HAVE_OFF64_T)
-typedef off64_t of_offset_t;
+typedef off64_t OFFileOffset;
#else
-typedef off_t of_offset_t;
+typedef off_t OFFileOffset;
#endif
/**
* @class OFSeekableStream OFSeekableStream.h ObjFW/OFSeekableStream.h
*
@@ -69,11 +69,11 @@
* `SEEK_SET` | Seek to the specified byte
* `SEEK_CUR` | Seek to the current location + offset
* `SEEK_END` | Seek to the end of the stream + offset
* @return The new offset form the start of the file
*/
-- (of_offset_t)seekToOffset: (of_offset_t)offset whence: (int)whence;
+- (OFFileOffset)seekToOffset: (OFFileOffset)offset whence: (int)whence;
/**
* @brief Seek the stream on the lowlevel.
*
* @warning Do not call this directly!
@@ -89,9 +89,9 @@
* `SEEK_SET` | Seek to the specified byte
* `SEEK_CUR` | Seek to the current location + offset
* `SEEK_END` | Seek to the end of the stream + offset
* @return The new offset from the start of the file
*/
-- (of_offset_t)lowlevelSeekToOffset: (of_offset_t)offset whence: (int)whence;
+- (OFFileOffset)lowlevelSeekToOffset: (OFFileOffset)offset whence: (int)whence;
@end
OF_ASSUME_NONNULL_END
Index: src/OFSeekableStream.m
==================================================================
--- src/OFSeekableStream.m
+++ src/OFSeekableStream.m
@@ -36,24 +36,24 @@
}
return [super init];
}
-- (of_offset_t)lowlevelSeekToOffset: (of_offset_t)offset whence: (int)whence
+- (OFFileOffset)lowlevelSeekToOffset: (OFFileOffset)offset whence: (int)whence
{
OF_UNRECOGNIZED_SELECTOR
}
-- (of_offset_t)seekToOffset: (of_offset_t)offset whence: (int)whence
+- (OFFileOffset)seekToOffset: (OFFileOffset)offset whence: (int)whence
{
if (whence == SEEK_CUR)
offset -= _readBufferLength;
offset = [self lowlevelSeekToOffset: offset whence: whence];
- free(_readBufferMemory);
+ OFFreeMemory(_readBufferMemory);
_readBuffer = _readBufferMemory = NULL;
_readBufferLength = 0;
return offset;
}
@end
Index: src/OFSelectKernelEventObserver.m
==================================================================
--- src/OFSelectKernelEventObserver.m
+++ src/OFSelectKernelEventObserver.m
@@ -29,17 +29,16 @@
#include
#import "OFSelectKernelEventObserver.h"
#import "OFArray.h"
+#import "OFSocket+Private.h"
#import "OFInitializationFailedException.h"
#import "OFObserveFailedException.h"
#import "OFOutOfRangeException.h"
-#import "socket_helpers.h"
-
#ifdef OF_AMIGAOS
# include
#endif
#ifdef OF_HPUX
@@ -97,11 +96,11 @@
#endif
if (fd > _maxFD)
_maxFD = fd;
- FD_SET((of_socket_t)fd, &_readFDs);
+ FD_SET((OFSocketHandle)fd, &_readFDs);
[super addObjectForReading: object];
}
- (void)addObjectForWriting: (id )object
@@ -121,11 +120,11 @@
#endif
if (fd > _maxFD)
_maxFD = fd;
- FD_SET((of_socket_t)fd, &_writeFDs);
+ FD_SET((OFSocketHandle)fd, &_writeFDs);
[super addObjectForWriting: object];
}
- (void)removeObjectForReading: (id )object
@@ -141,11 +140,11 @@
#ifndef OF_WINDOWS
if (fd >= (int)FD_SETSIZE)
@throw [OFOutOfRangeException exception];
#endif
- FD_CLR((of_socket_t)fd, &_readFDs);
+ FD_CLR((OFSocketHandle)fd, &_readFDs);
[super removeObjectForReading: object];
}
- (void)removeObjectForWriting: (id )object
@@ -162,16 +161,16 @@
#ifndef OF_WINDOWS
if (fd >= (int)FD_SETSIZE)
@throw [OFOutOfRangeException exception];
#endif
- FD_CLR((of_socket_t)fd, &_writeFDs);
+ FD_CLR((OFSocketHandle)fd, &_writeFDs);
[super removeObjectForWriting: object];
}
-- (void)observeForTimeInterval: (of_time_interval_t)timeInterval
+- (void)observeForTimeInterval: (OFTimeInterval)timeInterval
{
fd_set readFDs;
fd_set writeFDs;
struct timeval timeout;
int events;
@@ -232,11 +231,11 @@
#endif
if (events < 0)
@throw [OFObserveFailedException
exceptionWithObserver: self
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
#ifdef OF_AMIGAOS
if (execSignalMask != 0 &&
[_delegate respondsToSelector: @selector(execSignalWasReceived:)])
[_delegate execSignalWasReceived: execSignalMask];
@@ -243,13 +242,13 @@
#else
if (FD_ISSET(_cancelFD[0], &readFDs)) {
char buffer;
# ifdef OF_HAVE_PIPE
- OF_ENSURE(read(_cancelFD[0], &buffer, 1) == 1);
+ OFEnsure(read(_cancelFD[0], &buffer, 1) == 1);
# else
- OF_ENSURE(recvfrom(_cancelFD[0], (void *)&buffer, 1, 0, NULL,
+ OFEnsure(recvfrom(_cancelFD[0], (void *)&buffer, 1, 0, NULL,
NULL) == 1);
# endif
}
#endif
@@ -258,11 +257,11 @@
for (id object in
[[_readObjects copy] autorelease]) {
void *pool2 = objc_autoreleasePoolPush();
int fd = object.fileDescriptorForReading;
- if (FD_ISSET((of_socket_t)fd, &readFDs) &&
+ if (FD_ISSET((OFSocketHandle)fd, &readFDs) &&
[_delegate respondsToSelector:
@selector(objectIsReadyForReading:)])
[_delegate objectIsReadyForReading: object];
objc_autoreleasePoolPop(pool2);
@@ -271,11 +270,11 @@
for (id object in
[[_writeObjects copy] autorelease]) {
void *pool2 = objc_autoreleasePoolPush();
int fd = object.fileDescriptorForWriting;
- if (FD_ISSET((of_socket_t)fd, &writeFDs) &&
+ if (FD_ISSET((OFSocketHandle)fd, &writeFDs) &&
[_delegate respondsToSelector:
@selector(objectIsReadyForWriting:)])
[_delegate objectIsReadyForWriting: object];
objc_autoreleasePoolPop(pool2);
Index: src/OFSequencedPacketSocket.h
==================================================================
--- src/OFSequencedPacketSocket.h
+++ src/OFSequencedPacketSocket.h
@@ -14,12 +14,11 @@
*/
#import "OFObject.h"
#import "OFKernelEventObserver.h"
#import "OFRunLoop.h"
-
-#import "socket.h"
+#import "OFSocket.h"
OF_ASSUME_NONNULL_BEGIN
/** @file */
@@ -33,11 +32,11 @@
* @param length The length of the packet
* @param exception An exception which occurred while receiving or `nil` on
* success
* @return A bool whether the same block should be used for the next receive
*/
-typedef bool (^of_sequenced_packet_socket_async_receive_block_t)(size_t length,
+typedef bool (^OFSequencedPacketSocketAsyncReceiveBlock)(size_t length,
id _Nullable exception);
/**
* @brief A block which is called when a packet has been sent.
*
@@ -44,11 +43,11 @@
* @param data The data which was sent
* @param exception An exception which occurred while reading or `nil` on
* success
* @return The data to repeat the send with or nil if it should not repeat
*/
-typedef OFData *_Nullable (^of_sequenced_packet_socket_async_send_data_block_t)(
+typedef OFData *_Nullable (^OFSequencedPacketSocketAsyncSendDataBlock)(
OFData *_Nonnull data, id _Nullable exception);
/**
* @brief A block which is called when the socket accepted a connection.
*
@@ -56,11 +55,11 @@
* @param exception An exception which occurred while accepting the socket or
* `nil` on success
* @return A bool whether the same block should be used for the next incoming
* connection
*/
-typedef bool (^of_sequenced_packet_socket_async_accept_block_t)(
+typedef bool (^OFSequencedPacketSocketAsyncAcceptBlock)(
OFSequencedPacketSocket *acceptedSocket, id _Nullable exception);
#endif
/**
* @protocol OFSequencedPacketSocketDelegate OFSequencedPacketSocket.h \
@@ -125,13 +124,13 @@
* was called to create one "instance" for every thread!
*/
@interface OFSequencedPacketSocket: OFObject
{
- of_socket_t _socket;
+ OFSocketHandle _socket;
bool _canBlock, _listening;
- of_socket_address_t _remoteAddress;
+ OFSocketAddress _remoteAddress;
id _Nullable _delegate;
OF_RESERVE_IVARS(OFSequencedPacketSocket, 4)
}
/**
@@ -149,11 +148,11 @@
/**
* @brief The remote address.
*
* @note This only works for accepted sockets!
*/
-@property (readonly, nonatomic) const of_socket_address_t *remoteAddress;
+@property (readonly, nonatomic) const OFSocketAddress *remoteAddress;
/**
* @brief The delegate for asynchronous operations on the socket.
*
* @note The delegate is retained for as long as asynchronous operations are
@@ -201,11 +200,11 @@
* @param length The length of the buffer
* @param runLoopMode The run loop mode in which to perform the async receive
*/
- (void)asyncReceiveIntoBuffer: (void *)buffer
length: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode;
+ runLoopMode: (OFRunLoopMode)runLoopMode;
#ifdef OF_HAVE_BLOCKS
/**
* @brief Asynchronously receives a packet and stores it into the specified
* buffer.
@@ -218,15 +217,13 @@
* block returns true, it will be called again with the same
* buffer and maximum length when more packets have been received.
* If you want the next method in the queue to handle the packet
* received next, you need to return false from the method.
*/
-- (void)
- asyncReceiveIntoBuffer: (void *)buffer
- length: (size_t)length
- block: (of_sequenced_packet_socket_async_receive_block_t)
- block;
+- (void)asyncReceiveIntoBuffer: (void *)buffer
+ length: (size_t)length
+ block: (OFSequencedPacketSocketAsyncReceiveBlock)block;
/**
* @brief Asynchronously receives a packet and stores it into the specified
* buffer.
*
@@ -239,16 +236,14 @@
* block returns true, it will be called again with the same
* buffer and maximum length when more packets have been received.
* If you want the next method in the queue to handle the packet
* received next, you need to return false from the method.
*/
-- (void)
- asyncReceiveIntoBuffer: (void *)buffer
- length: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_sequenced_packet_socket_async_receive_block_t)
- block;
+- (void)asyncReceiveIntoBuffer: (void *)buffer
+ length: (size_t)length
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFSequencedPacketSocketAsyncReceiveBlock)block;
#endif
/**
* @brief Sends the specified packet.
*
@@ -268,12 +263,11 @@
* @brief Asynchronously sends the specified packet.
*
* @param data The data to send as a packet
* @param runLoopMode The run loop mode in which to perform the async send
*/
-- (void)asyncSendData: (OFData *)data
- runLoopMode: (of_run_loop_mode_t)runLoopMode;
+- (void)asyncSendData: (OFData *)data runLoopMode: (OFRunLoopMode)runLoopMode;
#ifdef OF_HAVE_BLOCKS
/**
* @brief Asynchronously sends the specified packet.
*
@@ -281,12 +275,11 @@
* @param block The block to call when the packet has been sent. It should
* return the data for the next send with the same callback or nil
* if it should not repeat.
*/
- (void)asyncSendData: (OFData *)data
- block: (of_sequenced_packet_socket_async_send_data_block_t)
- block;
+ block: (OFSequencedPacketSocketAsyncSendDataBlock)block;
/**
* @brief Asynchronously sends the specified packet.
*
* @param data The data to send as a packet
@@ -294,13 +287,12 @@
* @param block The block to call when the packet has been sent. It should
* return the data for the next send with the same callback or nil
* if it should not repeat.
*/
- (void)asyncSendData: (OFData *)data
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_sequenced_packet_socket_async_send_data_block_t)
- block;
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFSequencedPacketSocketAsyncSendDataBlock)block;
#endif
/**
* @brief Listen on the socket.
*
@@ -328,33 +320,33 @@
/**
* @brief Asynchronously accept an incoming connection.
*
* @param runLoopMode The run loop mode in which to perform the async accept
*/
-- (void)asyncAcceptWithRunLoopMode: (of_run_loop_mode_t)runLoopMode;
+- (void)asyncAcceptWithRunLoopMode: (OFRunLoopMode)runLoopMode;
#ifdef OF_HAVE_BLOCKS
/**
* @brief Asynchronously accept an incoming connection.
*
* @param block The block to execute when a new connection has been accepted.
* Returns whether the next incoming connection should be accepted
* by the specified block as well.
*/
-- (void)asyncAcceptWithBlock:
- (of_sequenced_packet_socket_async_accept_block_t)block;
+- (void)asyncAcceptWithBlock: (OFSequencedPacketSocketAsyncAcceptBlock)block;
/**
* @brief Asynchronously accept an incoming connection.
*
* @param runLoopMode The run loop mode in which to perform the async accept
* @param block The block to execute when a new connection has been accepted.
* Returns whether the next incoming connection should be accepted
* by the specified block as well.
*/
-- (void)asyncAcceptWithRunLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_sequenced_packet_socket_async_accept_block_t)block;
+- (void)
+ asyncAcceptWithRunLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFSequencedPacketSocketAsyncAcceptBlock)block;
#endif
/**
* @brief Cancels all pending asynchronous requests on the socket.
*/
Index: src/OFSequencedPacketSocket.m
==================================================================
--- src/OFSequencedPacketSocket.m
+++ src/OFSequencedPacketSocket.m
@@ -30,10 +30,12 @@
#import "OFSequencedPacketSocket.h"
#import "OFSequencedPacketSocket+Private.h"
#import "OFData.h"
#import "OFRunLoop+Private.h"
#import "OFRunLoop.h"
+#import "OFSocket.h"
+#import "OFSocket+Private.h"
#import "OFAcceptFailedException.h"
#import "OFInitializationFailedException.h"
#import "OFInvalidArgumentException.h"
#import "OFListenFailedException.h"
@@ -41,22 +43,19 @@
#import "OFOutOfRangeException.h"
#import "OFReadFailedException.h"
#import "OFSetOptionFailedException.h"
#import "OFWriteFailedException.h"
-#import "socket.h"
-#import "socket_helpers.h"
-
@implementation OFSequencedPacketSocket
@synthesize listening = _listening, delegate = _delegate;
+ (void)initialize
{
if (self != [OFSequencedPacketSocket class])
return;
- if (!of_socket_init())
+ if (!OFSocketInit())
@throw [OFInitializationFailedException
exceptionWithClass: self];
}
+ (instancetype)socket
@@ -72,11 +71,11 @@
if (self.class == [OFSequencedPacketSocket class]) {
[self doesNotRecognizeSelector: _cmd];
abort();
}
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
_canBlock = true;
} @catch (id e) {
[self release];
@throw e;
}
@@ -84,11 +83,11 @@
return self;
}
- (void)dealloc
{
- if (_socket != INVALID_SOCKET)
+ if (_socket != OFInvalidSocketHandle)
[self close];
[super dealloc];
}
@@ -98,11 +97,11 @@
int errNo;
socklen_t len = sizeof(errNo);
if (getsockopt(_socket, SOL_SOCKET, SO_ERROR, (char *)&errNo,
&len) != 0)
- return of_socket_errno();
+ return OFSocketErrNo();
return errNo;
}
#endif
@@ -139,11 +138,11 @@
u_long v = canBlock;
if (ioctlsocket(_socket, FIONBIO, &v) == SOCKET_ERROR)
@throw [OFSetOptionFailedException
exceptionWithObject: self
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
_canBlock = canBlock;
#else
OF_UNRECOGNIZED_SELECTOR
#endif
@@ -151,43 +150,43 @@
- (size_t)receiveIntoBuffer: (void *)buffer length: (size_t)length
{
ssize_t ret;
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
@throw [OFNotOpenException exceptionWithObject: self];
#ifndef OF_WINDOWS
if ((ret = recv(_socket, buffer, length, 0)) < 0)
@throw [OFReadFailedException
exceptionWithObject: self
requestedLength: length
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
#else
if (length > INT_MAX)
@throw [OFOutOfRangeException exception];
if ((ret = recv(_socket, buffer, (int)length, 0)) < 0)
@throw [OFReadFailedException
exceptionWithObject: self
requestedLength: length
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
#endif
return ret;
}
- (void)asyncReceiveIntoBuffer: (void *)buffer length: (size_t)length
{
[self asyncReceiveIntoBuffer: buffer
length: length
- runLoopMode: of_run_loop_mode_default];
+ runLoopMode: OFDefaultRunLoopMode];
}
- (void)asyncReceiveIntoBuffer: (void *)buffer
length: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ runLoopMode: (OFRunLoopMode)runLoopMode
{
[OFRunLoop of_addAsyncReceiveForSequencedPacketSocket: self
buffer: buffer
length: length
mode: runLoopMode
@@ -196,28 +195,25 @@
# endif
delegate: _delegate];
}
#ifdef OF_HAVE_BLOCKS
-- (void)
- asyncReceiveIntoBuffer: (void *)buffer
- length: (size_t)length
- block: (of_sequenced_packet_socket_async_receive_block_t)
- block
+- (void)asyncReceiveIntoBuffer: (void *)buffer
+ length: (size_t)length
+ block: (OFSequencedPacketSocketAsyncReceiveBlock)block
{
[self asyncReceiveIntoBuffer: buffer
length: length
- runLoopMode: of_run_loop_mode_default
+ runLoopMode: OFDefaultRunLoopMode
block: block];
}
- (void)
asyncReceiveIntoBuffer: (void *)buffer
length: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_sequenced_packet_socket_async_receive_block_t)
- block
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFSequencedPacketSocketAsyncReceiveBlock)block
{
[OFRunLoop of_addAsyncReceiveForSequencedPacketSocket: self
buffer: buffer
length: length
mode: runLoopMode
@@ -226,11 +222,11 @@
}
#endif
- (void)sendBuffer: (const void *)buffer length: (size_t)length
{
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
@throw [OFNotOpenException exceptionWithObject: self];
#ifndef OF_WINDOWS
ssize_t bytesWritten;
@@ -240,11 +236,11 @@
if ((bytesWritten = send(_socket, (void *)buffer, length, 0)) < 0)
@throw [OFWriteFailedException
exceptionWithObject: self
requestedLength: length
bytesWritten: 0
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
#else
int bytesWritten;
if (length > INT_MAX)
@throw [OFOutOfRangeException exception];
@@ -252,11 +248,11 @@
if ((bytesWritten = send(_socket, buffer, (int)length, 0)) < 0)
@throw [OFWriteFailedException
exceptionWithObject: self
requestedLength: length
bytesWritten: 0
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
#endif
if ((size_t)bytesWritten != length)
@throw [OFWriteFailedException exceptionWithObject: self
requestedLength: length
@@ -264,15 +260,14 @@
errNo: 0];
}
- (void)asyncSendData: (OFData *)data
{
- [self asyncSendData: data runLoopMode: of_run_loop_mode_default];
+ [self asyncSendData: data runLoopMode: OFDefaultRunLoopMode];
}
-- (void)asyncSendData: (OFData *)data
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+- (void)asyncSendData: (OFData *)data runLoopMode: (OFRunLoopMode)runLoopMode
{
[OFRunLoop of_addAsyncSendForSequencedPacketSocket: self
data: data
mode: runLoopMode
# ifdef OF_HAVE_BLOCKS
@@ -281,20 +276,20 @@
delegate: _delegate];
}
#ifdef OF_HAVE_BLOCKS
- (void)asyncSendData: (OFData *)data
- block: (of_sequenced_packet_socket_async_send_data_block_t)block
+ block: (OFSequencedPacketSocketAsyncSendDataBlock)block
{
[self asyncSendData: data
- runLoopMode: of_run_loop_mode_default
+ runLoopMode: OFDefaultRunLoopMode
block: block];
}
- (void)asyncSendData: (OFData *)data
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_sequenced_packet_socket_async_send_data_block_t)block
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFSequencedPacketSocketAsyncSendDataBlock)block
{
[OFRunLoop of_addAsyncSendForSequencedPacketSocket: self
data: data
mode: runLoopMode
block: block
@@ -307,18 +302,18 @@
[self listenWithBacklog: SOMAXCONN];
}
- (void)listenWithBacklog: (int)backlog
{
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
@throw [OFNotOpenException exceptionWithObject: self];
if (listen(_socket, backlog) == -1)
@throw [OFListenFailedException
exceptionWithSocket: self
backlog: backlog
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
_listening = true;
}
- (instancetype)accept
@@ -336,28 +331,29 @@
#if defined(HAVE_PACCEPT) && defined(SOCK_CLOEXEC)
if ((client->_socket = paccept(_socket,
&client->_remoteAddress.sockaddr.sockaddr,
&client->_remoteAddress.length, NULL, SOCK_CLOEXEC)) ==
- INVALID_SOCKET)
+ OFInvalidSocketHandle)
@throw [OFAcceptFailedException
exceptionWithSocket: self
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
#elif defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
if ((client->_socket = accept4(_socket,
&client->_remoteAddress.sockaddr.sockaddr,
- &client->_remoteAddress.length, SOCK_CLOEXEC)) == INVALID_SOCKET)
+ &client->_remoteAddress.length, SOCK_CLOEXEC)) ==
+ OFInvalidSocketHandle)
@throw [OFAcceptFailedException
exceptionWithSocket: self
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
#else
if ((client->_socket = accept(_socket,
&client->_remoteAddress.sockaddr.sockaddr,
- &client->_remoteAddress.length)) == INVALID_SOCKET)
+ &client->_remoteAddress.length)) == OFInvalidSocketHandle)
@throw [OFAcceptFailedException
exceptionWithSocket: self
- errNo: of_socket_errno()];
+ errNo: OFSocketErrNo()];
# if defined(HAVE_FCNTL) && defined(FD_CLOEXEC)
if ((flags = fcntl(client->_socket, F_GETFD, 0)) != -1)
fcntl(client->_socket, F_SETFD, flags | FD_CLOEXEC);
# endif
@@ -366,65 +362,63 @@
assert(client->_remoteAddress.length <=
(socklen_t)sizeof(client->_remoteAddress.sockaddr));
switch (client->_remoteAddress.sockaddr.sockaddr.sa_family) {
case AF_INET:
- client->_remoteAddress.family = OF_SOCKET_ADDRESS_FAMILY_IPV4;
+ client->_remoteAddress.family = OFSocketAddressFamilyIPv4;
break;
#ifdef OF_HAVE_IPV6
case AF_INET6:
- client->_remoteAddress.family = OF_SOCKET_ADDRESS_FAMILY_IPV6;
+ client->_remoteAddress.family = OFSocketAddressFamilyIPv6;
break;
#endif
#ifdef OF_HAVE_IPX
case AF_IPX:
- client->_remoteAddress.family = OF_SOCKET_ADDRESS_FAMILY_IPX;
+ client->_remoteAddress.family = OFSocketAddressFamilyIPX;
break;
#endif
default:
- client->_remoteAddress.family =
- OF_SOCKET_ADDRESS_FAMILY_UNKNOWN;
+ client->_remoteAddress.family = OFSocketAddressFamilyUnknown;
break;
}
return client;
}
- (void)asyncAccept
{
- [self asyncAcceptWithRunLoopMode: of_run_loop_mode_default];
+ [self asyncAcceptWithRunLoopMode: OFDefaultRunLoopMode];
}
-- (void)asyncAcceptWithRunLoopMode: (of_run_loop_mode_t)runLoopMode
+- (void)asyncAcceptWithRunLoopMode: (OFRunLoopMode)runLoopMode
{
[OFRunLoop of_addAsyncAcceptForSocket: self
mode: runLoopMode
block: NULL
delegate: _delegate];
}
#ifdef OF_HAVE_BLOCKS
-- (void)asyncAcceptWithBlock: (of_sequenced_packet_socket_async_accept_block_t)
- block
+- (void)asyncAcceptWithBlock: (OFSequencedPacketSocketAsyncAcceptBlock)block
{
- [self asyncAcceptWithRunLoopMode: of_run_loop_mode_default
- block: block];
+ [self asyncAcceptWithRunLoopMode: OFDefaultRunLoopMode block: block];
}
-- (void)asyncAcceptWithRunLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_sequenced_packet_socket_async_accept_block_t)block
+- (void)
+ asyncAcceptWithRunLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFSequencedPacketSocketAsyncAcceptBlock)block
{
[OFRunLoop of_addAsyncAcceptForSocket: self
mode: runLoopMode
block: block
delegate: nil];
}
#endif
-- (const of_socket_address_t *)remoteAddress
+- (const OFSocketAddress *)remoteAddress
{
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
@throw [OFNotOpenException exceptionWithObject: self];
if (_remoteAddress.length == 0)
@throw [OFInvalidArgumentException exception];
@@ -435,19 +429,19 @@
}
- (void)cancelAsyncRequests
{
[OFRunLoop of_cancelAsyncRequestsForObject: self
- mode: of_run_loop_mode_default];
+ mode: OFDefaultRunLoopMode];
}
- (int)fileDescriptorForReading
{
#ifndef OF_WINDOWS
return _socket;
#else
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
return -1;
if (_socket > INT_MAX)
@throw [OFOutOfRangeException exception];
@@ -458,11 +452,11 @@
- (int)fileDescriptorForWriting
{
#ifndef OF_WINDOWS
return _socket;
#else
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
return -1;
if (_socket > INT_MAX)
@throw [OFOutOfRangeException exception];
@@ -470,15 +464,15 @@
#endif
}
- (void)close
{
- if (_socket == INVALID_SOCKET)
+ if (_socket == OFInvalidSocketHandle)
@throw [OFNotOpenException exceptionWithObject: self];
_listening = false;
memset(&_remoteAddress, 0, sizeof(_remoteAddress));
closesocket(_socket);
- _socket = INVALID_SOCKET;
+ _socket = OFInvalidSocketHandle;
}
@end
Index: src/OFSerialization.h
==================================================================
--- src/OFSerialization.h
+++ src/OFSerialization.h
@@ -15,12 +15,10 @@
#import "OFObject.h"
OF_ASSUME_NONNULL_BEGIN
-#define OF_SERIALIZATION_NS @"https://objfw.nil.im/serialization"
-
@class OFXMLElement;
/**
* @protocol OFSerialization OFSerialization.h ObjFW/OFSerialization.h
*
@@ -38,7 +36,15 @@
* @param element An OFXMLElement with the serialized object
* @return An initialized object
*/
- (instancetype)initWithSerialization: (OFXMLElement *)element;
@end
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern OFString *const OFSerializationNS;
+#ifdef __cplusplus
+}
+#endif
OF_ASSUME_NONNULL_END
ADDED src/OFSerialization.m
Index: src/OFSerialization.m
==================================================================
--- src/OFSerialization.m
+++ src/OFSerialization.m
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#import "OFSerialization.h"
+#import "OFString.h"
+
+OFString *const OFSerializationNS = @"https://objfw.nil.im/serialization";
Index: src/OFSet.h
==================================================================
--- src/OFSet.h
+++ src/OFSet.h
@@ -38,19 +38,19 @@
*
* @param object The current object
* @param stop A pointer to a variable that can be set to true to stop the
* enumeration
*/
-typedef void (^of_set_enumeration_block_t)(id object, bool *stop);
+typedef void (^OFSetEnumerationBlock)(id object, bool *stop);
/**
* @brief A block for filtering an OFSet.
*
* @param object The object to inspect
* @return Whether the object should be in the filtered set
*/
-typedef bool (^of_set_filter_block_t)(id object);
+typedef bool (^OFSetFilterBlock)(id object);
#endif
/**
* @class OFSet OFSet.h ObjFW/OFSet.h
*
@@ -252,25 +252,25 @@
/**
* @brief Executes a block for each object in the set.
*
* @param block The block to execute for each object in the set
*/
-- (void)enumerateObjectsUsingBlock: (of_set_enumeration_block_t)block;
+- (void)enumerateObjectsUsingBlock: (OFSetEnumerationBlock)block;
/**
* @brief Creates a new set, only containing the objects for which the block
* returns true.
*
* @param block A block which determines if the object should be in the new set
* @return A new, autoreleased OFSet
*/
-- (OFSet OF_GENERIC(ObjectType) *)filteredSetUsingBlock:
- (of_set_filter_block_t)block;
+- (OFSet OF_GENERIC(ObjectType) *)
+ filteredSetUsingBlock: (OFSetFilterBlock)block;
#endif
#if !defined(OF_HAVE_GENERICS) && !defined(DOXYGEN)
# undef ObjectType
#endif
@end
OF_ASSUME_NONNULL_END
#import "OFMutableSet.h"
Index: src/OFSet.m
==================================================================
--- src/OFSet.m
+++ src/OFSet.m
@@ -239,11 +239,11 @@
- (OFEnumerator *)objectEnumerator
{
OF_UNRECOGNIZED_SELECTOR
}
-- (int)countByEnumeratingWithState: (of_fast_enumeration_state_t *)state
+- (int)countByEnumeratingWithState: (OFFastEnumerationState *)state
objects: (id *)objects
count: (int)count
{
OFEnumerator *enumerator;
int i;
@@ -367,14 +367,14 @@
void *pool = objc_autoreleasePoolPush();
OFXMLElement *element;
if ([self isKindOfClass: [OFMutableSet class]])
element = [OFXMLElement elementWithName: @"OFMutableSet"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
else
element = [OFXMLElement elementWithName: @"OFSet"
- namespace: OF_SERIALIZATION_NS];
+ namespace: OFSerializationNS];
for (id object in self) {
void *pool2 = objc_autoreleasePoolPush();
[element addChild: object.XMLElementBySerializing];
objc_autoreleasePoolPop(pool2);
@@ -426,11 +426,11 @@
objc_autoreleasePoolPop(pool);
return [ret autorelease];
}
#ifdef OF_HAVE_BLOCKS
-- (void)enumerateObjectsUsingBlock: (of_set_enumeration_block_t)block
+- (void)enumerateObjectsUsingBlock: (OFSetEnumerationBlock)block
{
bool stop = false;
for (id object in self) {
block(object, &stop);
@@ -438,11 +438,11 @@
if (stop)
break;
}
}
-- (OFSet *)filteredSetUsingBlock: (of_set_filter_block_t)block
+- (OFSet *)filteredSetUsingBlock: (OFSetFilterBlock)block
{
OFMutableSet *ret = [OFMutableSet set];
[self enumerateObjectsUsingBlock: ^ (id object, bool *stop) {
if (block(object))
ADDED src/OFSizeValue.h
Index: src/OFSizeValue.h
==================================================================
--- src/OFSizeValue.h
+++ src/OFSizeValue.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#import "OFValue.h"
+
+OF_ASSUME_NONNULL_BEGIN
+
+@interface OFSizeValue: OFValue
+{
+ OFSize _size;
+}
+
+- (instancetype)initWithSize: (OFSize)size;
+@end
+
+OF_ASSUME_NONNULL_END
ADDED src/OFSizeValue.m
Index: src/OFSizeValue.m
==================================================================
--- src/OFSizeValue.m
+++ src/OFSizeValue.m
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#import "OFSizeValue.h"
+#import "OFMethodSignature.h"
+#import "OFString.h"
+
+#import "OFOutOfRangeException.h"
+
+@implementation OFSizeValue
+@synthesize sizeValue = _size;
+
+- (instancetype)initWithSize: (OFSize)size
+{
+ self = [super init];
+
+ _size = size;
+
+ return self;
+}
+
+- (const char *)objCType
+{
+ return @encode(OFSize);
+}
+
+- (void)getValue: (void *)value size: (size_t)size
+{
+ if (size != sizeof(_size))
+ @throw [OFOutOfRangeException exception];
+
+ memcpy(value, &_size, sizeof(_size));
+}
+
+- (OFString *)description
+{
+ return [OFString stringWithFormat:
+ @"", _size.width, _size.height];
+}
+@end
ADDED src/OFSocket+Private.h
Index: src/OFSocket+Private.h
==================================================================
--- src/OFSocket+Private.h
+++ src/OFSocket+Private.h
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#include "unistd_wrapper.h"
+
+#ifdef HAVE_ARPA_INET_H
+# include
+#endif
+#ifdef HAVE_NETDB_H
+# include
+#endif
+
+#include "OFSocket.h"
+
+#ifndef INADDR_NONE
+# define INADDR_NONE ((in_addr_t)-1)
+#endif
+
+#ifndef SOMAXCONN
+/*
+ * Use 16 as everything > 17 fails on Nintendo 3DS and 16 is a less arbitrary
+ * number than 17.
+ */
+# define SOMAXCONN 16
+#endif
+
+#ifndef SOCK_CLOEXEC
+# define SOCK_CLOEXEC 0
+#endif
+
+#if defined(OF_AMIGAOS)
+# ifdef OF_MORPHOS
+# include
+# else
+# include
+# endif
+# include
+# define closesocket(sock) CloseSocket(sock)
+# define ioctlsocket(fd, req, arg) IoctlSocket(fd, req, arg)
+# define hstrerror(err) "unknown (no hstrerror)"
+# define SOCKET_ERROR -1
+# if defined(OF_HAVE_THREADS) && !defined(OF_MORPHOS)
+# define SocketBase ((struct Library *)OFTLSKeyGet(OFSocketBaseKey))
+# ifdef OF_AMIGAOS4
+# define ISocket ((struct SocketIFace *)OFTLSKeyGet(OFSocketInterfaceKey))
+# endif
+# endif
+# ifdef OF_MORPHOS
+typedef uint32_t in_addr_t;
+# endif
+#elif !defined(OF_WINDOWS) && !defined(OF_WII)
+# define closesocket(sock) close(sock)
+#endif
+
+#ifdef OF_WII
+# define accept(sock, addr, addrlen) net_accept(sock, addr, addrlen)
+# define bind(sock, addr, addrlen) net_bind(sock, addr, addrlen)
+# define closesocket(sock) net_close(sock)
+# define connect(sock, addr, addrlen) \
+ net_connect(sock, (struct sockaddr *)addr, addrlen)
+# define fcntl(fd, cmd, flags) net_fcntl(fd, cmd, flags)
+# define h_errno 0
+# define hstrerror(err) "unknown (no hstrerror)"
+# define listen(sock, backlog) net_listen(sock, backlog)
+# define poll(fds, nfds, timeout) net_poll(fds, nfds, timeout)
+# define recv(sock, buf, len, flags) net_recv(sock, buf, len, flags)
+# define recvfrom(sock, buf, len, flags, addr, addrlen) \
+ net_recvfrom(sock, buf, len, flags, addr, addrlen)
+# define select(nfds, readfds, writefds, errorfds, timeout) \
+ net_select(nfds, readfds, writefds, errorfds, timeout)
+# define send(sock, buf, len, flags) net_send(sock, buf, len, flags)
+# define sendto(sock, buf, len, flags, addr, addrlen) \
+ net_sendto(sock, buf, len, flags, (struct sockaddr *)(addr), addrlen)
+# define setsockopt(sock, level, name, value, len) \
+ net_setsockopt(sock, level, name, value, len)
+# define socket(domain, type, proto) net_socket(domain, type, proto)
+typedef u32 in_addr_t;
+typedef u32 nfds_t;
+#endif
ADDED src/OFSocket.h
Index: src/OFSocket.h
==================================================================
--- src/OFSocket.h
+++ src/OFSocket.h
@@ -0,0 +1,296 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "objfw-defs.h"
+
+#ifndef OF_HAVE_SOCKETS
+# error No sockets available!
+#endif
+
+#include
+
+#import "OFString.h"
+#if defined(OF_HAVE_THREADS) && defined(OF_AMIGAOS)
+# import "OFTLSKey.h"
+#endif
+
+#ifdef OF_HAVE_SYS_SOCKET_H
+# include
+#endif
+#ifdef OF_HAVE_NETINET_IN_H
+# include
+#endif
+#ifdef OF_HAVE_NETINET_TCP_H
+# include
+#endif
+#ifdef OF_HAVE_NETIPX_IPX_H
+# include
+#endif
+
+#ifdef OF_WINDOWS
+# include
+# include
+# ifdef OF_HAVE_IPX
+# include
+# endif
+#endif
+
+/** @file */
+
+#ifdef OF_WII
+# include
+#endif
+
+#ifdef OF_PSP
+# include
+#endif
+
+#import "macros.h"
+
+OF_ASSUME_NONNULL_BEGIN
+
+#ifndef OF_WINDOWS
+typedef int OFSocketHandle;
+static const OFSocketHandle OFInvalidSocketHandle = -1;
+#else
+typedef SOCKET OFSocketHandle;
+static const OFSocketHandle OFInvalidSocketHandle = INVALID_SOCKET;
+#endif
+
+#ifdef OF_WII
+typedef u8 sa_family_t;
+#endif
+
+#ifdef OF_MORPHOS
+typedef long socklen_t;
+typedef u_char sa_family_t;
+typedef u_short in_port_t;
+#endif
+
+/**
+ * @brief A socket address family.
+ */
+typedef enum {
+ /** An unknown address family. */
+ OFSocketAddressFamilyUnknown,
+ /** IPv4 */
+ OFSocketAddressFamilyIPv4,
+ /** IPv6 */
+ OFSocketAddressFamilyIPv6,
+ /** IPX */
+ OFSocketAddressFamilyIPX,
+ /** Any address family */
+ OFSocketAddressFamilyAny = 255
+} OFSocketAddressFamily;
+
+#ifndef OF_HAVE_IPV6
+struct sockaddr_in6 {
+ sa_family_t sin6_family;
+ in_port_t sin6_port;
+ uint32_t sin6_flowinfo;
+ struct in6_addr {
+ uint8_t s6_addr[16];
+ } sin6_addr;
+ uint32_t sin6_scope_id;
+};
+#endif
+
+#ifndef OF_HAVE_IPX
+# define IPX_NODE_LEN 6
+struct sockaddr_ipx {
+ sa_family_t sipx_family;
+ uint32_t sipx_network;
+ unsigned char sipx_node[IPX_NODE_LEN];
+ uint16_t sipx_port;
+ uint8_t sipx_type;
+};
+#endif
+#ifdef OF_WINDOWS
+# define IPX_NODE_LEN 6
+# define sipx_family sa_family
+# define sipx_network sa_netnum
+# define sipx_node sa_nodenum
+# define sipx_port sa_socket
+#endif
+
+/**
+ * @struct OFSocketAddress OFSocket.h ObjFW/OFSocket.h
+ *
+ * @brief A struct which represents a host / port pair for a socket.
+ */
+typedef struct OF_BOXABLE {
+ /*
+ * Even though struct sockaddr contains the family, we need to use our
+ * own family, as we need to support storing an IPv6 address on systems
+ * that don't support IPv6. These may not have AF_INET6 defined and we
+ * can't just define it, as the value is system-dependent and might
+ * clash with an existing value.
+ */
+ OFSocketAddressFamily family;
+ union {
+ struct sockaddr sockaddr;
+ struct sockaddr_in in;
+ struct sockaddr_in6 in6;
+ struct sockaddr_ipx ipx;
+ } sockaddr;
+ socklen_t length;
+} OFSocketAddress;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+/**
+ * @brief Parses the specified IP (either v4 or v6) and port into an
+ * @ref OFSocketAddress.
+ *
+ * @param IP The IP to parse
+ * @param port The port to use
+ * @return The parsed IP and port as an OFSocketAddress
+ */
+extern OFSocketAddress OFSocketAddressParseIP(OFString *IP, uint16_t port);
+
+/**
+ * @brief Parses the specified IPv4 and port into an @ref OFSocketAddress.
+ *
+ * @param IP The IPv4 to parse
+ * @param port The port to use
+ * @return The parsed IPv4 and port as an OFSocketAddress
+ */
+extern OFSocketAddress OFSocketAddressParseIPv4(OFString *IP, uint16_t port);
+
+/**
+ * @brief Parses the specified IPv6 and port into an @ref OFSocketAddress.
+ *
+ * @param IP The IPv6 to parse
+ * @param port The port to use
+ * @return The parsed IPv6 and port as an OFSocketAddress
+ */
+extern OFSocketAddress OFSocketAddressParseIPv6(OFString *IP, uint16_t port);
+
+/**
+ * @brief Creates an IPX address for the specified network, node and port.
+ *
+ * @param node The node in the IPX network
+ * @param network The IPX network
+ * @param port The IPX port (sometimes called socket number) on the node
+ */
+extern OFSocketAddress OFSocketAddressMakeIPX(
+ const unsigned char node[_Nonnull IPX_NODE_LEN], uint32_t network,
+ uint16_t port);
+
+/**
+ * @brief Compares two OFSocketAddress for equality.
+ *
+ * @param address1 The address to compare with the second address
+ * @param address2 The second address
+ * @return Whether the two addresses are equal
+ */
+extern bool OFSocketAddressEqual(const OFSocketAddress *_Nonnull address1,
+ const OFSocketAddress *_Nonnull address2);
+
+/**
+ * @brief Returns the hash for the specified @ref OFSocketAddress.
+ *
+ * @param address The address to hash
+ * @return The hash for the specified OFSocketAddress
+ */
+extern unsigned long OFSocketAddressHash(
+ const OFSocketAddress *_Nonnull address);
+
+/**
+ * @brief Converts the specified @ref OFSocketAddress to a string.
+ *
+ * @param address The address to convert to a string
+ * @return The address as an IP string
+ */
+extern OFString *_Nonnull OFSocketAddressString(
+ const OFSocketAddress *_Nonnull address);
+
+/**
+ * @brief Sets the port of the specified @ref OFSocketAddress, independent of
+ * the address family used.
+ *
+ * @param address The address on which to set the port
+ * @param port The port to set on the address
+ */
+extern void OFSocketAddressSetPort(OFSocketAddress *_Nonnull address,
+ uint16_t port);
+
+/**
+ * @brief Returns the port of the specified @ref OFSocketAddress, independent of
+ * the address family used.
+ *
+ * @param address The address on which to get the port
+ * @return The port of the address
+ */
+extern uint16_t OFSocketAddressPort(const OFSocketAddress *_Nonnull address);
+
+/**
+ * @brief Sets the IPX network of the specified @ref OFSocketAddress.
+ *
+ * @param address The address on which to set the IPX network
+ * @param network The IPX network to set on the address
+ */
+extern void OFSocketAddressSetIPXNetwork(OFSocketAddress *_Nonnull address,
+ uint32_t network);
+
+/**
+ * @brief Returns the IPX network of the specified @ref OFSocketAddress.
+ *
+ * @param address The address on which to get the IPX network
+ * @return The IPX network of the address
+ */
+extern uint32_t OFSocketAddressIPXNetwork(
+ const OFSocketAddress *_Nonnull address);
+
+/**
+ * @brief Sets the IPX node of the specified @ref OFSocketAddress.
+ *
+ * @param address The address on which to set the IPX node
+ * @param node The IPX node to set on the address
+ */
+extern void OFSocketAddressSetIPXNode(OFSocketAddress *_Nonnull address,
+ const unsigned char node[_Nonnull IPX_NODE_LEN]);
+
+/**
+ * @brief Gets the IPX node of the specified @ref OFSocketAddress.
+ *
+ * @param address The address on which to get the IPX node
+ * @param node A byte array to store the IPX node of the address
+ */
+extern void OFSocketAddressIPXNode(const OFSocketAddress *_Nonnull address,
+ unsigned char node[_Nonnull IPX_NODE_LEN]);
+
+extern bool OFSocketInit(void);
+#if defined(OF_HAVE_THREADS) && defined(OF_AMIGAOS) && !defined(OF_MORPHOS)
+extern void OFSocketDeinit(void);
+#endif
+extern int OFSocketErrNo(void);
+#if !defined(OF_WII) && !defined(OF_NINTENDO_3DS)
+extern int OFGetSockName(OFSocketHandle sock, struct sockaddr *restrict addr,
+ socklen_t *restrict addrLen);
+#endif
+
+#if defined(OF_HAVE_THREADS) && defined(OF_AMIGAOS) && !defined(OF_MORPHOS)
+extern OFTLSKey OFSocketBaseKey;
+# ifdef OF_AMIGAOS4
+extern OFTLSKey OFSocketInterfaceKey;
+# endif
+#endif
+#ifdef __cplusplus
+}
+#endif
+
+OF_ASSUME_NONNULL_END
ADDED src/OFSocket.m
Index: src/OFSocket.m
==================================================================
--- src/OFSocket.m
+++ src/OFSocket.m
@@ -0,0 +1,849 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#ifndef _XOPEN_SOURCE_EXTENDED
+# define _XOPEN_SOURCE_EXTENDED
+#endif
+#define _HPUX_ALT_XOPEN_SOCKET_API
+
+#ifdef OF_NINTENDO_3DS
+# include /* For memalign() */
+#endif
+
+#include
+
+#import "OFArray.h"
+#import "OFCharacterSet.h"
+#import "OFLocale.h"
+#ifdef OF_HAVE_THREADS
+# import "OFMutex.h"
+#endif
+#import "OFOnce.h"
+#import "OFSocket.h"
+#import "OFSocket+Private.h"
+#import "OFString.h"
+#ifdef OF_HAVE_THREADS
+# import "OFTLSKey.h"
+#endif
+
+#import "OFException.h" /* For some E* -> WSAE* defines */
+#import "OFInitializationFailedException.h"
+#import "OFInvalidArgumentException.h"
+#import "OFInvalidFormatException.h"
+#import "OFLockFailedException.h"
+#import "OFUnlockFailedException.h"
+
+#ifdef OF_AMIGAOS
+# include
+#endif
+
+#ifdef OF_NINTENDO_3DS
+# include <3ds/types.h>
+# include <3ds/services/soc.h>
+#endif
+
+#if defined(OF_HAVE_THREADS) && (!defined(OF_AMIGAOS) || defined(OF_MORPHOS))
+static OFMutex *mutex;
+
+static void
+releaseMutex(void)
+{
+ [mutex release];
+}
+#endif
+#if !defined(OF_AMIGAOS) || defined(OF_MORPHOS) || !defined(OF_HAVE_THREADS)
+static bool initSuccessful = false;
+#endif
+
+#ifdef OF_AMIGAOS
+# if defined(OF_HAVE_THREADS) && !defined(OF_MORPHOS)
+OFTLSKey OFSocketBaseKey;
+# ifdef OF_AMIGAOS4
+OFTLSKey OFSocketInterfaceKey;
+# endif
+# else
+struct Library *SocketBase;
+# ifdef OF_AMIGAOS4
+struct SocketIFace *ISocket = NULL;
+# endif
+# endif
+#endif
+
+#if defined(OF_HAVE_THREADS) && defined(OF_AMIGAOS) && !defined(OF_MORPHOS)
+OF_CONSTRUCTOR()
+{
+ if (OFTLSKeyNew(&OFSocketBaseKey) != 0)
+ @throw [OFInitializationFailedException exception];
+
+# ifdef OF_AMIGAOS4
+ if (OFTLSKeyNew(&OFSocketInterfaceKey) != 0)
+ @throw [OFInitializationFailedException exception];
+# endif
+}
+#endif
+
+#if !defined(OF_AMIGAOS) || defined(OF_MORPHOS) || !defined(OF_HAVE_THREADS)
+static void
+init(void)
+{
+# if defined(OF_WINDOWS)
+ WSADATA wsa;
+
+ if (WSAStartup(MAKEWORD(2, 0), &wsa))
+ return;
+# elif defined(OF_AMIGAOS)
+ if ((SocketBase = OpenLibrary("bsdsocket.library", 4)) == NULL)
+ return;
+
+# ifdef OF_AMIGAOS4
+ if ((ISocket = (struct SocketIFace *)
+ GetInterface(SocketBase, "main", 1, NULL)) == NULL) {
+ CloseLibrary(SocketBase);
+ return;
+ }
+# endif
+# elif defined(OF_WII)
+ if (net_init() < 0)
+ return;
+# elif defined(OF_NINTENDO_3DS)
+ void *ctx;
+
+ if ((ctx = memalign(0x1000, 0x100000)) == NULL)
+ return;
+
+ if (socInit(ctx, 0x100000) != 0)
+ return;
+
+ atexit((void (*)(void))socExit);
+# endif
+
+# if defined(OF_HAVE_THREADS) && (!defined(OF_AMIGAOS) || defined(OF_MORPHOS))
+ mutex = [[OFMutex alloc] init];
+ atexit(releaseMutex);
+
+# ifdef OF_WII
+ if (OFSpinlockNew(&spinlock) != 0)
+ return;
+# endif
+# endif
+
+ initSuccessful = true;
+}
+
+OF_DESTRUCTOR()
+{
+# ifdef OF_AMIGAOS
+# ifdef OF_AMIGAOS4
+ if (ISocket != NULL)
+ DropInterface((struct Interface *)ISocket);
+# endif
+
+ if (SocketBase != NULL)
+ CloseLibrary(SocketBase);
+# endif
+}
+#endif
+
+bool
+OFSocketInit(void)
+{
+#if !defined(OF_AMIGAOS) || defined(OF_MORPHOS) || !defined(OF_HAVE_THREADS)
+ static OFOnceControl onceControl = OFOnceControlInitValue;
+ OFOnce(&onceControl, init);
+
+ return initSuccessful;
+#else
+ struct Library *socketBase;
+# ifdef OF_AMIGAOS4
+ struct SocketIFace *socketInterface;
+# endif
+
+# ifdef OF_AMIGAOS4
+ if ((socketInterface = OFTLSKeyGet(OFSocketInterfaceKey)) != NULL)
+# else
+ if ((socketBase = OFTLSKeyGet(OFSocketBaseKey)) != NULL)
+# endif
+ return true;
+
+ if ((socketBase = OpenLibrary("bsdsocket.library", 4)) == NULL)
+ return false;
+
+# ifdef OF_AMIGAOS4
+ if ((socketInterface = (struct SocketIFace *)
+ GetInterface(socketBase, "main", 1, NULL)) == NULL) {
+ CloseLibrary(socketBase);
+ return false;
+ }
+# endif
+
+ if (OFTLSKeySet(OFSocketBaseKey, socketBase) != 0) {
+ CloseLibrary(socketBase);
+# ifdef OF_AMIGAOS4
+ DropInterface((struct Interface *)socketInterface);
+# endif
+ return false;
+ }
+
+# ifdef OF_AMIGAOS4
+ if (OFTLSKeySet(OFSocketInterfaceKey, socketInterface) != 0) {
+ CloseLibrary(socketBase);
+ DropInterface((struct Interface *)socketInterface);
+ return false;
+ }
+# endif
+
+ return true;
+#endif
+}
+
+#if defined(OF_HAVE_THREADS) && defined(OF_AMIGAOS) && !defined(OF_MORPHOS)
+void
+OFSocketDeinit(void)
+{
+ struct Library *socketBase = OFTLSKeyGet(OFSocketBaseKey);
+# ifdef OF_AMIGAOS4
+ struct SocketIFace *socketInterface = OFTLSKeyGet(OFSocketInterfaceKey);
+
+ if (socketInterface != NULL)
+ DropInterface((struct Interface *)socketInterface);
+# endif
+ if (socketBase != NULL)
+ CloseLibrary(socketBase);
+}
+#endif
+
+int
+OFSocketErrNo()
+{
+#if defined(OF_WINDOWS)
+ switch (WSAGetLastError()) {
+ case WSAEACCES:
+ return EACCES;
+ case WSAEADDRINUSE:
+ return EADDRINUSE;
+ case WSAEADDRNOTAVAIL:
+ return EADDRNOTAVAIL;
+ case WSAEAFNOSUPPORT:
+ return EAFNOSUPPORT;
+ case WSAEALREADY:
+ return EALREADY;
+ case WSAEBADF:
+ return EBADF;
+ case WSAECONNABORTED:
+ return ECONNABORTED;
+ case WSAECONNREFUSED:
+ return ECONNREFUSED;
+ case WSAECONNRESET:
+ return ECONNRESET;
+ case WSAEDESTADDRREQ:
+ return EDESTADDRREQ;
+ case WSAEDISCON:
+ return EPIPE;
+ case WSAEDQUOT:
+ return EDQUOT;
+ case WSAEFAULT:
+ return EFAULT;
+ case WSAEHOSTDOWN:
+ return EHOSTDOWN;
+ case WSAEHOSTUNREACH:
+ return EHOSTUNREACH;
+ case WSAEINPROGRESS:
+ return EINPROGRESS;
+ case WSAEINTR:
+ return EINTR;
+ case WSAEINVAL:
+ return EINVAL;
+ case WSAEISCONN:
+ return EISCONN;
+ case WSAELOOP:
+ return ELOOP;
+ case WSAEMSGSIZE:
+ return EMSGSIZE;
+ case WSAENAMETOOLONG:
+ return ENAMETOOLONG;
+ case WSAENETDOWN:
+ return ENETDOWN;
+ case WSAENETRESET:
+ return ENETRESET;
+ case WSAENETUNREACH:
+ return ENETUNREACH;
+ case WSAENOBUFS:
+ return ENOBUFS;
+ case WSAENOPROTOOPT:
+ return ENOPROTOOPT;
+ case WSAENOTCONN:
+ return ENOTCONN;
+ case WSAENOTEMPTY:
+ return ENOTEMPTY;
+ case WSAENOTSOCK:
+ return ENOTSOCK;
+ case WSAEOPNOTSUPP:
+ return EOPNOTSUPP;
+ case WSAEPFNOSUPPORT:
+ return EPFNOSUPPORT;
+ case WSAEPROCLIM:
+ return EPROCLIM;
+ case WSAEPROTONOSUPPORT:
+ return EPROTONOSUPPORT;
+ case WSAEPROTOTYPE:
+ return EPROTOTYPE;
+ case WSAEREMOTE:
+ return EREMOTE;
+ case WSAESHUTDOWN:
+ return ESHUTDOWN;
+ case WSAESOCKTNOSUPPORT:
+ return ESOCKTNOSUPPORT;
+ case WSAESTALE:
+ return ESTALE;
+ case WSAETIMEDOUT:
+ return ETIMEDOUT;
+ case WSAETOOMANYREFS:
+ return ETOOMANYREFS;
+ case WSAEUSERS:
+ return EUSERS;
+ case WSAEWOULDBLOCK:
+ return EWOULDBLOCK;
+ }
+
+ return 0;
+#elif defined(OF_AMIGAOS)
+ return Errno();
+#else
+ return errno;
+#endif
+}
+
+#ifndef OF_WII
+int
+OFGetSockName(OFSocketHandle sock, struct sockaddr *restrict addr,
+ socklen_t *restrict addrLen)
+{
+ int ret;
+
+# if defined(OF_HAVE_THREADS) && (!defined(OF_AMIGAOS) || defined(OF_MORPHOS))
+ [mutex lock];
+# endif
+ ret = getsockname(sock, addr, addrLen);
+# if defined(OF_HAVE_THREADS) && (!defined(OF_AMIGAOS) || defined(OF_MORPHOS))
+ [mutex unlock];
+# endif
+
+ return ret;
+}
+#endif
+
+OFSocketAddress
+OFSocketAddressParseIPv4(OFString *IPv4, uint16_t port)
+{
+ void *pool = objc_autoreleasePoolPush();
+ OFCharacterSet *whitespaceCharacterSet =
+ [OFCharacterSet whitespaceCharacterSet];
+ OFSocketAddress ret;
+ struct sockaddr_in *addrIn = &ret.sockaddr.in;
+ OFArray OF_GENERIC(OFString *) *components;
+ uint32_t addr;
+
+ memset(&ret, '\0', sizeof(ret));
+ ret.family = OFSocketAddressFamilyIPv4;
+#if defined(OF_WII) || defined(OF_NINTENDO_3DS)
+ ret.length = 8;
+#else
+ ret.length = sizeof(ret.sockaddr.in);
+#endif
+
+ addrIn->sin_family = AF_INET;
+ addrIn->sin_port = OFToBigEndian16(port);
+#ifdef OF_WII
+ addrIn->sin_len = ret.length;
+#endif
+
+ components = [IPv4 componentsSeparatedByString: @"."];
+
+ if (components.count != 4)
+ @throw [OFInvalidFormatException exception];
+
+ addr = 0;
+
+ for (OFString *component in components) {
+ unsigned long long number;
+
+ if (component.length == 0)
+ @throw [OFInvalidFormatException exception];
+
+ if ([component indexOfCharacterFromSet:
+ whitespaceCharacterSet] != OFNotFound)
+ @throw [OFInvalidFormatException exception];
+
+ number = component.unsignedLongLongValue;
+
+ if (number > UINT8_MAX)
+ @throw [OFInvalidFormatException exception];
+
+ addr = (addr << 8) | ((uint32_t)number & 0xFF);
+ }
+
+ addrIn->sin_addr.s_addr = OFToBigEndian32(addr);
+
+ objc_autoreleasePoolPop(pool);
+
+ return ret;
+}
+
+static uint16_t
+parseIPv6Component(OFString *component)
+{
+ unsigned long long number;
+
+ if ([component indexOfCharacterFromSet:
+ [OFCharacterSet whitespaceCharacterSet]] != OFNotFound)
+ @throw [OFInvalidFormatException exception];
+
+ number = [component unsignedLongLongValueWithBase: 16];
+
+ if (number > UINT16_MAX)
+ @throw [OFInvalidFormatException exception];
+
+ return (uint16_t)number;
+}
+
+OFSocketAddress
+OFSocketAddressParseIPv6(OFString *IPv6, uint16_t port)
+{
+ void *pool = objc_autoreleasePoolPush();
+ OFSocketAddress ret;
+ struct sockaddr_in6 *addrIn6 = &ret.sockaddr.in6;
+ size_t doubleColon;
+
+ memset(&ret, '\0', sizeof(ret));
+ ret.family = OFSocketAddressFamilyIPv6;
+ ret.length = sizeof(ret.sockaddr.in6);
+
+#ifdef AF_INET6
+ addrIn6->sin6_family = AF_INET6;
+#else
+ addrIn6->sin6_family = AF_UNSPEC;
+#endif
+ addrIn6->sin6_port = OFToBigEndian16(port);
+
+ doubleColon = [IPv6 rangeOfString: @"::"].location;
+
+ if (doubleColon != OFNotFound) {
+ OFString *left = [IPv6 substringToIndex: doubleColon];
+ OFString *right = [IPv6 substringFromIndex: doubleColon + 2];
+ OFArray OF_GENERIC(OFString *) *leftComponents;
+ OFArray OF_GENERIC(OFString *) *rightComponents;
+ size_t i;
+
+ if ([right hasPrefix: @":"] || [right containsString: @"::"])
+ @throw [OFInvalidFormatException exception];
+
+ leftComponents = [left componentsSeparatedByString: @":"];
+ rightComponents = [right componentsSeparatedByString: @":"];
+
+ if (leftComponents.count + rightComponents.count > 7)
+ @throw [OFInvalidFormatException exception];
+
+ i = 0;
+ for (OFString *component in leftComponents) {
+ uint16_t number = parseIPv6Component(component);
+
+ addrIn6->sin6_addr.s6_addr[i++] = number >> 8;
+ addrIn6->sin6_addr.s6_addr[i++] = number;
+ }
+
+ i = 16;
+ for (OFString *component in rightComponents.reversedArray) {
+ uint16_t number = parseIPv6Component(component);
+
+ addrIn6->sin6_addr.s6_addr[--i] = number;
+ addrIn6->sin6_addr.s6_addr[--i] = number >> 8;
+ }
+ } else {
+ OFArray OF_GENERIC(OFString *) *components =
+ [IPv6 componentsSeparatedByString: @":"];
+ size_t i;
+
+ if (components.count != 8)
+ @throw [OFInvalidFormatException exception];
+
+ i = 0;
+ for (OFString *component in components) {
+ uint16_t number;
+
+ if (component.length == 0)
+ @throw [OFInvalidFormatException exception];
+
+ number = parseIPv6Component(component);
+
+ addrIn6->sin6_addr.s6_addr[i++] = number >> 8;
+ addrIn6->sin6_addr.s6_addr[i++] = number;
+ }
+ }
+
+ objc_autoreleasePoolPop(pool);
+
+ return ret;
+}
+
+OFSocketAddress
+OFSocketAddressParseIP(OFString *IP, uint16_t port)
+{
+ OFSocketAddress ret;
+
+ @try {
+ ret = OFSocketAddressParseIPv6(IP, port);
+ } @catch (OFInvalidFormatException *e) {
+ ret = OFSocketAddressParseIPv4(IP, port);
+ }
+
+ return ret;
+}
+
+OFSocketAddress
+OFSocketAddressMakeIPX(const unsigned char node[IPX_NODE_LEN], uint32_t network,
+ uint16_t port)
+{
+ OFSocketAddress ret;
+
+ memset(&ret, '\0', sizeof(ret));
+ ret.family = OFSocketAddressFamilyIPX;
+ ret.length = sizeof(ret.sockaddr.ipx);
+
+#ifdef AF_IPX
+ ret.sockaddr.ipx.sipx_family = AF_IPX;
+#else
+ ret.sockaddr.ipx.sipx_family = AF_UNSPEC;
+#endif
+ memcpy(ret.sockaddr.ipx.sipx_node, node, IPX_NODE_LEN);
+ network = OFToBigEndian32(network);
+ memcpy(&ret.sockaddr.ipx.sipx_network, &network,
+ sizeof(ret.sockaddr.ipx.sipx_network));
+ ret.sockaddr.ipx.sipx_port = OFToBigEndian16(port);
+
+ return ret;
+}
+
+bool
+OFSocketAddressEqual(const OFSocketAddress *address1,
+ const OFSocketAddress *address2)
+{
+ const struct sockaddr_in *addrIn1, *addrIn2;
+ const struct sockaddr_in6 *addrIn6_1, *addrIn6_2;
+ const struct sockaddr_ipx *addrIPX1, *addrIPX2;
+
+ if (address1->family != address2->family)
+ return false;
+
+ switch (address1->family) {
+ case OFSocketAddressFamilyIPv4:
+#if defined(OF_WII) || defined(OF_NINTENDO_3DS)
+ if (address1->length < 8 || address2->length < 8)
+ @throw [OFInvalidArgumentException exception];
+#else
+ if (address1->length < (socklen_t)sizeof(struct sockaddr_in) ||
+ address2->length < (socklen_t)sizeof(struct sockaddr_in))
+ @throw [OFInvalidArgumentException exception];
+#endif
+
+ addrIn1 = &address1->sockaddr.in;
+ addrIn2 = &address2->sockaddr.in;
+
+ if (addrIn1->sin_port != addrIn2->sin_port)
+ return false;
+ if (addrIn1->sin_addr.s_addr != addrIn2->sin_addr.s_addr)
+ return false;
+
+ break;
+ case OFSocketAddressFamilyIPv6:
+ if (address1->length < (socklen_t)sizeof(struct sockaddr_in6) ||
+ address2->length < (socklen_t)sizeof(struct sockaddr_in6))
+ @throw [OFInvalidArgumentException exception];
+
+ addrIn6_1 = &address1->sockaddr.in6;
+ addrIn6_2 = &address2->sockaddr.in6;
+
+ if (addrIn6_1->sin6_port != addrIn6_2->sin6_port)
+ return false;
+ if (memcmp(addrIn6_1->sin6_addr.s6_addr,
+ addrIn6_2->sin6_addr.s6_addr,
+ sizeof(addrIn6_1->sin6_addr.s6_addr)) != 0)
+ return false;
+
+ break;
+ case OFSocketAddressFamilyIPX:
+ if (address1->length < (socklen_t)sizeof(struct sockaddr_ipx) ||
+ address2->length < (socklen_t)sizeof(struct sockaddr_ipx))
+ @throw [OFInvalidArgumentException exception];
+
+ addrIPX1 = &address1->sockaddr.ipx;
+ addrIPX2 = &address2->sockaddr.ipx;
+
+ if (addrIPX1->sipx_port != addrIPX2->sipx_port)
+ return false;
+ if (memcmp(&addrIPX1->sipx_network, &addrIPX2->sipx_network,
+ 4) != 0)
+ return false;
+ if (memcmp(addrIPX1->sipx_node, addrIPX2->sipx_node,
+ IPX_NODE_LEN) != 0)
+ return false;
+
+ break;
+ default:
+ @throw [OFInvalidArgumentException exception];
+ }
+
+ return true;
+}
+
+unsigned long
+OFSocketAddressHash(const OFSocketAddress *address)
+{
+ unsigned long hash;
+
+ OFHashInit(&hash);
+ OFHashAdd(&hash, address->family);
+
+ switch (address->family) {
+ case OFSocketAddressFamilyIPv4:
+#if defined(OF_WII) || defined(OF_NINTENDO_3DS)
+ if (address->length < 8)
+ @throw [OFInvalidArgumentException exception];
+#else
+ if (address->length < (socklen_t)sizeof(struct sockaddr_in))
+ @throw [OFInvalidArgumentException exception];
+#endif
+
+ OFHashAdd(&hash, address->sockaddr.in.sin_port >> 8);
+ OFHashAdd(&hash, address->sockaddr.in.sin_port);
+ OFHashAdd(&hash, address->sockaddr.in.sin_addr.s_addr >> 24);
+ OFHashAdd(&hash, address->sockaddr.in.sin_addr.s_addr >> 16);
+ OFHashAdd(&hash, address->sockaddr.in.sin_addr.s_addr >> 8);
+ OFHashAdd(&hash, address->sockaddr.in.sin_addr.s_addr);
+
+ break;
+ case OFSocketAddressFamilyIPv6:
+ if (address->length < (socklen_t)sizeof(struct sockaddr_in6))
+ @throw [OFInvalidArgumentException exception];
+
+ OFHashAdd(&hash, address->sockaddr.in6.sin6_port >> 8);
+ OFHashAdd(&hash, address->sockaddr.in6.sin6_port);
+
+ for (size_t i = 0;
+ i < sizeof(address->sockaddr.in6.sin6_addr.s6_addr); i++)
+ OFHashAdd(&hash,
+ address->sockaddr.in6.sin6_addr.s6_addr[i]);
+
+ break;
+ case OFSocketAddressFamilyIPX:;
+ unsigned char network[
+ sizeof(address->sockaddr.ipx.sipx_network)];
+
+ if (address->length < (socklen_t)sizeof(struct sockaddr_ipx))
+ @throw [OFInvalidArgumentException exception];
+
+ OFHashAdd(&hash, address->sockaddr.ipx.sipx_port >> 8);
+ OFHashAdd(&hash, address->sockaddr.ipx.sipx_port);
+
+ memcpy(network, &address->sockaddr.ipx.sipx_network,
+ sizeof(network));
+
+ for (size_t i = 0; i < sizeof(network); i++)
+ OFHashAdd(&hash, network[i]);
+
+ for (size_t i = 0; i < IPX_NODE_LEN; i++)
+ OFHashAdd(&hash, address->sockaddr.ipx.sipx_node[i]);
+
+ break;
+ default:
+ @throw [OFInvalidArgumentException exception];
+ }
+
+ OFHashFinalize(&hash);
+
+ return hash;
+}
+
+static OFString *
+IPv4String(const OFSocketAddress *address)
+{
+ const struct sockaddr_in *addrIn = &address->sockaddr.in;
+ uint32_t addr = OFFromBigEndian32(addrIn->sin_addr.s_addr);
+ OFString *string;
+
+ string = [OFString stringWithFormat: @"%u.%u.%u.%u",
+ (addr & 0xFF000000) >> 24, (addr & 0x00FF0000) >> 16,
+ (addr & 0x0000FF00) >> 8, addr & 0x000000FF];
+
+ return string;
+}
+
+static OFString *
+IPv6String(const OFSocketAddress *address)
+{
+ OFMutableString *string = [OFMutableString string];
+ const struct sockaddr_in6 *addrIn6 = &address->sockaddr.in6;
+ int_fast8_t zerosStart = -1, maxZerosStart = -1;
+ uint_fast8_t zerosCount = 0, maxZerosCount = 0;
+ bool first = true;
+
+ for (uint_fast8_t i = 0; i < 16; i += 2) {
+ if (addrIn6->sin6_addr.s6_addr[i] == 0 &&
+ addrIn6->sin6_addr.s6_addr[i + 1] == 0) {
+ if (zerosStart >= 0)
+ zerosCount++;
+ else {
+ zerosStart = i;
+ zerosCount = 1;
+ }
+ } else {
+ if (zerosCount > maxZerosCount) {
+ maxZerosStart = zerosStart;
+ maxZerosCount = zerosCount;
+ }
+
+ zerosStart = -1;
+ }
+ }
+ if (zerosCount > maxZerosCount) {
+ maxZerosStart = zerosStart;
+ maxZerosCount = zerosCount;
+ }
+
+ if (maxZerosCount >= 2) {
+ for (int_fast8_t i = 0; i < maxZerosStart; i += 2) {
+ [string appendFormat:
+ (first ? @"%x" : @":%x"),
+ (addrIn6->sin6_addr.s6_addr[(uint_fast8_t)i] << 8) |
+ addrIn6->sin6_addr.s6_addr[(uint_fast8_t)i + 1]];
+ first = false;
+ }
+
+ [string appendString: @"::"];
+ first = true;
+
+ for (int_fast8_t i = maxZerosStart + (maxZerosCount * 2);
+ i < 16; i += 2) {
+ [string appendFormat:
+ (first ? @"%x" : @":%x"),
+ (addrIn6->sin6_addr.s6_addr[(uint_fast8_t)i] << 8) |
+ addrIn6->sin6_addr.s6_addr[(uint_fast8_t)i + 1]];
+ first = false;
+ }
+ } else {
+ for (uint_fast8_t i = 0; i < 16; i += 2) {
+ [string appendFormat:
+ (first ? @"%x" : @":%x"),
+ (addrIn6->sin6_addr.s6_addr[i] << 8) |
+ addrIn6->sin6_addr.s6_addr[i + 1]];
+ first = false;
+ }
+ }
+
+ [string makeImmutable];
+
+ return string;
+}
+
+OFString *
+OFSocketAddressString(const OFSocketAddress *address)
+{
+ switch (address->family) {
+ case OFSocketAddressFamilyIPv4:
+ return IPv4String(address);
+ case OFSocketAddressFamilyIPv6:
+ return IPv6String(address);
+ default:
+ @throw [OFInvalidArgumentException exception];
+ }
+}
+
+void
+OFSocketAddressSetPort(OFSocketAddress *address, uint16_t port)
+{
+ switch (address->family) {
+ case OFSocketAddressFamilyIPv4:
+ address->sockaddr.in.sin_port = OFToBigEndian16(port);
+ break;
+ case OFSocketAddressFamilyIPv6:
+ address->sockaddr.in6.sin6_port = OFToBigEndian16(port);
+ break;
+ case OFSocketAddressFamilyIPX:
+ address->sockaddr.ipx.sipx_port = OFToBigEndian16(port);
+ break;
+ default:
+ @throw [OFInvalidArgumentException exception];
+ }
+}
+
+uint16_t
+OFSocketAddressPort(const OFSocketAddress *address)
+{
+ switch (address->family) {
+ case OFSocketAddressFamilyIPv4:
+ return OFFromBigEndian16(address->sockaddr.in.sin_port);
+ case OFSocketAddressFamilyIPv6:
+ return OFFromBigEndian16(address->sockaddr.in6.sin6_port);
+ case OFSocketAddressFamilyIPX:
+ return OFFromBigEndian16(address->sockaddr.ipx.sipx_port);
+ default:
+ @throw [OFInvalidArgumentException exception];
+ }
+}
+
+void
+OFSocketAddressSetIPXNetwork(OFSocketAddress *address, uint32_t network)
+{
+ if (address->family != OFSocketAddressFamilyIPX)
+ @throw [OFInvalidArgumentException exception];
+
+ network = OFToBigEndian32(network);
+ memcpy(&address->sockaddr.ipx.sipx_network, &network,
+ sizeof(address->sockaddr.ipx.sipx_network));
+}
+
+uint32_t
+OFSocketAddressIPXNetwork(const OFSocketAddress *address)
+{
+ uint32_t network;
+
+ if (address->family != OFSocketAddressFamilyIPX)
+ @throw [OFInvalidArgumentException exception];
+
+ memcpy(&network, &address->sockaddr.ipx.sipx_network, sizeof(network));
+
+ return OFFromBigEndian32(network);
+}
+
+void
+OFSocketAddressSetIPXNode(OFSocketAddress *address,
+ const unsigned char node[IPX_NODE_LEN])
+{
+ if (address->family != OFSocketAddressFamilyIPX)
+ @throw [OFInvalidArgumentException exception];
+
+ memcpy(address->sockaddr.ipx.sipx_node, node, IPX_NODE_LEN);
+}
+
+void
+OFSocketAddressIPXNode(const OFSocketAddress *address,
+ unsigned char node[IPX_NODE_LEN])
+{
+ if (address->family != OFSocketAddressFamilyIPX)
+ @throw [OFInvalidArgumentException exception];
+
+ memcpy(node, address->sockaddr.ipx.sipx_node, IPX_NODE_LEN);
+}
Index: src/OFSortedList.h
==================================================================
--- src/OFSortedList.h
+++ src/OFSortedList.h
@@ -31,27 +31,25 @@
#endif
{
OF_RESERVE_IVARS(OFSortedList, 4)
}
-- (of_list_object_t *)appendObject: (ObjectType)object OF_UNAVAILABLE;
-- (of_list_object_t *)prependObject: (ObjectType)object OF_UNAVAILABLE;
-- (of_list_object_t *)insertObject: (ObjectType)object
- beforeListObject: (of_list_object_t *)listObject
- OF_UNAVAILABLE;
-- (of_list_object_t *)insertObject: (ObjectType)object
- afterListObject: (of_list_object_t *)listObject
- OF_UNAVAILABLE;
+- (OFListItem)appendObject: (ObjectType)object OF_UNAVAILABLE;
+- (OFListItem)prependObject: (ObjectType)object OF_UNAVAILABLE;
+- (OFListItem)insertObject: (ObjectType)object
+ beforeListItem: (OFListItem)listItem OF_UNAVAILABLE;
+- (OFListItem)insertObject: (ObjectType)object
+ afterListItem: (OFListItem)listItem OF_UNAVAILABLE;
/**
* @brief Inserts the object to the list while keeping the list sorted.
*
* @param object The object to insert
* @return The list object for the object just added
*/
-- (of_list_object_t *)insertObject: (ObjectType )object;
+- (OFListItem)insertObject: (ObjectType )object;
#if !defined(OF_HAVE_GENERICS) && !defined(DOXYGEN)
# undef ObjectType
#endif
@end
OF_ASSUME_NONNULL_END
Index: src/OFSortedList.m
==================================================================
--- src/OFSortedList.m
+++ src/OFSortedList.m
@@ -16,40 +16,39 @@
#include "config.h"
#import "OFSortedList.h"
@implementation OFSortedList
-- (of_list_object_t *)appendObject: (id)object
-{
- OF_UNRECOGNIZED_SELECTOR
-}
-
-- (of_list_object_t *)prependObject: (id)object
-{
- OF_UNRECOGNIZED_SELECTOR
-}
-
-- (of_list_object_t *)insertObject: (id)object
- beforeListObject: (of_list_object_t *)listObject
-{
- OF_UNRECOGNIZED_SELECTOR
-}
-
-- (of_list_object_t *)insertObject: (id)object
- afterListObject: (of_list_object_t *)listObject
-{
- OF_UNRECOGNIZED_SELECTOR
-}
-
-- (of_list_object_t *)insertObject: (id )object
-{
- of_list_object_t *iter;
-
- for (iter = _lastListObject; iter != NULL; iter = iter->previous) {
- if ([object compare: iter->object] != OF_ORDERED_ASCENDING)
- return [super insertObject: object
- afterListObject: iter];
+- (OFListItem)appendObject: (id)object
+{
+ OF_UNRECOGNIZED_SELECTOR
+}
+
+- (OFListItem)prependObject: (id)object
+{
+ OF_UNRECOGNIZED_SELECTOR
+}
+
+- (OFListItem)insertObject: (id)object beforeListItem: (OFListItem)listItem
+{
+ OF_UNRECOGNIZED_SELECTOR
+}
+
+- (OFListItem)insertObject: (id)object afterListItem: (OFListItem)listItem
+{
+ OF_UNRECOGNIZED_SELECTOR
+}
+
+- (OFListItem)insertObject: (id )object
+{
+ OFListItem iter;
+
+ for (iter = _lastListItem; iter != NULL;
+ iter = OFListItemPrevious(iter)) {
+ if ([object compare: OFListItemObject(iter)] !=
+ OFOrderedAscending)
+ return [super insertObject: object afterListItem: iter];
}
return [super prependObject: object];
}
@end
Index: src/OFStdIOStream.h
==================================================================
--- src/OFStdIOStream.h
+++ src/OFStdIOStream.h
@@ -29,11 +29,11 @@
/**
* @class OFStdIOStream OFStdIOStream.h ObjFW/OFStdIOStream.h
*
* @brief A class for providing standard input, output and error as OFStream.
*
- * The global variables @ref of_stdin, @ref of_stdout and @ref of_stderr are
+ * The global variables @ref OFStdIn, @ref OFStdOut and @ref OFStdErr are
* instances of this class and need no initialization.
*/
#ifdef OF_STDIO_STREAM_WIN32_CONSOLE_H
OF_SUBCLASSING_RESTRICTED
#endif
@@ -116,19 +116,19 @@
* @brief Moves the cursor to the specified absolute position. Does nothing if
* there is no underlying terminal.
*
* @param position The position to move the cursor to
*/
-- (void)setCursorPosition: (of_point_t)position;
+- (void)setCursorPosition: (OFPoint)position;
/**
* @brief Moves the cursor to the specified relative position. Does nothing if
* there is no underlying terminal.
*
* @param position The position to move the cursor to
*/
-- (void)setRelativeCursorPosition: (of_point_t)position;
+- (void)setRelativeCursorPosition: (OFPoint)position;
@end
#ifdef __cplusplus
extern "C" {
#endif
@@ -135,29 +135,29 @@
/** @file */
/**
* @brief The standard input as an OFStream.
*/
-extern OFStdIOStream *_Nullable of_stdin;
+extern OFStdIOStream *_Nullable OFStdIn;
/**
* @brief The standard output as an OFStream.
*/
-extern OFStdIOStream *_Nullable of_stdout;
+extern OFStdIOStream *_Nullable OFStdOut;
/**
* @brief The standard error as an OFStream.
*/
-extern OFStdIOStream *_Nullable of_stderr;
+extern OFStdIOStream *_Nullable OFStdErr;
/**
- * @brief Log the specified printf-style format to @ref of_stderr.
+ * @brief Log the specified printf-style format to @ref OFStdErr.
*
* This prefixes the output with the date, timestamp, process name and PID and
* allows `%@` as a printf-style formatted to print objects.
*/
-extern void of_log(OFConstantString *format, ...);
+extern void OFLog(OFConstantString *format, ...);
#ifdef __cplusplus
}
#endif
OF_ASSUME_NONNULL_END
Index: src/OFStdIOStream.m
==================================================================
--- src/OFStdIOStream.m
+++ src/OFStdIOStream.m
@@ -59,25 +59,25 @@
{
[OFWin32ConsoleStdIOStream class];
}
#endif
-OFStdIOStream *of_stdin = nil;
-OFStdIOStream *of_stdout = nil;
-OFStdIOStream *of_stderr = nil;
+OFStdIOStream *OFStdIn = nil;
+OFStdIOStream *OFStdOut = nil;
+OFStdIOStream *OFStdErr = nil;
#ifdef OF_AMIGAOS
OF_DESTRUCTOR()
{
- [of_stdin dealloc];
- [of_stdout dealloc];
- [of_stderr dealloc];
+ [OFStdIn dealloc];
+ [OFStdOut dealloc];
+ [OFStdErr dealloc];
}
#endif
void
-of_log(OFConstantString *format, ...)
+OFLog(OFConstantString *format, ...)
{
void *pool = objc_autoreleasePoolPush();
OFDate *date;
OFString *dateString, *me, *msg;
va_list arguments;
@@ -93,12 +93,12 @@
va_start(arguments, format);
msg = [[[OFString alloc] initWithFormat: format
arguments: arguments] autorelease];
va_end(arguments);
- [of_stderr writeFormat: @"[%@.%03d %@(%d)] %@\n", dateString,
- date.microsecond / 1000, me, getpid(), msg];
+ [OFStdErr writeFormat: @"[%@.%03d %@(%d)] %@\n", dateString,
+ date.microsecond / 1000, me, getpid(), msg];
objc_autoreleasePoolPop(pool);
}
#ifdef HAVE_ISATTY
@@ -151,17 +151,16 @@
# ifndef OF_AMIGAOS
int fd;
if ((fd = fileno(stdin)) >= 0)
- of_stdin = [[OFStdIOStream alloc]
- of_initWithFileDescriptor: fd];
+ OFStdIn = [[OFStdIOStream alloc] of_initWithFileDescriptor: fd];
if ((fd = fileno(stdout)) >= 0)
- of_stdout = [[OFStdIOStream alloc]
+ OFStdOut = [[OFStdIOStream alloc]
of_initWithFileDescriptor: fd];
if ((fd = fileno(stderr)) >= 0)
- of_stderr = [[OFStdIOStream alloc]
+ OFStdErr = [[OFStdIOStream alloc]
of_initWithFileDescriptor: fd];
# else
BPTR input, output, error;
bool inputClosable = false, outputClosable = false,
errorClosable = false;
@@ -183,16 +182,16 @@
if (error == 0) {
error = Open("*", MODE_OLDFILE);
errorClosable = true;
}
- of_stdin = [[OFStdIOStream alloc] of_initWithHandle: input
- closable: inputClosable];
- of_stdout = [[OFStdIOStream alloc] of_initWithHandle: output
- closable: outputClosable];
- of_stderr = [[OFStdIOStream alloc] of_initWithHandle: error
- closable: errorClosable];
+ OFStdIn = [[OFStdIOStream alloc] of_initWithHandle: input
+ closable: inputClosable];
+ OFStdOut = [[OFStdIOStream alloc] of_initWithHandle: output
+ closable: outputClosable];
+ OFStdErr = [[OFStdIOStream alloc] of_initWithHandle: error
+ closable: errorClosable];
# endif
}
#endif
- (instancetype)init
@@ -381,11 +380,11 @@
{
}
- (unsigned int)retainCount
{
- return OF_RETAIN_COUNT_MAX;
+ return OFMaxRetainCount;
}
- (bool)hasTerminal
{
#ifdef HAVE_ISATTY
@@ -491,11 +490,11 @@
[self writeFormat: @"\033[%uG", column + 1];
#endif
}
-- (void)setCursorPosition: (of_point_t)position
+- (void)setCursorPosition: (OFPoint)position
{
if (position.x < 0 || position.y < 0)
@throw [OFInvalidArgumentException exception];
#ifdef HAVE_ISATTY
@@ -505,11 +504,11 @@
[self writeFormat: @"\033[%u;%uH",
(unsigned)position.y + 1, (unsigned)position.x + 1];
#endif
}
-- (void)setRelativeCursorPosition: (of_point_t)position
+- (void)setRelativeCursorPosition: (OFPoint)position
{
#ifdef HAVE_ISATTY
if (!isatty(_fd))
return;
ADDED src/OFStrPTime.h
Index: src/OFStrPTime.h
==================================================================
--- src/OFStrPTime.h
+++ src/OFStrPTime.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#ifndef __STDC_LIMIT_MACROS
+# define __STDC_LIMIT_MACROS
+#endif
+#ifndef __STDC_CONSTANT_MACROS
+# define __STDC_CONSTANT_MACROS
+#endif
+
+#include
+
+#import "macros.h"
+
+OF_ASSUME_NONNULL_BEGIN
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern const char *OFStrPTime(const char *buf, const char *fmt, struct tm *tm,
+ short *tz);
+#ifdef __cplusplus
+}
+#endif
+
+OF_ASSUME_NONNULL_END
ADDED src/OFStrPTime.m
Index: src/OFStrPTime.m
==================================================================
--- src/OFStrPTime.m
+++ src/OFStrPTime.m
@@ -0,0 +1,230 @@
+/*
+ * Copyright (c) 2008-2021 Jonathan Schleifer
+ *
+ * All rights reserved.
+ *
+ * This file is part of ObjFW. It may be distributed under the terms of the
+ * Q Public License 1.0, which can be found in the file LICENSE.QPL included in
+ * the packaging of this file.
+ *
+ * Alternatively, it may be distributed under the terms of the GNU General
+ * Public License, either version 2 or 3, which can be found in the file
+ * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
+ * file.
+ */
+
+#include "config.h"
+
+#include
+
+#include
+
+#import "macros.h"
+
+const char *
+OFStrPTime(const char *buffer, const char *format, struct tm *tm, short *tz)
+{
+ enum {
+ stateSearchConversionSpecifier,
+ stateInConversionSpecifier
+ } state = stateSearchConversionSpecifier;
+ size_t j, bufferLen, formatLen;
+
+ bufferLen = strlen(buffer);
+ formatLen = strlen(format);
+
+ j = 0;
+ for (size_t i = 0; i < formatLen; i++) {
+ if (j >= bufferLen)
+ return NULL;
+
+ switch (state) {
+ case stateSearchConversionSpecifier:
+ if (format[i] == '%')
+ state = stateInConversionSpecifier;
+ else if (format[i] != buffer[j++])
+ return NULL;
+
+ break;
+ case stateInConversionSpecifier:;
+ int k, maxLen, number = 0;
+
+ switch (format[i]) {
+ case 'd':
+ case 'e':
+ case 'H':
+ case 'm':
+ case 'M':
+ case 'S':
+ case 'y':
+ maxLen = 2;
+ break;
+ case 'Y':
+ maxLen = 4;
+ break;
+ case '%':
+ case 'a':
+ case 'b':
+ case 'n':
+ case 't':
+ case 'z':
+ maxLen = 0;
+ break;
+ default:
+ return NULL;
+ }
+
+ if (maxLen > 0 && (buffer[j] < '0' || buffer[j] > '9'))
+ return NULL;
+
+ for (k = 0; k < maxLen && j < bufferLen &&
+ buffer[j] >= '0' && buffer[j] <= '9'; k++, j++) {
+ number *= 10;
+ number += buffer[j] - '0';
+ }
+
+ switch (format[i]) {
+ case 'a':
+ if (bufferLen < j + 3)
+ return NULL;
+
+ if (memcmp(buffer + j, "Sun", 3) == 0)
+ tm->tm_wday = 0;
+ else if (memcmp(buffer + j, "Mon", 3) == 0)
+ tm->tm_wday = 1;
+ else if (memcmp(buffer + j, "Tue", 3) == 0)
+ tm->tm_wday = 2;
+ else if (memcmp(buffer + j, "Wed", 3) == 0)
+ tm->tm_wday = 3;
+ else if (memcmp(buffer + j, "Thu", 3) == 0)
+ tm->tm_wday = 4;
+ else if (memcmp(buffer + j, "Fri", 3) == 0)
+ tm->tm_wday = 5;
+ else if (memcmp(buffer + j, "Sat", 3) == 0)
+ tm->tm_wday = 6;
+ else
+ return NULL;
+
+ j += 3;
+ break;
+ case 'b':
+ if (bufferLen < j + 3)
+ return NULL;
+
+ if (memcmp(buffer + j, "Jan", 3) == 0)
+ tm->tm_mon = 0;
+ else if (memcmp(buffer + j, "Feb", 3) == 0)
+ tm->tm_mon = 1;
+ else if (memcmp(buffer + j, "Mar", 3) == 0)
+ tm->tm_mon = 2;
+ else if (memcmp(buffer + j, "Apr", 3) == 0)
+ tm->tm_mon = 3;
+ else if (memcmp(buffer + j, "May", 3) == 0)
+ tm->tm_mon = 4;
+ else if (memcmp(buffer + j, "Jun", 3) == 0)
+ tm->tm_mon = 5;
+ else if (memcmp(buffer + j, "Jul", 3) == 0)
+ tm->tm_mon = 6;
+ else if (memcmp(buffer + j, "Aug", 3) == 0)
+ tm->tm_mon = 7;
+ else if (memcmp(buffer + j, "Sep", 3) == 0)
+ tm->tm_mon = 8;
+ else if (memcmp(buffer + j, "Oct", 3) == 0)
+ tm->tm_mon = 9;
+ else if (memcmp(buffer + j, "Nov", 3) == 0)
+ tm->tm_mon = 10;
+ else if (memcmp(buffer + j, "Dec", 3) == 0)
+ tm->tm_mon = 11;
+ else
+ return NULL;
+
+ j += 3;
+ break;
+ case 'd':
+ case 'e':
+ tm->tm_mday = number;
+ break;
+ case 'H':
+ tm->tm_hour = number;
+ break;
+ case 'm':
+ tm->tm_mon = number - 1;
+ break;
+ case 'M':
+ tm->tm_min = number;
+ break;
+ case 'S':
+ tm->tm_sec = number;
+ break;
+ case 'y':
+ if (number <= 68)
+ number += 100;
+
+ tm->tm_year = number;
+ break;
+ case 'Y':
+ if (number < 1900)
+ return NULL;
+
+ tm->tm_year = number - 1900;
+ break;
+ case 'z':
+ if (buffer[j] == '-' || buffer[j] == '+') {
+ const char *b = buffer + j;
+
+ if (bufferLen < j + 5)
+ return NULL;
+
+ if (tz == NULL)
+ break;
+
+ *tz = (((short)b[1] - '0') * 600 +
+ ((short)b[2] - '0') * 60 +
+ ((short)b[3] - '0') * 10 +
+ ((short)b[4] - '0')) *
+ (b[0] == '-' ? -1 : 1);
+
+ j += 5;
+ } else if (buffer[j] == 'Z') {
+ if (tz != NULL)
+ *tz = 0;
+
+ j++;
+ } else if (buffer[j] == 'G') {
+ if (bufferLen < j + 3)
+ return NULL;
+
+ if (buffer[j + 1] != 'M' ||
+ buffer[j + 2] != 'T')
+ return NULL;
+
+ if (tz != NULL)
+ *tz = 0;
+
+ j += 3;
+ } else
+ return NULL;
+
+ break;
+ case '%':
+ if (buffer[j++] != '%')
+ return NULL;
+ break;
+ case 'n':
+ if (buffer[j++] != '\n')
+ return NULL;
+ break;
+ case 't':
+ if (buffer[j++] != '\t')
+ return NULL;
+ break;
+ }
+
+ state = stateSearchConversionSpecifier;
+
+ break;
+ }
+ }
+
+ return buffer + j;
+}
Index: src/OFStream.h
==================================================================
--- src/OFStream.h
+++ src/OFStream.h
@@ -44,12 +44,11 @@
* @param length The length of the data that has been read
* @param exception An exception which occurred while reading or `nil` on
* success
* @return A bool whether the same block should be used for the next read
*/
-typedef bool (^of_stream_async_read_block_t)(size_t length,
- id _Nullable exception);
+typedef bool (^OFStreamAsyncReadBlock)(size_t length, id _Nullable exception);
/**
* @brief A block which is called when a line was read asynchronously from a
* stream.
*
@@ -57,11 +56,11 @@
* occurred
* @param exception An exception which occurred while reading or `nil` on
* success
* @return A bool whether the same block should be used for the next read
*/
-typedef bool (^of_stream_async_read_line_block_t)(OFString *_Nullable line,
+typedef bool (^OFStreamAsyncReadLineBlock)(OFString *_Nullable line,
id _Nullable exception);
/**
* @brief A block which is called when data was written asynchronously to a
* stream.
@@ -72,12 +71,12 @@
* asynchronous write if no exception was encountered.
* @param exception An exception which occurred while writing or `nil` on
* success
* @return The data to repeat the write with or nil if it should not repeat
*/
-typedef OFData *_Nullable (^of_stream_async_write_data_block_t)(
- OFData *_Nonnull data, size_t bytesWritten, id _Nullable exception);
+typedef OFData *_Nullable (^OFStreamAsyncWriteDataBlock)(OFData *_Nonnull data,
+ size_t bytesWritten, id _Nullable exception);
/**
* @brief A block which is called when a string was written asynchronously to a
* stream.
*
@@ -87,11 +86,11 @@
* asynchronous write if no exception was encountered.
* @param exception An exception which occurred while writing or `nil` on
* success
* @return The string to repeat the write with or nil if it should not repeat
*/
-typedef OFString *_Nullable (^of_stream_async_write_string_block_t)(
+typedef OFString *_Nullable (^OFStreamAsyncWriteStringBlock)(
OFString *_Nonnull string, size_t bytesWritten, id _Nullable exception);
#endif
/**
* @protocol OFStreamDelegate OFStream.h ObjFW/OFStream.h
@@ -159,11 +158,11 @@
* @param exception An exception that occurred while writing, or nil on success
* @return The string to repeat the write with or nil if it should not repeat
*/
- (nullable OFString *)stream: (OFStream *)stream
didWriteString: (OFString *)string
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
bytesWritten: (size_t)bytesWritten
exception: (nullable id)exception;
@end
/**
@@ -311,11 +310,11 @@
* The buffer *must* be *at least* this big!
* @param runLoopMode The run loop mode in which to perform the async read
*/
- (void)asyncReadIntoBuffer: (void *)buffer
length: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode;
+ runLoopMode: (OFRunLoopMode)runLoopMode;
/**
* @brief Asynchronously reads exactly the specified length bytes from the
* stream into a buffer.
*
@@ -350,11 +349,11 @@
* The buffer *must* be *at least* this big!
* @param runLoopMode The run loop mode in which to perform the async read
*/
- (void)asyncReadIntoBuffer: (void *)buffer
exactLength: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode;
+ runLoopMode: (OFRunLoopMode)runLoopMode;
# ifdef OF_HAVE_BLOCKS
/**
* @brief Asynchronously reads *at most* ref size bytes from the stream into a
* buffer.
@@ -380,11 +379,11 @@
* you want the next block in the queue to handle the data
* received next, you need to return false from the block.
*/
- (void)asyncReadIntoBuffer: (void *)buffer
length: (size_t)length
- block: (of_stream_async_read_block_t)block;
+ block: (OFStreamAsyncReadBlock)block;
/**
* @brief Asynchronously reads *at most* ref size bytes from the stream into a
* buffer.
*
@@ -410,12 +409,12 @@
* you want the next block in the queue to handle the data
* received next, you need to return false from the block.
*/
- (void)asyncReadIntoBuffer: (void *)buffer
length: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_stream_async_read_block_t)block;
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFStreamAsyncReadBlock)block;
/**
* @brief Asynchronously reads exactly the specified length bytes from the
* stream into a buffer.
*
@@ -436,11 +435,11 @@
* you want the next block in the queue to handle the data
* received next, you need to return false from the block.
*/
- (void)asyncReadIntoBuffer: (void *)buffer
exactLength: (size_t)length
- block: (of_stream_async_read_block_t)block;
+ block: (OFStreamAsyncReadBlock)block;
/**
* @brief Asynchronously reads exactly the specified length bytes from the
* stream into a buffer.
*
@@ -462,12 +461,12 @@
* you want the next block in the queue to handle the data
* received next, you need to return false from the block.
*/
- (void)asyncReadIntoBuffer: (void *)buffer
exactLength: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_stream_async_read_block_t)block;
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFStreamAsyncReadBlock)block;
# endif
#endif
/**
* @brief Reads a uint8_t from the stream.
@@ -790,11 +789,11 @@
* @param encoding The encoding of the string to read from the stream
* @param length The length (in bytes) of the string to read from the stream
* @return A string with the specified length
*/
- (OFString *)readStringWithLength: (size_t)length
- encoding: (of_string_encoding_t)encoding;
+ encoding: (OFStringEncoding)encoding;
/**
* @brief Reads until a newline, `\0` or end of stream occurs.
*
* @return The line that was read, autoreleased, or `nil` if the end of the
@@ -808,11 +807,11 @@
*
* @param encoding The encoding used by the stream
* @return The line that was read, autoreleased, or `nil` if the end of the
* stream has been reached.
*/
-- (nullable OFString *)readLineWithEncoding: (of_string_encoding_t)encoding;
+- (nullable OFString *)readLineWithEncoding: (OFStringEncoding)encoding;
#ifdef OF_HAVE_SOCKETS
/**
* @brief Asynchronously reads until a newline, `\0`, end of stream or an
* exception occurs.
@@ -829,11 +828,11 @@
* @note The stream must conform to @ref OFReadyForReadingObserving in order
* for this to work!
*
* @param encoding The encoding used by the stream
*/
-- (void)asyncReadLineWithEncoding: (of_string_encoding_t)encoding;
+- (void)asyncReadLineWithEncoding: (OFStringEncoding)encoding;
/**
* @brief Asynchronously reads with the specified encoding until a newline,
* `\0`, end of stream or an exception occurs.
*
@@ -841,12 +840,12 @@
* for this to work!
*
* @param encoding The encoding used by the stream
* @param runLoopMode The run loop mode in which to perform the async read
*/
-- (void)asyncReadLineWithEncoding: (of_string_encoding_t)encoding
- runLoopMode: (of_run_loop_mode_t)runLoopMode;
+- (void)asyncReadLineWithEncoding: (OFStringEncoding)encoding
+ runLoopMode: (OFRunLoopMode)runLoopMode;
# ifdef OF_HAVE_BLOCKS
/**
* @brief Asynchronously reads until a newline, `\0`, end of stream or an
* exception occurs.
@@ -858,11 +857,11 @@
* If the block returns true, it will be called again when the next
* line has been received. If you want the next block in the queue
* to handle the next line, you need to return false from the
* block.
*/
-- (void)asyncReadLineWithBlock: (of_stream_async_read_line_block_t)block;
+- (void)asyncReadLineWithBlock: (OFStreamAsyncReadLineBlock)block;
/**
* @brief Asynchronously reads with the specified encoding until a newline,
* `\0`, end of stream or an exception occurs.
*
@@ -874,12 +873,12 @@
* If the block returns true, it will be called again when the next
* line has been received. If you want the next block in the queue
* to handle the next line, you need to return false from the
* block.
*/
-- (void)asyncReadLineWithEncoding: (of_string_encoding_t)encoding
- block: (of_stream_async_read_line_block_t)block;
+- (void)asyncReadLineWithEncoding: (OFStringEncoding)encoding
+ block: (OFStreamAsyncReadLineBlock)block;
/**
* @brief Asynchronously reads with the specified encoding until a newline,
* `\0`, end of stream or an exception occurs.
*
@@ -892,13 +891,13 @@
* If the block returns true, it will be called again when the next
* line has been received. If you want the next block in the queue
* to handle the next line, you need to return false from the
* block.
*/
-- (void)asyncReadLineWithEncoding: (of_string_encoding_t)encoding
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_stream_async_read_line_block_t)block;
+- (void)asyncReadLineWithEncoding: (OFStringEncoding)encoding
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFStreamAsyncReadLineBlock)block;
# endif
#endif
/**
* @brief Tries to read a line from the stream (see @ref readLine) and returns
@@ -916,11 +915,11 @@
*
* @param encoding The encoding used by the stream
* @return The line that was read, autoreleased, or `nil` if the line is not
* complete yet
*/
-- (nullable OFString *)tryReadLineWithEncoding: (of_string_encoding_t)encoding;
+- (nullable OFString *)tryReadLineWithEncoding: (OFStringEncoding)encoding;
/**
* @brief Reads until the specified string or `\0` is found or the end of
* stream occurs.
*
@@ -938,11 +937,11 @@
* @param encoding The encoding used by the stream
* @return The line that was read, autoreleased, or `nil` if the end of the
* stream has been reached.
*/
- (nullable OFString *)readTillDelimiter: (OFString *)delimiter
- encoding: (of_string_encoding_t)encoding;
+ encoding: (OFStringEncoding)encoding;
/**
* @brief Tries to reads until the specified string or `\0` is found or the end
* of stream (see @ref readTillDelimiter:) and returns `nil` if not
* enough data has been received yet.
@@ -962,11 +961,11 @@
* @param encoding The encoding used by the stream
* @return The line that was read, autoreleased, or `nil` if the end of the
* stream has been reached.
*/
- (nullable OFString *)tryReadTillDelimiter: (OFString *)delimiter
- encoding: (of_string_encoding_t)encoding;
+ encoding: (OFStringEncoding)encoding;
/**
* @brief Writes everything in the write buffer to the stream.
*/
- (void)flushWriteBuffer;
@@ -1000,11 +999,11 @@
*
* @param data The data which is written into the stream
* @param runLoopMode The run loop mode in which to perform the async write
*/
- (void)asyncWriteData: (OFData *)data
- runLoopMode: (of_run_loop_mode_t)runLoopMode;
+ runLoopMode: (OFRunLoopMode)runLoopMode;
/**
* @brief Asynchronously writes a string in UTF-8 encoding into the stream.
*
* @note The stream must conform to @ref OFReadyForWritingObserving in order
@@ -1024,11 +1023,11 @@
* @param string The string which is written into the stream
* @param encoding The encoding in which the string should be written to the
* stream
*/
- (void)asyncWriteString: (OFString *)string
- encoding: (of_string_encoding_t)encoding;
+ encoding: (OFStringEncoding)encoding;
/**
* @brief Asynchronously writes a string in the specified encoding into the
* stream.
*
@@ -1039,12 +1038,12 @@
* @param encoding The encoding in which the string should be written to the
* stream
* @param runLoopMode The run loop mode in which to perform the async write
*/
- (void)asyncWriteString: (OFString *)string
- encoding: (of_string_encoding_t)encoding
- runLoopMode: (of_run_loop_mode_t)runLoopMode;
+ encoding: (OFStringEncoding)encoding
+ runLoopMode: (OFRunLoopMode)runLoopMode;
# ifdef OF_HAVE_BLOCKS
/**
* @brief Asynchronously writes data into the stream.
*
@@ -1055,11 +1054,11 @@
* @param block The block to call when the data has been written. It should
* return the data for the next write with the same callback or
* nil if it should not repeat.
*/
- (void)asyncWriteData: (OFData *)data
- block: (of_stream_async_write_data_block_t)block;
+ block: (OFStreamAsyncWriteDataBlock)block;
/**
* @brief Asynchronously writes data into the stream.
*
* @note The stream must conform to @ref OFReadyForWritingObserving in order
@@ -1070,12 +1069,12 @@
* @param block The block to call when the data has been written. It should
* return the data for the next write with the same callback or
* nil if it should not repeat.
*/
- (void)asyncWriteData: (OFData *)data
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_stream_async_write_data_block_t)block;
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFStreamAsyncWriteDataBlock)block;
/**
* @brief Asynchronously writes a string into the stream.
*
* @note The stream must conform to @ref OFReadyForWritingObserving in order
@@ -1085,11 +1084,11 @@
* @param block The block to call when the string has been written. It should
* return the string for the next write with the same callback or
* nil if it should not repeat.
*/
- (void)asyncWriteString: (OFString *)string
- block: (of_stream_async_write_string_block_t)block;
+ block: (OFStreamAsyncWriteStringBlock)block;
/**
* @brief Asynchronously writes a string in the specified encoding into the
* stream.
*
@@ -1102,12 +1101,12 @@
* @param block The block to call when the string has been written. It should
* return the string for the next write with the same callback or
* nil if it should not repeat.
*/
- (void)asyncWriteString: (OFString *)string
- encoding: (of_string_encoding_t)encoding
- block: (of_stream_async_write_string_block_t)block;
+ encoding: (OFStringEncoding)encoding
+ block: (OFStreamAsyncWriteStringBlock)block;
/**
* @brief Asynchronously writes a string in the specified encoding into the
* stream.
*
@@ -1121,13 +1120,13 @@
* @param block The block to call when the string has been written. It should
* return the string for the next write with the same callback or
* nil if it should not repeat.
*/
- (void)asyncWriteString: (OFString *)string
- encoding: (of_string_encoding_t)encoding
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_stream_async_write_string_block_t)block;
+ encoding: (OFStringEncoding)encoding
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFStreamAsyncWriteStringBlock)block;
# endif
#endif
/**
* @brief Writes a uint8_t into the stream.
@@ -1341,12 +1340,11 @@
*
* @param string The string from which the data is written to the stream
* @param encoding The encoding in which to write the string to the stream
* @return The number of bytes written
*/
-- (size_t)writeString: (OFString *)string
- encoding: (of_string_encoding_t)encoding;
+- (size_t)writeString: (OFString *)string encoding: (OFStringEncoding)encoding;
/**
* @brief Writes a string into the stream with a trailing newline.
*
* @param string The string from which the data is written to the stream
@@ -1360,19 +1358,18 @@
*
* @param string The string from which the data is written to the stream
* @param encoding The encoding in which to write the string to the stream
* @return The number of bytes written
*/
-- (size_t)writeLine: (OFString *)string
- encoding: (of_string_encoding_t)encoding;
+- (size_t)writeLine: (OFString *)string encoding: (OFStringEncoding)encoding;
/**
* @brief Writes a formatted string into the stream.
*
* See printf for the format syntax. As an addition, `%@` is available as
- * format specifier for objects, `%C` for `of_unichar_t` and `%S` for
- * `const of_unichar_t *`.
+ * format specifier for objects, `%C` for `OFUnichar` and `%S` for
+ * `const OFUnichar *`.
*
* @param format A string used as format
* @return The number of bytes written
*/
- (size_t)writeFormat: (OFConstantString *)format, ...;
@@ -1379,12 +1376,12 @@
/**
* @brief Writes a formatted string into the stream.
*
* See printf for the format syntax. As an addition, `%@` is available as
- * format specifier for objects, `%C` for `of_unichar_t` and `%S` for
- * `const of_unichar_t *`.
+ * format specifier for objects, `%C` for `OFUnichar` and `%S` for
+ * `const OFUnichar *`.
*
* @param format A string used as format
* @param arguments The arguments used in the format string
* @return The number of bytes written
*/
Index: src/OFStream.m
==================================================================
--- src/OFStream.m
+++ src/OFStream.m
@@ -26,26 +26,26 @@
#ifdef HAVE_FCNTL_H
# include
#endif
-#ifdef OF_HAVE_SOCKETS
-# import "socket_helpers.h"
-#endif
-
#include "platform.h"
#if !defined(OF_WINDOWS) && !defined(OF_MORPHOS)
# include
#endif
#import "OFStream.h"
#import "OFStream+Private.h"
+#import "OFASPrintF.h"
#import "OFData.h"
#import "OFKernelEventObserver.h"
#import "OFRunLoop+Private.h"
#import "OFRunLoop.h"
+#ifdef OF_HAVE_SOCKETS
+# import "OFSocket+Private.h"
+#endif
#import "OFString.h"
#import "OFSystemInfo.h"
#import "OFInvalidArgumentException.h"
#import "OFInvalidFormatException.h"
@@ -54,13 +54,11 @@
#import "OFOutOfRangeException.h"
#import "OFSetOptionFailedException.h"
#import "OFTruncatedDataException.h"
#import "OFWriteFailedException.h"
-#import "of_asprintf.h"
-
-#define MIN_READ_SIZE 512
+#define minReadSize 512
@implementation OFStream
@synthesize buffersWrites = _buffersWrites;
@synthesize of_waitingForDelimiter = _waitingForDelimiter, delegate = _delegate;
@@ -91,12 +89,12 @@
return self;
}
- (void)dealloc
{
- free(_readBufferMemory);
- free(_writeBuffer);
+ OFFreeMemory(_readBufferMemory);
+ OFFreeMemory(_writeBuffer);
[super dealloc];
}
- (bool)lowlevelIsAtEndOfStream
@@ -133,22 +131,22 @@
/*
* For small sizes, it is cheaper to read more and cache the
* remainder - even if that means more copying of data - than
* to do a syscall for every read.
*/
- if (length < MIN_READ_SIZE) {
- char tmp[MIN_READ_SIZE], *readBuffer;
+ if (length < minReadSize) {
+ char tmp[minReadSize], *readBuffer;
size_t bytesRead;
- bytesRead = [self
- lowlevelReadIntoBuffer: tmp
- length: MIN_READ_SIZE];
+ bytesRead = [self lowlevelReadIntoBuffer: tmp
+ length: minReadSize];
if (bytesRead > length) {
memcpy(buffer, tmp, length);
- readBuffer = of_alloc(bytesRead - length, 1);
+ readBuffer = OFAllocMemory(bytesRead - length,
+ 1);
memcpy(readBuffer, tmp + length,
bytesRead - length);
_readBuffer = _readBufferMemory = readBuffer;
_readBufferLength = bytesRead - length;
@@ -165,11 +163,11 @@
if (length >= _readBufferLength) {
size_t ret = _readBufferLength;
memcpy(buffer, _readBuffer, _readBufferLength);
- free(_readBufferMemory);
+ OFFreeMemory(_readBufferMemory);
_readBuffer = _readBufferMemory = NULL;
_readBufferLength = 0;
return ret;
} else {
@@ -198,16 +196,16 @@
#ifdef OF_HAVE_SOCKETS
- (void)asyncReadIntoBuffer: (void *)buffer length: (size_t)length
{
[self asyncReadIntoBuffer: buffer
length: length
- runLoopMode: of_run_loop_mode_default];
+ runLoopMode: OFDefaultRunLoopMode];
}
- (void)asyncReadIntoBuffer: (void *)buffer
length: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ runLoopMode: (OFRunLoopMode)runLoopMode
{
OFStream *stream =
(OFStream *)self;
[OFRunLoop of_addAsyncReadForStream: stream
@@ -222,16 +220,16 @@
- (void)asyncReadIntoBuffer: (void *)buffer exactLength: (size_t)length
{
[self asyncReadIntoBuffer: buffer
exactLength: length
- runLoopMode: of_run_loop_mode_default];
+ runLoopMode: OFDefaultRunLoopMode];
}
- (void)asyncReadIntoBuffer: (void *)buffer
exactLength: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ runLoopMode: (OFRunLoopMode)runLoopMode
{
OFStream *stream =
(OFStream *)self;
[OFRunLoop of_addAsyncReadForStream: stream
@@ -245,22 +243,22 @@
}
# ifdef OF_HAVE_BLOCKS
- (void)asyncReadIntoBuffer: (void *)buffer
length: (size_t)length
- block: (of_stream_async_read_block_t)block
+ block: (OFStreamAsyncReadBlock)block
{
[self asyncReadIntoBuffer: buffer
length: length
- runLoopMode: of_run_loop_mode_default
+ runLoopMode: OFDefaultRunLoopMode
block: block];
}
- (void)asyncReadIntoBuffer: (void *)buffer
length: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_stream_async_read_block_t)block
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFStreamAsyncReadBlock)block
{
OFStream *stream =
(OFStream *)self;
[OFRunLoop of_addAsyncReadForStream: stream
@@ -271,22 +269,22 @@
delegate: nil];
}
- (void)asyncReadIntoBuffer: (void *)buffer
exactLength: (size_t)length
- block: (of_stream_async_read_block_t)block
+ block: (OFStreamAsyncReadBlock)block
{
[self asyncReadIntoBuffer: buffer
exactLength: length
- runLoopMode: of_run_loop_mode_default
+ runLoopMode: OFDefaultRunLoopMode
block: block];
}
- (void)asyncReadIntoBuffer: (void *)buffer
exactLength: (size_t)length
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_stream_async_read_block_t)block
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFStreamAsyncReadBlock)block
{
OFStream *stream =
(OFStream *)self;
[OFRunLoop of_addAsyncReadForStream: stream
@@ -308,39 +306,39 @@
- (uint16_t)readBigEndianInt16
{
uint16_t ret;
[self readIntoBuffer: (char *)&ret exactLength: 2];
- return OF_BSWAP16_IF_LE(ret);
+ return OFFromBigEndian16(ret);
}
- (uint32_t)readBigEndianInt32
{
uint32_t ret;
[self readIntoBuffer: (char *)&ret exactLength: 4];
- return OF_BSWAP32_IF_LE(ret);
+ return OFFromBigEndian32(ret);
}
- (uint64_t)readBigEndianInt64
{
uint64_t ret;
[self readIntoBuffer: (char *)&ret exactLength: 8];
- return OF_BSWAP64_IF_LE(ret);
+ return OFFromBigEndian64(ret);
}
- (float)readBigEndianFloat
{
float ret;
[self readIntoBuffer: (char *)&ret exactLength: 4];
- return OF_BSWAP_FLOAT_IF_LE(ret);
+ return OFFromBigEndianFloat(ret);
}
- (double)readBigEndianDouble
{
double ret;
[self readIntoBuffer: (char *)&ret exactLength: 8];
- return OF_BSWAP_DOUBLE_IF_LE(ret);
+ return OFFromBigEndianDouble(ret);
}
- (size_t)readBigEndianInt16sIntoBuffer: (uint16_t *)buffer count: (size_t)count
{
size_t size;
@@ -352,11 +350,11 @@
[self readIntoBuffer: buffer exactLength: size];
#ifndef OF_BIG_ENDIAN
for (size_t i = 0; i < count; i++)
- buffer[i] = OF_BSWAP16(buffer[i]);
+ buffer[i] = OFByteSwap16(buffer[i]);
#endif
return size;
}
@@ -371,11 +369,11 @@
[self readIntoBuffer: buffer exactLength: size];
#ifndef OF_BIG_ENDIAN
for (size_t i = 0; i < count; i++)
- buffer[i] = OF_BSWAP32(buffer[i]);
+ buffer[i] = OFByteSwap32(buffer[i]);
#endif
return size;
}
@@ -390,11 +388,11 @@
[self readIntoBuffer: buffer exactLength: size];
#ifndef OF_BIG_ENDIAN
for (size_t i = 0; i < count; i++)
- buffer[i] = OF_BSWAP64(buffer[i]);
+ buffer[i] = OFByteSwap64(buffer[i]);
#endif
return size;
}
@@ -409,11 +407,11 @@
[self readIntoBuffer: buffer exactLength: size];
#ifndef OF_FLOAT_BIG_ENDIAN
for (size_t i = 0; i < count; i++)
- buffer[i] = OF_BSWAP_FLOAT(buffer[i]);
+ buffer[i] = OFByteSwapFloat(buffer[i]);
#endif
return size;
}
@@ -428,49 +426,49 @@
[self readIntoBuffer: buffer exactLength: size];
#ifndef OF_FLOAT_BIG_ENDIAN
for (size_t i = 0; i < count; i++)
- buffer[i] = OF_BSWAP_DOUBLE(buffer[i]);
+ buffer[i] = OFByteSwapDouble(buffer[i]);
#endif
return size;
}
- (uint16_t)readLittleEndianInt16
{
uint16_t ret;
[self readIntoBuffer: (char *)&ret exactLength: 2];
- return OF_BSWAP16_IF_BE(ret);
+ return OFFromLittleEndian16(ret);
}
- (uint32_t)readLittleEndianInt32
{
uint32_t ret;
[self readIntoBuffer: (char *)&ret exactLength: 4];
- return OF_BSWAP32_IF_BE(ret);
+ return OFFromLittleEndian32(ret);
}
- (uint64_t)readLittleEndianInt64
{
uint64_t ret;
[self readIntoBuffer: (char *)&ret exactLength: 8];
- return OF_BSWAP64_IF_BE(ret);
+ return OFFromLittleEndian64(ret);
}
- (float)readLittleEndianFloat
{
float ret;
[self readIntoBuffer: (char *)&ret exactLength: 4];
- return OF_BSWAP_FLOAT_IF_BE(ret);
+ return OFFromLittleEndianFloat(ret);
}
- (double)readLittleEndianDouble
{
double ret;
[self readIntoBuffer: (char *)&ret exactLength: 8];
- return OF_BSWAP_DOUBLE_IF_BE(ret);
+ return OFFromLittleEndianDouble(ret);
}
- (size_t)readLittleEndianInt16sIntoBuffer: (uint16_t *)buffer
count: (size_t)count
{
@@ -483,11 +481,11 @@
[self readIntoBuffer: buffer exactLength: size];
#ifdef OF_BIG_ENDIAN
for (size_t i = 0; i < count; i++)
- buffer[i] = OF_BSWAP16(buffer[i]);
+ buffer[i] = OFByteSwap16(buffer[i]);
#endif
return size;
}
@@ -503,11 +501,11 @@
[self readIntoBuffer: buffer exactLength: size];
#ifdef OF_BIG_ENDIAN
for (size_t i = 0; i < count; i++)
- buffer[i] = OF_BSWAP32(buffer[i]);
+ buffer[i] = OFByteSwap32(buffer[i]);
#endif
return size;
}
@@ -523,11 +521,11 @@
[self readIntoBuffer: buffer exactLength: size];
#ifdef OF_BIG_ENDIAN
for (size_t i = 0; i < count; i++)
- buffer[i] = OF_BSWAP64(buffer[i]);
+ buffer[i] = OFByteSwap64(buffer[i]);
#endif
return size;
}
@@ -543,11 +541,11 @@
[self readIntoBuffer: buffer exactLength: size];
#ifdef OF_FLOAT_BIG_ENDIAN
for (size_t i = 0; i < count; i++)
- buffer[i] = OF_BSWAP_FLOAT(buffer[i]);
+ buffer[i] = OFByteSwapFloat(buffer[i]);
#endif
return size;
}
@@ -563,11 +561,11 @@
[self readIntoBuffer: buffer exactLength: size];
#ifdef OF_FLOAT_BIG_ENDIAN
for (size_t i = 0; i < count; i++)
- buffer[i] = OF_BSWAP_DOUBLE(buffer[i]);
+ buffer[i] = OFByteSwapDouble(buffer[i]);
#endif
return size;
}
@@ -582,19 +580,19 @@
char *buffer;
if OF_UNLIKELY (count > SIZE_MAX / itemSize)
@throw [OFOutOfRangeException exception];
- buffer = of_alloc(count, itemSize);
+ buffer = OFAllocMemory(count, itemSize);
@try {
[self readIntoBuffer: buffer exactLength: count * itemSize];
ret = [OFData dataWithItemsNoCopy: buffer
count: count
itemSize: itemSize
freeWhenDone: true];
} @catch (id e) {
- free(buffer);
+ OFFreeMemory(buffer);
@throw e;
}
return ret;
}
@@ -601,50 +599,50 @@
- (OFData *)readDataUntilEndOfStream
{
OFMutableData *data = [OFMutableData data];
size_t pageSize = [OFSystemInfo pageSize];
- char *buffer = of_alloc(1, pageSize);
+ char *buffer = OFAllocMemory(1, pageSize);
@try {
while (!self.atEndOfStream) {
size_t length =
[self readIntoBuffer: buffer length: pageSize];
[data addItems: buffer count: length];
}
} @finally {
- free(buffer);
+ OFFreeMemory(buffer);
}
[data makeImmutable];
return data;
}
- (OFString *)readStringWithLength: (size_t)length
{
return [self readStringWithLength: length
- encoding: OF_STRING_ENCODING_UTF_8];
+ encoding: OFStringEncodingUTF8];
}
- (OFString *)readStringWithLength: (size_t)length
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
OFString *ret;
- char *buffer = of_alloc(length + 1, 1);
+ char *buffer = OFAllocMemory(length + 1, 1);
buffer[length] = 0;
@try {
[self readIntoBuffer: buffer exactLength: length];
ret = [OFString stringWithCString: buffer encoding: encoding];
} @finally {
- free(buffer);
+ OFFreeMemory(buffer);
}
return ret;
}
-- (OFString *)tryReadLineWithEncoding: (of_string_encoding_t)encoding
+- (OFString *)tryReadLineWithEncoding: (OFStringEncoding)encoding
{
size_t pageSize, bufferLength;
char *buffer, *readBuffer;
OFString *ret;
@@ -671,11 +669,11 @@
}
}
/* Read and see if we got a newline or \0 */
pageSize = [OFSystemInfo pageSize];
- buffer = of_alloc(1, pageSize);
+ buffer = OFAllocMemory(1, pageSize);
@try {
if ([self lowlevelIsAtEndOfStream]) {
size_t retLength;
@@ -691,11 +689,11 @@
ret = [OFString stringWithCString: _readBuffer
encoding: encoding
length: retLength];
- free(_readBufferMemory);
+ OFFreeMemory(_readBufferMemory);
_readBuffer = _readBufferMemory = NULL;
_readBufferLength = 0;
_waitingForDelimiter = false;
return ret;
@@ -707,11 +705,11 @@
/* Look if there's a newline or \0 */
for (size_t i = 0; i < bufferLength; i++) {
if OF_UNLIKELY (buffer[i] == '\n' ||
buffer[i] == '\0') {
size_t retLength = _readBufferLength + i;
- char *retCString = of_alloc(retLength, 1);
+ char *retCString = OFAllocMemory(retLength, 1);
if (_readBuffer != NULL)
memcpy(retCString, _readBuffer,
_readBufferLength);
memcpy(retCString + _readBufferLength,
@@ -730,38 +728,39 @@
if (bufferLength > 0) {
/*
* Append data to _readBuffer
* to prevent loss of data.
*/
- readBuffer = of_alloc(
+ readBuffer = OFAllocMemory(
_readBufferLength +
bufferLength, 1);
memcpy(readBuffer, _readBuffer,
_readBufferLength);
memcpy(readBuffer +
_readBufferLength,
buffer, bufferLength);
- free(_readBufferMemory);
+ OFFreeMemory(_readBufferMemory);
_readBuffer = readBuffer;
_readBufferMemory = readBuffer;
_readBufferLength +=
bufferLength;
}
@throw e;
} @finally {
- free(retCString);
+ OFFreeMemory(retCString);
}
- readBuffer = of_alloc(bufferLength - i - 1, 1);
+ readBuffer = OFAllocMemory(bufferLength - i - 1,
+ 1);
if (readBuffer != NULL)
memcpy(readBuffer, buffer + i + 1,
bufferLength - i - 1);
- free(_readBufferMemory);
+ OFFreeMemory(_readBufferMemory);
_readBuffer = _readBufferMemory = readBuffer;
_readBufferLength = bufferLength - i - 1;
_waitingForDelimiter = false;
return ret;
@@ -768,35 +767,35 @@
}
}
/* There was no newline or \0 */
if (bufferLength > 0) {
- readBuffer = of_alloc(_readBufferLength + bufferLength,
- 1);
+ readBuffer = OFAllocMemory(
+ _readBufferLength + bufferLength, 1);
memcpy(readBuffer, _readBuffer, _readBufferLength);
memcpy(readBuffer + _readBufferLength,
buffer, bufferLength);
- free(_readBufferMemory);
+ OFFreeMemory(_readBufferMemory);
_readBuffer = _readBufferMemory = readBuffer;
_readBufferLength += bufferLength;
}
} @finally {
- free(buffer);
+ OFFreeMemory(buffer);
}
_waitingForDelimiter = true;
return nil;
}
- (OFString *)readLine
{
- return [self readLineWithEncoding: OF_STRING_ENCODING_UTF_8];
+ return [self readLineWithEncoding: OFStringEncodingUTF8];
}
-- (OFString *)readLineWithEncoding: (of_string_encoding_t)encoding
+- (OFString *)readLineWithEncoding: (OFStringEncoding)encoding
{
OFString *line = nil;
while ((line = [self tryReadLineWithEncoding: encoding]) == nil)
if (self.atEndOfStream)
@@ -806,22 +805,22 @@
}
#ifdef OF_HAVE_SOCKETS
- (void)asyncReadLine
{
- [self asyncReadLineWithEncoding: OF_STRING_ENCODING_UTF_8
- runLoopMode: of_run_loop_mode_default];
+ [self asyncReadLineWithEncoding: OFStringEncodingUTF8
+ runLoopMode: OFDefaultRunLoopMode];
}
-- (void)asyncReadLineWithEncoding: (of_string_encoding_t)encoding
+- (void)asyncReadLineWithEncoding: (OFStringEncoding)encoding
{
[self asyncReadLineWithEncoding: encoding
- runLoopMode: of_run_loop_mode_default];
+ runLoopMode: OFDefaultRunLoopMode];
}
-- (void)asyncReadLineWithEncoding: (of_string_encoding_t)encoding
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+- (void)asyncReadLineWithEncoding: (OFStringEncoding)encoding
+ runLoopMode: (OFRunLoopMode)runLoopMode
{
OFStream *stream =
(OFStream *)self;
[OFRunLoop of_addAsyncReadLineForStream: stream
@@ -832,28 +831,28 @@
# endif
delegate: _delegate];
}
# ifdef OF_HAVE_BLOCKS
-- (void)asyncReadLineWithBlock: (of_stream_async_read_line_block_t)block
+- (void)asyncReadLineWithBlock: (OFStreamAsyncReadLineBlock)block
{
- [self asyncReadLineWithEncoding: OF_STRING_ENCODING_UTF_8
- runLoopMode: of_run_loop_mode_default
+ [self asyncReadLineWithEncoding: OFStringEncodingUTF8
+ runLoopMode: OFDefaultRunLoopMode
block: block];
}
-- (void)asyncReadLineWithEncoding: (of_string_encoding_t)encoding
- block: (of_stream_async_read_line_block_t)block
+- (void)asyncReadLineWithEncoding: (OFStringEncoding)encoding
+ block: (OFStreamAsyncReadLineBlock)block
{
[self asyncReadLineWithEncoding: encoding
- runLoopMode: of_run_loop_mode_default
+ runLoopMode: OFDefaultRunLoopMode
block: block];
}
-- (void)asyncReadLineWithEncoding: (of_string_encoding_t)encoding
- runLoopMode: (of_run_loop_mode_t)runLoopMode
- block: (of_stream_async_read_line_block_t)block
+- (void)asyncReadLineWithEncoding: (OFStringEncoding)encoding
+ runLoopMode: (OFRunLoopMode)runLoopMode
+ block: (OFStreamAsyncReadLineBlock)block
{
OFStream *stream =
(OFStream *)self;
[OFRunLoop of_addAsyncReadLineForStream: stream
@@ -865,15 +864,15 @@
# endif
#endif
- (OFString *)tryReadLine
{
- return [self tryReadLineWithEncoding: OF_STRING_ENCODING_UTF_8];
+ return [self tryReadLineWithEncoding: OFStringEncodingUTF8];
}
- (OFString *)tryReadTillDelimiter: (OFString *)delimiter
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
const char *delimiterCString;
size_t j, delimiterLength, pageSize, bufferLength;
char *buffer, *readBuffer;
OFString *ret;
@@ -909,11 +908,11 @@
}
}
/* Read and see if we got a delimiter or \0 */
pageSize = [OFSystemInfo pageSize];
- buffer = of_alloc(1, pageSize);
+ buffer = OFAllocMemory(1, pageSize);
@try {
if ([self lowlevelIsAtEndOfStream]) {
if (_readBuffer == NULL) {
_waitingForDelimiter = false;
@@ -922,11 +921,11 @@
ret = [OFString stringWithCString: _readBuffer
encoding: encoding
length: _readBufferLength];
- free(_readBufferMemory);
+ OFFreeMemory(_readBufferMemory);
_readBuffer = _readBufferMemory = NULL;
_readBufferLength = 0;
_waitingForDelimiter = false;
return ret;
@@ -947,11 +946,11 @@
if (buffer[i] == '\0')
delimiterLength = 1;
retLength = _readBufferLength + i + 1 -
delimiterLength;
- retCString = of_alloc(retLength, 1);
+ retCString = OFAllocMemory(retLength, 1);
if (_readBuffer != NULL &&
_readBufferLength <= retLength)
memcpy(retCString, _readBuffer,
_readBufferLength);
@@ -971,38 +970,39 @@
if (bufferLength > 0) {
/*
* Append data to _readBuffer
* to prevent loss of data.
*/
- readBuffer = of_alloc(
+ readBuffer = OFAllocMemory(
_readBufferLength +
bufferLength, 1);
memcpy(readBuffer, _readBuffer,
_readBufferLength);
memcpy(readBuffer +
_readBufferLength,
buffer, bufferLength);
- free(_readBufferMemory);
+ OFFreeMemory(_readBufferMemory);
_readBuffer = readBuffer;
_readBufferMemory = readBuffer;
_readBufferLength +=
bufferLength;
}
@throw e;
} @finally {
- free(retCString);
+ OFFreeMemory(retCString);
}
- readBuffer = of_alloc(bufferLength - i - 1, 1);
+ readBuffer = OFAllocMemory(bufferLength - i - 1,
+ 1);
if (readBuffer != NULL)
memcpy(readBuffer, buffer + i + 1,
bufferLength - i - 1);
- free(_readBufferMemory);
+ OFFreeMemory(_readBufferMemory);
_readBuffer = _readBufferMemory = readBuffer;
_readBufferLength = bufferLength - i - 1;
_waitingForDelimiter = false;
return ret;
@@ -1009,23 +1009,23 @@
}
}
/* Neither the delimiter nor \0 was found */
if (bufferLength > 0) {
- readBuffer = of_alloc(_readBufferLength + bufferLength,
- 1);
+ readBuffer = OFAllocMemory(
+ _readBufferLength + bufferLength, 1);
memcpy(readBuffer, _readBuffer, _readBufferLength);
memcpy(readBuffer + _readBufferLength,
buffer, bufferLength);
- free(_readBufferMemory);
+ OFFreeMemory(_readBufferMemory);
_readBuffer = _readBufferMemory = readBuffer;
_readBufferLength += bufferLength;
}
} @finally {
- free(buffer);
+ OFFreeMemory(buffer);
}
_waitingForDelimiter = true;
return nil;
}
@@ -1032,15 +1032,15 @@
- (OFString *)readTillDelimiter: (OFString *)delimiter
{
return [self readTillDelimiter: delimiter
- encoding: OF_STRING_ENCODING_UTF_8];
+ encoding: OFStringEncodingUTF8];
}
- (OFString *)readTillDelimiter: (OFString *)delimiter
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
OFString *ret = nil;
while ((ret = [self tryReadTillDelimiter: delimiter
encoding: encoding]) == nil)
@@ -1051,21 +1051,21 @@
}
- (OFString *)tryReadTillDelimiter: (OFString *)delimiter
{
return [self tryReadTillDelimiter: delimiter
- encoding: OF_STRING_ENCODING_UTF_8];
+ encoding: OFStringEncodingUTF8];
}
- (void)flushWriteBuffer
{
if (_writeBuffer == NULL)
return;
[self lowlevelWriteBuffer: _writeBuffer length: _writeBufferLength];
- free(_writeBuffer);
+ OFFreeMemory(_writeBuffer);
_writeBuffer = NULL;
_writeBufferLength = 0;
}
- (size_t)writeBuffer: (const void *)buffer
@@ -1082,11 +1082,11 @@
bytesWritten: bytesWritten
errNo: 0];
return bytesWritten;
} else {
- _writeBuffer = of_realloc(_writeBuffer,
+ _writeBuffer = OFResizeMemory(_writeBuffer,
_writeBufferLength + length, 1);
memcpy(_writeBuffer + _writeBufferLength, buffer, length);
_writeBufferLength += length;
return length;
@@ -1094,15 +1094,14 @@
}
#ifdef OF_HAVE_SOCKETS
- (void)asyncWriteData: (OFData *)data
{
- [self asyncWriteData: data runLoopMode: of_run_loop_mode_default];
+ [self asyncWriteData: data runLoopMode: OFDefaultRunLoopMode];
}
-- (void)asyncWriteData: (OFData *)data
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+- (void)asyncWriteData: (OFData *)data runLoopMode: (OFRunLoopMode)runLoopMode
{
OFStream *stream =
(OFStream *)self;
[OFRunLoop of_addAsyncWriteForStream: stream
@@ -1115,25 +1114,25 @@
}
- (void)asyncWriteString: (OFString *)string
{
[self asyncWriteString: string
- encoding: OF_STRING_ENCODING_UTF_8
- runLoopMode: of_run_loop_mode_default];
+ encoding: OFStringEncodingUTF8
+ runLoopMode: OFDefaultRunLoopMode];
}
- (void)asyncWriteString: (OFString *)string
- encoding: (of_string_encoding_t)encoding
+ encoding: (OFStringEncoding)encoding
{
[self asyncWriteString: string
encoding: encoding
- runLoopMode: of_run_loop_mode_default];
+ runLoopMode: OFDefaultRunLoopMode];
}
- (void)asyncWriteString: (OFString *)string
- encoding: (of_string_encoding_t)encoding
- runLoopMode: (of_run_loop_mode_t)runLoopMode
+ encoding: (OFStringEncoding)encoding
+ runLoopMode: (OFRunLoopMode)runLoopMode
{
OFStream *stream =
(OFStream