@@ -510,3 +510,61 @@ STATIC mp_obj_t stream_ioctl(size_t n_args, const mp_obj_t *args) {
510
510
return mp_obj_new_int (res );
511
511
}
512
512
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN (mp_stream_ioctl_obj , 2 , 3 , stream_ioctl );
513
+
514
+ /*
515
+ * POSIX-like functions
516
+ *
517
+ * These functions have POSIX-compatible signature (except for "void *stream"
518
+ * first argument instead of "int fd"). They are useful to port existing
519
+ * POSIX-compatible software to work with MicroPython streams.
520
+ */
521
+
522
+
523
+ // errno-like variable. If any of the functions below returned with error
524
+ // status, this variable will contain error no.
525
+ int mp_stream_errno ;
526
+
527
+ ssize_t mp_stream_posix_write (mp_obj_t stream , const void * buf , size_t len ) {
528
+ mp_obj_base_t * o = (mp_obj_base_t * )MP_OBJ_TO_PTR (stream );
529
+ const mp_stream_p_t * stream_p = o -> type -> protocol ;
530
+ mp_uint_t out_sz = stream_p -> write (stream , buf , len , & mp_stream_errno );
531
+ if (out_sz == MP_STREAM_ERROR ) {
532
+ return -1 ;
533
+ } else {
534
+ return out_sz ;
535
+ }
536
+ }
537
+
538
+ ssize_t mp_stream_posix_read (mp_obj_t stream , void * buf , size_t len ) {
539
+ mp_obj_base_t * o = (mp_obj_base_t * )MP_OBJ_TO_PTR (stream );
540
+ const mp_stream_p_t * stream_p = o -> type -> protocol ;
541
+ mp_uint_t out_sz = stream_p -> read (stream , buf , len , & mp_stream_errno );
542
+ if (out_sz == MP_STREAM_ERROR ) {
543
+ return -1 ;
544
+ } else {
545
+ return out_sz ;
546
+ }
547
+ }
548
+
549
+ off_t mp_stream_posix_lseek (mp_obj_t stream , off_t offset , int whence ) {
550
+ const mp_obj_base_t * o = (mp_obj_base_t * )MP_OBJ_TO_PTR (stream );
551
+ const mp_stream_p_t * stream_p = o -> type -> protocol ;
552
+ struct mp_stream_seek_t seek_s ;
553
+ seek_s .offset = offset ;
554
+ seek_s .whence = whence ;
555
+ mp_uint_t res = stream_p -> ioctl (stream , MP_STREAM_SEEK , (mp_uint_t )(uintptr_t )& seek_s , & mp_stream_errno );
556
+ if (res == MP_STREAM_ERROR ) {
557
+ return -1 ;
558
+ }
559
+ return seek_s .offset ;
560
+ }
561
+
562
+ int mp_stream_posix_fsync (mp_obj_t stream ) {
563
+ mp_obj_base_t * o = (mp_obj_base_t * )MP_OBJ_TO_PTR (stream );
564
+ const mp_stream_p_t * stream_p = o -> type -> protocol ;
565
+ mp_uint_t res = stream_p -> ioctl (stream , MP_STREAM_FLUSH , 0 , & mp_stream_errno );
566
+ if (res == MP_STREAM_ERROR ) {
567
+ return -1 ;
568
+ }
569
+ return res ;
570
+ }
0 commit comments