Skip to content

Commit

Permalink
refactor(algo): 💡 remove ShareResouce
Browse files Browse the repository at this point in the history
  • Loading branch information
M-Adoo committed Apr 25, 2024
1 parent 923eb68 commit 483bfec
Show file tree
Hide file tree
Showing 17 changed files with 62 additions and 104 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Please only add new entries below the [Unreleased](#unreleased---releasedate) he
### Changed

- **gpu**: Removed dependency on the texture array feature of wgpu. (#pr, @M-Adoo)
- **algo**: removed `Resource` and rename `ShareResource` to `Resource`. (#pr, @M-Adoo)

## [0.3.0-alpha.4] - 2024-04-17

Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ rctree = "0.5.0"
rustybuzz = "0.11.0"
rxrust = {version = "1.0.0-beta.6", default-features = false, features = ["futures-scheduler"]}
scoped_threadpool = "0.1.9"
triomphe = "0.1.11"
serde = "1.0"
serde_json = "1.0.82"
smallvec = "1.8.0"
Expand Down
1 change: 1 addition & 0 deletions algo/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ repository = "https://github.com/RibirX/Ribir/algo"
version.workspace = true

[dependencies]
triomphe.workspace = true
ahash.workspace = true
log.workspace = true
serde = {workspace = true, features = ["derive", "rc"]}
Expand Down
80 changes: 19 additions & 61 deletions algo/src/resource.rs
Original file line number Diff line number Diff line change
@@ -1,89 +1,48 @@
use std::{
hash::{Hash, Hasher},
ops::Deref,
rc::Rc,
};

use serde::{Deserialize, Serialize};

/// Enum to store both share and local resource. Share resources can have many
/// copy, and every copy as the same one. Local resources means is individual
/// and no other copy exist, two local resources will not as same one even its
/// content is equal.
#[derive(Eq, Debug, Clone)]
pub enum Resource<T> {
Share(ShareResource<T>),
Local(T),
}

/// A smarter pointer help us to share resource in application, and it' use a
/// cheap way to compare if two resource is same one.
///
/// # Notice
/// Compare two `ShareResource` just compare if it come form same resource not
/// Compare two `Resource` just compare if it come form same resource not
/// compare its content.
#[derive(Debug, Serialize, Deserialize)]
pub struct ShareResource<T>(Rc<T>);
pub struct Resource<T>(triomphe::Arc<T>);

impl<T> ShareResource<T> {
impl<T> Resource<T> {
#[inline]
pub fn new(v: T) -> Self { ShareResource(Rc::new(v)) }
pub fn new(v: T) -> Self { Resource(triomphe::Arc::new(v)) }

#[inline]
pub fn as_ptr(this: &Self) -> *const () { Rc::as_ptr(&this.0) as *const () }
pub fn as_ptr(this: &Self) -> *const () { triomphe::Arc::as_ptr(&this.0) as *const () }
}

impl<T> Clone for ShareResource<T> {
impl<T> Clone for Resource<T> {
#[inline]
fn clone(&self) -> Self { Self(self.0.clone()) }
}

impl<T> Deref for Resource<T> {
type Target = T;

fn deref(&self) -> &Self::Target {
match self {
Resource::Share(s) => s.deref(),
Resource::Local(l) => l,
}
}
}

impl<T> PartialEq for Resource<T> {
#[inline]
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Resource::Share(a), Resource::Share(b)) => a == b,
_ => false,
}
}
}

impl<T> Deref for ShareResource<T> {
type Target = T;

fn deref(&self) -> &Self::Target { self.0.deref() }
}

impl<T> PartialEq for ShareResource<T> {
#[inline]
fn eq(&self, other: &Self) -> bool { Rc::ptr_eq(&self.0, &other.0) }
}

impl<T> Eq for ShareResource<T> {}

impl<T> Hash for ShareResource<T> {
impl<T> PartialEq for Resource<T> {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) { Rc::as_ptr(&self.0).hash(state); }
fn eq(&self, other: &Self) -> bool { triomphe::Arc::ptr_eq(&self.0, &other.0) }
}

impl<T> From<T> for Resource<T> {
#[inline]
fn from(r: T) -> Self { Resource::Local(r) }
}
impl<T> Eq for Resource<T> {}

impl<T> From<ShareResource<T>> for Resource<T> {
impl<T> Hash for Resource<T> {
#[inline]
fn from(s: ShareResource<T>) -> Self { Resource::Share(s) }
fn hash<H: Hasher>(&self, state: &mut H) { triomphe::Arc::as_ptr(&self.0).hash(state); }
}

#[cfg(test)]
Expand All @@ -92,8 +51,8 @@ mod tests {

#[test]
fn compare() {
let a = ShareResource::new(5);
let b = ShareResource::new(5);
let a = Resource::new(5);
let b = Resource::new(5);
assert_ne!(a, b);

#[allow(clippy::redundant_clone)]
Expand All @@ -104,19 +63,18 @@ mod tests {

#[test]
fn hash() {
let a = ShareResource::new("a");
let a = Resource::new("a");
let mut map = std::collections::HashSet::new();
map.insert(a.clone());

assert!(!map.contains(&ShareResource::new("a")));
assert!(!map.contains(&Resource::new("a")));
assert!(map.contains(&a));
}

#[test]
fn share_local_compare() {
let s = ShareResource::new(1);
let l = Resource::Local(1);
assert_ne!(l, s.into());
assert_ne!(l, 1.into());
let a = Resource::new(1);
let b = Resource::new(1);
assert_ne!(b, a);
}
}
4 changes: 2 additions & 2 deletions core/src/builtin_widgets/image_widget.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::prelude::*;

impl Render for ShareResource<PixelImage> {
impl Render for Resource<PixelImage> {
fn perform_layout(&self, _: BoxClamp, _: &mut LayoutCtx) -> Size {
Size::new(self.width() as f32, self.height() as f32)
}
Expand All @@ -16,6 +16,6 @@ impl Render for ShareResource<PixelImage> {
}
}

impl Query for ShareResource<PixelImage> {
impl Query for Resource<PixelImage> {
crate::widget::impl_query_self_only!();
}
4 changes: 2 additions & 2 deletions core/src/builtin_widgets/theme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::{collections::HashMap, rc::Rc};

use ribir_algo::Sc;
pub use ribir_algo::{CowArc, ShareResource};
pub use ribir_algo::{CowArc, Resource};
use ribir_macros::Declare;

use crate::{fill_svgs, prelude::*};
Expand Down Expand Up @@ -53,7 +53,7 @@ pub struct InheritTheme {
/// icon size standard
pub icon_size: Option<IconSize>,
/// a collection of icons.
pub icons: Option<HashMap<NamedSvg, ShareResource<Svg>, ahash::RandomState>>,
pub icons: Option<HashMap<NamedSvg, Resource<Svg>, ahash::RandomState>>,
pub transitions_theme: Option<TransitionTheme>,
pub compose_decorators: Option<ComposeDecorators>,
pub custom_styles: Option<CustomStyles>,
Expand Down
14 changes: 6 additions & 8 deletions core/src/builtin_widgets/theme/icon_theme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub struct IconTheme {
/// icon size standard
pub icon_size: IconSize,
/// a collection of icons.
svgs: HashMap<NamedSvg, ShareResource<Svg>, ahash::RandomState>,
svgs: HashMap<NamedSvg, Resource<Svg>, ahash::RandomState>,
}

/// A five level standard of the size of icon in application.
Expand Down Expand Up @@ -44,7 +44,7 @@ macro_rules! define_named_svg {
macro_rules! fill_svgs {
($theme: expr, $($name: path: $path: literal),+) => {
$(
let icon = ShareResource::new(include_crate_svg!($path));
let icon = Resource::new(include_crate_svg!($path));
$theme.set_svg($name, icon);
)+
};
Expand All @@ -66,17 +66,15 @@ impl Compose for NamedSvg {
impl IconTheme {
pub fn new(icon_size: IconSize) -> Self {
let svg = include_crate_svg!("./icons/miss_icon.svg");
let miss_icon = ShareResource::new(svg);
let miss_icon = Resource::new(svg);
let mut icons = HashMap::<_, _, ahash::RandomState>::default();
icons.insert(MISS_ICON, miss_icon);

Self { icon_size, svgs: icons }
}

#[inline]
pub fn set_svg(
&mut self, name: NamedSvg, icon: ShareResource<Svg>,
) -> Option<ShareResource<Svg>> {
pub fn set_svg(&mut self, name: NamedSvg, icon: Resource<Svg>) -> Option<Resource<Svg>> {
self.svgs.insert(name, icon)
}

Expand All @@ -101,7 +99,7 @@ impl NamedSvg {

/// get the svg icon of the ident from the context if it have otherwise return
/// a default icon.
pub fn of_or_miss(self, ctx: &BuildCtx) -> ShareResource<Svg> {
pub fn of_or_miss(self, ctx: &BuildCtx) -> Resource<Svg> {
ctx
.find_cfg(|t| match t {
Theme::Full(t) => t.icon_theme.svgs.get(&self).or_else(|| {
Expand All @@ -118,7 +116,7 @@ impl NamedSvg {
}

/// get the svg icon of the ident from the context if it have.
pub fn of(self, ctx: &BuildCtx) -> Option<ShareResource<Svg>> {
pub fn of(self, ctx: &BuildCtx) -> Option<Resource<Svg>> {
ctx
.find_cfg(|t| match t {
Theme::Full(t) => t.icon_theme.svgs.get(&self),
Expand Down
6 changes: 3 additions & 3 deletions core/src/widget.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ impl<W: ComposeChild<Child = Option<C>> + 'static, C> ComposeChildBuilder for W
}
}

impl<T: Query> Query for ShareResource<T> {
impl<T: Query> Query for Resource<T> {
impl_proxy_and_self_query!(deref());
}
impl<T: Query> Query for Sc<T> {
Expand All @@ -392,7 +392,7 @@ impl<T: Query> Query for Sc<T> {
impl<T: Query> Query for RefCell<T> {
impl_proxy_and_self_query!(borrow());
}
impl_proxy_render!(proxy deref(), ShareResource<T>, <T>, where T: Render + 'static);
impl_proxy_render!(proxy deref(), Resource<T>, <T>, where T: Render + 'static);

pub(crate) fn hit_test_impl(ctx: &HitTestCtx, pos: Point) -> bool {
ctx
Expand Down Expand Up @@ -485,5 +485,5 @@ mod tests {
}
impl_wrap_test!(Sc);
impl_wrap_test!(RefCell);
impl_wrap_test!(ShareResource);
impl_wrap_test!(Resource);
}
2 changes: 1 addition & 1 deletion examples/messages/src/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl Compose for MessageList {
let name = message.avatar.to_string();
let avatar = format!("{}/examples/attachments/3DDD-{name}.png", env!("CARGO_WORKSPACE_DIR"));
let img = PixelImage::from_png(&std::fs::read(avatar).unwrap());
ShareResource::new(img)
Resource::new(img)
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions examples/storybook/src/storybook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ fn content() -> impl WidgetBuilder {
line_number: 2usize,
@Leading {
@Avatar {
@ { ShareResource::new(PixelImage::from_png(include_bytes!("../../attachments/3DDD-1.png"))) }
@ { Resource::new(PixelImage::from_png(include_bytes!("../../attachments/3DDD-1.png"))) }
}
}
@ { HeadlineText(Label::new("Two lines list item")) }
Expand All @@ -277,7 +277,7 @@ fn content() -> impl WidgetBuilder {
@Divider { indent: 16. }
@ListItem {
@Leading {
@ { Poster(ShareResource::new(PixelImage::from_png(include_bytes!("../../attachments/3DDD-3.png")))) }
@ { Poster(Resource::new(PixelImage::from_png(include_bytes!("../../attachments/3DDD-3.png")))) }
}
@ { HeadlineText(Label::new("One lines list item")) }
@ { SupportingText(Label::new("One lines supporting text")) }
Expand Down
9 changes: 4 additions & 5 deletions gpu/src/gpu_backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,7 @@ pub fn add_draw_rect_vertices<Attr: Copy>(
#[cfg(feature = "wgpu")]
#[cfg(test)]
mod tests {
use ribir_algo::ShareResource;
use ribir_algo::Resource;
use ribir_dev_helper::*;
use ribir_geom::*;
use ribir_painter::{Brush, Painter, Path, Radius, Svg};
Expand All @@ -525,7 +525,7 @@ mod tests {
let mut painter = painter(Size::new(512., 512.));

let img = PixelImage::from_png(include_bytes!("../imgs/leaves.png"));
let share_img = ShareResource::new(img);
let share_img = Resource::new(img);

let img_brush = Brush::Image(share_img);

Expand Down Expand Up @@ -565,8 +565,7 @@ mod tests {
.rect(&rect)
.fill();

let leaves_brush =
ShareResource::new(PixelImage::from_png(include_bytes!("../imgs/leaves.png")));
let leaves_brush = Resource::new(PixelImage::from_png(include_bytes!("../imgs/leaves.png")));

painter
.set_brush(leaves_brush)
Expand Down Expand Up @@ -631,7 +630,7 @@ mod tests {

painter_backend_eq_image_test!(draw_partial_img);
fn draw_partial_img() -> Painter {
let img = ShareResource::new(PixelImage::from_png(include_bytes!("../imgs/leaves.png")));
let img = Resource::new(PixelImage::from_png(include_bytes!("../imgs/leaves.png")));
let m_width = img.width() as f32;
let m_height = img.height() as f32;
let mut painter = painter(Size::new(m_width * 2., m_height * 2.));
Expand Down
10 changes: 5 additions & 5 deletions gpu/src/gpu_backend/textures_mgr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{

use guillotiere::euclid::SideOffsets2D;
use rayon::{prelude::ParallelIterator, slice::ParallelSlice};
use ribir_algo::ShareResource;
use ribir_algo::Resource;
use ribir_geom::{rect_corners, DevicePoint, DeviceRect, DeviceSize, Point, Transform};
use ribir_painter::{
image::ColorFormat, AntiAliasing, PaintPath, Path, PathSegment, PixelImage, Vertex, VertexBuffers,
Expand All @@ -28,7 +28,7 @@ pub(super) enum TextureID {

pub(super) struct TexturesMgr<T: Texture> {
alpha_atlas: Atlas<T, PathKey, f32>,
rgba_atlas: Atlas<T, ShareResource<PixelImage>, ()>,
rgba_atlas: Atlas<T, Resource<PixelImage>, ()>,
fill_task: Vec<FillTask>,
fill_task_buffers: VertexBuffers<f32>,
}
Expand Down Expand Up @@ -187,7 +187,7 @@ where
}

pub(super) fn store_image(
&mut self, img: &ShareResource<PixelImage>, gpu_impl: &mut T::Host,
&mut self, img: &Resource<PixelImage>, gpu_impl: &mut T::Host,
) -> TextureSlice {
match img.color_format() {
ColorFormat::Rgba8 => {
Expand Down Expand Up @@ -540,14 +540,14 @@ pub mod tests {
use super::*;
use crate::{WgpuImpl, WgpuTexture};

pub fn color_image(color: Color, width: u32, height: u32) -> ShareResource<PixelImage> {
pub fn color_image(color: Color, width: u32, height: u32) -> Resource<PixelImage> {
let data = std::iter::repeat(color.into_components())
.take(width as usize * height as usize)
.flatten()
.collect::<Vec<_>>();

let img = PixelImage::new(Cow::Owned(data), width, height, ColorFormat::Rgba8);
ShareResource::new(img)
Resource::new(img)
}

#[test]
Expand Down
Loading

0 comments on commit 483bfec

Please sign in to comment.