From 8d19dabe737868adef57373d8f974dc117739bea Mon Sep 17 00:00:00 2001 From: Daniel Erat Date: Mon, 18 Jul 2011 00:24:15 +0000 Subject: [PATCH] sqlite: read Change-Id: I925cce717ead61ae35d06602e9a7df16cc78db22 --- misc/sqlite/sqlite3_os_go.c | 5 +++-- misc/sqlite/vfs.go | 42 +++++++++++++++++++++++++++++++++++-- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/misc/sqlite/sqlite3_os_go.c b/misc/sqlite/sqlite3_os_go.c index 251b69df4..e2cbd83a1 100644 --- a/misc/sqlite/sqlite3_os_go.c +++ b/misc/sqlite/sqlite3_os_go.c @@ -22,8 +22,9 @@ static int go_file_close(sqlite3_file* file) { } static int go_file_read(sqlite3_file* file, void* dest, int iAmt, sqlite3_int64 iOfst) { - fprintf(stderr, "read\n"); - return 0; + return GoFileRead(((GoFile*) file)->fd, dest, iAmt, iOfst) == 0 ? + SQLITE_OK : + SQLITE_ERROR; } static int go_file_write(sqlite3_file* file, const void* src, int iAmt, sqlite3_int64 iOfst) { diff --git a/misc/sqlite/vfs.go b/misc/sqlite/vfs.go index 5a92ab0cf..2b10b4b74 100644 --- a/misc/sqlite/vfs.go +++ b/misc/sqlite/vfs.go @@ -1,6 +1,8 @@ package sqlite /* +#include + #define SKIP_SQLITE_VERSION #include "sqlite3.h" */ @@ -9,6 +11,7 @@ import "C" import ( "os" "sync" + "unsafe" ) var file_map_mutex sync.Mutex @@ -21,15 +24,50 @@ func GetFile(fd int) (file *os.File) { } //export GoFileClose -// Returns 0 on success and 1 on error. +// Returns 0 on success and -1 on error. func GoFileClose(fd C.int) (int) { file := GetFile(int(fd)) if file.Close() != nil { - return 1 + return -1 } return 0 } +//export GoFileRead +// Returns 0 on success and -1 on error. +func GoFileRead(fd C.int, dst *C.char, n C.int, offset C.int) (rv int) { + println("reading", n, "bytes at offset", offset, "from fd", fd); + defer func() { + println("read returning", rv); + }() + + file := GetFile(int(fd)) + if file == nil { + return -1 + } + + buf := make([]byte, n) + curbuf := buf + for n > 0 { + read, err := file.ReadAt(curbuf, int64(offset)) + curbuf = curbuf[read:] + n -= C.int(read) + if err == os.EOF { + break + } + if err != nil { + return -1 + } + } + + if n != 0 { + return -1 + } + + C.memcpy(unsafe.Pointer(dst), unsafe.Pointer(&buf[0]), C.size_t(len(buf))) + return 0 +} + //export GoVFSOpen // fd is -1 on error. func GoVFSOpen(filename *C.char, flags C.int) (fd int) {