github.com/igggame/nebulas-go@v2.1.0+incompatible/nf/nvm/v8/samples/memory_storage.cc (about) 1 // Copyright (C) 2017 go-nebulas authors 2 // 3 // This file is part of the go-nebulas library. 4 // 5 // the go-nebulas library is free software: you can redistribute it and/or 6 // modify it under the terms of the GNU General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // the go-nebulas library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU General Public License for more details. 14 // 15 // You should have received a copy of the GNU General Public License 16 // along with the go-nebulas library. If not, see 17 // <http://www.gnu.org/licenses/>. 18 // 19 #include "memory_storage.h" 20 21 #include <atomic> 22 #include <mutex> 23 #include <string> 24 #include <unordered_map> 25 26 #include <stdio.h> 27 #include <stdlib.h> 28 #include <string.h> 29 30 using namespace std; 31 32 static std::mutex mapMutex; 33 static unordered_map<string, string> memoryMap; 34 static atomic<uintptr_t> handlerCounter(1234); 35 36 string genKey(void *handler, const char *key) { 37 uintptr_t prefix = (uintptr_t)handler; 38 string sKey = to_string(prefix); 39 sKey.append("-"); 40 sKey.append(key); 41 return sKey; 42 } 43 44 void *CreateStorageHandler() { return (void *)handlerCounter.fetch_add(1); } 45 46 void DeleteStorageHandler(void *handler) {} 47 48 char *StorageGet(void *handler, const char *key, size_t *cnt) { 49 char *ret = NULL; 50 string sKey = genKey(handler, key); 51 52 mapMutex.lock(); 53 auto it = memoryMap.find(sKey); 54 if (it != memoryMap.end()) { 55 string &value = it->second; 56 ret = (char *)calloc(value.length() + 1, sizeof(char)); 57 strncpy(ret, value.c_str(), value.length()); 58 } 59 mapMutex.unlock(); 60 61 *cnt = 0; 62 63 return ret; 64 } 65 66 int StoragePut(void *handler, const char *key, const char *value, size_t *cnt) { 67 string sKey = genKey(handler, key); 68 69 mapMutex.lock(); 70 memoryMap[sKey] = string(value); 71 mapMutex.unlock(); 72 73 *cnt = strlen(key) + strlen(value); 74 return 0; 75 } 76 77 int StorageDel(void *handler, const char *key, size_t *cnt) { 78 string sKey = genKey(handler, key); 79 80 mapMutex.lock(); 81 memoryMap.erase(sKey); 82 mapMutex.unlock(); 83 84 *cnt = 0; 85 86 return 0; 87 }