1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2006 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 #include "por-file-writer.h"
31 #include <data/case.h>
32 #include <data/casewriter-provider.h>
33 #include <data/casewriter.h>
34 #include <data/dictionary.h>
35 #include <data/file-handle-def.h>
36 #include <data/format.h>
37 #include <data/missing-values.h>
38 #include <data/short-names.h>
39 #include <data/value-labels.h>
40 #include <data/variable.h>
42 #include <libpspp/alloc.h>
43 #include <libpspp/hash.h>
44 #include <libpspp/magic.h>
45 #include <libpspp/message.h>
46 #include <libpspp/misc.h>
47 #include <libpspp/str.h>
48 #include <libpspp/version.h>
51 #define _(msgid) gettext (msgid)
53 /* Maximum width of a variable in a portable file. */
54 #define MAX_POR_WIDTH 255
56 /* Portable file writer. */
59 struct file_handle *fh; /* File handle. */
60 FILE *file; /* File stream. */
62 int lc; /* Number of characters on this line so far. */
64 size_t var_cnt; /* Number of variables. */
65 struct pfm_var *vars; /* Variables. */
67 int digits; /* Digits of precision. */
70 /* A variable to write to the portable file. */
73 int width; /* 0=numeric, otherwise string var width. */
74 int fv; /* Starting case index. */
77 static struct casewriter_class por_file_casewriter_class;
79 static bool close_writer (struct pfm_writer *);
80 static void buf_write (struct pfm_writer *, const void *, size_t);
81 static void write_header (struct pfm_writer *);
82 static void write_version_data (struct pfm_writer *);
83 static void write_variables (struct pfm_writer *, struct dictionary *);
84 static void write_value_labels (struct pfm_writer *,
85 const struct dictionary *);
87 static void format_trig_double (long double, int base_10_precision, char[]);
88 static char *format_trig_int (int, bool force_sign, char[]);
90 /* Returns default options for writing a portable file. */
91 struct pfm_write_options
92 pfm_writer_default_options (void)
94 struct pfm_write_options opts;
95 opts.create_writeable = true;
97 opts.digits = DBL_DIG;
101 /* Writes the dictionary DICT to portable file HANDLE according
102 to the given OPTS. Returns nonzero only if successful. DICT
103 will not be modified, except to assign short names. */
105 pfm_open_writer (struct file_handle *fh, struct dictionary *dict,
106 struct pfm_write_options opts)
108 struct pfm_writer *w = NULL;
114 mode = S_IRUSR | S_IRGRP | S_IROTH;
115 if (opts.create_writeable)
116 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
117 fd = open (fh_get_file_name (fh), O_WRONLY | O_CREAT | O_TRUNC, mode);
121 /* Open file handle. */
122 if (!fh_open (fh, FH_REF_FILE, "portable file", "we"))
125 /* Initialize data structures. */
126 w = xmalloc (sizeof *w);
128 w->file = fdopen (fd, "w");
139 w->var_cnt = dict_get_var_cnt (dict);
140 w->vars = xnmalloc (w->var_cnt, sizeof *w->vars);
141 for (i = 0; i < w->var_cnt; i++)
143 const struct variable *dv = dict_get_var (dict, i);
144 struct pfm_var *pv = &w->vars[i];
145 pv->width = MIN (var_get_width (dv), MAX_POR_WIDTH);
146 pv->fv = var_get_case_index (dv);
149 w->digits = opts.digits;
152 msg (ME, _("Invalid decimal digits count %d. Treating as %d."),
157 /* Write file header. */
159 write_version_data (w);
160 write_variables (w, dict);
161 write_value_labels (w, dict);
162 buf_write (w, "F", 1);
163 if (ferror (w->file))
165 return casewriter_create (&por_file_casewriter_class, w);
172 msg (ME, _("An error occurred while opening \"%s\" for writing "
173 "as a portable file: %s."),
174 fh_get_file_name (fh), strerror (errno));
178 /* Write NBYTES starting at BUF to the portable file represented by
179 H. Break lines properly every 80 characters. */
181 buf_write (struct pfm_writer *w, const void *buf_, size_t nbytes)
183 const char *buf = buf_;
185 if (ferror (w->file))
188 assert (buf != NULL);
189 while (nbytes + w->lc >= 80)
191 size_t n = 80 - w->lc;
194 fwrite (buf, n, 1, w->file);
195 fwrite ("\r\n", 2, 1, w->file);
201 fwrite (buf, nbytes, 1, w->file);
206 /* Write D to the portable file as a floating-point field. */
208 write_float (struct pfm_writer *w, double d)
211 format_trig_double (d, floor (d) == d ? DBL_DIG : w->digits, buffer);
212 buf_write (w, buffer, strlen (buffer));
213 buf_write (w, "/", 1);
216 /* Write N to the portable file as an integer field. */
218 write_int (struct pfm_writer *w, int n)
221 format_trig_int (n, false, buffer);
222 buf_write (w, buffer, strlen (buffer));
223 buf_write (w, "/", 1);
226 /* Write S to the portable file as a string field. */
228 write_string (struct pfm_writer *w, const char *s)
230 size_t n = strlen (s);
231 write_int (w, (int) n);
235 /* Write file header. */
237 write_header (struct pfm_writer *w)
239 static const char spss2ascii[256] =
241 "0000000000000000000000000000000000000000000000000000000000000000"
242 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ."
243 "<(+|&[]!$*);^-/|,%_>?`:$@'=\"000000~-0000123456789000-()0{}\\00000"
244 "0000000000000000000000000000000000000000000000000000000000000000"
248 for (i = 0; i < 5; i++)
249 buf_write (w, "ASCII SPSS PORT FILE ", 40);
251 buf_write (w, spss2ascii, 256);
252 buf_write (w, "SPSSPORT", 8);
255 /* Writes version, date, and identification records. */
257 write_version_data (struct pfm_writer *w)
265 if ((time_t) -1 == time (&t))
267 tm.tm_sec = tm.tm_min = tm.tm_hour = tm.tm_mon = tm.tm_year = 0;
272 tmp = localtime (&t);
274 sprintf (date_str, "%04d%02d%02d",
275 tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday);
276 sprintf (time_str, "%02d%02d%02d", tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
277 buf_write (w, "A", 1);
278 write_string (w, date_str);
279 write_string (w, time_str);
281 /* Product identification. */
282 buf_write (w, "1", 1);
283 write_string (w, version);
285 /* Subproduct identification. */
286 buf_write (w, "3", 1);
287 write_string (w, host_system);
290 /* Write format F to file H. The format is first resized to fit
291 a value of the given WIDTH, which is handy in case F
292 represents a string longer than 255 bytes and thus WIDTH is
293 truncated to 255 bytes. */
295 write_format (struct pfm_writer *w, struct fmt_spec f, int width)
297 fmt_resize (&f, width);
298 write_int (w, fmt_to_io (f.type));
303 /* Write value V for variable VV to file H. */
305 write_value (struct pfm_writer *w, union value *v, struct variable *vv)
307 if (var_is_numeric (vv))
308 write_float (w, v->f);
311 int width = MIN (var_get_width (vv), MAX_POR_WIDTH);
312 write_int (w, width);
313 buf_write (w, v->s, width);
317 /* Write variable records. */
319 write_variables (struct pfm_writer *w, struct dictionary *dict)
323 short_names_assign (dict);
325 buf_write (w, "4", 1);
326 write_int (w, dict_get_var_cnt (dict));
329 for (i = 0; i < dict_get_var_cnt (dict); i++)
331 struct variable *v = dict_get_var (dict, i);
332 struct missing_values mv;
333 int width = MIN (var_get_width (v), MAX_POR_WIDTH);
335 buf_write (w, "7", 1);
336 write_int (w, width);
337 write_string (w, var_get_short_name (v, 0));
338 write_format (w, *var_get_print_format (v), width);
339 write_format (w, *var_get_write_format (v), width);
341 /* Write missing values. */
342 mv_copy (&mv, var_get_missing_values (v));
343 while (mv_has_range (&mv))
346 mv_pop_range (&mv, &x, &y);
349 buf_write (w, "9", 1);
352 else if (y == HIGHEST)
354 buf_write (w, "A", 1);
359 buf_write (w, "B", 1);
364 while (mv_has_value (&mv))
367 mv_pop_value (&mv, &value);
368 buf_write (w, "8", 1);
369 write_value (w, &value, v);
372 /* Write variable label. */
373 if (var_get_label (v) != NULL)
375 buf_write (w, "C", 1);
376 write_string (w, var_get_label (v));
381 /* Write value labels to disk. FIXME: Inefficient. */
383 write_value_labels (struct pfm_writer *w, const struct dictionary *dict)
387 for (i = 0; i < dict_get_var_cnt (dict); i++)
389 struct val_labs_iterator *j;
390 struct variable *v = dict_get_var (dict, i);
391 const struct val_labs *val_labs = var_get_value_labels (v);
394 if (val_labs == NULL)
397 buf_write (w, "D", 1);
399 write_string (w, var_get_short_name (v, 0));
400 write_int (w, val_labs_count (val_labs));
402 for (vl = val_labs_first_sorted (val_labs, &j); vl != NULL;
403 vl = val_labs_next (val_labs, &j))
405 write_value (w, &vl->value, v);
406 write_string (w, vl->label);
411 /* Writes case C to the portable file represented by H. */
413 por_file_casewriter_write (struct casewriter *writer, void *w_,
416 struct pfm_writer *w = w_;
419 if (!ferror (w->file))
421 for (i = 0; i < w->var_cnt; i++)
423 struct pfm_var *v = &w->vars[i];
426 write_float (w, case_num_idx (c, v->fv));
429 write_int (w, v->width);
430 buf_write (w, case_str_idx (c, v->fv), v->width);
435 casewriter_force_error (writer);
441 por_file_casewriter_destroy (struct casewriter *writer, void *w_)
443 struct pfm_writer *w = w_;
444 if (!close_writer (w))
445 casewriter_force_error (writer);
448 /* Closes a portable file after we're done with it.
449 Returns true if successful, false if an I/O error occurred. */
451 close_writer (struct pfm_writer *w)
462 memset (buf, 'Z', sizeof buf);
463 buf_write (w, buf, w->lc >= 80 ? 80 : 80 - w->lc);
465 ok = !ferror (w->file);
466 if (fclose (w->file) == EOF)
470 msg (ME, _("An I/O error occurred writing portable file \"%s\"."),
471 fh_get_file_name (w->fh));
474 fh_close (w->fh, "portable file", "we");
482 /* Base-30 conversion.
484 Portable files represent numbers in base-30 format, so we need
485 to be able to convert real and integer number to that base.
486 Older versions of PSPP used libgmp to do so, but this added a
487 big library dependency to do just one thing. Now we do it
488 ourselves internally.
490 Important fact: base 30 is called "trigesimal". */
492 /* Conversion base. */
493 #define BASE 30 /* As an integer. */
494 #define LDBASE ((long double) BASE) /* As a long double. */
496 /* This is floor(log30(2**31)), the minimum number of trigesimal
497 digits that a `long int' can hold. */
500 /* pow_tab[i] = pow (30, pow (2, i)) */
501 static long double pow_tab[16];
503 /* Initializes pow_tab[]. */
507 static bool did_init = false;
511 /* Only initialize once. */
516 /* Set each element of pow_tab[] until we run out of numerical
519 for (power = 30.0L; power < DBL_MAX; power *= power)
521 assert (i < sizeof pow_tab / sizeof *pow_tab);
522 pow_tab[i++] = power;
526 /* Returns 30**EXPONENT, for 0 <= EXPONENT <= log30(DBL_MAX). */
528 pow30_nonnegative (int exponent)
533 assert (exponent >= 0);
534 assert (exponent < 1L << (sizeof pow_tab / sizeof *pow_tab));
537 for (i = 0; exponent > 0; exponent >>= 1, i++)
544 /* Returns 30**EXPONENT, for log30(DBL_MIN) <= EXPONENT <=
550 return pow30_nonnegative (exponent);
552 return 1.L / pow30_nonnegative (-exponent);
555 /* Returns the character corresponding to TRIG. */
557 trig_to_char (int trig)
559 assert (trig >= 0 && trig < 30);
560 return "0123456789ABCDEFGHIJKLMNOPQRST"[trig];
563 /* Formats the TRIG_CNT trigs in TRIGS[], writing them as
564 null-terminated STRING. The trigesimal point is inserted
565 after TRIG_PLACES characters have been printed, if necessary
566 adding extra zeros at either end for correctness. Returns the
567 character after the formatted number. */
569 format_trig_digits (char *string,
570 const char trigs[], int trig_cnt, int trig_places)
575 while (trig_places++ < 0)
579 while (trig_cnt-- > 0)
581 if (trig_places-- == 0)
583 *string++ = trig_to_char (*trigs++);
585 while (trig_places-- > 0)
591 /* Helper function for format_trig_int() that formats VALUE as a
592 trigesimal integer at CP. VALUE must be nonnegative.
593 Returns the character following the formatted integer. */
595 recurse_format_trig_int (char *cp, int value)
597 int trig = value % BASE;
600 cp = recurse_format_trig_int (cp, value);
601 *cp++ = trig_to_char (trig);
605 /* Formats VALUE as a trigesimal integer in null-terminated
606 STRING[]. VALUE must be in the range -DBL_MAX...DBL_MAX. If
607 FORCE_SIGN is true, a sign is always inserted; otherwise, a
608 sign is only inserted if VALUE is negative. */
610 format_trig_int (int value, bool force_sign, char string[])
621 /* Format integer. */
622 string = recurse_format_trig_int (string, value);
627 /* Determines whether the TRIG_CNT trigesimals in TRIGS[] warrant
628 rounding up or down. Returns true if TRIGS[] represents a
629 value greater than half, false if less than half. If TRIGS[]
630 is exactly half, examines TRIGS[-1] and returns true if odd,
631 false if even ("round to even"). */
633 should_round_up (const char trigs[], int trig_cnt)
635 assert (trig_cnt > 0);
637 if (*trigs < BASE / 2)
639 /* Less than half: round down. */
642 else if (*trigs > BASE / 2)
644 /* Greater than half: round up. */
649 /* Approximately half: look more closely. */
651 for (i = 1; i < trig_cnt; i++)
654 /* Slightly greater than half: round up. */
658 /* Exactly half: round to even. */
659 return trigs[-1] % 2;
663 /* Rounds up the rightmost trig in the TRIG_CNT trigs in TRIGS[],
664 carrying to the left as necessary. Returns true if
665 successful, false on failure (due to a carry out of the
666 leftmost position). */
668 try_round_up (char *trigs, int trig_cnt)
672 char *round_trig = trigs + --trig_cnt;
673 if (*round_trig != BASE - 1)
675 /* Round this trig up to the next value. */
680 /* Carry over to the next trig to the left. */
684 /* Ran out of trigs to carry. */
688 /* Converts VALUE to trigesimal format in string OUTPUT[] with the
689 equivalent of at least BASE_10_PRECISION decimal digits of
690 precision. The output format may use conventional or
691 scientific notation. Missing, infinite, and extreme values
692 are represented with "*.". */
694 format_trig_double (long double value, int base_10_precision, char output[])
696 /* Original VALUE was negative? */
699 /* Number of significant trigesimals. */
700 int base_30_precision;
702 /* Base-2 significand and exponent for original VALUE. */
706 /* VALUE as a set of trigesimals. */
707 char buffer[DBL_DIG + 16];
711 /* Number of trigesimal places for trigs.
712 trigs[0] has coefficient 30**(trig_places - 1),
713 trigs[1] has coefficient 30**(trig_places - 2),
715 In other words, the trigesimal point is just before trigs[0].
719 /* Number of trigesimal places left to write into BUFFER. */
724 /* Handle special cases. */
730 /* Make VALUE positive. */
739 /* Adjust VALUE to roughly 30**3, by shifting the trigesimal
740 point left or right as necessary. We approximate the
741 base-30 exponent by obtaining the base-2 exponent, then
742 multiplying by log30(2). This approximation is sufficient
743 to ensure that the adjusted VALUE is always in the range
744 0...30**6, an invariant of the loop below. */
746 base_2_sig = frexp (value, &base_2_exp);
747 if (errno != 0 || !finite (base_2_sig))
749 if (base_2_exp == 0 && base_2_sig == 0.)
751 if (base_2_exp <= INT_MIN / 20379L || base_2_exp >= INT_MAX / 20379L)
753 trig_places = (base_2_exp * 20379L / 100000L) + CHUNK_SIZE / 2;
754 value *= pow30 (CHUNK_SIZE - trig_places);
756 /* Dump all the trigs to buffer[], CHUNK_SIZE at a time. */
759 for (trigs_to_output = DIV_RND_UP (DBL_DIG * 2, 3) + 1 + (CHUNK_SIZE / 2);
761 trigs_to_output -= CHUNK_SIZE)
766 /* The current chunk is just the integer part of VALUE,
767 truncated to the nearest integer. The chunk fits in a
770 assert (pow30 (CHUNK_SIZE) <= LONG_MAX);
771 assert (chunk >= 0 && chunk < pow30 (CHUNK_SIZE));
775 /* Append the chunk, in base 30, to trigs[]. */
776 for (trigs_left = CHUNK_SIZE; chunk > 0 && trigs_left > 0; )
778 trigs[trig_cnt + --trigs_left] = chunk % 30;
781 while (trigs_left > 0)
782 trigs[trig_cnt + --trigs_left] = 0;
783 trig_cnt += CHUNK_SIZE;
785 /* Proceed to the next chunk. */
788 value *= pow (LDBASE, CHUNK_SIZE);
791 /* Strip leading zeros. */
792 while (trig_cnt > 1 && *trigs == 0)
799 /* Round to requested precision, conservatively estimating the
800 required base-30 precision as 2/3 of the base-10 precision
801 (log30(10) = .68). */
802 assert (base_10_precision > 0);
803 if (base_10_precision > LDBL_DIG)
804 base_10_precision = LDBL_DIG;
805 base_30_precision = DIV_RND_UP (base_10_precision * 2, 3);
806 if (trig_cnt > base_30_precision)
808 if (should_round_up (trigs + base_30_precision,
809 trig_cnt - base_30_precision))
811 /* Try to round up. */
812 if (try_round_up (trigs, base_30_precision))
814 /* Rounding up worked. */
815 trig_cnt = base_30_precision;
819 /* Couldn't round up because we ran out of trigs to
820 carry into. Do the carry here instead. */
829 trig_cnt = base_30_precision;
834 /* No rounding required: fewer digits available than
838 /* Strip trailing zeros. */
839 while (trig_cnt > 1 && trigs[trig_cnt - 1] == 0)
845 if (trig_places >= -1 && trig_places < trig_cnt + 3)
847 /* Use conventional notation. */
848 format_trig_digits (output, trigs, trig_cnt, trig_places);
852 /* Use scientific notation. */
854 op = format_trig_digits (output, trigs, trig_cnt, trig_cnt);
855 op = format_trig_int (trig_places - trig_cnt, true, op);
860 strcpy (output, "0");
864 strcpy (output, "*.");
868 static struct casewriter_class por_file_casewriter_class =
870 por_file_casewriter_write,
871 por_file_casewriter_destroy,