forked from numpy/numpy-user-dtypes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcasts.cpp
More file actions
1666 lines (1455 loc) · 51.7 KB
/
casts.cpp
File metadata and controls
1666 lines (1455 loc) · 51.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
#define PY_ARRAY_UNIQUE_SYMBOL QuadPrecType_ARRAY_API
#define PY_UFUNC_UNIQUE_SYMBOL QuadPrecType_UFUNC_API
#define NPY_NO_DEPRECATED_API NPY_2_0_API_VERSION
#define NPY_TARGET_VERSION NPY_2_0_API_VERSION
#define NO_IMPORT_ARRAY
#define NO_IMPORT_UFUNC
extern "C" {
#include <Python.h>
#include "numpy/arrayobject.h"
#include "numpy/halffloat.h"
#include "numpy/ndarraytypes.h"
#include "numpy/dtype_api.h"
}
#include <cstring>
#include <cstdlib>
#include "sleef.h"
#include "sleefquad.h"
#include "quad_common.h"
#include "scalar.h"
#include "casts.h"
#include "dtype.h"
#include "utilities.h"
#include "lock.h"
#include "dragon4.h"
#include "ops.hpp"
#define NUM_CASTS 40 // 18 to_casts + 18 from_casts + 1 quad_to_quad + 1 void_to_quad
#define QUAD_STR_WIDTH 50 // 42 is enough for scientific notation float128, just keeping some buffer
static NPY_CASTING
quad_to_quad_resolve_descriptors(PyObject *NPY_UNUSED(self),
PyArray_DTypeMeta *NPY_UNUSED(dtypes[2]),
QuadPrecDTypeObject *given_descrs[2],
QuadPrecDTypeObject *loop_descrs[2], npy_intp *view_offset)
{
Py_INCREF(given_descrs[0]);
loop_descrs[0] = given_descrs[0];
if (given_descrs[1] == NULL) {
Py_INCREF(given_descrs[0]);
loop_descrs[1] = given_descrs[0];
*view_offset = 0;
return NPY_NO_CASTING;
}
Py_INCREF(given_descrs[1]);
loop_descrs[1] = given_descrs[1];
if (given_descrs[0]->backend != given_descrs[1]->backend) {
// Different backends require actual conversion, no view possible
*view_offset = NPY_MIN_INTP;
if (given_descrs[0]->backend == BACKEND_SLEEF) {
// SLEEF -> long double may lose precision
return NPY_SAME_KIND_CASTING;
}
// long double -> SLEEF preserves value exactly
return NPY_SAFE_CASTING;
}
*view_offset = 0;
return NPY_NO_CASTING;
}
template <bool Aligned>
static int
quad_to_quad_strided_loop(PyArrayMethod_Context *context, char *const data[],
npy_intp const dimensions[], npy_intp const strides[],
void *NPY_UNUSED(auxdata))
{
npy_intp N = dimensions[0];
char *in_ptr = data[0];
char *out_ptr = data[1];
npy_intp in_stride = strides[0];
npy_intp out_stride = strides[1];
QuadPrecDTypeObject *descr_in = (QuadPrecDTypeObject *)context->descriptors[0];
QuadPrecDTypeObject *descr_out = (QuadPrecDTypeObject *)context->descriptors[1];
QuadBackendType backend_in = descr_in->backend;
QuadBackendType backend_out = descr_out->backend;
// inter-backend casting
if (backend_in != backend_out) {
while (N--) {
quad_value in_val;
load_quad<Aligned>(in_ptr, backend_in, &in_val);
quad_value out_val;
if (backend_in == BACKEND_SLEEF)
{
out_val.longdouble_value = static_cast<long double>(cast_sleef_to_double(in_val.sleef_value));
}
else
{
long double ld = in_val.longdouble_value;
if (std::isnan(ld)) {
out_val.sleef_value = (!ld_signbit(&ld)) ? QUAD_PRECISION_NAN : QUAD_PRECISION_NEG_NAN;
}
else if (std::isinf(ld)) {
out_val.sleef_value = (ld > 0) ? QUAD_PRECISION_INF : QUAD_PRECISION_NINF;
}
else
{
// to prevent compiler optimizations, ABI handling issues with __float128 on x86-64 machines
// won't be expensive as for fixed size compiler can optimize memcpy with movq
Sleef_quad temp = Sleef_cast_from_doubleq1(static_cast<double>(ld));
std::memcpy(&out_val.sleef_value, &temp, sizeof(Sleef_quad));
}
}
store_quad<Aligned>(out_ptr, &out_val, backend_out);
in_ptr += in_stride;
out_ptr += out_stride;
}
return 0;
}
// same backend: direct copy
// same_value casting not needed here as values are identical
while(N--) {
quad_value val;
load_quad<Aligned>(in_ptr, backend_in, &val);
store_quad<Aligned>(out_ptr, &val, backend_out);
in_ptr += in_stride;
out_ptr += out_stride;
}
return 0;
}
static NPY_CASTING
void_to_quad_resolve_descriptors(PyObject *NPY_UNUSED(self), PyArray_DTypeMeta *dtypes[2],
PyArray_Descr *given_descrs[2], PyArray_Descr *loop_descrs[2],
npy_intp *view_offset)
{
PyErr_SetString(PyExc_TypeError, "Void to QuadPrecision cast is not implemented");
return (NPY_CASTING)-1;
}
static int
void_to_quad_strided_loop(PyArrayMethod_Context *context, char *const data[],
npy_intp const dimensions[], npy_intp const strides[],
void *NPY_UNUSED(auxdata))
{
PyErr_SetString(PyExc_RuntimeError, "void_to_quad_strided_loop should not be called");
return -1;
}
// Unicode/String to QuadDType casting
static NPY_CASTING
unicode_to_quad_resolve_descriptors(PyObject *NPY_UNUSED(self), PyArray_DTypeMeta *dtypes[2],
PyArray_Descr *given_descrs[2], PyArray_Descr *loop_descrs[2],
npy_intp *view_offset)
{
if (!PyArray_ISNBO(given_descrs[0]->byteorder)) {
loop_descrs[0] = PyArray_DescrNewByteorder(given_descrs[0], NPY_NATIVE);
if (loop_descrs[0] == nullptr) {
return (NPY_CASTING)-1;
}
}
else {
Py_INCREF(given_descrs[0]);
loop_descrs[0] = given_descrs[0];
}
if (given_descrs[1] == NULL) {
loop_descrs[1] = (PyArray_Descr *)new_quaddtype_instance(BACKEND_SLEEF);
if (loop_descrs[1] == nullptr) {
Py_DECREF(loop_descrs[0]);
return (NPY_CASTING)-1;
}
}
else {
Py_INCREF(given_descrs[1]);
loop_descrs[1] = given_descrs[1];
}
return NPY_UNSAFE_CASTING;
}
// Helper function: Convert UCS4 string to quad_value
static inline int
unicode_to_quad_convert(const Py_UCS4 *ucs4_str, npy_intp unicode_size_chars,
QuadBackendType backend, quad_value *out_val)
{
PyObject *unicode_obj = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, ucs4_str, unicode_size_chars);
if (unicode_obj == NULL) {
return -1;
}
const char *utf8_str = PyUnicode_AsUTF8(unicode_obj);
if (utf8_str == NULL) {
Py_DECREF(unicode_obj);
return -1;
}
char *endptr;
int err = NumPyOS_ascii_strtoq(utf8_str, backend, out_val, &endptr);
if (err < 0) {
PyErr_Format(PyExc_ValueError,
"could not convert string to QuadPrecision: np.str_('%s')", utf8_str);
Py_DECREF(unicode_obj);
return -1;
}
// Check that we parsed the entire string (skip trailing whitespace)
while (ascii_isspace(*endptr)) {
endptr++;
}
if (*endptr != '\0') {
PyErr_Format(PyExc_ValueError,
"could not convert string to QuadPrecision: np.str_('%s')", utf8_str);
Py_DECREF(unicode_obj);
return -1;
}
Py_DECREF(unicode_obj);
return 0;
}
template <bool Aligned>
static int
unicode_to_quad_strided_loop(PyArrayMethod_Context *context, char *const data[],
npy_intp const dimensions[], npy_intp const strides[],
void *NPY_UNUSED(auxdata))
{
npy_intp N = dimensions[0];
char *in_ptr = data[0];
char *out_ptr = data[1];
npy_intp in_stride = strides[0];
npy_intp out_stride = strides[1];
PyArray_Descr *const *descrs = context->descriptors;
QuadPrecDTypeObject *descr_out = (QuadPrecDTypeObject *)descrs[1];
QuadBackendType backend = descr_out->backend;
// Unicode strings are stored as UCS4 (4 bytes per character)
npy_intp unicode_size_chars = descrs[0]->elsize / 4;
while (N--) {
Py_UCS4 *ucs4_str = (Py_UCS4 *)in_ptr;
quad_value out_val;
if (unicode_to_quad_convert(ucs4_str, unicode_size_chars, backend, &out_val) < 0) {
return -1;
}
store_quad<Aligned>(out_ptr, &out_val, backend);
in_ptr += in_stride;
out_ptr += out_stride;
}
return 0;
}
// QuadDType to unicode/string
static NPY_CASTING
quad_to_unicode_resolve_descriptors(PyObject *NPY_UNUSED(self), PyArray_DTypeMeta *dtypes[2],
PyArray_Descr *given_descrs[2], PyArray_Descr *loop_descrs[2],
npy_intp *view_offset)
{
npy_intp required_size_chars = QUAD_STR_WIDTH;
npy_intp required_size_bytes = required_size_chars * 4; // UCS4 = 4 bytes per char
Py_INCREF(given_descrs[0]);
loop_descrs[0] = given_descrs[0];
if (given_descrs[1] == NULL) {
// Create descriptor with required size
PyArray_Descr *unicode_descr = PyArray_DescrNewFromType(NPY_UNICODE);
if (unicode_descr == nullptr) {
Py_DECREF(loop_descrs[0]);
return (NPY_CASTING)-1;
}
unicode_descr->elsize = required_size_bytes;
loop_descrs[1] = unicode_descr;
}
else {
// Handle non-native byte order by requesting native byte order
// NumPy will handle the byte swapping automatically
if (!PyArray_ISNBO(given_descrs[1]->byteorder)) {
loop_descrs[1] = PyArray_DescrNewByteorder(given_descrs[1], NPY_NATIVE);
if (loop_descrs[1] == nullptr) {
Py_DECREF(loop_descrs[0]);
return (NPY_CASTING)-1;
}
}
else {
Py_INCREF(given_descrs[1]);
loop_descrs[1] = given_descrs[1];
}
}
*view_offset = 0;
// If target descriptor is wide enough, it's a safe cast
if (loop_descrs[1]->elsize >= required_size_bytes) {
return NPY_SAFE_CASTING;
}
return NPY_SAME_KIND_CASTING;
}
// Helper function: Convert quad to string with adaptive notation
static inline PyObject *
quad_to_string_adaptive(Sleef_quad *sleef_val, npy_intp unicode_size_chars)
{
// Try positional format first to see if it would fit
PyObject *positional_str = Dragon4_Positional_QuadDType(
sleef_val, DigitMode_Unique, CutoffMode_TotalLength, SLEEF_QUAD_DECIMAL_DIG, 0, 1,
TrimMode_LeaveOneZero, 1, 0);
if (positional_str == NULL) {
return NULL;
}
const char *pos_str = PyUnicode_AsUTF8(positional_str);
if (pos_str == NULL) {
Py_DECREF(positional_str);
return NULL;
}
// no need to scan full, only checking if its longer
npy_intp pos_len = strnlen(pos_str, unicode_size_chars + 1);
// If positional format fits, use it; otherwise use scientific notation
if (pos_len <= unicode_size_chars) {
return positional_str; // Keep the positional string
}
Py_DECREF(positional_str);
// Use scientific notation with full precision
return Dragon4_Scientific_QuadDType(sleef_val, DigitMode_Unique,
SLEEF_QUAD_DECIMAL_DIG, 0, 1,
TrimMode_LeaveOneZero, 1, 2);
}
static inline const char *
quad_to_string_adaptive_cstr(Sleef_quad *sleef_val, npy_intp unicode_size_chars)
{
// Try positional format first to see if it would fit
const char* positional_str = Dragon4_Positional_QuadDType_CStr(
sleef_val, DigitMode_Unique, CutoffMode_TotalLength, SLEEF_QUAD_DECIMAL_DIG, 0, 1,
TrimMode_LeaveOneZero, 1, 0);
if (positional_str == NULL) {
PyErr_SetString(PyExc_RuntimeError, "Float formatting failed");
return NULL;
}
// no need to scan full, only checking if its longer
npy_intp pos_len = strnlen(positional_str, unicode_size_chars + 1);
// If positional format fits, use it; otherwise use scientific notation
if (pos_len <= unicode_size_chars) {
return positional_str; // Keep the positional string
}
// Use scientific notation with full precision
const char *scientific_str = Dragon4_Scientific_QuadDType_CStr(sleef_val, DigitMode_Unique,
SLEEF_QUAD_DECIMAL_DIG, 0, 1,
TrimMode_LeaveOneZero, 1, 2);
if (scientific_str == NULL) {
PyErr_SetString(PyExc_RuntimeError, "Float formatting failed");
return NULL;
}
return scientific_str;
}
template <bool Aligned>
static int
quad_to_unicode_loop(PyArrayMethod_Context *context, char *const data[],
npy_intp const dimensions[], npy_intp const strides[],
void *NPY_UNUSED(auxdata))
{
npy_intp N = dimensions[0];
char *in_ptr = data[0];
char *out_ptr = data[1];
npy_intp in_stride = strides[0];
npy_intp out_stride = strides[1];
PyArray_Descr *const *descrs = context->descriptors;
QuadPrecDTypeObject *descr_in = (QuadPrecDTypeObject *)descrs[0];
QuadBackendType backend = descr_in->backend;
npy_intp unicode_size_chars = descrs[1]->elsize / 4;
while (N--) {
quad_value in_val;
load_quad<Aligned>(in_ptr, backend, &in_val);
// Convert to Sleef_quad for Dragon4
Sleef_quad sleef_val = quad_to_sleef_quad(&in_val, backend);
// Get string representation with adaptive notation
PyObject *py_str = quad_to_string_adaptive(&sleef_val, unicode_size_chars);
if (py_str == NULL) {
return -1;
}
const char *temp_str = PyUnicode_AsUTF8(py_str);
if (temp_str == NULL) {
Py_DECREF(py_str);
return -1;
}
// Convert char string to UCS4 and store in output
Py_UCS4 *out_ucs4 = (Py_UCS4 *)out_ptr;
npy_intp str_len = strnlen(temp_str, unicode_size_chars);
for (npy_intp i = 0; i < str_len; i++) {
out_ucs4[i] = (Py_UCS4)temp_str[i];
}
for (npy_intp i = str_len; i < unicode_size_chars; i++) {
out_ucs4[i] = 0;
}
Py_DECREF(py_str);
in_ptr += in_stride;
out_ptr += out_stride;
}
return 0;
}
// Bytes to QuadDType casting
static NPY_CASTING
bytes_to_quad_resolve_descriptors(PyObject *NPY_UNUSED(self), PyArray_DTypeMeta *dtypes[2],
PyArray_Descr *given_descrs[2], PyArray_Descr *loop_descrs[2],
npy_intp *view_offset)
{
// Bytes dtype doesn't have byte order concerns like Unicode
Py_INCREF(given_descrs[0]);
loop_descrs[0] = given_descrs[0];
if (given_descrs[1] == NULL) {
loop_descrs[1] = (PyArray_Descr *)new_quaddtype_instance(BACKEND_SLEEF);
if (loop_descrs[1] == nullptr) {
Py_DECREF(loop_descrs[0]);
return (NPY_CASTING)-1;
}
}
else {
Py_INCREF(given_descrs[1]);
loop_descrs[1] = given_descrs[1];
}
return NPY_UNSAFE_CASTING;
}
// Helper function: Convert bytes string to quad_value
static inline int
bytes_to_quad_convert(const char *bytes_str, npy_intp bytes_size,
QuadBackendType backend, quad_value *out_val)
{
// Create a null-terminated copy since bytes might not be null-terminated
char *temp_str = (char *)malloc(bytes_size + 1);
if (temp_str == NULL) {
PyErr_NoMemory();
return -1;
}
memcpy(temp_str, bytes_str, bytes_size);
// Find the actual end (null byte or first occurrence)
npy_intp actual_len = 0;
while (actual_len < bytes_size && temp_str[actual_len] != '\0') {
actual_len++;
}
temp_str[actual_len] = '\0';
char *endptr;
int err = NumPyOS_ascii_strtoq(temp_str, backend, out_val, &endptr);
if (err < 0) {
PyErr_Format(PyExc_ValueError,
"could not convert bytes to QuadPrecision: np.bytes_(%s)", temp_str);
free(temp_str);
return -1;
}
while (ascii_isspace(*endptr)) {
endptr++;
}
if (*endptr != '\0') {
PyErr_Format(PyExc_ValueError,
"could not convert bytes to QuadPrecision: np.bytes_(%s)", temp_str);
free(temp_str);
return -1;
}
free(temp_str);
return 0;
}
template <bool Aligned>
static int
bytes_to_quad_strided_loop(PyArrayMethod_Context *context, char *const data[],
npy_intp const dimensions[], npy_intp const strides[],
void *NPY_UNUSED(auxdata))
{
npy_intp N = dimensions[0];
char *in_ptr = data[0];
char *out_ptr = data[1];
npy_intp in_stride = strides[0];
npy_intp out_stride = strides[1];
PyArray_Descr *const *descrs = context->descriptors;
QuadPrecDTypeObject *descr_out = (QuadPrecDTypeObject *)descrs[1];
QuadBackendType backend = descr_out->backend;
npy_intp bytes_size = descrs[0]->elsize;
while (N--) {
quad_value out_val;
if (bytes_to_quad_convert(in_ptr, bytes_size, backend, &out_val) < 0) {
return -1;
}
store_quad<Aligned>(out_ptr, &out_val, backend);
in_ptr += in_stride;
out_ptr += out_stride;
}
return 0;
}
// QuadDType to bytes
static NPY_CASTING
quad_to_bytes_resolve_descriptors(PyObject *NPY_UNUSED(self), PyArray_DTypeMeta *dtypes[2],
PyArray_Descr *given_descrs[2], PyArray_Descr *loop_descrs[2],
npy_intp *view_offset)
{
npy_intp required_size_bytes = QUAD_STR_WIDTH;
if (given_descrs[1] == NULL) {
PyArray_Descr *new_descr = PyArray_DescrNewFromType(NPY_STRING);
if (new_descr == NULL) {
return (NPY_CASTING)-1;
}
new_descr->elsize = required_size_bytes;
loop_descrs[1] = new_descr;
}
else {
Py_INCREF(given_descrs[1]);
loop_descrs[1] = given_descrs[1];
}
Py_INCREF(given_descrs[0]);
loop_descrs[0] = given_descrs[0];
*view_offset = 0;
// If target descriptor is wide enough, it's a safe cast
if (loop_descrs[1]->elsize >= required_size_bytes) {
return NPY_SAFE_CASTING;
}
return NPY_SAME_KIND_CASTING;
}
template <bool Aligned>
static int
quad_to_bytes_loop(PyArrayMethod_Context *context, char *const data[],
npy_intp const dimensions[], npy_intp const strides[],
void *NPY_UNUSED(auxdata))
{
npy_intp N = dimensions[0];
char *in_ptr = data[0];
char *out_ptr = data[1];
npy_intp in_stride = strides[0];
npy_intp out_stride = strides[1];
PyArray_Descr *const *descrs = context->descriptors;
QuadPrecDTypeObject *descr_in = (QuadPrecDTypeObject *)descrs[0];
QuadBackendType backend = descr_in->backend;
npy_intp bytes_size = descrs[1]->elsize;
while (N--) {
quad_value in_val;
load_quad<Aligned>(in_ptr, backend, &in_val);
Sleef_quad sleef_val = quad_to_sleef_quad(&in_val, backend);
PyObject *py_str = quad_to_string_adaptive(&sleef_val, bytes_size);
if (py_str == NULL) {
return -1;
}
const char *temp_str = PyUnicode_AsUTF8(py_str);
if (temp_str == NULL) {
Py_DECREF(py_str);
return -1;
}
// Copy string to output buffer, padding with nulls
strncpy(out_ptr, temp_str, bytes_size);
Py_DECREF(py_str);
in_ptr += in_stride;
out_ptr += out_stride;
}
return 0;
}
// StringDType to QuadDType casting
static NPY_CASTING
stringdtype_to_quad_resolve_descriptors(PyObject *NPY_UNUSED(self), PyArray_DTypeMeta *dtypes[2],
PyArray_Descr *given_descrs[2], PyArray_Descr *loop_descrs[2],
npy_intp *view_offset)
{
if (given_descrs[1] == NULL) {
loop_descrs[1] = (PyArray_Descr *)new_quaddtype_instance(BACKEND_SLEEF);
if (loop_descrs[1] == nullptr) {
return (NPY_CASTING)-1;
}
}
else {
Py_INCREF(given_descrs[1]);
loop_descrs[1] = given_descrs[1];
}
Py_INCREF(given_descrs[0]);
loop_descrs[0] = given_descrs[0];
return NPY_UNSAFE_CASTING;
}
// Note: StringDType elements are always aligned, so Aligned template parameter
// is kept for API consistency but both versions use the same logic
template <bool Aligned>
static int
stringdtype_to_quad_strided_loop(PyArrayMethod_Context *context, char *const data[],
npy_intp const dimensions[], npy_intp const strides[],
void *NPY_UNUSED(auxdata))
{
npy_intp N = dimensions[0];
char *in_ptr = data[0];
char *out_ptr = data[1];
npy_intp in_stride = strides[0];
npy_intp out_stride = strides[1];
PyArray_Descr *const *descrs = context->descriptors;
PyArray_StringDTypeObject *str_descr = (PyArray_StringDTypeObject *)descrs[0];
QuadPrecDTypeObject *descr_out = (QuadPrecDTypeObject *)descrs[1];
QuadBackendType backend = descr_out->backend;
npy_string_allocator *allocator = NpyString_acquire_allocator(str_descr);
while (N--) {
const npy_packed_static_string *ps = (npy_packed_static_string *)in_ptr;
npy_static_string s = {0, NULL};
int is_null = NpyString_load(allocator, ps, &s);
if (is_null == -1) {
NpyString_release_allocator(allocator);
PyErr_SetString(PyExc_MemoryError, "Failed to load string in StringDType to Quad cast");
return -1;
}
else if (is_null) {
// Handle null string - use the default string if available, otherwise error
if (str_descr->has_string_na || str_descr->default_string.buf != NULL) {
s = str_descr->default_string;
}
else {
NpyString_release_allocator(allocator);
PyErr_SetString(PyExc_ValueError, "Cannot convert null string to QuadPrecision");
return -1;
}
}
quad_value out_val;
if (bytes_to_quad_convert(s.buf, s.size, backend, &out_val) < 0) {
NpyString_release_allocator(allocator);
return -1;
}
store_quad<Aligned>(out_ptr, &out_val, backend);
in_ptr += in_stride;
out_ptr += out_stride;
}
NpyString_release_allocator(allocator);
return 0;
}
// QuadDType to StringDType casting
static NPY_CASTING
quad_to_stringdtype_resolve_descriptors(PyObject *NPY_UNUSED(self), PyArray_DTypeMeta *dtypes[2],
PyArray_Descr *given_descrs[2], PyArray_Descr *loop_descrs[2],
npy_intp *view_offset)
{
if (given_descrs[1] == NULL) {
// Default StringDType() already has coerce=True
loop_descrs[1] = (PyArray_Descr *)PyObject_CallNoArgs(
(PyObject *)&PyArray_StringDType);
if (loop_descrs[1] == NULL) {
return (NPY_CASTING)-1;
}
}
else {
Py_INCREF(given_descrs[1]);
loop_descrs[1] = given_descrs[1];
}
Py_INCREF(given_descrs[0]);
loop_descrs[0] = given_descrs[0];
return NPY_SAFE_CASTING;
}
// Note: StringDType elements are always aligned, so Aligned template parameter
// is kept for API consistency but both versions use the same logic
template <bool Aligned>
static int
quad_to_stringdtype_strided_loop(PyArrayMethod_Context *context, char *const data[],
npy_intp const dimensions[], npy_intp const strides[],
void *NPY_UNUSED(auxdata))
{
npy_intp N = dimensions[0];
char *in_ptr = data[0];
char *out_ptr = data[1];
npy_intp in_stride = strides[0];
npy_intp out_stride = strides[1];
PyArray_Descr *const *descrs = context->descriptors;
QuadPrecDTypeObject *descr_in = (QuadPrecDTypeObject *)descrs[0];
PyArray_StringDTypeObject *str_descr = (PyArray_StringDTypeObject *)descrs[1];
QuadBackendType backend = descr_in->backend;
npy_string_allocator *allocator = NpyString_acquire_allocator(str_descr);
while (N--) {
quad_value in_val;
load_quad<Aligned>(in_ptr, backend, &in_val);
Sleef_quad sleef_val = quad_to_sleef_quad(&in_val, backend);
// Get string representation with adaptive notation
// Use a large buffer size to allow for full precision
const char *str_buf = quad_to_string_adaptive_cstr(&sleef_val, QUAD_STR_WIDTH);
if (str_buf == NULL) {
NpyString_release_allocator(allocator);
return -1;
}
Py_ssize_t str_size = strnlen(str_buf, QUAD_STR_WIDTH);
npy_packed_static_string *out_ps = (npy_packed_static_string *)out_ptr;
if (NpyString_pack(allocator, out_ps, str_buf, (size_t)str_size) < 0) {
NpyString_release_allocator(allocator);
PyErr_SetString(PyExc_MemoryError, "Failed to pack string in Quad to StringDType cast");
return -1;
}
in_ptr += in_stride;
out_ptr += out_stride;
}
NpyString_release_allocator(allocator);
return 0;
}
// Tag dispatching to ensure npy_bool/npy_ubyte and npy_half/npy_ushort do not alias in templates
// see e.g. https://stackoverflow.com/q/32522279
struct spec_npy_bool {};
struct spec_npy_half {};
template <typename T>
struct NpyType {
typedef T TYPE;
};
template <>
struct NpyType<spec_npy_bool> {
typedef npy_bool TYPE;
};
template <>
struct NpyType<spec_npy_half> {
typedef npy_half TYPE;
};
// Casting from other types to QuadDType
template <typename T>
static inline quad_value
to_quad(typename NpyType<T>::TYPE x, QuadBackendType backend);
template <>
inline quad_value
to_quad<spec_npy_bool>(npy_bool x, QuadBackendType backend)
{
quad_value result;
if (backend == BACKEND_SLEEF) {
result.sleef_value = x ? Sleef_cast_from_doubleq1(1.0) : Sleef_cast_from_doubleq1(0.0);
}
else {
result.longdouble_value = x ? 1.0L : 0.0L;
}
return result;
}
template <>
inline quad_value
to_quad<npy_byte>(npy_byte x, QuadBackendType backend)
{
quad_value result;
if (backend == BACKEND_SLEEF) {
result.sleef_value = Sleef_cast_from_int64q1(x);
}
else {
result.longdouble_value = (long double)x;
}
return result;
}
template <>
inline quad_value
to_quad<npy_ubyte>(npy_ubyte x, QuadBackendType backend)
{
quad_value result;
if (backend == BACKEND_SLEEF) {
result.sleef_value = Sleef_cast_from_uint64q1(x);
}
else {
result.longdouble_value = (long double)x;
}
return result;
}
template <>
inline quad_value
to_quad<npy_short>(npy_short x, QuadBackendType backend)
{
quad_value result;
if (backend == BACKEND_SLEEF) {
result.sleef_value = Sleef_cast_from_int64q1(x);
}
else {
result.longdouble_value = (long double)x;
}
return result;
}
template <>
inline quad_value
to_quad<npy_ushort>(npy_ushort x, QuadBackendType backend)
{
quad_value result;
if (backend == BACKEND_SLEEF) {
result.sleef_value = Sleef_cast_from_uint64q1(x);
}
else {
result.longdouble_value = (long double)x;
}
return result;
}
template <>
inline quad_value
to_quad<npy_int>(npy_int x, QuadBackendType backend)
{
quad_value result;
if (backend == BACKEND_SLEEF) {
result.sleef_value = Sleef_cast_from_int64q1(x);
}
else {
result.longdouble_value = (long double)x;
}
return result;
}
template <>
inline quad_value
to_quad<npy_uint>(npy_uint x, QuadBackendType backend)
{
quad_value result;
if (backend == BACKEND_SLEEF) {
result.sleef_value = Sleef_cast_from_uint64q1(x);
}
else {
result.longdouble_value = (long double)x;
}
return result;
}
template <>
inline quad_value
to_quad<npy_long>(npy_long x, QuadBackendType backend)
{
quad_value result;
if (backend == BACKEND_SLEEF) {
result.sleef_value = Sleef_cast_from_int64q1(x);
}
else {
result.longdouble_value = (long double)x;
}
return result;
}
template <>
inline quad_value
to_quad<npy_ulong>(npy_ulong x, QuadBackendType backend)
{
quad_value result;
if (backend == BACKEND_SLEEF) {
result.sleef_value = Sleef_cast_from_uint64q1(x);
}
else {
result.longdouble_value = (long double)x;
}
return result;
}
template <>
inline quad_value
to_quad<npy_longlong>(npy_longlong x, QuadBackendType backend)
{
quad_value result;
if (backend == BACKEND_SLEEF) {
result.sleef_value = Sleef_cast_from_int64q1(x);
}
else {
result.longdouble_value = (long double)x;
}
return result;
}
template <>
inline quad_value
to_quad<npy_ulonglong>(npy_ulonglong x, QuadBackendType backend)
{
quad_value result;
if (backend == BACKEND_SLEEF) {
result.sleef_value = Sleef_cast_from_uint64q1(x);
}
else {
result.longdouble_value = (long double)x;
}
return result;
}
template <>
inline quad_value
to_quad<spec_npy_half>(npy_half x, QuadBackendType backend)
{
quad_value result;
double d = npy_half_to_double(x);
if (backend == BACKEND_SLEEF) {
if (std::isnan(d)) {
result.sleef_value = std::signbit(d) ? QUAD_PRECISION_NEG_NAN : QUAD_PRECISION_NAN;
}
else if (std::isinf(d)) {
result.sleef_value = (d > 0) ? QUAD_PRECISION_INF : QUAD_PRECISION_NINF;
}
else {
Sleef_quad temp = Sleef_cast_from_doubleq1(d);
std::memcpy(&result.sleef_value, &temp, sizeof(Sleef_quad));
}
}
else {
result.longdouble_value = (long double)d;
}
return result;
}
template <>
inline quad_value
to_quad<float>(float x, QuadBackendType backend)
{
quad_value result;
if (backend == BACKEND_SLEEF)
{
if (std::isnan(x)) {
result.sleef_value = std::signbit(x) ? QUAD_PRECISION_NEG_NAN : QUAD_PRECISION_NAN;
}
else if (std::isinf(x)) {
result.sleef_value = (x > 0) ? QUAD_PRECISION_INF : QUAD_PRECISION_NINF;
}
else {
Sleef_quad temp = Sleef_cast_from_doubleq1(static_cast<double>(x));
std::memcpy(&result.sleef_value, &temp, sizeof(Sleef_quad));
}
}
else {
result.longdouble_value = (long double)x;
}
return result;
}
template <>
inline quad_value
to_quad<double>(double x, QuadBackendType backend)
{
quad_value result;