Skip to content

Commit 944f603

Browse files
Correctly handle Vec with zero capacity in from_vec (#332)
* ci: Fix running fuzz. * from_vec: early return if capacity zero When the capacity of the vec it zero, there might not have been any memory allocated for it, thus the pointer obtained by `as_mut_ptr` may dangle. --------- Co-authored-by: Bruce Mitchener <[email protected]>
1 parent b955ac6 commit 944f603

File tree

4 files changed

+18
-9
lines changed

4 files changed

+18
-9
lines changed

.github/workflows/main.yml

+6-8
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,14 @@ jobs:
1515
toolchain: ["stable", "beta", "nightly", "1.57.0"]
1616
include:
1717
- toolchain: stable
18-
env:
19-
DO_FUZZ: 1
18+
fuzz: 1
2019
- toolchain: beta
21-
env:
22-
DO_FUZZ: 1
20+
fuzz: 1
2321
steps:
2422
- uses: actions/checkout@v4
2523

26-
- name: Install packages
27-
if: matrix.os == 'ubuntu-latest'
24+
- name: Install packages for fuzzing
25+
if: runner.os == 'Linux' && matrix.fuzz == 1
2826
run: sudo apt-get update -y && sudo apt-get install -y binutils-dev libunwind8-dev libcurl4-openssl-dev libelf-dev libdw-dev cmake gcc libiberty-dev
2927

3028
- name: Install toolchain
@@ -60,9 +58,9 @@ jobs:
6058
MIRIFLAGS: '-Zmiri-tag-raw-pointers'
6159

6260
- name: fuzz
63-
if: env.DO_FUZZ == '1'
61+
if: matrix.fuzz == 1
6462
working-directory: fuzz
65-
run: ./travis_fuzz.sh
63+
run: ./travis-fuzz.sh
6664

6765
no-std:
6866
name: no_std

fuzz/travis-fuzz.sh

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/bin/bash
22
set -e
3-
cargo install --force honggfuzz --version 0.5.47
3+
cargo install --force honggfuzz --version "^0.5.47"
44
for TARGET in fuzz_targets/*; do
55
FILENAME=$(basename $TARGET)
66
FILE="${FILENAME%.*}"

src/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,10 @@ impl<T, const N: usize> SmallVec<T, N> {
524524

525525
#[inline]
526526
pub fn from_vec(vec: Vec<T>) -> Self {
527+
if vec.capacity() == 0 {
528+
return Self::new();
529+
}
530+
527531
if Self::is_zst() {
528532
// "Move" elements to stack buffer. They're ZST so we don't actually have to do
529533
// anything. Just make sure they're not dropped.

src/tests.rs

+7
Original file line numberDiff line numberDiff line change
@@ -717,6 +717,13 @@ fn shrink_to_fit_unspill() {
717717
assert!(!vec.spilled(), "shrink_to_fit will un-spill if possible");
718718
}
719719

720+
#[test]
721+
fn shrink_after_from_empty_vec() {
722+
let mut v = SmallVec::<u8, 2>::from_vec(vec![]);
723+
v.shrink_to_fit();
724+
assert!(!v.spilled())
725+
}
726+
720727
#[test]
721728
fn test_into_vec() {
722729
let vec = SmallVec::<u8, 2>::from_iter(0..2);

0 commit comments

Comments
 (0)