Coverage Report

Created: 2026-12-01 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/postgis/liblwgeom/lwprint.c
Line
Count
Source
1
/**********************************************************************
2
 *
3
 * PostGIS - Spatial Types for PostgreSQL
4
 * http://postgis.net
5
 *
6
 * PostGIS 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 2 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * PostGIS 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 PostGIS.  If not, see <http://www.gnu.org/licenses/>.
18
 *
19
 **********************************************************************
20
 *
21
 * Copyright (C) 2010-2015 Paul Ramsey <pramsey@cleverelephant.ca>
22
 * Copyright (C) 2011 Sandro Santilli <strk@kbt.io>
23
 *
24
 **********************************************************************/
25
26
#include "liblwgeom_internal.h"
27
28
#include <assert.h>
29
#include <math.h>
30
#include <stdio.h>
31
#include <string.h>
32
33
#include "ryu/ryu.h"
34
35
/* Ensures the given lat and lon are in the "normal" range:
36
 * -90 to +90 for lat, -180 to +180 for lon. */
37
static void
38
lwprint_normalize_latlon(double *lat, double *lon)
39
0
{
40
  /* First remove all the truly excessive trips around the world via up or down.
41
   * fmod reduces in O(1); a plain subtraction loop never terminates for
42
   * magnitudes where the ULP exceeds 360 (above ~4.6e18). */
43
0
  *lat = fmod(*lat, 360.0);
44
0
  if (*lat > 270)
45
0
    *lat -= 360;
46
0
  else if (*lat < -270)
47
0
    *lat += 360;
48
49
  /* Now see if latitude is past the top or bottom of the world.
50
   * Past 90  or -90 puts us on the other side of the earth,
51
   * so wrap latitude and add 180 to longitude to reflect that. */
52
0
  if (*lat > 90)
53
0
  {
54
0
    *lat = 180 - *lat;
55
0
    *lon += 180;
56
0
  }
57
0
  if (*lat < -90)
58
0
  {
59
0
    *lat = -180 - *lat;
60
0
    *lon += 180;
61
0
  }
62
  /* Now make sure lon is in the normal range.  Wrapping longitude
63
   * has no effect on latitude. */
64
0
  *lon = fmod(*lon, 360.0);
65
0
  if (*lon > 180)
66
0
    *lon -= 360;
67
0
  else if (*lon < -180)
68
0
    *lon += 360;
69
0
}
70
71
/* Converts a single double to DMS given the specified DMS format string.
72
 * Symbols are specified since N/S or E/W are the only differences when printing
73
 * lat vs. lon.  They are only used if the "C" (compass dir) token appears in the
74
 * format string.
75
 * NOTE: Format string and symbols are required to be in UTF-8. */
76
static char *
77
lwdouble_to_dms(double val, const char *pos_dir_symbol, const char *neg_dir_symbol, const char *format)
78
0
{
79
  /* 3 numbers, 1 sign or compass dir, and 5 possible strings (degree signs, spaces, misc text, etc) between or
80
   * around them.*/
81
0
#define NUM_PIECES 9
82
0
#define WORK_SIZE 1024
83
0
  char pieces[NUM_PIECES][WORK_SIZE];
84
0
  int current_piece = 0;
85
0
  int is_negative = 0;
86
87
0
  double degrees = 0.0;
88
0
  double minutes = 0.0;
89
0
  double seconds = 0.0;
90
91
0
  int compass_dir_piece = -1;
92
93
0
  int reading_deg = 0;
94
0
  int deg_digits = 0;
95
0
  int deg_has_decpoint = 0;
96
0
  int deg_dec_digits = 0;
97
0
  int deg_piece = -1;
98
99
0
  int reading_min = 0;
100
0
  int min_digits = 0;
101
0
  int min_has_decpoint = 0;
102
0
  int min_dec_digits = 0;
103
0
  int min_piece = -1;
104
105
0
  int reading_sec = 0;
106
0
  int sec_digits = 0;
107
0
  int sec_has_decpoint = 0;
108
0
  int sec_dec_digits = 0;
109
0
  int sec_piece = -1;
110
111
0
  int round_pow = 0;
112
113
0
  int format_length = ((NULL == format) ? 0 : strlen(format));
114
115
0
  char *result;
116
117
0
  int index, following_byte_index;
118
0
  int multibyte_char_width = 1;
119
120
  /* Initialize the working strs to blank.  We may not populate all of them, and
121
   * this allows us to concat them all at the end without worrying about how many
122
   * we actually needed. */
123
0
  for (index = 0; index < NUM_PIECES; index++)
124
0
  {
125
0
    pieces[index][0] = '\0';
126
0
  }
127
128
  /* If no format is provided, use a default. */
129
0
  if (0 == format_length)
130
0
  {
131
    /* C2B0 is UTF-8 for the degree symbol. */
132
0
    format =
133
0
        "D\xC2\xB0"
134
0
        "M'S.SSS\"C";
135
0
    format_length = strlen(format);
136
0
  }
137
0
  else if (format_length > WORK_SIZE)
138
0
  {
139
    /* Sanity check, we don't want to overwrite an entire piece of work and no one should need a 1K-sized
140
     * format string anyway. */
141
0
    lwerror("Bad format, exceeds maximum length (%d).", WORK_SIZE);
142
0
  }
143
144
0
  for (index = 0; index < format_length; index++)
145
0
  {
146
0
    char next_char = format[index];
147
0
    switch (next_char)
148
0
    {
149
0
    case 'D':
150
0
      if (reading_deg)
151
0
      {
152
        /* If we're reading degrees, add another digit. */
153
0
        deg_has_decpoint ? deg_dec_digits++ : deg_digits++;
154
0
      }
155
0
      else
156
0
      {
157
        /* If we're not reading degrees, we are now. */
158
0
        current_piece++;
159
0
        deg_piece = current_piece;
160
0
        if (deg_digits > 0)
161
0
        {
162
0
          lwerror("Bad format, cannot include degrees (DD.DDD) more than once.");
163
0
        }
164
0
        reading_deg = 1;
165
0
        reading_min = 0;
166
0
        reading_sec = 0;
167
0
        deg_digits++;
168
0
      }
169
0
      break;
170
0
    case 'M':
171
0
      if (reading_min)
172
0
      {
173
        /* If we're reading minutes, add another digit. */
174
0
        min_has_decpoint ? min_dec_digits++ : min_digits++;
175
0
      }
176
0
      else
177
0
      {
178
        /* If we're not reading minutes, we are now. */
179
0
        current_piece++;
180
0
        min_piece = current_piece;
181
0
        if (min_digits > 0)
182
0
        {
183
0
          lwerror("Bad format, cannot include minutes (MM.MMM) more than once.");
184
0
        }
185
0
        reading_deg = 0;
186
0
        reading_min = 1;
187
0
        reading_sec = 0;
188
0
        min_digits++;
189
0
      }
190
0
      break;
191
0
    case 'S':
192
0
      if (reading_sec)
193
0
      {
194
        /* If we're reading seconds, add another digit. */
195
0
        sec_has_decpoint ? sec_dec_digits++ : sec_digits++;
196
0
      }
197
0
      else
198
0
      {
199
        /* If we're not reading seconds, we are now. */
200
0
        current_piece++;
201
0
        sec_piece = current_piece;
202
0
        if (sec_digits > 0)
203
0
        {
204
0
          lwerror("Bad format, cannot include seconds (SS.SSS) more than once.");
205
0
        }
206
0
        reading_deg = 0;
207
0
        reading_min = 0;
208
0
        reading_sec = 1;
209
0
        sec_digits++;
210
0
      }
211
0
      break;
212
0
    case 'C':
213
      /* We're done reading anything else we might have been reading. */
214
0
      if (reading_deg || reading_min || reading_sec)
215
0
      {
216
        /* We were reading something, that means this is the next piece. */
217
0
        reading_deg = 0;
218
0
        reading_min = 0;
219
0
        reading_sec = 0;
220
0
      }
221
0
      current_piece++;
222
223
0
      if (compass_dir_piece >= 0)
224
0
      {
225
0
        lwerror("Bad format, cannot include compass dir (C) more than once.");
226
0
      }
227
      /* The compass dir is a piece all by itself.  */
228
0
      compass_dir_piece = current_piece;
229
0
      current_piece++;
230
0
      break;
231
0
    case '.':
232
      /* If we're reading deg, min, or sec, we want a decimal point for it. */
233
0
      if (reading_deg)
234
0
      {
235
0
        deg_has_decpoint = 1;
236
0
      }
237
0
      else if (reading_min)
238
0
      {
239
0
        min_has_decpoint = 1;
240
0
      }
241
0
      else if (reading_sec)
242
0
      {
243
0
        sec_has_decpoint = 1;
244
0
      }
245
0
      else
246
0
      {
247
        /* Not reading anything, just pass through the '.' */
248
0
        strncat(pieces[current_piece], &next_char, 1);
249
0
      }
250
0
      break;
251
0
    default:
252
      /* Any other char is just passed through unchanged.  But it does mean we are done reading D, M,
253
       * or S.*/
254
0
      if (reading_deg || reading_min || reading_sec)
255
0
      {
256
        /* We were reading something, that means this is the next piece. */
257
0
        current_piece++;
258
0
        reading_deg = 0;
259
0
        reading_min = 0;
260
0
        reading_sec = 0;
261
0
      }
262
263
      /* Check if this is a multi-byte UTF-8 character.  If so go ahead and read the rest of the bytes
264
       * as well. */
265
0
      multibyte_char_width = 1;
266
0
      if (next_char & 0x80)
267
0
      {
268
0
        if ((next_char & 0xF8) == 0xF0)
269
0
        {
270
0
          multibyte_char_width += 3;
271
0
        }
272
0
        else if ((next_char & 0xF0) == 0xE0)
273
0
        {
274
0
          multibyte_char_width += 2;
275
0
        }
276
0
        else if ((next_char & 0xE0) == 0xC0)
277
0
        {
278
0
          multibyte_char_width += 1;
279
0
        }
280
0
        else
281
0
        {
282
0
          lwerror(
283
0
              "Bad format, invalid high-order byte found first, format string may not be UTF-8.");
284
0
        }
285
0
      }
286
0
      if (multibyte_char_width > 1)
287
0
      {
288
0
        if (index + multibyte_char_width >= format_length)
289
0
        {
290
0
          lwerror(
291
0
              "Bad format, UTF-8 character first byte found with insufficient following bytes, format string may not be UTF-8.");
292
0
        }
293
0
        for (following_byte_index = (index + 1);
294
0
             following_byte_index < (index + multibyte_char_width);
295
0
             following_byte_index++)
296
0
        {
297
0
          if ((format[following_byte_index] & 0xC0) != 0x80)
298
0
          {
299
0
            lwerror(
300
0
                "Bad format, invalid byte found following leading byte of multibyte character, format string may not be UTF-8.");
301
0
          }
302
0
        }
303
0
      }
304
      /* Copy all the character's bytes into the current piece. */
305
0
      strncat(pieces[current_piece], &(format[index]), multibyte_char_width);
306
      /* Now increment index past the rest of those bytes. */
307
0
      index += multibyte_char_width - 1;
308
0
      break;
309
0
    }
310
0
    if (current_piece >= NUM_PIECES)
311
0
    {
312
0
      lwerror("Internal error, somehow needed more pieces than it should.");
313
0
    }
314
0
  }
315
0
  if (deg_piece < 0)
316
0
  {
317
0
    lwerror("Bad format, degrees (DD.DDD) must be included.");
318
0
  }
319
320
  /* Divvy the number up into D, DM, or DMS */
321
0
  if (val < 0)
322
0
  {
323
0
    val *= -1;
324
0
    is_negative = 1;
325
0
  }
326
0
  degrees = val;
327
0
  if (min_digits > 0)
328
0
  {
329
    /* Break degrees to integer and use fraction for minutes */
330
0
    minutes = modf(val, &degrees) * 60;
331
0
  }
332
0
  if (sec_digits > 0)
333
0
  {
334
0
    if (0 == min_digits)
335
0
    {
336
0
      lwerror("Bad format, cannot include seconds (SS.SSS) without including minutes (MM.MMM).");
337
0
    }
338
0
    seconds = modf(minutes, &minutes) * 60;
339
0
    if (sec_piece >= 0)
340
0
    {
341
      /* See if the formatted seconds round up to 60. If so, increment minutes and reset seconds. */
342
0
      round_pow = pow(10, sec_dec_digits);
343
0
      if (lround(seconds * round_pow) >= 60 * round_pow)
344
0
      {
345
0
        minutes += 1;
346
0
        seconds = 0;
347
        /* See if the formatted minutes round up to 60. If so, increment degrees and reset
348
         * seconds. */
349
0
        if (lround(minutes * round_pow) >= 60 * round_pow)
350
0
        {
351
0
          degrees += 1;
352
0
          minutes = 0;
353
0
        }
354
0
      }
355
0
    }
356
0
  }
357
358
  /* Handle the compass direction.  If not using compass dir, display degrees as a positive/negative number. */
359
0
  if (compass_dir_piece >= 0)
360
0
  {
361
0
    strcpy(pieces[compass_dir_piece], is_negative ? neg_dir_symbol : pos_dir_symbol);
362
0
  }
363
0
  else if (is_negative)
364
0
  {
365
0
    degrees *= -1;
366
0
  }
367
368
  /* Format the degrees into their string piece. */
369
0
  if (deg_digits + deg_dec_digits + 2 > WORK_SIZE)
370
0
  {
371
0
    lwerror("Bad format, degrees (DD.DDD) number of digits was greater than our working limit.");
372
0
  }
373
0
  if (deg_piece >= 0)
374
0
  {
375
0
    snprintf(pieces[deg_piece], WORK_SIZE, "%*.*f", deg_digits, deg_dec_digits, degrees);
376
0
  }
377
378
0
  if (min_piece >= 0)
379
0
  {
380
    /* Format the minutes into their string piece. */
381
0
    if (min_digits + min_dec_digits + 2 > WORK_SIZE)
382
0
    {
383
0
      lwerror("Bad format, minutes (MM.MMM) number of digits was greater than our working limit.");
384
0
    }
385
0
    snprintf(pieces[min_piece], WORK_SIZE, "%*.*f", min_digits, min_dec_digits, minutes);
386
0
  }
387
0
  if (sec_piece >= 0)
388
0
  {
389
    /* Format the seconds into their string piece. */
390
0
    if (sec_digits + sec_dec_digits + 2 > WORK_SIZE)
391
0
    {
392
0
      lwerror("Bad format, seconds (SS.SSS) number of digits was greater than our working limit.");
393
0
    }
394
0
    snprintf(pieces[sec_piece], WORK_SIZE, "%*.*f", sec_digits, sec_dec_digits, seconds);
395
0
  }
396
397
  /* Allocate space for the result.  Leave plenty of room for excess digits, negative sign, etc.*/
398
0
  result = (char *)lwalloc(format_length + WORK_SIZE);
399
0
  memset(result, 0, format_length + WORK_SIZE);
400
401
  /* Append all the pieces together. There may be less than 9, but in that case the rest will be blank. */
402
0
  strcpy(result, pieces[0]);
403
0
  for (index = 1; index < NUM_PIECES; index++)
404
0
  {
405
0
    strcat(result, pieces[index]);
406
0
  }
407
408
0
  return result;
409
0
}
410
411
/* Print two doubles (lat and lon) in DMS form using the specified format.
412
 * First normalizes them so they will display as -90 to 90 and -180 to 180.
413
 * Format string may be null or 0-length, in which case a default format will be used.
414
 * NOTE: Format string is required to be in UTF-8.
415
 * NOTE2: returned string is lwalloc'ed, caller is responsible to lwfree it up
416
 */
417
static char *
418
lwdoubles_to_latlon(double lat, double lon, const char *format)
419
0
{
420
0
  char *lat_text;
421
0
  char *lon_text;
422
0
  char *result;
423
0
  size_t sz;
424
425
  /* Normalize lat/lon to the normal (-90 to 90, -180 to 180) range. */
426
0
  lwprint_normalize_latlon(&lat, &lon);
427
  /* This is somewhat inefficient as the format is parsed twice. */
428
0
  lat_text = lwdouble_to_dms(lat, "N", "S", format);
429
0
  lon_text = lwdouble_to_dms(lon, "E", "W", format);
430
431
  /* lat + lon + a space between + the null terminator. */
432
0
  sz = strlen(lat_text) + strlen(lon_text) + 2;
433
0
  result = (char *)lwalloc(sz);
434
0
  snprintf(result, sz, "%s %s", lat_text, lon_text);
435
0
  lwfree(lat_text);
436
0
  lwfree(lon_text);
437
0
  return result;
438
0
}
439
440
/* Print the X (lon) and Y (lat) of the given point in DMS form using
441
 * the specified format.
442
 * First normalizes the values so they will display as -90 to 90 and -180 to 180.
443
 * Format string may be null or 0-length, in which case a default format will be used.
444
 * NOTE: Format string is required to be in UTF-8.
445
 * NOTE2: returned string is lwalloc'ed, caller is responsible to lwfree it up
446
 */
447
char *
448
lwpoint_to_latlon(const LWPOINT *pt, const char *format)
449
0
{
450
0
  const POINT2D *p;
451
0
  if (NULL == pt)
452
0
  {
453
0
    lwerror("Cannot convert a null point into formatted text.");
454
0
  }
455
0
  if (lwgeom_is_empty((LWGEOM *)pt))
456
0
  {
457
0
    lwerror("Cannot convert an empty point into formatted text.");
458
0
  }
459
0
  p = getPoint2d_cp(pt->point, 0);
460
0
  return lwdoubles_to_latlon(p->y, p->x, format);
461
0
}
462
463
/*
464
 * Print an ordinate value using at most **maxdd** number of decimal digits
465
 * The actual number of printed decimal digits may be less than the
466
 * requested ones if out of significant digits.
467
 *
468
 * The function will write at most OUT_DOUBLE_BUFFER_SIZE bytes, including the
469
 * terminating NULL.
470
 * It returns the number of bytes written (excluding the final NULL)
471
 *
472
 */
473
int
474
lwprint_double(double d, int maxdd, char *buf)
475
0
{
476
0
  int length;
477
0
  double ad = fabs(d);
478
0
  int precision = FP_MAX(0, maxdd);
479
480
0
  if (ad <= OUT_MIN_DOUBLE || ad >= OUT_MAX_DOUBLE)
481
0
  {
482
0
    length = d2sexp_buffered_n(d, precision, buf);
483
0
  }
484
0
  else
485
0
  {
486
0
    length = d2sfixed_buffered_n(d, precision, buf);
487
0
  }
488
0
  buf[length] = '\0';
489
490
0
  return length;
491
0
}