Skip to content

Commit

Permalink
Support option=None per Optional[int]
Browse files Browse the repository at this point in the history
  • Loading branch information
ijl committed Dec 2, 2022
1 parent 8a97cb7 commit 6c28b9b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
24 changes: 14 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,12 +324,14 @@ pub unsafe extern "C" fn dumps(

let mut optsbits: i32 = 0;
if let Some(opts) = optsptr {
if (*opts.as_ptr()).ob_type != typeref::INT_TYPE {
return raise_dumps_exception(Cow::Borrowed("Invalid opts"));
}
optsbits = PyLong_AsLong(optsptr.unwrap().as_ptr()) as i32;
if !(0..=opt::MAX_OPT).contains(&optsbits) {
if opts.as_ptr() == typeref::NONE {
} else if (*opts.as_ptr()).ob_type != typeref::INT_TYPE {
return raise_dumps_exception(Cow::Borrowed("Invalid opts"));
} else {
optsbits = PyLong_AsLong(optsptr.unwrap().as_ptr()) as i32;
if !(0..=opt::MAX_OPT).contains(&optsbits) {
return raise_dumps_exception(Cow::Borrowed("Invalid opts"));
}
}
}

Expand Down Expand Up @@ -392,12 +394,14 @@ pub unsafe extern "C" fn dumps(

let mut optsbits: i32 = 0;
if let Some(opts) = optsptr {
if (*opts.as_ptr()).ob_type != typeref::INT_TYPE {
return raise_dumps_exception(Cow::Borrowed("Invalid opts"));
}
optsbits = PyLong_AsLong(optsptr.unwrap().as_ptr()) as i32;
if optsbits < 0 || optsbits > opt::MAX_OPT {
if opts.as_ptr() == typeref::NONE {
} else if (*opts.as_ptr()).ob_type != typeref::INT_TYPE {
return raise_dumps_exception(Cow::Borrowed("Invalid opts"));
} else {
optsbits = PyLong_AsLong(optsptr.unwrap().as_ptr()) as i32;
if !(0..=opt::MAX_OPT).contains(&optsbits) {
return raise_dumps_exception(Cow::Borrowed("Invalid opts"));
}
}
}

Expand Down
10 changes: 10 additions & 0 deletions test/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,15 @@ def test_valueerror(self):
pytest.raises(orjson.JSONDecodeError, orjson.loads, "{")
pytest.raises(ValueError, orjson.loads, "{")

def test_optional_none(self):
"""
dumps() option, default None
"""
assert orjson.dumps([], option=None) == b"[]"
assert orjson.dumps([], default=None) == b"[]"
assert orjson.dumps([], option=None, default=None) == b"[]"
assert orjson.dumps([], None, None) == b"[]"

def test_option_not_int(self):
"""
dumps() option not int or None
Expand Down Expand Up @@ -173,6 +182,7 @@ def test_dumps_signature(self):
)
inspect.signature(orjson.dumps).bind("str")
inspect.signature(orjson.dumps).bind("str", default=default, option=1)
inspect.signature(orjson.dumps).bind("str", default=None, option=None)

def test_loads_signature(self):
"""
Expand Down

0 comments on commit 6c28b9b

Please sign in to comment.