pub struct RCHandle<Native>(/* private fields */)
where
Native: NativeRefCounted;
Expand description
A wrapper type represented by a reference counted pointer to the native type.
Implementations§
§impl RCHandle<SkBlender>
impl RCHandle<SkBlender>
pub fn mode(mode: SkBlendMode) -> RCHandle<SkBlender>
pub fn mode(mode: SkBlendMode) -> RCHandle<SkBlender>
Create a blender that implements the specified BlendMode
.
§impl RCHandle<SkColorFilter>
impl RCHandle<SkColorFilter>
ColorFilters are optional objects in the drawing pipeline. When present in a paint, they are called with the “src” colors, and return new colors, which are then passed onto the next stage (either ImageFilter or Xfermode).
All subclasses are required to be reentrant-safe : it must be legal to share the same instance between several threads.
pub fn to_a_color_mode(&self) -> Option<(Color, SkBlendMode)>
pub fn to_a_color_mode(&self) -> Option<(Color, SkBlendMode)>
If the filter can be represented by a source color plus Mode, this
returns the color and mode appropriately.
If not, this returns None
and ignores the parameters.
pub fn to_a_color_matrix(&self) -> Option<[f32; 20]>
pub fn to_a_color_matrix(&self) -> Option<[f32; 20]>
If the filter can be represented by a 5x4 matrix, this
returns the matrix appropriately.
If not, this returns None
and ignores the parameter.
pub fn is_alpha_unchanged(&self) -> bool
pub fn is_alpha_unchanged(&self) -> bool
Returns true
if the filter is guaranteed to never change the alpha of a color it filters.
pub fn filter_color(&self, color: impl Into<Color>) -> Color
pub fn filter_color4f(
&self,
color: impl AsRef<Color4f>,
src_color_space: &RCHandle<SkColorSpace>,
dst_color_space: Option<&RCHandle<SkColorSpace>>,
) -> Color4f
pub fn filter_color4f( &self, color: impl AsRef<Color4f>, src_color_space: &RCHandle<SkColorSpace>, dst_color_space: Option<&RCHandle<SkColorSpace>>, ) -> Color4f
Converts the src color (in src colorspace), into the dst colorspace, then applies this filter to it, returning the filtered color in the dst colorspace.
pub fn composed(
&self,
inner: impl Into<RCHandle<SkColorFilter>>,
) -> Option<RCHandle<SkColorFilter>>
pub fn composed( &self, inner: impl Into<RCHandle<SkColorFilter>>, ) -> Option<RCHandle<SkColorFilter>>
Construct a color filter whose effect is to first apply the inner filter and then apply this filter, applied to the output of the inner filter.
result = this(inner(…))
pub fn with_working_color_space(
&self,
color_space: impl Into<RCHandle<SkColorSpace>>,
) -> Option<RCHandle<SkColorFilter>>
pub fn with_working_color_space( &self, color_space: impl Into<RCHandle<SkColorSpace>>, ) -> Option<RCHandle<SkColorFilter>>
Return a color filter that will compute this filter in a specific color space. By default all filters operate in the destination (surface) color space. This allows filters like Blend and Matrix, or runtime color filters to perform their math in a known space.
§impl RCHandle<SkColorSpace>
impl RCHandle<SkColorSpace>
pub fn new_srgb() -> RCHandle<SkColorSpace>
pub fn new_srgb_linear() -> RCHandle<SkColorSpace>
pub fn to_xyzd50_hash(&self) -> XYZD50Hash
pub fn with_linear_gamma(&self) -> RCHandle<SkColorSpace>
pub fn with_srgb_gamma(&self) -> RCHandle<SkColorSpace>
pub fn with_color_spin(&self) -> RCHandle<SkColorSpace>
pub fn is_srgb(&self) -> bool
pub fn serialize(&self) -> RCHandle<SkData>
pub fn deserialize(data: impl Into<RCHandle<SkData>>) -> RCHandle<SkColorSpace>
§impl RCHandle<SkColorTable>
impl RCHandle<SkColorTable>
pub fn new(table: &[u8; 256]) -> RCHandle<SkColorTable>
pub fn new(table: &[u8; 256]) -> RCHandle<SkColorTable>
Creates a new ColorTable
with ‘table’ used for all four channels. The table is copied
into the ColorTable
.
pub fn new_per_channel<'a>( table_a: impl Into<Option<&'a [u8; 256]>>, table_r: impl Into<Option<&'a [u8; 256]>>, table_g: impl Into<Option<&'a [u8; 256]>>, table_b: impl Into<Option<&'a [u8; 256]>>, ) -> Option<RCHandle<SkColorTable>>
pub fn alpha_table(&self) -> &[u8; 256]
pub fn red_table(&self) -> &[u8; 256]
pub fn green_table(&self) -> &[u8; 256]
pub fn blue_table(&self) -> &[u8; 256]
§impl RCHandle<SkContourMeasure>
impl RCHandle<SkContourMeasure>
pub fn length(&self) -> f32
pub fn pos_tan(&self, distance: f32) -> Option<(Point, Point)>
pub fn get_matrix( &self, distance: f32, flags: impl Into<Option<MatrixFlags>>, ) -> Option<Matrix>
pub fn segment( &self, start_d: f32, stop_d: f32, start_with_move_to: bool, ) -> Option<Handle<SkPath>>
pub fn is_closed(&self) -> bool
§impl RCHandle<SkData>
impl RCHandle<SkData>
pub fn size(&self) -> usize
pub fn is_empty(&self) -> bool
pub fn as_bytes(&self) -> &[u8] ⓘ
pub fn copy_range(&self, offset: usize, buffer: &mut [u8]) -> &RCHandle<SkData>
pub fn new_copy(data: &[u8]) -> RCHandle<SkData>
pub unsafe fn new_bytes(data: &[u8]) -> RCHandle<SkData>
pub unsafe fn new_bytes(data: &[u8]) -> RCHandle<SkData>
Constructs Data from a given byte slice without copying it.
Users must make sure that the underlying slice will outlive the lifetime of the Data.
pub unsafe fn new_uninitialized(length: usize) -> RCHandle<SkData>
pub fn new_zero_initialized(length: usize) -> RCHandle<SkData>
pub fn new_subset( data: &RCHandle<SkData>, offset: usize, length: usize, ) -> RCHandle<SkData>
pub fn new_str(str: impl AsRef<str>) -> RCHandle<SkData>
pub fn new_str(str: impl AsRef<str>) -> RCHandle<SkData>
Constructs Data from a copy of a &str.
Functions that use Data
as a string container usually expect it to contain a c-string
including the terminating 0 byte, so this function converts the Rust str
to a CString
and calls Self::new_cstr()
.
pub fn new_cstr(cstr: &CStr) -> RCHandle<SkData>
pub fn new_cstr(cstr: &CStr) -> RCHandle<SkData>
Constructs Data from a &CStr by copying its contents.
pub fn from_filename(path: impl AsRef<Path>) -> Option<RCHandle<SkData>>
pub fn from_filename(path: impl AsRef<Path>) -> Option<RCHandle<SkData>>
Create a new Data
referencing the file with the specified path. If the file cannot be
opened, the path contains 0 bytes, or the path is not valid UTF-8, this returns None
.
This function opens the file as a memory mapped file for the lifetime of Data
returned.
pub fn from_stream(stream: impl Read, size: usize) -> Option<RCHandle<SkData>>
pub fn from_stream(stream: impl Read, size: usize) -> Option<RCHandle<SkData>>
Attempt to read size bytes into a Data
. If the read succeeds, return the data,
else return None
. Either way the stream’s cursor may have been changed as a result
of calling read().
pub fn new_empty() -> RCHandle<SkData>
§impl RCHandle<SkDataTable>
impl RCHandle<SkDataTable>
pub fn is_empty(&self) -> bool
pub fn count(&self) -> usize
pub fn at_size(&self, index: usize) -> usize
pub fn at(&self, index: usize) -> &[u8] ⓘ
pub unsafe fn at_t<T>(&self, index: usize) -> &[T]where
T: Copy,
pub fn at_str(&self, index: usize) -> &CStr
pub fn new_empty() -> RCHandle<SkDataTable>
pub fn from_slices(slices: &[&[u8]]) -> RCHandle<SkDataTable>
pub fn from_slice<T>(slice: &[T]) -> RCHandle<SkDataTable>where
T: Copy,
pub fn iter(&self) -> Iter<'_> ⓘ
§impl RCHandle<SkDrawable>
impl RCHandle<SkDrawable>
pub fn draw(&mut self, canvas: &Canvas, matrix: Option<&Matrix>)
pub fn draw_at(&mut self, canvas: &Canvas, point: impl Into<Point>)
pub fn snap_gpu_draw_handler( &mut self, api: GrBackendApi, matrix: &Matrix, clip_bounds: impl Into<IRect>, buffer_info: &Handle<SkImageInfo>, ) -> Option<RefHandle<SkDrawable_GpuDrawHandler>>
pub fn make_picture_snapshot(&mut self) -> RCHandle<SkPicture>
pub fn generation_id(&mut self) -> u32
pub fn bounds(&mut self) -> Rect
pub fn approximate_bytes_used(&mut self) -> usize
pub fn notify_drawing_changed(&mut self)
§impl RCHandle<SkFontStyleSet>
impl RCHandle<SkFontStyleSet>
pub fn count(&mut self) -> usize
pub fn style(&mut self, index: usize) -> (FontStyle, Option<String>)
pub fn new_typeface(&mut self, index: usize) -> Option<RCHandle<SkTypeface>>
pub fn match_style( &mut self, index: usize, pattern: FontStyle, ) -> Option<RCHandle<SkTypeface>>
pub fn new_empty() -> RCHandle<SkFontStyleSet>
§impl RCHandle<SkFontMgr>
impl RCHandle<SkFontMgr>
pub fn new() -> RCHandle<SkFontMgr>
pub fn empty() -> RCHandle<SkFontMgr>
pub fn count_families(&self) -> usize
pub fn family_name(&self, index: usize) -> String
pub fn family_names( &self, ) -> impl Iterator<Item = String> + Captures<&RCHandle<SkFontMgr>>
pub fn new_styleset(&self, index: usize) -> RCHandle<SkFontStyleSet>
pub fn new_style_set(&self, index: usize) -> RCHandle<SkFontStyleSet>
pub fn match_family( &self, family_name: impl AsRef<str>, ) -> RCHandle<SkFontStyleSet>
pub fn match_family_style( &self, family_name: impl AsRef<str>, style: FontStyle, ) -> Option<RCHandle<SkTypeface>>
pub fn match_family_style_character( &self, family_name: impl AsRef<str>, style: FontStyle, bcp_47: &[&str], character: i32, ) -> Option<RCHandle<SkTypeface>>
pub fn match_face_style( &self, _typeface: impl AsRef<RCHandle<SkTypeface>>, _style: FontStyle, ) -> !
pub fn new_from_data( &self, bytes: &[u8], ttc_index: impl Into<Option<usize>>, ) -> Option<RCHandle<SkTypeface>>
pub fn legacy_make_typeface<'a>( &self, family_name: impl Into<Option<&'a str>>, style: FontStyle, ) -> Option<RCHandle<SkTypeface>>
§impl RCHandle<SkImage>
impl RCHandle<SkImage>
pub fn from_raster_data(
info: &Handle<SkImageInfo>,
pixels: impl Into<RCHandle<SkData>>,
row_bytes: usize,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.63.0: use images::raster_from_data()
pub fn from_raster_data( info: &Handle<SkImageInfo>, pixels: impl Into<RCHandle<SkData>>, row_bytes: usize, ) -> Option<RCHandle<SkImage>>
Creates Image
from ImageInfo
, sharing pixels.
Image
is returned if ImageInfo
is valid. Valid ImageInfo
parameters include:
dimensions are greater than zero;
each dimension fits in 29 bits;
ColorType
and AlphaType
are valid, and ColorType
is not ColorType::Unknown
;
rowBytes are large enough to hold one row of pixels;
pixels is not nullptr, and contains enough data for Image
.
info
contains width, height,AlphaType
,ColorType
,ColorSpace
pixels
address or pixel storagerowBytes
size of pixel row or larger Returns:Image
sharing pixels, orNone
pub fn from_bitmap(bitmap: &Handle<SkBitmap>) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.63.0: use images::raster_from_bitmap()
pub fn from_bitmap(bitmap: &Handle<SkBitmap>) -> Option<RCHandle<SkImage>>
Creates Image
from bitmap, sharing or copying bitmap pixels. If the bitmap
is marked immutable, and its pixel memory is shareable, it may be shared
instead of copied.
Image
is returned if bitmap is valid. Valid Bitmap
parameters include:
dimensions are greater than zero;
each dimension fits in 29 bits;
ColorType
and AlphaType
are valid, and ColorType
is not ColorType::Unknown
;
row bytes are large enough to hold one row of pixels;
pixel address is not null
.
pub fn from_generator(
image_generator: RefHandle<SkImageGenerator>,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.63.0: use images::deferred_from_generator()
pub fn from_generator( image_generator: RefHandle<SkImageGenerator>, ) -> Option<RCHandle<SkImage>>
pub fn from_encoded(
data: impl Into<RCHandle<SkData>>,
) -> Option<RCHandle<SkImage>>
pub fn from_encoded( data: impl Into<RCHandle<SkData>>, ) -> Option<RCHandle<SkImage>>
pub fn from_encoded_with_alpha_type(
data: impl Into<RCHandle<SkData>>,
alpha_type: impl Into<Option<SkAlphaType>>,
) -> Option<RCHandle<SkImage>>
pub fn from_encoded_with_alpha_type( data: impl Into<RCHandle<SkData>>, alpha_type: impl Into<Option<SkAlphaType>>, ) -> Option<RCHandle<SkImage>>
Return an image backed by the encoded data, but attempt to defer decoding until the image is actually used/drawn. This deferral allows the system to cache the result, either on the CPU or on the GPU, depending on where the image is drawn. If memory is low, the cache may be purged, causing the next draw of the image to have to re-decode.
If alphaType is None
, the image’s alpha type will be chosen automatically based on the
image format. Transparent images will default to AlphaType::Premul
. If alphaType contains
AlphaType::Premul
or AlphaType::Unpremul
, that alpha type will be used. Forcing opaque
(passing AlphaType::Opaque
) is not allowed, and will return nullptr.
This is similar to decode_to_{raster,texture}
, but this method will attempt to defer the
actual decode, while the decode_to
… method explicitly decode and allocate the backend
when the call is made.
If the encoded format is not supported, None
is returned.
encoded
the encoded data Returns: createdImage
, orNone
pub fn decode_to_raster(_encoded: &[u8], _subset: impl Into<Option<IRect>>) -> !
pub fn new_raster_from_compressed(
data: impl Into<RCHandle<SkData>>,
dimensions: impl Into<ISize>,
ty: SkTextureCompressionType,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.63.0: use images::raster_from_compressed_texture_data()
pub fn new_raster_from_compressed( data: impl Into<RCHandle<SkData>>, dimensions: impl Into<ISize>, ty: SkTextureCompressionType, ) -> Option<RCHandle<SkImage>>
Creates a CPU-backed Image
from compressed data.
This method will decompress the compressed data and create an image wrapping it. Any mipmap levels present in the compressed data are discarded.
pub fn from_picture(
picture: impl Into<RCHandle<SkPicture>>,
dimensions: impl Into<ISize>,
matrix: Option<&Matrix>,
paint: Option<&Handle<SkPaint>>,
bit_depth: SkImages_BitDepth,
color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.63.0: use images::deferred_from_picture()
pub fn from_picture( picture: impl Into<RCHandle<SkPicture>>, dimensions: impl Into<ISize>, matrix: Option<&Matrix>, paint: Option<&Handle<SkPaint>>, bit_depth: SkImages_BitDepth, color_space: impl Into<Option<RCHandle<SkColorSpace>>>, ) -> Option<RCHandle<SkImage>>
pub fn from_picture_with_props(
picture: impl Into<RCHandle<SkPicture>>,
dimensions: impl Into<ISize>,
matrix: Option<&Matrix>,
paint: Option<&Handle<SkPaint>>,
bit_depth: SkImages_BitDepth,
color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
props: SurfaceProps,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.63.0: use images::deferred_from_picture()
pub fn from_picture_with_props( picture: impl Into<RCHandle<SkPicture>>, dimensions: impl Into<ISize>, matrix: Option<&Matrix>, paint: Option<&Handle<SkPaint>>, bit_depth: SkImages_BitDepth, color_space: impl Into<Option<RCHandle<SkColorSpace>>>, props: SurfaceProps, ) -> Option<RCHandle<SkImage>>
Creates Image
from picture. Returned Image
width and height are set by dimensions.
Image
draws picture with matrix and paint, set to bitDepth and colorSpace.
If matrix is None
, draws with identity Matrix
. If paint is None
, draws
with default Paint
. color_space may be None
.
picture
stream of drawing commandsdimensions
width and heightmatrix
Matrix
to rotate, scale, translate, and so on; may beNone
paint
Paint
to apply transparency, filtering, and so on; may beNone
bitDepth
8-bit integer or 16-bit float: per componentcolor_space
range of colors; may beNone
props
props to use when rasterizing the picture Returns: createdImage
, orNone
pub fn new_texture_from_compressed(
context: &mut RCHandle<GrDirectContext>,
data: RCHandle<SkData>,
dimensions: impl Into<ISize>,
ty: SkTextureCompressionType,
mipmapped: impl Into<Option<skgpu_Mipmapped>>,
is_protected: impl Into<Option<skgpu_Protected>>,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.63.0: use gpu::images::texture_from_compressed_texture_data()
pub fn new_texture_from_compressed( context: &mut RCHandle<GrDirectContext>, data: RCHandle<SkData>, dimensions: impl Into<ISize>, ty: SkTextureCompressionType, mipmapped: impl Into<Option<skgpu_Mipmapped>>, is_protected: impl Into<Option<skgpu_Protected>>, ) -> Option<RCHandle<SkImage>>
Creates a GPU-backed Image
from compressed data.
This method will return an Image
representing the compressed data.
If the GPU doesn’t support the specified compression method, the data
will be decompressed and then wrapped in a GPU-backed image.
Note: one can query the supported compression formats via
gpu::RecordingContext::compressed_backend_format
.
context
GPU contextdata
compressed data to store inImage
width
width of fullImage
height
height of fullImage
ty
type of compression usedmipmapped
does ‘data’ contain data for all the mipmap levels?is_protected
do the contents of ‘data’ require DRM protection (on Vulkan)? Returns: createdImage
, orNone
pub fn from_compressed( _context: &mut RCHandle<GrRecordingContext>, _data: RCHandle<SkData>, _dimensions: impl Into<ISize>, _ct: SkTextureCompressionType, ) -> !
pub fn from_texture(
context: &mut RCHandle<GrRecordingContext>,
backend_texture: &RefHandle<GrBackendTexture>,
origin: GrSurfaceOrigin,
color_type: ColorType,
alpha_type: SkAlphaType,
color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
) -> Option<RCHandle<SkImage>>
pub fn from_texture( context: &mut RCHandle<GrRecordingContext>, backend_texture: &RefHandle<GrBackendTexture>, origin: GrSurfaceOrigin, color_type: ColorType, alpha_type: SkAlphaType, color_space: impl Into<Option<RCHandle<SkColorSpace>>>, ) -> Option<RCHandle<SkImage>>
Creates Image
from GPU texture associated with context. GPU texture must stay
valid and unchanged until texture_release_proc
is called. texture_release_proc
is
passed release_context
when Image
is deleted or no longer refers to texture.
Image
is returned if format of backend_texture
is recognized and supported.
Recognized formats vary by GPU back-end.
Note: When using a DDL recording context, texture_release_proc
will be called on the
GPU thread after the DDL is played back on the direct context.
context
GPU contextbackend_texture
Texture residing on GPUorigin
Origin ofbackend_texture
color_type
Color type of the resulting imagealpha_type
Alpha type of the resulting imagecolor_space
This describes the color space of this image’s contents, as seen after sampling. In general, if the format of the backend texture is SRGB, some linearcolor_space
should be supplied (e.g.,ColorSpace::new_srgb_linear()
)). If the format of the backend texture is linear, then thecolor_space
should include a description of the transfer function as well (e.g.,ColorSpace::MakeSRGB
).texture_release_proc
Function called when texture can be releasedrelease_context
State passed totexture_release_proc
Returns: CreatedImage
, orNone
pub fn from_pixmap_cross_context( context: &mut RCHandle<GrDirectContext>, pixmap: &Pixmap<'_>, build_mips: bool, limit_to_max_texture_size: impl Into<Option<bool>>, ) -> Option<RCHandle<SkImage>>
pub fn new_cross_context_from_pixmap(
context: &mut RCHandle<GrDirectContext>,
pixmap: &Pixmap<'_>,
build_mips: bool,
limit_to_max_texture_size: impl Into<Option<bool>>,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.63.0: use gpu::images::cross_context_texture_from_pixmap()
pub fn new_cross_context_from_pixmap( context: &mut RCHandle<GrDirectContext>, pixmap: &Pixmap<'_>, build_mips: bool, limit_to_max_texture_size: impl Into<Option<bool>>, ) -> Option<RCHandle<SkImage>>
Creates Image
from pixmap. Image
is uploaded to GPU back-end using context.
Created Image
is available to other GPU contexts, and is available across thread
boundaries. All contexts must be in the same GPU share group, or otherwise
share resources.
When Image
is no longer referenced, context releases texture memory
asynchronously.
ColorSpace
of Image
is determined by pixmap.color_space()
.
Image
is returned referring to GPU back-end if context is not None
,
format of data is recognized and supported, and if context supports moving
resources between contexts. Otherwise, pixmap pixel data is copied and Image
as returned in raster format if possible; None
may be returned.
Recognized GPU formats vary by platform and GPU back-end.
pub fn from_adopted_texture(
context: &mut RCHandle<GrRecordingContext>,
backend_texture: &RefHandle<GrBackendTexture>,
texture_origin: GrSurfaceOrigin,
color_type: ColorType,
alpha_type: impl Into<Option<SkAlphaType>>,
color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.63.0: use gpu::images::adopt_texture_from()
pub fn from_adopted_texture( context: &mut RCHandle<GrRecordingContext>, backend_texture: &RefHandle<GrBackendTexture>, texture_origin: GrSurfaceOrigin, color_type: ColorType, alpha_type: impl Into<Option<SkAlphaType>>, color_space: impl Into<Option<RCHandle<SkColorSpace>>>, ) -> Option<RCHandle<SkImage>>
Creates Image
from backend_texture
associated with context. backend_texture
and
returned Image
are managed internally, and are released when no longer needed.
Image
is returned if format of backend_texture
is recognized and supported.
Recognized formats vary by GPU back-end.
context
GPU contextbackend_texture
texture residing on GPUtexture_origin
origin ofbackend_texture
color_type
color type of the resulting imagealpha_type
alpha type of the resulting imagecolor_space
range of colors; may beNone
Returns: createdImage
, orNone
pub fn from_yuva_textures(
context: &mut RCHandle<GrRecordingContext>,
yuva_textures: &Handle<GrYUVABackendTextures>,
image_color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.63.0: use gpu::images::texture_from_yuva_textures()
pub fn from_yuva_textures( context: &mut RCHandle<GrRecordingContext>, yuva_textures: &Handle<GrYUVABackendTextures>, image_color_space: impl Into<Option<RCHandle<SkColorSpace>>>, ) -> Option<RCHandle<SkImage>>
Creates an Image
from YUV[A]
planar textures. This requires that the textures stay valid
for the lifetime of the image. The ReleaseContext
can be used to know when it is safe to
either delete or overwrite the textures. If ReleaseProc
is provided it is also called before
return on failure.
context
GPU contextyuva_textures
A set of textures containing YUVA data and a description of the data and transformation to RGBA.image_color_space
range of colors of the resulting image after conversion to RGB; may beNone
texture_release_proc
called when the backend textures can be releasedrelease_context
state passed totexture_release_proc
Returns: createdImage
, orNone
pub fn from_yuva_pixmaps(
context: &mut RCHandle<GrRecordingContext>,
yuva_pixmaps: &Handle<SkYUVAPixmaps>,
build_mips: impl Into<Option<skgpu_Mipmapped>>,
limit_to_max_texture_size: impl Into<Option<bool>>,
image_color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.63.0: use gpu::images::texture_from_yuva_pixmaps()
pub fn from_yuva_pixmaps( context: &mut RCHandle<GrRecordingContext>, yuva_pixmaps: &Handle<SkYUVAPixmaps>, build_mips: impl Into<Option<skgpu_Mipmapped>>, limit_to_max_texture_size: impl Into<Option<bool>>, image_color_space: impl Into<Option<RCHandle<SkColorSpace>>>, ) -> Option<RCHandle<SkImage>>
Creates Image
from crate::YUVAPixmaps
.
The image will remain planar with each plane converted to a texture using the passed
gpu::RecordingContext
.
crate::YUVAPixmaps
has a crate::YUVAInfo
which specifies the transformation from YUV to RGB.
The ColorSpace
of the resulting RGB values is specified by image_color_space
. This will
be the ColorSpace
reported by the image and when drawn the RGB values will be converted
from this space into the destination space (if the destination is tagged).
Currently, this is only supported using the GPU backend and will fail if context is None
.
crate::YUVAPixmaps
does not need to remain valid after this returns.
context
GPU contextpixmaps
The planes as pixmaps with supportedcrate::YUVAInfo
that specifies conversion to RGB.build_mips
create internal YUVA textures as mip map ifYes
. This is silently ignored if the context does not support mip maps.limit_to_max_texture_size
downscale image to GPU maximum texture size, if necessaryimage_color_space
range of colors of the resulting image; may beNone
Returns: createdImage
, orNone
pub fn from_nv12_textures_copy( _context: &mut RCHandle<GrDirectContext>, _yuv_color_space: SkYUVColorSpace, _nv12_textures: &[RefHandle<GrBackendTexture>; 2], _image_origin: GrSurfaceOrigin, _image_color_space: impl Into<Option<RCHandle<SkColorSpace>>>, ) -> !
pub fn image_info(&self) -> &Handle<SkImageInfo>
pub fn image_info(&self) -> &Handle<SkImageInfo>
pub fn dimensions(&self) -> ISize
pub fn dimensions(&self) -> ISize
Returns ISize
{ width(), height() }
.
Returns: integral size of width()
and height()
pub fn bounds(&self) -> IRect
pub fn bounds(&self) -> IRect
Returns IRect
{ 0, 0, width(), height() }
.
Returns: integral rectangle from origin to width()
and height()
pub fn alpha_type(&self) -> SkAlphaType
pub fn alpha_type(&self) -> SkAlphaType
pub fn color_type(&self) -> ColorType
pub fn color_type(&self) -> ColorType
Returns ColorType
if known; otherwise, returns ColorType::Unknown
.
pub fn color_space(&self) -> RCHandle<SkColorSpace>
pub fn color_space(&self) -> RCHandle<SkColorSpace>
Returns a smart pointer to ColorSpace
, the range of colors, associated with
Image
. The smart pointer tracks the number of objects sharing this
ColorSpace
reference so the memory is released when the owners destruct.
The returned ColorSpace
is immutable.
ColorSpace
returned was passed to an Image
constructor,
or was parsed from encoded data. ColorSpace
returned may be ignored when Image
is drawn, depending on the capabilities of the crate::Surface
receiving the drawing.
Returns: ColorSpace
in Image
, or None
, wrapped in a smart pointer
pub fn is_alpha_only(&self) -> bool
pub fn is_alpha_only(&self) -> bool
Returns true
if Image
pixels represent transparency only. If true
, each pixel
is packed in 8 bits as defined by ColorType::Alpha8
.
Returns: true
if pixels represent a transparency mask
pub fn is_opaque(&self) -> bool
pub fn is_opaque(&self) -> bool
Returns true
if pixels ignore their alpha value and are treated as fully opaque.
Returns: true
if AlphaType
is AlphaType::Opaque
pub fn to_shader<'a>(
&self,
tile_modes: impl Into<Option<(SkTileMode, SkTileMode)>>,
sampling: impl Into<SamplingOptions>,
local_matrix: impl Into<Option<&'a Matrix>>,
) -> Option<RCHandle<SkShader>>
pub fn to_shader<'a>( &self, tile_modes: impl Into<Option<(SkTileMode, SkTileMode)>>, sampling: impl Into<SamplingOptions>, local_matrix: impl Into<Option<&'a Matrix>>, ) -> Option<RCHandle<SkShader>>
Make a shader with the specified tiling and mipmap sampling.
pub fn to_raw_shader<'a>(
&self,
tile_modes: impl Into<Option<(SkTileMode, SkTileMode)>>,
sampling: impl Into<SamplingOptions>,
local_matrix: impl Into<Option<&'a Matrix>>,
) -> Option<RCHandle<SkShader>>
pub fn to_raw_shader<'a>( &self, tile_modes: impl Into<Option<(SkTileMode, SkTileMode)>>, sampling: impl Into<SamplingOptions>, local_matrix: impl Into<Option<&'a Matrix>>, ) -> Option<RCHandle<SkShader>>
to_raw_shader
functions like to_shader
, but for images that contain non-color data.
This includes images encoding things like normals, material properties (eg, roughness),
heightmaps, or any other purely mathematical data that happens to be stored in an image.
These types of images are useful with some programmable shaders (see: crate::RuntimeEffect
).
Raw image shaders work like regular image shaders (including filtering and tiling), with a few major differences:
- No color space transformation is ever applied (the color space of the image is ignored).
- Images with an alpha type of
Unpremul
are not automatically premultiplied. - Bicubic filtering is not supported. If
SamplingOptions::use_cubic
istrue
, these factories will returnNone
.
pub fn peek_pixels(&self) -> Option<Pixmap<'_>>
pub fn peek_pixels(&self) -> Option<Pixmap<'_>>
Copies Image
pixel address, row bytes, and ImageInfo
to pixmap, if address
is available, and returns true
. If pixel address is not available, return
false
and leave pixmap unchanged.
pixmap
storage for pixel state if pixels are readable; otherwise, ignored Returns:true
ifImage
has direct access to pixels
pub fn is_texture_backed(&self) -> bool
pub fn is_texture_backed(&self) -> bool
pub fn texture_size(&self) -> usize
pub fn texture_size(&self) -> usize
Returns an approximation of the amount of texture memory used by the image. Returns zero if the image is not texture backed or if the texture has an external format.
pub fn is_valid(&self, context: &mut RCHandle<GrRecordingContext>) -> bool
pub fn is_valid(&self, context: &mut RCHandle<GrRecordingContext>) -> bool
Returns true
if Image
can be drawn on either raster surface or GPU surface.
If context is None
, tests if Image
draws on raster surface;
otherwise, tests if Image
draws on GPU surface associated with context.
Image
backed by GPU texture may become invalid if associated context is
invalid. lazy image may be invalid and may not draw to raster surface or
GPU surface or both.
context
GPU context Returns:true
ifImage
can be drawn
pub fn flush<'a>(
&self,
context: &mut RCHandle<GrDirectContext>,
flush_info: impl Into<Option<&'a FlushInfo>>,
) -> GrSemaphoresSubmitted
👎Deprecated since 0.63.0: use gpu::DirectContext::flush()
pub fn flush<'a>( &self, context: &mut RCHandle<GrDirectContext>, flush_info: impl Into<Option<&'a FlushInfo>>, ) -> GrSemaphoresSubmitted
pub fn flush_with_info(
&self,
context: &mut RCHandle<GrDirectContext>,
flush_info: &FlushInfo,
) -> GrSemaphoresSubmitted
👎Deprecated since 0.46.0: use gpu::DirectContext::flush()
pub fn flush_with_info( &self, context: &mut RCHandle<GrDirectContext>, flush_info: &FlushInfo, ) -> GrSemaphoresSubmitted
Flushes any pending uses of texture-backed images in the GPU backend. If the image is not
texture-backed (including promise texture images) or if the gpu::DirectContext
does not
have the same context ID as the context backing the image then this is a no-op.
If the image was not used in any non-culled draws in the current queue of work for the
passed gpu::DirectContext
then this is a no-op unless the gpu::FlushInfo
contains semaphores or
a finish proc. Those are respected even when the image has not been used.
context
the context on which to flush pending usages of the image.info
flush options
pub fn flush_and_submit(&self, context: &mut RCHandle<GrDirectContext>)
👎Deprecated since 0.63.0: use gpu::DirectContext::flush_and_submit()
pub fn flush_and_submit(&self, context: &mut RCHandle<GrDirectContext>)
Version of flush()
that uses a default gpu::FlushInfo
. Also submits the flushed work to the
GPU.
pub fn backend_texture(
&self,
flush_pending_gr_context_io: bool,
) -> Option<(RefHandle<GrBackendTexture>, GrSurfaceOrigin)>
👎Deprecated since 0.63.0: use gpu::images::get_backend_texture_from_image()
pub fn backend_texture( &self, flush_pending_gr_context_io: bool, ) -> Option<(RefHandle<GrBackendTexture>, GrSurfaceOrigin)>
Retrieves the back-end texture. If Image
has no back-end texture, None
is returned.
If flush_pending_gr_context_io
is true
, completes deferred I/O operations.
If origin in not None
, copies location of content drawn into Image
.
flush_pending_gr_context_io
flag to flush outstanding requests Returns: back-end API texture handle; invalid on failure
pub fn read_pixels_with_context<'a, P>(
&self,
context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>,
dst_info: &Handle<SkImageInfo>,
pixels: &mut [P],
dst_row_bytes: usize,
src: impl Into<IPoint>,
caching_hint: SkImage_CachingHint,
) -> bool
pub fn read_pixels_with_context<'a, P>( &self, context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>, dst_info: &Handle<SkImageInfo>, pixels: &mut [P], dst_row_bytes: usize, src: impl Into<IPoint>, caching_hint: SkImage_CachingHint, ) -> bool
Copies crate::Rect
of pixels from Image
to dst_pixels
. Copy starts at offset (src_x
, src_y
),
and does not exceed Image
(width(), height()).
dst_info
specifies width, height, ColorType
, AlphaType
, and ColorSpace
of
destination. dst_row_bytes
specifies the gap from one destination row to the next.
Returns true
if pixels are copied. Returns false
if:
dst_info
.addr()
equalsNone
dst_row_bytes
is less thandst_info.min_row_bytes()
crate::PixelRef
isNone
Pixels are copied only if pixel conversion is possible. If Image
ColorType
is
ColorType::Gray8
, or ColorType::Alpha8
; dst_info.color_type()
must match.
If Image
ColorType
is ColorType::Gray8
, dst_info
.color_space()
must match.
If Image
AlphaType
is AlphaType::Opaque
, dst_info
.alpha_type()
must
match. If Image
ColorSpace
is None
, dst_info.color_space()
must match. Returns
false
if pixel conversion is not possible.
src_x
and src_y
may be negative to copy only top or left of source. Returns
false
if width()
or height()
is zero or negative.
Returns false
if abs(src_x
) >= Image width(), or if abs(src_y
) >= Image height().
If caching_hint
is CachingHint::Allow
, pixels may be retained locally.
If caching_hint
is CachingHint::Disallow
, pixels are not added to the local cache.
context
thegpu::DirectContext
in play, if it existsdst_info
destination width, height,ColorType
,AlphaType
,ColorSpace
dst_pixels
destination pixel storagedst_row_bytes
destination row lengthsrc_x
column index whose absolute value is less thanwidth()
src_y
row index whose absolute value is less thanheight()
caching_hint
whether the pixels should be cached locally Returns:true
if pixels are copied todst_pixels
pub fn read_pixels_to_pixmap_with_context<'a>(
&self,
context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>,
dst: &Pixmap<'_>,
src: impl Into<IPoint>,
caching_hint: SkImage_CachingHint,
) -> bool
pub fn read_pixels_to_pixmap_with_context<'a>( &self, context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>, dst: &Pixmap<'_>, src: impl Into<IPoint>, caching_hint: SkImage_CachingHint, ) -> bool
Copies a crate::Rect
of pixels from Image
to dst. Copy starts at (src_x
, src_y
), and
does not exceed Image
(width(), height()).
dst specifies width, height, ColorType
, AlphaType
, ColorSpace
, pixel storage,
and row bytes of destination. dst.row_bytes()
specifics the gap from one destination
row to the next. Returns true
if pixels are copied. Returns false
if:
- dst pixel storage equals
None
- dst.
row_bytes
is less thanImageInfo::min_row_bytes
crate::PixelRef
isNone
Pixels are copied only if pixel conversion is possible. If Image
ColorType
is
ColorType::Gray8
, or ColorType::Alpha8
; dst.color_type()
must match.
If Image
ColorType
is ColorType::Gray8
, dst.color_space()
must match.
If Image
AlphaType
is AlphaType::Opaque
, dst.alpha_type()
must
match. If Image
ColorSpace
is None
, dst.color_space()
must match. Returns
false
if pixel conversion is not possible.
src_x
and src_y
may be negative to copy only top or left of source. Returns
false
if width()
or height()
is zero or negative.
Returns false
if abs(src_x
) >= Image width(), or if abs(src_y
) >= Image height().
If caching_hint
is CachingHint::Allow
, pixels may be retained locally.
If caching_hint
is CachingHint::Disallow
, pixels are not added to the local cache.
context
thegpu::DirectContext
in play, if it existsdst
destinationPixmap
:ImageInfo
, pixels, row bytessrc_x
column index whose absolute value is less thanwidth()
src_y
row index whose absolute value is less thanheight()
caching_hint
whether the pixels should be cachedlocally_z
Returns:true
if pixels are copied to dst
pub fn read_pixels<P>(
&self,
dst_info: &Handle<SkImageInfo>,
pixels: &mut [P],
dst_row_bytes: usize,
src: impl Into<IPoint>,
caching_hint: SkImage_CachingHint,
) -> bool
pub fn read_pixels<P>( &self, dst_info: &Handle<SkImageInfo>, pixels: &mut [P], dst_row_bytes: usize, src: impl Into<IPoint>, caching_hint: SkImage_CachingHint, ) -> bool
pub unsafe fn read_pixels_to_pixmap(
&self,
dst: &Pixmap<'_>,
src: impl Into<IPoint>,
caching_hint: SkImage_CachingHint,
) -> bool
pub unsafe fn read_pixels_to_pixmap( &self, dst: &Pixmap<'_>, src: impl Into<IPoint>, caching_hint: SkImage_CachingHint, ) -> bool
pub fn scale_pixels(
&self,
dst: &Pixmap<'_>,
sampling: impl Into<SamplingOptions>,
caching_hint: impl Into<Option<SkImage_CachingHint>>,
) -> bool
pub fn scale_pixels( &self, dst: &Pixmap<'_>, sampling: impl Into<SamplingOptions>, caching_hint: impl Into<Option<SkImage_CachingHint>>, ) -> bool
Copies Image
to dst, scaling pixels to fit dst.width()
and dst.height()
, and
converting pixels to match dst.color_type()
and dst.alpha_type()
. Returns true
if
pixels are copied. Returns false
if dst.addr()
is None
, or dst.row_bytes()
is
less than dst ImageInfo::min_row_bytes
.
Pixels are copied only if pixel conversion is possible. If Image
ColorType
is
ColorType::Gray8
, or ColorType::Alpha8
; dst.color_type()
must match.
If Image
ColorType
is ColorType::Gray8
, dst.color_space()
must match.
If Image
AlphaType
is AlphaType::Opaque
, dst.alpha_type()
must
match. If Image
ColorSpace
is None
, dst.color_space()
must match. Returns
false
if pixel conversion is not possible.
If caching_hint
is CachingHint::Allow
, pixels may be retained locally.
If caching_hint
is CachingHint::Disallow
, pixels are not added to the local cache.
pub fn encode_to_data_with_context(
&self,
context: impl Into<Option<RCHandle<GrDirectContext>>>,
image_format: SkEncodedImageFormat,
quality: impl Into<Option<u32>>,
) -> Option<RCHandle<SkData>>
👎Deprecated since 0.63.0: Use encode
pub fn encode_to_data_with_context( &self, context: impl Into<Option<RCHandle<GrDirectContext>>>, image_format: SkEncodedImageFormat, quality: impl Into<Option<u32>>, ) -> Option<RCHandle<SkData>>
Encodes Image
pixels, returning result as Data
.
Returns None
if encoding fails, or if encoded_image_format
is not supported.
Image
encoding in a format requires both building with one or more of:
SK_ENCODE_JPEG, SK_ENCODE_PNG, SK_ENCODE_WEBP; and platform support
for the encoded format.
If SK_BUILD_FOR_MAC or SK_BUILD_FOR_IOS is defined, encoded_image_format
can
additionally be one of: EncodedImageFormat::ICO
, EncodedImageFormat::BMP
,
EncodedImageFormat::GIF
.
quality is a platform and format specific metric trading off size and encoding error. When used, quality equaling 100 encodes with the least error. quality may be ignored by the encoder.
context
- thegpu::DirectContext
in play, if it exists; can beNone
encoded_image_format
- one of:EncodedImageFormat::JPEG
,EncodedImageFormat::PNG
,EncodedImageFormat::WEBP
quality
- encoder specific metric with 100 equaling best Returns: encodedImage
, orNone
pub fn encode_to_data(
&self,
image_format: SkEncodedImageFormat,
) -> Option<RCHandle<SkData>>
👎Deprecated since 0.63.0: Support for encoding GPU backed images without a context was removed, use encode_to_data_with_context
instead
pub fn encode_to_data( &self, image_format: SkEncodedImageFormat, ) -> Option<RCHandle<SkData>>
encode_to_data_with_context
insteadpub fn encode_to_data_with_quality(
&self,
image_format: SkEncodedImageFormat,
quality: u32,
) -> Option<RCHandle<SkData>>
👎Deprecated since 0.63.0: Support for encoding GPU backed images without a context was removed, use encode_to_data_with_context
instead
pub fn encode_to_data_with_quality( &self, image_format: SkEncodedImageFormat, quality: u32, ) -> Option<RCHandle<SkData>>
encode_to_data_with_context
insteadEncodes Image
pixels, returning result as Data
.
Returns None
if encoding fails, or if encoded_image_format
is not supported.
Image
encoding in a format requires both building with one or more of:
SK_ENCODE_JPEG, SK_ENCODE_PNG, SK_ENCODE_WEBP; and platform support
for the encoded format.
If SK_BUILD_FOR_MAC or SK_BUILD_FOR_IOS is defined, encoded_image_format
can
additionally be one of: EncodedImageFormat::ICO
, EncodedImageFormat::BMP
,
EncodedImageFormat::GIF
.
quality is a platform and format specific metric trading off size and encoding error. When used, quality equaling 100 encodes with the least error. quality may be ignored by the encoder.
encoded_image_format
one of:EncodedImageFormat::JPEG
,EncodedImageFormat::PNG
,EncodedImageFormat::WEBP
quality
encoder specific metric with 100 equaling best Returns: encodedImage
, orNone
pub fn encoded_data(&self) -> Option<RCHandle<SkData>>
pub fn encoded_data(&self) -> Option<RCHandle<SkData>>
Returns encoded Image
pixels as Data
, if Image
was created from supported
encoded stream format. Platform support for formats vary and may require building
with one or more of: SK_ENCODE_JPEG, SK_ENCODE_PNG, SK_ENCODE_WEBP.
Returns None
if Image
contents are not encoded.
Returns: encoded Image
, or None
pub fn new_subset(&self, rect: impl AsRef<IRect>) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.64.0: use make_subset()
pub fn new_subset(&self, rect: impl AsRef<IRect>) -> Option<RCHandle<SkImage>>
pub fn new_subset_with_context<'a>(
&self,
rect: impl AsRef<IRect>,
direct: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.64.0: use make_subset()
pub fn new_subset_with_context<'a>( &self, rect: impl AsRef<IRect>, direct: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>, ) -> Option<RCHandle<SkImage>>
Returns subset of this image.
Returns None
if any of the following are true:
- Subset is empty
- Subset is not contained inside the image’s bounds
- Pixels in the image could not be read or copied
If this image is texture-backed, the context parameter is required and must match the context of the source image. If the context parameter is provided, and the image is raster-backed, the subset will be converted to texture-backed.
subset
bounds of returnedImage
context
thegpu::DirectContext
in play, if it exists Returns: the subsetted image, orNone
pub fn make_subset<'a>(
&self,
direct: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>,
subset: impl AsRef<IRect>,
) -> Option<RCHandle<SkImage>>
pub fn make_subset<'a>( &self, direct: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>, subset: impl AsRef<IRect>, ) -> Option<RCHandle<SkImage>>
Returns subset of this image.
Returns None
if any of the following are true:
- Subset is empty - Subset is not contained inside the image’s bounds
- Pixels in the source image could not be read or copied
- This image is texture-backed and the provided context is null or does not match the
source image’s context.
If the source image was texture-backed, the resulting image will be texture-backed also. Otherwise, the returned image will be raster-backed.
direct
- thegpu::DirectContext
of the source image (None
is ok if the source image is not texture-backed).subset
- bounds of returnedImage
Returns: the subsetted image, orNone
pub fn has_mipmaps(&self) -> bool
pub fn has_mipmaps(&self) -> bool
Returns true
if the image has mipmap levels.
pub fn with_default_mipmaps(&self) -> Option<RCHandle<SkImage>>
pub fn with_default_mipmaps(&self) -> Option<RCHandle<SkImage>>
Returns an image with the same “base” pixels as the this image, but with mipmap levels automatically generated and attached.
pub fn new_texture_image(
&self,
context: &mut RCHandle<GrDirectContext>,
mipmapped: skgpu_Mipmapped,
) -> Option<RCHandle<SkImage>>
pub fn new_texture_image( &self, context: &mut RCHandle<GrDirectContext>, mipmapped: skgpu_Mipmapped, ) -> Option<RCHandle<SkImage>>
pub fn new_texture_image_budgeted(
&self,
direct_context: &mut RCHandle<GrDirectContext>,
mipmapped: skgpu_Mipmapped,
budgeted: Budgeted,
) -> Option<RCHandle<SkImage>>
pub fn new_texture_image_budgeted( &self, direct_context: &mut RCHandle<GrDirectContext>, mipmapped: skgpu_Mipmapped, budgeted: Budgeted, ) -> Option<RCHandle<SkImage>>
Returns Image
backed by GPU texture associated with context. Returned Image
is
compatible with crate::Surface
created with dst_color_space
. The returned Image
respects
mipmapped setting; if mipmapped equals gpu::Mipmapped::Yes
, the backing texture
allocates mip map levels.
The mipmapped parameter is effectively treated as No
if MIP maps are not supported by the
GPU.
Returns original Image
if the image is already texture-backed, the context matches, and
mipmapped is compatible with the backing GPU texture. crate::Budgeted
is ignored in this case.
Returns None
if context is None
, or if Image
was created with another
gpu::DirectContext
.
direct_context
thegpu::DirectContext
in play, if it existsmipmapped
whether createdImage
texture must allocate mip map levelsbudgeted
whether to count a newly created texture for the returned image counts against the context’s budget. Returns: createdImage
, orNone
pub fn to_non_texture_image(&self) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.64.0: use make_non_texture_image()
pub fn to_non_texture_image(&self) -> Option<RCHandle<SkImage>>
Returns raster image or lazy image. Copies Image
backed by GPU texture into
CPU memory if needed. Returns original Image
if decoded in raster bitmap,
or if encoded in a stream.
Returns None
if backed by GPU texture and copy fails.
Returns: raster image, lazy image, or None
example: https://fiddle.skia.org/c/@Image_makeNonTextureImage
pub fn make_non_texture_image<'a>(
&self,
context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>,
) -> Option<RCHandle<SkImage>>
pub fn make_non_texture_image<'a>( &self, context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>, ) -> Option<RCHandle<SkImage>>
Returns raster image or lazy image. Copies Image
backed by GPU texture into
CPU memory if needed. Returns original Image
if decoded in raster bitmap,
or if encoded in a stream.
Returns None
if backed by GPU texture and copy fails.
Returns: raster image, lazy image, or None
example: https://fiddle.skia.org/c/@Image_makeNonTextureImage
pub fn to_raster_image(
&self,
caching_hint: impl Into<Option<SkImage_CachingHint>>,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.64.0: use make_raster_image()
pub fn to_raster_image( &self, caching_hint: impl Into<Option<SkImage_CachingHint>>, ) -> Option<RCHandle<SkImage>>
Returns raster image. Copies Image
backed by GPU texture into CPU memory,
or decodes Image
from lazy image. Returns original Image
if decoded in
raster bitmap.
Returns None
if copy, decode, or pixel read fails.
If caching_hint
is CachingHint::Allow
, pixels may be retained locally.
If caching_hint
is CachingHint::Disallow
, pixels are not added to the local cache.
Returns: raster image, or None
pub fn make_raster_image<'a>(
&self,
context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>,
caching_hint: impl Into<Option<SkImage_CachingHint>>,
) -> Option<RCHandle<SkImage>>
pub fn make_raster_image<'a>( &self, context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>, caching_hint: impl Into<Option<SkImage_CachingHint>>, ) -> Option<RCHandle<SkImage>>
Returns raster image. Copies Image
backed by GPU texture into CPU memory,
or decodes Image
from lazy image. Returns original Image
if decoded in
raster bitmap.
Returns None
if copy, decode, or pixel read fails.
If caching_hint
is CachingHint::Allow
, pixels may be retained locally.
If caching_hint
is CachingHint::Disallow
, pixels are not added to the local cache.
Returns: raster image, or None
pub fn new_with_filter(
&self,
_context: Option<&mut RCHandle<GrRecordingContext>>,
filter: &RCHandle<SkImageFilter>,
clip_bounds: impl Into<IRect>,
subset: impl Into<IRect>,
) -> Option<(RCHandle<SkImage>, IRect, IPoint)>
👎Deprecated since 0.67.0: use images::make_with_filter()
pub fn new_with_filter( &self, _context: Option<&mut RCHandle<GrRecordingContext>>, filter: &RCHandle<SkImageFilter>, clip_bounds: impl Into<IRect>, subset: impl Into<IRect>, ) -> Option<(RCHandle<SkImage>, IRect, IPoint)>
Creates filtered Image
. filter processes original Image
, potentially changing
color, position, and size. subset is the bounds of original Image
processed
by filter. clip_bounds
is the expected bounds of the filtered Image
. out_subset
is required storage for the actual bounds of the filtered Image
. offset is
required storage for translation of returned Image
.
Returns None
if Image
could not be created or if the recording context provided doesn’t
match the GPU context in which the image was created. If None
is returned, out_subset
and offset are undefined.
Useful for animation of ImageFilter
that varies size from frame to frame.
Returned Image
is created larger than required by filter so that GPU texture
can be reused with different sized effects. out_subset
describes the valid bounds
of GPU texture returned. offset translates the returned Image
to keep subsequent
animation frames aligned with respect to each other.
context
thegpu::RecordingContext
in play - if it existsfilter
howImage
is sampled when transformedsubset
bounds ofImage
processed by filterclip_bounds
expected bounds of filteredImage
out_subset
storage for returnedImage
boundsoffset
storage for returnedImage
translation Returns: filteredImage
, orNone
pub fn is_lazy_generated(&self) -> bool
pub fn is_lazy_generated(&self) -> bool
Returns true
if Image
is backed by an image-generator or other service that creates
and caches its pixels or texture on-demand.
Returns: true
if Image
is created as needed
example: https://fiddle.skia.org/c/@Image_isLazyGenerated_a example: https://fiddle.skia.org/c/@Image_isLazyGenerated_b
pub fn new_color_space(
&self,
color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.64.0: use make_color_space()
pub fn new_color_space( &self, color_space: impl Into<Option<RCHandle<SkColorSpace>>>, ) -> Option<RCHandle<SkImage>>
pub fn new_color_space_with_context<'a>(
&self,
color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
direct: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>,
) -> Option<RCHandle<SkImage>>
👎Deprecated since 0.64.0: use make_color_space()
pub fn new_color_space_with_context<'a>( &self, color_space: impl Into<Option<RCHandle<SkColorSpace>>>, direct: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>, ) -> Option<RCHandle<SkImage>>
Creates Image
in target ColorSpace
.
Returns None
if Image
could not be created.
Returns original Image
if it is in target ColorSpace
.
Otherwise, converts pixels from Image
ColorSpace
to target ColorSpace
.
If Image
color_space()
returns None
, Image
ColorSpace
is assumed to be s_rgb
.
If this image is texture-backed, the context parameter is required and must match the context of the source image.
target
ColorSpace
describing color range of returnedImage
direct
Thegpu::DirectContext
in play, if it exists Returns: createdImage
in targetColorSpace
pub fn make_color_space<'a>(
&self,
direct: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>,
color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
) -> Option<RCHandle<SkImage>>
pub fn make_color_space<'a>( &self, direct: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>, color_space: impl Into<Option<RCHandle<SkColorSpace>>>, ) -> Option<RCHandle<SkImage>>
Creates Image
in target ColorSpace
.
Returns None
if Image
could not be created.
Returns original Image
if it is in target ColorSpace
.
Otherwise, converts pixels from Image
ColorSpace
to target ColorSpace
.
If Image
color_space()
returns None
, Image
ColorSpace
is assumed to be s_rgb
.
If this image is texture-backed, the context parameter is required and must match the context of the source image.
direct
Thegpu::DirectContext
in play, if it existstarget
ColorSpace
describing color range of returnedImage
Returns: createdImage
in targetColorSpace
pub fn reinterpret_color_space(
&self,
new_color_space: impl Into<RCHandle<SkColorSpace>>,
) -> Option<RCHandle<SkImage>>
pub fn reinterpret_color_space( &self, new_color_space: impl Into<RCHandle<SkColorSpace>>, ) -> Option<RCHandle<SkImage>>
Creates a new Image
identical to this one, but with a different ColorSpace
.
This does not convert the underlying pixel data, so the resulting image will draw
differently.
§impl RCHandle<SkImageFilter>
impl RCHandle<SkImageFilter>
pub fn filter_bounds<'a>( &self, src: impl AsRef<IRect>, ctm: &Matrix, map_direction: SkImageFilter_MapDirection, input_rect: impl Into<Option<&'a IRect>>, ) -> IRect
pub fn color_filter_node(&self) -> Option<RCHandle<SkColorFilter>>
pub fn to_a_color_filter(&self) -> Option<RCHandle<SkColorFilter>>
pub fn count_inputs(&self) -> usize
pub fn input(&self, i: usize) -> Option<RCHandle<SkImageFilter>>
pub fn get_input(&self, i: usize) -> Option<RCHandle<SkImageFilter>>
pub fn inputs( &self, ) -> impl Iterator<Item = Option<RCHandle<SkImageFilter>>> + Captures<&RCHandle<SkImageFilter>>
pub fn compute_fast_bounds(&self, bounds: impl AsRef<Rect>) -> Rect
pub fn can_compute_fast_bounds(&self) -> bool
pub fn with_local_matrix( &self, matrix: &Matrix, ) -> Option<RCHandle<SkImageFilter>>
§impl RCHandle<SkMaskFilter>
impl RCHandle<SkMaskFilter>
pub fn blur(
style: SkBlurStyle,
sigma: f32,
respect_ctm: impl Into<Option<bool>>,
) -> Option<RCHandle<SkMaskFilter>>
pub fn blur( style: SkBlurStyle, sigma: f32, respect_ctm: impl Into<Option<bool>>, ) -> Option<RCHandle<SkMaskFilter>>
Create a blur mask filter.
style
TheBlurStyle
to usesigma
Standard deviation of the Gaussian blur to apply. Must be > 0.respect_ctm
iftrue
the blur’s sigma is modified by thectm
. Returns the new blur mask filter
pub fn approximate_filtered_bounds(&self, src: impl AsRef<Rect>) -> Rect
pub fn approximate_filtered_bounds(&self, src: impl AsRef<Rect>) -> Rect
Returns the approximate bounds that would result from filtering the src
rect. The actual
result may be different, but it should be contained within the returned bounds.
pub fn compose( _outer: RCHandle<SkMaskFilter>, _inner: RCHandle<SkMaskFilter>, ) -> !
pub fn combine( _filter_a: RCHandle<SkMaskFilter>, _filter_b: RCHandle<SkMaskFilter>, _mode: SkCoverageMode, ) -> !
pub fn with_matrix(&self, _matrix: &Matrix) -> !
§impl RCHandle<SkPathEffect>
impl RCHandle<SkPathEffect>
pub fn sum( first: impl Into<RCHandle<SkPathEffect>>, second: impl Into<RCHandle<SkPathEffect>>, ) -> RCHandle<SkPathEffect>
pub fn compose( first: impl Into<RCHandle<SkPathEffect>>, second: impl Into<RCHandle<SkPathEffect>>, ) -> RCHandle<SkPathEffect>
pub fn as_a_dash(&self) -> Option<DashInfo>
pub fn filter_path( &self, src: &Handle<SkPath>, stroke_rec: &Handle<SkStrokeRec>, cull_rect: impl AsRef<Rect>, ) -> Option<(Handle<SkPath>, Handle<SkStrokeRec>)>
pub fn filter_path_inplace( &self, dst: &mut Handle<SkPath>, src: &Handle<SkPath>, stroke_rec: &mut Handle<SkStrokeRec>, cull_rect: impl AsRef<Rect>, ) -> bool
pub fn filter_path_inplace_with_matrix( &self, dst: &mut Handle<SkPath>, src: &Handle<SkPath>, stroke_rec: &mut Handle<SkStrokeRec>, cull_rect: impl AsRef<Rect>, ctm: &Matrix, ) -> bool
pub fn needs_ctm(&self) -> bool
§impl RCHandle<SkPicture>
impl RCHandle<SkPicture>
pub fn from_data(data: &RCHandle<SkData>) -> Option<RCHandle<SkPicture>>
pub fn from_bytes(bytes: &[u8]) -> Option<RCHandle<SkPicture>>
pub fn playback(&self, canvas: &Canvas)
pub fn cull_rect(&self) -> Rect
pub fn unique_id(&self) -> u32
pub fn serialize(&self) -> RCHandle<SkData>
pub fn new_placeholder(cull: impl AsRef<Rect>) -> RCHandle<SkPicture>
pub fn approximate_op_count(&self) -> usize
pub fn approximate_op_count_nested( &self, nested: impl Into<Option<bool>>, ) -> usize
pub fn approximate_bytes_used(&self) -> usize
pub fn to_shader<'a, 'b>( &self, tm: impl Into<Option<(SkTileMode, SkTileMode)>>, mode: SkFilterMode, local_matrix: impl Into<Option<&'a Matrix>>, tile_rect: impl Into<Option<&'b Rect>>, ) -> RCHandle<SkShader>
§impl RCHandle<SkPixelRef>
impl RCHandle<SkPixelRef>
pub fn dimensions(&self) -> ISize
pub fn width(&self) -> i32
pub fn height(&self) -> i32
pub unsafe fn pixels(&self) -> *mut c_void
pub fn row_bytes(&self) -> usize
pub fn generation_id(&self) -> u32
pub fn notify_pixels_changed(&mut self)
pub fn is_immutable(&self) -> bool
pub fn set_immutable(&mut self)
pub fn notify_added_to_cache(&mut self)
§impl RCHandle<SkShader>
impl RCHandle<SkShader>
Shaders specify the source color(s) for what is being drawn. If a paint has no shader, then the paint’s color is used. If the paint has a shader, then the shader’s color(s) are use instead, but they are modulated by the paint’s alpha. This makes it easy to create a shader once (e.g. bitmap tiling or gradient) and then change its transparency w/o having to modify the original shader… only the paint’s alpha needs to be modified.
pub fn is_opaque(&self) -> bool
pub fn is_opaque(&self) -> bool
Returns true
if the shader is guaranteed to produce only opaque
colors, subject to the crate::Paint
using the shader to apply an opaque
alpha value. Subclasses should override this to allow some
optimizations.
pub fn image(
&self,
) -> Option<(RCHandle<SkImage>, Matrix, (SkTileMode, SkTileMode))>
pub fn image( &self, ) -> Option<(RCHandle<SkImage>, Matrix, (SkTileMode, SkTileMode))>
Returns iff this shader is backed by a single Image
.
If not, returns None
.
pub fn is_a_image(&self) -> bool
pub fn with_local_matrix(&self, matrix: &Matrix) -> RCHandle<SkShader>
pub fn with_local_matrix(&self, matrix: &Matrix) -> RCHandle<SkShader>
Return a shader that will apply the specified local_matrix
to this shader.
The specified matrix will be applied before any matrix associated with this shader.
pub fn with_color_filter(
&self,
color_filter: impl Into<RCHandle<SkColorFilter>>,
) -> RCHandle<SkShader>
pub fn with_color_filter( &self, color_filter: impl Into<RCHandle<SkColorFilter>>, ) -> RCHandle<SkShader>
Create a new shader that produces the same colors as invoking this shader and then applying the color filter.
pub fn with_working_color_space(
&self,
color_space: impl Into<RCHandle<SkColorSpace>>,
) -> RCHandle<SkShader>
pub fn with_working_color_space( &self, color_space: impl Into<RCHandle<SkColorSpace>>, ) -> RCHandle<SkShader>
Return a shader that will compute this shader in a specific color space. By default, all shaders operate in the destination (surface) color space. The results of a shader are still always converted to the destination - this API has no impact on simple shaders or images. Primarily, it impacts shaders that perform mathematical operations, like Blend shaders, or runtime shaders.
§impl RCHandle<SkSurface>
impl RCHandle<SkSurface>
pub fn new_raster_direct<'pixels>(
image_info: &Handle<SkImageInfo>,
pixels: &'pixels mut [u8],
row_bytes: impl Into<Option<usize>>,
surface_props: Option<&SurfaceProps>,
) -> Option<Borrows<'pixels, RCHandle<SkSurface>>>
👎Deprecated since 0.64.0: use surfaces::wrap_pixels()
pub fn new_raster_direct<'pixels>( image_info: &Handle<SkImageInfo>, pixels: &'pixels mut [u8], row_bytes: impl Into<Option<usize>>, surface_props: Option<&SurfaceProps>, ) -> Option<Borrows<'pixels, RCHandle<SkSurface>>>
Allocates raster Surface
. Canvas
returned by Surface
draws directly into pixels.
Surface
is returned if all parameters are valid.
Valid parameters include:
info dimensions are greater than zero;
info contains crate::ColorType
and crate::AlphaType
supported by raster surface;
pixels is not None
;
row_bytes
is large enough to contain info width pixels of crate::ColorType
.
Pixel buffer size should be info height times computed row_bytes
.
Pixels are not initialized.
To access pixels after drawing, Self::peek_pixels()
or Self::read_pixels()
.
image_info
- width, height,crate::ColorType
,crate::AlphaType
,crate::ColorSpace
, of raster surface; width and height must be greater than zeropixels
- pointer to destination pixels bufferrow_bytes
- interval from oneSurface
row to the nextsurface_props
- LCD striping orientation and setting for device independent fonts; may beNone
Returns:Surface
if all parameters are valid; otherwise,None
pub fn new_raster(
image_info: &Handle<SkImageInfo>,
row_bytes: impl Into<Option<usize>>,
surface_props: Option<&SurfaceProps>,
) -> Option<RCHandle<SkSurface>>
👎Deprecated since 0.64.0: use surfaces::raster()
pub fn new_raster( image_info: &Handle<SkImageInfo>, row_bytes: impl Into<Option<usize>>, surface_props: Option<&SurfaceProps>, ) -> Option<RCHandle<SkSurface>>
Allocates raster Surface
. Canvas
returned by Surface
draws directly into pixels.
Allocates and zeroes pixel memory. Pixel memory size is image_info.height()
times
row_bytes
, or times image_info.min_row_bytes()
if row_bytes
is zero.
Pixel memory is deleted when Surface
is deleted.
Surface
is returned if all parameters are valid.
Valid parameters include:
info dimensions are greater than zero;
info contains crate::ColorType
and crate::AlphaType
supported by raster surface;
row_bytes
is large enough to contain info width pixels of crate::ColorType
, or is zero.
If row_bytes
is zero, a suitable value will be chosen internally.
image_info
- width, height,crate::ColorType
,crate::AlphaType
,crate::ColorSpace
, of raster surface; width and height must be greater than zerorow_bytes
- interval from oneSurface
row to the next; may be zerosurface_props
- LCD striping orientation and setting for device independent fonts; may beNone
Returns:Surface
if all parameters are valid; otherwise,None
pub fn new_raster_n32_premul(
size: impl Into<ISize>,
) -> Option<RCHandle<SkSurface>>
👎Deprecated since 0.64.0: use surfaces::raster_n32_premul()
pub fn new_raster_n32_premul( size: impl Into<ISize>, ) -> Option<RCHandle<SkSurface>>
Allocates raster Surface
. Canvas
returned by Surface
draws directly into pixels.
Allocates and zeroes pixel memory. Pixel memory size is height times width times
four. Pixel memory is deleted when Surface
is deleted.
Internally, sets ImageInfo
to width, height, native color type, and
crate::AlphaType::Premul
.
Surface
is returned if width and height are greater than zero.
Use to create Surface
that matches crate::PMColor
, the native pixel arrangement on
the platform. Surface
drawn to output device skips converting its pixel format.
width
- pixel column count; must be greater than zeroheight
- pixel row count; must be greater than zerosurface_props
- LCD striping orientation and setting for device independent fonts; may beNone
Returns:Surface
if all parameters are valid; otherwise,None
§impl RCHandle<SkSurface>
impl RCHandle<SkSurface>
pub fn from_backend_texture(
context: &mut RCHandle<GrRecordingContext>,
backend_texture: &RefHandle<GrBackendTexture>,
origin: GrSurfaceOrigin,
sample_cnt: impl Into<Option<usize>>,
color_type: ColorType,
color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
surface_props: Option<&SurfaceProps>,
) -> Option<RCHandle<SkSurface>>
👎Deprecated since 0.64.0: use gpu::surfaces::wrap_backend_texture()
pub fn from_backend_texture( context: &mut RCHandle<GrRecordingContext>, backend_texture: &RefHandle<GrBackendTexture>, origin: GrSurfaceOrigin, sample_cnt: impl Into<Option<usize>>, color_type: ColorType, color_space: impl Into<Option<RCHandle<SkColorSpace>>>, surface_props: Option<&SurfaceProps>, ) -> Option<RCHandle<SkSurface>>
Wraps a GPU-backed texture into Surface
. Caller must ensure the texture is
valid for the lifetime of returned Surface
. If sample_cnt
greater than zero,
creates an intermediate MSAA Surface
which is used for drawing backend_texture
.
Surface
is returned if all parameters are valid. backend_texture
is valid if
its pixel configuration agrees with color_space
and context; for instance, if
backend_texture
has an sRGB configuration, then context must support sRGB,
and color_space
must be present. Further, backend_texture
width and height must
not exceed context capabilities, and the context must be able to support
back-end textures.
context
- GPU contextbackend_texture
- texture residing on GPUsample_cnt
- samples per pixel, or 0 to disable full scene anti-aliasingcolor_space
- range of colors; may beNone
surface_props
- LCD striping orientation and setting for device independent fonts; may beNone
Returns:Surface
if all parameters are valid; otherwise,None
pub fn from_backend_render_target(
context: &mut RCHandle<GrRecordingContext>,
backend_render_target: &Handle<GrBackendRenderTarget>,
origin: GrSurfaceOrigin,
color_type: ColorType,
color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
surface_props: Option<&SurfaceProps>,
) -> Option<RCHandle<SkSurface>>
👎Deprecated since 0.64.0: use gpu::surfaces::wrap_backend_render_target()
pub fn from_backend_render_target( context: &mut RCHandle<GrRecordingContext>, backend_render_target: &Handle<GrBackendRenderTarget>, origin: GrSurfaceOrigin, color_type: ColorType, color_space: impl Into<Option<RCHandle<SkColorSpace>>>, surface_props: Option<&SurfaceProps>, ) -> Option<RCHandle<SkSurface>>
Wraps a GPU-backed buffer into Surface
. Caller must ensure backend_render_target
is valid for the lifetime of returned Surface
.
Surface
is returned if all parameters are valid. backend_render_target
is valid if
its pixel configuration agrees with color_space
and context; for instance, if
backend_render_target
has an sRGB configuration, then context must support sRGB,
and color_space
must be present. Further, backend_render_target
width and height must
not exceed context capabilities, and the context must be able to support
back-end render targets.
context
- GPU contextbackend_render_target
- GPU intermediate memory buffercolor_space
- range of colorssurface_props
- LCD striping orientation and setting for device independent fonts; may beNone
Returns:Surface
if all parameters are valid; otherwise,None
pub fn new_render_target(
context: &mut RCHandle<GrRecordingContext>,
budgeted: Budgeted,
image_info: &Handle<SkImageInfo>,
sample_count: impl Into<Option<usize>>,
surface_origin: impl Into<Option<GrSurfaceOrigin>>,
surface_props: Option<&SurfaceProps>,
should_create_with_mips: impl Into<Option<bool>>,
) -> Option<RCHandle<SkSurface>>
👎Deprecated since 0.64.0: use gpu::surfaces::render_target()
pub fn new_render_target( context: &mut RCHandle<GrRecordingContext>, budgeted: Budgeted, image_info: &Handle<SkImageInfo>, sample_count: impl Into<Option<usize>>, surface_origin: impl Into<Option<GrSurfaceOrigin>>, surface_props: Option<&SurfaceProps>, should_create_with_mips: impl Into<Option<bool>>, ) -> Option<RCHandle<SkSurface>>
Returns Surface
on GPU indicated by context. Allocates memory for
pixels, based on the width, height, and crate::ColorType
in ImageInfo
. budgeted
selects whether allocation for pixels is tracked by context. image_info
describes the pixel format in crate::ColorType
, and transparency in
crate::AlphaType
, and color matching in crate::ColorSpace
.
sample_count
requests the number of samples per pixel.
Pass zero to disable multi-sample anti-aliasing. The request is rounded
up to the next supported count, or rounded down if it is larger than the
maximum supported count.
surface_origin
pins either the top-left or the bottom-left corner to the origin.
should_create_with_mips
hints that Image
returned by Image::image_snapshot
is mip map.
context
- GPU contextimage_info
- width, height,crate::ColorType
,crate::AlphaType
,crate::ColorSpace
; width, or height, or both, may be zerosample_count
- samples per pixel, or 0 to disable full scene anti-aliasingsurface_props
- LCD striping orientation and setting for device independent fonts; may beNone
should_create_with_mips
- hint thatSurface
will host mip map images Returns:Surface
if all parameters are valid; otherwise,None
§impl RCHandle<SkSurface>
impl RCHandle<SkSurface>
pub fn new_null(size: impl Into<ISize>) -> Option<RCHandle<SkSurface>>
👎Deprecated since 0.64.0: use surfaces::null()
pub fn new_null(size: impl Into<ISize>) -> Option<RCHandle<SkSurface>>
pub fn width(&self) -> i32
pub fn width(&self) -> i32
Returns pixel count in each row; may be zero or greater.
Returns: number of pixel columns
pub fn height(&self) -> i32
pub fn height(&self) -> i32
Returns pixel row count; may be zero or greater.
Returns: number of pixel rows
pub fn image_info(&mut self) -> Handle<SkImageInfo>
pub fn image_info(&mut self) -> Handle<SkImageInfo>
Returns an ImageInfo
describing the surface.
pub fn generation_id(&mut self) -> u32
pub fn generation_id(&mut self) -> u32
Returns unique value identifying the content of Surface
. Returned value changes
each time the content changes. Content is changed by drawing, or by calling
Self::notify_content_will_change()
.
Returns: unique content identifier
example: https://fiddle.skia.org/c/@Surface_notifyContentWillChange
pub fn notify_content_will_change(
&mut self,
mode: SkSurface_ContentChangeMode,
) -> &mut RCHandle<SkSurface>
pub fn notify_content_will_change( &mut self, mode: SkSurface_ContentChangeMode, ) -> &mut RCHandle<SkSurface>
Notifies that Surface
contents will be changed by code outside of Skia.
Subsequent calls to Self::generation_id()
return a different value.
example: https://fiddle.skia.org/c/@Surface_notifyContentWillChange
§impl RCHandle<SkSurface>
impl RCHandle<SkSurface>
pub fn recording_context(&self) -> Option<RCHandle<GrRecordingContext>>
pub fn recording_context(&self) -> Option<RCHandle<GrRecordingContext>>
Returns the recording context being used by the Surface
.
Returns: the recording context, if available; None
otherwise
pub fn direct_context(&self) -> Option<RCHandle<GrDirectContext>>
pub fn direct_context(&self) -> Option<RCHandle<GrDirectContext>>
rust-skia helper, not in Skia
pub fn get_backend_texture(
&mut self,
handle_access: SkSurface_BackendHandleAccess,
) -> Option<RefHandle<GrBackendTexture>>
👎Deprecated since 0.64.0: use gpu::surfaces::get_backend_texture()
pub fn get_backend_texture( &mut self, handle_access: SkSurface_BackendHandleAccess, ) -> Option<RefHandle<GrBackendTexture>>
Retrieves the back-end texture. If Surface
has no back-end texture, None
is returned.
The returned gpu::BackendTexture
should be discarded if the Surface
is drawn to or deleted.
Returns: GPU texture reference; None
on failure
pub fn get_backend_render_target(
&mut self,
handle_access: SkSurface_BackendHandleAccess,
) -> Option<Handle<GrBackendRenderTarget>>
👎Deprecated since 0.64.0: use gpu::surfaces::get_backend_render_target()
pub fn get_backend_render_target( &mut self, handle_access: SkSurface_BackendHandleAccess, ) -> Option<Handle<GrBackendRenderTarget>>
Retrieves the back-end render target. If Surface
has no back-end render target, None
is returned.
The returned gpu::BackendRenderTarget
should be discarded if the Surface
is drawn to
or deleted.
Returns: GPU render target reference; None
on failure
pub fn replace_backend_texture(
&mut self,
backend_texture: &RefHandle<GrBackendTexture>,
origin: GrSurfaceOrigin,
) -> bool
pub fn replace_backend_texture( &mut self, backend_texture: &RefHandle<GrBackendTexture>, origin: GrSurfaceOrigin, ) -> bool
If the surface was made via Self::from_backend_texture
then it’s backing texture may be
substituted with a different texture. The contents of the previous backing texture are
copied into the new texture. Canvas
state is preserved. The original sample count is
used. The gpu::BackendFormat
and dimensions of replacement texture must match that of
the original.
backend_texture
- the new backing texture for the surface
pub fn replace_backend_texture_with_mode(
&mut self,
backend_texture: &RefHandle<GrBackendTexture>,
origin: GrSurfaceOrigin,
mode: impl Into<Option<SkSurface_ContentChangeMode>>,
) -> bool
pub fn replace_backend_texture_with_mode( &mut self, backend_texture: &RefHandle<GrBackendTexture>, origin: GrSurfaceOrigin, mode: impl Into<Option<SkSurface_ContentChangeMode>>, ) -> bool
If the surface was made via Self::from_backend_texture()
then it’s backing texture may be
substituted with a different texture. The contents of the previous backing texture are
copied into the new texture. Canvas
state is preserved. The original sample count is
used. The gpu::BackendFormat
and dimensions of replacement texture must match that of
the original.
backend_texture
- the new backing texture for the surfacemode
- Retain or discard current Content
§impl RCHandle<SkSurface>
impl RCHandle<SkSurface>
pub fn new_surface(
&mut self,
image_info: &Handle<SkImageInfo>,
) -> Option<RCHandle<SkSurface>>
pub fn new_surface( &mut self, image_info: &Handle<SkImageInfo>, ) -> Option<RCHandle<SkSurface>>
Returns a compatible Surface
, or None
. Returned Surface
contains
the same raster, GPU, or null properties as the original. Returned Surface
does not share the same pixels.
Returns None
if image_info
width or height are zero, or if image_info
is incompatible with Surface
.
image_info
- width, height,crate::ColorType
,crate::AlphaType
,crate::ColorSpace
, ofSurface
; width and height must be greater than zero Returns: compatibleSurface
orNone
pub fn new_surface_with_dimensions(
&mut self,
dim: impl Into<ISize>,
) -> Option<RCHandle<SkSurface>>
pub fn new_surface_with_dimensions( &mut self, dim: impl Into<ISize>, ) -> Option<RCHandle<SkSurface>>
Calls Self::new_surface()
with the same ImageInfo
as this surface, but with the
specified width and height.
pub fn image_snapshot(&mut self) -> RCHandle<SkImage>
pub fn image_snapshot(&mut self) -> RCHandle<SkImage>
Returns Image
capturing Surface
contents. Subsequent drawing to Surface
contents
are not captured. Image
allocation is accounted for if Surface
was created with
gpu::Budgeted::Yes
.
Returns: Image
initialized with Surface
contents
example: https://fiddle.skia.org/c/@Surface_makeImageSnapshot
pub fn image_snapshot_with_bounds(
&mut self,
bounds: impl AsRef<IRect>,
) -> Option<RCHandle<SkImage>>
pub fn image_snapshot_with_bounds( &mut self, bounds: impl AsRef<IRect>, ) -> Option<RCHandle<SkImage>>
Like the no-parameter version, this returns an image of the current surface contents. This variant takes a rectangle specifying the subset of the surface that is of interest. These bounds will be sanitized before being used.
- If bounds extends beyond the surface, it will be trimmed to just the intersection of it and the surface.
- If bounds does not intersect the surface, then this returns
None
. - If bounds == the surface, then this is the same as calling the no-parameter variant.
example: https://fiddle.skia.org/c/@Surface_makeImageSnapshot_2
pub fn draw(
&mut self,
canvas: &Canvas,
offset: impl Into<Point>,
sampling: impl Into<SamplingOptions>,
paint: Option<&Handle<SkPaint>>,
)
pub fn draw( &mut self, canvas: &Canvas, offset: impl Into<Point>, sampling: impl Into<SamplingOptions>, paint: Option<&Handle<SkPaint>>, )
Draws Surface
contents to canvas, with its top-left corner at (offset.x, offset.y)
.
If Paint
paint is not None
, apply crate::ColorFilter
, alpha, crate::ImageFilter
, and crate::BlendMode
.
canvas
-Canvas
drawn intooffset.x
- horizontal offset inCanvas
offset.y
- vertical offset inCanvas
sampling
- what technique to use when sampling the surface pixelspaint
-Paint
containingcrate::BlendMode
,crate::ColorFilter
,crate::ImageFilter
, and so on; orNone
pub fn peek_pixels(&mut self) -> Option<Pixmap<'_>>
pub fn read_pixels_to_pixmap(
&mut self,
dst: &Pixmap<'_>,
src: impl Into<IPoint>,
) -> bool
pub fn read_pixels_to_pixmap( &mut self, dst: &Pixmap<'_>, src: impl Into<IPoint>, ) -> bool
Copies crate::Rect
of pixels to dst.
Source crate::Rect
corners are (src.x
, src.y
) and Surface
(width(), height())
.
Destination crate::Rect
corners are (0, 0)
and (dst.width(), dst.height())
.
Copies each readable pixel intersecting both rectangles, without scaling,
converting to dst_color_type()
and dst_alpha_type()
if required.
Pixels are readable when Surface
is raster, or backed by a GPU.
The destination pixel storage must be allocated by the caller.
Pixel values are converted only if crate::ColorType
and crate::AlphaType
do not match. Only pixels within both source and destination rectangles
are copied. dst contents outside crate::Rect
intersection are unchanged.
Pass negative values for src.x
or src.y
to offset pixels across or down destination.
Does not copy, and returns false
if:
- Source and destination rectangles do not intersect.
Pixmap
pixels could not be allocated.dst.row_bytes()
is too small to contain one row of pixels.
dst
- storage for pixels copied fromSurface
src_x
- offset into readable pixels on x-axis; may be negativesrc_y
- offset into readable pixels on y-axis; may be negative Returns:true
if pixels were copied
pub fn read_pixels(
&mut self,
dst_info: &Handle<SkImageInfo>,
dst_pixels: &mut [u8],
dst_row_bytes: usize,
src: impl Into<IPoint>,
) -> bool
pub fn read_pixels( &mut self, dst_info: &Handle<SkImageInfo>, dst_pixels: &mut [u8], dst_row_bytes: usize, src: impl Into<IPoint>, ) -> bool
Copies crate::Rect
of pixels from Canvas
into dst_pixels
.
Source crate::Rect
corners are (src.x
, src.y
) and Surface
(width(), height()).
Destination crate::Rect
corners are (0, 0) and (dst_info
.width(), dst_info
.height()).
Copies each readable pixel intersecting both rectangles, without scaling,
converting to dst_info_color_type()
and dst_info_alpha_type()
if required.
Pixels are readable when Surface
is raster, or backed by a GPU.
The destination pixel storage must be allocated by the caller.
Pixel values are converted only if crate::ColorType
and crate::AlphaType
do not match. Only pixels within both source and destination rectangles
are copied. dst_pixels
contents outside crate::Rect
intersection are unchanged.
Pass negative values for src.x
or src.y
to offset pixels across or down destination.
Does not copy, and returns false
if:
- Source and destination rectangles do not intersect.
Surface
pixels could not be converted todst_info.color_type()
ordst_info.alpha_type()
.dst_row_bytes
is too small to contain one row of pixels.
dst_info
- width, height,crate::ColorType
, andcrate::AlphaType
ofdst_pixels
dst_pixels
- storage for pixels;dst_info.height()
timesdst_row_bytes
, or largerdst_row_bytes
- size of one destination row;dst_info.width()
times pixel size, or largersrc.x
- offset into readable pixels on x-axis; may be negativesrc.y
- offset into readable pixels on y-axis; may be negative Returns:true
if pixels were copied
pub fn read_pixels_to_bitmap(
&mut self,
bitmap: &Handle<SkBitmap>,
src: impl Into<IPoint>,
) -> bool
pub fn read_pixels_to_bitmap( &mut self, bitmap: &Handle<SkBitmap>, src: impl Into<IPoint>, ) -> bool
Copies crate::Rect
of pixels from Surface
into bitmap.
Source crate::Rect
corners are (src.x
, src.y
) and Surface
(width(), height()).
Destination crate::Rect
corners are (0, 0)
and (bitmap.width(), bitmap.height())
.
Copies each readable pixel intersecting both rectangles, without scaling,
converting to bitmap.color_type()
and bitmap.alpha_type()
if required.
Pixels are readable when Surface
is raster, or backed by a GPU.
The destination pixel storage must be allocated by the caller.
Pixel values are converted only if crate::ColorType
and crate::AlphaType
do not match. Only pixels within both source and destination rectangles
are copied. dst contents outside crate::Rect
intersection are unchanged.
Pass negative values for src.x
or src.y
to offset pixels across or down destination.
Does not copy, and returns false
if:
- Source and destination rectangles do not intersect.
Surface
pixels could not be converted todst.color_type()
ordst.alpha_type()
.- dst pixels could not be allocated.
dst.row_bytes()
is too small to contain one row of pixels.
dst
- storage for pixels copied fromSurface
src.x
- offset into readable pixels on x-axis; may be negativesrc.y
- offset into readable pixels on y-axis; may be negative Returns:true
if pixels were copied
pub fn write_pixels_from_pixmap(
&mut self,
src: &Pixmap<'_>,
dst: impl Into<IPoint>,
)
pub fn write_pixels_from_pixmap( &mut self, src: &Pixmap<'_>, dst: impl Into<IPoint>, )
Copies crate::Rect
of pixels from the src Pixmap
to the Surface
.
Source crate::Rect
corners are (0, 0)
and (src.width(), src.height())
.
Destination crate::Rect
corners are (
dst.x,
dst.y)
and
(dst.x
+ Surface width(), dst.y
+ Surface height()).
Copies each readable pixel intersecting both rectangles, without scaling,
converting to Surface
color_type()
and Surface
alpha_type()
if required.
pub fn write_pixels_from_bitmap(
&mut self,
bitmap: &Handle<SkBitmap>,
dst: impl Into<IPoint>,
)
pub fn write_pixels_from_bitmap( &mut self, bitmap: &Handle<SkBitmap>, dst: impl Into<IPoint>, )
Copies crate::Rect
of pixels from the src Bitmap
to the Surface
.
Source crate::Rect
corners are (0, 0)
and (src.width(), src.height())
.
Destination crate::Rect
corners are (
dst.x,
dst.y)
and
(
dst.x+ Surface width(),
dst.y + Surface height())
.
Copies each readable pixel intersecting both rectangles, without scaling,
converting to Surface
color_type()
and Surface
alpha_type()
if required.
pub fn props(&self) -> &SurfaceProps
pub fn props(&self) -> &SurfaceProps
Returns SurfaceProps
for surface.
Returns: LCD striping orientation and setting for device independent fonts
§impl RCHandle<SkSurface>
impl RCHandle<SkSurface>
pub fn resolve_msaa(&mut self)
👎Deprecated since 0.65.0: Use gpu::surfaces::resolve_msaa
pub fn resolve_msaa(&mut self)
If a surface is GPU texture backed, is being drawn with MSAA, and there is a resolve
texture, this call will insert a resolve command into the stream of gpu commands. In order
for the resolve to actually have an effect, the work still needs to be flushed and submitted
to the GPU after recording the resolve command. If a resolve is not supported or the
Surface
has no dirty work to resolve, then this call is a no-op.
This call is most useful when the Surface
is created by wrapping a single sampled gpu
texture, but asking Skia to render with MSAA. If the client wants to use the wrapped texture
outside of Skia, the only way to trigger a resolve is either to call this command or use
Self::flush()
.
§impl RCHandle<SkTextBlob>
impl RCHandle<SkTextBlob>
pub fn new( str: impl AsRef<str>, font: &Handle<SkFont>, ) -> Option<RCHandle<SkTextBlob>>
pub fn bounds(&self) -> &Rect
pub fn unique_id(&self) -> u32
pub fn get_intercepts( &self, bounds: [f32; 2], paint: Option<&Handle<SkPaint>>, ) -> Vec<f32>
pub fn from_str( str: impl AsRef<str>, font: &Handle<SkFont>, ) -> Option<RCHandle<SkTextBlob>>
pub fn from_text( text: impl EncodedText, font: &Handle<SkFont>, ) -> Option<RCHandle<SkTextBlob>>
pub fn from_pos_text_h( text: impl EncodedText, x_pos: &[f32], const_y: f32, font: &Handle<SkFont>, ) -> Option<RCHandle<SkTextBlob>>
pub fn from_pos_text( text: impl EncodedText, pos: &[Point], font: &Handle<SkFont>, ) -> Option<RCHandle<SkTextBlob>>
pub fn from_rsxform( text: impl EncodedText, xform: &[RSXform], font: &Handle<SkFont>, ) -> Option<RCHandle<SkTextBlob>>
§impl RCHandle<SkTypeface>
impl RCHandle<SkTypeface>
pub fn font_style(&self) -> FontStyle
pub fn is_bold(&self) -> bool
pub fn is_italic(&self) -> bool
pub fn is_fixed_pitch(&self) -> bool
pub fn variation_design_position(&self) -> Option<Vec<Coordinate>>
pub fn variation_design_parameters(&self) -> Option<Vec<Axis>>
pub fn unique_id(&self) -> u32
pub fn equal( face_a: impl AsRef<RCHandle<SkTypeface>>, face_b: impl AsRef<RCHandle<SkTypeface>>, ) -> bool
pub fn clone_with_arguments( &self, arguments: &FontArguments<'_, '_>, ) -> Option<RCHandle<SkTypeface>>
pub fn serialize_stream( &self, write: impl Write, behavior: SkTypeface_SerializeBehavior, )
pub fn serialize( &self, behavior: SkTypeface_SerializeBehavior, ) -> RCHandle<SkData>
pub fn make_deserialize( data: impl Read, last_resort_mgr: impl Into<Option<RCHandle<SkFontMgr>>>, ) -> Option<RCHandle<SkTypeface>>
pub fn unichars_to_glyphs(&self, uni: &[i32], glyphs: &mut [u16])
pub fn str_to_glyphs(&self, str: impl AsRef<str>, glyphs: &mut [u16]) -> usize
pub fn text_to_glyphs( &self, text: impl EncodedText, glyphs: &mut [u16], ) -> usize
pub fn unichar_to_glyph(&self, unichar: i32) -> u16
pub fn count_glyphs(&self) -> usize
pub fn count_tables(&self) -> usize
pub fn get_table_size(&self, tag: u32) -> Option<usize>
pub fn get_table_data(&self, tag: u32, data: &mut [u8]) -> usize
pub fn copy_table_data(&self, tag: u32) -> Option<RCHandle<SkData>>
pub fn units_per_em(&self) -> Option<i32>
pub fn get_kerning_pair_adjustments( &self, glyphs: &[u16], adjustments: &mut [i32], ) -> bool
pub fn new_family_name_iterator(&self) -> impl Iterator<Item = LocalizedString>
pub fn family_name(&self) -> String
pub fn post_script_name(&self) -> Option<String>
pub fn to_font_data(&self) -> Option<(Vec<u8>, usize)>
pub fn bounds(&self) -> Rect
§impl RCHandle<SkVertices>
impl RCHandle<SkVertices>
pub fn new_copy( mode: SkVertices_VertexMode, positions: &[Point], texs: &[Point], colors: &[Color], indices: Option<&[u16]>, ) -> RCHandle<SkVertices>
pub const MAX_CUSTOM_ATTRIBUTES: usize = 8usize
pub fn unique_id(&self) -> u32
pub fn mode(&self) -> SkVertices_VertexMode
pub fn bounds(&self) -> &Rect
pub fn has_colors(&self) -> bool
pub fn has_tex_coords(&self) -> bool
pub fn has_bones(&self) -> bool
pub fn has_indices(&self) -> bool
pub fn vertex_count(&self) -> usize
pub fn index_count(&self) -> usize
pub fn positions(&self) -> &[Point]
pub fn tex_coords(&self) -> Option<&[Point]>
pub fn colors(&self) -> Option<&[Color]>
pub fn bone_indices(&self) -> Option<&[[u32; 4]]>
pub fn bone_weights(&self) -> Option<&[[u32; 4]]>
pub fn indices(&self) -> Option<&[u16]>
pub fn is_volatile(&self) -> bool
pub fn apply_bones(&self, _bones: &[Bone]) -> !
pub fn approximate_size(&self) -> usize
pub fn decode(_buffer: &[u8]) -> !
pub fn encode(&self) -> !
§impl RCHandle<SkShader>
impl RCHandle<SkShader>
pub fn fractal_perlin_noise( base_frequency: (f32, f32), num_octaves: usize, seed: f32, tile_size: impl Into<Option<ISize>>, ) -> Option<RCHandle<SkShader>>
pub fn turbulence_perlin_noise( base_frequency: (f32, f32), num_octaves: usize, seed: f32, tile_size: impl Into<Option<ISize>>, ) -> Option<RCHandle<SkShader>>
§impl RCHandle<SkShader>
impl RCHandle<SkShader>
pub fn linear_gradient<'a>( points: (impl Into<Point>, impl Into<Point>), colors: impl Into<GradientShaderColors<'a>>, pos: impl Into<Option<&'a [f32]>>, mode: SkTileMode, flags: impl Into<Option<Flags>>, local_matrix: impl Into<Option<&'a Matrix>>, ) -> Option<RCHandle<SkShader>>
pub fn linear_gradient_with_interpolation<'a>( points: (impl Into<Point>, impl Into<Point>), colors: (&[Color4f], impl Into<Option<RCHandle<SkColorSpace>>>), pos: impl Into<Option<&'a [f32]>>, mode: SkTileMode, interpolation: impl Into<Interpolation>, local_matrix: impl Into<Option<&'a Matrix>>, ) -> Option<RCHandle<SkShader>>
pub fn radial_gradient<'a>( center: impl Into<Point>, radius: f32, colors: impl Into<GradientShaderColors<'a>>, pos: impl Into<Option<&'a [f32]>>, mode: SkTileMode, flags: impl Into<Option<Flags>>, local_matrix: impl Into<Option<&'a Matrix>>, ) -> Option<RCHandle<SkShader>>
pub fn radial_gradient_with_interpolation<'a>( center_and_radius: (impl Into<Point>, f32), colors: (&[Color4f], impl Into<Option<RCHandle<SkColorSpace>>>), pos: impl Into<Option<&'a [f32]>>, mode: SkTileMode, interpolation: impl Into<Interpolation>, local_matrix: impl Into<Option<&'a Matrix>>, ) -> Option<RCHandle<SkShader>>
pub fn two_point_conical_gradient<'a>( start: impl Into<Point>, start_radius: f32, end: impl Into<Point>, end_radius: f32, colors: impl Into<GradientShaderColors<'a>>, pos: impl Into<Option<&'a [f32]>>, mode: SkTileMode, flags: impl Into<Option<Flags>>, local_matrix: impl Into<Option<&'a Matrix>>, ) -> Option<RCHandle<SkShader>>
pub fn two_point_conical_gradient_with_interpolation<'a>( start_and_radius: (impl Into<Point>, f32), end_and_radius: (impl Into<Point>, f32), colors: (&[Color4f], impl Into<Option<RCHandle<SkColorSpace>>>), pos: impl Into<Option<&'a [f32]>>, mode: SkTileMode, interpolation: impl Into<Interpolation>, local_matrix: impl Into<Option<&'a Matrix>>, ) -> Option<RCHandle<SkShader>>
pub fn sweep_gradient<'a>( center: impl Into<Point>, colors: impl Into<GradientShaderColors<'a>>, pos: impl Into<Option<&'a [f32]>>, mode: SkTileMode, angles: impl Into<Option<(f32, f32)>>, flags: impl Into<Option<Flags>>, local_matrix: impl Into<Option<&'a Matrix>>, ) -> Option<RCHandle<SkShader>>
pub fn sweep_gradient_with_interpolation<'a>( center: impl Into<Point>, colors: (&[Color4f], impl Into<Option<RCHandle<SkColorSpace>>>), pos: impl Into<Option<&'a [f32]>>, mode: SkTileMode, angles: impl Into<Option<(f32, f32)>>, interpolation: impl Into<Interpolation>, local_matrix: impl Into<Option<&'a Matrix>>, ) -> Option<RCHandle<SkShader>>
§impl RCHandle<SkColorFilter>
impl RCHandle<SkColorFilter>
pub fn high_contrast( config: &HighContrastConfig, ) -> Option<RCHandle<SkColorFilter>>
§impl RCHandle<SkImageFilter>
impl RCHandle<SkImageFilter>
pub fn arithmetic<'a>(
inputs: impl Into<ArithmeticFPInputs>,
background: impl Into<Option<RCHandle<SkImageFilter>>>,
foreground: impl Into<Option<RCHandle<SkImageFilter>>>,
crop_rect: impl Into<Option<&'a IRect>>,
) -> Option<RCHandle<SkImageFilter>>
pub fn arithmetic<'a>( inputs: impl Into<ArithmeticFPInputs>, background: impl Into<Option<RCHandle<SkImageFilter>>>, foreground: impl Into<Option<RCHandle<SkImageFilter>>>, crop_rect: impl Into<Option<&'a IRect>>, ) -> Option<RCHandle<SkImageFilter>>
pub fn blur<'a>(
self,
crop_rect: impl Into<Option<&'a IRect>>,
sigma: (f32, f32),
tile_mode: impl Into<Option<SkTileMode>>,
) -> Option<RCHandle<SkImageFilter>>
pub fn blur<'a>( self, crop_rect: impl Into<Option<&'a IRect>>, sigma: (f32, f32), tile_mode: impl Into<Option<SkTileMode>>, ) -> Option<RCHandle<SkImageFilter>>
pub fn color_filter<'a>(
self,
crop_rect: impl Into<Option<&'a IRect>>,
cf: impl Into<RCHandle<SkColorFilter>>,
) -> Option<RCHandle<SkImageFilter>>
pub fn color_filter<'a>( self, crop_rect: impl Into<Option<&'a IRect>>, cf: impl Into<RCHandle<SkColorFilter>>, ) -> Option<RCHandle<SkImageFilter>>
pub fn compose(
outer: impl Into<RCHandle<SkImageFilter>>,
inner: impl Into<RCHandle<SkImageFilter>>,
) -> Option<RCHandle<SkImageFilter>>
pub fn compose( outer: impl Into<RCHandle<SkImageFilter>>, inner: impl Into<RCHandle<SkImageFilter>>, ) -> Option<RCHandle<SkImageFilter>>
pub fn crop(
rect: impl AsRef<Rect>,
tile_mode: impl Into<Option<SkTileMode>>,
input: impl Into<Option<RCHandle<SkImageFilter>>>,
) -> Option<RCHandle<SkImageFilter>>
pub fn crop( rect: impl AsRef<Rect>, tile_mode: impl Into<Option<SkTileMode>>, input: impl Into<Option<RCHandle<SkImageFilter>>>, ) -> Option<RCHandle<SkImageFilter>>
pub fn displacement_map_effect<'a>(
channel_selectors: (SkColorChannel, SkColorChannel),
scale: f32,
displacement: impl Into<Option<RCHandle<SkImageFilter>>>,
color: impl Into<Option<RCHandle<SkImageFilter>>>,
crop_rect: impl Into<Option<&'a IRect>>,
) -> Option<RCHandle<SkImageFilter>>
pub fn displacement_map_effect<'a>( channel_selectors: (SkColorChannel, SkColorChannel), scale: f32, displacement: impl Into<Option<RCHandle<SkImageFilter>>>, color: impl Into<Option<RCHandle<SkImageFilter>>>, crop_rect: impl Into<Option<&'a IRect>>, ) -> Option<RCHandle<SkImageFilter>>
pub fn distant_lit_diffuse_lighting<'a>(
self,
crop_rect: impl Into<Option<&'a IRect>>,
direction: impl Into<Point3>,
light_color: impl Into<Color>,
surface_scale: f32,
kd: f32,
) -> Option<RCHandle<SkImageFilter>>
pub fn distant_lit_diffuse_lighting<'a>( self, crop_rect: impl Into<Option<&'a IRect>>, direction: impl Into<Point3>, light_color: impl Into<Color>, surface_scale: f32, kd: f32, ) -> Option<RCHandle<SkImageFilter>>
pub fn point_lit_diffuse_lighting<'a>(
self,
crop_rect: impl Into<Option<&'a IRect>>,
location: impl Into<Point3>,
light_color: impl Into<Color>,
surface_scale: f32,
kd: f32,
) -> Option<RCHandle<SkImageFilter>>
pub fn point_lit_diffuse_lighting<'a>( self, crop_rect: impl Into<Option<&'a IRect>>, location: impl Into<Point3>, light_color: impl Into<Color>, surface_scale: f32, kd: f32, ) -> Option<RCHandle<SkImageFilter>>
pub fn spot_lit_diffuse_lighting<'a>(
self,
crop_rect: impl Into<Option<&'a IRect>>,
location: impl Into<Point3>,
target: impl Into<Point3>,
specular_exponent: f32,
cutoff_angle: f32,
light_color: impl Into<Color>,
surface_scale: f32,
kd: f32,
) -> Option<RCHandle<SkImageFilter>>
pub fn spot_lit_diffuse_lighting<'a>( self, crop_rect: impl Into<Option<&'a IRect>>, location: impl Into<Point3>, target: impl Into<Point3>, specular_exponent: f32, cutoff_angle: f32, light_color: impl Into<Color>, surface_scale: f32, kd: f32, ) -> Option<RCHandle<SkImageFilter>>
pub fn distant_lit_specular_lighting<'a>(
self,
crop_rect: impl Into<Option<&'a IRect>>,
direction: impl Into<Point3>,
light_color: impl Into<Color>,
surface_scale: f32,
ks: f32,
shininess: f32,
) -> Option<RCHandle<SkImageFilter>>
pub fn distant_lit_specular_lighting<'a>( self, crop_rect: impl Into<Option<&'a IRect>>, direction: impl Into<Point3>, light_color: impl Into<Color>, surface_scale: f32, ks: f32, shininess: f32, ) -> Option<RCHandle<SkImageFilter>>
pub fn point_lit_specular_lighting<'a>(
self,
crop_rect: impl Into<Option<&'a IRect>>,
location: impl Into<Point3>,
light_color: impl Into<Color>,
surface_scale: f32,
ks: f32,
shininess: f32,
) -> Option<RCHandle<SkImageFilter>>
pub fn point_lit_specular_lighting<'a>( self, crop_rect: impl Into<Option<&'a IRect>>, location: impl Into<Point3>, light_color: impl Into<Color>, surface_scale: f32, ks: f32, shininess: f32, ) -> Option<RCHandle<SkImageFilter>>
pub fn spot_lit_specular_lighting<'a>(
self,
crop_rect: impl Into<Option<&'a IRect>>,
location: impl Into<Point3>,
target: impl Into<Point3>,
specular_exponent: f32,
cutoff_angle: f32,
light_color: impl Into<Color>,
surface_scale: f32,
ks: f32,
shininess: f32,
) -> Option<RCHandle<SkImageFilter>>
pub fn spot_lit_specular_lighting<'a>( self, crop_rect: impl Into<Option<&'a IRect>>, location: impl Into<Point3>, target: impl Into<Point3>, specular_exponent: f32, cutoff_angle: f32, light_color: impl Into<Color>, surface_scale: f32, ks: f32, shininess: f32, ) -> Option<RCHandle<SkImageFilter>>
pub fn magnifier<'a>(
self,
lens_bounds: impl AsRef<Rect>,
zoom_amount: f32,
inset: f32,
sampling_options: SamplingOptions,
crop_rect: impl Into<Option<&'a IRect>>,
) -> Option<RCHandle<SkImageFilter>>
pub fn magnifier<'a>( self, lens_bounds: impl AsRef<Rect>, zoom_amount: f32, inset: f32, sampling_options: SamplingOptions, crop_rect: impl Into<Option<&'a IRect>>, ) -> Option<RCHandle<SkImageFilter>>
pub fn matrix_convolution<'a>(
self,
crop_rect: impl Into<Option<&'a IRect>>,
kernel_size: impl Into<ISize>,
kernel: &[f32],
gain: f32,
bias: f32,
kernel_offset: impl Into<IPoint>,
tile_mode: SkTileMode,
convolve_alpha: bool,
) -> Option<RCHandle<SkImageFilter>>
pub fn matrix_convolution<'a>( self, crop_rect: impl Into<Option<&'a IRect>>, kernel_size: impl Into<ISize>, kernel: &[f32], gain: f32, bias: f32, kernel_offset: impl Into<IPoint>, tile_mode: SkTileMode, convolve_alpha: bool, ) -> Option<RCHandle<SkImageFilter>>
pub fn merge<'a>(
filters: impl IntoIterator<Item = Option<RCHandle<SkImageFilter>>>,
crop_rect: impl Into<Option<&'a IRect>>,
) -> Option<RCHandle<SkImageFilter>>
pub fn merge<'a>( filters: impl IntoIterator<Item = Option<RCHandle<SkImageFilter>>>, crop_rect: impl Into<Option<&'a IRect>>, ) -> Option<RCHandle<SkImageFilter>>
pub fn dilate<'a>(
self,
crop_rect: impl Into<Option<&'a IRect>>,
radii: (f32, f32),
) -> Option<RCHandle<SkImageFilter>>
pub fn dilate<'a>( self, crop_rect: impl Into<Option<&'a IRect>>, radii: (f32, f32), ) -> Option<RCHandle<SkImageFilter>>
pub fn erode<'a>(
self,
crop_rect: impl Into<Option<&'a IRect>>,
radii: (f32, f32),
) -> Option<RCHandle<SkImageFilter>>
pub fn erode<'a>( self, crop_rect: impl Into<Option<&'a IRect>>, radii: (f32, f32), ) -> Option<RCHandle<SkImageFilter>>
pub fn offset<'a>(
self,
crop_rect: impl Into<Option<&'a IRect>>,
delta: impl Into<Point>,
) -> Option<RCHandle<SkImageFilter>>
pub fn offset<'a>( self, crop_rect: impl Into<Option<&'a IRect>>, delta: impl Into<Point>, ) -> Option<RCHandle<SkImageFilter>>
§impl RCHandle<SkRuntimeEffect>
impl RCHandle<SkRuntimeEffect>
pub fn make_for_color_filer<'a>( sksl: impl AsRef<str>, options: impl Into<Option<&'a Options>>, ) -> Result<RCHandle<SkRuntimeEffect>, String>
pub fn make_for_shader<'a>( sksl: impl AsRef<str>, options: impl Into<Option<&'a Options>>, ) -> Result<RCHandle<SkRuntimeEffect>, String>
pub fn make_for_blender<'a>( sksl: impl AsRef<str>, options: impl Into<Option<&'a Options>>, ) -> Result<RCHandle<SkRuntimeEffect>, String>
pub fn make_shader<'a>( &self, uniforms: impl Into<RCHandle<SkData>>, children: &[ChildPtr], local_matrix: impl Into<Option<&'a Matrix>>, ) -> Option<RCHandle<SkShader>>
pub fn make_color_filter<'a>( &self, inputs: impl Into<RCHandle<SkData>>, children: impl Into<Option<&'a [ChildPtr]>>, ) -> Option<RCHandle<SkColorFilter>>
pub fn make_blender<'a>( &self, uniforms: impl Into<RCHandle<SkData>>, children: impl Into<Option<&'a [ChildPtr]>>, ) -> Option<RCHandle<SkBlender>>
pub fn source(&self) -> &str
pub fn input_size(&self) -> usize
pub fn uniform_size(&self) -> usize
pub fn inputs(&self) -> &[Handle<SkRuntimeEffect_Uniform>]
pub fn uniforms(&self) -> &[Handle<SkRuntimeEffect_Uniform>]
pub fn children(&self) -> &[Handle<SkRuntimeEffect_Child>]
pub fn find_input( &self, name: impl AsRef<str>, ) -> Option<&Handle<SkRuntimeEffect_Uniform>>
pub fn find_uniform( &self, name: impl AsRef<str>, ) -> Option<&Handle<SkRuntimeEffect_Uniform>>
pub fn find_child( &self, name: impl AsRef<str>, ) -> Option<&Handle<SkRuntimeEffect_Child>>
pub fn allow_shader(&self) -> bool
pub fn allow_color_filter(&self) -> bool
pub fn allow_blender(&self) -> bool
§impl RCHandle<SkMaskFilter>
impl RCHandle<SkMaskFilter>
pub fn from_shader( shader: impl Into<RCHandle<SkShader>>, ) -> RCHandle<SkMaskFilter>
§impl RCHandle<SkColorFilter>
impl RCHandle<SkColorFilter>
pub fn from_table(table: &[u8; 256]) -> RCHandle<SkColorFilter>
pub fn from_argb( table_a: Option<&[u8; 256]>, table_r: Option<&[u8; 256]>, table_g: Option<&[u8; 256]>, table_b: Option<&[u8; 256]>, ) -> RCHandle<SkColorFilter>
§impl RCHandle<GrDirectContext>
impl RCHandle<GrDirectContext>
pub fn new_gl<'a>( interface: impl Into<RCHandle<GrGLInterface>>, options: impl Into<Option<&'a ContextOptions>>, ) -> Option<RCHandle<GrDirectContext>>
pub fn reset( &mut self, backend_state: Option<u32>, ) -> &mut RCHandle<GrDirectContext>
pub fn reset_gl_texture_bindings(&mut self) -> &mut RCHandle<GrDirectContext>
pub fn abandon(&mut self) -> &mut RCHandle<GrDirectContext>
pub fn is_device_lost(&mut self) -> bool
pub fn oomed(&mut self) -> bool
pub fn release_resources_and_abandon( &mut self, ) -> &mut RCHandle<GrDirectContext>
pub fn resource_cache_limit(&self) -> usize
pub fn resource_cache_usage(&self) -> ResourceCacheUsage
pub fn resource_cache_purgeable_bytes(&self) -> usize
pub fn set_resource_cache_limits(&mut self, limits: ResourceCacheLimits)
pub fn set_resource_cache_limit(&mut self, max_resource_bytes: usize)
pub fn free_gpu_resources(&mut self) -> &mut RCHandle<GrDirectContext>
pub fn perform_deferred_cleanup( &mut self, not_used: Duration, opts: impl Into<Option<GrPurgeResourceOptions>>, ) -> &mut RCHandle<GrDirectContext>
pub fn purge_unlocked_resource_bytes( &mut self, bytes_to_purge: usize, prefer_scratch_resources: bool, ) -> &mut RCHandle<GrDirectContext>
pub fn purge_unlocked_resources( &mut self, opts: GrPurgeResourceOptions, ) -> &mut RCHandle<GrDirectContext>
pub fn flush_and_submit(&mut self) -> &mut RCHandle<GrDirectContext>
pub fn flush_submit_and_sync_cpu(&mut self) -> &mut RCHandle<GrDirectContext>
pub fn flush_with_info(&mut self, info: &FlushInfo) -> GrSemaphoresSubmitted
pub fn flush<'a>( &mut self, info: impl Into<Option<&'a FlushInfo>>, ) -> GrSemaphoresSubmitted
pub fn flush_image_with_info( &mut self, image: &RCHandle<SkImage>, info: &FlushInfo, ) -> GrSemaphoresSubmitted
pub fn flush_image(&mut self, image: &RCHandle<SkImage>)
pub fn flush_and_submit_image(&mut self, image: &RCHandle<SkImage>)
pub fn flush_surface_with_access( &mut self, surface: &mut RCHandle<SkSurface>, access: SkSurfaces_BackendSurfaceAccess, info: &FlushInfo, ) -> GrSemaphoresSubmitted
pub fn flush_surface_with_texture_state( &mut self, surface: &mut RCHandle<SkSurface>, info: &FlushInfo, new_state: Option<&RCHandle<skgpu_MutableTextureState>>, ) -> GrSemaphoresSubmitted
pub fn flush_and_submit_surface( &mut self, surface: &mut RCHandle<SkSurface>, sync_cpu: impl Into<Option<GrSyncCpu>>, )
pub fn flush_surface(&mut self, surface: &mut RCHandle<SkSurface>)
pub fn submit(&mut self, sync_cpu: impl Into<Option<GrSyncCpu>>) -> bool
pub fn check_async_work_completion(&mut self)
pub fn supports_distance_field_text(&self) -> bool
pub fn compressed_backend_format( &self, compression: SkTextureCompressionType, ) -> Handle<GrBackendFormat>
pub fn set_backend_texture_state( &mut self, backend_texture: &RefHandle<GrBackendTexture>, state: &RCHandle<skgpu_MutableTextureState>, ) -> bool
pub fn set_backend_texture_state_and_return_previous( &mut self, backend_texture: &RefHandle<GrBackendTexture>, state: &RCHandle<skgpu_MutableTextureState>, ) -> Option<RCHandle<skgpu_MutableTextureState>>
pub fn set_backend_render_target_state( &mut self, target: &Handle<GrBackendRenderTarget>, state: &RCHandle<skgpu_MutableTextureState>, ) -> bool
pub fn set_backend_render_target_state_and_return_previous( &mut self, target: &Handle<GrBackendRenderTarget>, state: &RCHandle<skgpu_MutableTextureState>, ) -> Option<RCHandle<skgpu_MutableTextureState>>
pub fn delete_backend_texture(&mut self, texture: &RefHandle<GrBackendTexture>)
pub fn precompile_shader( &mut self, key: &RCHandle<SkData>, data: &RCHandle<SkData>, ) -> bool
pub fn id(&self) -> DirectContextId
§impl RCHandle<GrGLInterface>
impl RCHandle<GrGLInterface>
pub fn new_native() -> Option<RCHandle<GrGLInterface>>
pub fn new_load_with<F>(load_fn: F) -> Option<RCHandle<GrGLInterface>>
pub fn new_load_with_cstr<F>(load_fn: F) -> Option<RCHandle<GrGLInterface>>
pub fn validate(&self) -> bool
pub fn extensions(&self) -> &Handle<GrGLExtensions>
pub fn extensions_mut(&mut self) -> &mut Handle<GrGLExtensions>
pub fn has_extension(&self, extension: impl AsRef<str>) -> bool
§impl RCHandle<skgpu_MutableTextureState>
impl RCHandle<skgpu_MutableTextureState>
pub fn copied(&self) -> RCHandle<skgpu_MutableTextureState>
pub fn backend(&self) -> skgpu_BackendApi
§impl RCHandle<GrRecordingContext>
impl RCHandle<GrRecordingContext>
pub fn as_direct_context(&mut self) -> Option<RCHandle<GrDirectContext>>
pub fn backend(&self) -> GrBackendApi
pub fn default_backend_format( &self, ct: ColorType, renderable: skgpu_Renderable, ) -> Handle<GrBackendFormat>
pub fn compressed_backend_format( &self, compression_type: SkTextureCompressionType, ) -> Handle<GrBackendFormat>
pub fn abandoned(&mut self) -> bool
pub fn color_type_supported_as_surface(&self, color_type: ColorType) -> bool
pub fn max_texture_size(&self) -> i32
pub fn max_render_target_size(&self) -> i32
pub fn color_type_supported_as_image(&self, color_type: ColorType) -> bool
pub fn supports_protected_content(&self) -> bool
pub fn max_surface_sample_count_for_color_type( &self, color_type: ColorType, ) -> usize
§impl RCHandle<skia_textlayout_FontCollection>
impl RCHandle<skia_textlayout_FontCollection>
pub fn new() -> RCHandle<skia_textlayout_FontCollection>
pub fn font_managers_count(&self) -> usize
pub fn set_asset_font_manager( &mut self, font_manager: impl Into<Option<RCHandle<SkFontMgr>>>, )
pub fn set_dynamic_font_manager( &mut self, font_manager: impl Into<Option<RCHandle<SkFontMgr>>>, )
pub fn set_test_font_manager( &mut self, font_manager: impl Into<Option<RCHandle<SkFontMgr>>>, )
pub fn set_default_font_manager<'a>( &mut self, font_manager: impl Into<Option<RCHandle<SkFontMgr>>>, default_family_name: impl Into<Option<&'a str>>, )
pub fn set_default_font_manager_and_family_names( &mut self, font_manager: impl Into<Option<RCHandle<SkFontMgr>>>, family_names: &[impl AsRef<str>], )
pub fn fallback_manager(&self) -> Option<RCHandle<SkFontMgr>>
pub fn find_typefaces( &mut self, family_names: &[impl AsRef<str>], font_style: FontStyle, ) -> Vec<RCHandle<SkTypeface>>
pub fn find_typefaces_with_font_arguments<'fa>( &mut self, family_names: &[impl AsRef<str>], font_style: FontStyle, font_args: impl Into<Option<&'fa Handle<skia_textlayout_FontArguments>>>, ) -> Vec<RCHandle<SkTypeface>>
pub fn default_fallback_char( &mut self, unicode: i32, font_style: FontStyle, locale: impl AsRef<str>, ) -> Option<RCHandle<SkTypeface>>
pub fn default_fallback(&mut self) -> Option<RCHandle<SkTypeface>>
pub fn default_emoji_fallback( &mut self, emoji_start: i32, font_style: FontStyle, locale: impl AsRef<str>, ) -> Option<RCHandle<SkTypeface>>
pub fn disable_font_fallback(&mut self)
pub fn enable_font_fallback(&mut self)
pub fn font_fallback_enabled(&self) -> bool
pub fn paragraph_cache(&self) -> &Handle<skia_textlayout_ParagraphCache>
pub fn paragraph_cache_mut( &mut self, ) -> &mut Handle<skia_textlayout_ParagraphCache>
pub fn clear_caches(&mut self)
§impl RCHandle<SkSVGDOM>
impl RCHandle<SkSVGDOM>
pub fn read<R>(
reader: R,
font_mgr: impl Into<RCHandle<SkFontMgr>>,
) -> Result<RCHandle<SkSVGDOM>, LoadError>where
R: Read,
pub fn from_str( svg: impl AsRef<str>, font_mgr: impl Into<RCHandle<SkFontMgr>>, ) -> Result<RCHandle<SkSVGDOM>, LoadError>
pub fn from_bytes( svg: &[u8], font_mgr: impl Into<RCHandle<SkFontMgr>>, ) -> Result<RCHandle<SkSVGDOM>, LoadError>
pub fn render(&self, canvas: &Canvas)
pub fn set_container_size(&mut self, size: impl Into<Size>)
Methods from Deref<Target = [u8]>§
sourcepub fn as_str(&self) -> &str
🔬This is a nightly-only experimental API. (ascii_char
)
pub fn as_str(&self) -> &str
ascii_char
)Views this slice of ASCII characters as a UTF-8 str
.
sourcepub fn as_bytes(&self) -> &[u8] ⓘ
🔬This is a nightly-only experimental API. (ascii_char
)
pub fn as_bytes(&self) -> &[u8] ⓘ
ascii_char
)Views this slice of ASCII characters as a slice of u8
bytes.
1.23.0 · sourcepub fn is_ascii(&self) -> bool
pub fn is_ascii(&self) -> bool
Checks if all bytes in this slice are within the ASCII range.
sourcepub fn as_ascii(&self) -> Option<&[AsciiChar]>
🔬This is a nightly-only experimental API. (ascii_char
)
pub fn as_ascii(&self) -> Option<&[AsciiChar]>
ascii_char
)If this slice is_ascii
, returns it as a slice of
ASCII characters, otherwise returns None
.
sourcepub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]
🔬This is a nightly-only experimental API. (ascii_char
)
pub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]
ascii_char
)Converts this slice of bytes into a slice of ASCII characters, without checking whether they’re valid.
§Safety
Every byte in the slice must be in 0..=127
, or else this is UB.
1.23.0 · sourcepub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool
pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool
Checks that two slices are an ASCII case-insensitive match.
Same as to_ascii_lowercase(a) == to_ascii_lowercase(b)
,
but without allocating and copying temporaries.
1.23.0 · sourcepub fn make_ascii_uppercase(&mut self)
pub fn make_ascii_uppercase(&mut self)
Converts this slice to its ASCII upper case equivalent in-place.
ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.
To return a new uppercased value without modifying the existing one, use
to_ascii_uppercase
.
1.23.0 · sourcepub fn make_ascii_lowercase(&mut self)
pub fn make_ascii_lowercase(&mut self)
Converts this slice to its ASCII lower case equivalent in-place.
ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.
To return a new lowercased value without modifying the existing one, use
to_ascii_lowercase
.
1.60.0 · sourcepub fn escape_ascii(&self) -> EscapeAscii<'_>
pub fn escape_ascii(&self) -> EscapeAscii<'_>
Returns an iterator that produces an escaped version of this slice, treating it as an ASCII string.
§Examples
let s = b"0\t\r\n'\"\\\x9d";
let escaped = s.escape_ascii().to_string();
assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
1.80.0 · sourcepub fn trim_ascii_start(&self) -> &[u8] ⓘ
pub fn trim_ascii_start(&self) -> &[u8] ⓘ
Returns a byte slice with leading ASCII whitespace bytes removed.
‘Whitespace’ refers to the definition used by
u8::is_ascii_whitespace
.
§Examples
assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
assert_eq!(b" ".trim_ascii_start(), b"");
assert_eq!(b"".trim_ascii_start(), b"");
1.80.0 · sourcepub fn trim_ascii_end(&self) -> &[u8] ⓘ
pub fn trim_ascii_end(&self) -> &[u8] ⓘ
Returns a byte slice with trailing ASCII whitespace bytes removed.
‘Whitespace’ refers to the definition used by
u8::is_ascii_whitespace
.
§Examples
assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world");
assert_eq!(b" ".trim_ascii_end(), b"");
assert_eq!(b"".trim_ascii_end(), b"");
1.80.0 · sourcepub fn trim_ascii(&self) -> &[u8] ⓘ
pub fn trim_ascii(&self) -> &[u8] ⓘ
Returns a byte slice with leading and trailing ASCII whitespace bytes removed.
‘Whitespace’ refers to the definition used by
u8::is_ascii_whitespace
.
§Examples
assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world");
assert_eq!(b" ".trim_ascii(), b"");
assert_eq!(b"".trim_ascii(), b"");
1.0.0 · sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true
if the slice has a length of 0.
§Examples
let a = [1, 2, 3];
assert!(!a.is_empty());
let b: &[i32] = &[];
assert!(b.is_empty());
1.0.0 · sourcepub fn first(&self) -> Option<&T>
pub fn first(&self) -> Option<&T>
Returns the first element of the slice, or None
if it is empty.
§Examples
let v = [10, 40, 30];
assert_eq!(Some(&10), v.first());
let w: &[i32] = &[];
assert_eq!(None, w.first());
1.0.0 · sourcepub fn first_mut(&mut self) -> Option<&mut T>
pub fn first_mut(&mut self) -> Option<&mut T>
Returns a mutable pointer to the first element of the slice, or None
if it is empty.
§Examples
let x = &mut [0, 1, 2];
if let Some(first) = x.first_mut() {
*first = 5;
}
assert_eq!(x, &[5, 1, 2]);
let y: &mut [i32] = &mut [];
assert_eq!(None, y.first_mut());
1.5.0 · sourcepub fn split_first(&self) -> Option<(&T, &[T])>
pub fn split_first(&self) -> Option<(&T, &[T])>
Returns the first and all the rest of the elements of the slice, or None
if it is empty.
§Examples
let x = &[0, 1, 2];
if let Some((first, elements)) = x.split_first() {
assert_eq!(first, &0);
assert_eq!(elements, &[1, 2]);
}
1.5.0 · sourcepub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>
pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])>
Returns the first and all the rest of the elements of the slice, or None
if it is empty.
§Examples
let x = &mut [0, 1, 2];
if let Some((first, elements)) = x.split_first_mut() {
*first = 3;
elements[0] = 4;
elements[1] = 5;
}
assert_eq!(x, &[3, 4, 5]);
1.5.0 · sourcepub fn split_last(&self) -> Option<(&T, &[T])>
pub fn split_last(&self) -> Option<(&T, &[T])>
Returns the last and all the rest of the elements of the slice, or None
if it is empty.
§Examples
let x = &[0, 1, 2];
if let Some((last, elements)) = x.split_last() {
assert_eq!(last, &2);
assert_eq!(elements, &[0, 1]);
}
1.5.0 · sourcepub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>
pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])>
Returns the last and all the rest of the elements of the slice, or None
if it is empty.
§Examples
let x = &mut [0, 1, 2];
if let Some((last, elements)) = x.split_last_mut() {
*last = 3;
elements[0] = 4;
elements[1] = 5;
}
assert_eq!(x, &[4, 5, 3]);
1.0.0 · sourcepub fn last(&self) -> Option<&T>
pub fn last(&self) -> Option<&T>
Returns the last element of the slice, or None
if it is empty.
§Examples
let v = [10, 40, 30];
assert_eq!(Some(&30), v.last());
let w: &[i32] = &[];
assert_eq!(None, w.last());
1.0.0 · sourcepub fn last_mut(&mut self) -> Option<&mut T>
pub fn last_mut(&mut self) -> Option<&mut T>
Returns a mutable reference to the last item in the slice, or None
if it is empty.
§Examples
let x = &mut [0, 1, 2];
if let Some(last) = x.last_mut() {
*last = 10;
}
assert_eq!(x, &[0, 1, 10]);
let y: &mut [i32] = &mut [];
assert_eq!(None, y.last_mut());
1.77.0 · sourcepub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>
pub fn first_chunk<const N: usize>(&self) -> Option<&[T; N]>
Returns an array reference to the first N
items in the slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let u = [10, 40, 30];
assert_eq!(Some(&[10, 40]), u.first_chunk::<2>());
let v: &[i32] = &[10];
assert_eq!(None, v.first_chunk::<2>());
let w: &[i32] = &[];
assert_eq!(Some(&[]), w.first_chunk::<0>());
1.77.0 · sourcepub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
pub fn first_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
Returns a mutable array reference to the first N
items in the slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let x = &mut [0, 1, 2];
if let Some(first) = x.first_chunk_mut::<2>() {
first[0] = 5;
first[1] = 4;
}
assert_eq!(x, &[5, 4, 2]);
assert_eq!(None, x.first_chunk_mut::<4>());
1.77.0 · sourcepub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>
pub fn split_first_chunk<const N: usize>(&self) -> Option<(&[T; N], &[T])>
Returns an array reference to the first N
items in the slice and the remaining slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let x = &[0, 1, 2];
if let Some((first, elements)) = x.split_first_chunk::<2>() {
assert_eq!(first, &[0, 1]);
assert_eq!(elements, &[2]);
}
assert_eq!(None, x.split_first_chunk::<4>());
1.77.0 · sourcepub fn split_first_chunk_mut<const N: usize>(
&mut self,
) -> Option<(&mut [T; N], &mut [T])>
pub fn split_first_chunk_mut<const N: usize>( &mut self, ) -> Option<(&mut [T; N], &mut [T])>
Returns a mutable array reference to the first N
items in the slice and the remaining
slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let x = &mut [0, 1, 2];
if let Some((first, elements)) = x.split_first_chunk_mut::<2>() {
first[0] = 3;
first[1] = 4;
elements[0] = 5;
}
assert_eq!(x, &[3, 4, 5]);
assert_eq!(None, x.split_first_chunk_mut::<4>());
1.77.0 · sourcepub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T], &[T; N])>
pub fn split_last_chunk<const N: usize>(&self) -> Option<(&[T], &[T; N])>
Returns an array reference to the last N
items in the slice and the remaining slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let x = &[0, 1, 2];
if let Some((elements, last)) = x.split_last_chunk::<2>() {
assert_eq!(elements, &[0]);
assert_eq!(last, &[1, 2]);
}
assert_eq!(None, x.split_last_chunk::<4>());
1.77.0 · sourcepub fn split_last_chunk_mut<const N: usize>(
&mut self,
) -> Option<(&mut [T], &mut [T; N])>
pub fn split_last_chunk_mut<const N: usize>( &mut self, ) -> Option<(&mut [T], &mut [T; N])>
Returns a mutable array reference to the last N
items in the slice and the remaining
slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let x = &mut [0, 1, 2];
if let Some((elements, last)) = x.split_last_chunk_mut::<2>() {
last[0] = 3;
last[1] = 4;
elements[0] = 5;
}
assert_eq!(x, &[5, 3, 4]);
assert_eq!(None, x.split_last_chunk_mut::<4>());
1.77.0 · sourcepub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>
pub fn last_chunk<const N: usize>(&self) -> Option<&[T; N]>
Returns an array reference to the last N
items in the slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let u = [10, 40, 30];
assert_eq!(Some(&[40, 30]), u.last_chunk::<2>());
let v: &[i32] = &[10];
assert_eq!(None, v.last_chunk::<2>());
let w: &[i32] = &[];
assert_eq!(Some(&[]), w.last_chunk::<0>());
1.77.0 · sourcepub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
pub fn last_chunk_mut<const N: usize>(&mut self) -> Option<&mut [T; N]>
Returns a mutable array reference to the last N
items in the slice.
If the slice is not at least N
in length, this will return None
.
§Examples
let x = &mut [0, 1, 2];
if let Some(last) = x.last_chunk_mut::<2>() {
last[0] = 10;
last[1] = 20;
}
assert_eq!(x, &[0, 10, 20]);
assert_eq!(None, x.last_chunk_mut::<4>());
1.0.0 · sourcepub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>where
I: SliceIndex<[T]>,
pub fn get<I>(&self, index: I) -> Option<&<I as SliceIndex<[T]>>::Output>where
I: SliceIndex<[T]>,
Returns a reference to an element or subslice depending on the type of index.
- If given a position, returns a reference to the element at that
position or
None
if out of bounds. - If given a range, returns the subslice corresponding to that range,
or
None
if out of bounds.
§Examples
let v = [10, 40, 30];
assert_eq!(Some(&40), v.get(1));
assert_eq!(Some(&[10, 40][..]), v.get(0..2));
assert_eq!(None, v.get(3));
assert_eq!(None, v.get(0..4));
1.0.0 · sourcepub fn get_mut<I>(
&mut self,
index: I,
) -> Option<&mut <I as SliceIndex<[T]>>::Output>where
I: SliceIndex<[T]>,
pub fn get_mut<I>(
&mut self,
index: I,
) -> Option<&mut <I as SliceIndex<[T]>>::Output>where
I: SliceIndex<[T]>,
1.0.0 · sourcepub unsafe fn get_unchecked<I>(
&self,
index: I,
) -> &<I as SliceIndex<[T]>>::Outputwhere
I: SliceIndex<[T]>,
pub unsafe fn get_unchecked<I>(
&self,
index: I,
) -> &<I as SliceIndex<[T]>>::Outputwhere
I: SliceIndex<[T]>,
Returns a reference to an element or subslice, without doing bounds checking.
For a safe alternative see get
.
§Safety
Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used.
You can think of this like .get(index).unwrap_unchecked()
. It’s UB
to call .get_unchecked(len)
, even if you immediately convert to a
pointer. And it’s UB to call .get_unchecked(..len + 1)
,
.get_unchecked(..=len)
, or similar.
§Examples
let x = &[1, 2, 4];
unsafe {
assert_eq!(x.get_unchecked(1), &2);
}
1.0.0 · sourcepub unsafe fn get_unchecked_mut<I>(
&mut self,
index: I,
) -> &mut <I as SliceIndex<[T]>>::Outputwhere
I: SliceIndex<[T]>,
pub unsafe fn get_unchecked_mut<I>(
&mut self,
index: I,
) -> &mut <I as SliceIndex<[T]>>::Outputwhere
I: SliceIndex<[T]>,
Returns a mutable reference to an element or subslice, without doing bounds checking.
For a safe alternative see get_mut
.
§Safety
Calling this method with an out-of-bounds index is undefined behavior even if the resulting reference is not used.
You can think of this like .get_mut(index).unwrap_unchecked()
. It’s
UB to call .get_unchecked_mut(len)
, even if you immediately convert
to a pointer. And it’s UB to call .get_unchecked_mut(..len + 1)
,
.get_unchecked_mut(..=len)
, or similar.
§Examples
let x = &mut [1, 2, 4];
unsafe {
let elem = x.get_unchecked_mut(1);
*elem = 13;
}
assert_eq!(x, &[1, 13, 4]);
1.0.0 · sourcepub fn as_ptr(&self) -> *const T
pub fn as_ptr(&self) -> *const T
Returns a raw pointer to the slice’s buffer.
The caller must ensure that the slice outlives the pointer this function returns, or else it will end up dangling.
The caller must also ensure that the memory the pointer (non-transitively) points to
is never written to (except inside an UnsafeCell
) using this pointer or any pointer
derived from it. If you need to mutate the contents of the slice, use as_mut_ptr
.
Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any pointers to it invalid.
§Examples
let x = &[1, 2, 4];
let x_ptr = x.as_ptr();
unsafe {
for i in 0..x.len() {
assert_eq!(x.get_unchecked(i), &*x_ptr.add(i));
}
}
1.0.0 · sourcepub fn as_mut_ptr(&mut self) -> *mut T
pub fn as_mut_ptr(&mut self) -> *mut T
Returns an unsafe mutable pointer to the slice’s buffer.
The caller must ensure that the slice outlives the pointer this function returns, or else it will end up dangling.
Modifying the container referenced by this slice may cause its buffer to be reallocated, which would also make any pointers to it invalid.
§Examples
let x = &mut [1, 2, 4];
let x_ptr = x.as_mut_ptr();
unsafe {
for i in 0..x.len() {
*x_ptr.add(i) += 2;
}
}
assert_eq!(x, &[3, 4, 6]);
1.48.0 · sourcepub fn as_ptr_range(&self) -> Range<*const T> ⓘ
pub fn as_ptr_range(&self) -> Range<*const T> ⓘ
Returns the two raw pointers spanning the slice.
The returned range is half-open, which means that the end pointer points one past the last element of the slice. This way, an empty slice is represented by two equal pointers, and the difference between the two pointers represents the size of the slice.
See as_ptr
for warnings on using these pointers. The end pointer
requires extra caution, as it does not point to a valid element in the
slice.
This function is useful for interacting with foreign interfaces which use two pointers to refer to a range of elements in memory, as is common in C++.
It can also be useful to check if a pointer to an element refers to an element of this slice:
let a = [1, 2, 3];
let x = &a[1] as *const _;
let y = &5 as *const _;
assert!(a.as_ptr_range().contains(&x));
assert!(!a.as_ptr_range().contains(&y));
1.48.0 · sourcepub fn as_mut_ptr_range(&mut self) -> Range<*mut T> ⓘ
pub fn as_mut_ptr_range(&mut self) -> Range<*mut T> ⓘ
Returns the two unsafe mutable pointers spanning the slice.
The returned range is half-open, which means that the end pointer points one past the last element of the slice. This way, an empty slice is represented by two equal pointers, and the difference between the two pointers represents the size of the slice.
See as_mut_ptr
for warnings on using these pointers. The end
pointer requires extra caution, as it does not point to a valid element
in the slice.
This function is useful for interacting with foreign interfaces which use two pointers to refer to a range of elements in memory, as is common in C++.
1.0.0 · sourcepub fn swap(&mut self, a: usize, b: usize)
pub fn swap(&mut self, a: usize, b: usize)
Swaps two elements in the slice.
If a
equals to b
, it’s guaranteed that elements won’t change value.
§Arguments
- a - The index of the first element
- b - The index of the second element
§Panics
Panics if a
or b
are out of bounds.
§Examples
let mut v = ["a", "b", "c", "d", "e"];
v.swap(2, 4);
assert!(v == ["a", "b", "e", "d", "c"]);
sourcepub unsafe fn swap_unchecked(&mut self, a: usize, b: usize)
🔬This is a nightly-only experimental API. (slice_swap_unchecked
)
pub unsafe fn swap_unchecked(&mut self, a: usize, b: usize)
slice_swap_unchecked
)Swaps two elements in the slice, without doing bounds checking.
For a safe alternative see swap
.
§Arguments
- a - The index of the first element
- b - The index of the second element
§Safety
Calling this method with an out-of-bounds index is undefined behavior.
The caller has to ensure that a < self.len()
and b < self.len()
.
§Examples
#![feature(slice_swap_unchecked)]
let mut v = ["a", "b", "c", "d"];
// SAFETY: we know that 1 and 3 are both indices of the slice
unsafe { v.swap_unchecked(1, 3) };
assert!(v == ["a", "d", "c", "b"]);
1.0.0 · sourcepub fn reverse(&mut self)
pub fn reverse(&mut self)
Reverses the order of elements in the slice, in place.
§Examples
let mut v = [1, 2, 3];
v.reverse();
assert!(v == [3, 2, 1]);
1.0.0 · sourcepub fn iter(&self) -> Iter<'_, T>
pub fn iter(&self) -> Iter<'_, T>
Returns an iterator over the slice.
The iterator yields all items from start to end.
§Examples
let x = &[1, 2, 4];
let mut iterator = x.iter();
assert_eq!(iterator.next(), Some(&1));
assert_eq!(iterator.next(), Some(&2));
assert_eq!(iterator.next(), Some(&4));
assert_eq!(iterator.next(), None);
1.0.0 · sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>
pub fn iter_mut(&mut self) -> IterMut<'_, T>
Returns an iterator that allows modifying each value.
The iterator yields all items from start to end.
§Examples
let x = &mut [1, 2, 4];
for elem in x.iter_mut() {
*elem += 2;
}
assert_eq!(x, &[3, 4, 6]);
1.0.0 · sourcepub fn windows(&self, size: usize) -> Windows<'_, T>
pub fn windows(&self, size: usize) -> Windows<'_, T>
Returns an iterator over all contiguous windows of length
size
. The windows overlap. If the slice is shorter than
size
, the iterator returns no values.
§Panics
Panics if size
is 0.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.windows(3);
assert_eq!(iter.next().unwrap(), &['l', 'o', 'r']);
assert_eq!(iter.next().unwrap(), &['o', 'r', 'e']);
assert_eq!(iter.next().unwrap(), &['r', 'e', 'm']);
assert!(iter.next().is_none());
If the slice is shorter than size
:
let slice = ['f', 'o', 'o'];
let mut iter = slice.windows(4);
assert!(iter.next().is_none());
There’s no windows_mut
, as that existing would let safe code violate the
“only one &mut
at a time to the same thing” rule. However, you can sometimes
use Cell::as_slice_of_cells
in
conjunction with windows
to accomplish something similar:
use std::cell::Cell;
let mut array = ['R', 'u', 's', 't', ' ', '2', '0', '1', '5'];
let slice = &mut array[..];
let slice_of_cells: &[Cell<char>] = Cell::from_mut(slice).as_slice_of_cells();
for w in slice_of_cells.windows(3) {
Cell::swap(&w[0], &w[2]);
}
assert_eq!(array, ['s', 't', ' ', '2', '0', '1', '5', 'u', 'R']);
1.0.0 · sourcepub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>
pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>
Returns an iterator over chunk_size
elements of the slice at a time, starting at the
beginning of the slice.
The chunks are slices and do not overlap. If chunk_size
does not divide the length of the
slice, then the last chunk will not have length chunk_size
.
See chunks_exact
for a variant of this iterator that returns chunks of always exactly
chunk_size
elements, and rchunks
for the same iterator but starting at the end of the
slice.
§Panics
Panics if chunk_size
is 0.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.chunks(2);
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert_eq!(iter.next().unwrap(), &['m']);
assert!(iter.next().is_none());
1.0.0 · sourcepub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T>
pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T>
Returns an iterator over chunk_size
elements of the slice at a time, starting at the
beginning of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size
does not divide the
length of the slice, then the last chunk will not have length chunk_size
.
See chunks_exact_mut
for a variant of this iterator that returns chunks of always
exactly chunk_size
elements, and rchunks_mut
for the same iterator but starting at
the end of the slice.
§Panics
Panics if chunk_size
is 0.
§Examples
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
for chunk in v.chunks_mut(2) {
for elem in chunk.iter_mut() {
*elem += count;
}
count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 3]);
1.31.0 · sourcepub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>
pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>
Returns an iterator over chunk_size
elements of the slice at a time, starting at the
beginning of the slice.
The chunks are slices and do not overlap. If chunk_size
does not divide the length of the
slice, then the last up to chunk_size-1
elements will be omitted and can be retrieved
from the remainder
function of the iterator.
Due to each chunk having exactly chunk_size
elements, the compiler can often optimize the
resulting code better than in the case of chunks
.
See chunks
for a variant of this iterator that also returns the remainder as a smaller
chunk, and rchunks_exact
for the same iterator but starting at the end of the slice.
§Panics
Panics if chunk_size
is 0.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.chunks_exact(2);
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['m']);
1.31.0 · sourcepub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T>
pub fn chunks_exact_mut(&mut self, chunk_size: usize) -> ChunksExactMut<'_, T>
Returns an iterator over chunk_size
elements of the slice at a time, starting at the
beginning of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size
does not divide the
length of the slice, then the last up to chunk_size-1
elements will be omitted and can be
retrieved from the into_remainder
function of the iterator.
Due to each chunk having exactly chunk_size
elements, the compiler can often optimize the
resulting code better than in the case of chunks_mut
.
See chunks_mut
for a variant of this iterator that also returns the remainder as a
smaller chunk, and rchunks_exact_mut
for the same iterator but starting at the end of
the slice.
§Panics
Panics if chunk_size
is 0.
§Examples
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
for chunk in v.chunks_exact_mut(2) {
for elem in chunk.iter_mut() {
*elem += count;
}
count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 0]);
sourcepub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]
🔬This is a nightly-only experimental API. (slice_as_chunks
)
pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]
slice_as_chunks
)Splits the slice into a slice of N
-element arrays,
assuming that there’s no remainder.
§Safety
This may only be called when
- The slice splits exactly into
N
-element chunks (akaself.len() % N == 0
). N != 0
.
§Examples
#![feature(slice_as_chunks)]
let slice: &[char] = &['l', 'o', 'r', 'e', 'm', '!'];
let chunks: &[[char; 1]] =
// SAFETY: 1-element chunks never have remainder
unsafe { slice.as_chunks_unchecked() };
assert_eq!(chunks, &[['l'], ['o'], ['r'], ['e'], ['m'], ['!']]);
let chunks: &[[char; 3]] =
// SAFETY: The slice length (6) is a multiple of 3
unsafe { slice.as_chunks_unchecked() };
assert_eq!(chunks, &[['l', 'o', 'r'], ['e', 'm', '!']]);
// These would be unsound:
// let chunks: &[[_; 5]] = slice.as_chunks_unchecked() // The slice length is not a multiple of 5
// let chunks: &[[_; 0]] = slice.as_chunks_unchecked() // Zero-length chunks are never allowed
sourcepub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])
🔬This is a nightly-only experimental API. (slice_as_chunks
)
pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])
slice_as_chunks
)Splits the slice into a slice of N
-element arrays,
starting at the beginning of the slice,
and a remainder slice with length strictly less than N
.
§Panics
Panics if N
is 0. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(slice_as_chunks)]
let slice = ['l', 'o', 'r', 'e', 'm'];
let (chunks, remainder) = slice.as_chunks();
assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]);
assert_eq!(remainder, &['m']);
If you expect the slice to be an exact multiple, you can combine
let
-else
with an empty slice pattern:
#![feature(slice_as_chunks)]
let slice = ['R', 'u', 's', 't'];
let (chunks, []) = slice.as_chunks::<2>() else {
panic!("slice didn't have even length")
};
assert_eq!(chunks, &[['R', 'u'], ['s', 't']]);
sourcepub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])
🔬This is a nightly-only experimental API. (slice_as_chunks
)
pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])
slice_as_chunks
)Splits the slice into a slice of N
-element arrays,
starting at the end of the slice,
and a remainder slice with length strictly less than N
.
§Panics
Panics if N
is 0. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(slice_as_chunks)]
let slice = ['l', 'o', 'r', 'e', 'm'];
let (remainder, chunks) = slice.as_rchunks();
assert_eq!(remainder, &['l']);
assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);
sourcepub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N>
🔬This is a nightly-only experimental API. (array_chunks
)
pub fn array_chunks<const N: usize>(&self) -> ArrayChunks<'_, T, N>
array_chunks
)Returns an iterator over N
elements of the slice at a time, starting at the
beginning of the slice.
The chunks are array references and do not overlap. If N
does not divide the
length of the slice, then the last up to N-1
elements will be omitted and can be
retrieved from the remainder
function of the iterator.
This method is the const generic equivalent of chunks_exact
.
§Panics
Panics if N
is 0. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(array_chunks)]
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.array_chunks();
assert_eq!(iter.next().unwrap(), &['l', 'o']);
assert_eq!(iter.next().unwrap(), &['r', 'e']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['m']);
sourcepub unsafe fn as_chunks_unchecked_mut<const N: usize>(
&mut self,
) -> &mut [[T; N]]
🔬This is a nightly-only experimental API. (slice_as_chunks
)
pub unsafe fn as_chunks_unchecked_mut<const N: usize>( &mut self, ) -> &mut [[T; N]]
slice_as_chunks
)Splits the slice into a slice of N
-element arrays,
assuming that there’s no remainder.
§Safety
This may only be called when
- The slice splits exactly into
N
-element chunks (akaself.len() % N == 0
). N != 0
.
§Examples
#![feature(slice_as_chunks)]
let slice: &mut [char] = &mut ['l', 'o', 'r', 'e', 'm', '!'];
let chunks: &mut [[char; 1]] =
// SAFETY: 1-element chunks never have remainder
unsafe { slice.as_chunks_unchecked_mut() };
chunks[0] = ['L'];
assert_eq!(chunks, &[['L'], ['o'], ['r'], ['e'], ['m'], ['!']]);
let chunks: &mut [[char; 3]] =
// SAFETY: The slice length (6) is a multiple of 3
unsafe { slice.as_chunks_unchecked_mut() };
chunks[1] = ['a', 'x', '?'];
assert_eq!(slice, &['L', 'o', 'r', 'a', 'x', '?']);
// These would be unsound:
// let chunks: &[[_; 5]] = slice.as_chunks_unchecked_mut() // The slice length is not a multiple of 5
// let chunks: &[[_; 0]] = slice.as_chunks_unchecked_mut() // Zero-length chunks are never allowed
sourcepub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T])
🔬This is a nightly-only experimental API. (slice_as_chunks
)
pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T])
slice_as_chunks
)Splits the slice into a slice of N
-element arrays,
starting at the beginning of the slice,
and a remainder slice with length strictly less than N
.
§Panics
Panics if N
is 0. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(slice_as_chunks)]
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
let (chunks, remainder) = v.as_chunks_mut();
remainder[0] = 9;
for chunk in chunks {
*chunk = [count; 2];
count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 9]);
sourcepub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]])
🔬This is a nightly-only experimental API. (slice_as_chunks
)
pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]])
slice_as_chunks
)Splits the slice into a slice of N
-element arrays,
starting at the end of the slice,
and a remainder slice with length strictly less than N
.
§Panics
Panics if N
is 0. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(slice_as_chunks)]
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
let (remainder, chunks) = v.as_rchunks_mut();
remainder[0] = 9;
for chunk in chunks {
*chunk = [count; 2];
count += 1;
}
assert_eq!(v, &[9, 1, 1, 2, 2]);
sourcepub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N>
🔬This is a nightly-only experimental API. (array_chunks
)
pub fn array_chunks_mut<const N: usize>(&mut self) -> ArrayChunksMut<'_, T, N>
array_chunks
)Returns an iterator over N
elements of the slice at a time, starting at the
beginning of the slice.
The chunks are mutable array references and do not overlap. If N
does not divide
the length of the slice, then the last up to N-1
elements will be omitted and
can be retrieved from the into_remainder
function of the iterator.
This method is the const generic equivalent of chunks_exact_mut
.
§Panics
Panics if N
is 0. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(array_chunks)]
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
for chunk in v.array_chunks_mut() {
*chunk = [count; 2];
count += 1;
}
assert_eq!(v, &[1, 1, 2, 2, 0]);
sourcepub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N>
🔬This is a nightly-only experimental API. (array_windows
)
pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N>
array_windows
)Returns an iterator over overlapping windows of N
elements of a slice,
starting at the beginning of the slice.
This is the const generic equivalent of windows
.
If N
is greater than the size of the slice, it will return no windows.
§Panics
Panics if N
is 0. This check will most probably get changed to a compile time
error before this method gets stabilized.
§Examples
#![feature(array_windows)]
let slice = [0, 1, 2, 3];
let mut iter = slice.array_windows();
assert_eq!(iter.next().unwrap(), &[0, 1]);
assert_eq!(iter.next().unwrap(), &[1, 2]);
assert_eq!(iter.next().unwrap(), &[2, 3]);
assert!(iter.next().is_none());
1.31.0 · sourcepub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T>
pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T>
Returns an iterator over chunk_size
elements of the slice at a time, starting at the end
of the slice.
The chunks are slices and do not overlap. If chunk_size
does not divide the length of the
slice, then the last chunk will not have length chunk_size
.
See rchunks_exact
for a variant of this iterator that returns chunks of always exactly
chunk_size
elements, and chunks
for the same iterator but starting at the beginning
of the slice.
§Panics
Panics if chunk_size
is 0.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.rchunks(2);
assert_eq!(iter.next().unwrap(), &['e', 'm']);
assert_eq!(iter.next().unwrap(), &['o', 'r']);
assert_eq!(iter.next().unwrap(), &['l']);
assert!(iter.next().is_none());
1.31.0 · sourcepub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T>
pub fn rchunks_mut(&mut self, chunk_size: usize) -> RChunksMut<'_, T>
Returns an iterator over chunk_size
elements of the slice at a time, starting at the end
of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size
does not divide the
length of the slice, then the last chunk will not have length chunk_size
.
See rchunks_exact_mut
for a variant of this iterator that returns chunks of always
exactly chunk_size
elements, and chunks_mut
for the same iterator but starting at the
beginning of the slice.
§Panics
Panics if chunk_size
is 0.
§Examples
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
for chunk in v.rchunks_mut(2) {
for elem in chunk.iter_mut() {
*elem += count;
}
count += 1;
}
assert_eq!(v, &[3, 2, 2, 1, 1]);
1.31.0 · sourcepub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T>
pub fn rchunks_exact(&self, chunk_size: usize) -> RChunksExact<'_, T>
Returns an iterator over chunk_size
elements of the slice at a time, starting at the
end of the slice.
The chunks are slices and do not overlap. If chunk_size
does not divide the length of the
slice, then the last up to chunk_size-1
elements will be omitted and can be retrieved
from the remainder
function of the iterator.
Due to each chunk having exactly chunk_size
elements, the compiler can often optimize the
resulting code better than in the case of rchunks
.
See rchunks
for a variant of this iterator that also returns the remainder as a smaller
chunk, and chunks_exact
for the same iterator but starting at the beginning of the
slice.
§Panics
Panics if chunk_size
is 0.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let mut iter = slice.rchunks_exact(2);
assert_eq!(iter.next().unwrap(), &['e', 'm']);
assert_eq!(iter.next().unwrap(), &['o', 'r']);
assert!(iter.next().is_none());
assert_eq!(iter.remainder(), &['l']);
1.31.0 · sourcepub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T>
pub fn rchunks_exact_mut(&mut self, chunk_size: usize) -> RChunksExactMut<'_, T>
Returns an iterator over chunk_size
elements of the slice at a time, starting at the end
of the slice.
The chunks are mutable slices, and do not overlap. If chunk_size
does not divide the
length of the slice, then the last up to chunk_size-1
elements will be omitted and can be
retrieved from the into_remainder
function of the iterator.
Due to each chunk having exactly chunk_size
elements, the compiler can often optimize the
resulting code better than in the case of chunks_mut
.
See rchunks_mut
for a variant of this iterator that also returns the remainder as a
smaller chunk, and chunks_exact_mut
for the same iterator but starting at the beginning
of the slice.
§Panics
Panics if chunk_size
is 0.
§Examples
let v = &mut [0, 0, 0, 0, 0];
let mut count = 1;
for chunk in v.rchunks_exact_mut(2) {
for elem in chunk.iter_mut() {
*elem += count;
}
count += 1;
}
assert_eq!(v, &[0, 2, 2, 1, 1]);
1.77.0 · sourcepub fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, T, F>
pub fn chunk_by<F>(&self, pred: F) -> ChunkBy<'_, T, F>
Returns an iterator over the slice producing non-overlapping runs of elements using the predicate to separate them.
The predicate is called for every pair of consecutive elements,
meaning that it is called on slice[0]
and slice[1]
,
followed by slice[1]
and slice[2]
, and so on.
§Examples
let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
let mut iter = slice.chunk_by(|a, b| a == b);
assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
assert_eq!(iter.next(), Some(&[3, 3][..]));
assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
assert_eq!(iter.next(), None);
This method can be used to extract the sorted subslices:
let slice = &[1, 1, 2, 3, 2, 3, 2, 3, 4];
let mut iter = slice.chunk_by(|a, b| a <= b);
assert_eq!(iter.next(), Some(&[1, 1, 2, 3][..]));
assert_eq!(iter.next(), Some(&[2, 3][..]));
assert_eq!(iter.next(), Some(&[2, 3, 4][..]));
assert_eq!(iter.next(), None);
1.77.0 · sourcepub fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, T, F>
pub fn chunk_by_mut<F>(&mut self, pred: F) -> ChunkByMut<'_, T, F>
Returns an iterator over the slice producing non-overlapping mutable runs of elements using the predicate to separate them.
The predicate is called for every pair of consecutive elements,
meaning that it is called on slice[0]
and slice[1]
,
followed by slice[1]
and slice[2]
, and so on.
§Examples
let slice = &mut [1, 1, 1, 3, 3, 2, 2, 2];
let mut iter = slice.chunk_by_mut(|a, b| a == b);
assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
assert_eq!(iter.next(), Some(&mut [3, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
assert_eq!(iter.next(), None);
This method can be used to extract the sorted subslices:
let slice = &mut [1, 1, 2, 3, 2, 3, 2, 3, 4];
let mut iter = slice.chunk_by_mut(|a, b| a <= b);
assert_eq!(iter.next(), Some(&mut [1, 1, 2, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 3][..]));
assert_eq!(iter.next(), Some(&mut [2, 3, 4][..]));
assert_eq!(iter.next(), None);
1.0.0 · sourcepub fn split_at(&self, mid: usize) -> (&[T], &[T])
pub fn split_at(&self, mid: usize) -> (&[T], &[T])
Divides one slice into two at an index.
The first will contain all indices from [0, mid)
(excluding
the index mid
itself) and the second will contain all
indices from [mid, len)
(excluding the index len
itself).
§Panics
Panics if mid > len
. For a non-panicking alternative see
split_at_checked
.
§Examples
let v = [1, 2, 3, 4, 5, 6];
{
let (left, right) = v.split_at(0);
assert_eq!(left, []);
assert_eq!(right, [1, 2, 3, 4, 5, 6]);
}
{
let (left, right) = v.split_at(2);
assert_eq!(left, [1, 2]);
assert_eq!(right, [3, 4, 5, 6]);
}
{
let (left, right) = v.split_at(6);
assert_eq!(left, [1, 2, 3, 4, 5, 6]);
assert_eq!(right, []);
}
1.0.0 · sourcepub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])
pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T])
Divides one mutable slice into two at an index.
The first will contain all indices from [0, mid)
(excluding
the index mid
itself) and the second will contain all
indices from [mid, len)
(excluding the index len
itself).
§Panics
Panics if mid > len
. For a non-panicking alternative see
split_at_mut_checked
.
§Examples
let mut v = [1, 0, 3, 0, 5, 6];
let (left, right) = v.split_at_mut(2);
assert_eq!(left, [1, 0]);
assert_eq!(right, [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1.79.0 · sourcepub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])
pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T])
Divides one slice into two at an index, without doing bounds checking.
The first will contain all indices from [0, mid)
(excluding
the index mid
itself) and the second will contain all
indices from [mid, len)
(excluding the index len
itself).
For a safe alternative see split_at
.
§Safety
Calling this method with an out-of-bounds index is undefined behavior
even if the resulting reference is not used. The caller has to ensure that
0 <= mid <= self.len()
.
§Examples
let v = [1, 2, 3, 4, 5, 6];
unsafe {
let (left, right) = v.split_at_unchecked(0);
assert_eq!(left, []);
assert_eq!(right, [1, 2, 3, 4, 5, 6]);
}
unsafe {
let (left, right) = v.split_at_unchecked(2);
assert_eq!(left, [1, 2]);
assert_eq!(right, [3, 4, 5, 6]);
}
unsafe {
let (left, right) = v.split_at_unchecked(6);
assert_eq!(left, [1, 2, 3, 4, 5, 6]);
assert_eq!(right, []);
}
1.79.0 · sourcepub unsafe fn split_at_mut_unchecked(
&mut self,
mid: usize,
) -> (&mut [T], &mut [T])
pub unsafe fn split_at_mut_unchecked( &mut self, mid: usize, ) -> (&mut [T], &mut [T])
Divides one mutable slice into two at an index, without doing bounds checking.
The first will contain all indices from [0, mid)
(excluding
the index mid
itself) and the second will contain all
indices from [mid, len)
(excluding the index len
itself).
For a safe alternative see split_at_mut
.
§Safety
Calling this method with an out-of-bounds index is undefined behavior
even if the resulting reference is not used. The caller has to ensure that
0 <= mid <= self.len()
.
§Examples
let mut v = [1, 0, 3, 0, 5, 6];
// scoped to restrict the lifetime of the borrows
unsafe {
let (left, right) = v.split_at_mut_unchecked(2);
assert_eq!(left, [1, 0]);
assert_eq!(right, [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
}
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
1.80.0 · sourcepub fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])>
pub fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])>
Divides one slice into two at an index, returning None
if the slice is
too short.
If mid ≤ len
returns a pair of slices where the first will contain all
indices from [0, mid)
(excluding the index mid
itself) and the
second will contain all indices from [mid, len)
(excluding the index
len
itself).
Otherwise, if mid > len
, returns None
.
§Examples
let v = [1, -2, 3, -4, 5, -6];
{
let (left, right) = v.split_at_checked(0).unwrap();
assert_eq!(left, []);
assert_eq!(right, [1, -2, 3, -4, 5, -6]);
}
{
let (left, right) = v.split_at_checked(2).unwrap();
assert_eq!(left, [1, -2]);
assert_eq!(right, [3, -4, 5, -6]);
}
{
let (left, right) = v.split_at_checked(6).unwrap();
assert_eq!(left, [1, -2, 3, -4, 5, -6]);
assert_eq!(right, []);
}
assert_eq!(None, v.split_at_checked(7));
1.80.0 · sourcepub fn split_at_mut_checked(
&mut self,
mid: usize,
) -> Option<(&mut [T], &mut [T])>
pub fn split_at_mut_checked( &mut self, mid: usize, ) -> Option<(&mut [T], &mut [T])>
Divides one mutable slice into two at an index, returning None
if the
slice is too short.
If mid ≤ len
returns a pair of slices where the first will contain all
indices from [0, mid)
(excluding the index mid
itself) and the
second will contain all indices from [mid, len)
(excluding the index
len
itself).
Otherwise, if mid > len
, returns None
.
§Examples
let mut v = [1, 0, 3, 0, 5, 6];
if let Some((left, right)) = v.split_at_mut_checked(2) {
assert_eq!(left, [1, 0]);
assert_eq!(right, [3, 0, 5, 6]);
left[1] = 2;
right[1] = 4;
}
assert_eq!(v, [1, 2, 3, 4, 5, 6]);
assert_eq!(None, v.split_at_mut_checked(7));
1.0.0 · sourcepub fn split<F>(&self, pred: F) -> Split<'_, T, F>
pub fn split<F>(&self, pred: F) -> Split<'_, T, F>
Returns an iterator over subslices separated by elements that match
pred
. The matched element is not contained in the subslices.
§Examples
let slice = [10, 40, 33, 20];
let mut iter = slice.split(|num| num % 3 == 0);
assert_eq!(iter.next().unwrap(), &[10, 40]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
If the first element is matched, an empty slice will be the first item returned by the iterator. Similarly, if the last element in the slice is matched, an empty slice will be the last item returned by the iterator:
let slice = [10, 40, 33];
let mut iter = slice.split(|num| num % 3 == 0);
assert_eq!(iter.next().unwrap(), &[10, 40]);
assert_eq!(iter.next().unwrap(), &[]);
assert!(iter.next().is_none());
If two matched elements are directly adjacent, an empty slice will be present between them:
let slice = [10, 6, 33, 20];
let mut iter = slice.split(|num| num % 3 == 0);
assert_eq!(iter.next().unwrap(), &[10]);
assert_eq!(iter.next().unwrap(), &[]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
1.0.0 · sourcepub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<'_, T, F>
Returns an iterator over mutable subslices separated by elements that
match pred
. The matched element is not contained in the subslices.
§Examples
let mut v = [10, 40, 30, 20, 60, 50];
for group in v.split_mut(|num| *num % 3 == 0) {
group[0] = 1;
}
assert_eq!(v, [1, 40, 30, 1, 60, 1]);
1.51.0 · sourcepub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
pub fn split_inclusive<F>(&self, pred: F) -> SplitInclusive<'_, T, F>
Returns an iterator over subslices separated by elements that match
pred
. The matched element is contained in the end of the previous
subslice as a terminator.
§Examples
let slice = [10, 40, 33, 20];
let mut iter = slice.split_inclusive(|num| num % 3 == 0);
assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
assert_eq!(iter.next().unwrap(), &[20]);
assert!(iter.next().is_none());
If the last element of the slice is matched, that element will be considered the terminator of the preceding slice. That slice will be the last item returned by the iterator.
let slice = [3, 10, 40, 33];
let mut iter = slice.split_inclusive(|num| num % 3 == 0);
assert_eq!(iter.next().unwrap(), &[3]);
assert_eq!(iter.next().unwrap(), &[10, 40, 33]);
assert!(iter.next().is_none());
1.51.0 · sourcepub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
pub fn split_inclusive_mut<F>(&mut self, pred: F) -> SplitInclusiveMut<'_, T, F>
Returns an iterator over mutable subslices separated by elements that
match pred
. The matched element is contained in the previous
subslice as a terminator.
§Examples
let mut v = [10, 40, 30, 20, 60, 50];
for group in v.split_inclusive_mut(|num| *num % 3 == 0) {
let terminator_idx = group.len()-1;
group[terminator_idx] = 1;
}
assert_eq!(v, [10, 40, 1, 20, 1, 1]);
1.27.0 · sourcepub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
pub fn rsplit<F>(&self, pred: F) -> RSplit<'_, T, F>
Returns an iterator over subslices separated by elements that match
pred
, starting at the end of the slice and working backwards.
The matched element is not contained in the subslices.
§Examples
let slice = [11, 22, 33, 0, 44, 55];
let mut iter = slice.rsplit(|num| *num == 0);
assert_eq!(iter.next().unwrap(), &[44, 55]);
assert_eq!(iter.next().unwrap(), &[11, 22, 33]);
assert_eq!(iter.next(), None);
As with split()
, if the first or last element is matched, an empty
slice will be the first (or last) item returned by the iterator.
let v = &[0, 1, 1, 2, 3, 5, 8];
let mut it = v.rsplit(|n| *n % 2 == 0);
assert_eq!(it.next().unwrap(), &[]);
assert_eq!(it.next().unwrap(), &[3, 5]);
assert_eq!(it.next().unwrap(), &[1, 1]);
assert_eq!(it.next().unwrap(), &[]);
assert_eq!(it.next(), None);
1.27.0 · sourcepub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
pub fn rsplit_mut<F>(&mut self, pred: F) -> RSplitMut<'_, T, F>
Returns an iterator over mutable subslices separated by elements that
match pred
, starting at the end of the slice and working
backwards. The matched element is not contained in the subslices.
§Examples
let mut v = [100, 400, 300, 200, 600, 500];
let mut count = 0;
for group in v.rsplit_mut(|num| *num % 3 == 0) {
count += 1;
group[0] = count;
}
assert_eq!(v, [3, 400, 300, 2, 600, 1]);
1.0.0 · sourcepub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<'_, T, F>
Returns an iterator over subslices separated by elements that match
pred
, limited to returning at most n
items. The matched element is
not contained in the subslices.
The last element returned, if any, will contain the remainder of the slice.
§Examples
Print the slice split once by numbers divisible by 3 (i.e., [10, 40]
,
[20, 60, 50]
):
let v = [10, 40, 30, 20, 60, 50];
for group in v.splitn(2, |num| *num % 3 == 0) {
println!("{group:?}");
}
1.0.0 · sourcepub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<'_, T, F>
Returns an iterator over mutable subslices separated by elements that match
pred
, limited to returning at most n
items. The matched element is
not contained in the subslices.
The last element returned, if any, will contain the remainder of the slice.
§Examples
let mut v = [10, 40, 30, 20, 60, 50];
for group in v.splitn_mut(2, |num| *num % 3 == 0) {
group[0] = 1;
}
assert_eq!(v, [1, 40, 30, 1, 60, 50]);
1.0.0 · sourcepub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<'_, T, F>
Returns an iterator over subslices separated by elements that match
pred
limited to returning at most n
items. This starts at the end of
the slice and works backwards. The matched element is not contained in
the subslices.
The last element returned, if any, will contain the remainder of the slice.
§Examples
Print the slice split once, starting from the end, by numbers divisible
by 3 (i.e., [50]
, [10, 40, 30, 20]
):
let v = [10, 40, 30, 20, 60, 50];
for group in v.rsplitn(2, |num| *num % 3 == 0) {
println!("{group:?}");
}
1.0.0 · sourcepub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<'_, T, F>
Returns an iterator over subslices separated by elements that match
pred
limited to returning at most n
items. This starts at the end of
the slice and works backwards. The matched element is not contained in
the subslices.
The last element returned, if any, will contain the remainder of the slice.
§Examples
let mut s = [10, 40, 30, 20, 60, 50];
for group in s.rsplitn_mut(2, |num| *num % 3 == 0) {
group[0] = 1;
}
assert_eq!(s, [1, 40, 30, 20, 60, 1]);
sourcepub fn split_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
🔬This is a nightly-only experimental API. (slice_split_once
)
pub fn split_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
slice_split_once
)Splits the slice on the first element that matches the specified predicate.
If any matching elements are present in the slice, returns the prefix
before the match and suffix after. The matching element itself is not
included. If no elements match, returns None
.
§Examples
#![feature(slice_split_once)]
let s = [1, 2, 3, 2, 4];
assert_eq!(s.split_once(|&x| x == 2), Some((
&[1][..],
&[3, 2, 4][..]
)));
assert_eq!(s.split_once(|&x| x == 0), None);
sourcepub fn rsplit_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
🔬This is a nightly-only experimental API. (slice_split_once
)
pub fn rsplit_once<F>(&self, pred: F) -> Option<(&[T], &[T])>
slice_split_once
)Splits the slice on the last element that matches the specified predicate.
If any matching elements are present in the slice, returns the prefix
before the match and suffix after. The matching element itself is not
included. If no elements match, returns None
.
§Examples
#![feature(slice_split_once)]
let s = [1, 2, 3, 2, 4];
assert_eq!(s.rsplit_once(|&x| x == 2), Some((
&[1, 2, 3][..],
&[4][..]
)));
assert_eq!(s.rsplit_once(|&x| x == 0), None);
1.0.0 · sourcepub fn contains(&self, x: &T) -> boolwhere
T: PartialEq,
pub fn contains(&self, x: &T) -> boolwhere
T: PartialEq,
Returns true
if the slice contains an element with the given value.
This operation is O(n).
Note that if you have a sorted slice, binary_search
may be faster.
§Examples
let v = [10, 40, 30];
assert!(v.contains(&30));
assert!(!v.contains(&50));
If you do not have a &T
, but some other value that you can compare
with one (for example, String
implements PartialEq<str>
), you can
use iter().any
:
let v = [String::from("hello"), String::from("world")]; // slice of `String`
assert!(v.iter().any(|e| e == "hello")); // search with `&str`
assert!(!v.iter().any(|e| e == "hi"));
1.0.0 · sourcepub fn starts_with(&self, needle: &[T]) -> boolwhere
T: PartialEq,
pub fn starts_with(&self, needle: &[T]) -> boolwhere
T: PartialEq,
Returns true
if needle
is a prefix of the slice or equal to the slice.
§Examples
let v = [10, 40, 30];
assert!(v.starts_with(&[10]));
assert!(v.starts_with(&[10, 40]));
assert!(v.starts_with(&v));
assert!(!v.starts_with(&[50]));
assert!(!v.starts_with(&[10, 50]));
Always returns true
if needle
is an empty slice:
let v = &[10, 40, 30];
assert!(v.starts_with(&[]));
let v: &[u8] = &[];
assert!(v.starts_with(&[]));
1.0.0 · sourcepub fn ends_with(&self, needle: &[T]) -> boolwhere
T: PartialEq,
pub fn ends_with(&self, needle: &[T]) -> boolwhere
T: PartialEq,
Returns true
if needle
is a suffix of the slice or equal to the slice.
§Examples
let v = [10, 40, 30];
assert!(v.ends_with(&[30]));
assert!(v.ends_with(&[40, 30]));
assert!(v.ends_with(&v));
assert!(!v.ends_with(&[50]));
assert!(!v.ends_with(&[50, 30]));
Always returns true
if needle
is an empty slice:
let v = &[10, 40, 30];
assert!(v.ends_with(&[]));
let v: &[u8] = &[];
assert!(v.ends_with(&[]));
1.51.0 · sourcepub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>
pub fn strip_prefix<P>(&self, prefix: &P) -> Option<&[T]>
Returns a subslice with the prefix removed.
If the slice starts with prefix
, returns the subslice after the prefix, wrapped in Some
.
If prefix
is empty, simply returns the original slice. If prefix
is equal to the
original slice, returns an empty slice.
If the slice does not start with prefix
, returns None
.
§Examples
let v = &[10, 40, 30];
assert_eq!(v.strip_prefix(&[10]), Some(&[40, 30][..]));
assert_eq!(v.strip_prefix(&[10, 40]), Some(&[30][..]));
assert_eq!(v.strip_prefix(&[10, 40, 30]), Some(&[][..]));
assert_eq!(v.strip_prefix(&[50]), None);
assert_eq!(v.strip_prefix(&[10, 50]), None);
let prefix : &str = "he";
assert_eq!(b"hello".strip_prefix(prefix.as_bytes()),
Some(b"llo".as_ref()));
1.51.0 · sourcepub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>
pub fn strip_suffix<P>(&self, suffix: &P) -> Option<&[T]>
Returns a subslice with the suffix removed.
If the slice ends with suffix
, returns the subslice before the suffix, wrapped in Some
.
If suffix
is empty, simply returns the original slice. If suffix
is equal to the
original slice, returns an empty slice.
If the slice does not end with suffix
, returns None
.
§Examples
let v = &[10, 40, 30];
assert_eq!(v.strip_suffix(&[30]), Some(&[10, 40][..]));
assert_eq!(v.strip_suffix(&[40, 30]), Some(&[10][..]));
assert_eq!(v.strip_suffix(&[10, 40, 30]), Some(&[][..]));
assert_eq!(v.strip_suffix(&[50]), None);
assert_eq!(v.strip_suffix(&[50, 30]), None);
1.0.0 · sourcepub fn binary_search(&self, x: &T) -> Result<usize, usize>where
T: Ord,
pub fn binary_search(&self, x: &T) -> Result<usize, usize>where
T: Ord,
Binary searches this slice for a given element. If the slice is not sorted, the returned result is unspecified and meaningless.
If the value is found then Result::Ok
is returned, containing the
index of the matching element. If there are multiple matches, then any
one of the matches could be returned. The index is chosen
deterministically, but is subject to change in future versions of Rust.
If the value is not found then Result::Err
is returned, containing
the index where a matching element could be inserted while maintaining
sorted order.
See also binary_search_by
, binary_search_by_key
, and partition_point
.
§Examples
Looks up a series of four elements. The first is found, with a
uniquely determined position; the second and third are not
found; the fourth could match any position in [1, 4]
.
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
assert_eq!(s.binary_search(&13), Ok(9));
assert_eq!(s.binary_search(&4), Err(7));
assert_eq!(s.binary_search(&100), Err(13));
let r = s.binary_search(&1);
assert!(match r { Ok(1..=4) => true, _ => false, });
If you want to find that whole range of matching items, rather than
an arbitrary matching one, that can be done using partition_point
:
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let low = s.partition_point(|x| x < &1);
assert_eq!(low, 1);
let high = s.partition_point(|x| x <= &1);
assert_eq!(high, 5);
let r = s.binary_search(&1);
assert!((low..high).contains(&r.unwrap()));
assert!(s[..low].iter().all(|&x| x < 1));
assert!(s[low..high].iter().all(|&x| x == 1));
assert!(s[high..].iter().all(|&x| x > 1));
// For something not found, the "range" of equal items is empty
assert_eq!(s.partition_point(|x| x < &11), 9);
assert_eq!(s.partition_point(|x| x <= &11), 9);
assert_eq!(s.binary_search(&11), Err(9));
If you want to insert an item to a sorted vector, while maintaining
sort order, consider using partition_point
:
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let num = 42;
let idx = s.partition_point(|&x| x <= num);
// If `num` is unique, `s.partition_point(|&x| x < num)` (with `<`) is equivalent to
// `s.binary_search(&num).unwrap_or_else(|x| x)`, but using `<=` will allow `insert`
// to shift less elements.
s.insert(idx, num);
assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
1.0.0 · sourcepub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
pub fn binary_search_by<'a, F>(&'a self, f: F) -> Result<usize, usize>
Binary searches this slice with a comparator function.
The comparator function should return an order code that indicates
whether its argument is Less
, Equal
or Greater
the desired
target.
If the slice is not sorted or if the comparator function does not
implement an order consistent with the sort order of the underlying
slice, the returned result is unspecified and meaningless.
If the value is found then Result::Ok
is returned, containing the
index of the matching element. If there are multiple matches, then any
one of the matches could be returned. The index is chosen
deterministically, but is subject to change in future versions of Rust.
If the value is not found then Result::Err
is returned, containing
the index where a matching element could be inserted while maintaining
sorted order.
See also binary_search
, binary_search_by_key
, and partition_point
.
§Examples
Looks up a series of four elements. The first is found, with a
uniquely determined position; the second and third are not
found; the fourth could match any position in [1, 4]
.
let s = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let seek = 13;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Ok(9));
let seek = 4;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(7));
let seek = 100;
assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13));
let seek = 1;
let r = s.binary_search_by(|probe| probe.cmp(&seek));
assert!(match r { Ok(1..=4) => true, _ => false, });
1.10.0 · sourcepub fn binary_search_by_key<'a, B, F>(
&'a self,
b: &B,
f: F,
) -> Result<usize, usize>
pub fn binary_search_by_key<'a, B, F>( &'a self, b: &B, f: F, ) -> Result<usize, usize>
Binary searches this slice with a key extraction function.
Assumes that the slice is sorted by the key, for instance with
sort_by_key
using the same key extraction function.
If the slice is not sorted by the key, the returned result is
unspecified and meaningless.
If the value is found then Result::Ok
is returned, containing the
index of the matching element. If there are multiple matches, then any
one of the matches could be returned. The index is chosen
deterministically, but is subject to change in future versions of Rust.
If the value is not found then Result::Err
is returned, containing
the index where a matching element could be inserted while maintaining
sorted order.
See also binary_search
, binary_search_by
, and partition_point
.
§Examples
Looks up a series of four elements in a slice of pairs sorted by
their second elements. The first is found, with a uniquely
determined position; the second and third are not found; the
fourth could match any position in [1, 4]
.
let s = [(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
(1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
(1, 21), (2, 34), (4, 55)];
assert_eq!(s.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
assert_eq!(s.binary_search_by_key(&4, |&(a, b)| b), Err(7));
assert_eq!(s.binary_search_by_key(&100, |&(a, b)| b), Err(13));
let r = s.binary_search_by_key(&1, |&(a, b)| b);
assert!(match r { Ok(1..=4) => true, _ => false, });
1.20.0 · sourcepub fn sort_unstable(&mut self)where
T: Ord,
pub fn sort_unstable(&mut self)where
T: Ord,
Sorts the slice without preserving the initial order of equal elements.
This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and O(n * log(n)) worst-case.
If the implementation of Ord
for T
does not implement a total order the resulting
order of elements in the slice is unspecified. All original elements will remain in the
slice and any possible modifications via interior mutability are observed in the input. Same
is true if the implementation of Ord
for T
panics.
Sorting types that only implement PartialOrd
such as f32
and f64
require
additional precautions. For example, f32::NAN != f32::NAN
, which doesn’t fulfill the
reflexivity requirement of Ord
. By using an alternative comparison function with
slice::sort_unstable_by
such as f32::total_cmp
or f64::total_cmp
that defines a
total order users can sort slices containing floating-point values. Alternatively, if all
values in the slice are guaranteed to be in a subset for which PartialOrd::partial_cmp
forms a total order, it’s possible to sort the slice with sort_unstable_by(|a, b| a.partial_cmp(b).unwrap())
.
§Current implementation
The current implementation is based on ipnsort by Lukas Bergdoll and Orson Peters, which combines the fast average case of quicksort with the fast worst case of heapsort, achieving linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the expected time to sort the data is O(n * log(k)).
It is typically faster than stable sorting, except in a few special cases, e.g., when the slice is partially sorted.
§Panics
May panic if the implementation of Ord
for T
does not implement a total order.
§Examples
let mut v = [4, -5, 1, -3, 2];
v.sort_unstable();
assert_eq!(v, [-5, -3, 1, 2, 4]);
1.20.0 · sourcepub fn sort_unstable_by<F>(&mut self, compare: F)
pub fn sort_unstable_by<F>(&mut self, compare: F)
Sorts the slice with a comparison function, without preserving the initial order of equal elements.
This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and O(n * log(n)) worst-case.
If the comparison function compare
does not implement a total order the resulting order
of elements in the slice is unspecified. All original elements will remain in the slice and
any possible modifications via interior mutability are observed in the input. Same is true
if compare
panics.
For example |a, b| (a - b).cmp(a)
is a comparison function that is neither transitive nor
reflexive nor total, a < b < c < a
with a = 1, b = 2, c = 3
. For more information and
examples see the Ord
documentation.
§Current implementation
The current implementation is based on ipnsort by Lukas Bergdoll and Orson Peters, which combines the fast average case of quicksort with the fast worst case of heapsort, achieving linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the expected time to sort the data is O(n * log(k)).
It is typically faster than stable sorting, except in a few special cases, e.g., when the slice is partially sorted.
§Panics
May panic if compare
does not implement a total order.
§Examples
let mut v = [4, -5, 1, -3, 2];
v.sort_unstable_by(|a, b| a.cmp(b));
assert_eq!(v, [-5, -3, 1, 2, 4]);
// reverse sorting
v.sort_unstable_by(|a, b| b.cmp(a));
assert_eq!(v, [4, 2, 1, -3, -5]);
1.20.0 · sourcepub fn sort_unstable_by_key<K, F>(&mut self, f: F)
pub fn sort_unstable_by_key<K, F>(&mut self, f: F)
Sorts the slice with a key extraction function, without preserving the initial order of equal elements.
This sort is unstable (i.e., may reorder equal elements), in-place (i.e., does not allocate), and O(n * log(n)) worst-case.
If the implementation of Ord
for K
does not implement a total order the resulting
order of elements in the slice is unspecified. All original elements will remain in the
slice and any possible modifications via interior mutability are observed in the input. Same
is true if the implementation of Ord
for K
panics.
§Current implementation
The current implementation is based on ipnsort by Lukas Bergdoll and Orson Peters, which combines the fast average case of quicksort with the fast worst case of heapsort, achieving linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the expected time to sort the data is O(n * log(k)).
It is typically faster than stable sorting, except in a few special cases, e.g., when the slice is partially sorted.
§Panics
May panic if the implementation of Ord
for K
does not implement a total order.
§Examples
let mut v = [4i32, -5, 1, -3, 2];
v.sort_unstable_by_key(|k| k.abs());
assert_eq!(v, [1, 2, -3, 4, -5]);
1.49.0 · sourcepub fn select_nth_unstable(
&mut self,
index: usize,
) -> (&mut [T], &mut T, &mut [T])where
T: Ord,
pub fn select_nth_unstable(
&mut self,
index: usize,
) -> (&mut [T], &mut T, &mut [T])where
T: Ord,
Reorders the slice such that the element at index
after the reordering is at its final
sorted position.
This reordering has the additional property that any value at position i < index
will be
less than or equal to any value at a position j > index
. Additionally, this reordering is
unstable (i.e. any number of equal elements may end up at position index
), in-place (i.e.
does not allocate), and runs in O(n) time. This function is also known as “kth element”
in other libraries.
It returns a triplet of the following from the reordered slice: the subslice prior to
index
, the element at index
, and the subslice after index
; accordingly, the values in
those two subslices will respectively all be less-than-or-equal-to and
greater-than-or-equal-to the value of the element at index
.
§Current implementation
The current algorithm is an introselect implementation based on ipnsort by Lukas Bergdoll
and Orson Peters, which is also the basis for sort_unstable
. The fallback algorithm is
Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime
for all inputs.
§Panics
Panics when index >= len()
, meaning it always panics on empty slices.
May panic if the implementation of Ord
for T
does not implement a total order.
§Examples
let mut v = [-5i32, 4, 2, -3, 1];
// Find the items less than or equal to the median, the median, and greater than or equal to
// the median.
let (lesser, median, greater) = v.select_nth_unstable(2);
assert!(lesser == [-3, -5] || lesser == [-5, -3]);
assert_eq!(median, &mut 1);
assert!(greater == [4, 2] || greater == [2, 4]);
// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [-3, -5, 1, 2, 4] ||
v == [-5, -3, 1, 2, 4] ||
v == [-3, -5, 1, 4, 2] ||
v == [-5, -3, 1, 4, 2]);
1.49.0 · sourcepub fn select_nth_unstable_by<F>(
&mut self,
index: usize,
compare: F,
) -> (&mut [T], &mut T, &mut [T])
pub fn select_nth_unstable_by<F>( &mut self, index: usize, compare: F, ) -> (&mut [T], &mut T, &mut [T])
Reorders the slice with a comparator function such that the element at index
after the
reordering is at its final sorted position.
This reordering has the additional property that any value at position i < index
will be
less than or equal to any value at a position j > index
using the comparator function.
Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
position index
), in-place (i.e. does not allocate), and runs in O(n) time. This
function is also known as “kth element” in other libraries.
It returns a triplet of the following from the slice reordered according to the provided
comparator function: the subslice prior to index
, the element at index
, and the subslice
after index
; accordingly, the values in those two subslices will respectively all be
less-than-or-equal-to and greater-than-or-equal-to the value of the element at index
.
§Current implementation
The current algorithm is an introselect implementation based on ipnsort by Lukas Bergdoll
and Orson Peters, which is also the basis for sort_unstable
. The fallback algorithm is
Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime
for all inputs.
§Panics
Panics when index >= len()
, meaning it always panics on empty slices.
May panic if compare
does not implement a total order.
§Examples
let mut v = [-5i32, 4, 2, -3, 1];
// Find the items less than or equal to the median, the median, and greater than or equal to
// the median as if the slice were sorted in descending order.
let (lesser, median, greater) = v.select_nth_unstable_by(2, |a, b| b.cmp(a));
assert!(lesser == [4, 2] || lesser == [2, 4]);
assert_eq!(median, &mut 1);
assert!(greater == [-3, -5] || greater == [-5, -3]);
// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [2, 4, 1, -5, -3] ||
v == [2, 4, 1, -3, -5] ||
v == [4, 2, 1, -5, -3] ||
v == [4, 2, 1, -3, -5]);
1.49.0 · sourcepub fn select_nth_unstable_by_key<K, F>(
&mut self,
index: usize,
f: F,
) -> (&mut [T], &mut T, &mut [T])
pub fn select_nth_unstable_by_key<K, F>( &mut self, index: usize, f: F, ) -> (&mut [T], &mut T, &mut [T])
Reorders the slice with a key extraction function such that the element at index
after the
reordering is at its final sorted position.
This reordering has the additional property that any value at position i < index
will be
less than or equal to any value at a position j > index
using the key extraction function.
Additionally, this reordering is unstable (i.e. any number of equal elements may end up at
position index
), in-place (i.e. does not allocate), and runs in O(n) time. This
function is also known as “kth element” in other libraries.
It returns a triplet of the following from the slice reordered according to the provided key
extraction function: the subslice prior to index
, the element at index
, and the subslice
after index
; accordingly, the values in those two subslices will respectively all be
less-than-or-equal-to and greater-than-or-equal-to the value of the element at index
.
§Current implementation
The current algorithm is an introselect implementation based on ipnsort by Lukas Bergdoll
and Orson Peters, which is also the basis for sort_unstable
. The fallback algorithm is
Median of Medians using Tukey’s Ninther for pivot selection, which guarantees linear runtime
for all inputs.
§Panics
Panics when index >= len()
, meaning it always panics on empty slices.
May panic if K: Ord
does not implement a total order.
§Examples
let mut v = [-5i32, 4, 1, -3, 2];
// Find the items less than or equal to the median, the median, and greater than or equal to
// the median as if the slice were sorted according to absolute value.
let (lesser, median, greater) = v.select_nth_unstable_by_key(2, |a| a.abs());
assert!(lesser == [1, 2] || lesser == [2, 1]);
assert_eq!(median, &mut -3);
assert!(greater == [4, -5] || greater == [-5, 4]);
// We are only guaranteed the slice will be one of the following, based on the way we sort
// about the specified index.
assert!(v == [1, 2, -3, 4, -5] ||
v == [1, 2, -3, -5, 4] ||
v == [2, 1, -3, 4, -5] ||
v == [2, 1, -3, -5, 4]);
sourcepub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])where
T: PartialEq,
🔬This is a nightly-only experimental API. (slice_partition_dedup
)
pub fn partition_dedup(&mut self) -> (&mut [T], &mut [T])where
T: PartialEq,
slice_partition_dedup
)Moves all consecutive repeated elements to the end of the slice according to the
PartialEq
trait implementation.
Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.
If the slice is sorted, the first returned slice contains no duplicates.
§Examples
#![feature(slice_partition_dedup)]
let mut slice = [1, 2, 2, 3, 3, 2, 1, 1];
let (dedup, duplicates) = slice.partition_dedup();
assert_eq!(dedup, [1, 2, 3, 2, 1]);
assert_eq!(duplicates, [2, 3, 1]);
sourcepub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])
🔬This is a nightly-only experimental API. (slice_partition_dedup
)
pub fn partition_dedup_by<F>(&mut self, same_bucket: F) -> (&mut [T], &mut [T])
slice_partition_dedup
)Moves all but the first of consecutive elements to the end of the slice satisfying a given equality relation.
Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.
The same_bucket
function is passed references to two elements from the slice and
must determine if the elements compare equal. The elements are passed in opposite order
from their order in the slice, so if same_bucket(a, b)
returns true
, a
is moved
at the end of the slice.
If the slice is sorted, the first returned slice contains no duplicates.
§Examples
#![feature(slice_partition_dedup)]
let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
let (dedup, duplicates) = slice.partition_dedup_by(|a, b| a.eq_ignore_ascii_case(b));
assert_eq!(dedup, ["foo", "BAZ", "Bar", "baz"]);
assert_eq!(duplicates, ["bar", "Foo", "BAZ"]);
sourcepub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])
🔬This is a nightly-only experimental API. (slice_partition_dedup
)
pub fn partition_dedup_by_key<K, F>(&mut self, key: F) -> (&mut [T], &mut [T])
slice_partition_dedup
)Moves all but the first of consecutive elements to the end of the slice that resolve to the same key.
Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.
If the slice is sorted, the first returned slice contains no duplicates.
§Examples
#![feature(slice_partition_dedup)]
let mut slice = [10, 20, 21, 30, 30, 20, 11, 13];
let (dedup, duplicates) = slice.partition_dedup_by_key(|i| *i / 10);
assert_eq!(dedup, [10, 20, 30, 20, 11]);
assert_eq!(duplicates, [21, 30, 13]);
1.26.0 · sourcepub fn rotate_left(&mut self, mid: usize)
pub fn rotate_left(&mut self, mid: usize)
Rotates the slice in-place such that the first mid
elements of the
slice move to the end while the last self.len() - mid
elements move to
the front.
After calling rotate_left
, the element previously at index mid
will
become the first element in the slice.
§Panics
This function will panic if mid
is greater than the length of the
slice. Note that mid == self.len()
does not panic and is a no-op
rotation.
§Complexity
Takes linear (in self.len()
) time.
§Examples
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.rotate_left(2);
assert_eq!(a, ['c', 'd', 'e', 'f', 'a', 'b']);
Rotating a subslice:
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a[1..5].rotate_left(1);
assert_eq!(a, ['a', 'c', 'd', 'e', 'b', 'f']);
1.26.0 · sourcepub fn rotate_right(&mut self, k: usize)
pub fn rotate_right(&mut self, k: usize)
Rotates the slice in-place such that the first self.len() - k
elements of the slice move to the end while the last k
elements move
to the front.
After calling rotate_right
, the element previously at index
self.len() - k
will become the first element in the slice.
§Panics
This function will panic if k
is greater than the length of the
slice. Note that k == self.len()
does not panic and is a no-op
rotation.
§Complexity
Takes linear (in self.len()
) time.
§Examples
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.rotate_right(2);
assert_eq!(a, ['e', 'f', 'a', 'b', 'c', 'd']);
Rotating a subslice:
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
a[1..5].rotate_right(1);
assert_eq!(a, ['a', 'e', 'b', 'c', 'd', 'f']);
1.50.0 · sourcepub fn fill(&mut self, value: T)where
T: Clone,
pub fn fill(&mut self, value: T)where
T: Clone,
Fills self
with elements by cloning value
.
§Examples
let mut buf = vec![0; 10];
buf.fill(1);
assert_eq!(buf, vec![1; 10]);
1.51.0 · sourcepub fn fill_with<F>(&mut self, f: F)where
F: FnMut() -> T,
pub fn fill_with<F>(&mut self, f: F)where
F: FnMut() -> T,
Fills self
with elements returned by calling a closure repeatedly.
This method uses a closure to create new values. If you’d rather
Clone
a given value, use fill
. If you want to use the Default
trait to generate values, you can pass Default::default
as the
argument.
§Examples
let mut buf = vec![1; 10];
buf.fill_with(Default::default);
assert_eq!(buf, vec![0; 10]);
1.7.0 · sourcepub fn clone_from_slice(&mut self, src: &[T])where
T: Clone,
pub fn clone_from_slice(&mut self, src: &[T])where
T: Clone,
Copies the elements from src
into self
.
The length of src
must be the same as self
.
§Panics
This function will panic if the two slices have different lengths.
§Examples
Cloning two elements from a slice into another:
let src = [1, 2, 3, 4];
let mut dst = [0, 0];
// Because the slices have to be the same length,
// we slice the source slice from four elements
// to two. It will panic if we don't do this.
dst.clone_from_slice(&src[2..]);
assert_eq!(src, [1, 2, 3, 4]);
assert_eq!(dst, [3, 4]);
Rust enforces that there can only be one mutable reference with no
immutable references to a particular piece of data in a particular
scope. Because of this, attempting to use clone_from_slice
on a
single slice will result in a compile failure:
let mut slice = [1, 2, 3, 4, 5];
slice[..2].clone_from_slice(&slice[3..]); // compile fail!
To work around this, we can use split_at_mut
to create two distinct
sub-slices from a slice:
let mut slice = [1, 2, 3, 4, 5];
{
let (left, right) = slice.split_at_mut(2);
left.clone_from_slice(&right[1..]);
}
assert_eq!(slice, [4, 5, 3, 4, 5]);
1.9.0 · sourcepub fn copy_from_slice(&mut self, src: &[T])where
T: Copy,
pub fn copy_from_slice(&mut self, src: &[T])where
T: Copy,
Copies all elements from src
into self
, using a memcpy.
The length of src
must be the same as self
.
If T
does not implement Copy
, use clone_from_slice
.
§Panics
This function will panic if the two slices have different lengths.
§Examples
Copying two elements from a slice into another:
let src = [1, 2, 3, 4];
let mut dst = [0, 0];
// Because the slices have to be the same length,
// we slice the source slice from four elements
// to two. It will panic if we don't do this.
dst.copy_from_slice(&src[2..]);
assert_eq!(src, [1, 2, 3, 4]);
assert_eq!(dst, [3, 4]);
Rust enforces that there can only be one mutable reference with no
immutable references to a particular piece of data in a particular
scope. Because of this, attempting to use copy_from_slice
on a
single slice will result in a compile failure:
let mut slice = [1, 2, 3, 4, 5];
slice[..2].copy_from_slice(&slice[3..]); // compile fail!
To work around this, we can use split_at_mut
to create two distinct
sub-slices from a slice:
let mut slice = [1, 2, 3, 4, 5];
{
let (left, right) = slice.split_at_mut(2);
left.copy_from_slice(&right[1..]);
}
assert_eq!(slice, [4, 5, 3, 4, 5]);
1.37.0 · sourcepub fn copy_within<R>(&mut self, src: R, dest: usize)
pub fn copy_within<R>(&mut self, src: R, dest: usize)
Copies elements from one part of the slice to another part of itself, using a memmove.
src
is the range within self
to copy from. dest
is the starting
index of the range within self
to copy to, which will have the same
length as src
. The two ranges may overlap. The ends of the two ranges
must be less than or equal to self.len()
.
§Panics
This function will panic if either range exceeds the end of the slice,
or if the end of src
is before the start.
§Examples
Copying four bytes within a slice:
let mut bytes = *b"Hello, World!";
bytes.copy_within(1..5, 8);
assert_eq!(&bytes, b"Hello, Wello!");
1.27.0 · sourcepub fn swap_with_slice(&mut self, other: &mut [T])
pub fn swap_with_slice(&mut self, other: &mut [T])
Swaps all elements in self
with those in other
.
The length of other
must be the same as self
.
§Panics
This function will panic if the two slices have different lengths.
§Example
Swapping two elements across slices:
let mut slice1 = [0, 0];
let mut slice2 = [1, 2, 3, 4];
slice1.swap_with_slice(&mut slice2[2..]);
assert_eq!(slice1, [3, 4]);
assert_eq!(slice2, [1, 2, 0, 0]);
Rust enforces that there can only be one mutable reference to a
particular piece of data in a particular scope. Because of this,
attempting to use swap_with_slice
on a single slice will result in
a compile failure:
let mut slice = [1, 2, 3, 4, 5];
slice[..2].swap_with_slice(&mut slice[3..]); // compile fail!
To work around this, we can use split_at_mut
to create two distinct
mutable sub-slices from a slice:
let mut slice = [1, 2, 3, 4, 5];
{
let (left, right) = slice.split_at_mut(2);
left.swap_with_slice(&mut right[1..]);
}
assert_eq!(slice, [4, 5, 3, 1, 2]);
1.30.0 · sourcepub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])
pub unsafe fn align_to<U>(&self) -> (&[T], &[U], &[T])
Transmutes the slice to a slice of another type, ensuring alignment of the types is maintained.
This method splits the slice into three distinct slices: prefix, correctly aligned middle slice of a new type, and the suffix slice. The middle part will be as big as possible under the given alignment constraint and element size.
This method has no purpose when either input element T
or output element U
are
zero-sized and will return the original slice without splitting anything.
§Safety
This method is essentially a transmute
with respect to the elements in the returned
middle slice, so all the usual caveats pertaining to transmute::<T, U>
also apply here.
§Examples
Basic usage:
unsafe {
let bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
let (prefix, shorts, suffix) = bytes.align_to::<u16>();
// less_efficient_algorithm_for_bytes(prefix);
// more_efficient_algorithm_for_aligned_shorts(shorts);
// less_efficient_algorithm_for_bytes(suffix);
}
1.30.0 · sourcepub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T])
pub unsafe fn align_to_mut<U>(&mut self) -> (&mut [T], &mut [U], &mut [T])
Transmutes the mutable slice to a mutable slice of another type, ensuring alignment of the types is maintained.
This method splits the slice into three distinct slices: prefix, correctly aligned middle slice of a new type, and the suffix slice. The middle part will be as big as possible under the given alignment constraint and element size.
This method has no purpose when either input element T
or output element U
are
zero-sized and will return the original slice without splitting anything.
§Safety
This method is essentially a transmute
with respect to the elements in the returned
middle slice, so all the usual caveats pertaining to transmute::<T, U>
also apply here.
§Examples
Basic usage:
unsafe {
let mut bytes: [u8; 7] = [1, 2, 3, 4, 5, 6, 7];
let (prefix, shorts, suffix) = bytes.align_to_mut::<u16>();
// less_efficient_algorithm_for_bytes(prefix);
// more_efficient_algorithm_for_aligned_shorts(shorts);
// less_efficient_algorithm_for_bytes(suffix);
}
sourcepub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
🔬This is a nightly-only experimental API. (portable_simd
)
pub fn as_simd<const LANES: usize>(&self) -> (&[T], &[Simd<T, LANES>], &[T])
portable_simd
)Splits a slice into a prefix, a middle of aligned SIMD types, and a suffix.
This is a safe wrapper around slice::align_to
, so inherits the same
guarantees as that method.
§Panics
This will panic if the size of the SIMD type is different from
LANES
times that of the scalar.
At the time of writing, the trait restrictions on Simd<T, LANES>
keeps
that from ever happening, as only power-of-two numbers of lanes are
supported. It’s possible that, in the future, those restrictions might
be lifted in a way that would make it possible to see panics from this
method for something like LANES == 3
.
§Examples
#![feature(portable_simd)]
use core::simd::prelude::*;
let short = &[1, 2, 3];
let (prefix, middle, suffix) = short.as_simd::<4>();
assert_eq!(middle, []); // Not enough elements for anything in the middle
// They might be split in any possible way between prefix and suffix
let it = prefix.iter().chain(suffix).copied();
assert_eq!(it.collect::<Vec<_>>(), vec![1, 2, 3]);
fn basic_simd_sum(x: &[f32]) -> f32 {
use std::ops::Add;
let (prefix, middle, suffix) = x.as_simd();
let sums = f32x4::from_array([
prefix.iter().copied().sum(),
0.0,
0.0,
suffix.iter().copied().sum(),
]);
let sums = middle.iter().copied().fold(sums, f32x4::add);
sums.reduce_sum()
}
let numbers: Vec<f32> = (1..101).map(|x| x as _).collect();
assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0);
sourcepub fn as_simd_mut<const LANES: usize>(
&mut self,
) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
🔬This is a nightly-only experimental API. (portable_simd
)
pub fn as_simd_mut<const LANES: usize>( &mut self, ) -> (&mut [T], &mut [Simd<T, LANES>], &mut [T])
portable_simd
)Splits a mutable slice into a mutable prefix, a middle of aligned SIMD types, and a mutable suffix.
This is a safe wrapper around slice::align_to_mut
, so inherits the same
guarantees as that method.
This is the mutable version of slice::as_simd
; see that for examples.
§Panics
This will panic if the size of the SIMD type is different from
LANES
times that of the scalar.
At the time of writing, the trait restrictions on Simd<T, LANES>
keeps
that from ever happening, as only power-of-two numbers of lanes are
supported. It’s possible that, in the future, those restrictions might
be lifted in a way that would make it possible to see panics from this
method for something like LANES == 3
.
1.82.0 · sourcepub fn is_sorted(&self) -> boolwhere
T: PartialOrd,
pub fn is_sorted(&self) -> boolwhere
T: PartialOrd,
Checks if the elements of this slice are sorted.
That is, for each element a
and its following element b
, a <= b
must hold. If the
slice yields exactly zero or one element, true
is returned.
Note that if Self::Item
is only PartialOrd
, but not Ord
, the above definition
implies that this function returns false
if any two consecutive items are not
comparable.
§Examples
let empty: [i32; 0] = [];
assert!([1, 2, 2, 9].is_sorted());
assert!(![1, 3, 2, 4].is_sorted());
assert!([0].is_sorted());
assert!(empty.is_sorted());
assert!(![0.0, 1.0, f32::NAN].is_sorted());
1.82.0 · sourcepub fn is_sorted_by<'a, F>(&'a self, compare: F) -> bool
pub fn is_sorted_by<'a, F>(&'a self, compare: F) -> bool
Checks if the elements of this slice are sorted using the given comparator function.
Instead of using PartialOrd::partial_cmp
, this function uses the given compare
function to determine whether two elements are to be considered in sorted order.
§Examples
assert!([1, 2, 2, 9].is_sorted_by(|a, b| a <= b));
assert!(![1, 2, 2, 9].is_sorted_by(|a, b| a < b));
assert!([0].is_sorted_by(|a, b| true));
assert!([0].is_sorted_by(|a, b| false));
let empty: [i32; 0] = [];
assert!(empty.is_sorted_by(|a, b| false));
assert!(empty.is_sorted_by(|a, b| true));
1.82.0 · sourcepub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
pub fn is_sorted_by_key<'a, F, K>(&'a self, f: F) -> bool
Checks if the elements of this slice are sorted using the given key extraction function.
Instead of comparing the slice’s elements directly, this function compares the keys of the
elements, as determined by f
. Apart from that, it’s equivalent to is_sorted
; see its
documentation for more information.
§Examples
assert!(["c", "bb", "aaa"].is_sorted_by_key(|s| s.len()));
assert!(![-2i32, -1, 0, 3].is_sorted_by_key(|n| n.abs()));
1.52.0 · sourcepub fn partition_point<P>(&self, pred: P) -> usize
pub fn partition_point<P>(&self, pred: P) -> usize
Returns the index of the partition point according to the given predicate (the index of the first element of the second partition).
The slice is assumed to be partitioned according to the given predicate.
This means that all elements for which the predicate returns true are at the start of the slice
and all elements for which the predicate returns false are at the end.
For example, [7, 15, 3, 5, 4, 12, 6]
is partitioned under the predicate x % 2 != 0
(all odd numbers are at the start, all even at the end).
If this slice is not partitioned, the returned result is unspecified and meaningless, as this method performs a kind of binary search.
See also binary_search
, binary_search_by
, and binary_search_by_key
.
§Examples
let v = [1, 2, 3, 3, 5, 6, 7];
let i = v.partition_point(|&x| x < 5);
assert_eq!(i, 4);
assert!(v[..i].iter().all(|&x| x < 5));
assert!(v[i..].iter().all(|&x| !(x < 5)));
If all elements of the slice match the predicate, including if the slice is empty, then the length of the slice will be returned:
let a = [2, 4, 8];
assert_eq!(a.partition_point(|x| x < &100), a.len());
let a: [i32; 0] = [];
assert_eq!(a.partition_point(|x| x < &100), 0);
If you want to insert an item to a sorted vector, while maintaining sort order:
let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
let num = 42;
let idx = s.partition_point(|&x| x <= num);
s.insert(idx, num);
assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
sourcepub fn take<'a, R>(self: &mut &'a [T], range: R) -> Option<&'a [T]>where
R: OneSidedRange<usize>,
🔬This is a nightly-only experimental API. (slice_take
)
pub fn take<'a, R>(self: &mut &'a [T], range: R) -> Option<&'a [T]>where
R: OneSidedRange<usize>,
slice_take
)Removes the subslice corresponding to the given range and returns a reference to it.
Returns None
and does not modify the slice if the given
range is out of bounds.
Note that this method only accepts one-sided ranges such as
2..
or ..6
, but not 2..6
.
§Examples
Taking the first three elements of a slice:
#![feature(slice_take)]
let mut slice: &[_] = &['a', 'b', 'c', 'd'];
let mut first_three = slice.take(..3).unwrap();
assert_eq!(slice, &['d']);
assert_eq!(first_three, &['a', 'b', 'c']);
Taking the last two elements of a slice:
#![feature(slice_take)]
let mut slice: &[_] = &['a', 'b', 'c', 'd'];
let mut tail = slice.take(2..).unwrap();
assert_eq!(slice, &['a', 'b']);
assert_eq!(tail, &['c', 'd']);
Getting None
when range
is out of bounds:
#![feature(slice_take)]
let mut slice: &[_] = &['a', 'b', 'c', 'd'];
assert_eq!(None, slice.take(5..));
assert_eq!(None, slice.take(..5));
assert_eq!(None, slice.take(..=4));
let expected: &[char] = &['a', 'b', 'c', 'd'];
assert_eq!(Some(expected), slice.take(..4));
sourcepub fn take_mut<'a, R>(self: &mut &'a mut [T], range: R) -> Option<&'a mut [T]>where
R: OneSidedRange<usize>,
🔬This is a nightly-only experimental API. (slice_take
)
pub fn take_mut<'a, R>(self: &mut &'a mut [T], range: R) -> Option<&'a mut [T]>where
R: OneSidedRange<usize>,
slice_take
)Removes the subslice corresponding to the given range and returns a mutable reference to it.
Returns None
and does not modify the slice if the given
range is out of bounds.
Note that this method only accepts one-sided ranges such as
2..
or ..6
, but not 2..6
.
§Examples
Taking the first three elements of a slice:
#![feature(slice_take)]
let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
let mut first_three = slice.take_mut(..3).unwrap();
assert_eq!(slice, &mut ['d']);
assert_eq!(first_three, &mut ['a', 'b', 'c']);
Taking the last two elements of a slice:
#![feature(slice_take)]
let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
let mut tail = slice.take_mut(2..).unwrap();
assert_eq!(slice, &mut ['a', 'b']);
assert_eq!(tail, &mut ['c', 'd']);
Getting None
when range
is out of bounds:
#![feature(slice_take)]
let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
assert_eq!(None, slice.take_mut(5..));
assert_eq!(None, slice.take_mut(..5));
assert_eq!(None, slice.take_mut(..=4));
let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
assert_eq!(Some(expected), slice.take_mut(..4));
sourcepub fn take_first<'a>(self: &mut &'a [T]) -> Option<&'a T>
🔬This is a nightly-only experimental API. (slice_take
)
pub fn take_first<'a>(self: &mut &'a [T]) -> Option<&'a T>
slice_take
)Removes the first element of the slice and returns a reference to it.
Returns None
if the slice is empty.
§Examples
#![feature(slice_take)]
let mut slice: &[_] = &['a', 'b', 'c'];
let first = slice.take_first().unwrap();
assert_eq!(slice, &['b', 'c']);
assert_eq!(first, &'a');
sourcepub fn take_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
🔬This is a nightly-only experimental API. (slice_take
)
pub fn take_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
slice_take
)Removes the first element of the slice and returns a mutable reference to it.
Returns None
if the slice is empty.
§Examples
#![feature(slice_take)]
let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
let first = slice.take_first_mut().unwrap();
*first = 'd';
assert_eq!(slice, &['b', 'c']);
assert_eq!(first, &'d');
sourcepub fn take_last<'a>(self: &mut &'a [T]) -> Option<&'a T>
🔬This is a nightly-only experimental API. (slice_take
)
pub fn take_last<'a>(self: &mut &'a [T]) -> Option<&'a T>
slice_take
)Removes the last element of the slice and returns a reference to it.
Returns None
if the slice is empty.
§Examples
#![feature(slice_take)]
let mut slice: &[_] = &['a', 'b', 'c'];
let last = slice.take_last().unwrap();
assert_eq!(slice, &['a', 'b']);
assert_eq!(last, &'c');
sourcepub fn take_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
🔬This is a nightly-only experimental API. (slice_take
)
pub fn take_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
slice_take
)Removes the last element of the slice and returns a mutable reference to it.
Returns None
if the slice is empty.
§Examples
#![feature(slice_take)]
let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
let last = slice.take_last_mut().unwrap();
*last = 'd';
assert_eq!(slice, &['a', 'b']);
assert_eq!(last, &'d');
sourcepub unsafe fn get_many_unchecked_mut<const N: usize>(
&mut self,
indices: [usize; N],
) -> [&mut T; N]
🔬This is a nightly-only experimental API. (get_many_mut
)
pub unsafe fn get_many_unchecked_mut<const N: usize>( &mut self, indices: [usize; N], ) -> [&mut T; N]
get_many_mut
)Returns mutable references to many indices at once, without doing any checks.
For a safe alternative see get_many_mut
.
§Safety
Calling this method with overlapping or out-of-bounds indices is undefined behavior even if the resulting references are not used.
§Examples
#![feature(get_many_mut)]
let x = &mut [1, 2, 4];
unsafe {
let [a, b] = x.get_many_unchecked_mut([0, 2]);
*a *= 10;
*b *= 100;
}
assert_eq!(x, &[10, 2, 400]);
sourcepub fn get_many_mut<const N: usize>(
&mut self,
indices: [usize; N],
) -> Result<[&mut T; N], GetManyMutError<N>>
🔬This is a nightly-only experimental API. (get_many_mut
)
pub fn get_many_mut<const N: usize>( &mut self, indices: [usize; N], ) -> Result<[&mut T; N], GetManyMutError<N>>
get_many_mut
)Returns mutable references to many indices at once.
Returns an error if any index is out-of-bounds, or if the same index was passed more than once.
§Examples
#![feature(get_many_mut)]
let v = &mut [1, 2, 3];
if let Ok([a, b]) = v.get_many_mut([0, 2]) {
*a = 413;
*b = 612;
}
assert_eq!(v, &[413, 2, 612]);
sourcepub fn elem_offset(&self, element: &T) -> Option<usize>
🔬This is a nightly-only experimental API. (substr_range
)
pub fn elem_offset(&self, element: &T) -> Option<usize>
substr_range
)Returns the index that an element reference points to.
Returns None
if element
does not point within the slice or if it points between elements.
This method is useful for extending slice iterators like slice::split
.
Note that this uses pointer arithmetic and does not compare elements.
To find the index of an element via comparison, use
.iter().position()
instead.
§Panics
Panics if T
is zero-sized.
§Examples
Basic usage:
#![feature(substr_range)]
let nums: &[u32] = &[1, 7, 1, 1];
let num = &nums[2];
assert_eq!(num, &1);
assert_eq!(nums.elem_offset(num), Some(2));
Returning None
with an in-between element:
#![feature(substr_range)]
let arr: &[[u32; 2]] = &[[0, 1], [2, 3]];
let flat_arr: &[u32] = arr.as_flattened();
let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap();
let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap();
assert_eq!(ok_elm, &[0, 1]);
assert_eq!(weird_elm, &[1, 2]);
assert_eq!(arr.elem_offset(ok_elm), Some(0)); // Points to element 0
assert_eq!(arr.elem_offset(weird_elm), None); // Points between element 0 and 1
sourcepub fn subslice_range(&self, subslice: &[T]) -> Option<Range<usize>>
🔬This is a nightly-only experimental API. (substr_range
)
pub fn subslice_range(&self, subslice: &[T]) -> Option<Range<usize>>
substr_range
)Returns the range of indices that a subslice points to.
Returns None
if subslice
does not point within the slice or if it points between elements.
This method does not compare elements. Instead, this method finds the location in the slice that
subslice
was obtained from. To find the index of a subslice via comparison, instead use
.windows()
.position()
.
This method is useful for extending slice iterators like slice::split
.
Note that this may return a false positive (either Some(0..0)
or Some(self.len()..self.len())
)
if subslice
has a length of zero and points to the beginning or end of another, separate, slice.
§Panics
Panics if T
is zero-sized.
§Examples
Basic usage:
#![feature(substr_range)]
let nums = &[0, 5, 10, 0, 0, 5];
let mut iter = nums
.split(|t| *t == 0)
.map(|n| nums.subslice_range(n).unwrap());
assert_eq!(iter.next(), Some(0..0));
assert_eq!(iter.next(), Some(1..3));
assert_eq!(iter.next(), Some(4..4));
assert_eq!(iter.next(), Some(5..6));
1.80.0 · sourcepub fn as_flattened(&self) -> &[T]
pub fn as_flattened(&self) -> &[T]
Takes a &[[T; N]]
, and flattens it to a &[T]
.
§Panics
This panics if the length of the resulting slice would overflow a usize
.
This is only possible when flattening a slice of arrays of zero-sized
types, and thus tends to be irrelevant in practice. If
size_of::<T>() > 0
, this will never panic.
§Examples
assert_eq!([[1, 2, 3], [4, 5, 6]].as_flattened(), &[1, 2, 3, 4, 5, 6]);
assert_eq!(
[[1, 2, 3], [4, 5, 6]].as_flattened(),
[[1, 2], [3, 4], [5, 6]].as_flattened(),
);
let slice_of_empty_arrays: &[[i32; 0]] = &[[], [], [], [], []];
assert!(slice_of_empty_arrays.as_flattened().is_empty());
let empty_slice_of_arrays: &[[u32; 10]] = &[];
assert!(empty_slice_of_arrays.as_flattened().is_empty());
1.80.0 · sourcepub fn as_flattened_mut(&mut self) -> &mut [T]
pub fn as_flattened_mut(&mut self) -> &mut [T]
Takes a &mut [[T; N]]
, and flattens it to a &mut [T]
.
§Panics
This panics if the length of the resulting slice would overflow a usize
.
This is only possible when flattening a slice of arrays of zero-sized
types, and thus tends to be irrelevant in practice. If
size_of::<T>() > 0
, this will never panic.
§Examples
fn add_5_to_all(slice: &mut [i32]) {
for i in slice {
*i += 5;
}
}
let mut array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
add_5_to_all(array.as_flattened_mut());
assert_eq!(array, [[6, 7, 8], [9, 10, 11], [12, 13, 14]]);
sourcepub fn sort_floats(&mut self)
🔬This is a nightly-only experimental API. (sort_floats
)
pub fn sort_floats(&mut self)
sort_floats
)Sorts the slice of floats.
This sort is in-place (i.e. does not allocate), O(n * log(n)) worst-case, and uses
the ordering defined by f32::total_cmp
.
§Current implementation
This uses the same sorting algorithm as sort_unstable_by
.
§Examples
#![feature(sort_floats)]
let mut v = [2.6, -5e-8, f32::NAN, 8.29, f32::INFINITY, -1.0, 0.0, -f32::INFINITY, -0.0];
v.sort_floats();
let sorted = [-f32::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f32::INFINITY, f32::NAN];
assert_eq!(&v[..8], &sorted[..8]);
assert!(v[8].is_nan());
sourcepub fn sort_floats(&mut self)
🔬This is a nightly-only experimental API. (sort_floats
)
pub fn sort_floats(&mut self)
sort_floats
)Sorts the slice of floats.
This sort is in-place (i.e. does not allocate), O(n * log(n)) worst-case, and uses
the ordering defined by f64::total_cmp
.
§Current implementation
This uses the same sorting algorithm as sort_unstable_by
.
§Examples
#![feature(sort_floats)]
let mut v = [2.6, -5e-8, f64::NAN, 8.29, f64::INFINITY, -1.0, 0.0, -f64::INFINITY, -0.0];
v.sort_floats();
let sorted = [-f64::INFINITY, -1.0, -5e-8, -0.0, 0.0, 2.6, 8.29, f64::INFINITY, f64::NAN];
assert_eq!(&v[..8], &sorted[..8]);
assert!(v[8].is_nan());
1.79.0 · sourcepub fn utf8_chunks(&self) -> Utf8Chunks<'_>
pub fn utf8_chunks(&self) -> Utf8Chunks<'_>
Creates an iterator over the contiguous valid UTF-8 ranges of this slice, and the non-UTF-8 fragments in between.
§Examples
This function formats arbitrary but mostly-UTF-8 bytes into Rust source
code in the form of a C-string literal (c"..."
).
use std::fmt::Write as _;
pub fn cstr_literal(bytes: &[u8]) -> String {
let mut repr = String::new();
repr.push_str("c\"");
for chunk in bytes.utf8_chunks() {
for ch in chunk.valid().chars() {
// Escapes \0, \t, \r, \n, \\, \', \", and uses \u{...} for non-printable characters.
write!(repr, "{}", ch.escape_debug()).unwrap();
}
for byte in chunk.invalid() {
write!(repr, "\\x{:02X}", byte).unwrap();
}
}
repr.push('"');
repr
}
fn main() {
let lit = cstr_literal(b"\xferris the \xf0\x9f\xa6\x80\x07");
let expected = stringify!(c"\xFErris the 🦀\u{7}");
assert_eq!(lit, expected);
}
1.0.0 · sourcepub fn sort(&mut self)where
T: Ord,
pub fn sort(&mut self)where
T: Ord,
Sorts the slice, preserving initial order of equal elements.
This sort is stable (i.e., does not reorder equal elements) and O(n * log(n)) worst-case.
If the implementation of Ord
for T
does not implement a total order the resulting
order of elements in the slice is unspecified. All original elements will remain in the
slice and any possible modifications via interior mutability are observed in the input. Same
is true if the implementation of Ord
for T
panics.
When applicable, unstable sorting is preferred because it is generally faster than stable
sorting and it doesn’t allocate auxiliary memory. See
sort_unstable
. The exception are partially sorted slices, which
may be better served with slice::sort
.
Sorting types that only implement PartialOrd
such as f32
and f64
require
additional precautions. For example, f32::NAN != f32::NAN
, which doesn’t fulfill the
reflexivity requirement of Ord
. By using an alternative comparison function with
slice::sort_by
such as f32::total_cmp
or f64::total_cmp
that defines a total
order users can sort slices containing floating-point values. Alternatively, if all values
in the slice are guaranteed to be in a subset for which PartialOrd::partial_cmp
forms a
total order, it’s possible to sort the slice with sort_by(|a, b| a.partial_cmp(b).unwrap())
.
§Current implementation
The current implementation is based on driftsort by Orson Peters and Lukas Bergdoll, which combines the fast average case of quicksort with the fast worst case and partial run detection of mergesort, achieving linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the expected time to sort the data is O(n * log(k)).
The auxiliary memory allocation behavior depends on the input length. Short slices are
handled without allocation, medium sized slices allocate self.len()
and beyond that it
clamps at self.len() / 2
.
§Panics
May panic if the implementation of Ord
for T
does not implement a total order.
§Examples
let mut v = [4, -5, 1, -3, 2];
v.sort();
assert_eq!(v, [-5, -3, 1, 2, 4]);
1.0.0 · sourcepub fn sort_by<F>(&mut self, compare: F)
pub fn sort_by<F>(&mut self, compare: F)
Sorts the slice with a comparison function, preserving initial order of equal elements.
This sort is stable (i.e., does not reorder equal elements) and O(n * log(n)) worst-case.
If the comparison function compare
does not implement a total order the resulting order
of elements in the slice is unspecified. All original elements will remain in the slice and
any possible modifications via interior mutability are observed in the input. Same is true
if compare
panics.
For example |a, b| (a - b).cmp(a)
is a comparison function that is neither transitive nor
reflexive nor total, a < b < c < a
with a = 1, b = 2, c = 3
. For more information and
examples see the Ord
documentation.
§Current implementation
The current implementation is based on driftsort by Orson Peters and Lukas Bergdoll, which combines the fast average case of quicksort with the fast worst case and partial run detection of mergesort, achieving linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the expected time to sort the data is O(n * log(k)).
The auxiliary memory allocation behavior depends on the input length. Short slices are
handled without allocation, medium sized slices allocate self.len()
and beyond that it
clamps at self.len() / 2
.
§Panics
May panic if compare
does not implement a total order.
§Examples
let mut v = [4, -5, 1, -3, 2];
v.sort_by(|a, b| a.cmp(b));
assert_eq!(v, [-5, -3, 1, 2, 4]);
// reverse sorting
v.sort_by(|a, b| b.cmp(a));
assert_eq!(v, [4, 2, 1, -3, -5]);
1.7.0 · sourcepub fn sort_by_key<K, F>(&mut self, f: F)
pub fn sort_by_key<K, F>(&mut self, f: F)
Sorts the slice with a key extraction function, preserving initial order of equal elements.
This sort is stable (i.e., does not reorder equal elements) and O(m * n * log(n)) worst-case, where the key function is O(m).
If the implementation of Ord
for K
does not implement a total order the resulting
order of elements in the slice is unspecified. All original elements will remain in the
slice and any possible modifications via interior mutability are observed in the input. Same
is true if the implementation of Ord
for K
panics.
§Current implementation
The current implementation is based on driftsort by Orson Peters and Lukas Bergdoll, which combines the fast average case of quicksort with the fast worst case and partial run detection of mergesort, achieving linear time on fully sorted and reversed inputs. On inputs with k distinct elements, the expected time to sort the data is O(n * log(k)).
The auxiliary memory allocation behavior depends on the input length. Short slices are
handled without allocation, medium sized slices allocate self.len()
and beyond that it
clamps at self.len() / 2
.
§Panics
May panic if the implementation of Ord
for K
does not implement a total order.
§Examples
let mut v = [4i32, -5, 1, -3, 2];
v.sort_by_key(|k| k.abs());
assert_eq!(v, [1, 2, -3, 4, -5]);
1.34.0 · sourcepub fn sort_by_cached_key<K, F>(&mut self, f: F)
pub fn sort_by_cached_key<K, F>(&mut self, f: F)
Sorts the slice with a key extraction function, preserving initial order of equal elements.
This sort is stable (i.e., does not reorder equal elements) and O(m * n + n * log(n)) worst-case, where the key function is O(m).
During sorting, the key function is called at most once per element, by using temporary storage to remember the results of key evaluation. The order of calls to the key function is unspecified and may change in future versions of the standard library.
If the implementation of Ord
for K
does not implement a total order the resulting
order of elements in the slice is unspecified. All original elements will remain in the
slice and any possible modifications via interior mutability are observed in the input. Same
is true if the implementation of Ord
for K
panics.
For simple key functions (e.g., functions that are property accesses or basic operations),
sort_by_key
is likely to be faster.
§Current implementation
The current implementation is based on instruction-parallel-network sort by Lukas Bergdoll, which combines the fast average case of randomized quicksort with the fast worst case of heapsort, while achieving linear time on fully sorted and reversed inputs. And O(k * log(n)) where k is the number of distinct elements in the input. It leverages superscalar out-of-order execution capabilities commonly found in CPUs, to efficiently perform the operation.
In the worst case, the algorithm allocates temporary storage in a Vec<(K, usize)>
the
length of the slice.
§Panics
May panic if the implementation of Ord
for K
does not implement a total order.
§Examples
let mut v = [4i32, -5, 1, -3, 2, 10];
// Strings are sorted by lexicographical order.
v.sort_by_cached_key(|k| k.to_string());
assert_eq!(v, [-3, -5, 1, 10, 2, 4]);
1.0.0 · sourcepub fn to_vec(&self) -> Vec<T>where
T: Clone,
pub fn to_vec(&self) -> Vec<T>where
T: Clone,
Copies self
into a new Vec
.
§Examples
let s = [10, 40, 30];
let x = s.to_vec();
// Here, `s` and `x` can be modified independently.
sourcepub fn to_vec_in<A>(&self, alloc: A) -> Vec<T, A>
🔬This is a nightly-only experimental API. (allocator_api
)
pub fn to_vec_in<A>(&self, alloc: A) -> Vec<T, A>
allocator_api
)Copies self
into a new Vec
with an allocator.
§Examples
#![feature(allocator_api)]
use std::alloc::System;
let s = [10, 40, 30];
let x = s.to_vec_in(System);
// Here, `s` and `x` can be modified independently.
1.0.0 · sourcepub fn concat<Item>(&self) -> <[T] as Concat<Item>>::Output ⓘ
pub fn concat<Item>(&self) -> <[T] as Concat<Item>>::Output ⓘ
Flattens a slice of T
into a single value Self::Output
.
§Examples
assert_eq!(["hello", "world"].concat(), "helloworld");
assert_eq!([[1, 2], [3, 4]].concat(), [1, 2, 3, 4]);
1.3.0 · sourcepub fn join<Separator>(
&self,
sep: Separator,
) -> <[T] as Join<Separator>>::Output ⓘ
pub fn join<Separator>( &self, sep: Separator, ) -> <[T] as Join<Separator>>::Output ⓘ
Flattens a slice of T
into a single value Self::Output
, placing a
given separator between each.
§Examples
assert_eq!(["hello", "world"].join(" "), "hello world");
assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]);
assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]);
1.0.0 · sourcepub fn connect<Separator>(
&self,
sep: Separator,
) -> <[T] as Join<Separator>>::Output ⓘ
👎Deprecated since 1.3.0: renamed to join
pub fn connect<Separator>( &self, sep: Separator, ) -> <[T] as Join<Separator>>::Output ⓘ
Flattens a slice of T
into a single value Self::Output
, placing a
given separator between each.
§Examples
assert_eq!(["hello", "world"].connect(" "), "hello world");
assert_eq!([[1, 2], [3, 4]].connect(&0), [1, 2, 0, 3, 4]);
1.23.0 · sourcepub fn to_ascii_uppercase(&self) -> Vec<u8>
pub fn to_ascii_uppercase(&self) -> Vec<u8>
Returns a vector containing a copy of this slice where each byte is mapped to its ASCII upper case equivalent.
ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.
To uppercase the value in-place, use make_ascii_uppercase
.
1.23.0 · sourcepub fn to_ascii_lowercase(&self) -> Vec<u8>
pub fn to_ascii_lowercase(&self) -> Vec<u8>
Returns a vector containing a copy of this slice where each byte is mapped to its ASCII lower case equivalent.
ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.
To lowercase the value in-place, use make_ascii_lowercase
.
Trait Implementations§
§impl<H> ConditionallySend for RCHandle<H>where
H: NativeRefCountedBase,
impl<H> ConditionallySend for RCHandle<H>where
H: NativeRefCountedBase,
RCHandle<H>
is conditionally Send and can be sent to
another thread when its reference count is 1.
§impl<N> Flattenable for RCHandle<N>where
N: NativeFlattenable + NativeRefCountedBase,
impl<N> Flattenable for RCHandle<N>where
N: NativeFlattenable + NativeRefCountedBase,
§impl<N> From<&RCHandle<N>> for RCHandle<N>where
N: NativeRefCounted,
impl<N> From<&RCHandle<N>> for RCHandle<N>where
N: NativeRefCounted,
A reference counted handle is cheap to clone, so we do support a conversion from a reference to a ref counter to an owned handle.
§impl From<SkBlendMode> for RCHandle<SkBlender>
impl From<SkBlendMode> for RCHandle<SkBlender>
§fn from(mode: SkBlendMode) -> RCHandle<SkBlender>
fn from(mode: SkBlendMode) -> RCHandle<SkBlender>
§impl<N> PointerWrapper<N> for RCHandle<N>where
N: NativeRefCounted,
impl<N> PointerWrapper<N> for RCHandle<N>where
N: NativeRefCounted,
impl Send for RCHandle<SkBlender>
impl Send for RCHandle<SkColorFilter>
impl Send for RCHandle<SkColorSpace>
impl Send for RCHandle<SkColorTable>
impl Send for RCHandle<SkContourMeasure>
impl Send for RCHandle<SkData>
impl Send for RCHandle<SkDataTable>
impl Send for RCHandle<SkImage>
impl Send for RCHandle<SkImageFilter>
impl Send for RCHandle<SkMaskFilter>
impl Send for RCHandle<SkPathEffect>
impl Send for RCHandle<SkPicture>
impl Send for RCHandle<SkPixelRef>
impl Send for RCHandle<SkSVGDOM>
impl Send for RCHandle<SkShader>
impl Send for RCHandle<SkTextBlob>
impl Send for RCHandle<SkTypeface>
impl Send for RCHandle<SkVertices>
impl Send for RCHandle<skgpu_MutableTextureState>
impl Sync for RCHandle<SkBlender>
impl Sync for RCHandle<SkColorFilter>
impl Sync for RCHandle<SkColorSpace>
impl Sync for RCHandle<SkColorTable>
impl Sync for RCHandle<SkContourMeasure>
impl Sync for RCHandle<SkData>
impl Sync for RCHandle<SkDataTable>
impl Sync for RCHandle<SkImage>
impl Sync for RCHandle<SkImageFilter>
impl Sync for RCHandle<SkMaskFilter>
impl Sync for RCHandle<SkPathEffect>
impl Sync for RCHandle<SkPicture>
impl Sync for RCHandle<SkPixelRef>
impl Sync for RCHandle<SkSVGDOM>
impl Sync for RCHandle<SkShader>
impl Sync for RCHandle<SkTextBlob>
impl Sync for RCHandle<SkTypeface>
impl Sync for RCHandle<SkVertices>
impl Sync for RCHandle<skgpu_MutableTextureState>
Auto Trait Implementations§
impl<Native> Freeze for RCHandle<Native>
impl<Native> RefUnwindSafe for RCHandle<Native>where
Native: RefUnwindSafe,
impl<Native> !Send for RCHandle<Native>
impl<Native> !Sync for RCHandle<Native>
impl<Native> Unpin for RCHandle<Native>
impl<Native> UnwindSafe for RCHandle<Native>where
Native: RefUnwindSafe,
Blanket Implementations§
§impl<T> AnyEq for T
impl<T> AnyEq for T
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§unsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.