]> sigrok.org Git - libsigrok.git/blame - src/analog.c
libsigrok-internal.h: add more endianess aware stream reader routines
[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 *
8dc423b0
UH
163 * Sufficient memory for outbuf must have been pre-allocated by the caller,
164 * who is also responsible for freeing it when no longer needed.
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{
0519db86 180 unsigned int b, count;
fb019a0e 181 gboolean bigendian;
f37f11ec
TK
182 uint8_t conv_buf[sizeof(double)];
183 float *conv_f = (float*)conv_buf;
184 double *conv_d = (double*)conv_buf;
5cee3d08
UH
185
186 if (!analog || !(analog->data) || !(analog->meaning)
187 || !(analog->encoding) || !outbuf)
188 return SR_ERR_ARG;
189
190 count = analog->num_samples * g_slist_length(analog->meaning->channels);
fb019a0e
BV
191
192#ifdef WORDS_BIGENDIAN
193 bigendian = TRUE;
194#else
195 bigendian = FALSE;
196#endif
8dc423b0 197
fb019a0e 198 if (!analog->encoding->is_float) {
4d376e08
SB
199 float offset = analog->encoding->offset.p / (float)analog->encoding->offset.q;
200 float scale = analog->encoding->scale.p / (float)analog->encoding->scale.q;
201 gboolean is_signed = analog->encoding->is_signed;
202 gboolean is_bigendian = analog->encoding->is_bigendian;
203 int8_t *data8 = (int8_t *)(analog->data);
204 int16_t *data16 = (int16_t *)(analog->data);
205 int32_t *data32 = (int32_t *)(analog->data);
206
207 switch (analog->encoding->unitsize) {
208 case 1:
209 if (is_signed) {
210 for (unsigned int i = 0; i < count; i++) {
211 outbuf[i] = scale * data8[i];
212 outbuf[i] += offset;
213 }
214 } else {
215 for (unsigned int i = 0; i < count; i++) {
216 outbuf[i] = scale * R8(data8 + i);
217 outbuf[i] += offset;
218 }
219 }
220 break;
221 case 2:
222 if (is_signed && is_bigendian) {
223 for (unsigned int i = 0; i < count; i++) {
224 outbuf[i] = scale * RB16S(&data16[i]);
225 outbuf[i] += offset;
226 }
227 } else if (is_bigendian) {
228 for (unsigned int i = 0; i < count; i++) {
229 outbuf[i] = scale * RB16(&data16[i]);
230 outbuf[i] += offset;
231 }
232 } else if (is_signed) {
233 for (unsigned int i = 0; i < count; i++) {
234 outbuf[i] = scale * RL16S(&data16[i]);
235 outbuf[i] += offset;
236 }
237 } else {
238 for (unsigned int i = 0; i < count; i++) {
239 outbuf[i] = scale * RL16(&data16[i]);
240 outbuf[i] += offset;
241 }
242 }
243 break;
244 case 4:
245 if (is_signed && is_bigendian) {
246 for (unsigned int i = 0; i < count; i++) {
247 outbuf[i] = scale * RB32S(&data32[i]);
248 outbuf[i] += offset;
249 }
250 } else if (is_bigendian) {
251 for (unsigned int i = 0; i < count; i++) {
252 outbuf[i] = scale * RB32(&data32[i]);
253 outbuf[i] += offset;
254 }
255 } else if (is_signed) {
256 for (unsigned int i = 0; i < count; i++) {
257 outbuf[i] = scale * RL32S(&data32[i]);
258 outbuf[i] += offset;
259 }
260 } else {
261 for (unsigned int i = 0; i < count; i++) {
262 outbuf[i] = scale * RL32(&data32[i]);
263 outbuf[i] += offset;
264 }
265 }
266 break;
267 default:
8dc423b0
UH
268 sr_err("Unsupported unit size '%d' for analog-to-float"
269 " conversion.", analog->encoding->unitsize);
4d376e08
SB
270 return SR_ERR;
271 }
272 return SR_OK;
fb019a0e
BV
273 }
274
275 if (analog->encoding->unitsize == sizeof(float)
276 && analog->encoding->is_bigendian == bigendian
b07a1b04
ML
277 && analog->encoding->scale.p == 1
278 && analog->encoding->scale.q == 1
4b4fdeea 279 && analog->encoding->offset.p / (float)analog->encoding->offset.q == 0) {
fb019a0e 280 /* The data is already in the right format. */
7d65dd3a 281 memcpy(outbuf, analog->data, count * sizeof(float));
fb019a0e 282 } else {
f37f11ec 283 for (unsigned int i = 0; i < count; i++) {
fb019a0e
BV
284 for (b = 0; b < analog->encoding->unitsize; b++) {
285 if (analog->encoding->is_bigendian == bigendian)
f37f11ec 286 conv_buf[b] =
3e277549 287 ((uint8_t *)analog->data)[i * analog->encoding->unitsize + b];
fb019a0e 288 else
f37f11ec 289 conv_buf[analog->encoding->unitsize - b - 1] =
3e277549 290 ((uint8_t *)analog->data)[i * analog->encoding->unitsize + b];
fb019a0e 291 }
f37f11ec
TK
292
293 if (analog->encoding->unitsize == sizeof(float)) {
294 if (analog->encoding->scale.p != 1
295 || analog->encoding->scale.q != 1)
296 *conv_f = (*conv_f * analog->encoding->scale.p) / analog->encoding->scale.q;
297 float offset = ((float)analog->encoding->offset.p / (float)analog->encoding->offset.q);
298 *conv_f += offset;
299
300 outbuf[i] = *conv_f;
301 }
302 else if (analog->encoding->unitsize == sizeof(double)) {
303 if (analog->encoding->scale.p != 1
304 || analog->encoding->scale.q != 1)
305 *conv_d = (*conv_d * analog->encoding->scale.p) / analog->encoding->scale.q;
306 double offset = ((double)analog->encoding->offset.p / (double)analog->encoding->offset.q);
307 *conv_d += offset;
308
309 outbuf[i] = *conv_d;
310 }
311 else {
312 sr_err("Unsupported floating-point unit size '%d' for analog-to-float"
313 " conversion.", analog->encoding->unitsize);
314 return SR_ERR;
315 }
fb019a0e
BV
316 }
317 }
318
319 return SR_OK;
320}
c2a25ebb 321
962172e4
AJ
322/**
323 * Scale a float value to the appropriate SI prefix.
324 *
325 * @param[in,out] value The float value to convert to appropriate SI prefix.
326 * @param[in,out] digits The number of significant decimal digits in value.
327 *
328 * @return The SI prefix to which value was scaled, as a printable string.
329 *
330 * @since 0.5.0
331 */
332SR_API const char *sr_analog_si_prefix(float *value, int *digits)
333{
f200d59e 334/** @cond PRIVATE */
405b9c10 335#define NEG_PREFIX_COUNT 5 /* number of prefixes below unity */
962172e4 336#define POS_PREFIX_COUNT (int)(ARRAY_SIZE(prefixes) - NEG_PREFIX_COUNT - 1)
f200d59e 337/** @endcond */
8dc423b0 338 static const char *prefixes[] = { "f", "p", "n", "µ", "m", "", "k", "M", "G", "T" };
962172e4 339
8dc423b0 340 if (!value || !digits || isnan(*value))
962172e4
AJ
341 return prefixes[NEG_PREFIX_COUNT];
342
343 float logval = log10f(fabsf(*value));
344 int prefix = (logval / 3) - (logval < 1);
345
8dc423b0
UH
346 if (prefix < -NEG_PREFIX_COUNT)
347 prefix = -NEG_PREFIX_COUNT;
348 if (3 * prefix < -*digits)
349 prefix = (-*digits + 2 * (*digits < 0)) / 3;
350 if (prefix > POS_PREFIX_COUNT)
351 prefix = POS_PREFIX_COUNT;
962172e4
AJ
352
353 *value *= powf(10, -3 * prefix);
354 *digits += 3 * prefix;
8dc423b0 355
962172e4
AJ
356 return prefixes[prefix + NEG_PREFIX_COUNT];
357}
358
5728718b
AJ
359/**
360 * Check if a unit "accepts" an SI prefix.
361 *
362 * E.g. SR_UNIT_VOLT is SI prefix friendly while SR_UNIT_DECIBEL_MW or
363 * SR_UNIT_PERCENTAGE are not.
364 *
365 * @param[in] unit The unit to check for SI prefix "friendliness".
366 *
367 * @return TRUE if the unit "accept" an SI prefix.
368 *
369 * @since 0.5.0
370 */
371SR_API gboolean sr_analog_si_prefix_friendly(enum sr_unit unit)
372{
373 static const enum sr_unit prefix_friendly_units[] = {
374 SR_UNIT_VOLT,
375 SR_UNIT_AMPERE,
376 SR_UNIT_OHM,
377 SR_UNIT_FARAD,
378 SR_UNIT_KELVIN,
379 SR_UNIT_HERTZ,
380 SR_UNIT_SECOND,
381 SR_UNIT_SIEMENS,
382 SR_UNIT_VOLT_AMPERE,
383 SR_UNIT_WATT,
384 SR_UNIT_WATT_HOUR,
385 SR_UNIT_METER_SECOND,
386 SR_UNIT_HENRY,
387 SR_UNIT_GRAM
388 };
389 unsigned int i;
390
391 for (i = 0; i < ARRAY_SIZE(prefix_friendly_units); i++)
392 if (unit == prefix_friendly_units[i])
5e5fde6e 393 return TRUE;
5728718b 394
5e5fde6e 395 return FALSE;
5728718b
AJ
396}
397
22fb1bff 398/**
a5892391
BV
399 * Convert the unit/MQ/MQ flags in the analog struct to a string.
400 *
8dc423b0
UH
401 * The string is allocated by the function and must be freed by the caller
402 * after use by calling g_free().
403 *
22fb1bff
UH
404 * @param[in] analog Struct containing the unit, MQ and MQ flags.
405 * Must not be NULL. analog->meaning must not be NULL.
406 * @param[out] result Pointer to store result. Must not be NULL.
a24da9a8 407 *
22fb1bff
UH
408 * @retval SR_OK Success.
409 * @retval SR_ERR_ARG Invalid argument.
a5892391
BV
410 *
411 * @since 0.4.0
412 */
edb691fc 413SR_API int sr_analog_unit_to_string(const struct sr_datafeed_analog *analog,
a24da9a8 414 char **result)
a5892391 415{
a24da9a8 416 int i;
5cee3d08
UH
417 GString *buf;
418
419 if (!analog || !(analog->meaning) || !result)
420 return SR_ERR_ARG;
421
422 buf = g_string_new(NULL);
a5892391 423
a5892391
BV
424 for (i = 0; unit_strings[i].value; i++) {
425 if (analog->meaning->unit == unit_strings[i].value) {
a24da9a8 426 g_string_assign(buf, unit_strings[i].str);
a5892391
BV
427 break;
428 }
429 }
430
431 /* More than one MQ flag may apply. */
a24da9a8
ML
432 for (i = 0; mq_strings[i].value; i++)
433 if (analog->meaning->mqflags & mq_strings[i].value)
434 g_string_append(buf, mq_strings[i].str);
435
436 *result = buf->str;
437 g_string_free(buf, FALSE);
a5892391
BV
438
439 return SR_OK;
440}
441
22fb1bff 442/**
90cefe0c
BV
443 * Set sr_rational r to the given value.
444 *
22fb1bff
UH
445 * @param[out] r Rational number struct to set. Must not be NULL.
446 * @param[in] p Numerator.
447 * @param[in] q Denominator.
448 *
449 * @since 0.4.0
90cefe0c 450 */
53e5d3d1 451SR_API void sr_rational_set(struct sr_rational *r, int64_t p, uint64_t q)
90cefe0c 452{
5cee3d08
UH
453 if (!r)
454 return;
455
90cefe0c
BV
456 r->p = p;
457 r->q = q;
458}
459
bdba3626
SB
460#ifndef HAVE___INT128_T
461struct sr_int128_t {
462 int64_t high;
463 uint64_t low;
464};
465
466struct sr_uint128_t {
467 uint64_t high;
468 uint64_t low;
469};
470
471static void mult_int64(struct sr_int128_t *res, const int64_t a,
472 const int64_t b)
473{
474 uint64_t t1, t2, t3, t4;
475
476 t1 = (UINT32_MAX & a) * (UINT32_MAX & b);
477 t2 = (UINT32_MAX & a) * (b >> 32);
478 t3 = (a >> 32) * (UINT32_MAX & b);
479 t4 = (a >> 32) * (b >> 32);
480
481 res->low = t1 + (t2 << 32) + (t3 << 32);
482 res->high = (t1 >> 32) + (uint64_t)((uint32_t)(t2)) + (uint64_t)((uint32_t)(t3));
483 res->high >>= 32;
484 res->high += ((int64_t)t2 >> 32) + ((int64_t)t3 >> 32) + t4;
485}
486
487static void mult_uint64(struct sr_uint128_t *res, const uint64_t a,
488 const uint64_t b)
489{
490 uint64_t t1, t2, t3, t4;
491
492 // (x1 + x2) * (y1 + y2) = x1*y1 + x1*y2 + x2*y1 + x2*y2
493 t1 = (UINT32_MAX & a) * (UINT32_MAX & b);
494 t2 = (UINT32_MAX & a) * (b >> 32);
495 t3 = (a >> 32) * (UINT32_MAX & b);
496 t4 = (a >> 32) * (b >> 32);
497
498 res->low = t1 + (t2 << 32) + (t3 << 32);
499 res->high = (t1 >> 32) + (uint64_t)((uint32_t)(t2)) + (uint64_t)((uint32_t)(t3));
500 res->high >>= 32;
501 res->high += ((int64_t)t2 >> 32) + ((int64_t)t3 >> 32) + t4;
502}
503#endif
504
505/**
8dc423b0 506 * Compare two sr_rational for equality.
bdba3626 507 *
8dc423b0 508 * The values are compared for numerical equality, i.e. 2/10 == 1/5.
bdba3626 509 *
8dc423b0
UH
510 * @param[in] a First value.
511 * @param[in] b Second value.
bdba3626 512 *
8dc423b0
UH
513 * @retval 1 if both values are equal.
514 * @retval 0 Otherwise.
bdba3626
SB
515 *
516 * @since 0.5.0
517 */
518SR_API int sr_rational_eq(const struct sr_rational *a, const struct sr_rational *b)
519{
520#ifdef HAVE___INT128_T
521 __int128_t m1, m2;
522
523 /* p1/q1 = p2/q2 <=> p1*q2 = p2*q1 */
524 m1 = ((__int128_t)(b->p)) * ((__uint128_t)a->q);
525 m2 = ((__int128_t)(a->p)) * ((__uint128_t)b->q);
526
527 return (m1 == m2);
528
529#else
530 struct sr_int128_t m1, m2;
531
532 mult_int64(&m1, a->q, b->p);
533 mult_int64(&m2, a->p, b->q);
534
535 return (m1.high == m2.high) && (m1.low == m2.low);
536#endif
537}
538
ee1b6054 539/**
8dc423b0 540 * Multiply two sr_rational.
ee1b6054
SB
541 *
542 * The resulting nominator/denominator are reduced if the result would not fit
543 * otherwise. If the resulting nominator/denominator are relatively prime,
544 * this may not be possible.
545 *
8dc423b0
UH
546 * It is safe to use the same variable for result and input values.
547 *
548 * @param[in] a First value.
549 * @param[in] b Second value.
550 * @param[out] res Result.
17d5a11c 551 *
ee1b6054 552 * @retval SR_OK Success.
8dc423b0 553 * @retval SR_ERR_ARG Resulting value too large.
ee1b6054
SB
554 *
555 * @since 0.5.0
556 */
557SR_API int sr_rational_mult(struct sr_rational *res, const struct sr_rational *a,
558 const struct sr_rational *b)
559{
560#ifdef HAVE___INT128_T
561 __int128_t p;
562 __uint128_t q;
563
564 p = (__int128_t)(a->p) * (__int128_t)(b->p);
565 q = (__uint128_t)(a->q) * (__uint128_t)(b->q);
566
567 if ((p > INT64_MAX) || (p < INT64_MIN) || (q > UINT64_MAX)) {
568 while (!((p & 1) || (q & 1))) {
569 p /= 2;
570 q /= 2;
571 }
572 }
573
574 if ((p > INT64_MAX) || (p < INT64_MIN) || (q > UINT64_MAX)) {
575 // TODO: determine gcd to do further reduction
576 return SR_ERR_ARG;
577 }
578
405b9c10
UH
579 res->p = (int64_t)p;
580 res->q = (uint64_t)q;
ee1b6054
SB
581
582 return SR_OK;
583
584#else
585 struct sr_int128_t p;
586 struct sr_uint128_t q;
587
588 mult_int64(&p, a->p, b->p);
589 mult_uint64(&q, a->q, b->q);
590
591 while (!(p.low & 1) && !(q.low & 1)) {
592 p.low /= 2;
8dc423b0
UH
593 if (p.high & 1)
594 p.low |= (1ll << 63);
ee1b6054
SB
595 p.high >>= 1;
596 q.low /= 2;
8dc423b0
UH
597 if (q.high & 1)
598 q.low |= (1ll << 63);
ee1b6054
SB
599 q.high >>= 1;
600 }
601
602 if (q.high)
603 return SR_ERR_ARG;
604 if ((p.high >= 0) && (p.low > INT64_MAX))
605 return SR_ERR_ARG;
606 if (p.high < -1)
607 return SR_ERR_ARG;
608
609 res->p = (int64_t)p.low;
610 res->q = q.low;
611
612 return SR_OK;
613#endif
614}
615
17d5a11c 616/**
8dc423b0 617 * Divide rational a by rational b.
17d5a11c
SB
618 *
619 * The resulting nominator/denominator are reduced if the result would not fit
620 * otherwise. If the resulting nominator/denominator are relatively prime,
621 * this may not be possible.
622 *
8dc423b0
UH
623 * It is safe to use the same variable for result and input values.
624 *
625 * @param[in] num Numerator.
626 * @param[in] div Divisor.
627 * @param[out] res Result.
17d5a11c
SB
628 *
629 * @retval SR_OK Success.
6762401d
UH
630 * @retval SR_ERR_ARG Division by zero, denominator of divisor too large,
631 * or resulting value too large.
17d5a11c
SB
632 *
633 * @since 0.5.0
634 */
635SR_API int sr_rational_div(struct sr_rational *res, const struct sr_rational *num,
636 const struct sr_rational *div)
637{
638 struct sr_rational t;
639
640 if (div->q > INT64_MAX)
641 return SR_ERR_ARG;
642 if (div->p == 0)
643 return SR_ERR_ARG;
644
645 if (div->p > 0) {
646 t.p = div->q;
647 t.q = div->p;
648 } else {
649 t.p = -div->q;
650 t.q = -div->p;
651 }
652
653 return sr_rational_mult(res, num, &t);
654}
655
e00b3f58 656/** @} */