unic_char_range/
step.rs

1// Copyright 2017 The UNIC Project Developers.
2//
3// See the COPYRIGHT file at the top-level directory of this distribution.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11use core::char;
12
13pub const BEFORE_SURROGATE: char = '\u{D7FF}';
14pub const AFTER_SURROGATE: char = '\u{E000}';
15
16#[inline]
17#[allow(unsafe_code)]
18/// Step a character one step towards `char::MAX`.
19///
20/// # Safety
21///
22/// If the given character is `char::MAX`, the return value is not a valid character.
23pub unsafe fn forward(ch: char) -> char {
24    if ch == BEFORE_SURROGATE {
25        AFTER_SURROGATE
26    } else {
27        char::from_u32_unchecked(ch as u32 + 1)
28    }
29}
30
31#[inline]
32#[allow(unsafe_code)]
33/// Step a character one step towards `'\0'`.
34///
35/// # Safety
36///
37/// If the given character is `'\0'`, this will cause an underflow.
38/// (Thus, it will panic in debug mode, undefined behavior in release mode.)
39pub unsafe fn backward(ch: char) -> char {
40    if ch == AFTER_SURROGATE {
41        BEFORE_SURROGATE
42    } else {
43        char::from_u32_unchecked(ch as u32 - 1)
44    }
45}