2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2019-02-26 00:35:50 -05:00
|
|
|
const { Buffer, mkdir, open } = Deno;
|
2019-03-07 19:25:16 -05:00
|
|
|
type File = Deno.File;
|
|
|
|
type Reader = Deno.Reader;
|
2019-10-16 14:39:33 -04:00
|
|
|
import * as path from "../path/mod.ts";
|
2020-04-01 15:23:39 -04:00
|
|
|
import { encode } from "../encoding/utf8.ts";
|
2019-10-16 14:39:33 -04:00
|
|
|
|
2020-04-17 16:12:14 -04:00
|
|
|
/**
|
|
|
|
* Copy bytes from one Uint8Array to another. Bytes from `src` which don't fit
|
|
|
|
* into `dst` will not be copied.
|
|
|
|
*
|
|
|
|
* @param src Source byte array
|
2020-04-30 16:39:25 -04:00
|
|
|
* @param dst Destination byte array
|
2020-04-17 16:12:14 -04:00
|
|
|
* @param off Offset into `dst` at which to begin writing values from `src`.
|
|
|
|
* @return number of bytes copied
|
|
|
|
*/
|
2020-04-30 16:39:25 -04:00
|
|
|
export function copyBytes(src: Uint8Array, dst: Uint8Array, off = 0): number {
|
2019-01-21 22:56:35 -05:00
|
|
|
off = Math.max(0, Math.min(off, dst.byteLength));
|
2020-04-17 16:12:14 -04:00
|
|
|
const dstBytesAvailable = dst.byteLength - off;
|
|
|
|
if (src.byteLength > dstBytesAvailable) {
|
|
|
|
src = src.subarray(0, dstBytesAvailable);
|
2018-11-07 14:17:36 -05:00
|
|
|
}
|
|
|
|
dst.set(src, off);
|
|
|
|
return src.byteLength;
|
|
|
|
}
|
2018-11-07 23:19:08 -05:00
|
|
|
|
|
|
|
export function charCode(s: string): number {
|
|
|
|
return s.charCodeAt(0);
|
|
|
|
}
|
2018-12-17 22:40:42 -05:00
|
|
|
|
|
|
|
export function stringsReader(s: string): Reader {
|
2019-02-10 18:49:48 -05:00
|
|
|
return new Buffer(encode(s).buffer);
|
|
|
|
}
|
|
|
|
|
2019-06-19 00:22:01 -04:00
|
|
|
/** Create or open a temporal file at specified directory with prefix and
|
|
|
|
* postfix
|
|
|
|
* */
|
2019-02-10 18:49:48 -05:00
|
|
|
export async function tempFile(
|
|
|
|
dir: string,
|
|
|
|
opts: {
|
|
|
|
prefix?: string;
|
|
|
|
postfix?: string;
|
|
|
|
} = { prefix: "", postfix: "" }
|
|
|
|
): Promise<{ file: File; filepath: string }> {
|
|
|
|
const r = Math.floor(Math.random() * 1000000);
|
|
|
|
const filepath = path.resolve(
|
|
|
|
`${dir}/${opts.prefix || ""}${r}${opts.postfix || ""}`
|
|
|
|
);
|
2020-01-07 14:14:33 -05:00
|
|
|
await mkdir(path.dirname(filepath), { recursive: true });
|
2020-04-24 18:45:55 -04:00
|
|
|
const file = await open(filepath, {
|
|
|
|
create: true,
|
|
|
|
read: true,
|
|
|
|
write: true,
|
|
|
|
append: true,
|
|
|
|
});
|
2019-02-10 18:49:48 -05:00
|
|
|
return { file, filepath };
|
2018-12-17 22:40:42 -05:00
|
|
|
}
|