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 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
//! Diese Modul repliziert einen String in einer no_std Crate.
//!
//! Im wesentlich kam ich auf die Idee, einen String typ in einer no_std crate zu definieren,
//! da man auch in einer umgebung ohne dynamische speicherverwaltungen einen String gebrauchen kann, der zwar eine
//! festgelegte maximal menge hat, aber bis dahin genug platz hat um dem string weitere strings hinzuzufuegen.
//!
//! Das Ein String ja im wesentlichen den byte in einem Vektor speichert verwenden wir hir anstelle der std Vec Struktur
//! die Vec Methode der heapless crate. Diese bietet uns eine festgelegte Maximal Menge an Speicher die wir verwenden koennen.
//!
//! Ich habe zeitgleich to_string neu definiert als trait und fuer einige typen vor implementiert, so wird auch wieder to_string in einer no_std crate verfuegbar sein.
//!
use core::error::Error;
use core::fmt;
use core::hash;
use core::iter;
use core::iter::from_fn;
use core::iter::FusedIterator;
use core::ops::Add;
use core::ops::AddAssign;
use core::ops::Bound::{Excluded, Included, Unbounded};
use core::ops::{self, Range, RangeBounds};
use core::ptr;
use core::slice;
use core::str::pattern::Pattern;
use core::str::{self, from_utf8_unchecked_mut, Chars, Utf8Error};
use core::str::FromStr;
use crate::value::Value;
use crate::vec::Vec;
/// # Wir definieren hier die Grundstruktur des Strings.
/// Den const N: usize parameter mussten wir setzen, da dieser von der heapless crate verwendet wird.
/// Mithilfe von deriven haben wir ein paar standard implementierungen bereitgestellt.
#[derive(PartialEq, PartialOrd, Eq, Ord, Default, Clone)]
pub struct String<const N: usize> {
vec: Vec<u8, N>,
}
/// Hier definieren wir ein paar alias typen, die man verwenden kann wenn die erwartete grenze dran ist.
/// Es gibt folgende Typen:
/// - String64: Ein String mit einer maximal Groesse von 64 byte;
/// ```rust
/// pub type String64 = String<64>;
/// ```
/// - String128: Ein String mit einer maximal Groesse von 128 byte;
/// ```rust
/// pub type String128 = String<128>;
/// ```
/// - String256: Ein String mit einer maximal Groesse von 256 byte;
/// ```rust
/// pub type String256 = String<256>;
/// ```
/// - String64: Ein String mit einer maximal Groesse von 64 byte;
/// ```rust
/// pub type String64 = String<64>;
/// ```
/// - String128: Ein String mit einer maximal Groesse von 128 byte;
/// ```rust
/// pub type String128 = String<128>;
/// ```
/// - String256: Ein String mit einer maximal Groesse von 256 byte;
/// ```rust
/// pub type String256 = String<256>;
/// ```
/// - String512: Ein String mit einer maximal Groesse von 512 byte;
/// ```rust
/// pub type String512 = String<512>;
/// ```
/// - String1024: Ein String mit einer maximal Groesse von 1024 byte;
/// ```rust
/// pub type String1024 = String<1024>;
/// ```
/// - String2048: Ein String mit einer maximal Groesse von 2048 byte;
/// ```rust
/// pub type String2048 = String<2048>;
/// ```
/// - String4096: Ein String mit einer maximal Groesse von 4096 byte;
/// ```rust
/// pub type String4096 = String<4096>;
/// ```
pub type String64 = String<64>;
pub type String128 = String<128>;
pub type String256 = String<256>;
pub type String512 = String<512>;
pub type String1024 = String<1024>;
pub type String2048 = String<2048>;
pub type String4096 = String<4096>;
/// # Wir definieren hier ein paar Fehlertypen, die beim Utf8 Konvertieren auftauchen koennen.
/// Wir machen in der ganzen crate im grunde die selbe implementierung wie in der std crate,
/// nur ohne die funktionen die sowohl nicht im heapless vec als auch dynamische speicherverwaltung benoetigt.
#[derive(Debug, PartialEq, Eq)]
pub struct FromUtf8Error<const N: usize> {
bytes: Vec<u8, N>,
error: Utf8Error,
}
#[derive(Debug)]
pub struct FromUtf16Error(());
impl<const N: usize> String<N> {
/// Erstelle einen neuen String ohne content
///
/// ```rust
/// let str = String::<64>::new();
/// ```
#[inline]
#[must_use]
pub const fn new() -> String<N> {
String { vec: Vec::new() }
}
/// Erstelle einen String aus einem utf8 Vektor
///
/// ```rust
/// let str = String::<64>::from_utf8(vec);
/// ```
#[inline]
#[must_use]
pub fn from_utf8(vec: Vec<u8, N>) -> Result<String<N>, FromUtf8Error<N>> {
match core::str::from_utf8(&vec) {
Ok(..) => Ok(String { vec }),
Err(e) => Err(FromUtf8Error { bytes: vec, error: e }),
}
}
/// Erstelle einen String aus einem utf8 Vektor ohne Fehlermeldungen
///
/// Achtung diese Funktion ist unsicher, da sie keine Fehlermeldungen wirft, sondern einfach nur den vector ungeprueft einnimmt
///
/// ```rust
/// let str = String::<64>::from_utf8_unchecked(vec);
/// ```
#[inline]
pub unsafe fn from_utf8_unchecked(vec: Vec<u8, N>) -> String<N> {
String { vec }
}
/// Erstelle einen String aus einem utf8 Slice
///
/// ```rust
/// let str = String::<64>::from_utf8_slice(slice);
/// ```
#[inline]
#[must_use]
pub fn from_utf8_slice(byte: &[u8]) -> Result<String<N>, FromUtf8Error<N>> {
match core::str::from_utf8(byte) {
Ok(..) => Ok(String { vec: Vec::from_slice(byte).unwrap_or_default() }),
Err(e) => Err(FromUtf8Error { bytes: Vec::from_slice(byte).unwrap_or_default(), error: e }),
}
}
/// Erstelle einen String aus einem utf8 Slice ohne Fehlermeldungen
///
/// Achtung diese Funktion ist unsicher, da sie keine Fehlermeldungen wirft, sondern einfach nur den vector ungeprueft einnimmt
///
/// ```rust
/// let str = String::<64>::from_utf8_slice_unchecked(slice);
/// ```
#[inline]
pub unsafe fn from_utf8_slice_unchecked(byte: &[u8]) -> String<N> {
String { vec: Vec::from_slice(byte).unwrap_or_default() }
}
/// Gibt einen Slice zurck, der die bytes des Strings repraesentiert
///
/// ```rust
/// let str = String::<64>::as_bytes();
/// ```
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&self.vec
}
/// Gibt einen Slice zurck, der die bytes des Strings repraesentiert
///
/// ```rust
/// let str = String::<64>::as_mut_bytes();
/// ```
#[inline]
pub fn as_mut_bytes(&mut self) -> &mut [u8] {
&mut self.vec
}
/// Gibt einen String zurck, der die bytes des Strings repraesentiert
///
/// ```rust
/// let str = String::<64>::as_str();
/// ```
#[inline]
pub fn as_str(&self) -> &str {
core::str::from_utf8(self.as_bytes()).unwrap_or_default()
}
/// Gibt einen String zurck, der die bytes des Strings repraesentiert
///
/// ```rust
/// let str = String::<64>::as_mut_str();
/// ```
#[inline]
pub fn as_mut_str(&mut self) -> &mut str {
core::str::from_utf8_mut(self.as_mut_bytes()).unwrap_or_default()
}
/// Gibt einen String zurck, der die bytes des Strings repraesentiert
///
/// ```rust
/// let str = String::<64>::as_str_unchecked();
/// ```
#[inline]
pub unsafe fn as_str_unchecked(&self) -> &str {
unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
}
/// Gibt einen String zurck, der die bytes des Strings repraesentiert
///
/// ```rust
/// let str = String::<64>::as_mut_str_unchecked();
/// ```
#[inline]
pub unsafe fn as_mut_str_unchecked(&mut self) -> &mut str {
unsafe { core::str::from_utf8_unchecked_mut(self.as_mut_bytes()) }
}
/// Gibt einen Pointer zurck, der die bytes des Strings repraesentiert
///
/// ```rust
/// let str = String::<64>::as_ptr();
/// ```
#[inline]
pub fn as_ptr(&self) -> *const u8 {
self.vec.as_ptr()
}
/// Gibt einen Pointer zurck, der die bytes des Strings repraesentiert
///
/// ```rust
/// let str = String::<64>::as_mut_ptr();
/// ```
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut u8 {
self.vec.as_mut_ptr()
}
/// Erstelle einen String aus einem utf16 Vektor
///
/// ```rust
/// let str = String::<64>::from_utf16(vec);
/// ```
pub fn from_utf16(v: &[u16]) -> Result<String<N>, FromUtf16Error> {
let mut ret = String::<N>::new();
for c in char::decode_utf16(v.iter().cloned()) {
if let Ok(c) = c {
ret.push(c);
} else {
return Err(FromUtf16Error(()));
}
}
Ok(ret)
}
/// Erstelle einen String aus einem utf16 Vektor ohne Fehlermeldungen
///
/// ```rust
/// let str = String::<64>::from_utf16_lossy(vec);
/// ```
pub fn from_utf16_lossy(v: &[u16]) -> String<N> {
char::decode_utf16(v.iter().cloned())
.map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
.collect()
}
/// Erstelle einen String aus einem utf16 Vektor ohne Fehlermeldungen
///
/// ```rust
/// let str = String::<64>::into_raw_parts();
/// ```
#[must_use = "self will be dropped, if the result is not using"]
pub fn into_raw_parts(self) -> (*mut u8, usize, usize) {
let mut n = self.clone();
let ptr = n.as_mut_ptr();
let len = n.vec.len();
let cap = n.vec.capacity();
(ptr, len, cap)
}
/// Erstelle einen String aus einem utf16 Vektor ohne Fehlermeldungen
///
/// ```rust
/// let str = String::<64>::into_bytes();
/// ```
#[inline]
#[must_use = "self will be dropped, if the result is not using"]
pub fn into_bytes(self) -> Vec<u8, N> {
self.vec
}
/// Fuege einen String an den String an
///
/// ```rust
/// let str = String::<64>::push_str(str);
/// ```
#[inline]
#[rustc_confusables("append", "push")]
pub fn push_str(&mut self, string: &str) {
self.vec.extend_from_slice(string.as_bytes()).expect("String<N>, const N is to small");
}
/// Gibt die Kapazitaet des Strings zurck
///
/// ```rust
/// let str = String::<64>::capacity();
/// ```
#[inline]
#[must_use]
pub fn capacity(&self) -> usize {
self.vec.capacity()
}
/// Fuege einen Character an den String an
///
/// ```rust
/// let str = String::<64>::push(ch);
/// ```
#[inline]
pub fn push(&mut self, ch: char) {
match ch.len_utf8() {
1 => self.vec.push(ch as u8).expect("String<N>, const N is to small"),
_ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()).expect("String<N>, const N is to small"),
}
}
/// Entferne den letzten Character des Strings
///
/// ```rust
/// let str = String::<64>::pop();
/// ```
#[inline]
pub fn pop(&mut self) -> Option<char> {
let ch = self.chars().rev().next()?;
let nlen = self.len() - ch.len_utf8();
unsafe {
self.vec.set_len(nlen);
}
Some(ch)
}
/// Entferne den Character an der Position
///
/// ```rust
/// let str = String::<64>::remove(idx);
/// ```
#[inline]
#[rustc_confusables("delete", "take")]
pub fn remove(&mut self, idx: usize) -> char {
let ch = match self[idx..].chars().next() {
Some(ch) => ch,
None => panic!("cannot remove a char from the end of string"),
};
let next = idx + ch.len_utf8();
let len = self.len();
unsafe {
ptr::copy(self.as_ptr().add(next), self.as_mut_ptr().add(idx), len - next);
self.vec.set_len(len - (next - idx));
}
ch
}
/// Entferne alle Vorkasse des Patterns
///
/// ```rust
/// let str = String::<64>::remove_matches(pat);
/// ```
pub fn remove_matches<'a, P>(&'a mut self, pat: P)
where
P: for<'x> Pattern<'x>,
{
use core::str::pattern::Searcher;
let rej = {
let mut searcher = pat.into_searcher(self);
let mut front = 0;
let rej: Vec<_, N> = from_fn(|| {
let (start, end) = searcher.next_match()?;
let prev = front;
front = end;
Some((prev, start))
})
.collect();
rej.into_iter().chain(core::iter::once((front, self.len())))
};
let mut len = 0;
let ptr = self.as_mut_ptr();
for (start, end) in rej {
let count = end - start;
if start != len {
unsafe {
ptr::copy(ptr.add(start), ptr.add(len), count);
}
}
len += count;
}
unsafe {
self.vec.set_len(len);
}
}
/// Entferne alle Vorkasse des Patterns
///
/// ```rust
/// let str = String::<64>::retain(f);
/// ```
#[inline]
pub fn reatain<F>(&mut self, mut f: F)
where
F: FnMut(char) -> bool,
{
struct SetLenOnDrop<'a, const N: usize> {
s: &'a mut String<N>,
idx: usize,
del: usize,
}
impl<'a, const N: usize> Drop for SetLenOnDrop<'a, N> {
fn drop(&mut self) {
let nlen = self.idx - self.del;
debug_assert!(nlen <= self.s.len());
unsafe {
self.s.vec.set_len(nlen)
};
}
}
let len = self.len();
let mut guard = SetLenOnDrop { s: self, idx: 0, del: 0 };
while guard.idx < len {
let ch = unsafe {
guard.s.get_unchecked(guard.idx..len).chars().next().unwrap_unchecked()
};
let clen = ch.len_utf8();
if !f(ch) {
guard.del += clen;
} else if guard.del > 0 {
ch.encode_utf8(unsafe {
core::slice::from_raw_parts_mut(
guard.s.as_mut_ptr().add(guard.idx - guard.del),
ch.len_utf8(),
)
});
}
guard.idx += clen;
}
drop(guard);
}
/// Fuege einen Character an den String an
///
/// ```rust
/// let str = String::<64>::insert(idx, ch);
/// ```
#[inline]
#[rustc_confusables("set")]
pub fn insert(&mut self, idx: usize, ch: char) {
assert!(self.is_char_boundary(idx));
let mut bits = [0; 4];
let bits = ch.encode_utf8(&mut bits).as_bytes();
unsafe {
self.insert_bytes(idx, bits);
}
}
/// Fuege einen Byte an den String an
///
/// ```rust
/// let str = String::<64>::insert_bytes(idx, bytes);
/// ```
unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) {
let len = self.len();
let amt = bytes.len();
unsafe {
ptr::copy(
self.as_ptr().add(idx),
self.as_mut_ptr().add(idx + amt),
len - idx
);
ptr::copy_nonoverlapping(
bytes.as_ptr(),
self.as_mut_ptr().add(idx),
amt
);
self.vec.set_len(len + amt);
}
}
/// Fuege einen String an den String an
///
/// ```rust
/// let str = String::<64>::insert_str(idx, s);
/// ```
#[inline]
pub fn insert_str(&mut self, idx: usize, s: &str) {
assert!(self.is_char_boundary(idx));
unsafe {
self.insert_bytes(idx, s.as_bytes());
}
}
/// Gibt den Vector zurck, der den String repraesentiert
///
/// ```rust
/// let str = String::<64>::as_mut_vec();
/// ```
#[inline]
pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8, N> {
&mut self.vec
}
/// Gibt die Laenge des Strings zurck
///
/// ```rust
/// let str = String::<64>::len();
/// ```
#[inline]
#[must_use]
#[rustc_confusables("length", "size")]
pub fn len(&self) -> usize {
self.vec.len()
}
/// Gibt zurck, ob der String leer ist
///
/// ```rust
/// let str = String::<64>::is_empty();
/// ```
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Schneide den String auf
///
/// ```rust
/// let str = String::<64>::truncate(nlen);
/// ```
#[inline]
pub fn truncate(&mut self, nlen: usize) {
if nlen <= self.len() {
assert!(self.is_char_boundary(nlen));
self.vec.truncate(nlen)
}
}
/// Leere den String
///
/// ```rust
/// let str = String::<64>::clear();
/// ```
#[inline]
pub fn clear(&mut self) {
self.vec.clear()
}
/// Gibt einen Drain zurck, der den String repraesentiert
///
/// ```rust
/// let str = String::<64>::drain(range);
/// ```
pub fn drain<R>(&mut self, range: R) -> Drain<'_, N>
where
R: RangeBounds<usize>,
{
// Memory safety
//
// The String version of Drain does not have the memory safety issues
// of the vector version. The data is just plain bytes.
// Because the range removal happens in Drop, if the Drain iterator is leaked,
// the removal will not happen.
let Range { start, end } = slice::range(range, ..self.len());
assert!(self.is_char_boundary(start));
assert!(self.is_char_boundary(end));
// Take out two simultaneous borrows. The &mut String won't be accessed
// until iteration is over, in Drop.
let self_ptr = self as *mut _;
// SAFETY: `slice::range` and `is_char_boundary` do the appropriate bounds checks.
let chars_iter = unsafe { self.get_unchecked(start..end) }.chars();
Drain { start, end, iter: chars_iter, string: self_ptr }
}
}
impl<const N: usize> FromUtf8Error<N> {
/// Gibt die bytes des Fehlers zurck
///
/// ```rust
/// let str = FromUtf8Error { bytes: Vec::new(), error: Utf8Error::new() };
/// str.as_bytes();
/// ```
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.bytes[..]
}
/// Konvertiere den Fehler in einen Vektor
///
/// ```rust
/// let str = FromUtf8Error { bytes: Vec::new(), error: Utf8Error::new() };
/// let bytes = str.into_bytes();
/// ```
#[must_use = "self will be dropped, if the result is not using"]
pub fn into_bytes(self) -> Vec<u8, N> {
self.bytes
}
/// Gibt den Utf8 Error zurck
///
/// ```rust
/// let str = FromUtf8Error { bytes: Vec::new(), error: Utf8Error::new() };
/// let error = str.utf8_error();
/// ```
#[must_use]
pub fn utf8_error(&self) -> Utf8Error {
self.error
}
}
/// Repraesentiert einen Fehler, der beim Konvertieren eines Utf8 Strings in einen String<N> auftreten kann
///
/// ```rust
/// let str = FromUtf8Error { bytes: Vec::new(), error: Utf8Error::new() };
/// write!("{}", str);
/// ```
impl<const N: usize> fmt::Display for FromUtf8Error<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.error, f)
}
}
/// Repraesentiert einen Fehler, der beim Konvertieren eines Utf16 Strings in einen String<N> auftreten kann
///
/// ```rust
/// let str = FromUtf16Error(());
/// write!("{}", str);
/// ```
impl fmt::Display for FromUtf16Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt("invalid utf-16: lone surrogate found", f)
}
}
impl<const N: usize> Error for FromUtf8Error<N> {
#[allow(deprecated)]
fn description(&self) -> &str {
"invalid utf8"
}
}
impl Error for FromUtf16Error {
#[allow(deprecated)]
fn description(&self) -> &str {
"invalid utf16"
}
}
impl<const N: usize> FromIterator<char> for String<N> {
fn from_iter<T: IntoIterator<Item = char>>(iter: T) -> Self {
let mut buf = String::<N>::new();
buf.extend(iter);
buf
}
}
impl<'a, const N: usize> FromIterator<&'a char> for String<N> {
fn from_iter<T: IntoIterator<Item = &'a char>>(iter: T) -> Self {
let mut buf = String::<N>::new();
buf.extend(iter);
buf
}
}
impl<'a, const N: usize> FromIterator<&'a str> for String<N> {
fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
let mut buf = String::<N>::new();
buf.extend(iter);
buf
}
}
impl<const N: usize> Extend<char> for String<N> {
fn extend<T: IntoIterator<Item = char>>(&mut self, iter: T) {
let iterator = iter.into_iter();
let (lbound, _) = iterator.size_hint();
iterator.for_each(move |c| self.push(c));
}
#[inline]
fn extend_one(&mut self, item: char) {
self.push(item);
}
}
impl<'a, const N: usize> Extend<&'a char> for String<N> {
fn extend<T: IntoIterator<Item = &'a char>>(&mut self, iter: T) {
self.extend(iter.into_iter().cloned());
}
#[inline]
fn extend_one(&mut self, &item: &'a char) {
self.push(item);
}
}
impl<'a, const N: usize> Extend<&'a str> for String<N> {
fn extend<T: IntoIterator<Item = &'a str>>(&mut self, iter: T) {
iter.into_iter().for_each(move |s| self.push_str(s));
}
#[inline]
fn extend_one(&mut self, item: &'a str) {
self.push_str(item);
}
}
impl<'a, 'b, const N: usize> Pattern<'a> for &'b String<N> {
type Searcher = <&'b str as Pattern<'a>>::Searcher;
fn into_searcher(self, haystack: &'a str) -> Self::Searcher {
self[..].into_searcher(haystack)
}
#[inline]
fn is_contained_in(self, haystack: &'a str) -> bool {
self[..].is_contained_in(haystack)
}
#[inline]
fn is_prefix_of(self, haystack: &'a str) -> bool {
self[..].is_prefix_of(haystack)
}
#[inline]
fn is_suffix_of(self, haystack: &'a str) -> bool
where
Self::Searcher: str::pattern::ReverseSearcher<'a>, {
self[..].is_suffix_of(haystack)
}
#[inline]
fn strip_prefix_of(self, haystack: &'a str) -> Option<&'a str> {
self[..].strip_prefix_of(haystack)
}
#[inline]
fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str>
where
Self::Searcher: str::pattern::ReverseSearcher<'a>, {
self[..].strip_suffix_of(haystack)
}
}
macro_rules! impl_eq {
($lhs:ty, $rhs: ty) => {
#[allow(unused_lifetimes)]
impl<'a, 'b, const N: usize> PartialEq<$rhs> for $lhs {
#[inline]
fn eq(&self, other: &$rhs) -> bool {
PartialEq::eq(&self[..], &other[..])
}
#[inline]
fn ne(&self, other: &$rhs) -> bool {
PartialEq::ne(&self[..], &other[..])
}
}
#[allow(unused_lifetimes)]
impl<'a, 'b, const N: usize> PartialEq<$lhs> for $rhs {
#[inline]
fn eq(&self, other: &$lhs) -> bool {
PartialEq::eq(&self[..], &other[..])
}
#[inline]
fn ne(&self, other: &$lhs) -> bool {
PartialEq::ne(&self[..], &other[..])
}
}
};
}
impl_eq! { String<N>, str }
impl_eq! { String<N>, &'a str }
impl<const N: usize> fmt::Display for String<N> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<const N: usize> fmt::Debug for String<N> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<const N: usize> hash::Hash for String<N> {
#[inline]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state)
}
}
impl<const N: usize> Add<&str> for String<N> {
type Output = String<N>;
#[inline]
fn add(mut self, rhs: &str) -> Self::Output {
self.push_str(rhs);
self
}
}
impl<const N: usize> AddAssign<&str> for String<N> {
#[inline]
fn add_assign(&mut self, rhs: &str) {
self.push_str(rhs);
}
}
impl<I, const N: usize> ops::Index<I> for String<N>
where
I: slice::SliceIndex<str>,
{
type Output = I::Output;
#[inline]
fn index(&self, index: I) -> &Self::Output {
index.index(self.as_str())
}
}
impl<I, const N: usize> ops::IndexMut<I> for String<N>
where
I: slice::SliceIndex<str>,
{
#[inline]
fn index_mut(&mut self, index: I) -> &mut Self::Output {
index.index_mut(self.as_mut_str())
}
}
impl<const N: usize> ops::Deref for String<N> {
type Target = str;
#[inline]
fn deref(&self) -> &Self::Target {
unsafe {
core::str::from_utf8_unchecked(&self.vec)
}
}
}
unsafe impl<const N: usize> ops::DerefPure for String<N> {}
impl<const N: usize> ops::DerefMut for String<N> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe {
core::str::from_utf8_unchecked_mut(&mut *self.vec)
}
}
}
pub type ParseError = core::convert::Infallible;
impl<const N: usize> FromStr for String<N> {
type Err = ParseError;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(String::from(s))
}
}
pub trait ToString<const N: usize> {
#[rustc_conversion_suggestion]
#[cfg_attr(not(test), rustc_diagnostic_item = "to_string_methode")]
fn to_string(&self) -> String<N>;
fn to_string_valued(&self) -> Value<String<N>> {
let string = self.to_string();
Value::nok(string)
}
}
impl<T: fmt::Display + ?Sized, const N: usize> ToString<N> for T {
#[inline]
default fn to_string(&self) -> String<N> {
let mut buf = String::<N>::new();
let mut formatter = core::fmt::Formatter::new(&mut buf);
fmt::Display::fmt(self, &mut formatter)
.expect("a Display implementation returned an error unexpectly");
buf
}
}
#[doc(hidden)]
impl<const N: usize> ToString<N> for core::ascii::Char {
#[inline]
fn to_string(&self) -> String<N> {
self.as_str().to_string()
}
}
#[doc(hidden)]
impl<const N: usize> ToString<N> for char {
#[inline]
fn to_string(&self) -> String<N> {
String::<N>::from(self.encode_utf8(&mut [0; 4]))
}
}
#[doc(hidden)]
impl<const N: usize> ToString<N> for bool {
#[inline]
fn to_string(&self) -> String<N> {
String::<N>::from(if *self { "true" } else { "false" })
}
}
#[doc(hidden)]
impl<const N: usize> ToString<N> for u8 {
#[inline]
fn to_string(&self) -> String<N> {
let mut buf = String::<N>::new();
let mut n = *self;
if n >= 10 {
if n >= 100 {
buf.push((b'0' + n / 100) as char);
n %= 100;
}
buf.push((b'0' + n / 10) as char);
n %= 10;
}
buf.push((b'0' + n) as char);
buf
}
}
#[doc(hidden)]
impl<const N: usize> ToString<N> for i8 {
#[inline]
fn to_string(&self) -> String<N> {
let mut buf = String::<N>::new();
if self.is_negative() {
buf.push('-');
}
let mut n = self.unsigned_abs();
if n >= 10 {
if n >= 100 {
buf.push('1');
n -= 100;
}
buf.push((b'0' + n / 10) as char);
n %= 10;
}
buf.push((b'0' + n) as char);
buf
}
}
#[doc(hidden)]
impl<const N: usize> ToString<N> for str {
#[inline]
fn to_string(&self) -> String<N> {
String::<N>::from(self)
}
}
impl<const N: usize> ToString<N> for String<N> {
#[inline]
fn to_string(&self) -> String<N> {
self.clone()
}
}
impl<const N: usize> AsRef<str> for String<N> {
#[inline]
fn as_ref(&self) -> &str {
self
}
}
impl<const N: usize> AsMut<str> for String<N> {
#[inline]
fn as_mut(&mut self) -> &mut str {
self
}
}
impl<const N: usize> AsRef<[u8]> for String<N> {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl<const N: usize> AsMut<[u8]> for String<N> {
#[inline]
fn as_mut(&mut self) -> &mut [u8] {
self.as_mut_bytes()
}
}
impl<const N: usize> From<&str> for String<N> {
#[inline]
fn from(value: &str) -> Self {
String::<N>::from_utf8_slice(value.as_bytes()).unwrap_or_default()
}
}
impl<const N: usize> From<&mut str> for String<N> {
#[inline]
fn from(value: &mut str) -> Self {
String::<N>::from_utf8_slice(value.as_bytes()).unwrap_or_default()
}
}
impl<const N: usize> From<&String<N>> for String<N> {
#[inline]
fn from(value: &String<N>) -> Self {
value.clone()
}
}
impl<const N: usize> From<String<N>> for Vec<u8, N> {
#[inline]
fn from(value: String<N>) -> Self {
value.into_bytes()
}
}
impl<const N: usize> fmt::Write for String<N> {
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
self.push_str(s);
Ok(())
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
self.push(c);
Ok(())
}
}
pub struct Drain<'a, const N: usize> {
string: *mut String<N>,
start: usize,
end: usize,
iter: Chars<'a>,
}
impl<const N: usize> fmt::Debug for Drain<'_, N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Drain").field(&self.as_str()).finish()
}
}
unsafe impl<const N: usize> Sync for Drain<'_, N> {}
unsafe impl<const N: usize> Send for Drain<'_, N> {}
impl<'a, const N: usize> Drain<'a, N> {
#[must_use]
pub fn as_str(&self) -> &str {
self.iter.as_str()
}
}
impl<'a, const N: usize> AsRef<str> for Drain<'a, N> {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl<const N: usize> Iterator for Drain<'_, N> {
type Item = char;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
#[inline]
fn last(mut self) -> Option<Self::Item>
where
Self: Sized, {
self.next_back()
}
}
impl<const N: usize> DoubleEndedIterator for Drain<'_, N> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back()
}
}
impl<const N: usize> FusedIterator for Drain<'_, N> {}
impl<const N: usize> From<char> for String<N> {
#[inline]
fn from(value: char) -> Self {
value.to_string()
}
}
pub trait FromString<const N: usize> {
#[rustc_conversion_suggestion]
#[cfg_attr(not(test), rustc_diagnostic_item = "from_string_methode")]
#[must_use]
fn from_string(value: String<N>) -> Value<Self>
where
Self: Sized;
}
#[cfg(test)]
mod tests {
use super::String;
#[test]
fn test1() {
let orig = "Hallo";
let mut s = String::<5>::from(orig);
assert_eq!(s, "Hallo");
assert_eq!(s, orig);
}
}