Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 37 additions & 34 deletions msgspec/_core.c
Original file line number Diff line number Diff line change
Expand Up @@ -8755,8 +8755,14 @@ ms_decode_pyint(PyObject *obj, TypeNode *type, PathNode *path) {
if (MS_UNLIKELY(type->types & MS_INT_CONSTRS)) {
if (!ms_passes_int_constraints(ux, neg, type, path)) return NULL;
}
Py_INCREF(obj);
return obj;
if (MS_LIKELY(PyLong_CheckExact(obj))) {
Py_INCREF(obj);
return obj;
}
if (!neg) {
return PyLong_FromUnsignedLongLong(ux);
}
return PyLong_FromLongLong(-(int64_t)ux);
}

static MS_NOINLINE PyObject *
Expand Down Expand Up @@ -17586,8 +17592,7 @@ from_builtins_bytes(
return NULL;
}
if (type->types & MS_TYPE_BYTES) {
Py_INCREF(obj);
return obj;
return PyBytes_FromObject(obj);
}
return PyByteArray_FromObject(obj);
}
Expand Down Expand Up @@ -18322,63 +18327,61 @@ static PyObject *
from_builtins(
FromBuiltinsState *self, PyObject *obj, TypeNode *type, PathNode *path
) {
PyObject *out = NULL;
if (MS_UNLIKELY(type->types & (MS_TYPE_CUSTOM | MS_TYPE_CUSTOM_GENERIC))) {
Py_INCREF(obj);
return ms_decode_custom(obj, self->dec_hook, type, path);
}

PyTypeObject *pytype = Py_TYPE(obj);
if (pytype == &PyUnicode_Type) {
out = self->from_builtins_str(self, obj, false, type, path);
return self->from_builtins_str(self, obj, false, type, path);
}
else if (pytype == &PyLong_Type) {
out = from_builtins_int(self, obj, type, path);
else if (pytype == &PyBool_Type) {
return from_builtins_bool(self, obj, type, path);
}
else if (PyLong_Check(obj)) {
return from_builtins_int(self, obj, type, path);
}
else if (pytype == &PyFloat_Type) {
out = from_builtins_float(self, obj, type, path);
return from_builtins_float(self, obj, type, path);
}
else if (pytype == &PyList_Type || pytype == &PyTuple_Type) {
out = from_builtins_array(self, obj, type, path);
return from_builtins_array(self, obj, type, path);
}
else if (pytype == &PyDict_Type) {
out = from_builtins_object(self, obj, type, path);
}
else if (pytype == &PyBool_Type) {
out = from_builtins_bool(self, obj, type, path);
return from_builtins_object(self, obj, type, path);
}
else if (obj == Py_None) {
out = from_builtins_none(self, obj, type, path);
return from_builtins_none(self, obj, type, path);
}
else if (pytype == &PyBytes_Type) {
out = from_builtins_bytes(self, obj, type, path);
else if (PyBytes_Check(obj)) {
return from_builtins_bytes(self, obj, type, path);
}
else if (pytype == &PyByteArray_Type) {
out = from_builtins_bytearray(self, obj, type, path);
return from_builtins_bytearray(self, obj, type, path);
}
else if (pytype == PyDateTimeAPI->DateTimeType) {
out = from_builtins_datetime(self, obj, type, path);
return from_builtins_datetime(self, obj, type, path);
}
else if (pytype == PyDateTimeAPI->TimeType) {
out = from_builtins_time(self, obj, type, path);
return from_builtins_time(self, obj, type, path);
}
else if (pytype == PyDateTimeAPI->DateType) {
out = from_builtins_immutable(self, MS_TYPE_DATE, "date", obj, type, path);
return from_builtins_immutable(self, MS_TYPE_DATE, "date", obj, type, path);
}
else if (pytype == (PyTypeObject *)self->mod->UUIDType) {
out = from_builtins_immutable(self, MS_TYPE_UUID, "uuid", obj, type, path);
return from_builtins_immutable(self, MS_TYPE_UUID, "uuid", obj, type, path);
}
else if (pytype == (PyTypeObject *)self->mod->DecimalType) {
out = from_builtins_immutable(self, MS_TYPE_DECIMAL, "decimal", obj, type, path);
return from_builtins_immutable(self, MS_TYPE_DECIMAL, "decimal", obj, type, path);
}
else {
PyErr_Format(
PyExc_TypeError,
"from_builtins doesn't support objects of type '%.200s'",
pytype->tp_name
);
return NULL;
else if (type->types & MS_TYPE_ANY) {
Py_INCREF(obj);
return obj;
}

if (MS_UNLIKELY(type->types & (MS_TYPE_CUSTOM | MS_TYPE_CUSTOM_GENERIC))) {
return ms_decode_custom(out, self->dec_hook, type, path);
else {
return ms_validation_error(pytype->tp_name, type, path);
}
return out;
}

PyDoc_STRVAR(msgspec_from_builtins__doc__,
Expand Down
88 changes: 84 additions & 4 deletions tests/test_from_builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,49 @@ def test_bad_calls(self):
def test_dec_hook_explicit_none(self):
assert from_builtins(1, int, dec_hook=None) == 1

def test_unsupported_input_type(self):
class Oops:
def test_custom_input_type(self):
class Custom:
pass

with pytest.raises(TypeError, match="doesn't support objects of type 'Oops'"):
from_builtins(Oops(), Any)
with pytest.raises(ValidationError, match="Expected `int`, got `Custom`"):
from_builtins(Custom(), int)

def test_custom_input_type_works_with_any(self):
class Custom:
pass

x = Custom()
res = from_builtins(x, Any)
assert res is x
assert sys.getrefcount(x) == 3 # x + res + 1

def test_custom_input_type_works_with_custom(self):
class Custom:
pass

x = Custom()
res = from_builtins(x, Custom)
assert res is x
assert sys.getrefcount(x) == 3 # x + res + 1

def test_custom_input_type_works_with_dec_hook(self):
class Custom:
pass

class Custom2:
pass

def dec_hook(typ, x):
if typ is Custom2:
assert isinstance(x, Custom)
return Custom2()
raise TypeError

x = Custom()
res = from_builtins(x, Custom2, dec_hook=dec_hook)
assert isinstance(res, Custom2)
assert sys.getrefcount(res) == 2 # res + 1
assert sys.getrefcount(x) == 2 # x + 1

def test_unsupported_output_type(self):
with pytest.raises(TypeError, match="more than one array-like"):
Expand Down Expand Up @@ -250,6 +287,20 @@ class Ex(Struct):
with pytest.raises(ValidationError):
from_builtins({"x": x}, Ex)

def test_int_subclass(self):
class MyInt(int):
pass

for val in [10, 0, -10]:
sol = from_builtins(MyInt(val), int)
assert type(sol) is int
assert sol == val

x = MyInt(100)
sol = from_builtins(x, MyInt)
assert sol is x
assert sys.getrefcount(x) == 3 # x + sol + 1


class TestFloat:
def test_float(self):
Expand Down Expand Up @@ -362,6 +413,22 @@ class Ex(Struct):
with pytest.raises(ValidationError):
from_builtins(msg, Ex)

def test_bytes_subclass(self):
class MyBytes(bytes):
pass

msg = MyBytes(b"abc")

for typ in [bytes, bytearray]:
sol = from_builtins(msg, typ)
assert type(sol) is typ
assert sol == b"abc"

assert sys.getrefcount(msg) == 2 # msg + 1
sol = from_builtins(msg, MyBytes)
assert sol is msg
assert sys.getrefcount(msg) == 3 # msg + sol + 1


class TestDateTime:
def test_datetime_wrong_type(self):
Expand Down Expand Up @@ -529,6 +596,19 @@ class Ex(enum.IntEnum):
with pytest.raises(ValidationError, match="Expected `int`, got `str`"):
from_builtins("A", Ex)

def test_int_enum_int_subclass(self):
class MyInt(int):
pass

class Ex(enum.IntEnum):
x = 1
y = 2

msg = MyInt(1)
assert from_builtins(msg, Ex) is Ex.x
assert sys.getrefcount(msg) == 2 # msg + 1
assert from_builtins(MyInt(2), Ex) is Ex.y


class TestLiteral:
def test_str_literal(self):
Expand Down