Skip to content

Commit

Permalink
support pickle/unpickle
Browse files Browse the repository at this point in the history
  • Loading branch information
lepenkinya committed Oct 2, 2023
1 parent 3d5f68c commit 5ab3f16
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 8 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "uuid-utils"
version = "0.3.0"
version = "0.3.1"
edition = "2021"

[lib]
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,9 @@ UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

- The `getnode` function is not available.
- The `uuid1` and `uuid6` take `node` argument as mandatory.

## How to build

```bash
RUSTFLAGS="--cfg uuid_unstable" maturin build --release
```
13 changes: 7 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
use pyo3::{
exceptions::{PyTypeError, PyValueError},
prelude::*,
pyclass::CompareOp,
types::PyBytes,
};
use pyo3::{exceptions::{PyTypeError, PyValueError}, intern, prelude::*, pyclass::CompareOp, types::PyBytes};
use std::hash::Hasher;
use std::{collections::hash_map::DefaultHasher, hash::Hash};
use pyo3::types::PyTuple;
use uuid::{Builder, Bytes, Context, Timestamp, Uuid, Variant, Version};

pub const RESERVED_NCS: &str = "reserved for NCS compatibility";
Expand Down Expand Up @@ -284,6 +280,11 @@ impl UUID {
uuid: Uuid::from_u128(int),
})
}

fn __reduce__<'a>(&self, py: Python<'a>) -> PyResult<&'a PyTuple> {
let result = py.import("uuid_utils")?.getattr(intern!(py, "UUID"))?;
return Ok(PyTuple::new(py, [result, PyTuple::new(py, [self.uuid.to_string()])]))
}
}

#[pyfunction]
Expand Down
8 changes: 8 additions & 0 deletions tests/test_uuid.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import pickle
from uuid import UUID, getnode

import pytest
Expand Down Expand Up @@ -168,3 +169,10 @@ def test_uuid_timestamp() -> None:

with pytest.raises(ValueError):
uuid_utils.uuid4().timestamp


def test_pickle():
uuid = uuid_utils.UUID("a8098c1a-f86e-11da-bd1a-00112444be1e")
uuid_pickle = pickle.dumps(uuid)
uuid_unpickle = pickle.loads(uuid_pickle)
assert uuid_unpickle == uuid

0 comments on commit 5ab3f16

Please sign in to comment.