Last active
November 18, 2017 04:22
-
-
Save fero23/249b6d00ab699fb237e218057acf92db to your computer and use it in GitHub Desktop.
Fibonacci sequence creation in Rust to bind in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] extern crate cpython; | |
use std::vec::Vec; | |
use cpython::{PyResult, Python}; | |
// add bindings to the generated python module | |
// N.B: names: "libfibonacci" must be the name of the `.so` or `.pyd` file | |
py_module_initializer!(libfibonacci, initlibfibonacci, PyInit_libfibonacci, |py, m| { | |
try!(m.add(py, "__doc__", "Fibonacci sequence creation in Rust.")); | |
try!(m.add(py, "fibonacci", py_fn!(py, fibonacci_py(a: u64)))); | |
Ok(()) | |
}); | |
fn fibonacci(max: u64) -> Vec<u64> { | |
let mut seq = Vec::new(); | |
let (mut a, mut b) = (0, 1); | |
while a <= max { | |
seq.push(a); | |
let temp = a; | |
a = b; | |
b += temp; | |
} | |
seq | |
} | |
fn fibonacci_py(_: Python, max: u64) -> PyResult<Vec<u64>> { | |
Ok(fibonacci(max)) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> import libfibonacci | |
>>> libfibonacci.fibonacci(100000) | |
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025] | |
>>> help(libfibonacci) | |
Help on module libfibonacci | |
NAME | |
libfibonacci - Fibonacci sequence creation in Rust. | |
FUNCTIONS | |
fibonacci = fibonacci_py(...) | |
FILE | |
/path/to/libfibonacci.so |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment