Hash a bounded byte value or incrementally hash larger input with an owned context.
Import
import stdlib/digest/sha256 as sha256
For an async function, select the async module instead:
import stdlib/digest/sha256/async as sha256
Await effectful operations. In the signatures below, an ordinary effectful function becomes async under the async import; parameter and result types stay the same. Pure functions and value methods remain ordinary calls. The two imports share their value and error types.
hash()
pure hash(data: Bytes): Bytes
Parameters
data: Bytes— at most 16 MiB.
Returns: Bytes, the 32-byte SHA-256 digest.
Pure and synchronous, including when imported through /async. It does not yield. Use a context for larger inputs or smaller cooperative work steps.
Errors: Oversized input traps rather than returning a Result. Unsupported hosts also report a VM error for this pure operation.
create()
create(): Result[Sha256Context,Sha256Error]
Parameters
None.
Returns: Result[Sha256Context,Sha256Error].
Creates a new context owned by the invocation. At most 65,536 contexts may be created per invocation.
Errors: Initialization, resource-limit and unsupported-host failures are reported.
update()
update(context: Sha256Context, data: Bytes): Result[Unit,Sha256Error]
Parameters
context: Sha256Context— live context.data: Bytes— next chunk, at most 65,536 bytes.
Returns: Result[Unit,Sha256Error].
Appends bytes to the running digest. The async form performs one bounded atomic step, then yields. Oversized chunks are rejected before mutation and can be retried in smaller pieces.
Errors: Invalid context, oversized chunk and digest failure are distinct. A digest-library failure invalidates the context.
finish()
finish(context: Sha256Context): Result[Bytes,Sha256Error]
Parameters
context: Sha256Context— live context.
Returns: Result[Bytes,Sha256Error], the 32-byte digest.
Finalises and consumes the context, including when finalisation fails. Do not call close after successful finish or reuse an alias.
Errors: Invalid context and finalisation failure are reported.
close()
close(context: Sha256Context): Result[Unit,Sha256Error]
Parameters
context: Sha256Context— live unfinished context.
Returns: Result[Unit,Sha256Error].
Releases the context without producing a digest and invalidates all aliases. Use this when abandoning a calculation.
Errors: A consumed, closed or foreign context is invalid.
Ownership and cancellation
Contexts cannot cross invocation boundaries. Async operations yield after a bounded native mutation, not halfway through it. Cancellation before that step makes no change; cancellation afterwards does not roll it back. Task/VM teardown closes owned resources. A failure to allocate an acknowledgement after mutation closes the context rather than leaving an uncertain reusable state.
Sha256Error
record Sha256Error { operation: Sha256Operation, kind: Sha256ErrorKind, native: HostError }
operation identifies creation, update (with byte count), finish or close. Input contents and handles are not retained. Use problem.kind for control flow and render for a human-readable explanation. The native field preserves the original failure. Host-backed native errors contain operation: Str, code: Str and native_code: Nat; a zero native number means no host error number was supplied.
enum Sha256ErrorKind {
InvalidContext, ChunkTooLarge, InvalidArgument, InitializationFailed,
DigestFailed, ResourceLimit, UnsupportedHost, OtherFailure
}
Sha256Error.render()
pure render(): Str
Parameters
None.
Returns: Str, a human-readable explanation of this error, including the available operation and failure details.
Pure. Use the structured error fields for control flow; the wording is diagnostic text and must not be parsed.
Example
Hash multiple chunks with cleanup.
Complete example: async digest
import stdlib/digest/sha256/async as digest
import stdlib/console/async as console
import stdlib/host/async as host
async hash_parts(parts: [Bytes]): Result[Bytes,Str] {
match await digest.create() {
Error(problem) => Error(problem.render()),
Ok(context) => {
mut failure: Option[Str] = None()
for part in parts {
if failure == None() {
match await digest.update(context, part) {
Ok(updated) => (), Error(problem) => { failure = Some(problem.render()); () }
}
}
}
match failure {
None() => {
// finish consumes the context, even if finalisation fails.
match await digest.finish(context) {
Ok(hash) => Ok(hash), Error(problem) => Error(problem.render())
}
},
Some(message) => match await digest.close(context) {
Ok(closed) => Error(message),
Error(cleanup) => Error(message + "\nCleanup also reported: " + cleanup.render())
}
}
}
}
}
async main(): Unit {
match await hash_parts(["a".encode_utf8(), "bc".encode_utf8()]) {
Error(message) => {
reported = await console.write_error_line(message)
await host.exit(1)
},
Ok(hash) => {
matches = hash == digest.hash("abc".encode_utf8())
match await console.write_line("Chunked SHA-256 matches one-shot: ${matches}") {
Error(write_error) => await host.exit(1), Ok(written) => ()
}
}
}
}Implementation: view source on GitHub.