GithubHelp home page GithubHelp logo

packtpublishing / rust-programming-cookbook Goto Github PK

View Code? Open in Web Editor NEW
72.0 3.0 32.0 72.47 MB

Rust Programming Cookbook, published by Packt

License: MIT License

Rust 73.84% Makefile 0.53% C 22.71% HTML 0.99% JavaScript 0.13% Python 1.17% Handlebars 0.63%
rust-programming-cookbook rust rust-language

rust-programming-cookbook's Introduction

Rust Programming Cookbook

Rust Programming Cookbook

This is the code repository for Rust Programming Cookbook , published by Packt.

Explore the latest features of Rust 2018 for building fast and secure apps

What is this book about?

Rust 2018, Rust's first major milestone since version 1.0, brings more advancement in the Rust language. The Rust Programming Cookbook is a practical guide to help you overcome challenges when writing Rust code.

This book covers the following exciting features: Understand how Rust provides unique solutions to solve system programming language problems Grasp the core concepts of Rust to develop fast and safe applications Explore the possibility of integrating Rust units into existing applications for improved efficiency Discover how to achieve better parallelism and security with Rust Write Python extensions in Rust Compile external assembly files and use the Foreign Function Interface (FFI) Build web applications and services using Rust for high performance

If you feel this book is for you, get your copy today!

https://www.packtpub.com/

Instructions and Navigations

All of the code is organized into folders. For example, Chapter02.

The code will look like the following:

fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
   let mut ls_child = Command::new("ls");
   if !cfg!(target_os = "windows") {
       ls_child.args(&["-alh"]);

Following is what you need for this book: The Rust cookbook is for software developers looking to enhance their knowledge of Rust and leverage its features using modern programming practices. Familiarity with Rust language is expected to get the most out of this book.

With the following software and hardware list you can run all code files present in the book (Chapter 1-).

Software and Hardware List

No Software required OS required
1 Rust nightly > 2019-10-10 Windows/Linux/macOS
2 Visual Studio Code Windows/Linux/macOS
3 Docker CE stable 19.03 Windows/Linux/macOS
4 Node.js 10.16.3 Windows/Linux/macOS
5 Python 3.6 or later Windows/Linux/macOS
6 gcc >= 9.2 Windows/Linux/macOS
7 Rust stable > 1.38.0 Windows/Linux/macOS

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. Click here to download it.

Related products

Get to Know the Author

Claus Matzinger is a software engineer with a very diverse background. After working in a small company maintaining code for embedded devices, he joined a large corporation to work on legacy Smalltalk applications. This led to a great interest in programming languages early on, and Claus became the CTO for a health games start-up based on Scala technology. Since then, Claus' roles have shifted toward customer-facing roles in the IoT database technology start-up, Crate IO (creators of CrateDB), and, most recently, Microsoft. There, he hosts a podcast, writes code together with customers, and blogs about the solutions arising from these engagements. For more than 5 years, Claus has been implementing software to help customers innovate, achieve, and maintain success.

Suggestions and Feedback

Click here if you have any feedback or suggestions.

Special thanks

Rust is an evolving language and we rely on you to point out anything that has changed since the book release. Open an issue if you find something won't compile and we'll gladly help out.

@tomus85 - Thank you updating three recipes: static-web, json-handling, and legacy-c-code.### Download a free PDF

If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.

https://packt.link/free-ebook/9781789530667

rust-programming-cookbook's People

Contributors

celaus avatar dominicpereira92 avatar gaurav-packt avatar jknight avatar packt-diwakar avatar packt-itservice avatar packtutkarshr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

rust-programming-cookbook's Issues

Chapter 8 Authentication

I have updated the middlewares.rs file.

The full working code is here: (This took me a while to figure out)

use actix_service::{Service, Transform};
use actix_web::dev::{ServiceRequest, ServiceResponse};
use actix_web::{http, Error, HttpResponse};
use jsonwebtoken::{decode, Validation};
use serde::{Deserialize, Serialize};

use futures::future::{ok, Either, Ready};

use std::task::{Context, Poll};

#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
    pub user_id: String,
}

pub struct JwtLogin;

impl<S, B> Transform<S> for JwtLogin
where
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
{
    type Request = ServiceRequest;
    type Response = ServiceResponse<B>;
    type Error = S::Error;
    type InitError = ();
    type Transform = JwtLoginMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
         ok( JwtLoginMiddleware{ service } )
    }
}

pub struct JwtLoginMiddleware<S> {
    service: S,
}

impl<S, B> Service for JwtLoginMiddleware<S>
where
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error >,
    S::Future: 'static,
    // B: 'static,
{
    type Request    = ServiceRequest;
    type Response   = ServiceResponse<B>;
    type Error      = Error;
    type Future = Either<S::Future, Ready<Result<Self::Response, Self::Error>>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.service.poll_ready(cx)
    }

    fn call(&mut self, req: ServiceRequest) -> Self::Future {
        if req.path() == "/login" {
            Either::Left(self.service.call(req))
        }
        else {
            if let Some(header_value) = req.headers().get(http::header::AUTHORIZATION) {
                let token = header_value.to_str().unwrap().replace("Bearer", "");
                let mut validation = Validation::default();
                validation.validate_exp = false; // our login don't expire

                // expire
                if let Ok(_) = decode::<Claims>(&token.trim(), crate::TOKEN_SECRET.as_ref(), &validation) {
                    Either::Left(self.service.call(req))
                }
                else {
                    Either::Right(ok(
                        req.into_response(HttpResponse::Unauthorized().finish().into_body())
                    ))
                }
            }
            else {
                Either::Right(ok(
                    req.into_response(HttpResponse::Unauthorized().finish().into_body())
                ))
            }
        }
    }
}

Chapter 10 web-requests fails to build on latest nightly

$ cargo +nightly run
    Updating crates.io index
  [...]
   Compiling surf v1.0.2
error[E0277]: the trait bound `std::io::Empty: futures_io::if_std::AsyncRead` is not satisfied
  --> /Users/cm/.cargo/registry/src/github.com-1ecc6299db9ec823/surf-1.0.2/src/http_client/mod.rs:64:21
   |
64 |             reader: Box::new(std::io::empty()),
   |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `futures_io::if_std::AsyncRead` is not implemented for `std::io::Empty`
   |
   = note: required for the cast to the object type `dyn futures_io::if_std::AsyncRead + std::marker::Send + std::marker::Unpin`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: could not compile `surf`.
warning: build failed, waiting for other jobs to finish...
error: build failed

Nightly version: 1.40.0

Chapter 7 legacy-c-code

I have followed this command on the macOS:

cargo build

And I am getting this error message

   Compiling rust-digest v0.1.0 (/Users/thomascurley/Downloads/Rust-Programming-Cookbook-master/Chapter07/legacy-c-code/rust-digest)
error: linking with `cc` failed: exit code: 1
  |
  = note: "cc" "-m64" "-L" "/...x86_64-apple-darwin/lib/rustlib/x86_64-apple-darwin/lib/libcompiler_builtins-2c7441db766b2d25.rlib" "-framework" "Security" "-lSystem" "-lresolv" "-lc" "-lm" "-dynamiclib" "-Wl,-dylib"
  = note: Undefined symbols for architecture x86_64:
            "_pre_digest", referenced from:
                _digest in digest.5eqjzyyo4y86c2c8.rcgu.o
          ld: symbol(s) not found for architecture x86_64
          clang: error: linker command failed with exit code 1 (use -v to see invocation)
          

error: aborting due to previous error

error: could not compile `rust-digest`.

To learn more, run the command again with --verbose.

Please note that the output console text is shrunk. How do I solve this. I even downloaded the source from this git repo and still getting the same message

Chapter 8 Static Web won't compile

https://github.com/PacktPublishing/Rust-Programming-Cookbook/tree/master/Chapter08/static-web

I have tried this on macOS Catalina and Ubuntu 18.04 and can't get it compile. This is the response I got

error[E0277]: the trait bound `fn() -> std::result::Result<actix_files::named::NamedFile, actix_web::Error> {<foxes as actix_web::dev::HttpServiceFactory>::register::foxes}: actix_web::dev::Factory<_, _>` is not satisfied
  --> src/main.rs:61:4
   |
61 | fn foxes() -> Result<fs::NamedFile> {
   |    ^^^^^ the trait `actix_web::dev::Factory<_, _>` is not implemented for `fn() -> std::result::Result<actix_files::named::NamedFile, actix_web::Error> {<foxes as actix_web::dev::HttpServiceFactory>::register::foxes}`

error[E0277]: the trait bound `fn() -> std::result::Result<actix_files::named::NamedFile, actix_web::Error> {index}: actix_web::dev::Factory<_, _>` is not satisfied
  --> src/main.rs:72:44
   |
72 |             .service(web::resource("/").to(index))
   |                                            ^^^^^ the trait `actix_web::dev::Factory<_, _>` is not implemented for `fn() -> std::result::Result<actix_files::named::NamedFile, actix_web::Error> {index}`

How do I fix this?

Chapter 8 json-handling 'serde_derive` library.

In this example, I was getting a compile error,

8 | use serde_derive::{Deserialize, Serialize};
  |     ^^^^^^^^^^^^ help: a similar path exists: `serde::serde_derive`

error: cannot determine resolution for the derive macro `Serialize`
  --> src/main.rs:12:24
   |
12 | #[derive(Debug, Clone, Serialize, Deserialize)]
   |                        ^^^^^^^^^
   |
   = note: import resolution is stuck, try simplifying macro imports

error: cannot determine resolution for the derive macro `Deserialize`
  --> src/main.rs:12:35
   |
12 | #[derive(Debug, Clone, Serialize, Deserialize)]

To fix this go to Cargo.toml file and replace

serde_derive = "1"

with

serde = { version = "1.0", features = ["derive"] }

Then go back to main.rs and replace

use serde_derive::{Deserialize, Serialize};

with

use serde::{Deserialize, Serialize};

This should now compile. Tested on macOS Catalina

[book errata] Including Legacy C code - how to do it

Hi,
I followed the book instruction on safari online

$ cd rust-digest/target/release
$ LD_LIBRARY_PATH=$(pwd)
$ echo $LD_LIBRARY_PATH 
/tmp/Rust-Cookbook/Chapter07/legacy-c-code/rust-digest/target/release
$ ./target/main

but got:

./target/main: error while loading shared libraries: libdigest.so: cannot open shared object file: No such file or directory

In bash, we should also export LD_LIBRARY_PATH. I think adding ldd to double check libdigest.so is found would be nice ๐Ÿ˜€.
Or can we make it a static binary?

Ch 1 - data-types - arithmetic-overflow

I was unable to compile because my version of Rust (1.48.0) throws an error on the line which would overflow:

let _ = a - b;

I fixed it by adding an annotation at the top:

#![warn(arithmetic_overflow)]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.