1use std::io;
4use std::ops::Range;
5
6pub(crate) trait Overlaps {
8 fn overlaps(&self, other: &Self) -> bool;
10}
11
12impl<I: Ord> Overlaps for Range<I> {
13 fn overlaps(&self, other: &Self) -> bool {
14 self.start < other.end && other.start < self.end
15 }
16}
17
18pub(crate) trait ErrorContext {
23 fn context<C: std::fmt::Display>(self, context: C) -> Self;
25}
26
27impl ErrorContext for io::Error {
28 fn context<C: std::fmt::Display>(self, context: C) -> Self {
29 io::Error::new(self.kind(), format!("{context}: {self}"))
30 }
31}
32
33pub(crate) trait ResultErrorContext {
37 fn err_context<C: std::fmt::Display, F: FnOnce() -> C>(self, context: F) -> Self;
41}
42
43impl<V, E: ErrorContext> ResultErrorContext for Result<V, E> {
44 fn err_context<C: std::fmt::Display, F: FnOnce() -> C>(self, context: F) -> Self {
45 self.map_err(|err| err.context(context()))
46 }
47}
48
49#[cfg(feature = "vm-memory")]
57pub trait ImagoAsRef<'a, T: ?Sized> {
58 fn as_ref(&self) -> &'a T;
60}
61
62#[cfg(feature = "vm-memory")]
63impl<'a, T: ?Sized, U: ImagoAsRef<'a, T>> ImagoAsRef<'a, T> for &'a U {
64 fn as_ref(&self) -> &'a T {
65 <U as ImagoAsRef<T>>::as_ref(self)
66 }
67}
68
69#[cfg(feature = "vm-memory")]
70impl<'a, B: vm_memory::bitmap::BitmapSlice> ImagoAsRef<'a, vm_memory::VolatileSlice<'a, B>>
71 for &'a vm_memory::VolatileSlice<'a, B>
72{
73 fn as_ref(&self) -> &'a vm_memory::VolatileSlice<'a, B> {
74 self
75 }
76}
77
78#[cfg(unix)]
86pub(crate) fn while_eintr<R: From<i8> + PartialEq, F: FnMut() -> R>(
87 mut syscall: F,
88) -> io::Result<R> {
89 loop {
90 let ret: R = syscall();
91 if ret == R::from(-1i8) {
92 let err = io::Error::last_os_error();
93 if err.raw_os_error() != Some(libc::EINTR) {
94 return Err(err);
95 }
96 } else {
97 return Ok(ret);
98 }
99 }
100}
101
102pub(crate) fn invalid_data<E: Into<Box<dyn std::error::Error + Send + Sync>>>(
104 error: E,
105) -> io::Error {
106 io::Error::new(io::ErrorKind::InvalidData, error)
107}