Struct NonZeroChar

Source
pub struct NonZeroChar(/* private fields */);
Expand description

A char that is known not to equal zero.

This enables some memory layout optimization. For example, Option<NonZeroChar> is the same size as char:

use std::mem::size_of;
assert_eq!(size_of::<Option<NonZeroChar>>(), size_of::<NonZeroChar>());

§Layout

NonZeroChar is guaranteed to have the same layout and bit validity as char with the exception that 0 is not a valid instance.

Currently implemented using NonZeroU32, there are not as many invalid values as real char

Option<NonZeroChar> is guaranteed to be compatible with char, including in FFI.

Thanks to the null pointer optimization, NonZeroChar and Option<NonZeroChar> are guaranteed to have the same size and alignment:


assert_eq!(size_of::<NonZeroChar>(), size_of::<Option<NonZeroChar>>());
assert_eq!(align_of::<NonZeroChar>(), align_of::<Option<NonZeroChar>>());

Implementations§

Source§

impl NonZeroChar

Source

pub const MIN: Self

The lowest valid code point a NonZeroChar can have, '\x01'.

Unlike integer types, char actually has a gap in the middle, meaning that the range of possible chars is smaller than you might expect. Ranges of char will automatically hop this gap for you:

let dist = u32::from(char::MAX) - u32::from(char::MIN);
let size = (char::MIN..=char::MAX).count() as u32;
assert!(size < dist);

Despite this gap, the MIN and MAX values can be used as bounds for all char values.

§Examples
let c: char = something_which_returns_char();
assert!(char::MIN <= c);

let value_at_min = u32::from(NonZeroChar::MIN);
assert_eq!(char::from_u32(value_at_min), Some('\x01'));
Source

pub const MAX: Self

The highest valid code point a char can have, '\u{10FFFF}'.

Unlike integer types, char actually has a gap in the middle, meaning that the range of possible chars is smaller than you might expect. Ranges of char will automatically hop this gap for you:

let dist = u32::from(NonZeroChar::MAX) - u32::from(NonZeroChar::MIN);
let size = NonZeroChar::MIN.iter_inclusive(NonZeroChar::MAX).count() as u32;
assert!(size < dist);

Despite this gap, the MIN and MAX values can be used as bounds for all char values.

§Examples
let c: char = something_which_returns_char();
assert!(c <= char::MAX);

let value_at_max = u32::from(NonZeroChar::MAX);
assert_eq!(char::from_u32(value_at_max), Some('\u{10FFFF}'));
assert_eq!(NonZeroChar::from_u32(value_at_max + 1), None);
Source

pub const REPLACEMENT_CHARACTER: Self

U+FFFD REPLACEMENT CHARACTER (�) is used in Unicode to represent a decoding error.

It can occur, for example, when giving ill-formed UTF-8 bytes to String::from_utf8_lossy.

Source

pub const UNICODE_VERSION: (u8, u8, u8) = char::UNICODE_VERSION

The version of Unicode that the Unicode parts of char and str methods are based on.

New versions of Unicode are released regularly and subsequently all methods in the standard library depending on Unicode are updated. Therefore the behavior of some char and str methods and the value of this constant changes over time. This is not considered to be a breaking change.

The version numbering scheme is explained in Unicode 11.0 or later, Section 3.1 Versions of the Unicode Standard.

Source

pub const fn new(ch: char) -> Option<Self>

Creates a non-zero if the given value is not zero.

§Examples
assert_eq!(NonZeroChar::new('a').map(NonZeroChar::get), Some('a'));
assert_eq!(NonZeroChar::new('\0').map(NonZeroChar::get), None);
Source

pub const unsafe fn new_unchecked(ch: char) -> Self

Creates a non-zero without checking whether the value is non-zero. This results in undefined behavior if the value is zero.

§Safety

The value must not be zero (‘\0’).

Source

pub const fn get(self) -> char

Returns the contained value as a primitive type.

Source

pub fn iter_inclusive(self, max: Self) -> RangeInclusiveIter

Like self..=max

§Examples
let mut iter = NonZeroChar::new('a').unwrap()
    .iter_inclusive(NonZeroChar::new('c').unwrap());
assert_eq!(iter.next(), Some(NonZeroChar::new('a').unwrap()));
assert_eq!(iter.next(), Some(NonZeroChar::new('b').unwrap()));
assert_eq!(iter.next(), Some(NonZeroChar::new('c').unwrap()));
assert_eq!(iter.next(), None);
Source

pub fn decode_utf16<I: IntoIterator<Item = u16>>( iter: I, ) -> DecodeUtf16<I::IntoIter>

Creates an iterator over the native endian UTF-16 encoded code points in iter, returning unpaired surrogates as Errs.

§Examples

Basic usage:

// 𝄞mus<invalid>ic<invalid>
let v = [
    0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
];

assert_eq!(
    char::decode_utf16(v)
        .map(|r| r.map_err(|e| e.unpaired_surrogate()))
        .collect::<Vec<_>>(),
    vec![
        Ok('𝄞'),
        Ok('m'), Ok('u'), Ok('s'),
        Err(0xDD1E),
        Ok('i'), Ok('c'),
        Err(0xD834)
    ]
);

A lossy decoder can be obtained by replacing Err results with the replacement character:

// 𝄞mus<invalid>ic<invalid>
let v = [
    0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
];

assert_eq!(
    char::decode_utf16(v)
       .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
       .collect::<String>(),
    "𝄞mus�ic�"
);
Source

pub fn as_nonzero_u32(self) -> NonZeroU32

Converts a NonZeroChar to a NonZeroU32

§Examples
let ch = NonZeroChar::new('\x1b').unwrap();
let num = NonZeroU32::new(0x1b).unwrap();
assert_eq!(ch.as_nonzero_u32(), num);
Source

pub fn as_u32(self) -> u32

Converts a NonZeroChar to a u32

§Examples
let ch = NonZeroChar::new('\x1b').unwrap();
assert_eq!(ch.as_u32(), 0x1b);
Source

pub const fn from_u32(i: u32) -> Option<Self>

Converts a u32 to a NonZeroChar.

Note that all NonZeroChars are valid u32s, and can be cast to one with as_u32:

let c = '💯';
let i = c as u32;

assert_eq!(128175, i);

However, the reverse is not true: not all valid u32s are valid chars. from_u32() will return None if the input is not a valid value for a char.

For an unsafe version of this function which ignores these checks, see from_u32_unchecked.

§Examples

Basic usage:

let c = NonZeroChar::from_u32(0x2764);

assert_eq!(Some(NonZeroChar::new('❤').unwrap()), c);

Returning None when the input is not a valid char:

let c = NonZeroChar::from_u32(0x110000);

assert_eq!(None, c);

Returning None when the input by zero:

let c = NonZeroChar::from_u32(0);

assert_eq!(None, c);
Source

pub const unsafe fn from_u32_unchecked(i: u32) -> Self

Converts a u32 to a char, ignoring validity.

Note that all chars are valid u32s, and can be cast to one with as:

let c = '💯';
let i = c as u32;

assert_eq!(128175, i);

However, the reverse is not true: not all valid u32s are valid chars. from_u32_unchecked() will ignore this, and blindly cast to char, possibly creating an invalid one.

§Safety

The value must not be zero (‘\0’).

This function is unsafe, as it may construct invalid char values.

For a safe version of this function, see the from_u32 function.

§Examples

Basic usage:

let c = unsafe { NonZeroChar::from_u32_unchecked(0x2764) };

assert_eq!(NonZeroChar::new('❤').unwrap(), c);
Source

pub const fn from_digit(num: u32, radix: u32) -> Option<Self>

Converts a digit in the given radix to a char.

A ‘radix’ here is sometimes also called a ‘base’. A radix of two indicates a binary number, a radix of ten, decimal, and a radix of sixteen, hexadecimal, to give some common values. Arbitrary radices are supported.

from_digit() will return None if the input is not a digit in the given radix.

§Panics

Panics if given a radix larger than 36.

§Examples

Basic usage:

let c = NonZeroChar::from_digit(4, 10);
let d = NonZeroChar::new('4').unwrap();

assert_eq!(Some(d), c);

// Decimal 11 is a single digit in base 16
let c = NonZeroChar::from_digit(11, 16);
let d = NonZeroChar::new('b').unwrap();

assert_eq!(Some(d), c);

Returning None when the input is not a digit:

let c = NonZeroChar::from_digit(20, 10);

assert_eq!(None, c);

Passing a large radix, causing a panic:

// this panics
let _c = NonZeroChar::from_digit(1, 37);
Source

pub fn is_digit(self, radix: u32) -> bool

Checks if a char is a digit in the given radix.

A ‘radix’ here is sometimes also called a ‘base’. A radix of two indicates a binary number, a radix of ten, decimal, and a radix of sixteen, hexadecimal, to give some common values. Arbitrary radices are supported.

Compared to is_numeric(), this function only recognizes the characters 0-9, a-z and A-Z.

‘Digit’ is defined to be only the following characters:

  • 0-9
  • a-z
  • A-Z

For a more comprehensive understanding of ‘digit’, see is_numeric().

§Panics

Panics if given a radix smaller than 2 or larger than 36.

§Examples

Basic usage:

assert!('1'.is_digit(10));
assert!('f'.is_digit(16));
assert!(!'f'.is_digit(10));

Passing a large radix, causing a panic:

// this panics
'1'.is_digit(37);

Passing a small radix, causing a panic:

// this panics
'1'.is_digit(1);
Source

pub const fn to_digit(self, radix: u32) -> Option<u32>

Converts a char to a digit in the given radix.

A ‘radix’ here is sometimes also called a ‘base’. A radix of two indicates a binary number, a radix of ten, decimal, and a radix of sixteen, hexadecimal, to give some common values. Arbitrary radices are supported.

‘Digit’ is defined to be only the following characters:

  • 0-9
  • a-z
  • A-Z
§Errors

Returns None if the char does not refer to a digit in the given radix.

§Panics

Panics if given a radix smaller than 2 or larger than 36.

§Examples

Basic usage:

assert_eq!('1'.to_digit(10), Some(1));
assert_eq!('f'.to_digit(16), Some(15));

Passing a non-digit results in failure:

assert_eq!('f'.to_digit(10), None);
assert_eq!('z'.to_digit(16), None);

Passing a large radix, causing a panic:

// this panics
let _ = '1'.to_digit(37);

Passing a small radix, causing a panic:

// this panics
let _ = '1'.to_digit(1);
Source

pub fn escape_unicode(self) -> EscapeUnicode

Returns an iterator that yields the hexadecimal Unicode escape of a character as chars.

This will escape characters with the Rust syntax of the form \u{NNNNNN} where NNNNNN is a hexadecimal representation.

§Examples

As an iterator:

for c in '❤'.escape_unicode() {
    print!("{c}");
}
println!();

Using println! directly:

println!("{}", '❤'.escape_unicode());

Both are equivalent to:

println!("\\u{{2764}}");

Using to_string:

assert_eq!('❤'.escape_unicode().to_string(), "\\u{2764}");
Source

pub fn escape_debug(self) -> EscapeDebug

Returns an iterator that yields the literal escape code of a character as chars.

This will escape the characters similar to the Debug implementations of str or char.

§Examples

As an iterator:

for c in '\n'.escape_debug() {
    print!("{c}");
}
println!();

Using println! directly:

println!("{}", '\n'.escape_debug());

Both are equivalent to:

println!("\\n");

Using to_string:

assert_eq!('\n'.escape_debug().to_string(), "\\n");
Source

pub fn escape_default(self) -> EscapeDefault

Returns an iterator that yields the literal escape code of a character as chars.

The default is chosen with a bias toward producing literals that are legal in a variety of languages, including C++11 and similar C-family languages. The exact rules are:

  • Tab is escaped as \t.
  • Carriage return is escaped as \r.
  • Line feed is escaped as \n.
  • Single quote is escaped as \'.
  • Double quote is escaped as \".
  • Backslash is escaped as \\.
  • Any character in the ‘printable ASCII’ range 0x20 .. 0x7e inclusive is not escaped.
  • All other characters are given hexadecimal Unicode escapes; see escape_unicode.
§Examples

As an iterator:

for c in '"'.escape_default() {
    print!("{c}");
}
println!();

Using println! directly:

println!("{}", '"'.escape_default());

Both are equivalent to:

println!("\\\"");

Using to_string:

assert_eq!('"'.escape_default().to_string(), "\\\"");
Source

pub const fn len_utf8(self) -> usize

Returns the number of bytes this char would need if encoded in UTF-8.

That number of bytes is always between 1 and 4, inclusive.

§Examples

Basic usage:

let len = 'A'.len_utf8();
assert_eq!(len, 1);

let len = 'ß'.len_utf8();
assert_eq!(len, 2);

let len = 'ℝ'.len_utf8();
assert_eq!(len, 3);

let len = '💣'.len_utf8();
assert_eq!(len, 4);

The &str type guarantees that its contents are UTF-8, and so we can compare the length it would take if each code point was represented as a char vs in the &str itself:

// as chars
let eastern = '東';
let capital = '京';

// both can be represented as three bytes
assert_eq!(3, eastern.len_utf8());
assert_eq!(3, capital.len_utf8());

// as a &str, these two are encoded in UTF-8
let tokyo = "東京";

let len = eastern.len_utf8() + capital.len_utf8();

// we can see that they take six bytes total...
assert_eq!(6, tokyo.len());

// ... just like the &str
assert_eq!(len, tokyo.len());
Source

pub const fn len_utf16(self) -> usize

Returns the number of 16-bit code units this char would need if encoded in UTF-16.

That number of code units is always either 1 or 2, for unicode scalar values in the basic multilingual plane or supplementary planes respectively.

See the documentation for len_utf8() for more explanation of this concept. This function is a mirror, but for UTF-16 instead of UTF-8.

§Examples

Basic usage:

let n = 'ß'.len_utf16();
assert_eq!(n, 1);

let len = '💣'.len_utf16();
assert_eq!(len, 2);
Source

pub const fn encode_utf8(self, dst: &mut [u8]) -> &mut str

Encodes this character as UTF-8 into the provided byte buffer, and then returns the subslice of the buffer that contains the encoded character.

§Panics

Panics if the buffer is not large enough. A buffer of length four is large enough to encode any char.

§Examples

In both of these examples, ‘ß’ takes two bytes to encode.

let mut b = [0; 2];

let result = 'ß'.encode_utf8(&mut b);

assert_eq!(result, "ß");

assert_eq!(result.len(), 2);

A buffer that’s too small:

let mut b = [0; 1];

// this panics
'ß'.encode_utf8(&mut b);
Source

pub const fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16]

Encodes this character as native endian UTF-16 into the provided u16 buffer, and then returns the subslice of the buffer that contains the encoded character.

§Panics

Panics if the buffer is not large enough. A buffer of length 2 is large enough to encode any char.

§Examples

In both of these examples, ‘𝕊’ takes two u16s to encode.

let mut b = [0; 2];

let result = '𝕊'.encode_utf16(&mut b);

assert_eq!(result.len(), 2);

A buffer that’s too small:

let mut b = [0; 1];

// this panics
'𝕊'.encode_utf16(&mut b);
Source

pub fn is_alphabetic(self) -> bool

Returns true if this char has the Alphabetic property.

Alphabetic is described in Chapter 4 (Character Properties) of the Unicode Standard and specified in the Unicode Character Database DerivedCoreProperties.txt.

§Examples

Basic usage:

assert!('a'.is_alphabetic());
assert!('京'.is_alphabetic());

let c = '💝';
// love is many things, but it is not alphabetic
assert!(!c.is_alphabetic());
Source

pub const fn is_lowercase(self) -> bool

Returns true if this char has the Lowercase property.

Lowercase is described in Chapter 4 (Character Properties) of the Unicode Standard and specified in the Unicode Character Database DerivedCoreProperties.txt.

§Examples

Basic usage:

assert!('a'.is_lowercase());
assert!('δ'.is_lowercase());
assert!(!'A'.is_lowercase());
assert!(!'Δ'.is_lowercase());

// The various Chinese scripts and punctuation do not have case, and so:
assert!(!'中'.is_lowercase());
assert!(!' '.is_lowercase());

In a const context:

const CAPITAL_DELTA_IS_LOWERCASE: bool = 'Δ'.is_lowercase();
assert!(!CAPITAL_DELTA_IS_LOWERCASE);
Source

pub const fn is_uppercase(self) -> bool

Returns true if this char has the Uppercase property.

Uppercase is described in Chapter 4 (Character Properties) of the Unicode Standard and specified in the Unicode Character Database DerivedCoreProperties.txt.

§Examples

Basic usage:

assert!(!'a'.is_uppercase());
assert!(!'δ'.is_uppercase());
assert!('A'.is_uppercase());
assert!('Δ'.is_uppercase());

// The various Chinese scripts and punctuation do not have case, and so:
assert!(!'中'.is_uppercase());
assert!(!' '.is_uppercase());

In a const context:

const CAPITAL_DELTA_IS_UPPERCASE: bool = 'Δ'.is_uppercase();
assert!(CAPITAL_DELTA_IS_UPPERCASE);
Source

pub fn is_whitespace(self) -> bool

Returns true if this char has the White_Space property.

White_Space is specified in the Unicode Character Database PropList.txt.

§Examples

Basic usage:

assert!(' '.is_whitespace());

// line break
assert!('\n'.is_whitespace());

// a non-breaking space
assert!('\u{A0}'.is_whitespace());

assert!(!'越'.is_whitespace());
Source

pub fn is_alphanumeric(self) -> bool

Returns true if this char satisfies either is_alphabetic() or is_numeric().

§Examples

Basic usage:

assert!('٣'.is_alphanumeric());
assert!('7'.is_alphanumeric());
assert!('৬'.is_alphanumeric());
assert!('¾'.is_alphanumeric());
assert!('①'.is_alphanumeric());
assert!('K'.is_alphanumeric());
assert!('و'.is_alphanumeric());
assert!('藏'.is_alphanumeric());
Source

pub fn is_control(self) -> bool

Returns true if this char has the general category for control codes.

Control codes (code points with the general category of Cc) are described in Chapter 4 (Character Properties) of the Unicode Standard and specified in the Unicode Character Database UnicodeData.txt.

§Examples

Basic usage:

// U+009C, STRING TERMINATOR
assert!('œ'.is_control());
assert!(!'q'.is_control());
Source

pub fn is_numeric(self) -> bool

Returns true if this char has one of the general categories for numbers.

The general categories for numbers (Nd for decimal digits, Nl for letter-like numeric characters, and No for other numeric characters) are specified in the Unicode Character Database UnicodeData.txt.

This method doesn’t cover everything that could be considered a number, e.g. ideographic numbers like ‘三’. If you want everything including characters with overlapping purposes then you might want to use a unicode or language-processing library that exposes the appropriate character properties instead of looking at the unicode categories.

If you want to parse ASCII decimal digits (0-9) or ASCII base-N, use is_ascii_digit or is_digit instead.

§Examples

Basic usage:

assert!('٣'.is_numeric());
assert!('7'.is_numeric());
assert!('৬'.is_numeric());
assert!('¾'.is_numeric());
assert!('①'.is_numeric());
assert!(!'K'.is_numeric());
assert!(!'و'.is_numeric());
assert!(!'藏'.is_numeric());
assert!(!'三'.is_numeric());
Source

pub fn to_lowercase(self) -> ToLowercase

Returns an iterator that yields the lowercase mapping of this char as one or more chars.

If this char does not have a lowercase mapping, the iterator yields the same char.

If this char has a one-to-one lowercase mapping given by the Unicode Character Database UnicodeData.txt, the iterator yields that char.

If this char requires special considerations (e.g. multiple chars) the iterator yields the char(s) given by SpecialCasing.txt.

This operation performs an unconditional mapping without tailoring. That is, the conversion is independent of context and language.

In the Unicode Standard, Chapter 4 (Character Properties) discusses case mapping in general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.

§Examples

As an iterator:

for c in 'İ'.to_lowercase() {
    print!("{c}");
}
println!();

Using println! directly:

println!("{}", 'İ'.to_lowercase());

Both are equivalent to:

println!("i\u{307}");

Using to_string:

assert_eq!('C'.to_lowercase().to_string(), "c");

// Sometimes the result is more than one character:
assert_eq!('İ'.to_lowercase().to_string(), "i\u{307}");

// Characters that do not have both uppercase and lowercase
// convert into themselves.
assert_eq!('山'.to_lowercase().to_string(), "山");
Source

pub fn to_uppercase(self) -> ToUppercase

Returns an iterator that yields the uppercase mapping of this char as one or more chars.

If this char does not have an uppercase mapping, the iterator yields the same char.

If this char has a one-to-one uppercase mapping given by the Unicode Character Database UnicodeData.txt, the iterator yields that char.

If this char requires special considerations (e.g. multiple chars) the iterator yields the char(s) given by SpecialCasing.txt.

This operation performs an unconditional mapping without tailoring. That is, the conversion is independent of context and language.

In the Unicode Standard, Chapter 4 (Character Properties) discusses case mapping in general and Chapter 3 (Conformance) discusses the default algorithm for case conversion.

§Examples

As an iterator:

for c in 'ß'.to_uppercase() {
    print!("{c}");
}
println!();

Using println! directly:

println!("{}", 'ß'.to_uppercase());

Both are equivalent to:

println!("SS");

Using to_string:

assert_eq!('c'.to_uppercase().to_string(), "C");

// Sometimes the result is more than one character:
assert_eq!('ß'.to_uppercase().to_string(), "SS");

// Characters that do not have both uppercase and lowercase
// convert into themselves.
assert_eq!('山'.to_uppercase().to_string(), "山");
§Note on locale

In Turkish, the equivalent of ‘i’ in Latin has five forms instead of two:

  • ‘Dotless’: I / ı, sometimes written ï
  • ‘Dotted’: İ / i

Note that the lowercase dotted ‘i’ is the same as the Latin. Therefore:

let upper_i = 'i'.to_uppercase().to_string();

The value of upper_i here relies on the language of the text: if we’re in en-US, it should be "I", but if we’re in tr_TR, it should be "İ". to_uppercase() does not take this into account, and so:

let upper_i = 'i'.to_uppercase().to_string();

assert_eq!(upper_i, "I");

holds across languages.

Source

pub const fn is_ascii(&self) -> bool

Checks if the value is within the ASCII range.

§Examples
let ascii = 'a';
let non_ascii = '❤';

assert!(ascii.is_ascii());
assert!(!non_ascii.is_ascii());
Source

pub const fn to_ascii_uppercase(&self) -> Self

Makes a copy of the value in 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().

To uppercase ASCII characters in addition to non-ASCII characters, use to_uppercase().

§Examples
let ascii = 'a';
let non_ascii = '❤';

assert_eq!('A', ascii.to_ascii_uppercase());
assert_eq!('❤', non_ascii.to_ascii_uppercase());
Source

pub const fn to_ascii_lowercase(&self) -> Self

Makes a copy of the value in 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().

To lowercase ASCII characters in addition to non-ASCII characters, use to_lowercase().

§Examples
let ascii = 'A';
let non_ascii = '❤';

assert_eq!('a', ascii.to_ascii_lowercase());
assert_eq!('❤', non_ascii.to_ascii_lowercase());
Source

pub const fn eq_ignore_ascii_case(&self, other: &char) -> bool

Checks that two values are an ASCII case-insensitive match.

Equivalent to to_ascii_lowercase(a) == to_ascii_lowercase(b).

§Examples
let upper_a = 'A';
let lower_a = 'a';
let lower_z = 'z';

assert!(upper_a.eq_ignore_ascii_case(&lower_a));
assert!(upper_a.eq_ignore_ascii_case(&upper_a));
assert!(!upper_a.eq_ignore_ascii_case(&lower_z));
Source

pub const fn make_ascii_uppercase(&mut self)

Converts this type 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().

§Examples
let mut ascii = NonZeroChar::new('a').unwrap();

ascii.make_ascii_uppercase();

assert_eq!('A', ascii);
Source

pub const fn make_ascii_lowercase(&mut self)

Converts this type 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().

§Examples
let mut ascii = NonZeroChar::new('A').unwrap();

ascii.make_ascii_lowercase();

assert_eq!('a', ascii);
Source

pub const fn is_ascii_alphabetic(&self) -> bool

Checks if the value is an ASCII alphabetic character:

  • U+0041 ‘A’ ..= U+005A ‘Z’, or
  • U+0061 ‘a’ ..= U+007A ‘z’.
§Examples
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(uppercase_a.is_ascii_alphabetic());
assert!(uppercase_g.is_ascii_alphabetic());
assert!(a.is_ascii_alphabetic());
assert!(g.is_ascii_alphabetic());
assert!(!zero.is_ascii_alphabetic());
assert!(!percent.is_ascii_alphabetic());
assert!(!space.is_ascii_alphabetic());
assert!(!lf.is_ascii_alphabetic());
assert!(!esc.is_ascii_alphabetic());
Source

pub const fn is_ascii_uppercase(&self) -> bool

Checks if the value is an ASCII uppercase character: U+0041 ‘A’ ..= U+005A ‘Z’.

§Examples
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(uppercase_a.is_ascii_uppercase());
assert!(uppercase_g.is_ascii_uppercase());
assert!(!a.is_ascii_uppercase());
assert!(!g.is_ascii_uppercase());
assert!(!zero.is_ascii_uppercase());
assert!(!percent.is_ascii_uppercase());
assert!(!space.is_ascii_uppercase());
assert!(!lf.is_ascii_uppercase());
assert!(!esc.is_ascii_uppercase());
Source

pub const fn is_ascii_lowercase(&self) -> bool

Checks if the value is an ASCII lowercase character: U+0061 ‘a’ ..= U+007A ‘z’.

§Examples
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(!uppercase_a.is_ascii_lowercase());
assert!(!uppercase_g.is_ascii_lowercase());
assert!(a.is_ascii_lowercase());
assert!(g.is_ascii_lowercase());
assert!(!zero.is_ascii_lowercase());
assert!(!percent.is_ascii_lowercase());
assert!(!space.is_ascii_lowercase());
assert!(!lf.is_ascii_lowercase());
assert!(!esc.is_ascii_lowercase());
Source

pub const fn is_ascii_alphanumeric(&self) -> bool

Checks if the value is an ASCII alphanumeric character:

  • U+0041 ‘A’ ..= U+005A ‘Z’, or
  • U+0061 ‘a’ ..= U+007A ‘z’, or
  • U+0030 ‘0’ ..= U+0039 ‘9’.
§Examples
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(uppercase_a.is_ascii_alphanumeric());
assert!(uppercase_g.is_ascii_alphanumeric());
assert!(a.is_ascii_alphanumeric());
assert!(g.is_ascii_alphanumeric());
assert!(zero.is_ascii_alphanumeric());
assert!(!percent.is_ascii_alphanumeric());
assert!(!space.is_ascii_alphanumeric());
assert!(!lf.is_ascii_alphanumeric());
assert!(!esc.is_ascii_alphanumeric());
Source

pub const fn is_ascii_digit(&self) -> bool

Checks if the value is an ASCII decimal digit: U+0030 ‘0’ ..= U+0039 ‘9’.

§Examples
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(!uppercase_a.is_ascii_digit());
assert!(!uppercase_g.is_ascii_digit());
assert!(!a.is_ascii_digit());
assert!(!g.is_ascii_digit());
assert!(zero.is_ascii_digit());
assert!(!percent.is_ascii_digit());
assert!(!space.is_ascii_digit());
assert!(!lf.is_ascii_digit());
assert!(!esc.is_ascii_digit());
Source

pub const fn is_ascii_hexdigit(&self) -> bool

Checks if the value is an ASCII hexadecimal digit:

  • U+0030 ‘0’ ..= U+0039 ‘9’, or
  • U+0041 ‘A’ ..= U+0046 ‘F’, or
  • U+0061 ‘a’ ..= U+0066 ‘f’.
§Examples
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(uppercase_a.is_ascii_hexdigit());
assert!(!uppercase_g.is_ascii_hexdigit());
assert!(a.is_ascii_hexdigit());
assert!(!g.is_ascii_hexdigit());
assert!(zero.is_ascii_hexdigit());
assert!(!percent.is_ascii_hexdigit());
assert!(!space.is_ascii_hexdigit());
assert!(!lf.is_ascii_hexdigit());
assert!(!esc.is_ascii_hexdigit());
Source

pub const fn is_ascii_punctuation(&self) -> bool

Checks if the value is an ASCII punctuation character:

  • U+0021 ..= U+002F ! " # $ % & ' ( ) * + , - . /, or
  • U+003A ..= U+0040 : ; < = > ? @, or
  • U+005B ..= U+0060 [ \ ] ^ _ ` , or
  • U+007B ..= U+007E { | } ~
§Examples
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(!uppercase_a.is_ascii_punctuation());
assert!(!uppercase_g.is_ascii_punctuation());
assert!(!a.is_ascii_punctuation());
assert!(!g.is_ascii_punctuation());
assert!(!zero.is_ascii_punctuation());
assert!(percent.is_ascii_punctuation());
assert!(!space.is_ascii_punctuation());
assert!(!lf.is_ascii_punctuation());
assert!(!esc.is_ascii_punctuation());
Source

pub const fn is_ascii_graphic(&self) -> bool

Checks if the value is an ASCII graphic character: U+0021 ‘!’ ..= U+007E ‘~’.

§Examples
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(uppercase_a.is_ascii_graphic());
assert!(uppercase_g.is_ascii_graphic());
assert!(a.is_ascii_graphic());
assert!(g.is_ascii_graphic());
assert!(zero.is_ascii_graphic());
assert!(percent.is_ascii_graphic());
assert!(!space.is_ascii_graphic());
assert!(!lf.is_ascii_graphic());
assert!(!esc.is_ascii_graphic());
Source

pub const fn is_ascii_whitespace(&self) -> bool

Checks if the value is an ASCII whitespace character: U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED, U+000C FORM FEED, or U+000D CARRIAGE RETURN.

Rust uses the WhatWG Infra Standard’s definition of ASCII whitespace. There are several other definitions in wide use. For instance, the POSIX locale includes U+000B VERTICAL TAB as well as all the above characters, but—from the very same specification—the default rule for “field splitting” in the Bourne shell considers only SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.

If you are writing a program that will process an existing file format, check what that format’s definition of whitespace is before using this function.

§Examples
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(!uppercase_a.is_ascii_whitespace());
assert!(!uppercase_g.is_ascii_whitespace());
assert!(!a.is_ascii_whitespace());
assert!(!g.is_ascii_whitespace());
assert!(!zero.is_ascii_whitespace());
assert!(!percent.is_ascii_whitespace());
assert!(space.is_ascii_whitespace());
assert!(lf.is_ascii_whitespace());
assert!(!esc.is_ascii_whitespace());
Source

pub const fn is_ascii_control(&self) -> bool

Checks if the value is an ASCII control character: U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE. Note that most ASCII whitespace characters are control characters, but SPACE is not.

§Examples
let uppercase_a = 'A';
let uppercase_g = 'G';
let a = 'a';
let g = 'g';
let zero = '0';
let percent = '%';
let space = ' ';
let lf = '\n';
let esc = '\x1b';

assert!(!uppercase_a.is_ascii_control());
assert!(!uppercase_g.is_ascii_control());
assert!(!a.is_ascii_control());
assert!(!g.is_ascii_control());
assert!(!zero.is_ascii_control());
assert!(!percent.is_ascii_control());
assert!(!space.is_ascii_control());
assert!(lf.is_ascii_control());
assert!(esc.is_ascii_control());

Trait Implementations§

Source§

impl Clone for NonZeroChar

Source§

fn clone(&self) -> NonZeroChar

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for NonZeroChar

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for NonZeroChar

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'a> Extend<&'a NonZeroChar> for String

Source§

fn extend<T: IntoIterator<Item = &'a NonZeroChar>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl Extend<NonZeroChar> for String

Source§

fn extend<T: IntoIterator<Item = NonZeroChar>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl From<NonZeroChar> for String

Source§

fn from(value: NonZeroChar) -> Self

Converts to this type from the input type.
Source§

impl From<NonZeroChar> for u128

Source§

fn from(value: NonZeroChar) -> Self

Converts to this type from the input type.
Source§

impl From<NonZeroChar> for u32

Source§

fn from(value: NonZeroChar) -> Self

Converts to this type from the input type.
Source§

impl From<NonZeroChar> for u64

Source§

fn from(value: NonZeroChar) -> Self

Converts to this type from the input type.
Source§

impl<'a> FromIterator<&'a NonZeroChar> for Box<str>

Source§

fn from_iter<T: IntoIterator<Item = &'a NonZeroChar>>(iter: T) -> Self

Creates a value from an iterator. Read more
Source§

impl<'a> FromIterator<&'a NonZeroChar> for Cow<'_, str>

Source§

fn from_iter<T: IntoIterator<Item = &'a NonZeroChar>>(iter: T) -> Self

Creates a value from an iterator. Read more
Source§

impl<'a> FromIterator<&'a NonZeroChar> for String

Source§

fn from_iter<T: IntoIterator<Item = &'a NonZeroChar>>(iter: T) -> Self

Creates a value from an iterator. Read more
Source§

impl FromIterator<NonZeroChar> for Box<str>

Source§

fn from_iter<T: IntoIterator<Item = NonZeroChar>>(iter: T) -> Self

Creates a value from an iterator. Read more
Source§

impl FromIterator<NonZeroChar> for Cow<'_, str>

Source§

fn from_iter<T: IntoIterator<Item = NonZeroChar>>(iter: T) -> Self

Creates a value from an iterator. Read more
Source§

impl FromIterator<NonZeroChar> for String

Source§

fn from_iter<T: IntoIterator<Item = NonZeroChar>>(iter: T) -> Self

Creates a value from an iterator. Read more
Source§

impl FromStr for NonZeroChar

Source§

type Err = ParseNonZeroCharError

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for NonZeroChar

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for NonZeroChar

Source§

fn cmp(&self, other: &NonZeroChar) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq<NonZeroChar> for char

Source§

fn eq(&self, other: &NonZeroChar) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq<char> for NonZeroChar

Source§

fn eq(&self, other: &char) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialEq for NonZeroChar

Source§

fn eq(&self, other: &NonZeroChar) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd<NonZeroChar> for char

Source§

fn partial_cmp(&self, other: &NonZeroChar) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
Source§

fn lt(&self, other: &NonZeroChar) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
Source§

fn le(&self, other: &NonZeroChar) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
Source§

fn gt(&self, other: &NonZeroChar) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
Source§

fn ge(&self, other: &NonZeroChar) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl PartialOrd<char> for NonZeroChar

Source§

fn partial_cmp(&self, other: &char) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
Source§

fn lt(&self, other: &char) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
Source§

fn le(&self, other: &char) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
Source§

fn gt(&self, other: &char) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
Source§

fn ge(&self, other: &char) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl PartialOrd for NonZeroChar

Source§

fn partial_cmp(&self, other: &NonZeroChar) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl TryFrom<NonZeroChar> for u16

Source§

type Error = <u16 as TryFrom<char>>::Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: NonZeroChar) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<NonZeroChar> for u8

Source§

type Error = <u8 as TryFrom<char>>::Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: NonZeroChar) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<u32> for NonZeroChar

Source§

type Error = TryFromByteError

The type returned in the event of a conversion error.
Source§

fn try_from(value: u32) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<u8> for NonZeroChar

Source§

type Error = TryFromByteError

The type returned in the event of a conversion error.
Source§

fn try_from(value: u8) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl Copy for NonZeroChar

Source§

impl Eq for NonZeroChar

Source§

impl StructuralPartialEq for NonZeroChar

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.