From 17a7e9bd171bb933e1641c7af0bc1d0767d4bc84 Mon Sep 17 00:00:00 2001 From: Tristan <122918260+TAdev0@users.noreply.github.com> Date: Fri, 29 Nov 2024 19:56:22 +0100 Subject: [PATCH] Core Lib Documentation: `Panics` module (#6785) Co-authored-by: enitrat --- corelib/src/panics.cairo | 53 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/corelib/src/panics.cairo b/corelib/src/panics.cairo index 3c2012e0492..3913014e969 100644 --- a/corelib/src/panics.cairo +++ b/corelib/src/panics.cairo @@ -1,16 +1,65 @@ +//! Core panic mechanism. +//! +//! This module provides the core panic functionality used for error handling in Cairo. +//! It defines the basic types and functions used to trigger and manage panics, which +//! are Cairo's mechanism for handling unrecoverable errors. +//! +//! Panics can be triggered in several ways: +//! +//! Using the `panic` function: +//! +//! ``` +//! use core::panics::panic; +//! +//! panic(array!['An error occurred']); +//! ``` +//! +//! Or using the `panic!` macro: +//! +//! ``` +//! panic!("Panic message"); +//! ``` +//! +//! This macro internally converts the message into a `ByteArray` and uses `panic_with_byte_array`. + use crate::array::Array; +/// Represents a panic condition in Cairo. +/// +/// A `Panic` is created when the program encounters an unrecoverable error condition +/// and needs to terminate execution. pub struct Panic {} +/// Result type for operations that can trigger a panic. pub enum PanicResult { Ok: T, Err: (Panic, Array), } +/// Triggers an immediate panic with the provided data and terminates execution. +/// +/// # Examples +/// +/// ``` +/// use core::panics::panic; +/// +/// panic(array!['An error occurred']); +/// ``` pub extern fn panic(data: Array) -> crate::never; -/// Panics with the given ByteArray. That is, panics with an `Array` with -/// `BYTE_ARRAY_MAGIC`, and then the serialized given ByteArray. +/// Panics with a `ByteArray` message. +/// +/// Constructs a panic message by prepending the `BYTE_ARRAY_MAGIC` value and +/// serializing the provided `ByteArray` into the panic data. +/// +/// # Examples +/// +/// ``` +/// use core::panics::panic_with_byte_array; +/// +/// let error_msg = "An error occurred"; +/// panic_with_byte_array(@error_msg); +/// ``` #[inline] pub fn panic_with_byte_array(err: @ByteArray) -> crate::never { let mut serialized = array![crate::byte_array::BYTE_ARRAY_MAGIC];