Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add a feature that allows usage on no_std targets #242

Merged
merged 4 commits into from
Mar 18, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ jobs:
profile: minimal
override: true

- run: rustup target add thumbv7m-none-eabi
notgull marked this conversation as resolved.
Show resolved Hide resolved

- name: cargo clippy
uses: actions-rs/cargo@v1
with:
Expand All @@ -59,6 +61,10 @@ jobs:
command: test
args: --all-features

- name: Build with no default features
# Use no-std target to ensure we don't link to std.
run: cargo build --no-default-features --features libm --target thumbv7m-none-eabi

test-stable-wasm:
runs-on: ${{ matrix.os }}
strategy:
Expand Down
14 changes: 12 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,17 @@ categories = ["graphics"]
[package.metadata.docs.rs]
features = ["mint", "schemars", "serde"]

[dependencies]
arrayvec = "0.7.1"
[features]
default = ["std"]
std = []

[dependencies.arrayvec]
version = "0.7.1"
default-features = false

[dependencies.libm]
version = "0.2.6"
optional = true

[dependencies.mint]
version = "0.5.1"
Expand All @@ -27,6 +36,7 @@ optional = true
[dependencies.serde]
version = "1.0.105"
optional = true
default-features = false
features = ["derive"]

# This is used for research but not really needed; maybe refactor.
Expand Down
14 changes: 10 additions & 4 deletions examples/circle.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
//! Example of circle

use kurbo::{Circle, Shape};

#[cfg(feature = "std")]
fn main() {
use kurbo::{Circle, Shape};

let circle = Circle::new((400.0, 400.0), 380.0);
println!("<!DOCTYPE html>");
println!("<html>");
println!("<body>");
println!("<svg height=\"800\" width=\"800\">");
let path = circle.to_path(1e-3).to_svg();
println!(" <path d=\"{path}\" stroke=\"black\" fill=\"none\" />");
println!(" <path d=\"{}\" stroke=\"black\" fill=\"none\" />", path);
let path = circle.to_path(1.0).to_svg();
println!(" <path d=\"{path}\" stroke=\"red\" fill=\"none\" />");
println!(" <path d=\"{}\" stroke=\"red\" fill=\"none\" />", path);
println!("</svg>");
println!("</body>");
println!("</html>");
}

#[cfg(not(feature = "std"))]
fn main() {
println!("This example requires the standard library");
}
16 changes: 11 additions & 5 deletions examples/ellipse.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
//! Example of ellipse

use kurbo::{Ellipse, Shape};
use std::f64::consts::PI;

#[cfg(feature = "std")]
fn main() {
use kurbo::{Ellipse, Shape};
use std::f64::consts::PI;

let ellipse = Ellipse::new((400.0, 400.0), (200.0, 100.0), 0.25 * PI);
println!("<!DOCTYPE html>");
println!("<html>");
println!("<body>");
println!("<svg height=\"800\" width=\"800\" style=\"background-color: #999\">");
let path = ellipse.to_path(1e-3).to_svg();
println!(" <path d=\"{path}\" stroke=\"black\" fill=\"none\" />");
println!(" <path d=\"{}\" stroke=\"black\" fill=\"none\" />", path);
let path = ellipse.to_path(1.0).to_svg();
println!(" <path d=\"{path}\" stroke=\"red\" fill=\"none\" />");
println!(" <path d=\"{}\" stroke=\"red\" fill=\"none\" />", path);
println!("</svg>");
println!("</body>");
println!("</html>");
}

#[cfg(not(feature = "std"))]
fn main() {
println!("This example requires the standard library");
}
5 changes: 4 additions & 1 deletion src/affine.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
//! Affine transforms.

use std::ops::{Mul, MulAssign};
use core::ops::{Mul, MulAssign};

use crate::{Point, Rect, Vec2};

#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;

/// A 2D affine transform.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
Expand Down
5 changes: 4 additions & 1 deletion src/arc.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
//! An ellipse arc.

use crate::{PathEl, Point, Rect, Shape, Vec2};
use std::{
use core::{
f64::consts::{FRAC_PI_2, PI},
iter,
};

#[cfg(not(feature = "std"))]
use crate::common::{FloatFuncs, FloatFuncsExtra};

/// A single arc segment.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
Expand Down
21 changes: 13 additions & 8 deletions src/bezpath.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

#![allow(clippy::many_single_char_names)]

use std::iter::{Extend, FromIterator};
use std::mem;
use std::ops::{Mul, Range};
use core::iter::{Extend, FromIterator};
use core::mem;
use core::ops::{Mul, Range};

use alloc::vec::Vec;

use arrayvec::ArrayVec;

Expand All @@ -15,6 +17,9 @@ use crate::{
ParamCurveExtrema, ParamCurveNearest, Point, QuadBez, Rect, Shape, TranslateScale, Vec2,
};

#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;
cmyr marked this conversation as resolved.
Show resolved Hide resolved

/// A Bézier path.
///
/// These docs assume basic familiarity with Bézier curves; for an introduction,
Expand Down Expand Up @@ -404,7 +409,7 @@ impl FromIterator<PathEl> for BezPath {
/// slice, as it returns `PathEl` items, rather than references.
impl<'a> IntoIterator for &'a BezPath {
type Item = PathEl;
type IntoIter = std::iter::Cloned<std::slice::Iter<'a, PathEl>>;
type IntoIter = core::iter::Cloned<core::slice::Iter<'a, PathEl>>;

fn into_iter(self) -> Self::IntoIter {
self.elements().iter().cloned()
Expand All @@ -413,7 +418,7 @@ impl<'a> IntoIterator for &'a BezPath {

impl IntoIterator for BezPath {
type Item = PathEl;
type IntoIter = std::vec::IntoIter<PathEl>;
type IntoIter = alloc::vec::IntoIter<PathEl>;

fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
Expand Down Expand Up @@ -1108,7 +1113,7 @@ impl From<QuadBez> for PathSeg {
}

impl Shape for BezPath {
type PathElementsIter<'iter> = std::iter::Copied<std::slice::Iter<'iter, PathEl>>;
type PathElementsIter<'iter> = core::iter::Copied<core::slice::Iter<'iter, PathEl>>;

fn path_elements(&self, _tolerance: f64) -> Self::PathElementsIter<'_> {
self.0.iter().copied()
Expand Down Expand Up @@ -1178,7 +1183,7 @@ impl PathEl {
impl<'a> Shape for &'a [PathEl] {
type PathElementsIter<'iter>

= std::iter::Copied<std::slice::Iter<'a, PathEl>> where 'a: 'iter;
= core::iter::Copied<core::slice::Iter<'a, PathEl>> where 'a: 'iter;

#[inline]
fn path_elements(&self, _tolerance: f64) -> Self::PathElementsIter<'_> {
Expand Down Expand Up @@ -1218,7 +1223,7 @@ impl<'a> Shape for &'a [PathEl] {
///
/// If the array starts with `LineTo`, `QuadTo`, or `CurveTo`, it will be treated as a `MoveTo`.
impl<const N: usize> Shape for [PathEl; N] {
type PathElementsIter<'iter> = std::iter::Copied<std::slice::Iter<'iter, PathEl>>;
type PathElementsIter<'iter> = core::iter::Copied<core::slice::Iter<'iter, PathEl>>;

#[inline]
fn path_elements(&self, _tolerance: f64) -> Self::PathElementsIter<'_> {
Expand Down
7 changes: 5 additions & 2 deletions src/circle.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
//! Implementation of circle shape.

use std::{
use core::{
f64::consts::{FRAC_PI_2, PI},
iter,
ops::{Add, Mul, Sub},
};

use crate::{Affine, Arc, ArcAppendIter, Ellipse, PathEl, Point, Rect, Shape, Vec2};

#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;

/// A circle.
#[derive(Clone, Copy, Default, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
Expand Down Expand Up @@ -260,7 +263,7 @@ impl Sub<Vec2> for CircleSegment {
}
}

type CircleSegmentPathIter = std::iter::Chain<
type CircleSegmentPathIter = iter::Chain<
iter::Chain<
iter::Chain<iter::Chain<iter::Once<PathEl>, iter::Once<PathEl>>, ArcAppendIter>,
iter::Once<PathEl>,
Expand Down
85 changes: 85 additions & 0 deletions src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,91 @@

use arrayvec::ArrayVec;

/// Defines a trait that chooses between libstd or libm implementations of float methods.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so... is this actually necessary in the case of std? If std is present then these methods will already exist on our types, and method resolution will work, so it feels like we could get away with only defining this trait if the musl feature is active?

(the fact that this trait does nothing if std is active is supported by the need to add #[allow(unused_code)] on the import)

macro_rules! define_float_funcs {
($(
fn $name:ident(self $(,$arg:ident: $arg_ty:ty)*) -> $ret:ty
=> $lname:ident/$lfname:ident;
)+) => {
#[cfg(not(feature = "std"))]
pub(crate) trait FloatFuncs : Sized {
$(fn $name(self $(,$arg: $arg_ty)*) -> $ret;)+
}

#[cfg(not(feature = "std"))]
impl FloatFuncs for f32 {
$(fn $name(self $(,$arg: $arg_ty)*) -> $ret {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want an #[inline] here? Not clear that this crosses crate boundaries (I guess not?) so maybe it doesn't matter..

#[cfg(feature = "libm")]
return libm::$lfname(self $(,$arg as _)*);

#[cfg(not(feature = "libm"))]
compile_error!("kurbo requires either the `std` or `libm` feature")
})+
}

#[cfg(not(feature = "std"))]
impl FloatFuncs for f64 {
$(fn $name(self $(,$arg: $arg_ty)*) -> $ret {
#[cfg(feature = "libm")]
return libm::$lname(self $(,$arg as _)*);

#[cfg(not(feature = "libm"))]
compile_error!("kurbo requires either the `std` or `libm` feature")
})+
}
}
}

define_float_funcs! {
fn abs(self) -> Self => fabs/fabsf;
fn atan2(self, other: Self) -> Self => atan2/atan2f;
fn cbrt(self) -> Self => cbrt/cbrtf;
fn ceil(self) -> Self => ceil/ceilf;
fn copysign(self, sign: Self) -> Self => copysign/copysignf;
fn floor(self) -> Self => floor/floorf;
fn hypot(self, other: Self) -> Self => hypot/hypotf;
fn ln(self) -> Self => log/logf;
fn log2(self) -> Self => log2/log2f;
fn mul_add(self, a: Self, b: Self) -> Self => fma/fmaf;
fn powi(self, n: i32) -> Self => pow/powf;
fn powf(self, n: Self) -> Self => pow/powf;
fn round(self) -> Self => round/roundf;
fn sin_cos(self) -> (Self, Self) => sincos/sincosf;
fn sqrt(self) -> Self => sqrt/sqrtf;
fn tan(self) -> Self => tan/tanf;
fn trunc(self) -> Self => trunc/truncf;
}

/// Special implementation for signum, because libm doesn't have it.
#[cfg(not(feature = "std"))]
pub(crate) trait FloatFuncsExtra {
notgull marked this conversation as resolved.
Show resolved Hide resolved
fn signum(self) -> Self;
}

#[cfg(not(feature = "std"))]
impl FloatFuncsExtra for f32 {
#[inline]
fn signum(self) -> f32 {
if self.is_nan() {
f32::NAN
} else {
1.0_f32.copysign(self)
}
}
}

#[cfg(not(feature = "std"))]
impl FloatFuncsExtra for f64 {
#[inline]
fn signum(self) -> f64 {
if self.is_nan() {
f64::NAN
} else {
1.0_f64.copysign(self)
}
}
}

/// Adds convenience methods to `f32` and `f64`.
pub trait FloatExt<T> {
/// Rounds to the nearest integer away from zero,
Expand Down
9 changes: 7 additions & 2 deletions src/cubicbez.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
//! Cubic Bézier segments.

use std::ops::{Mul, Range};
use alloc::vec;
use alloc::vec::Vec;
use core::ops::{Mul, Range};

use crate::MAX_EXTREMA;
use crate::{Line, QuadSpline, Vec2};
Expand All @@ -15,6 +17,9 @@ use crate::{
ParamCurveDeriv, ParamCurveExtrema, ParamCurveNearest, PathEl, Point, QuadBez, Rect, Shape,
};

#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;

const MAX_SPLINE_SPLIT: usize = 100;

/// A single cubic Bézier segment.
Expand Down Expand Up @@ -217,7 +222,7 @@ impl CubicBez {
let delta_2 = dt * dt;
let delta_3 = dt * delta_2;

std::iter::from_fn(move || {
core::iter::from_fn(move || {
// if storage exists, we use it exclusively
if let Some(storage) = storage.as_mut() {
return storage.pop();
Expand Down
7 changes: 5 additions & 2 deletions src/ellipse.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
//! Implementation of ellipse shape.

use std::f64::consts::PI;
use std::{
use core::f64::consts::PI;
use core::{
iter,
ops::{Add, Mul, Sub},
};

use crate::{Affine, Arc, ArcAppendIter, Circle, PathEl, Point, Rect, Shape, Size, Vec2};

#[cfg(not(feature = "std"))]
use crate::common::FloatFuncs;

/// An ellipse.
#[derive(Clone, Copy, Default, Debug, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
Expand Down
2 changes: 1 addition & 1 deletion src/insets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

//! A description of the distances between the edges of two rectangles.

use std::ops::{Add, Neg, Sub};
use core::ops::{Add, Neg, Sub};

use crate::{Rect, Size};

Expand Down
Loading