From 0c97e4c4144565ca3b18593d708f0d7a94905c71 Mon Sep 17 00:00:00 2001
From: Paul Sokolovsky <pfalcon@users.sourceforge.net>
Date: Sun, 10 Apr 2016 12:45:46 +0300
Subject: [PATCH] py/stream: Add Python-level ioctl() method.

Will call underlying C virtual methods of stream interface. This isn't
intended to be added to every stream object (it's not in CPython), but
is convenient way to expose extra operation on Python side without
adding bunch of Python-level methods.
---
 py/stream.c | 22 ++++++++++++++++++++++
 py/stream.h |  1 +
 2 files changed, 23 insertions(+)

diff --git a/py/stream.c b/py/stream.c
index 89b9e2af4..4fda97c54 100644
--- a/py/stream.c
+++ b/py/stream.c
@@ -410,6 +410,28 @@ STATIC mp_obj_t stream_tell(mp_obj_t self) {
 }
 MP_DEFINE_CONST_FUN_OBJ_1(mp_stream_tell_obj, stream_tell);
 
+STATIC mp_obj_t stream_ioctl(size_t n_args, const mp_obj_t *args) {
+    const mp_stream_p_t *stream_p = mp_get_stream_raise(args[0], MP_STREAM_OP_IOCTL);
+
+    mp_buffer_info_t bufinfo;
+    uintptr_t val;
+    if (MP_OBJ_IS_INT(args[2])) {
+        val = mp_obj_get_int(args[2]);
+    } else {
+        mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_READ);
+        val = (uintptr_t)bufinfo.buf;
+    }
+
+    int error;
+    mp_int_t res = stream_p->ioctl(args[0], mp_obj_get_int(args[1]), val, &error);
+    if (res == MP_STREAM_ERROR) {
+        nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(error)));
+    }
+
+    return mp_obj_new_int(res);
+}
+MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_ioctl_obj, 2, 3, stream_ioctl);
+
 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_read_obj, 1, 2, stream_read);
 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_readinto_obj, 2, 3, stream_readinto);
 MP_DEFINE_CONST_FUN_OBJ_1(mp_stream_readall_obj, stream_readall);
diff --git a/py/stream.h b/py/stream.h
index 3df669fda..df6e94adf 100644
--- a/py/stream.h
+++ b/py/stream.h
@@ -55,6 +55,7 @@ MP_DECLARE_CONST_FUN_OBJ(mp_stream_unbuffered_readlines_obj);
 MP_DECLARE_CONST_FUN_OBJ(mp_stream_write_obj);
 MP_DECLARE_CONST_FUN_OBJ(mp_stream_seek_obj);
 MP_DECLARE_CONST_FUN_OBJ(mp_stream_tell_obj);
+MP_DECLARE_CONST_FUN_OBJ(mp_stream_ioctl_obj);
 
 // these are for mp_get_stream_raise and can be or'd together
 #define MP_STREAM_OP_READ (1)
-- 
GitLab