作者: 韩晨旭 10225101440 李畅 10225102463
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

566 lines
17 KiB

  1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #include "leveldb/c.h"
  5. #include <stdlib.h>
  6. #include "leveldb/cache.h"
  7. #include "leveldb/comparator.h"
  8. #include "leveldb/db.h"
  9. #include "leveldb/env.h"
  10. #include "leveldb/filter_policy.h"
  11. #include "leveldb/iterator.h"
  12. #include "leveldb/options.h"
  13. #include "leveldb/status.h"
  14. #include "leveldb/write_batch.h"
  15. using leveldb::Cache;
  16. using leveldb::Comparator;
  17. using leveldb::CompressionType;
  18. using leveldb::DB;
  19. using leveldb::Env;
  20. using leveldb::FileLock;
  21. using leveldb::FilterPolicy;
  22. using leveldb::Iterator;
  23. using leveldb::kMajorVersion;
  24. using leveldb::kMinorVersion;
  25. using leveldb::Logger;
  26. using leveldb::NewBloomFilterPolicy;
  27. using leveldb::NewLRUCache;
  28. using leveldb::Options;
  29. using leveldb::RandomAccessFile;
  30. using leveldb::Range;
  31. using leveldb::ReadOptions;
  32. using leveldb::SequentialFile;
  33. using leveldb::Slice;
  34. using leveldb::Snapshot;
  35. using leveldb::Status;
  36. using leveldb::WritableFile;
  37. using leveldb::WriteBatch;
  38. using leveldb::WriteOptions;
  39. extern "C" {
  40. struct leveldb_t {
  41. DB* rep;
  42. };
  43. struct leveldb_iterator_t {
  44. Iterator* rep;
  45. };
  46. struct leveldb_writebatch_t {
  47. WriteBatch rep;
  48. };
  49. struct leveldb_snapshot_t {
  50. const Snapshot* rep;
  51. };
  52. struct leveldb_readoptions_t {
  53. ReadOptions rep;
  54. };
  55. struct leveldb_writeoptions_t {
  56. WriteOptions rep;
  57. };
  58. struct leveldb_options_t {
  59. Options rep;
  60. };
  61. struct leveldb_cache_t {
  62. Cache* rep;
  63. };
  64. struct leveldb_seqfile_t {
  65. SequentialFile* rep;
  66. };
  67. struct leveldb_randomfile_t {
  68. RandomAccessFile* rep;
  69. };
  70. struct leveldb_writablefile_t {
  71. WritableFile* rep;
  72. };
  73. struct leveldb_logger_t {
  74. Logger* rep;
  75. };
  76. struct leveldb_filelock_t {
  77. FileLock* rep;
  78. };
  79. struct leveldb_comparator_t : public Comparator {
  80. virtual ~leveldb_comparator_t() { (*destructor_)(state_); }
  81. virtual int Compare(const Slice& a, const Slice& b) const {
  82. return (*compare_)(state_, a.data(), a.size(), b.data(), b.size());
  83. }
  84. virtual const char* Name() const { return (*name_)(state_); }
  85. // No-ops since the C binding does not support key shortening methods.
  86. virtual void FindShortestSeparator(std::string*, const Slice&) const {}
  87. virtual void FindShortSuccessor(std::string* key) const {}
  88. void* state_;
  89. void (*destructor_)(void*);
  90. int (*compare_)(void*, const char* a, size_t alen, const char* b,
  91. size_t blen);
  92. const char* (*name_)(void*);
  93. };
  94. struct leveldb_filterpolicy_t : public FilterPolicy {
  95. virtual ~leveldb_filterpolicy_t() { (*destructor_)(state_); }
  96. virtual const char* Name() const { return (*name_)(state_); }
  97. virtual void CreateFilter(const Slice* keys, int n, std::string* dst) const {
  98. std::vector<const char*> key_pointers(n);
  99. std::vector<size_t> key_sizes(n);
  100. for (int i = 0; i < n; i++) {
  101. key_pointers[i] = keys[i].data();
  102. key_sizes[i] = keys[i].size();
  103. }
  104. size_t len;
  105. char* filter = (*create_)(state_, &key_pointers[0], &key_sizes[0], n, &len);
  106. dst->append(filter, len);
  107. free(filter);
  108. }
  109. virtual bool KeyMayMatch(const Slice& key, const Slice& filter) const {
  110. return (*key_match_)(state_, key.data(), key.size(), filter.data(),
  111. filter.size());
  112. }
  113. void* state_;
  114. void (*destructor_)(void*);
  115. const char* (*name_)(void*);
  116. char* (*create_)(void*, const char* const* key_array,
  117. const size_t* key_length_array, int num_keys,
  118. size_t* filter_length);
  119. unsigned char (*key_match_)(void*, const char* key, size_t length,
  120. const char* filter, size_t filter_length);
  121. };
  122. struct leveldb_env_t {
  123. Env* rep;
  124. bool is_default;
  125. };
  126. static bool SaveError(char** errptr, const Status& s) {
  127. assert(errptr != nullptr);
  128. if (s.ok()) {
  129. return false;
  130. } else if (*errptr == nullptr) {
  131. *errptr = strdup(s.ToString().c_str());
  132. } else {
  133. // TODO(sanjay): Merge with existing error?
  134. free(*errptr);
  135. *errptr = strdup(s.ToString().c_str());
  136. }
  137. return true;
  138. }
  139. static char* CopyString(const std::string& str) {
  140. char* result = reinterpret_cast<char*>(malloc(sizeof(char) * str.size()));
  141. memcpy(result, str.data(), sizeof(char) * str.size());
  142. return result;
  143. }
  144. leveldb_t* leveldb_open(const leveldb_options_t* options, const char* name,
  145. char** errptr) {
  146. DB* db;
  147. if (SaveError(errptr, DB::Open(options->rep, std::string(name), &db))) {
  148. return nullptr;
  149. }
  150. leveldb_t* result = new leveldb_t;
  151. result->rep = db;
  152. return result;
  153. }
  154. void leveldb_close(leveldb_t* db) {
  155. delete db->rep;
  156. delete db;
  157. }
  158. void leveldb_put(leveldb_t* db, const leveldb_writeoptions_t* options,
  159. const char* key, size_t keylen, const char* val, size_t vallen,
  160. char** errptr) {
  161. SaveError(errptr,
  162. db->rep->Put(options->rep, Slice(key, keylen), Slice(val, vallen)));
  163. }
  164. void leveldb_delete(leveldb_t* db, const leveldb_writeoptions_t* options,
  165. const char* key, size_t keylen, char** errptr) {
  166. SaveError(errptr, db->rep->Delete(options->rep, Slice(key, keylen)));
  167. }
  168. void leveldb_write(leveldb_t* db, const leveldb_writeoptions_t* options,
  169. leveldb_writebatch_t* batch, char** errptr) {
  170. SaveError(errptr, db->rep->Write(options->rep, &batch->rep));
  171. }
  172. char* leveldb_get(leveldb_t* db, const leveldb_readoptions_t* options,
  173. const char* key, size_t keylen, size_t* vallen,
  174. char** errptr) {
  175. char* result = nullptr;
  176. std::string tmp;
  177. Status s = db->rep->Get(options->rep, Slice(key, keylen), &tmp);
  178. if (s.ok()) {
  179. *vallen = tmp.size();
  180. result = CopyString(tmp);
  181. } else {
  182. *vallen = 0;
  183. if (!s.IsNotFound()) {
  184. SaveError(errptr, s);
  185. }
  186. }
  187. return result;
  188. }
  189. leveldb_iterator_t* leveldb_create_iterator(
  190. leveldb_t* db, const leveldb_readoptions_t* options) {
  191. leveldb_iterator_t* result = new leveldb_iterator_t;
  192. result->rep = db->rep->NewIterator(options->rep);
  193. return result;
  194. }
  195. const leveldb_snapshot_t* leveldb_create_snapshot(leveldb_t* db) {
  196. leveldb_snapshot_t* result = new leveldb_snapshot_t;
  197. result->rep = db->rep->GetSnapshot();
  198. return result;
  199. }
  200. void leveldb_release_snapshot(leveldb_t* db,
  201. const leveldb_snapshot_t* snapshot) {
  202. db->rep->ReleaseSnapshot(snapshot->rep);
  203. delete snapshot;
  204. }
  205. char* leveldb_property_value(leveldb_t* db, const char* propname) {
  206. std::string tmp;
  207. if (db->rep->GetProperty(Slice(propname), &tmp)) {
  208. // We use strdup() since we expect human readable output.
  209. return strdup(tmp.c_str());
  210. } else {
  211. return nullptr;
  212. }
  213. }
  214. void leveldb_approximate_sizes(leveldb_t* db, int num_ranges,
  215. const char* const* range_start_key,
  216. const size_t* range_start_key_len,
  217. const char* const* range_limit_key,
  218. const size_t* range_limit_key_len,
  219. uint64_t* sizes) {
  220. Range* ranges = new Range[num_ranges];
  221. for (int i = 0; i < num_ranges; i++) {
  222. ranges[i].start = Slice(range_start_key[i], range_start_key_len[i]);
  223. ranges[i].limit = Slice(range_limit_key[i], range_limit_key_len[i]);
  224. }
  225. db->rep->GetApproximateSizes(ranges, num_ranges, sizes);
  226. delete[] ranges;
  227. }
  228. void leveldb_compact_range(leveldb_t* db, const char* start_key,
  229. size_t start_key_len, const char* limit_key,
  230. size_t limit_key_len) {
  231. Slice a, b;
  232. db->rep->CompactRange(
  233. // Pass null Slice if corresponding "const char*" is null
  234. (start_key ? (a = Slice(start_key, start_key_len), &a) : nullptr),
  235. (limit_key ? (b = Slice(limit_key, limit_key_len), &b) : nullptr));
  236. }
  237. void leveldb_destroy_db(const leveldb_options_t* options, const char* name,
  238. char** errptr) {
  239. SaveError(errptr, DestroyDB(name, options->rep));
  240. }
  241. void leveldb_repair_db(const leveldb_options_t* options, const char* name,
  242. char** errptr) {
  243. SaveError(errptr, RepairDB(name, options->rep));
  244. }
  245. void leveldb_iter_destroy(leveldb_iterator_t* iter) {
  246. delete iter->rep;
  247. delete iter;
  248. }
  249. unsigned char leveldb_iter_valid(const leveldb_iterator_t* iter) {
  250. return iter->rep->Valid();
  251. }
  252. void leveldb_iter_seek_to_first(leveldb_iterator_t* iter) {
  253. iter->rep->SeekToFirst();
  254. }
  255. void leveldb_iter_seek_to_last(leveldb_iterator_t* iter) {
  256. iter->rep->SeekToLast();
  257. }
  258. void leveldb_iter_seek(leveldb_iterator_t* iter, const char* k, size_t klen) {
  259. iter->rep->Seek(Slice(k, klen));
  260. }
  261. void leveldb_iter_next(leveldb_iterator_t* iter) { iter->rep->Next(); }
  262. void leveldb_iter_prev(leveldb_iterator_t* iter) { iter->rep->Prev(); }
  263. const char* leveldb_iter_key(const leveldb_iterator_t* iter, size_t* klen) {
  264. Slice s = iter->rep->key();
  265. *klen = s.size();
  266. return s.data();
  267. }
  268. const char* leveldb_iter_value(const leveldb_iterator_t* iter, size_t* vlen) {
  269. Slice s = iter->rep->value();
  270. *vlen = s.size();
  271. return s.data();
  272. }
  273. void leveldb_iter_get_error(const leveldb_iterator_t* iter, char** errptr) {
  274. SaveError(errptr, iter->rep->status());
  275. }
  276. leveldb_writebatch_t* leveldb_writebatch_create() {
  277. return new leveldb_writebatch_t;
  278. }
  279. void leveldb_writebatch_destroy(leveldb_writebatch_t* b) { delete b; }
  280. void leveldb_writebatch_clear(leveldb_writebatch_t* b) { b->rep.Clear(); }
  281. void leveldb_writebatch_put(leveldb_writebatch_t* b, const char* key,
  282. size_t klen, const char* val, size_t vlen) {
  283. b->rep.Put(Slice(key, klen), Slice(val, vlen));
  284. }
  285. void leveldb_writebatch_delete(leveldb_writebatch_t* b, const char* key,
  286. size_t klen) {
  287. b->rep.Delete(Slice(key, klen));
  288. }
  289. void leveldb_writebatch_iterate(const leveldb_writebatch_t* b, void* state,
  290. void (*put)(void*, const char* k, size_t klen,
  291. const char* v, size_t vlen),
  292. void (*deleted)(void*, const char* k,
  293. size_t klen)) {
  294. class H : public WriteBatch::Handler {
  295. public:
  296. void* state_;
  297. void (*put_)(void*, const char* k, size_t klen, const char* v, size_t vlen);
  298. void (*deleted_)(void*, const char* k, size_t klen);
  299. virtual void Put(const Slice& key, const Slice& value) {
  300. (*put_)(state_, key.data(), key.size(), value.data(), value.size());
  301. }
  302. virtual void Delete(const Slice& key) {
  303. (*deleted_)(state_, key.data(), key.size());
  304. }
  305. };
  306. H handler;
  307. handler.state_ = state;
  308. handler.put_ = put;
  309. handler.deleted_ = deleted;
  310. b->rep.Iterate(&handler);
  311. }
  312. void leveldb_writebatch_append(leveldb_writebatch_t* destination,
  313. const leveldb_writebatch_t* source) {
  314. destination->rep.Append(source->rep);
  315. }
  316. leveldb_options_t* leveldb_options_create() { return new leveldb_options_t; }
  317. void leveldb_options_destroy(leveldb_options_t* options) { delete options; }
  318. void leveldb_options_set_comparator(leveldb_options_t* opt,
  319. leveldb_comparator_t* cmp) {
  320. opt->rep.comparator = cmp;
  321. }
  322. void leveldb_options_set_filter_policy(leveldb_options_t* opt,
  323. leveldb_filterpolicy_t* policy) {
  324. opt->rep.filter_policy = policy;
  325. }
  326. void leveldb_options_set_create_if_missing(leveldb_options_t* opt,
  327. unsigned char v) {
  328. opt->rep.create_if_missing = v;
  329. }
  330. void leveldb_options_set_error_if_exists(leveldb_options_t* opt,
  331. unsigned char v) {
  332. opt->rep.error_if_exists = v;
  333. }
  334. void leveldb_options_set_paranoid_checks(leveldb_options_t* opt,
  335. unsigned char v) {
  336. opt->rep.paranoid_checks = v;
  337. }
  338. void leveldb_options_set_env(leveldb_options_t* opt, leveldb_env_t* env) {
  339. opt->rep.env = (env ? env->rep : nullptr);
  340. }
  341. void leveldb_options_set_info_log(leveldb_options_t* opt, leveldb_logger_t* l) {
  342. opt->rep.info_log = (l ? l->rep : nullptr);
  343. }
  344. void leveldb_options_set_write_buffer_size(leveldb_options_t* opt, size_t s) {
  345. opt->rep.write_buffer_size = s;
  346. }
  347. void leveldb_options_set_max_open_files(leveldb_options_t* opt, int n) {
  348. opt->rep.max_open_files = n;
  349. }
  350. void leveldb_options_set_cache(leveldb_options_t* opt, leveldb_cache_t* c) {
  351. opt->rep.block_cache = c->rep;
  352. }
  353. void leveldb_options_set_block_size(leveldb_options_t* opt, size_t s) {
  354. opt->rep.block_size = s;
  355. }
  356. void leveldb_options_set_block_restart_interval(leveldb_options_t* opt, int n) {
  357. opt->rep.block_restart_interval = n;
  358. }
  359. void leveldb_options_set_max_file_size(leveldb_options_t* opt, size_t s) {
  360. opt->rep.max_file_size = s;
  361. }
  362. void leveldb_options_set_compression(leveldb_options_t* opt, int t) {
  363. opt->rep.compression = static_cast<CompressionType>(t);
  364. }
  365. leveldb_comparator_t* leveldb_comparator_create(
  366. void* state, void (*destructor)(void*),
  367. int (*compare)(void*, const char* a, size_t alen, const char* b,
  368. size_t blen),
  369. const char* (*name)(void*)) {
  370. leveldb_comparator_t* result = new leveldb_comparator_t;
  371. result->state_ = state;
  372. result->destructor_ = destructor;
  373. result->compare_ = compare;
  374. result->name_ = name;
  375. return result;
  376. }
  377. void leveldb_comparator_destroy(leveldb_comparator_t* cmp) { delete cmp; }
  378. leveldb_filterpolicy_t* leveldb_filterpolicy_create(
  379. void* state, void (*destructor)(void*),
  380. char* (*create_filter)(void*, const char* const* key_array,
  381. const size_t* key_length_array, int num_keys,
  382. size_t* filter_length),
  383. unsigned char (*key_may_match)(void*, const char* key, size_t length,
  384. const char* filter, size_t filter_length),
  385. const char* (*name)(void*)) {
  386. leveldb_filterpolicy_t* result = new leveldb_filterpolicy_t;
  387. result->state_ = state;
  388. result->destructor_ = destructor;
  389. result->create_ = create_filter;
  390. result->key_match_ = key_may_match;
  391. result->name_ = name;
  392. return result;
  393. }
  394. void leveldb_filterpolicy_destroy(leveldb_filterpolicy_t* filter) {
  395. delete filter;
  396. }
  397. leveldb_filterpolicy_t* leveldb_filterpolicy_create_bloom(int bits_per_key) {
  398. // Make a leveldb_filterpolicy_t, but override all of its methods so
  399. // they delegate to a NewBloomFilterPolicy() instead of user
  400. // supplied C functions.
  401. struct Wrapper : public leveldb_filterpolicy_t {
  402. static void DoNothing(void*) {}
  403. ~Wrapper() { delete rep_; }
  404. const char* Name() const { return rep_->Name(); }
  405. void CreateFilter(const Slice* keys, int n, std::string* dst) const {
  406. return rep_->CreateFilter(keys, n, dst);
  407. }
  408. bool KeyMayMatch(const Slice& key, const Slice& filter) const {
  409. return rep_->KeyMayMatch(key, filter);
  410. }
  411. const FilterPolicy* rep_;
  412. };
  413. Wrapper* wrapper = new Wrapper;
  414. wrapper->rep_ = NewBloomFilterPolicy(bits_per_key);
  415. wrapper->state_ = nullptr;
  416. wrapper->destructor_ = &Wrapper::DoNothing;
  417. return wrapper;
  418. }
  419. leveldb_readoptions_t* leveldb_readoptions_create() {
  420. return new leveldb_readoptions_t;
  421. }
  422. void leveldb_readoptions_destroy(leveldb_readoptions_t* opt) { delete opt; }
  423. void leveldb_readoptions_set_verify_checksums(leveldb_readoptions_t* opt,
  424. unsigned char v) {
  425. opt->rep.verify_checksums = v;
  426. }
  427. void leveldb_readoptions_set_fill_cache(leveldb_readoptions_t* opt,
  428. unsigned char v) {
  429. opt->rep.fill_cache = v;
  430. }
  431. void leveldb_readoptions_set_snapshot(leveldb_readoptions_t* opt,
  432. const leveldb_snapshot_t* snap) {
  433. opt->rep.snapshot = (snap ? snap->rep : nullptr);
  434. }
  435. leveldb_writeoptions_t* leveldb_writeoptions_create() {
  436. return new leveldb_writeoptions_t;
  437. }
  438. void leveldb_writeoptions_destroy(leveldb_writeoptions_t* opt) { delete opt; }
  439. void leveldb_writeoptions_set_sync(leveldb_writeoptions_t* opt,
  440. unsigned char v) {
  441. opt->rep.sync = v;
  442. }
  443. leveldb_cache_t* leveldb_cache_create_lru(size_t capacity) {
  444. leveldb_cache_t* c = new leveldb_cache_t;
  445. c->rep = NewLRUCache(capacity);
  446. return c;
  447. }
  448. void leveldb_cache_destroy(leveldb_cache_t* cache) {
  449. delete cache->rep;
  450. delete cache;
  451. }
  452. leveldb_env_t* leveldb_create_default_env() {
  453. leveldb_env_t* result = new leveldb_env_t;
  454. result->rep = Env::Default();
  455. result->is_default = true;
  456. return result;
  457. }
  458. void leveldb_env_destroy(leveldb_env_t* env) {
  459. if (!env->is_default) delete env->rep;
  460. delete env;
  461. }
  462. char* leveldb_env_get_test_directory(leveldb_env_t* env) {
  463. std::string result;
  464. if (!env->rep->GetTestDirectory(&result).ok()) {
  465. return nullptr;
  466. }
  467. char* buffer = static_cast<char*>(malloc(result.size() + 1));
  468. memcpy(buffer, result.data(), result.size());
  469. buffer[result.size()] = '\0';
  470. return buffer;
  471. }
  472. void leveldb_free(void* ptr) { free(ptr); }
  473. int leveldb_major_version() { return kMajorVersion; }
  474. int leveldb_minor_version() { return kMinorVersion; }
  475. } // end extern "C"