daemonic_error 0.2.0

Errors that compose, predict, and leave receipts - Compose: algebraic combination (in active development) - Predict: Glass/Severity - Receipts: audit trail, position, checksum - Reflection: Runtime Reflection through TopologySegment (in active development)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
use alloc::boxed::Box;
use alloc::collections::TryReserveError;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::ffi::CStr;
use core::ops::Deref;
use crate::daemonic::{daemonic_hasher, TopologySegment, TopologyAnchor, AnchorDomainSet};
use crate::daemonic::daemonic_hasher::{DaemonicHashable, DaemonicHasher};
use crate::daemonic::daemonic_hasher::random::DefaultDaemonicHasher;
use crate::daemonic::frame::ReferenceFrame;
use crate::daemonic::glass::Glass;

/// An owned, mutable path (akin to [`String`]).
///
/// This type provides methods like [`push`] and [`set_extension`] that mutate
/// the path in place. It also implements [`Deref`] to [`Path`], meaning that
/// all methods on [`Path`] slices are available on `PathBuf` values as well.
///
/// [`push`]: PathBuf::push
/// [`set_extension`]: PathBuf::set_extension
///
/// More details about the overall approach can be found in
/// the [module documentation](self).
///
/// # Examples
///
/// You can use [`push`] to build up a `PathBuf` from
/// components:
///
/// ```
/// use DaemonicError::PathBuf;
///
/// let mut path = PathBuf::new();
///
/// path.push(r"C:\");
/// path.push("windows");
/// path.push("system32");
///
/// path.set_extension("dll");
/// ```
///
/// However, [`push`] is best used for dynamic situations. This is a better way
/// to do this when you know all of the components ahead of time:
///
/// ```
/// use DaemonicError::PathBuf;
///
/// let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
/// ```
///
/// We can still do better than this! Since these are all strings, we can use
/// `From::from`:
///
/// ```
/// use DaemonicError::PathBuf;
///
/// let path = PathBuf::from(r"C:\windows\system32.dll");
/// ```
///
/// Which method works best depends on what kind of situation you're in.
///
/// Note that `PathBuf` does not always sanitize arguments, for example
/// [`push`] allows paths built from strings which include separators:
///
/// ```
/// use DaemonicError::PathBuf;
///
/// let mut path = PathBuf::new();
///
/// path.push(r"C:\");
/// path.push("windows");
/// path.push(r"..\otherdir");
/// path.push("system32");
/// ```
///
/// The behavior of `PathBuf` may be changed to a panic on such inputs
/// in the future. [`Extend::extend`] should be used to add multi-part paths.
#[derive(Debug)]
pub struct DaemonicPathBuf {
	inner: DaemonicOsString,
}
#[inline]
pub fn is_sep_byte(b: u8) -> bool {
	b == b'/'
}

#[inline]
pub fn is_verbatim_sep(b: u8) -> bool {
	b == b'/'
}
/// Platform-specific extensions to [`DaemonicOsString`].
///
/// This trait is sealed: it cannot be implemented outside the standard library.
/// This is so that future additional methods are not breaking changes.
pub trait DaemonicOsStringExt {
	/// Creates an [`OsString`] from a byte vector.
	///
	/// See the module documentation for an example.
	fn from_vec(vec: Vec<u8>) -> Self;
	
	/// Yields the underlying byte vector of this [`OsString`].
	///
	/// See the module documentation for an example.
	fn into_vec(self) -> Vec<u8>;
}

impl DaemonicOsStringExt for DaemonicOsString {
	#[inline]
	fn from_vec(vec: Vec<u8>) -> DaemonicOsString {
		FromInner::from_inner(DaemonicBuf { inner: vec })
	}
	#[inline]
	fn into_vec(self) -> Vec<u8> {
		self.into_inner().inner
	}
}
#[inline]
pub fn parse_prefix(_: &DaemonicOsStr) -> Option<Prefix<'_>> {
	None
}
use crate::daemonic::glass::daemonic_system_call::c_types::*;
static GETCWD_TOPOLOGY_SEGMENT: TopologySegment = TopologySegment::new("Daemonic::Glass::Floating::fn getcwd() -> Observation<DaemonicPathBuf>");
/// This function is also fucking bullshit
fn getcwd() -> Observation<DaemonicPathBuf>
	where
		DaemonicOsString: AsRef<DaemonicPath> + DaemonicSystemCall,
{
	use crate::daemonic::glass::daemonic_system_call::DaemonicSystemCall;
	
	let mut buf = Vec::with_capacity(512);
	loop {
		unsafe {
			let ptr = buf.as_mut_ptr() as *mut c_char;
			let obs = <DaemonicOsString as DaemonicSystemCall>::glass_call79_getcwd(ptr, buf.capacity() as c_ulong);
			match obs.severity {
				Severity::Cracked => {
					// Cracked could be ERANGE (34) or other retryable errors.
					// For getcwd specifically: Cracked = buffer too small.
					// Expand and retry.
					let cap = buf.capacity();
					buf.set_len(cap);
					buf.reserve(1);
					continue;
				}
				Severity::Stable => {
					let len = CStr::from_ptr(buf.as_ptr() as *const c_char).to_bytes().len();
					buf.set_len(len);
					buf.shrink_to_fit();
					// buf variable at this point in the process is a `Vec<c_char>`
					let mut fuck_buf = DaemonicPathBuf::new();
					// push the buffer from the vector into a new OsString variant
					fuck_buf.push(DaemonicOsString::from_vec(buf));
					// Now observation sees it correctly, original code told me to fuck off despite same semantics.
					return Observation {
						position: &GETCWD_TOPOLOGY_SEGMENT,
						severity: crate::Severity::Stable,
						tier: crate::ObservationTier::Composed,
						annotation: crate::Annotation::None,
						temporal: crate::Temporal::Current,
						payload: Some(DaemonicPathBuf::from(fuck_buf)),
					};
				}
				Severity::Warp => {
					// errno 12 (ENOMEM): out of memory.
					// errno 14 (EFAULT): bad pointer (our bug).
					// errno 22 (EINVAL): null buffer or zero size (our bug).
					//
					// EFAULT and EINVAL here mean WE screwed up,
					// not the caller. The buffer construction is wrong.
					// This should be unreachable if our code is correct.
					return Observation::shattered(&GETCWD_TOPOLOGY_SEGMENT)
						.with_note("getcwd: internal error — buffer construction failed. \
                              EFAULT/EINVAL at this layer indicates a bug in DaemonicError, \
                              not in your code. Please file an issue: \
                              https://gitlab.com/Mephistophel3s/daemonic-error");
				}
				
				Severity::Fracture => {
					// errno 36 (ENAMETOOLONG): path exceeds system limit.
					// errno 2 (ENOENT): working directory deleted.
					//
					// ENOENT: the directory you're standing in no longer exists.
					// This happens when another process deletes the cwd.
					// Real failure. Not retryable. Not our bug.
					return Observation::shattered(&GETCWD_TOPOLOGY_SEGMENT)
						.with_note("getcwd: working directory is inaccessible. \
                              Either the directory was deleted while the process was running \
                              (ENOENT) or the path exceeds system limits (ENAMETOOLONG).");
				}
				
				_ => {
					// Unexpected severity from the syscall.
					// Shouldn't happen with the known errno set.
					return Observation::shattered(&GETCWD_TOPOLOGY_SEGMENT)
						.with_note("getcwd: unexpected error state from syscall 79.");
				}
			}
		}
	}
}
pub const MAIN_SEP_STR: &str = "/";
pub const MAIN_SEP: char = '/';
impl<P: AsRef<DaemonicPath>> Extend<P> for DaemonicPathBuf
	where
		DaemonicPath: AsRef<DaemonicPath>,
{
	fn extend<I: IntoIterator<Item=P>>(&mut self, iter: I) {
		iter.into_iter().for_each(move |p| self.push(p.as_ref()));
	}
	
	#[inline]
	fn extend_one(&mut self, p: P) {
		self.push(p.as_ref());
	}
}
/// Make a POSIX path absolute without changing its semantics.
/// Glass Observed
/// Meph note: This function is fucking bullshit.
/// Note from Meph and Ada: This blob was cloned from std and the assumptions die under observation.
pub(crate) fn absolute(path: &DaemonicPath) -> Observation<DaemonicPathBuf>
	where
		str: AsRef<daemonic_path::DaemonicPath>,
		DaemonicOsString: AsRef<daemonic_path::DaemonicPath>,
		DaemonicOsStr: AsRef<daemonic_path::DaemonicPath> + Clone,
{
	/// This is mostly a wrapper around collecting `Path::components`, with
	/// exceptions made where this conflicts with the POSIX specification.
	/// See 4.13 Pathname Resolution, IEEE Std 1003.1-2017
	/// https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
	/// Get the components, skipping the redundant leading "." component if it exists.
	/// This assumption doesnt hold up under Niche unix conditions, notably
	/// files and folders with a . preceeding the name are hidden by convention
	/// and are treated a little differently from normal files which breaks convention somewhat
	/// from posix standard upstream. This method does not account for this.
	let mut components = path.strip_prefix(".").unwrap_or(path).components();
	let path_os = path.as_os_str().as_encoded_bytes();
	
	let mut normalized = if path.is_absolute() {
		/// "If a pathname begins with two successive <slash> characters, the
		/// first component following the leading <slash> characters may be
		/// interpreted in an implementation-defined manner, although more than
		/// two leading <slash> characters shall be treated as a single <slash>
		/// character."
		/// Note from Meph:
		/// This is also missing assumptions with host pathing in paths that begin with a double //
		/// in this context, information is type erased and non-recoverable past this point.
		/// A flaw in the method.
		if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
			components.next();
			let slash = DaemonicOsString::from("//").as_ref().clone();
			let mut slash_ext = DaemonicPathBuf::new();
			slash_ext.push(slash);
			DaemonicPathBuf::from(slash_ext)
		} else {
			let slash = DaemonicOsString::from("/").as_ref().clone();
			let mut slash_ext = DaemonicPathBuf::new();
			slash_ext.push(slash);
			DaemonicPathBuf::from(slash_ext)
		}
	} else {
		getcwd()?
	};
	normalized.extend(components);
	
	/// "Interfaces using pathname resolution may specify additional constraints
	/// when a pathname that does not name an existing directory contains at
	/// least one non- <slash> character and contains one or more trailing
	/// <slash> characters".
	/// A trailing <slash> is also meaningful if "a symbolic link is
	/// encountered during pathname resolution".
	/// Note from Meph: Not necessarily, in some contexts yes, but in alot of cases its purely decorative
	/// or completely useless otherwise. A trailing slash is not structural and cannot be treated as such
	/// in all contexts.
	/// Some network sensitive parsers, such as older SSHD parser enginers might not resolve this
	/// as intended, and trying to figure that out at the call sight would likely be fucking impossible
	if path_os.ends_with(b"/") {
		normalized.push("");
	}
	Observation {
		position: &ABSOLUTE_TOPOLOGY_SEGMENT,
		severity: crate::Severity::Stable,
		tier: crate::ObservationTier::GlyphicExecutable,
		annotation: crate::Annotation::None,
		temporal: crate::Temporal::Current,
		payload: Some(normalized),
	}
}
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
pub enum Prefix<'a> {
	/// Verbatim prefix, e.g., `\\?\cat_pics`.
	///
	/// Verbatim prefixes consist of `\\?\` immediately followed by the given
	/// component.
	
	Verbatim(&'a DaemonicOsStr),
	
	/// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_,
	/// e.g., `\\?\UNC\server\share`.
	///
	/// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the
	/// server's hostname and a share name.
	
	VerbatimUNC(
		&'a DaemonicOsStr,
		&'a DaemonicOsStr,
	),
	
	/// Verbatim disk prefix, e.g., `\\?\C:`.
	///
	/// Verbatim disk prefixes consist of `\\?\` immediately followed by the
	/// drive letter and `:`.
	
	VerbatimDisk(u8),
	
	/// Device namespace prefix, e.g., `\\.\COM42`.
	///
	/// Device namespace prefixes consist of `\\.\` (possibly using `/`
	/// instead of `\`), immediately followed by the device name.
	
	DeviceNS(&'a DaemonicOsStr),
	
	/// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g.
	/// `\\server\share`.
	///
	/// UNC prefixes consist of the server's hostname and a share name.
	
	UNC(
		&'a DaemonicOsStr,
		&'a DaemonicOsStr,
	),
	
	/// Prefix `C:` for the given disk drive.
	
	Disk(u8),
}
impl<'prefix> DaemonicHashable for Prefix<'prefix> {
	fn declare_hashable<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(&self, state: &mut GLASS) {
		match self {
			Prefix::Verbatim(DaemonicOsStr) => {
				0u8.declare_hashable(state);
				DaemonicOsStr.declare_hashable(state);
			}
			Prefix::VerbatimUNC(DaemonicOsStr1, DaemonicOsStr2) => {
				1u8.declare_hashable(state);
				DaemonicOsStr1.declare_hashable(state);
				DaemonicOsStr2.declare_hashable(state);
			}
			Prefix::VerbatimDisk(u8) => {
				2u8.declare_hashable(state);
				u8.declare_hashable(state);
			}
			Prefix::DeviceNS(DaemonicOsStr) => {
				3u8.declare_hashable(state);
				DaemonicOsStr.declare_hashable(state);
			}
			Prefix::UNC(DaemonicOsStr1, DaemonicOsStr2) => {
				4u8.declare_hashable(state);
				DaemonicOsStr1.declare_hashable(state);
				DaemonicOsStr2.declare_hashable(state);
			}
			Prefix::Disk(u8) => {
				5u8.declare_hashable(state);
				u8.declare_hashable(state);
			}
		}
	}
}
static ABSOLUTE_TOPOLOGY_SEGMENT: TopologySegment = TopologySegment::new("Daemonic::Glass::Floating::absolute(path: &DaemonicPath) -> Observation<DaemonicPathBuf>");
pub(crate) fn is_absolute(path: &DaemonicPath) -> bool {
	if cfg!(any(unix, target_os = "hermit", target_os = "wasi")) {
		path.has_root()
	} else {
		path.has_root() && path.prefix().is_some()
	}
}
fn validate_extension(extension: &DaemonicOsStr) {
	for &b in extension.as_encoded_bytes() {
		if is_sep_byte(b) {
			panic!("extension cannot contain path separators: {extension:?}");
		}
	}
}
impl Deref for DaemonicPathBuf {
	type Target = DaemonicPath;
	
	#[inline]
	fn deref(&self) -> &DaemonicPath {
		self.as_path()
	}
}
impl DaemonicPathBuf {
	/// Allocates an empty `PathBuf`.
	///
	/// # Examples
	///
	/// ```
	/// use std::path::PathBuf;
	///
	/// let path = PathBuf::new();
	/// ```
	#[must_use]
	#[inline]
	pub fn new() -> DaemonicPathBuf {
		DaemonicPathBuf { inner: DaemonicOsString::new() }
	}
	
	/// Creates a new `PathBuf` with a given capacity used to create the
	/// internal [`DaemonicOsString`]. See [`with_capacity`] defined on [`DaemonicOsString`].
	///
	/// # Examples
	///
	/// ```
	/// use std::path::PathBuf;
	///
	/// let mut path = PathBuf::with_capacity(10);
	/// let capacity = path.capacity();
	///
	/// // This push is done without reallocating
	/// path.push(r"C:\");
	///
	/// assert_eq!(capacity, path.capacity());
	/// ```
	///
	/// [`with_capacity`]: DaemonicOsString::with_capacity
	#[must_use]
	#[inline]
	pub fn with_capacity(capacity: usize) -> DaemonicPathBuf {
		DaemonicPathBuf { inner: DaemonicOsString::with_capacity(capacity) }
	}
	
	/// Coerces to a [`Path`] slice.
	///
	/// # Examples
	///
	/// ```
	/// use std::path::{Path, PathBuf};
	///
	/// let p = PathBuf::from("/test");
	/// assert_eq!(Path::new("/test"), p.as_path());
	/// ```
	#[must_use]
	#[inline]
	pub fn as_path(&self) -> &DaemonicPath {
		DaemonicPath::new(self.inner.as_os_str())
	}
	
	/// Consumes and leaks the `PathBuf`, returning a mutable reference to the contents,
	/// `&'a mut Path`.
	///
	/// The caller has free choice over the returned lifetime, including 'static.
	/// Indeed, this function is ideally used for data that lives for the remainder of
	/// the program’s life, as dropping the returned reference will cause a memory leak.
	///
	/// It does not reallocate or shrink the `PathBuf`, so the leaked allocation may include
	/// unused capacity that is not part of the returned slice. If you want to discard excess
	/// capacity, call [`into_boxed_path`], and then [`Box::leak`] instead.
	/// However, keep in mind that trimming the capacity may result in a reallocation and copy.
	///
	/// [`into_boxed_path`]: Self::into_boxed_path
	#[inline]
	pub fn leak<'a>(self) -> &'a mut DaemonicPathBuf {
		Box::leak(Box::new(self))
	}
	// The following (private!) function allows construction of a path from a u8
	// slice, which is only safe when it is known to follow the OsStr encoding.
	unsafe fn from_u8_slice(s: &[u8]) -> &DaemonicPath {
		unsafe { DaemonicPath::new(DaemonicOsStr::from_encoded_bytes_unchecked(s)) }
	}
	// The following (private!) function reveals the byte encoding used for OsStr.
	pub(crate) fn as_u8_slice(&self) -> &[u8] {
		self.inner.as_encoded_bytes()
	}
	pub fn components(&self) -> Components<'_> {
		let prefix = parse_prefix(self.inner.as_os_str());
		Components {
			path: self.as_u8_slice(),
			prefix,
			has_physical_root: has_physical_root(self.as_u8_slice(), prefix),
			front: State::Prefix,
			back: State::Body,
		}
	}
	/// Extends `self` with `path`.
	///
	/// If `path` is absolute, it replaces the current path.
	///
	/// On Windows:
	///
	/// * if `path` has a root but no prefix (e.g., `\windows`), it
	///   replaces everything except for the prefix (if any) of `self`.
	/// * if `path` has a prefix but no root, it replaces `self`.
	/// * if `self` has a verbatim prefix (e.g. `\\?\C:\windows`)
	///   and `path` is not empty, the new path is normalized: all references
	///   to `.` and `..` are removed.
	///
	/// Consider using [`Path::join`] if you need a new `PathBuf` instead of
	/// using this function on a cloned `PathBuf`.
	///
	/// # Examples
	///
	/// Pushing a relative path extends the existing path:
	///
	/// ```
	/// use std::path::PathBuf;
	///
	/// let mut path = PathBuf::from("/tmp");
	/// path.push("file.bk");
	/// assert_eq!(path, PathBuf::from("/tmp/file.bk"));
	/// ```
	///
	/// Pushing an absolute path replaces the existing path:
	///
	/// ```
	/// use std::path::PathBuf;
	///
	/// let mut path = PathBuf::from("/tmp");
	/// path.push("/etc");
	/// assert_eq!(path, PathBuf::from("/etc"));
	/// ```
	pub fn push<P: AsRef<DaemonicPath>>(&mut self, path: P) {
		self._push(path.as_ref())
	}
	
	fn _push(&mut self, path: &DaemonicPath) {
		// in general, a separator is needed if the rightmost byte is not a separator
		let buf = self.inner.as_encoded_bytes();
		let mut need_sep = buf.last().map(|c| !is_sep_byte(*c)).unwrap_or(false);
		
		// in the special case of `C:` on Windows, do *not* add a separator
		let comps = self.components();
		
		if comps.prefix_len() > 0
			&& comps.prefix_len() == comps.path.len()
			&& comps.prefix.unwrap().is_drive()
		{
			need_sep = false
		}
		
		// absolute `path` replaces `self`
		if path.is_absolute() || path.prefix().is_some() {
			self.inner.truncate(0);
		
		// verbatim paths need . and .. removed
		} else if comps.prefix_verbatim() && !path.inner.is_empty() {
			let mut buf: Vec<_> = comps.collect();
			for c in path.components() {
				match c {
					Component::RootDir => {
						buf.truncate(1);
						buf.push(c);
					}
					Component::CurDir => (),
					Component::ParentDir => {
						if let Some(Component::Normal(_)) = buf.last() {
							buf.pop();
						}
					}
					_ => buf.push(c),
				}
			}
			
			let mut res = DaemonicOsString::new();
			let mut need_sep = false;
			
			for c in buf {
				if need_sep && c != Component::RootDir {
					res.push(MAIN_SEP_STR);
				}
				res.push(c.as_os_str());
				
				need_sep = match c {
					Component::RootDir => false,
					Component::Prefix(prefix) => {
						!prefix.parsed.is_drive() && prefix.parsed.len() > 0
					}
					_ => true,
				}
			}
			
			self.inner = res;
			return;
		
		// `path` has a root but no prefix, e.g., `\windows` (Windows only)
		} else if path.has_root() {
			let prefix_len = self.components().prefix_remaining();
			self.inner.truncate(prefix_len);
		
		// `path` is a pure relative path
		} else if need_sep {
			self.inner.push(MAIN_SEP_STR);
		}
		
		self.inner.push(path);
	}
	
	/// Truncates `self` to [`self.parent`].
	///
	/// Returns `false` and does nothing if [`self.parent`] is [`None`].
	/// Otherwise, returns `true`.
	///
	/// [`self.parent`]: Path::parent
	///
	/// # Examples
	///
	/// ```
	/// use std::path::{Path, PathBuf};
	///
	/// let mut p = PathBuf::from("/spirited/away.rs");
	///
	/// p.pop();
	/// assert_eq!(Path::new("/spirited"), p);
	/// p.pop();
	/// assert_eq!(Path::new("/"), p);
	/// ```
	pub fn pop(&mut self) -> bool {
		match self.parent().map(|p| p.as_u8_slice().len()) {
			Some(len) => {
				self.inner.truncate(len);
				true
			}
			None => false,
		}
	}
	/// Returns the `Path` without its final component, if there is one.
	///
	/// This means it returns `Some("")` for relative paths with one component.
	///
	/// Returns [`None`] if the path terminates in a root or prefix, or if it's
	/// the empty string.
	///
	/// # Examples
	///
	/// ```
	/// use std::path::Path;
	///
	/// let path = Path::new("/foo/bar");
	/// let parent = path.parent().unwrap();
	/// assert_eq!(parent, Path::new("/foo"));
	///
	/// let grand_parent = parent.parent().unwrap();
	/// assert_eq!(grand_parent, Path::new("/"));
	/// assert_eq!(grand_parent.parent(), None);
	///
	/// let relative_path = Path::new("foo/bar");
	/// let parent = relative_path.parent();
	/// assert_eq!(parent, Some(Path::new("foo")));
	/// let grand_parent = parent.and_then(Path::parent);
	/// assert_eq!(grand_parent, Some(Path::new("")));
	/// let great_grand_parent = grand_parent.and_then(Path::parent);
	/// assert_eq!(great_grand_parent, None);
	/// ```
	#[doc(alias = "dirname")]
	#[must_use]
	pub fn parent(&self) -> Option<&DaemonicPath> {
		let mut comps = self.components();
		let comp = comps.next_back();
		comp.and_then(|p| match p {
			Component::Normal(_) | Component::CurDir | Component::ParentDir => {
				Some(comps.as_path())
			}
			_ => None,
		})
	}
	/// Updates [`self.file_name`] to `file_name`.
	///
	/// If [`self.file_name`] was [`None`], this is equivalent to pushing
	/// `file_name`.
	///
	/// Otherwise it is equivalent to calling [`pop`] and then pushing
	/// `file_name`. The new path will be a sibling of the original path.
	/// (That is, it will have the same parent.)
	///
	/// The argument is not sanitized, so can include separators. This
	/// behavior may be changed to a panic in the future.
	///
	/// [`self.file_name`]: Path::file_name
	/// [`pop`]: PathBuf::pop
	pub fn set_file_name<S: AsRef<DaemonicOsStr>>(&mut self, file_name: S)
		where
			DaemonicOsStr: AsRef<daemonic_path::DaemonicPath>,
	{
		self._set_file_name(file_name.as_ref())
	}
	
	fn _set_file_name(&mut self, file_name: &DaemonicOsStr)
		where
			DaemonicOsStr: AsRef<DaemonicPath>,
	{
		/// Self at this stage is a &mut DaemonicPathBuf
		if self.file_name().is_some() { // todo: filename not in scope, transparent wrapper passthrough working too well
			let popped = self.pop();
			debug_assert!(popped);
		}
		self.push(file_name);
	}
	
	/// Updates [`self.extension`] to `Some(extension)` or to `None` if
	/// `extension` is empty.
	///
	/// Returns `false` and does nothing if [`self.file_name`] is [`None`],
	/// returns `true` and updates the extension otherwise.
	///
	/// If [`self.extension`] is [`None`], the extension is added; otherwise
	/// it is replaced.
	///
	/// If `extension` is the empty string, [`self.extension`] will be [`None`]
	/// afterwards, not `Some("")`.
	///
	/// # Panics
	///
	/// Panics if the passed extension contains a path separator (see
	/// [`is_separator`]).
	///
	/// # Caveats
	///
	/// The new `extension` may contain dots and will be used in its entirety,
	/// but only the part after the final dot will be reflected in
	/// [`self.extension`].
	///
	/// If the file stem contains internal dots and `extension` is empty, part
	/// of the old file stem will be considered the new [`self.extension`].
	///
	/// See the examples below.
	///
	/// [`self.file_name`]: Path::file_name
	/// [`self.extension`]: Path::extension
	///
	/// # Examples
	///
	/// ```
	/// use std::path::{Path, PathBuf};
	///
	/// let mut p = PathBuf::from("/feel/the");
	///
	/// p.set_extension("force");
	/// assert_eq!(Path::new("/feel/the.force"), p.as_path());
	///
	/// p.set_extension("dark.side");
	/// assert_eq!(Path::new("/feel/the.dark.side"), p.as_path());
	///
	/// p.set_extension("cookie");
	/// assert_eq!(Path::new("/feel/the.dark.cookie"), p.as_path());
	///
	/// p.set_extension("");
	/// assert_eq!(Path::new("/feel/the.dark"), p.as_path());
	///
	/// p.set_extension("");
	/// assert_eq!(Path::new("/feel/the"), p.as_path());
	///
	/// p.set_extension("");
	/// assert_eq!(Path::new("/feel/the"), p.as_path());
	/// ```
	pub fn set_extension<S: AsRef<DaemonicOsStr>>(&mut self, extension: S) -> bool {
		self._set_extension(extension.as_ref())
	}
	
	fn _set_extension(&mut self, extension: &DaemonicOsStr) -> bool {
		validate_extension(extension);
		
		let file_stem = match self.file_stem() {
			None => return false,
			Some(f) => f.as_encoded_bytes(),
		};
		
		// truncate until right after the file stem
		let end_file_stem = file_stem[file_stem.len()..].as_ptr().addr();
		let start = self.inner.as_encoded_bytes().as_ptr().addr();
		self.inner.truncate(end_file_stem.wrapping_sub(start));
		
		// add the new extension, if any
		let new = extension.as_encoded_bytes();
		if !new.is_empty() {
			self.inner.reserve_exact(new.len() + 1);
			self.inner.push(".");
			// SAFETY: Since a UTF-8 string was just pushed, it is not possible
			// for the buffer to end with a surrogate half.
			unsafe { self.inner.extend_from_slice_unchecked(new) };
		}
		
		true
	}
	
	/// Append [`self.extension`] with `extension`.
	///
	/// Returns `false` and does nothing if [`self.file_name`] is [`None`],
	/// returns `true` and updates the extension otherwise.
	///
	/// # Panics
	///
	/// Panics if the passed extension contains a path separator (see
	/// [`is_separator`]).
	///
	/// # Caveats
	///
	/// The appended `extension` may contain dots and will be used in its entirety,
	/// but only the part after the final dot will be reflected in
	/// [`self.extension`].
	///
	/// See the examples below.
	///
	/// [`self.file_name`]: Path::file_name
	/// [`self.extension`]: Path::extension
	///
	/// # Examples
	///
	/// ```
	/// #![feature(path_add_extension)]
	///
	/// use std::path::{Path, PathBuf};
	///
	/// let mut p = PathBuf::from("/feel/the");
	///
	/// p.add_extension("formatted");
	/// assert_eq!(Path::new("/feel/the.formatted"), p.as_path());
	///
	/// p.add_extension("dark.side");
	/// assert_eq!(Path::new("/feel/the.formatted.dark.side"), p.as_path());
	///
	/// p.set_extension("cookie");
	/// assert_eq!(Path::new("/feel/the.formatted.dark.cookie"), p.as_path());
	///
	/// p.set_extension("");
	/// assert_eq!(Path::new("/feel/the.formatted.dark"), p.as_path());
	///
	/// p.add_extension("");
	/// assert_eq!(Path::new("/feel/the.formatted.dark"), p.as_path());
	/// ```
	pub fn add_extension<S: AsRef<DaemonicOsStr>>(&mut self, extension: S) -> bool {
		self._add_extension(extension.as_ref())
	}
	
	fn _add_extension(&mut self, extension: &DaemonicOsStr) -> bool {
		validate_extension(extension);
		
		let file_name = match self.file_name() {
			None => return false,
			Some(f) => f.as_encoded_bytes(),
		};
		
		let new = extension.as_encoded_bytes();
		if !new.is_empty() {
			// truncate until right after the file name
			// this is necessary for trimming the trailing slash
			let end_file_name = file_name[file_name.len()..].as_ptr().addr();
			let start = self.inner.as_encoded_bytes().as_ptr().addr();
			self.inner.truncate(end_file_name.wrapping_sub(start));
			
			// append the new extension
			self.inner.reserve_exact(new.len() + 1);
			self.inner.push(".");
			// SAFETY: Since a UTF-8 string was just pushed, it is not possible
			// for the buffer to end with a surrogate half.
			unsafe { self.inner.extend_from_slice_unchecked(new) };
		}
		
		true
	}
	
	/// Yields a mutable reference to the underlying [`DaemonicOsString`] instance.
	///
	/// # Examples
	///
	/// ```
	/// use std::path::{Path, PathBuf};
	///
	/// let mut path = PathBuf::from("/foo");
	///
	/// path.push("bar");
	/// assert_eq!(path, Path::new("/foo/bar"));
	///
	/// // DaemonicOsString's `push` does not add a separator.
	/// path.as_mut_os_string().push("baz");
	/// assert_eq!(path, Path::new("/foo/barbaz"));
	/// ```
	#[must_use]
	#[inline]
	pub fn as_mut_os_string(&mut self) -> &mut DaemonicOsString {
		&mut self.inner
	}
	
	/// Consumes the `PathBuf`, yielding its internal [`DaemonicOsString`] storage.
	///
	/// # Examples
	///
	/// ```
	/// use std::path::PathBuf;
	///
	/// let p = PathBuf::from("/the/head");
	/// let os_str = p.into_os_string();
	/// ```
	#[must_use = "`self` will be dropped if the result is not used"]
	#[inline]
	pub fn into_os_string(self) -> DaemonicOsString {
		self.inner
	}
	
	/// Converts this `PathBuf` into a [boxed](Box) [`Path`].
	#[must_use = "`self` will be dropped if the result is not used"]
	#[inline]
	pub fn into_boxed_path(self) -> Box<DaemonicPath> {
		let rw = Box::into_raw(self.inner.into_boxed_os_str()) as *mut DaemonicPath;
		unsafe { Box::from_raw(rw) }
	}
	
	/// Invokes [`capacity`] on the underlying instance of [`DaemonicOsString`].
	///
	/// [`capacity`]: DaemonicOsString::capacity
	#[must_use]
	#[inline]
	pub fn capacity(&self) -> usize {
		self.inner.capacity()
	}
	
	/// Invokes [`clear`] on the underlying instance of [`DaemonicOsString`].
	///
	/// [`clear`]: DaemonicOsString::clear
	#[inline]
	pub fn clear(&mut self) {
		self.inner.clear()
	}
	
	/// Invokes [`reserve`] on the underlying instance of [`DaemonicOsString`].
	///
	/// [`reserve`]: DaemonicOsString::reserve
	#[inline]
	pub fn reserve(&mut self, additional: usize) {
		self.inner.reserve(additional)
	}
	
	/// Invokes [`try_reserve`] on the underlying instance of [`DaemonicOsString`].
	///
	/// [`try_reserve`]: DaemonicOsString::try_reserve
	#[inline]
	pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
		self.inner.try_reserve(additional)
	}
	
	/// Invokes [`reserve_exact`] on the underlying instance of [`DaemonicOsString`].
	///
	/// [`reserve_exact`]: DaemonicOsString::reserve_exact
	#[inline]
	pub fn reserve_exact(&mut self, additional: usize) {
		self.inner.reserve_exact(additional)
	}
	
	/// Invokes [`try_reserve_exact`] on the underlying instance of [`DaemonicOsString`].
	///
	/// [`try_reserve_exact`]: DaemonicOsString::try_reserve_exact
	#[inline]
	pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
		self.inner.try_reserve_exact(additional)
	}
	
	/// Invokes [`shrink_to_fit`] on the underlying instance of [`DaemonicOsString`].
	///
	/// [`shrink_to_fit`]: DaemonicOsString::shrink_to_fit
	#[inline]
	pub fn shrink_to_fit(&mut self) {
		self.inner.shrink_to_fit()
	}
	
	/// Invokes [`shrink_to`] on the underlying instance of [`DaemonicOsString`].
	///
	/// [`shrink_to`]: DaemonicOsString::shrink_to
	#[inline]
	pub fn shrink_to(&mut self, min_capacity: usize) {
		self.inner.shrink_to(min_capacity)
	}
}
impl Clone for DaemonicPathBuf {
	#[inline]
	fn clone(&self) -> Self {
		DaemonicPathBuf { inner: self.inner.clone() }
	}
	
	/// Clones the contents of `source` into `self`.
	///
	/// This method is preferred over simply assigning `source.clone()` to `self`,
	/// as it avoids reallocation if possible.
	#[inline]
	fn clone_from(&mut self, source: &Self) {
		self.inner.clone_from(&source.inner)
	}
}
use daemonic_path::*;

mod daemonic_path;

use daemonic_os_str::*;
mod daemonic_os_str;
use daemonic_slice::*;
mod daemonic_slice;
use daemonic_buf::*;
use crate::{Observation, Severity};
mod path_components;
use path_components::*;
use crate::daemonic::glass::daemonic_system_call::DaemonicSystemCall;

mod daemonic_buf;

//todo this should be moved to the DaemonicHasher blob under generic or standard implementations
impl DaemonicHashable for Vec<u8> {
	fn declare_hashable<GLASS: DaemonicHasher<GLASS> + Glass<GLASS>>(&self, state: &mut GLASS) {
		"Vec<u8>".declare_hashable(state);
		self.as_slice().declare_hashable(state);
	}
}