├── src ├── features │ ├── currying_function.rs │ ├── enum_type.rs │ ├── new_types.rs │ ├── mod.rs │ ├── rust_io_impl.rs │ ├── union_type.rs │ ├── channels_feature.rs │ ├── do_notation_style.rs │ ├── race_futures.rs │ ├── extension_method.rs │ ├── dependency_injection.rs │ ├── promise.rs │ ├── type_classes.rs │ ├── memory_management.rs │ ├── lens.rs │ ├── monad.rs │ ├── try_monad.rs │ ├── collection.rs │ ├── smart_pointer.rs │ ├── async_programming.rs │ ├── effect_system.rs │ ├── functions.rs │ ├── either_monad.rs │ └── pattern_matching.rs └── main.rs ├── SQUICD ├── src │ ├── lib.rs │ ├── common.rs │ └── main.rs ├── Cargo.toml ├── cert.crt ├── cert.key └── README.md ├── img ├── tc.png ├── bevy.png ├── design.png ├── kafka.png ├── lambda.jpg ├── rust.jpg ├── actix-web.png ├── reactivex.png └── red_panda.png ├── patterns ├── src │ ├── structural │ │ ├── mod.rs │ │ ├── decorator.rs │ │ ├── facade.rs │ │ └── composite.rs │ ├── creational │ │ ├── mod.rs │ │ ├── factory.rs │ │ ├── singleton.rs │ │ └── builder.rs │ ├── behavioral │ │ ├── mod.rs │ │ ├── chain_of_responsibility.rs │ │ ├── strategy.rs │ │ └── memento.rs │ └── main.rs ├── Cargo.toml └── README.md ├── architecture ├── src │ └── main.rs └── Cargo.toml ├── dragon_ball ├── assets │ ├── dbz.ogg │ ├── trunk.png │ ├── dr_hero.png │ ├── trunk_b.png │ ├── android_17.png │ ├── android_18.png │ ├── background.png │ ├── trunk_player.png │ ├── dr_hero_player.png │ ├── android_17_player.png │ └── android_18_player.png ├── Cargo.toml └── README.md ├── golden_axe ├── assets │ ├── logo.png │ ├── player.png │ ├── Heninger.png │ ├── Longmoan.png │ ├── barbarian.png │ ├── Storchinaya.png │ └── background.png ├── Cargo.toml └── README.md ├── monkey_island ├── img │ └── game.png ├── assets │ ├── logo.png │ ├── guybrush.png │ ├── lechuck.png │ ├── background.png │ ├── monkey_island.ogg │ └── guybrush_monkey.png ├── Cargo.toml └── README.md ├── quiche-feature ├── img │ ├── output.png │ ├── output-2.png │ └── output-3.png ├── Cargo.toml ├── README.md ├── cert.crt └── cert.key ├── street_fighter ├── assets │ ├── ken.png │ ├── ryu.png │ ├── fight.ogg │ ├── hadooken.ogg │ ├── background.png │ ├── ken_player.png │ ├── ryu_player.png │ └── shoryuken.ogg ├── Cargo.toml └── README.md ├── street_of_rage ├── assets │ ├── red.png │ ├── axel.png │ ├── logo.png │ ├── punk.png │ ├── round.png │ ├── skin.png │ ├── street.png │ └── street_extra.png ├── Cargo.toml └── README.md ├── ai_api_integration ├── pkg │ ├── README.md │ ├── ai_api_integration_bg.wasm │ ├── package.json │ ├── ai_api_integration_bg.wasm.d.ts │ └── ai_api_integration.d.ts ├── Cargo.toml ├── README.md ├── src │ └── lib.rs └── index.html ├── RxRust └── Cargo.toml ├── .gitignore ├── dynamic_loading_contract ├── Cargo.toml └── src │ └── lib.rs ├── kafka ├── src │ ├── main.rs │ ├── kafka_producer.rs │ └── kafka_consumer.rs ├── Cargo.toml └── kafka.iml ├── .idea ├── vcs.xml ├── misc.xml └── modules.xml ├── rust_ai_model ├── Cargo.toml └── src │ └── main.rs ├── actix ├── src │ ├── main.rs │ ├── actix_web_server.rs │ └── actix_server.rs ├── Cargo.toml ├── static │ └── index.html └── actix.iml ├── tokio ├── build.rs ├── proto │ └── grpc_service.proto ├── src │ ├── tokio_async.rs │ ├── tokio_green_thread.rs │ ├── main.rs │ ├── tokio_grpc_client.rs │ ├── tokio_select.rs │ ├── tokio_grpc_server.rs │ └── tokio_http_hyper.rs ├── tokio.iml └── Cargo.toml ├── dynamic_loading_plugin ├── Cargo.toml └── src │ └── lib.rs ├── kds-feature ├── Cargo.toml └── README.md ├── test_container └── Cargo.toml ├── rust_ai_dsl ├── Cargo.toml └── src │ └── main.rs ├── goose ├── src │ ├── main.rs │ ├── mock_http_server.rs │ └── goose_load_test.rs ├── Cargo.toml └── goose.iml ├── physics_engine ├── Cargo.toml └── src │ ├── main.rs │ ├── ball.rs │ └── launcher.rs ├── rust_io └── Cargo.toml ├── actor_model └── Cargo.toml ├── rust_chain ├── Cargo.toml └── src │ └── main.rs ├── game_3d ├── Cargo.toml └── src │ ├── main.rs │ ├── board.rs │ ├── director.rs │ └── player.rs ├── Cargo.toml ├── ai_hello_world_model ├── Cargo.toml ├── README.md └── hello_rust.csv ├── dynamic_loading ├── Cargo.toml └── src │ └── main.rs ├── red_panda ├── Cargo.toml ├── red_panda.iml └── src │ └── red_panda_producer.rs ├── red_panda_benchmark ├── Cargo.toml ├── src │ ├── produce_consume_load_test.rs │ ├── consume_load_test.rs │ └── produce_load_test.rs └── README.md ├── LICENSE └── index.html /src/features/currying_function.rs: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /SQUICD/src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod common; 2 | pub mod dsl; 3 | -------------------------------------------------------------------------------- /img/tc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/img/tc.png -------------------------------------------------------------------------------- /img/bevy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/img/bevy.png -------------------------------------------------------------------------------- /img/design.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/img/design.png -------------------------------------------------------------------------------- /img/kafka.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/img/kafka.png -------------------------------------------------------------------------------- /img/lambda.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/img/lambda.jpg -------------------------------------------------------------------------------- /img/rust.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/img/rust.jpg -------------------------------------------------------------------------------- /patterns/src/structural/mod.rs: -------------------------------------------------------------------------------- 1 | mod composite; 2 | mod decorator; 3 | mod facade; 4 | -------------------------------------------------------------------------------- /img/actix-web.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/img/actix-web.png -------------------------------------------------------------------------------- /img/reactivex.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/img/reactivex.png -------------------------------------------------------------------------------- /img/red_panda.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/img/red_panda.png -------------------------------------------------------------------------------- /patterns/src/creational/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod builder; 2 | pub mod factory; 3 | pub mod singleton; 4 | -------------------------------------------------------------------------------- /patterns/src/behavioral/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod chain_of_responsibility; 2 | mod memento; 3 | mod strategy; 4 | 5 | -------------------------------------------------------------------------------- /architecture/src/main.rs: -------------------------------------------------------------------------------- 1 | mod circuit_breaker; 2 | 3 | fn main() { 4 | println!("Hello, world!"); 5 | } 6 | -------------------------------------------------------------------------------- /dragon_ball/assets/dbz.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/dragon_ball/assets/dbz.ogg -------------------------------------------------------------------------------- /golden_axe/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/golden_axe/assets/logo.png -------------------------------------------------------------------------------- /monkey_island/img/game.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/monkey_island/img/game.png -------------------------------------------------------------------------------- /dragon_ball/assets/trunk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/dragon_ball/assets/trunk.png -------------------------------------------------------------------------------- /golden_axe/assets/player.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/golden_axe/assets/player.png -------------------------------------------------------------------------------- /monkey_island/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/monkey_island/assets/logo.png -------------------------------------------------------------------------------- /quiche-feature/img/output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/quiche-feature/img/output.png -------------------------------------------------------------------------------- /street_fighter/assets/ken.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_fighter/assets/ken.png -------------------------------------------------------------------------------- /street_fighter/assets/ryu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_fighter/assets/ryu.png -------------------------------------------------------------------------------- /street_of_rage/assets/red.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_of_rage/assets/red.png -------------------------------------------------------------------------------- /dragon_ball/assets/dr_hero.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/dragon_ball/assets/dr_hero.png -------------------------------------------------------------------------------- /dragon_ball/assets/trunk_b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/dragon_ball/assets/trunk_b.png -------------------------------------------------------------------------------- /golden_axe/assets/Heninger.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/golden_axe/assets/Heninger.png -------------------------------------------------------------------------------- /golden_axe/assets/Longmoan.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/golden_axe/assets/Longmoan.png -------------------------------------------------------------------------------- /golden_axe/assets/barbarian.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/golden_axe/assets/barbarian.png -------------------------------------------------------------------------------- /quiche-feature/img/output-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/quiche-feature/img/output-2.png -------------------------------------------------------------------------------- /quiche-feature/img/output-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/quiche-feature/img/output-3.png -------------------------------------------------------------------------------- /street_fighter/assets/fight.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_fighter/assets/fight.ogg -------------------------------------------------------------------------------- /street_of_rage/assets/axel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_of_rage/assets/axel.png -------------------------------------------------------------------------------- /street_of_rage/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_of_rage/assets/logo.png -------------------------------------------------------------------------------- /street_of_rage/assets/punk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_of_rage/assets/punk.png -------------------------------------------------------------------------------- /street_of_rage/assets/round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_of_rage/assets/round.png -------------------------------------------------------------------------------- /street_of_rage/assets/skin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_of_rage/assets/skin.png -------------------------------------------------------------------------------- /dragon_ball/assets/android_17.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/dragon_ball/assets/android_17.png -------------------------------------------------------------------------------- /dragon_ball/assets/android_18.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/dragon_ball/assets/android_18.png -------------------------------------------------------------------------------- /dragon_ball/assets/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/dragon_ball/assets/background.png -------------------------------------------------------------------------------- /golden_axe/assets/Storchinaya.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/golden_axe/assets/Storchinaya.png -------------------------------------------------------------------------------- /golden_axe/assets/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/golden_axe/assets/background.png -------------------------------------------------------------------------------- /monkey_island/assets/guybrush.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/monkey_island/assets/guybrush.png -------------------------------------------------------------------------------- /monkey_island/assets/lechuck.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/monkey_island/assets/lechuck.png -------------------------------------------------------------------------------- /street_fighter/assets/hadooken.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_fighter/assets/hadooken.ogg -------------------------------------------------------------------------------- /street_of_rage/assets/street.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_of_rage/assets/street.png -------------------------------------------------------------------------------- /ai_api_integration/pkg/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | https://aistudio.google.com/app/apikey 4 | 5 | https://politrons.github.io/FunctionalRust/ -------------------------------------------------------------------------------- /dragon_ball/assets/trunk_player.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/dragon_ball/assets/trunk_player.png -------------------------------------------------------------------------------- /monkey_island/assets/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/monkey_island/assets/background.png -------------------------------------------------------------------------------- /street_fighter/assets/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_fighter/assets/background.png -------------------------------------------------------------------------------- /street_fighter/assets/ken_player.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_fighter/assets/ken_player.png -------------------------------------------------------------------------------- /street_fighter/assets/ryu_player.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_fighter/assets/ryu_player.png -------------------------------------------------------------------------------- /street_fighter/assets/shoryuken.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_fighter/assets/shoryuken.ogg -------------------------------------------------------------------------------- /dragon_ball/assets/dr_hero_player.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/dragon_ball/assets/dr_hero_player.png -------------------------------------------------------------------------------- /monkey_island/assets/monkey_island.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/monkey_island/assets/monkey_island.ogg -------------------------------------------------------------------------------- /street_of_rage/assets/street_extra.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/street_of_rage/assets/street_extra.png -------------------------------------------------------------------------------- /RxRust/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "RxRust" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | rxrust="1.0.0-beta.8" -------------------------------------------------------------------------------- /dragon_ball/assets/android_17_player.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/dragon_ball/assets/android_17_player.png -------------------------------------------------------------------------------- /dragon_ball/assets/android_18_player.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/dragon_ball/assets/android_18_player.png -------------------------------------------------------------------------------- /monkey_island/assets/guybrush_monkey.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/monkey_island/assets/guybrush_monkey.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | debug/78p9o´pç 4 | ç`´pñ´ñ.l.nc xz<>zxcvgbhjklñ´ññ¨´-.–.*.pdb 5 | -------------------------------------------------------------------------------- /patterns/src/main.rs: -------------------------------------------------------------------------------- 1 | mod creational; 2 | mod structural; 3 | mod behavioral; 4 | 5 | fn main() { 6 | println!("Hello pattern world!"); 7 | } 8 | -------------------------------------------------------------------------------- /ai_api_integration/pkg/ai_api_integration_bg.wasm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/politrons/FunctionalRust/HEAD/ai_api_integration/pkg/ai_api_integration_bg.wasm -------------------------------------------------------------------------------- /dynamic_loading_contract/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "dynamic_loading_contract" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | -------------------------------------------------------------------------------- /kafka/src/main.rs: -------------------------------------------------------------------------------- 1 | mod kafka_consumer; 2 | mod kafka_producer; 3 | 4 | fn main() { 5 | // kafka_consumer::run(); 6 | kafka_producer::run(); 7 | 8 | } 9 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /patterns/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "patterns" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /architecture/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "architecture" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | -------------------------------------------------------------------------------- /rust_ai_model/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust_ai_model" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | linfa = "0.7.0" 8 | linfa-logistic = "0.7.0" 9 | ndarray = "0.15.4" 10 | regex = "1.5.6" 11 | 12 | -------------------------------------------------------------------------------- /actix/src/main.rs: -------------------------------------------------------------------------------- 1 | mod actix_server; 2 | mod actix_web_server; 3 | 4 | #[actix_web::main] 5 | async fn main() -> std::io::Result<()> { 6 | // actix_server::run_server().await 7 | actix_web_server::run_server().await 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/features/enum_type.rs: -------------------------------------------------------------------------------- 1 | use crate::features::enum_type::RustTypes::IntegerR; 2 | 3 | pub fn run() { 4 | let x = IntegerR("1981"); 5 | } 6 | 7 | enum RustTypes { 8 | IntegerR(T), 9 | StringR(T), 10 | BooleanR(T), 11 | } -------------------------------------------------------------------------------- /tokio/build.rs: -------------------------------------------------------------------------------- 1 | /** 2 | gRPC main class responsible to build the code defined in [proto] file, using [protoc] command 3 | */ 4 | fn main() -> Result<(), Box> { 5 | tonic_build::compile_protos("proto/grpc_service.proto")?; 6 | Ok(()) 7 | } -------------------------------------------------------------------------------- /kafka/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "FunctionalRust" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | kafka = "0.9" 10 | uuid = "1.3.2" -------------------------------------------------------------------------------- /actix/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "FunctionalRust" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | actix-web = "4" 10 | actix-files = "0.6.2" -------------------------------------------------------------------------------- /dynamic_loading_contract/src/lib.rs: -------------------------------------------------------------------------------- 1 | ///The trait contract to be used by the [plugin] to create the implementation, 2 | /// and by the [dynamic_loading] cargo to load in runtime any implementation of this contract 3 | pub trait PluginTrait { 4 | fn hello_world(&self); 5 | } 6 | 7 | -------------------------------------------------------------------------------- /dynamic_loading_plugin/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "dynamic_loading_plugin" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [lib] 7 | crate-type = ["cdylib"] 8 | 9 | [dependencies] 10 | dynamic_loading_contract={ version = "0.1.0", path = "../dynamic_loading_contract" } -------------------------------------------------------------------------------- /monkey_island/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "monkey_island" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | bevy="0.11.0" 10 | bevy_audio = "0.11.0" -------------------------------------------------------------------------------- /kds-feature/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "kds-feature" 3 | version = "0.1.0" 4 | edition = "2024" 5 | 6 | [dependencies] 7 | aws-config = "1.2" 8 | aws-sdk-kinesis = "1.2" 9 | tokio = { version = "1", features = ["full"] } 10 | anyhow = "1" 11 | 12 | -------------------------------------------------------------------------------- /actix/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

Politrons Actix Web Page

6 | 7 | 8 | 9 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /test_container/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "test_container" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | testcontainers = "0.14.0" 8 | tokio = { version = "1.32.0", features = ["full"] } 9 | tokio-postgres = "0.7.10" 10 | uuid = { version = "1.10.0", features = ["v4"] } 11 | 12 | -------------------------------------------------------------------------------- /tokio/proto/grpc_service.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package grpcservice; 3 | 4 | service MyGrpc { 5 | rpc SimpleRequest (MyGrpcRequest) returns (MyGrpcResponse); 6 | } 7 | 8 | message MyGrpcRequest { 9 | string name = 1; 10 | } 11 | 12 | message MyGrpcResponse { 13 | string message = 1; 14 | } -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /rust_ai_dsl/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust_ai_dsl" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | reqwest = { version = "0.11", features = ["json"] } 8 | serde = { version = "1.0", features = ["derive"] } 9 | serde_json = "1.0" 10 | ureq = { version = "2.5.0", features = ["json"] } 11 | -------------------------------------------------------------------------------- /goose/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | 3 | use goose::prelude::*; 4 | 5 | mod mock_http_server; 6 | mod goose_load_test; 7 | 8 | #[tokio::main] 9 | async fn main() { 10 | // mock_http_server::run_server().await; 11 | let result = goose_load_test::run().await; 12 | println!("{:?}", result) 13 | } 14 | -------------------------------------------------------------------------------- /physics_engine/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "physics_engine" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | bevy="0.11.0" 10 | bevy_rapier2d = "0.22.0" 11 | bevy_prototype_lyon = "0.9.0" 12 | -------------------------------------------------------------------------------- /rust_io/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust_io" 3 | version = "0.6.0" 4 | edition = "2021" 5 | description="Macro implementation for [rust_io] defining several operators to be used emulating Haskel [do notation]" 6 | license="Apache-2.0" 7 | 8 | [dependencies] 9 | futures = "0.3" 10 | rand = "0.8.5" 11 | async-std = "1.12.0" -------------------------------------------------------------------------------- /actor_model/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "actor_model" 3 | version = "0.1.0" 4 | edition = "2024" 5 | 6 | [dependencies] 7 | tokio = { version = "1", features = ["full"] } 8 | serde = { version = "1.0", features = ["derive"] } 9 | bincode = "1.3" 10 | uuid = { version = "1.16.0", features = ["v4", "serde"] } 11 | 12 | 13 | -------------------------------------------------------------------------------- /quiche-feature/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "quiche-feature" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | quiche ="0.22.0" 8 | ring = "0.17.8" 9 | url = "2.5.2" 10 | mio = { version = "0.8", features = ["net", "os-poll"] } 11 | log = "0.4.22" 12 | rand = "0.9.0-alpha.2" 13 | env_logger = "0.11.5" 14 | -------------------------------------------------------------------------------- /rust_chain/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust_chain" 3 | version = "0.1.0" 4 | edition = "2024" 5 | 6 | [dependencies] 7 | sha2 = "0.10" # hashing SHA-256 8 | serde = { version = "1.0", features = ["derive"] } 9 | serde_json = "1.0" # para imprimir la cadena 10 | chrono = "0.4" # marca temporal 11 | 12 | -------------------------------------------------------------------------------- /street_of_rage/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "street_of_rage" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | bevy="0.11.0" 10 | bevy_audio = "0.11.0" 11 | rand = "0.8" 12 | lazy_static = "1.4.0" 13 | -------------------------------------------------------------------------------- /game_3d/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "game_3d" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | bevy="0.11.0" 10 | bevy_audio = "0.11.0" 11 | rand = "0.8" 12 | lazy_static = "1.4.0" 13 | bevy_third_person_camera = "0.1.5" -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "FunctionalRust" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | futures = "0.3" 10 | rand = "0.8.5" 11 | do-notation="0.1.3" 12 | async-std = "1.12.0" 13 | pl-lens = "1.0" 14 | rust_io="0.6.0" 15 | -------------------------------------------------------------------------------- /goose/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "FunctionalRust" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | goose="0.17.0" 10 | goose-eggs = "0.5.1" 11 | tokio = { version = "1", features = ["full"] } 12 | hyper = { version = "0.14", features = ["full"] } -------------------------------------------------------------------------------- /ai_hello_world_model/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ai_hello_world_model" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | csv = "1" 8 | serde = { version = "1.0", features = ["derive"] } 9 | bincode = "1.3" 10 | itertools = "0.12" 11 | ndarray = "0.15" 12 | linfa = "0.7.1" 13 | linfa-logistic = "0.7.1" 14 | 15 | -------------------------------------------------------------------------------- /dragon_ball/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "dragon_ball" 3 | version = "0.1.0" 4 | edition = "2021" 5 | description="Dragon ball Z Fight game" 6 | license="Apache-2.0" 7 | 8 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 9 | 10 | [dependencies] 11 | bevy="0.11.0" 12 | bevy_audio = "0.11.0" 13 | rand = "0.8" 14 | lazy_static = "1.4.0" -------------------------------------------------------------------------------- /dynamic_loading/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "dynamic_loading" 3 | version = "0.1.0" 4 | edition = "2021" 5 | default-libraries = false 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | libloading="0.8.0" 11 | dynamic_loading_contract={ version = "0.1.0", path = "../dynamic_loading_contract" } 12 | -------------------------------------------------------------------------------- /tokio/src/tokio_async.rs: -------------------------------------------------------------------------------- 1 | pub async fn run() { 2 | // Calling `say_world()` does not execute the body of `say_world()`. 3 | let op = say_world(); 4 | 5 | // This println! comes first 6 | println!("hello"); 7 | 8 | // Calling `.await` on `op` starts executing `say_world`. 9 | op.await; 10 | } 11 | 12 | async fn say_world() { 13 | println!("world"); 14 | } 15 | -------------------------------------------------------------------------------- /golden_axe/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "golden_axe" 3 | version = "0.1.0" 4 | edition = "2021" 5 | description="16 bits Golden Axe game engine" 6 | license="Apache-2.0" 7 | 8 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 9 | 10 | [dependencies] 11 | bevy="0.11.0" 12 | bevy_audio = "0.11.0" 13 | rand = "0.8" 14 | lazy_static = "1.4.0" -------------------------------------------------------------------------------- /red_panda/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "FunctionalRust" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | 7 | [[bin]] 8 | name = "red_panda_consumer" 9 | path = "src/red_panda_consumer.rs" 10 | 11 | [[bin]] 12 | name = "red_panda_producer" 13 | path = "src/red_panda_producer.rs" 14 | 15 | [dependencies] 16 | rdkafka = "0.25.0" 17 | tokio = { version = "1", features = ["full"] } 18 | -------------------------------------------------------------------------------- /tokio/src/tokio_green_thread.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | 3 | pub async fn run() { 4 | let handle = tokio::spawn(async { 5 | // Do some async work 6 | println!("Running in Thread:{:?}", thread::current().name()); 7 | "return value" 8 | }); 9 | 10 | // Do some other work 11 | 12 | let out = handle.await.unwrap(); 13 | println!("GOT {}", out); 14 | } -------------------------------------------------------------------------------- /ai_api_integration/pkg/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ai_api_integration", 3 | "type": "module", 4 | "version": "0.1.0", 5 | "files": [ 6 | "ai_api_integration_bg.wasm", 7 | "ai_api_integration.js", 8 | "ai_api_integration.d.ts" 9 | ], 10 | "main": "ai_api_integration.js", 11 | "types": "ai_api_integration.d.ts", 12 | "sideEffects": [ 13 | "./snippets/*" 14 | ] 15 | } -------------------------------------------------------------------------------- /street_fighter/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "street_fighter" 3 | version = "0.1.0" 4 | edition = "2021" 5 | description="16 bits Street Fighter 2 game engine" 6 | license="Apache-2.0" 7 | 8 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 9 | 10 | [dependencies] 11 | bevy="0.11.0" 12 | bevy_audio = "0.11.0" 13 | rand = "0.8" 14 | lazy_static = "1.4.0" -------------------------------------------------------------------------------- /game_3d/src/main.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy::prelude::shape::Plane; 3 | use bevy_third_person_camera::*; 4 | 5 | mod player; 6 | mod board; 7 | mod director; 8 | 9 | use player::PlayerPlugin; 10 | use board::BoardPlugin; 11 | use director::DirectorPlugin; 12 | 13 | fn main() { 14 | App::new() 15 | .add_plugins((DefaultPlugins,PlayerPlugin,BoardPlugin,DirectorPlugin, ThirdPersonCameraPlugin)) 16 | .run() 17 | } 18 | 19 | 20 | -------------------------------------------------------------------------------- /tokio/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | 3 | mod tokio_async; 4 | mod tokio_green_thread; 5 | mod tokio_http_hyper; 6 | mod tokio_select; 7 | mod tokio_grpc_server; 8 | 9 | 10 | #[tokio::main] 11 | async fn main() { 12 | // tokio_async::run().await; 13 | // tokio_green_thread::run().await; 14 | // tokio_http_hyper::run_server().await; 15 | // tokio_http_hyper::run_client().await; 16 | // tokio_select::race_condition().await; 17 | // server::run_server(); 18 | 19 | } 20 | 21 | -------------------------------------------------------------------------------- /monkey_island/README.md: -------------------------------------------------------------------------------- 1 | # Rust Monkey Island 2 | 3 | ![My image](img/game.png) 4 | 5 | Author Pablo Picouto Garcia 6 | 7 | A Tribute to the Monkey Island Game Engine Using [Bevy](https://bevyengine.org) 8 | 9 | ## Sprites 10 | 11 | ![My image](assets/guybrush.png) 12 | 13 | ![My image](assets/lechuck.png) 14 | 15 | ![My image](assets/guybrush_monkey.png) 16 | 17 | ## How to Play 18 | 19 | Clone the repo, and run ```Main``` class 20 | 21 | ## Keyboard 22 | 23 | ```Left, Right``` keyboards to move 24 | -------------------------------------------------------------------------------- /actix/actix.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /goose/goose.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /kafka/kafka.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /tokio/tokio.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /red_panda/red_panda.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /ai_api_integration/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ai_api_integration" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | wasm-bindgen = { version = "0.2.84", features = ["serde-serialize"] } 8 | wasm-bindgen-futures = "0.4.43" 9 | serde = { version = "1.0.209", features = ["derive"] } 10 | serde_json = "1.0.127" 11 | web-sys = { version = "0.3.70", features = ["Window", "Request", "Response", "RequestInit", "RequestMode","Headers", "console"] } 12 | 13 | [lib] 14 | crate-type = ["cdylib", "rlib"] 15 | 16 | [profile.release] 17 | opt-level = "z" 18 | lto = true 19 | codegen-units = 1 20 | -------------------------------------------------------------------------------- /game_3d/src/board.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | 3 | pub struct BoardPlugin; 4 | 5 | impl Plugin for BoardPlugin { 6 | 7 | fn build(&self, app: &mut App){ 8 | app.add_systems(Startup, spawn_board); 9 | } 10 | } 11 | 12 | fn spawn_board( 13 | mut command: Commands, 14 | mut mesh: ResMut>, 15 | mut materials: ResMut>) { 16 | let board = PbrBundle { 17 | mesh: mesh.add(Mesh::from(shape::Plane::from_size(15.0))), 18 | material: materials.add(Color::DARK_GREEN.into()), 19 | ..default() 20 | }; 21 | command.spawn(board); 22 | } -------------------------------------------------------------------------------- /patterns/README.md: -------------------------------------------------------------------------------- 1 | # Patterns 2 | 3 | ![My image](../img/design.png) 4 | 5 | 6 | ## Creational 7 | 8 | * **[Singleton](src/creational/singleton.rs)** 9 | * **[Builder](src/creational/builder.rs)** 10 | * **[Factory](src/creational/factory.rs)** 11 | 12 | ## Structural 13 | 14 | * **[Composite](src/structural/composite.rs)** 15 | * **[Decorator](src/structural/decorator.rs)** 16 | * **[Facade](src/structural/facade.rs)** 17 | 18 | ## Behavioral 19 | 20 | * **[Chain of responsibility](src/behavioral/chain_of_responsibility.rs)** 21 | * **[Memento](src/behavioral/memento.rs)** 22 | * **[Strategy](src/behavioral/strategy.rs)** 23 | -------------------------------------------------------------------------------- /tokio/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "FunctionalRust" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [[bin]] # Bin to run the HelloWorld gRPC server 7 | name = "tokio-grpc-server" 8 | path = "src/tokio_grpc_server.rs" 9 | 10 | [[bin]] # Bin to run the HelloWorld gRPC client 11 | name = "tokio-grpc-client" 12 | path = "src/tokio_grpc_client.rs" 13 | 14 | 15 | [dependencies] 16 | tokio = { version = "1", features = ["full"] } 17 | hyper = { version = "0.14", features = ["full"] } 18 | mini-redis = "0.4" 19 | futures = "0.3" 20 | rand = "0.8.5" 21 | tonic = "0.9" 22 | prost = "0.11" 23 | 24 | [build-dependencies] 25 | tonic-build = "0.9" -------------------------------------------------------------------------------- /src/features/new_types.rs: -------------------------------------------------------------------------------- 1 | /** 2 | In rust we can use [struct] as [New-types] which is an opaque wrapper for a type. 3 | [New-types] are a zero-cost abstraction – there’s no runtime overhead 4 | */ 5 | pub fn run() { 6 | let user = User(String::from("Politrons")); 7 | let password = Password(String::from("fgsafdsak")); 8 | login(user, password) 9 | } 10 | 11 | /** 12 | [New-types] it has anonymous access, and is defined as a tuple of only one element. 13 | So the way we access one element is by his array numeric position. 14 | */ 15 | fn login(user: User, pass: Password) { 16 | println!("Login user:{:?} password:{:?}", user.0, pass.0) 17 | } 18 | 19 | struct User(String); 20 | 21 | struct Password(String); 22 | -------------------------------------------------------------------------------- /red_panda_benchmark/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "red_panda_benchmark" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [[bin]] 7 | name = "red_panda_proxy_server" 8 | path = "src/red_panda_proxy_server.rs" 9 | 10 | [[bin]] 11 | name = "produce_load_test" 12 | path = "src/produce_load_test.rs" 13 | 14 | [[bin]] 15 | name = "consume_load_test" 16 | path = "src/consume_load_test.rs" 17 | 18 | [[bin]] 19 | name = "produce_consume_load_test" 20 | path = "src/produce_consume_load_test.rs" 21 | 22 | [dependencies] 23 | uuid = { version = "1.4.0", features = ["serde", "v4"] } 24 | rdkafka = "0.25.0" 25 | goose="0.17.0" 26 | goose-eggs = "0.5.1" 27 | tokio = { version = "1", features = ["full"] } 28 | hyper = { version = "0.14", features = ["full"] } 29 | lazy_static = "1.4" -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | mod features; 2 | 3 | use crate::features::{async_programming, channels_feature, collection, currying_function, do_notation_style, effect_system, either_monad, extension_method, functions, memory_management, monad, new_types, pattern_matching, smart_pointer, try_monad, type_classes}; 4 | 5 | fn main() { 6 | functions::run(); 7 | monad::run(); 8 | type_classes::run(); 9 | try_monad::run(); 10 | effect_system::run(); 11 | extension_method::run(); 12 | memory_management::run(); 13 | collection::run(); 14 | async_programming::run(); 15 | channels_feature::run(); 16 | pattern_matching::run(); 17 | either_monad::run(); 18 | smart_pointer::run(); 19 | new_types::run(); 20 | do_notation_style::run(); 21 | } 22 | -------------------------------------------------------------------------------- /src/features/mod.rs: -------------------------------------------------------------------------------- 1 | /** 2 | Mod file to expose all rust files to the main. 3 | Is mandatory that all mod we want to be exposed to main, has [pub] 4 | */ 5 | pub mod async_programming; 6 | pub mod functions; 7 | pub mod monad; 8 | pub mod type_classes; 9 | pub mod try_monad; 10 | pub mod effect_system; 11 | pub mod extension_method; 12 | pub mod memory_management; 13 | pub mod collection; 14 | pub mod channels_feature; 15 | pub mod pattern_matching; 16 | pub mod either_monad; 17 | pub mod enum_type; 18 | pub mod smart_pointer; 19 | pub mod currying_function; 20 | pub mod new_types; 21 | pub mod do_notation_style; 22 | pub mod rust_io; 23 | pub mod race_futures; 24 | pub mod promise; 25 | mod union_type; 26 | mod lens; 27 | mod rust_io_impl; 28 | mod dependency_injection; 29 | 30 | -------------------------------------------------------------------------------- /ai_api_integration/pkg/ai_api_integration_bg.wasm.d.ts: -------------------------------------------------------------------------------- 1 | /* tslint:disable */ 2 | /* eslint-disable */ 3 | export const memory: WebAssembly.Memory; 4 | export function ask_question(a: number, b: number, c: number, d: number): number; 5 | export function __wbindgen_malloc(a: number, b: number): number; 6 | export function __wbindgen_realloc(a: number, b: number, c: number, d: number): number; 7 | export const __wbindgen_export_2: WebAssembly.Table; 8 | export function _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__hd776ad9755cdf332(a: number, b: number, c: number): void; 9 | export function __wbindgen_exn_store(a: number): void; 10 | export function wasm_bindgen__convert__closures__invoke2_mut__h9de656cccec126bb(a: number, b: number, c: number, d: number): void; 11 | -------------------------------------------------------------------------------- /SQUICD/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "SQUICD" 3 | version = "0.1.1" 4 | authors = ["politrons"] 5 | edition = "2021" 6 | license = "MIT OR Apache-2.0" 7 | description = "Squicd is a Domain-Specific Language (DSL) in Rust designed to simplify the creation of QUIC-based servers and clients for message passing." 8 | repository = "https://github.com/politrons/FunctionalRust/tree/main/SQUICD" 9 | homepage = "https://github.com/politrons/FunctionalRust/tree/main/SQUICD" 10 | readme = "README.md" 11 | 12 | [dependencies] 13 | quiche ="0.22.0" 14 | serde = { version = "1.0", features = ["derive"] } 15 | serde_cbor = "0.11" # For CBOR serialization 16 | flate2 = "1.0" # For compression 17 | ring = "0.17.8" 18 | url = "2.5.2" 19 | mio = { version = "0.8", features = ["net", "os-poll"] } 20 | log = "0.4.22" 21 | rand = "0.9.0-alpha.2" 22 | env_logger = "0.11.5" 23 | -------------------------------------------------------------------------------- /game_3d/src/director.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_third_person_camera::*; 3 | 4 | pub struct DirectorPlugin; 5 | 6 | impl Plugin for DirectorPlugin { 7 | 8 | fn build(&self, app: &mut App){ 9 | app.add_systems(Startup, (spawn_camera, spawn_light)); 10 | } 11 | } 12 | 13 | 14 | fn spawn_camera(mut command: Commands) { 15 | let camera = (Camera3dBundle { 16 | transform: Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y), 17 | ..default() 18 | }, ThirdPersonCamera::default()); 19 | command.spawn(camera); 20 | } 21 | 22 | fn spawn_light(mut command: Commands) { 23 | let light = PointLightBundle { 24 | point_light: PointLight { 25 | intensity: 2000.0, 26 | ..default() 27 | }, 28 | transform: Transform::from_xyz(0.0, 5.0, 0.0), 29 | ..default() 30 | }; 31 | command.spawn(light); 32 | } 33 | -------------------------------------------------------------------------------- /src/features/rust_io_impl.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | mod tests { 3 | use rust_io::{rust_io, RustIO}; 4 | use rust_io::{Lift}; 5 | 6 | #[test] 7 | fn rio() { 8 | let rio_program: RustIO = rust_io! { 9 | _ <- RustIO::of(String::from("1981")); 10 | v <- RustIO::from_option(Some(String::from("hello"))); 11 | t <- RustIO::from_option_func(|| Some(String::from(" pure"))); 12 | z <- RustIO::from_func(|| String::from(" functional")); 13 | x <- RustIO::from_result(Ok(String::from(" world"))); 14 | i <- RustIO::of(String::from("!!")); 15 | y <- RustIO::from_result_func(|| Ok(String::from("!!"))); 16 | 17 | yield v + &t + &z + &x + &i + &y; 18 | }; 19 | println!("${:?}", rio_program.is_empty()); 20 | println!("${:?}", rio_program.is_ok()); 21 | assert_eq!(rio_program.get(), "hello pure functional world!!!!"); 22 | } 23 | } -------------------------------------------------------------------------------- /ai_hello_world_model/README.md: -------------------------------------------------------------------------------- 1 | # Detecting “Hello World” Validity in Rust 2 | 3 | This project trains a binary **Logistic Regression** model (via the 4 | [`linfa`](https://crates.io/crates/linfa) ecosystem) that decides whether a small 5 | Rust code snippet prints **“Hello, world!”** correctly (`VALID = 1`) or 6 | contains an error/variation (`INVALID = 0`). 7 | 8 | --- 9 | 10 | ## Dataset 11 | 12 | * **File**: `hello_rust.csv` 13 | * **Columns** 14 | 15 | | column | type | description | 16 | | ------ | ---- | ------------------------------------- | 17 | | `code` | `String` | The Rust snippet (≤ a few lines) | 18 | | `label` | `u8` (`0` or `1`) | Ground-truth verdict | 19 | 20 | For demonstration the repo also includes three hard-coded snippets in 21 | `EXAMPLES`, shown again at prediction time: 22 | 23 | ```rust 24 | fn main() { println!("Hello, world!"); } // VALID 25 | fn mian() { println!("Hello, world!"); } // INVALID (typo) 26 | fn main() { println!("Hola, mundo!"); } // INVALID (different text) 27 | -------------------------------------------------------------------------------- /src/features/union_type.rs: -------------------------------------------------------------------------------- 1 | 2 | /// In rust we dont have Union type like in Scala. 3 | /// But using enum type to create only the allowed types we want to union in a condition 4 | /// invocation is fine. 5 | enum UnionType { 6 | Apple(String), 7 | Banana(u32), 8 | Coconut() 9 | } 10 | 11 | /// In this example we only allow three possible types. In Scala it would be [Apple | Banana | Coconut] 12 | fn allow_only_fruit(fruit:UnionType){ 13 | match fruit { 14 | UnionType::Apple(s) => println!("You're a Apple"), 15 | UnionType::Banana(i) => println!("You're a Banana"), 16 | UnionType::Coconut() => println!("You're a Coconut"), 17 | } 18 | } 19 | 20 | 21 | #[cfg(test)] 22 | mod tests { 23 | use crate::features::union_type::UnionType::{Apple, Banana, Coconut}; 24 | use super::*; 25 | 26 | #[test] 27 | fn enum_type() { 28 | allow_only_fruit(Apple(String::from("apple type"))); 29 | allow_only_fruit(Banana(1981)); 30 | allow_only_fruit(Coconut()) 31 | 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /street_of_rage/README.md: -------------------------------------------------------------------------------- 1 | # Rust Street of Rage 2 | 3 | ![My image](assets/logo.png) 4 | 5 | Author Pablo Picouto Garcia 6 | 7 | Street of Rage Game Engine Using [Bevy](https://bevyengine.org) 8 | 9 | All used Sprites are coming from [spriters-resource](https://www.spriters-resource.com) 10 | 11 | You can also find the [crates.io](https://crates.io/crates/golden_axe) 12 | 13 | 14 | 15 | https://github.com/politrons/FunctionalRust/assets/2054461/ef72c692-9c2b-4258-81c7-f912df03d296 16 | 17 | 18 | https://github.com/politrons/FunctionalRust/assets/2054461/78af7410-81db-406d-a82f-71aa4c5275f2 19 | 20 | 21 | 22 | ## Sprites 23 | 24 | ![My image](assets/axel.png) 25 | 26 | ![My image](assets/punk.png) 27 | 28 | ![My image](assets/red.png) 29 | 30 | ![My image](assets/skin.png) 31 | 32 | 33 | ## How to Play 34 | 35 | Clone the repo, and run ```Main``` class 36 | 37 | ## Keyboard 38 | 39 | ```<-``` Left ```->``` Right ```^``` Up ```v``` Down 40 | 41 | ```Shift``` + ```direction``` Run. 42 | 43 | ```A``` Fist. 44 | 45 | ```S``` Hook. 46 | 47 | ```D``` Knee. 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /golden_axe/README.md: -------------------------------------------------------------------------------- 1 | # Rust Golden Axe 2 | 3 | ![My image](assets/logo.png) 4 | 5 | 6 | Author Pablo Picouto Garcia 7 | 8 | 9 | https://github.com/politrons/FunctionalRust/assets/2054461/a8c4051e-556b-459c-b43d-9dfefa182a85 10 | 11 | 12 | https://github.com/politrons/FunctionalRust/assets/2054461/f373403e-9afb-4e0d-ad2e-27b96999f649 13 | 14 | 15 | https://github.com/politrons/FunctionalRust/assets/2054461/b780a38c-d20a-4d19-9173-004ff45369a8 16 | 17 | 18 | Golden Axe Game Engine Using [Bevy](https://bevyengine.org) 19 | 20 | All used Sprites are coming from [spriters-resource](https://www.spriters-resource.com) 21 | 22 | You can also find the [crates.io](https://crates.io/crates/golden_axe) 23 | 24 | ## Sprites 25 | 26 | ![My image](assets/barbarian.png) 27 | 28 | ![My image](assets/Heninger.png) 29 | 30 | ![My image](assets/Storchinaya.png) 31 | 32 | ## How to Play 33 | 34 | Clone the repo, and run ```Main``` class 35 | 36 | ## Keyboard 37 | 38 | ```<-``` Left ```->``` Right ```^``` Up ```v``` Down 39 | 40 | ```Space``` Attack. 41 | 42 | ```Shift``` + ```direction``` Run. 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /dynamic_loading_plugin/src/lib.rs: -------------------------------------------------------------------------------- 1 | use dynamic_loading_contract::{PluginTrait}; 2 | 3 | /// In order to create a dynamic library that can be used in runtime discovery we need to use 4 | /// crate-type = ["cdylib"] in our [Cargo.toml] file. Then it will create a .[dylib] extension file 5 | 6 | pub struct PluginImplementation; 7 | 8 | ///Implementation of the contract [X] defined as an external dependency, we share with [dynamic_loading] cargo. 9 | impl PluginTrait for PluginImplementation { 10 | fn hello_world(&self) { 11 | println!("Plugin Hello world implementation"); 12 | } 13 | } 14 | 15 | ///For this patter, we use "dynamic objects", which typically refers to objects whose types 16 | /// are not known at compile time and can vary at runtime. 17 | /// The [Box] it will expose all functions defined in the [Trait]. 18 | /// Use [pub extern "C"] is mandatory to create a reference that can be used by consumer of this library, 19 | /// to discover the function in runtime loading. 20 | #[no_mangle] 21 | pub extern "C" fn create_plugin() -> Box { 22 | Box::new(PluginImplementation { }) 23 | } 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /actix/src/actix_web_server.rs: -------------------------------------------------------------------------------- 1 | use std::path::PathBuf; 2 | use actix_files::NamedFile; 3 | use actix_web::{web, App, HttpServer}; 4 | use actix_web::{HttpRequest, Result}; 5 | 6 | 7 | /** 8 | * We use [parse] to search for the resource and we return a [PathBuf] 9 | * we use [NamedFile::open] feature to open unwrap the [Result], and return a [Result] 10 | which actix framework will use to render that static file. 11 | */ 12 | async fn index(_req: HttpRequest) -> Result { 13 | let path: PathBuf = "./static/index.html".parse().unwrap(); 14 | Ok(NamedFile::open(path)?) 15 | } 16 | 17 | /** 18 | We cover in [actix_server] how actix server is configured and running. 19 | In here just to add, using [web::scope] we can specify the path where this server is 20 | listening. In this case we listen from endpoint [/app] 21 | */ 22 | pub async fn run_server() -> std::io::Result<()> { 23 | HttpServer::new(|| { 24 | App::new().service( 25 | web::scope("/app") 26 | .route("/", web::get().to(index)), 27 | ) 28 | }) 29 | .bind(("127.0.0.1", 8080))? 30 | .run() 31 | .await 32 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Pablo Picouto Garcia 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /street_fighter/README.md: -------------------------------------------------------------------------------- 1 | # Rust Street Fighter 2 2 | 3 | Author Pablo Picouto Garcia 4 | 5 | Street Fighter 2 Game Engine Using [Bevy](https://bevyengine.org) 6 | 7 | All used Sprites are coming from [spriters-resource](https://www.spriters-resource.com) 8 | 9 | You can also find the [crates.io](https://crates.io/crates/street_fighter) 10 | 11 | 12 | https://github.com/politrons/FunctionalRust/assets/2054461/ae9d5aa3-f7c7-4915-ae18-b11ba785d382 13 | 14 | 15 | https://github.com/politrons/FunctionalRust/assets/2054461/0c4d669a-26cb-4060-89a0-7f7022c35686 16 | 17 | 18 | https://github.com/politrons/FunctionalRust/assets/2054461/3dd9e7a3-8b6f-4151-bacd-7c210579334f 19 | 20 | 21 | ## Players 22 | 23 | ![My image](assets/ryu_player.png) 24 | 25 | 26 | 27 | ![My image](assets/ken_player.png) 28 | 29 | ## Sprites 30 | 31 | ![My image](assets/ryu.png) 32 | 33 | ![My image](assets/ken.png) 34 | 35 | ![My image](assets/background.png) 36 | 37 | 38 | ## How to Play 39 | 40 | Clone the repo, and run ```Main``` class 41 | 42 | ## Keyboard 43 | 44 | ```<-``` Left ```->``` Right ```^``` Up ```v``` Down 45 | 46 | ```A``` Fist. 47 | 48 | ```S``` Kick. 49 | 50 | ```D``` Hadoken. 51 | 52 | ```<-``` Block under attack. 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /src/features/channels_feature.rs: -------------------------------------------------------------------------------- 1 | use std::{thread, time}; 2 | use std::future::Future; 3 | use std::io; 4 | use std::net::TcpListener; 5 | use std::sync::mpsc::{channel, Receiver, RecvError, SendError}; 6 | use std::sync::mpsc; 7 | use std::sync::mpsc::Sender; 8 | 9 | use futures::executor::block_on; 10 | 11 | pub fn run() { 12 | local_channel(); 13 | } 14 | 15 | fn local_channel() { 16 | let (sender, receiver): (Sender, Receiver) = mpsc::channel(); 17 | let sender_future = send_message(sender); 18 | let receive_future = receive_message(receiver); 19 | block_on(sender_future); 20 | block_on(receive_future); 21 | } 22 | 23 | async fn send_message(sender: Sender) { 24 | thread::sleep(time::Duration::from_secs(2)); 25 | let ack = sender.send(String::from("Hello channel")); 26 | match ack { 27 | Ok(()) => println!("Message sent successful"), 28 | Err(error) => println!("{}", error.to_string()), 29 | } 30 | } 31 | 32 | async fn receive_message(receiver: Receiver) { 33 | let result = receiver.recv(); 34 | match result { 35 | Ok(v) => println!("Received: {}", v), 36 | Err(error) => println!("{}", error.to_string()), 37 | } 38 | } 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /SQUICD/src/common.rs: -------------------------------------------------------------------------------- 1 | use serde::{Serialize, Deserialize}; 2 | use serde_cbor; 3 | use flate2::write::ZlibEncoder; 4 | use flate2::read::ZlibDecoder; 5 | use flate2::Compression; 6 | use std::io::{Read, Write}; 7 | 8 | #[derive(Serialize, Deserialize, Debug)] 9 | pub struct Message { 10 | pub id: u32, 11 | pub content: String, 12 | pub timestamp: u64, 13 | } 14 | 15 | pub fn serialize_and_compress(message: &Message) -> Result, Box> { 16 | // Serialize the message to CBOR format 17 | let serialized = serde_cbor::to_vec(message)?; 18 | 19 | // Compress the serialized data 20 | let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default()); 21 | encoder.write_all(&serialized)?; 22 | let compressed = encoder.finish()?; 23 | 24 | Ok(compressed) 25 | } 26 | 27 | pub fn decompress_and_deserialize(data: &[u8]) -> Result> { 28 | // Decompress the data 29 | let mut decoder = ZlibDecoder::new(data); 30 | let mut decompressed_data = Vec::new(); 31 | decoder.read_to_end(&mut decompressed_data)?; 32 | 33 | // Deserialize the message from CBOR format 34 | let message = serde_cbor::from_slice(&decompressed_data)?; 35 | 36 | Ok(message) 37 | } 38 | -------------------------------------------------------------------------------- /src/features/do_notation_style.rs: -------------------------------------------------------------------------------- 1 | use do_notation::m; 2 | 3 | /** 4 | Thanks to crates like [do_notation] https://github.com/phaazon/do-notation we can write our code 5 | using [do notation] style like in Haskell or Scala with [for-comprehension] 6 | */ 7 | pub fn run() { 8 | option_program(); 9 | result_program(); 10 | } 11 | 12 | fn option_program() { 13 | let maybe_user_info = m! { 14 | user <- login("politrons"); 15 | account <- get_user_account(user); 16 | get_user_info(account) 17 | }; 18 | println!("{:?}", maybe_user_info) 19 | } 20 | 21 | fn result_program() { 22 | let result_user_info: Result = m! { 23 | user <- Ok(User("Politrons".to_string())); 24 | account <- Ok(Account { info: user.0 }); 25 | Ok(account) 26 | }; 27 | println!("{:?}", result_user_info.unwrap().info) 28 | } 29 | 30 | fn login(username: &str) -> Option { 31 | Some(User(username.to_string())) 32 | } 33 | 34 | fn get_user_account(user: User) -> Option { 35 | Some(Account { info: user.0 }) 36 | } 37 | 38 | fn get_user_info(account: Account) -> Option { 39 | Some(account.info) 40 | } 41 | 42 | struct User(String); 43 | 44 | struct Account { 45 | info: String, 46 | } -------------------------------------------------------------------------------- /dragon_ball/README.md: -------------------------------------------------------------------------------- 1 | # Rust Dragon Ball Z 2 | 3 | Author Pablo Picouto Garcia 4 | 5 | Dragon Ball Z Fight Game Engine Using [Bevy](https://bevyengine.org) 6 | 7 | All used Sprites are coming from [spriters-resource](https://www.spriters-resource.com) 8 | 9 | You can also find the [crates.io](https://crates.io/crates/dragon_ball) 10 | 11 | 12 | https://github.com/politrons/FunctionalRust/assets/2054461/aa0b7a0c-687b-4866-9af5-d3742334af77 13 | 14 | 15 | https://github.com/politrons/FunctionalRust/assets/2054461/eef4da97-e9d4-4637-b642-77938e27cd48 16 | 17 | 18 | https://github.com/politrons/FunctionalRust/assets/2054461/d35eb1b5-d29e-48fb-90e2-069f040c4f73 19 | 20 | ## Players 21 | 22 | ![My image](assets/trunk_player.png) 23 | ![My image](assets/dr_hero_player.png) 24 | ![My image](assets/android_17_player.png) 25 | ![My image](assets/android_18_player.png) 26 | 27 | ## Sprites 28 | 29 | ![My image](assets/trunk.png) 30 | 31 | ![My image](assets/dr_hero.png) 32 | 33 | ![My image](assets/android_17.png) 34 | 35 | ![My image](assets/android_18.png) 36 | 37 | ## How to Play 38 | 39 | Clone the repo, and run ```Main``` class 40 | 41 | ## Keyboard 42 | 43 | ```<-``` Dodge. 44 | 45 | ```Space``` Attack. 46 | 47 | ```Enter``` Super Attack. 48 | 49 | ```S``` Super Saiyan mode. 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /dynamic_loading/src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate libloading; 2 | 3 | use libloading::{Library, Symbol}; 4 | use dynamic_loading_contract::PluginTrait; 5 | 6 | /// Using [libloading] library we're able to load Trait implementations in runtime, without have to know the specific type 7 | /// that implement the trait, allowing same pattern than in Java Service Provider Interface(SPI). 8 | /// This allow inject in a program different implementations just adding the path of the [.dylib] file that contains 9 | /// the implementation, and knowing the name of the [symbol] created in that library. 10 | /// 11 | /// [Library::new] oad the shared object file 12 | /// [lib.get(b"your_symbol_name\0")] Use a symbol from the shared object file and return a [Symbol] function type 13 | /// [plugin_symbol_func()] we run the function so we get the dynamic object Box 14 | /// [plugin.hello_world()] we run the action 15 | /// The shared object file is unloaded automatically when 'lib' goes out of scope 16 | fn main() { 17 | unsafe { 18 | let shared_obj_lib = Library::new("../dynamic_loading_plugin/target/release/libdynamic_loading_plugin.dylib").unwrap(); 19 | let plugin_symbol_func: Symbol Box> = shared_obj_lib.get(b"create_plugin\0").unwrap(); 20 | let plugin = plugin_symbol_func(); 21 | plugin.hello_world(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /patterns/src/creational/factory.rs: -------------------------------------------------------------------------------- 1 | ///Trait contract of the feature we want to implement 2 | pub trait Animal { 3 | fn speak(&self); 4 | } 5 | 6 | /// Data type of the implementation of trait 7 | pub struct Human; 8 | 9 | /// Implementation of the trait 10 | impl Animal for Human{ 11 | fn speak(&self) { 12 | println!("Hello there") 13 | } 14 | } 15 | 16 | /// Trait contract of the factory 17 | pub trait Factory { 18 | fn build_animal(&self) -> Box; 19 | } 20 | 21 | /// Factory type to be implemented 22 | pub struct AnimalFactory; 23 | 24 | /// Implementation of the factory for a specific type, but without specify that type to the 25 | /// consumer of the factory. We hide that implementation using [Box] 26 | /// So now potentially we can refactor the implementation type of [Animal] in the factory, 27 | /// and the client using the factory wont notice any differences. 28 | impl Factory for AnimalFactory { 29 | fn build_animal(&self) -> Box { 30 | Box::new(Human) 31 | } 32 | } 33 | 34 | #[cfg(test)] 35 | mod tests { 36 | use crate::creational::factory::{AnimalFactory, Factory}; 37 | 38 | #[test] 39 | fn factory_pattern() { 40 | let animal_factory:Box = Box::new(AnimalFactory); 41 | let animal = animal_factory.build_animal(); 42 | println!("${:?}", animal.speak()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /patterns/src/structural/decorator.rs: -------------------------------------------------------------------------------- 1 | /// Contract of the component to implement 2 | pub trait Animal { 3 | fn skills(&self) -> String; 4 | } 5 | 6 | /// Data type to implement a normal component 7 | pub struct Human; 8 | 9 | /// Implementation of component 10 | impl Animal for Human { 11 | fn skills(&self) -> String { 12 | String::from("Hello there I can speak") 13 | } 14 | } 15 | 16 | /// [Decorator] Data type than can do what a [Animal] can do and even more. 17 | /// It contains an instance of any [Animal] to do what that animal can do, 18 | /// and [extend] the functionality 19 | pub struct SuperHuman { 20 | animal: Box, 21 | } 22 | 23 | /// [Decorator] [Animal] implementation to behave like another animal, but with more capacity than 24 | /// a regular animal type. 25 | /// Here in the [skills] function, we execute the animal instance [skills] and we extend with something else. 26 | impl Animal for SuperHuman { 27 | fn skills(&self) -> String { 28 | format!("{}. And I can also fly", self.animal.skills()) 29 | } 30 | } 31 | 32 | #[cfg(test)] 33 | mod tests { 34 | use crate::structural::decorator::{Animal, Human, SuperHuman}; 35 | 36 | #[test] 37 | fn decorator_pattern() { 38 | let human = Box::new(Human); 39 | println!("${}",human.skills()); 40 | let decorator = Box::new(SuperHuman{animal:human}); 41 | println!("${}",decorator.skills()); 42 | 43 | } 44 | } -------------------------------------------------------------------------------- /quiche-feature/README.md: -------------------------------------------------------------------------------- 1 | # QUIC Client-Server 2 | 3 | This project demonstrates a simple QUIC client-server communication using the [quiche](https://github.com/cloudflare/quiche) library in Rust. The client sends multiple requests to the server over QUIC, and the server responds with acknowledgments for each stream. 4 | 5 | ## Features 6 | 7 | - Utilizes the QUIC protocol for fast and secure UDP communication. 8 | - Client sends up to 999 requests in parallel on bidirectional streams. 9 | - Server handles multiple concurrent connections and responds to each request. 10 | - Demonstrates stream-based data transfer with flow control using the `quiche` library. 11 | 12 | ## Requirements 13 | 14 | - **Rust**: Latest stable version recommended. 15 | - **`quiche` library**: To install and use the quiche library, refer to its [official documentation](https://github.com/cloudflare/quiche). 16 | - **TLS Certificate**: You need a valid TLS certificate (`cert.crt`) and a private key (`cert.key`) for the server. 17 | 18 | ### Dependencies 19 | 20 | To include `quiche` in your Rust project, add it to your `Cargo.toml`: 21 | 22 | ```toml 23 | [dependencies] 24 | quiche = "0.22.0" 25 | ``` 26 | 27 | ## Run 28 | 29 | Run server 30 | ``` 31 | cargo run --bin server 32 | ``` 33 | Run client 34 | ``` 35 | cargo run --bin client 36 | ``` 37 | 38 | ## Benchmarks 39 | 40 | ![My image](img/output-2.png) 41 | ![My image](img/output-3.png) 42 | ![My image](img/output.png) 43 | -------------------------------------------------------------------------------- /src/features/race_futures.rs: -------------------------------------------------------------------------------- 1 | use futures::{ 2 | future::FutureExt, 3 | pin_mut, 4 | select, 5 | }; 6 | 7 | #[cfg(test)] 8 | mod tests { 9 | use std::future; 10 | use std::time::Duration; 11 | 12 | use futures::executor::block_on; 13 | 14 | use super::*; 15 | 16 | // 17 | // #[test] 18 | // fn race() { 19 | // block_on(race_tasks()); 20 | // } 21 | // 22 | // async fn race_tasks() { 23 | // let mut t1 = future::ready(1); 24 | // let mut t2 = future::ready(2); 25 | // loop { 26 | // select! { 27 | // car1 = t1 => println!("${} win", car1), 28 | // car2 = t2 => println!("${} win", car2), 29 | // complete => break, 30 | // default => unreachable!(), // never runs (futures are ready, then complete) 31 | // }; 32 | // } 33 | // // let t1 = lotus().fuse(); 34 | // // let t2 = ferrari().fuse(); 35 | // 36 | // // pin_mut!(t1, t2); 37 | // // 38 | // // select! { 39 | // // car1 = t1 => println!("${} win", car1), 40 | // // car2 = t2 => println!("${} win", car2), 41 | // // } 42 | // } 43 | // 44 | // async fn lotus() -> String { 45 | // std::thread::sleep(Duration::from_secs(2)); 46 | // return "Lotus".to_string(); 47 | // } 48 | // 49 | // async fn ferrari() -> String { 50 | // return "Ferrari".to_string(); 51 | // } 52 | } 53 | -------------------------------------------------------------------------------- /patterns/src/creational/singleton.rs: -------------------------------------------------------------------------------- 1 | use std::sync::{Mutex, Once}; 2 | 3 | /// RThis represent the Singleton object 4 | pub struct Human { 5 | age: u32, 6 | name: String, 7 | sex: String, 8 | } 9 | 10 | /// Implementation of [instance] to retrieve always same instance created [ONCE] 11 | /// Using static [Once] from rust, we ensure we have only one instance created during the life of the program. 12 | /// We use [*const Human] to have a [lazy_static] creation of the type. This it will require we create an instance wrapped in 13 | /// [Box::into_raw] of a [Box::new] of [Human] 14 | /// Inside [call_once] we do the construction of the Singleton Box type. 15 | impl Human { 16 | pub fn instance() -> &'static Self { 17 | static mut INSTANCE: *const Human = 0 as *const Human; 18 | static ONCE: Once = Once::new(); 19 | 20 | unsafe { 21 | ONCE.call_once(|| { 22 | println!("Instantiating Singleton..."); 23 | INSTANCE = Box::into_raw(Box::new(Human { 24 | age: 42, 25 | name: "Politrons".to_string(), 26 | sex: "Male".to_string(), 27 | })); 28 | }); 29 | &*INSTANCE 30 | } 31 | } 32 | } 33 | 34 | #[cfg(test)] 35 | mod tests { 36 | use crate::creational::singleton::Human; 37 | 38 | #[test] 39 | fn singleton_pattern() { 40 | let human = Human::instance(); 41 | let same_human = Human::instance(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /SQUICD/cert.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIID9zCCAt+gAwIBAgIULoZhwUi3b2HAQZtwpWkiHpcSqDcwDQYJKoZIhvcNAQEL 3 | BQAwgYoxCzAJBgNVBAYTAkVTMQ8wDQYDVQQIDAZNYWRyaWQxDzANBgNVBAcMBk1h 4 | ZHJpZDESMBAGA1UECgwJcG9saXRyb25zMRIwEAYDVQQLDAlwb2xpdHJvbnMxDTAL 5 | BgNVBAMMBFBhdWwxIjAgBgkqhkiG9w0BCQEWE3BvbGl0cm9uc0BnbWFpbC5jb20w 6 | HhcNMjQxMDE1MDkyMTM4WhcNMjUxMDE1MDkyMTM4WjCBijELMAkGA1UEBhMCRVMx 7 | DzANBgNVBAgMBk1hZHJpZDEPMA0GA1UEBwwGTWFkcmlkMRIwEAYDVQQKDAlwb2xp 8 | dHJvbnMxEjAQBgNVBAsMCXBvbGl0cm9uczENMAsGA1UEAwwEUGF1bDEiMCAGCSqG 9 | SIb3DQEJARYTcG9saXRyb25zQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQAD 10 | ggEPADCCAQoCggEBANIWTKfAbrlrhvSDLtveakPN0Yv5W5fFyS+vCtzBRGpsy3o+ 11 | l7Kd8+3MLDWAiBQlWS+v8AXspAgot7AYqPQFUDqT48Gl9wXVXXaiSoGyPjcgt24F 12 | 49iIctJW2Skz2E+3865KA9TmgLssXd0WKlDRA5RNHeTivKL2avQUPBagBpNoNxMw 13 | 12vZfLN999wgFS9qZBgFdBiroWg/JRznLQszvJdzbnzyNDlIjCYoSLE82x2EY5Lw 14 | IqVpv0uAl44/9FGljMUKHXwAn+glEJHlH887PKO3Wa3+hhmPTJIKdglIi9XmCeqY 15 | HaxTImy3DzABdPjkG9Tyn5j8lyef6pomRfqZ828CAwEAAaNTMFEwHQYDVR0OBBYE 16 | FAl4Q/pZEg8r+J9SDhM/z+mSSGvLMB8GA1UdIwQYMBaAFAl4Q/pZEg8r+J9SDhM/ 17 | z+mSSGvLMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAB+wS24+ 18 | 8vPIbOmLM/KtkEy8LdCJzvZ0Rttm+CpNRpSAS3PsxF6gcwYJiib5hQnFNR5tD6Hh 19 | hmj3S1fRCUIqLyGtWPRe5SKaWpOImL4Qqlp0Pbft7cE/oGqqSNBrmCxPHew6ADHW 20 | 1Ut/azHeKxMmN8sh+mFOzZ90JyKGF2/+uSS4iifQmnMX48b8U9h5wW/cX5jvAx5U 21 | X2plsTYZbsXdH2vfVoBH0q8WRs9daSAEHW2rHiuKZLA/3kiQUeqePB/7uGx22PFl 22 | lUO7CNQ0L1Rm+58pd8T5g/KiDL2PCwAzjk5N4sBdQTkmaNjSPO7bQ3DtXZMdIXWa 23 | 5qoblH4d+9+zl2M= 24 | -----END CERTIFICATE----- 25 | -------------------------------------------------------------------------------- /patterns/src/behavioral/chain_of_responsibility.rs: -------------------------------------------------------------------------------- 1 | 2 | pub trait Animal { 3 | fn next_animal(&mut self, next: Box); 4 | fn eat(&self, request: &str); 5 | } 6 | 7 | pub struct Human { 8 | next: Option>, 9 | } 10 | 11 | impl Animal for Human { 12 | fn next_animal(&mut self, next: Box) { 13 | self.next = Some(next); 14 | } 15 | 16 | fn eat(&self, food: &str) { 17 | if food == "Fish & chips" { 18 | println!("This {} is a human food mmmmm", food); 19 | } else if let Some(ref next) = self.next { 20 | next.eat(food); 21 | } 22 | } 23 | } 24 | 25 | pub struct Dog { 26 | next: Option>, 27 | } 28 | 29 | impl Animal for Dog { 30 | fn next_animal(&mut self, next: Box) { 31 | self.next = Some(next); 32 | } 33 | 34 | fn eat(&self, food: &str) { 35 | if food == "bone" { 36 | println!("This {} is a dog food mmmmm", food); 37 | } else { 38 | println!("Nobody wants this {} food", food); 39 | } 40 | } 41 | } 42 | 43 | #[cfg(test)] 44 | mod tests { 45 | use crate::behavioral::chain_of_responsibility::{Animal, Dog, Human}; 46 | 47 | #[test] 48 | fn cor_pattern() { 49 | let dog = Box::new(Dog { next: None }); 50 | let human = Box::new(Human { next: Some(dog) }); 51 | human.eat("bone"); 52 | human.eat("Fish & chips"); 53 | human.eat("poison cake") 54 | 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /quiche-feature/cert.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIID9zCCAt+gAwIBAgIULoZhwUi3b2HAQZtwpWkiHpcSqDcwDQYJKoZIhvcNAQEL 3 | BQAwgYoxCzAJBgNVBAYTAkVTMQ8wDQYDVQQIDAZNYWRyaWQxDzANBgNVBAcMBk1h 4 | ZHJpZDESMBAGA1UECgwJcG9saXRyb25zMRIwEAYDVQQLDAlwb2xpdHJvbnMxDTAL 5 | BgNVBAMMBFBhdWwxIjAgBgkqhkiG9w0BCQEWE3BvbGl0cm9uc0BnbWFpbC5jb20w 6 | HhcNMjQxMDE1MDkyMTM4WhcNMjUxMDE1MDkyMTM4WjCBijELMAkGA1UEBhMCRVMx 7 | DzANBgNVBAgMBk1hZHJpZDEPMA0GA1UEBwwGTWFkcmlkMRIwEAYDVQQKDAlwb2xp 8 | dHJvbnMxEjAQBgNVBAsMCXBvbGl0cm9uczENMAsGA1UEAwwEUGF1bDEiMCAGCSqG 9 | SIb3DQEJARYTcG9saXRyb25zQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQAD 10 | ggEPADCCAQoCggEBANIWTKfAbrlrhvSDLtveakPN0Yv5W5fFyS+vCtzBRGpsy3o+ 11 | l7Kd8+3MLDWAiBQlWS+v8AXspAgot7AYqPQFUDqT48Gl9wXVXXaiSoGyPjcgt24F 12 | 49iIctJW2Skz2E+3865KA9TmgLssXd0WKlDRA5RNHeTivKL2avQUPBagBpNoNxMw 13 | 12vZfLN999wgFS9qZBgFdBiroWg/JRznLQszvJdzbnzyNDlIjCYoSLE82x2EY5Lw 14 | IqVpv0uAl44/9FGljMUKHXwAn+glEJHlH887PKO3Wa3+hhmPTJIKdglIi9XmCeqY 15 | HaxTImy3DzABdPjkG9Tyn5j8lyef6pomRfqZ828CAwEAAaNTMFEwHQYDVR0OBBYE 16 | FAl4Q/pZEg8r+J9SDhM/z+mSSGvLMB8GA1UdIwQYMBaAFAl4Q/pZEg8r+J9SDhM/ 17 | z+mSSGvLMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAB+wS24+ 18 | 8vPIbOmLM/KtkEy8LdCJzvZ0Rttm+CpNRpSAS3PsxF6gcwYJiib5hQnFNR5tD6Hh 19 | hmj3S1fRCUIqLyGtWPRe5SKaWpOImL4Qqlp0Pbft7cE/oGqqSNBrmCxPHew6ADHW 20 | 1Ut/azHeKxMmN8sh+mFOzZ90JyKGF2/+uSS4iifQmnMX48b8U9h5wW/cX5jvAx5U 21 | X2plsTYZbsXdH2vfVoBH0q8WRs9daSAEHW2rHiuKZLA/3kiQUeqePB/7uGx22PFl 22 | lUO7CNQ0L1Rm+58pd8T5g/KiDL2PCwAzjk5N4sBdQTkmaNjSPO7bQ3DtXZMdIXWa 23 | 5qoblH4d+9+zl2M= 24 | -----END CERTIFICATE----- 25 | -------------------------------------------------------------------------------- /tokio/src/tokio_grpc_client.rs: -------------------------------------------------------------------------------- 1 | use tonic::Request; 2 | use grpc_service::my_grpc_client::MyGrpcClient; 3 | use grpc_service::MyGrpcRequest; 4 | 5 | /** 6 | For every change in grpc_service.proto you need to run the command to re-build the code with protoc [cargo run --bin tokio-grpc--client] 7 | Using [include_proto] we specify the [package] name we use in proto file 8 | */ 9 | pub mod grpc_service { 10 | tonic::include_proto!("grpcservice"); 11 | } 12 | 13 | /** 14 | gRPC client implementation. 15 | We use gRPC service name [MyGrpc][Client] using operator [connect] where we pass the hostname, 16 | to create gRPC client. It return a Future, so we need to await and unwrap. 17 | 18 | With the client we can invoke the service method [simple_request] defined in protobuf file. 19 | 20 | It return a Future> so we await for the future, and we unwrap [?] the Result… 21 | */ 22 | #[tokio::main] 23 | async fn main() -> Result<(), Box> { 24 | let mut client = MyGrpcClient::connect("http://[::1]:9100").await?; 25 | let request = create_request(); 26 | let response = client.simple_request(request).await?; 27 | println!("Response={:?}", response); 28 | Ok(()) 29 | } 30 | 31 | /** 32 | Function to create the request type. 33 | We use [Request::new] to create the request and we pass the instance of the protobuf type [MyGrpcRequest] 34 | */ 35 | fn create_request() -> Request { 36 | Request::new(MyGrpcRequest { 37 | name: "Politrons".into(), 38 | }) 39 | } -------------------------------------------------------------------------------- /SQUICD/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use std::time::Duration; 3 | 4 | use SQUICD::common::Message; 5 | use SQUICD::dsl::Squicd; 6 | 7 | fn main() -> ! { 8 | thread::spawn(move || { 9 | run_server(); 10 | }); 11 | run_client(); 12 | loop { 13 | std::thread::park(); 14 | } 15 | } 16 | 17 | fn run_server() { 18 | Squicd::with_handler( 19 | |message| { 20 | println!("Received message: {:?}", message); 21 | thread::sleep(Duration::from_secs(1)); 22 | let new_message = Message { 23 | id: message.id + 1, 24 | content: message.content.clone(), 25 | timestamp: message.timestamp, 26 | }; 27 | //Send message to next service. 28 | if let Err(e) = Squicd::send_message("127.0.0.1:4433", new_message) { 29 | eprintln!("Error sending message: {:?}", e); 30 | } 31 | }) 32 | .with_error_handler( 33 | |err| { 34 | println!("Side-effect handle: {:?}", err); 35 | }) 36 | .with_cert("cert.crt") 37 | .with_key("cert.key") 38 | .with_port("4433") 39 | .start(); 40 | } 41 | 42 | fn run_client() { 43 | let message = Message { 44 | id: 1, 45 | content: "Hello, Squicd!".to_string(), 46 | timestamp: 1234567890, 47 | }; 48 | 49 | if let Err(e) = Squicd::send_message("127.0.0.1:4433", message) { 50 | eprintln!("Error sending message: {:?}", e); 51 | } 52 | } 53 | 54 | -------------------------------------------------------------------------------- /patterns/src/structural/facade.rs: -------------------------------------------------------------------------------- 1 | /// Data type to implement a human component 2 | pub struct Human; 3 | 4 | /// Implementation of human data type 5 | impl Human { 6 | pub fn speak(&self) { 7 | println!("Hello there"); 8 | } 9 | } 10 | 11 | /// Data type to implement a dog component 12 | pub struct Dog; 13 | 14 | /// Implementation of dog data type 15 | impl Dog { 16 | pub fn speak(&self) { 17 | println!("Barf"); 18 | } 19 | } 20 | 21 | /// Facade pattern allow to gather multiple component executions, orchestate the order of execution, 22 | /// and made that complexity agnostic for the one that use this [Facade] 23 | /// We contain all dependencies that we want to execute 24 | pub struct Facade { 25 | human: Human, 26 | dog: Dog, 27 | } 28 | 29 | /// Implementation of [Facade] patter. 30 | /// with [new] We create internally all dependencies that we want to execute. 31 | /// with [animal_speak] we orchestrate the execution of all animals we have as dependencies 32 | /// completely agnostic for the client. 33 | impl Facade { 34 | pub fn new() -> Self { 35 | Facade { 36 | human: Human, 37 | dog: Dog, 38 | } 39 | } 40 | 41 | pub fn animal_speak(&self) { 42 | self.human.speak(); 43 | self.dog.speak(); 44 | } 45 | } 46 | 47 | 48 | #[cfg(test)] 49 | mod tests { 50 | use crate::structural::facade::{Human, Dog, Facade}; 51 | 52 | #[test] 53 | fn decorator_pattern() { 54 | let facade = Facade::new(); 55 | facade.animal_speak(); 56 | } 57 | } -------------------------------------------------------------------------------- /src/features/extension_method.rs: -------------------------------------------------------------------------------- 1 | /** 2 | Once we implement an extension trait over a specific type [String,Integer,Bool...] we can start using 3 | this new method like part of this API. 4 | */ 5 | pub fn run() { 6 | println!("Contains hello:{}","Hello world".contains_hello()); 7 | println!("Number:{}",1981.multiply_by(10)); 8 | println!("Animal info:{}",Animal{ species:"Dog".to_string(), age:5}.animal_description()); 9 | } 10 | 11 | /** 12 | Make extension methods in Rust is quite simple and clean. 13 | We just need to define a [trait] with the the definition we want to extend. 14 | And then create an implementation [impl] using the specific type to extend after [for] 15 | */ 16 | trait StringExt { 17 | fn contains_hello(&self) -> bool; 18 | } 19 | 20 | /**Implementation extension of [str] type*/ 21 | impl StringExt for str { 22 | fn contains_hello(&self) -> bool { 23 | self.contains("Hello") 24 | } 25 | } 26 | 27 | trait NumberExt { 28 | fn multiply_by(&self,number:i32) -> i32; 29 | } 30 | 31 | /**Implementation extension of [i32] type*/ 32 | impl NumberExt for i32 { 33 | 34 | fn multiply_by(&self, number: i32) -> i32 { 35 | self * number 36 | } 37 | } 38 | 39 | trait AnimalExt { 40 | fn animal_description(self)->String; 41 | } 42 | 43 | /**Implementation extension of [Animal] type*/ 44 | impl AnimalExt for Animal{ 45 | fn animal_description(self) -> String { 46 | self.species + &"-" + &self.age.to_string() 47 | } 48 | } 49 | 50 | struct Animal { 51 | species:String, 52 | age:i32, 53 | } 54 | -------------------------------------------------------------------------------- /goose/src/mock_http_server.rs: -------------------------------------------------------------------------------- 1 | //Server 2 | use std::convert::Infallible; 3 | use std::net::SocketAddr; 4 | use hyper::{Body, Request, Response, Server}; 5 | use hyper::service::{make_service_fn, service_fn}; 6 | use hyper::{Method, StatusCode}; 7 | 8 | //Client 9 | use std::error::Error; 10 | use std::num::NonZeroU16; 11 | use std::thread; 12 | use std::time::Duration; 13 | use hyper::Client; 14 | use hyper::body::HttpBody as _; 15 | use hyper::client::HttpConnector; 16 | use tokio::io; 17 | use tokio::io::{stdout, AsyncWriteExt as _}; 18 | 19 | 20 | pub async fn run_server() { 21 | println!("Preparing Service..."); 22 | let port = 1981; 23 | let addr = SocketAddr::from(([127, 0, 0, 1], port)); 24 | let server = Server::bind(&addr) 25 | .serve(make_service_fn(|_conn| async { 26 | println!("New request received."); 27 | Ok::<_, Infallible>(service_fn(create_service)) 28 | })); 29 | if let Err(e) = server.await { 30 | println!("server error: {}", e); 31 | } 32 | } 33 | 34 | async fn create_service(req: Request) -> Result, Infallible> { 35 | let mut response = Response::new(Body::empty()); 36 | match (req.method(), req.uri().path()) { 37 | (&Method::GET, "/hello") => { 38 | *response.status_mut() = StatusCode::OK; 39 | *response.body_mut() = Body::from("In the near future, we will implement /world"); 40 | } 41 | _ => { 42 | *response.status_mut() = StatusCode::NOT_FOUND; 43 | } 44 | }; 45 | Ok(response) 46 | } -------------------------------------------------------------------------------- /src/features/dependency_injection.rs: -------------------------------------------------------------------------------- 1 | /// Contract of the dependency that I will receive 2 | pub trait LangDependency { 3 | fn say_hello(&self); 4 | } 5 | 6 | /// Data type for Service, that define a field [Dependency] that 7 | /// it can be any implementation of [LangDependency] 8 | pub struct LangService { 9 | dependency: Box, 10 | } 11 | 12 | /// Implementation of the service that it require in the [new] constructor, pass the dependency 13 | /// so then we can instantiate [LangService] passing the dependency 14 | impl LangService { 15 | pub fn new(dependency: Box) -> Self { 16 | LangService { dependency } 17 | } 18 | 19 | pub fn run(&self) { 20 | self.dependency.say_hello(); 21 | } 22 | } 23 | 24 | 25 | 26 | 27 | #[cfg(test)] 28 | mod tests { 29 | use super::*; 30 | 31 | /// Dependencies implementations 32 | pub struct English; 33 | 34 | impl LangDependency for English { 35 | fn say_hello(&self) { 36 | println!("Hi mate"); 37 | } 38 | } 39 | 40 | pub struct Spanish; 41 | 42 | impl LangDependency for Spanish { 43 | fn say_hello(&self) { 44 | println!("Hola amigo"); 45 | } 46 | } 47 | 48 | #[test] 49 | fn dependency_injection() { 50 | let english = Box::new(English); 51 | let hello_service = LangService::new(english); 52 | hello_service.run(); 53 | 54 | let spanish = Box::new(Spanish); 55 | let hola_service = LangService::new(spanish); 56 | hola_service.run() 57 | } 58 | } -------------------------------------------------------------------------------- /ai_api_integration/README.md: -------------------------------------------------------------------------------- 1 | # The Matrix AI - WASM + Rust + Google Gemini API 2 | 3 | Welcome to **The Matrix AI** project! This repository contains a Rust-based web server that interacts with Google's Gemini AI API to generate responses to user questions. The server is embedded in a web page using WebAssembly (WASM) to provide a seamless experience 4 | 5 | ## Project Overview 6 | 7 | This project leverages the power of Rust, WebAssembly (WASM), and Google's Gemini AI API to create an interactive web experience. Users can input a question and an API token, which the server uses to query the Gemini AI API and return a generated response. 8 | 9 | ## Features 10 | 11 | - **Rust-based Backend**: The backend is written in Rust and serves as a bridge between the web client and the Gemini AI API. 12 | - **WASM Integration**: The Rust code is compiled to WebAssembly, allowing it to run directly in the browser. 13 | - **Interactive Web Interface**: Users can input questions and their API token through a user-friendly web interface styled like "The Matrix" movie. 14 | - **Real-time AI Responses**: The system queries the Gemini AI API in real-time and displays the responses directly on the web page. 15 | 16 | ## Requirements 17 | 18 | Before you start, ensure you have the following installed: 19 | 20 | - **Rust**: The latest version of Rust, including the WASM target. 21 | - **Wasm-Pack**: A tool for building Rust-generated WebAssembly packages. 22 | 23 | ## Try yourself 24 | 25 | You can test how this service works hosted in my Github pages [Here](https://politrons.github.io/FunctionalRust/) 26 | 27 | In order to use the service, you will have to obtain a AIStudio API Key [Here](https://aistudio.google.com/app/apikey) 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /red_panda_benchmark/src/produce_consume_load_test.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use goose::prelude::*; 3 | use goose_eggs::{Validate, validate_and_load_static_assets}; 4 | 5 | 6 | #[tokio::main] 7 | async fn main() { 8 | let result = produce_and_consume().await; 9 | println!("{:?}", result) 10 | } 11 | 12 | /// Simulation of Goose where we can define the [transactions] that we want to run and what configuration 13 | /// we want to have for the transactions. 14 | /// We use [GooseAttack::initialize()] to start the builder, then we can register transactions, 15 | /// where we can pass multiple [TransactionResult] 16 | /// Once we have all transactions configured, we can configure the simulation overriding 17 | /// [GooseDefault] using [set_default] operator. 18 | pub async fn produce_and_consume() -> Result<(), GooseError> { 19 | println!("Running produce and consume red panda records...."); 20 | GooseAttack::initialize()? 21 | .register_scenario(scenario!("Produce and consume Red panda records") 22 | .register_transaction(transaction!(produce_and_consume_request))) 23 | .set_default(GooseDefault::Host, "http://127.0.0.1:1981")? 24 | .set_default(GooseDefault::Users, 2)? 25 | .set_default(GooseDefault::StartupTime, 10)? 26 | .set_default(GooseDefault::RunningMetrics, 5)? 27 | .set_default(GooseDefault::RunTime, 120)? 28 | .execute() 29 | .await?; 30 | Ok(()) 31 | } 32 | 33 | async fn produce_and_consume_request(user: &mut GooseUser) -> TransactionResult { 34 | let goose = user.get("/panda/produce_consume").await?; 35 | let validate = &Validate::builder() 36 | .status(200) 37 | .build(); 38 | validate_and_load_static_assets(user, goose, &validate).await?; 39 | Ok(()) 40 | } 41 | -------------------------------------------------------------------------------- /SQUICD/cert.key: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDSFkynwG65a4b0 3 | gy7b3mpDzdGL+VuXxckvrwrcwURqbMt6PpeynfPtzCw1gIgUJVkvr/AF7KQIKLew 4 | GKj0BVA6k+PBpfcF1V12okqBsj43ILduBePYiHLSVtkpM9hPt/OuSgPU5oC7LF3d 5 | FipQ0QOUTR3k4ryi9mr0FDwWoAaTaDcTMNdr2XyzfffcIBUvamQYBXQYq6FoPyUc 6 | 5y0LM7yXc2588jQ5SIwmKEixPNsdhGOS8CKlab9LgJeOP/RRpYzFCh18AJ/oJRCR 7 | 5R/POzyjt1mt/oYZj0ySCnYJSIvV5gnqmB2sUyJstw8wAXT45BvU8p+Y/Jcnn+qa 8 | JkX6mfNvAgMBAAECggEAFVdpkxLzzIc1TupynKhD8D5cvpTmrozLiroD5vgFHLCP 9 | nQv1uhHcoTf/97FmYXGH1VXQkrF+2ktUmaFvrFZL15+FX/sdlGyf0XjcC7/RHSWI 10 | LLeRdUIrM93ZsptPKo37xaVELWD7C8iOgnKJeus4q1yIIGO+GOniZIgXsI6yDFA3 11 | KEadypUnwd0XpkbazIKsdxY+/nUu9efPuAKBRF0h/rVYjBEzMq7FsI7xspOmgPpC 12 | eLXjpVZwvQBaXDYVwb5kW/KT1yu3YJ1v9/+jyzCeo6A7Ea5GmuuxGZdY+LZ1jReP 13 | lOupWQRTI3TDU3ys1vzl3uoVrsiJNoz324oO/gpXjQKBgQD4xr0vzByLuajtGuhI 14 | 657m+WgjmbYnkJm/7e4Yf4VhAh10VStKBj4t0wp759eTbCZ7hd9Tc+Y3ZzoRHtEl 15 | J88EcIE3vZi2MmQ8Fj4uy4jaROYTmUUVs3s2rcKi++wC4lk/+L2qZYe5eVJdcYTl 16 | x1tN0bs8VMJxj7xCYdwBmLCwIwKBgQDYL/eGvTbX07ZCjg5mhhHIEs0ljjLZkT9k 17 | 69Nd14OVmHnTHB3FCggayelSN6VW5WIoTpNS7JpZhRAK8QB9OhkNU11H4ptrL/HC 18 | EQmP1NN6wmCA0jT1OgTvLZLhy+rWwj/C1Oh+mBPKoSV8dUDFlC0UsjeTh6pBn0Po 19 | flq+MoY+RQKBgQCHwFsoI+dHz64AhHhQolJ5k4tiMdSWTm+3rewI7j0oLHFKM9eF 20 | c1amxsynxGF8jr2JFgpBjbMIdInZIcnazphGweWhNxKICYNszm5sNqCdCo/KDg8G 21 | woPv2G2nZnTpNf6hy+gjfXfMnAl3+CQfBuQp2NKlH1NjiJ2gU6osLNftpQKBgQCW 22 | fzXqp5ghQXH0/R2LQ7PnOydzCH3ftdyS7hSzlE82+fF9BGq4+5XOyFbT9Ib2ajMd 23 | 6i1nIe0FertDUqjLhIFiJHGglGErijHbrq6gYUFjiSNTKoLRYDWFJ43EAIgYPxvS 24 | DxNW5ZmJiwskjB+uK8wCR1qnKl9c1XmZxTR4iYWonQKBgHJRXT3ag5tmCusFU5eX 25 | uqNMCb4YjDQL1+5G7wEeUZzjZ+15h2zdBdbkeNlUm9DBmc/zVkuSuYd4zocIxihX 26 | aweDr2GGSJ+o9w6qT0OMAlCG8JWEG5EVL5d/NqZF8r+WNIzxyfsm3jd1QYCFRj9T 27 | PaPdNC24OkVsIy/hPgd/ra+S 28 | -----END PRIVATE KEY----- 29 | -------------------------------------------------------------------------------- /quiche-feature/cert.key: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDSFkynwG65a4b0 3 | gy7b3mpDzdGL+VuXxckvrwrcwURqbMt6PpeynfPtzCw1gIgUJVkvr/AF7KQIKLew 4 | GKj0BVA6k+PBpfcF1V12okqBsj43ILduBePYiHLSVtkpM9hPt/OuSgPU5oC7LF3d 5 | FipQ0QOUTR3k4ryi9mr0FDwWoAaTaDcTMNdr2XyzfffcIBUvamQYBXQYq6FoPyUc 6 | 5y0LM7yXc2588jQ5SIwmKEixPNsdhGOS8CKlab9LgJeOP/RRpYzFCh18AJ/oJRCR 7 | 5R/POzyjt1mt/oYZj0ySCnYJSIvV5gnqmB2sUyJstw8wAXT45BvU8p+Y/Jcnn+qa 8 | JkX6mfNvAgMBAAECggEAFVdpkxLzzIc1TupynKhD8D5cvpTmrozLiroD5vgFHLCP 9 | nQv1uhHcoTf/97FmYXGH1VXQkrF+2ktUmaFvrFZL15+FX/sdlGyf0XjcC7/RHSWI 10 | LLeRdUIrM93ZsptPKo37xaVELWD7C8iOgnKJeus4q1yIIGO+GOniZIgXsI6yDFA3 11 | KEadypUnwd0XpkbazIKsdxY+/nUu9efPuAKBRF0h/rVYjBEzMq7FsI7xspOmgPpC 12 | eLXjpVZwvQBaXDYVwb5kW/KT1yu3YJ1v9/+jyzCeo6A7Ea5GmuuxGZdY+LZ1jReP 13 | lOupWQRTI3TDU3ys1vzl3uoVrsiJNoz324oO/gpXjQKBgQD4xr0vzByLuajtGuhI 14 | 657m+WgjmbYnkJm/7e4Yf4VhAh10VStKBj4t0wp759eTbCZ7hd9Tc+Y3ZzoRHtEl 15 | J88EcIE3vZi2MmQ8Fj4uy4jaROYTmUUVs3s2rcKi++wC4lk/+L2qZYe5eVJdcYTl 16 | x1tN0bs8VMJxj7xCYdwBmLCwIwKBgQDYL/eGvTbX07ZCjg5mhhHIEs0ljjLZkT9k 17 | 69Nd14OVmHnTHB3FCggayelSN6VW5WIoTpNS7JpZhRAK8QB9OhkNU11H4ptrL/HC 18 | EQmP1NN6wmCA0jT1OgTvLZLhy+rWwj/C1Oh+mBPKoSV8dUDFlC0UsjeTh6pBn0Po 19 | flq+MoY+RQKBgQCHwFsoI+dHz64AhHhQolJ5k4tiMdSWTm+3rewI7j0oLHFKM9eF 20 | c1amxsynxGF8jr2JFgpBjbMIdInZIcnazphGweWhNxKICYNszm5sNqCdCo/KDg8G 21 | woPv2G2nZnTpNf6hy+gjfXfMnAl3+CQfBuQp2NKlH1NjiJ2gU6osLNftpQKBgQCW 22 | fzXqp5ghQXH0/R2LQ7PnOydzCH3ftdyS7hSzlE82+fF9BGq4+5XOyFbT9Ib2ajMd 23 | 6i1nIe0FertDUqjLhIFiJHGglGErijHbrq6gYUFjiSNTKoLRYDWFJ43EAIgYPxvS 24 | DxNW5ZmJiwskjB+uK8wCR1qnKl9c1XmZxTR4iYWonQKBgHJRXT3ag5tmCusFU5eX 25 | uqNMCb4YjDQL1+5G7wEeUZzjZ+15h2zdBdbkeNlUm9DBmc/zVkuSuYd4zocIxihX 26 | aweDr2GGSJ+o9w6qT0OMAlCG8JWEG5EVL5d/NqZF8r+WNIzxyfsm3jd1QYCFRj9T 27 | PaPdNC24OkVsIy/hPgd/ra+S 28 | -----END PRIVATE KEY----- 29 | -------------------------------------------------------------------------------- /src/features/promise.rs: -------------------------------------------------------------------------------- 1 | use std::{thread, time}; 2 | use std::future::Future; 3 | use std::io; 4 | use std::net::TcpListener; 5 | use std::sync::mpsc::{channel, Receiver, RecvError, SendError}; 6 | use std::sync::mpsc; 7 | use std::sync::mpsc::Sender; 8 | 9 | use futures::executor::block_on; 10 | 11 | /// We can implement the [Promise] pattern in Rust using [Channels] 12 | /// We create a [Sender(Promise)] and the [Receiver(Future)]. 13 | /// we can run an async task passing the Sender channel, and then continue the logic of your program 14 | /// without blocks. 15 | /// Then once you need to get the result form the Promise, you can subscribe from the [Receiver] 16 | /// and once the Promise finish you will receive the [Result] with the value specify in the type, 17 | /// or side-effect [RecvError] 18 | fn promise_feature() { 19 | let (promise, future): (Sender, Receiver) = mpsc::channel(); 20 | async_std::task::spawn(async_task(promise)); 21 | println!("Continue the work...."); 22 | let result = future.recv(); 23 | match result { 24 | Ok(v) => println!("Received: {}", v), 25 | Err(error) => println!("{}", error.to_string()), 26 | } 27 | } 28 | 29 | /// Here we do an async computation that it will take 2 seconds. Then we will finish the promise 30 | /// using [send] operator. 31 | async fn async_task(promise: Sender) { 32 | thread::sleep(time::Duration::from_secs(2)); 33 | let ack = promise.send(String::from("I finish my task successfully")); 34 | match ack { 35 | Ok(()) => println!("Promise sent successfully"), 36 | Err(error) => println!("{}", error.to_string()), 37 | } 38 | } 39 | 40 | #[cfg(test)] 41 | mod tests { 42 | use super::*; 43 | 44 | #[test] 45 | fn promise() { 46 | promise_feature() 47 | } 48 | } 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /goose/src/goose_load_test.rs: -------------------------------------------------------------------------------- 1 | use goose::prelude::*; 2 | use goose_eggs::{Validate, validate_and_load_static_assets}; 3 | 4 | /// Simulation of Goose where we can define the [transactions] that we want to run and what configuration 5 | /// we want to have for the transactions. 6 | /// We use [GooseAttack::initialize()] to start the builder, then we can register transactions, 7 | /// where we can pass multiple [TransactionResult] 8 | /// Once we have all transactions configured, we can configure the simulation overriding 9 | /// [GooseDefault] using [set_default] operator. 10 | pub async fn run() -> Result<(), GooseError> { 11 | GooseAttack::initialize()? 12 | .register_scenario(scenario!("Mock http server") 13 | .register_transaction(transaction!(hello_endpoint))) 14 | .set_default(GooseDefault::Host, "http://127.0.0.1:1981")? 15 | .set_default(GooseDefault::Users, 30)? 16 | .set_default(GooseDefault::StartupTime, 10)? 17 | .set_default(GooseDefault::RunningMetrics, 5)? 18 | .set_default(GooseDefault::RunTime, 120)? 19 | .execute() 20 | .await?; 21 | Ok(()) 22 | } 23 | 24 | /// [TransactionResult] is the definition of how we make the call to the service endpoint, and 25 | /// how we validate the response. 26 | /// Using from [goose-eggs] dependency [Validate] we can create a validate instance, to be used 27 | /// to compare with [GooseResponse] from the call. 28 | /// We can check what is the [status], [text] from the body is what we expect. 29 | /// 30 | async fn hello_endpoint(user: &mut GooseUser) -> TransactionResult { 31 | let goose = user.get("/hello").await?; 32 | let validate = &Validate::builder() 33 | .status(200) 34 | .text("we will implement /world") 35 | .build(); 36 | validate_and_load_static_assets(user, goose, &validate).await?; 37 | Ok(()) 38 | } 39 | -------------------------------------------------------------------------------- /kafka/src/kafka_producer.rs: -------------------------------------------------------------------------------- 1 | use std::{fs, time}; 2 | use std::string::ToString; 3 | use time::Duration; 4 | 5 | use kafka::producer::{Producer, Record}; 6 | use uuid::Uuid; 7 | 8 | pub fn run() { 9 | let hosts = vec!["localhost:9092".to_owned()]; 10 | let mut producer = create_producer(hosts); 11 | send_records(&mut producer); 12 | } 13 | 14 | /** 15 | We can create a [Kafka] producer using [Producer] struct. Then using [from_host] we create the builder 16 | to append rest of properties like idle_timeout or ack_timeout. 17 | Once finish we can use [create] to finish the builder, and create a [Result] of Producer 18 | */ 19 | fn create_producer(hosts: Vec) -> Producer { 20 | match Producer::from_hosts(hosts) 21 | .with_connection_idle_timeout(Duration::from_secs(10)) 22 | .with_ack_timeout(Duration::from_secs(10)) 23 | .create() { 24 | Ok(producer) => producer, 25 | Err(e) => { 26 | println!("Error creating Kafka producer. Caused by {}", e); 27 | panic!() 28 | } 29 | } 30 | } 31 | 32 | /** 33 | Function to create Records and send to Kafka topic using the [Producer] created previously. 34 | [Record] builder can start the creation of the record by [from], [from_key_value] or [from_key_value] 35 | where you need to specify an already created Record, a key-value pair or just the value. 36 | Then a [Result] type of [Record] is returned to control any possible side-effect 37 | */ 38 | fn send_records(producer: &mut Producer) { 39 | let topic = "topic-name"; 40 | let value = fs::read_to_string("resources/uuid.txt").unwrap(); 41 | for i in 0..1000 { 42 | match producer.send(&Record::from_value(topic,value.as_bytes())) { 43 | Ok(_) => println!("Record Sent: {i}"), 44 | Err(e) => println!("Error sending record. Caused by: {}", e) 45 | } 46 | } 47 | } 48 | 49 | 50 | -------------------------------------------------------------------------------- /tokio/src/tokio_select.rs: -------------------------------------------------------------------------------- 1 | use std::thread; 2 | use futures::channel::oneshot; 3 | 4 | /** 5 | In tokio we can use [spawn] to run any async process i a [green thread]. 6 | In case we want to run several task in parallel and make a [race] like in [ZIO] or other systems, 7 | we can use [select!] which it will be subscribe to all futures in progress, and once it detects that 8 | one finish, it will cancel the rest of the futures in progress. 9 | 10 | [select!] it work with [tokio] [channels], so it subscribe to all [receivers] each of them associated with 11 | as callback operation. And once the received [receive] the data, it invoke the callback 12 | 13 | Here we emulate a Race between cars where once [select!] detect the first car in finish the race, 14 | we automatically invoke the callback associated, and it cancel the rest of futures. 15 | */ 16 | pub async fn race_condition() { 17 | let (tx1, rx1) = oneshot::channel(); 18 | let (tx2, rx2) = oneshot::channel(); 19 | let (tx3, rx3) = oneshot::channel(); 20 | 21 | tokio::spawn(async { 22 | let car = "Porsche"; 23 | println!("{} running race in track {:?}",car, thread::current().id()); 24 | let _ = tx1.send(car); 25 | }); 26 | tokio::spawn(async { 27 | let car = "Ferrari"; 28 | println!("{} running race in track {:?}",car, thread::current().id()); 29 | let _ = tx2.send(car); 30 | }); 31 | tokio::spawn(async { 32 | let car = "Lotus"; 33 | println!("{} running race in track {:?}",car, thread::current().id()); 34 | let _ = tx3.send(car); 35 | }); 36 | 37 | tokio::select! { 38 | winner = rx1 => { 39 | println!("{:?} win the race ", winner); 40 | } 41 | winner = rx2 => { 42 | println!("{:?} win the race ", winner); 43 | } 44 | winner = rx3 => { 45 | println!("{:?} win the race ", winner); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /SQUICD/README.md: -------------------------------------------------------------------------------- 1 | # Squicd 2 | 3 | Author: Pablo Picouto Garcia 4 | 5 | Is this project useful? Please ⭐ Star this repository and share the love. 6 | 7 | Squicd is a Domain-Specific Language (DSL) in Rust designed to simplify the creation of QUIC-based servers and clients for message passing. 8 | 9 | ## Usage 10 | 11 | ### Setting Up the Server 12 | 13 | ```rust 14 | use squicd::dsl::Squicd; 15 | use squicd::common::Message; 16 | 17 | fn main() { 18 | Squicd::with_handler(|message: Message| { 19 | println!("Received message: {:?}", message); 20 | // Additional processing... 21 | }) 22 | .with_error_handler( 23 | |err| { 24 | // Handle side effects 25 | }) 26 | .with_cert("cert.crt") 27 | .with_key("cert.key") 28 | .with_port("4433") 29 | .start(); 30 | } 31 | 32 | ``` 33 | 34 | ### Sending Messages 35 | ```rust 36 | use squicd::common::Message; 37 | use squicd::dsl::Squicd; 38 | 39 | fn main() { 40 | let message = Message { 41 | id: 1, 42 | content: "Hello, Squicd!".to_string(), 43 | timestamp: 1234567890, 44 | }; 45 | 46 | if let Err(e) = Squicd::send_message("127.0.0.1:4433", message) { 47 | eprintln!("Error sending message: {:?}", e); 48 | } 49 | } 50 | 51 | ``` 52 | 53 | ## How It Works 54 | 55 | * Initialization: Configure the server with the provided certificate, key, and port. 56 | 57 | * Starting the Server: Call start() to begin listening for incoming QUIC connections. 58 | * Accepting Connections: New QUIC connections are accepted using the quiche library. 59 | * Receiving Messages: Messages are decompressed, deserialized, and passed to the message handler. 60 | * Processing Messages: The message handler processes incoming messages and can send responses or forward messages. 61 | * Sending Messages: Use send_message to establish a QUIC connection and send messages to other services. -------------------------------------------------------------------------------- /src/features/type_classes.rs: -------------------------------------------------------------------------------- 1 | pub fn run() { 2 | let int_result = TypeClassImpl::sum(10,20); 3 | println!("Integer:{}", int_result.to_string()); 4 | 5 | let str_result = TypeClassImpl::sum("Hello".to_string(),"world".to_string()); 6 | println!("String:{}", str_result.to_string()); 7 | 8 | let bool_result = TypeClassImpl::sum(true,true); 9 | println!("Boolean:{}", bool_result.to_string()); 10 | 11 | let float_result = TypeClassImpl::sum(30.5,10.1); 12 | println!("Float:{}", float_result.to_string()); 13 | 14 | } 15 | 16 | /**Trait interface like in Scala, where we define the function to implement by type classes*/ 17 | trait TypeClass { 18 | fn sum(t1: T, t2: T) -> T; 19 | } 20 | 21 | /** 22 | Type to be used as generic type implementation for [TypeClass] trait. 23 | Once we have implementation of the trait, we can reference this struct, passing 24 | the specific type of the generic, to be redirect to the specific implementation. 25 | */ 26 | struct TypeClassImpl { 27 | value: T, 28 | } 29 | 30 | /** 31 | We define [impl] of the trait type [TypeClass], and then we use 32 | [for] operator to specify over which type class we implement the trait. 33 | In this case we implement [u64] type class 34 | */ 35 | impl TypeClass for TypeClassImpl{ 36 | fn sum(t1: u64, t2: u64) -> u64 { 37 | t1 + t2 38 | } 39 | } 40 | 41 | /** 42 | Type class of [String] type class 43 | */ 44 | impl TypeClass for TypeClassImpl{ 45 | fn sum(t1: String, t2: String) -> String { 46 | t1 + &t2.to_string() 47 | } 48 | } 49 | 50 | /** 51 | Type class of [f64] type class 52 | */ 53 | impl TypeClass for TypeClassImpl{ 54 | fn sum(t1: f64, t2: f64) -> f64 { 55 | t1 + t2 56 | } 57 | } 58 | 59 | /** 60 | Type class of [bool] type class 61 | */ 62 | impl TypeClass for TypeClassImpl{ 63 | fn sum(t1: bool, t2: bool) -> bool { 64 | t1 && t2 65 | } 66 | } -------------------------------------------------------------------------------- /physics_engine/src/main.rs: -------------------------------------------------------------------------------- 1 | use bevy::{ 2 | prelude::*, 3 | window::{PresentMode}, 4 | }; 5 | use bevy_prototype_lyon::prelude::*; 6 | use bevy_rapier2d::prelude::*; 7 | 8 | mod ball; 9 | use ball::*; 10 | 11 | // mod flippers; 12 | // use flippers::*; 13 | 14 | mod walls; 15 | use walls::*; 16 | 17 | mod launcher; 18 | use launcher::*; 19 | 20 | // mod pins; 21 | // use pins::*; 22 | 23 | pub const PIXELS_PER_METER: f32 = 492.3; 24 | 25 | fn main() { 26 | App::new() 27 | .insert_resource(Msaa::default()) 28 | .insert_resource(ClearColor(Color::rgb(0.0, 0.0, 0.0))) 29 | .add_plugins(DefaultPlugins.set(WindowPlugin { 30 | primary_window: Some(Window { 31 | title: "Pinball2d".into(), 32 | resolution: (360., 640.).into(), 33 | present_mode: PresentMode::AutoVsync, 34 | // Tells wasm to resize the window according to the available canvas 35 | fit_canvas_to_parent: true, 36 | // Tells wasm not to override default event handling, like F5, Ctrl+R etc. 37 | prevent_default_event_handling: false, 38 | ..default() 39 | }), 40 | ..default() 41 | })) 42 | .add_plugins(WallsPlugin) 43 | .add_plugins(LauncherPlugin) 44 | // .add_plugins(FlippersPlugin) 45 | .add_plugins(BallPlugin) 46 | // .add_plugins(PinsPlugin) 47 | .add_plugins(ShapePlugin) 48 | .add_systems(Startup,setup) 49 | .add_plugins(RapierPhysicsPlugin::::pixels_per_meter( 50 | PIXELS_PER_METER, 51 | )) 52 | .run(); 53 | } 54 | 55 | fn setup(mut commands: Commands, mut rapier_config: ResMut) { 56 | // Set gravity to x and spawn camera. 57 | //rapier_config.gravity = Vector2::zeros(); 58 | rapier_config.gravity = Vec2::new(0.0, -520.0); 59 | 60 | commands.spawn(Camera2dBundle::default()); 61 | } -------------------------------------------------------------------------------- /patterns/src/structural/composite.rs: -------------------------------------------------------------------------------- 1 | /// Public contract for all data types to be used as component 2 | pub trait Animal { 3 | fn speak(&self); 4 | } 5 | 6 | pub struct Human; 7 | 8 | impl Animal for Human { 9 | fn speak(&self) { 10 | println!("Hello there"); 11 | } 12 | } 13 | 14 | pub struct Dog; 15 | 16 | impl Animal for Dog { 17 | fn speak(&self) { 18 | println!("Burf"); 19 | } 20 | } 21 | 22 | /// [Composite] pattern allow the use of [one] or [multiple] groups of [components] 23 | /// Here we specify the collection of Component elements to bind together. 24 | pub struct Composite { 25 | children: Vec>, 26 | } 27 | 28 | /// In the implementation of Composite, we can initialize the collection, 29 | /// and then add elements into that collection. 30 | /// Then using [add_animal] we can add components as much as we like in the collection. 31 | impl Composite { 32 | pub fn new() -> Self { 33 | Composite { 34 | children: Vec::new(), 35 | } 36 | } 37 | 38 | pub fn add_animal(&mut self, child: Box) { 39 | self.children.push(child); 40 | } 41 | } 42 | 43 | /// We create a [Composite] implementation of the trait, tom be consider another [Component], 44 | /// but in the implementation, we invoke the collection of all [Component] to [Compose] all of them 45 | /// together 46 | impl Animal for Composite { 47 | fn speak(&self) { 48 | println!("Composing all animals"); 49 | for child in &self.children { 50 | child.speak(); 51 | } 52 | } 53 | } 54 | 55 | #[cfg(test)] 56 | mod tests { 57 | 58 | use crate::structural::composite::{Animal, Composite, Dog, Human}; 59 | 60 | #[test] 61 | fn composite_pattern() { 62 | let human = Box::new(Human {}); 63 | let dog = Box::new(Dog {}); 64 | let mut composite = Composite::new(); 65 | composite.add_animal(human); 66 | composite.add_animal(dog); 67 | composite.speak(); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /game_3d/src/player.rs: -------------------------------------------------------------------------------- 1 | use bevy::prelude::*; 2 | use bevy_third_person_camera::*; 3 | 4 | pub struct PlayerPlugin; 5 | 6 | impl Plugin for PlayerPlugin { 7 | fn build(&self, app: &mut App) { 8 | app.add_systems(Startup, spawn_player) 9 | .add_systems(Update, movement); 10 | } 11 | } 12 | 13 | #[derive(Component)] 14 | struct Player; 15 | 16 | #[derive(Component)] 17 | struct Speed(f32); 18 | 19 | fn movement( 20 | input_keys: Res>, 21 | time: Res