ObjFW  Check-in [b431203426]

Overview
Comment:OFZooArchive: Add write support
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: b431203426d5b10938276ab9ebacecb3d667eb8518248085c4fa6be0f6d59849
User & Date: js on 2024-03-03 19:29:53
Other Links: manifest | tags
Context
2024-03-03
19:38
Add IRI handler for Zoo archives check-in: 4e1846598b user: js tags: trunk
19:29
OFZooArchive: Add write support check-in: b431203426 user: js tags: trunk
2024-03-02
21:20
Minor documentation fix check-in: 7619af113a user: js tags: trunk
Changes

Modified src/OFLHAArchive.m from [97efb45aaf] to [7fd2208cb9].

294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
{
	if (_stream == nil)
		@throw [OFNotOpenException exceptionWithObject: self];

	@try {
		[_lastReturnedStream close];
	} @catch (OFNotOpenException *e) {
		/* Might have already been closed by the user - that's fine */
	}

	/* LHA archives should be terminated with a header of size 0 */
	if (_hasWritten)
		[_stream writeBuffer: "" length: 1];

	_lastReturnedStream = nil;







|







294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
{
	if (_stream == nil)
		@throw [OFNotOpenException exceptionWithObject: self];

	@try {
		[_lastReturnedStream close];
	} @catch (OFNotOpenException *e) {
		/* Might have already been closed by the user - that's fine. */
	}

	/* LHA archives should be terminated with a header of size 0 */
	if (_hasWritten)
		[_stream writeBuffer: "" length: 1];

	_lastReturnedStream = nil;

Modified src/OFMutableZooArchiveEntry.m from [26fa9bdcde] to [5eea787dbf].

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
- (instancetype)initWithFileName: (OFString *)fileName
{
	self = [super of_init];

	@try {
		void *pool = objc_autoreleasePoolPush();

		_fileName = [fileName copy];
		self.modificationDate = [OFDate date];

		objc_autoreleasePoolPop(pool);
	} @catch (id e) {
		[self release];
		@throw e;
	}







|







35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
- (instancetype)initWithFileName: (OFString *)fileName
{
	self = [super of_init];

	@try {
		void *pool = objc_autoreleasePoolPush();

		self.fileName = fileName;
		self.modificationDate = [OFDate date];

		objc_autoreleasePoolPop(pool);
	} @catch (id e) {
		[self release];
		@throw e;
	}
125
126
127
128
129
130
131



132











133
134
135
136
137



138
139
140
141
142
143
144
	OFString *old = _fileComment;
	_fileComment = [fileComment copy];
	[old release];
}

- (void)setFileName: (OFString *)fileName
{



	OFString *old = _fileName;











	_fileName = [fileName copy];
	[old release];

	[_directoryName release];
	_directoryName = nil;



}

- (void)setOperatingSystemIdentifier: (uint16_t)operatingSystemIdentifier
{
	_operatingSystemIdentifier = operatingSystemIdentifier;
}








>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
|
|

|
|
>
>
>







125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
	OFString *old = _fileComment;
	_fileComment = [fileComment copy];
	[old release];
}

- (void)setFileName: (OFString *)fileName
{
	void *pool = objc_autoreleasePoolPush();
	OFString *oldFileName = _fileName, *oldDirectoryName = _directoryName;
	size_t lastSlash;

	lastSlash = [fileName rangeOfString: @"/"
				    options: OFStringSearchBackwards].location;
	if (lastSlash != OFNotFound) {
		_fileName = [[fileName substringWithRange: OFMakeRange(
		    lastSlash + 1, fileName.length - lastSlash - 1)] copy];
		[oldFileName release];

		_directoryName = [[fileName substringWithRange:
		    OFMakeRange(0, lastSlash)] copy];
		[oldDirectoryName release];
	} else {
		_fileName = [fileName copy];
		[oldFileName release];

		[_directoryName release];
		_directoryName = nil;
	}

	objc_autoreleasePoolPop(pool);
}

- (void)setOperatingSystemIdentifier: (uint16_t)operatingSystemIdentifier
{
	_operatingSystemIdentifier = operatingSystemIdentifier;
}

Modified src/OFZooArchive.h from [2cebcb2c91] to [3db7e3fb48].

10
11
12
13
14
15
16

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34


35
36
37
38
39



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101

102

103
104
105
106


107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123

























124
125
126
127
128
129
130
131
132
 * 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 "OFObject.h"

#import "OFString.h"
#import "OFZooArchiveEntry.h"

OF_ASSUME_NONNULL_BEGIN

@class OFStream;

/**
 * @class OFZooArchive OFZooArchive.h ObjFW/OFZooArchive.h
 *
 * @brief A class for accessing and manipulating Zoo files.
 */
OF_SUBCLASSING_RESTRICTED
@interface OFZooArchive: OFObject
{
	OF_KINDOF(OFStream *) _stream;
	uint_least8_t _mode;
	OFStringEncoding _encoding;


	OFZooArchiveEntry *_Nullable _currentEntry;
#ifdef OF_ZOO_ARCHIVE_M
@public
#endif
	OFStream *_Nullable _lastReturnedStream;



}

/**
 * @brief The encoding to use for the archive. Defaults to UTF-8.
 */
@property (nonatomic) OFStringEncoding encoding;

/**
 * @brief Creates a new OFZooArchive object with the specified stream.
 *
 * @param stream A stream from which the Zoo archive will be read.
 *		 For read mode, this needs to be an OFSeekableStream.
 * @param mode The mode for the Zoo file. The only valid mode is "r" for
 *	       reading.
 * @return A new, autoreleased OFZooArchive
 */
+ (instancetype)archiveWithStream: (OFStream *)stream mode: (OFString *)mode;

/**
 * @brief Creates a new OFZooArchive object with the specified file.
 *
 * @param IRI The IRI to the Zoo file
 * @param mode The mode for the Zoo file. The only valid mode is "r" for
 *	       reading.
 * @return A new, autoreleased OFZooArchive
 */
+ (instancetype)archiveWithIRI: (OFIRI *)IRI mode: (OFString *)mode;

- (instancetype)init OF_UNAVAILABLE;

/**
 * @brief Initializes an already allocated OFZooArchive object with the
 *	  specified stream.
 *
 * @param stream A stream from which the Zoo archive will be read.
 *		 For read mode, this needs to be an OFSeekableStream.
 * @param mode The mode for the Zoo file. The only valid mode is "r" for
 *	       reading.
 * @return An initialized OFZooArchive
 */
- (instancetype)initWithStream: (OFStream *)stream
			  mode: (OFString *)mode OF_DESIGNATED_INITIALIZER;

/**
 * @brief Initializes an already allocated OFZooArchive object with the
 *	  specified file.
 *
 * @param IRI The IRI to the Zoo file
 * @param mode The mode for the Zoo file. The only valid mode is "r" for
 *	       reading.
 * @return An initialized OFZooArchive
 */
- (instancetype)initWithIRI: (OFIRI *)IRI mode: (OFString *)mode;

/**
 * @brief Returns the next entry from the Zoo archive or `nil` if all entries
 *	  have been read.
 *
 * @note This is only available in read mode.
 *
 * @warning Calling @ref nextEntry will invalidate all streams returned by
 *	    @ref streamForReadingCurrentEntry! Reading from an invalidated

 *	    stream will throw an @ref OFReadFailedException!

 *
 * @return The next entry from the Zoo archive or `nil` if all entries have
 *	   been read
 * @throw OFInvalidFormatException The archive's format is invalid


 * @throw OFTruncatedDataException The archive was truncated
 */
- (nullable OFZooArchiveEntry *)nextEntry;

/**
 * @brief Returns a stream for reading the current entry.
 *
 * @note This is only available in read mode.
 *
 * @note The returned stream conforms to @ref OFReadyForReadingObserving if the
 *	 underlying stream does so, too.
 *
 * @return A stream for reading the current entry
 * @throw OFSeekFailedException Seeking to the data in the archive failed
 */
- (OFStream *)streamForReadingCurrentEntry;


























/**
 * @brief Closes the OFZooArchive.
 *
 * @throw OFNotOpenException The archive is not open
 */
- (void)close;
@end

OF_ASSUME_NONNULL_END







>





<
<











>
>





>
>
>












|
|








|
|












|
|










|
|











|
>
|
>




>
>

















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>









10
11
12
13
14
15
16
17
18
19
20
21
22


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
 * 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 "OFObject.h"
#import "OFSeekableStream.h"
#import "OFString.h"
#import "OFZooArchiveEntry.h"

OF_ASSUME_NONNULL_BEGIN



/**
 * @class OFZooArchive OFZooArchive.h ObjFW/OFZooArchive.h
 *
 * @brief A class for accessing and manipulating Zoo files.
 */
OF_SUBCLASSING_RESTRICTED
@interface OFZooArchive: OFObject
{
	OF_KINDOF(OFStream *) _stream;
	uint_least8_t _mode;
	OFStringEncoding _encoding;
	uint16_t _minVersionNeeded;
	uint8_t _headerType;
	OFZooArchiveEntry *_Nullable _currentEntry;
#ifdef OF_ZOO_ARCHIVE_M
@public
#endif
	OFStream *_Nullable _lastReturnedStream;
@protected
	OFStreamOffset _lastHeaderOffset;
	size_t _lastHeaderLength;
}

/**
 * @brief The encoding to use for the archive. Defaults to UTF-8.
 */
@property (nonatomic) OFStringEncoding encoding;

/**
 * @brief Creates a new OFZooArchive object with the specified stream.
 *
 * @param stream A stream from which the Zoo archive will be read.
 *		 For read mode, this needs to be an OFSeekableStream.
 * @param mode The mode for the Zoo file. Valid modes are "r" for reading and
 *	       "w" for creating a new file.
 * @return A new, autoreleased OFZooArchive
 */
+ (instancetype)archiveWithStream: (OFStream *)stream mode: (OFString *)mode;

/**
 * @brief Creates a new OFZooArchive object with the specified file.
 *
 * @param IRI The IRI to the Zoo file
 * @param mode The mode for the Zoo file. Valid modes are "r" for reading and
 *	       "w" for creating a new file.
 * @return A new, autoreleased OFZooArchive
 */
+ (instancetype)archiveWithIRI: (OFIRI *)IRI mode: (OFString *)mode;

- (instancetype)init OF_UNAVAILABLE;

/**
 * @brief Initializes an already allocated OFZooArchive object with the
 *	  specified stream.
 *
 * @param stream A stream from which the Zoo archive will be read.
 *		 For read mode, this needs to be an OFSeekableStream.
 * @param mode The mode for the Zoo file. Valid modes are "r" for reading and
 *	       "w" for creating a new file.
 * @return An initialized OFZooArchive
 */
- (instancetype)initWithStream: (OFStream *)stream
			  mode: (OFString *)mode OF_DESIGNATED_INITIALIZER;

/**
 * @brief Initializes an already allocated OFZooArchive object with the
 *	  specified file.
 *
 * @param IRI The IRI to the Zoo file
 * @param mode The mode for the Zoo file. Valid modes is "r" for reading and
 *	       "w" for creating a new file.
 * @return An initialized OFZooArchive
 */
- (instancetype)initWithIRI: (OFIRI *)IRI mode: (OFString *)mode;

/**
 * @brief Returns the next entry from the Zoo archive or `nil` if all entries
 *	  have been read.
 *
 * @note This is only available in read mode.
 *
 * @warning Calling @ref nextEntry will invalidate all streams returned by
 *	    @ref streamForReadingCurrentEntry or
 *	    @ref streamForWritingEntry:! Reading from or writing to an
 *	    invalidated stream will throw an @ref OFReadFailedException or
 *	    @ref OFWriteFailedException!
 *
 * @return The next entry from the Zoo archive or `nil` if all entries have
 *	   been read
 * @throw OFInvalidFormatException The archive's format is invalid
 * @throw OFUnsupportedVersionException The archive's format is of an
 *					unsupported version
 * @throw OFTruncatedDataException The archive was truncated
 */
- (nullable OFZooArchiveEntry *)nextEntry;

/**
 * @brief Returns a stream for reading the current entry.
 *
 * @note This is only available in read mode.
 *
 * @note The returned stream conforms to @ref OFReadyForReadingObserving if the
 *	 underlying stream does so, too.
 *
 * @return A stream for reading the current entry
 * @throw OFSeekFailedException Seeking to the data in the archive failed
 */
- (OFStream *)streamForReadingCurrentEntry;

/**
 * @brief Returns a stream for writing the specified entry.
 *
 * @note This is only available in write and append mode.
 *
 * @note The returned stream conforms to @ref OFReadyForWritingObserving if the
 *	 underlying stream does so, too.
 *
 * @warning Calling @ref streamForWritingEntry: will invalidate all streams
 *	    returned by @ref streamForReadingCurrentEntry or
 *	    @ref streamForWritingEntry:! Reading from or writing to an
 *	    invalidated stream will throw an @ref OFReadFailedException or
 *	    @ref OFWriteFailedException!
 *
 * @param entry The entry for which a stream for writing should be returned.@n
 *	        The following parts of the specified entry will be ignored:
 *	          * The header type.
 *	          * The minimum version needed.
 *	          * The compressed size.
 *	          * The uncompressed size.
 *	          * The CRC16.
 * @return A stream for writing the specified entry
 */
- (OFStream *)streamForWritingEntry: (OFZooArchiveEntry *)entry;

/**
 * @brief Closes the OFZooArchive.
 *
 * @throw OFNotOpenException The archive is not open
 */
- (void)close;
@end

OF_ASSUME_NONNULL_END

Modified src/OFZooArchive.m from [1d909708d8] to [02c033a0c2].

12
13
14
15
16
17
18


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

37
38

39
40
41

42
43
44
45
46
47
48
 * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
 * file.
 */

#define OF_ZOO_ARCHIVE_M

#include "config.h"



#import "OFZooArchive.h"
#import "OFZooArchiveEntry.h"
#import "OFZooArchiveEntry+Private.h"
#import "OFCRC16.h"
#import "OFIRI.h"
#import "OFIRIHandler.h"
#import "OFKernelEventObserver.h"
#import "OFLHADecompressingStream.h"
#import "OFSeekableStream.h"
#import "OFStream.h"
#import "OFString.h"

#import "OFChecksumMismatchException.h"
#import "OFInvalidArgumentException.h"
#import "OFInvalidFormatException.h"
#import "OFNotImplementedException.h"
#import "OFNotOpenException.h"

#import "OFTruncatedDataException.h"
#import "OFUnsupportedVersionException.h"


enum {
	modeRead

};

OF_DIRECT_MEMBERS
@interface OFZooArchive ()
- (void)of_readArchiveHeader;
@end








>
>


















>


>


|
>







12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 * LICENSE.GPLv2 or LICENSE.GPLv3 respectively included in the packaging of this
 * file.
 */

#define OF_ZOO_ARCHIVE_M

#include "config.h"

#include <errno.h>

#import "OFZooArchive.h"
#import "OFZooArchiveEntry.h"
#import "OFZooArchiveEntry+Private.h"
#import "OFCRC16.h"
#import "OFIRI.h"
#import "OFIRIHandler.h"
#import "OFKernelEventObserver.h"
#import "OFLHADecompressingStream.h"
#import "OFSeekableStream.h"
#import "OFStream.h"
#import "OFString.h"

#import "OFChecksumMismatchException.h"
#import "OFInvalidArgumentException.h"
#import "OFInvalidFormatException.h"
#import "OFNotImplementedException.h"
#import "OFNotOpenException.h"
#import "OFOutOfRangeException.h"
#import "OFTruncatedDataException.h"
#import "OFUnsupportedVersionException.h"
#import "OFWriteFailedException.h"

enum {
	modeRead,
	modeWrite
};

OF_DIRECT_MEMBERS
@interface OFZooArchive ()
- (void)of_readArchiveHeader;
@end

58
59
60
61
62
63
64





















65
66
67
68
69
70
71
	bool _atEndOfStream;
}

- (instancetype)of_initWithArchive: (OFZooArchive *)archive
			    stream: (OFStream *)stream
			     entry: (OFZooArchiveEntry *)entry;
@end






















@implementation OFZooArchive
@synthesize encoding = _encoding;

+ (instancetype)archiveWithStream: (OFStream *)stream mode: (OFString *)mode
{
	return [[[self alloc] initWithStream: stream mode: mode] autorelease];







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
	bool _atEndOfStream;
}

- (instancetype)of_initWithArchive: (OFZooArchive *)archive
			    stream: (OFStream *)stream
			     entry: (OFZooArchiveEntry *)entry;
@end

OF_DIRECT_MEMBERS
@interface OFZooArchiveFileWriteStream: OFStream <OFReadyForWritingObserving>
{
	OFZooArchive *_archive;
	OFMutableZooArchiveEntry *_entry;
	OFStringEncoding _encoding;
	OFSeekableStream *_stream;
	OFStreamOffset *_lastHeaderOffset;
	size_t *_lastHeaderLength;
	uint32_t _bytesWritten;
	uint16_t _CRC16;
}

- (instancetype)of_initWithArchive: (OFZooArchive *)archive
			    stream: (OFSeekableStream *)stream
			     entry: (OFZooArchiveEntry *)entry
			  encoding: (OFStringEncoding)encoding
		  lastHeaderOffset: (OFStreamOffset *)lastHeaderOffset
		  lastHeaderLength: (size_t *)lastHeaderLength;
@end

@implementation OFZooArchive
@synthesize encoding = _encoding;

+ (instancetype)archiveWithStream: (OFStream *)stream mode: (OFString *)mode
{
	return [[[self alloc] initWithStream: stream mode: mode] autorelease];
84
85
86
87
88
89
90
91


92
93
94
95
96
97



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
- (instancetype)initWithStream: (OFStream *)stream mode: (OFString *)mode
{
	self = [super init];

	@try {
		if ([mode isEqual: @"r"])
			_mode = modeRead;
		else if ([mode isEqual: @"w"] || [mode isEqual: @"a"])


			@throw [OFNotImplementedException
			    exceptionWithSelector: _cmd
					   object: nil];
		else
			@throw [OFInvalidArgumentException exception];




		_stream = [stream retain];
		_encoding = OFStringEncodingUTF8;

		if (_mode == modeRead) {
			if (![stream isKindOfClass: [OFSeekableStream class]])
				@throw [OFInvalidArgumentException exception];

			[self of_readArchiveHeader];
		}
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}

- (instancetype)initWithIRI: (OFIRI *)IRI mode: (OFString *)mode
{
	void *pool = objc_autoreleasePoolPush();
	OFStream *stream;

	@try {
		if ([mode isEqual: @"a"])
			stream = [OFIRIHandler openItemAtIRI: IRI mode: @"r+"];
		else
			stream = [OFIRIHandler openItemAtIRI: IRI mode: mode];
	} @catch (id e) {
		[self release];
		@throw e;
	}








|
>
>






>
>
>



|
<
<
<

<














|
|







110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132



133

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
- (instancetype)initWithStream: (OFStream *)stream mode: (OFString *)mode
{
	self = [super init];

	@try {
		if ([mode isEqual: @"r"])
			_mode = modeRead;
		else if ([mode isEqual: @"w"])
			_mode = modeWrite;
		else if ([mode isEqual: @"a"])
			@throw [OFNotImplementedException
			    exceptionWithSelector: _cmd
					   object: nil];
		else
			@throw [OFInvalidArgumentException exception];

		if (![stream isKindOfClass: [OFSeekableStream class]])
			@throw [OFInvalidArgumentException exception];

		_stream = [stream retain];
		_encoding = OFStringEncodingUTF8;

		if (_mode == modeRead)



			[self of_readArchiveHeader];

	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}

- (instancetype)initWithIRI: (OFIRI *)IRI mode: (OFString *)mode
{
	void *pool = objc_autoreleasePoolPush();
	OFStream *stream;

	@try {
		if ([mode isEqual: @"w"])
			stream = [OFIRIHandler openItemAtIRI: IRI mode: @"w+"];
		else
			stream = [OFIRIHandler openItemAtIRI: IRI mode: mode];
	} @catch (id e) {
		[self release];
		@throw e;
	}

155
156
157
158
159
160
161



162


163


164
165
166
167
168
169
170
		@throw [OFInvalidFormatException exception];

	firstFileOffset = [_stream readLittleEndianInt32];

	if ([_stream readLittleEndianInt32] != ~(uint32_t)(firstFileOffset - 1))
		@throw [OFInvalidFormatException exception];




	/* Version */


	[_stream readBigEndianInt16];



	[_stream seekToOffset: firstFileOffset whence: OFSeekSet];
}

- (OFZooArchiveEntry *)nextEntry
{
	if (_mode != modeRead)







>
>
>
|
>
>
|
>
>







182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
		@throw [OFInvalidFormatException exception];

	firstFileOffset = [_stream readLittleEndianInt32];

	if ([_stream readLittleEndianInt32] != ~(uint32_t)(firstFileOffset - 1))
		@throw [OFInvalidFormatException exception];

	if ((_minVersionNeeded = [_stream readBigEndianInt16]) > 0x201)
		@throw [OFUnsupportedVersionException exceptionWithVersion:
		    [OFString stringWithFormat: @"%" PRIu8 @".%" PRIu8,
						_minVersionNeeded >> 8,
						_minVersionNeeded & 0xFF]];

	if ((_headerType = [_stream readInt8]) > 1)
		@throw [OFUnsupportedVersionException exceptionWithVersion:
		    [OFString stringWithFormat: @"%" PRIu8, _headerType]];

	[_stream seekToOffset: firstFileOffset whence: OFSeekSet];
}

- (OFZooArchiveEntry *)nextEntry
{
	if (_mode != modeRead)
202
203
204
205
206
207
208



















































































209
210
211
212
213
214
215
216
217
218
219

220











221




222
223
224
225
226
227
228
	_lastReturnedStream = [[[OFZooArchiveFileReadStream alloc]
	    of_initWithArchive: self
			stream: _stream
			 entry: _currentEntry] autorelease];

	return _lastReturnedStream;
}




















































































- (void)close
{
	if (_stream == nil)
		@throw [OFNotOpenException exceptionWithObject: self];

	@try {
		[_lastReturnedStream close];
	} @catch (OFNotOpenException *e) {
		/* Might have already been closed by the user - that's fine. */
	}













	_lastReturnedStream = nil;





	[_stream release];
	_stream = nil;
}
@end

@implementation OFZooArchiveFileReadStream







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>











>

>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>







236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
	_lastReturnedStream = [[[OFZooArchiveFileReadStream alloc]
	    of_initWithArchive: self
			stream: _stream
			 entry: _currentEntry] autorelease];

	return _lastReturnedStream;
}

- (void)of_fixUpLastHeader
{
	OFStreamOffset offset;
	unsigned char *buffer;

	if (_lastHeaderOffset == 0)
		return;

	offset = [_stream seekToOffset: 0 whence: OFSeekCurrent];

	if (offset < 0 || offset > UINT32_MAX || _lastHeaderLength < 56)
		@throw [OFOutOfRangeException exception];

	[_stream seekToOffset: _lastHeaderOffset whence: OFSeekSet];
	buffer = OFAllocMemory(1, _lastHeaderLength);
	@try {
		uint16_t tmp16;
		uint32_t tmp32;

		[_stream readIntoBuffer: buffer exactLength: _lastHeaderLength];

		tmp32 = OFToLittleEndian32((uint32_t)offset);
		memcpy(buffer + 6, &tmp32, 4);

		tmp16 = OFToLittleEndian16(
		    OFCRC16(0, buffer, _lastHeaderLength));
		memcpy(buffer + 54, &tmp16, 2);

		[_stream seekToOffset: _lastHeaderOffset whence: OFSeekSet];
		[_stream writeBuffer: buffer length: _lastHeaderLength];

		[_stream seekToOffset: offset whence: OFSeekSet];
	} @finally {
		OFFreeMemory(buffer);
	}
}

- (OFStream *)streamForWritingEntry: (OFZooArchiveEntry *)entry
{
	if (_mode != modeWrite)
		@throw [OFInvalidArgumentException exception];

	if (entry.compressionMethod != 0)
		@throw [OFNotImplementedException exceptionWithSelector: _cmd
								 object: self];

	if (_lastHeaderOffset == 0) {
		/* First file - write header. */
		[_stream writeBuffer: "ObjFW Zoo Archive.\x1F" length: 20];
		[_stream writeLittleEndianInt32: 0xFDC4A7DC];
		[_stream writeLittleEndianInt32: 42];
		[_stream writeLittleEndianInt32: -42];
		/* TODO: Increase to 0x201 once we add compressed files. */
		[_stream writeBigEndianInt16: 0x200];
		/* Header type */
		[_stream writeInt8: 1];
		/* Archive comment offset */
		[_stream writeLittleEndianInt32: 0];
		/* Archive comment length */
		[_stream writeLittleEndianInt16: 0];
		/* Version flag */
		[_stream writeInt8: 0];
	} else
		[self of_fixUpLastHeader];

	@try {
		[_lastReturnedStream close];
	} @catch (OFNotOpenException *e) {
		/* Might have already been closed by the user - that's fine. */
	}
	_lastReturnedStream = nil;

	_lastReturnedStream = [[[OFZooArchiveFileWriteStream alloc]
	    of_initWithArchive: self
			stream: _stream
			 entry: entry
		      encoding: _encoding
	      lastHeaderOffset: &_lastHeaderOffset
	      lastHeaderLength: &_lastHeaderLength] autorelease];

	return  _lastReturnedStream;
}

- (void)close
{
	if (_stream == nil)
		@throw [OFNotOpenException exceptionWithObject: self];

	@try {
		[_lastReturnedStream close];
	} @catch (OFNotOpenException *e) {
		/* Might have already been closed by the user - that's fine. */
	}
	_lastReturnedStream = nil;

	/*
	 * Zoo archives should be terminated with an entry that has a next
	 * header offset of 0.
	 */
	if (_mode == modeWrite) {
		static const unsigned char header[56] = {
			0xDC, 0xA7, 0xC4, 0xFD, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0xFC, 0x83
		};

		[self of_fixUpLastHeader];

		[_stream writeBuffer: header length: sizeof(header)];
	}

	[_stream release];
	_stream = nil;
}
@end

@implementation OFZooArchiveFileReadStream
345
346
347
348
349
350
351
352
353
354
355


























































































































		@throw [OFNotOpenException exceptionWithObject: self];

	[_stream release];
	_stream = nil;

	[_decompressedStream release];
	_decompressedStream = nil;

	[super close];
}
@end





































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
		@throw [OFNotOpenException exceptionWithObject: self];

	[_stream release];
	_stream = nil;

	[_decompressedStream release];
	_decompressedStream = nil;

	[super close];
}
@end

@implementation OFZooArchiveFileWriteStream
- (instancetype)of_initWithArchive: (OFZooArchive *)archive
			    stream: (OFSeekableStream *)stream
			     entry: (OFZooArchiveEntry *)entry
			  encoding: (OFStringEncoding)encoding
		  lastHeaderOffset: (OFStreamOffset *)lastHeaderOffset
		  lastHeaderLength: (size_t *)lastHeaderLength
{
	self = [super init];

	@try {
		_archive = [archive retain];
		_entry = [entry mutableCopy];
		_encoding = encoding;
		_lastHeaderOffset = lastHeaderOffset;
		_lastHeaderLength = lastHeaderLength;

		*_lastHeaderOffset = [stream seekToOffset: 0
						   whence: OFSeekCurrent];
		*_lastHeaderLength = [_entry of_writeToStream: stream
						     encoding: _encoding];

		/*
		 * Retain stream last, so that -[close] called by -[dealloc]
		 * doesn't write in case of error.
		 */
		_stream = [stream retain];
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}

- (void)dealloc
{
	if (_stream != nil)
		[self close];

	[_entry release];

	if (_archive->_lastReturnedStream == self)
		_archive->_lastReturnedStream = nil;

	[_archive release];

	[super dealloc];
}

- (size_t)lowlevelWriteBuffer: (const void *)buffer length: (size_t)length
{
	if (_stream == nil)
		@throw [OFNotOpenException exceptionWithObject: self];

	if (UINT32_MAX - _bytesWritten < length)
		@throw [OFOutOfRangeException exception];

	@try {
		[_stream writeBuffer: buffer length: length];
	} @catch (OFWriteFailedException *e) {
		OFEnsure(e.bytesWritten <= length);

		_bytesWritten += (uint32_t)e.bytesWritten;
		_CRC16 = OFCRC16(_CRC16, buffer, e.bytesWritten);

		if (e.errNo == EWOULDBLOCK || e.errNo == EAGAIN)
			return e.bytesWritten;

		@throw e;
	}

	_bytesWritten += (uint32_t)length;
	_CRC16 = OFCRC16(_CRC16, buffer, length);

	return length;
}

- (bool)lowlevelIsAtEndOfStream
{
	if (_stream == nil)
		@throw [OFNotOpenException exceptionWithObject: self];

	return _stream.atEndOfStream;
}

- (int)fileDescriptorForWriting
{
	return ((id <OFReadyForWritingObserving>)_stream)
	    .fileDescriptorForWriting;
}

- (void)close
{
	OFStreamOffset offset;

	if (_stream == nil)
		@throw [OFNotOpenException exceptionWithObject: self];

	_entry.uncompressedSize = _bytesWritten;
	_entry.compressedSize = _bytesWritten;
	_entry.CRC16 = _CRC16;

	offset = [_stream seekToOffset: 0 whence: OFSeekCurrent];

	if (offset > UINT32_MAX)
		@throw [OFOutOfRangeException exception];

	[_stream seekToOffset: *_lastHeaderOffset whence: OFSeekSet];
	_entry->_dataOffset = (uint32_t)offset;

	OFEnsure([_entry of_writeToStream: _stream
				 encoding: _encoding] == *_lastHeaderLength);
	[_stream seekToOffset: offset whence: OFSeekSet];

	[_stream release];
	_stream = nil;

	[super close];
}
@end

Modified src/OFZooArchiveEntry+Private.h from [4d0560d4d7] to [e4afeb0b7b].

10
11
12
13
14
15
16

17
18
19
20
21
22
23
24


25
26
27
 * 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 "OFZooArchive.h"


OF_ASSUME_NONNULL_BEGIN

@interface OFZooArchiveEntry ()
- (instancetype)of_init OF_METHOD_FAMILY(init);
- (nullable instancetype)of_initWithStream: (OF_KINDOF(OFStream *))stream
				  encoding: (OFStringEncoding)encoding
    OF_METHOD_FAMILY(init) OF_DIRECT;


@end

OF_ASSUME_NONNULL_END







>





|


>
>



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 * 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 "OFZooArchive.h"
#import "OFSeekableStream.h"

OF_ASSUME_NONNULL_BEGIN

@interface OFZooArchiveEntry ()
- (instancetype)of_init OF_METHOD_FAMILY(init);
- (nullable instancetype)of_initWithStream: (OFSeekableStream *)stream
				  encoding: (OFStringEncoding)encoding
    OF_METHOD_FAMILY(init) OF_DIRECT;
- (size_t)of_writeToStream: (OFSeekableStream *)stream
		  encoding: (OFStringEncoding)encoding;
@end

OF_ASSUME_NONNULL_END

Modified src/OFZooArchiveEntry.m from [ce552a79a7] to [b94a906de8].

13
14
15
16
17
18
19

20
21
22
23
24
25
26

27
28
29
30
31
32
33
 * file.
 */

#include "config.h"

#import "OFZooArchiveEntry.h"
#import "OFZooArchiveEntry+Private.h"

#import "OFDate.h"
#import "OFNumber.h"
#import "OFSeekableStream.h"
#import "OFStream.h"
#import "OFString.h"

#import "OFInvalidFormatException.h"

#import "OFUnsupportedVersionException.h"

@implementation OFZooArchiveEntry
- (instancetype)init
{
	OF_INVALID_INIT_METHOD
}







>



<



>







13
14
15
16
17
18
19
20
21
22
23

24
25
26
27
28
29
30
31
32
33
34
 * file.
 */

#include "config.h"

#import "OFZooArchiveEntry.h"
#import "OFZooArchiveEntry+Private.h"
#import "OFData.h"
#import "OFDate.h"
#import "OFNumber.h"
#import "OFSeekableStream.h"

#import "OFString.h"

#import "OFInvalidFormatException.h"
#import "OFOutOfRangeException.h"
#import "OFUnsupportedVersionException.h"

@implementation OFZooArchiveEntry
- (instancetype)init
{
	OF_INVALID_INIT_METHOD
}
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

83





84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107

108
109
110

111
112
113
114
115
116
117
		[self release];
		@throw e;
	}

	return self;
}

- (instancetype)of_initWithStream: (OF_KINDOF(OFStream *))stream
			 encoding: (OFStringEncoding)encoding
{
	self = [super init];

	@try {
		void *pool = objc_autoreleasePoolPush();
		char fileNameBuffer[13];
		uint32_t commentOffset;
		uint16_t commentLength;

		if ([stream readLittleEndianInt32] != 0xFDC4A7DC)
			@throw [OFInvalidFormatException exception];

		if ((_headerType = [stream readInt8]) > 2)
			@throw [OFUnsupportedVersionException
			    exceptionWithVersion: [OFString
			    stringWithFormat: @"%u", _headerType]];

		_compressionMethod = [stream readInt8];
		_nextHeaderOffset = [stream readLittleEndianInt32];

		if (_nextHeaderOffset == 0) {
			[self release];
			return nil;
		}

		_dataOffset = [stream readLittleEndianInt32];
		_lastModifiedFileDate = [stream readLittleEndianInt16];
		_lastModifiedFileTime = [stream readLittleEndianInt16];
		_CRC16 = [stream readLittleEndianInt16];
		_uncompressedSize = [stream readLittleEndianInt32];
		_compressedSize = [stream readLittleEndianInt32];

		_minVersionNeeded = [stream readBigEndianInt16];





		_deleted = [stream readInt8];
		/*
		 * File structure, whatever that is meant to be. Seems to
		 * always be 0.
		 */
		[stream readInt8];
		commentOffset = [stream readLittleEndianInt32];
		commentLength = [stream readLittleEndianInt16];

		[stream readIntoBuffer: fileNameBuffer exactLength: 13];
		if (fileNameBuffer[12] != '\0')
			fileNameBuffer[12] = '\0';

		if (_headerType >= 2) {
			uint16_t extraLength = [stream readLittleEndianInt16];
			uint8_t fileNameLength, directoryNameLength;

			if (extraLength < 10)
				@throw [OFInvalidFormatException exception];

			_timeZone = [stream readInt8];
			/* CRC16 of the header */
			[stream readLittleEndianInt16];


			fileNameLength = [stream readInt8];
			directoryNameLength = [stream readInt8];
			extraLength -= 2;


			if (fileNameLength > 0) {
				if (extraLength < fileNameLength)
					@throw [OFInvalidFormatException
					    exception];

				_fileName = [[stream







|
















|















>
|
>
>
>
>
>















|
<
<
<





>
|
|
|
>







44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
		[self release];
		@throw e;
	}

	return self;
}

- (instancetype)of_initWithStream: (OFSeekableStream *)stream
			 encoding: (OFStringEncoding)encoding
{
	self = [super init];

	@try {
		void *pool = objc_autoreleasePoolPush();
		char fileNameBuffer[13];
		uint32_t commentOffset;
		uint16_t commentLength;

		if ([stream readLittleEndianInt32] != 0xFDC4A7DC)
			@throw [OFInvalidFormatException exception];

		if ((_headerType = [stream readInt8]) > 2)
			@throw [OFUnsupportedVersionException
			    exceptionWithVersion: [OFString
			    stringWithFormat: @"%" PRIu8, _headerType]];

		_compressionMethod = [stream readInt8];
		_nextHeaderOffset = [stream readLittleEndianInt32];

		if (_nextHeaderOffset == 0) {
			[self release];
			return nil;
		}

		_dataOffset = [stream readLittleEndianInt32];
		_lastModifiedFileDate = [stream readLittleEndianInt16];
		_lastModifiedFileTime = [stream readLittleEndianInt16];
		_CRC16 = [stream readLittleEndianInt16];
		_uncompressedSize = [stream readLittleEndianInt32];
		_compressedSize = [stream readLittleEndianInt32];

		if ((_minVersionNeeded = [stream readBigEndianInt16]) > 0x201)
			@throw [OFUnsupportedVersionException
			    exceptionWithVersion: [OFString stringWithFormat:
			    @"%" PRIu8 @".%" PRIu8,
			    _minVersionNeeded >> 8, _minVersionNeeded & 0xFF]];

		_deleted = [stream readInt8];
		/*
		 * File structure, whatever that is meant to be. Seems to
		 * always be 0.
		 */
		[stream readInt8];
		commentOffset = [stream readLittleEndianInt32];
		commentLength = [stream readLittleEndianInt16];

		[stream readIntoBuffer: fileNameBuffer exactLength: 13];
		if (fileNameBuffer[12] != '\0')
			fileNameBuffer[12] = '\0';

		if (_headerType >= 2) {
			uint16_t extraLength = [stream readLittleEndianInt16];
			uint8_t fileNameLength = 0, directoryNameLength = 0;




			_timeZone = [stream readInt8];
			/* CRC16 of the header */
			[stream readLittleEndianInt16];

			if (extraLength >= 2) {
				fileNameLength = [stream readInt8];
				directoryNameLength = [stream readInt8];
				extraLength -= 2;
			}

			if (fileNameLength > 0) {
				if (extraLength < fileNameLength)
					@throw [OFInvalidFormatException
					    exception];

				_fileName = [[stream
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
{
	return [self retain];
}

- (id)mutableCopy
{
	OFZooArchiveEntry *copy = [[OFMutableZooArchiveEntry alloc]
	    initWithFileName: _fileName];

	@try {
		copy->_headerType = _headerType;
		copy->_compressionMethod = _compressionMethod;
		copy->_nextHeaderOffset = _nextHeaderOffset;
		copy->_dataOffset = _dataOffset;
		copy->_lastModifiedFileDate = _lastModifiedFileDate;
		copy->_lastModifiedFileTime = _lastModifiedFileTime;
		copy->_CRC16 = _CRC16;
		copy->_uncompressedSize = _uncompressedSize;
		copy->_compressedSize = _compressedSize;
		copy->_minVersionNeeded = _minVersionNeeded;
		copy->_deleted = _deleted;
		copy->_fileComment = [_fileComment copy];
		copy->_directoryName = [_directoryName copy];
		copy->_operatingSystemIdentifier = _operatingSystemIdentifier;
		copy->_POSIXPermissions = [_POSIXPermissions retain];
		copy->_timeZone = _timeZone;
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return self;
}

- (uint8_t)headerType
{
	return _headerType;
}








|














<








|







199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
{
	return [self retain];
}

- (id)mutableCopy
{
	OFZooArchiveEntry *copy = [[OFMutableZooArchiveEntry alloc]
	    initWithFileName: self.fileName];

	@try {
		copy->_headerType = _headerType;
		copy->_compressionMethod = _compressionMethod;
		copy->_nextHeaderOffset = _nextHeaderOffset;
		copy->_dataOffset = _dataOffset;
		copy->_lastModifiedFileDate = _lastModifiedFileDate;
		copy->_lastModifiedFileTime = _lastModifiedFileTime;
		copy->_CRC16 = _CRC16;
		copy->_uncompressedSize = _uncompressedSize;
		copy->_compressedSize = _compressedSize;
		copy->_minVersionNeeded = _minVersionNeeded;
		copy->_deleted = _deleted;
		copy->_fileComment = [_fileComment copy];

		copy->_operatingSystemIdentifier = _operatingSystemIdentifier;
		copy->_POSIXPermissions = [_POSIXPermissions retain];
		copy->_timeZone = _timeZone;
	} @catch (id e) {
		[self release];
		@throw e;
	}

	return copy;
}

- (uint8_t)headerType
{
	return _headerType;
}

317
318
319
320
321
322
323








































































































































324
325
326
327
328
329
330
- (OFNumber *)timeZone
{
	if (_timeZone == 0x7F)
		return nil;

	return [OFNumber numberWithFloat: -(float)_timeZone / 4];
}









































































































































- (OFString *)description
{
	void *pool = objc_autoreleasePoolPush();
	OFString *ret = [OFString stringWithFormat:
	    @"<%@:\n"
	    @"\tFile name = %@\n"







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
- (OFNumber *)timeZone
{
	if (_timeZone == 0x7F)
		return nil;

	return [OFNumber numberWithFloat: -(float)_timeZone / 4];
}

- (size_t)of_writeToStream: (OFSeekableStream *)stream
		  encoding: (OFStringEncoding)encoding
{
	void *pool = objc_autoreleasePoolPush();
	OFMutableData *data = [OFMutableData dataWithCapacity: 56];
	OFStreamOffset offset = [stream seekToOffset: 0 whence: OFSeekCurrent];
	size_t dataOffsetIndex, commentOffsetIndex;
	char fileNameBuffer[13] = { 0 };
	uint8_t tmp8;
	uint16_t tmp16;
	uint32_t tmp32;
	size_t commentLength, fileNameLength, directoryNameLength, length;

	if (_uncompressedSize > UINT32_MAX || _compressedSize > UINT32_MAX)
		@throw [OFOutOfRangeException exception];

	commentLength = [_fileComment cStringLengthWithEncoding: encoding];
	if (commentLength > UINT16_MAX)
		@throw [OFOutOfRangeException exception];

	fileNameLength = [_fileName cStringLengthWithEncoding: encoding];
	if (fileNameLength > UINT8_MAX)
		@throw [OFOutOfRangeException exception];

	directoryNameLength =
	    [_directoryName cStringLengthWithEncoding: encoding];
	if (directoryNameLength > UINT8_MAX)
		@throw [OFOutOfRangeException exception];

	[data addItems: "\xDC\xA7\xC4\xFD" count: 4];
	/* Header type */
	[data addItem: "\x02"];
	[data addItem: &_compressionMethod];

	/* Next header offset filled when writing the next header */
	[data increaseCountBy: 4];
	/* Data offset is filled after generating the header */
	dataOffsetIndex = data.count;
	[data increaseCountBy: 4];

	tmp16 = OFToLittleEndian16(_lastModifiedFileDate);
	[data addItems: &tmp16 count: 2];
	tmp16 = OFToLittleEndian16(_lastModifiedFileTime);
	[data addItems: &tmp16 count: 2];
	tmp16 = OFToLittleEndian16(_CRC16);
	[data addItems: &tmp16 count: 2];

	tmp32 = OFToLittleEndian32((uint32_t)_uncompressedSize);
	[data addItems: &tmp32 count: 4];
	tmp32 = OFToLittleEndian32((uint32_t)_compressedSize);
	[data addItems: &tmp32 count: 4];

	/* Min version needed */
	/* TODO: Increase to 2.1 once we add compression. */
	[data addItems: "\x02\x00" count: 2];

	[data addItem: (_deleted ? "\x01" : "")];

	/*
	 * File structure, whatever that is meant to be.
	 * Seems to always be 0.
	 */
	[data addItem: ""];

	/* Comment offset is filled after generating the header */
	commentOffsetIndex = data.count;
	[data increaseCountBy: 4];
	tmp16 = OFToLittleEndian16((uint16_t)commentLength);
	[data addItems: &tmp16 count: 2];

	strncpy(fileNameBuffer, [_fileName cStringWithEncoding: encoding], 12);
	[data addItems: fileNameBuffer count: 13];

	/* Variable length. */
	tmp16 = OFToLittleEndian16(fileNameLength + directoryNameLength + 4 +
	    (_POSIXPermissions != nil ? 3 : 0));
	[data addItems: &tmp16 count: 2];

	[data addItem: &_timeZone];

	/*
	 * CRC16 is filled when writing the next header, as the CRC needs to
	 * include the next header offset.
	 */
	[data increaseCountBy: 2];

	tmp8 = (uint8_t)fileNameLength;
	[data addItem: &tmp8];
	tmp8 = (uint8_t)directoryNameLength;
	[data addItem: &tmp8];

	[data addItems: [_fileName cStringWithEncoding: encoding]
		 count: fileNameLength];
	[data addItems: [_directoryName cStringWithEncoding: encoding]
		 count: directoryNameLength];

	tmp16 = OFToLittleEndian16((uint16_t)_operatingSystemIdentifier);
	[data addItems: &tmp16 count: 2];

	if (_POSIXPermissions != nil) {
		unsigned short mode = _POSIXPermissions.unsignedShortValue;
		uint8_t attributes[3];

		attributes[0] = mode & 0xFF;
		attributes[1] = mode >> 8;
		attributes[2] = (1 << 6);

		[data addItems: attributes count: sizeof(attributes)];
	}

	/* Now that we have the entire header, we know where the data starts. */
	if (SIZE_MAX - data.count < commentLength)
		@throw [OFOutOfRangeException exception];

	if (offset < 0 || UINT32_MAX - (unsigned long long)offset <
	    data.count + commentLength)
		@throw [OFOutOfRangeException exception];

	tmp32 = OFToLittleEndian32(
	    (uint32_t)offset + (uint32_t)data.count + (uint32_t)commentLength);
	memcpy([data mutableItemAtIndex: dataOffsetIndex], &tmp32, 4);

	tmp32 = OFToLittleEndian32((uint32_t)offset + (uint32_t)data.count);
	memcpy([data mutableItemAtIndex: commentOffsetIndex], &tmp32, 4);

	[stream writeData: data];
	length = data.count;

	if (commentLength > 0)
		[stream writeString: _fileComment encoding: encoding];

	objc_autoreleasePoolPop(pool);

	return length;
}

- (OFString *)description
{
	void *pool = objc_autoreleasePoolPush();
	OFString *ret = [OFString stringWithFormat:
	    @"<%@:\n"
	    @"\tFile name = %@\n"