10000 Use `const fn` where possible by ShaharNaveh · Pull Request #5894 · RustPython/RustPython · GitHub
[go: up one dir, main page]

Skip to content

Use const fn where possible #5894

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Jul 4, 2025
2 changes: 1 addition & 1 deletion common/src/cformat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ bitflags! {

impl CConversionFlags {
#[inline]
pub fn sign_string(&self) -> &'static str {
pub const fn sign_string(&self) -> &'static str {
if self.contains(Self::SIGN_CHAR) {
"+"
} else if self.contains(Self::BLANK_SIGN) {
Expand Down
6 changes: 5 additions & 1 deletion common/src/encodings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,11 @@ struct DecodeError<'a> {

/// # Safety
/// `v[..valid_up_to]` must be valid utf8
unsafe fn make_decode_err(v: &[u8], valid_up_to: usize, err_len: Option<usize>) -> DecodeError<'_> {
const unsafe fn make_decode_err(
v: &[u8],
valid_up_to: usize,
err_len: Option<usize>,
) -> DecodeError<'_> {
let (valid_prefix, rest) = unsafe { v.split_at_unchecked(valid_up_to) };
let valid_prefix = unsafe { core::str::from_utf8_unchecked(valid_prefix) };
DecodeError {
Expand Down
4 changes: 2 additions & 2 deletions common/src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ pub fn lcg_urandom(mut x: u32, buf: &mut [u8]) {
}

#[inline]
pub fn hash_object_id_raw(p: usize) -> PyHash {
pub const fn hash_object_id_raw(p: usize) -> PyHash {
// TODO: Use commented logic when below issue resolved.
// Ref: https://github.com/RustPython/RustPython/pull/3951#issuecomment-1193108966

Expand All @@ -175,7 +175,7 @@ pub fn hash_object_id_raw(p: usize) -> PyHash {
}

#[inline]
pub fn hash_object_id(p: usize) -> PyHash {
pub const fn hash_object_id(p: usize) -> PyHash {
fix_sentinel(hash_object_id_raw(p))
}

Expand Down
14 changes: 7 additions & 7 deletions common/src/linked_list.rs
F438
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ impl<L: Link> LinkedList<L, L::Target> {
// }

/// Returns whether the linked list does not contain any node
pub fn is_empty(&self) -> bool {
pub const fn is_empty(&self) -> bool {
self.head.is_none()
// if self.head.is_some() {
// return false;
Expand Down Expand Up @@ -284,7 +284,7 @@ pub struct DrainFilter<'a, T: Link, F> {
}

impl<T: Link> LinkedList<T, T::Target> {
pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
pub const fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
where
F: FnMut(&mut T::Target) -> bool,
{
Expand Down Expand Up @@ -323,7 +323,7 @@ where

impl<T> Pointers<T> {
/// Create a new set of empty pointers
pub fn new() -> Self {
pub const fn new() -> Self {
Self {
inner: UnsafeCell::new(PointersInner {
prev: None,
Expand All @@ -333,15 +333,15 @@ impl<T> Pointers<T> {
}
}

fn get_prev(&self) -> Option<NonNull<T>> {
const fn get_prev(&self) -> Option<NonNull<T>> {
// SAFETY: prev is the first field in PointersInner, which is #[repr(C)].
unsafe {
let inner = self.inner.get();
let prev = inner as *const Option<NonNull<T>>;
ptr::read(prev)
}
}
fn get_next(&self) -> Option<NonNull<T>> {
const fn get_next(&self) -> Option<NonNull<T>> {
// SAFETY: next is the second field in PointersInner, which is #[repr(C)].
unsafe {
let inner = self.inner.get();
Expand All @@ -351,15 +351,15 @@ impl<T> Pointers<T> {
}
}

fn set_prev(&mut self, value: Option<NonNull<T>>) {
const fn set_prev(&mut self, value: Option<NonNull<T>>) {
// SAFETY: prev is the first field in PointersInner, which is #[repr(C)].
unsafe {
let inner = self.inner.get();
let prev = inner as *mut Option<NonNull<T>>;
ptr::write(prev, value);
}
}
fn set_next(&mut self, value: Option<NonNull<T>>) {
const fn set_next(&mut self, value: Option<NonNull<T>>) {
// SAFETY: next is the second field in PointersInner, which is #[repr(C)].
unsafe {
let inner = self.inner.get();
Expand Down
2 changes: 1 addition & 1 deletion common/src/lock/thread_mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ pub struct ThreadMutex<R: RawMutex, G: GetThreadId, T: ?Sized> {
}

impl<R: RawMutex, G: GetThreadId, T> ThreadMutex<R, G, T> {
pub fn new(val: T) -> Self {
pub const fn new(val: T) -> Self {
Self {
raw: RawThreadMutex::INIT,
data: UnsafeCell::new(val),
Expand Down
4 changes: 2 additions & 2 deletions compiler/codegen/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ impl Default for PatternContext {
}

impl PatternContext {
pub fn new() -> Self {
pub const fn new() -> Self {
Self {
stores: Vec::new(),
allow_irrefutable: false,
Expand Down Expand Up @@ -4118,7 +4118,7 @@ impl Compiler<'_> {
code.current_block = block;
}

fn set_source_range(&mut self, range: TextRange) {
const fn set_source_range(&mut self, range: TextRange) {
self.current_source_range = range;
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/codegen/src/string_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ struct StringParser {
}

impl StringParser {
fn new(source: Box<str>, flags: AnyStringFlags) -> Self {
const fn new(source: Box<str>, flags: AnyStringFlags) -> Self {
Self {
source,
cursor: 0,
Expand Down
6 changes: 3 additions & 3 deletions compiler/codegen/src/symboltable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,18 +162,18 @@ impl Symbol {
}
}

pub fn is_global(&self) -> bool {
pub const fn is_global(&self) -> bool {
matches!(
self.scope,
SymbolScope::GlobalExplicit | SymbolScope::GlobalImplicit
)
}

pub fn is_local(&self) -> bool {
pub const fn is_local(&self) -> bool {
matches!(self.scope, SymbolScope::Local | SymbolScope::Cell)
}

pub fn is_bound(&self) -> bool {
pub const fn is_bound(&self) -> bool {
self.flags.intersects(SymbolFlags::BOUND)
}
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/codegen/src/unparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ struct Unparser<'a, 'b, 'c> {
source: &'c SourceCode<'c>,
}
impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> {
fn new(f: &'b mut fmt::Formatter<'a>, source: &'c SourceCode<'c>) -> Self {
const fn new(f: &'b mut fmt::Formatter<'a>, source: &'c SourceCode<'c>) -> Self {
Unparser { f, source }
}

Expand Down Expand Up @@ -602,7 +602,7 @@ pub struct UnparseExpr<'a> {
source: &'a SourceCode<'a>,
}

pub fn unparse_expr<'a>(expr: &'a Expr, source: &'a SourceCode<'a>) -> UnparseExpr<'a> {
pub const fn unparse_expr<'a>(expr: &'a Expr, source: &'a SourceCode<'a>) -> UnparseExpr<< 10000 span class="pl-c1">'a> {
UnparseExpr { expr, source }
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ impl CompileError {
}
}

pub fn python_location(&self) -> (usize, usize) {
pub const fn python_location(&self) -> (usize, usize) {
match self {
Self::Codegen(codegen_error) => {
if let Some(location) = &codegen_error.location {
Expand Down
14 changes: 7 additions & 7 deletions stdlib/src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,26 +89,26 @@ mod array {
}
}

fn typecode(&self) -> char {
const fn typecode(&self) -> char {
match self {
$(ArrayContentType::$n(_) => $c,)*
}
}

fn typecode_str(&self) -> &'static str {
const fn typecode_str(&self) -> &'static str {
match self {
$(ArrayContentType::$n(_) => $scode,)*
}
}

fn itemsize_of_typecode(c: char) -> Option<usize> {
const fn itemsize_of_typecode(c: char) -> Option<usize> {
match c {
$($c => Some(std::mem::size_of::<$t>()),)*
_ => None,
}
}

fn itemsize(&self) -> usize {
const fn itemsize(&self) -> usize {
match self {
$(ArrayContentType::$n(_) => std::mem::size_of::<$t>(),)*
}
Expand Down Expand Up @@ -554,11 +554,11 @@ mod array {
(f64, f64_try_into_from_object, f64_swap_bytes, PyFloat::from),
);

fn f32_swap_bytes(x: f32) -> f32 {
const fn f32_swap_bytes(x: f32) -> f32 {
f32::from_bits(x.to_bits().swap_bytes())
}

fn f64_swap_bytes(x: f64) -> f64 {
const fn f64_swap_bytes(x: f64) -> f64 {
f64::from_bits(x.to_bits().swap_bytes())
}

Expand Down Expand Up @@ -1557,7 +1557,7 @@ mod array {
_ => None,
}
}
fn item_size(self) -> usize {
const fn item_size(self) -> usize {
match self {
Self::Int8 { .. } => 1,
Self::Int16 { .. } | Self::Utf16 { .. } => 2,
Expand Down
4 changes: 2 additions & 2 deletions stdlib/src/binascii.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ mod decl {
})
}

fn unhex_nibble(c: u8) -> Option<u8> {
const fn unhex_nibble(c: u8) -> Option<u8> {
match c {
b'0'..=b'9' => Some(c - b'0'),
b'a'..=b'f' => Some(c - b'a' + 10),
Expand Down Expand Up @@ -810,7 +810,7 @@ mod decl {
vm: &VirtualMachine,
) -> PyResult<Vec<u8>> {
#[inline]
fn uu_b2a(num: u8, backtick: bool) -> u8 {
const fn uu_b2a(num: u8, backtick: bool) -> u8 {
if backtick && num == 0 {
0x60
} else {
Expand Down
16 changes: 8 additions & 8 deletions stdlib/src/compression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ impl DecompressFlushKind for () {
const SYNC: Self = ();
}

pub fn flush_sync<T: DecompressFlushKind>(_final_chunk: bool) -> T {
pub const fn flush_sync<T: DecompressFlushKind>(_final_chunk: bool) -> T {
T::SYNC
}

Expand All @@ -76,13 +76,13 @@ pub struct Chunker<'a> {
data2: &'a [u8],
}
impl<'a> Chunker<'a> {
pub fn new(data: &'a [u8]) -> Self {
pub const fn new(data: &'a [u8]) -> Self {
Self {
data1: data,
data2: &[],
}
}
pub fn chain(data1: &'a [u8], data2: &'a [u8]) -> Self {
pub const fn chain(data1: &'a [u8], data2: &'a [u8]) -> Self {
if data1.is_empty() {
Self {
data1: data2,
Expand All @@ -92,10 +92,10 @@ impl<'a> Chunker<'a> {
Self { data1, data2 }
}
}
pub fn len(&self) -> usize {
pub const fn len(&self) -> usize {
self.data1.len() + self.data2.len()
}
pub fn is_empty(&self) -> bool {
pub const fn is_empty(&self) -> bool {
self.data1.is_empty()
}
pub fn to_vec(&self) -> Vec<u8> {
Expand Down Expand Up @@ -216,7 +216,7 @@ pub struct CompressState<C: Compressor> {
}

impl<C: Compressor> CompressState<C> {
pub fn new(compressor: C) -> Self {
pub const fn new(compressor: C) -> Self {
Self {
compressor: Some(compressor),
}
Expand Down Expand Up @@ -293,15 +293,15 @@ impl<D: Decompressor> DecompressState<D> {
}
}

pub fn eof(&self) -> bool {
pub const fn eof(&self) -> bool {
self.eof
}

pub fn unused_data(&self) -> PyBytesRef {
self.unused_data.clone()
}

pub fn needs_input(&self) -> bool {
pub const fn needs_input(&self) -> bool {
self.needs_input
}

Expand Down
12 changes: 6 additions & 6 deletions stdlib/src/csv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,11 @@ mod _csv {
Some(vm.ctx.new_str(format!("{}", self.quotechar? as char)))
}
#[pygetset]
fn doublequote(&self) -> bool {
const fn doublequote(&self) -> bool {
self.doublequote
}
#[pygetset]
fn skipinitialspace(&self) -> bool {
const fn skipinitialspace(&self) -> bool {
self.skipinitialspace
}
#[pygetset]
Expand All @@ -108,7 +108,7 @@ mod _csv {
Some(vm.ctx.new_str(format!("{}", self.escapechar? as char)))
}
#[pygetset(name = "strict")]
fn get_strict(&self) -> bool {
const fn get_strict(&self) -> bool {
self.strict
}
}
Expand Down Expand Up @@ -659,7 +659,7 @@ mod _csv {
}

impl FormatOptions {
fn update_py_dialect(&self, mut res: PyDialect) -> PyDialect {
const fn update_py_dialect(&self, mut res: PyDialect) -> PyDialect {
macro_rules! check_and_fill {
($res:ident, $e:ident) => {{
if let Some(t) = self.$e {
Expand Down Expand Up @@ -916,7 +916,7 @@ mod _csv {
self.state.lock().line_num
}
#[pygetset]
fn dialect(&self, _vm: &VirtualMachine) -> PyDialect {
const fn dialect(&self, _vm: &VirtualMachine) -> PyDialect {
self.dialect
}
}
Expand Down Expand Up @@ -1066,7 +1066,7 @@ mod _csv {
#[pyclass]
impl Writer {
#[pygetset(name = "dialect")]
fn get_dialect(&self, _vm: &VirtualMachine) -> PyDialect {
const fn get_dialect(&self, _vm: &VirtualMachine) -> PyDialect {
self.dialect
}
#[pymethod]
Expand Down
4 changes: 2 additions & 2 deletions stdlib/src/faulthandler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ mod decl {
}

#[pyfunction]
fn enable(_args: EnableArgs) {
const fn enable(_args: EnableArgs) {
// TODO
}

Expand All @@ -57,7 +57,7 @@ mod decl {
}

#[pyfunction]
fn register(_args: RegisterArgs) {
const fn register(_args: RegisterArgs) {
// TODO
}
}
Loading
Loading
0