2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2019-10-16 14:39:33 -04:00
|
|
|
import * as path from "../path/mod.ts";
|
|
|
|
|
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
|
|
|
|
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: "" }
|
2020-06-12 15:23:38 -04:00
|
|
|
): Promise<{ file: Deno.File; filepath: string }> {
|
2019-02-10 18:49:48 -05:00
|
|
|
const r = Math.floor(Math.random() * 1000000);
|
|
|
|
const filepath = path.resolve(
|
|
|
|
`${dir}/${opts.prefix || ""}${r}${opts.postfix || ""}`
|
|
|
|
);
|
2020-06-12 15:23:38 -04:00
|
|
|
await Deno.mkdir(path.dirname(filepath), { recursive: true });
|
|
|
|
const file = await Deno.open(filepath, {
|
2020-04-24 18:45:55 -04:00
|
|
|
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
|
|
|
}
|