Skip to content

Commit da78307

Browse files
committed
implement the __bytes__ method and add a test case
1 parent c6e81a0 commit da78307

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src_c/color.c

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,9 @@ _color_int(pgColorObject *);
181181
static PyObject *
182182
_color_float(pgColorObject *);
183183

184+
static PyObject *
185+
_color_bytes(pgColorObject *);
186+
184187
/* Sequence protocol methods */
185188
static Py_ssize_t
186189
_color_length(pgColorObject *);
@@ -256,6 +259,8 @@ static PyMethodDef _color_methods[] = {
256259
{"premul_alpha", (PyCFunction)_premul_alpha, METH_NOARGS,
257260
DOC_COLOR_PREMULALPHA},
258261
{"update", (PyCFunction)_color_update, METH_FASTCALL, DOC_COLOR_UPDATE},
262+
{"__bytes__", (PyCFunction)_color_bytes, METH_NOARGS,
263+
"Get a byte representation of the color"},
259264
{NULL, NULL, 0, NULL}};
260265

261266
/**
@@ -1753,6 +1758,16 @@ _color_float(pgColorObject *color)
17531758
return PyFloat_FromDouble((double)tmp);
17541759
}
17551760

1761+
/**
1762+
* bytes(color)
1763+
*/
1764+
static PyObject *
1765+
_color_bytes(pgColorObject *color)
1766+
{
1767+
return PyBytes_FromFormat("%c%c%c%c", color->data[0], color->data[1],
1768+
color->data[2], color->data[3]);
1769+
}
1770+
17561771
/* Sequence protocol methods */
17571772

17581773
/**

test/color_test.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -773,6 +773,17 @@ def test_long(self):
773773
self.assertEqual(c.a, 146)
774774
self.assertEqual(int(c), int(0x33727592))
775775

776+
def test_bytes(self):
777+
c = pygame.Color(0x00012345)
778+
self.assertEqual(c.r, 0x00)
779+
self.assertEqual(c.g, 0x01)
780+
self.assertEqual(c.b, 0x23)
781+
self.assertEqual(c.a, 0x45)
782+
783+
as_bytes = bytes(c)
784+
self.assertEqual(as_bytes, bytes([0x00, 0x01, 0x23, 0x45]))
785+
self.assertEqual(len(as_bytes), 4)
786+
776787
def test_from_cmy(self):
777788
cmy = pygame.Color.from_cmy(0.5, 0.5, 0.5)
778789
cmy_tuple = pygame.Color.from_cmy((0.5, 0.5, 0.5))

0 commit comments

Comments
 (0)