Unverified Commit 91e8764d authored by Steven Allen's avatar Steven Allen Committed by GitHub

Merge pull request #48 from ipfs/feat/get-size

add GetSize function
parents d2629a26 1df2c1e0
......@@ -577,6 +577,18 @@ func (fs *Datastore) Has(key datastore.Key) (exists bool, err error) {
}
}
func (fs *Datastore) GetSize(key datastore.Key) (size int, err error) {
_, path := fs.encode(key)
switch s, err := os.Stat(path); {
case err == nil:
return int(s.Size()), nil
case os.IsNotExist(err):
return -1, datastore.ErrNotFound
default:
return -1, err
}
}
// Delete removes a key/value from the Datastore. Please read
// the Put() explanation about the handling of concurrent write
// operations to the same key.
......
......@@ -256,8 +256,8 @@ func testHasNotFound(dirFunc mkShardFunc, t *testing.T) {
if err != nil {
t.Fatalf("Has fail: %v\n", err)
}
if g, e := found, false; g != e {
t.Fatalf("wrong Has: %v != %v", g, e)
if found {
t.Fatal("Has should have returned false")
}
}
......@@ -282,13 +282,57 @@ func testHasFound(dirFunc mkShardFunc, t *testing.T) {
if err != nil {
t.Fatalf("Has fail: %v\n", err)
}
if g, e := found, true; g != e {
t.Fatalf("wrong Has: %v != %v", g, e)
if !found {
t.Fatal("Has should have returned true")
}
}
func TestHasFound(t *testing.T) { tryAllShardFuncs(t, testHasFound) }
func testGetSizeFound(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
_, err = fs.GetSize(datastore.NewKey("quux"))
if err != datastore.ErrNotFound {
t.Fatalf("GetSize should have returned ErrNotFound, got: %v\n", err)
}
}
func TestGetSizeFound(t *testing.T) { tryAllShardFuncs(t, testGetSizeFound) }
func testGetSizeNotFound(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
fs, err := flatfs.CreateOrOpen(temp, dirFunc(2), false)
if err != nil {
t.Fatalf("New fail: %v\n", err)
}
defer fs.Close()
err = fs.Put(datastore.NewKey("quux"), []byte("foobar"))
if err != nil {
t.Fatalf("Put fail: %v\n", err)
}
size, err := fs.GetSize(datastore.NewKey("quux"))
if err != nil {
t.Fatalf("GetSize failed with: %v\n", err)
}
if size != len("foobar") {
t.Fatalf("GetSize returned wrong size: got %d, expected %d", size, len("foobar"))
}
}
func TestGetSizeNotFound(t *testing.T) { tryAllShardFuncs(t, testGetSizeNotFound) }
func testDeleteNotFound(dirFunc mkShardFunc, t *testing.T) {
temp, cleanup := tempdir(t)
defer cleanup()
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment