1use std::{
45 cell::Cell,
46 ffi::c_void,
47 fmt, io,
48 os::unix::ffi::OsStrExt as _,
49 path::Path,
50 ptr,
51 sync::{
52 OnceLock,
53 atomic::{AtomicBool, AtomicI32, AtomicU8, AtomicU64, AtomicUsize, Ordering, fence},
54 },
55};
56
57const ALT_STACK_BASE: usize = 65_536;
60
61const TASK_CAPACITY: usize = 1_024;
64
65const LOCK_CAPACITY: usize = 4_095;
69
70const PATH_BUFFER: usize = 4_096;
73
74const MESSAGE_CAPACITY: usize = 1_280;
77
78const WRITE_ATTEMPTS: u32 = 8;
81
82const TASK_PREFIX: &[u8] = b"error: the program of task ";
84
85const TASK_SUFFIX: &[u8] =
87 b" overflowed the stack, so kizz stopped; its values are probably nested too deeply\n";
88
89const NO_TASK: &[u8] = b"error: kizz overflowed its stack and stopped\n";
91
92static TASK: Slot<TASK_CAPACITY> = Slot::new();
94
95static LOCK: Slot<LOCK_CAPACITY> = Slot::new();
97
98static NEXT_NOTE: AtomicU64 = AtomicU64::new(1);
100
101static INSTALLED: AtomicBool = AtomicBool::new(false);
103
104static INSTALLER: AtomicI32 = AtomicI32::new(0);
106
107static STATUS: AtomicI32 = AtomicI32::new(2);
109
110static EARLIER_SEGV: OnceLock<libc::sigaction> = OnceLock::new();
113
114static EARLIER_BUS: OnceLock<libc::sigaction> = OnceLock::new();
117
118thread_local! {
119 static REGION: Cell<Region> = const { Cell::new(Region::NONE) };
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128struct Region {
129 start: usize,
131 end: usize,
133}
134
135impl Region {
136 const NONE: Self = Self { start: 0, end: 0 };
138
139 const fn contains(
141 self,
142 address: usize,
143 ) -> bool {
144 self.start <= address && address < self.end
145 }
146}
147
148fn guard_region(
154 lowest: usize,
155 guard_size: usize,
156 page: usize,
157) -> Option<Region> {
158 let guard = guard_size.max(page);
159 if guard == 0 {
160 return None;
161 }
162 Some(Region {
163 start: lowest.checked_sub(guard)?,
164 end: lowest.checked_add(guard)?,
165 })
166}
167
168fn alt_stack_size(
172 page: usize,
173 minimum: usize,
174) -> Option<usize> {
175 ALT_STACK_BASE
176 .checked_add(minimum)?
177 .checked_next_multiple_of(page)
178}
179
180fn cut(
183 text: &str,
184 capacity: usize,
185) -> &str {
186 (0..=capacity.min(text.len()))
187 .rev()
188 .find(|&end| text.is_char_boundary(end))
189 .and_then(|end| text.get(..end))
190 .unwrap_or_default()
191}
192
193fn compose(
198 task: Option<&[u8]>,
199 out: &mut [u8],
200) -> usize {
201 let parts: [&[u8]; 3] = match task {
202 Some(task) if !task.is_empty() => [TASK_PREFIX, task, TASK_SUFFIX],
203 _ => [NO_TASK, &[], &[]],
204 };
205 let mut length: usize = 0;
206 for (slot, byte) in out
207 .iter_mut()
208 .zip(parts.iter().flat_map(|part| part.iter()))
209 {
210 *slot = *byte;
211 length = length.saturating_add(1);
212 }
213 length
214}
215
216struct Slot<const N: usize> {
224 seq: AtomicU64,
226 len: AtomicUsize,
228 owner: AtomicU64,
230 bytes: [AtomicU8; N],
232}
233
234impl<const N: usize> Slot<N> {
235 const fn new() -> Self {
237 Self {
238 seq: AtomicU64::new(0),
239 len: AtomicUsize::new(0),
240 owner: AtomicU64::new(0),
241 bytes: [const { AtomicU8::new(0) }; N],
242 }
243 }
244
245 fn begin(&self) {
247 loop {
248 let seq = self.seq.load(Ordering::Relaxed);
249 if (seq & 1) == 0
250 && self
251 .seq
252 .compare_exchange_weak(
253 seq,
254 seq.wrapping_add(1),
255 Ordering::Acquire,
256 Ordering::Relaxed,
257 )
258 .is_ok()
259 {
260 break;
261 }
262 std::hint::spin_loop();
263 }
264 fence(Ordering::Release);
265 }
266
267 fn end(&self) {
269 self.seq.fetch_add(1, Ordering::Release);
270 }
271
272 fn write(
275 &self,
276 bytes: &[u8],
277 ) -> u64 {
278 let id = NEXT_NOTE.fetch_add(1, Ordering::Relaxed);
279 self.begin();
280 let mut length: usize = 0;
281 for (slot, byte) in self.bytes.iter().zip(bytes) {
282 slot.store(*byte, Ordering::Relaxed);
283 length = length.saturating_add(1);
284 }
285 self.len.store(length, Ordering::Relaxed);
286 self.owner.store(id, Ordering::Relaxed);
287 self.end();
288 id
289 }
290
291 fn clear(
294 &self,
295 id: u64,
296 ) {
297 self.begin();
298 if self.owner.load(Ordering::Relaxed) == id {
299 self.len.store(0, Ordering::Relaxed);
300 self.owner.store(0, Ordering::Relaxed);
301 }
302 self.end();
303 }
304
305 fn read(
312 &self,
313 out: &mut [u8],
314 between: impl FnOnce(),
315 ) -> Option<usize> {
316 let before = self.seq.load(Ordering::Acquire);
317 if (before & 1) != 0 {
318 return None;
319 }
320 let length = self.len.load(Ordering::Relaxed);
321 for (slot, byte) in out.iter_mut().zip(&self.bytes).take(length) {
322 *slot = byte.load(Ordering::Relaxed);
323 }
324 between();
325 fence(Ordering::Acquire);
326 let after = self.seq.load(Ordering::Relaxed);
327 (after == before && length > 0 && length <= out.len()).then_some(length)
328 }
329}
330
331#[derive(Debug)]
333#[must_use = "the note is removed when it is dropped"]
334pub struct Note {
335 id: u64,
337 clear: fn(u64),
339}
340
341impl Drop for Note {
342 fn drop(&mut self) {
343 if self.id != 0 {
344 (self.clear)(self.id);
345 }
346 }
347}
348
349fn clear_task(id: u64) {
351 TASK.clear(id);
352}
353
354fn clear_lock(id: u64) {
356 LOCK.clear(id);
357}
358
359pub fn note_task(text: &str) -> Note {
363 Note {
364 id: TASK.write(cut(text, TASK_CAPACITY).as_bytes()),
365 clear: clear_task,
366 }
367}
368
369pub fn note_lock(path: &Path) -> Note {
373 let bytes = path.as_os_str().as_bytes();
374 if bytes.is_empty() || bytes.len() > LOCK_CAPACITY || bytes.contains(&0) {
375 return Note {
376 id: 0,
377 clear: clear_lock,
378 };
379 }
380 Note {
381 id: LOCK.write(bytes),
382 clear: clear_lock,
383 }
384}
385
386#[derive(Debug)]
388pub struct InstallError {
389 call: &'static str,
391 error: io::Error,
393}
394
395impl InstallError {
396 fn last(call: &'static str) -> Self {
398 Self {
399 call,
400 error: io::Error::last_os_error(),
401 }
402 }
403
404 fn code(
406 call: &'static str,
407 code: i32,
408 ) -> Self {
409 Self {
410 call,
411 error: io::Error::from_raw_os_error(code),
412 }
413 }
414
415 fn invalid(
417 call: &'static str,
418 what: &'static str,
419 ) -> Self {
420 Self {
421 call,
422 error: io::Error::new(io::ErrorKind::InvalidData, what),
423 }
424 }
425}
426
427impl fmt::Display for InstallError {
428 fn fmt(
429 &self,
430 formatter: &mut fmt::Formatter<'_>,
431 ) -> fmt::Result {
432 write!(formatter, "{} failed: {}", self.call, self.error)
433 }
434}
435
436impl std::error::Error for InstallError {}
438
439fn page_size() -> Result<usize, InstallError> {
441 let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
443 usize::try_from(page)
444 .ok()
445 .filter(|&page| page > 0)
446 .ok_or_else(|| InstallError::invalid("sysconf", "no page size"))
447}
448
449fn stack_region() -> Result<Region, InstallError> {
452 let page = page_size()?;
453 let mut attributes = std::mem::MaybeUninit::<libc::pthread_attr_t>::uninit();
454 let status = unsafe { libc::pthread_getattr_np(libc::pthread_self(), attributes.as_mut_ptr()) };
457 if status != 0 {
458 return Err(InstallError::code("pthread_getattr_np", status));
459 }
460 let mut lowest: *mut c_void = ptr::null_mut();
461 let mut size: usize = 0;
462 let mut guard: usize = 0;
463 let stack =
466 unsafe { libc::pthread_attr_getstack(attributes.as_ptr(), &raw mut lowest, &raw mut size) };
467 let guarded = unsafe { libc::pthread_attr_getguardsize(attributes.as_ptr(), &raw mut guard) };
469 unsafe { libc::pthread_attr_destroy(attributes.as_mut_ptr()) };
472 if stack != 0 {
473 return Err(InstallError::code("pthread_attr_getstack", stack));
474 }
475 if guarded != 0 {
476 return Err(InstallError::code("pthread_attr_getguardsize", guarded));
477 }
478 guard_region(lowest.addr(), guard, page)
479 .ok_or_else(|| InstallError::invalid("pthread_attr_getstack", "the guard region overflows"))
480}
481
482struct AltStack {
484 base: *mut c_void,
486 length: usize,
488 earlier: libc::stack_t,
490}
491
492impl AltStack {
493 fn set_up() -> Result<Self, InstallError> {
496 let page = page_size()?;
497 let minimum = unsafe { libc::getauxval(libc::AT_MINSIGSTKSZ) };
499 let size = alt_stack_size(page, usize::try_from(minimum).unwrap_or(0))
500 .ok_or_else(|| InstallError::invalid("getauxval", "the signal stack size overflows"))?;
501 let length = size
502 .checked_add(page)
503 .ok_or_else(|| InstallError::invalid("getauxval", "the signal stack size overflows"))?;
504 let base = unsafe {
507 libc::mmap(
508 ptr::null_mut(),
509 length,
510 libc::PROT_READ | libc::PROT_WRITE,
511 libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_STACK,
512 -1,
513 0,
514 )
515 };
516 if base == libc::MAP_FAILED {
517 return Err(InstallError::last("mmap"));
518 }
519 if unsafe { libc::mprotect(base, page, libc::PROT_NONE) } != 0 {
521 let error = InstallError::last("mprotect");
522 unsafe { libc::munmap(base, length) };
524 return Err(error);
525 }
526 let stack = libc::stack_t {
527 ss_sp: base.cast::<u8>().wrapping_add(page).cast(),
528 ss_flags: 0,
529 ss_size: size,
530 };
531 let mut earlier: libc::stack_t = unsafe { std::mem::zeroed() };
533 if unsafe { libc::sigaltstack(&raw const stack, &raw mut earlier) } != 0 {
536 let error = InstallError::last("sigaltstack");
537 unsafe { libc::munmap(base, length) };
539 return Err(error);
540 }
541 Ok(Self {
542 base,
543 length,
544 earlier,
545 })
546 }
547
548 fn restore(self) {
552 if unsafe { libc::sigaltstack(&raw const self.earlier, ptr::null_mut()) } == 0 {
554 unsafe { libc::munmap(self.base, self.length) };
557 }
558 }
559}
560
561pub(crate) struct ThreadGuard {
563 stack: Option<AltStack>,
565 region: bool,
567}
568
569impl Drop for ThreadGuard {
570 fn drop(&mut self) {
571 if self.region {
572 let _cleared: Result<(), std::thread::AccessError> =
573 REGION.try_with(|region| region.set(Region::NONE));
574 }
575 if let Some(stack) = self.stack.take() {
576 stack.restore();
577 }
578 }
579}
580
581pub(crate) fn guard_thread() -> ThreadGuard {
586 if !INSTALLED.load(Ordering::Acquire) {
587 return ThreadGuard {
588 stack: None,
589 region: false,
590 };
591 }
592 let region =
593 stack_region().is_ok_and(|region| REGION.try_with(|cell| cell.set(region)).is_ok());
594 ThreadGuard {
595 stack: AltStack::set_up().ok(),
596 region,
597 }
598}
599
600fn earlier(signal: libc::c_int) -> Option<&'static libc::sigaction> {
602 match signal {
603 libc::SIGSEGV => EARLIER_SEGV.get(),
604 libc::SIGBUS => EARLIER_BUS.get(),
605 _ => None,
606 }
607}
608
609fn zeroed_action() -> libc::sigaction {
611 unsafe { std::mem::zeroed() }
614}
615
616fn take_over(
618 signal: libc::c_int,
619 kept: &OnceLock<libc::sigaction>,
620) -> Result<(), InstallError> {
621 let mut current = zeroed_action();
622 if unsafe { libc::sigaction(signal, ptr::null(), &raw mut current) } != 0 {
624 return Err(InstallError::last("sigaction"));
625 }
626 let _kept: &libc::sigaction = kept.get_or_init(|| current);
627 let mut action = zeroed_action();
628 let handler: extern "C" fn(libc::c_int, *mut libc::siginfo_t, *mut c_void) = handle;
629 action.sa_sigaction = handler as libc::sighandler_t;
630 action.sa_flags = libc::SA_SIGINFO | libc::SA_ONSTACK;
631 unsafe { libc::sigemptyset(&raw mut action.sa_mask) };
633 if unsafe { libc::sigaction(signal, &raw const action, ptr::null_mut()) } != 0 {
636 return Err(InstallError::last("sigaction"));
637 }
638 Ok(())
639}
640
641fn give_back(signal: libc::c_int) {
644 let fallback = zeroed_action();
645 let action = earlier(signal).unwrap_or(&fallback);
646 unsafe { libc::sigaction(signal, ptr::from_ref(action), ptr::null_mut()) };
648}
649
650pub fn install(status: u8) -> Result<(), InstallError> {
662 if INSTALLED.load(Ordering::Acquire) {
663 return Ok(());
664 }
665 let region = stack_region()?;
666 let stack = AltStack::set_up()?;
667 if REGION.try_with(|cell| cell.set(region)).is_err() {
668 stack.restore();
669 return Err(InstallError::invalid(
670 "thread_local",
671 "the thread is ending",
672 ));
673 }
674 STATUS.store(i32::from(status), Ordering::Relaxed);
675 INSTALLER.store(unsafe { libc::getpid() }, Ordering::Relaxed);
677 let undo = |stack: AltStack| {
678 let _cleared: Result<(), std::thread::AccessError> =
679 REGION.try_with(|cell| cell.set(Region::NONE));
680 stack.restore();
681 };
682 if let Err(error) = take_over(libc::SIGSEGV, &EARLIER_SEGV) {
683 undo(stack);
684 return Err(error);
685 }
686 if let Err(error) = take_over(libc::SIGBUS, &EARLIER_BUS) {
687 give_back(libc::SIGSEGV);
688 undo(stack);
689 return Err(error);
690 }
691 INSTALLED.store(true, Ordering::Release);
692 Ok(())
693}
694
695extern "C" fn handle(
698 signal: libc::c_int,
699 info: *mut libc::siginfo_t,
700 _context: *mut c_void,
701) {
702 if overflowed(info) {
703 stop();
704 }
705 let errno = unsafe { *libc::__errno_location() };
708 give_back(signal);
709 unsafe { *libc::__errno_location() = errno };
711}
712
713fn overflowed(info: *const libc::siginfo_t) -> bool {
716 if info.is_null() {
717 return false;
718 }
719 let (code, address) = unsafe { ((*info).si_code, (*info).si_addr().addr()) };
722 if code <= 0 {
723 return false;
724 }
725 if unsafe { libc::getpid() } != INSTALLER.load(Ordering::Relaxed) {
727 return false;
728 }
729 REGION
730 .try_with(Cell::get)
731 .is_ok_and(|region| region.contains(address))
732}
733
734#[inline(never)]
737fn stop() -> ! {
738 let mut task = [0_u8; TASK_CAPACITY];
739 let noted = TASK.read(&mut task, || {});
740 let mut message = [0_u8; MESSAGE_CAPACITY];
741 let length = compose(noted.and_then(|length| task.get(..length)), &mut message);
742 write_error(message.get(..length).unwrap_or_default());
743 let mut path = [0_u8; PATH_BUFFER];
744 let locked = path
745 .get_mut(..LOCK_CAPACITY)
746 .and_then(|start| LOCK.read(start, || {}));
747 if locked.is_some() {
748 unsafe { libc::unlink(path.as_ptr().cast()) };
751 }
752 unsafe { libc::_exit(STATUS.load(Ordering::Relaxed)) }
754}
755
756fn write_error(bytes: &[u8]) {
759 let mut rest = bytes;
760 for _attempt in 0..WRITE_ATTEMPTS {
761 if rest.is_empty() {
762 return;
763 }
764 let written = unsafe { libc::write(libc::STDERR_FILENO, rest.as_ptr().cast(), rest.len()) };
766 let Ok(count) = usize::try_from(written) else {
767 if unsafe { *libc::__errno_location() } == libc::EINTR {
769 continue;
770 }
771 return;
772 };
773 if count == 0 {
774 return;
775 }
776 rest = rest.get(count..).unwrap_or_default();
777 }
778}
779
780#[cfg(debug_assertions)]
785pub fn fault_outside_guards() {
786 let Ok(page) = page_size() else {
787 return;
788 };
789 let mapped = unsafe {
792 libc::mmap(
793 ptr::null_mut(),
794 page,
795 libc::PROT_NONE,
796 libc::MAP_PRIVATE | libc::MAP_ANONYMOUS,
797 -1,
798 0,
799 )
800 };
801 if mapped == libc::MAP_FAILED {
802 return;
803 }
804 let _byte: u8 = unsafe { ptr::read_volatile(mapped.cast::<u8>()) };
807 unsafe { libc::munmap(mapped, page) };
809}
810
811#[cfg(test)]
813#[allow(
814 clippy::arithmetic_side_effects,
815 clippy::disallowed_macros,
816 clippy::disallowed_methods,
817 reason = "test code: the tests assert, compute expected sizes and repeat text"
818)]
819mod tests {
820 use std::path::PathBuf;
821
822 use super::{
823 LOCK, LOCK_CAPACITY, MESSAGE_CAPACITY, NO_TASK, PATH_BUFFER, Region, Slot, TASK,
824 TASK_CAPACITY, TASK_PREFIX, TASK_SUFFIX, alt_stack_size, compose, cut, guard_region,
825 note_lock, note_task,
826 };
827
828 const PAGE: usize = 4_096;
830
831 #[test]
835 fn the_guard_region_surrounds_the_lowest_address() {
836 let region = guard_region(0x10_0000, PAGE, PAGE).unwrap();
837 assert_eq!(region, Region {
838 start: 0x10_0000 - PAGE,
839 end: 0x10_0000 + PAGE,
840 });
841 assert!(region.contains(0x10_0000 - PAGE));
842 assert!(region.contains(0x10_0000));
843 assert!(region.contains(0x10_0000 + PAGE - 1));
844 assert!(!region.contains(0x10_0000 - PAGE - 1));
845 assert!(!region.contains(0x10_0000 + PAGE));
846 }
847
848 #[test]
851 fn the_guard_is_at_least_a_page() {
852 assert_eq!(
853 guard_region(0x10_0000, 0, PAGE),
854 guard_region(0x10_0000, PAGE, PAGE)
855 );
856 assert_eq!(guard_region(0x10_0000, 4 * PAGE, PAGE).unwrap(), Region {
857 start: 0x10_0000 - 4 * PAGE,
858 end: 0x10_0000 + 4 * PAGE,
859 });
860 assert_eq!(guard_region(0x10_0000, 0, 0), None);
861 }
862
863 #[test]
866 fn the_guard_region_never_overflows() {
867 assert_eq!(guard_region(PAGE - 1, PAGE, PAGE), None);
868 assert_eq!(guard_region(0, PAGE, PAGE), None);
869 let low = guard_region(PAGE, PAGE, PAGE).unwrap();
870 assert!(low.contains(0));
871 assert!(!low.contains(2 * PAGE));
872 assert_eq!(guard_region(usize::MAX - PAGE + 1, PAGE, PAGE), None);
873 assert_eq!(guard_region(usize::MAX, 0, PAGE), None);
874 assert_eq!(guard_region(0x10_0000, usize::MAX, PAGE), None);
875 let high = guard_region(usize::MAX - PAGE, PAGE, PAGE).unwrap();
876 assert!(high.contains(usize::MAX - 1));
877 assert!(!high.contains(usize::MAX));
878 assert!(!Region::NONE.contains(0));
879 assert!(!Region::NONE.contains(usize::MAX));
880 }
881
882 #[test]
885 fn the_alternate_stack_is_whole_pages() {
886 assert_eq!(alt_stack_size(PAGE, 0), Some(65_536));
887 assert_eq!(alt_stack_size(PAGE, 3_000), Some(65_536 + 4_096));
888 assert_eq!(alt_stack_size(PAGE, PAGE), Some(65_536 + 4_096));
889 assert_eq!(alt_stack_size(0, 0), None);
890 assert_eq!(alt_stack_size(PAGE, usize::MAX), None);
891 assert_eq!(alt_stack_size(PAGE, usize::MAX - 65_536), None);
892 }
893
894 #[test]
898 fn notes_are_read_back_until_dropped() {
899 let mut out = [0_u8; TASK_CAPACITY];
900 let task = note_task("kizz.md:12 (Deep)");
901 assert_eq!(TASK.read(&mut out, || {}), Some(17));
902 assert_eq!(out.get(..17).unwrap(), b"kizz.md:12 (Deep)");
903 drop(task);
904 assert_eq!(TASK.read(&mut out, || {}), None);
905
906 let long = format!("{}é", "a".repeat(TASK_CAPACITY - 1));
907 let task = note_task(&long);
908 assert_eq!(TASK.read(&mut out, || {}), Some(TASK_CAPACITY - 1));
909 assert!(
910 out.get(..TASK_CAPACITY - 1)
911 .unwrap()
912 .iter()
913 .all(|&byte| byte == b'a')
914 );
915 drop(task);
916
917 let mut path = [0_u8; PATH_BUFFER];
918 let lock = note_lock(&PathBuf::from("/tmp/cache/kizz.lock"));
919 let start = path.get_mut(..LOCK_CAPACITY).unwrap();
920 assert_eq!(LOCK.read(start, || {}), Some(20));
921 assert_eq!(path.get(..21).unwrap(), b"/tmp/cache/kizz.lock\0");
922 drop(lock);
923 assert_eq!(LOCK.read(&mut path, || {}), None);
924
925 let longest = PathBuf::from(format!("/{}", "p".repeat(LOCK_CAPACITY - 1)));
926 let lock = note_lock(&longest);
927 assert_eq!(LOCK.read(&mut path, || {}), Some(LOCK_CAPACITY));
928 drop(lock);
929 let too_long = PathBuf::from(format!("/{}", "p".repeat(LOCK_CAPACITY)));
930 let lock = note_lock(&too_long);
931 assert_eq!(LOCK.read(&mut path, || {}), None);
932 drop(lock);
933 assert_eq!(PATH_BUFFER, LOCK_CAPACITY + 1);
934 }
935
936 #[test]
938 fn long_texts_are_cut_at_a_character_boundary() {
939 assert_eq!(cut("kizz.md:1", 100), "kizz.md:1");
940 assert_eq!(cut("abc", 2), "ab");
941 assert_eq!(cut("aé", 2), "a");
942 assert_eq!(cut("aé", 3), "aé");
943 assert_eq!(cut("é", 1), "");
944 assert_eq!(cut("", 0), "");
945 }
946
947 #[test]
950 fn an_overlapped_copy_is_no_note() {
951 let slot: Slot<16> = Slot::new();
952 let mut out = [0_u8; 16];
953 let _first = slot.write(b"first");
954 assert_eq!(
955 slot.read(&mut out, || {
956 slot.write(b"second");
957 }),
958 None
959 );
960 assert_eq!(slot.read(&mut out, || {}), Some(6));
961 assert_eq!(out.get(..6).unwrap(), b"second");
962 }
963
964 #[test]
967 fn only_the_current_note_is_removed() {
968 let slot: Slot<16> = Slot::new();
969 let mut out = [0_u8; 16];
970 let older = slot.write(b"older");
971 let newer = slot.write(b"newer");
972 slot.clear(older);
973 assert_eq!(slot.read(&mut out, || {}), Some(5));
974 let mut short = [0_u8; 3];
975 assert_eq!(slot.read(&mut short, || {}), None);
976 slot.clear(newer);
977 assert_eq!(slot.read(&mut out, || {}), None);
978 let empty = slot.write(b"");
979 assert_eq!(slot.read(&mut out, || {}), None);
980 slot.clear(empty);
981 }
982
983 #[test]
985 fn the_messages_are_exact() {
986 let mut out = [0_u8; MESSAGE_CAPACITY];
987 let length = compose(Some(b"kizz.md:12 (Deep)".as_slice()), &mut out);
988 assert_eq!(
989 out.get(..length).unwrap(),
990 b"error: the program of task kizz.md:12 (Deep) overflowed the stack, so kizz stopped; \
991 its values are probably nested too deeply\n"
992 );
993 let length = compose(None, &mut out);
994 assert_eq!(
995 out.get(..length).unwrap(),
996 b"error: kizz overflowed its stack and stopped\n"
997 );
998 assert_eq!(compose(Some(b"".as_slice()), &mut out), NO_TASK.len());
999 let longest = [b'x'; TASK_CAPACITY];
1000 let length = compose(Some(longest.as_slice()), &mut out);
1001 assert_eq!(
1002 length,
1003 TASK_PREFIX.len() + TASK_CAPACITY + TASK_SUFFIX.len()
1004 );
1005 assert!(length <= MESSAGE_CAPACITY);
1006 assert!(out.get(..length).unwrap().ends_with(TASK_SUFFIX));
1007 }
1008}