use crate::Error;
use windows_sys::Win32::Foundation::STATUS_INSUFFICIENT_RESOURCES;
#[cfg(feature = "alloc")]
use alloc::collections::TryReserveError;
#[cfg(feature = "allocator-api")]
use core::alloc::AllocError;
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
impl From<TryReserveError> for Error {
#[inline]
fn from(_: TryReserveError) -> Self {
Self(STATUS_INSUFFICIENT_RESOURCES)
}
}
#[cfg(feature = "allocator-api")]
#[cfg_attr(docsrs, doc(cfg(feature = "allocator-api")))]
impl From<AllocError> for Error {
#[inline]
fn from(_: AllocError) -> Self {
Self(STATUS_INSUFFICIENT_RESOURCES)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "alloc")]
#[test]
fn try_reserve_error_maps_to_insufficient_resources() {
let err: TryReserveError = alloc::vec::Vec::<u8>::new()
.try_reserve(usize::MAX)
.unwrap_err();
assert_eq!(Error::from(err).ntstatus(), STATUS_INSUFFICIENT_RESOURCES);
}
#[cfg(feature = "alloc")]
#[test]
fn try_reserve_error_propagates_through_question_mark() {
fn allocate(len: usize) -> crate::Result<alloc::vec::Vec<u8>> {
let mut buf = alloc::vec::Vec::new();
buf.try_reserve(len)?;
Ok(buf)
}
assert!(allocate(16).is_ok());
assert!(
allocate(usize::MAX)
.unwrap_err()
.is(STATUS_INSUFFICIENT_RESOURCES)
);
}
#[cfg(feature = "allocator-api")]
#[test]
fn alloc_error_maps_to_insufficient_resources() {
assert_eq!(
Error::from(AllocError).ntstatus(),
STATUS_INSUFFICIENT_RESOURCES
);
}
#[cfg(feature = "allocator-api")]
#[test]
fn alloc_error_propagates_through_question_mark() {
fn fallible(fail: bool) -> crate::Result<u32> {
if fail {
Err(AllocError)?;
}
Ok(7)
}
assert_eq!(fallible(false).unwrap(), 7);
assert!(
fallible(true)
.unwrap_err()
.is(STATUS_INSUFFICIENT_RESOURCES)
);
}
}