Skip to content

Commit

Permalink
Add support for no_std
Browse files Browse the repository at this point in the history
  • Loading branch information
brysgo committed May 3, 2021
1 parent 5f42ea6 commit eac42a1
Show file tree
Hide file tree
Showing 8 changed files with 58 additions and 25 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@ jobs:

- name: Run tests
run: RUSTFLAGS="-D warnings" cargo test --workspace

- name: Run tests with no defaults
run: RUSTFLAGS="-D warnings" cargo test --workspace --no-default-features
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@ keywords = ["texture", "atlas", "bin", "box", "packer"]
description = "A general purpose, deterministic bin packer designed to conform to any two or three dimensional use case."
license = "MIT/Apache-2.0"
repository = "https://github.com/chinedufn/rectangle-pack"

[features]
default = ["std"]
std = []
9 changes: 6 additions & 3 deletions src/bin_section.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use crate::packed_location::RotatedBy;
use crate::{BoxSizeHeuristicFn, PackedLocation, RectToInsert, WidthHeightDepth};
use std::cmp::Ordering;
use std::fmt::{Display, Formatter};

use core::{
cmp::Ordering,
fmt::{Debug, Display, Error as ErrorFmt, Formatter},
};

mod overlaps;

Expand Down Expand Up @@ -57,7 +60,7 @@ pub enum BinSectionError {
}

impl Display for BinSectionError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFmt> {
let err = match self {
BinSectionError::PlacementWiderThanBinSection => {
"Can not place a rectangle inside of a bin that is wider than that rectangle."
Expand Down
21 changes: 15 additions & 6 deletions src/grouped_rects_to_place.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
use crate::RectToInsert;
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, HashMap};
use std::fmt::Debug;
use std::hash::Hash;

#[cfg(std)]
use crate::Vec;
#[cfg(not(std))]
use alloc::collections::BTreeMap as KeyValMap;
use alloc::{
collections::{btree_map::Entry, BTreeMap},
vec::Vec,
};
use core::{fmt::Debug, hash::Hash};
#[cfg(std)]
use std::collections::HashMap as KeyValMap;

/// Groups of rectangles that need to be placed into bins.
///
Expand All @@ -19,9 +27,10 @@ where
{
// FIXME: inbound_id_to_group_id appears to be unused. If so, remove it. Also remove the
// Hash and Eq constraints on RectToPlaceId if we remove this map
pub(crate) inbound_id_to_group_ids: HashMap<RectToPlaceId, Vec<Group<GroupId, RectToPlaceId>>>,
pub(crate) inbound_id_to_group_ids:
KeyValMap<RectToPlaceId, Vec<Group<GroupId, RectToPlaceId>>>,
pub(crate) group_id_to_inbound_ids: BTreeMap<Group<GroupId, RectToPlaceId>, Vec<RectToPlaceId>>,
pub(crate) rects: HashMap<RectToPlaceId, RectToInsert>,
pub(crate) rects: KeyValMap<RectToPlaceId, RectToInsert>,
}

/// A group of rectangles that need to be placed together
Expand Down
33 changes: 21 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
//! `rectangle-pack` is a library focused on laying out any number of smaller rectangles
//! (both 2d rectangles and 3d rectangular prisms) inside any number of larger rectangles.
#![cfg_attr(not(std), no_std)]
#![deny(missing_docs)]

use std::collections::{BTreeMap, HashMap};
use std::fmt::{Debug, Display, Formatter};
use std::hash::Hash;
#[macro_use]
extern crate alloc;

#[cfg(not(std))]
use alloc::collections::BTreeMap as KeyValMap;
use alloc::{collections::BTreeMap, vec::Vec};
use core::{
fmt::{Debug, Display, Error as ErrorFmt, Formatter},
hash::Hash,
};
#[cfg(std)]
use std::collections::HashMap as KeyValMap;

pub use crate::bin_section::contains_smallest_box;
pub use crate::bin_section::BinSection;
Expand Down Expand Up @@ -128,7 +137,7 @@ pub fn pack_rects<
box_size_heuristic: &BoxSizeHeuristicFn,
more_suitable_containers_fn: &ComparePotentialContainersFn,
) -> Result<RectanglePackOk<RectToPlaceId, BinId>, RectanglePackError> {
let mut packed_locations = HashMap::new();
let mut packed_locations = KeyValMap::new();

let mut target_bins: Vec<(&BinId, &mut TargetBin)> = target_bins.iter_mut().collect();
sort_bins_smallest_to_largest(&mut target_bins, box_size_heuristic);
Expand Down Expand Up @@ -254,7 +263,7 @@ where
/// Information about successfully packed rectangles.
#[derive(Debug, PartialEq)]
pub struct RectanglePackOk<RectToPlaceId: PartialEq + Eq + Hash, BinId: PartialEq + Eq + Hash> {
packed_locations: HashMap<RectToPlaceId, (BinId, PackedLocation)>,
packed_locations: KeyValMap<RectToPlaceId, (BinId, PackedLocation)>,
// TODO: Other information such as information about how the bins were packed
// (perhaps percentage filled)
}
Expand All @@ -263,7 +272,7 @@ impl<RectToPlaceId: PartialEq + Eq + Hash, BinId: PartialEq + Eq + Hash>
RectanglePackOk<RectToPlaceId, BinId>
{
/// Indicates where every incoming rectangle was placed
pub fn packed_locations(&self) -> &HashMap<RectToPlaceId, (BinId, PackedLocation)> {
pub fn packed_locations(&self) -> &KeyValMap<RectToPlaceId, (BinId, PackedLocation)> {
&self.packed_locations
}
}
Expand All @@ -276,15 +285,15 @@ pub enum RectanglePackError {
}

impl Display for RectanglePackError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), ErrorFmt> {
match self {
RectanglePackError::NotEnoughBinSpace => {
f.write_str("Not enough space to place all of the rectangles.")
}
}
}
}

#[cfg(std)]
impl std::error::Error for RectanglePackError {}

fn sort_bins_smallest_to_largest<BinId>(
Expand Down Expand Up @@ -349,7 +358,6 @@ mod tests {

use super::*;
use crate::packed_location::RotatedBy;
use std::path::PathBuf;

/// If the provided rectangles can't fit into the provided bins.
#[test]
Expand Down Expand Up @@ -787,7 +795,8 @@ mod tests {
let mut previous_packed = None;

for _ in 0..5 {
let mut rects_to_place: GroupedRectsToPlace<PathBuf, &str> = GroupedRectsToPlace::new();
let mut rects_to_place: GroupedRectsToPlace<&'static str, &str> =
GroupedRectsToPlace::new();

let mut target_bins = BTreeMap::new();
for bin_id in 0..5 {
Expand All @@ -803,7 +812,7 @@ mod tests {
];

for rect_id in rectangles.iter() {
rects_to_place.push_rect(PathBuf::from(rect_id), None, RectToInsert::new(4, 4, 1));
rects_to_place.push_rect(rect_id, None, RectToInsert::new(4, 4, 1));
}

let packed = pack_rects(
Expand Down
1 change: 1 addition & 0 deletions src/target_bin.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::bin_section::BinSection;
use crate::width_height_depth::WidthHeightDepth;
use alloc::vec::Vec;

mod coalesce;
mod push_available_bin_section;
Expand Down
8 changes: 6 additions & 2 deletions src/target_bin/coalesce.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::TargetBin;
use std::ops::Range;

use core::ops::Range;

impl TargetBin {
/// Over time as you use [`TargetBin.push_available_bin_section`] to return remove packed
Expand Down Expand Up @@ -78,7 +79,10 @@ impl TargetBin {
// Tests cases should have a rectangle and then a neighbor (above, below, left, right) and
// verify that they get combined, but only if the comparison indices are correct and only if
// the neighbor has the same width (uf above/below) or height (if left/right).
pub fn coalesce_available_sections(_bin_section_index: usize, _compare_to_indices: Range<usize>) {
pub fn coalesce_available_sections(
_bin_section_index: usize,
_compare_to_indices: Range<usize>,
) {
unimplemented!()
}
}
4 changes: 2 additions & 2 deletions src/target_bin/push_available_bin_section.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

use crate::bin_section::BinSection;
use crate::TargetBin;
use std::fmt::{Display, Formatter};
use core::fmt::{Display, Formatter, Result as ResultFmt};

impl TargetBin {
/// Push a [`BinSection`] to the list of remaining [`BinSection`]'s that rectangles can be
Expand Down Expand Up @@ -77,7 +77,7 @@ pub enum PushBinSectionError {
}

impl Display for PushBinSectionError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
fn fmt(&self, f: &mut Formatter<'_>) -> ResultFmt {
match self {
PushBinSectionError::OutOfBounds(oob) => {
f.debug_tuple("BinSection").field(oob).finish()
Expand Down

0 comments on commit eac42a1

Please sign in to comment.