forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple.rs
More file actions
1313 lines (1217 loc) · 49.7 KB
/
Copy pathsimple.rs
File metadata and controls
1313 lines (1217 loc) · 49.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::_ctypes::CArgObject;
use super::array::PyCArray;
use super::base::{
CDATA_BUFFER_METHODS, FfiArgValue, PyCData, StgInfo, StgInfoFlags, buffer_to_ffi_value,
bytes_to_pyobject,
};
use super::function::PyCFuncPtr;
use super::pointer::PyCPointer;
use crate::builtins::{PyByteArray, PyBytes, PyInt, PyNone, PyStr, PyType, PyTypeRef};
use crate::convert::ToPyObject;
use crate::function::{Either, FuncArgs, OptionalArg};
use crate::protocol::{BufferDescriptor, PyBuffer, PyNumberMethods};
use crate::types::{AsBuffer, AsNumber, Constructor, Initializer, Representable};
use crate::{
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, set_attrs,
};
use alloc::borrow::Cow;
use core::fmt::Debug;
use num_traits::ToPrimitive;
use rustpython_host_env::ctypes::{
SimpleStorageValue, simple_storage_value_to_bytes_endian, simple_type_align,
simple_type_pep3118_code, simple_type_size, write_simple_storage_buffer, zeroed_bytes,
};
/// Valid type codes for ctypes simple types
pub(super) const SIMPLE_TYPE_CHARS: &str = cfg_select! {
// spell-checker: disable-next-line
windows => "cbBhHiIlLdfuzZqQPXOv?g",
// spell-checker: disable-next-line
_ => "cbBhHiIlLdfuzZqQPOv?g",
};
/// _ctypes_alloc_format_string_for_type
fn alloc_format_string_for_type(code: char, big_endian: bool) -> String {
let prefix = if big_endian { ">" } else { "<" };
let pep_code = simple_type_pep3118_code(code);
format!("{prefix}{pep_code}")
}
/// Create a new simple type instance from a class
fn new_simple_type(
cls: Either<&PyObject, &Py<PyType>>,
vm: &VirtualMachine,
) -> PyResult<PyCSimple> {
let cls = match cls {
Either::A(obj) => obj,
Either::B(typ) => typ.as_object(),
};
let _type_ = cls
.get_attr("_type_", vm)
.map_err(|_| vm.new_attribute_error("class must define a '_type_' attribute"))?;
if !_type_.is_instance((&vm.ctx.types.str_type).as_ref(), vm)? {
return Err(vm.new_type_error("class must define a '_type_' string attribute"));
}
let tp_str = _type_.str(vm)?.to_string();
if tp_str.len() != 1 {
return Err(vm.new_value_error(format!(
"class must define a '_type_' attribute which must be a string of length 1, str: {tp_str}"
)));
}
if !SIMPLE_TYPE_CHARS.contains(tp_str.as_str()) {
return Err(vm.new_attribute_error(format!(
"class must define a '_type_' attribute which must be\n a single character string containing one of {SIMPLE_TYPE_CHARS}, currently it is {tp_str}."
)));
}
let size = simple_type_size(&tp_str).expect("invalid ctypes simple type");
Ok(PyCSimple(PyCData::from_bytes(zeroed_bytes(size), None)))
}
fn set_primitive(_type_: &str, value: &PyObject, vm: &VirtualMachine) -> PyResult {
match _type_ {
"c" => {
// c_set: accepts bytes(len=1), bytearray(len=1), or int(0-255)
if value
.downcast_ref_if_exact::<PyBytes>(vm)
.is_some_and(|v| v.len() == 1)
|| value
.downcast_ref_if_exact::<PyByteArray>(vm)
.is_some_and(|v| v.borrow_buf().len() == 1)
|| value.downcast_ref_if_exact::<PyInt>(vm).is_some_and(|v| {
v.as_bigint()
.to_i64()
.is_some_and(|n| (0..=255).contains(&n))
})
{
Ok(value.to_owned())
} else {
Err(vm.new_type_error("one character bytes, bytearray or integer expected"))
}
}
"u" => {
if let Some(s) = value.downcast_ref::<PyStr>() {
if s.as_wtf8().code_points().count() == 1 {
Ok(value.to_owned())
} else {
Err(vm.new_type_error("one character unicode string expected"))
}
} else {
Err(vm.new_type_error(format!(
"unicode string expected instead of {} instance",
value.class().name()
)))
}
}
"b" | "h" | "H" | "i" | "I" | "l" | "q" | "L" | "Q" => {
// Support __index__ protocol
if value.try_index(vm).is_ok() {
Ok(value.to_owned())
} else {
Err(vm.new_type_error(format!(
"an integer is required (got type {})",
value.class().name()
)))
}
}
"f" | "d" | "g" => {
// Handle int specially to check overflow
if let Some(int_obj) = value.downcast_ref_if_exact::<PyInt>(vm) {
// Check if int can fit in f64
if let Some(f) = int_obj.as_bigint().to_f64()
&& f.is_finite()
{
return Ok(value.to_owned());
}
return Err(vm.new_overflow_error("int too large to convert to float"));
}
// __float__ protocol
if value.try_float(vm).is_ok() {
Ok(value.to_owned())
} else {
Err(vm.new_type_error(format!("must be real number, not {}", value.class().name())))
}
}
"?" => Ok(PyObjectRef::from(
vm.ctx.new_bool(value.to_owned().try_to_bool(vm)?),
)),
"v" => {
// VARIANT_BOOL: any truthy → True
Ok(PyObjectRef::from(
vm.ctx.new_bool(value.to_owned().try_to_bool(vm)?),
))
}
"B" => {
// Support __index__ protocol
if value.try_index(vm).is_ok() {
// Store as-is, conversion to unsigned happens in the getter
Ok(value.to_owned())
} else {
Err(vm.new_type_error(format!("int expected instead of {}", value.class().name())))
}
}
"z" => {
if value.is(&vm.ctx.none)
|| value.downcast_ref_if_exact::<PyInt>(vm).is_some()
|| value.downcast_ref_if_exact::<PyBytes>(vm).is_some()
{
Ok(value.to_owned())
} else {
Err(vm.new_type_error(format!(
"bytes or integer address expected instead of {} instance",
value.class().name()
)))
}
}
"Z" => {
if value.is(&vm.ctx.none)
|| value.downcast_ref_if_exact::<PyInt>(vm).is_some()
|| value.downcast_ref_if_exact::<PyStr>(vm).is_some()
{
Ok(value.to_owned())
} else {
Err(vm.new_type_error(format!(
"unicode string or integer address expected instead of {} instance",
value.class().name()
)))
}
}
// O_set: py_object accepts any Python object
"O" => Ok(value.to_owned()),
// X_set: BSTR - same as Z (c_wchar_p), accepts None, int, or str
"X" => {
if value.is(&vm.ctx.none)
|| value.downcast_ref_if_exact::<PyInt>(vm).is_some()
|| value.downcast_ref_if_exact::<PyStr>(vm).is_some()
{
Ok(value.to_owned())
} else {
Err(vm.new_type_error(format!(
"unicode string or integer address expected instead of {} instance",
value.class().name()
)))
}
}
_ => {
// "P"
if value.downcast_ref_if_exact::<PyInt>(vm).is_some()
|| value.downcast_ref_if_exact::<PyNone>(vm).is_some()
{
Ok(value.to_owned())
} else {
Err(vm.new_type_error("cannot be converted to pointer"))
}
}
}
}
#[pyclass(module = "_ctypes", name = "PyCSimpleType", base = PyType)]
#[derive(Debug)]
#[repr(transparent)]
pub(crate) struct PyCSimpleType(PyType);
#[pyclass(flags(BASETYPE), with(AsNumber, Initializer))]
impl PyCSimpleType {
#[pygetset(name = "__pointer_type__")]
fn pointer_type(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult {
super::base::pointer_type_get(&zelf, vm)
}
#[pygetset(name = "__pointer_type__", setter)]
fn set_pointer_type(zelf: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
super::base::pointer_type_set(&zelf, value, vm)
}
#[allow(clippy::new_ret_no_self)]
#[pymethod]
fn new(cls: PyTypeRef, _: OptionalArg, vm: &VirtualMachine) -> PyResult {
Ok(PyObjectRef::from(
new_simple_type(Either::B(&cls), vm)?.into_ref_with_type(vm, cls)?,
))
}
#[pymethod]
fn from_param(zelf: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult {
// zelf is the class (e.g., c_int) that from_param was called on
let cls = zelf
.downcast::<PyType>()
.map_err(|_| vm.new_type_error("from_param: expected a type"))?;
// 1. If the value is already an instance of the requested type, return it
if value.is_instance(cls.as_object(), vm)? {
return Ok(value);
}
// 2. Get the type code to determine conversion rules
let type_code = cls.type_code(vm);
// 3. Handle None for pointer types (c_char_p, c_wchar_p, c_void_p)
if vm.is_none(&value) && matches!(type_code.as_deref(), Some("z" | "Z" | "P")) {
return Ok(value);
}
// Helper to create CArgObject wrapping a simple instance
let create_simple_with_value = |type_str: &str, val: &PyObject| -> PyResult {
let simple = new_simple_type(Either::B(&cls), vm)?;
let buffer_bytes = value_to_bytes_endian(type_str, val, false, vm);
*simple.0.buffer.write() = alloc::borrow::Cow::Owned(buffer_bytes.clone());
let simple_obj: PyObjectRef = simple.into_ref_with_type(vm, cls.clone())?.into();
// from_param returns CArgObject, not the simple type itself
let tag = type_str.as_bytes().first().copied().unwrap_or(b'?');
let ffi_value = buffer_to_ffi_value(type_str, &buffer_bytes);
Ok(CArgObject {
tag,
value: ffi_value,
obj: simple_obj,
size: 0,
offset: 0,
}
.to_pyobject(vm))
};
// 4. Try to convert value based on type code
match type_code.as_deref() {
// Integer types: accept integers
Some(tc @ ("b" | "B" | "h" | "H" | "i" | "I" | "l" | "L" | "q" | "Q"))
if value.try_int(vm).is_ok() =>
{
return create_simple_with_value(tc, &value);
}
// Float types: accept numbers
Some(tc @ ("f" | "d" | "g"))
if value.try_float(vm).is_ok() || value.try_int(vm).is_ok() =>
{
return create_simple_with_value(tc, &value);
}
// c_char: 1 byte character
Some("c") => {
if let Some(bytes) = value.downcast_ref::<PyBytes>()
&& bytes.len() == 1
{
return create_simple_with_value("c", &value);
}
if let Ok(int_val) = value.try_int(vm)
&& int_val.as_bigint().to_u8().is_some()
{
return create_simple_with_value("c", &value);
}
return Err(vm.new_type_error("one character bytes, bytearray or integer expected"));
}
// c_wchar: 1 unicode character
Some("u") => {
if let Some(s) = value.downcast_ref::<PyStr>()
&& s.as_wtf8().code_points().count() == 1
{
return create_simple_with_value("u", &value);
}
return Err(vm.new_type_error("one character unicode string expected"));
}
// c_char_p: bytes pointer
Some("z") => {
// 1. bytes → create CArgObject with null-terminated buffer
if let Some(bytes) = value.downcast_ref::<PyBytes>() {
let (kept_alive, ptr) = super::base::ensure_z_null_terminated(bytes, vm);
return Ok(CArgObject {
tag: b'z',
value: FfiArgValue::OwnedPointer(ptr, kept_alive),
obj: value.clone(),
size: 0,
offset: 0,
}
.to_pyobject(vm));
}
// 2. Array/Pointer with c_char element type
if is_cchar_array_or_pointer(&value, vm) {
return Ok(value);
}
// 3. CArgObject (byref(c_char(...)))
if let Some(carg) = value.downcast_ref::<CArgObject>()
&& carg.tag == b'c'
{
return Ok(value.clone());
}
}
// c_wchar_p: unicode pointer
Some("Z") => {
// 1. str → create CArgObject with null-terminated wchar buffer
if let Some(s) = value.downcast_ref::<PyStr>() {
let (holder, ptr) = super::base::str_to_wchar_bytes(s.as_wtf8(), vm);
return Ok(CArgObject {
tag: b'Z',
value: FfiArgValue::OwnedPointer(ptr, holder),
obj: value.clone(),
size: 0,
offset: 0,
}
.to_pyobject(vm));
}
// 2. Array/Pointer with c_wchar element type
if is_cwchar_array_or_pointer(&value, vm)? {
return Ok(value);
}
// 3. CArgObject (byref(c_wchar(...)))
if let Some(carg) = value.downcast_ref::<CArgObject>()
&& carg.tag == b'u'
{
return Ok(value.clone());
}
}
// c_void_p: most flexible - accepts int, bytes, str, any array/pointer, funcptr
Some("P") => {
// 1. int → create c_void_p with that address
if value.try_int(vm).is_ok() {
return create_simple_with_value("P", &value);
}
// 2. bytes → create CArgObject with null-terminated buffer
if let Some(bytes) = value.downcast_ref::<PyBytes>() {
let (kept_alive, ptr) = super::base::ensure_z_null_terminated(bytes, vm);
return Ok(CArgObject {
tag: b'z',
value: FfiArgValue::OwnedPointer(ptr, kept_alive),
obj: value.clone(),
size: 0,
offset: 0,
}
.to_pyobject(vm));
}
// 3. str → create CArgObject with null-terminated wchar buffer
if let Some(s) = value.downcast_ref::<PyStr>() {
let (holder, ptr) = super::base::str_to_wchar_bytes(s.as_wtf8(), vm);
return Ok(CArgObject {
tag: b'Z',
value: FfiArgValue::OwnedPointer(ptr, holder),
obj: value.clone(),
size: 0,
offset: 0,
}
.to_pyobject(vm));
}
// 4. Any Array or Pointer → accept directly
if value.downcast_ref::<PyCArray>().is_some()
|| value.downcast_ref::<PyCPointer>().is_some()
{
return Ok(value);
}
// 5. CArgObject with 'P' tag (byref(c_void_p(...)))
if let Some(carg) = value.downcast_ref::<CArgObject>()
&& carg.tag == b'P'
{
return Ok(value.clone());
}
// 6. PyCFuncPtr → extract function pointer address
if let Some(funcptr) = value.downcast_ref::<PyCFuncPtr>() {
let ptr_val = {
let buffer = funcptr._base.buffer.read();
rustpython_host_env::ctypes::read_pointer_from_buffer(&buffer)
};
return Ok(CArgObject {
tag: b'P',
value: FfiArgValue::pointer(ptr_val),
obj: value.clone(),
size: 0,
offset: 0,
}
.to_pyobject(vm));
}
// 7. c_char_p or c_wchar_p instance → extract pointer value
if let Some(simple) = value.downcast_ref::<PyCSimple>() {
let value_type_code = value.class().type_code(vm);
if matches!(value_type_code.as_deref(), Some("z" | "Z")) {
let ptr_val = {
let buffer = simple.0.buffer.read();
rustpython_host_env::ctypes::read_pointer_from_buffer(&buffer)
};
return Ok(CArgObject {
tag: b'Z',
value: FfiArgValue::pointer(ptr_val),
obj: value.clone(),
size: 0,
offset: 0,
}
.to_pyobject(vm));
}
}
}
// py_object: pass any Python object as PyObject*
Some("O") => {
return Ok(CArgObject {
tag: b'O',
value: FfiArgValue::pointer(value.get_id()),
obj: value,
size: 0,
offset: 0,
}
.to_pyobject(vm));
}
// c_bool
Some("?") => {
let bool_val = value.is_true(vm)?;
let bool_obj: PyObjectRef = vm.ctx.new_bool(bool_val).into();
return create_simple_with_value("?", &bool_obj);
}
_ => {}
}
// 5. Check for _as_parameter_ attribute
if let Ok(as_parameter) = value.get_attr("_as_parameter_", vm) {
return Self::from_param(cls.as_object().to_owned(), as_parameter, vm);
}
// 6. Type-specific error messages
match type_code.as_deref() {
Some("z") => Err(vm.new_type_error(format!(
"'{}' object cannot be interpreted as ctypes.c_char_p",
value.class().name()
))),
Some("Z") => Err(vm.new_type_error(format!(
"'{}' object cannot be interpreted as ctypes.c_wchar_p",
value.class().name()
))),
_ => Err(vm.new_type_error("wrong type")),
}
}
fn __mul__(cls: PyTypeRef, n: isize, vm: &VirtualMachine) -> PyResult {
PyCSimple::repeat(cls, n, vm)
}
}
impl AsNumber for PyCSimpleType {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
multiply: Some(|a, b, vm| {
// a is a PyCSimpleType instance (type object like c_char)
// b is int (array size)
let cls = a
.downcast_ref::<PyType>()
.ok_or_else(|| vm.new_type_error("expected type"))?;
let n = b
.try_index(vm)?
.as_bigint()
.to_isize()
.ok_or_else(|| vm.new_overflow_error("array size too large"))?;
PyCSimple::repeat(cls.to_owned(), n, vm)
}),
..PyNumberMethods::NOT_IMPLEMENTED
};
&AS_NUMBER
}
}
impl Initializer for PyCSimpleType {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// type_init requires exactly 3 positional arguments: name, bases, dict
if args.args.len() != 3 {
return Err(vm.new_type_error(format!(
"type.__init__() takes 3 positional arguments but {} were given",
args.args.len()
)));
}
// Get the type from the metatype instance
let type_ref: PyTypeRef = zelf
.as_object()
.to_owned()
.downcast()
.map_err(|_| vm.new_type_error("expected type"))?;
type_ref.check_not_initialized(vm)?;
// Get _type_ attribute
let type_attr = match type_ref.as_object().get_attr("_type_", vm) {
Ok(attr) => attr,
Err(_) => {
return Err(vm.new_attribute_error("class must define a '_type_' attribute"));
}
};
// Validate _type_ is a string
let type_str = type_attr.str(vm)?.to_string();
// Validate _type_ is a single character
if type_str.len() != 1 {
return Err(vm.new_value_error(
"class must define a '_type_' attribute which must be a string of length 1",
));
}
// Validate _type_ is a valid type character
if !SIMPLE_TYPE_CHARS.contains(type_str.as_str()) {
return Err(vm.new_attribute_error(format!(
"class must define a '_type_' attribute which must be a single character string containing one of '{SIMPLE_TYPE_CHARS}', currently it is '{type_str}'."
)));
}
// Initialize StgInfo
let size = simple_type_size(&type_str).expect("invalid ctypes simple type");
let align = simple_type_align(&type_str).expect("invalid ctypes simple type");
let mut stg_info = StgInfo::new(size, align);
// Set format for PEP 3118 buffer protocol
stg_info.format = Some(alloc_format_string_for_type(
type_str.chars().next().unwrap_or('?'),
cfg!(target_endian = "big"),
));
stg_info.paramfunc = super::base::ParamFunc::Simple;
// Set TYPEFLAG_ISPOINTER for pointer types: z (c_char_p), Z (c_wchar_p),
// P (c_void_p), s (char array), X (BSTR), O (py_object)
if matches!(type_str.as_str(), "z" | "Z" | "P" | "s" | "X" | "O") {
stg_info.flags |= StgInfoFlags::TYPEFLAG_ISPOINTER;
}
super::base::set_or_init_stginfo(&type_ref, stg_info);
// Create __ctype_le__ and __ctype_be__ swapped types
create_swapped_types(&type_ref, &type_str, vm)?;
Ok(())
}
}
/// Create __ctype_le__ and __ctype_be__ swapped byte order types
/// On little-endian systems: __ctype_le__ = self, __ctype_be__ = swapped type
/// On big-endian systems: __ctype_be__ = self, __ctype_le__ = swapped type
///
/// - Single-byte types (c, b, B): __ctype_le__ = __ctype_be__ = self
/// - Pointer/unsupported types (z, Z, P, u, O): NO __ctype_le__/__ctype_be__ attributes
/// - Multi-byte numeric types (h, H, i, I, l, L, q, Q, f, d, g, ?): create swapped types
fn create_swapped_types(
type_ref: &Py<PyType>,
type_str: &str,
vm: &VirtualMachine,
) -> PyResult<()> {
use crate::builtins::PyDict;
// Avoid infinite recursion - if __ctype_le__ already exists, skip
if type_ref.as_object().get_attr("__ctype_le__", vm).is_ok() {
return Ok(());
}
// Types that don't support byte order swapping - no __ctype_le__/__ctype_be__
// c_void_p (P), c_char_p (z), c_wchar_p (Z), c_wchar (u), py_object (O)
let unsupported_types = ["P", "z", "Z", "u", "O"];
if unsupported_types.contains(&type_str) {
return Ok(());
}
// Single-byte types - __ctype_le__ = __ctype_be__ = self (no swapping needed)
// c_char (c), c_byte (b), c_ubyte (B)
let single_byte_types = ["c", "b", "B"];
if single_byte_types.contains(&type_str) {
set_attrs!(
type_ref.as_object(), vm,
"__ctype_le__" => type_ref.as_object().to_owned(),
"__ctype_be__" => type_ref.as_object().to_owned(),
);
return Ok(());
}
// Multi-byte types - create swapped type
// Check system byte order at compile time
let is_little_endian = cfg!(target_endian = "little");
// Create dict for the swapped (non-native) type
let swapped_dict: crate::PyRef<crate::builtins::PyDict> = PyDict::default().into_ref(&vm.ctx);
swapped_dict.set_item("_type_", vm.ctx.new_str(type_str).into(), vm)?;
// Create the swapped type using the same metaclass
let metaclass = type_ref.class();
let bases = vm.ctx.new_tuple(vec![type_ref.as_object().to_owned()]);
// Set placeholder first to prevent recursion
set_attrs!(
type_ref.as_object(), vm,
"__ctype_le__" => vm.ctx.none(),
"__ctype_be__" => vm.ctx.none(),
);
// Create only the non-native endian type
let suffix = if is_little_endian { "_be" } else { "_le" };
let swapped_type = metaclass.as_object().call(
(
vm.ctx.new_str(format!("{}{}", type_ref.name(), suffix)),
bases,
swapped_dict.as_object().to_owned(),
),
vm,
)?;
// Set _swappedbytes_ on the swapped type to indicate byte swapping is needed
set_attrs!(
swapped_type, vm,
"_swappedbytes_" => vm.ctx.none(),
);
// Update swapped type's StgInfo format to use opposite endian prefix
if let Ok(swapped_type_ref) = swapped_type.clone().downcast::<PyType>()
&& let Some(mut sw_stg) = swapped_type_ref.get_type_data_mut::<StgInfo>()
{
// Swapped: little-endian system uses big-endian prefix and vice versa
sw_stg.format = Some(alloc_format_string_for_type(
type_str.chars().next().unwrap_or('?'),
is_little_endian,
));
}
// Set attributes based on system byte order
// Native endian attribute points to self, non-native points to swapped type
let type_obj = type_ref.as_object().to_owned();
let swapped_obj = swapped_type.clone();
let (ctype_le, ctype_be) = if is_little_endian {
// Little-endian system: __ctype_le__ = self, __ctype_be__ = swapped
(type_obj, swapped_obj)
} else {
// Big-endian system: __ctype_le__ = swapped, __ctype_be__ = self
(swapped_obj, type_obj)
};
set_attrs!(
type_ref.as_object(), vm,
"__ctype_le__" => ctype_le.clone(),
"__ctype_be__" => ctype_be.clone(),
);
set_attrs!(
swapped_type, vm,
"__ctype_le__" => ctype_le,
"__ctype_be__" => ctype_be,
);
Ok(())
}
#[pyclass(
module = "_ctypes",
name = "_SimpleCData",
base = PyCData,
metaclass = "PyCSimpleType"
)]
#[repr(transparent)]
pub(crate) struct PyCSimple(pub PyCData);
impl Debug for PyCSimple {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("PyCSimple")
.field("size", &self.0.buffer.read().len())
.finish()
}
}
fn value_to_bytes_endian(
_type_: &str,
value: &PyObject,
swapped: bool,
vm: &VirtualMachine,
) -> Vec<u8> {
let storage_value = match _type_ {
"c" => {
// c_char - single byte (bytes, bytearray, or int 0-255)
if let Some(bytes) = value.downcast_ref::<PyBytes>()
&& !bytes.is_empty()
{
SimpleStorageValue::Byte(bytes.as_bytes()[0])
} else if let Some(bytearray) = value.downcast_ref::<PyByteArray>() {
let buf = bytearray.borrow_buf();
if !buf.is_empty() {
SimpleStorageValue::Byte(buf[0])
} else {
SimpleStorageValue::Zero
}
} else if let Ok(int_val) = value.try_int(vm)
&& let Some(v) = int_val.as_bigint().to_u8()
{
SimpleStorageValue::Byte(v)
} else {
SimpleStorageValue::Zero
}
}
"u" => {
// c_wchar - platform-dependent size (2 on Windows, 4 on Unix)
if let Some(s) = value.downcast_ref::<PyStr>() {
let mut cps = s.as_wtf8().code_points();
if let (Some(c), None) = (cps.next(), cps.next()) {
SimpleStorageValue::Wchar(c.to_u32())
} else {
SimpleStorageValue::Zero
}
} else {
SimpleStorageValue::Zero
}
}
"b" => {
// c_byte - signed char (1 byte)
if let Ok(int_val) = value.try_index(vm) {
SimpleStorageValue::Signed(int_val.as_bigint().to_i128().expect("int too large"))
} else {
SimpleStorageValue::Zero
}
}
"B" => {
// c_ubyte - unsigned char (1 byte)
if let Ok(int_val) = value.try_index(vm) {
SimpleStorageValue::Signed(int_val.as_bigint().to_i128().expect("int too large"))
} else {
SimpleStorageValue::Zero
}
}
"h" => {
// c_short (2 bytes)
if let Ok(int_val) = value.try_index(vm) {
SimpleStorageValue::Signed(int_val.as_bigint().to_i128().expect("int too large"))
} else {
SimpleStorageValue::Zero
}
}
"H" => {
// c_ushort (2 bytes)
if let Ok(int_val) = value.try_index(vm) {
SimpleStorageValue::Signed(int_val.as_bigint().to_i128().expect("int too large"))
} else {
SimpleStorageValue::Zero
}
}
"i" => {
// c_int (4 bytes)
if let Ok(int_val) = value.try_index(vm) {
SimpleStorageValue::Signed(int_val.as_bigint().to_i128().expect("int too large"))
} else {
SimpleStorageValue::Zero
}
}
"I" => {
// c_uint (4 bytes)
if let Ok(int_val) = value.try_index(vm) {
SimpleStorageValue::Signed(int_val.as_bigint().to_i128().expect("int too large"))
} else {
SimpleStorageValue::Zero
}
}
"l" => {
// c_long (platform dependent)
if let Ok(int_val) = value.try_index(vm) {
SimpleStorageValue::Signed(int_val.as_bigint().to_i128().expect("int too large"))
} else {
SimpleStorageValue::Zero
}
}
"L" => {
// c_ulong (platform dependent)
if let Ok(int_val) = value.try_index(vm) {
SimpleStorageValue::Signed(int_val.as_bigint().to_i128().expect("int too large"))
} else {
SimpleStorageValue::Zero
}
}
"q" => {
// c_longlong (8 bytes)
if let Ok(int_val) = value.try_index(vm) {
SimpleStorageValue::Signed(int_val.as_bigint().to_i128().expect("int too large"))
} else {
SimpleStorageValue::Zero
}
}
"Q" => {
// c_ulonglong (8 bytes)
if let Ok(int_val) = value.try_index(vm) {
SimpleStorageValue::Signed(int_val.as_bigint().to_i128().expect("int too large"))
} else {
SimpleStorageValue::Zero
}
}
"f" => {
// c_float (4 bytes) - also accepts int
if let Ok(float_val) = value.try_float(vm) {
SimpleStorageValue::Float(float_val.to_f64())
} else if let Ok(int_val) = value.try_int(vm)
&& let Some(v) = int_val.as_bigint().to_f64()
{
SimpleStorageValue::Float(v)
} else {
SimpleStorageValue::Zero
}
}
"d" => {
// c_double (8 bytes) - also accepts int
if let Ok(float_val) = value.try_float(vm) {
SimpleStorageValue::Float(float_val.to_f64())
} else if let Ok(int_val) = value.try_int(vm)
&& let Some(v) = int_val.as_bigint().to_f64()
{
SimpleStorageValue::Float(v)
} else {
SimpleStorageValue::Zero
}
}
"g" => {
// long double - platform dependent size
// Store as f64, zero-pad to platform long double size
// Note: This may lose precision on platforms where long double > 64 bits
let value = if let Ok(float_val) = value.try_float(vm) {
float_val.to_f64()
} else if let Ok(int_val) = value.try_int(vm) {
int_val.as_bigint().to_f64().unwrap_or(0.0)
} else {
0.0
};
SimpleStorageValue::Float(value)
}
"?" => {
// c_bool (1 byte)
if let Ok(b) = value.to_owned().try_to_bool(vm) {
SimpleStorageValue::Bool(b)
} else {
SimpleStorageValue::Zero
}
}
"v" => {
// VARIANT_BOOL: True = 0xFFFF (-1 as i16), False = 0x0000
if let Ok(b) = value.to_owned().try_to_bool(vm) {
SimpleStorageValue::Bool(b)
} else {
SimpleStorageValue::Zero
}
}
"P" => {
// c_void_p - pointer type (platform pointer size)
if let Ok(int_val) = value.try_index(vm) {
let v = int_val
.as_bigint()
.to_usize()
.expect("int too large for pointer");
SimpleStorageValue::Pointer(v)
} else {
SimpleStorageValue::Zero
}
}
"z" => {
// c_char_p - pointer to char (stores pointer value from int)
// PyBytes case is handled in slot_new/set_value with make_z_buffer()
if let Ok(int_val) = value.try_index(vm) {
let v = int_val
.as_bigint()
.to_usize()
.expect("int too large for pointer");
SimpleStorageValue::Pointer(v)
} else {
SimpleStorageValue::Zero
}
}
"Z" => {
// c_wchar_p - pointer to wchar_t (stores pointer value from int)
// PyStr case is handled in slot_new/set_value with make_wchar_buffer()
if let Ok(int_val) = value.try_index(vm) {
let v = int_val
.as_bigint()
.to_usize()
.expect("int too large for pointer");
SimpleStorageValue::Pointer(v)
} else {
SimpleStorageValue::Zero
}
}
"O" => {
// py_object - store object id as non-zero marker
// The actual object is stored in _objects
// Use object's id as a non-zero placeholder (indicates non-NULL)
SimpleStorageValue::ObjectId(value.get_id())
}
_ => SimpleStorageValue::Zero,
};
simple_storage_value_to_bytes_endian(_type_, storage_value, swapped)
}
/// Check if value is a c_char array or pointer(c_char)
fn is_cchar_array_or_pointer(value: &PyObject, vm: &VirtualMachine) -> bool {
// Check Array with c_char element type
if let Some(arr) = value.downcast_ref::<PyCArray>()
&& let Some(info) = arr.class().stg_info_opt()
&& let Some(ref elem_type) = info.element_type
&& let Some(elem_code) = elem_type.type_code(vm)
{
return elem_code == "c";
}
// Check Pointer to c_char
if let Some(ptr) = value.downcast_ref::<PyCPointer>()
&& let Some(info) = ptr.class().stg_info_opt()
&& let Some(ref proto) = info.proto
&& let Some(proto_code) = proto.type_code(vm)
{
return proto_code == "c";
}
false
}
/// Check if value is a c_wchar array or pointer(c_wchar)
fn is_cwchar_array_or_pointer(value: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
// Check Array with c_wchar element type
if let Some(arr) = value.downcast_ref::<PyCArray>() {
let info = arr.class().stg_info(vm)?;
let elem_type = info.element_type.as_ref().expect("array has element_type");
if let Some(elem_code) = elem_type.type_code(vm) {
return Ok(elem_code == "u");
}
}
// Check Pointer to c_wchar
if let Some(ptr) = value.downcast_ref::<PyCPointer>() {
let info = ptr.class().stg_info(vm)?;
if let Some(ref proto) = info.proto
&& let Some(proto_code) = proto.type_code(vm)
{
return Ok(proto_code == "u");
}
}
Ok(false)
}
impl Constructor for PyCSimple {
type Args = (OptionalArg,);
fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
let args: Self::Args = args.bind(vm)?;
let _type_ = cls
.type_code(vm)
.ok_or_else(|| vm.new_type_error("abstract class"))?;
// Save the initial argument for c_char_p/c_wchar_p _objects
let init_arg = args.0.into_option();
// Handle z/Z types with PyBytes/PyStr separately to avoid memory leak
if let Some(ref v) = init_arg {
if _type_ == "z" {
if let Some(bytes) = v.downcast_ref::<PyBytes>() {
let (kept_alive, ptr) = super::base::ensure_z_null_terminated(bytes, vm);
let buffer = rustpython_host_env::ctypes::pointer_bytes(ptr);
let cdata = PyCData::from_bytes(buffer, Some(v.clone()));
*cdata.base.write() = Some(kept_alive);
return Self(cdata).into_ref_with_type(vm, cls).map(Into::into);
}
} else if _type_ == "Z"
&& let Some(s) = v.downcast_ref::<PyStr>()
{
let (holder, ptr) = super::base::str_to_wchar_bytes(s.as_wtf8(), vm);
let buffer = rustpython_host_env::ctypes::pointer_bytes(ptr);