use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use super::{CURSOR_VERSION, CursorError, MAX_CURSOR_KIND_LENGTH, MAX_CURSOR_LENGTH};
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
struct CursorEnvelope<T> {
version: u8,
#[serde(skip_serializing_if = "Option::is_none")]
kind: Option<String>,
payload: T,
}
pub fn encode_cursor<T>(value: &T) -> Result<String, CursorError>
where
T: Serialize + ?Sized,
{
encode_cursor_with_kind(None, value)
}
pub fn decode_cursor<T>(cursor: &str) -> Result<T, CursorError>
where
T: DeserializeOwned,
{
decode_cursor_with_kind(None, cursor)
}
pub fn encode_typed_cursor<T>(kind: impl Into<String>, value: &T) -> Result<String, CursorError>
where
T: Serialize + ?Sized,
{
let kind = kind.into();
validate_cursor_kind(&kind)?;
encode_cursor_with_kind(Some(kind), value)
}
pub fn decode_typed_cursor<T>(kind: &str, cursor: &str) -> Result<T, CursorError>
where
T: DeserializeOwned,
{
validate_cursor_kind(kind)?;
decode_cursor_with_kind(Some(kind), cursor)
}
pub(super) fn encode_cursor_with_kind<T>(
kind: Option<String>,
value: &T,
) -> Result<String, CursorError>
where
T: Serialize + ?Sized,
{
let bytes = serde_json::to_vec(&CursorEnvelope {
version: CURSOR_VERSION,
kind,
payload: value,
})?;
let cursor = URL_SAFE_NO_PAD.encode(bytes);
validate_cursor_length(&cursor)?;
Ok(cursor)
}
pub(super) fn decode_cursor_with_kind<T>(kind: Option<&str>, cursor: &str) -> Result<T, CursorError>
where
T: DeserializeOwned,
{
validate_cursor_length(cursor)?;
let bytes = URL_SAFE_NO_PAD
.decode(cursor)
.map_err(|_| CursorError::InvalidEncoding)?;
let envelope: CursorEnvelope<serde::de::IgnoredAny> = serde_json::from_slice(&bytes)?;
validate_cursor_envelope(&envelope, kind)?;
let envelope: CursorEnvelope<T> = serde_json::from_slice(&bytes)?;
Ok(envelope.payload)
}
fn validate_cursor_envelope<T>(
envelope: &CursorEnvelope<T>,
expected_kind: Option<&str>,
) -> Result<(), CursorError> {
if envelope.version != CURSOR_VERSION {
return Err(CursorError::UnsupportedVersion {
actual: envelope.version,
});
}
if let Some(actual) = &envelope.kind {
validate_cursor_kind(actual)?;
}
if let Some(expected) = expected_kind
&& envelope.kind.as_deref() != Some(expected)
{
return Err(CursorError::KindMismatch {
expected: expected.to_owned(),
actual: envelope.kind.clone(),
});
}
Ok(())
}
pub(super) fn validate_cursor_length(cursor: &str) -> Result<(), CursorError> {
if cursor.is_empty() {
return Err(CursorError::Empty);
}
if cursor.len() > MAX_CURSOR_LENGTH {
return Err(CursorError::TooLarge {
max: MAX_CURSOR_LENGTH,
});
}
Ok(())
}
pub(super) fn validate_cursor_kind(kind: &str) -> Result<(), CursorError> {
if kind.is_empty()
|| kind.len() > MAX_CURSOR_KIND_LENGTH
|| !kind
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
{
return Err(CursorError::InvalidKind);
}
Ok(())
}