1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#![cfg_attr(not(feature = "stable"), feature(proc_macro_span))]
extern crate proc_macro;
use std::fs::File;
use std::path::PathBuf;
use std::str::from_utf8;
use libflate::deflate::Encoder;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{Error, LitByteStr, LitStr, Result};
#[cfg_attr(feature = "stable", proc_macro_hack::proc_macro_hack)]
#[cfg_attr(not(feature = "stable"), proc_macro)]
pub fn deflate_file(ts: TokenStream) -> TokenStream {
match inner(ts, false) {
Ok(ts) => ts.into(),
Err(err) => err.to_compile_error().into(),
}
}
#[cfg_attr(feature = "stable", proc_macro_hack::proc_macro_hack)]
#[cfg_attr(not(feature = "stable"), proc_macro)]
pub fn deflate_utf8_file(ts: TokenStream) -> TokenStream {
match inner(ts, true) {
Ok(ts) => ts.into(),
Err(err) => err.to_compile_error().into(),
}
}
fn inner(ts: TokenStream, utf8: bool) -> Result<impl Into<TokenStream>> {
let dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let lit = syn::parse::<LitStr>(ts)?;
let path = PathBuf::from(lit.value());
let target = if path.is_relative() {
dir.join(path)
} else {
path
};
fn emap<E: std::fmt::Display>(error: E) -> Error {
Error::new(Span::call_site(), error)
}
let mut file = File::open(target).map_err(emap)?;
let mut encoder = Encoder::new(Vec::<u8>::new());
if utf8 {
use std::io::Write;
let mut vec = Vec::<u8>::new();
std::io::copy(&mut file, &mut vec).map_err(emap)?;
from_utf8(&vec).map_err(emap)?;
encoder.write_all(&vec).map_err(emap)?;
} else {
std::io::copy(&mut file, &mut encoder).map_err(emap)?;
}
let bytes = encoder.finish().into_result().map_err(emap)?;
let bytes = LitByteStr::new(&bytes, Span::call_site());
let result = quote!(#bytes);
Ok(result)
}