From 7bcbfe071256fd6025468fcd917d9dcfa16d2b6c Mon Sep 17 00:00:00 2001 From: Kevin Reid Date: Thu, 20 Feb 2025 12:55:56 -0800 Subject: [PATCH] wgpu-core: Adjust imports to allow `no_std`. Dependencies on `std` that still exist: * Locks * `std::error::Error` (waiting for Rust 1.81) * `std::os::raw::c_char` for FFI * `thread_local` and `Backtrace` in `snatch` --- wgpu-core/src/binding_model.rs | 63 ++++++++++++----------- wgpu-core/src/command/allocator.rs | 2 + wgpu-core/src/command/bind.rs | 20 +++---- wgpu-core/src/command/bundle.rs | 27 +++++++--- wgpu-core/src/command/clear.rs | 3 +- wgpu-core/src/command/compute.rs | 24 +++++---- wgpu-core/src/command/compute_command.rs | 5 +- wgpu-core/src/command/draw.rs | 6 ++- wgpu-core/src/command/memory_init.rs | 6 ++- wgpu-core/src/command/mod.rs | 15 +++--- wgpu-core/src/command/query.rs | 6 ++- wgpu-core/src/command/ray_tracing.rs | 21 ++++---- wgpu-core/src/command/render.rs | 19 +++---- wgpu-core/src/command/render_command.rs | 13 ++--- wgpu-core/src/command/timestamp_writes.rs | 2 +- wgpu-core/src/command/transfer.rs | 12 ++--- wgpu-core/src/device/bgl.rs | 2 +- wgpu-core/src/device/global.rs | 17 +++--- wgpu-core/src/device/life.rs | 9 ++-- wgpu-core/src/device/mod.rs | 11 ++-- wgpu-core/src/device/queue.rs | 30 +++++------ wgpu-core/src/device/ray_tracing.rs | 4 +- wgpu-core/src/device/resource.rs | 54 ++++++++++--------- wgpu-core/src/device/trace.rs | 11 ++-- wgpu-core/src/error.rs | 3 +- wgpu-core/src/global.rs | 5 +- wgpu-core/src/hash_utils.rs | 8 +-- wgpu-core/src/hub.rs | 4 +- wgpu-core/src/id.rs | 4 +- wgpu-core/src/identity.rs | 4 +- wgpu-core/src/indirect_validation.rs | 7 +-- wgpu-core/src/init_tracker/buffer.rs | 3 +- wgpu-core/src/init_tracker/mod.rs | 6 ++- wgpu-core/src/init_tracker/texture.rs | 5 +- wgpu-core/src/instance.rs | 31 ++++++----- wgpu-core/src/lib.rs | 17 ++++-- wgpu-core/src/lock/observing.rs | 10 ++-- wgpu-core/src/lock/ranked.rs | 25 ++++----- wgpu-core/src/lock/vanilla.rs | 20 +++---- wgpu-core/src/pipeline.rs | 17 ++++-- wgpu-core/src/pipeline_cache.rs | 9 ++-- wgpu-core/src/pool.rs | 21 ++++---- wgpu-core/src/present.rs | 7 +-- wgpu-core/src/ray_tracing.rs | 17 +++--- wgpu-core/src/registry.rs | 10 ++-- wgpu-core/src/resource.rs | 51 +++++++++--------- wgpu-core/src/scratch.rs | 8 +-- wgpu-core/src/snatch.rs | 19 ++++--- wgpu-core/src/storage.rs | 9 ++-- wgpu-core/src/track/buffer.rs | 10 ++-- wgpu-core/src/track/metadata.rs | 2 + wgpu-core/src/track/mod.rs | 11 ++-- wgpu-core/src/track/range.rs | 4 +- wgpu-core/src/track/stateless.rs | 4 +- wgpu-core/src/track/texture.rs | 6 +-- wgpu-core/src/validation.rs | 11 +++- wgpu-core/src/weak_vec.rs | 4 +- 57 files changed, 427 insertions(+), 327 deletions(-) diff --git a/wgpu-core/src/binding_model.rs b/wgpu-core/src/binding_model.rs index 1aa4cf7a7..111442270 100644 --- a/wgpu-core/src/binding_model.rs +++ b/wgpu-core/src/binding_model.rs @@ -1,3 +1,21 @@ +use alloc::{ + borrow::{Cow, ToOwned}, + boxed::Box, + string::String, + sync::{Arc, Weak}, + vec::Vec, +}; +use core::{fmt, mem::ManuallyDrop, ops::Range}; +use std::sync::OnceLock; + +use arrayvec::ArrayVec; +use thiserror::Error; + +#[cfg(feature = "serde")] +use serde::Deserialize; +#[cfg(feature = "serde")] +use serde::Serialize; + use crate::{ device::{ bgl, Device, DeviceError, MissingDownlevelFlags, MissingFeatures, SHADER_STAGE_COUNT, @@ -7,7 +25,7 @@ use crate::{ pipeline::{ComputePipeline, RenderPipeline}, resource::{ Buffer, DestroyedResourceError, InvalidResourceError, Labeled, MissingBufferUsageError, - MissingTextureUsageError, ResourceErrorIdent, Sampler, TextureView, TrackingData, + MissingTextureUsageError, ResourceErrorIdent, Sampler, TextureView, Tlas, TrackingData, }, resource_log, snatch::{SnatchGuard, Snatchable}, @@ -15,23 +33,6 @@ use crate::{ Label, }; -use arrayvec::ArrayVec; - -#[cfg(feature = "serde")] -use serde::Deserialize; -#[cfg(feature = "serde")] -use serde::Serialize; - -use std::{ - borrow::Cow, - mem::ManuallyDrop, - ops::Range, - sync::{Arc, OnceLock, Weak}, -}; - -use crate::resource::Tlas; -use thiserror::Error; - #[derive(Clone, Debug, Error)] #[non_exhaustive] pub enum BindGroupLayoutEntryError { @@ -477,9 +478,9 @@ where [BufferBinding]: ToOwned, [S]: ToOwned, [TV]: ToOwned, - <[BufferBinding] as ToOwned>::Owned: std::fmt::Debug, - <[S] as ToOwned>::Owned: std::fmt::Debug, - <[TV] as ToOwned>::Owned: std::fmt::Debug, + <[BufferBinding] as ToOwned>::Owned: fmt::Debug, + <[S] as ToOwned>::Owned: fmt::Debug, + <[TV] as ToOwned>::Owned: fmt::Debug, { /// Slot for which binding provides resource. Corresponds to an entry of the same /// binding index in the [`BindGroupLayoutDescriptor`]. @@ -510,11 +511,11 @@ pub struct BindGroupDescriptor< [BufferBinding]: ToOwned, [S]: ToOwned, [TV]: ToOwned, - <[BufferBinding] as ToOwned>::Owned: std::fmt::Debug, - <[S] as ToOwned>::Owned: std::fmt::Debug, - <[TV] as ToOwned>::Owned: std::fmt::Debug, + <[BufferBinding] as ToOwned>::Owned: fmt::Debug, + <[S] as ToOwned>::Owned: fmt::Debug, + <[TV] as ToOwned>::Owned: fmt::Debug, [BindGroupEntry<'a, B, S, TV, TLAS>]: ToOwned, - <[BindGroupEntry<'a, B, S, TV, TLAS>] as ToOwned>::Owned: std::fmt::Debug, + <[BindGroupEntry<'a, B, S, TV, TLAS>] as ToOwned>::Owned: fmt::Debug, { /// Debug label of the bind group. /// @@ -564,8 +565,8 @@ pub(crate) enum ExclusivePipeline { Compute(Weak), } -impl std::fmt::Display for ExclusivePipeline { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Display for ExclusivePipeline { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ExclusivePipeline::None => f.write_str("None"), ExclusivePipeline::Render(p) => { @@ -703,7 +704,7 @@ pub enum PushConstantUploadError { pub struct PipelineLayoutDescriptor<'a, BGL = BindGroupLayoutId> where [BGL]: ToOwned, - <[BGL] as ToOwned>::Owned: std::fmt::Debug, + <[BGL] as ToOwned>::Owned: fmt::Debug, { /// Debug label of the pipeline layout. /// @@ -866,9 +867,9 @@ where [BufferBinding]: ToOwned, [S]: ToOwned, [TV]: ToOwned, - <[BufferBinding] as ToOwned>::Owned: std::fmt::Debug, - <[S] as ToOwned>::Owned: std::fmt::Debug, - <[TV] as ToOwned>::Owned: std::fmt::Debug, + <[BufferBinding] as ToOwned>::Owned: fmt::Debug, + <[S] as ToOwned>::Owned: fmt::Debug, + <[TV] as ToOwned>::Owned: fmt::Debug, { Buffer(BufferBinding), #[cfg_attr( diff --git a/wgpu-core/src/command/allocator.rs b/wgpu-core/src/command/allocator.rs index 82839c37e..21b81c978 100644 --- a/wgpu-core/src/command/allocator.rs +++ b/wgpu-core/src/command/allocator.rs @@ -1,3 +1,5 @@ +use alloc::{boxed::Box, vec::Vec}; + use crate::lock::{rank, Mutex}; /// A pool of free [`wgpu_hal::CommandEncoder`]s, owned by a `Device`. diff --git a/wgpu-core/src/command/bind.rs b/wgpu-core/src/command/bind.rs index 2e1ffa030..445313214 100644 --- a/wgpu-core/src/command/bind.rs +++ b/wgpu-core/src/command/bind.rs @@ -1,4 +1,7 @@ -use std::sync::Arc; +use alloc::{boxed::Box, sync::Arc, vec::Vec}; + +use arrayvec::ArrayVec; +use thiserror::Error; use crate::{ binding_model::{BindGroup, LateMinBufferBindingSizeMismatch, PipelineLayout}, @@ -7,10 +10,14 @@ use crate::{ resource::{Labeled, ResourceErrorIdent}, }; -use arrayvec::ArrayVec; -use thiserror::Error; - mod compat { + use alloc::{ + string::{String, ToString as _}, + sync::{Arc, Weak}, + vec::Vec, + }; + use core::{num::NonZeroU32, ops::Range}; + use arrayvec::ArrayVec; use thiserror::Error; use wgt::{BindingType, ShaderStages}; @@ -20,11 +27,6 @@ mod compat { error::MultiError, resource::{Labeled, ParentDevice, ResourceErrorIdent}, }; - use std::{ - num::NonZeroU32, - ops::Range, - sync::{Arc, Weak}, - }; pub(crate) enum Error { Incompatible { diff --git a/wgpu-core/src/command/bundle.rs b/wgpu-core/src/command/bundle.rs index 85646af04..099446426 100644 --- a/wgpu-core/src/command/bundle.rs +++ b/wgpu-core/src/command/bundle.rs @@ -78,6 +78,21 @@ index format changes. #![allow(clippy::reversed_empty_ranges)] +use alloc::{ + borrow::{Cow, ToOwned as _}, + string::String, + sync::Arc, + vec::Vec, +}; +use core::{ + mem::size_of, + num::{NonZeroU32, NonZeroU64}, + ops::Range, +}; + +use arrayvec::ArrayVec; +use thiserror::Error; + use crate::{ binding_model::{BindError, BindGroup, PipelineLayout}, command::{ @@ -101,10 +116,6 @@ use crate::{ track::RenderBundleScope, Label, LabelHelpers, }; -use arrayvec::ArrayVec; - -use std::{borrow::Cow, mem::size_of, num::NonZeroU32, ops::Range, sync::Arc}; -use thiserror::Error; use super::{ render_command::{ArcRenderCommand, RenderCommand}, @@ -455,7 +466,7 @@ impl RenderBundleEncoder { let render_bundle = RenderBundle { base: BasePass { - label: desc.label.as_ref().map(|cow| cow.to_string()), + label: desc.label.as_deref().map(str::to_owned), commands, dynamic_offsets: flat_dynamic_offsets, string_data: self.base.string_data, @@ -591,7 +602,7 @@ fn set_index_buffer( buffer_id: id::Id, index_format: wgt::IndexFormat, offset: u64, - size: Option, + size: Option, ) -> Result<(), RenderBundleErrorInner> { let buffer = buffer_guard.get(buffer_id).get()?; @@ -624,7 +635,7 @@ fn set_vertex_buffer( slot: u32, buffer_id: id::Id, offset: u64, - size: Option, + size: Option, ) -> Result<(), RenderBundleErrorInner> { let max_vertex_buffers = state.device.limits.max_vertex_buffers; if slot >= max_vertex_buffers { @@ -1493,7 +1504,7 @@ where pub mod bundle_ffi { use super::{RenderBundleEncoder, RenderCommand}; use crate::{id, RawString}; - use std::{convert::TryInto, slice}; + use core::{convert::TryInto, slice}; use wgt::{BufferAddress, BufferSize, DynamicOffset, IndexFormat}; /// # Safety diff --git a/wgpu-core/src/command/clear.rs b/wgpu-core/src/command/clear.rs index 6efb7eeb5..8feb1e389 100644 --- a/wgpu-core/src/command/clear.rs +++ b/wgpu-core/src/command/clear.rs @@ -1,4 +1,5 @@ -use std::{ops::Range, sync::Arc}; +use alloc::{sync::Arc, vec::Vec}; +use core::ops::Range; #[cfg(feature = "trace")] use crate::device::trace::Command as TraceCommand; diff --git a/wgpu-core/src/command/compute.rs b/wgpu-core/src/command/compute.rs index 8ebdcb5e6..d973176c6 100644 --- a/wgpu-core/src/command/compute.rs +++ b/wgpu-core/src/command/compute.rs @@ -1,12 +1,20 @@ +use thiserror::Error; +use wgt::{BufferAddress, DynamicOffset}; + +use alloc::{borrow::Cow, boxed::Box, sync::Arc, vec::Vec}; +use core::{fmt, mem::size_of, str}; + use crate::{ binding_model::{ BindError, BindGroup, LateMinBufferBindingSizeMismatch, PushConstantUploadError, }, command::{ - bind::Binder, + bind::{Binder, BinderError}, compute_command::ArcComputeCommand, end_pipeline_statistics_query, - memory_init::{fixup_discarded_surfaces, SurfacesInDiscardState}, + memory_init::{ + fixup_discarded_surfaces, CommandBufferTextureMemoryActions, SurfacesInDiscardState, + }, validate_and_begin_pipeline_statistics_query, ArcPassTimestampWrites, BasePass, BindGroupStateChange, CommandBuffer, CommandEncoderError, MapPassErr, PassErrorScope, PassTimestampWrites, QueryUseError, StateChange, @@ -16,6 +24,7 @@ use crate::{ hal_label, id, init_tracker::{BufferInitTrackerAction, MemoryInitKind}, pipeline::ComputePipeline, + ray_tracing::TlasAction, resource::{ self, Buffer, DestroyedResourceError, InvalidResourceError, Labeled, MissingBufferUsageError, ParentDevice, @@ -25,13 +34,6 @@ use crate::{ Label, }; -use thiserror::Error; -use wgt::{BufferAddress, DynamicOffset}; - -use super::{bind::BinderError, memory_init::CommandBufferTextureMemoryActions}; -use crate::ray_tracing::TlasAction; -use std::{fmt, mem::size_of, str, sync::Arc}; - pub struct ComputePass { /// All pass data & records is stored here. /// @@ -289,7 +291,7 @@ impl Global { let hub = &self.hub; let mut arc_desc = ArcComputePassDescriptor { - label: desc.label.as_deref().map(std::borrow::Cow::Borrowed), + label: desc.label.as_deref().map(Cow::Borrowed), timestamp_writes: None, // Handle only once we resolved the encoder. }; @@ -363,7 +365,7 @@ impl Global { let (mut compute_pass, encoder_error) = self.command_encoder_begin_compute_pass( encoder_id, &ComputePassDescriptor { - label: label.as_deref().map(std::borrow::Cow::Borrowed), + label: label.as_deref().map(Cow::Borrowed), timestamp_writes: timestamp_writes.cloned(), }, ); diff --git a/wgpu-core/src/command/compute_command.rs b/wgpu-core/src/command/compute_command.rs index e8c9ad997..249713db6 100644 --- a/wgpu-core/src/command/compute_command.rs +++ b/wgpu-core/src/command/compute_command.rs @@ -1,4 +1,4 @@ -use std::sync::Arc; +use alloc::sync::Arc; use crate::{ binding_model::BindGroup, @@ -73,8 +73,9 @@ impl ComputeCommand { pub fn resolve_compute_command_ids( hub: &crate::hub::Hub, commands: &[ComputeCommand], - ) -> Result, super::ComputePassError> { + ) -> Result, super::ComputePassError> { use super::{ComputePassError, PassErrorScope}; + use alloc::vec::Vec; let buffers_guard = hub.buffers.read(); let bind_group_guard = hub.bind_groups.read(); diff --git a/wgpu-core/src/command/draw.rs b/wgpu-core/src/command/draw.rs index 3b545f345..d2bdd1903 100644 --- a/wgpu-core/src/command/draw.rs +++ b/wgpu-core/src/command/draw.rs @@ -1,3 +1,7 @@ +use alloc::boxed::Box; + +use thiserror::Error; + use crate::{ binding_model::{LateMinBufferBindingSizeMismatch, PushConstantUploadError}, resource::{ @@ -7,8 +11,6 @@ use crate::{ track::ResourceUsageCompatibilityError, }; -use thiserror::Error; - use super::bind::BinderError; /// Error validating a draw call. diff --git a/wgpu-core/src/command/memory_init.rs b/wgpu-core/src/command/memory_init.rs index 7f3bb1064..df2601a1e 100644 --- a/wgpu-core/src/command/memory_init.rs +++ b/wgpu-core/src/command/memory_init.rs @@ -1,4 +1,8 @@ -use std::{ops::Range, sync::Arc, vec::Drain}; +use alloc::{ + sync::Arc, + vec::{Drain, Vec}, +}; +use core::ops::Range; use hashbrown::hash_map::Entry; diff --git a/wgpu-core/src/command/mod.rs b/wgpu-core/src/command/mod.rs index a699545c0..abc804373 100644 --- a/wgpu-core/src/command/mod.rs +++ b/wgpu-core/src/command/mod.rs @@ -14,8 +14,9 @@ mod timestamp_writes; mod transfer; mod transition_resources; -use std::mem::{self, ManuallyDrop}; -use std::sync::Arc; +use alloc::{borrow::ToOwned as _, boxed::Box, string::String, sync::Arc, vec::Vec}; +use core::mem::{self, ManuallyDrop}; +use core::ops; pub(crate) use self::clear::clear_texture; pub use self::{ @@ -202,7 +203,7 @@ impl<'a> Drop for RecordingGuard<'a> { } } -impl<'a> std::ops::Deref for RecordingGuard<'a> { +impl<'a> ops::Deref for RecordingGuard<'a> { type Target = CommandBufferMutable; fn deref(&self) -> &Self::Target { @@ -213,7 +214,7 @@ impl<'a> std::ops::Deref for RecordingGuard<'a> { } } -impl<'a> std::ops::DerefMut for RecordingGuard<'a> { +impl<'a> ops::DerefMut for RecordingGuard<'a> { fn deref_mut(&mut self) -> &mut Self::Target { match self.inner { CommandEncoderStatus::Recording(command_buffer_mutable) => command_buffer_mutable, @@ -707,7 +708,7 @@ pub struct BasePass { impl BasePass { fn new(label: &Label) -> Self { Self { - label: label.as_ref().map(|cow| cow.to_string()), + label: label.as_deref().map(str::to_owned), commands: Vec::new(), dynamic_offsets: Vec::new(), string_data: Vec::new(), @@ -783,7 +784,7 @@ impl Global { #[cfg(feature = "trace")] if let Some(ref mut list) = cmd_buf_data.commands { - list.push(TraceCommand::PushDebugGroup(label.to_string())); + list.push(TraceCommand::PushDebugGroup(label.to_owned())); } let cmd_buf_raw = cmd_buf_data.encoder.open()?; @@ -818,7 +819,7 @@ impl Global { #[cfg(feature = "trace")] if let Some(ref mut list) = cmd_buf_data.commands { - list.push(TraceCommand::InsertDebugMarker(label.to_string())); + list.push(TraceCommand::InsertDebugMarker(label.to_owned())); } if !cmd_buf diff --git a/wgpu-core/src/command/query.rs b/wgpu-core/src/command/query.rs index 6ec7069bd..737ceaee8 100644 --- a/wgpu-core/src/command/query.rs +++ b/wgpu-core/src/command/query.rs @@ -1,3 +1,6 @@ +use alloc::{sync::Arc, vec, vec::Vec}; +use core::{iter, mem}; + #[cfg(feature = "trace")] use crate::device::trace::Command as TraceCommand; use crate::{ @@ -13,7 +16,6 @@ use crate::{ track::{StatelessTracker, TrackerIndex}, FastHashMap, }; -use std::{iter, sync::Arc}; use thiserror::Error; use wgt::BufferAddress; @@ -39,7 +41,7 @@ impl QueryResetMap { ) }); - std::mem::replace(&mut vec_pair.0[query as usize], true) + mem::replace(&mut vec_pair.0[query as usize], true) } pub fn reset_queries(&mut self, raw_encoder: &mut dyn hal::DynCommandEncoder) { diff --git a/wgpu-core/src/command/ray_tracing.rs b/wgpu-core/src/command/ray_tracing.rs index a0ad48ca8..ea4ca1707 100644 --- a/wgpu-core/src/command/ray_tracing.rs +++ b/wgpu-core/src/command/ray_tracing.rs @@ -1,4 +1,15 @@ +use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use core::{ + cmp::max, + num::NonZeroU64, + ops::{Deref, Range}, + sync::atomic::Ordering, +}; + +use wgt::{math::align_to, BufferUsages, BufferUses, Features}; + use crate::{ + command::CommandBufferMutable, device::queue::TempResource, global::Global, hub::Hub, @@ -17,16 +28,6 @@ use crate::{ FastHashSet, }; -use wgt::{math::align_to, BufferUsages, BufferUses, Features}; - -use super::CommandBufferMutable; -use std::{ - cmp::max, - num::NonZeroU64, - ops::{Deref, Range}, - sync::{atomic::Ordering, Arc}, -}; - struct TriangleBufferStore<'a> { vertex_buffer: Arc, vertex_transition: Option>, diff --git a/wgpu-core/src/command/render.rs b/wgpu-core/src/command/render.rs index d7c825ae3..cf14d6b4d 100644 --- a/wgpu-core/src/command/render.rs +++ b/wgpu-core/src/command/render.rs @@ -1,3 +1,13 @@ +use alloc::{borrow::Cow, sync::Arc, vec::Vec}; +use core::{fmt, mem::size_of, num::NonZeroU32, ops::Range, str}; + +use arrayvec::ArrayVec; +use thiserror::Error; +use wgt::{ + BufferAddress, BufferSize, BufferUsages, Color, DynamicOffset, IndexFormat, ShaderStages, + TextureSelector, TextureUsages, TextureViewDimension, VertexStepMode, +}; + use crate::binding_model::BindGroup; use crate::command::{ validate_and_begin_occlusion_query, validate_and_begin_pipeline_statistics_query, @@ -33,20 +43,11 @@ use crate::{ Label, }; -use arrayvec::ArrayVec; -use thiserror::Error; -use wgt::{ - BufferAddress, BufferSize, BufferUsages, Color, DynamicOffset, IndexFormat, ShaderStages, - TextureSelector, TextureUsages, TextureViewDimension, VertexStepMode, -}; - #[cfg(feature = "serde")] use serde::Deserialize; #[cfg(feature = "serde")] use serde::Serialize; -use std::{borrow::Cow, fmt, mem::size_of, num::NonZeroU32, ops::Range, str, sync::Arc}; - use super::render_command::ArcRenderCommand; use super::{ memory_init::TextureSurfaceDiscard, CommandBufferTextureMemoryActions, CommandEncoder, diff --git a/wgpu-core/src/command/render_command.rs b/wgpu-core/src/command/render_command.rs index 8585f645e..b7fa73915 100644 --- a/wgpu-core/src/command/render_command.rs +++ b/wgpu-core/src/command/render_command.rs @@ -1,14 +1,14 @@ +use alloc::sync::Arc; + +use wgt::{BufferAddress, BufferSize, Color}; + +use super::{Rect, RenderBundle}; use crate::{ binding_model::BindGroup, id, pipeline::RenderPipeline, resource::{Buffer, QuerySet}, }; -use wgt::{BufferAddress, BufferSize, Color}; - -use std::sync::Arc; - -use super::{Rect, RenderBundle}; #[doc(hidden)] #[derive(Clone, Copy, Debug)] @@ -127,8 +127,9 @@ impl RenderCommand { pub fn resolve_render_command_ids( hub: &crate::hub::Hub, commands: &[RenderCommand], - ) -> Result, super::RenderPassError> { + ) -> Result, super::RenderPassError> { use super::{DrawKind, PassErrorScope, RenderPassError}; + use alloc::vec::Vec; let buffers_guard = hub.buffers.read(); let bind_group_guard = hub.bind_groups.read(); diff --git a/wgpu-core/src/command/timestamp_writes.rs b/wgpu-core/src/command/timestamp_writes.rs index 5e5fad5ec..8519ff3bd 100644 --- a/wgpu-core/src/command/timestamp_writes.rs +++ b/wgpu-core/src/command/timestamp_writes.rs @@ -1,4 +1,4 @@ -use std::sync::Arc; +use alloc::sync::Arc; use crate::id; diff --git a/wgpu-core/src/command/transfer.rs b/wgpu-core/src/command/transfer.rs index 1113e9b3e..97a4ec20f 100644 --- a/wgpu-core/src/command/transfer.rs +++ b/wgpu-core/src/command/transfer.rs @@ -1,3 +1,9 @@ +use alloc::{sync::Arc, vec::Vec}; + +use arrayvec::ArrayVec; +use thiserror::Error; +use wgt::{BufferAddress, BufferUsages, Extent3d, TextureSelector, TextureUsages}; + #[cfg(feature = "trace")] use crate::device::trace::Command as TraceCommand; use crate::{ @@ -18,12 +24,6 @@ use crate::{ snatch::SnatchGuard, }; -use arrayvec::ArrayVec; -use thiserror::Error; -use wgt::{BufferAddress, BufferUsages, Extent3d, TextureSelector, TextureUsages}; - -use std::sync::Arc; - use super::{ClearError, CommandBufferMutable}; pub type TexelCopyBufferInfo = wgt::TexelCopyBufferInfo; diff --git a/wgpu-core/src/device/bgl.rs b/wgpu-core/src/device/bgl.rs index 9b7bdc0fe..482ed1754 100644 --- a/wgpu-core/src/device/bgl.rs +++ b/wgpu-core/src/device/bgl.rs @@ -1,4 +1,4 @@ -use std::hash::{Hash, Hasher}; +use core::hash::{Hash, Hasher}; use crate::{ binding_model::{self}, diff --git a/wgpu-core/src/device/global.rs b/wgpu-core/src/device/global.rs index 2493e618e..5b56fe99c 100644 --- a/wgpu-core/src/device/global.rs +++ b/wgpu-core/src/device/global.rs @@ -1,3 +1,6 @@ +use alloc::{borrow::Cow, boxed::Box, string::String, sync::Arc, vec::Vec}; +use core::{ptr::NonNull, sync::atomic::Ordering}; + #[cfg(feature = "trace")] use crate::device::trace; use crate::{ @@ -28,12 +31,6 @@ use crate::{ use wgt::{BufferAddress, TextureFormat}; -use std::{ - borrow::Cow, - ptr::NonNull, - sync::{atomic::Ordering, Arc}, -}; - use super::{ImplicitPipelineIds, UserClosures}; impl Global { @@ -112,7 +109,7 @@ impl Global { #[cfg(feature = "trace")] if let Some(ref mut trace) = *device.trace.lock() { let mut desc = desc.clone(); - let mapped_at_creation = std::mem::replace(&mut desc.mapped_at_creation, false); + let mapped_at_creation = core::mem::replace(&mut desc.mapped_at_creation, false); if mapped_at_creation && !desc.usage.contains(wgt::BufferUsages::MAP_WRITE) { desc.usage |= wgt::BufferUsages::COPY_DST; } @@ -239,7 +236,7 @@ impl Global { } .map_err(|e| device.handle_hal_error(e))?; - unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), mapping.ptr.as_ptr(), data.len()) }; + unsafe { core::ptr::copy_nonoverlapping(data.as_ptr(), mapping.ptr.as_ptr(), data.len()) }; if !mapping.is_coherent { #[allow(clippy::single_range_in_vec_init)] @@ -968,7 +965,7 @@ impl Global { #[cfg(feature = "trace")] if let Some(ref mut trace) = *device.trace.lock() { let data = trace.make_binary("spv", unsafe { - std::slice::from_raw_parts(source.as_ptr().cast::(), source.len() * 4) + core::slice::from_raw_parts(source.as_ptr().cast::(), source.len() * 4) }); trace.add(trace::Action::CreateShaderModule { id: fid.id(), @@ -1809,7 +1806,7 @@ impl Global { Err(_) => break 'error E::UnsupportedQueueFamily, }; - let mut hal_view_formats = vec![]; + let mut hal_view_formats = Vec::new(); for format in config.view_formats.iter() { if *format == config.format { continue; diff --git a/wgpu-core/src/device/life.rs b/wgpu-core/src/device/life.rs index 1e585f3bb..7e20c53a9 100644 --- a/wgpu-core/src/device/life.rs +++ b/wgpu-core/src/device/life.rs @@ -1,3 +1,8 @@ +use alloc::{sync::Arc, vec::Vec}; + +use smallvec::SmallVec; +use thiserror::Error; + use crate::{ device::{ queue::{EncoderInFlight, SubmittedWorkDoneClosure, TempResource}, @@ -7,10 +12,6 @@ use crate::{ snatch::SnatchGuard, SubmissionIndex, }; -use smallvec::SmallVec; - -use std::sync::Arc; -use thiserror::Error; /// A command submitted to the GPU for execution. /// diff --git a/wgpu-core/src/device/mod.rs b/wgpu-core/src/device/mod.rs index bb2ffd6b0..5bb1aad6f 100644 --- a/wgpu-core/src/device/mod.rs +++ b/wgpu-core/src/device/mod.rs @@ -1,3 +1,6 @@ +use alloc::{boxed::Box, string::String, vec::Vec}; +use core::{fmt, num::NonZeroU32}; + use crate::{ binding_model, hub::Hub, @@ -15,8 +18,6 @@ use smallvec::SmallVec; use thiserror::Error; use wgt::{BufferAddress, DeviceLostReason, TextureFormat}; -use std::num::NonZeroU32; - pub(crate) mod bgl; pub mod global; mod life; @@ -236,7 +237,7 @@ pub(crate) fn map_buffer( // If this is a write mapping zeroing out the memory here is the only // reasonable way as all data is pushed to GPU anyways. - let mapped = unsafe { std::slice::from_raw_parts_mut(mapping.ptr.as_ptr(), size as usize) }; + let mapped = unsafe { core::slice::from_raw_parts_mut(mapping.ptr.as_ptr(), size as usize) }; // We can't call flush_mapped_ranges in this case, so we can't drain the uninitialized ranges either if !mapping.is_coherent @@ -288,8 +289,8 @@ pub struct DeviceMismatch { pub(super) target_device: ResourceErrorIdent, } -impl std::fmt::Display for DeviceMismatch { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { +impl fmt::Display for DeviceMismatch { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { write!( f, "{} of {} doesn't match {}", diff --git a/wgpu-core/src/device/queue.rs b/wgpu-core/src/device/queue.rs index 497ba306f..e19f9bc5f 100644 --- a/wgpu-core/src/device/queue.rs +++ b/wgpu-core/src/device/queue.rs @@ -1,5 +1,18 @@ +use alloc::{boxed::Box, sync::Arc, vec, vec::Vec}; +use core::{ + iter, + mem::{self, ManuallyDrop}, + ptr::NonNull, + sync::atomic::Ordering, +}; + +use smallvec::SmallVec; +use thiserror::Error; + +use super::{life::LifetimeTracker, Device}; #[cfg(feature = "trace")] use crate::device::trace::Action; +use crate::scratch::ScratchBuffer; use crate::{ api_log, command::{ @@ -25,19 +38,6 @@ use crate::{ FastHashMap, SubmissionIndex, }; -use smallvec::SmallVec; - -use crate::scratch::ScratchBuffer; -use std::{ - iter, - mem::{self, ManuallyDrop}, - ptr::NonNull, - sync::{atomic::Ordering, Arc}, -}; -use thiserror::Error; - -use super::{life::LifetimeTracker, Device}; - pub struct Queue { raw: Box, pub(crate) pending_writes: Mutex, @@ -721,7 +721,7 @@ impl Queue { if has_copy_partial_init_tracker_coverage(size, destination.mip_level, &dst.desc) { for layer_range in dst_initialization_status.mips[destination.mip_level as usize] .drain(init_layer_range) - .collect::>>() + .collect::>>() { let mut trackers = self.device.trackers.lock(); crate::command::clear_texture( @@ -974,7 +974,7 @@ impl Queue { if has_copy_partial_init_tracker_coverage(&size, destination.mip_level, &dst.desc) { for layer_range in dst_initialization_status.mips[destination.mip_level as usize] .drain(init_layer_range) - .collect::>>() + .collect::>>() { let mut trackers = self.device.trackers.lock(); crate::command::clear_texture( diff --git a/wgpu-core/src/device/ray_tracing.rs b/wgpu-core/src/device/ray_tracing.rs index 8a9745bcc..52d01b6a5 100644 --- a/wgpu-core/src/device/ray_tracing.rs +++ b/wgpu-core/src/device/ray_tracing.rs @@ -1,5 +1,5 @@ -use std::mem::ManuallyDrop; -use std::sync::Arc; +use alloc::{string::ToString as _, sync::Arc, vec::Vec}; +use core::mem::ManuallyDrop; use crate::api_log; #[cfg(feature = "trace")] diff --git a/wgpu-core/src/device/resource.rs b/wgpu-core/src/device/resource.rs index e18edfc6f..036140e31 100644 --- a/wgpu-core/src/device/resource.rs +++ b/wgpu-core/src/device/resource.rs @@ -1,3 +1,26 @@ +use alloc::{ + borrow::Cow, + boxed::Box, + string::{String, ToString as _}, + sync::{Arc, Weak}, + vec::Vec, +}; +use core::{ + fmt, + mem::{self, ManuallyDrop}, + num::NonZeroU32, + sync::atomic::{AtomicBool, AtomicU64, Ordering}, +}; +use std::sync::OnceLock; + +use arrayvec::ArrayVec; +use bitflags::Flags; +use smallvec::SmallVec; +use wgt::{ + math::align_to, DeviceLostReason, TextureFormat, TextureSampleType, TextureSelector, + TextureViewDimension, +}; + #[cfg(feature = "trace")] use crate::device::trace; use crate::{ @@ -18,8 +41,8 @@ use crate::{ pipeline, pool::ResourcePool, resource::{ - self, Buffer, Fallible, Labeled, ParentDevice, QuerySet, Sampler, StagingBuffer, Texture, - TextureView, TextureViewNotRenderableReason, TrackingData, + self, AccelerationStructure, Buffer, Fallible, Labeled, ParentDevice, QuerySet, Sampler, + StagingBuffer, Texture, TextureView, TextureViewNotRenderableReason, Tlas, TrackingData, }, resource_log, snatch::{SnatchGuard, SnatchLock, Snatchable}, @@ -29,25 +52,6 @@ use crate::{ FastHashMap, LabelHelpers, }; -use arrayvec::ArrayVec; -use bitflags::Flags; -use smallvec::SmallVec; -use wgt::{ - math::align_to, DeviceLostReason, TextureFormat, TextureSampleType, TextureSelector, - TextureViewDimension, -}; - -use crate::resource::{AccelerationStructure, Tlas}; -use std::{ - borrow::Cow, - mem::{self, ManuallyDrop}, - num::NonZeroU32, - sync::{ - atomic::{AtomicBool, AtomicU64, Ordering}, - Arc, OnceLock, Weak, - }, -}; - use super::{ queue::Queue, DeviceDescriptor, DeviceError, DeviceLostClosure, UserClosures, ENTRYPOINT_FAILURE_ERROR, ZERO_BUFFER_SIZE, @@ -133,8 +137,8 @@ pub(crate) enum DeferredDestroy { BindGroups(WeakVec), } -impl std::fmt::Debug for Device { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Debug for Device { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Device") .field("label", &self.label()) .field("limits", &self.limits) @@ -656,7 +660,7 @@ impl Device { let map_size = buffer.size; let mapping = if map_size == 0 { hal::BufferMapping { - ptr: std::ptr::NonNull::dangling(), + ptr: core::ptr::NonNull::dangling(), is_coherent: true, } } else { @@ -975,7 +979,7 @@ impl Device { )); } - let mut hal_view_formats = vec![]; + let mut hal_view_formats = Vec::new(); for format in desc.view_formats.iter() { if desc.format == *format { continue; diff --git a/wgpu-core/src/device/trace.rs b/wgpu-core/src/device/trace.rs index a5f849cb8..421b07b2c 100644 --- a/wgpu-core/src/device/trace.rs +++ b/wgpu-core/src/device/trace.rs @@ -1,7 +1,10 @@ -use crate::id; -use std::ops::Range; +use alloc::{string::String, vec::Vec}; +use core::ops::Range; + #[cfg(feature = "trace")] -use std::{borrow::Cow, io::Write as _}; +use {alloc::borrow::Cow, std::io::Write as _}; + +use crate::id; //TODO: consider a readable Id that doesn't include the backend @@ -235,7 +238,7 @@ impl Trace { pub fn make_binary(&mut self, kind: &str, data: &[u8]) -> String { self.binary_id += 1; - let name = format!("data{}.{}", self.binary_id, kind); + let name = std::format!("data{}.{}", self.binary_id, kind); let _ = std::fs::write(self.path.join(&name), data); name } diff --git a/wgpu-core/src/error.rs b/wgpu-core/src/error.rs index 519a5f930..b5881825e 100644 --- a/wgpu-core/src/error.rs +++ b/wgpu-core/src/error.rs @@ -1,5 +1,6 @@ +use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; use core::fmt; -use std::{error::Error, sync::Arc}; +use std::error::Error; // TODO(https://github.com/gfx-rs/wgpu/issues/6826): use core::error after MSRV bump use thiserror::Error; diff --git a/wgpu-core/src/global.rs b/wgpu-core/src/global.rs index 0be903382..9a4382b00 100644 --- a/wgpu-core/src/global.rs +++ b/wgpu-core/src/global.rs @@ -1,4 +1,5 @@ -use std::{fmt, sync::Arc}; +use alloc::{borrow::ToOwned as _, boxed::Box, sync::Arc}; +use core::{fmt, iter}; use crate::{ hal_api::HalApi, @@ -50,7 +51,7 @@ impl Global { Self { instance: Instance { name: name.to_owned(), - instance_per_backend: std::iter::once((A::VARIANT, dyn_instance)).collect(), + instance_per_backend: iter::once((A::VARIANT, dyn_instance)).collect(), ..Default::default() }, surfaces: Registry::new(), diff --git a/wgpu-core/src/hash_utils.rs b/wgpu-core/src/hash_utils.rs index fa2db6bf2..5c5b25388 100644 --- a/wgpu-core/src/hash_utils.rs +++ b/wgpu-core/src/hash_utils.rs @@ -1,14 +1,14 @@ //! Module for hashing utilities. //! -//! Named hash_utils to prevent clashing with the std::hash module. +//! Named hash_utils to prevent clashing with the core::hash module. /// HashMap using a fast, non-cryptographic hash algorithm. pub type FastHashMap = - hashbrown::HashMap>; + hashbrown::HashMap>; /// HashSet using a fast, non-cryptographic hash algorithm. pub type FastHashSet = - hashbrown::HashSet>; + hashbrown::HashSet>; /// IndexMap using a fast, non-cryptographic hash algorithm. pub type FastIndexMap = - indexmap::IndexMap>; + indexmap::IndexMap>; diff --git a/wgpu-core/src/hub.rs b/wgpu-core/src/hub.rs index 15d3e3c06..f52ac006a 100644 --- a/wgpu-core/src/hub.rs +++ b/wgpu-core/src/hub.rs @@ -100,6 +100,9 @@ flagged as errors as well. */ +use alloc::sync::Arc; +use core::fmt::Debug; + use crate::{ binding_model::{BindGroup, BindGroupLayout, PipelineLayout}, command::{CommandBuffer, RenderBundle}, @@ -111,7 +114,6 @@ use crate::{ Blas, Buffer, Fallible, QuerySet, Sampler, StagingBuffer, Texture, TextureView, Tlas, }, }; -use std::{fmt::Debug, sync::Arc}; #[derive(Debug, PartialEq, Eq)] pub struct HubReport { diff --git a/wgpu-core/src/id.rs b/wgpu-core/src/id.rs index dd68ba945..a74b9e909 100644 --- a/wgpu-core/src/id.rs +++ b/wgpu-core/src/id.rs @@ -1,5 +1,5 @@ use crate::{Epoch, Index}; -use std::{ +use core::{ cmp::Ordering, fmt::{self, Debug}, hash::Hash, @@ -165,7 +165,7 @@ where T: Marker, { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { self.0.hash(state); } } diff --git a/wgpu-core/src/identity.rs b/wgpu-core/src/identity.rs index 0493b9d2c..0870b905e 100644 --- a/wgpu-core/src/identity.rs +++ b/wgpu-core/src/identity.rs @@ -1,9 +1,11 @@ +use alloc::vec::Vec; +use core::{fmt::Debug, marker::PhantomData}; + use crate::{ id::{Id, Marker}, lock::{rank, Mutex}, Epoch, Index, }; -use std::{fmt::Debug, marker::PhantomData}; #[derive(Copy, Clone, Debug, PartialEq)] enum IdSource { diff --git a/wgpu-core/src/indirect_validation.rs b/wgpu-core/src/indirect_validation.rs index e16828aed..8cce7614b 100644 --- a/wgpu-core/src/indirect_validation.rs +++ b/wgpu-core/src/indirect_validation.rs @@ -1,5 +1,6 @@ -use std::mem::size_of; -use std::num::NonZeroU64; +use alloc::{boxed::Box, format, string::ToString as _}; +use core::mem::size_of; +use core::num::NonZeroU64; use thiserror::Error; @@ -117,7 +118,7 @@ impl IndirectValidation { }) })?; let hal_shader = hal::ShaderInput::Naga(hal::NagaShader { - module: std::borrow::Cow::Owned(module), + module: alloc::borrow::Cow::Owned(module), info, debug_source: None, }); diff --git a/wgpu-core/src/init_tracker/buffer.rs b/wgpu-core/src/init_tracker/buffer.rs index ee8e99aa2..4d2cc42f5 100644 --- a/wgpu-core/src/init_tracker/buffer.rs +++ b/wgpu-core/src/init_tracker/buffer.rs @@ -1,6 +1,7 @@ use super::{InitTracker, MemoryInitKind}; use crate::resource::Buffer; -use std::{ops::Range, sync::Arc}; +use alloc::sync::Arc; +use core::ops::Range; #[derive(Debug, Clone)] pub(crate) struct BufferInitTrackerAction { diff --git a/wgpu-core/src/init_tracker/mod.rs b/wgpu-core/src/init_tracker/mod.rs index 15a79bf52..c77eecd86 100644 --- a/wgpu-core/src/init_tracker/mod.rs +++ b/wgpu-core/src/init_tracker/mod.rs @@ -31,8 +31,9 @@ system there are two kind of writes: */ +use core::{fmt, iter, ops::Range}; + use smallvec::SmallVec; -use std::{fmt, iter, ops::Range}; mod buffer; mod texture; @@ -280,7 +281,8 @@ impl InitTracker { #[cfg(test)] mod test { - use std::ops::Range; + use alloc::{vec, vec::Vec}; + use core::ops::Range; type Tracker = super::InitTracker; diff --git a/wgpu-core/src/init_tracker/texture.rs b/wgpu-core/src/init_tracker/texture.rs index f3cc471aa..af9856b30 100644 --- a/wgpu-core/src/init_tracker/texture.rs +++ b/wgpu-core/src/init_tracker/texture.rs @@ -1,7 +1,8 @@ use super::{InitTracker, MemoryInitKind}; use crate::resource::Texture; +use alloc::{sync::Arc, vec::Vec}; use arrayvec::ArrayVec; -use std::{ops::Range, sync::Arc}; +use core::ops::Range; use wgt::TextureSelector; #[derive(Debug, Clone)] @@ -52,7 +53,7 @@ pub(crate) struct TextureInitTracker { impl TextureInitTracker { pub(crate) fn new(mip_level_count: u32, depth_or_array_layers: u32) -> Self { TextureInitTracker { - mips: std::iter::repeat(TextureLayerInitTracker::new(depth_or_array_layers)) + mips: core::iter::repeat(TextureLayerInitTracker::new(depth_or_array_layers)) .take(mip_level_count as usize) .collect(), } diff --git a/wgpu-core/src/instance.rs b/wgpu-core/src/instance.rs index bf413b04e..78d2003d0 100644 --- a/wgpu-core/src/instance.rs +++ b/wgpu-core/src/instance.rs @@ -1,5 +1,10 @@ -use std::borrow::Cow; -use std::sync::Arc; +use alloc::{ + borrow::{Cow, ToOwned as _}, + boxed::Box, + string::String, + sync::Arc, + vec::Vec, +}; use hashbrown::HashMap; @@ -111,7 +116,7 @@ impl Instance { init(hal::api::Noop, instance_desc, &mut instance_per_backend); Self { - name: name.to_string(), + name: name.to_owned(), instance_per_backend, flags: instance_desc.flags, } @@ -203,7 +208,7 @@ impl Instance { #[cfg(metal)] pub unsafe fn create_surface_metal( &self, - layer: *mut std::ffi::c_void, + layer: *mut core::ffi::c_void, ) -> Result { profiling::scope!("Instance::create_surface_metal"); @@ -228,7 +233,7 @@ impl Instance { let surface = Surface { presentation: Mutex::new(rank::SURFACE_PRESENTATION, None), - surface_per_backend: std::iter::once((Backend::Metal, raw_surface)).collect(), + surface_per_backend: core::iter::once((Backend::Metal, raw_surface)).collect(), }; Ok(surface) @@ -245,7 +250,7 @@ impl Instance { let surface = Surface { presentation: Mutex::new(rank::SURFACE_PRESENTATION, None), - surface_per_backend: std::iter::once((Backend::Dx12, surface)).collect(), + surface_per_backend: core::iter::once((Backend::Dx12, surface)).collect(), }; Ok(surface) @@ -257,7 +262,7 @@ impl Instance { /// The visual must be valid and able to be used to make a swapchain with. pub unsafe fn create_surface_from_visual( &self, - visual: *mut std::ffi::c_void, + visual: *mut core::ffi::c_void, ) -> Result { profiling::scope!("Instance::instance_create_surface_from_visual"); self.create_surface_dx12(|inst| unsafe { inst.create_surface_from_visual(visual) }) @@ -269,7 +274,7 @@ impl Instance { /// The surface_handle must be valid and able to be used to make a swapchain with. pub unsafe fn create_surface_from_surface_handle( &self, - surface_handle: *mut std::ffi::c_void, + surface_handle: *mut core::ffi::c_void, ) -> Result { profiling::scope!("Instance::instance_create_surface_from_surface_handle"); self.create_surface_dx12(|inst| unsafe { @@ -283,7 +288,7 @@ impl Instance { /// The swap_chain_panel must be valid and able to be used to make a swapchain with. pub unsafe fn create_surface_from_swap_chain_panel( &self, - swap_chain_panel: *mut std::ffi::c_void, + swap_chain_panel: *mut core::ffi::c_void, ) -> Result { profiling::scope!("Instance::instance_create_surface_from_swap_chain_panel"); self.create_surface_dx12(|inst| unsafe { @@ -773,7 +778,7 @@ impl Global { #[cfg(metal)] pub unsafe fn instance_create_surface_metal( &self, - layer: *mut std::ffi::c_void, + layer: *mut core::ffi::c_void, id_in: Option, ) -> Result { let surface = unsafe { self.instance.create_surface_metal(layer) }?; @@ -787,7 +792,7 @@ impl Global { /// The visual must be valid and able to be used to make a swapchain with. pub unsafe fn instance_create_surface_from_visual( &self, - visual: *mut std::ffi::c_void, + visual: *mut core::ffi::c_void, id_in: Option, ) -> Result { let surface = unsafe { self.instance.create_surface_from_visual(visual) }?; @@ -801,7 +806,7 @@ impl Global { /// The surface_handle must be valid and able to be used to make a swapchain with. pub unsafe fn instance_create_surface_from_surface_handle( &self, - surface_handle: *mut std::ffi::c_void, + surface_handle: *mut core::ffi::c_void, id_in: Option, ) -> Result { let surface = unsafe { @@ -818,7 +823,7 @@ impl Global { /// The swap_chain_panel must be valid and able to be used to make a swapchain with. pub unsafe fn instance_create_surface_from_swap_chain_panel( &self, - swap_chain_panel: *mut std::ffi::c_void, + swap_chain_panel: *mut core::ffi::c_void, id_in: Option, ) -> Result { let surface = unsafe { diff --git a/wgpu-core/src/lib.rs b/wgpu-core/src/lib.rs index 47aaa87a5..ec873852d 100644 --- a/wgpu-core/src/lib.rs +++ b/wgpu-core/src/lib.rs @@ -6,6 +6,7 @@ #![doc = document_features::document_features!()] //! +#![no_std] // When we have no backends, we end up with a lot of dead or otherwise unreachable code. #![cfg_attr( all( @@ -41,7 +42,10 @@ rustdoc::private_intra_doc_links )] #![warn( + clippy::alloc_instead_of_core, clippy::ptr_as_ptr, + clippy::std_instead_of_alloc, + clippy::std_instead_of_core, trivial_casts, trivial_numeric_casts, unsafe_op_in_unsafe_fn, @@ -56,6 +60,9 @@ // (the only reason to use wgpu-core on the web in the first place) that have atomics enabled. #![cfg_attr(not(send_sync), allow(clippy::arc_with_non_send_sync))] +extern crate alloc; +// TODO(https://github.com/gfx-rs/wgpu/issues/6826): this should be optional +extern crate std; extern crate wgpu_hal as hal; extern crate wgpu_types as wgt; @@ -98,7 +105,11 @@ pub use validation::{map_storage_format_from_naga, map_storage_format_to_naga}; pub use hal::{api, MAX_BIND_GROUPS, MAX_COLOR_ATTACHMENTS, MAX_VERTEX_BUFFERS}; pub use naga; -use std::{borrow::Cow, os::raw::c_char}; +use alloc::{ + borrow::{Cow, ToOwned as _}, + string::String, +}; +use std::os::raw::c_char; pub(crate) use hash_utils::*; @@ -123,10 +134,10 @@ impl<'a> LabelHelpers<'a> for Label<'a> { return None; } - self.as_ref().map(|cow| cow.as_ref()) + self.as_deref() } fn to_string(&self) -> String { - self.as_ref().map(|cow| cow.to_string()).unwrap_or_default() + self.as_deref().map(str::to_owned).unwrap_or_default() } } diff --git a/wgpu-core/src/lock/observing.rs b/wgpu-core/src/lock/observing.rs index c530a5653..3c880ca02 100644 --- a/wgpu-core/src/lock/observing.rs +++ b/wgpu-core/src/lock/observing.rs @@ -28,16 +28,20 @@ //! //! [`lock/rank.rs`]: ../../../src/wgpu_core/lock/rank.rs.html -use crate::FastHashSet; +#![allow(clippy::std_instead_of_alloc, clippy::std_instead_of_core)] -use super::rank::{LockRank, LockRankSet}; use std::{ cell::RefCell, + format, fs::File, panic::Location, path::{Path, PathBuf}, + vec::Vec, }; +use super::rank::{LockRank, LockRankSet}; +use crate::FastHashSet; + /// A `Mutex` instrumented for lock acquisition order observation. /// /// This is just a wrapper around a [`parking_lot::Mutex`], along with @@ -290,7 +294,7 @@ fn release(saved: Option) { }); } -thread_local! { +std::thread_local! { static LOCK_STATE: RefCell = const { RefCell::new(ThreadState::Initial) }; } diff --git a/wgpu-core/src/lock/ranked.rs b/wgpu-core/src/lock/ranked.rs index c3aedb1b0..6f368c8f3 100644 --- a/wgpu-core/src/lock/ranked.rs +++ b/wgpu-core/src/lock/ranked.rs @@ -55,8 +55,9 @@ //! //! [`lock::rank`]: crate::lock::rank +use core::{cell::Cell, fmt, ops, panic::Location}; + use super::rank::LockRank; -use std::{cell::Cell, panic::Location}; /// A `Mutex` instrumented for deadlock prevention. /// @@ -80,7 +81,7 @@ pub struct MutexGuard<'a, T> { saved: LockStateGuard, } -thread_local! { +std::thread_local! { static LOCK_STATE: Cell = const { Cell::new(LockState::INITIAL) }; } @@ -191,7 +192,7 @@ impl Mutex { } } -impl<'a, T> std::ops::Deref for MutexGuard<'a, T> { +impl<'a, T> ops::Deref for MutexGuard<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { @@ -199,14 +200,14 @@ impl<'a, T> std::ops::Deref for MutexGuard<'a, T> { } } -impl<'a, T> std::ops::DerefMut for MutexGuard<'a, T> { +impl<'a, T> ops::DerefMut for MutexGuard<'a, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.inner.deref_mut() } } -impl std::fmt::Debug for Mutex { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Debug for Mutex { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.inner.fmt(f) } } @@ -280,13 +281,13 @@ impl<'a, T> RwLockWriteGuard<'a, T> { } } -impl std::fmt::Debug for RwLock { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Debug for RwLock { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.inner.fmt(f) } } -impl<'a, T> std::ops::Deref for RwLockReadGuard<'a, T> { +impl<'a, T> ops::Deref for RwLockReadGuard<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { @@ -294,7 +295,7 @@ impl<'a, T> std::ops::Deref for RwLockReadGuard<'a, T> { } } -impl<'a, T> std::ops::Deref for RwLockWriteGuard<'a, T> { +impl<'a, T> ops::Deref for RwLockWriteGuard<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { @@ -302,7 +303,7 @@ impl<'a, T> std::ops::Deref for RwLockWriteGuard<'a, T> { } } -impl<'a, T> std::ops::DerefMut for RwLockWriteGuard<'a, T> { +impl<'a, T> ops::DerefMut for RwLockWriteGuard<'a, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.inner.deref_mut() } @@ -381,7 +382,7 @@ fn non_stack_like() { // Avoid a double panic from dropping this while unwinding due to the panic // we're testing for. - std::mem::forget(guard2); + core::mem::forget(guard2); drop(guard1); } diff --git a/wgpu-core/src/lock/vanilla.rs b/wgpu-core/src/lock/vanilla.rs index 9a35b6d9d..6318dae2d 100644 --- a/wgpu-core/src/lock/vanilla.rs +++ b/wgpu-core/src/lock/vanilla.rs @@ -3,6 +3,8 @@ //! These definitions are used when no particular lock instrumentation //! Cargo feature is selected. +use core::{fmt, ops}; + /// A plain wrapper around [`parking_lot::Mutex`]. /// /// This is just like [`parking_lot::Mutex`], except that our [`new`] @@ -30,7 +32,7 @@ impl Mutex { } } -impl<'a, T> std::ops::Deref for MutexGuard<'a, T> { +impl<'a, T> ops::Deref for MutexGuard<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { @@ -38,14 +40,14 @@ impl<'a, T> std::ops::Deref for MutexGuard<'a, T> { } } -impl<'a, T> std::ops::DerefMut for MutexGuard<'a, T> { +impl<'a, T> ops::DerefMut for MutexGuard<'a, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.0.deref_mut() } } -impl std::fmt::Debug for Mutex { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Debug for Mutex { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } @@ -92,13 +94,13 @@ impl<'a, T> RwLockWriteGuard<'a, T> { } } -impl std::fmt::Debug for RwLock { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Debug for RwLock { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } -impl<'a, T> std::ops::Deref for RwLockReadGuard<'a, T> { +impl<'a, T> ops::Deref for RwLockReadGuard<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { @@ -106,7 +108,7 @@ impl<'a, T> std::ops::Deref for RwLockReadGuard<'a, T> { } } -impl<'a, T> std::ops::Deref for RwLockWriteGuard<'a, T> { +impl<'a, T> ops::Deref for RwLockWriteGuard<'a, T> { type Target = T; fn deref(&self) -> &Self::Target { @@ -114,7 +116,7 @@ impl<'a, T> std::ops::Deref for RwLockWriteGuard<'a, T> { } } -impl<'a, T> std::ops::DerefMut for RwLockWriteGuard<'a, T> { +impl<'a, T> ops::DerefMut for RwLockWriteGuard<'a, T> { fn deref_mut(&mut self) -> &mut Self::Target { self.0.deref_mut() } diff --git a/wgpu-core/src/pipeline.rs b/wgpu-core/src/pipeline.rs index d7d29589d..ebf3cdcae 100644 --- a/wgpu-core/src/pipeline.rs +++ b/wgpu-core/src/pipeline.rs @@ -1,3 +1,16 @@ +use alloc::{ + borrow::Cow, + boxed::Box, + string::{String, ToString as _}, + sync::Arc, + vec::Vec, +}; +use core::{marker::PhantomData, mem::ManuallyDrop, num::NonZeroU32}; + +use arrayvec::ArrayVec; +use naga::error::ShaderError; +use thiserror::Error; + pub use crate::pipeline_cache::PipelineCacheValidationError; use crate::{ binding_model::{CreateBindGroupLayoutError, CreatePipelineLayoutError, PipelineLayout}, @@ -7,10 +20,6 @@ use crate::{ resource::{InvalidResourceError, Labeled, TrackingData}, resource_log, validation, Label, }; -use arrayvec::ArrayVec; -use naga::error::ShaderError; -use std::{borrow::Cow, marker::PhantomData, mem::ManuallyDrop, num::NonZeroU32, sync::Arc}; -use thiserror::Error; /// Information about buffer bindings, which /// is validated against the shader (and pipeline) diff --git a/wgpu-core/src/pipeline_cache.rs b/wgpu-core/src/pipeline_cache.rs index e506d2cd5..b206c09ea 100644 --- a/wgpu-core/src/pipeline_cache.rs +++ b/wgpu-core/src/pipeline_cache.rs @@ -1,4 +1,4 @@ -use std::mem::size_of; +use core::mem::size_of; use thiserror::Error; use wgt::AdapterInfo; @@ -277,7 +277,7 @@ impl<'a> Writer<'a> { if N > self.data.len() { return None; } - let data = std::mem::take(&mut self.data); + let data = core::mem::take(&mut self.data); let (start, data) = data.split_at_mut(N); self.data = data; start.copy_from_slice(array); @@ -297,6 +297,7 @@ impl<'a> Writer<'a> { #[cfg(test)] mod tests { + use alloc::{string::String, vec::Vec}; use wgt::AdapterInfo; use crate::pipeline_cache::{PipelineCacheValidationError as E, HEADER_LENGTH}; @@ -484,7 +485,7 @@ mod tests { let cache = cache .into_iter() .flatten() - .chain(std::iter::repeat(0u8).take(100)) + .chain(core::iter::repeat(0u8).take(100)) .collect::>(); let validation_result = super::validate_pipeline_cache(&cache, &ADAPTER, VALIDATION_KEY); let expected: &[u8] = &[0; 100]; @@ -505,7 +506,7 @@ mod tests { let cache = cache .into_iter() .flatten() - .chain(std::iter::repeat(0u8).take(200)) + .chain(core::iter::repeat(0u8).take(200)) .collect::>(); let validation_result = super::validate_pipeline_cache(&cache, &ADAPTER, VALIDATION_KEY); assert_eq!(validation_result, Err(E::Extended)); diff --git a/wgpu-core/src/pool.rs b/wgpu-core/src/pool.rs index 375b36c32..ae5272e09 100644 --- a/wgpu-core/src/pool.rs +++ b/wgpu-core/src/pool.rs @@ -1,7 +1,5 @@ -use std::{ - hash::Hash, - sync::{Arc, Weak}, -}; +use alloc::sync::{Arc, Weak}; +use core::hash::Hash; use hashbrown::{hash_map::Entry, HashMap}; use once_cell::sync::OnceCell; @@ -107,10 +105,11 @@ impl ResourcePool { #[cfg(test)] mod tests { - use std::sync::{ - atomic::{AtomicU32, Ordering}, - Barrier, + use core::{ + sync::atomic::{AtomicU32, Ordering}, + time::Duration, }; + use std::{eprintln, sync::Barrier, thread}; use super::*; @@ -202,7 +201,7 @@ mod tests { eprintln!("{idx}: init"); // Simulate long running constructor, ensuring that both threads will be in get_or_init. - std::thread::sleep(std::time::Duration::from_millis(250)); + thread::sleep(Duration::from_millis(250)); resources.counter.fetch_add(1, Ordering::SeqCst); @@ -215,7 +214,7 @@ mod tests { ret } - let thread1 = std::thread::spawn({ + let thread1 = thread::spawn({ let resource_clone = Arc::clone(&resources); move || thread_inner(1, &resource_clone) }); @@ -290,7 +289,7 @@ mod tests { eprintln!("1: postwait"); // We wait a little bit, making sure that thread0_inner has started spinning. - std::thread::sleep(std::time::Duration::from_millis(250)); + thread::sleep(Duration::from_millis(250)); eprintln!("1: postsleep"); // We remove the entry from the pool, allowing thread0_inner to re-create. @@ -298,7 +297,7 @@ mod tests { eprintln!("1: removal"); } - let thread1 = std::thread::spawn({ + let thread1 = thread::spawn({ let resource_clone = Arc::clone(&resources); move || thread1_inner(&resource_clone) }); diff --git a/wgpu-core/src/present.rs b/wgpu-core/src/present.rs index b0b040074..12d076b65 100644 --- a/wgpu-core/src/present.rs +++ b/wgpu-core/src/present.rs @@ -9,7 +9,8 @@ When this texture is presented, we remove it from the device tracker as well as extract it from the hub. !*/ -use std::{mem::ManuallyDrop, sync::Arc}; +use alloc::{sync::Arc, vec::Vec}; +use core::mem::ManuallyDrop; #[cfg(feature = "trace")] use crate::device::trace::Action; @@ -131,7 +132,7 @@ impl Surface { let suf = self.raw(device.backend()).unwrap(); let (texture, status) = match unsafe { suf.acquire_texture( - Some(std::time::Duration::from_millis(FRAME_TIMEOUT_MS as u64)), + Some(core::time::Duration::from_millis(FRAME_TIMEOUT_MS as u64)), fence.as_ref(), ) } { @@ -139,7 +140,7 @@ impl Surface { drop(fence); let texture_desc = wgt::TextureDescriptor { - label: Some(std::borrow::Cow::Borrowed("")), + label: Some(alloc::borrow::Cow::Borrowed("")), size: wgt::Extent3d { width: config.width, height: config.height, diff --git a/wgpu-core/src/ray_tracing.rs b/wgpu-core/src/ray_tracing.rs index 236bb8fb2..2d8217dfe 100644 --- a/wgpu-core/src/ray_tracing.rs +++ b/wgpu-core/src/ray_tracing.rs @@ -7,18 +7,21 @@ // - partial instance buffer uploads (api surface already designed with this in mind) // - ([non performance] extract function in build (rust function extraction with guards is a pain)) +use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use core::num::NonZeroU64; + +use thiserror::Error; +use wgt::{AccelerationStructureGeometryFlags, BufferAddress, IndexFormat, VertexFormat}; + use crate::{ command::CommandEncoderError, device::{DeviceError, MissingFeatures}, id::{BlasId, BufferId, TlasId}, - resource::{DestroyedResourceError, InvalidResourceError, MissingBufferUsageError}, + resource::{ + Blas, DestroyedResourceError, InvalidResourceError, MissingBufferUsageError, + ResourceErrorIdent, Tlas, + }, }; -use std::num::NonZeroU64; -use std::sync::Arc; - -use crate::resource::{Blas, ResourceErrorIdent, Tlas}; -use thiserror::Error; -use wgt::{AccelerationStructureGeometryFlags, BufferAddress, IndexFormat, VertexFormat}; #[derive(Clone, Debug, Error)] pub enum CreateBlasError { diff --git a/wgpu-core/src/registry.rs b/wgpu-core/src/registry.rs index b3349235e..753fb0c1e 100644 --- a/wgpu-core/src/registry.rs +++ b/wgpu-core/src/registry.rs @@ -1,4 +1,5 @@ -use std::{mem::size_of, sync::Arc}; +use alloc::sync::Arc; +use core::mem::size_of; use crate::{ id::Id, @@ -126,11 +127,10 @@ impl Registry { #[cfg(test)] mod tests { - use std::sync::Arc; - - use crate::{id::Marker, resource::ResourceType, storage::StorageItem}; - use super::Registry; + use crate::{id::Marker, resource::ResourceType, storage::StorageItem}; + use alloc::sync::Arc; + struct TestData; struct TestDataId; impl Marker for TestDataId {} diff --git a/wgpu-core/src/resource.rs b/wgpu-core/src/resource.rs index 73435fc31..f9ee161a9 100644 --- a/wgpu-core/src/resource.rs +++ b/wgpu-core/src/resource.rs @@ -1,3 +1,17 @@ +use alloc::{borrow::Cow, borrow::ToOwned as _, boxed::Box, string::String, sync::Arc, vec::Vec}; +use core::{ + borrow::Borrow, + fmt, + mem::{self, ManuallyDrop}, + num::NonZeroU64, + ops::Range, + ptr::NonNull, +}; + +use smallvec::SmallVec; +use thiserror::Error; +use wgt::TextureSelector; + #[cfg(feature = "trace")] use crate::device::trace; use crate::{ @@ -21,21 +35,6 @@ use crate::{ Label, LabelHelpers, SubmissionIndex, }; -use wgt::TextureSelector; - -use smallvec::SmallVec; -use thiserror::Error; - -use std::num::NonZeroU64; -use std::{ - borrow::{Borrow, Cow}, - fmt::Debug, - mem::{self, ManuallyDrop}, - ops::Range, - ptr::NonNull, - sync::Arc, -}; - /// Information about the wgpu-core resource. /// /// Each type representing a `wgpu-core` resource, like [`Device`], @@ -87,8 +86,8 @@ pub struct ResourceErrorIdent { label: String, } -impl std::fmt::Display for ResourceErrorIdent { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { +impl fmt::Display for ResourceErrorIdent { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { write!(f, "{} with '{}' label", self.r#type, self.label) } } @@ -114,7 +113,7 @@ pub trait ParentDevice: Labeled { } fn same_device(&self, device: &Device) -> Result<(), DeviceError> { - if std::ptr::eq(&**self.device(), device) { + if core::ptr::eq(&**self.device(), device) { Ok(()) } else { Err(DeviceError::DeviceMismatch(Box::new(DeviceMismatch { @@ -224,8 +223,8 @@ pub struct BufferMapOperation { pub callback: Option, } -impl Debug for BufferMapOperation { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Debug for BufferMapOperation { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("BufferMapOperation") .field("host", &self.host) .field("callback", &self.callback.as_ref().map(|_| "?")) @@ -683,7 +682,7 @@ impl Buffer { if let Some(ref mut trace) = *device.trace.lock() { let size = range.end - range.start; let data = trace.make_binary("bin", unsafe { - std::slice::from_raw_parts(mapping.ptr.as_ptr(), size as usize) + core::slice::from_raw_parts(mapping.ptr.as_ptr(), size as usize) }); trace.add(trace::Action::WriteBuffer { id: buffer_id, @@ -793,7 +792,7 @@ pub struct DestroyedBuffer { } impl DestroyedBuffer { - pub fn label(&self) -> &dyn Debug { + pub fn label(&self) -> &dyn fmt::Debug { &self.label } } @@ -889,7 +888,7 @@ impl StagingBuffer { #[cfg(feature = "trace")] pub(crate) fn get_data(&self) -> &[u8] { - unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.size.get() as usize) } + unsafe { core::slice::from_raw_parts(self.ptr.as_ptr(), self.size.get() as usize) } } pub(crate) fn write_zeros(&mut self) { @@ -1421,7 +1420,7 @@ pub struct DestroyedTexture { } impl DestroyedTexture { - pub fn label(&self) -> &dyn Debug { + pub fn label(&self) -> &dyn fmt::Debug { &self.label } } @@ -1808,8 +1807,8 @@ pub enum SamplerFilterErrorType { MipmapFilter, } -impl Debug for SamplerFilterErrorType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Debug for SamplerFilterErrorType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { SamplerFilterErrorType::MagFilter => write!(f, "magFilter"), SamplerFilterErrorType::MinFilter => write!(f, "minFilter"), diff --git a/wgpu-core/src/scratch.rs b/wgpu-core/src/scratch.rs index a8242be07..be12c7c4c 100644 --- a/wgpu-core/src/scratch.rs +++ b/wgpu-core/src/scratch.rs @@ -1,8 +1,10 @@ +use alloc::{boxed::Box, sync::Arc}; +use core::mem::ManuallyDrop; + +use wgt::BufferUses; + use crate::device::{Device, DeviceError}; use crate::resource_log; -use std::mem::ManuallyDrop; -use std::sync::Arc; -use wgt::BufferUses; #[derive(Debug)] pub struct ScratchBuffer { diff --git a/wgpu-core/src/snatch.rs b/wgpu-core/src/snatch.rs index 0d57f41fc..8c2c7bd9b 100644 --- a/wgpu-core/src/snatch.rs +++ b/wgpu-core/src/snatch.rs @@ -1,14 +1,13 @@ #![allow(unused)] -use crate::lock::{RwLock, RwLockReadGuard, RwLockWriteGuard}; -use std::{ - backtrace::Backtrace, +use core::{ cell::{Cell, RefCell, UnsafeCell}, + fmt, panic::{self, Location}, - thread, }; +use std::{backtrace::Backtrace, thread}; -use crate::lock::rank; +use crate::lock::{rank, RwLock, RwLockReadGuard, RwLockWriteGuard}; /// A guard that provides read access to snatchable data. pub struct SnatchGuard<'a>(RwLockReadGuard<'a, ()>); @@ -59,8 +58,8 @@ impl Snatchable { // Can't safely print the contents of a snatchable object without holding // the lock. -impl std::fmt::Debug for Snatchable { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { +impl fmt::Debug for Snatchable { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "") } } @@ -73,8 +72,8 @@ struct LockTrace { backtrace: Backtrace, } -impl std::fmt::Display for LockTrace { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl fmt::Display for LockTrace { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "a {} lock at {}\n{}", @@ -117,7 +116,7 @@ impl LockTrace { fn exit() {} } -thread_local! { +std::thread_local! { static SNATCH_LOCK_TRACE: Cell> = const { Cell::new(None) }; } diff --git a/wgpu-core/src/storage.rs b/wgpu-core/src/storage.rs index c2ab9faa7..4efe9f77a 100644 --- a/wgpu-core/src/storage.rs +++ b/wgpu-core/src/storage.rs @@ -1,4 +1,5 @@ -use std::sync::Arc; +use alloc::{sync::Arc, vec::Vec}; +use core::mem; use crate::id::{Id, Marker}; use crate::resource::ResourceType; @@ -41,7 +42,7 @@ macro_rules! impl_storage_item { /// A table of `T` values indexed by the id type `I`. /// -/// `Storage` implements [`std::ops::Index`], accepting `Id` values as +/// `Storage` implements [`core::ops::Index`], accepting `Id` values as /// indices. /// /// The table is represented as a vector indexed by the ids' index @@ -78,7 +79,7 @@ where if index >= self.map.len() { self.map.resize_with(index + 1, || Element::Vacant); } - match std::mem::replace(&mut self.map[index], Element::Occupied(value, epoch)) { + match mem::replace(&mut self.map[index], Element::Occupied(value, epoch)) { Element::Vacant => {} Element::Occupied(_, storage_epoch) => { assert_ne!( @@ -93,7 +94,7 @@ where pub(crate) fn remove(&mut self, id: Id) -> T { let (index, epoch) = id.unzip(); - match std::mem::replace(&mut self.map[index as usize], Element::Vacant) { + match mem::replace(&mut self.map[index as usize], Element::Vacant) { Element::Occupied(value, storage_epoch) => { assert_eq!(epoch, storage_epoch); value diff --git a/wgpu-core/src/track/buffer.rs b/wgpu-core/src/track/buffer.rs index ba23dbcd6..17d1970b1 100644 --- a/wgpu-core/src/track/buffer.rs +++ b/wgpu-core/src/track/buffer.rs @@ -4,7 +4,13 @@ //! a 16 bit bitflag of buffer usages. Because there is only ever //! one subresource, they have no selector. -use std::sync::{Arc, Weak}; +use alloc::{ + sync::{Arc, Weak}, + vec::Vec, +}; + +use hal::BufferBarrier; +use wgt::{strict_assert, strict_assert_eq, BufferUses}; use super::{PendingTransition, TrackerIndex}; use crate::{ @@ -15,8 +21,6 @@ use crate::{ ResourceUsageCompatibilityError, ResourceUses, }, }; -use hal::BufferBarrier; -use wgt::{strict_assert, strict_assert_eq, BufferUses}; impl ResourceUses for BufferUses { const EXCLUSIVE: Self = Self::EXCLUSIVE; diff --git a/wgpu-core/src/track/metadata.rs b/wgpu-core/src/track/metadata.rs index 8f03caf7b..2d63b1a7b 100644 --- a/wgpu-core/src/track/metadata.rs +++ b/wgpu-core/src/track/metadata.rs @@ -1,5 +1,7 @@ //! The `ResourceMetadata` type. +use alloc::vec::Vec; + use bit_vec::BitVec; use wgt::strict_assert; diff --git a/wgpu-core/src/track/mod.rs b/wgpu-core/src/track/mod.rs index 3cd9a4ecb..12ede00a5 100644 --- a/wgpu-core/src/track/mod.rs +++ b/wgpu-core/src/track/mod.rs @@ -109,7 +109,9 @@ use crate::{ snatch::SnatchGuard, }; -use std::{fmt, ops, sync::Arc}; +use alloc::{sync::Arc, vec::Vec}; +use core::{fmt, mem, ops}; + use thiserror::Error; pub(crate) use buffer::{ @@ -513,10 +515,9 @@ impl<'a> Drop for UsageScope<'a> { // clear vecs and push into pool self.buffers.clear(); self.textures.clear(); - self.pool.lock().push(( - std::mem::take(&mut self.buffers), - std::mem::take(&mut self.textures), - )); + self.pool + .lock() + .push((mem::take(&mut self.buffers), mem::take(&mut self.textures))); } } diff --git a/wgpu-core/src/track/range.rs b/wgpu-core/src/track/range.rs index ee6773278..4ee5bcfd0 100644 --- a/wgpu-core/src/track/range.rs +++ b/wgpu-core/src/track/range.rs @@ -2,7 +2,7 @@ //TODO: consider getting rid of it. use smallvec::SmallVec; -use std::{fmt::Debug, iter, ops::Range}; +use core::{fmt::Debug, iter, ops::Range}; /// Structure that keeps track of a I -> T mapping, /// optimized for a case where keys of the same values @@ -148,7 +148,7 @@ impl RangedStates { /// Helper method for isolation that checks the sanity of the results. #[cfg(test)] - pub fn sanely_isolated(&self, index: Range, default: T) -> Vec<(Range, T)> { + pub fn sanely_isolated(&self, index: Range, default: T) -> alloc::vec::Vec<(Range, T)> { let mut clone = self.clone(); let result = clone.isolate(&index, default).to_vec(); clone.check_sanity(); diff --git a/wgpu-core/src/track/stateless.rs b/wgpu-core/src/track/stateless.rs index 975a850f3..26aec9308 100644 --- a/wgpu-core/src/track/stateless.rs +++ b/wgpu-core/src/track/stateless.rs @@ -1,5 +1,5 @@ -use std::slice::Iter; -use std::sync::Arc; +use alloc::{sync::Arc, vec::Vec}; +use core::slice::Iter; /// A tracker that holds strong references to resources. /// diff --git a/wgpu-core/src/track/texture.rs b/wgpu-core/src/track/texture.rs index 268e81c4b..a64826fe6 100644 --- a/wgpu-core/src/track/texture.rs +++ b/wgpu-core/src/track/texture.rs @@ -34,11 +34,11 @@ use naga::FastHashMap; use wgt::{strict_assert, strict_assert_eq, TextureSelector, TextureUses}; -use std::{ - iter, +use alloc::{ sync::{Arc, Weak}, - vec::Drain, + vec::{Drain, Vec}, }; +use core::iter; impl ResourceUses for TextureUses { const EXCLUSIVE: Self = Self::EXCLUSIVE; diff --git a/wgpu-core/src/validation.rs b/wgpu-core/src/validation.rs index 236675b8a..274cfab1c 100644 --- a/wgpu-core/src/validation.rs +++ b/wgpu-core/src/validation.rs @@ -1,10 +1,17 @@ -use crate::{device::bgl, resource::InvalidResourceError, FastHashMap, FastHashSet}; +use alloc::{ + boxed::Box, + string::{String, ToString as _}, + vec::Vec, +}; +use core::fmt; + use arrayvec::ArrayVec; use hashbrown::hash_map::Entry; -use std::fmt; use thiserror::Error; use wgt::{BindGroupLayoutEntry, BindingType}; +use crate::{device::bgl, resource::InvalidResourceError, FastHashMap, FastHashSet}; + #[derive(Debug)] enum ResourceType { Buffer { diff --git a/wgpu-core/src/weak_vec.rs b/wgpu-core/src/weak_vec.rs index e00cc9e59..af69a4811 100644 --- a/wgpu-core/src/weak_vec.rs +++ b/wgpu-core/src/weak_vec.rs @@ -1,6 +1,6 @@ //! Module containing the [`WeakVec`] API. -use std::sync::Weak; +use alloc::{sync::Weak, vec::Vec}; /// An optimized container for `Weak` references of `T` that minimizes reallocations by /// dropping older elements that no longer have strong references to them. @@ -45,7 +45,7 @@ impl WeakVec { } pub(crate) struct WeakVecIter { - inner: std::vec::IntoIter>, + inner: alloc::vec::IntoIter>, } impl Iterator for WeakVecIter {