Skip to content

Commit a8d7b66

Browse files
committed
Start to implement Borsh Write by reusing the write function, wrap std
1 parent 7559fc5 commit a8d7b66

2 files changed

Lines changed: 41 additions & 5 deletions

File tree

src/arrayvec.rs

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1340,17 +1340,26 @@ where
13401340
}
13411341
}
13421342

1343+
impl<const CAP: usize> ArrayVec<u8, CAP> {
1344+
/// `Write` appends written data to the end of the vector.
1345+
pub fn write(&mut self, data: &[u8]) -> usize {
1346+
let len = cmp::min(self.remaining_capacity(), data.len());
1347+
let _result = self.try_extend_from_slice(&data[..len]);
1348+
debug_assert!(_result.is_ok());
1349+
len
1350+
}
1351+
}
1352+
13431353
#[cfg(feature = "std")]
13441354
/// `Write` appends written data to the end of the vector.
1355+
/// Wraps the existing write function.
13451356
///
13461357
/// Requires `features="std"`.
13471358
impl<const CAP: usize> io::Write for ArrayVec<u8, CAP> {
13481359
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
1349-
let len = cmp::min(self.remaining_capacity(), data.len());
1350-
let _result = self.try_extend_from_slice(&data[..len]);
1351-
debug_assert!(_result.is_ok());
1352-
Ok(len)
1360+
Ok(ArrayVec::write(self, data))
13531361
}
1362+
13541363
fn flush(&mut self) -> io::Result<()> {
13551364
Ok(())
13561365
}
@@ -1419,6 +1428,33 @@ where
14191428
}
14201429
}
14211430

1431+
#[cfg(all(feature = "borsh", not(feature = "std")))]
1432+
/// Requires crate feature `"borsh"`
1433+
impl<const CAP: usize> borsh::io::Write for ArrayVec<u8, CAP> {
1434+
fn write(&mut self, data: &[u8]) -> borsh::io::Result<usize> {
1435+
Ok(ArrayVec::write(self, data))
1436+
}
1437+
1438+
fn write_all(&mut self, mut buf: &[u8]) -> borsh::io::Result<()> {
1439+
while !buf.is_empty() {
1440+
match self.write(buf) {
1441+
0 => {
1442+
return Err(borsh::io::Error::new(
1443+
borsh::io::ErrorKind::WriteZero,
1444+
"failed to write whole buffer",
1445+
));
1446+
}
1447+
n => buf = &buf[n..],
1448+
}
1449+
}
1450+
Ok(())
1451+
}
1452+
1453+
fn flush(&mut self) -> borsh::io::Result<()> {
1454+
Ok(())
1455+
}
1456+
}
1457+
14221458
#[cfg(feature = "borsh")]
14231459
/// Requires crate feature `"borsh"`
14241460
impl<T, const CAP: usize> borsh::BorshDeserialize for ArrayVec<T, CAP>

tests/tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -490,7 +490,7 @@ fn test_write() {
490490
let mut v = ArrayVec::<_, 8>::new();
491491
write!(&mut v, "\x01\x02\x03").unwrap();
492492
assert_eq!(&v[..], &[1, 2, 3]);
493-
let r = v.write(&[9; 16]).unwrap();
493+
let r = v.write(&[9; 16]);
494494
assert_eq!(r, 5);
495495
assert_eq!(&v[..], &[1, 2, 3, 9, 9, 9, 9, 9]);
496496
}

0 commit comments

Comments
 (0)