Skip to content

Commit

Permalink
Correctly handle Vec with zero capacity in from_vec (#332)
Browse files Browse the repository at this point in the history
* 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 <bruce.mitchener@gmail.com>
  • Loading branch information
matzemathics and waywardmonkeys authored Jan 13, 2024
1 parent b955ac6 commit 944f603
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 9 deletions.
14 changes: 6 additions & 8 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,14 @@ jobs:
toolchain: ["stable", "beta", "nightly", "1.57.0"]
include:
- toolchain: stable
env:
DO_FUZZ: 1
fuzz: 1
- toolchain: beta
env:
DO_FUZZ: 1
fuzz: 1
steps:
- uses: actions/checkout@v4

- name: Install packages
if: matrix.os == 'ubuntu-latest'
- name: Install packages for fuzzing
if: runner.os == 'Linux' && matrix.fuzz == 1
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

- name: Install toolchain
Expand Down Expand Up @@ -60,9 +58,9 @@ jobs:
MIRIFLAGS: '-Zmiri-tag-raw-pointers'

- name: fuzz
if: env.DO_FUZZ == '1'
if: matrix.fuzz == 1
working-directory: fuzz
run: ./travis_fuzz.sh
run: ./travis-fuzz.sh

no-std:
name: no_std
Expand Down
2 changes: 1 addition & 1 deletion fuzz/travis-fuzz.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#!/bin/bash
set -e
cargo install --force honggfuzz --version 0.5.47
cargo install --force honggfuzz --version "^0.5.47"
for TARGET in fuzz_targets/*; do
FILENAME=$(basename $TARGET)
FILE="${FILENAME%.*}"
Expand Down
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,10 @@ impl<T, const N: usize> SmallVec<T, N> {

#[inline]
pub fn from_vec(vec: Vec<T>) -> Self {
if vec.capacity() == 0 {
return Self::new();
}

if Self::is_zst() {
// "Move" elements to stack buffer. They're ZST so we don't actually have to do
// anything. Just make sure they're not dropped.
Expand Down
7 changes: 7 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,13 @@ fn shrink_to_fit_unspill() {
assert!(!vec.spilled(), "shrink_to_fit will un-spill if possible");
}

#[test]
fn shrink_after_from_empty_vec() {
let mut v = SmallVec::<u8, 2>::from_vec(vec![]);
v.shrink_to_fit();
assert!(!v.spilled())
}

#[test]
fn test_into_vec() {
let vec = SmallVec::<u8, 2>::from_iter(0..2);
Expand Down

0 comments on commit 944f603

Please sign in to comment.