Skip to content

Commit

Permalink
Merge pull request #40 from vemoo/avoid-vec
Browse files Browse the repository at this point in the history
Avoid vector allocation
  • Loading branch information
Peter authored Oct 11, 2018
2 parents 6a29be2 + f85b647 commit c4b5672
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 24 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rust-embed"
version = "3.0.2"
version = "4.0.0"
description = "Rust Custom Derive Macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev"
readme = "readme.md"
documentation = "https://docs.rs/rust-embed"
Expand Down
19 changes: 6 additions & 13 deletions examples/actix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ extern crate actix_web;
extern crate rust_embed;
extern crate mime_guess;

use actix_web::{App, HttpRequest, HttpResponse, server};
use actix_web::http::Method;
use actix_web::{server, App, Body, HttpRequest, HttpResponse};
use mime_guess::guess_mime_type;

#[derive(RustEmbed)]
Expand All @@ -13,11 +13,9 @@ struct Asset;

fn handle_embedded_file(path: &str) -> HttpResponse {
match Asset::get(path) {
Some(content) => {
HttpResponse::Ok()
.content_type(guess_mime_type(path).as_ref())
.body(content)
}
Some(content) => HttpResponse::Ok()
.content_type(guess_mime_type(path).as_ref())
.body(Body::from_slice(content.as_ref())),
None => HttpResponse::NotFound().body("404 Not Found"),
}
}
Expand All @@ -32,13 +30,8 @@ fn dist(req: HttpRequest) -> HttpResponse {
}

fn main() {
server::new(|| {
App::new().route("/", Method::GET, index).route(
"/dist/{_:.*}",
Method::GET,
dist,
)
}).bind("127.0.0.1:8000")
server::new(|| App::new().route("/", Method::GET, index).route("/dist/{_:.*}", Method::GET, dist))
.bind("127.0.0.1:8000")
.unwrap()
.run();
}
2 changes: 1 addition & 1 deletion examples/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ struct Asset;

fn main() {
let index_html = Asset::get("index.html").unwrap();
println!("{:?}", std::str::from_utf8(&index_html));
println!("{:?}", std::str::from_utf8(index_html.as_ref()));
}
8 changes: 4 additions & 4 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ You can use this to embed your css, js and images into a single executable which

```
[dependencies]
rust-embed="3.0.2"
rust-embed="4.0.0"
```

## Documentation
Expand All @@ -23,9 +23,9 @@ You need to add the custom derive macro RustEmbed to your struct with an attribu
#[folder = "examples/public/"]
struct Asset;
```
This macro adds a single static method `get` to your type. This method allows you to get your assets from the fs during dev and from the binary during release. It takes the file path as string and returns an optional vector of u8.
This macro adds a single static method `get` to your type. This method allows you to get your assets from the fs during dev and from the binary during release. It takes the file path as string and returns an `Option` with the bytes.
```rust
pub fn get(file_path: &str) -> Option<Vec<u8>>
pub fn get(file_path: &str) -> Option<impl AsRef<[u8]>>
```

## Usage
Expand All @@ -39,7 +39,7 @@ struct Asset;

fn main() {
let index_html = Asset::get("index.html").unwrap();
println!("{:?}", std::str::from_utf8(&index_html));
println!("{:?}", std::str::from_utf8(index_html.as_ref()));
}
```

Expand Down
14 changes: 9 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ extern crate syn;
extern crate walkdir;

use proc_macro::TokenStream;
use syn::*;
use quote::Tokens;
use std::path::Path;
use syn::*;

#[cfg(debug_assertions)]
fn generate_assets(ident: &syn::Ident, folder_path: String) -> quote::Tokens {
quote!{
impl #ident {
pub fn get(file_path: &str) -> Option<Vec<u8>> {
pub fn get(file_path: &str) -> Option<impl AsRef<[u8]>> {
use std::fs::File;
use std::io::Read;
use std::path::Path;
Expand Down Expand Up @@ -63,13 +63,13 @@ fn generate_assets(ident: &syn::Ident, folder_path: String) -> quote::Tokens {
let key = if std::path::MAIN_SEPARATOR == '\\' { key.replace('\\', "/") } else { key };
let canonical_path_str = canonical_path.to_str();
let value = quote!{
#key => Some(include_bytes!(#canonical_path_str).to_vec()),
#key => Some(&include_bytes!(#canonical_path_str)[..]),
};
values.push(value);
}
quote!{
impl #ident {
pub fn get(file_path: &str) -> Option<Vec<u8>> {
pub fn get(file_path: &str) -> Option<impl AsRef<[u8]>> {
match file_path {
#(#values)*
_ => None,
Expand Down Expand Up @@ -115,7 +115,11 @@ fn impl_rust_embed(ast: &syn::DeriveInput) -> Tokens {
}
};
if !Path::new(&folder_path).exists() {
panic!("#[derive(RustEmbed)] folder '{}' does not exist. cwd: '{}'", folder_path, std::env::current_dir().unwrap().to_str().unwrap());
panic!(
"#[derive(RustEmbed)] folder '{}' does not exist. cwd: '{}'",
folder_path,
std::env::current_dir().unwrap().to_str().unwrap()
);
};
generate_assets(ident, folder_path)
}
Expand Down

0 comments on commit c4b5672

Please sign in to comment.