Starknet 백서

Starknet

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 14쪽

ore::traits::BitOr; #[derive(Drop, PartialEq)] struct Scalar { inner: bool, } impl BitOrScalar of BitOr { fn bitor(lhs: Scalar, rhs: Scalar) -> Scalar { Scalar { inner: lhs.inner | rhs.inner } } } assert!(Scalar { inner: true } | Scalar { inner: true } == Scalar { inner: true }); assert!(Scalar { inner: true } | Scalar { inner: false } == Scalar { inner: true }); assert!(Scalar { inner: false } | Scalar { inner: true } == Scalar { inner: true }); assert!(Scalar { inner: false } | Scalar { inner: false } == Scalar { inner: false }); ``` ## Trait functions ### bitor Performs the `|` operation. #### Signature ```rust theme={null} fn bitor(lhs: T, rhs: T) -> T ``` #### Examples ```rust theme={null} assert!(1_u8 | 2_u8 == 3); ``` # core::traits::BitXor Source: https://docs.starknet.io/build/corelib/core-traits-BitXor The bitwise XOR operator `^`. ## Signature ```rust theme={null} pub trait BitXor ``` ## Examples An implementation of `BitXor` for a wrapper around `bool`. ```rust theme={null} use core::traits::BitXor; #[derive(Drop, PartialEq)] struct Scalar { inner: bool, } impl BitXorScalar of BitXor { fn bitxor(lhs: Scalar, rhs: Scalar) -> Scalar { Scalar { inner: lhs.inner ^ rhs.inner } } } assert!(Scalar { inner: true } ^ Scalar { inner: true } == Scalar { inner: false }); assert!(Scalar { inner: true } ^ Scalar { inner: false } == Scalar { inner: true }); assert!(Scalar { inner: false } ^ Scalar { inner: true } == Scalar { inner: true }); assert!(Scalar { inner: false } ^ Scalar { inner: false } == Scalar { inner: false }); ``` ## Trait functions ### bitxor Performs the `^` operation. #### Signature ```rust theme={null} fn bitxor(lhs: T, rhs: T) -> T ``` #### Examples ```rust theme={null} assert!(1_u8 ^ 2_u8 == 3); ``` # core::traits::Copy Source: https://docs.starknet.io/build/corelib/core-traits-Copy A trait for copying values. By default, variables in Cairo have 'move semantics', meaning they are moved when used. However, types implementing `Copy` have 'copy semantics', allowing the value to be duplicated instead of moved. ## Signature ```rust theme={null} pub trait Copy ``` ## Examples Without `Copy` (move semantics): ```rust theme={null} #[derive(Drop)] struct Point { x: u128, y: u128, } fn main() { let p1 = Point { x: 5, y: 10 }; foo(p1); foo(p1); // error: Variable was previously moved. } fn foo(p: Point) {} ``` With `Copy` (copy semantics): ```rust theme={null} #[derive(Copy, Drop)] struct Point { x: u128, y: u128, } fn main() { let p1 = Point { x: 5, y: 10 }; foo(p1); foo(p1); // works: `p1` is copied when passed to `foo` } fn foo(p: Point) {} ``` # core::traits::Default Source: https://docs.starknet.io/build/corelib/core-traits-Default A trait for giving a type a useful default value. Cairo implements `Default` for various primitives types. This trait can be used with `#[derive]` if all of the type's fields implement `Default`. When `derive`d, it will use the default value for each field's type. <Info> When using `#[derive(Default)]` on an `enum`, you need to choose which unit variant will be default. You do this by placing the `#[default]` attribute on the variant. ```rust theme={null} #[derive(Default)] enum Kind { #[default] A, B, C, } ``` You can even use the `#[default]` attribute even on non-unit variants, provided that the associated type implements `Default`. </Info> ## Signature ```rust theme={null} pub trait Default ``` ## Examples ```rust theme={null} #[derive(Drop, Default, PartialEq)] struct SomeOptions { foo: i32, bar: u32, } assert!(Default::default() == SomeOptions { foo: 0, bar: 0 }); ``` To implement `Default`, provide an implementation for the `default()` method that returns the value of your type that should be the default: ```rust theme={null} #[derive(Copy, Drop)] enum Kind { A, B, C, } impl DefaultKind of Default { fn default() -> Kind { Kind::A } } ``` ## Trait functions ### default Returns the "default value" for a type. Default values are often some kind of initial value, identity value, or anything else that may make sense as a default. #### Signature ```rust theme={null} fn default() -> T ``` #### Examples ```rust theme={null} let i: i8 = Default::default(); let (x, y): (Option, u64) = Default::default(); let (a, b, (c, d)): (i32, u32, (bool, bool)) = Default::default(); ``` # core::traits::Destruct Source: https://docs.starknet.io/build/corelib/core-traits-Destruct A trait that allows for custom destruction behavior of a type. In Cairo, values must be explicitly handled - they cannot be silently dropped. Types can only go out of scope in two ways: 1. Implement `Drop` - for types that can be discarded trivially 2. Implement `Destruct` - for types that need cleanup when destroyed. Typically, any type that contains a `Felt252Dict` must implement `Destruct`, as the `Felt252Dict` needs to be "squashed" when going out of scope to ensure a program is sound. Generally, `Destruct` does not need to be implemented manually. It can be derived from the `Drop` and `Destruct` implementations of the type's fields. ## Signature ```rust theme={null} pub trait Destruct ``` ## Examples Here's a simple type that wraps a `Felt252Dict` and needs to be destructed: ```rust theme={null} use core::dict::Felt252Dict; // A struct containing a Felt252Dict must implement Destruct #[derive(Destruct, Default)] struct ResourceManager { resources: Felt252Dict, count: u32, } #[generate_trait] impl ResourceManagerImpl of ResourceManagerTrait{ fn add_resource(ref self: ResourceManager, resource_id: felt252, amount: u32){ assert!(self.resources.get(resource_id) == 0, "Resource already exists"); self.resources.insert(resource_id, amount); self.count += amount; } } let mut manager = Default::default(); // Add some resources manager.add_resource(1, 100); // When manager goes out of scope here, Destruct is automatically called, // which ensures the dictionary is properly squashed ``` ## Trait functions ### destruct #### Signature ```rust theme={null} fn destruct(self: T) ``` # core::traits::Div Source: https://docs.starknet.io/build/corelib/core-traits-Div The division operator `/`. Types implementing this trait support the division operation via the `/` operator. ## Signature ```rust theme={null} pub trait Div ``` ## Examples `Div`isible types: ```rust theme={null} assert!(4_u8 / 2_u8 == 2_u8); ``` Implementing `Div` for a type: ```rust theme={null} #[derive(Copy, Drop, PartialEq)] struct Point { x: u32, y: u32, } impl PointDiv of Div { fn div(lhs: Point, rhs: Point) -> Point { Point { x: lhs.x / rhs.x, y: lhs.y / rhs.y, } } } let p1 = Point { x: 2, y: 4 }; let p2 = Point { x: 2, y: 2 }; let p3 = p1 / p2; assert!(p3 == Point { x: 1, y: 2 }); ``` ## Trait functions ### div Performs the `/` operation. #### Signature ```rust theme={null} fn div(lhs: T, rhs: T) -> T ``` #### Examples ```rust theme={null} assert!(12 / 2 == 6); ``` # core::traits::DivEq Source: https://docs.starknet.io/build/corelib/core-traits-DivEq ## Signature ```rust theme={null} pub trait DivEq ``` ## Trait functions ### div\_eq #### Signature ```rust theme={null} fn div_eq(ref self: T, other: T) ``` # core::traits::DivRem Source: https://docs.starknet.io/build/corelib/core-traits-DivRem Performs truncated division and remainder. This trait provides a way to efficiently compute both the quotient and remainder in a single operation. The division truncates towards zero, matching the behavior of the `/` and `%` operators. ## Signature ```rust theme={null} pub trait DivRem ``` ## Examples ```rust theme={null} assert!(DivRem::div_rem(7_u32, 3) == (2, 1)); ``` ## Trait functions ### div\_rem Performs the `/` and the `%` operations, returning both the quotient and remainder. #### Signature ```rust theme={null} fn div_rem(lhs: T, rhs: NonZero) -> (T, T) ``` #### Examples ```rust theme={null} assert!(DivRem::div_rem(12_u32, 10) == (1, 2)); ``` # core::traits::Drop Source: https://docs.starknet.io/build/corelib/core-traits-Drop A trait for types that can be safely dropped. Types implementing `Drop` can be automatically discarded when they go out of scope. The drop operation is a no-op - it simply indicates to the compiler that this type can be safely discarded. ## Signature ```rust theme={null} pub trait Drop ``` ## Examples Without `Drop`: ```rust theme={null} struct Point { x: u128, y: u128, } fn foo(p: Point) {} // Error: `p` cannot be dropped ``` With `Drop`: ```rust theme={null} #[derive(Drop)] struct Point { x: u128, y: u128, } fn foo(p: Point) {} // OK: `p` is dropped at the end of the function ``` # core::traits::Felt252DictValue Source: https://docs.starknet.io/build/corelib/core-traits-Felt252DictValue A trait that must be implemented for any type that will be stored as a value in a `Felt252Dict`. When working with dictionaries in Cairo, we need a way to represent "empty" or "uninitialized" slots. This trait provides a zero-like default value that is returned when accessing a key that hasn't been explicitly set. <Info> The `Felt252Dict` implementation needs to handle cases where a key hasn't been assigned a value yet. Instead of using `Option` or similar constructs, it uses a zero-like value specific to each type. This trait is only implemented for primitive scalar types and `Nullable`. It cannot be implemented manually. Instead, if you want to use a custom type as a value in a dictionary, you can wrap your type in a [`Nullable`](./core-nullable-Nullable), which implements `Felt252DictValue` for any wrapped type. </Info> ## Signature ```rust theme={null} pub trait Felt252DictValue ``` ## Examples ```rust theme={null} use core::dict::Felt252Dict; #[derive(Copy, Drop, Default)] struct Counter { value: u32, } // u8 already implements Felt252DictValue let mut dict: Felt252Dict = Default::default(); assert!(dict.get(123) == 0); // Counter is wrapped in a Nullable, as it doesn't implement Felt252DictValue let mut counters: Felt252Dict> = Default::default(); // If the key is not set, `deref` would panic. `deref_or` returns the default value. let maybe_counter: Nullable = counters.get(123); assert!(maybe_counter.deref_or(Default::default()).value == 0); ``` ## Trait functions ### zero\_default Returns the default value for this type when used in a `Felt252Dict`. This value should be logically equivalent to zero or an "empty" state. #### Signature ```rust theme={null} fn zero_default() -> T ``` # core::traits::Index Source: https://docs.starknet.io/build/corelib/core-traits-Index ## Signature ```rust theme={null} pub trait Index ``` ## Trait functions ### index #### Signature ```rust theme={null} fn index(ref self: C, index: I) -> V ``` # core::traits::IndexView Source: https://docs.starknet.io/build/corelib/core-traits-IndexView ## Signature ```rust theme={null} pub trait IndexView ``` ## Trait functions ### index #### Signature ```rust theme={null} fn index(self: @C, index: I) -> V ``` # core::traits::Into Source: https://docs.starknet.io/build/corelib/core-traits-Into A value-to-value conversion that consumes the input value. Note: This trait must not fail. If the conversion can fail, use [`TryInto`](./core-traits-TryInto). ## Signature ```rust theme={null} pub trait Into ``` # Generic Implementations * [`Into`](./core-traits-Into) is reflexive, which means that `Into` is implemented ## Examples Converting from RGB components to a packed color value: ```rust theme={null} #[derive(Copy, Drop, PartialEq)] struct Color { // Packed as 0x00RRGGBB value: u32, } impl RGBIntoColor of Into { fn into(self: (u8, u8, u8)) -> Color { let (r, g, b) = self; let value = (r.into() * 0x10000_u32) + (g.into() * 0x100_u32) + b.into(); Color { value } } } // Convert RGB(255, 128, 0) to 0x00FF8000 let orange: Color = (255_u8, 128_u8, 0_u8).into(); assert!(orange == Color { value: 0x00FF8000_u32 }); ``` ## Trait functions ### into Converts the input type T into the output type S. #### Signature ```rust theme={null} fn into(self: T) -> S ``` #### Examples ```rust theme={null} let a: u8 = 1; let b: u16 = a.into(); ``` # core::traits::Mul Source: https://docs.starknet.io/build/corelib/core-traits-Mul The multiplication operator `*`. ## Signature ```rust theme={null} pub trait Mul ``` ## Examples Multipliable types: ```rust theme={null} assert!(3_u8 * 2_u8 == 6_u8); ``` Implementing `Mul` for a type: ```rust theme={null} #[derive(Copy, Drop, PartialEq)] struct Point { x: u32, y: u32, } impl PointMul of Mul { fn mul(lhs: Point, rhs: Point) -> Point { Point { x: lhs.x * rhs.x, y: lhs.y * rhs.y, } } } let p1 = Point { x: 2, y: 3 }; let p2 = Point { x: 1, y: 0 }; let p3 = p1 * p2; assert!(p3 == Point { x: 2, y: 0 }); ``` ## Trait functions ### mul Performs the `*` operation. #### Signature ```rust theme={null} fn mul(lhs: T, rhs: T) -> T ``` #### Examples ```rust theme={null} assert!(12 * 2 == 24); ``` # core::traits::MulEq Source: https://docs.starknet.io/build/corelib/core-traits-MulEq ## Signature ```rust theme={null} pub trait MulEq ``` ## Trait functions ### mul\_eq #### Signature ```rust theme={null} fn mul_eq(ref self: T, other: T) ``` # core::traits::Neg Source: https://docs.starknet.io/build/corelib/core-traits-Neg The unary negation operator `-`. ## Signature ```rust theme={null} pub trait Neg ``` ## Examples An implementation of `Neg` for `Sign`, which allows the use of `-` to negate its value. ```rust theme={null} #[derive(Copy, Drop, PartialEq)] enum Sign { Negative, Zero, Positive, } impl SignNeg of Neg { fn neg(a: Sign) -> Sign { match a { Sign::Negative => Sign::Positive, Sign::Zero => Sign::Zero, Sign::Positive => Sign::Negative, } } } // A negative positive is a negative assert!(-Sign::Positive == Sign::Negative); // A double negative is a positive assert!(-Sign::Negative == Sign::Positive); // Zero is its own negation assert!(-Sign::Zero == Sign::Zero); ``` ## Trait functions ### neg Performs the unary `-` operation. #### Signature ```rust theme={null} fn neg(a: T) -> T ``` #### Examples ```rust theme={null} let x: i8 = 1; assert!(-x == -1); ``` # core::traits::Not Source: https://docs.starknet.io/build/corelib/core-traits-Not The unary logical negation operator `!`. ## Signature ```rust theme={null} pub trait Not ``` ## Examples An implementation of `Not` for `Answer`, which enables the use of `!` to invert its value. ```rust theme={null} #[derive(Drop, PartialEq)] enum Answer { Yes, No, } impl AnswerNot of Not { fn not(a: Answer) -> Answer { match a { Answer::Yes => Answer::No, Answer::No => Answer::Yes, } } } assert!(!Answer::Yes == Answer::No); assert!(!Answer::No == Answer::Yes); ``` ## Trait functions ### not Performs the unary `!` operation. #### Signature ```rust theme={null} fn not(a: T) -> T ``` #### Examples ```rust theme={null} assert!(!true == false); assert!(!false == true); ``` # core::traits::PanicDestruct Source: https://docs.starknet.io/build/corelib/core-traits-PanicDestruct A trait that allows for destruction of a value in case of a panic. This trait is automatically implemented from the `Destruct` implementation for a type. ## Signature ```rust theme={null} pub trait PanicDestruct ``` ## Trait functions ### panic\_destruct #### Signature ```rust theme={null} fn panic_destruct(self: T, ref panic: Panic) ``` # core::traits::PartialEq Source: https://docs.starknet.io/build/corelib/core-traits-PartialEq Trait for comparisons using the equality operator. Implementing this trait for types provides the `==` and `!=` operators for those types. This trait can be used with `#[derive]`. When `derive`d on structs, two instances are equal if all fields are equal, and not equal if any fields are not equal. When `derive`d on enums, two instances are equal if they are the same variant and all fields are equal. ## Signature ```rust theme={null} pub trait PartialEq ``` ## Examples An example in which two points are equal if their x and y coordinates are equal. ```rust theme={null} #[derive(Copy, Drop)] struct Point { x: u32, y: u32 } impl PointEq of PartialEq { fn eq(lhs: @Point, rhs: @Point) -> bool { lhs.x == rhs.x && lhs.y == rhs.y } } let p1 = Point { x: 1, y: 2 }; let p2 = Point { x: 1, y: 2 }; assert!(p1 == p2); assert!(!(p1 != p2)); ``` ## Trait functions ### eq Returns whether `lhs` and `rhs` equal, and is used by `==`. #### Signature ```rust theme={null} fn eq(lhs: @T, rhs: @T) -> bool ``` #### Examples ```rust theme={null} assert!(1 == 1); ``` ### ne Returns whether `lhs` and `rhs` are not equal, and is used by `!=`. #### Signature ```rust theme={null} fn ne(lhs: @T, rhs: @T) -> bool ``` #### Examples ```rust theme={null} assert!(0 != 1); ``` # core::traits::PartialOrd Source: https://docs.starknet.io/build/corelib/core-traits-PartialOrd Trait for comparing types that form a partialorder. The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using the \`\`, and `>=` operators, respectively. PartialOrd is not derivable, but can be implemented manually ## Signature ```rust theme={null} pub trait PartialOrd ``` # Implementing `PartialOrd` Here's how to implement `PartialOrd` for a custom type. This example implements comparison operations for a 2D point where points are compared based on their squared Euclidean distance from the origin (0,0): ```rust theme={null} #[derive(Copy, Drop, PartialEq)] struct Point { x: u32, y: u32, } impl PointPartialOrd of PartialOrd { fn lt(lhs: Point, rhs: Point) -> bool { let lhs_dist = lhs.x * lhs.x + lhs.y * lhs.y; let rhs_dist = rhs.x * rhs.x + rhs.y * rhs.y; lhs_dist p1); assert!(p2 >= p1); ``` Note that only the `lt` method needs to be implemented. The other comparison operations (`le`, `gt`, `ge`) are automatically derived from `lt`. However, you can override them for better performance if needed. ## Trait functions ### lt Tests less than (for `self` and `other`) and is used by the \`(lhs: T, rhs: T) -> bool ``` ### ge Tests less than or equal to (for `self` and `other`) and is used by the `(lhs: T, rhs: T) -> bool ``` ### gt Tests greater than (for `self` and `other`) and is used by the `>` operator. #### Signature ```rust theme={null} fn gt(lhs: T, rhs: T) -> bool ``` #### Examples ```rust theme={null} assert_eq!(1 > 1, false); assert_eq!(1 > 2, false); assert_eq!(2 > 1, true); ``` ### le Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. #### Signature ```rust theme={null} fn le(lhs: T, rhs: T) -> bool ``` #### Examples ```rust theme={null} assert_eq!(1 >= 1, true); assert_eq!(1 >= 2, false); assert_eq!(2 >= 1, true); ``` # core::traits::Rem Source: https://docs.starknet.io/build/corelib/core-traits-Rem The remainder operator `%`. Types implementing this trait support the remainder operation via the `%` operator. ## Signature ```rust theme={null} pub trait Rem ``` ## Examples ```rust theme={null} assert!(3_u8 % 2_u8 == 1_u8); ``` ## Trait functions ### rem Performs the `%` operation. #### Signature ```rust theme={null} fn rem(lhs: T, rhs: T) -> T ``` #### Examples ```rust theme={null} assert!(12_u8 % 10_u8 == 2_u8); ``` # core::traits::RemEq Source: https://docs.starknet.io/build/corelib/core-traits-RemEq ## Signature ```rust theme={null} pub trait RemEq ``` ## Trait functions ### rem\_eq #### Signature ```rust theme={null} fn rem_eq(ref self: T, other: T) ``` # core::traits::Sub Source: https://docs.starknet.io/build/corelib/core-traits-Sub The subtraction operator `-`. ## Signature ```rust theme={null} pub trait Sub ``` ## Examples `Sub`tractable types: ```rust theme={null} assert!(3_u8 - 2_u8 == 1_u8); ``` Implementing `Sub` for a type: ```rust theme={null} #[derive(Copy, Drop, PartialEq)] struct Point { x: u32, y: u32, } impl
프로젝트로 돌아가기