convert
Manages data format conversion between a variety of targets.
converthint, inputoutput
name | type | description |
---|---|---|
hint | An object with the keys | |
input | The value to be converted. | |
output | The result of the conversion. |
Behind the scenes, Confidential generics, like encrypt
operate on byte arrays. The purpose of convert
is to make it easier to convert between byte arrays and other formats, like UTF-8 strings.
However, you will not typically need to use convert
directly because Confidential also provides from
and to
convenience methods for most classes, which call convert
for you behind the scenes.
A conversion is specified by the fields of hint
, from
and to
. These identify the current and target format of input
, respectively.
Supported Hints
bytes
: A byte array, specificallyUint8Array
utf8
: AString
with UTF-8 encodingbase64
: AString
with Base64 encodingsafe-base64
: AString
with URL-Safe Base64 encoding
Errors
convert
is meant to provide safe and correct format conversion for your data. There are a number of checks in place that will throw errors if they fail:
- Specifying an unsupported conversion
- Failing to specify either
from
orto
- Specifying the same value for
from
andto
- Specifying a value for
from
that conflicts with the type ofinput
. ex, specifyingbytes
when the input is a string
Example
import assert from "assert"
import {confidential} from "panda-confidential"
{convert} = confidential()
assert.equal "Hello, World!",
convert from: "base64", to: "utf8", "SGVsbG8sIFdvcmxkIQ=="
assert.equal (Buffer.from "Hello, World!"),
convert from: "utf8", to: "bytes" , "Hello, World!"
assert.equal "Hello, World!",
convert from: "bytes", to: "utf8", Buffer.from "Hello, World!"