APLevelDB.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. //
  2. // APLevelDB.m
  3. //
  4. // Created by Adam Preble on 1/23/12.
  5. // Copyright (c) 2012 Adam Preble. All rights reserved.
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in
  15. // all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. // THE SOFTWARE.
  24. //
  25. // Portions of APLevelDB are based on LevelDB-ObjC:
  26. // https://github.com/hoisie/LevelDB-ObjC
  27. // Specifically the SliceFromString/StringFromSlice macros, and the structure of
  28. // the enumeration methods. License for those potions follows:
  29. //
  30. // Copyright (c) 2011 Pave Labs
  31. //
  32. // Permission is hereby granted, free of charge, to any person obtaining a copy
  33. // of this software and associated documentation files (the "Software"), to deal
  34. // in the Software without restriction, including without limitation the rights
  35. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  36. // copies of the Software, and to permit persons to whom the Software is
  37. // furnished to do so, subject to the following conditions:
  38. //
  39. // The above copyright notice and this permission notice shall be included in
  40. // all copies or substantial portions of the Software.
  41. //
  42. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  43. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  44. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  45. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  46. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  47. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  48. // THE SOFTWARE.
  49. //
  50. #import "FirebaseDatabase/Sources/third_party/Wrap-leveldb/APLevelDB.h"
  51. #import "leveldb/db.h"
  52. #import "leveldb/options.h"
  53. #import "leveldb/write_batch.h"
  54. NSString * const APLevelDBErrorDomain = @"APLevelDBErrorDomain";
  55. #define SliceFromString(_string_) (leveldb::Slice((char *)[_string_ UTF8String], [_string_ lengthOfBytesUsingEncoding:NSUTF8StringEncoding]))
  56. #define StringFromSlice(_slice_) ([[NSString alloc] initWithBytes:_slice_.data() length:_slice_.size() encoding:NSUTF8StringEncoding])
  57. @interface APLevelDBWriteBatch : NSObject <APLevelDBWriteBatch> {
  58. @package
  59. leveldb::WriteBatch _batch;
  60. }
  61. @property (nonatomic, strong) APLevelDB *levelDB;
  62. - (id)initWithLevelDB:(APLevelDB *)levelDB;
  63. @end
  64. #pragma mark - APLevelDB
  65. @interface APLevelDB () {
  66. leveldb::DB *_db;
  67. leveldb::ReadOptions _readOptions;
  68. leveldb::WriteOptions _writeOptions;
  69. }
  70. - (id)initWithPath:(NSString *)path error:(NSError **)errorOut;
  71. + (leveldb::Options)defaultCreateOptions;
  72. @property (nonatomic, readonly) leveldb::DB *db;
  73. @end
  74. @implementation APLevelDB
  75. @synthesize path = _path;
  76. @synthesize db = _db;
  77. + (APLevelDB *)levelDBWithPath:(NSString *)path error:(NSError *__autoreleasing *)errorOut
  78. {
  79. return [[APLevelDB alloc] initWithPath:path error:errorOut];
  80. }
  81. - (id)initWithPath:(NSString *)path error:(NSError *__autoreleasing *)errorOut
  82. {
  83. if ((self = [super init]))
  84. {
  85. _path = path;
  86. leveldb::Options options = [[self class] defaultCreateOptions];
  87. leveldb::Status status = leveldb::DB::Open(options, [_path UTF8String], &_db);
  88. if (!status.ok())
  89. {
  90. if (errorOut)
  91. {
  92. NSString *statusString = [[NSString alloc] initWithCString:status.ToString().c_str() encoding:NSUTF8StringEncoding];
  93. *errorOut = [NSError errorWithDomain:APLevelDBErrorDomain
  94. code:0
  95. userInfo:[NSDictionary dictionaryWithObjectsAndKeys:statusString, NSLocalizedDescriptionKey, nil]];
  96. }
  97. return nil;
  98. }
  99. _writeOptions.sync = false;
  100. }
  101. return self;
  102. }
  103. - (void)close {
  104. if (_db != NULL) {
  105. delete _db;
  106. _db = NULL;
  107. }
  108. }
  109. - (void)dealloc
  110. {
  111. if (_db != NULL) {
  112. delete _db;
  113. _db = NULL;
  114. }
  115. }
  116. + (leveldb::Options)defaultCreateOptions
  117. {
  118. leveldb::Options options;
  119. options.create_if_missing = true;
  120. return options;
  121. }
  122. - (BOOL)setData:(NSData *)data forKey:(NSString *)key
  123. {
  124. leveldb::Slice keySlice = SliceFromString(key);
  125. leveldb::Slice valueSlice = leveldb::Slice((const char *)[data bytes], (size_t)[data length]);
  126. leveldb::Status status = _db->Put(_writeOptions, keySlice, valueSlice);
  127. return (status.ok() == true);
  128. }
  129. - (BOOL)setString:(NSString *)str forKey:(NSString *)key
  130. {
  131. // This could have been based on
  132. leveldb::Slice keySlice = SliceFromString(key);
  133. leveldb::Slice valueSlice = SliceFromString(str);
  134. leveldb::Status status = _db->Put(_writeOptions, keySlice, valueSlice);
  135. return (status.ok() == true);
  136. }
  137. - (NSData *)dataForKey:(NSString *)key
  138. {
  139. leveldb::Slice keySlice = SliceFromString(key);
  140. std::string valueCPPString;
  141. leveldb::Status status = _db->Get(_readOptions, keySlice, &valueCPPString);
  142. if (!status.ok())
  143. return nil;
  144. else
  145. return [NSData dataWithBytes:valueCPPString.data() length:valueCPPString.size()];
  146. }
  147. - (NSString *)stringForKey:(NSString *)key
  148. {
  149. leveldb::Slice keySlice = SliceFromString(key);
  150. std::string valueCPPString;
  151. leveldb::Status status = _db->Get(_readOptions, keySlice, &valueCPPString);
  152. // We assume (dangerously?) UTF-8 string encoding:
  153. if (!status.ok())
  154. return nil;
  155. else
  156. return [[NSString alloc] initWithBytes:valueCPPString.data() length:valueCPPString.size() encoding:NSUTF8StringEncoding];
  157. }
  158. - (BOOL)removeKey:(NSString *)key
  159. {
  160. leveldb::Slice keySlice = SliceFromString(key);
  161. leveldb::Status status = _db->Delete(_writeOptions, keySlice);
  162. return (status.ok() == true);
  163. }
  164. - (NSArray *)allKeys
  165. {
  166. NSMutableArray *keys = [NSMutableArray array];
  167. [self enumerateKeys:^(NSString *key, BOOL *stop) {
  168. [keys addObject:key];
  169. }];
  170. return keys;
  171. }
  172. - (void)enumerateKeysAndValuesAsStrings:(void (^)(NSString *key, NSString *value, BOOL *stop))block
  173. {
  174. [self enumerateKeysWithPrefix:@"" asStrings:block];
  175. }
  176. - (void)enumerateKeysWithPrefix:(NSString *)prefixString asStrings:(void (^)(NSString *, NSString *, BOOL *))block
  177. {
  178. @autoreleasepool {
  179. BOOL stop = NO;
  180. leveldb::Iterator* iter = _db->NewIterator(leveldb::ReadOptions());
  181. leveldb::Slice prefix = SliceFromString(prefixString);
  182. for (iter->Seek(prefix); iter->Valid(); iter->Next()) {
  183. leveldb::Slice key = iter->key(), value = iter->value();
  184. if (key.starts_with(prefix)) {
  185. NSString *k = StringFromSlice(key);
  186. NSString *v = [[NSString alloc] initWithBytes:value.data() length:value.size() encoding:NSUTF8StringEncoding];
  187. block(k, v, &stop);
  188. if (stop)
  189. break;
  190. } else {
  191. break;
  192. }
  193. }
  194. delete iter;
  195. }
  196. }
  197. - (void)enumerateKeys:(void (^)(NSString *key, BOOL *stop))block
  198. {
  199. [self enumerateKeysWithPrefix:@"" usingBlock:block];
  200. }
  201. - (void)enumerateKeysWithPrefix:(NSString *)prefixString usingBlock:(void (^)(NSString *key, BOOL *stop))block;
  202. {
  203. @autoreleasepool {
  204. BOOL stop = NO;
  205. leveldb::Slice prefix = SliceFromString(prefixString);
  206. leveldb::Iterator* iter = _db->NewIterator(leveldb::ReadOptions());
  207. for (iter->Seek(prefix); iter->Valid(); iter->Next()) {
  208. leveldb::Slice key = iter->key();
  209. if (key.starts_with(prefix)) {
  210. NSString *k = StringFromSlice(key);
  211. block(k, &stop);
  212. if (stop)
  213. break;
  214. } else {
  215. break;
  216. }
  217. }
  218. delete iter;
  219. }
  220. }
  221. - (void)enumerateKeysAndValuesAsData:(void (^)(NSString *key, NSData *data, BOOL *stop))block
  222. {
  223. [self enumerateKeysWithPrefix:@"" asData:block];
  224. }
  225. - (void)enumerateKeysWithPrefix:(NSString *)prefixString asData:(void (^)(NSString *, NSData *, BOOL *))block
  226. {
  227. @autoreleasepool {
  228. BOOL stop = NO;
  229. leveldb::Iterator* iter = _db->NewIterator(leveldb::ReadOptions());
  230. leveldb::Slice prefix = SliceFromString(prefixString);
  231. for (iter->Seek(prefix); iter->Valid(); iter->Next()) {
  232. leveldb::Slice key = iter->key(), value = iter->value();
  233. if (key.starts_with(prefix)) {
  234. NSString *k = StringFromSlice(key);
  235. NSData *data = [NSData dataWithBytes:value.data() length:value.size()];
  236. block(k, data, &stop);
  237. if (stop)
  238. break;
  239. } else {
  240. break;
  241. }
  242. }
  243. delete iter;
  244. }
  245. }
  246. - (NSUInteger)exactSizeFrom:(NSString *)from to:(NSString *)to {
  247. NSUInteger size = 0;
  248. leveldb::Iterator* iter = _db->NewIterator(leveldb::ReadOptions());
  249. leveldb::Slice fromSlice = SliceFromString(from);
  250. leveldb::Slice toSlice = SliceFromString(to);
  251. iter->Seek(fromSlice);
  252. while (iter->Valid() && iter->key().compare(toSlice) <= 0) {
  253. size += iter->value().size();
  254. iter->Next();
  255. }
  256. delete iter;
  257. return size;
  258. }
  259. - (NSUInteger)approximateSizeFrom:(NSString *)from to:(NSString *)to {
  260. leveldb::Range ranges[1];
  261. leveldb::Slice fromSlice = SliceFromString(from);
  262. leveldb::Slice toSlice = SliceFromString(to);
  263. ranges[0] = leveldb::Range(fromSlice, toSlice);
  264. uint64_t sizes[1];
  265. _db->GetApproximateSizes(ranges, 1, sizes);
  266. return (NSUInteger)sizes[0];
  267. }
  268. #pragma mark - Subscripting Support
  269. - (id)objectForKeyedSubscript:(id)key
  270. {
  271. if (![key respondsToSelector: @selector(componentsSeparatedByString:)])
  272. {
  273. [NSException raise:NSInvalidArgumentException format:@"key must be an NSString"];
  274. }
  275. return [self stringForKey:key];
  276. }
  277. - (void)setObject:(id)thing forKeyedSubscript:(id<NSCopying>)key
  278. {
  279. id idKey = (id) key;
  280. if (![idKey respondsToSelector: @selector(componentsSeparatedByString:)])
  281. {
  282. [NSException raise:NSInvalidArgumentException format:@"key must be NSString or NSData"];
  283. }
  284. if ([thing respondsToSelector:@selector(componentsSeparatedByString:)])
  285. [self setString:thing forKey:(NSString *)key];
  286. else if ([thing respondsToSelector:@selector(subdataWithRange:)])
  287. [self setData:thing forKey:(NSString *)key];
  288. else
  289. [NSException raise:NSInvalidArgumentException format:@"object must be NSString or NSData"];
  290. }
  291. #pragma mark - Atomic Updates
  292. - (id<APLevelDBWriteBatch>)beginWriteBatch
  293. {
  294. APLevelDBWriteBatch *batch = [[APLevelDBWriteBatch alloc] initWithLevelDB:self];
  295. return batch;
  296. }
  297. - (BOOL)commitWriteBatch:(id<APLevelDBWriteBatch>)theBatch
  298. {
  299. if (!theBatch)
  300. return NO;
  301. APLevelDBWriteBatch *batch = theBatch;
  302. leveldb::Status status;
  303. status = _db->Write(_writeOptions, &batch->_batch);
  304. return (status.ok() == true);
  305. }
  306. @end
  307. #pragma mark - APLevelDBIterator
  308. @interface APLevelDBIterator () {
  309. leveldb::Iterator *_iter;
  310. }
  311. @property (nonatomic, strong) APLevelDB *levelDB;
  312. @end
  313. @implementation APLevelDBIterator
  314. + (id)iteratorWithLevelDB:(APLevelDB *)db
  315. {
  316. APLevelDBIterator *iter = [[[self class] alloc] initWithLevelDB:db];
  317. return iter;
  318. }
  319. - (id)initWithLevelDB:(APLevelDB *)db
  320. {
  321. if ((self = [super init]))
  322. {
  323. // Hold on to the database so it doesn't get deallocated before the iterator is deallocated
  324. self->_levelDB = db;
  325. _iter = db.db->NewIterator(leveldb::ReadOptions());
  326. _iter->SeekToFirst();
  327. if (!_iter->Valid())
  328. return nil;
  329. }
  330. return self;
  331. }
  332. - (id)init
  333. {
  334. [NSException raise:@"BadInitializer" format:@"Use the designated initializer, -initWithLevelDB:, instead."];
  335. return nil;
  336. }
  337. - (void)dealloc
  338. {
  339. self->_levelDB = nil;
  340. delete _iter;
  341. _iter = NULL;
  342. }
  343. - (BOOL)seekToKey:(NSString *)key
  344. {
  345. leveldb::Slice target = SliceFromString(key);
  346. _iter->Seek(target);
  347. return _iter->Valid() == true;
  348. }
  349. - (void)seekToFirst
  350. {
  351. _iter->SeekToFirst();
  352. }
  353. - (void)seekToLast
  354. {
  355. _iter->SeekToLast();
  356. }
  357. - (NSString *)nextKey
  358. {
  359. _iter->Next();
  360. return [self key];
  361. }
  362. - (NSString *)key
  363. {
  364. if (_iter->Valid() == false)
  365. return nil;
  366. leveldb::Slice value = _iter->key();
  367. return StringFromSlice(value);
  368. }
  369. - (NSString *)valueAsString
  370. {
  371. if (_iter->Valid() == false)
  372. return nil;
  373. leveldb::Slice value = _iter->value();
  374. return StringFromSlice(value);
  375. }
  376. - (NSData *)valueAsData
  377. {
  378. if (_iter->Valid() == false)
  379. return nil;
  380. leveldb::Slice value = _iter->value();
  381. return [NSData dataWithBytes:value.data() length:value.size()];
  382. }
  383. @end
  384. #pragma mark - APLevelDBWriteBatch
  385. @implementation APLevelDBWriteBatch
  386. - (id)initWithLevelDB:(APLevelDB *)levelDB {
  387. self = [super init];
  388. if (self != nil) {
  389. self->_levelDB = levelDB;
  390. }
  391. return self;
  392. }
  393. - (void)setData:(NSData *)data forKey:(NSString *)key
  394. {
  395. leveldb::Slice keySlice = SliceFromString(key);
  396. leveldb::Slice valueSlice = leveldb::Slice((const char *)[data bytes], (size_t)[data length]);
  397. _batch.Put(keySlice, valueSlice);
  398. }
  399. - (void)setString:(NSString *)str forKey:(NSString *)key
  400. {
  401. leveldb::Slice keySlice = SliceFromString(key);
  402. leveldb::Slice valueSlice = SliceFromString(str);
  403. _batch.Put(keySlice, valueSlice);
  404. }
  405. - (void)removeKey:(NSString *)key
  406. {
  407. leveldb::Slice keySlice = SliceFromString(key);
  408. _batch.Delete(keySlice);
  409. }
  410. - (void)clear
  411. {
  412. _batch.Clear();
  413. }
  414. - (BOOL)commit {
  415. return [self.levelDB commitWriteBatch:self];
  416. }
  417. @end