Struct RCHandle
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>
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).
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
Use filter_color4f()
pub fn filter_color4f(
&self,
color: impl Into<Color4f>,
src_color_space: Option<&RCHandle<SkColorSpace>>,
dst_color_space: Option<&RCHandle<SkColorSpace>>,
) -> Color4f
pub fn filter_color4f( &self, color: impl Into<Color4f>, src_color_space: Option<&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_linear() -> RCHandle<SkColorSpace>
pub fn new_srgb_linear() -> RCHandle<SkColorSpace>
Creates a color space with the sRGB primaries, but a linear (1.0) gamma.
pub fn new_icc(data: &[u8]) -> Option<RCHandle<SkColorSpace>>
pub fn new_icc(data: &[u8]) -> Option<RCHandle<SkColorSpace>>
Creates a ColorSpace from a parsed (skcms) ICC profile. Returns None if data is not
a valid ICC profile.
datathe ICC profile bytes
pub fn new_cicp(
primaries: SkNamedPrimaries_CicpId,
transfer_characteristics: SkNamedTransferFn_CicpId,
) -> Option<RCHandle<SkColorSpace>>
pub fn new_cicp( primaries: SkNamedPrimaries_CicpId, transfer_characteristics: SkNamedTransferFn_CicpId, ) -> Option<RCHandle<SkColorSpace>>
Creates a ColorSpace from code points specified in Rec. ITU-T H.273. Returns None for
an invalid or unsupported combination of code points.
primariesidentifies an entry in Rec. ITU-T H.273, Table 2transfer_characteristicsidentifies an entry in Rec. ITU-T H.273, Table 3
ColorSpace (and the underlying skcms_ICCProfile) only supports RGB color spaces and
therefore this function does not take a matrix_coefficients parameter; the caller is
expected to verify that matrix_coefficients is 0.
Narrow range images are extremely rare, so this function does not take a
video_full_range_flag; the caller is expected to verify that it is 1 (indicating a full
range image).
pub fn to_xyzd50_hash(&self) -> XYZD50Hash
pub fn to_xyzd50_hash(&self) -> XYZD50Hash
Returns a hash of the gamut transformation to XYZ D50. Allows for fast equality checking of gamuts, at the (very small) risk of collision.
pub fn with_linear_gamma(&self) -> RCHandle<SkColorSpace>
pub fn with_linear_gamma(&self) -> RCHandle<SkColorSpace>
Returns a color space with the same gamut as this one, but with a linear gamma.
pub fn with_srgb_gamma(&self) -> RCHandle<SkColorSpace>
pub fn with_srgb_gamma(&self) -> RCHandle<SkColorSpace>
Returns a color space with the same gamut as this one, but with the sRGB transfer function.
pub fn with_color_spin(&self) -> RCHandle<SkColorSpace>
pub fn with_color_spin(&self) -> RCHandle<SkColorSpace>
Returns a color space with the same transfer function as this one, but with the primary colors rotated. In other words, this produces a new color space that maps RGB to GBR (when applied to a source), and maps RGB to BRG (when applied to a destination).
This is used for testing, to construct color spaces that have severe and testable behavior.
pub fn is_srgb(&self) -> bool
pub fn is_srgb(&self) -> bool
Returns true if the color space is sRGB. Returns false otherwise.
This allows a little bit of tolerance, given that we might see small numerical error in some cases: converting ICC fixed point to float, converting white point to D50, rounding decisions on transfer function and matrix.
This does not consider a 2.2f exponential transfer function to be sRGB. While these functions are similar (and it is sometimes useful to consider them together), this function checks for logical equality.
pub fn deserialize(data: impl Into<RCHandle<SkData>>) -> RCHandle<SkColorSpace>
pub fn transfer_fn(&self) -> ColorSpaceTransferFn
pub fn inv_transfer_fn(&self) -> ColorSpaceTransferFn
pub fn transfer_fn_hash(&self) -> u32
pub fn hash(&self) -> u64
§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 pos_tan(&self, distance: f32) -> Option<(Point, Point)>
pub fn pos_tan(&self, distance: f32) -> Option<(Point, Point)>
Pins distance to 0 <= distance <= length(), then computes the corresponding
position and tangent.
distancedistance along the contour.
pub fn get_matrix(
&self,
distance: f32,
flags: impl Into<Option<MatrixFlags>>,
) -> Option<Matrix>
pub fn get_matrix( &self, distance: f32, flags: impl Into<Option<MatrixFlags>>, ) -> Option<Matrix>
Pins distance to 0 <= distance <= length(), then computes the corresponding
matrix (by calling Self::pos_tan()).
Returns None if there is no path, or a zero-length path was specified.
distancedistance along the contour.flagscontrols whether position, tangent, or both are computed.
pub fn segment(
&self,
start_d: f32,
stop_d: f32,
path_builder: &mut RefHandle<SkPathBuilder>,
start_with_move_to: bool,
) -> bool
👎Deprecated since 0.94.0: Use get_segment()
pub fn segment( &self, start_d: f32, stop_d: f32, path_builder: &mut RefHandle<SkPathBuilder>, start_with_move_to: bool, ) -> bool
Use get_segment()
Given a start and stop distance, appends the intervening segment(s) to path_builder.
If the segment is zero-length, returns false; otherwise returns true.
start_d and stop_d are pinned to legal values (0..length()). If
start_d > stop_d, returns false and leaves path_builder untouched.
Begins the segment with a move_to if start_with_move_to is true.
start_dstart distance along the contour.stop_dstop distance along the contour.path_builderdestination that receives the segment.start_with_move_towhether to begin withmove_to.
pub fn get_segment(
&self,
start_d: f32,
stop_d: f32,
path_builder: &mut RefHandle<SkPathBuilder>,
start_with_move_to: bool,
) -> bool
pub fn get_segment( &self, start_d: f32, stop_d: f32, path_builder: &mut RefHandle<SkPathBuilder>, start_with_move_to: bool, ) -> bool
Given a start and stop distance, appends the intervening segment(s) to path_builder.
If the segment is zero-length, returns false; otherwise returns true.
start_d and stop_d are pinned to legal values (0..length()). If
start_d > stop_d, returns false and leaves path_builder untouched.
Begins the segment with a move_to if start_with_move_to is true.
start_dstart distance along the contour.stop_dstop distance along the contour.path_builderdestination that receives the segment.start_with_move_towhether to begin withmove_to.
pub fn verbs(&self) -> ForwardVerbIterator<'_> ⓘ
pub fn verbs(&self) -> ForwardVerbIterator<'_> ⓘ
Returns an iterator over measurement data for the contour’s verbs.
§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>
Returns data that shares a subset of this data’s storage without copying it.
Returns None when offset + length exceeds this data’s size.
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 fn new_with_owner<T>(owner: T) -> RCHandle<SkData>
pub fn new_with_owner<T>(owner: T) -> RCHandle<SkData>
Constructs Data that references the bytes of owner without copying them.
owner is moved to the heap and kept alive until the last reference to the returned
Data (including references held internally by Skia) is released. It is then dropped,
possibly on a different thread.
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 at_size(&self, index: usize) -> usize
pub fn at_size(&self, index: usize) -> usize
Returns the size of the index’th entry in the table. The caller must ensure that index
is valid for this table.
indexentry index
pub fn at(&self, index: usize) -> &[u8] ⓘ
pub fn at(&self, index: usize) -> &[u8] ⓘ
Returns the data of the index’th entry in the table. The caller must ensure that index
is valid for this table.
indexentry index
pub unsafe fn at_t<T>(&self, index: usize) -> &[T]where
T: Copy,
pub fn at_str(&self, index: usize) -> &CStr
pub fn at_str(&self, index: usize) -> &CStr
Returns the index’th entry as a c-string, and assumes that the trailing null byte had
been copied into the table as well.
indexentry index
pub fn from_slices(slices: &[&[u8]]) -> RCHandle<SkDataTable>
pub fn from_slices(slices: &[&[u8]]) -> RCHandle<SkDataTable>
Returns a new table that contains a copy of the data stored in each slice.
slicesslices to copy into the table
pub fn from_slice<T>(slice: &[T]) -> RCHandle<SkDataTable>where
T: Copy,
pub fn from_slice<T>(slice: &[T]) -> RCHandle<SkDataTable>where
T: Copy,
Returns a new table that contains a copy of the data in slice.
slicecontiguous array of data for all elements to be copied
pub fn iter(&self) -> Iter<'_> ⓘ
§impl RCHandle<SkDrawable>
impl RCHandle<SkDrawable>
pub fn draw(&mut self, canvas: &Canvas, matrix: Option<&Matrix>)
pub fn draw(&mut self, canvas: &Canvas, matrix: Option<&Matrix>)
Draws into the specified content. The drawing sequence will be balanced upon return (i.e.
the save level on the canvas will match what it was when draw was called, and the current
matrix and clip settings will not be changed).
canvascanvas to draw intomatrixoptional matrix to apply
pub fn draw_at(&mut self, canvas: &Canvas, point: impl Into<Point>)
pub fn draw_at(&mut self, canvas: &Canvas, point: impl Into<Point>)
Draws into the specified content at the given point.
canvascanvas to draw intopointpoint to draw at
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 snap_gpu_draw_handler( &mut self, api: GrBackendApi, matrix: &Matrix, clip_bounds: impl Into<IRect>, buffer_info: &Handle<SkImageInfo>, ) -> Option<RefHandle<SkDrawable_GpuDrawHandler>>
Snaps off a gpu_draw_handler::GPUDrawHandler to represent the state of the drawable at
the time the snap is called. This is used for executing GPU backend specific draws
intermixed with normal Skia GPU draws. The GPU API, which will be used for the draw, as well
as the full matrix, device clip bounds and image info of the target buffer are passed in as
inputs.
apiGPU backend APImatrixfull matrixclip_boundsdevice clip boundsbuffer_infoimage info of the target buffer
pub fn make_picture_snapshot(&mut self) -> RCHandle<SkPicture>
pub fn make_picture_snapshot(&mut self) -> RCHandle<SkPicture>
Returns a Picture with the contents of this drawable.
pub fn generation_id(&mut self) -> u32
pub fn generation_id(&mut self) -> u32
Returns a unique value for this instance. If two calls to this return the same value, it is
presumed that calling the Self::draw() method will render the same thing as well.
Subclasses that change their state should call Self::notify_drawing_changed() to ensure
that a new value will be returned the next time it is called.
pub fn bounds(&mut self) -> Rect
pub fn bounds(&mut self) -> Rect
Returns the (conservative) bounds of what the drawable will draw. If the drawable can change what it draws (e.g. animation or in response to some external change), then this must return a bounds that is always valid for all possible states.
pub fn approximate_bytes_used(&mut self) -> usize
pub fn approximate_bytes_used(&mut self) -> usize
Returns approximately how many bytes would be freed if this drawable is destroyed. The base implementation returns 0 to indicate that this is unknown.
pub fn notify_drawing_changed(&mut self)
pub fn notify_drawing_changed(&mut self)
Calling this invalidates the previous generation ID, and causes a new one to be computed the
next time Self::generation_id() is called. Typically this is called by the object itself,
in response to its internal state changing.
§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, 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 empty() -> RCHandle<SkFontMgr>
Returns an empty font manager without any typeface dependencies.
pub fn custom_empty() -> Option<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> + use<'_>
pub fn new_styleset(&self, index: usize) -> RCHandle<SkFontStyleSet>
Use new_style_set
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( &self, family_name: impl AsRef<str>, ) -> RCHandle<SkFontStyleSet>
Will return an empty set if the name is not found.
It is possible that this will return a style set not accessible from
Self::new_style_set() due to hidden or auto-activated fonts.
pub fn match_family_style(
&self,
family_name: impl AsRef<str>,
style: FontStyle,
) -> Option<RCHandle<SkTypeface>>
pub fn match_family_style( &self, family_name: impl AsRef<str>, style: FontStyle, ) -> Option<RCHandle<SkTypeface>>
Find the closest matching typeface to the specified family name and style and return a ref
to it. Returns None if no ‘good’ match is found.
It is possible that this will return a style set not accessible from
Self::new_style_set() or Self::match_family() due to hidden or auto-activated fonts.
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_family_style_character( &self, family_name: impl AsRef<str>, style: FontStyle, bcp_47: &[&str], character: i32, ) -> Option<RCHandle<SkTypeface>>
Use the system fallback to find a typeface for the given character.
Note that bcp_47 is a combination of ISO 639, 15924, and 3166-1 codes,
so it is fine to just pass a ISO 639 here.
Returns None if no family can be found for the character
in the system fallback.
bcp_47[0] is the least significant fallback, bcp_47[bcp_47.len() - 1] is the most
significant. If no specified bcp_47 codes match, any font with the requested character
will be matched.
pub fn match_request(
&self,
request: &Request<'_>,
) -> Option<RCHandle<SkTypeface>>
pub fn match_request( &self, request: &Request<'_>, ) -> Option<RCHandle<SkTypeface>>
The family name must strongly match, everything else is tie breakers.
pub fn fallback(&self, request: &Request<'_>) -> Option<RCHandle<SkTypeface>>
pub fn fallback(&self, request: &Request<'_>) -> Option<RCHandle<SkTypeface>>
The first cmap entry must match. Then matched by Request::bcp_47, then
Request::family_name, then Request::model (italic, slant, width, weight), with
synthetics allowed or not.
pub fn fallback_request( &self, request: &Request<'_>, ) -> Option<RCHandle<SkTypeface>>
pub fn match_face_style( &self, _typeface: impl AsRef<RCHandle<SkTypeface>>, _style: FontStyle, ) -> !
Removed without replacement
pub fn new_from_data(
&self,
data: RCHandle<SkData>,
ttc_index: impl Into<Option<u32>>,
) -> Option<RCHandle<SkTypeface>>
pub fn new_from_data( &self, data: RCHandle<SkData>, ttc_index: impl Into<Option<u32>>, ) -> Option<RCHandle<SkTypeface>>
Create a typeface for the specified data and TTC index (pass None for none), or None
if the data is not recognized.
pub fn new_from_bytes(
&self,
bytes: &[u8],
ttc_index: impl Into<Option<u32>>,
) -> Option<RCHandle<SkTypeface>>
pub fn new_from_bytes( &self, bytes: &[u8], ttc_index: impl Into<Option<u32>>, ) -> Option<RCHandle<SkTypeface>>
Create a typeface for the specified bytes and TTC index (pass None for none), or None
if the bytes are not recognized.
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>>
use images::raster_from_data()
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 None, and contains enough data for Image.
infocontains width, height,AlphaType,ColorType,ColorSpacepixelsaddress or pixel storagerowBytessize of pixel row or larger
Returns: Image sharing pixels, or None
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>>
use images::raster_from_bitmap()
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.
bitmapImageInfo, row bytes, and pixels
Returns: created Image, or None
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>>
use images::deferred_from_generator()
Creates Image from data returned by image_generator. Generated data is owned by Image and
may not be shared or accessed.
Image is returned if generator data is valid. Valid data parameters vary by type of data
and platform.
imageGenerator may wrap Picture data, codec data, or custom data.
image_generatorstock or custom routines to retrieveImage
Returns: created Image, or None
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 None.
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.
encodedthe encoded data
Returns: created Image, or None
Example (C++): https://fiddle.skia.org/c/@Image_DeferredFromEncodedData
pub fn decode_to_raster(_encoded: &[u8], _subset: impl Into<Option<IRect>>) -> !
Removed without replacement
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>>
use images::raster_from_compressed_texture_data()
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.
datacompressed data to store inImagewidthwidth of fullImageheightheight of fullImagetytype of compression used
Returns: created Image, or None
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>>
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>>
👎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>>
use images::deferred_from_picture()
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.
picturestream of drawing commandsdimensionswidth and heightmatrixMatrixto rotate, scale, translate, and so on; may beNonepaintPaintto apply transparency, filtering, and so on; may beNonebitDepth8-bit integer or 16-bit float: per componentcolor_spacerange of colors; may beNonepropsprops to use when rasterizing the picture
Returns: created Image, or None
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.
contextGPU contextbackend_textureTexture residing on GPUoriginOrigin ofbackend_texturecolor_typeColor type of the resulting imagealpha_typeAlpha type of the resulting imagecolor_spaceThis 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_spaceshould be supplied (e.g.,ColorSpace::new_srgb_linear())). If the format of the backend texture is linear, then thecolor_spaceshould include a description of the transfer function as well (e.g.,ColorSpace::MakeSRGB).texture_release_procFunction called when texture can be releasedrelease_contextState passed totexture_release_proc
Returns: Created Image, or None
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 { [Image::width()], [Image::height()] }.
Returns: integral size of Image::width() and Image::height()
pub fn bounds(&self) -> IRect
pub fn bounds(&self) -> IRect
Returns IRect { 0, 0, [Image::width()], [Image::height()] }.
Returns: integral rectangle from origin to Image::width() and Image::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.
Example (C++): https://fiddle.skia.org/c/@Image_colorType
pub fn color_space(&self) -> Option<RCHandle<SkColorSpace>>
pub fn color_space(&self) -> Option<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
Example (C++): https://fiddle.skia.org/c/@Image_colorSpace Example (C++): https://fiddle.skia.org/c/@Image_refColorSpace
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
Example (C++): https://fiddle.skia.org/c/@Image_isAlphaOnly
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
Unpremulare not automatically premultiplied. - Bicubic filtering is not supported. If
SamplingOptions::use_cubicistrue, 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.
pixmapstorage for pixel state if pixels are readable; otherwise, ignored
Returns: true if Image has direct access to pixels
Example (C++): https://fiddle.skia.org/c/@Image_peekPixels
pub fn is_texture_backed(&self) -> bool
pub fn is_texture_backed(&self) -> bool
Returns true if the contents of Image was created on or uploaded to GPU memory,
and is available as a GPU texture.
Returns: true if Image is a GPU texture
Example (C++): https://fiddle.skia.org/c/@Image_isTextureBacked
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, recorder: Option<&mut dyn Recorder>) -> bool
pub fn is_valid(&self, recorder: Option<&mut dyn Recorder>) -> bool
Returns true if Image can be drawn on either raster surface or GPU surface.
If recorder is None, tests if Image draws on raster surface;
otherwise, tests if Image draws on the associated GPU surface.
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.
contextGPU context
Returns: true if Image can be drawn
Example (C++): https://fiddle.skia.org/c/@Image_isValid
pub fn make_scaled(
&self,
info: &Handle<SkImageInfo>,
scaling: impl Into<SamplingOptions>,
) -> Option<RCHandle<SkImage>>
pub fn make_scaled( &self, info: &Handle<SkImageInfo>, scaling: impl Into<SamplingOptions>, ) -> Option<RCHandle<SkImage>>
Create a new image by copying this image and scaling to fit the ImageInfo’s dimensions
and converting the pixels into the ImageInfo’s crate::ColorInfo.
This is done retaining the domain (backend) of the image (e.g. gpu, raster).
Returns None if the requested crate::ColorInfo is not supported, its dimensions are out
of range.
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()).
Graphite has deprecated this API in favor of the equivalent asynchronous API on
skgpu::graphite::Context (with an optional explicit synchronization).
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()equalsNonedst_row_bytesis less thandst_info.min_row_bytes()crate::PixelRefisNone
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.
contextthegpu::DirectContextin play, if it existsdst_infodestination width, height,ColorType,AlphaType,ColorSpacedst_pixelsdestination pixel storagedst_row_bytesdestination row lengthsrc_xcolumn index whose absolute value is less thanwidth()src_yrow index whose absolute value is less thanheight()caching_hintwhether the pixels should be cached locally
Returns: true if pixels are copied to dst_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()).
Graphite has deprecated this API in favor of the equivalent asynchronous API on
skgpu::graphite::Context (with an optional explicit synchronization).
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_bytesis less thanImageInfo::min_row_bytes crate::PixelRefisNone
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.
contextthegpu::DirectContextin play, if it existsdstdestinationPixmap:ImageInfo, pixels, row bytessrc_xcolumn index whose absolute value is less thanwidth()src_yrow index whose absolute value is less thanheight()caching_hintwhether 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 async_rescale_and_read_pixels(
&self,
info: &Handle<SkImageInfo>,
src_rect: impl AsRef<IRect>,
rescale_gamma: SkImage_RescaleGamma,
rescale_mode: SkImage_RescaleMode,
callback: impl FnOnce(Option<RefHandle<SkImage_AsyncReadResult>>) + Send + 'static,
)
pub fn async_rescale_and_read_pixels( &self, info: &Handle<SkImageInfo>, src_rect: impl AsRef<IRect>, rescale_gamma: SkImage_RescaleGamma, rescale_mode: SkImage_RescaleMode, callback: impl FnOnce(Option<RefHandle<SkImage_AsyncReadResult>>) + Send + 'static, )
Makes image pixel data available to caller, possibly asynchronously. It can also rescale the image pixels.
Currently asynchronous reads are only supported in the Ganesh GPU backend and only when the underlying 3D API supports transfer buffers and CPU/GPU synchronization primitives. In all other cases this operates synchronously.
For the Graphite backend this API has been deprecated in favor of the equivalent API
on skgpu::graphite::Context.
Data is read from the source sub-rectangle, is optionally converted to a linear gamma, is
rescaled to the size indicated by info, is then converted to the color space, color type,
and alpha type of info. A src_rect that is not contained by the bounds of the image
causes failure.
When the pixel data is ready the caller’s callback is called with a
AsyncReadResult containing pixel data in the requested color type, alpha type, and color
space. The AsyncReadResult will have AsyncReadResult::count() == 1. Upon failure the
callback is called with None for AsyncReadResult. For a GPU image this flushes work but
a submit must occur to guarantee a finite time before the callback is called.
The data is valid for the lifetime of AsyncReadResult with the exception that if the
Image is GPU-backed the data is immediately invalidated if the context is abandoned or
destroyed.
callback is called exactly once: before this function returns, from
crate::gpu::DirectContext::check_async_work_completion(), or when the context is
dropped. A panic in callback aborts the process. callback must be Send because a
GPU-backed Image calls back on the thread of its context.
infoinfo of the requested pixelssrc_rectsubrectangle of image to readrescale_gammacontrols whether rescaling is done in the image’s gamma or whether the source data is transformed to a linear gamma before rescaling.rescale_modecontrols the technique (and cost) of the rescalingcallbackfunction to call with result of the read
pub fn async_rescale_and_read_pixels_yuv420(
&self,
yuv_color_space: SkYUVColorSpace,
dst_color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
src_rect: impl AsRef<IRect>,
dst_size: impl Into<ISize>,
rescale_gamma: SkImage_RescaleGamma,
rescale_mode: SkImage_RescaleMode,
callback: impl FnOnce(Option<RefHandle<SkImage_AsyncReadResult>>) + Send + 'static,
)
pub fn async_rescale_and_read_pixels_yuv420( &self, yuv_color_space: SkYUVColorSpace, dst_color_space: impl Into<Option<RCHandle<SkColorSpace>>>, src_rect: impl AsRef<IRect>, dst_size: impl Into<ISize>, rescale_gamma: SkImage_RescaleGamma, rescale_mode: SkImage_RescaleMode, callback: impl FnOnce(Option<RefHandle<SkImage_AsyncReadResult>>) + Send + 'static, )
Similar to Self::async_rescale_and_read_pixels() but performs an additional conversion
to YUV. The RGB->YUV conversion is controlled by yuv_color_space. The YUV data is returned
as three planes ordered y, u, v. The u and v planes are half the width and height of the
resized rectangle. The y, u, and v values are single bytes. Currently this fails if
dst_size width and height are not even. A src_rect that is not contained by the bounds
of the image causes failure.
When the pixel data is ready the caller’s callback is called with a
AsyncReadResult containing the planar data. The AsyncReadResult will have
AsyncReadResult::count() == 3. Upon failure the callback is called with None for
AsyncReadResult. For a GPU image this flushes work but a submit must occur to guarantee
a finite time before the callback is called.
The data is valid for the lifetime of AsyncReadResult with the exception that if the
Image is GPU-backed the data is immediately invalidated if the context is abandoned or
destroyed.
callback is called exactly once: before this function returns, from
crate::gpu::DirectContext::check_async_work_completion(), or when the context is
dropped. A panic in callback aborts the process. callback must be Send because a
GPU-backed Image calls back on the thread of its context. Raster and Graphite images do
not support this read and call back with None.
yuv_color_spaceThe transformation from RGB to YUV. Applied to the resized image after it is converted todst_color_space.dst_color_spaceThe color space to convert the resized image to, after rescaling.src_rectThe portion of the image to rescale and convert to YUV planes.dst_sizeThe size to rescalesrc_recttorescale_gammacontrols whether rescaling is done in the image’s gamma or whether the source data is transformed to a linear gamma before rescaling.rescale_modecontrols the technique (and cost) of the rescalingcallbackfunction to call with the planar read result
pub fn async_rescale_and_read_pixels_yuva420(
&self,
yuv_color_space: SkYUVColorSpace,
dst_color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
src_rect: impl AsRef<IRect>,
dst_size: impl Into<ISize>,
rescale_gamma: SkImage_RescaleGamma,
rescale_mode: SkImage_RescaleMode,
callback: impl FnOnce(Option<RefHandle<SkImage_AsyncReadResult>>) + Send + 'static,
)
pub fn async_rescale_and_read_pixels_yuva420( &self, yuv_color_space: SkYUVColorSpace, dst_color_space: impl Into<Option<RCHandle<SkColorSpace>>>, src_rect: impl AsRef<IRect>, dst_size: impl Into<ISize>, rescale_gamma: SkImage_RescaleGamma, rescale_mode: SkImage_RescaleMode, callback: impl FnOnce(Option<RefHandle<SkImage_AsyncReadResult>>) + Send + 'static, )
Identical to Self::async_rescale_and_read_pixels_yuv420() but a fourth plane is returned
in the AsyncReadResult passed to callback. The fourth plane contains the alpha chanel
at the same full resolution as the Y plane.
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.
Returns: true if pixels are scaled to fit dst
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>>
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>>
👎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>>
Support for encoding GPU backed images without a context was removed, use encode_to_data_with_context instead
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.
encoded_image_formatone of:EncodedImageFormat::JPEG,EncodedImageFormat::PNG,EncodedImageFormat::WEBPqualityencoder specific metric with 100 equaling best
Returns: encoded Image, or None
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
Example (C++): https://fiddle.skia.org/c/@Image_refEncodedData
pub fn make_subset(
&self,
recorder: Option<&mut dyn Recorder>,
subset: impl AsRef<IRect>,
required_properties: RequiredProperties,
) -> Option<RCHandle<SkImage>>
pub fn make_subset( &self, recorder: Option<&mut dyn Recorder>, subset: impl AsRef<IRect>, required_properties: RequiredProperties, ) -> 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
- 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.
recorder- the recorder of the source image (Noneis ok if the source image was texture-backed).subset- bounds of returnedImagerequired_properties- properties the returnedImagemust possess (e.g. mipmaps)
Returns: the subsetted image, or None
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_contextthegpu::DirectContextin play, if it existsmipmappedwhether createdImagetexture must allocate mip map levelsbudgetedwhether to count a newly created texture for the returned image counts against the context’s budget.
Returns: created Image, or None
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>>
use make_non_texture_image()
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 (C++): 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>>
use make_raster_image()
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
Example (C++): https://fiddle.skia.org/c/@Image_makeRasterImage
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)>
use images::make_with_filter()
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.
contextthegpu::RecordingContextin play - if it existsfilterhowImageis sampled when transformedsubsetbounds ofImageprocessed by filterclip_boundsexpected bounds of filteredImageout_subsetstorage for returnedImageboundsoffsetstorage for returnedImagetranslation
Returns: filtered Image, or None
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 (C++): https://fiddle.skia.org/c/@Image_isLazyGenerated_a Example (C++): https://fiddle.skia.org/c/@Image_isLazyGenerated_b
pub fn make_color_space(
&self,
recorder: Option<&mut dyn Recorder>,
color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
required_properties: RequiredProperties,
) -> Option<RCHandle<SkImage>>
pub fn make_color_space( &self, recorder: Option<&mut dyn Recorder>, color_space: impl Into<Option<RCHandle<SkColorSpace>>>, required_properties: RequiredProperties, ) -> 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 graphite-backed, the recorder parameter is required.
target_color_space-ColorSpacedescribing color range of returnedImagerecorder- The Recorder in which to create the new imagerequired_properties- properties the returnedImagemust possess (e.g. mipmaps)
Returns: created Image in target ColorSpace
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>>
use get_input()
pub fn get_input(&self, i: usize) -> Option<RCHandle<SkImageFilter>>
pub fn inputs( &self, ) -> impl Iterator<Item = Option<RCHandle<SkImageFilter>>> + use<'_>
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.
styleTheBlurStyleto usesigmaStandard deviation of the Gaussian blur to apply. Must be > 0.respect_ctmiftruethe blur’s sigma is modified by thectm.
Returns the new blur mask filter
§impl RCHandle<SkMeshSpecification>
impl RCHandle<SkMeshSpecification>
pub const MAX_STRIDE: usize = sb::SkMeshSpecification_kMaxStride
pub const MAX_STRIDE: usize = sb::SkMeshSpecification_kMaxStride
The maximum vertex stride. Enforced when creating a specification.
pub const MAX_ATTRIBUTES: usize = sb::SkMeshSpecification_kMaxAttributes
pub const MAX_ATTRIBUTES: usize = sb::SkMeshSpecification_kMaxAttributes
The maximum number of attributes. Enforced when creating a specification.
pub const STRIDE_ALIGNMENT: usize = sb::SkMeshSpecification_kStrideAlignment
pub const STRIDE_ALIGNMENT: usize = sb::SkMeshSpecification_kStrideAlignment
The alignment of the vertex stride. Enforced when creating a specification.
pub const OFFSET_ALIGNMENT: usize = sb::SkMeshSpecification_kOffsetAlignment
pub const OFFSET_ALIGNMENT: usize = sb::SkMeshSpecification_kOffsetAlignment
The alignment of attribute offsets. Enforced when creating a specification.
pub const MAX_VARYINGS: usize = sb::SkMeshSpecification_kMaxVaryings
pub const MAX_VARYINGS: usize = sb::SkMeshSpecification_kMaxVaryings
The maximum number of varyings. Enforced when creating a specification.
pub fn make(
attributes: &[Handle<SkMeshSpecification_Attribute>],
vertex_stride: usize,
varyings: &[Handle<SkMeshSpecification_Varying>],
vs: impl AsRef<str>,
fs: impl AsRef<str>,
) -> Result<RCHandle<SkMeshSpecification>, String>
pub fn make( attributes: &[Handle<SkMeshSpecification_Attribute>], vertex_stride: usize, varyings: &[Handle<SkMeshSpecification_Varying>], vs: impl AsRef<str>, fs: impl AsRef<str>, ) -> Result<RCHandle<SkMeshSpecification>, String>
If successful the return is a specification. Otherwise, it is a non-empty error string.
The color produced by fs (if any) is sRGB and premultiplied.
attributesThe vertex attributes that will be consumed byvs. Attributes need not be tightly packed but attribute offsets must be aligned toSelf::OFFSET_ALIGNMENTand offset + size may not be greater thanvertex_stride. At least one attribute is required.vertex_strideThe offset between successive attribute values. This must be aligned toSelf::STRIDE_ALIGNMENT.varyingsThe varyings that will be written byvsand read byfs. This may be empty.vsThe vertex shader code that computes a vertex position and the varyings from the attributes.fsThe fragment code that computes a local coordinate and optionally a color from the varyings. The local coordinate is used to samplecrate::Shader.
pub fn make_with_color_space(
attributes: &[Handle<SkMeshSpecification_Attribute>],
vertex_stride: usize,
varyings: &[Handle<SkMeshSpecification_Varying>],
vs: impl AsRef<str>,
fs: impl AsRef<str>,
color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
alpha_type: impl Into<Option<SkAlphaType>>,
) -> Result<RCHandle<SkMeshSpecification>, String>
pub fn make_with_color_space( attributes: &[Handle<SkMeshSpecification_Attribute>], vertex_stride: usize, varyings: &[Handle<SkMeshSpecification_Varying>], vs: impl AsRef<str>, fs: impl AsRef<str>, color_space: impl Into<Option<RCHandle<SkColorSpace>>>, alpha_type: impl Into<Option<SkAlphaType>>, ) -> Result<RCHandle<SkMeshSpecification>, String>
Like Self::make(), with the color space and alpha type of the color produced by fs.
color_spaceThe colorspace of the color produced byfs. Ignored iffs’s main() function does not have a color out param. If it has one,Noneis an error.alpha_typeThe alpha type of the color produced byfs. Ignored iffs’s main() function does not have a color out param. Cannot beAlphaType::Unknown.NoneusesAlphaType::Premul.
pub fn attributes(&self) -> &[Handle<SkMeshSpecification_Attribute>]
pub fn uniform_size(&self) -> usize
pub fn uniform_size(&self) -> usize
Combined size of all ‘uniform’ variables. When creating a Mesh with this specification
provide a Data of this size, containing values for all of those variables. Use
Self::uniforms() to get the offset of each uniform within the Data.
pub fn uniforms(&self) -> &[Handle<SkRuntimeEffect_Uniform>]
pub fn uniforms(&self) -> &[Handle<SkRuntimeEffect_Uniform>]
Provides info about individual uniforms including the offset into a Data where each
uniform value should be placed.
pub fn children(&self) -> &[Handle<SkRuntimeEffect_Child>]
pub fn children(&self) -> &[Handle<SkRuntimeEffect_Child>]
Provides basic info about individual children: names, indices and runtime effect type.
pub fn find_child(
&self,
name: impl AsRef<str>,
) -> Option<&Handle<SkRuntimeEffect_Child>>
pub fn find_child( &self, name: impl AsRef<str>, ) -> Option<&Handle<SkRuntimeEffect_Child>>
Returns the named child’s description, or None if not found.
pub fn find_uniform(
&self,
name: impl AsRef<str>,
) -> Option<&Handle<SkRuntimeEffect_Uniform>>
pub fn find_uniform( &self, name: impl AsRef<str>, ) -> Option<&Handle<SkRuntimeEffect_Uniform>>
Returns the named uniform variable’s description, or None if not found.
pub fn find_attribute(
&self,
name: impl AsRef<str>,
) -> Option<&Handle<SkMeshSpecification_Attribute>>
pub fn find_attribute( &self, name: impl AsRef<str>, ) -> Option<&Handle<SkMeshSpecification_Attribute>>
Returns the named attribute, or None if not found.
pub fn find_varying(
&self,
name: impl AsRef<str>,
) -> Option<&Handle<SkMeshSpecification_Varying>>
pub fn find_varying( &self, name: impl AsRef<str>, ) -> Option<&Handle<SkMeshSpecification_Varying>>
Returns the named varying, or None if not found.
pub fn stride(&self) -> usize
pub fn color_space(&self) -> Option<RCHandle<SkColorSpace>>
pub fn color_space(&self) -> Option<RCHandle<SkColorSpace>>
The color space of the color produced by the fragment program, None if it produces none.
§impl RCHandle<SkMesh_IndexBuffer>
impl RCHandle<SkMesh_IndexBuffer>
pub fn update<'a>(
&self,
context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>,
data: &[u8],
offset: usize,
) -> bool
pub fn update<'a>( &self, context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>, data: &[u8], offset: usize, ) -> bool
Modifies the data in the IndexBuffer by copying data into the buffer at offset.
Fails if offset + data.len() > self.size() or if either offset or data.len() is not
aligned to 4 bytes. The gpu::DirectContext must match that used to create the buffer.
We take it as a parameter to emphasize that the context must be used to update the data
and thus the context must be valid for the current thread.
A CPU-backed buffer is updated with None and fails if a context is passed.
The buffer is shared: every Mesh and clone that holds it sees the update.
§impl RCHandle<SkMesh_VertexBuffer>
impl RCHandle<SkMesh_VertexBuffer>
pub fn update<'a>(
&self,
context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>,
data: &[u8],
offset: usize,
) -> bool
pub fn update<'a>( &self, context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>, data: &[u8], offset: usize, ) -> bool
Modifies the data in the VertexBuffer by copying data into the buffer at offset.
Fails if offset + data.len() > self.size() or if either offset or data.len() is not
aligned to 4 bytes. The gpu::DirectContext must match that used to create the buffer.
We take it as a parameter to emphasize that the context must be used to update the data
and thus the context must be valid for the current thread.
A CPU-backed buffer is updated with None and fails if a context is passed.
The buffer is shared: every Mesh and clone that holds it sees the update.
§impl RCHandle<SkPathEffect>
impl RCHandle<SkPathEffect>
pub fn sum(
first: impl Into<RCHandle<SkPathEffect>>,
second: impl Into<RCHandle<SkPathEffect>>,
) -> RCHandle<SkPathEffect>
pub fn sum( first: impl Into<RCHandle<SkPathEffect>>, second: impl Into<RCHandle<SkPathEffect>>, ) -> RCHandle<SkPathEffect>
Returns a path effect that applies each effect (first and second) to the original path,
and returns a path with the sum of these.
result = first(path) + second(path)
firstfirst effectsecondsecond effect
pub fn compose(
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>
Returns a path effect that applies the inner effect to the path, and then applies the outer effect to the result of the inner’s.
result = outer(inner(path))
firstouter effectsecondinner effect
pub fn filter_path(
&self,
src: &Handle<SkPath>,
stroke_rec: &Handle<SkStrokeRec>,
cull_rect: impl AsRef<Rect>,
) -> Option<(RefHandle<SkPathBuilder>, Handle<SkStrokeRec>)>
pub fn filter_path( &self, src: &Handle<SkPath>, stroke_rec: &Handle<SkStrokeRec>, cull_rect: impl AsRef<Rect>, ) -> Option<(RefHandle<SkPathBuilder>, Handle<SkStrokeRec>)>
Given a src path (input) and a stroke-rec (input and output), applies this effect to the
src path, returning the new path in dst, and returns true. If this effect cannot be
applied, returns false and ignores dst and the stroke-rec.
The stroke-rec specifies the initial request for stroking (if any). The effect can treat
this as input only, or it can choose to change the rec as well. For example, the effect can
decide to change the stroke’s width or join, or the effect can change the rec from stroke to
fill (or fill to stroke) in addition to returning a new (dst) path.
If this method returns true, the caller will apply (as needed) the resulting stroke-rec to
dst and then draw.
srcsource pathstroke_recstroke recordcull_rectcull rectangle
pub fn filter_path_inplace(
&self,
dst: &mut RefHandle<SkPathBuilder>,
src: &Handle<SkPath>,
stroke_rec: &mut Handle<SkStrokeRec>,
cull_rect: impl AsRef<Rect>,
) -> bool
pub fn filter_path_inplace( &self, dst: &mut RefHandle<SkPathBuilder>, src: &Handle<SkPath>, stroke_rec: &mut Handle<SkStrokeRec>, cull_rect: impl AsRef<Rect>, ) -> bool
Applies this effect to the src path, returning the new path in dst. See
Self::filter_path() for the full contract.
dstdestination path buildersrcsource pathstroke_recstroke recordcull_rectcull rectangle
pub fn filter_path_inplace_with_matrix(
&self,
dst: &mut RefHandle<SkPathBuilder>,
src: &Handle<SkPath>,
stroke_rec: &mut Handle<SkStrokeRec>,
cull_rect: impl AsRef<Rect>,
ctm: &Matrix,
) -> bool
pub fn filter_path_inplace_with_matrix( &self, dst: &mut RefHandle<SkPathBuilder>, src: &Handle<SkPath>, stroke_rec: &mut Handle<SkStrokeRec>, cull_rect: impl AsRef<Rect>, ctm: &Matrix, ) -> bool
Applies this effect to the src path, returning the new path in dst. See
Self::filter_path() for the full contract.
dstdestination path buildersrcsource pathstroke_recstroke recordcull_rectcull rectanglectmcurrent transformation matrix
§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 playback(&self, canvas: &Canvas)
Replays the drawing commands on the specified canvas. In the case that the commands are
recorded, each command in the Picture is sent separately to canvas.
To add a single command to draw Picture to recording canvas, call
crate::Canvas::draw_picture() instead.
canvasreceiver of drawing commands
Example (C++): https://fiddle.skia.org/c/@Picture_playback
pub fn cull_rect(&self) -> Rect
pub fn cull_rect(&self) -> Rect
Returns cull Rect for this picture, passed in when Picture was created. Returned
Rect does not specify clipping Rect for Picture; cull is hint of Picture
bounds.
Picture is free to discard recorded drawing commands that fall outside cull.
Returns: bounds passed when Picture was created
Example (C++): https://fiddle.skia.org/c/@Picture_cullRect
pub fn unique_id(&self) -> u32
pub fn serialize(&self) -> RCHandle<SkData>
pub fn serialize(&self) -> RCHandle<SkData>
Returns storage containing Data describing Picture, using optional custom encoders.
Returns: storage containing serialized Picture
Example (C++): https://fiddle.skia.org/c/@Picture_serialize Example (C++): https://fiddle.skia.org/c/@Picture_serialize_2
pub fn new_placeholder(cull: impl AsRef<Rect>) -> RCHandle<SkPicture>
pub fn new_placeholder(cull: impl AsRef<Rect>) -> RCHandle<SkPicture>
Returns a placeholder Picture. Result does not draw, and contains only cull Rect, a
hint of its bounds. Result is immutable; it cannot be changed later. Result identifier is
unique.
Returned placeholder can be intercepted during playback to insert other commands into
crate::Canvas draw stream.
cullplaceholder dimensions
Returns: placeholder with unique identifier
Example (C++): https://fiddle.skia.org/c/@Picture_MakePlaceholder
pub fn approximate_op_count(&self) -> usize
pub fn approximate_op_count(&self) -> usize
Returns the approximate number of operations in Picture. Returned value may be greater
or less than the number of crate::Canvas calls recorded: some calls may be recorded as
more than one operation, other calls may be optimized away.
Returns: approximate operation count. If 0 is returned, we say the Picture is “empty”
meaning its Picture::cull_rect() is the result of an crate::Rect::new_empty().
Example (C++): https://fiddle.skia.org/c/@Picture_approximateOpCount
pub fn approximate_op_count_nested(
&self,
nested: impl Into<Option<bool>>,
) -> usize
pub fn approximate_op_count_nested( &self, nested: impl Into<Option<bool>>, ) -> usize
Version of Picture::approximate_op_count() that includes the op-counts of nested
pictures.
nestedif true, include the op-counts of nested pictures as well, else just return count the ops in the top-level picture.
pub fn approximate_bytes_used(&self) -> usize
pub fn approximate_bytes_used(&self) -> usize
Returns the approximate byte size of Picture. Does not include large objects referenced
by Picture.
Returns: approximate size
Example (C++): https://fiddle.skia.org/c/@Picture_approximateBytesUsed
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 generation_id(&self) -> u32
Returns a non-zero, unique value corresponding to the pixels in this pixel ref. Each time
the pixels are changed (and Self::notify_pixels_changed() is called), a different
generation ID will be returned.
pub fn notify_pixels_changed(&mut self)
pub fn notify_pixels_changed(&mut self)
Call this if you have changed the contents of the pixels. This will in turn cause a
different generation ID value to be returned from Self::generation_id().
pub fn is_immutable(&self) -> bool
pub fn is_immutable(&self) -> bool
Returns true if this pixel ref is marked as immutable, meaning that the contents of its pixels will not change for the lifetime of the pixel ref.
pub fn set_immutable(&mut self)
pub fn set_immutable(&mut self)
Marks this pixel ref as immutable, meaning that the contents of its pixels will not change for the lifetime of the pixel ref. This state can be set on a pixel ref, but it cannot be cleared once it is set.
pub fn notify_added_to_cache(&mut self)
pub fn notify_added_to_cache(&mut self)
Call when this pixel ref is part of the key to a resource cache entry. This allows the cache to know automatically those entries can be purged when this pixel ref is changed or deleted.
§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
without having to modify the original shader… only the paint’s alpha needs
to be modified.
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 without 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,
input_cs: impl Into<Option<RCHandle<SkColorSpace>>>,
output_cs: impl Into<Option<RCHandle<SkColorSpace>>>,
) -> RCHandle<SkShader>
pub fn with_working_color_space( &self, input_cs: impl Into<Option<RCHandle<SkColorSpace>>>, output_cs: impl Into<Option<RCHandle<SkColorSpace>>>, ) -> RCHandle<SkShader>
Return a shader that will compute this shader in a context such that any child shaders
return RGBA values converted to the input_cs colorspace.
It is then assumed that the RGBA values returned by this shader have been transformed into
output_cs by the shader being wrapped. By default, shaders are assumed to return values
in the destination colorspace and premultiplied. Using a different output_cs than input_cs
allows custom shaders to replace the color management Skia normally performs w/o forcing
authors to otherwise manipulate surface/image color info to avoid unnecessary or incorrect
work.
If the shader is not performing colorspace conversion but needs to operate in the input_cs
then it should have output_cs be the same as input_cs. Regardless of the output_cs here,
the RGBA values of the returned Shader are always converted from output_cs to the
destination surface color space.
A None input_cs is assumed to be the destination CS.
A None output_cs is assumed to be the input_cs.
§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>>>
use surfaces::wrap_pixels()
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 oneSurfacerow 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>>
use surfaces::raster()
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 oneSurfacerow 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>>
use surfaces::raster_n32_premul()
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 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>>
use surfaces::null()
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(&self) -> Handle<SkImageInfo>
pub fn image_info(&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 (C++): 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 (C++): 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 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 crate::gpu::ganesh::surface_ganesh::wrap_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 crate::gpu::ganesh::surface_ganesh::wrap_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: compatible Surface or None
Example (C++): https://fiddle.skia.org/c/@Surface_makeSurface
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 (C++): https://fiddle.skia.org/c/@Surface_makeImageSnapshot
pub fn make_temporary_image(&mut self) -> Option<RCHandle<SkImage>>
pub fn make_temporary_image(&mut self) -> Option<RCHandle<SkImage>>
Returns an Image capturing the current Surface contents. However, the contents of the
Image are only valid as long as no other writes to the Surface occur. If writes to the
original Surface happen then contents of the Image are undefined. However, continued use
of the Image should not cause crashes or similar fatal behavior.
This API is useful for cases where the client either immediately destroys the Surface
after the Image is created or knows they will destroy the Image before writing to the
Surface again.
This API can be more performant than Self::image_snapshot() as it never does an internal copy
of the data assuming the user frees either the Image or Surface as described above.
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 (C++): 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-Canvasdrawn intooffset.x- horizontal offset inCanvasoffset.y- vertical offset inCanvassampling- what technique to use when sampling the surface pixelspaint-Paintcontainingcrate::BlendMode,crate::ColorFilter,crate::ImageFilter, and so on; orNone
Example (C++): https://fiddle.skia.org/c/@Surface_draw
pub fn peek_pixels(&mut self) -> Option<Pixmap<'_>>
pub fn peek_pixels(&mut self) -> Option<Pixmap<'_>>
Copies Surface pixel address, row bytes, and ImageInfo to Pixmap, if address
is available, and returns Some(Pixmap). If pixel address is not available, return None
and leave Pixmap unchanged.
pixmap contents become invalid on any future change to Surface.
Example (C++): https://fiddle.skia.org/c/@Surface_peekPixels
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 Pixmap::color_type() and Pixmap::alpha_type() if required.
Pixels are readable when Surface is raster, or backed by a Ganesh GPU backend. Graphite
has deprecated this API in favor of the equivalent asynchronous API on
skgpu::graphite::Context (with an optional explicit synchonization).
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.
Pixmappixels could not be allocated.dst.row_bytes()is too small to contain one row of pixels.
dst- storage for pixels copied fromSurfacesrc_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
Example (C++): https://fiddle.skia.org/c/@Surface_readPixels
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 Ganesh GPU backend. Graphite
has deprecated this API in favor of the equivalent asynchronous API on
skgpu::graphite::Context (with an optional explicit synchonization).
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.
Surfacepixels could not be converted todst_info.color_type()ordst_info.alpha_type().dst_row_bytesis too small to contain one row of pixels.
dst_info- width, height,crate::ColorType, andcrate::AlphaTypeofdst_pixelsdst_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 Ganesh GPU backend. Graphite
has deprecated this API in favor of the equivalent asynchronous API on
skgpu::graphite::Context (with an optional explicit synchonization).
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.
Surfacepixels 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 fromSurfacesrc.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
Example (C++): https://fiddle.skia.org/c/@Surface_readPixels_3
pub fn async_rescale_and_read_pixels(
&mut self,
info: &Handle<SkImageInfo>,
src_rect: impl AsRef<IRect>,
rescale_gamma: SkImage_RescaleGamma,
rescale_mode: SkImage_RescaleMode,
callback: impl FnOnce(Option<RefHandle<SkImage_AsyncReadResult>>) + 'static,
)
pub fn async_rescale_and_read_pixels( &mut self, info: &Handle<SkImageInfo>, src_rect: impl AsRef<IRect>, rescale_gamma: SkImage_RescaleGamma, rescale_mode: SkImage_RescaleMode, callback: impl FnOnce(Option<RefHandle<SkImage_AsyncReadResult>>) + 'static, )
Makes surface pixel data available to caller, possibly asynchronously. It can also rescale the surface pixels.
Currently asynchronous reads are only supported in the Ganesh GPU backend and only when the underlying 3D API supports transfer buffers and CPU/GPU synchronization primitives. In all other cases this operates synchronously.
For the Graphite backend this API has been deprecated in favor of the equivalent API
on skgpu::graphite::Context.
Data is read from the source sub-rectangle, is optionally converted to a linear gamma, is
rescaled to the size indicated by info, is then converted to the color space, color type,
and alpha type of info. A src_rect that is not contained by the bounds of the surface
causes failure.
When the pixel data is ready the caller’s callback is called with a
AsyncReadResult containing pixel data in the requested color type, alpha type, and color
space. The AsyncReadResult will have AsyncReadResult::count() == 1. Upon failure the
callback is called with None for AsyncReadResult. For a GPU surface this flushes work
but a submit must occur to guarantee a finite time before the callback is called.
The data is valid for the lifetime of AsyncReadResult with the exception that if the
Surface is GPU-backed the data is immediately invalidated if the context is abandoned
or destroyed.
callback is called exactly once: before this function returns, from
crate::gpu::DirectContext::check_async_work_completion(), or when the context is
dropped. A panic in callback aborts the process.
infoinfo of the requested pixelssrc_rectsubrectangle of surface to readrescale_gammacontrols whether rescaling is done in the surface’s gamma or whether the source data is transformed to a linear gamma before rescaling.rescale_modecontrols the technique of the rescalingcallbackfunction to call with result of the read
pub fn async_rescale_and_read_pixels_yuv420(
&mut self,
yuv_color_space: SkYUVColorSpace,
dst_color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
src_rect: impl AsRef<IRect>,
dst_size: impl Into<ISize>,
rescale_gamma: SkImage_RescaleGamma,
rescale_mode: SkImage_RescaleMode,
callback: impl FnOnce(Option<RefHandle<SkImage_AsyncReadResult>>) + 'static,
)
pub fn async_rescale_and_read_pixels_yuv420( &mut self, yuv_color_space: SkYUVColorSpace, dst_color_space: impl Into<Option<RCHandle<SkColorSpace>>>, src_rect: impl AsRef<IRect>, dst_size: impl Into<ISize>, rescale_gamma: SkImage_RescaleGamma, rescale_mode: SkImage_RescaleMode, callback: impl FnOnce(Option<RefHandle<SkImage_AsyncReadResult>>) + 'static, )
Similar to Self::async_rescale_and_read_pixels() but performs an additional conversion
to YUV. The RGB->YUV conversion is controlled by yuv_color_space. The YUV data is returned
as three planes ordered y, u, v. The u and v planes are half the width and height of the
resized rectangle. The y, u, and v values are single bytes. Currently this fails if
dst_size width and height are not even. A src_rect that is not contained by the bounds
of the surface causes failure.
When the pixel data is ready the caller’s callback is called with a
AsyncReadResult containing the planar data. The AsyncReadResult will have
AsyncReadResult::count() == 3. Upon failure the callback is called with None for
AsyncReadResult. For a GPU surface this flushes work but a submit must occur to
guarantee a finite time before the callback is called.
The data is valid for the lifetime of AsyncReadResult with the exception that if the
Surface is GPU-backed the data is immediately invalidated if the context is abandoned
or destroyed.
callback is called exactly once: before this function returns, from
crate::gpu::DirectContext::check_async_work_completion(), or when the context is
dropped. A panic in callback aborts the process. Raster and Graphite surfaces do not
support this read and call back with None.
yuv_color_spaceThe transformation from RGB to YUV. Applied to the resized image after it is converted todst_color_space.dst_color_spaceThe color space to convert the resized image to, after rescaling.src_rectThe portion of the surface to rescale and convert to YUV planes.dst_sizeThe size to rescalesrc_recttorescale_gammacontrols whether rescaling is done in the surface’s gamma or whether the source data is transformed to a linear gamma before rescaling.rescale_modecontrols the sampling technique of the rescalingcallbackfunction to call with the planar read result
pub fn async_rescale_and_read_pixels_yuva420(
&mut self,
yuv_color_space: SkYUVColorSpace,
dst_color_space: impl Into<Option<RCHandle<SkColorSpace>>>,
src_rect: impl AsRef<IRect>,
dst_size: impl Into<ISize>,
rescale_gamma: SkImage_RescaleGamma,
rescale_mode: SkImage_RescaleMode,
callback: impl FnOnce(Option<RefHandle<SkImage_AsyncReadResult>>) + 'static,
)
pub fn async_rescale_and_read_pixels_yuva420( &mut self, yuv_color_space: SkYUVColorSpace, dst_color_space: impl Into<Option<RCHandle<SkColorSpace>>>, src_rect: impl AsRef<IRect>, dst_size: impl Into<ISize>, rescale_gamma: SkImage_RescaleGamma, rescale_mode: SkImage_RescaleMode, callback: impl FnOnce(Option<RefHandle<SkImage_AsyncReadResult>>) + 'static, )
Identical to Self::async_rescale_and_read_pixels_yuv420() but a fourth plane is returned
in the AsyncReadResult passed to callback. The fourth plane contains the alpha chanel
at the same full resolution as the Y plane.
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.
src- storage for pixels to copy toSurfacedst.x- x-axis position relative toSurfaceto begin copy; may be negativedst.y- y-axis position relative toSurfaceto begin copy; may be negative
Example (C++): https://fiddle.skia.org/c/@Surface_writePixels
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.
src- storage for pixels to copy toSurfacedst.x- x-axis position relative toSurfaceto begin copy; may be negativedst.y- y-axis position relative toSurfaceto begin copy; may be negative
Example (C++): https://fiddle.skia.org/c/@Surface_writePixels_2
pub fn props(&self) -> &SurfaceProps
pub fn props(&self) -> &SurfaceProps
Returns SurfaceProps for surface.
Returns: LCD striping orientation and setting for device independent fonts
pub fn wait(
&mut self,
wait_semaphores: &[Handle<GrBackendSemaphore>],
delete_semaphores_after_wait: impl Into<Option<bool>>,
) -> bool
pub fn wait( &mut self, wait_semaphores: &[Handle<GrBackendSemaphore>], delete_semaphores_after_wait: impl Into<Option<bool>>, ) -> bool
Inserts a list of GPU semaphores that the current GPU-backed API
must wait on before executing any more commands on the GPU for
this surface. If this call returns false, then the GPU back-end
will not wait on any passed-in semaphores, and the client will
still own the semaphores, regardless of the value of
delete_semaphores_after_wait.
If delete_semaphores_after_wait is false then Skia will not
delete the semaphores. In this case it is the client’s
responsibility to not destroy or attempt to reuse the semaphores
until it knows that Skia has finished waiting on them. This can
be done by using finished_procs on flush calls.
Returns: true if the GPU is waiting on the semaphores
§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 bounds(&self) -> &Rect
Returns the conservative bounding box. Uses the Paint associated with each glyph to
determine glyph bounds, and unions all bounds. The returned bounds may be larger than the
bounds of all glyphs in runs.
pub fn get_intercepts(
&self,
bounds: [f32; 2],
paint: Option<&Handle<SkPaint>>,
) -> Vec<f32>
pub fn get_intercepts( &self, bounds: [f32; 2], paint: Option<&Handle<SkPaint>>, ) -> Vec<f32>
Returns the number of intervals that intersect bounds. bounds describes a pair of lines
parallel to the text advance. The return count is zero or a multiple of two, and is at most
twice the number of glyphs in the blob.
Runs within the blob that contain RSXform are ignored when computing intercepts.
boundslower and upper line parallel to the advancepaintoptional paint specifying stroking and path effect that affects the result
pub fn from_str(
str: impl AsRef<str>,
font: &Handle<SkFont>,
) -> Option<RCHandle<SkTextBlob>>
pub fn from_str( str: impl AsRef<str>, font: &Handle<SkFont>, ) -> Option<RCHandle<SkTextBlob>>
Creates a text blob with a single run. The string is encoded as UTF-8.
font contains attributes used to define the run text.
This function uses the default character-to-glyph mapping from the Typeface in font.
It does not perform typeface fallback for characters not found in the Typeface. It does
not perform kerning or other complex shaping; glyphs are positioned based on their default
advances.
strcharacter code points drawnfonttext size, typeface, text scale, and so on, used to draw
pub fn from_text(
text: impl EncodedText,
font: &Handle<SkFont>,
) -> Option<RCHandle<SkTextBlob>>
pub fn from_text( text: impl EncodedText, font: &Handle<SkFont>, ) -> Option<RCHandle<SkTextBlob>>
Creates a text blob with a single run.
font contains attributes used to define the run text.
When the encoding is UTF-8, UTF-16, or UTF-32, this function uses the default
character-to-glyph mapping from the Typeface in font. It does not perform typeface
fallback for characters not found in the Typeface. It does not perform kerning or other
complex shaping; glyphs are positioned based on their default advances.
textcharacter code points or glyphs drawnfonttext size, typeface, text scale, and so on, used to draw
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_h( text: impl EncodedText, x_pos: &[f32], const_y: f32, font: &Handle<SkFont>, ) -> Option<RCHandle<SkTextBlob>>
Returns a text blob built from a single run of text with x-positions and a single y value.
This is equivalent to using TextBlobBuilder and calling alloc_run_pos_h. Returns None
if the text is empty.
textcharacter code points or glyphs drawn (based on encoding)x_posarray of x-positions, must contain values for all of the character pointsconst_yshared y-position for each character point, to be paired with eachx_posfontfont used for this run
pub fn from_pos_text(
text: impl EncodedText,
pos: &[Point],
font: &Handle<SkFont>,
) -> Option<RCHandle<SkTextBlob>>
pub fn from_pos_text( text: impl EncodedText, pos: &[Point], font: &Handle<SkFont>, ) -> Option<RCHandle<SkTextBlob>>
Returns a text blob built from a single run of text with positions. This is equivalent to
using TextBlobBuilder and calling alloc_run_pos. Returns None if the text is empty.
textcharacter code points or glyphs drawn (based on encoding)posarray of positions, must contain values for all of the character pointsfontfont used for this run
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 font_style(&self) -> FontStyle
Returns the typeface’s intrinsic style attributes.
pub fn is_bold(&self) -> bool
pub fn is_bold(&self) -> bool
Returns true if Self::font_style() weight is at least semi-bold.
pub fn is_italic(&self) -> bool
pub fn is_italic(&self) -> bool
Returns true if Self::font_style() is not upright.
pub fn is_fixed_pitch(&self) -> bool
pub fn is_fixed_pitch(&self) -> bool
Returns true if the typeface claims to be fixed-pitch.
This is a style bit; advance widths may vary even when this returns true.
pub fn variation_design_position(&self) -> Option<Vec<Coordinate>>
pub fn variation_design_position(&self) -> Option<Vec<Coordinate>>
Returns the design variation coordinates for this typeface.
Returns the number of axes and copies the coordinates if available.
Returns None on error.
pub fn variation_design_parameters(&self) -> Option<Vec<Axis>>
pub fn variation_design_parameters(&self) -> Option<Vec<Axis>>
Returns the design variation parameters for this typeface.
Returns the number of axes and copies the parameters if available.
Returns None on error.
pub fn is_synthetic_bold(&self) -> bool
pub fn is_synthetic_bold(&self) -> bool
Returns true if the typeface is internally being fake-bolded.
pub fn is_synthetic_oblique(&self) -> bool
pub fn is_synthetic_oblique(&self) -> bool
Returns true if the typeface is internally being fake-obliqued.
pub fn unique_id(&self) -> u32
pub fn unique_id(&self) -> u32
Returns a 32bit value for this typeface, unique for the underlying font data. Will never return 0.
pub fn equal(
face_a: impl AsRef<RCHandle<SkTypeface>>,
face_b: impl AsRef<RCHandle<SkTypeface>>,
) -> bool
pub fn equal( face_a: impl AsRef<RCHandle<SkTypeface>>, face_b: impl AsRef<RCHandle<SkTypeface>>, ) -> bool
Returns true if the two typefaces reference the same underlying font.
None does not compare equal to any typeface.
face_afirst typeface.face_bsecond typeface.
pub fn clone_with_arguments(
&self,
arguments: &FontArguments<'_, '_>,
) -> Option<RCHandle<SkTypeface>>
pub fn clone_with_arguments( &self, arguments: &FontArguments<'_, '_>, ) -> Option<RCHandle<SkTypeface>>
Returns a typeface based on this typeface and parameterized by arguments.
If arguments does not supply a value for some font parameter, the value from this
typeface is used.
argumentsclone parameters to apply.
pub fn serialize_stream(
&self,
write: impl Write,
behavior: SkTypeface_SerializeBehavior,
)
pub fn serialize_stream( &self, write: impl Write, behavior: SkTypeface_SerializeBehavior, )
Writes a signature sufficient to reconstruct a typeface referencing the same font.
writedestination stream.behaviorcontrols whether font data is included.
pub fn serialize(
&self,
behavior: SkTypeface_SerializeBehavior,
) -> RCHandle<SkData>
pub fn serialize( &self, behavior: SkTypeface_SerializeBehavior, ) -> RCHandle<SkData>
Returns serialized typeface data.
behaviorcontrols whether font data is included.
pub fn make_deserialize(
data: impl Read,
last_resort_mgr: impl Into<Option<RCHandle<SkFontMgr>>>,
) -> Option<RCHandle<SkTypeface>>
pub fn make_deserialize( data: impl Read, last_resort_mgr: impl Into<Option<RCHandle<SkFontMgr>>>, ) -> Option<RCHandle<SkTypeface>>
Deserializes a typeface previously produced by Self::serialize() or
Self::serialize_stream().
Goes through all registered typeface factories and last_resort_mgr when provided.
dataserialized typeface bytes.last_resort_mgroptional fallback font manager.
pub fn unichars_to_glyphs(&self, uni: &[i32], glyphs: &mut [u16])
pub fn unichars_to_glyphs(&self, uni: &[i32], glyphs: &mut [u16])
Converts UTF-32 code points to glyph IDs.
uniUTF-32 code points.glyphsoutput glyph IDs.
pub fn str_to_glyphs(&self, str: impl AsRef<str>, glyphs: &mut [u16]) -> usize
pub fn str_to_glyphs(&self, str: impl AsRef<str>, glyphs: &mut [u16]) -> usize
Converts UTF-8 text to glyph IDs.
strinput text.glyphsoutput glyph IDs.
pub fn text_to_glyphs(
&self,
text: impl EncodedText,
glyphs: &mut [u16],
) -> usize
pub fn text_to_glyphs( &self, text: impl EncodedText, glyphs: &mut [u16], ) -> usize
Converts encoded text to glyph IDs.
textencoded text input.glyphsoutput glyph IDs.
pub fn unichar_to_glyph(&self, unichar: i32) -> u16
pub fn unichar_to_glyph(&self, unichar: i32) -> u16
Returns the glyph ID corresponding to a Unicode code point.
Returns 0 when the code point is not supported.
unicharUnicode code point.
pub fn count_glyphs(&self) -> usize
pub fn count_glyphs(&self) -> usize
Returns the number of glyphs in the typeface.
pub fn count_tables(&self) -> usize
pub fn count_tables(&self) -> usize
Returns the number of tables in the font.
use read_table_tags
Returns the list of table tags in the font.
Returns None on error.
pub fn get_table_size(&self, tag: u32) -> Option<usize>
pub fn get_table_size(&self, tag: u32) -> Option<usize>
Returns the size, in bytes, of table tag.
Returns None if the table is not present.
tagtable tag.
pub fn get_table_data(&self, tag: u32, data: &mut [u8]) -> usize
pub fn get_table_data(&self, tag: u32, data: &mut [u8]) -> usize
Copies table tag data into data.
Returns the number of bytes copied.
tagtable tag.datadestination buffer.
pub fn copy_table_data(&self, tag: u32) -> Option<RCHandle<SkData>>
pub fn copy_table_data(&self, tag: u32) -> Option<RCHandle<SkData>>
Returns an immutable copy of table tag data.
Returns None if the table is not found.
tagtable tag.
pub fn units_per_em(&self) -> Option<i32>
pub fn units_per_em(&self) -> Option<i32>
Returns the units-per-em value for this typeface.
Returns None on error.
pub fn get_kerning_pair_adjustments(
&self,
glyphs: &[u16],
adjustments: &mut [i32],
) -> bool
pub fn get_kerning_pair_adjustments( &self, glyphs: &[u16], adjustments: &mut [i32], ) -> bool
Returns horizontal kerning adjustments for glyphs.
Adjustments are in design units relative to units-per-em.
glyphsinput glyph run.adjustmentsoutput adjustments; length should beglyphs.len() - 1.
pub fn new_family_name_iterator(&self) -> impl Iterator<Item = LocalizedString>
pub fn new_family_name_iterator(&self) -> impl Iterator<Item = LocalizedString>
Returns an iterator over all family names specified by the font.
The iterator may borrow backend-owned data. In particular, Fontations-backed
typefaces expose localized strings through data tied to the typeface, so this
iterator must not outlive self.
pub fn family_name(&self) -> String
pub fn family_name(&self) -> String
Returns the family name for this typeface as UTF-8.
pub fn post_script_name(&self) -> Option<String>
pub fn post_script_name(&self) -> Option<String>
Returns the PostScript name for this typeface.
The value may vary with variation parameters.
pub fn resource_name(&self) -> Option<String>
pub fn resource_name(&self) -> Option<String>
Returns a user-facing name for the primary resource backing this typeface.
Returns None when no resource name is available.
pub fn to_font_bytes(&self) -> Option<(Vec<u8>, u32)>
pub fn to_font_bytes(&self) -> Option<(Vec<u8>, u32)>
Returns raw font data bytes and the TTC index (or 0 if not a collection).
Returns None on failure.
pub fn to_existing_font_data(&self) -> Option<(RCHandle<SkData>, u32)>
pub fn to_existing_font_data(&self) -> Option<(RCHandle<SkData>, u32)>
Attempts to re-use existing font data when possible, avoiding additional
memory allocation. If existing font data is not available, the typical
way to access font data is via tables using copy_table_data (or
get_table_data).
Returns a Data object which can access the font data and the TTC
index (or 0 if not a collection).
Returns None on failure.
§impl RCHandle<SkVertices>
impl RCHandle<SkVertices>
pub const MAX_CUSTOM_ATTRIBUTES: usize = 8
pub fn new_copy(
mode: SkVertices_VertexMode,
positions: &[Point],
texs: &[Point],
colors: &[Color],
indices: Option<&[u16]>,
) -> RCHandle<SkVertices>
pub fn new_copy( mode: SkVertices_VertexMode, positions: &[Point], texs: &[Point], colors: &[Color], indices: Option<&[u16]>, ) -> RCHandle<SkVertices>
Creates vertices by copying the specified arrays. indices is ignored if empty.
modevertex modepositionsvertex positionstexstexture coordinatescolorsvertex colorsindicesoptional vertex indices
pub fn unique_id(&self) -> u32
pub fn mode(&self) -> SkVertices_VertexMode
will be removed without replacement
pub fn bounds(&self) -> &Rect
pub fn has_colors(&self) -> bool
will be removed without replacement
pub fn has_tex_coords(&self) -> bool
will be removed without replacement
pub fn has_bones(&self) -> bool
returns false
pub fn has_indices(&self) -> bool
will be removed without replacement
pub fn vertex_count(&self) -> usize
will be removed without replacement
pub fn index_count(&self) -> usize
will be removed without replacement
pub fn positions(&self) -> &[Point]
will be removed without replacement
pub fn tex_coords(&self) -> Option<&[Point]>
will be removed without replacement
pub fn colors(&self) -> Option<&[Color]>
will be removed without replacement
pub fn bone_indices(&self) -> Option<&[[u32; 4]]>
returns None
pub fn bone_weights(&self) -> Option<&[[u32; 4]]>
returns None
pub fn indices(&self) -> Option<&[u16]>
will be removed without replacement
pub fn is_volatile(&self) -> bool
returns false
pub fn apply_bones(&self, _bones: &[Bone]) -> !
removed without replacement
pub fn approximate_size(&self) -> usize
pub fn approximate_size(&self) -> usize
Returns the approximate byte size of the vertices object.
pub fn decode(_buffer: &[u8]) -> !
removed without replacement
pub fn encode(&self) -> !
removed without replacement
§impl RCHandle<SkShader>
impl RCHandle<SkShader>
§impl RCHandle<SkPathEffect>
impl RCHandle<SkPathEffect>
pub fn path_1d(
path: &Handle<SkPath>,
advance: f32,
phase: f32,
style: SkPath1DPathEffect_Style,
) -> Option<RCHandle<SkPathEffect>>
pub fn path_1d( path: &Handle<SkPath>, advance: f32, phase: f32, style: SkPath1DPathEffect_Style, ) -> Option<RCHandle<SkPathEffect>>
Dashes the path by replicating the specified path.
paththe path to replicate (dash)advancethe space between instances ofpathphasedistance (modadvance) along path for its initial positionstylehow to transform path at each point (based on the current position and tangent)
§impl RCHandle<SkBlender>
impl RCHandle<SkBlender>
pub fn arithmetic(
k1: f32,
k2: f32,
k3: f32,
k4: f32,
enforce_premul: bool,
) -> Option<RCHandle<SkBlender>>
pub fn arithmetic( k1: f32, k2: f32, k3: f32, k4: f32, enforce_premul: bool, ) -> Option<RCHandle<SkBlender>>
Create a blender that implements the following:
k1 * src * dst + k2 * src + k3 * dst + k4
k1,k2,k3,k4the four coefficientsenforce_premuliftrue, the RGB channels will be clamped to the calculated alpha
§impl RCHandle<SkPathEffect>
impl RCHandle<SkPathEffect>
pub fn corner_path(radius: f32) -> Option<RCHandle<SkPathEffect>>
pub fn corner_path(radius: f32) -> Option<RCHandle<SkPathEffect>>
Turns sharp corners into various treatments (e.g. rounded corners).
radiusmust be > 0 to have an effect. It specifies the distance from each corner that should be “rounded”.
§impl RCHandle<SkPathEffect>
impl RCHandle<SkPathEffect>
pub fn dash(intervals: &[f32], phase: f32) -> Option<RCHandle<SkPathEffect>>
pub fn dash(intervals: &[f32], phase: f32) -> Option<RCHandle<SkPathEffect>>
Dashes the path by copying it with the specified intervals.
intervalsarray containing an even number of entries (>=2), with the even indices specifying the length of “on” intervals, and the odd indices specifying the length of “off” intervalsphaseoffset into the intervals array (mod the sum of all of the intervals). For example: ifintervalsis[10, 20]andphaseis 25, this will set up a dashed path like so: 5 pixels off, 10 pixels on, 20 pixels off, 10 pixels on, 20 pixels off, … A phase of -5, 25, 55, 85, etc. would all result in the same path, because the sum of all the intervals is 30.
Note: only affects stroked paths.
§impl RCHandle<SkPathEffect>
impl RCHandle<SkPathEffect>
pub fn discrete(
seg_length: f32,
dev: f32,
seed_assist: impl Into<Option<u32>>,
) -> Option<RCHandle<SkPathEffect>>
pub fn discrete( seg_length: f32, dev: f32, seed_assist: impl Into<Option<u32>>, ) -> Option<RCHandle<SkPathEffect>>
Chops a path into discrete segments, and randomly displaces them.
seg_lengthbreak the path into segments of this lengthdevrandomly move the endpoints away from the original path by a maximum of this deviationseed_assista caller-supplied seed that modifies the seed value that is used to randomize the path segments’ endpoints. IfNone, it defaults to 0, in which case filtering a path multiple times will result in the same set of segments (this is useful for testing). If a caller does not want this behaviour they can pass in a differentseed_assistto get a different set of path segments.
Note: works on filled or framed paths.
§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>>
Use gradient::shaders::linear_gradient() instead
pub fn linear_gradient_with_interpolation<'a>( points: (impl Into<Point>, impl Into<Point>), colors: (&'a [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>>
Use gradient::shaders::linear_gradient() instead
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>>
Use gradient::shaders::radial_gradient() instead
pub fn radial_gradient_with_interpolation<'a>( center_and_radius: (impl Into<Point>, f32), colors: (&'a [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>>
Use gradient::shaders::radial_gradient() instead
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>>
Use gradient::shaders::two_point_conical_gradient() instead
pub fn two_point_conical_gradient_with_interpolation<'a>( start_and_radius: (impl Into<Point>, f32), end_and_radius: (impl Into<Point>, f32), colors: (&'a [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>>
Use gradient::shaders::two_point_conical_gradient() instead
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>>
Use gradient::shaders::sweep_gradient() instead
pub fn sweep_gradient_with_interpolation<'a>( center: impl Into<Point>, colors: (&'a [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>>
Use gradient::shaders::sweep_gradient() instead
§impl RCHandle<SkColorFilter>
impl RCHandle<SkColorFilter>
pub fn high_contrast(
config: &HighContrastConfig,
) -> Option<RCHandle<SkColorFilter>>
pub fn high_contrast( config: &HighContrastConfig, ) -> Option<RCHandle<SkColorFilter>>
Color filter that provides transformations to improve contrast for users with low vision.
Applies the following transformations in this order. Each of these can be configured
using HighContrastConfig.
- Conversion to grayscale
- Color inversion (either in RGB or HSL space)
- Increasing the resulting contrast.
Returns None if the config is invalid, e.g. if the contrast is outside the range of
-1.0 to 1.0.
§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<SkPicture>
impl RCHandle<SkPicture>
§impl RCHandle<SkColorFilter>
impl RCHandle<SkColorFilter>
pub fn luma() -> RCHandle<SkColorFilter>
pub fn luma() -> RCHandle<SkColorFilter>
Multiplies the luma of its input into the alpha channel, and sets the red, green, and blue channels to zero.
luma(r, g, b, a) = {0, 0, 0, a * luma(r, g, b)}
This is similar to a luminanceToAlpha feColorMatrix, but note how this filter folds in the previous alpha, something an feColorMatrix cannot do:
feColorMatrix(luminanceToAlpha; r, g, b, a) = {0, 0, 0, luma(r, g, b)}
§impl RCHandle<SkRuntimeEffect>
impl RCHandle<SkRuntimeEffect>
pub fn make_for_color_filter(
sksl: impl AsRef<str>,
options: Option<&Options<'_>>,
) -> Result<RCHandle<SkRuntimeEffect>, String>
pub fn make_for_color_filter( sksl: impl AsRef<str>, options: Option<&Options<'_>>, ) -> Result<RCHandle<SkRuntimeEffect>, String>
Creates a runtime effect for use as a ColorFilter.
Color filter SkSL requires an entry point that looks like:
vec4 main(vec4 inColor) { ... }skslthe SkSL source code of the effectoptionsoptions for creating the effect
Returns the effect, or the compiler error message on failure.
pub fn make_for_shader(
sksl: impl AsRef<str>,
options: Option<&Options<'_>>,
) -> Result<RCHandle<SkRuntimeEffect>, String>
pub fn make_for_shader( sksl: impl AsRef<str>, options: Option<&Options<'_>>, ) -> Result<RCHandle<SkRuntimeEffect>, String>
Creates a runtime effect for use as a Shader.
Shader SkSL requires an entry point that looks like:
vec4 main(vec2 inCoords) { ... }The color that is returned should be premultiplied.
skslthe SkSL source code of the effectoptionsoptions for creating the effect
Returns the effect, or the compiler error message on failure.
pub fn make_for_blender(
sksl: impl AsRef<str>,
options: Option<&Options<'_>>,
) -> Result<RCHandle<SkRuntimeEffect>, String>
pub fn make_for_blender( sksl: impl AsRef<str>, options: Option<&Options<'_>>, ) -> Result<RCHandle<SkRuntimeEffect>, String>
Creates a runtime effect for use as a Blender.
Blend SkSL requires an entry point that looks like:
vec4 main(vec4 srcColor, vec4 dstColor) { ... }skslthe SkSL source code of the effectoptionsoptions for creating the effect
Returns the effect, or the compiler error message on failure.
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_shader<'a>( &self, uniforms: impl Into<RCHandle<SkData>>, children: &[ChildPtr], local_matrix: impl Into<Option<&'a Matrix>>, ) -> Option<RCHandle<SkShader>>
Creates a Shader from this effect.
uniformsaDatablock of sizeRuntimeEffect::uniform_size(), containing values for all uniform variableschildrenthe child shaders/color filters/blenders required by the effect, in the order given byRuntimeEffect::children()local_matrixan optional local matrix applied to the shader
pub fn make_color_filter<'a>(
&self,
inputs: impl Into<RCHandle<SkData>>,
children: impl Into<Option<&'a [ChildPtr]>>,
) -> Option<RCHandle<SkColorFilter>>
pub fn make_color_filter<'a>( &self, inputs: impl Into<RCHandle<SkData>>, children: impl Into<Option<&'a [ChildPtr]>>, ) -> Option<RCHandle<SkColorFilter>>
Creates a ColorFilter from this effect.
inputsaDatablock of sizeRuntimeEffect::uniform_size(), containing values for all uniform variableschildrenthe child color filters/shaders required by the effect
pub fn make_blender<'a>(
&self,
uniforms: impl Into<RCHandle<SkData>>,
children: impl Into<Option<&'a [ChildPtr]>>,
) -> Option<RCHandle<SkBlender>>
pub fn make_blender<'a>( &self, uniforms: impl Into<RCHandle<SkData>>, children: impl Into<Option<&'a [ChildPtr]>>, ) -> Option<RCHandle<SkBlender>>
Creates a Blender from this effect.
uniformsaDatablock of sizeRuntimeEffect::uniform_size(), containing values for all uniform variableschildrenthe child blenders/color filters/shaders required by the effect
pub fn input_size(&self) -> usize
Use uniform_size() instead
pub fn uniform_size(&self) -> usize
pub fn uniform_size(&self) -> usize
Combined size of all uniform variables. When calling
RuntimeEffect::make_color_filter() or RuntimeEffect::make_shader(), provide a
Data of this size, containing values for all of those variables.
pub fn inputs(&self) -> &[Handle<SkRuntimeEffect_Uniform>]
Use uniforms() instead
pub fn uniforms(&self) -> &[Handle<SkRuntimeEffect_Uniform>]
pub fn uniforms(&self) -> &[Handle<SkRuntimeEffect_Uniform>]
The descriptions of all uniform variables in the effect’s SkSL.
pub fn children(&self) -> &[Handle<SkRuntimeEffect_Child>]
pub fn children(&self) -> &[Handle<SkRuntimeEffect_Child>]
The descriptions of all child effects in the effect’s SkSL.
pub fn find_input( &self, name: impl AsRef<str>, ) -> Option<&Handle<SkRuntimeEffect_Uniform>>
Use find_uniform()
pub fn find_uniform(
&self,
name: impl AsRef<str>,
) -> Option<&Handle<SkRuntimeEffect_Uniform>>
pub fn find_uniform( &self, name: impl AsRef<str>, ) -> Option<&Handle<SkRuntimeEffect_Uniform>>
Returns the description of the named uniform variable, or None if not found.
pub fn find_child(
&self,
name: impl AsRef<str>,
) -> Option<&Handle<SkRuntimeEffect_Child>>
pub fn find_child( &self, name: impl AsRef<str>, ) -> Option<&Handle<SkRuntimeEffect_Child>>
Returns the description of the named child, or None if not found.
pub fn allow_shader(&self) -> bool
pub fn allow_shader(&self) -> bool
Returns whether this effect can be used as a Shader.
pub fn allow_color_filter(&self) -> bool
pub fn allow_color_filter(&self) -> bool
Returns whether this effect can be used as a ColorFilter.
pub fn allow_blender(&self) -> bool
pub fn allow_blender(&self) -> bool
Returns whether this effect can be used as a Blender.
§impl RCHandle<SkMaskFilter>
impl RCHandle<SkMaskFilter>
pub fn from_shader( shader: impl Into<RCHandle<SkShader>>, ) -> RCHandle<SkMaskFilter>
ShaderMaskFilters will be deleted entirely in an upcoming Skia release.
§impl RCHandle<SkColorFilter>
impl RCHandle<SkColorFilter>
pub fn from_table(table: &[u8; 256]) -> RCHandle<SkColorFilter>
Use color_filters::table()
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>
Use color_filters::table_argb()
§impl RCHandle<SkMaskFilter>
impl RCHandle<SkMaskFilter>
pub fn table(table: &[u8; 256]) -> RCHandle<SkMaskFilter>
TableMaskFilter will be remove entirely in an upcoming Skia release.
pub fn gamma(gamma: f32) -> RCHandle<SkMaskFilter>
TableMaskFilter will be remove entirely in an upcoming Skia release.
pub fn clip(min: u8, max: u8) -> RCHandle<SkMaskFilter>
TableMaskFilter will be remove entirely in an upcoming Skia release.
§impl RCHandle<SkPathEffect>
impl RCHandle<SkPathEffect>
pub fn trim(
start_t: f32,
stop_t: f32,
mode: impl Into<Option<SkTrimPathEffect_Mode>>,
) -> Option<RCHandle<SkPathEffect>>
pub fn trim( start_t: f32, stop_t: f32, mode: impl Into<Option<SkTrimPathEffect_Mode>>, ) -> Option<RCHandle<SkPathEffect>>
Takes start and stop “t” values (values between 0…1), and returns a path that is that subset of the original path.
e.g.
trim(0.5, 1.0, ..)returns the 2nd half of the pathtrim(0.33333, 0.66667, ..)returns the middle third of the path
The trim values apply to the entire path, so if it contains several contours, all of them are including in the calculation.
start_t and stop_t must be 0..1 inclusive. If they are outside of that interval,
they will be pinned to the nearest legal value. If either is NaN, None will be
returned.
Note: for Mode::Normal, this will return one (logical) segment (even if it is
spread across multiple contours). For Mode::Inverted, this will return 2 logical
segments: stopT..1 and 0…startT, in this order.
§impl RCHandle<SkImage>
impl RCHandle<SkImage>
pub fn encode<'a>(
&self,
context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>,
format: SkEncodedImageFormat,
quality: impl Into<Option<u32>>,
) -> Option<RCHandle<SkData>>
pub fn encode<'a>( &self, context: impl Into<Option<&'a mut RCHandle<GrDirectContext>>>, format: SkEncodedImageFormat, quality: impl Into<Option<u32>>, ) -> Option<RCHandle<SkData>>
Encode the image and return the resulting bytes, or None if the format is not supported or
the encoding fails.
contextIf the image was created as a texture-backed image on a GPU context, that context must be provided so the pixels can be read before being encoded. For raster-backed images, it can beNone.qualityAn encoder specific value in the range0..=100.Noneselects the default of100.
§impl RCHandle<GrDirectContext>
impl RCHandle<GrDirectContext>
pub fn reset(
&mut self,
backend_state: Option<u32>,
) -> &mut RCHandle<GrDirectContext>
pub fn reset( &mut self, backend_state: Option<u32>, ) -> &mut RCHandle<GrDirectContext>
The context normally assumes that no outsider is setting state
within the underlying 3D API’s context/device/whatever. This call informs
the context that the state was modified and it should resend. Shouldn’t
be called frequently for good performance.
The flag bits, backend_state, is dependent on which backend is used by the
context, either GL or D3D (possible in future).
backend_stateflag bits to reset, orNoneto reset all backend state
pub fn reset_gl_texture_bindings(&mut self) -> &mut RCHandle<GrDirectContext>
pub fn reset_gl_texture_bindings(&mut self) -> &mut RCHandle<GrDirectContext>
If the backend is crate::gpu::ganesh::BackendApi::OpenGL, then all texture
unit/target combinations for
which the context has modified the bound texture will have texture id 0 bound. This does
not flush the context. Calling DirectContext::reset() does not change the set that
will be bound to texture id 0 on the next call to
DirectContext::reset_gl_texture_bindings(). After this is called all unit/target
combinations are considered to have unmodified bindings until the context subsequently
modifies them (meaning if this is called twice in a row with no intervening context usage
then the second call is a no-op.)
pub fn abandon(&mut self) -> &mut RCHandle<GrDirectContext>
pub fn abandon(&mut self) -> &mut RCHandle<GrDirectContext>
Abandons all GPU resources and assumes the underlying backend 3D API context is no longer usable. Call this if you have lost the associated GPU context, and thus internal texture, buffer, etc. references/IDs are now invalid. Calling this ensures that the destructors of the context and any of its created resource objects will not make backend 3D API calls. Content rendered but not previously flushed may be lost. After this function is called all subsequent calls on the context will fail or be no-ops.
The typical use case for this function is that the underlying 3D context was lost and further API calls may crash.
This call is not valid to be made inside release procs passed into crate::Surface or
crate::Image. The call will simply fail (and assert in debug) if it is called while
inside a release proc.
For Vulkan, even if the device becomes lost, the VkQueue, VkDevice, or VkInstance used
to create the context must be kept alive even after abandoning the context. Those
objects must live for the lifetime of the context object itself. The reason for this is
so that we can continue to delete any outstanding BackendTextures/RenderTargets
which must be cleaned up even in a device lost state.
pub fn is_device_lost(&mut self) -> bool
pub fn is_device_lost(&mut self) -> bool
Returns true if the context was abandoned or if the backend specific context has gotten into an unrecoverarble, lost state (e.g. in Vulkan backend if we’ve gotten a VK_ERROR_DEVICE_LOST). If the backend context is lost, this call will also abandon this context.
pub fn oomed(&mut self) -> bool
pub fn oomed(&mut self) -> bool
Returns true if the backend specific context has gotten into an unrecoverarble, lost state (e.g. in Vulkan backend if we’ve gotten a VK_ERROR_DEVICE_LOST). If the backend context is lost, this call will also abandon this context.
pub fn release_resources_and_abandon(
&mut self,
) -> &mut RCHandle<GrDirectContext>
pub fn release_resources_and_abandon( &mut self, ) -> &mut RCHandle<GrDirectContext>
This is similar to DirectContext::abandon() however the underlying 3D context is
not yet lost and the context will cleanup all allocated resources before returning.
After returning it will assume that the underlying context may no longer be valid.
The typical use case for this function is that the client is going to destroy the 3D context but can’t guarantee that context will be destroyed first (perhaps because it may be ref’ed elsewhere by either the client or Skia objects).
For Vulkan, even if the device becomes lost, the VkQueue, VkDevice, or VkInstance used
to create the context must be alive before calling
DirectContext::release_resources_and_abandon().
pub fn resource_cache_limit(&self) -> usize
pub fn resource_cache_limit(&self) -> usize
Return the current GPU resource cache limit in bytes.
pub fn resource_cache_usage(&self) -> ResourceCacheUsage
pub fn resource_cache_usage(&self) -> ResourceCacheUsage
Gets the current GPU resource cache usage.
pub fn resource_cache_purgeable_bytes(&self) -> usize
pub fn resource_cache_purgeable_bytes(&self) -> usize
Gets the number of bytes in the cache consumed by purgeable (e.g. unlocked) resources.
pub fn set_resource_cache_limits(&mut self, limits: ResourceCacheLimits)
pub fn set_resource_cache_limits(&mut self, limits: ResourceCacheLimits)
Specify the GPU resource cache limits. If the current cache exceeds the
max_resource_bytes limit, it will be purged (LRU) to keep the cache within the limit.
pub fn set_resource_cache_limit(&mut self, max_resource_bytes: usize)
pub fn set_resource_cache_limit(&mut self, max_resource_bytes: usize)
Specify the GPU resource cache limit. If the cache currently exceeds this limit, it will be purged (LRU) to keep the cache within the limit.
pub fn free_gpu_resources(&mut self) -> &mut RCHandle<GrDirectContext>
pub fn free_gpu_resources(&mut self) -> &mut RCHandle<GrDirectContext>
Frees GPU created by the context. Can be called to reduce GPU memory pressure.
pub fn perform_deferred_cleanup(
&mut self,
not_used: Duration,
opts: impl Into<Option<GrPurgeResourceOptions>>,
) -> &mut RCHandle<GrDirectContext>
pub fn perform_deferred_cleanup( &mut self, not_used: Duration, opts: impl Into<Option<GrPurgeResourceOptions>>, ) -> &mut RCHandle<GrDirectContext>
Purge GPU resources that haven’t been used in the past not_used milliseconds or are
otherwise marked for deletion, regardless of whether the context is under budget.
not_usedonly unlocked resources not used in these last milliseconds will be cleaned upoptsspecify which resources should be cleaned up. If [PurgeResourceOptions:: ScratchResourcesOnly] then, all unlocked scratch resources older thannot_usedwill be purged but the unlocked resources with persistent data will remain.
pub fn purge_unlocked_resource_bytes(
&mut self,
bytes_to_purge: usize,
prefer_scratch_resources: bool,
) -> &mut RCHandle<GrDirectContext>
pub fn purge_unlocked_resource_bytes( &mut self, bytes_to_purge: usize, prefer_scratch_resources: bool, ) -> &mut RCHandle<GrDirectContext>
Purge unlocked resources from the cache until the provided byte count has been reached or we have purged all unlocked resources. The default policy is to purge in LRU order, but can be overridden to prefer purging scratch resources (in LRU order) prior to purging other resource types.
bytes_to_purgethe desired number of bytes to be purgedprefer_scratch_resourcesif true scratch resources will be purged prior to other resource types
pub fn purge_unlocked_resources(
&mut self,
opts: GrPurgeResourceOptions,
) -> &mut RCHandle<GrDirectContext>
pub fn purge_unlocked_resources( &mut self, opts: GrPurgeResourceOptions, ) -> &mut RCHandle<GrDirectContext>
This entry point is intended for instances where an app has been backgrounded or
suspended.
If opts is PurgeResourceOptions::ScratchResourcesOnly all unlocked scratch
resources will be purged but the unlocked resources with persistent data will remain.
If it is PurgeResourceOptions::AllResources then all unlocked resources will be
purged.
In either case, after the unlocked resources are purged a separate pass will be made to
ensure that resource usage is under budget (i.e., even if scratch resources only are
purged some resources with persistent data may be purged to be under budget).
pub fn supported_gpu_stats(&self) -> GpuStatsFlags
pub fn supported_gpu_stats(&self) -> GpuStatsFlags
Gets the types of GPU stats supported by this context.
pub fn flush_and_submit(&mut self) -> Result<GrSemaphoresSubmitted, FlushError>
pub fn flush_and_submit(&mut self) -> Result<GrSemaphoresSubmitted, FlushError>
Call to ensure all drawing to the context has been flushed and submitted to the
underlying 3D API. This is equivalent to calling DirectContext::flush() with a
default FlushInfo followed by DirectContext::submit().
Returns Ok with the SemaphoresSubmitted value of the flush, or Err with a
FlushError if the flush or the submit failed.
pub fn flush_submit_and_sync_cpu(
&mut self,
) -> Result<GrSemaphoresSubmitted, FlushError>
pub fn flush_submit_and_sync_cpu( &mut self, ) -> Result<GrSemaphoresSubmitted, FlushError>
Version of DirectContext::flush() that uses a default FlushInfo and submits with
SyncCpu::Yes, so it returns once the gpu has finished with all submitted work.
Returns Ok with the SemaphoresSubmitted value of the flush, or Err with a
FlushError if the flush or the submit failed.
pub fn flush<'a>(
&mut self,
info: impl Into<Option<&'a FlushInfo>>,
) -> Result<GrSemaphoresSubmitted, FlushError>
pub fn flush<'a>( &mut self, info: impl Into<Option<&'a FlushInfo>>, ) -> Result<GrSemaphoresSubmitted, FlushError>
Call to ensure all drawing to the context has been flushed to underlying 3D API
specific objects. A call to DirectContext::submit() is always required to ensure
work is actually sent to the gpu. Some specific API details:
GL: Commands are actually sent to the driver, but glFlush is never called. Thus some sync objects from the flush will not be valid until a submission occurs.
Vulkan/Metal/D3D/Dawn: Commands are recorded to the backend APIs corresponding command buffer or encoder objects. However, these objects are not sent to the gpu until a submission occurs.
If the returned SemaphoresSubmitted is crate::gpu::SemaphoresSubmitted::Yes, only
initialized crate::gpu::BackendSemaphores will be submitted to the gpu during the next
submit call (it is possible Skia failed to create a subset of the semaphores). The client
should not wait on these semaphores until after submit has been called, and must keep them
alive until then. If it is crate::gpu::SemaphoresSubmitted::No, the GPU backend will
not submit any semaphores to be signaled on the GPU. Thus the client should not have the
GPU wait on any of the semaphores passed in with the FlushInfo. Regardless of whether
semaphores were submitted to the GPU or not, the client is still responsible for
deleting any initialized semaphores.
Regardless of semaphore submission the context will still be flushed. It should be
emphasized that a crate::gpu::SemaphoresSubmitted::No value does not mean the flush did
not happen. It simply means there were no semaphores submitted to the GPU. A caller should
only take this as a failure if they passed in semaphores to be submitted.
Returns Ok with the SemaphoresSubmitted value of the flush, or Err with a
FlushError if the flush failed.
infoflush options, orNonefor default flush options
pub fn flush_image_with_info(
&mut self,
image: &RCHandle<SkImage>,
info: &FlushInfo,
) -> Result<GrSemaphoresSubmitted, FlushError>
pub fn flush_image_with_info( &mut self, image: &RCHandle<SkImage>, info: &FlushInfo, ) -> Result<GrSemaphoresSubmitted, FlushError>
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 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 DirectContext then this is a no-op unless the FlushInfo contains
semaphores or a finish proc. Those are respected even when the image has not been used.
Returns Ok with the SemaphoresSubmitted value of the flush, or Err with a
FlushError if the flush failed.
imagethe image to flushinfoflush options
pub fn flush_image(
&mut self,
image: &RCHandle<SkImage>,
) -> Result<GrSemaphoresSubmitted, FlushError>
pub fn flush_image( &mut self, image: &RCHandle<SkImage>, ) -> Result<GrSemaphoresSubmitted, FlushError>
Version of DirectContext::flush_image_with_info() that uses a default
FlushInfo.
pub fn flush_and_submit_image(
&mut self,
image: &RCHandle<SkImage>,
) -> Result<GrSemaphoresSubmitted, FlushError>
pub fn flush_and_submit_image( &mut self, image: &RCHandle<SkImage>, ) -> Result<GrSemaphoresSubmitted, FlushError>
Version of DirectContext::flush() that uses a default FlushInfo. Also submits
the flushed image work to the GPU.
The submit is issued even when the flush failed, so the semaphores reported by
FlushError::submitted may still be signaled by it.
pub fn flush_surface_with_access(
&mut self,
surface: &mut RCHandle<SkSurface>,
access: SkSurfaces_BackendSurfaceAccess,
info: &FlushInfo,
) -> Result<GrSemaphoresSubmitted, FlushError>
pub fn flush_surface_with_access( &mut self, surface: &mut RCHandle<SkSurface>, access: SkSurfaces_BackendSurfaceAccess, info: &FlushInfo, ) -> Result<GrSemaphoresSubmitted, FlushError>
Issues pending Surface commands to the GPU-backed API objects and resolves any
Surface MSAA. A call to DirectContext::submit() is always required to ensure
work is actually sent to the gpu. Some specific API details:
GL: Commands are actually sent to the driver, but glFlush is never called. Thus some sync objects from the flush will not be valid until a submission occurs.
Vulkan/Metal/D3D/Dawn: Commands are recorded to the backend APIs corresponding command buffer or encoder objects. However, these objects are not sent to the gpu until a submission occurs.
The work that is submitted to the GPU will be dependent on the access that is passed
in.
If surfaces::BackendSurfaceAccess::NoAccess is passed in all commands will be issued
to the GPU.
If surfaces::BackendSurfaceAccess::Present is passed in and the backend API is not
Vulkan, it is treated the same as NoAccess. If the backend API is Vulkan, the VkImage
that backs the Surface will be transferred back to its original queue. If the
Surface was created by wrapping a VkImage, the queue will be set to the queue which
was originally passed in on the GrVkImageInfo. Additionally, if the original queue was
not external or foreign the layout of the VkImage will be set to
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR.
The FlushInfo describes additional options to flush. Please see documentation at
FlushInfo for more info.
If the returned SemaphoresSubmitted is crate::gpu::SemaphoresSubmitted::Yes, only
initialized crate::gpu::BackendSemaphores will be submitted to the gpu during the next
submit call (it is possible Skia failed to create a subset of the semaphores). The client
should not wait on these semaphores until after submit has been called, but must keep them
alive until then. If a submit flag was passed in with the flush these valid semaphores can
be waited on immediately. If it is crate::gpu::SemaphoresSubmitted::No, the GPU backend
will not submit any semaphores to be signaled on the GPU. Thus the client should not have
the GPU wait on any of the semaphores passed in with the FlushInfo. Regardless of
whether semaphores were submitted to the GPU or not, the client is still responsible for
deleting any initialized semaphores.
Regardless of semaphore submission the context will still be flushed. It should be
emphasized that a crate::gpu::SemaphoresSubmitted::No value does not mean the flush did
not happen. It simply means there were no semaphores submitted to the GPU. A caller should
only take this as a failure if they passed in semaphores to be submitted.
Pending surface commands are flushed regardless of the return result.
Returns Ok with the SemaphoresSubmitted value of the flush, or Err with a
FlushError if the flush failed.
surfacethe GPU backed surface to be flushed. Has no effect on a CPU-backed surfaceaccesstype of access the call will do on the backend object after flushinfoflush options
pub fn flush_surface_with_texture_state(
&mut self,
surface: &mut RCHandle<SkSurface>,
info: &FlushInfo,
new_state: Option<&RCHandle<skgpu_MutableTextureState>>,
) -> Result<GrSemaphoresSubmitted, FlushError>
pub fn flush_surface_with_texture_state( &mut self, surface: &mut RCHandle<SkSurface>, info: &FlushInfo, new_state: Option<&RCHandle<skgpu_MutableTextureState>>, ) -> Result<GrSemaphoresSubmitted, FlushError>
Same as DirectContext::flush_surface_with_access() except:
If a MutableTextureState is passed in, at the end of the flush we will transition
the surface to be in the state requested by the MutableTextureState. If the surface
(or crate::Image or backend object wrapping the same backend object) is used again
after this flush the state may be changed and no longer match what is requested here.
This is often used if the surface will be used for presenting or external use and the
client wants the backend object to be prepped for that use. A finished proc or semaphore
on the FlushInfo will also include the work for any requested state change.
If the backend API is Vulkan, the caller can set the MutableTextureState’s
VkImageLayout to VK_IMAGE_LAYOUT_UNDEFINED or queueFamilyIndex to VK_QUEUE_FAMILY_IGNORED
to tell Skia to not change those respective states.
Returns Ok with the SemaphoresSubmitted value of the flush, or Err with a
FlushError if the flush failed.
surfacethe GPU backed surface to be flushed. Has no effect on a CPU-backed surfaceinfoflush optionsnew_stateoptional state change request after flush
pub fn flush_and_submit_surface(
&mut self,
surface: &mut RCHandle<SkSurface>,
sync_cpu: impl Into<Option<GrSyncCpu>>,
) -> Result<GrSemaphoresSubmitted, FlushError>
pub fn flush_and_submit_surface( &mut self, surface: &mut RCHandle<SkSurface>, sync_cpu: impl Into<Option<GrSyncCpu>>, ) -> Result<GrSemaphoresSubmitted, FlushError>
Call to ensure all reads/writes of the surface have been issued to the underlying 3D
API. Skia will correctly order its own draws and pixel operations. This must be used to
ensure correct ordering when the surface backing store is accessed outside Skia (e.g.
direct use of the 3D API or a windowing system). This is equivalent to calling
DirectContext::flush_surface() with a default FlushInfo followed by
DirectContext::submit().
Has no effect on a CPU-backed surface.
The submit is issued even when the flush failed, so the semaphores reported by
FlushError::submitted may still be signaled by it.
Returns Ok with the SemaphoresSubmitted value of the flush, or Err with a
FlushError if the flush or the submit failed.
sync_cpuwhether submit should return once the GPU has finished with all submitted work, defaults toSyncCpu::No
pub fn flush_surface(
&mut self,
surface: &mut RCHandle<SkSurface>,
) -> Result<GrSemaphoresSubmitted, FlushError>
pub fn flush_surface( &mut self, surface: &mut RCHandle<SkSurface>, ) -> Result<GrSemaphoresSubmitted, FlushError>
Flushes the given surface with the default FlushInfo.
Has no effect on a CPU-backed surface.
pub fn submit(&mut self, submit_info: impl Into<SubmitInfo>) -> bool
pub fn submit(&mut self, submit_info: impl Into<SubmitInfo>) -> bool
Submit outstanding work to the gpu from all previously un-submitted flushes. The return value of the submit will indicate whether or not the submission to the GPU was successful.
If the call returns true, all previously passed in semaphores in flush calls will have been submitted to the GPU and they can safely be waited on. The caller should wait on those semaphores or perform some other global synchronization before deleting the semaphores.
If it returns false, then those same semaphores will not have been submitted and we will not try to submit them again. The caller is free to delete the semaphores at any time.
If SubmitInfo::sync is SyncCpu::Yes, this function will return once the gpu has
finished with all submitted work.
If SubmitInfo::mark_boundary is
crate::gpu::ganesh::MarkFrameBoundary::Yes and the GPU supports a
way to be notified about frame boundaries, then we will notify the GPU during/after the
submission of work to the GPU. SubmitInfo::frame_id is a frame ID that is passed to
the GPU when marking a boundary. Ideally this value should be unique for each frame.
Currently marking frame boundaries is only supported with the Vulkan backend and only if
the VK_EXT_frame_boundary extension is available.
pub fn check_async_work_completion(&mut self)
pub fn check_async_work_completion(&mut self)
Checks whether any asynchronous work is complete and if so calls related callbacks.
pub fn supports_distance_field_text(&self) -> bool
pub fn supports_distance_field_text(&self) -> bool
Returns true if this context supports rendering glyphs as distance fields.
§impl RCHandle<GrDirectContext>
impl RCHandle<GrDirectContext>
pub fn compressed_backend_format(
&self,
compression: SkTextureCompressionType,
) -> Handle<GrBackendFormat>
pub fn compressed_backend_format( &self, compression: SkTextureCompressionType, ) -> Handle<GrBackendFormat>
Retrieve the BackendFormat for a given TextureCompressionType. This is
guaranteed to match the backend format used by the compressed backend texture creation
methods that take a TextureCompressionType.
The caller should check that the returned format is valid.
pub fn set_backend_texture_state(
&mut self,
backend_texture: &RefHandle<GrBackendTexture>,
state: &RCHandle<skgpu_MutableTextureState>,
) -> bool
pub fn set_backend_texture_state( &mut self, backend_texture: &RefHandle<GrBackendTexture>, state: &RCHandle<skgpu_MutableTextureState>, ) -> bool
Updates the state of the BackendTexture to have the passed in
MutableTextureState. All objects that wrap the backend surface (i.e. Surfaces
and crate::Images) will also be aware of this state change. This call does not
submit the state change to the gpu, but requires the client to call
DirectContext::submit() to send it to the GPU. The work for this call is ordered
linearly with all other calls that require submit to be called (e.g. flush).
See MutableTextureState to see what state can be set via this call.
If the backend API is Vulkan, the caller can set the MutableTextureState’s
VkImageLayout to VK_IMAGE_LAYOUT_UNDEFINED or queueFamilyIndex to VK_QUEUE_FAMILY_IGNORED
to tell Skia to not change those respective states.
Returns whether the state was successfully updated.
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_texture_state_and_return_previous( &mut self, backend_texture: &RefHandle<GrBackendTexture>, state: &RCHandle<skgpu_MutableTextureState>, ) -> Option<RCHandle<skgpu_MutableTextureState>>
Same as DirectContext::set_backend_texture_state(), but also returns the previous
state of the BackendTexture if the state was successfully updated, or None
otherwise.
pub fn set_backend_render_target_state(
&mut self,
target: &Handle<GrBackendRenderTarget>,
state: &RCHandle<skgpu_MutableTextureState>,
) -> bool
pub fn set_backend_render_target_state( &mut self, target: &Handle<GrBackendRenderTarget>, state: &RCHandle<skgpu_MutableTextureState>, ) -> bool
Updates the state of the BackendRenderTarget to have the passed in
MutableTextureState, see DirectContext::set_backend_texture_state() for details.
Returns whether the state was successfully updated.
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 set_backend_render_target_state_and_return_previous( &mut self, target: &Handle<GrBackendRenderTarget>, state: &RCHandle<skgpu_MutableTextureState>, ) -> Option<RCHandle<skgpu_MutableTextureState>>
Same as DirectContext::set_backend_render_target_state(), but also returns the
previous state of the BackendRenderTarget if the state was successfully updated, or
None otherwise.
pub fn delete_backend_texture(&mut self, texture: &RefHandle<GrBackendTexture>)
pub fn delete_backend_texture(&mut self, texture: &RefHandle<GrBackendTexture>)
Deletes a BackendTexture that was created by Skia via the explicitly allocated
backend texture API. It is the client’s responsibility to delete all these objects
before deleting the context used to create them. If the backend is Vulkan, the textures
must be deleted before abandoning the context as well. Additionally, clients should only
delete these objects on the thread for which that context is active.
pub fn precompile_shader(
&mut self,
key: &RCHandle<SkData>,
data: &RCHandle<SkData>,
) -> bool
pub fn precompile_shader( &mut self, key: &RCHandle<SkData>, data: &RCHandle<SkData>, ) -> bool
Pre-compiles a shader and populates the runtime program cache. The key and data
blobs should be the ones passed to the persistent cache, in SkSL format.
To use this API, create a DirectContext as normal, but set the persistent cache on
crate::gpu::ContextOptions to something that will save the cached shader blobs, with
a shader
cache strategy of crate::gpu::ganesh::context_options::ShaderCacheStrategy::SkSL
to ensure
the blobs are SkSL and are
suitable for pre-compilation. Then run the application and save all of the key/data
pairs that are fed to the cache. At startup (or any convenient time), call this function
for each key/data pair to compile the SkSL and populate the runtime cache.
This is only guaranteed to work if the context/device used when the shader blobs were
created is created in the same way as the one used here, and the same
crate::gpu::ContextOptions
are specified. Using cached shader blobs on a different device or driver is undefined.
pub fn id(&self) -> DirectContextId
pub fn id(&self) -> DirectContextId
Returns the unique DirectContextId of this context.
§impl RCHandle<GrGLInterface>
impl RCHandle<GrGLInterface>
pub fn new_native() -> Option<RCHandle<GrGLInterface>>
pub fn new_native() -> Option<RCHandle<GrGLInterface>>
Rather than depend on platform-specific GL headers and libraries, we require the client to
provide a struct of GL function pointers. This struct can be specified per
crate::gpu::ganesh::DirectContext as a parameter to
crate::gpu::direct_contexts::make_gl(). If no interface is passed to
crate::gpu::direct_contexts::make_gl() then a default GL interface is created
using Self::new_native(). If this returns None then
crate::gpu::direct_contexts::make_gl() will fail.
The implementation of Self::new_native() is platform-specific. Several implementations
have been provided (for GLX, WGL, EGL, etc), along with an implementation that simply
returns None. Clients should select the most appropriate one to build.
pub fn new_load_with<F>(load_fn: F) -> Option<RCHandle<GrGLInterface>>
pub fn new_load_with<F>(load_fn: F) -> Option<RCHandle<GrGLInterface>>
Generic function for creating an Interface for either OpenGL or GLES. It calls
load_fn to get each function address.
pub fn new_load_with_cstr<F>(load_fn: F) -> Option<RCHandle<GrGLInterface>>
pub fn new_load_with_cstr<F>(load_fn: F) -> Option<RCHandle<GrGLInterface>>
Generic function for creating an Interface for either OpenGL or GLES. It calls
load_fn to get each function address.
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<GrRecordingContext>
impl RCHandle<GrRecordingContext>
pub fn as_direct_context(&mut self) -> Option<RCHandle<GrDirectContext>>
pub fn as_direct_context(&mut self) -> Option<RCHandle<GrDirectContext>>
Returns this context as a DirectContext, or None if this context is not a
DirectContext.
pub fn backend(&self) -> GrBackendApi
pub fn default_backend_format(
&self,
ct: ColorType,
renderable: skgpu_Renderable,
) -> Handle<GrBackendFormat>
pub fn default_backend_format( &self, ct: ColorType, renderable: skgpu_Renderable, ) -> Handle<GrBackendFormat>
Retrieve the default BackendFormat for a given ColorType and renderability.
The caller should check that the returned format is valid.
pub fn compressed_backend_format(
&self,
compression_type: SkTextureCompressionType,
) -> Handle<GrBackendFormat>
pub fn compressed_backend_format( &self, compression_type: SkTextureCompressionType, ) -> Handle<GrBackendFormat>
Retrieve the BackendFormat for a given TextureCompressionType.
The caller should check that the returned format is valid.
pub fn abandoned(&mut self) -> bool
pub fn abandoned(&mut self) -> bool
Reports whether the DirectContext associated with this RecordingContext is
abandoned. When called on a DirectContext it may actively check whether the
underlying 3D API device/context has been disconnected before reporting the status.
If so, calling this method will transition the DirectContext to the abandoned state.
pub fn color_type_supported_as_surface(&self, color_type: ColorType) -> bool
pub fn color_type_supported_as_surface(&self, color_type: ColorType) -> bool
Can a crate::Surface be created with the given color type. To check whether MSAA is
supported use RecordingContext::max_surface_sample_count_for_color_type().
pub fn max_texture_size(&self) -> i32
pub fn max_texture_size(&self) -> i32
Gets the maximum supported texture size.
pub fn max_render_target_size(&self) -> i32
pub fn max_render_target_size(&self) -> i32
Gets the maximum supported render target size.
pub fn color_type_supported_as_image(&self, color_type: ColorType) -> bool
pub fn color_type_supported_as_image(&self, color_type: ColorType) -> bool
Can a crate::Image be created with the given color type.
pub fn supports_protected_content(&self) -> bool
pub fn supports_protected_content(&self) -> bool
Does this context support protected content?
pub fn max_surface_sample_count_for_color_type(
&self,
color_type: ColorType,
) -> usize
pub fn max_surface_sample_count_for_color_type( &self, color_type: ColorType, ) -> usize
Gets the maximum supported sample count for a color type. 1 is returned if only non-MSAA rendering is supported for the color type. 0 is returned if rendering to this color type is not supported at all.
pub fn as_recorder(&mut self) -> &mut RecorderRef
pub fn as_recorder(&mut self) -> &mut RecorderRef
Returns this context as a RecorderRef.
pub fn make_cpu_recorder(&mut self) -> Recorder<'_>
pub fn make_cpu_recorder(&mut self) -> Recorder<'_>
Returns a new CPU recorder associated with this context.
§impl RCHandle<skgpu_MutableTextureState>
impl RCHandle<skgpu_MutableTextureState>
pub fn copied(&self) -> RCHandle<skgpu_MutableTextureState>
pub fn backend(&self) -> skgpu_BackendApi
§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<'fa>( &mut self, unicode: i32, font_style: FontStyle, locale: impl AsRef<str>, font_args: impl Into<Option<&'fa Handle<skia_textlayout_FontArguments>>>, ) -> Option<RCHandle<SkTypeface>>
pub fn default_fallback_char_and_families<'fa>( &mut self, unicode: i32, family_names: &[impl AsRef<str>], font_style: FontStyle, locale: impl AsRef<str>, font_args: impl Into<Option<&'fa Handle<skia_textlayout_FontArguments>>>, ) -> 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<skresources_ImageAsset>
impl RCHandle<skresources_ImageAsset>
pub fn is_multi_frame(&self) -> bool
pub fn is_multi_frame(&self) -> bool
Returns true if the image asset is animated.
pub fn from_data(
data: impl Into<RCHandle<SkData>>,
decode_strategy: impl Into<Option<skresources_ImageDecodeStrategy>>,
) -> Option<RCHandle<skresources_ImageAsset>>
pub fn from_data( data: impl Into<RCHandle<SkData>>, decode_strategy: impl Into<Option<skresources_ImageDecodeStrategy>>, ) -> Option<RCHandle<skresources_ImageAsset>>
Create a multi-frame image asset from the given encoded data. Clients must register the required decoding image codecs before calling this.
§impl RCHandle<SkSVGClipPath>
impl RCHandle<SkSVGClipPath>
pub fn clip_path_units(&self) -> &SkSVGObjectBoundingBoxUnits_Type
pub fn set_clip_path_units(&mut self, value: SkSVGObjectBoundingBoxUnits_Type)
§impl RCHandle<SkSVGContainer>
impl RCHandle<SkSVGContainer>
pub fn append_child(&mut self, node: impl Into<RCHandle<SkSVGNode>>)
pub fn children(&self) -> &[RCHandle<SkSVGNode>]
pub fn children_typed(&self) -> Vec<TypedNode>
§impl RCHandle<SkSVGDOM>
This type represents an SVG as a node-based data structure.
impl RCHandle<SkSVGDOM>
This type represents an SVG as a node-based data structure.
To convert an SVG to a Dom, a NativeResourceProvider is required.
§Creating a Resource Provider
To create a resource provider, a crate::FontMgr is required at a minimum.
- If you don’t need font support, pass
crate::FontMgr::new_empty()as the resource provider. - To use the installed fonts on your system, pass
crate::FontMgr::default()as the resource provider.
When you pass a crate::FontMgr as the resource provider, a
crate::resources::LocalResourceProvider is created behind the scenes. This provider, in
addition to supporting typefaces, also adds support for data: URLs.
§Supporting External Resources
To support http:// or https:// external resources, enable the ureq feature and create a
[crate::resources::UReqResourceProvider].
§Custom Resource Providers
If you need more customization, you can implement the trait crate::resources::ResourceProvider.
pub fn read<R>(
reader: R,
resource_provider: impl Into<RCHandle<RustResourceProvider>>,
) -> Result<RCHandle<SkSVGDOM>, LoadError>where
R: Read,
pub fn from_str( svg: impl AsRef<str>, resource_provider: impl Into<RCHandle<RustResourceProvider>>, ) -> Result<RCHandle<SkSVGDOM>, LoadError>
pub fn from_bytes( svg: &[u8], resource_provider: impl Into<RCHandle<RustResourceProvider>>, ) -> Result<RCHandle<SkSVGDOM>, LoadError>
pub fn render(&self, canvas: &Canvas)
pub fn set_container_size(&mut self, size: impl Into<Size>)
pub fn set_container_size(&mut self, size: impl Into<Size>)
Specify a “container size” for the SVG dom.
This is used to resolve the initial viewport when the root SVG width/height are specified in relative units.
If the root dimensions are in absolute units, then the container size has no effect since the initial viewport is fixed.
§impl RCHandle<SkSVGFeFunc>
impl RCHandle<SkSVGFeFunc>
pub fn func_a() -> RCHandle<SkSVGFeFunc>
pub fn func_r() -> RCHandle<SkSVGFeFunc>
pub fn func_g() -> RCHandle<SkSVGFeFunc>
pub fn func_b() -> RCHandle<SkSVGFeFunc>
pub fn table_values(&self) -> &[f32]
pub fn amplitude(&self) -> f32
pub fn set_amplitude(&mut self, value: f32)
pub fn exponent(&self) -> f32
pub fn set_exponent(&mut self, value: f32)
pub fn intercept(&self) -> f32
pub fn set_intercept(&mut self, value: f32)
pub fn offset(&self) -> f32
pub fn set_offset(&mut self, value: f32)
pub fn slope(&self) -> f32
pub fn set_slope(&mut self, value: f32)
pub fn kind(&self) -> &SkSVGFeFuncType
pub fn set_kind(&mut self, value: SkSVGFeFuncType)
§impl RCHandle<SkSVGFeComposite>
impl RCHandle<SkSVGFeComposite>
pub fn input2(&self) -> &Input
pub fn set_input2(&mut self, value: Input)
pub fn k1(&self) -> f32
pub fn set_k1(&mut self, value: f32)
pub fn k2(&self) -> f32
pub fn set_k2(&mut self, value: f32)
pub fn k3(&self) -> f32
pub fn set_k3(&mut self, value: f32)
pub fn k4(&self) -> f32
pub fn set_k4(&mut self, value: f32)
pub fn operator(&self) -> &SkSVGFeCompositeOperator
pub fn set_operator(&mut self, value: SkSVGFeCompositeOperator)
§impl RCHandle<SkSVGFeDisplacementMap>
impl RCHandle<SkSVGFeDisplacementMap>
pub fn input2(&self) -> &Input
pub fn set_input2(&mut self, value: Input)
pub fn x_channel_selector(&self) -> &SkColorChannel
pub fn set_x_channel_selector(&mut self, value: SkColorChannel)
pub fn y_channel_selector(&self) -> &SkColorChannel
pub fn set_y_channel_selector(&mut self, value: SkColorChannel)
pub fn scale(&self) -> &f32
pub fn set_scale(&mut self, value: f32)
§impl RCHandle<SkSVGFeGaussianBlur>
impl RCHandle<SkSVGFeGaussianBlur>
pub fn std_deviation(&self) -> &StdDeviation
pub fn set_std_deviation(&mut self, value: StdDeviation)
§impl RCHandle<SkSVGFeImage>
impl RCHandle<SkSVGFeImage>
pub fn href(&self) -> &Handle<SkSVGIRI>
pub fn set_href(&mut self, value: Handle<SkSVGIRI>)
pub fn preserve_aspect_ratio(&self) -> &PreserveAspectRatio
pub fn set_preserve_aspect_ratio(&mut self, value: PreserveAspectRatio)
§impl RCHandle<SkSVGFeDistantLight>
impl RCHandle<SkSVGFeDistantLight>
pub fn azimuth(&self) -> f32
pub fn set_azimuth(&mut self, value: f32)
pub fn elevation(&self) -> f32
pub fn set_elevation(&mut self, value: f32)
§impl RCHandle<SkSVGFeSpotLight>
impl RCHandle<SkSVGFeSpotLight>
pub fn x(&self) -> f32
pub fn set_x(&mut self, value: f32)
pub fn y(&self) -> f32
pub fn set_y(&mut self, value: f32)
pub fn z(&self) -> f32
pub fn set_z(&mut self, value: f32)
pub fn points_at_x(&self) -> f32
pub fn set_points_at_x(&mut self, value: f32)
pub fn points_at_y(&self) -> f32
pub fn set_points_at_y(&mut self, value: f32)
pub fn points_at_z(&self) -> f32
pub fn set_points_at_z(&mut self, value: f32)
pub fn specular_exponent(&self) -> f32
pub fn set_specular_exponent(&mut self, value: f32)
pub fn limiting_cone_angle(&self) -> Option<f32>
pub fn set_limiting_cone_angle(&mut self, value: f32)
§impl RCHandle<SkSVGFeLighting>
impl RCHandle<SkSVGFeLighting>
pub fn surface_scale(&self) -> f32
pub fn set_surface_scale(&mut self, value: f32)
pub fn kernel_unit_length(&self) -> Option<KernelUnitLength>
pub fn set_kernel_unit_length(&mut self, value: KernelUnitLength)
§impl RCHandle<SkSVGFeSpecularLighting>
impl RCHandle<SkSVGFeSpecularLighting>
pub fn specular_constant(&self) -> f32
pub fn set_specular_constant(&mut self, value: f32)
pub fn specular_exponent(&self) -> f32
pub fn set_specular_exponent(&mut self, value: f32)
§impl RCHandle<SkSVGFeDiffuseLighting>
impl RCHandle<SkSVGFeDiffuseLighting>
pub fn diffuse_constant(&self) -> f32
pub fn set_diffuse_constant(&mut self, value: f32)
§impl RCHandle<SkSVGFeMorphology>
impl RCHandle<SkSVGFeMorphology>
pub fn operator(&self) -> &SkSVGFeMorphology_Operator
pub fn set_operator(&mut self, value: SkSVGFeMorphology_Operator)
pub fn radius(&self) -> &Radius
pub fn set_radius(&mut self, value: Radius)
§impl RCHandle<SkSVGFeTurbulence>
impl RCHandle<SkSVGFeTurbulence>
pub fn base_frequency(&self) -> &TurbulenceBaseFrequency
pub fn set_base_frequency(&mut self, value: TurbulenceBaseFrequency)
pub fn num_octaves(&self) -> i32
pub fn set_num_octaves(&mut self, value: i32)
pub fn seed(&self) -> f32
pub fn set_seed(&mut self, value: f32)
pub fn turbulence_type(&self) -> &SkSVGFeTurbulenceType_Type
pub fn set_turbulence_type(&mut self, value: SkSVGFeTurbulenceType_Type)
§impl RCHandle<SkSVGFe>
impl RCHandle<SkSVGFe>
pub fn input(&self) -> &Input
pub fn set_input(&mut self, value: Input)
pub fn result(&self) -> &Handle<SkString>
pub fn set_result(&mut self, value: Handle<SkString>)
pub fn x(&self) -> Option<&Length>
pub fn set_x(&mut self, value: Length)
pub fn y(&self) -> Option<&Length>
pub fn set_y(&mut self, value: Length)
pub fn width(&self) -> Option<&Length>
pub fn set_width(&mut self, value: Length)
pub fn height(&self) -> Option<&Length>
pub fn set_height(&mut self, value: Length)
§impl RCHandle<SkSVGFilter>
impl RCHandle<SkSVGFilter>
pub fn x(&self) -> &Length
pub fn set_x(&mut self, value: Length)
pub fn y(&self) -> &Length
pub fn set_y(&mut self, value: Length)
pub fn width(&self) -> &Length
pub fn set_width(&mut self, value: Length)
pub fn height(&self) -> &Length
pub fn set_height(&mut self, value: Length)
pub fn filter_units(&self) -> &SkSVGObjectBoundingBoxUnits_Type
pub fn set_filter_units(&mut self, value: SkSVGObjectBoundingBoxUnits_Type)
pub fn primitive_units(&self) -> &SkSVGObjectBoundingBoxUnits_Type
pub fn set_primitive_units(&mut self, value: SkSVGObjectBoundingBoxUnits_Type)
§impl RCHandle<SkSVGRadialGradient>
impl RCHandle<SkSVGRadialGradient>
pub fn cx(&self) -> &Length
pub fn set_cx(&mut self, value: Length)
pub fn cy(&self) -> &Length
pub fn set_cy(&mut self, value: Length)
pub fn r(&self) -> &Length
pub fn set_r(&mut self, value: Length)
pub fn fx(&self) -> Option<&Length>
pub fn set_fx(&mut self, value: Length)
pub fn fy(&self) -> Option<&Length>
pub fn set_fy(&mut self, value: Length)
§impl RCHandle<SkSVGGradient>
impl RCHandle<SkSVGGradient>
pub fn href(&self) -> &Handle<SkSVGIRI>
pub fn set_href(&mut self, value: Handle<SkSVGIRI>)
pub fn gradient_transform(&self) -> &Matrix
pub fn set_gradient_transform(&mut self, value: Matrix)
pub fn spread_method(&self) -> &SkSVGSpreadMethod_Type
pub fn set_spread_method(&mut self, value: SkSVGSpreadMethod_Type)
pub fn gradient_units(&self) -> &SkSVGObjectBoundingBoxUnits_Type
pub fn set_gradient_units(&mut self, value: SkSVGObjectBoundingBoxUnits_Type)
§impl RCHandle<SkSVGImage>
impl RCHandle<SkSVGImage>
pub fn x(&self) -> &Length
pub fn set_x(&mut self, value: Length)
pub fn y(&self) -> &Length
pub fn set_y(&mut self, value: Length)
pub fn width(&self) -> &Length
pub fn set_width(&mut self, value: Length)
pub fn height(&self) -> &Length
pub fn set_height(&mut self, value: Length)
pub fn href(&self) -> &Handle<SkSVGIRI>
pub fn set_href(&mut self, value: Handle<SkSVGIRI>)
pub fn preserve_aspect_ratio(&self) -> &PreserveAspectRatio
pub fn set_preserve_aspect_ratio(&mut self, value: PreserveAspectRatio)
§impl RCHandle<SkSVGMask>
impl RCHandle<SkSVGMask>
pub fn x(&self) -> &Length
pub fn set_x(&mut self, value: Length)
pub fn y(&self) -> &Length
pub fn set_y(&mut self, value: Length)
pub fn width(&self) -> &Length
pub fn set_width(&mut self, value: Length)
pub fn height(&self) -> &Length
pub fn set_height(&mut self, value: Length)
pub fn mask_units(&self) -> &SkSVGObjectBoundingBoxUnits_Type
pub fn set_mask_units(&mut self, value: SkSVGObjectBoundingBoxUnits_Type)
pub fn mask_content_units(&self) -> &SkSVGObjectBoundingBoxUnits_Type
pub fn set_mask_content_units( &mut self, value: SkSVGObjectBoundingBoxUnits_Type, )
§impl RCHandle<SkSVGNode>
impl RCHandle<SkSVGNode>
pub fn tag(&self) -> SkSVGTag
pub fn typed(self) -> TypedNode
pub fn clip_rule(&self) -> Option<&SkSVGFillRule_Type>
pub fn set_clip_rule(&mut self, value: SkSVGFillRule_Type)
pub fn color_interpolation(&self) -> Option<&SkSVGColorspace>
pub fn set_color_interpolation(&mut self, value: SkSVGColorspace)
pub fn color_interpolation_filters(&self) -> Option<&SkSVGColorspace>
pub fn set_color_interpolation_filters(&mut self, value: SkSVGColorspace)
pub fn color(&self) -> Option<&Color>
pub fn set_color(&mut self, value: Color)
pub fn fill_rule(&self) -> Option<&SkSVGFillRule_Type>
pub fn set_fill_rule(&mut self, value: SkSVGFillRule_Type)
pub fn fill(&self) -> Option<&Handle<SkSVGPaint>>
pub fn set_fill(&mut self, value: Handle<SkSVGPaint>)
pub fn fill_opacity(&self) -> Option<f32>
pub fn set_fill_opacity(&mut self, value: f32)
pub fn font_family(&self) -> Option<&FontFamily>
pub fn set_font_family(&mut self, value: FontFamily)
pub fn font_size(&self) -> Option<&FontSize>
pub fn set_font_size(&mut self, value: FontSize)
pub fn font_style(&self) -> Option<&SkSVGFontStyle_Type>
pub fn set_font_style(&mut self, value: SkSVGFontStyle_Type)
pub fn font_weight(&self) -> Option<&SkSVGFontWeight_Type>
pub fn set_font_weight(&mut self, value: SkSVGFontWeight_Type)
pub fn stroke(&self) -> Option<&Handle<SkSVGPaint>>
pub fn set_stroke(&mut self, value: Handle<SkSVGPaint>)
pub fn stroke_line_cap(&self) -> Option<&SkSVGLineCap>
pub fn set_stroke_line_cap(&mut self, value: SkSVGLineCap)
pub fn stroke_line_join(&self) -> Option<&SkSVGLineJoin_Type>
pub fn set_stroke_line_join(&mut self, value: SkSVGLineJoin_Type)
pub fn stroke_miter_limit(&self) -> Option<f32>
pub fn set_stroke_miter_limit(&mut self, value: f32)
pub fn stroke_opacity(&self) -> Option<f32>
pub fn set_stroke_opacity(&mut self, value: f32)
pub fn stroke_width(&self) -> Option<&Length>
pub fn set_stroke_width(&mut self, value: Length)
pub fn text_anchor(&self) -> Option<&SkSVGTextAnchor_Type>
pub fn set_text_anchor(&mut self, value: SkSVGTextAnchor_Type)
pub fn visibility(&self) -> Option<&SkSVGVisibility_Type>
pub fn set_visibility(&mut self, value: SkSVGVisibility_Type)
pub fn clip_path(&self) -> Option<&Handle<SkSVGFuncIRI>>
pub fn set_clip_path(&mut self, value: Handle<SkSVGFuncIRI>)
pub fn display(&self) -> Option<&SkSVGDisplay>
pub fn set_display(&mut self, value: SkSVGDisplay)
pub fn mask(&self) -> Option<&Handle<SkSVGFuncIRI>>
pub fn set_mask(&mut self, value: Handle<SkSVGFuncIRI>)
pub fn filter(&self) -> Option<&Handle<SkSVGFuncIRI>>
pub fn set_filter(&mut self, value: Handle<SkSVGFuncIRI>)
pub fn opacity(&self) -> Option<f32>
pub fn set_opacity(&mut self, value: f32)
pub fn stop_color(&self) -> Option<&Handle<SkSVGColor>>
pub fn set_stop_color(&mut self, value: Handle<SkSVGColor>)
pub fn stop_opacity(&self) -> Option<f32>
pub fn set_stop_opacity(&mut self, value: f32)
pub fn flood_color(&self) -> Option<&Handle<SkSVGColor>>
pub fn set_flood_color(&mut self, value: Handle<SkSVGColor>)
pub fn flood_opacity(&self) -> Option<f32>
pub fn set_flood_opacity(&mut self, value: f32)
pub fn lighting_color(&self) -> Option<&Handle<SkSVGColor>>
pub fn set_lighting_color(&mut self, value: Handle<SkSVGColor>)
§impl<T> RCHandle<T>where
T: NativeRefCounted + NodeSubtype,
impl<T> RCHandle<T>where
T: NativeRefCounted + NodeSubtype,
pub fn as_base(&self) -> &RCHandle<<T as NodeSubtype>::Base>
pub fn as_base_mut(&mut self) -> &mut RCHandle<<T as NodeSubtype>::Base>
§impl RCHandle<SkSVGPattern>
impl RCHandle<SkSVGPattern>
pub fn href(&self) -> &Handle<SkSVGIRI>
pub fn set_href(&mut self, value: Handle<SkSVGIRI>)
pub fn x(&self) -> Option<&Length>
pub fn set_x(&mut self, value: Length)
pub fn y(&self) -> Option<&Length>
pub fn set_y(&mut self, value: Length)
pub fn width(&self) -> Option<&Length>
pub fn set_width(&mut self, value: Length)
pub fn height(&self) -> Option<&Length>
pub fn set_height(&mut self, value: Length)
pub fn pattern_transform(&self) -> Option<&Matrix>
pub fn set_pattern_transform(&mut self, value: Matrix)
§impl RCHandle<SkSVGRect>
impl RCHandle<SkSVGRect>
pub fn x(&self) -> &Length
pub fn set_x(&mut self, value: Length)
pub fn y(&self) -> &Length
pub fn set_y(&mut self, value: Length)
pub fn width(&self) -> &Length
pub fn set_width(&mut self, value: Length)
pub fn height(&self) -> &Length
pub fn set_height(&mut self, value: Length)
pub fn rx(&self) -> Option<&Length>
pub fn set_rx(&mut self, value: Length)
pub fn ry(&self) -> Option<&Length>
pub fn set_ry(&mut self, value: Length)
§impl RCHandle<SkSVGSVG>
impl RCHandle<SkSVGSVG>
pub fn new(kind: SkSVGSVG_Type) -> RCHandle<SkSVGSVG>
pub fn x(&self) -> &Length
pub fn set_x(&mut self, value: Length)
pub fn y(&self) -> &Length
pub fn set_y(&mut self, value: Length)
pub fn width(&self) -> &Length
pub fn set_width(&mut self, value: Length)
pub fn height(&self) -> &Length
pub fn set_height(&mut self, value: Length)
pub fn preserve_aspect_ratio(&self) -> &PreserveAspectRatio
pub fn set_preserve_aspect_ratio(&mut self, value: PreserveAspectRatio)
pub fn view_box(&self) -> Option<&Rect>
pub fn set_view_box(&mut self, value: Rect)
pub fn intrinsic_size(&self) -> Size
§impl RCHandle<SkSVGTextPath>
impl RCHandle<SkSVGTextPath>
pub fn href(&self) -> &Handle<SkSVGIRI>
pub fn set_href(&mut self, value: Handle<SkSVGIRI>)
pub fn start_offset(&self) -> &Length
pub fn set_start_offset(&mut self, value: Length)
§impl RCHandle<SkSVGTransformableNode>
impl RCHandle<SkSVGTransformableNode>
pub fn set_transform(&mut self, transform: &Matrix)
pub fn transform(&self) -> &Matrix
Methods from Deref<Target = [u8]>§
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.
An empty slice returns true.
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. Importantly, this definition excludes
the \0x0B byte even though it has the Unicode White_Space property
and is removed by str::trim_start.
§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. Importantly, this definition excludes
the \0x0B byte even though it has the Unicode White_Space property
and is removed by str::trim_end.
§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. Importantly, this definition excludes
the \0x0B byte even though it has the Unicode White_Space property
and is removed by str::trim.
§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"");Sourcepub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> ⓘ
🔬This is a nightly-only experimental API. (u8_split_ascii_whitespace)
pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> ⓘ
u8_split_ascii_whitespace)Splits a byte slice by ASCII whitespace.
The returned iterator yields byte slices that are subslices of the original byte slice, separated by any amount of ASCII whitespace.
This uses the same definition as u8::is_ascii_whitespace.
§Examples
Basic usage:
#![feature(u8_split_ascii_whitespace)]
let mut iter = b"A few words".split_ascii_whitespace();
assert_eq!(Some(&b"A"[..]), iter.next());
assert_eq!(Some(&b"few"[..]), iter.next());
assert_eq!(Some(&b"words"[..]), iter.next());
assert_eq!(None, iter.next());Various kinds of ASCII whitespace are considered
(see u8::is_ascii_whitespace):
#![feature(u8_split_ascii_whitespace)]
let mut iter = b" Mary had\ta little \n\t lamb".split_ascii_whitespace();
assert_eq!(Some(&b"Mary"[..]), iter.next());
assert_eq!(Some(&b"had"[..]), iter.next());
assert_eq!(Some(&b"a"[..]), iter.next());
assert_eq!(Some(&b"little"[..]), iter.next());
assert_eq!(Some(&b"lamb"[..]), iter.next());
assert_eq!(None, iter.next());If the byte slice is empty or contains only ASCII whitespace, the iterator yields no byte slices:
#![feature(u8_split_ascii_whitespace)]
assert_eq!(b"".split_ascii_whitespace().next(), None);
assert_eq!(b" ".split_ascii_whitespace().next(), None);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 reference 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
Noneif out of bounds. - If given a range, returns the subslice corresponding to that range,
or
Noneif 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.93.0 · Sourcepub fn as_array<const N: usize>(&self) -> Option<&[T; N]>
pub fn as_array<const N: usize>(&self) -> Option<&[T; N]>
Gets a reference to the underlying array.
If N is not exactly equal to the length of self, then this method returns None.
1.93.0 · Sourcepub fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]>
pub fn as_mut_array<const N: usize>(&mut self) -> Option<&mut [T; N]>
Gets a mutable reference to the slice’s underlying array.
If N is not exactly equal to the length of self, then this method returns None.
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 zero.
§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());Because the Iterator trait cannot represent the required lifetimes,
there is no windows_mut analog to windows;
[0,1,2].windows_mut(2).collect() would violate the rules of references
(though a LendingIterator analog is possible). You can sometimes use
Cell::as_slice_of_cells in
conjunction with windows instead:
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.
If your chunk_size is a constant, consider using as_chunks instead, which will
give references to arrays of exactly that length, rather than slices.
§Panics
Panics if chunk_size is zero.
§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.
If your chunk_size is a constant, consider using as_chunks_mut instead, which will
give references to arrays of exactly that length, rather than slices.
§Panics
Panics if chunk_size is zero.
§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.
If your chunk_size is a constant, consider using as_chunks instead, which will
give references to arrays of exactly that length, rather than slices.
§Panics
Panics if chunk_size is zero.
§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.
If your chunk_size is a constant, consider using as_chunks_mut instead, which will
give references to arrays of exactly that length, rather than slices.
§Panics
Panics if chunk_size is zero.
§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]);1.88.0 · Sourcepub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]
pub unsafe fn as_chunks_unchecked<const N: usize>(&self) -> &[[T; N]]
Splits the slice into a slice of N-element arrays,
assuming that there’s no remainder.
This is the inverse operation to as_flattened.
As this is unsafe, consider whether you could use as_chunks or
as_rchunks instead, perhaps via something like
if let (chunks, []) = slice.as_chunks() or
let (chunks, []) = slice.as_chunks() else { unreachable!() };.
§Safety
This may only be called when
- The slice splits exactly into
N-element chunks (akaself.len() % N == 0). N != 0.
§Examples
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 allowed1.88.0 · Sourcepub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])
pub fn as_chunks<const N: usize>(&self) -> (&[[T; N]], &[T])
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.
The remainder is meaningful in the division sense. Given
let (chunks, remainder) = slice.as_chunks(), then:
chunks.len()equalsslice.len() / N,remainder.len()equalsslice.len() % N, andslice.len()equalschunks.len() * N + remainder.len().
You can flatten the chunks back into a slice-of-T with as_flattened.
§Panics
Panics if N is zero.
Note that this check is against a const generic parameter, not a runtime value, and thus a particular monomorphization will either always panic or it will never panic.
§Examples
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:
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']]);1.88.0 · Sourcepub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])
pub fn as_rchunks<const N: usize>(&self) -> (&[T], &[[T; N]])
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.
The remainder is meaningful in the division sense. Given
let (remainder, chunks) = slice.as_rchunks(), then:
remainder.len()equalsslice.len() % N,chunks.len()equalsslice.len() / N, andslice.len()equalschunks.len() * N + remainder.len().
You can flatten the chunks back into a slice-of-T with as_flattened.
§Panics
Panics if N is zero.
Note that this check is against a const generic parameter, not a runtime value, and thus a particular monomorphization will either always panic or it will never panic.
§Examples
let slice = ['l', 'o', 'r', 'e', 'm'];
let (remainder, chunks) = slice.as_rchunks();
assert_eq!(remainder, &['l']);
assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]);1.88.0 · Sourcepub unsafe fn as_chunks_unchecked_mut<const N: usize>(
&mut self,
) -> &mut [[T; N]]
pub unsafe fn as_chunks_unchecked_mut<const N: usize>( &mut self, ) -> &mut [[T; N]]
Splits the slice into a slice of N-element arrays,
assuming that there’s no remainder.
This is the inverse operation to as_flattened_mut.
As this is unsafe, consider whether you could use as_chunks_mut or
as_rchunks_mut instead, perhaps via something like
if let (chunks, []) = slice.as_chunks_mut() or
let (chunks, []) = slice.as_chunks_mut() else { unreachable!() };.
§Safety
This may only be called when
- The slice splits exactly into
N-element chunks (akaself.len() % N == 0). N != 0.
§Examples
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 allowed1.88.0 · Sourcepub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T])
pub fn as_chunks_mut<const N: usize>(&mut self) -> (&mut [[T; N]], &mut [T])
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.
The remainder is meaningful in the division sense. Given
let (chunks, remainder) = slice.as_chunks_mut(), then:
chunks.len()equalsslice.len() / N,remainder.len()equalsslice.len() % N, andslice.len()equalschunks.len() * N + remainder.len().
You can flatten the chunks back into a slice-of-T with as_flattened_mut.
§Panics
Panics if N is zero.
Note that this check is against a const generic parameter, not a runtime value, and thus a particular monomorphization will either always panic or it will never panic.
§Examples
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]);1.88.0 · Sourcepub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]])
pub fn as_rchunks_mut<const N: usize>(&mut self) -> (&mut [T], &mut [[T; N]])
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.
The remainder is meaningful in the division sense. Given
let (remainder, chunks) = slice.as_rchunks_mut(), then:
remainder.len()equalsslice.len() % N,chunks.len()equalsslice.len() / N, andslice.len()equalschunks.len() * N + remainder.len().
You can flatten the chunks back into a slice-of-T with as_flattened_mut.
§Panics
Panics if N is zero.
Note that this check is against a const generic parameter, not a runtime value, and thus a particular monomorphization will either always panic or it will never panic.
§Examples
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]);1.94.0 · Sourcepub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> ⓘ
pub fn array_windows<const N: usize>(&self) -> ArrayWindows<'_, T, N> ⓘ
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 zero.
Note that this check is against a const generic parameter, not a runtime value, and thus a particular monomorphization will either always panic or it will never panic.
§Examples
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.
If your chunk_size is a constant, consider using as_rchunks instead, which will
give references to arrays of exactly that length, rather than slices.
§Panics
Panics if chunk_size is zero.
§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.
If your chunk_size is a constant, consider using as_rchunks_mut instead, which will
give references to arrays of exactly that length, rather than slices.
§Panics
Panics if chunk_size is zero.
§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.
If your chunk_size is a constant, consider using as_rchunks instead, which will
give references to arrays of exactly that length, rather than slices.
§Panics
Panics if chunk_size is zero.
§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.
If your chunk_size is a constant, consider using as_rchunks_mut instead, which will
give references to arrays of exactly that length, rather than slices.
§Panics
Panics if chunk_size is zero.
§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 = ['a', 'b', 'c'];
{
let (left, right) = v.split_at(0);
assert_eq!(left, []);
assert_eq!(right, ['a', 'b', 'c']);
}
{
let (left, right) = v.split_at(2);
assert_eq!(left, ['a', 'b']);
assert_eq!(right, ['c']);
}
{
let (left, right) = v.split_at(3);
assert_eq!(left, ['a', 'b', 'c']);
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 = ['a', 'b', 'c'];
unsafe {
let (left, right) = v.split_at_unchecked(0);
assert_eq!(left, []);
assert_eq!(right, ['a', 'b', 'c']);
}
unsafe {
let (left, right) = v.split_at_unchecked(2);
assert_eq!(left, ['a', 'b']);
assert_eq!(right, ['c']);
}
unsafe {
let (left, right) = v.split_at_unchecked(3);
assert_eq!(left, ['a', 'b', 'c']);
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.98.0 · Sourcepub fn strip_circumfix<S, P>(&self, prefix: &P, suffix: &S) -> Option<&[T]>
pub fn strip_circumfix<S, P>(&self, prefix: &P, suffix: &S) -> Option<&[T]>
Returns a subslice with the prefix and suffix removed.
If the slice starts with prefix, ends with suffix, and
the prefix and suffix don’t overlap, returns the subslice after
the prefix and before the suffix, wrapped in Some.
If the slice does not start with prefix, does not end with suffix,
or the prefix and suffix overlap in the slice, returns None.
§Examples
let v = &[10, 50, 40, 30];
assert_eq!(v.strip_circumfix(&[10], &[30]), Some(&[50, 40][..]));
assert_eq!(v.strip_circumfix(&[10], &[40, 30]), Some(&[50][..]));
assert_eq!(v.strip_circumfix(&[10, 50], &[40, 30]), Some(&[][..]));
assert_eq!(v.strip_circumfix(&[50], &[30]), None);
assert_eq!(v.strip_circumfix(&[10], &[40]), None);
assert_eq!(v.strip_circumfix(&[], &[40, 30]), Some(&[10, 50][..]));
assert_eq!(v.strip_circumfix(&[10, 50], &[]), Some(&[40, 30][..]));
assert_eq!(v.strip_circumfix(&[10, 50, 40], &[50, 40, 30]), None);1.100.0 · Sourcepub fn trim_prefix<P>(&self, prefix: &P) -> &[T]
pub fn trim_prefix<P>(&self, prefix: &P) -> &[T]
Returns a subslice with the optional prefix removed.
If the slice starts with prefix, returns the subslice after the prefix. If prefix
is empty or the slice does not start with prefix, simply returns the original slice.
If prefix is equal to the original slice, returns an empty slice.
§Examples
let v = &[10, 40, 30];
// Prefix present - removes it
assert_eq!(v.trim_prefix(&[10]), &[40, 30][..]);
assert_eq!(v.trim_prefix(&[10, 40]), &[30][..]);
assert_eq!(v.trim_prefix(&[10, 40, 30]), &[][..]);
// Prefix absent - returns original slice
assert_eq!(v.trim_prefix(&[50]), &[10, 40, 30][..]);
assert_eq!(v.trim_prefix(&[10, 50]), &[10, 40, 30][..]);
let prefix : &str = "he";
assert_eq!(b"hello".trim_prefix(prefix.as_bytes()), b"llo".as_ref());1.100.0 · Sourcepub fn trim_suffix<P>(&self, suffix: &P) -> &[T]
pub fn trim_suffix<P>(&self, suffix: &P) -> &[T]
Returns a subslice with the optional suffix removed.
If the slice ends with suffix, returns the subslice before the suffix. If suffix
is empty or the slice does not end with suffix, simply returns the original slice.
If suffix is equal to the original slice, returns an empty slice.
§Examples
let v = &[10, 40, 30];
// Suffix present - removes it
assert_eq!(v.trim_suffix(&[30]), &[10, 40][..]);
assert_eq!(v.trim_suffix(&[40, 30]), &[10][..]);
assert_eq!(v.trim_suffix(&[10, 40, 30]), &[][..]);
// Suffix absent - returns original slice
assert_eq!(v.trim_suffix(&[50]), &[10, 40, 30][..]);
assert_eq!(v.trim_suffix(&[50, 30]), &[10, 40, 30][..]);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 in ascending order 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 function
may panic; even if the function exits normally, the resulting order of elements in the slice
is unspecified. See also the note on panicking below.
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.
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, or if
the Ord implementation panics.
§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 in ascending order 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 function
may panic; even if the function exits normally, the resulting order of elements in the slice
is unspecified. See also the note on panicking below.
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.
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.
§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 compare does not implement a total order, or if
the compare itself panics.
§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 in ascending order 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 function
may panic; even if the function exits normally, the resulting order of elements in the slice
is unspecified. See also the note on panicking below.
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.
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, or if
the Ord implementation panics.
§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]);Sourcepub fn partial_sort_unstable<R>(&mut self, range: R)
🔬This is a nightly-only experimental API. (slice_partial_sort_unstable)
pub fn partial_sort_unstable<R>(&mut self, range: R)
slice_partial_sort_unstable)Partially sorts the slice in ascending order without preserving the initial order of equal elements.
Upon completion, for the specified range start..end, it’s guaranteed that:
- Every element in
self[..start]is smaller than or equal to - Every element in
self[start..end], which is sorted, and smaller than or equal to - Every element in
self[end..].
This partial sort is unstable, meaning it may reorder equal elements in the specified range. It may reorder elements outside the specified range as well, but the guarantees above still hold.
This partial sort is in-place (i.e., does not allocate), and O(n + k * log(k)) worst-case, where n is the length of the slice and k is the length of the specified range.
See the documentation of sort_unstable for implementation notes.
§Panics
May panic if the implementation of Ord for T does not implement a total order, or if
the Ord implementation panics, or if the specified range is out of bounds.
§Examples
#![feature(slice_partial_sort_unstable)]
let mut v = [4, -5, 1, -3, 2];
// empty range at the beginning, nothing changed
v.partial_sort_unstable(0..0);
assert_eq!(v, [4, -5, 1, -3, 2]);
// empty range in the middle, partitioning the slice
v.partial_sort_unstable(2..2);
for i in 0..2 {
assert!(v[i] <= v[2]);
}
for i in 3..v.len() {
assert!(v[2] <= v[i]);
}
// single element range, same as select_nth_unstable
v.partial_sort_unstable(2..3);
for i in 0..2 {
assert!(v[i] <= v[2]);
}
for i in 3..v.len() {
assert!(v[2] <= v[i]);
}
// partial sort a subrange
v.partial_sort_unstable(1..4);
assert_eq!(&v[1..4], [-3, 1, 2]);
// partial sort the whole range, same as sort_unstable
v.partial_sort_unstable(..);
assert_eq!(v, [-5, -3, 1, 2, 4]);Sourcepub fn partial_sort_unstable_by<F, R>(&mut self, range: R, compare: F)
🔬This is a nightly-only experimental API. (slice_partial_sort_unstable)
pub fn partial_sort_unstable_by<F, R>(&mut self, range: R, compare: F)
slice_partial_sort_unstable)Partially sorts the slice in ascending order with a comparison function, without preserving the initial order of equal elements.
Upon completion, for the specified range start..end, it’s guaranteed that:
- Every element in
self[..start]is smaller than or equal to - Every element in
self[start..end], which is sorted, and smaller than or equal to - Every element in
self[end..].
This partial sort is unstable, meaning it may reorder equal elements in the specified range. It may reorder elements outside the specified range as well, but the guarantees above still hold.
This partial sort is in-place (i.e., does not allocate), and O(n + k * log(k)) worst-case, where n is the length of the slice and k is the length of the specified range.
See the documentation of sort_unstable_by for implementation notes.
§Panics
May panic if the compare does not implement a total order, or if
the compare itself panics, or if the specified range is out of bounds.
§Examples
#![feature(slice_partial_sort_unstable)]
let mut v = [4, -5, 1, -3, 2];
// empty range at the beginning, nothing changed
v.partial_sort_unstable_by(0..0, |a, b| b.cmp(a));
assert_eq!(v, [4, -5, 1, -3, 2]);
// empty range in the middle, partitioning the slice
v.partial_sort_unstable_by(2..2, |a, b| b.cmp(a));
for i in 0..2 {
assert!(v[i] >= v[2]);
}
for i in 3..v.len() {
assert!(v[2] >= v[i]);
}
// single element range, same as select_nth_unstable
v.partial_sort_unstable_by(2..3, |a, b| b.cmp(a));
for i in 0..2 {
assert!(v[i] >= v[2]);
}
for i in 3..v.len() {
assert!(v[2] >= v[i]);
}
// partial sort a subrange
v.partial_sort_unstable_by(1..4, |a, b| b.cmp(a));
assert_eq!(&v[1..4], [2, 1, -3]);
// partial sort the whole range, same as sort_unstable
v.partial_sort_unstable_by(.., |a, b| b.cmp(a));
assert_eq!(v, [4, 2, 1, -3, -5]);Sourcepub fn partial_sort_unstable_by_key<K, F, R>(&mut self, range: R, f: F)
🔬This is a nightly-only experimental API. (slice_partial_sort_unstable)
pub fn partial_sort_unstable_by_key<K, F, R>(&mut self, range: R, f: F)
slice_partial_sort_unstable)Partially sorts the slice in ascending order with a key extraction function, without preserving the initial order of equal elements.
Upon completion, for the specified range start..end, it’s guaranteed that:
- Every element in
self[..start]is smaller than or equal to - Every element in
self[start..end], which is sorted, and smaller than or equal to - Every element in
self[end..].
This partial sort is unstable, meaning it may reorder equal elements in the specified range. It may reorder elements outside the specified range as well, but the guarantees above still hold.
This partial sort is in-place (i.e., does not allocate), and O(n + k * log(k)) worst-case, where n is the length of the slice and k is the length of the specified range.
See the documentation of sort_unstable_by_key for implementation notes.
§Panics
May panic if the implementation of Ord for K does not implement a total order, or if
the Ord implementation panics, or if the specified range is out of bounds.
§Examples
#![feature(slice_partial_sort_unstable)]
let mut v = [4i32, -5, 1, -3, 2];
// empty range at the beginning, nothing changed
v.partial_sort_unstable_by_key(0..0, |k| k.abs());
assert_eq!(v, [4, -5, 1, -3, 2]);
// empty range in the middle, partitioning the slice
v.partial_sort_unstable_by_key(2..2, |k| k.abs());
for i in 0..2 {
assert!(v[i].abs() <= v[2].abs());
}
for i in 3..v.len() {
assert!(v[2].abs() <= v[i].abs());
}
// single element range, same as select_nth_unstable
v.partial_sort_unstable_by_key(2..3, |k| k.abs());
for i in 0..2 {
assert!(v[i].abs() <= v[2].abs());
}
for i in 3..v.len() {
assert!(v[2].abs() <= v[i].abs());
}
// partial sort a subrange
v.partial_sort_unstable_by_key(1..4, |k| k.abs());
assert_eq!(&v[1..4], [2, -3, 4]);
// partial sort the whole range, same as sort_unstable
v.partial_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 is at a sort-order position. All
elements before index will be <= to this value, and all elements after will be >= to
it.
This reordering is unstable (i.e. any element that compares equal to the nth element may end up at that position), in-place (i.e. does not allocate), and runs in O(n) time. This function is also known as “kth element” in other libraries.
Returns a triple that partitions the reordered slice:
-
The unsorted subslice before
index, whose elements all satisfyx <= self[index]. -
The element at
index. -
The unsorted subslice after
index, whose elements all satisfyx >= self[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(), and so 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 `<=` to the median, the median itself, and the items `>=` to it.
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 is at a
sort-order position. All elements before index will be <= to this value, and all
elements after will be >= to it, according to the comparator function.
This reordering is unstable (i.e. any element that compares equal to the nth element may end up at that position), in-place (i.e. does not allocate), and runs in O(n) time. This function is also known as “kth element” in other libraries.
Returns a triple partitioning the reordered slice:
-
The unsorted subslice before
index, whose elements all satisfycompare(x, self[index]).is_le(). -
The element at
index. -
The unsorted subslice after
index, whose elements all satisfycompare(x, self[index]).is_ge().
§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(), and so 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 `>=` to the median, the median itself, and the items `<=` to it, by using
// a reversed comparator.
let (before, median, after) = v.select_nth_unstable_by(2, |a, b| b.cmp(a));
assert!(before == [4, 2] || before == [2, 4]);
assert_eq!(median, &mut 1);
assert!(after == [-3, -5] || after == [-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 is at a
sort-order position. All elements before index will have keys <= to the key at index,
and all elements after will have keys >= to it.
This reordering is unstable (i.e. any element that compares equal to the nth element may end up at that position), in-place (i.e. does not allocate), and runs in O(n) time. This function is also known as “kth element” in other libraries.
Returns a triple partitioning the reordered slice:
-
The unsorted subslice before
index, whose elements all satisfyf(x) <= f(self[index]). -
The element at
index. -
The unsorted subslice after
index, whose elements all satisfyf(x) >= f(self[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 `<=` to the absolute median, the absolute median itself, and the items
// `>=` to it.
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 that are “equal” according to the given predicate function.
Returns two slices. The first contains no consecutive repeated elements. The second contains all the duplicates in no specified order.
The predicate same_bucket(x, p) is passed references to two elements from
the slice and must determine if the elements compare equal. The element p occurs
before x in the slice ([.., p, .., x, ..]), so same_bucket(x, p)
is receiving them in reversed order.
If the slice is sorted, the first returned slice contains no duplicates. For more complicated predicates however, the order (ascending vs. descending) can matter.
Both references passed to same_bucket are mutable.
This allows merged elements in the first slice by mutating p and returning true.
§Examples
#![feature(slice_partition_dedup)]
let mut slice = ["foo", "Foo", "BAZ", "Bar", "bar", "baz", "BAZ"];
let (dedup, duplicates) = slice.partition_dedup_by(|x, p| x.eq_ignore_ascii_case(p));
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']);Sourcepub fn shift_left<const N: usize>(&mut self, inserted: [T; N]) -> [T; N]
🔬This is a nightly-only experimental API. (slice_shift)
pub fn shift_left<const N: usize>(&mut self, inserted: [T; N]) -> [T; N]
slice_shift)Moves the elements of this slice N places to the left, returning the ones
that “fall off” the front, and putting inserted at the end.
Equivalently, you can think of concatenating self and inserted into one
long sequence, then returning the left-most N items and the rest into self:
self (before) inserted
vvvvvvvvvvvvvvv vvv
[1, 2, 3, 4, 5] [9]
↙ ↙ ↙ ↙ ↙ ↙
[1] [2, 3, 4, 5, 9]
^^^ ^^^^^^^^^^^^^^^
returned self (after)See also Self::shift_right and compare Self::rotate_left.
§Examples
#![feature(slice_shift)]
// Same as the diagram above
let mut a = [1, 2, 3, 4, 5];
let inserted = [9];
let returned = a.shift_left(inserted);
assert_eq!(returned, [1]);
assert_eq!(a, [2, 3, 4, 5, 9]);
// You can shift multiple items at a time
let mut a = *b"Hello world";
assert_eq!(a.shift_left(*b" peace"), *b"Hello ");
assert_eq!(a, *b"world peace");
// The name comes from this operation's similarity to bitshifts
let mut a: u8 = 0b10010110;
a <<= 3;
assert_eq!(a, 0b10110000_u8);
let mut a: [_; 8] = [1, 0, 0, 1, 0, 1, 1, 0];
a.shift_left([0; 3]);
assert_eq!(a, [1, 0, 1, 1, 0, 0, 0, 0]);
// Remember you can sub-slice to affect less that the whole slice.
// For example, this is similar to `.remove(1)` + `.insert(4, 'Z')`
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
assert_eq!(a[1..=4].shift_left(['Z']), ['b']);
assert_eq!(a, ['a', 'c', 'd', 'e', 'Z', 'f']);
// If the size matches it's equivalent to `mem::replace`
let mut a = [1, 2, 3];
assert_eq!(a.shift_left([7, 8, 9]), [1, 2, 3]);
assert_eq!(a, [7, 8, 9]);
// Some of the "inserted" elements end up returned if the slice is too short
let mut a = [];
assert_eq!(a.shift_left([1, 2, 3]), [1, 2, 3]);
let mut a = [9];
assert_eq!(a.shift_left([1, 2, 3]), [9, 1, 2]);
assert_eq!(a, [3]);Sourcepub fn shift_right<const N: usize>(&mut self, inserted: [T; N]) -> [T; N]
🔬This is a nightly-only experimental API. (slice_shift)
pub fn shift_right<const N: usize>(&mut self, inserted: [T; N]) -> [T; N]
slice_shift)Moves the elements of this slice N places to the right, returning the ones
that “fall off” the back, and putting inserted at the beginning.
Equivalently, you can think of concatenating inserted and self into one
long sequence, then returning the right-most N items and the rest into self:
inserted self (before)
vvv vvvvvvvvvvvvvvv
[0] [5, 6, 7, 8, 9]
↘ ↘ ↘ ↘ ↘ ↘
[0, 5, 6, 7, 8] [9]
^^^^^^^^^^^^^^^ ^^^
self (after) returnedSee also Self::shift_left and compare Self::rotate_right.
§Examples
#![feature(slice_shift)]
// Same as the diagram above
let mut a = [5, 6, 7, 8, 9];
let inserted = [0];
let returned = a.shift_right(inserted);
assert_eq!(returned, [9]);
assert_eq!(a, [0, 5, 6, 7, 8]);
// The name comes from this operation's similarity to bitshifts
let mut a: u8 = 0b10010110;
a >>= 3;
assert_eq!(a, 0b00010010_u8);
let mut a: [_; 8] = [1, 0, 0, 1, 0, 1, 1, 0];
a.shift_right([0; 3]);
assert_eq!(a, [0, 0, 0, 1, 0, 0, 1, 0]);
// Remember you can sub-slice to affect less that the whole slice.
// For example, this is similar to `.remove(4)` + `.insert(1, 'Z')`
let mut a = ['a', 'b', 'c', 'd', 'e', 'f'];
assert_eq!(a[1..=4].shift_right(['Z']), ['e']);
assert_eq!(a, ['a', 'Z', 'b', 'c', 'd', 'f']);
// If the size matches it's equivalent to `mem::replace`
let mut a = [1, 2, 3];
assert_eq!(a.shift_right([7, 8, 9]), [1, 2, 3]);
assert_eq!(a, [7, 8, 9]);
// Some of the "inserted" elements end up returned if the slice is too short
let mut a = [];
assert_eq!(a.shift_right([1, 2, 3]), [1, 2, 3]);
let mut a = [9];
assert_eq!(a.shift_right([1, 2, 3]), [2, 3, 9]);
assert_eq!(a, [1]);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]);1.87.0 · Sourcepub fn split_off<'a, R>(self: &mut &'a [T], range: R) -> Option<&'a [T]>where
R: OneSidedRange<usize>,
pub fn split_off<'a, R>(self: &mut &'a [T], range: R) -> Option<&'a [T]>where
R: OneSidedRange<usize>,
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
Splitting off the first three elements of a slice:
let mut slice: &[_] = &['a', 'b', 'c', 'd'];
let mut first_three = slice.split_off(..3).unwrap();
assert_eq!(slice, &['d']);
assert_eq!(first_three, &['a', 'b', 'c']);Splitting off a slice starting with the third element:
let mut slice: &[_] = &['a', 'b', 'c', 'd'];
let mut tail = slice.split_off(2..).unwrap();
assert_eq!(slice, &['a', 'b']);
assert_eq!(tail, &['c', 'd']);Getting None when range is out of bounds:
let mut slice: &[_] = &['a', 'b', 'c', 'd'];
assert_eq!(None, slice.split_off(5..));
assert_eq!(None, slice.split_off(..5));
assert_eq!(None, slice.split_off(..=4));
let expected: &[char] = &['a', 'b', 'c', 'd'];
assert_eq!(Some(expected), slice.split_off(..4));1.87.0 · Sourcepub fn split_off_mut<'a, R>(
self: &mut &'a mut [T],
range: R,
) -> Option<&'a mut [T]>where
R: OneSidedRange<usize>,
pub fn split_off_mut<'a, R>(
self: &mut &'a mut [T],
range: R,
) -> Option<&'a mut [T]>where
R: OneSidedRange<usize>,
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
Splitting off the first three elements of a slice:
let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
let mut first_three = slice.split_off_mut(..3).unwrap();
assert_eq!(slice, &mut ['d']);
assert_eq!(first_three, &mut ['a', 'b', 'c']);Splitting off a slice starting with the third element:
let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
let mut tail = slice.split_off_mut(2..).unwrap();
assert_eq!(slice, &mut ['a', 'b']);
assert_eq!(tail, &mut ['c', 'd']);Getting None when range is out of bounds:
let mut slice: &mut [_] = &mut ['a', 'b', 'c', 'd'];
assert_eq!(None, slice.split_off_mut(5..));
assert_eq!(None, slice.split_off_mut(..5));
assert_eq!(None, slice.split_off_mut(..=4));
let expected: &mut [_] = &mut ['a', 'b', 'c', 'd'];
assert_eq!(Some(expected), slice.split_off_mut(..4));1.87.0 · Sourcepub fn split_off_first<'a>(self: &mut &'a [T]) -> Option<&'a T>
pub fn split_off_first<'a>(self: &mut &'a [T]) -> Option<&'a T>
Removes the first element of the slice and returns a reference to it.
Returns None if the slice is empty.
§Examples
let mut slice: &[_] = &['a', 'b', 'c'];
let first = slice.split_off_first().unwrap();
assert_eq!(slice, &['b', 'c']);
assert_eq!(first, &'a');1.87.0 · Sourcepub fn split_off_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
pub fn split_off_first_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
Removes the first element of the slice and returns a mutable reference to it.
Returns None if the slice is empty.
§Examples
let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
let first = slice.split_off_first_mut().unwrap();
*first = 'd';
assert_eq!(slice, &['b', 'c']);
assert_eq!(first, &'d');1.87.0 · Sourcepub fn split_off_last<'a>(self: &mut &'a [T]) -> Option<&'a T>
pub fn split_off_last<'a>(self: &mut &'a [T]) -> Option<&'a T>
Removes the last element of the slice and returns a reference to it.
Returns None if the slice is empty.
§Examples
let mut slice: &[_] = &['a', 'b', 'c'];
let last = slice.split_off_last().unwrap();
assert_eq!(slice, &['a', 'b']);
assert_eq!(last, &'c');1.87.0 · Sourcepub fn split_off_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
pub fn split_off_last_mut<'a>(self: &mut &'a mut [T]) -> Option<&'a mut T>
Removes the last element of the slice and returns a mutable reference to it.
Returns None if the slice is empty.
§Examples
let mut slice: &mut [_] = &mut ['a', 'b', 'c'];
let last = slice.split_off_last_mut().unwrap();
*last = 'd';
assert_eq!(slice, &['a', 'b']);
assert_eq!(last, &'d');1.86.0 · Sourcepub unsafe fn get_disjoint_unchecked_mut<I, const N: usize>(
&mut self,
indices: [I; N],
) -> [&mut <I as SliceIndex<[T]>>::Output; N]
pub unsafe fn get_disjoint_unchecked_mut<I, const N: usize>( &mut self, indices: [I; N], ) -> [&mut <I as SliceIndex<[T]>>::Output; N]
Returns mutable references to many indices at once, without doing any checks.
An index can be either a usize, a Range or a RangeInclusive. Note
that this method takes an array, so all indices must be of the same type.
If passed an array of usizes this method gives back an array of mutable references
to single elements, while if passed an array of ranges it gives back an array of
mutable references to slices.
For a safe alternative see get_disjoint_mut.
§Safety
Calling this method with overlapping or out-of-bounds indices is undefined behavior even if the resulting references are not used.
§Examples
let x = &mut [1, 2, 4];
unsafe {
let [a, b] = x.get_disjoint_unchecked_mut([0, 2]);
*a *= 10;
*b *= 100;
}
assert_eq!(x, &[10, 2, 400]);
unsafe {
let [a, b] = x.get_disjoint_unchecked_mut([0..1, 1..3]);
a[0] = 8;
b[0] = 88;
b[1] = 888;
}
assert_eq!(x, &[8, 88, 888]);
unsafe {
let [a, b] = x.get_disjoint_unchecked_mut([1..=2, 0..=0]);
a[0] = 11;
a[1] = 111;
b[0] = 1;
}
assert_eq!(x, &[1, 11, 111]);1.86.0 · Sourcepub fn get_disjoint_mut<I, const N: usize>(
&mut self,
indices: [I; N],
) -> Result<[&mut <I as SliceIndex<[T]>>::Output; N], GetDisjointMutError>
pub fn get_disjoint_mut<I, const N: usize>( &mut self, indices: [I; N], ) -> Result<[&mut <I as SliceIndex<[T]>>::Output; N], GetDisjointMutError>
Returns mutable references to many indices at once.
An index can be either a usize, a Range or a RangeInclusive. Note
that this method takes an array, so all indices must be of the same type.
If passed an array of usizes this method gives back an array of mutable references
to single elements, while if passed an array of ranges it gives back an array of
mutable references to slices.
Returns an error if any index is out-of-bounds, or if there are overlapping indices. An empty range is not considered to overlap if it is located at the beginning or at the end of another range, but is considered to overlap if it is located in the middle.
This method does a O(n^2) check to check that there are no overlapping indices, so be careful when passing many indices.
§Examples
let v = &mut [1, 2, 3];
if let Ok([a, b]) = v.get_disjoint_mut([0, 2]) {
*a = 413;
*b = 612;
}
assert_eq!(v, &[413, 2, 612]);
if let Ok([a, b]) = v.get_disjoint_mut([0..1, 1..3]) {
a[0] = 8;
b[0] = 88;
b[1] = 888;
}
assert_eq!(v, &[8, 88, 888]);
if let Ok([a, b]) = v.get_disjoint_mut([1..=2, 0..=0]) {
a[0] = 11;
a[1] = 111;
b[0] = 1;
}
assert_eq!(v, &[1, 11, 111]);1.94.0 · Sourcepub fn element_offset(&self, element: &T) -> Option<usize>
pub fn element_offset(&self, element: &T) -> Option<usize>
Returns the index that an element reference points to.
Returns None if element does not point to the start of an element within the slice.
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:
let nums: &[u32] = &[1, 7, 1, 1];
let num = &nums[2];
assert_eq!(num, &1);
assert_eq!(nums.element_offset(num), Some(2));Returning None with an unaligned element:
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.element_offset(ok_elm), Some(0)); // Points to element 0
assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 11.98.0 · Sourcepub fn subslice_range(&self, subslice: &[T]) -> Option<Range<usize>>
pub fn subslice_range(&self, subslice: &[T]) -> Option<Range<usize>>
Returns the range of indices that a subslice points to.
Returns None if subslice does not point within the slice or if it is not aligned with the
elements in the slice.
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:
use core::range::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(Range { start: 0, end: 0 }));
assert_eq!(iter.next(), Some(Range { start: 1, end: 3 }));
assert_eq!(iter.next(), Some(Range { start: 4, end: 4 }));
assert_eq!(iter.next(), Some(Range { start: 5, end: 6 }));Sourcepub fn as_slice(&self) -> &[T]
🔬This is a nightly-only experimental API. (str_as_str)
pub fn as_slice(&self) -> &[T]
str_as_str)Returns the same slice &[T].
This method is redundant when used directly on &[T], but
it helps dereferencing other “container” types to slices,
for example Box<[T]> or Arc<[T]>.
Sourcepub fn as_mut_slice(&mut self) -> &mut [T]
🔬This is a nightly-only experimental API. (str_as_str)
pub fn as_mut_slice(&mut self) -> &mut [T]
str_as_str)Returns the same slice &mut [T].
This method is redundant when used directly on &mut [T], but
it helps dereferencing other “container” types to slices,
for example Box<[T]> or MutexGuard<[T]>.
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.
See the Utf8Chunk type for documentation of the items yielded by this iterator.
§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 in ascending order, 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 function
may panic; even if the function exits normally, the resulting order of elements in the slice
is unspecified. See also the note on panicking below.
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, or if
the Ord implementation itself panics.
All safe functions on slices preserve the invariant that even if the function panics, all
original elements will remain in the slice and any possible modifications via interior
mutability are observed in the input. This ensures that recovery code (for instance inside
of a Drop or following a catch_unwind) will still have access to all the original
elements. For instance, if the slice belongs to a Vec, the Vec::drop method will be able
to dispose of all contained elements.
§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 in ascending order 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 function may
panic; even if the function exits normally, the resulting order of elements in the slice is
unspecified. See also the note on panicking below.
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, or if compare itself panics.
All safe functions on slices preserve the invariant that even if the function panics, all
original elements will remain in the slice and any possible modifications via interior
mutability are observed in the input. This ensures that recovery code (for instance inside
of a Drop or following a catch_unwind) will still have access to all the original
elements. For instance, if the slice belongs to a Vec, the Vec::drop method will be able
to dispose of all contained elements.
§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 in ascending order 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 function
may panic; even if the function exits normally, the resulting order of elements in the slice
is unspecified. See also the note on panicking below.
§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, or if
the Ord implementation or the key-function f panics.
All safe functions on slices preserve the invariant that even if the function panics, all
original elements will remain in the slice and any possible modifications via interior
mutability are observed in the input. This ensures that recovery code (for instance inside
of a Drop or following a catch_unwind) will still have access to all the original
elements. For instance, if the slice belongs to a Vec, the Vec::drop method will be able
to dispose of all contained elements.
§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 in ascending order 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 function
may panic; even if the function exits normally, the resulting order of elements in the slice
is unspecified. See also the note on panicking below.
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, or if
the Ord implementation panics.
All safe functions on slices preserve the invariant that even if the function panics, all
original elements will remain in the slice and any possible modifications via interior
mutability are observed in the input. This ensures that recovery code (for instance inside
of a Drop or following a catch_unwind) will still have access to all the original
elements. For instance, if the slice belongs to a Vec, the Vec::drop method will be able
to dispose of all contained elements.
§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_ext)
pub fn to_vec_in<A>(&self, alloc: A) -> Vec<T, A>
allocator_ext)Copies self into a new Vec with an allocator.
§Examples
#![feature(allocator_ext)]
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 ⓘ
renamed to join
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,
RCHandle<H> is conditionally Send and can be sent to
another thread when its reference count is 1.
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> Debug for RCHandle<N>where
N: NativeRefCounted,
RCHandle<N>: DebugAttributes,
impl<N> Debug for RCHandle<N>where
N: NativeRefCounted,
RCHandle<N>: DebugAttributes,
§impl DebugAttributes for RCHandle<SkSVGClipPath>
impl DebugAttributes for RCHandle<SkSVGClipPath>
§impl DebugAttributes for RCHandle<SkSVGContainer>
impl DebugAttributes for RCHandle<SkSVGContainer>
§impl DebugAttributes for RCHandle<SkSVGDefs>
impl DebugAttributes for RCHandle<SkSVGDefs>
§impl DebugAttributes for RCHandle<SkSVGFeBlend>
impl DebugAttributes for RCHandle<SkSVGFeBlend>
§impl DebugAttributes for RCHandle<SkSVGFeColorMatrix>
impl DebugAttributes for RCHandle<SkSVGFeColorMatrix>
§impl DebugAttributes for RCHandle<SkSVGFeFunc>
impl DebugAttributes for RCHandle<SkSVGFeFunc>
§impl DebugAttributes for RCHandle<SkSVGFeComponentTransfer>
impl DebugAttributes for RCHandle<SkSVGFeComponentTransfer>
§impl DebugAttributes for RCHandle<SkSVGFeComposite>
impl DebugAttributes for RCHandle<SkSVGFeComposite>
§impl DebugAttributes for RCHandle<SkSVGFeDisplacementMap>
impl DebugAttributes for RCHandle<SkSVGFeDisplacementMap>
§impl DebugAttributes for RCHandle<SkSVGFeFlood>
impl DebugAttributes for RCHandle<SkSVGFeFlood>
§impl DebugAttributes for RCHandle<SkSVGFeGaussianBlur>
impl DebugAttributes for RCHandle<SkSVGFeGaussianBlur>
§impl DebugAttributes for RCHandle<SkSVGFeImage>
impl DebugAttributes for RCHandle<SkSVGFeImage>
§impl DebugAttributes for RCHandle<SkSVGFeDistantLight>
impl DebugAttributes for RCHandle<SkSVGFeDistantLight>
§impl DebugAttributes for RCHandle<SkSVGFePointLight>
impl DebugAttributes for RCHandle<SkSVGFePointLight>
§impl DebugAttributes for RCHandle<SkSVGFeSpotLight>
impl DebugAttributes for RCHandle<SkSVGFeSpotLight>
§impl DebugAttributes for RCHandle<SkSVGFeLighting>
impl DebugAttributes for RCHandle<SkSVGFeLighting>
§impl DebugAttributes for RCHandle<SkSVGFeSpecularLighting>
impl DebugAttributes for RCHandle<SkSVGFeSpecularLighting>
§impl DebugAttributes for RCHandle<SkSVGFeDiffuseLighting>
impl DebugAttributes for RCHandle<SkSVGFeDiffuseLighting>
§impl DebugAttributes for RCHandle<SkSVGFeMergeNode>
impl DebugAttributes for RCHandle<SkSVGFeMergeNode>
§impl DebugAttributes for RCHandle<SkSVGFeMerge>
impl DebugAttributes for RCHandle<SkSVGFeMerge>
§impl DebugAttributes for RCHandle<SkSVGFeMorphology>
impl DebugAttributes for RCHandle<SkSVGFeMorphology>
§impl DebugAttributes for RCHandle<SkSVGFeOffset>
impl DebugAttributes for RCHandle<SkSVGFeOffset>
§impl DebugAttributes for RCHandle<SkSVGFeTurbulence>
impl DebugAttributes for RCHandle<SkSVGFeTurbulence>
§impl DebugAttributes for RCHandle<SkSVGFe>
impl DebugAttributes for RCHandle<SkSVGFe>
§impl DebugAttributes for RCHandle<SkSVGFilter>
impl DebugAttributes for RCHandle<SkSVGFilter>
§impl DebugAttributes for RCHandle<SkSVGG>
impl DebugAttributes for RCHandle<SkSVGG>
§impl DebugAttributes for RCHandle<SkSVGLinearGradient>
impl DebugAttributes for RCHandle<SkSVGLinearGradient>
§impl DebugAttributes for RCHandle<SkSVGRadialGradient>
impl DebugAttributes for RCHandle<SkSVGRadialGradient>
§impl DebugAttributes for RCHandle<SkSVGGradient>
impl DebugAttributes for RCHandle<SkSVGGradient>
§impl DebugAttributes for RCHandle<SkSVGImage>
impl DebugAttributes for RCHandle<SkSVGImage>
§impl DebugAttributes for RCHandle<SkSVGMask>
impl DebugAttributes for RCHandle<SkSVGMask>
§impl DebugAttributes for RCHandle<SkSVGNode>
impl DebugAttributes for RCHandle<SkSVGNode>
§impl DebugAttributes for RCHandle<SkSVGPattern>
impl DebugAttributes for RCHandle<SkSVGPattern>
§impl DebugAttributes for RCHandle<SkSVGCircle>
impl DebugAttributes for RCHandle<SkSVGCircle>
§impl DebugAttributes for RCHandle<SkSVGEllipse>
impl DebugAttributes for RCHandle<SkSVGEllipse>
§impl DebugAttributes for RCHandle<SkSVGLine>
impl DebugAttributes for RCHandle<SkSVGLine>
§impl DebugAttributes for RCHandle<SkSVGPath>
impl DebugAttributes for RCHandle<SkSVGPath>
§impl DebugAttributes for RCHandle<SkSVGPoly>
impl DebugAttributes for RCHandle<SkSVGPoly>
§impl DebugAttributes for RCHandle<SkSVGRect>
impl DebugAttributes for RCHandle<SkSVGRect>
§impl DebugAttributes for RCHandle<SkSVGShape>
impl DebugAttributes for RCHandle<SkSVGShape>
§impl DebugAttributes for RCHandle<SkSVGStop>
impl DebugAttributes for RCHandle<SkSVGStop>
§impl DebugAttributes for RCHandle<SkSVGSVG>
impl DebugAttributes for RCHandle<SkSVGSVG>
§impl DebugAttributes for RCHandle<SkSVGTextContainer>
impl DebugAttributes for RCHandle<SkSVGTextContainer>
§impl DebugAttributes for RCHandle<SkSVGText>
impl DebugAttributes for RCHandle<SkSVGText>
§impl DebugAttributes for RCHandle<SkSVGTSpan>
impl DebugAttributes for RCHandle<SkSVGTSpan>
§impl DebugAttributes for RCHandle<SkSVGTextLiteral>
impl DebugAttributes for RCHandle<SkSVGTextLiteral>
§impl DebugAttributes for RCHandle<SkSVGTextPath>
impl DebugAttributes for RCHandle<SkSVGTextPath>
§impl DebugAttributes for RCHandle<SkSVGTransformableNode>
impl DebugAttributes for RCHandle<SkSVGTransformableNode>
§impl DebugAttributes for RCHandle<SkSVGUse>
impl DebugAttributes for RCHandle<SkSVGUse>
§impl<T> Deref for RCHandle<T>where
T: NativeRefCounted + NodeSubtype,
impl<T> Deref for RCHandle<T>where
T: NativeRefCounted + NodeSubtype,
§impl<T> DerefMut for RCHandle<T>where
T: NativeRefCounted + NodeSubtype,
impl<T> DerefMut for RCHandle<T>where
T: NativeRefCounted + NodeSubtype,
§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,
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<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<Box<dyn ResourceProvider>> for RCHandle<RustResourceProvider>
impl From<Box<dyn ResourceProvider>> for RCHandle<RustResourceProvider>
§fn from(
resource_provider: Box<dyn ResourceProvider>,
) -> RCHandle<RustResourceProvider>
fn from( resource_provider: Box<dyn ResourceProvider>, ) -> RCHandle<RustResourceProvider>
§impl From<RCHandle<SkFontMgr>> for RCHandle<RustResourceProvider>
Support a direct conversion from a FontMgr into a local native resource provider.
impl From<RCHandle<SkFontMgr>> for RCHandle<RustResourceProvider>
Support a direct conversion from a FontMgr into a local native resource provider.
§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<T> From<T> for RCHandle<RustResourceProvider>where
T: ResourceProvider + 'static,
impl<T> From<T> for RCHandle<RustResourceProvider>where
T: ResourceProvider + 'static,
§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<SkMeshSpecification>
impl Send for RCHandle<SkPathEffect>
impl Send for RCHandle<SkPicture>
impl Send for RCHandle<SkPixelRef>
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<SkMeshSpecification>
impl Sync for RCHandle<SkPathEffect>
impl Sync for RCHandle<SkPicture>
impl Sync for RCHandle<SkPixelRef>
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> !Send for RCHandle<Native>
impl<Native> !Sync for RCHandle<Native>
impl<Native> Freeze for RCHandle<Native>
impl<Native> RefUnwindSafe for RCHandle<Native>where
Native: RefUnwindSafe,
impl<Native> Unpin for RCHandle<Native>
impl<Native> UnsafeUnpin 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
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§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.§impl<T> DowncastSync for T
impl<T> DowncastSync for T
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
§impl<T> NoneValue for Twhere
T: Default,
impl<T> NoneValue for Twhere
T: Default,
type NoneType = T
§fn null_value() -> T
fn null_value() -> T
impl<T> Read<Exclusive, BecauseExclusive> for Twhere
T: ?Sized,
§impl<F, T, S> SimdInto<T, S> for Fwhere
T: SimdFrom<F, S>,
S: Simd,
impl<F, T, S> SimdInto<T, S> for Fwhere
T: SimdFrom<F, S>,
S: Simd,
Source§impl<T> ToHex for T
impl<T> ToHex for T
Source§fn encode_hex<U>(&self) -> Uwhere
U: FromIterator<char>,
fn encode_hex<U>(&self) -> Uwhere
U: FromIterator<char>,
self into the result. Lower case
letters are used (e.g. f9b4ca)Source§fn encode_hex_upper<U>(&self) -> Uwhere
U: FromIterator<char>,
fn encode_hex_upper<U>(&self) -> Uwhere
U: FromIterator<char>,
self into the result. Upper case
letters are used (e.g. F9B4CA)