Files
jap_learn/src/data.rs
T

82 lines
2.1 KiB
Rust
Raw Normal View History

2026-08-24 11:35:37 +03:00
pub mod entities;
2026-08-25 15:46:39 +03:00
pub mod repositories;
2026-08-24 11:35:37 +03:00
2026-08-25 12:04:07 +03:00
use rusqlite::ToSql;
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef};
2026-08-30 20:32:16 +03:00
use std::fmt::{write, Display, Formatter};
2026-08-18 12:58:02 +03:00
use std::num::ParseIntError;
use std::str::FromStr;
2026-04-13 22:25:58 +03:00
macro_rules! id_impl {
($id_type:ty, $name:ident, $invalid:ident) => {
#[derive(Clone, PartialEq, Eq, Debug, Hash, Copy, Ord, PartialOrd, Default)]
pub struct $name(pub(crate) $id_type);
pub const $invalid: $name = $name(0);
impl FromStr for $name {
type Err = ParseIntError;
2026-08-18 12:58:02 +03:00
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok($name(s.parse::<$id_type>()?))
}
}
2026-08-18 12:58:02 +03:00
impl From<$id_type> for $name {
fn from(value: $id_type) -> Self {
$name(value)
}
}
2026-08-18 12:58:02 +03:00
impl From<$name> for $id_type {
fn from(value: $name) -> Self {
value.0
}
}
impl Display for $name {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
2026-08-18 12:58:02 +03:00
}
impl FromSql for $name {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
match value {
ValueRef::Integer(i) => Ok($name(i as $id_type)),
_ => Err(FromSqlError::InvalidType),
}
}
}
2026-08-18 12:58:02 +03:00
impl ToSql for $name {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.0 as i64))
}
}
impl From<$name> for String {
fn from(value: $name) -> Self {
value.0.to_string()
}
}
impl $name {
pub(crate) fn is_valid(self) -> bool {
self.0 != 0
}
}
2026-08-20 16:22:38 +03:00
}
}
id_impl!(u32, Id, INVALID_ID);
id_impl!(u16, SmallId, INVALID_SMALL_ID);
2026-08-31 11:21:01 +03:00
impl From<SmallId> for Id {
fn from(value: SmallId) -> Self {
Self(value.0 as u32)
}
}
impl From<Id> for SmallId {
fn from(value: Id) -> Self {
Self(value.0 as u16)
}
}