Example #1
0
    bool SetInternal(const string& key, const string& val)
    {
        //update对应key的val,如果不存在则返回false
        Node* np = NULL;
        Link l;
        bool found = Find(key, &np, &l);
        if(!found)
            return false;

        Link val_link = np->GetValLink();
        if(val_link.GetTotalSize() >= val.length()) { 	//the old val has enough space, write new val at original offset
            Lseek(data_fd_, val_link.GetOffset(), SEEK_SET);
            val_link.SetSize(val.length());
        } else { 	//space is not enough, write the new val at the end of file
            (*free_data_)[val_link.GetTotalSize()] = val_link;		//add original data space to free data map
            val_link = FindRooMAndWrite(val.c_str(), val.length(), data_fd_, free_data_);
        }

        Write(data_fd_, val.c_str(), val.length());
        np->SetValLink(val_link);
        NodeWriteInplace(np, l.GetOffset());

        delete np;
        return true;
    }
Example #2
0
    string GetVal(const Link& l)
    {
        char* buf = new char[l.GetSize()];
        Lseek(data_fd_, l.GetOffset(), SEEK_SET);
        Read(data_fd_, buf, l.GetSize()); //至此,结点中的内容在buf里
        string val(buf, l.GetSize()); // 读取val
        delete[] buf;

        return val;
    }
Example #3
0
    //return link info that describes the write which just happened
    Link FindRooMAndWrite(const char* data, size_t len,  int fd, map<size_t, Link>* free_space)
    {
        Link l;
        //first find data space which is >= data length in free space map
        map<size_t, Link>::iterator iter = free_space->lower_bound(len);
        if(iter != free_space->end()) { // found proper space in free space map
            l = iter->second;
            Lseek(fd, l.GetOffset(), SEEK_SET);
            free_space->erase(iter);		//remove from free space map because it'll be reused
        } else {
            // no proper space in free space map, write data to the end of the file
            l.SetOffset(Lseek(fd, 0, SEEK_END));
            l.SetTotalSize(len);
            l.SetSize(len);
        }

        Write(fd, data, len);
        return l;
    }