]> sigrok.org Git - libsigrok.git/blame - src/analog.c
scpi-dmm: add support to get/set range on Agilent protocol using meters
[libsigrok.git] / src / analog.c
CommitLineData
fb019a0e
BV
1/*
2 * This file is part of the libsigrok project.
3 *
4 * Copyright (C) 2014 Bert Vermeulen <bert@biot.com>
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
6ec6c43b 20#include <config.h>
c2a25ebb
BV
21#include <stdio.h>
22#include <stdint.h>
fb019a0e 23#include <string.h>
c2a25ebb 24#include <ctype.h>
962172e4 25#include <math.h>
c1aae900 26#include <libsigrok/libsigrok.h>
fb019a0e
BV
27#include "libsigrok-internal.h"
28
e00b3f58 29/** @cond PRIVATE */
fb019a0e 30#define LOG_PREFIX "analog"
e00b3f58
UH
31/** @endcond */
32
33/**
34 * @file
35 *
36 * Handling and converting analog data.
37 */
38
39/**
40 * @defgroup grp_analog Analog data handling
41 *
42 * Handling and converting analog data.
43 *
44 * @{
45 */
fb019a0e 46
a5892391
BV
47struct unit_mq_string {
48 uint64_t value;
2c240774 49 const char *str;
a5892391
BV
50};
51
ca7dbb56 52/* Please use the same order as in enum sr_unit (libsigrok.h). */
a5892391
BV
53static struct unit_mq_string unit_strings[] = {
54 { SR_UNIT_VOLT, "V" },
55 { SR_UNIT_AMPERE, "A" },
56 { SR_UNIT_OHM, "\xe2\x84\xa6" },
57 { SR_UNIT_FARAD, "F" },
a5892391
BV
58 { SR_UNIT_KELVIN, "K" },
59 { SR_UNIT_CELSIUS, "\xc2\xb0""C" },
60 { SR_UNIT_FAHRENHEIT, "\xc2\xb0""F" },
61 { SR_UNIT_HERTZ, "Hz" },
62 { SR_UNIT_PERCENTAGE, "%" },
f7bcc686 63 { SR_UNIT_BOOLEAN, "" },
a5892391
BV
64 { SR_UNIT_SECOND, "s" },
65 { SR_UNIT_SIEMENS, "S" },
cdc31195
AJ
66 { SR_UNIT_DECIBEL_MW, "dBm" },
67 { SR_UNIT_DECIBEL_VOLT, "dBV" },
f7bcc686 68 { SR_UNIT_UNITLESS, "" },
a5892391
BV
69 { SR_UNIT_DECIBEL_SPL, "dB" },
70 { SR_UNIT_CONCENTRATION, "ppm" },
71 { SR_UNIT_REVOLUTIONS_PER_MINUTE, "RPM" },
72 { SR_UNIT_VOLT_AMPERE, "VA" },
73 { SR_UNIT_WATT, "W" },
74 { SR_UNIT_WATT_HOUR, "Wh" },
75 { SR_UNIT_METER_SECOND, "m/s" },
76 { SR_UNIT_HECTOPASCAL, "hPa" },
77 { SR_UNIT_HUMIDITY_293K, "%rF" },
78 { SR_UNIT_DEGREE, "\xc2\xb0" },
f7bcc686
UH
79 { SR_UNIT_HENRY, "H" },
80 { SR_UNIT_GRAM, "g" },
81 { SR_UNIT_CARAT, "ct" },
82 { SR_UNIT_OUNCE, "oz" },
83 { SR_UNIT_TROY_OUNCE, "oz t" },
84 { SR_UNIT_POUND, "lb" },
85 { SR_UNIT_PENNYWEIGHT, "dwt" },
86 { SR_UNIT_GRAIN, "gr" },
87 { SR_UNIT_TAEL, "tael" },
88 { SR_UNIT_MOMME, "momme" },
89 { SR_UNIT_TOLA, "tola" },
90 { SR_UNIT_PIECE, "pcs" },
fe8c5aef
FS
91 { SR_UNIT_JOULE, "J" },
92 { SR_UNIT_COULOMB, "C" },
93 { SR_UNIT_AMPERE_HOUR, "Ah" },
a5892391
BV
94 ALL_ZERO
95};
96
ca7dbb56 97/* Please use the same order as in enum sr_mqflag (libsigrok.h). */
a5892391 98static struct unit_mq_string mq_strings[] = {
a5892391
BV
99 { SR_MQFLAG_AC, " AC" },
100 { SR_MQFLAG_DC, " DC" },
101 { SR_MQFLAG_RMS, " RMS" },
102 { SR_MQFLAG_DIODE, " DIODE" },
103 { SR_MQFLAG_HOLD, " HOLD" },
104 { SR_MQFLAG_MAX, " MAX" },
105 { SR_MQFLAG_MIN, " MIN" },
106 { SR_MQFLAG_AUTORANGE, " AUTO" },
107 { SR_MQFLAG_RELATIVE, " REL" },
f7bcc686
UH
108 { SR_MQFLAG_SPL_FREQ_WEIGHT_A, "(A)" },
109 { SR_MQFLAG_SPL_FREQ_WEIGHT_C, "(C)" },
110 { SR_MQFLAG_SPL_FREQ_WEIGHT_Z, "(Z)" },
111 { SR_MQFLAG_SPL_FREQ_WEIGHT_FLAT, "(SPL)" },
112 { SR_MQFLAG_SPL_TIME_WEIGHT_S, " S" },
113 { SR_MQFLAG_SPL_TIME_WEIGHT_F, " F" },
114 { SR_MQFLAG_SPL_LAT, " LAT" },
115 /* Not a standard function for SLMs, so this is a made-up notation. */
116 { SR_MQFLAG_SPL_PCT_OVER_ALARM, "%oA" },
117 { SR_MQFLAG_DURATION, " DURATION" },
a5892391
BV
118 { SR_MQFLAG_AVG, " AVG" },
119 { SR_MQFLAG_REFERENCE, " REF" },
f7bcc686 120 { SR_MQFLAG_UNSTABLE, " UNSTABLE" },
6d5cd3bd 121 { SR_MQFLAG_FOUR_WIRE, " 4-WIRE" },
a5892391
BV
122 ALL_ZERO
123};
124
f200d59e 125/** @private */
edb691fc 126SR_PRIV int sr_analog_init(struct sr_datafeed_analog *analog,
41caa319
AJ
127 struct sr_analog_encoding *encoding,
128 struct sr_analog_meaning *meaning,
129 struct sr_analog_spec *spec,
130 int digits)
131{
132 memset(analog, 0, sizeof(*analog));
133 memset(encoding, 0, sizeof(*encoding));
134 memset(meaning, 0, sizeof(*meaning));
135 memset(spec, 0, sizeof(*spec));
136
137 analog->encoding = encoding;
138 analog->meaning = meaning;
139 analog->spec = spec;
140
141 encoding->unitsize = sizeof(float);
142 encoding->is_float = TRUE;
143#ifdef WORDS_BIGENDIAN
144 encoding->is_bigendian = TRUE;
145#else
146 encoding->is_bigendian = FALSE;
147#endif
148 encoding->digits = digits;
149 encoding->is_digits_decimal = TRUE;
150 encoding->scale.p = 1;
151 encoding->scale.q = 1;
152 encoding->offset.p = 0;
153 encoding->offset.q = 1;
154
155 spec->spec_digits = digits;
156
157 return SR_OK;
158}
159
22fb1bff
UH
160/**
161 * Convert an analog datafeed payload to an array of floats.
162 *
e62b284c
GS
163 * The caller must provide the #outbuf space for the conversion result,
164 * and is expected to free allocated space after use.
8dc423b0 165 *
22fb1bff
UH
166 * @param[in] analog The analog payload to convert. Must not be NULL.
167 * analog->data, analog->meaning, and analog->encoding
168 * must not be NULL.
169 * @param[out] outbuf Memory where to store the result. Must not be NULL.
170 *
22fb1bff
UH
171 * @retval SR_OK Success.
172 * @retval SR_ERR Unsupported encoding.
173 * @retval SR_ERR_ARG Invalid argument.
174 *
175 * @since 0.4.0
176 */
edb691fc 177SR_API int sr_analog_to_float(const struct sr_datafeed_analog *analog,
4b4fdeea 178 float *outbuf)
fb019a0e 179{
e62b284c
GS
180 size_t count;
181 gboolean host_bigendian;
182 gboolean input_float, input_signed, input_bigendian;
183 size_t input_unitsize;
184 double scale, offset, value;
185 const uint8_t *data8;
186 gboolean input_is_native;
187 char type_text[10];
5cee3d08 188
e62b284c
GS
189 if (!analog || !analog->data || !analog->meaning || !analog->encoding)
190 return SR_ERR_ARG;
191 if (!outbuf)
5cee3d08
UH
192 return SR_ERR_ARG;
193
194 count = analog->num_samples * g_slist_length(analog->meaning->channels);
fb019a0e 195
e62b284c
GS
196 /*
197 * Determine properties of the input data's and the host's
198 * native formats, to simplify test conditions below.
199 * Error messages for unsupported input property combinations
200 * will only be seen by developers and maintainers of input
201 * formats or acquisition device drivers. Terse output is
202 * acceptable there, users shall never see them.
203 */
fb019a0e 204#ifdef WORDS_BIGENDIAN
e62b284c 205 host_bigendian = TRUE;
fb019a0e 206#else
e62b284c 207 host_bigendian = FALSE;
fb019a0e 208#endif
e62b284c
GS
209 input_float = analog->encoding->is_float;
210 input_signed = analog->encoding->is_signed;
211 input_bigendian = analog->encoding->is_bigendian;
212 input_unitsize = analog->encoding->unitsize;
8dc423b0 213
e62b284c
GS
214 /*
215 * Prepare the iteration over the sample data: Get the common
216 * scale/offset factors which apply to all individual values.
217 * Position the read pointer on the first byte of input data.
218 */
219 offset = analog->encoding->offset.p;
220 offset /= analog->encoding->offset.q;
221 scale = analog->encoding->scale.p;
222 scale /= analog->encoding->scale.q;
223 data8 = analog->data;
4d376e08 224
e62b284c
GS
225 /*
226 * Immediately handle the special case where input data needs
227 * no conversion because it already is in the application's
228 * native format. Do apply scale/offset though when applicable
229 * on our way out.
230 */
231 input_is_native = input_float &&
232 input_unitsize == sizeof(outbuf[0]) &&
233 input_bigendian == host_bigendian;
234 if (input_is_native) {
235 memcpy(outbuf, data8, count * sizeof(outbuf[0]));
236 if (scale != 1.0 || offset != 0.0) {
237 while (count--) {
238 *outbuf *= scale;
239 *outbuf += offset;
240 outbuf++;
4d376e08 241 }
4d376e08
SB
242 }
243 return SR_OK;
fb019a0e
BV
244 }
245
e62b284c
GS
246 /*
247 * Accept sample values in different widths and data types and
248 * endianess formats (floating point or signed or unsigned
249 * integer, in either endianess, for a set of supported widths).
250 * Common scale/offset factors apply to all sample values.
251 *
252 * Do most internal calculations on double precision values.
253 * Only trim the result data to single precision, since that's
254 * the routine's result data type in its public API which needs
255 * to be kept for compatibility. It remains an option for later
256 * to add another public routine which returns double precision
257 * result data, call sites could migrate at their own pace.
258 */
259 if (input_float && input_unitsize == sizeof(float)) {
260 float (*reader)(const uint8_t **p);
261 if (input_bigendian)
262 reader = read_fltbe_inc;
263 else
264 reader = read_fltle_inc;
265 while (count--) {
266 value = reader(&data8);
267 value *= scale;
268 value += offset;
269 *outbuf++ = value;
270 }
271 return SR_OK;
272 }
273 if (input_float && input_unitsize == sizeof(double)) {
274 double (*reader)(const uint8_t **p);
275 if (input_bigendian)
276 reader = read_dblbe_inc;
277 else
278 reader = read_dblle_inc;
279 while (count--) {
280 value = reader(&data8);
281 value *= scale;
282 value += offset;
283 *outbuf++ = value;
fb019a0e 284 }
e62b284c
GS
285 return SR_OK;
286 }
287 if (input_float) {
288 snprintf(type_text, sizeof(type_text), "%c%zu%s",
289 'f', input_unitsize * 8, input_bigendian ? "be" : "le");
290 sr_err("Unsupported type for analog-to-float conversion: %s.",
291 type_text);
292 return SR_ERR;
fb019a0e
BV
293 }
294
e62b284c
GS
295 if (input_unitsize == sizeof(uint8_t) && input_signed) {
296 int8_t (*reader)(const uint8_t **p);
297 reader = read_i8_inc;
298 while (count--) {
299 value = reader(&data8);
300 value *= scale;
301 value += offset;
302 *outbuf++ = value;
303 }
304 return SR_OK;
305 }
306 if (input_unitsize == sizeof(uint8_t)) {
307 uint8_t (*reader)(const uint8_t **p);
308 reader = read_u8_inc;
309 while (count--) {
310 value = reader(&data8);
311 value *= scale;
312 value += offset;
313 *outbuf++ = value;
314 }
315 return SR_OK;
316 }
317 if (input_unitsize == sizeof(uint16_t) && input_signed) {
318 int16_t (*reader)(const uint8_t **p);
319 if (input_bigendian)
320 reader = read_i16be_inc;
321 else
322 reader = read_i16le_inc;
323 while (count--) {
324 value = reader(&data8);
325 value *= scale;
326 value += offset;
327 *outbuf++ = value;
328 }
329 return SR_OK;
330 }
331 if (input_unitsize == sizeof(uint16_t)) {
332 uint16_t (*reader)(const uint8_t **p);
333 if (input_bigendian)
334 reader = read_u16be_inc;
335 else
336 reader = read_u16le_inc;
337 while (count--) {
338 value = reader(&data8);
339 value *= scale;
340 value += offset;
341 *outbuf++ = value;
342 }
343 return SR_OK;
344 }
345 if (input_unitsize == sizeof(uint32_t) && input_signed) {
346 int32_t (*reader)(const uint8_t **p);
347 if (input_bigendian)
348 reader = read_i32be_inc;
349 else
350 reader = read_i32le_inc;
351 while (count--) {
352 value = reader(&data8);
353 value *= scale;
354 value += offset;
355 *outbuf++ = value;
356 }
357 return SR_OK;
358 }
359 if (input_unitsize == sizeof(uint32_t)) {
360 uint32_t (*reader)(const uint8_t **p);
361 if (input_bigendian)
362 reader = read_u32be_inc;
363 else
364 reader = read_u32le_inc;
365 while (count--) {
366 value = reader(&data8);
367 value *= scale;
368 value += offset;
369 *outbuf++ = value;
370 }
371 return SR_OK;
372 }
373 snprintf(type_text, sizeof(type_text), "%c%zu%s",
374 input_float ? 'f' : input_signed ? 'i' : 'u',
375 input_unitsize * 8, input_bigendian ? "be" : "le");
376 sr_err("Unsupported type for analog-to-float conversion: %s.",
377 type_text);
378 return SR_ERR;
fb019a0e 379}
c2a25ebb 380
962172e4
AJ
381/**
382 * Scale a float value to the appropriate SI prefix.
383 *
384 * @param[in,out] value The float value to convert to appropriate SI prefix.
385 * @param[in,out] digits The number of significant decimal digits in value.
386 *
387 * @return The SI prefix to which value was scaled, as a printable string.
388 *
389 * @since 0.5.0
390 */
391SR_API const char *sr_analog_si_prefix(float *value, int *digits)
392{
f200d59e 393/** @cond PRIVATE */
405b9c10 394#define NEG_PREFIX_COUNT 5 /* number of prefixes below unity */
962172e4 395#define POS_PREFIX_COUNT (int)(ARRAY_SIZE(prefixes) - NEG_PREFIX_COUNT - 1)
f200d59e 396/** @endcond */
8dc423b0 397 static const char *prefixes[] = { "f", "p", "n", "µ", "m", "", "k", "M", "G", "T" };
962172e4 398
8dc423b0 399 if (!value || !digits || isnan(*value))
962172e4
AJ
400 return prefixes[NEG_PREFIX_COUNT];
401
402 float logval = log10f(fabsf(*value));
403 int prefix = (logval / 3) - (logval < 1);
404
8dc423b0
UH
405 if (prefix < -NEG_PREFIX_COUNT)
406 prefix = -NEG_PREFIX_COUNT;
407 if (3 * prefix < -*digits)
408 prefix = (-*digits + 2 * (*digits < 0)) / 3;
409 if (prefix > POS_PREFIX_COUNT)
410 prefix = POS_PREFIX_COUNT;
962172e4
AJ
411
412 *value *= powf(10, -3 * prefix);
413 *digits += 3 * prefix;
8dc423b0 414
962172e4
AJ
415 return prefixes[prefix + NEG_PREFIX_COUNT];
416}
417
5728718b
AJ
418/**
419 * Check if a unit "accepts" an SI prefix.
420 *
421 * E.g. SR_UNIT_VOLT is SI prefix friendly while SR_UNIT_DECIBEL_MW or
422 * SR_UNIT_PERCENTAGE are not.
423 *
424 * @param[in] unit The unit to check for SI prefix "friendliness".
425 *
426 * @return TRUE if the unit "accept" an SI prefix.
427 *
428 * @since 0.5.0
429 */
430SR_API gboolean sr_analog_si_prefix_friendly(enum sr_unit unit)
431{
432 static const enum sr_unit prefix_friendly_units[] = {
433 SR_UNIT_VOLT,
434 SR_UNIT_AMPERE,
435 SR_UNIT_OHM,
436 SR_UNIT_FARAD,
437 SR_UNIT_KELVIN,
438 SR_UNIT_HERTZ,
439 SR_UNIT_SECOND,
440 SR_UNIT_SIEMENS,
441 SR_UNIT_VOLT_AMPERE,
442 SR_UNIT_WATT,
443 SR_UNIT_WATT_HOUR,
444 SR_UNIT_METER_SECOND,
445 SR_UNIT_HENRY,
446 SR_UNIT_GRAM
447 };
448 unsigned int i;
449
450 for (i = 0; i < ARRAY_SIZE(prefix_friendly_units); i++)
451 if (unit == prefix_friendly_units[i])
5e5fde6e 452 return TRUE;
5728718b 453
5e5fde6e 454 return FALSE;
5728718b
AJ
455}
456
22fb1bff 457/**
a5892391
BV
458 * Convert the unit/MQ/MQ flags in the analog struct to a string.
459 *
8dc423b0
UH
460 * The string is allocated by the function and must be freed by the caller
461 * after use by calling g_free().
462 *
22fb1bff
UH
463 * @param[in] analog Struct containing the unit, MQ and MQ flags.
464 * Must not be NULL. analog->meaning must not be NULL.
465 * @param[out] result Pointer to store result. Must not be NULL.
a24da9a8 466 *
22fb1bff
UH
467 * @retval SR_OK Success.
468 * @retval SR_ERR_ARG Invalid argument.
a5892391
BV
469 *
470 * @since 0.4.0
471 */
edb691fc 472SR_API int sr_analog_unit_to_string(const struct sr_datafeed_analog *analog,
a24da9a8 473 char **result)
a5892391 474{
a24da9a8 475 int i;
5cee3d08
UH
476 GString *buf;
477
478 if (!analog || !(analog->meaning) || !result)
479 return SR_ERR_ARG;
480
481 buf = g_string_new(NULL);
a5892391 482
a5892391
BV
483 for (i = 0; unit_strings[i].value; i++) {
484 if (analog->meaning->unit == unit_strings[i].value) {
a24da9a8 485 g_string_assign(buf, unit_strings[i].str);
a5892391
BV
486 break;
487 }
488 }
489
490 /* More than one MQ flag may apply. */
a24da9a8
ML
491 for (i = 0; mq_strings[i].value; i++)
492 if (analog->meaning->mqflags & mq_strings[i].value)
493 g_string_append(buf, mq_strings[i].str);
494
495 *result = buf->str;
496 g_string_free(buf, FALSE);
a5892391
BV
497
498 return SR_OK;
499}
500
22fb1bff 501/**
90cefe0c
BV
502 * Set sr_rational r to the given value.
503 *
22fb1bff
UH
504 * @param[out] r Rational number struct to set. Must not be NULL.
505 * @param[in] p Numerator.
506 * @param[in] q Denominator.
507 *
508 * @since 0.4.0
90cefe0c 509 */
53e5d3d1 510SR_API void sr_rational_set(struct sr_rational *r, int64_t p, uint64_t q)
90cefe0c 511{
5cee3d08
UH
512 if (!r)
513 return;
514
90cefe0c
BV
515 r->p = p;
516 r->q = q;
517}
518
bdba3626
SB
519#ifndef HAVE___INT128_T
520struct sr_int128_t {
521 int64_t high;
522 uint64_t low;
523};
524
525struct sr_uint128_t {
526 uint64_t high;
527 uint64_t low;
528};
529
530static void mult_int64(struct sr_int128_t *res, const int64_t a,
531 const int64_t b)
532{
533 uint64_t t1, t2, t3, t4;
534
535 t1 = (UINT32_MAX & a) * (UINT32_MAX & b);
536 t2 = (UINT32_MAX & a) * (b >> 32);
537 t3 = (a >> 32) * (UINT32_MAX & b);
538 t4 = (a >> 32) * (b >> 32);
539
540 res->low = t1 + (t2 << 32) + (t3 << 32);
541 res->high = (t1 >> 32) + (uint64_t)((uint32_t)(t2)) + (uint64_t)((uint32_t)(t3));
542 res->high >>= 32;
543 res->high += ((int64_t)t2 >> 32) + ((int64_t)t3 >> 32) + t4;
544}
545
546static void mult_uint64(struct sr_uint128_t *res, const uint64_t a,
547 const uint64_t b)
548{
549 uint64_t t1, t2, t3, t4;
550
551 // (x1 + x2) * (y1 + y2) = x1*y1 + x1*y2 + x2*y1 + x2*y2
552 t1 = (UINT32_MAX & a) * (UINT32_MAX & b);
553 t2 = (UINT32_MAX & a) * (b >> 32);
554 t3 = (a >> 32) * (UINT32_MAX & b);
555 t4 = (a >> 32) * (b >> 32);
556
557 res->low = t1 + (t2 << 32) + (t3 << 32);
558 res->high = (t1 >> 32) + (uint64_t)((uint32_t)(t2)) + (uint64_t)((uint32_t)(t3));
559 res->high >>= 32;
560 res->high += ((int64_t)t2 >> 32) + ((int64_t)t3 >> 32) + t4;
561}
562#endif
563
564/**
8dc423b0 565 * Compare two sr_rational for equality.
bdba3626 566 *
8dc423b0 567 * The values are compared for numerical equality, i.e. 2/10 == 1/5.
bdba3626 568 *
8dc423b0
UH
569 * @param[in] a First value.
570 * @param[in] b Second value.
bdba3626 571 *
8dc423b0
UH
572 * @retval 1 if both values are equal.
573 * @retval 0 Otherwise.
bdba3626
SB
574 *
575 * @since 0.5.0
576 */
577SR_API int sr_rational_eq(const struct sr_rational *a, const struct sr_rational *b)
578{
579#ifdef HAVE___INT128_T
580 __int128_t m1, m2;
581
582 /* p1/q1 = p2/q2 <=> p1*q2 = p2*q1 */
583 m1 = ((__int128_t)(b->p)) * ((__uint128_t)a->q);
584 m2 = ((__int128_t)(a->p)) * ((__uint128_t)b->q);
585
586 return (m1 == m2);
587
588#else
589 struct sr_int128_t m1, m2;
590
591 mult_int64(&m1, a->q, b->p);
592 mult_int64(&m2, a->p, b->q);
593
594 return (m1.high == m2.high) && (m1.low == m2.low);
595#endif
596}
597
ee1b6054 598/**
8dc423b0 599 * Multiply two sr_rational.
ee1b6054
SB
600 *
601 * The resulting nominator/denominator are reduced if the result would not fit
602 * otherwise. If the resulting nominator/denominator are relatively prime,
603 * this may not be possible.
604 *
8dc423b0
UH
605 * It is safe to use the same variable for result and input values.
606 *
607 * @param[in] a First value.
608 * @param[in] b Second value.
609 * @param[out] res Result.
17d5a11c 610 *
ee1b6054 611 * @retval SR_OK Success.
8dc423b0 612 * @retval SR_ERR_ARG Resulting value too large.
ee1b6054
SB
613 *
614 * @since 0.5.0
615 */
616SR_API int sr_rational_mult(struct sr_rational *res, const struct sr_rational *a,
617 const struct sr_rational *b)
618{
619#ifdef HAVE___INT128_T
620 __int128_t p;
621 __uint128_t q;
622
623 p = (__int128_t)(a->p) * (__int128_t)(b->p);
624 q = (__uint128_t)(a->q) * (__uint128_t)(b->q);
625
626 if ((p > INT64_MAX) || (p < INT64_MIN) || (q > UINT64_MAX)) {
627 while (!((p & 1) || (q & 1))) {
628 p /= 2;
629 q /= 2;
630 }
631 }
632
633 if ((p > INT64_MAX) || (p < INT64_MIN) || (q > UINT64_MAX)) {
634 // TODO: determine gcd to do further reduction
635 return SR_ERR_ARG;
636 }
637
405b9c10
UH
638 res->p = (int64_t)p;
639 res->q = (uint64_t)q;
ee1b6054
SB
640
641 return SR_OK;
642
643#else
644 struct sr_int128_t p;
645 struct sr_uint128_t q;
646
647 mult_int64(&p, a->p, b->p);
648 mult_uint64(&q, a->q, b->q);
649
650 while (!(p.low & 1) && !(q.low & 1)) {
651 p.low /= 2;
8dc423b0
UH
652 if (p.high & 1)
653 p.low |= (1ll << 63);
ee1b6054
SB
654 p.high >>= 1;
655 q.low /= 2;
8dc423b0
UH
656 if (q.high & 1)
657 q.low |= (1ll << 63);
ee1b6054
SB
658 q.high >>= 1;
659 }
660
661 if (q.high)
662 return SR_ERR_ARG;
663 if ((p.high >= 0) && (p.low > INT64_MAX))
664 return SR_ERR_ARG;
665 if (p.high < -1)
666 return SR_ERR_ARG;
667
668 res->p = (int64_t)p.low;
669 res->q = q.low;
670
671 return SR_OK;
672#endif
673}
674
17d5a11c 675/**
8dc423b0 676 * Divide rational a by rational b.
17d5a11c
SB
677 *
678 * The resulting nominator/denominator are reduced if the result would not fit
679 * otherwise. If the resulting nominator/denominator are relatively prime,
680 * this may not be possible.
681 *
8dc423b0
UH
682 * It is safe to use the same variable for result and input values.
683 *
684 * @param[in] num Numerator.
685 * @param[in] div Divisor.
686 * @param[out] res Result.
17d5a11c
SB
687 *
688 * @retval SR_OK Success.
6762401d
UH
689 * @retval SR_ERR_ARG Division by zero, denominator of divisor too large,
690 * or resulting value too large.
17d5a11c
SB
691 *
692 * @since 0.5.0
693 */
694SR_API int sr_rational_div(struct sr_rational *res, const struct sr_rational *num,
695 const struct sr_rational *div)
696{
697 struct sr_rational t;
698
699 if (div->q > INT64_MAX)
700 return SR_ERR_ARG;
701 if (div->p == 0)
702 return SR_ERR_ARG;
703
704 if (div->p > 0) {
705 t.p = div->q;
706 t.q = div->p;
707 } else {
708 t.p = -div->q;
709 t.q = -div->p;
710 }
711
712 return sr_rational_mult(res, num, &t);
713}
714
e00b3f58 715/** @} */