Skip to content

Instantly share code, notes, and snippets.

@tomkowz
Last active October 18, 2016 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomkowz/698183def6729aa700827b4f46884778 to your computer and use it in GitHub Desktop.
Save tomkowz/698183def6729aa700827b4f46884778 to your computer and use it in GitHub Desktop.
Vector implementation in Objective-C
#import "Vector.h"
@interface Vector ()
@property (nonatomic, assign) uint count;
@property (nonatomic, assign) size_t size;
@property (nonatomic, assign) void **storage;
@end
@implementation Vector
- (BOOL)isEmpty {
return _count == 0;
}
- (instancetype)init {
self = [super init];
if (self != nil) {
_count = 0;
_size = 2;
_storage = (malloc(_size * sizeof(NSObject *)));
}
return self;
}
- (void)append:(NSObject *)value {
[self insert:value at:_count];
[self increaseTheSizeIfNeeded];
}
- (NSObject *)at:(uint)index {
return (__bridge NSObject *)(_storage[index]);
}
- (void)insert:(NSObject *)value at:(uint)index {
if (index != _count) {
int i = _count;
while (i > index) {
_storage[i] = _storage[i - 1];
i = i - 1;
}
}
_storage[index] = (__bridge_retained void *)(value);
_count = _count + 1;
[self increaseTheSizeIfNeeded];
}
- (void)prepend:(NSObject *)value {
[self insert:value at:0];
}
- (NSObject *)pop {
uint idx = _count - 1;
NSObject *last = (__bridge NSObject *)(_storage[idx]);
[self deleteAt:idx];
return last;
}
- (void)deleteAt:(uint)index {
NSObject *obj = (__bridge NSObject *)(_storage[index]);
CFRelease((__bridge CFTypeRef)(obj));
for (int i = index + 1; i < _count; i++) {
_storage[i - 1] = _storage[i];
}
_count = _count - 1;
[self lowerTheSizeIfNeeded];
}
- (int)find:(NSObject *)value {
for (uint i = 0; i < _count; i++) {
if (_storage[i] == (__bridge void *)(value)) {
return i;
}
}
return -1;
}
// MARK: Private
- (void)lowerTheSizeIfNeeded {
if (_count + 1 <= _size * 0.25) {
[self resizeWithSize:_size / 2];
}
}
- (void)increaseTheSizeIfNeeded {
if (_count == _size) {
[self resizeWithSize:_size * 2];
}
}
- (void)resizeWithSize:(size_t)size {
_size = size;
_storage = realloc(_storage, size);
}
- (void)dealloc {
free(_storage);
}
// MARK: Debug
- (void)log {
NSLog(@"Vector Debug:");
NSLog(@"Count/Size: %d/%zu", _count, _size);
for (uint i = 0; i < _count; i++) {
NSLog(@"%@", _storage[i]);
}
NSLog(@"< END");
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment