include_base64/
lib.rs

1//! include-base64 is a library for including a file as a base64 string, à la [`std::include_str!`].
2#![deny(missing_docs)]
3extern crate proc_macro;
4#[macro_use]
5extern crate syn;
6
7use std::{
8    error::Error,
9    fs::File,
10    io::{self, BufReader},
11    path::Path,
12};
13
14use base64::{write::EncoderStringWriter, CharacterSet, Config};
15use proc_macro::TokenStream;
16use quote::quote;
17use syn::LitStr;
18
19/// Includes a file as a base-64 string literal at compile time.
20///
21/// # Example
22///
23/// ```rust
24/// # use include_base64::include_base64;
25/// const MY_FILE_BUT_IN_BASE64: &str = include_base64!("my_file.txt");
26/// ```
27#[proc_macro]
28pub fn include_base64(input: TokenStream) -> TokenStream {
29    let string = parse_macro_input!(input as LitStr).value();
30    include_from_file(Path::new(&string)).unwrap_or_else(|s| {
31        let s = s.to_string();
32        quote!(compile_error!(#s)).into()
33    })
34}
35
36fn include_from_file(path: &Path) -> Result<TokenStream, Box<dyn Error>> {
37    let len = path.metadata()?.len();
38    if len / 8 > usize::MAX as u64 {
39        return Err(format!("File too big (max: {})", usize::MAX).into());
40    }
41    let mut file_reader = BufReader::new(File::open(path)?);
42    let mut string_writer = EncoderStringWriter::new(Config::new(CharacterSet::UrlSafe, true));
43    io::copy(&mut file_reader, &mut string_writer)?;
44    let string = string_writer.into_inner();
45    Ok(quote!(#string).into())
46}