From 077af20ceb0869ddff9e08f5db1055138450fe2e Mon Sep 17 00:00:00 2001 From: "Kevin (Kun) \"Kassimo\" Qian" Date: Mon, 18 Feb 2019 15:26:41 -0800 Subject: Add `seek` and implement `Seeker` on `File` (#1797) This patch contains a special hack that circumvents the current tokio seek problem. tokio `seek` is implemented to take ownership of the original File and emit a new one in its future, which conflicts with the design of ResourceTable. To avoid the problem, the current hack makes the FsFile resource an Option which we could `take` the value ownership out of it. We then convert the tokio File into a Rust std File, perform the seek, and then put it back into the resource. This might be able to drop this hack after https://github.com/tokio-rs/tokio/pull/785 lands. --- js/files.ts | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) (limited to 'js/files.ts') diff --git a/js/files.ts b/js/files.ts index e2c7123e6..a77f788df 100644 --- a/js/files.ts +++ b/js/files.ts @@ -1,12 +1,12 @@ // Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. -import { Reader, Writer, Closer, ReadResult } from "./io"; +import { Reader, Writer, Seeker, Closer, ReadResult, SeekMode } from "./io"; import * as dispatch from "./dispatch"; import * as msg from "gen/msg_generated"; import { assert } from "./util"; import * as flatbuffers from "./flatbuffers"; /** The Deno abstraction for reading and writing files. */ -export class File implements Reader, Writer, Closer { +export class File implements Reader, Writer, Seeker, Closer { constructor(readonly rid: number) {} write(p: Uint8Array): Promise { @@ -17,6 +17,10 @@ export class File implements Reader, Writer, Closer { return read(this.rid, p); } + seek(offset: number, whence: SeekMode): Promise { + return seek(this.rid, offset, whence); + } + close(): void { close(this.rid); } @@ -123,6 +127,23 @@ export async function write(rid: number, p: Uint8Array): Promise { return res.nbyte(); } +/** Seek a file ID to the given offset under mode given by `whence`. + * + */ +export async function seek( + rid: number, + offset: number, + whence: SeekMode +): Promise { + const builder = flatbuffers.createBuilder(); + msg.Seek.startSeek(builder); + msg.Seek.addRid(builder, rid); + msg.Seek.addOffset(builder, offset); + msg.Seek.addWhence(builder, whence); + const inner = msg.Seek.endSeek(builder); + await dispatch.sendAsync(builder, msg.Any.Seek, inner); +} + /** Close the file ID. */ export function close(rid: number): void { const builder = flatbuffers.createBuilder(); -- cgit v1.2.3