Skip to content

Commit c61b924

Browse files
authored
Backport pyo3::intern! from pyo3 0.16 (#7355)
This should speed up all of these code-paths when called repeatedly.
1 parent 32c3d29 commit c61b924

File tree

13 files changed

+572
-298
lines changed

13 files changed

+572
-298
lines changed

src/rust/src/intern.rs

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// This file is dual licensed under the terms of the Apache License, Version
2+
// 2.0, and the BSD License. See the LICENSE file in the root of this repository
3+
// for complete details.
4+
5+
// This file is a backport of `pyo3::intern!` from pyo3 0.16.
6+
7+
#[macro_export]
8+
macro_rules! intern {
9+
($py: expr, $text: expr) => {{
10+
static INTERNED: $crate::intern::Interned = $crate::intern::Interned::new($text);
11+
INTERNED.get($py)
12+
}};
13+
}
14+
15+
#[doc(hidden)]
16+
pub struct Interned(
17+
&'static str,
18+
pyo3::once_cell::GILOnceCell<pyo3::Py<pyo3::types::PyString>>,
19+
);
20+
21+
impl Interned {
22+
pub const fn new(value: &'static str) -> Self {
23+
Interned(value, pyo3::once_cell::GILOnceCell::new())
24+
}
25+
26+
#[inline]
27+
pub fn get<'py>(&'py self, py: pyo3::Python<'py>) -> &'py pyo3::types::PyString {
28+
self.1
29+
.get_or_init(py, || pyo3::types::PyString::new(py, self.0).into())
30+
.as_ref(py)
31+
}
32+
}
33+
34+
#[cfg(test)]
35+
mod tests {
36+
use super::Interned;
37+
38+
#[test]
39+
fn test_interned_new() {
40+
for s in ["abc", "123"] {
41+
Interned::new(s);
42+
}
43+
}
44+
}

src/rust/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#![deny(rust_2018_idioms)]
66

77
mod asn1;
8+
mod intern;
89
pub(crate) mod oid;
910
mod x509;
1011

src/rust/src/oid.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ impl ObjectIdentifier {
3232
) -> pyo3::PyResult<&'p pyo3::PyAny> {
3333
let oid_names = py
3434
.import("cryptography.hazmat._oid")?
35-
.getattr("_OID_NAMES")?;
35+
.getattr(crate::intern!(py, "_OID_NAMES"))?;
3636
oid_names.call_method1("get", (slf, "Unknown OID"))
3737
}
3838
}

0 commit comments

Comments
 (0)