GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Use `const fn` where possible by ShaharNaveh · Pull Request #5894 · RustPython/RustPython

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.

Sign up for GitHub

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
youknowone merged 17 commits into RustPython:main from ShaharNaveh:constify
Jul 4, 2025

Uh oh!

There was an error while loading. Please reload this page.

Merged

Use const fn where possible #5894

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
b30c919
vm
ShaharNaveh Jul 3, 2025
a18f0c2
compiler
ShaharNaveh Jul 3, 2025
fde322c
sre engine
ShaharNaveh Jul 3, 2025
80fba2f
compiler
ShaharNaveh Jul 3, 2025
5f790b8
common
ShaharNaveh Jul 3, 2025
8aef1a3
stdlib
ShaharNaveh Jul 3, 2025
5e08620
vm
ShaharNaveh Jul 3, 2025
4e91f6a
cargo fmt
ShaharNaveh Jul 3, 2025
593b9d2
Merge remote-tracking branch 'upstream/main' into constify
ShaharNaveh Jul 4, 2025
29b26d3
vm
ShaharNaveh Jul 4, 2025
6cd01bf
vm
ShaharNaveh Jul 4, 2025
6b1deb4
common
ShaharNaveh Jul 4, 2025
8adcaa5
compiler
ShaharNaveh Jul 4, 2025
dbf0078
compiler codegen
ShaharNaveh Jul 4, 2025
4b12536
vm
ShaharNaveh Jul 4, 2025
e55f32b
cargo fmt
ShaharNaveh Jul 4, 2025
eb3e2b3
remove bad consts
ShaharNaveh Jul 4, 2025
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

2 changes: 1 addition & 1 deletion 2 common/src/cformat.rs
Show comments
View file
Open in desktop
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 6 common/src/encodings.rs
Show comments
View file
Open in desktop
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 4 common/src/hash.rs
Show comments
View file
Open in desktop
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 14 common/src/linked_list.rs
Show comments
View file
Open in desktop
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 2 common/src/lock/thread_mutex.rs
Show comments
View file
Open in desktop
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 4 compiler/codegen/src/compile.rs
Show comments
View file
Open in desktop
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 2 compiler/codegen/src/string_parser.rs
Show comments
View file
Open in desktop
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 6 compiler/codegen/src/symboltable.rs
Show comments
View file
Open in desktop
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 4 compiler/codegen/src/unparse.rs
Show comments
View file
Open in desktop
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<'a> {
UnparseExpr { expr, source }
}

Expand Down
2 changes: 1 addition & 1 deletion 2 compiler/src/lib.rs
Show comments
View file
Open in desktop
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 14 stdlib/src/array.rs
Show comments
View file
Open in desktop
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 4 stdlib/src/binascii.rs
Show comments
View file
Open in desktop
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 16 stdlib/src/compression.rs
Show comments
View file
Open in desktop
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 12 stdlib/src/csv.rs
Show comments
View file
Open in desktop
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 4 stdlib/src/faulthandler.rs
Show comments
View file
Open in desktop
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
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.