blob: ebd20a33c21f916707e9e18f946ffc79c9609127 (
plain)
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
|
/*
This file is part of jellything (https://codeberg.org/metamuffin/jellything)
which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
Copyright (C) 2026 metamuffin <metamuffin.org>
*/
use base64::{Engine, prelude::BASE64_URL_SAFE};
use sha2::Sha256;
use std::{
fmt::Display,
hash::{Hash, Hasher},
};
pub struct HashKey<T>(pub T);
impl<T: Hash> Display for HashKey<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use sha2::Digest;
struct ShaHasher(Sha256);
impl Hasher for ShaHasher {
fn finish(&self) -> u64 {
unreachable!()
}
fn write(&mut self, bytes: &[u8]) {
self.0.update(bytes);
}
}
let mut d = ShaHasher(sha2::Sha256::new());
self.0.hash(&mut d);
let d = d.0.finalize();
f.write_str(&BASE64_URL_SAFE.encode(d))
}
}
const SAFE_CHARS: percent_encoding::AsciiSet = percent_encoding::CONTROLS
.add(b'.')
.add(b'%')
.add(b'/')
.add(b'#')
.add(b'?')
.add(b'@');
pub struct EscapeKey<T>(pub T);
impl<T: Display> Display for EscapeKey<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// TODO perf
f.write_str(
&percent_encoding::utf8_percent_encode(&self.0.to_string(), &SAFE_CHARS)
.to_string()
.replace("%", "@"),
)
}
}
|