Tumgik
jacob-cs · 2 months
Text
coin trading PYTHON LIBRARIES
0 notes
jacob-cs · 2 months
Text
FREE SSL FOR wordpress
youtube
0 notes
jacob-cs · 3 months
Text
flask, nginx, uwgsi
0 notes
jacob-cs · 3 months
Text
godaddy flask setup
0 notes
jacob-cs · 3 months
Text
replit selenium , nix
replit 에서 selenium을 어떻게 사용하는지 알려주는 글
nix를 이용한 페키지 관리방법
0 notes
jacob-cs · 11 months
Text
RADIX scrypto 2
Tumblr media Tumblr media Tumblr media
vault method
Tumblr media Tumblr media Tumblr media
Accepting a Bucket of Resource
Tumblr media
if the ResourceAddress of the resource contained in the Bucket doesn’t match the ResourceAddress of the Vault, then the Radix Engine will not allow the resource to be passed into this Vault. Although, we can create some safety measures using assertions or simply send friendly messages!
Tumblr media
Returning a Bucket of Resource
When we need to send back tokens to the user, we’ll return the user a Bucket of tokens.
Tumblr media
Returning Overpayments
Tumblr media
you can specify behaviors to mark a resource as mintable, burnable or even restrict its withdrawal, making them “Soulbound” tokens. When specifying resource behaviors, you can also specify authorization rules around it to determine what badges need to be present before that action can be taken. We can also determine the mutability of these authorization rules to have the ability to change the authorization rules in the future or lock its mutability to prevent its rules from being changed.
List of Resource Behaviors
Tumblr media Tumblr media
Making a Resource Mintable
Tumblr media
mintable(AccessRule, Mutability)
The first argument is an AccessRule .  in brief, it is a Scrypto native concept which allows you to specify rules around the action you want to enforce. With this argument, we offer a macro rule!() that you can call for convenience. Since we specified rule!(allow_all), we’ve indicated that this resource can be minted by anyone.
The second argument is Mutability , this deals with the mutability of the rule.  determine whether this rule can be changed in the future. The Mutability argument under the hood is actually an enum, one of the selection of the enum is LOCKED, which means that this resource will always be freely minted by anyone and we can’t change the permission in the future. Alternatively, you can pass an AccessRule argument if you’d like to set rules around the ability to change rules in the future.
Making a Resource Burnable
Having a resource burnable indicates that an specified supply of this resource can essentially be destroyed. If all the supply of that resource is burnt, the ResourceManager will still exist. we call the .burnable() method when we create our resource.
Tumblr media
Burning our Resource Token
Tumblr media
Restricting Resource Withdrawal
Resources that have the restrict_withdraw flag can't be withdrawn and are effectively locked in the Vault that contains it. This makes the resource soulbound.
Tumblr media
Restricting Resource Deposit
Resources that are restricted from being deposited are commonly called transient resources. Applying the restrict_deposit flag forces a dangling resource to exist. Therefore, if the resource can’t be deposited into a Vault, the resource must be burnt, else we will encounter a dangling resource error. Transient resources are most commonly used as a means to force a specified condition to happen within a transaction. If that condition is met, we can permit the resource to be burned. Alternatively, if we specify an authorization requirement, we can allow this resource to be deposited (when the specified badge is present) if a certain condition is met.
Tumblr media
Allowing the Resource’s NonFungibleData to be Updateable
Each NonFungible resource has unique data that can be attributed to it. Therefore, we can allow this data to be changed. We can also specify that a badge must be present in order for the data to be changed if we apply an authorization requirement to this resource flag.
Tumblr media
Making a Resource Recallable
Having a resource to be recallable allows us to send our tokens to anybody, but have the ability for us to retrieve it if we desire. The most common use case for this is to allow for “Rental NFTs”. We can create conditions in how long this resource can essentially be borrowed for.
Tumblr media
ResourceManager
The resource address you receive after creating a new resource maps to a ResourceManager. ResourceManager defines how all of the individual tokens of a certain resource behave. For example, the token name, symbol, and supply is defined in its ResourceManager. As we will see later, it also defines the rules for actions (like minting and burning) for that particular resource. In the same token, we need to use the ResourceManager to perform resource actions (like minting and burning).
Tumblr media Tumblr media Tumblr media Tumblr media
Using the ResourceManager to Mint Tokens
Tumblr media
Using ResourceManager to Query Data
You can use resim to display the information related to a particular ResourceManager with resim show [resource_manager_address]:
Tumblr media
Using the ResourceManager Programmatically
Tumblr media
.
.
.
아래는 토큰거래하는 블루프린트 만드는 과정
Defining our blueprint
Tumblr media
Creating our Resource(s)
Tumblr media
Defining our Struct
Tumblr media
Defining our Component Instantiation
Tumblr media
Notice that the way we want to instantiate this Vault is by calling .new() which doesn’t accept Bucket as an argument, but rather a ResourceAddress. Since we will be expecting our payments to be received through this component, we want to create a Vault that receives the payment that we want. In this case the RADIX_TOKEN. RADIX_TOKEN is the globally recognized ResourceAddress of XRD, the native token of the Radix Network.
Creating our Instantiation Function
Tumblr media
Defining Methods
Tumblr media Tumblr media
위는 나머지 잔돈을 거슬러 주는 기능추가
full implementation
Tumblr media Tumblr media
Scrypto’s authorization model starts with three core concepts: Badges, Proofs, and Access Rules.
Badges
A badge is simply any token or resource that is used for authentication and authorization. Badges can either be a Fungible or NonFungible resource type; and anytime a user or component needs some form of authorization or authentication, the badge needs to be present before that action can be performed.
Proofs
proof는 badge의 사본같은 개념. 일시적으로 transaction에서만 사용가능
Proofs are a transient instance of a resource that can only exist within the duration of the transaction. For authorization and authentication, a Proof of the badge is sent instead of the actual badge. This is because assets on Scrypto have physical characteristics. When we send the physical badge to a component for authorization and authentication, that badge is physically being transferred away from our possession to the vault’s possession, effectively giving away our ownership of that badge. This can be dangerous because sending a badge to a malicious component effectively allows that component to use the badge for other means.
AccessRules
AccessRule is used to define security measures around your methods and resource behaviors. If you have certain methods you'd like to protect, you can quickly specify rules around what badge(s) are needed to call that method. Additionally, when we create resources, we can also set an AccessRule to protect resource behaviors such as the ability to mint or burn resource tokens. It is intuitive and easy to define your security measures, because much of your authorization needs are already baked into the platform.
Tumblr media
We now know that badges are the main resource we use for authorization and authentication.
Anytime we use badges for authorization, we instead want to submit a Proof of the badge to perform the authorization (as opposed to the actual badge itself).
We also introduced the concept of AccessRules that allows us to define security measures of our method calls and resource behaviors.
System-level Authentication
System-level authentication is performed by the Radix Engine. When we define AccessRules in our blueprint and implement them in our component, we communicate to the Radix Engine with the prerequisites required to perform an action. This is powerful as the Radix Engine is designed with a Finite State Machine to enforce strict resource management. Therefore, without having to consider potential edge-cases that may arise when building our own authorization system, the Radix Engine can enforce the rules we create around our components. After we’ve implemented AccessRules to our component, the Radix Engine can use the Proofs in the Authorization Zone and compare it against the badges specified in the component’s AccessRules.
The Authorization Zone (AuthZone)
Every transaction on the Radix Network contains a layer called the Authorization Zone or AuthZone. All Proofs are submitted in the AuthZone. Transactions submitted to the Radix Network are accompanied by the transaction manifest. Chapter 5 explains that the transaction manifest is a list of instruction(s) that describes a sequence of component method calls and movements of resources between components.
If there are AccessRules applied to these method calls and/or resource behaviors, then Proof of the badge(s) is required before these actions can be performed.  Every Proof generated is then immediately placed in the AuthZone when submitted. The Radix Engine utilizes the Proofs in the AuthZone and automatically compares the Proofs against the badges required by AccessRules implemented in the component. If the Proofs of the badge(s) satisfies the required badge(s) needed to perform an action, access to such action is granted and the call succeeds. Otherwise, the transaction immediately aborts.
Application-level Authentication
While every Proof is automatically sent to the AuthZone, we are not confined to authenticating Proofs in the AuthZone.   Instead, we can send Proofs directly to our component method(s) to perform our own authentications. This way of applying application-level authentication is called Passing Proofs by Intent. When we pass a Proof directly to our component method(s), authentications are handled by ProofValidation (that we will go over later in this chapter).
Conceptually speaking, when we design our component’s methods, we can specify to accept Proofs as an argument and create ProofValidation rules within the method logic for every Proof that is passed to our method(s). Arguably, the selection of ProofValidation we perform on Proofs sent to our methods can be more flexible compared to rules defined using AccessRules. While Passing Proof by Intent exposes us with more flexible authentications, more importantly, sending Proofs directly to our component method(s) allows us to read and utilize the NonFungibleData of the resource (if the resource is a NonFungible type)
Creating Fungible Badges
Creating badges is as simple as creating a resource as shown in Chapter 3. A badge is any resource (whether Fungible or NonFungible) that is used for authorization.
Tumblr media
Creating NonFungible Badges
Tumblr media
Fungible or NonFungible Badges?
If you need to uniquely identify your users you should create a NonFungible badge. This will allow you to refer to your users by their badge’s ID and also attach relevant information on the badge itself.
If you only care that the user has a particular badge without having to identify them separately, you should use a Fungible badge instead.
0 notes
jacob-cs · 11 months
Text
RADIX scrypto 1
Accounts on the Radix network are actually Scrypto components that hold resource containers and define rules for accessing them.
You can instantiate a new account component in the simulator with the resim new-account
This will give you back the created account’s address, public key and private key.
Additionally, at any time, you can find the current default account with the command resim show-configs.
You can send tokens from the default account to another one by running the command:
resim transfer [amount] [resource_address] [recipient_address]
Tumblr media
Let’s verify the balance of the second account. You can query the state of an address with the resim show [address] command.
resim show resource_sim1qyqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqs6d89k
Tumblr media
to easily create a boilerplate Scrypto package with basic functionality. To do this, simply type the following command scrypto new-package [package_name].
Directory Structure
At the root of the generated package directory, you should find the src, and tests folders plus a Cargo.toml file.
The tests folder is where you write the integration tests for your package. You can run the tests located in this directory with the scrypto test command.
All packages must have a lib.rs file - which is the starting point of your Scrypto package.
Tumblr media Tumblr media Tumblr media
You can think of blueprints and components like classes and objects in object-oriented programming.
When you create a new project with the scrypto new-package command, it creates a Scrypto package. A simple package, like the HelloToken example, will only contain a single blueprint but you could “package” together multiple blueprints that need each-other to work when deploying them on the ledger. That way, you are certain that all your blueprints are deployed at the same time and the platform knows that those blueprints are related to each other.
(즉 하나의 팩키지에 여러개의 블루프린트가 있을수있으며 하나의 팩키지안의 여러 블루프린트는 서로 연관되어있다고 여겨진다)
Tumblr media
#[blueprint]. A blueprint definition must contain a struct and an impl section with the name of the blueprint
impl 블락 안에
you will write the functions callable on the blueprint itself and the methods callable on the instantiated components.
It’s important to make a distinction between functions and methods:
Functions can be called on the blueprints and do not have access to any state.
Methods on the other hand are callable on individual components and are able to get data from the state and update or mutate it.
Tumblr media
위는 function 의 한 예시
Tumblr media
위는 method의 한 예시
&mut self가 전달되면 메소드 가 된다
Safe Types
These types are just like the u8, i8, u16, etc. but they differ in the fact that they panic (and make the transaction fail) if an overflow occurs when doing operations on them. You define these types by using an uppercase U for unsigned numbers and uppercase I for signed numbers:
I8, I16, I32, I64, I128, I256, I384, I512
U8, U16, U32, U64, U128, U256, U384, U512
They also have the benefit of offering 384 bits and 512 bits options instead of a maximum of 128 bits.
Strings
The String type is supported in Scrypto.
Floating points
the Rust types f32 and f64 representing floating point numbers are not supported in Scrypto. Instead, we offer the Decimal and PreciseDecimal types that allow you to represent numbers with a fractional part using fixed point arithmetic (which is deterministic).
Tumblr media
you have to wrap the number in quotes (as seen for c and e in the previous example). If you don’t, you will not be able to compile your package because it will detect the use of floating point numbers.
The Decimal type supports a maximum of 18 decimal places -if you need more you should use PreciseDecimal which supports up to 64 decimal places:
Tumblr media
Collections
Scrypto supports the basic Rust collections like Vec, HashMap and HashSet. We also provide a new type KeyValueStore which is like a HashMap, but it does not load the full content of the Map until you request it. Here are some examples:
Scrypto Types
The PackageAddress, ComponentAddress and ResourceAddress types are used to work with the different address types. The Scrypto types you will work with the most are the Bucket and Vault types
Creating Custom Types
You create a custom type by writing a struct outside of the blueprint! definition. It is important to remember to add the line #[scrypto(ScryptoCategorize, ScryptoEncode, ScryptoDecode, LegacyDescribe)] before the struct block. This adds, at compile time, methods to the type to make it compatible with the Radix Engine. Here is an example:
Tumblr media Tumblr media Tumblr media Tumblr media
To test our blueprint locally we will use resim. You may recall we saw how to use resim to create accounts and transfer tokens in the simulator. By running the resim --help command you will see that you can do much more with resim. In our case, we will use it to publish our package to the local simulator, instantiate our component, and call a method to interact with it.
To ensure we have a clean slate to begin with let’s run resim reset and then generate a new default account by running resim new-account be sure to save the account address as we will want to inspect it later. You can save this as an environment variable for convenience or just create a file for your own reference to copy and paste.
The next step is to build and deploy the package. You can do that with the following command: resim publish . (make sure you are in the hello_token directory!).
To create an instance of our deployed blueprint we will use the package address that we just received to instantiate our component by calling the instantiate_hello function on the Hello blueprint by running
resim call-function [package_address] [blueprint_name] [function]
which will look something like this:
resim call-function package_sim1qxxkyjgkyryztmtlsypzd8244xkvqeln32aqdersgk3szcwxzq Hello instantiate_hello
After running the call-function command above, you will get various information about the transaction that was executed.
Tumblr media Tumblr media
Now that we have an instantiated Hello component, all the methods defined by its blueprint are exposed to us and callable. We are going to call the free_token method on it with a resim command resim call-method [component_address] [method]
token도 resource 중의 한가지 이다
Resources are built into the platform
Resources on Radix need to always be placed in some kind of resource containers. Resource containers, as the name suggest, hold resources. Each resource container can only hold one type of resource and the purpose of these resource containers are to properly move, secure, and account for the resources that are being transacted. There are two types of resource containers: Bucket and Vault.
Bucket - Buckets are temporary containers and are used to move resources during a transaction; therefore, only exist in the duration of the transaction.
Vault - Vaults are permanent containers and at the end of each transaction, all resources must be stored in a Vault.
Scrypto offers a handful of utilities to conveniently create and manage resources.
ResourceBuilder - The ResourceBuilder is used to create Fungible and NonFungible resources.
ResourceManager - When a resource is created, a ResourceManager is also created to manage the resource.
The ResourceBuilder is a Scrypto utility that we use to create Fungible and NonFungible resources. Below is a table summarizing the methods provided by the ResourceBuilder for Fungible resources.
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
Notice that we have fields such as color and rarity. These values are a selection of enums and if you're not familiar with enums, the Rust handbook provides a section on enums.
Tumblr media Tumblr media
Creating a NonFungible Resource
Creating a NonFungible resource is a little different from creating a Fungible resource as we saw in the earlier section. To give some context, when we create a NonFungible resource, the collection of the NonFungible resource will have one ResourceAddress. However, each individual NonFungible that we decide to mint will have its own unique identifiers called NonFungibleLocalId. We have an option of data types we can declare to be our NonFungibleLocalId, but it is a requirement to declare a type.
아래는 integer를 id 로 사용하는 경우이다
Tumblr media
Creating NFTs with a Mutable Supply
You can create NFTs with no specified initial supply. To do so, we would need to create a badge that will be held by the component Vault.
Tumblr media Tumblr media
Viewing, Utilizing, and Mutating NonFungibleData
Tumblr media
full example code
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
0 notes
jacob-cs · 11 months
Text
RUST 179-
cargo
Tumblr media
User input
Tumblr media Tumblr media Tumblr media
environmental variables
Tumblr media Tumblr media Tumblr media
? 연산자
Tumblr media Tumblr media Tumblr media Tumblr media
? 연산자는 Result, Option 리턴하는 함수안에서만 사용가능하다
Tumblr media
main 함수는 (), Result만 리턴 가능하
Tumblr media
?연산자는 Err를 만나게되면 바로 함수 호출자에게 Err를 리턴한다
밑의 나머지 코드는 실행되지 않는다
file read write
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
위는 위위 코드의 축약
Tumblr media
위는 화일 만들고 바로 쓰기 방법
Tumblr media Tumblr media
cargo doc
Tumblr media
0 notes
jacob-cs · 11 months
Text
RUST 171-178 in english
time
Tumblr media Tumblr media Tumblr media Tumblr media
-
macro에 대한 참고 공부내용
Tumblr media Tumblr media Tumblr media
-
useful macro unreachable!()
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
macro
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
위는 틀린 코드
Tumblr media Tumblr media Tumblr media
https://www.youtube.com/watch?v=7aY3NzriR_Y&list=PLfllocyHVgsRwLkTAhG0E-2QxCf-ozBkk&index=177&pp=iAQB
macro이용 struct, function만들
Tumblr media
매크로 안에서 매크로 자신을 호출할수 있다.
Tumblr media Tumblr media
0 notes
jacob-cs · 11 months
Text
RUST 155-170 in english
Tumblr media Tumblr media
위와 위위는 같은 작업인데 아래 rayon을 이용한 경우가 좀더 빠르다 (parallel작업)
Tumblr media
 rust crates 페이지
Tumblr media
rust game engine
Tumblr media
array
Tumblr media
위는 틀린 코드. array 를 for loop 하고 같이 쓰려면  &[] 를 이용해야함
Tumblr media
위는 맞는 코드
Tumblr media
.iter() 를 이용한 위 코드도 맞는 코드
Tumblr media
[], () 를 이용해서 분해 할당 가능하다
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
integer
Tumblr media
add implementation
Tumblr media
아래도 이어짐
Tumblr media Tumblr media
사칙연산을 implementation할수 있다.
floats
Tumblr media Tumblr media
위 맞는 코드
Tumblr media
위 맞는 코드
bool
Tumblr media Tumblr media Tumblr media
Vec
Tumblr media Tumblr media
my_vec의 4번째에 있는 0 이 sort하고 나서 맨 앞의 0가 아닐수 있다.
이런 문제를 상관하지 않고 sort하는 것을 sort_unstable()이라고 한다
Tumblr media
String
String은 Vec의 한 종류이다
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
다양한 String
Tumblr media Tumblr media
mem
Tumblr media Tumblr media
transmute
Tumblr media Tumblr media
no_implicit_prelude
Tumblr media
function pointer
https://youtu.be/HduA3uaF_Ac
https://youtu.be/1sgBm7Z0CW8
0 notes
jacob-cs · 11 months
Text
RUST 134-154
channel
Tumblr media
위 경우 잘못된 경우 하나의 쓰레드만 수행되고 나머지가 수행되는 도중에 이미 프로그램이 끝나서 나머지 쓰레드 수행이 완료되지 못하는 상황
Tumblr media
위는 올바른 경우
Tumblr media
위는 올바른 경우 
Tumblr media
attributes
Tumblr media Tumblr media
기본으로 unused_variables, dead_code는 warn 하게 설정되어있는데
만약 명시적으로 설정한다면 위와 같다 (단 전역적으로 설정하는 것이므로 [ 앞에 !가 있어야하는 점이 빠졌음)
Tumblr media
기본 설정을 없애는 경우
Tumblr media
test attribute로 함수안에서 패닉이 발생하면 failed로 판단되게 한다
Tumblr media
위는 컴파일을 선택적으로 하게 설정하는 방법
Tumblr media
attributes 목록, 사용예시 링크
Default , builder pattern
Tumblr media Tumblr media
위 builder pattern에서 validation하는 함수 build를 만들어주고 
최종 작업은 build가 하게 한다
dereferencing , dot operator
Tumblr media Tumblr media Tumblr media
&오브젝트.메소드  와  
&&오브젝트.메소드  와  
&&&&&&오브젝트.메소드
다 같은 것이다 
Ref, DeRef
Tumblr media Tumblr media Tumblr media
위는 틀린 코드 HoldsANumber 가 deref 를 구현하고 있지 않기 때문이다
Tumblr media
기본 Deref 가 위와 같고 이를 기반으로 implement해야 한다
Tumblr media
위 올바르게 구현한 경우
Tumblr media
deref, derefmut는 . operator가 가능하게 만들어 준다. 즉 이를 통해 다양한 기능을 물려 받을수 있다. 위의 경우 pow 메소드를 사용할수 있게 된경우
Tumblr media Tumblr media
위위, 위 사진은 Deref를 implement  해서 * operator 에 특정 작업을 하는 경우를 보여준다
module, mod
Tumblr media Tumblr media
crate - mod - fn 의 순으로 구조되어있다.
한 화일안에서 mod를 접근할수 있지만 다른 곳에서는 pub mod로 지정해주지 않으면 접근 불가 하다. 
Tumblr media Tumblr media
struct는 pub mod를 통해 struct를 public으로 설정할수 있다. 그렇게 해도 각각의 property 를 또 설정해줘야 한다.
enum의 경우는 pub enum으로 안의 요소까지 다 public 으로 만들수 있다 
Tumblr media Tumblr media
testing
Tumblr media
testing 긴예시 코드
Tumblr media
0 notes
jacob-cs · 1 year
Text
RUST 122-133 in english
Arc
Tumblr media
위는 잘못된 코드 (타이포 borrow_mut() )
Rc는 쓰레드와 같이 사용할수 없다는 것을 보여준다.
Tumblr media
thread safe가 되기 위해서는 Send, Sync 두개다 가져야 한다
Tumblr media
위와 같이 RefCell의 경우는 Send는 있지만 Sync는 없으므로 thread safe 가 아님
Tumblr media
Arc , Mutex 같이 사용하기
Tumblr media Tumblr media
위 작동하는 코드 (단 타이포 Arc::new(Mutex::new(0))에서  Mutex 가 아니고 RwLock이)
Arc, RwLock 같이 사용한 경우 
Tumblr media Tumblr media
closure
Tumblr media Tumblr media
refs_it 에서 사용된경우는  borrow 방법 (Fn 방법) my_string이 closure안에서 값이 변화되지는 않았기 때문
mutes_it 에서 사용된 경우는 FnMut 방법 이다.  my_string이 closure안에서 값이 변화되었 때문
Tumblr media Tumblr media Tumblr media
위 맞는 코드 단( 타이포  cool_book.year % 2 == 0 )
Tumblr media Tumblr media
impl trait
Tumblr media
위 와 아래는 같은 효과
Tumblr media
Box
Tumblr media Tumblr media
위 array는 스택에 만들어지기 때문에 빠르지만 위와 같이 대용량 사용이 불가능하다 그래서  box를 이용해 heap 대용량 데이터를 저장할수 있다
Tumblr media
위와 같이 사용할수 있을것 같지만 사실은 아니다. 왜냐하면 데이터를 스택에 먼저 만들고 그것을 복사해서 heap에 만들기 때문이다
그래서 아래가 맞는 방법이다
Tumblr media Tumblr media
box는 포인터를 스택에 저장하고 데이터는 힙에 저장하므로
모든 box의 사이즈는 8 바이트로 같다
Tumblr media
box의 값에 접근해서 수정하는 경우 포인터와 같이 * operator를 이용한다
dyn
Tumblr media Tumblr media Tumblr media
channel
Tumblr media Tumblr media
위 타입 T 가 명시 되지 않았기 때문에 패닉
Tumblr media
위는 타입T가 정해졌으므로 패닉하지 않음
Tumblr media Tumblr media Tumblr media
0 notes
jacob-cs · 1 year
Text
RUST
https://youtu.be/m76sRj2VgGo
pointer
1. reference
단순히 메모리 주소를 가진다 (값을 빌려옴)
2. smart pointer
pointer 처럼 행동하는 데이터 스트럭쳐이며 추가적인 메타데이터, 기능을 가지고 있다. 실제로 데이터를 가지고 있다. String, Vector가 스마트 포인터의 종류이다
보통 deref, drop trait을 implementing 한다
Tumblr media Tumblr media
위 틀린 코드
Tumblr media
위 맞는 코드 작성중
Tumblr media
https://youtu.be/dYEC6NElVOg
Tumblr media
위 맞는 코드
Tumblr media
위 틀린코드 (마지막 부분)
Tumblr media
위 맞는 코드
Deref
Tumblr media Tumblr media
위 틀린 코드 Deref trait을 implement 해야 한다
Tumblr media Tumblr media
위 실제로 작동하는 내용을 자세하게 보여줌. 사실 컴파일러가 줄여서 *y 만으로도 작동하게 도와준다
Tumblr media
&String => &str 로 자동 변환된다. deref coercian 이라고 하고 규칙은 아래와 같다. mutable type을 deref하려는 경우는 DerefMut을 사용한다
Tumblr media
Drop
https://youtu.be/RPWZcTYBS4k
smart pointer 는 Deref , Drop trait을 implement 해야한다.
아래는 Drop trait implementing하는 법을 보여주고 있다.
아래와 같이 smart pointer struct를 통해 drop을 호출하는 것은 금지 
standard library의 drop을 통해 memory에서 없애는 것은 가
Tumblr media
Rc
https://youtu.be/M9Owp3iLigg
Tumblr media Tumblr media
위는 한번 a의 오너쉽이 Box::new()에 전달되었는데 밑에서 또 사용하려고 하기 때문에 잘못된 코드
Tumblr media
위는 올바른 코드
Tumblr media
위는 약간 변형된 형태로 똑같은 효과를 가진다
Tumblr media
아래는 결과
Tumblr media
interior mutability
https://youtu.be/77aRH6YBKyY
Tumblr media
위에서 &mut a;가 잘못된 이유는 애초에 a는 immutable이기 때문이다
위에서*d = 20;이 잘못된 이유는 애초에 &mut으로 하지 않았기 때문이다
0 notes
jacob-cs · 1 year
Text
RUST 113-121 in english
type, use, as
Tumblr media
위는 축약전
아래는 type , use 를 사용해서 줄인 코드
Tumblr media Tumblr media Tumblr media
todo!
Tumblr media
위 에러 발생
Tumblr media
위 작동 잘함
Tumblr media
unimplemented 와 같은 효과 todo
Rc
Tumblr media
위 struct의 impl 된 함수의 경우 마치 Class 함수처럼 접근도 가능하다
Tumblr media Tumblr media Tumblr media
위 Rc , RefCell 를 같이 사용한 경우
thread
Tumblr media
위의 경우 main함수가 두개의 thread 가 작업을 끝낼때 까지 기다리지 않고 
함수 끝에 도달하면 프로그램은 멈추게 된다
Tumblr media
join 을 통해 thread 작업이 마무리 될때 까지 기다린
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
순차적으로 쓰레드가 끝나는걸 보면 진정한 concurrency 가 아니다
Tumblr media
위 concurrency
2 notes · View notes
jacob-cs · 1 year
Text
RUST runtime
https://youtu.be/1QoT9fmPYr8
Tumblr media Tumblr media
맞는 코드 오너쉽을 넘겨주고 { }이 끝났기 때문에 문제 없음
Tumblr media
틀린 코드 { } 안에서 b 가 끝나고 없어지므로 garbage reference를 가지게 된다
Tumblr media
함수안에서 만들어진 a 는 함수안에서 사라지는데 이를 reference로 넘겨줬기 때문에 문제
Tumblr media
외부  scope의 lifetime을 가지고 있는 것을 받아서 다시 돌려 줬기 때문에 문제없다. 이정도는 <’a>가 없어도 compiler가 알아서 처리 한다
Tumblr media
맞는 코드
Tumblr media
위 문제 없음
Tumblr media
위 문제 없음 함수 리턴값이 &’a i32이고 param_1 에만 해당하고 param_2는 리턴값과 연관성이 없으므로 lifetime지정하지 않아도 된다
Tumblr media Tumblr media
리턴값이 어떤개 될지 모르지만 최소한 ‘a lifetime을 가진다고 표현한경우 (’b:’a 뜻은 b lifetime이 a lifetime보다 길다는 뜻 즉 최소한 a lifetime은 된다는 뜻)
이런경우는 흔치 않고 아래와 같이 같은 lifetime인 경우가 보통이다
Tumblr media Tumblr media
위에서 첫번째, 두번째는 맞는 코드
세번째는 틀린 예시 reference로 받은 게 없고 오너십과 함께 받은 파라미터는 함수가 끝나면 사라지는데 이걸 reference로 넘겨주면 garbage reference 가 된다
Tumblr media Tumblr media
위 맞는 코드
Tumblr media
위 맞는 코드
Tumblr media
위 맞는코드
Tumblr media
맞는 코드
0 notes
jacob-cs · 1 year
Text
RUST 100-112 in english
lifetime
Tumblr media
위에서 my_string은 lifetime specifier가 설정되어있지 않아서 문제
Tumblr media
static으로 lifetime으로 해도 my_string은 함수내에서만 존재하므로 문제발생
Tumblr media Tumblr media
위는 작동하는 코드
Tumblr media
위는 작동하는 코드
Tumblr media
위는 작동하지 않는 코드
Tumblr media
1 각각의 파라미터는 각각의 lifetime을 가지나 보통은 하나로 통일해서 사용하는 경우가 많다
2. 파라미터가 하나고 reference 리턴이 하나 있는 경우. 하나의 lifetime으로 컴파일러가 간주 처리한다
3. 여러 파라미터중 &self , &mut self가 있는 경우 lifetime self가 적용된 
Tumblr media
위 틀린 코드
Tumblr media
위 맞는 코드. 아래와 같이 축약도 가능하다
anonymous lifetime
Tumblr media
위 맞는 코드
Tumblr media
위 맞는 코드
Tumblr media
위 맞는 코드
interior mutability
Tumblr media Tumblr media Tumblr media
위 맞는 코드
RefCell
Tumblr media
위 맞는 코드
Tumblr media
위 mutable reference를 두번 borrow하려고 해서 패닉
그리고 Cell, RefCell은 런타임에서 다이나믹하게 처리된다
Tumblr media Tumblr media
빌린 reference를 통해서는 값을 볼수 있지만 빌려진 원래 변수를 통해서는 값을 확인할수 없는 것에 유의
Tumblr media
above , after drop we can see value through variable which was borrowed
Tumblr media
위위  drop을 이용하는 방법이 번거로운 경우 위 같이 좀더 간단하게 사용할수 있다
Tumblr media Tumblr media
Cell에서 take는 값을 take하고 Cell안은 default 값으로 남기는 것이
Mutex
Tumblr media
Mutex를 통해 interior mutability를 구현할수 있다. Mutex와 thread와 같이 사용해도 안전하다. lock() 하면 다른 곳에서 접근 불가하다
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
위 패닉이 발생할것으로 보이지만 실상은 timeout이 되버린다.
처음 lock하고 다음에서 lock하려고 계속 기다리게 된다
Tumblr media
위 첫번째 lock에서 lock되고 try_lock()에서는 값변경이 이루어지지않는다
Tumblr media
첫번째 lock이후 drop이 되고 try_lock()이 실행되고 값이 변경되고 변수에 저장한게 아니므로 작업후 바로 lock 이 풀린다. 그리고 출력하면 lock된 상태가 아니고 변경된 값은 변경된게 출력된다.
RwLock 
read write lock
Tumblr media
위는 Mutex를 사용한 경우 아래는 RwLock을 사용한 경우 
둘은 매우 비슷하다
Tumblr media Tumblr media
Cow
Tumblr media
vector slice
Tumblr media Tumblr media
0 notes
jacob-cs · 1 year
Text
RUST 89- in korean
inspect
Tumblr media
&str
Tumblr media
&str 를 못쓴다. 아래와 같이는 사용할수 있다
Tumblr media
lifetime
Tumblr media Tumblr media Tumblr media
위에서 사용한 static 틀린 예시
Tumblr media
위는 맞게 사용한 경우
Tumblr media
위는 틀리게 사용한 경우
Tumblr media
위는 맞게 사용한 경우
Tumblr media
두개의 다른 lifetime을 이용할수도 있지만 이런 경우는 매우 드물다
Tumblr media
impl에 lifetime을 설정해 주지 않아서 틀린 예시
Tumblr media Tumblr media
Cell
Tumblr media
Cell 은 thread safe 아님(스레드와 사용불가)
Cell을 이용하면 mut 지정없이도 mutable로 만들수 있다
https://doc.rust-lang.org/stable/std/cell/struct.Cell.html
Tumblr media Tumblr media
cell을 copy trait을 impl 한 타입과 사용하면 괜찮지만 아닌경우 
위와 같이 에러 발생한다.
String같이 copy 타입이 아닌경우 아래와 같이 RefCell을 이용할수있다 
RefCell
copy 타입이거나 아니거나 둘다에 사용가능하다
Tumblr media Tumblr media Tumblr media
reference와 같이 두군데서 borrow할수는 없다
Tumblr media
첫번째 RefCell(true)
두번째 RefCell(borrowed)
세번째 RefCell(borrowed) - 안에 값은 바뀌었지만 상태가 borrowed이다
네번째 RefCell(false)
Tumblr media Tumblr media
Rc
Tumblr media
0 notes