CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/util/base64.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2024 Sagemath, Inc.
3
* License: Distributed under the terms of the Modified BSD License (same as ipywidgets)
4
*/
5
6
// Inspiration: this is meant to be a more modern version of upstream ipywidget's
7
// packages/base-manager/src/utils.ts, which based on a non-maintained library.
8
// Hence the BSD license.
9
10
import { fromUint8Array, toUint8Array } from "js-base64";
11
12
// Convert an ArrayBuffer to a base64 string.
13
// UNCLEAR: I put in ArrayBufferView also, since it's mentioned in all the typings
14
// in ipywidgets, and we can at least handle one case of it Uint8Array in
15
// one direction.
16
export function bufferToBase64(buffer: ArrayBuffer | ArrayBufferView): string {
17
if (buffer instanceof ArrayBuffer) {
18
return fromUint8Array(new Uint8Array(buffer));
19
} else if (buffer instanceof Uint8Array) {
20
return fromUint8Array(buffer);
21
}
22
throw new Error("buffer must be either ArrayBuffer or Uint8Array");
23
}
24
25
// Convert a base64 string to an ArrayBuffer.
26
export function base64ToBuffer(base64: string): ArrayBuffer {
27
return toUint8Array(base64).buffer;
28
}
29
30