Skip to content

Commit 755f9c0

Browse files
committed
Try using no-std types
(cherry picked from commit c35147c0477b727221ed237368a0dea75e47fad5)
1 parent 29a1825 commit 755f9c0

File tree

15 files changed

+95
-93
lines changed

15 files changed

+95
-93
lines changed

benches/bench.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#![feature(test)]
22

33
extern crate test;
4+
use core::mem::MaybeUninit;
45
use test::Bencher;
56

67
use imagequant::*;
@@ -19,7 +20,7 @@ fn histogram(b: &mut Bencher) {
1920
#[bench]
2021
fn remap_ord(b: &mut Bencher) {
2122
let img = lodepng::decode32_file("/Users/kornel/Desktop/canvas.png").unwrap();
22-
let mut buf = vec![std::mem::MaybeUninit::uninit(); img.width * img.height];
23+
let mut buf = vec![MaybeUninit::uninit(); img.width * img.height];
2324
let mut liq = Attributes::new();
2425
liq.set_speed(10).unwrap();
2526
let mut img = liq.new_image(img.buffer, img.width, img.height, 0.).unwrap();
@@ -40,7 +41,7 @@ fn kmeans(b: &mut Bencher) {
4041
#[bench]
4142
fn remap_floyd(b: &mut Bencher) {
4243
let img = lodepng::decode32_file("/Users/kornel/Desktop/canvas.png").unwrap();
43-
let mut buf = vec![std::mem::MaybeUninit::uninit(); img.width * img.height];
44+
let mut buf = vec![MaybeUninit::uninit(); img.width * img.height];
4445
let mut liq = Attributes::new();
4546
liq.set_speed(10).unwrap();
4647
let mut img = liq.new_image(img.buffer, img.width, img.height, 0.).unwrap();

imagequant-sys/src/ffi.rs

Lines changed: 18 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,13 @@
88
#![allow(clippy::cast_possible_truncation)]
99
#![allow(clippy::cast_possible_wrap)]
1010

11+
use core::ffi::{c_char, c_int, c_uint, c_void};
12+
use core::mem::{ManuallyDrop, MaybeUninit};
13+
use core::{mem, ptr, slice};
1114
use imagequant::capi::*;
1215
use imagequant::Error::LIQ_OK;
1316
use imagequant::*;
1417
use std::ffi::CString;
15-
use std::mem::{ManuallyDrop, MaybeUninit};
16-
use std::os::raw::{c_char, c_int, c_uint, c_void};
17-
use std::ptr;
1818

1919
pub use imagequant::Error as liq_error;
2020

@@ -191,9 +191,9 @@ pub unsafe extern "C" fn liq_result_set_progress_callback(result: &mut liq_resul
191191

192192
#[allow(clippy::cast_ptr_alignment)]
193193
unsafe fn attr_to_liq_attr_ptr(ptr: &Attributes) -> &liq_attr {
194-
let liq_attr = std::ptr::NonNull::<liq_attr>::dangling();
195-
let outer_addr = std::ptr::addr_of!(*liq_attr.as_ptr()) as isize;
196-
let inner_addr = std::ptr::addr_of!((*liq_attr.as_ptr()).inner) as isize;
194+
let liq_attr = ptr::NonNull::<liq_attr>::dangling();
195+
let outer_addr = ptr::addr_of!(*liq_attr.as_ptr()) as isize;
196+
let inner_addr = ptr::addr_of!((*liq_attr.as_ptr()).inner) as isize;
197197

198198
&*(ptr as *const Attributes).cast::<u8>().offset(outer_addr - inner_addr).cast::<liq_attr>()
199199
}
@@ -304,7 +304,7 @@ pub unsafe extern "C" fn liq_write_remapped_image(result: &mut liq_result, input
304304

305305
let required_size = (input_image.width()) * (input_image.height());
306306
if buffer_size < required_size { return Error::BufferTooSmall; }
307-
let buffer_bytes = std::slice::from_raw_parts_mut(buffer_bytes, required_size);
307+
let buffer_bytes = slice::from_raw_parts_mut(buffer_bytes, required_size);
308308
liq_write_remapped_image_impl(result, input_image, buffer_bytes).err().unwrap_or(LIQ_OK)
309309
}
310310

@@ -317,7 +317,7 @@ pub unsafe extern "C" fn liq_write_remapped_image_rows(result: &mut liq_result,
317317
let result = &mut result.inner;
318318

319319
if liq_received_invalid_pointer(row_pointers.cast()) { return Error::InvalidPointer; }
320-
let rows = std::slice::from_raw_parts_mut(row_pointers, input_image.height());
320+
let rows = slice::from_raw_parts_mut(row_pointers, input_image.height());
321321

322322
liq_write_remapped_image_rows_impl(result, input_image, rows).err().unwrap_or(LIQ_OK)
323323
}
@@ -378,7 +378,7 @@ pub unsafe extern "C" fn liq_image_set_importance_map(img: &mut liq_image, impor
378378
return Error::BufferTooSmall;
379379
}
380380

381-
let importance_map_slice = std::slice::from_raw_parts(importance_map, required_size);
381+
let importance_map_slice = slice::from_raw_parts(importance_map, required_size);
382382
if ownership == liq_ownership::LIQ_COPY_PIXELS {
383383
img.set_importance_map(importance_map_slice).err().unwrap_or(LIQ_OK)
384384
} else if ownership == liq_ownership::LIQ_OWN_PIXELS {
@@ -430,7 +430,7 @@ pub extern "C" fn liq_attr_create_with_allocator(_unused: *mut c_void, free: uns
430430
inner: Attributes::new(),
431431
c_api_free: free,
432432
});
433-
debug_assert_eq!(std::ptr::addr_of!(*attr), unsafe { attr_to_liq_attr_ptr(&attr.inner) } as *const liq_attr);
433+
debug_assert_eq!(ptr::addr_of!(*attr), unsafe { attr_to_liq_attr_ptr(&attr.inner) } as *const liq_attr);
434434
Some(attr)
435435
}
436436

@@ -561,7 +561,7 @@ pub unsafe extern "C" fn liq_result_from_palette(
561561
}
562562

563563
let attr = &attr.inner;
564-
let palette = std::slice::from_raw_parts(palette, palette_size);
564+
let palette = slice::from_raw_parts(palette, palette_size);
565565

566566
let res = QuantizationResult::from_palette(attr, palette, gamma).map(|inner| liq_result {
567567
magic_header: LIQ_RESULT_MAGIC,
@@ -585,9 +585,9 @@ pub(crate) fn check_image_size(attr: &liq_attr, width: u32, height: u32) -> bool
585585
return false;
586586
}
587587

588-
if width as usize > c_int::MAX as usize / std::mem::size_of::<liq_color>() / height as usize ||
589-
width as usize > c_int::MAX as usize / 16 / std::mem::size_of::<f32>() ||
590-
height as usize > c_int::MAX as usize / std::mem::size_of::<usize>()
588+
if width as usize > c_int::MAX as usize / mem::size_of::<liq_color>() / height as usize ||
589+
width as usize > c_int::MAX as usize / 16 / mem::size_of::<f32>() ||
590+
height as usize > c_int::MAX as usize / mem::size_of::<usize>()
591591
{
592592
return false;
593593
}
@@ -612,7 +612,7 @@ pub unsafe extern "C" fn liq_image_create_custom(attr: &liq_attr, row_callback:
612612
pub unsafe extern "C" fn liq_image_create_rgba_rows<'rows>(attr: &liq_attr, rows: *const *const RGBA, width: c_uint, height: c_uint, gamma: f64) -> Option<Box<liq_image<'rows>>> {
613613
if !check_image_size(attr, width, height) { return None; }
614614
if rows.is_null() { return None; }
615-
let rows = std::slice::from_raw_parts(rows, height as _);
615+
let rows = slice::from_raw_parts(rows, height as _);
616616
liq_image_create_rgba_rows_impl(&attr.inner, rows, width as _, height as _, gamma)
617617
.map(move |inner| Box::new(liq_image {
618618
magic_header: LIQ_IMAGE_MAGIC,
@@ -651,7 +651,7 @@ pub unsafe extern "C" fn liq_histogram_add_colors(input_hist: &mut liq_histogram
651651

652652
if liq_received_invalid_pointer(entries.cast()) { return Error::InvalidPointer; }
653653

654-
let entries = std::slice::from_raw_parts(entries, num_entries);
654+
let entries = slice::from_raw_parts(entries, num_entries);
655655

656656
input_hist.add_colors(entries, gamma).err().unwrap_or(LIQ_OK)
657657
}
@@ -678,7 +678,6 @@ pub unsafe extern "Rust" fn liq_executing_user_callback(callback: liq_image_get_
678678

679679
#[test]
680680
fn links_and_runs() {
681-
use std::ptr;
682681
unsafe {
683682
assert!(liq_version() >= 40000);
684683
let attr = liq_attr_create().unwrap();
@@ -701,7 +700,6 @@ fn links_and_runs() {
701700
#[test]
702701
#[allow(deprecated)]
703702
fn link_every_symbol() {
704-
use std::os::raw::c_void;
705703

706704
let x = liq_attr_create as *const c_void as usize
707705
+ liq_attr_create_with_allocator as *const c_void as usize
@@ -757,8 +755,6 @@ fn link_every_symbol() {
757755

758756
#[test]
759757
fn c_callback_test_c() {
760-
use std::mem::MaybeUninit;
761-
762758
let mut called = 0;
763759
let mut res = unsafe {
764760
let mut a = liq_attr_create().unwrap();
@@ -772,17 +768,15 @@ fn c_callback_test_c() {
772768
let user_data = user_data.0.cast::<i32>();
773769
*user_data += 1;
774770
}
775-
let mut img = liq_image_create_custom(&a, get_row, AnySyncSendPtr(std::ptr::addr_of_mut!(called).cast::<c_void>()), 123, 5, 0.).unwrap();
771+
let mut img = liq_image_create_custom(&a, get_row, AnySyncSendPtr(ptr::addr_of_mut!(called).cast::<c_void>()), 123, 5, 0.).unwrap();
776772
liq_quantize_image(&mut a, &mut img).unwrap()
777773
};
778774
assert!(called > 5 && called < 50);
779775
let pal = liq_get_palette(&mut res).unwrap();
780776
assert_eq!(123, pal.count);
781777
}
782778

783-
784-
785779
#[test]
786780
fn ownership_bitflags() {
787-
assert_eq!(4+16, (liq_ownership::LIQ_OWN_ROWS | liq_ownership::LIQ_COPY_PIXELS).bits());
781+
assert_eq!(4 + 16, (liq_ownership::LIQ_OWN_ROWS | liq_ownership::LIQ_COPY_PIXELS).bits());
788782
}

src/capi.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ use crate::pal::Palette;
77
use crate::rows::RowCallback;
88
use crate::seacow::{Pointer, RowBitmapMut, SeaCow};
99
use crate::{Attributes, Error, Image, QuantizationResult, RGBA};
10-
use std::mem::MaybeUninit;
10+
use core::ffi::c_void;
11+
use core::mem::{self, MaybeUninit};
1112

1213
pub const LIQ_VERSION: u32 = 40202;
1314

@@ -28,7 +29,7 @@ pub unsafe fn liq_image_create_rgba_rows_impl<'rows>(attr: &Attributes, rows: &'
2829

2930
#[must_use]
3031
pub unsafe fn liq_image_create_rgba_bitmap_impl<'rows>(attr: &Attributes, rows: Box<[*const RGBA]>, width: u32, height: u32, gamma: f64) -> Option<crate::image::Image<'rows>> {
31-
let rows = SeaCow::boxed(std::mem::transmute::<Box<[*const RGBA]>, Box<[Pointer<RGBA>]>>(rows));
32+
let rows = SeaCow::boxed(mem::transmute::<Box<[*const RGBA]>, Box<[Pointer<RGBA>]>>(rows));
3233
let rows_slice = rows.as_slice();
3334
if rows_slice.iter().any(|r| r.0.is_null()) {
3435
return None;
@@ -52,6 +53,6 @@ pub unsafe fn liq_write_remapped_image_rows_impl(result: &mut QuantizationResult
5253
}
5354

5455
/// Not recommended
55-
pub unsafe fn liq_image_set_memory_ownership_impl(image: &mut Image<'_>, own_rows: bool, own_pixels: bool, free_fn: unsafe extern "C" fn(*mut std::os::raw::c_void)) -> Result<(), Error> {
56+
pub unsafe fn liq_image_set_memory_ownership_impl(image: &mut Image<'_>, own_rows: bool, own_pixels: bool, free_fn: unsafe extern "C" fn(*mut c_void)) -> Result<(), Error> {
5657
image.px.set_memory_ownership(own_rows, own_pixels, free_fn)
5758
}

src/error.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1+
use core::{error, fmt};
12
use std::collections::TryReserveError;
2-
use std::fmt;
33
pub use Error::*;
44

55
/// Error codes
@@ -29,7 +29,7 @@ pub enum Error {
2929
Unsupported,
3030
}
3131

32-
impl std::error::Error for Error {}
32+
impl error::Error for Error {}
3333

3434
impl fmt::Display for Error {
3535
#[cold]

src/hist.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ use crate::quant::QuantizationResult;
55
use crate::rows::{temp_buf, DynamicRows};
66
use crate::Attributes;
77
use std::collections::{HashMap, HashSet};
8-
use std::fmt;
9-
use std::hash::Hash;
8+
use core::{fmt, hash, mem};
9+
use core::hash::Hash;
1010

1111
/// Number of pixels in a given color for [`Histogram::add_colors()`]
1212
///
@@ -57,7 +57,7 @@ impl HistItem {
5757
// The u32 has been initialized when constructing the object, and u8/u16 is smaller than that
5858
#[inline(always)]
5959
pub fn likely_palette_index(&self) -> PalIndex {
60-
assert!(std::mem::size_of::<PalIndex>() <= std::mem::size_of::<u32>());
60+
assert!(mem::size_of::<PalIndex>() <= mem::size_of::<u32>());
6161
unsafe { self.tmp.likely_palette_index }
6262
}
6363
}
@@ -241,7 +241,7 @@ impl Histogram {
241241
let new_posterize_mask = self.posterize_mask();
242242

243243
let new_size = (self.hashmap.len() / 3).max(self.hashmap.capacity() / 5);
244-
let old_hashmap = std::mem::replace(&mut self.hashmap, HashMap::with_capacity_and_hasher(new_size, U32Hasher(0)));
244+
let old_hashmap = mem::replace(&mut self.hashmap, HashMap::with_capacity_and_hasher(new_size, U32Hasher(0)));
245245
self.hashmap.extend(old_hashmap.into_iter().map(move |(k, v)| {
246246
(k & new_posterize_mask, v)
247247
}));
@@ -381,7 +381,7 @@ pub(crate) struct Cluster {
381381
}
382382

383383
// Simple deterministic hasher for the color hashmap
384-
impl std::hash::BuildHasher for U32Hasher {
384+
impl hash::BuildHasher for U32Hasher {
385385
type Hasher = Self;
386386

387387
#[inline(always)]
@@ -391,7 +391,7 @@ impl std::hash::BuildHasher for U32Hasher {
391391
}
392392

393393
pub(crate) struct U32Hasher(pub u32);
394-
impl std::hash::Hasher for U32Hasher {
394+
impl hash::Hasher for U32Hasher {
395395
// magic constant from fxhash. For a single 32-bit key that's all it needs!
396396
#[inline(always)]
397397
fn finish(&self) -> u64 { u64::from(self.0).wrapping_mul(0x517cc1b727220a95) }
@@ -422,7 +422,7 @@ pub(crate) struct HashColor {
422422
#[allow(clippy::derived_hash_with_manual_eq)]
423423
impl Hash for HashColor {
424424
#[inline]
425-
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
425+
fn hash<H: hash::Hasher>(&self, state: &mut H) {
426426
let s: &[u8] = self.rgba.as_ref();
427427
u32::from_ne_bytes(s.try_into().unwrap()).hash(state);
428428
}

src/image.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::rows::{DynamicRows, PixelsSource};
77
use crate::seacow::{RowBitmap, SeaCow};
88
use crate::{PushInCapacity, LIQ_HIGH_MEMORY_LIMIT};
99
use rgb::prelude::*;
10-
use std::mem::MaybeUninit;
10+
use core::mem::{self, MaybeUninit};
1111

1212
/// Describes image dimensions and pixels for the library
1313
///
@@ -105,7 +105,7 @@ impl<'pixels> Image<'pixels> {
105105
};
106106
// if image is huge or converted pixels are not likely to be reused then don't cache converted pixels
107107
let low_memory_hint = !attr.use_contrast_maps && attr.use_dither_map == DitherMapMode::None;
108-
let limit = if low_memory_hint { LIQ_HIGH_MEMORY_LIMIT / 8 } else { LIQ_HIGH_MEMORY_LIMIT } / std::mem::size_of::<f_pixel>();
108+
let limit = if low_memory_hint { LIQ_HIGH_MEMORY_LIMIT / 8 } else { LIQ_HIGH_MEMORY_LIMIT } / mem::size_of::<f_pixel>();
109109
if (img.width()) * (img.height()) > limit {
110110
attr.verbose_print(" conserving memory"); // for simplicity of this API there's no explicit pixels argument,
111111
}
@@ -117,7 +117,7 @@ impl<'pixels> Image<'pixels> {
117117
return false;
118118
}
119119
if width.max(height) as usize > i32::MAX as usize ||
120-
width as usize > isize::MAX as usize / std::mem::size_of::<f_pixel>() / height as usize {
120+
width as usize > isize::MAX as usize / mem::size_of::<f_pixel>() / height as usize {
121121
return false;
122122
}
123123
true

src/kmeans.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ use crate::nearest::Nearest;
33
use crate::pal::{f_pixel, PalF, PalIndex, PalPop};
44
use crate::rayoff::*;
55
use crate::{CacheLineAlign, Error};
6+
use core::cell::RefCell;
67
use rgb::prelude::*;
78
use rgb::Argb;
8-
use std::cell::RefCell;
99

1010
/// K-Means iteration: new palette color is computed from weighted average of colors that map best to that palette entry.
1111
// avoid false sharing

src/lib.rs

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,8 @@ mod rayoff;
3939
#[cfg(feature = "threads")]
4040
mod rayoff {
4141
pub(crate) fn num_cpus() -> usize { std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1) }
42-
pub(crate) use rayon::prelude::{ParallelBridge, ParallelIterator, ParallelSliceMut};
4342
pub(crate) use rayon::in_place_scope as scope;
43+
pub(crate) use rayon::prelude::{ParallelBridge, ParallelIterator, ParallelSliceMut};
4444
pub(crate) use thread_local::ThreadLocal;
4545
}
4646

@@ -51,6 +51,8 @@ pub(crate) struct CacheLineAlign<T>(pub T);
5151
#[cfg(feature = "_internal_c_ffi")]
5252
pub mod capi;
5353

54+
use core::cmp::Ordering;
55+
5456
pub use attr::{Attributes, ControlFlow};
5557
pub use error::Error;
5658
pub use hist::{Histogram, HistogramEntry};
@@ -201,7 +203,7 @@ fn thread() {
201203

202204
#[test]
203205
fn r_callback_test() {
204-
use std::mem::MaybeUninit;
206+
use core::mem::MaybeUninit;
205207
use std::sync::atomic::AtomicU16;
206208
use std::sync::atomic::Ordering::SeqCst;
207209
use std::sync::Arc;
@@ -231,14 +233,14 @@ fn r_callback_test() {
231233

232234
#[test]
233235
fn sizes() {
234-
use pal::PalF;
235-
use pal::Palette;
236-
assert!(std::mem::size_of::<PalF>() < crate::pal::MAX_COLORS*(8*4)+32, "{}", std::mem::size_of::<PalF>());
237-
assert!(std::mem::size_of::<QuantizationResult>() < std::mem::size_of::<PalF>() + std::mem::size_of::<Palette>() + 100, "{}", std::mem::size_of::<QuantizationResult>());
238-
assert!(std::mem::size_of::<Attributes>() < 200);
239-
assert!(std::mem::size_of::<Image>() < 300);
240-
assert!(std::mem::size_of::<Histogram>() < 200);
241-
assert!(std::mem::size_of::<crate::hist::HistItem>() <= 32);
236+
use core::mem::size_of;
237+
use pal::{PalF, Palette};
238+
assert!(size_of::<PalF>() < crate::pal::MAX_COLORS * (8 * 4) + 32, "{}", size_of::<PalF>());
239+
assert!(size_of::<QuantizationResult>() < size_of::<PalF>() + size_of::<Palette>() + 100, "{}", size_of::<QuantizationResult>());
240+
assert!(size_of::<Attributes>() < 200);
241+
assert!(size_of::<Image>() < 300);
242+
assert!(size_of::<Histogram>() < 200);
243+
assert!(size_of::<crate::hist::HistItem>() <= 32);
242244
}
243245

244246
#[doc(hidden)]
@@ -259,7 +261,7 @@ pub fn _unstable_internal_kmeans_bench() -> impl FnMut() {
259261
let lut = pal::gamma_lut(0.45455);
260262
let mut p = PalF::new();
261263
for i in 0..=255 {
262-
p.push(pal::f_pixel::from_rgba(&lut, RGBA::new(i|7, i, i, 255)), PalPop::new(1.));
264+
p.push(pal::f_pixel::from_rgba(&lut, RGBA::new(i | 7, i, i, 255)), PalPop::new(1.));
263265
}
264266

265267
move || {
@@ -293,8 +295,8 @@ impl Eq for OrdFloat<f32> {
293295

294296
impl Ord for OrdFloat<f32> {
295297
#[inline]
296-
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
297-
self.0.partial_cmp(&other.0).unwrap_or(std::cmp::Ordering::Equal)
298+
fn cmp(&self, other: &Self) -> Ordering {
299+
self.0.partial_cmp(&other.0).unwrap_or(Ordering::Equal)
298300
}
299301
}
300302

@@ -303,8 +305,8 @@ impl Eq for OrdFloat<f64> {
303305

304306
impl Ord for OrdFloat<f64> {
305307
#[inline]
306-
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
307-
self.0.partial_cmp(&other.0).unwrap_or(std::cmp::Ordering::Equal)
308+
fn cmp(&self, other: &Self) -> Ordering {
309+
self.0.partial_cmp(&other.0).unwrap_or(Ordering::Equal)
308310
}
309311
}
310312

0 commit comments

Comments
 (0)