func (db *RocksDB) Get(hash data.Hash256) (data.Hashable, error) { db.mu.Lock() cached, ok := db.cache.Get(hash) db.mu.Unlock() if ok { db.hits.Mark(1) return cached.(data.Hashable), nil } value, err := db.db.Get(db.ro, hash[:]) if err != nil { return nil, err } defer value.Free() if value.Size() == 0 { return nil, ErrNotFound } node, err := data.NewDecoder(bytes.NewReader(value.Data())).Prefix() if err != nil { return nil, err } db.misses.Mark(1) db.mu.Lock() db.cache.Add(hash, node) db.mu.Unlock() return node, nil }
func NewMemoryDB(path string) (*MemoryDB, error) { mem := &MemoryDB{ nodes: make(map[data.Hash256]data.Hashable), } f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() r, err := gzip.NewReader(f) if err != nil { return nil, err } defer r.Close() scanner := bufio.NewScanner(r) for scanner.Scan() { parts := strings.Split(scanner.Text(), ":") var key data.Hash256 if _, err := hex.Decode(key[:], []byte(parts[0])); err != nil { return nil, err } value, err := hex.DecodeString(parts[1]) if err != nil { return nil, err } node, err := data.NewDecoder(bytes.NewReader(value)).Prefix() if err != nil { return nil, err } mem.nodes[key] = node } if scanner.Err() != nil { return nil, scanner.Err() } return mem, nil }