"""Utilities for advanced usage of ownership and borrowing."""fromcollections.abcimportCallablefromtypingimportno_type_checkfromguppylang_internals.decoratorimportcustom_functionfromguppylang_internals.std._internal.compiler.memimportWithOwnedCompilerfromguppylang_internals.std._internal.compiler.preludeimportMemSwapCompilerfromguppylangimportguppyfromguppylang.std.langimportownedT=guppy.type_var("T",copyable=False,droppable=False)Out=guppy.type_var("Out",copyable=False,droppable=False)
[docs]@custom_function(MemSwapCompiler())@no_type_checkdefmem_swap(x:T,y:T)->None:"""Swaps the values of two variables."""
[docs]@custom_function(WithOwnedCompiler())@no_type_checkdefwith_owned(val:T,f:Callable[[T@owned],tuple[Out,T]])->Out:"""Runs a closure where the borrowed argument is promoted to an owned one. The closure should return two values: * A generic return value that will be passed through. * Another value of type `T` that is written back into the borrowed place. This can either be the original passed value, or a new value of the same type that was created in the closure. Pretending that `val` is a pointer, this would be equivalent to the following operation in Rust/C: ``(out, *val) = f(*val)`` """