use super::*;
#[inline]
pub(crate) fn cache_now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|dur: Duration| dur.as_millis() as u64)
.unwrap_or(0)
}
#[inline(always)]
pub(crate) fn request_header_back<'a>(req: &'a Request, lower_key: &str) -> Option<&'a str> {
req.get_headers()
.get(lower_key)
.and_then(|values: &VecDeque<String>| values.back())
.map(String::as_str)
}
#[inline(always)]
pub(crate) fn response_header_back<'a>(resp: &'a Response, lower_key: &str) -> Option<&'a str> {
resp.get_headers()
.get(lower_key)
.and_then(|values: &VecDeque<String>| values.back())
.map(String::as_str)
}
#[inline]
pub(crate) fn format_u64_stack(mut value: u64, buf: &mut [u8; AGE_STACK_BUF_LEN]) -> &str {
let mut pos: usize = AGE_STACK_BUF_LEN;
if value == 0 {
pos -= 1;
buf[pos] = ASCII_ZERO;
} else {
while value > 0 {
pos -= 1;
buf[pos] = ASCII_ZERO + (value % 10) as u8;
value /= 10;
}
}
from_utf8(&buf[pos..]).unwrap_or_default()
}
#[inline(always)]
pub(crate) fn cache_shard_index(key: &str) -> usize {
let bytes: &[u8] = key.as_bytes();
let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
let mut hash: u64 = CACHE_FNV1A_OFFSET_BASIS ^ (bytes.len() as u64);
for chunk in chunks {
hash = (hash ^ u64::from_ne_bytes(*chunk)).wrapping_mul(CACHE_SHARD_MUL1);
}
if !rem.is_empty() {
let mut tail: u64 = 0;
for &b in rem {
tail = (tail << 8) | u64::from(b);
}
hash = (hash ^ tail).wrapping_mul(CACHE_SHARD_MUL2);
}
((hash ^ (hash >> 32)) as usize) & (CACHE_SHARD_COUNT - 1)
}
pub(crate) fn build_cached_http11_wire(value: &CachedValue) -> Option<Box<CachedHttp11Wire>> {
let status: usize = value.get_status_code();
if (100..=199).contains(&status) || status == 204 || status == 205 || status == 304 {
return None;
}
for (name, _) in value.get_headers() {
if name.eq_ignore_ascii_case(CONTENT_ENCODING)
|| name.eq_ignore_ascii_case(TRANSFER_ENCODING)
{
return None;
}
}
let mut resp: Response = Response::default();
resp.set_status_code(status);
for (name, val) in value.get_headers() {
resp.set_header(name, val);
}
resp.set_body(value.get_body().as_slice());
let without_diag: Vec<u8> = resp.build();
let hdr_end: usize = without_diag
.windows(CACHE_WIRE_HEADER_END.len())
.position(|w: &[u8]| w == CACHE_WIRE_HEADER_END)?;
let insert_pos: usize = hdr_end + CACHE_WIRE_CRLF.len();
let mut with_diag_prefix: Vec<u8> =
Vec::with_capacity(insert_pos + CACHE_WIRE_DIAG_PREFIX.len());
with_diag_prefix.extend_from_slice(&without_diag[..insert_pos]);
with_diag_prefix.extend_from_slice(CACHE_WIRE_DIAG_PREFIX);
let tail_slice: &[u8] = &without_diag[insert_pos..];
let mut with_diag_suffix: Vec<u8> =
Vec::with_capacity(CACHE_WIRE_CRLF.len() + tail_slice.len());
with_diag_suffix.extend_from_slice(CACHE_WIRE_CRLF);
with_diag_suffix.extend_from_slice(tail_slice);
Some(Box::new(CachedHttp11Wire {
without_diag,
with_diag_prefix,
with_diag_suffix,
}))
}
#[inline]
pub(crate) fn estimate_entry_bytes(key: &str, value: &CachedValue) -> usize {
let header_bytes: usize = value
.get_headers()
.iter()
.map(|(k, v): &(String, String)| k.len() + v.len())
.sum();
key.len() + header_bytes + value.get_body().len() + 64
}
#[inline(always)]
pub(crate) fn strip_prefix_ignore_ascii_case<'a>(input: &'a str, prefix: &str) -> Option<&'a str> {
if input.len() < prefix.len() {
return None;
}
let (head, tail): (&'a str, &'a str) = input.split_at(prefix.len());
if head.eq_ignore_ascii_case(prefix) {
Some(tail)
} else {
None
}
}
#[inline(always)]
pub(crate) fn parse_u64_ascii(raw: &str) -> Option<u64> {
let bytes: &[u8] = raw.as_bytes();
if bytes.is_empty() {
return None;
}
let mut acc: u64 = 0;
for &b in bytes {
if !b.is_ascii_digit() {
return None;
}
acc = acc.checked_mul(10)?.checked_add((b - ASCII_ZERO) as u64)?;
}
Some(acc)
}
#[inline]
pub(crate) fn parse_cache_control(header: Option<&str>) -> (bool, Option<u64>) {
let Some(raw) = header else {
return (true, None);
};
let mut s_maxage_secs: Option<u64> = None;
let mut max_age_secs: Option<u64> = None;
for directive in raw.split(',') {
let trimmed: &str = directive.trim();
if trimmed.eq_ignore_ascii_case(CC_NO_STORE)
|| trimmed.eq_ignore_ascii_case(CC_NO_CACHE)
|| trimmed.eq_ignore_ascii_case(CC_PRIVATE)
{
return (false, None);
}
if let Some(secs_str) = strip_prefix_ignore_ascii_case(trimmed, CC_S_MAXAGE_PREFIX)
&& let Some(secs) = parse_u64_ascii(secs_str.trim())
{
s_maxage_secs = Some(secs);
} else if let Some(secs_str) = strip_prefix_ignore_ascii_case(trimmed, CC_MAX_AGE_PREFIX)
&& let Some(secs) = parse_u64_ascii(secs_str.trim())
{
max_age_secs = Some(secs);
}
}
let chosen: Option<u64> = s_maxage_secs.or(max_age_secs);
if chosen == Some(0) {
return (false, None);
}
(true, chosen.map(|secs: u64| secs.saturating_mul(1_000)))
}
#[inline]
pub(crate) fn build_http_cache_key_cow<'a>(ctx: &'a Context) -> Cow<'a, str> {
let path: &'a str = ctx.get_request().get_path();
let querys: &'a RequestQuerys = ctx.get_request().get_querys();
if querys.is_empty() {
return Cow::Borrowed(path);
}
let mut pairs: Vec<(&str, &VecDeque<String>)> = Vec::with_capacity(querys.len());
let mut query_bytes: usize = 1;
for (k, vals) in querys {
pairs.push((k.as_str(), vals));
for v in vals {
query_bytes += k.len() + v.len() + 2;
}
}
if pairs.len() > 1 {
pairs.sort_unstable_by(
|a: &(&str, &VecDeque<String>), b: &(&str, &VecDeque<String>)| a.0.cmp(b.0),
);
}
let mut key: String = String::with_capacity(path.len() + query_bytes);
key.push_str(path);
key.push('?');
let mut first: bool = true;
for (k, vals) in pairs {
for v in vals {
if !first {
key.push('&');
}
first = false;
key.push_str(k);
key.push('=');
key.push_str(v);
}
}
Cow::Owned(key)
}