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
#![forbid(elided_lifetimes_in_paths, unsafe_code)]

//! Private implementation detail of the `gotham_restful` crate.

use base64::prelude::*;
use either::Either;
use sha2::{Digest, Sha256};
use std::{io::Write, iter};

#[doc(hidden)]
pub struct Redoc {
	/// HTML code.
	pub html: Vec<u8>,

	/// JS hash base64 encoded.
	pub script_hash: String
}

#[doc(hidden)]
pub fn html(spec: String) -> Redoc {
	let encoded_spec = spec
		.chars()
		.flat_map(|c| match c {
			'&' => Either::Left("&amp;".chars()),
			'<' => Either::Left("&lt;".chars()),
			'>' => Either::Left("&gt;".chars()),
			c => Either::Right(iter::once(c))
		})
		.collect::<String>();

	let script = include_str!("script.min.js");
	let mut script_hash = Sha256::new();
	script_hash.update(script);
	let script_hash = BASE64_STANDARD.encode(script_hash.finalize());

	let mut html = Vec::<u8>::new();
	write!(
		html,
		concat!(
			"<!DOCTYPE HTML>",
			"<html>",
			"<head>",
			r#"<meta charset="utf-8"/>"#,
			r#"<meta name="viewport" content="width=device-width,initial-scale=1"/>"#,
			"</head>",
			r#"<body style="margin:0">"#,
			r#"<div id="spec" style="display:none">{}</div>"#,
			r#"<div id="redoc"></div>"#,
			r#"<script>{}</script>"#,
			"</body>",
			"</html>"
		),
		encoded_spec, script
	)
	.unwrap();

	Redoc { html, script_hash }
}