Skip to content

Commit

Permalink
Use built-in try_reserve
Browse files Browse the repository at this point in the history
  • Loading branch information
kornelski committed Jul 19, 2022
1 parent 5feb415 commit aed9e2e
Show file tree
Hide file tree
Showing 10 changed files with 30 additions and 29 deletions.
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ doctest = false

[dependencies]
arrayvec = "0.7.2"
fallible_collections = "0.4.4"
noisy_float = "0.2.0"
rgb = { version = "0.8.31", features = ["argb"] }
rayon = { version = "1.5.1", optional = true }
Expand Down
4 changes: 2 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use fallible_collections::TryReserveError;
pub use Error::*;
use std::collections::TryReserveError;
use std::fmt;
pub use Error::*;

/// Error codes
#[cfg_attr(feature = "_internal_c_ffi", repr(C))]
Expand Down
9 changes: 5 additions & 4 deletions src/hist.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
use crate::error::*;
use crate::image::Image;
use crate::pal::MAX_COLORS;
use crate::pal::PalIndex;
use crate::pal::ARGBF;
use crate::pal::MAX_COLORS;
use crate::pal::{f_pixel, gamma_lut, RGBA};
use crate::quant::QuantizationResult;
use crate::rows::temp_buf;
use crate::rows::DynamicRows;
use crate::Attributes;
use fallible_collections::FallibleVec;
use rgb::ComponentSlice;
use std::collections::{HashMap, HashSet};
use std::convert::TryInto;
Expand Down Expand Up @@ -262,7 +261,8 @@ impl Histogram {
debug_assert!(gamma > 0.);

let mut counts = [0; LIQ_MAXCLUSTER];
let mut temp: Vec<_> = FallibleVec::try_with_capacity(self.hashmap.len())?;
let mut temp = Vec::new();
temp.try_reserve_exact(self.hashmap.len())?;
// Limit perceptual weight to 1/10th of the image surface area to prevent
// a single color from dominating all others.
let max_perceptual_weight = 0.1 * self.total_area as f32;
Expand Down Expand Up @@ -308,7 +308,8 @@ impl Histogram {
next_begin += count;
}

let mut items: Vec<_> = FallibleVec::try_with_capacity(temp.len())?;
let mut items = Vec::new();
items.try_reserve_exact(temp.len())?;
items.resize(temp.len(), HistItem {
color: if cfg!(debug_assertions) { f_pixel( ARGBF { r:f32::NAN, g:f32::NAN, b:f32::NAN, a:f32::NAN } ) } else { f_pixel::default() },
adjusted_weight: if cfg!(debug_assertions) { f32::NAN } else { 0. },
Expand Down
7 changes: 4 additions & 3 deletions src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ use crate::rows::{DynamicRows, PixelsSource};
use crate::seacow::RowBitmap;
use crate::seacow::SeaCow;
use crate::LIQ_HIGH_MEMORY_LIMIT;
use fallible_collections::FallibleVec;
use rgb::ComponentMap;
use std::mem::MaybeUninit;

Expand Down Expand Up @@ -205,7 +204,8 @@ impl<'pixels> Image<'pixels> {
pub fn add_fixed_color(&mut self, color: RGBA) -> Result<(), Error> {
if self.fixed_colors.len() >= MAX_COLORS { return Err(Unsupported); }
let lut = gamma_lut(self.px.gamma);
self.fixed_colors.try_push(f_pixel::from_rgba(&lut, RGBA {r: color.r, g: color.g, b: color.b, a: color.a}))?;
self.fixed_colors.try_reserve(1)?;
self.fixed_colors.push(f_pixel::from_rgba(&lut, RGBA {r: color.r, g: color.g, b: color.b, a: color.a}));
Ok(())
}

Expand Down Expand Up @@ -335,7 +335,8 @@ impl<'pixels> Image<'pixels> {
}

fn try_zero_vec(len: usize) -> Result<Vec<u8>, Error> {
let mut vec: Vec<_> = FallibleVec::try_with_capacity(len)?;
let mut vec = Vec::new();
vec.try_reserve_exact(len)?;
vec.resize(len, 0);
Ok(vec)
}
10 changes: 5 additions & 5 deletions src/kmeans.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use crate::Error;
use crate::hist::{HistItem, HistogramInternal};
use crate::nearest::Nearest;
use crate::pal::{PalF, PalIndex, PalPop, f_pixel};
use fallible_collections::FallibleVec;
use crate::pal::{f_pixel, PalF, PalIndex, PalPop};
use crate::rayoff::*;
use crate::Error;
use rgb::alt::ARGB;
use rgb::ComponentMap;
use std::cell::RefCell;
use crate::rayoff::*;

pub(crate) struct Kmeans {
averages: Vec<ColorAvg>,
Expand All @@ -23,7 +22,8 @@ struct ColorAvg {
impl Kmeans {
#[inline]
pub fn new(pal_len: usize) -> Result<Self, Error> {
let mut averages: Vec<_> = FallibleVec::try_with_capacity(pal_len)?;
let mut averages = Vec::new();
averages.try_reserve_exact(pal_len)?;
averages.resize(pal_len, ColorAvg::default());
Ok(Self {
averages,
Expand Down
4 changes: 2 additions & 2 deletions src/mediancut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use crate::pal::{f_pixel, PalF, PalPop};
use crate::pal::{PalLen, ARGBF};
use crate::quant::quality_to_mse;
use crate::{OrdFloat, Error};
use fallible_collections::FallibleVec;
use rgb::ComponentMap;
use rgb::ComponentSlice;
use std::cmp::Reverse;
Expand Down Expand Up @@ -232,7 +231,8 @@ impl<'hist> MedianCutter<'hist> {
debug_assert!(hist.clusters.last().unwrap().end as usize == hist.items.len());

let mut hist_items = &mut hist.items[..];
let mut boxes: Vec<_> = FallibleVec::try_with_capacity(target_colors as usize)?;
let mut boxes = Vec::new();
boxes.try_reserve(target_colors as usize)?;

let used_boxes = hist.clusters.iter().filter(|b| b.begin != b.end).count();
if used_boxes <= target_colors as usize / 3 {
Expand Down
4 changes: 2 additions & 2 deletions src/nearest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use crate::pal::MAX_COLORS;
use crate::pal::PalIndex;
use crate::pal::{f_pixel, PalF};
use crate::{OrdFloat, Error};
use fallible_collections::FallibleVec;

impl<'pal> Nearest<'pal> {
#[inline(never)]
Expand Down Expand Up @@ -131,7 +130,8 @@ fn vp_create_node(indexes: &mut [MapIndex], items: &PalF) -> Result<Node, Error>
let radius = radius_squared.sqrt();

let (near, far, rest) = if num_indexes < 7 {
let mut rest: Vec<_> = FallibleVec::try_with_capacity(num_indexes)?;
let mut rest = Vec::new();
rest.try_reserve_exact(num_indexes)?;
rest.extend(near.iter().chain(far.iter()).map(|i| Leaf {
idx: i.idx,
color: palette[usize::from(i.idx)],
Expand Down
11 changes: 6 additions & 5 deletions src/quant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ use crate::remap::{mse_to_standard_mse, DitherMapMode, Remapped};
use crate::seacow::RowBitmapMut;
use crate::OrdFloat;
use arrayvec::ArrayVec;
use fallible_collections::FallibleVec;
use std::cmp::Reverse;
use std::fmt;
use std::mem::MaybeUninit;
Expand Down Expand Up @@ -184,10 +183,11 @@ impl QuantizationResult {
let len = image.width() * image.height();
// Capacity is essential here, as it creates uninitialized buffer
unsafe {
let mut buf: Vec<u8> = FallibleVec::try_with_capacity(len)?;
let uninit_slice = std::slice::from_raw_parts_mut(buf.as_mut_ptr().cast::<MaybeUninit<u8>>(), buf.capacity());
let mut buf = Vec::new();
buf.try_reserve_exact(len)?;
let uninit_slice = &mut buf.spare_capacity_mut()[..len];
self.remap_into(image, uninit_slice)?;
buf.set_len(uninit_slice.len());
buf.set_len(len);
Ok((self.palette_vec(), buf))
}
}
Expand Down Expand Up @@ -215,7 +215,8 @@ impl QuantizationResult {
#[must_use]
pub fn palette_vec(&mut self) -> Vec<RGBA> {
let pal = self.palette();
let mut out: Vec<RGBA> = FallibleVec::try_with_capacity(pal.len()).unwrap();
let mut out: Vec<RGBA> = Vec::new();
out.try_reserve_exact(pal.len()).unwrap();
out.extend_from_slice(pal);
out
}
Expand Down
4 changes: 2 additions & 2 deletions src/remap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use crate::pal::{ARGBF, LIQ_WEIGHT_MSE, MIN_OPAQUE_A, PalF, PalIndex, Palette, f
use crate::quant::{quality_to_mse, QuantizationResult};
use crate::rows::temp_buf;
use crate::seacow::{RowBitmap, RowBitmapMut};
use fallible_collections::FallibleVec;
use crate::rayoff::*;
use std::cell::RefCell;
use std::mem::MaybeUninit;
Expand Down Expand Up @@ -161,7 +160,8 @@ pub(crate) fn remap_to_palette_floyd(input_image: &mut Image, mut output_pixels:
let mut background = input_image.background.as_mut().map(|bg| bg.px.rows_iter(&mut temp_row)).transpose()?;

let errwidth = width + 2; // +2 saves from checking out of bounds access
let mut thiserr_data: Vec<_> = FallibleVec::try_with_capacity(errwidth * 2)?;
let mut thiserr_data = Vec::new();
thiserr_data.try_reserve_exact(errwidth * 2)?;
thiserr_data.resize(errwidth * 2, f_pixel::default());
let (mut thiserr, mut nexterr) = thiserr_data.split_at_mut(errwidth);
let n = Nearest::new(&quant.palette)?;
Expand Down
5 changes: 2 additions & 3 deletions src/rows.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use fallible_collections::FallibleVec;

use crate::error::*;
use crate::pal::{f_pixel, gamma_lut, RGBA};
use crate::seacow::SeaCow;
Expand Down Expand Up @@ -197,7 +195,8 @@ impl<'pixels,'rows> DynamicRows<'pixels,'rows> {
}

pub(crate) fn temp_buf<T>(len: usize) -> Result<Box<[MaybeUninit<T>]>, Error> {
let mut v: Vec<_> = FallibleVec::try_with_capacity(len)?;
let mut v = Vec::new();
v.try_reserve_exact(len)?;
unsafe { v.set_len(len) };
Ok(v.into_boxed_slice())
}
Expand Down

0 comments on commit aed9e2e

Please sign in to comment.