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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
#![cfg_attr(not(feature = "std"), no_std)]
#![deny(missing_docs)]
//! A ring buffer specialization for strings. The crate provides two versions of the buffer and a
//! [`StringBuffer`](StringBuffer) trait they both implement. [`StRingBuffer`](StRingBuffer) is a
//! stack allocated version using const generics. [`HeapStRingBuffer`](HeapStRingBuffer) is a heap
//! allocated version.
//!
//! When full these buffers both operate by overwriting the current head. All operations happen
//! in constant time except where explicitly noted.
extern crate alloc;
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::fmt::{Formatter, Write};
use core::iter::{Chain, FusedIterator};
use core::str::{Chars, from_utf8_unchecked};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// An error type used for the failable push functions on StringBuffer.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum StringBufferError {
/// Returned if the buffer has 0 bytes of free space
BufferFull,
/// Returned if the buffer does not have enough free space to fit the given string
NotEnoughSpaceForStr,
/// Returned if the buffer does not have enough free space to fit the given char
NotEnoughSpaceForChar,
}
impl core::fmt::Display for StringBufferError {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
f.write_str(match self {
StringBufferError::BufferFull => "The buffer is full (0 bytes of free space).",
StringBufferError::NotEnoughSpaceForStr => "The buffer does not have enough space to fit the given String",
StringBufferError::NotEnoughSpaceForChar => "The buffer does not have enough space to fit the given char",
})
}
}
#[cfg(feature = "std")]
impl std::error::Error for StringBufferError {}
/// A buffer specializing in holding data for a string. Pushing data to the buffer will not fail nor
/// panic. When full, the end of the data overwrites the start, while keeping the integrity of the
/// underlying utf-8 data.
pub trait StringBuffer {
/// Adds a char to the buffer. Overwrites the start if the buffer is full.
///
/// This will never panic nor fail. However, if the length of the char in utf-8 exceeds the
/// length of the buffer then the buffer will be emptied.
/// # Example
/// ```rust
/// use st_ring_buffer::{StRingBuffer, StringBuffer};
/// let mut buffer = StRingBuffer::<5>::new();
/// buffer.push_char('F');
/// assert_eq!(buffer.as_slices().0, "F");
/// assert_eq!(buffer.as_slices().1, "");
/// ```
fn push_char(&mut self, c: char);
/// Remove a char from the buffer if one exists. Returns ```None``` if the buffer is empty.
fn pop(&mut self) -> Option<char>;
/// Remove a char from the front of the buffer if one exists. Returns ```None``` if the buffer is empty.
fn pop_front(&mut self) -> Option<char>;
/// Tries to push the given character into the buffer. Will return Ok(c.bytes_len) if the write
/// succeeded. If there is not enough room for the char or the buffer is full then
/// Err(NotEnoughSpaceForChar) or Err(BufferFull) is returned respectively.
///
/// # Example
/// ```rust
/// use st_ring_buffer::{StRingBuffer, StringBuffer, StringBufferError};
///
/// let mut buffer = StRingBuffer::<5>::new();
/// let res = buffer.try_push_char('🦀'); //Crab Emoji (Fat Ferris) (UTF-8: 0xF0 0x9F 0xA6 0x80)
/// assert_eq!(res, Ok(4));
///
/// let res = buffer.try_push_char('🦀');
/// //already 4 bytes in the buffer, can't fit 4 more
/// assert_eq!(res, Err(StringBufferError::NotEnoughSpaceForChar));
///
/// //but 1 more does fit
/// assert_eq!(buffer.try_push_char('A'), Ok(1));
///
/// //now the buffer is full and can't fit anything
/// assert_eq!(buffer.try_push_char('A'), Err(StringBufferError::BufferFull));
/// ```
fn try_push_char(&mut self, c: char) -> Result<usize, StringBufferError>;
/// Adds a &str to the buffer. Overwrites the start if the buffer is full.
///
/// This will never panic nor fail.
/// # Example
/// ```rust
/// use st_ring_buffer::{StRingBuffer, StringBuffer};
/// let mut buffer = StRingBuffer::<5>::new();
/// buffer.push_str("ABCDE");
/// buffer.push_char('F');
/// assert_eq!(buffer.as_slices().0,"BCDE");
/// assert_eq!(buffer.as_slices().1, "F");
/// ```
fn push_str(&mut self, s: &str) {
s.chars().for_each(|c| self.push_char(c));
}
/// Will push as many chars as will fit into the existing space of the buffer. Will not
/// overwrite any existing data.
///
/// # Example
/// ```rust
/// use st_ring_buffer::{StRingBuffer, StringBuffer};
///
/// let mut buffer = StRingBuffer::<5>::new();
/// let res = buffer.try_push_some("ABCDEFGHIJKLMNO"); // too long
/// assert_eq!(res, Ok(5)); //only 5 bytes pushed
/// // the first bytes are pushed so long as there's room
/// assert_eq!(buffer.as_slices().0,"ABCDE");
/// ```
fn try_push_some(&mut self, s: &str) -> Result<usize, StringBufferError>;
/// Try to push the entire string into the buffer. If the string is too long or the buffer is
/// full then nothing is written and Err(NotEnoughSpaceForStr) or Err(BufferFull) is returned
/// respectively.
///
/// # Example
/// ```rust
/// use st_ring_buffer::{StRingBuffer, StringBuffer, StringBufferError};
///
/// let mut buffer = StRingBuffer::<5>::new();
/// assert_eq!(buffer.try_push_all("ABCDE"), Ok(()));
/// assert_eq!(buffer.try_push_all("Z"), Err(StringBufferError::BufferFull));
///
/// buffer.clear();
/// let res = buffer.try_push_all("ABCDEFGHIJKLMNO"); // too long
/// assert_eq!(res, Err(StringBufferError::NotEnoughSpaceForStr));
/// ```
fn try_push_all(&mut self, s: &str) -> Result<(), StringBufferError> {
if self.remaining_size() == 0 {
return Err(StringBufferError::BufferFull);
}
if s.len() <= self.capacity() - self.len() {
self.push_str(s);
Ok(())
} else {
Err(StringBufferError::NotEnoughSpaceForStr)
}
}
/// Get a reference to the two buffer segments in order.
///
/// If the current data fits entirely in the buffer, and it is aligned, then the second
/// reference will be an empty &str.
/// # Example
/// ```rust
/// use st_ring_buffer::{StRingBuffer, StringBuffer};
/// let mut buffer = StRingBuffer::<5>::new();
/// buffer.push_str("ABCDE");
/// assert_eq!(buffer.as_slices().0, "ABCDE");
/// assert_eq!(buffer.as_slices().1, "");
///
/// buffer.push_char('F');
/// assert_eq!(buffer.as_slices().0, "BCDE");
/// assert_eq!(buffer.as_slices().1,"F");
/// ```
fn as_slices(&self) -> (&str, &str);
/// Copies data as required to make the head the start of the buffer. This allocates a temporary
/// buffer the size of the smaller &str given by [`as_slices`](StringBuffer::as_slices).
///
/// This is required to represent the entire buffer as a single &str.
/// # Example
/// ```rust
/// use st_ring_buffer::{StRingBuffer, StringBuffer};
/// let mut buffer = StRingBuffer::<5>::new();
/// buffer.push_str("ABCDE");
/// buffer.push_char('F');
/// assert_eq!(buffer.as_slices().0, "BCDE");
/// assert_eq!(buffer.as_slices().1, "F");
/// buffer.align();
/// assert_eq!(buffer.as_slices().0, "BCDEF");
/// ```
fn align(&mut self);
/// Aligns the head of the buffer to the start via rotation. Compared to
/// [`align`](StringBuffer::align) this function does not allocate any memory; however, it works
/// in O([`buffer.len()`](StringBuffer::len)) time.
///
/// This is required to represent the entire buffer as a single &str.
/// # Example
/// ```rust
/// use st_ring_buffer::{StRingBuffer, StringBuffer};
/// let mut buffer = StRingBuffer::<5>::new();
/// buffer.push_str("ABCDE");
/// buffer.push_char('F');
/// assert_eq!(buffer.as_slices().0, "BCDE");
/// assert_eq!(buffer.as_slices().1, "F");
/// buffer.align_no_alloc();
/// assert_eq!(buffer.as_slices().0, "BCDEF");
/// ```
fn align_no_alloc(&mut self);
/// Returns the length of this buffer, in bytes, not chars or graphemes
/// # Example
/// ```rust
/// use st_ring_buffer::{StRingBuffer, StringBuffer};
/// let mut buffer = StRingBuffer::<5>::new();
/// buffer.push_str("ABCDEF");
/// assert_eq!(buffer.len(), 5);
/// ```
fn len(&self) -> usize;
/// Returns true if there is no data in the buffer.
fn is_empty(&self) -> bool;
/// The number of bytes this buffer can hold. Not the number of chars or graphemes.
/// # Example
/// ```rust
/// use st_ring_buffer::{StRingBuffer, StringBuffer};
/// let mut buffer = StRingBuffer::<5>::new();
/// assert_eq!(buffer.capacity(), 5);
/// ```
fn capacity(&self) -> usize;
/// Convenience function to return the number of bytes remaining in the buffer before data is
/// overwritten. This is roughly equivalent to ```self.capacity() - self.len()```, but takes into
/// account any padding required along the edge of the buffer.
fn remaining_size(&self) -> usize;
/// Returns an iterator over the characters in the buffer. This includes both slices, in order,
/// if the buffer is currently split.
/// # Example
/// ```rust
/// use st_ring_buffer::{StRingBuffer, StringBuffer};
///
/// let mut buffer = StRingBuffer::<5>::new();
/// //Fill up the buffer
/// buffer.push_str("ABCDE");
/// //add one more so that the buffer is looped
/// buffer.push_char('F');
/// assert_eq!(buffer.as_slices().0, "BCDE");
/// assert_eq!(buffer.as_slices().1, "F");
///
/// //iterator doesn't care about loop and still gives all chars in order
/// let mut iter = buffer.chars();
/// assert_eq!(Some('B'), iter.next());
/// assert_eq!(Some('C'), iter.next());
/// assert_eq!(Some('D'), iter.next());
/// assert_eq!(Some('E'), iter.next());
/// assert_eq!(Some('F'), iter.next());
/// assert_eq!(None, iter.next());
/// ```
fn chars(&self) -> Chain<Chars<'_>, Chars<'_>> {
let (front, back) = self.as_slices();
front.chars().chain(back.chars())
}
/// Empties the buffer
fn clear(&mut self);
}
/// An implementation of [`StringBuffer`](StringBuffer) using const generics to store its data on
/// the stack.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct StRingBuffer<const SIZE: usize> {
data: [u8; SIZE],
state: State,
}
/// An implementation of [`StringBuffer`](StringBuffer) that stores its data on the heap.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct HeapStRingBuffer {
data: Box<[u8]>,
state: State,
}
macro_rules! impl_buffer_trait {
() => {
fn push_char(&mut self, c: char) {
let char_len = c.len_utf8();
let slice = match char_len.cmp(&self.capacity()) {
Ordering::Less => self.state.get_char_slice(char_len, &mut self.data),
Ordering::Equal => {
self.state = State::Straight {count: char_len };
&mut self.data
}
Ordering::Greater => {
self.clear();
return;
},
};
c.encode_utf8(slice);
}
fn pop(&mut self) -> Option<char> {
match &mut self.state {
State::Empty => None,
State::OffsetStraight { offset, next } => {
//SAFETY: We know there is at least one char in the buffer since we're in the
// straight state. The only way for prev_char_boundary to fail is if self.data is
// malformed, which is undefined behavior.
let new_next = unsafe {
prev_char_boundary(&self.data, *next - 1)
.unwrap_unchecked()
.max(*offset)
};
//SAFETY: we know that data is always valid utf-8 and have sliced it along a char
//boundary, ensuring that char iterator will return exactly one char
let c = unsafe { from_utf8_unchecked(&self.data[new_next..*next]).chars().next().unwrap_unchecked() };
if new_next == *offset {
self.state = State::Empty;
} else {
*next = new_next
}
Some(c)
}
State::Straight { count } => {
//SAFETY: We know there is at least one char in the buffer since we're in the
// straight state. The only way for prev_char_boundary to fail is if self.data is
// malformed, which is undefined behavior.
let new_count = unsafe { prev_char_boundary(&self.data, *count - 1).unwrap_unchecked() };
//SAFETY: we know that data is always valid utf-8 and have sliced it along a char
//boundary, ensuring that char iterator will return exactly one char
let c = unsafe { from_utf8_unchecked(&self.data[new_count..*count]).chars().next().unwrap_unchecked() };
if new_count == 0 {
self.state = State::Empty;
} else {
*count = new_count
}
Some(c)
}
State::Looped { first, end_offset, next } => {
let prev_offset = if *next > self.data.len() {
*end_offset as usize
} else {
0
} + 1;
//SAFETY: We know there is at least one char in the buffer since we're in the
// looped state. The only way for prev_char_boundary to fail is if self.data is
// malformed, which is undefined behavior.
let new_next = unsafe { prev_char_boundary(&self.data, *next - prev_offset).unwrap_unchecked() };
//SAFETY: we know that data is always valid utf-8 and have sliced it along a char
//boundary, ensuring that char iterator will return exactly one char
let c = unsafe { from_utf8_unchecked(&self.data[new_next..*next]).chars().next().unwrap_unchecked() };
if new_next == 0 {
self.state = State::OffsetStraight { offset: *first, next: self.data.len() }
} else if new_next == *first {
self.state = State::Empty;
} else {
*next = new_next
}
Some(c)
},
}
}
fn pop_front(&mut self) -> Option<char> {
match &mut self.state {
State::Empty => None,
State::OffsetStraight { offset, next } => {
//SAFETY: we know that data is always valid utf-8 and have limited the range to only
//include valid data
let c = unsafe { from_utf8_unchecked(&self.data[*offset..*next]).chars().next().unwrap_unchecked() };
if *offset + c.len_utf8() >= *next {
self.state = State::Empty;
} else {
*offset += c.len_utf8();
};
Some(c)
}
State::Straight { count } => {
//SAFETY: we know that data is always valid utf-8 and have limited the range to only
//include valid data
let c = unsafe { from_utf8_unchecked(&self.data[..*count]).chars().next().unwrap_unchecked() };
self.state = if c.len_utf8() >= *count {
State::Empty
} else {
State::OffsetStraight { offset: c.len_utf8(), next: *count }
};
Some(c)
}
State::Looped { first, end_offset, next } => {
//SAFETY: we know that data is always valid utf-8 and have limited the range to only
//include valid data
let c = unsafe { from_utf8_unchecked(&self.data[*first..self.data.len() - *end_offset as usize]).chars().next().unwrap_unchecked() };
if *first + c.len_utf8() >= self.data.len() - *end_offset as usize {
self.state = State::Straight { count: *next }
} else {
*first += c.len_utf8();
}
Some(c)
},
}
}
fn try_push_char(&mut self, c: char) -> Result<usize, StringBufferError> {
let remaining_size = self.remaining_size();
if remaining_size == 0 {
Err(StringBufferError::BufferFull)
} else if remaining_size < c.len_utf8() {
Err(StringBufferError::NotEnoughSpaceForChar)
} else {
self.push_char(c);
Ok(c.len_utf8())
}
}
fn push_str(&mut self, s: &str) {
unsafe {
//SAFETY: s is a valid utf-8 byte sequence because it's a &str
self.state.insert_bytes(&mut self.data, s.as_bytes());
}
}
fn try_push_some(&mut self, s: &str) -> Result<usize, StringBufferError> {
if self.remaining_size() == 0 {
return Err(StringBufferError::BufferFull)
}
let bytes = s.as_bytes();
let char_boundary = prev_char_boundary(bytes, self.remaining_size()).unwrap_or(0);
let b = &bytes[..char_boundary];
// SAFETY: we know b is valid utf-8 because it came from a &str and we made sure to
// split it on a char boundary. Self.data must also be valid utf-8.
let len = unsafe {
self.state.insert_bytes(&mut self.data, b)
};
if len == 0 {
Err(StringBufferError::NotEnoughSpaceForStr)
} else {
Ok(len)
}
}
fn as_slices(&self) -> (&str, &str) {
unsafe {
//SAFETY: self.data must be valid utf-8 sequence. This is ensured by any method in
//this trait that modifies the buffer.
match self.state {
State::Empty => ("", ""),
State::Straight { count } => (from_utf8_unchecked(&self.data[0..count]),""),
State::OffsetStraight {offset, next} => (from_utf8_unchecked(&self.data[offset..next]),""),
State::Looped { first, end_offset, next } => {
(from_utf8_unchecked(&self.data[first..(self.capacity() - end_offset as usize)]),
from_utf8_unchecked(&self.data[0..next]))
}
}
}
}
fn align(&mut self) {
match self.state {
State::Empty | State::Straight { .. } => {}
State::OffsetStraight { offset, next } => {
self.data.copy_within(offset..next, 0);
self.state = State::Straight { count: next - offset }
}
State::Looped { first, end_offset, next } => {
let count = self.len();
let capacity_minus_offset = self.capacity() - end_offset as usize;
let first_len = capacity_minus_offset - first;
if first_len < next {
let copy = self.data[first..capacity_minus_offset].to_owned();
self.data.copy_within(0..next, first_len);
self.data[0..first_len].copy_from_slice(©);
} else {
let copy = self.data[0..next].to_owned();
self.data.copy_within(first..capacity_minus_offset, 0);
self.data[first_len..].copy_from_slice(©);
}
self.state = State::Straight {count};
}
}
}
fn align_no_alloc(&mut self) {
match self.state {
State::Empty | State::Straight { .. } => {}
State::OffsetStraight { offset, next } => {
self.data.copy_within(offset..next, 0);
self.state = State::Straight { count: next - offset }
}
State::Looped { first, end_offset, next } => {
let len = if next == first {
let len = self.data.len() - end_offset as usize;
self.data[..len].rotate_left(first);
len
} else {
let first_len = self.data.len() - end_offset as usize;
let second_len = next;
self.data.rotate_left(first);
self.data[first_len..].rotate_left(end_offset as usize);
first_len + second_len
};
self.state = State::Straight {count: len};
}
}
}
fn len(&self) -> usize {
match self.state {
State::Empty => 0,
State::OffsetStraight{offset, next} => next - offset,
State::Straight { count } => count,
State::Looped { first, end_offset, next } => {
if next > first {
self.capacity() - end_offset as usize
} else {
self.capacity() - end_offset as usize - (first - next)
}
}
}
}
fn is_empty(&self) -> bool {
matches!(self.state, State::Empty)
}
fn capacity(&self) -> usize {
self.data.len()
}
fn remaining_size(&self) -> usize {
match self.state {
State::Empty | State::Straight { .. } | State::OffsetStraight { .. } => self.capacity() - self.len(),
State::Looped { end_offset, .. } => self.capacity() - self.len() - end_offset as usize,
}
}
fn clear(&mut self) {
self.state = State::Empty;
}
}
}
impl<const SIZE: usize> StringBuffer for StRingBuffer<SIZE> {
impl_buffer_trait!();
}
impl<const SIZE: usize> core::fmt::Display for StRingBuffer<SIZE> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
let (first, second) = self.as_slices();
write!(f, "({first}, {second})")
}
}
impl<const SIZE: usize> From<[u8; SIZE]> for StRingBuffer<SIZE> {
fn from(data: [u8; SIZE]) -> Self {
StRingBuffer {
data,
state: State::Empty,
}
}
}
impl<const SIZE: usize> Write for StRingBuffer<SIZE> {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
self.push_str(s);
Ok(())
}
fn write_char(&mut self, c: char) -> core::fmt::Result {
self.push_char(c);
Ok(())
}
}
impl<const SIZE: usize> StRingBuffer<SIZE> {
/// Creates a new StRingBuffer on the stack using the const generic size.
pub const fn new() -> Self {
Self {
data: [0; SIZE],
state: State::Empty,
}
}
}
impl StringBuffer for HeapStRingBuffer {
impl_buffer_trait!();
}
impl core::fmt::Display for HeapStRingBuffer {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
let (first, second) = self.as_slices();
write!(f, "({first}, {second})")
}
}
impl From<String> for HeapStRingBuffer {
fn from(s: String) -> Self {
let count = s.len();
let data = s.into_boxed_str().into_boxed_bytes();
HeapStRingBuffer {
data,
state: State::Straight { count },
}
}
}
impl TryFrom<Vec<u8>> for HeapStRingBuffer {
type Error = alloc::string::FromUtf8Error;
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
Ok(String::from_utf8(value)?.into())
}
}
impl TryFrom<Box<[u8]>> for HeapStRingBuffer {
type Error = alloc::string::FromUtf8Error;
fn try_from(value: Box<[u8]>) -> Result<Self, Self::Error> {
Ok(String::from_utf8(value.into())?.into())
}
}
impl HeapStRingBuffer {
/// Creates a new HeapStRingBuffer on the heap using the given size.
pub fn new(size: usize) -> Self {
HeapStRingBuffer{
data: vec![0; size].into_boxed_slice(),
state: Default::default(),
}
}
}
impl<const SIZE: usize> IntoIterator for StRingBuffer<SIZE> {
type Item = char;
type IntoIter = BufferIterator<StRingBuffer<SIZE>>;
fn into_iter(self) -> Self::IntoIter {
BufferIterator{
buffer: self
}
}
}
impl IntoIterator for HeapStRingBuffer {
type Item = char;
type IntoIter = BufferIterator<HeapStRingBuffer>;
fn into_iter(self) -> Self::IntoIter {
BufferIterator{
buffer: self
}
}
}
impl Write for HeapStRingBuffer {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
self.push_str(s);
Ok(())
}
fn write_char(&mut self, c: char) -> core::fmt::Result {
self.push_char(c);
Ok(())
}
}
/// An iterator for StringBuffer types.
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)]
pub struct BufferIterator<T>
where T: StringBuffer {
buffer: T,
}
impl<T> Iterator for BufferIterator<T>
where T: StringBuffer {
type Item = char;
fn next(&mut self) -> Option<Self::Item> {
self.buffer.pop()
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(self.buffer.len()))
}
fn last(mut self) -> Option<Self::Item> where Self: Sized {
let ret = self.buffer.pop_front();
self.buffer.clear();
ret
}
}
impl<T> DoubleEndedIterator for BufferIterator<T>
where T: StringBuffer {
fn next_back(&mut self) -> Option<Self::Item> {
self.buffer.pop_front()
}
}
impl<T> FusedIterator for BufferIterator<T> where T: StringBuffer {}
//-------------------------
const fn is_utf8_char_boundary(b: u8) -> bool {
// Stolen from core::num::mod, which keeps this function private
// This is bit magic equivalent to: b < 128 || b >= 192
(b as i8) >= -0x40
}
//Only returns None if 0 is not a char boundary--which is illegal state
fn prev_char_boundary(data: &[u8], start: usize) -> Option<usize> {
data[..=start].iter()
.rev()
.enumerate()
.find(|(_, b)| is_utf8_char_boundary(**b))
.map(|(i, _)| start - i)
}
fn next_char_boundary(data: &[u8], start: usize) -> Option<usize> {
data[start.min(data.len())..].iter()
.enumerate()
.find(|(_, b)| is_utf8_char_boundary(**b))
.map(|(i, _)| i + start)
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
enum State {
#[default]
Empty,
Straight{count: usize},
OffsetStraight{offset: usize, next: usize},
Looped{first: usize, end_offset: u8, next: usize}
}
impl State {
/// Returns the slice of data where the char should be inserted; modifying the state to prepare
/// for the insert if necessary.
fn get_char_slice<'a>(&'a mut self, char_len: usize, data: &'a mut [u8]) -> &'a mut [u8] {
debug_assert!(char_len < data.len());
match self {
State::Empty => {
*self = State::Straight { count: char_len };
data
}
State::OffsetStraight { offset, next } => {
if *next + char_len > data.len() {
//char doesn't fit in straight, need to convert to looped
let end_offset = (data.len() - *next).try_into().unwrap();
if char_len <= *offset {
//char fits before the offset
*self = State::Looped {
first: *offset,
end_offset,
next: char_len,
};
data
} else {
//offset needs to move
*self = match next_char_boundary(data, char_len) {
//nothing found, this should only happen if the buffer
//is small and adding this char overlaps the end and causes
//the char to be written from the start--clearing the existing buffer
None => State::Straight { count: char_len },
//new first found within straight
Some(first) =>
State::Looped {
first,
end_offset,
next: char_len,
},
};
data
}
} else {
//char fits as-is
*next += char_len;
&mut data[(*next - char_len)..*next]
}
}
State::Straight { count } => {
if *count + char_len > data.len() {
//char doesn't fit in straight, need to convert to looped
let end_offset = (data.len() - *count).try_into().unwrap();
*self = match next_char_boundary(&data[..*count], char_len) {
//nothing found, this should only happen if the buffer
//is small and adding this char overlaps the end and causes
//the char to be written from the start--clearing the existing buffer
None => State::Straight { count: char_len },
//new first found within straight
Some(first) =>
State::Looped {
first,
end_offset,
next: char_len,
},
};
data
} else {
//char fits as-is
*count += char_len;
&mut data[(*count - char_len)..*count]
}
}
State::Looped { first, end_offset, next } => {
if *first - *next < char_len {
//first needs to move
match next_char_boundary(data, *next + char_len) {
None => {
//first needs to loop back to the start (back to straight)
*self = State::Straight {count: *next};
// head down the straight pipeline
self.get_char_slice(char_len, data)
}
Some(new_first) => {
let next_copy = *next;
let new_next = next_copy + char_len;
if new_next > data.len() - *end_offset as usize {
//char insert overwrites end offset
*end_offset = (data.len() - new_next).try_into().unwrap();
}
*next = new_next;
*first = new_first;
&mut data[next_copy..new_next]
}
}
} else {
//big enough gap between first and next
let next_copy = *next;
*next = next_copy + char_len;
&mut data[next_copy..(next_copy + char_len)]
}
}
}
}
/// Inserts bytes into data, while ensuring the State remains valid.
///
/// Returns the number of bytes copied. If this is less than bytes.len() and the return value is
/// n then the bytes copied is `bytes[(bytes.len() - n)..]`.
///
/// # Safety
/// `bytes` must be a valid utf-8 sequence. If its not then any reads from `data` will result
/// in undefined behavior.
unsafe fn insert_bytes(&mut self, data: &mut [u8], bytes: &[u8]) -> usize {
if bytes.is_empty() { return 0 }
else if bytes.len() > data.len() {
let bytes_start_index = bytes.len() - data.len();
return match next_char_boundary(bytes, bytes_start_index) {
None => {
// there is no valid char boundary between where the split needs to be and the
// end. Treat the buffer like the start was written and then overwritten by
// later data and clear the buffer
*self = State::Empty;
0
}
Some(start_index) => {
data.copy_from_slice(&bytes[start_index..]);
*self = State::Straight {count: data.len()};
data.len()
}
};
} else if bytes.len() == data.len() {
data.copy_from_slice(bytes);
*self = State::Straight {count: data.len()};
return data.len();
}
match self {
State::Empty => {
let bytes_len = bytes.len();
let count = if bytes_len <= data.len() {
data[..bytes_len].copy_from_slice(bytes);
bytes_len
} else {
match next_char_boundary(bytes, bytes_len - data.len()) {
None => return 0,
Some(start) => {
let len = bytes_len - start;
data[..len].copy_from_slice(&bytes[start..]);
len
}
}
};
*self = State::Straight {count};
count
}
State::Straight { count } => {
let bytes_len = bytes.len();
if *count + bytes_len <= data.len() {
//everything fits
data[*count..(*count + bytes_len)].copy_from_slice(bytes);
*count += bytes_len;
} else {
// doesn't fit
// start by finding where to split bytes. The first half will be inserted after
// count, while the second half will loop back to the start
let first_len = data.len() - *count;
let index = prev_char_boundary(bytes, first_len)
.expect("Tried to insert bytes with malformed utf-8");
let (first, second) = bytes.split_at(index);
let end_offset = (first_len - first.len()).try_into().unwrap();
//copy first and calculate the end_offset
data[*count..(*count + first.len())].copy_from_slice(first);
data[..second.len()].copy_from_slice(second);
// find where the head should be
let search_range = if first.is_empty() {
// we didn't insert anything after count and we looped around so everything
// after count is "empty"
&data[..*count]
} else {
// if first was not empty then first may need to be the first char that
// was inserted from bytes
&data[..=*count]
};
match next_char_boundary(search_range, second.len()) {
None => *count = second.len(),
Some(new_first) => *self = State::Looped {
first: new_first,
end_offset,
next: second.len(),
},
};
}
bytes_len
}
State::OffsetStraight { offset, next } => {
let bytes_len = bytes.len();
if *next + bytes_len <= data.len() {
//everything fits
data[*next..(*next + bytes_len)].copy_from_slice(bytes);
*next += bytes_len;
} else {
// doesn't fit
// start by finding where to split bytes. The first half will be inserted after
// next, while the second half will loop back to the start
let first_len = data.len() - *next;
let index = prev_char_boundary(bytes, first_len)
.expect("Tried to insert bytes with malformed utf-8");
let (first, second) = bytes.split_at(index);
let end_offset = (first_len - first.len()).try_into().unwrap();
//copy first and calculate the end_offset
data[*next..(*next + first.len())].copy_from_slice(first);
data[..second.len()].copy_from_slice(second);
if second.len() > *offset {
// offset needs to move
// find where the head should be
let search_range = if first.is_empty() {
// we didn't insert anything after count and we looped around so everything
// after count is "empty"
&data[..*next]
} else {
// if first was not empty then first may need to be the first char that
// was inserted from bytes
&data[..=*next]
};
match next_char_boundary(search_range, second.len()) {
None => *next = second.len(),
Some(new_first) => *self = State::Looped {
first: new_first,
end_offset,
next: second.len(),
},
};
} else {
// offset stays, need to change to looped
*self = State::Looped {
first: *offset,
end_offset,
next: second.len()
};
}
}
bytes_len
}
State::Looped { first, end_offset, next } => {
if *first - *next >= bytes.len() {
// big enough gap between first and next to fit the bytes
data[*next..(*next + bytes.len())].copy_from_slice(bytes);
*next += bytes.len();
} else {
//first needs to move
match next_char_boundary(data, *first + bytes.len()) {
None => {
// first loops back to the start (straight)
*self = State::Straight {count: *next};
// finish in the straight pipeline
self.insert_bytes(data, bytes);
}
Some(new_first) => {
let new_next = *next + bytes.len();
if new_next > data.len() - *end_offset as usize {
//char insert overwrites end offset
*end_offset = (data.len() - new_next).try_into().unwrap();
}
data[*next..new_next].copy_from_slice(bytes);
*next = new_next;
*first = new_first;
}
}
}
// both branches always copy the whole byte slice
bytes.len()
}
}
}
}
#[cfg(test)]
mod tests {
use alloc::string::ToString;
use test_case::test_case;
use crate::{next_char_boundary, prev_char_boundary, StRingBuffer, StringBuffer, StringBufferError};
use crate::HeapStRingBuffer;
fn verify_empty(test: &impl StringBuffer) {
verify(test, 0, "", "");
}
fn verify(test: &impl StringBuffer, expected_len: usize, first: &str, second: &str) {
assert_eq!(test.len(), expected_len);
assert_eq!(test.is_empty(), expected_len == 0);
assert_eq!(test.as_slices().0, first);
assert_eq!(test.as_slices().1, second);
first.chars().chain(second.chars()).zip(test.chars()).for_each(|(expected, given)|assert_eq!(expected, given));
}
#[test_case(& mut StRingBuffer::< 5 >::new())]
#[test_case(& mut HeapStRingBuffer::new(5))]
fn basic(test: &mut impl StringBuffer){
verify_empty(test);
test.push_char('A');
verify(test, 1, "A", "");
test.push_str("BCDE");
verify(test, 5, "ABCDE", "");
test.push_char('X');
verify(test, 5, "BCDE", "X");
test.align();
verify(test, 5, "BCDEX", "");
test.clear();
verify_empty(test);
}
#[test_case(& mut StRingBuffer::< 5 >::new())]
#[test_case(& mut HeapStRingBuffer::new(5))]
fn basic_str(test: &mut impl StringBuffer) {
verify_empty(test);
test.push_str("ABC");
verify(test, 3, "ABC", "");
test.push_str("DE");
verify(test, 5, "ABCDE", "");
test.push_str("X");
verify(test, 5, "BCDE", "X");
test.align();
verify(test, 5, "BCDEX", "");
test.clear();
verify_empty(test);
}
#[test_case(& mut StRingBuffer::< 3 >::new())]
#[test_case(& mut HeapStRingBuffer::new(3))]
fn two_byte(test: &mut impl StringBuffer) {
verify_empty(test);
assert_eq!(test.capacity(), 3);
test.push_str("ABC");
//[^A, B, C*]
assert_eq!(test.len(), 3);
test.push_char('Ɵ'); //Latin Capital Letter O with Middle Tilde (0xC6 0x9F in UTF-8)
//[0xC6, 0x9F, *^C]
verify(test, 3, "C", "Ɵ");
test.push_char('X');
test.push_char('Y');
//[Y*, _, ^X]
verify(test, 2, "X", "Y");
//split on buffer end
test.push_char('Z');
//[Y, Z, *^X]
assert_eq!(test.len(), 3);
test.push_char('Ɵ');
//[^0xC6, 0x9F*, _]
verify(test, 2, "Ɵ", "");
test.push_char('ƛ'); //Latin Small Letter Lambda with Stroke (UTF-8: 0xC6 0x9B)
//[^0xC6, 0x9B*, _]
verify(test, 2, "ƛ", "");
//three bytes
test.push_char('Ꙃ'); //Cyrillic Capital Letter Dzelo (UTF-8: 0xEA 0x99 0x82)
//[^0xEA, 0x99, 0x82*]
verify(test, 3, "Ꙃ", "");
test.push_char('A');
//[^A*, _, _]
verify(test, 1, "A", "");
test.clear();
verify_empty(test);
}
#[test_case(& mut StRingBuffer::< 3 >::new())]
#[test_case(& mut HeapStRingBuffer::new(3))]
fn two_byte_str(test: &mut impl StringBuffer) {
verify_empty(test);
assert_eq!(test.capacity(), 3);
test.push_str("ABC");
//[^A, B, C*]
assert_eq!(test.len(), 3);
test.push_str("Ɵ"); //Latin Capital Letter O with Middle Tilde (0xC6 0x9F in UTF-8)
//[0xC6, 0x9F, *^C]
verify(test, 3, "C", "Ɵ");
test.push_str("XY");
//[Y*, _, ^X]
verify(test, 2, "X", "Y");
//split on buffer end
test.push_str("Z");
//[Y, Z, *^X]
verify(test, 3, "X", "YZ");
test.push_str("Ɵ");
//[^0xC6, 0x9F*, _]
verify(test, 2, "Ɵ", "");
test.push_str("ƛ"); //Latin Small Letter Lambda with Stroke (UTF-8: 0xC6 0x9B)
//[^0xC6, 0x9B*, _]
verify(test, 2, "ƛ", "");
//three bytes
test.push_str("Ꙃ"); //Cyrillic Capital Letter Dzelo (UTF-8: 0xEA 0x99 0x82)
//[^0xEA, 0x99, 0x82*]
verify(test, 3, "Ꙃ", "");
test.push_str("A");
//[^A*, _, _]
verify(test, 1, "A", "");
test.clear();
verify_empty(test);
}
#[test_case(& mut StRingBuffer::< 3 >::new())]
#[test_case(& mut HeapStRingBuffer::new(3))]
fn too_big(test: &mut impl StringBuffer) {
verify_empty(test);
//four bytes (too big for buffer)
test.push_char('🦀'); //Crab Emoji (Fat Ferris) (UTF-8: 0xF0 0x9F 0xA6 0x80)
//[^_*, _, _]
verify(test, 0, "", "");
test.clear();
verify_empty(test);
}
#[test_case(& mut StRingBuffer::< 3 >::new())]
#[test_case(& mut HeapStRingBuffer::new(3))]
fn too_big_str(test: &mut impl StringBuffer) {
verify_empty(test);
//four bytes (too big for buffer)
test.push_str("🦀"); //Crab Emoji (Fat Ferris) (UTF-8: 0xF0 0x9F 0xA6 0x80)
//[^_*, _, _]
verify(test, 0, "", "");
test.clear();
verify_empty(test);
}
#[test_case(& mut StRingBuffer::< 5 >::new())]
#[test_case(& mut HeapStRingBuffer::new(5))]
fn big_edge(test: &mut impl StringBuffer) {
verify_empty(test);
test.push_str("ABCD");
//[^A, B, C, D*, _]
verify(test, 4, "ABCD","");
test.push_char('ƛ'); //Latin Small Letter Lambda with Stroke (UTF-8: 0xC6 0x9B)
//[0xC6, 0x9B*, ^C, D, _]
verify(test, 4, "CD", "ƛ");
test.push_char('Ꙃ'); //Cyrillic Capital Letter Dzelo (UTF-8: 0xEA 0x99 0x82)
//[^0xC6, 0x9B, 0xEA, 0x99, 0x82*]
verify(test, 5, "ƛꙂ", "");
test.push_char('Ꙃ'); //Cyrillic Capital Letter Dzelo (UTF-8: 0xEA 0x99 0x82)
//[^0xEA, 0x99, 0x82*, _, _]
verify(test, 3, "Ꙃ", "");
test.clear();
verify_empty(test);
}
#[test_case(& mut StRingBuffer::< 5 >::new())]
#[test_case(& mut HeapStRingBuffer::new(5))]
fn big_edge_str(test: &mut impl StringBuffer) {
verify_empty(test);
test.push_str("ABCD");
//[^A, B, C, D*, _]
verify(test, 4, "ABCD","");
test.push_str("ƛ"); //Latin Small Letter Lambda with Stroke (UTF-8: 0xC6 0x9B)
//[0xC6, 0x9B*, ^C, D, _]
verify(test, 4, "CD", "ƛ");
test.push_str("Ꙃ"); //Cyrillic Capital Letter Dzelo (UTF-8: 0xEA 0x99 0x82)
//[^0xC6, 0x9B, 0xEA, 0x99, 0x82*]
verify(test, 5, "ƛꙂ", "");
test.push_str("Ꙃ"); //Cyrillic Capital Letter Dzelo (UTF-8: 0xEA 0x99 0x82)
//[^0xEA, 0x99, 0x82*, _, _]
verify(test, 3, "Ꙃ", "");
test.clear();
verify_empty(test);
}
#[test_case(& mut StRingBuffer::< 5 >::new())]
#[test_case(& mut HeapStRingBuffer::new(5))]
fn align(test: &mut impl StringBuffer) {
verify_empty(test);
test.push_str("ABCDE");
verify(test, 5, "ABCDE", "");
test.push_char('F');
verify(test, 5, "BCDE", "F");
test.align();
verify(test, 5, "BCDEF", "");
test.push_char('ƛ'); //Latin Small Letter Lambda with Stroke (UTF-8: 0xC6 0x9B)
verify(test, 5, "DEF", "ƛ");
test.align();
verify(test, 5, "DEFƛ", "");
test.push_char('Ꙃ'); //Cyrillic Capital Letter Dzelo (UTF-8: 0xEA 0x99 0x82)
verify(test, 5, "ƛ", "Ꙃ");
test.align();
verify(test, 5, "ƛꙂ", "");
test.clear();
verify_empty(test);
}
#[test_case(& mut StRingBuffer::< 5 >::new())]
#[test_case(& mut HeapStRingBuffer::new(5))]
fn align_linear(test: &mut impl StringBuffer) {
verify_empty(test);
test.push_str("ABCDE");
verify(test, 5, "ABCDE", "");
test.push_char('F');
verify(test, 5, "BCDE", "F");
test.align_no_alloc();
verify(test, 5, "BCDEF", "");
test.push_char('ƛ'); //Latin Small Letter Lambda with Stroke (UTF-8: 0xC6 0x9B)
verify(test, 5, "DEF", "ƛ");
test.align_no_alloc();
verify(test, 5, "DEFƛ", "");
test.push_char('Ꙃ'); //Cyrillic Capital Letter Dzelo (UTF-8: 0xEA 0x99 0x82)
verify(test, 5, "ƛ", "Ꙃ");
test.align_no_alloc();
verify(test, 5, "ƛꙂ", "");
test.clear();
verify_empty(test);
}
#[test]
fn next_char_boundary_simple() {
let data = "ABCD".as_bytes();
assert_eq!(next_char_boundary(data, 0), Some(0));
assert_eq!(next_char_boundary(data, 1), Some(1));
assert_eq!(next_char_boundary(data, 2), Some(2));
assert_eq!(next_char_boundary(data, 3), Some(3));
}
#[test]
fn next_char_boundary_two_byte() {
let data = "AƟB".as_bytes();
assert_eq!(next_char_boundary(data,0), Some(0));
assert_eq!(next_char_boundary(data,1), Some(1));
assert_eq!(next_char_boundary(data,2), Some(3));
assert_eq!(next_char_boundary(data,3), Some(3));
}
#[test]
fn next_char_boundary_three_byte() {
let data = "ꙂB".as_bytes();
assert_eq!(next_char_boundary(data, 0), Some(0));
assert_eq!(next_char_boundary(data,1), Some(3));
assert_eq!(next_char_boundary(data,2), Some(3));
assert_eq!(next_char_boundary(data,3), Some(3));
}
#[test]
fn next_char_boundary_none() {
let data = "AꙂ".as_bytes();
assert_eq!(next_char_boundary(data, 0), Some(0));
assert_eq!(next_char_boundary(data,1), Some(1));
assert_eq!(next_char_boundary(data,2), None);
assert_eq!(next_char_boundary(data,3), None);
}
#[test]
fn prev_char_boundary_simple() {
let data = "ABCD".as_bytes();
assert_eq!(prev_char_boundary(data, 0), Some(0));
assert_eq!(prev_char_boundary(data, 1), Some(1));
assert_eq!(prev_char_boundary(data, 2), Some(2));
assert_eq!(prev_char_boundary(data, 3), Some(3));
}
#[test]
fn prev_char_boundary_two_byte() {
let data = "AƟB".as_bytes();
assert_eq!(prev_char_boundary(data,0), Some(0));
assert_eq!(prev_char_boundary(data,1), Some(1));
assert_eq!(prev_char_boundary(data,2), Some(1));
assert_eq!(prev_char_boundary(data,3), Some(3));
}
#[test]
fn prev_char_boundary_three_byte() {
let data = "ꙂB".as_bytes();
assert_eq!(prev_char_boundary(data, 0), Some(0));
assert_eq!(prev_char_boundary(data,1), Some(0));
assert_eq!(prev_char_boundary(data,2), Some(0));
assert_eq!(prev_char_boundary(data,3), Some(3));
}
#[test]
fn prev_char_boundary_none() {
let data = "AꙂ".as_bytes();
assert_eq!(prev_char_boundary(data, 0), Some(0));
assert_eq!(prev_char_boundary(data,1), Some(1));
assert_eq!(prev_char_boundary(data,2), Some(1));
assert_eq!(prev_char_boundary(data,3), Some(1));
}
#[test]
fn from_string() {
let mut buffer: HeapStRingBuffer = "ABCDE".to_string().into();
verify(&mut buffer, 5, "ABCDE", "");
buffer.clear();
basic(&mut buffer);
}
#[test]
fn from_vec() {
let mut buffer: HeapStRingBuffer = "ABCDE".as_bytes().to_vec().try_into().unwrap();
verify(&mut buffer, 5, "ABCDE", "");
buffer.clear();
basic(&mut buffer);
}
#[test]
fn from_box_slice() {
let mut buffer: HeapStRingBuffer = "ABCDE".as_bytes().to_vec().into_boxed_slice().try_into().unwrap();
verify(&mut buffer, 5, "ABCDE", "");
buffer.clear();
basic(&mut buffer);
}
#[test]
fn test_send() {
fn assert_send<T: Send>() {}
assert_send::<StRingBuffer<0>>();
assert_send::<HeapStRingBuffer>();
}
#[test]
fn test_sync() {
fn assert_sync<T: Sync>() {}
assert_sync::<StRingBuffer<0>>();
assert_sync::<HeapStRingBuffer>();
}
#[test_case(& mut StRingBuffer::< 3 >::new())]
#[test_case(& mut HeapStRingBuffer::new(3))]
fn try_char(test: &mut impl StringBuffer) {
verify_empty(test);
//four bytes (too big for buffer)
let res = test.try_push_char('🦀'); //Crab Emoji (Fat Ferris) (UTF-8: 0xF0 0x9F 0xA6 0x80)
//[^_*, _, _]
assert_eq!(res, Err(StringBufferError::NotEnoughSpaceForChar));
verify(test, 0, "", "");
let res = test.try_push_char('Ꙃ'); //Cyrillic Capital Letter Dzelo (UTF-8: 0xEA 0x99 0x82)
//[^0xEA, 0x99, 0x82*]
assert_eq!(res, Ok(3));
verify(test, 3, "Ꙃ", "");
let res = test.try_push_char('A');
assert_eq!(res, Err(StringBufferError::BufferFull));
verify(test, 3, "Ꙃ", "");
test.push_str("AB");
//[^A, B, *_]
let res = test.try_push_char('Ꙃ'); //Cyrillic Capital Letter Dzelo (UTF-8: 0xEA 0x99 0x82)
assert_eq!(res, Err(StringBufferError::NotEnoughSpaceForChar));
verify(test, 2, "AB", "");
test.clear();
verify_empty(test);
}
#[test_case(& mut StRingBuffer::< 3 >::new())]
#[test_case(& mut HeapStRingBuffer::new(3))]
fn try_push_some(test: &mut impl StringBuffer) {
verify_empty(test);
//four bytes (too big for buffer)
let res = test.try_push_some("🦀"); //Crab Emoji (Fat Ferris) (UTF-8: 0xF0 0x9F 0xA6 0x80)
//[^_*, _, _]
assert_eq!(res, Err(StringBufferError::NotEnoughSpaceForStr));
verify_empty(test);
let res = test.try_push_some("ƛƛ"); //Latin Small Letter Lambda with Stroke (UTF-8: 0xC6 0x9B)
//[^0xC6, 0x9B, _*]
assert_eq!(res, Ok(2));
verify(test, 2, "ƛ", "");
test.clear();
let res = test.try_push_some("ABCD");
//[^A, B, C]*
assert_eq!(res, Ok(3));
verify(test, 3, "ABC", "");
let res = test.try_push_some("XYZ");
//[^A, B, C]*
assert_eq!(res, Err(StringBufferError::BufferFull));
verify(test, 3, "ABC", "");
test.push_char('X');
//[X, ^*B, C]
verify(test, 3, "BC", "X");
let res = test.try_push_some("YZ");
//[X, ^*B, C]
assert_eq!(res, Err(StringBufferError::BufferFull));
verify(test, 3, "BC", "X");
}
#[test_case(& mut StRingBuffer::< 3 >::new())]
#[test_case(& mut HeapStRingBuffer::new(3))]
fn try_str_all(test: &mut impl StringBuffer) {
verify_empty(test);
//four bytes (too big for buffer)
let res = test.try_push_all("🦀"); //Crab Emoji (Fat Ferris) (UTF-8: 0xF0 0x9F 0xA6 0x80)
//[^_*, _, _]
assert_eq!(res, Err(StringBufferError::NotEnoughSpaceForStr));
verify_empty(test);
let res = test.try_push_all("ƛƛ"); //Latin Small Letter Lambda with Stroke (UTF-8: 0xC6 0x9B)
//[^0xC6, 0x9B, _*]
assert_eq!(res, Err(StringBufferError::NotEnoughSpaceForStr));
verify_empty(test);
let res = test.try_push_all("ABCD");
//[^_*, _, _]
assert_eq!(res, Err(StringBufferError::NotEnoughSpaceForStr));
verify(test, 0, "", "");
let res = test.try_push_all("XYZ");
//[^X, Y, Z]*
assert_eq!(res, Ok(()));
verify(test, 3, "XYZ", "");
let res = test.try_push_all("ABC");
//[^X, Y, Z]*
assert_eq!(res, Err(StringBufferError::BufferFull));
verify(test, 3, "XYZ", "");
test.push_char('A');
//[A, ^*Y, Z]
verify(test, 3, "YZ", "A");
let res = test.try_push_all("BC");
//[A, ^*Y, Z]
assert_eq!(res, Err(StringBufferError::BufferFull));
verify(test, 3, "YZ", "A");
}
#[test_case(& mut StRingBuffer::< 4 >::new())]
#[test_case(& mut HeapStRingBuffer::new(4))]
fn big_char_small_gap(test: &mut impl StringBuffer) {
verify_empty(test);
test.push_str("ƛCD"); //Latin Small Letter Lambda with Stroke (UTF-8: 0xC6 0x9B)
test.push_char('E');
//[E, *_, ^C, D]
verify(test, 3, "CD", "E");
test.push_char('ƛ');
//[E, 0xC6, 0x9B, ^*D]
verify(test, 4, "D", "Eƛ");
}
#[test_case(& mut StRingBuffer::< 4 >::new())]
#[test_case(& mut HeapStRingBuffer::new(4))]
fn pop_char(test: &mut impl StringBuffer) {
//Empty
assert_eq!(test.pop(), None);
//Straight
test.push_char('A');
assert_eq!(test.pop(), Some('A'));
test.push_str("ƛƛ"); //Latin Small Letter Lambda with Stroke (UTF-8: 0xC6 0x9B)
assert_eq!(test.pop(), Some('ƛ'));
verify(test, 2, "ƛ", "");
assert_eq!(test.pop(), Some('ƛ'));
verify_empty(test);
assert_eq!(test.pop(), None);
//Looped
test.push_str("ABCD");
test.push_char('E');
//[E, ^*B, C, D]
assert_eq!(test.pop(), Some('E'));
//[_, ^B, C, D]*
verify(test, 3, "BCD", "");
test.push_char('ƛ');
//[0xC6, 0x9B, ^*C, D]
verify(test, 4, "CD", "ƛ");
assert_eq!(test.pop(), Some('ƛ'));
verify(test, 2, "CD", "");
}
#[test_case(& mut StRingBuffer::< 4 >::new())]
#[test_case(& mut HeapStRingBuffer::new(4))]
fn pop_to_empty(test: &mut impl StringBuffer) {
verify_empty(test);
//Straight
test.push_str("ABCD");
assert_eq!(test.pop(), Some('D'));
assert_eq!(test.pop(), Some('C'));
assert_eq!(test.pop(), Some('B'));
assert_eq!(test.pop(), Some('A'));
assert_eq!(test.pop(), None);
verify_empty(test);
//Looped
test.push_str("ABCD");
test.push_char('ƛ');
assert_eq!(test.pop(), Some('ƛ'));
assert_eq!(test.pop(), Some('D'));
assert_eq!(test.pop(), Some('C'));
assert_eq!(test.pop(), None);
verify_empty(test);
}
#[test_case(& mut StRingBuffer::< 4 >::new())]
#[test_case(& mut HeapStRingBuffer::new(4))]
fn pop_front(test: &mut impl StringBuffer) {
//Empty
assert_eq!(test.pop(), None);
//Straight
test.push_char('A');
assert_eq!(test.pop_front(), Some('A'));
test.push_str("ƛƛ"); //Latin Small Letter Lambda with Stroke (UTF-8: 0xC6 0x9B)
assert_eq!(test.pop_front(), Some('ƛ'));
verify(test, 2, "ƛ", "");
assert_eq!(test.pop_front(), Some('ƛ'));
verify_empty(test);
assert_eq!(test.pop_front(), None);
//Looped
test.push_str("ABCD");
test.push_char('E');
//[E, ^*B, C, D]
assert_eq!(test.pop_front(), Some('B'));
//[E, *_, ^C, D]
verify(test, 3, "CD", "E");
test.push_char('ƛ');
//[E, 0xC6, 0x9B, ^*D]
verify(test, 4, "D", "Eƛ");
assert_eq!(test.pop_front(), Some('D'));
verify(test, 3, "Eƛ", "");
}
#[test_case(& mut StRingBuffer::< 4 >::new())]
#[test_case(& mut HeapStRingBuffer::new(4))]
fn pop_front_to_empty(test: &mut impl StringBuffer) {
verify_empty(test);
//Straight
test.push_str("ABCD");
assert_eq!(test.pop_front(), Some('A'));
assert_eq!(test.pop_front(), Some('B'));
assert_eq!(test.pop_front(), Some('C'));
assert_eq!(test.pop_front(), Some('D'));
assert_eq!(test.pop_front(), None);
verify_empty(test);
//Looped
test.push_str("ABCD");
test.push_char('ƛ');
assert_eq!(test.pop_front(), Some('C'));
assert_eq!(test.pop_front(), Some('D'));
assert_eq!(test.pop_front(), Some('ƛ'));
assert_eq!(test.pop_front(), None);
verify_empty(test);
}
}