use core::num::NonZeroU32;
use std::error::Error;
use std::fmt;
use bytemuck::{Pod, Zeroable};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Pod, Zeroable)]
#[repr(transparent)]
pub struct FileId(u32);
impl FileId {
pub const SELF: FileId = FileId(0);
pub const SPECIAL_FLOOR: u32 = u32::MAX - 0xFFFF;
pub const fn is_self(self) -> bool {
self.0 == 0
}
pub const fn is_special(self) -> bool {
self.0 >= Self::SPECIAL_FLOOR
}
pub const fn get(self) -> u32 {
self.0
}
pub const fn as_u64(self) -> u64 {
self.0 as u64
}
pub(crate) const fn from_raw(v: u32) -> Self {
FileId(v)
}
pub const fn from_u64(v: u64) -> Option<Self> {
if v <= u32::MAX as u64 {
Some(FileId(v as u32))
} else {
None
}
}
pub(crate) const fn table_index(self) -> Option<usize> {
if self.0 >= 1 && !self.is_special() {
Some((self.0 - 1) as usize)
} else {
None
}
}
pub const fn resolve(self) -> Option<ResolvedFileId> {
ResolvedFileId::new(self)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(transparent)]
pub struct ResolvedFileId(NonZeroU32);
impl ResolvedFileId {
pub const fn new(id: FileId) -> Option<Self> {
if id.is_self() || id.is_special() {
return None;
}
match NonZeroU32::new(id.0) {
Some(nz) => Some(ResolvedFileId(nz)),
None => None,
}
}
pub const unsafe fn new_unchecked(id: FileId) -> Self {
ResolvedFileId(unsafe { NonZeroU32::new_unchecked(id.0) })
}
pub const fn get(self) -> FileId {
FileId(self.0.get())
}
pub const fn as_u32(self) -> u32 {
self.0.get()
}
pub const fn table_index(self) -> usize {
(self.0.get() - 1) as usize
}
}
impl From<ResolvedFileId> for FileId {
#[inline]
fn from(id: ResolvedFileId) -> FileId {
id.get()
}
}
impl TryFrom<FileId> for ResolvedFileId {
type Error = UnresolvedFileIdError;
#[inline]
fn try_from(id: FileId) -> Result<Self, UnresolvedFileIdError> {
ResolvedFileId::new(id).ok_or(UnresolvedFileIdError)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct UnresolvedFileIdError;
impl fmt::Display for UnresolvedFileIdError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("file id is SELF or a reserved special id, not an ordinary registered file")
}
}
impl Error for UnresolvedFileIdError {}