|
1 | 1 | // This is free and unencumbered software released into the public domain. |
2 | 2 |
|
3 | | -use asimov_directory::fs::ModuleDirectory as FsModuleDirectory; |
4 | | -use pyo3::prelude::*; |
| 3 | +use crate::util::wait_for_future; |
| 4 | +use asimov_directory::{ModuleNameIterator as _, fs::ModuleNameIterator as FsModuleNameIterator}; |
| 5 | +use pyo3::{ |
| 6 | + exceptions::{PyStopAsyncIteration, PyStopIteration}, |
| 7 | + prelude::*, |
| 8 | +}; |
| 9 | +use std::sync::Arc; |
| 10 | +use tokio::sync::Mutex; |
5 | 11 |
|
6 | | -/// TODO |
7 | | -#[pyclass(frozen, module = "asimov", str = "{0}")] |
8 | | -pub struct ModuleNameIterator(pub(crate) FsModuleDirectory); |
| 12 | +/// An iterator over module names in the module directory. |
| 13 | +#[pyclass(frozen, module = "asimov", str = "ModuleNameIterator")] |
| 14 | +pub struct ModuleNameIterator(pub(crate) Arc<Mutex<FsModuleNameIterator>>); |
| 15 | + |
| 16 | +impl From<FsModuleNameIterator> for ModuleNameIterator { |
| 17 | + fn from(input: FsModuleNameIterator) -> Self { |
| 18 | + Self(Arc::new(Mutex::new(input))) |
| 19 | + } |
| 20 | +} |
9 | 21 |
|
10 | 22 | #[pymethods] |
11 | | -impl ModuleNameIterator {} |
| 23 | +impl ModuleNameIterator { |
| 24 | + fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { |
| 25 | + slf |
| 26 | + } |
| 27 | + |
| 28 | + fn __aiter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { |
| 29 | + slf |
| 30 | + } |
| 31 | + |
| 32 | + fn __next__(&self, py: Python) -> PyResult<String> { |
| 33 | + let inner = Arc::clone(&self.0); |
| 34 | + let next = async move { |
| 35 | + let mut lock = inner.lock().await; |
| 36 | + let item = lock.next().await; |
| 37 | + drop(lock); |
| 38 | + match item { |
| 39 | + Some(name) => Ok(name), |
| 40 | + None => Err(PyStopIteration::new_err("")), |
| 41 | + } |
| 42 | + }; |
| 43 | + wait_for_future(py, next).flatten() |
| 44 | + } |
| 45 | + |
| 46 | + fn __anext__<'py>(&'py self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> { |
| 47 | + let inner = Arc::clone(&self.0); |
| 48 | + let anext = async move { |
| 49 | + let mut lock = inner.lock().await; |
| 50 | + let item = lock.next().await; |
| 51 | + drop(lock); |
| 52 | + match item { |
| 53 | + Some(name) => Ok(name), |
| 54 | + None => Err(PyStopAsyncIteration::new_err("")), |
| 55 | + } |
| 56 | + }; |
| 57 | + pyo3_async_runtimes::tokio::future_into_py(py, anext) |
| 58 | + } |
| 59 | +} |
0 commit comments