pure/
lib.rs

1#[cfg_attr(target_os = "macos", doc = include_str!("../../../README.md"))]
2mod readme {}
3
4use ahash::RandomState;
5use pyo3::{exceptions::PyRuntimeError, prelude::*, types::*};
6use pyo3_stub_gen::{create_exception, define_stub_info_gatherer, derive::*, module_variable};
7use std::{collections::HashMap, path::PathBuf};
8
9/// Returns the sum of two numbers as a string.
10#[gen_stub_pyfunction]
11#[pyfunction]
12fn sum(v: Vec<u32>) -> u32 {
13    v.iter().sum()
14}
15
16#[gen_stub_pyfunction]
17#[pyfunction]
18fn read_dict(dict: HashMap<usize, HashMap<usize, usize>>) {
19    for (k, v) in dict {
20        for (k2, v2) in v {
21            println!("{} {} {}", k, k2, v2);
22        }
23    }
24}
25
26#[gen_stub_pyfunction]
27#[pyfunction]
28fn create_dict(n: usize) -> HashMap<usize, Vec<usize>> {
29    let mut dict = HashMap::new();
30    for i in 0..n {
31        dict.insert(i, (0..i).collect());
32    }
33    dict
34}
35
36#[gen_stub_pyclass]
37#[pyclass]
38#[derive(Debug)]
39struct A {
40    #[pyo3(get, set)]
41    x: usize,
42}
43
44#[gen_stub_pymethods]
45#[pymethods]
46impl A {
47    /// This is a constructor of :class:`A`.
48    #[new]
49    fn new(x: usize) -> Self {
50        Self { x }
51    }
52
53    fn show_x(&self) {
54        println!("x = {}", self.x);
55    }
56
57    fn ref_test<'a>(&self, x: Bound<'a, PyDict>) -> Bound<'a, PyDict> {
58        x
59    }
60}
61
62#[gen_stub_pyfunction]
63#[pyfunction]
64#[pyo3(signature = (x = 2))]
65fn create_a(x: usize) -> A {
66    A { x }
67}
68
69create_exception!(pure, MyError, PyRuntimeError);
70
71/// Returns the length of the string.
72#[gen_stub_pyfunction]
73#[pyfunction]
74fn str_len(x: &str) -> PyResult<usize> {
75    Ok(x.len())
76}
77
78#[gen_stub_pyfunction]
79#[pyfunction]
80fn echo_path(path: PathBuf) -> PyResult<PathBuf> {
81    Ok(path)
82}
83
84#[gen_stub_pyfunction]
85#[pyfunction]
86fn ahash_dict() -> HashMap<String, i32, RandomState> {
87    let mut map: HashMap<String, i32, RandomState> = HashMap::with_hasher(RandomState::new());
88    map.insert("apple".to_string(), 3);
89    map.insert("banana".to_string(), 2);
90    map.insert("orange".to_string(), 5);
91    map
92}
93
94#[gen_stub_pyclass_enum]
95#[pyclass(eq, eq_int)]
96#[derive(Debug, Clone, PartialEq, Eq, Hash)]
97pub enum Number {
98    #[pyo3(name = "FLOAT")]
99    Float,
100    #[pyo3(name = "INTEGER")]
101    Integer,
102}
103
104module_variable!("pure", "MY_CONSTANT", usize);
105
106// Test if non-any PyObject Target can be a default value
107#[gen_stub_pyfunction]
108#[pyfunction]
109#[pyo3(signature = (num = Number::Float))]
110fn default_value(num: Number) -> Number {
111    num
112}
113
114/// Initializes the Python module
115#[pymodule]
116fn pure(m: &Bound<PyModule>) -> PyResult<()> {
117    m.add("MyError", m.py().get_type::<MyError>())?;
118    m.add("MY_CONSTANT", 19937)?;
119    m.add_class::<A>()?;
120    m.add_class::<Number>()?;
121    m.add_function(wrap_pyfunction!(sum, m)?)?;
122    m.add_function(wrap_pyfunction!(create_dict, m)?)?;
123    m.add_function(wrap_pyfunction!(read_dict, m)?)?;
124    m.add_function(wrap_pyfunction!(create_a, m)?)?;
125    m.add_function(wrap_pyfunction!(str_len, m)?)?;
126    m.add_function(wrap_pyfunction!(echo_path, m)?)?;
127    m.add_function(wrap_pyfunction!(ahash_dict, m)?)?;
128    m.add_function(wrap_pyfunction!(default_value, m)?)?;
129    Ok(())
130}
131
132define_stub_info_gatherer!(stub_info);
133
134/// Test of unit test for testing link problem
135#[cfg(test)]
136mod test {
137    #[test]
138    fn test() {
139        assert_eq!(2 + 2, 4);
140    }
141}