1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2006, 2009 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"
29 #include <data/case.h>
30 #include <data/casewriter-provider.h>
31 #include <data/casewriter.h>
32 #include <data/dictionary.h>
33 #include <data/file-handle-def.h>
34 #include <data/file-name.h>
35 #include <data/format.h>
36 #include <data/make-file.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/hash.h>
43 #include <libpspp/message.h>
44 #include <libpspp/misc.h>
45 #include <libpspp/str.h>
46 #include <libpspp/version.h>
51 #define _(msgid) gettext (msgid)
52 #define N_(msgid) (msgid)
54 /* Maximum width of a variable in a portable file. */
55 #define MAX_POR_WIDTH 255
57 /* Portable file writer. */
60 struct file_handle *fh; /* File handle. */
61 struct fh_lock *lock; /* Lock on file handle. */
62 FILE *file; /* File stream. */
63 struct replace_file *rf; /* Ticket for replacing output file. */
65 int lc; /* Number of characters on this line so far. */
67 size_t var_cnt; /* Number of variables. */
68 struct pfm_var *vars; /* Variables. */
70 int digits; /* Digits of precision. */
73 /* A variable to write to the portable file. */
76 int width; /* 0=numeric, otherwise string var width. */
77 int fv; /* Starting case index. */
80 static const struct casewriter_class por_file_casewriter_class;
82 static bool close_writer (struct pfm_writer *);
83 static void buf_write (struct pfm_writer *, const void *, size_t);
84 static void write_header (struct pfm_writer *);
85 static void write_version_data (struct pfm_writer *);
86 static void write_variables (struct pfm_writer *, struct dictionary *);
87 static void write_value_labels (struct pfm_writer *,
88 const struct dictionary *);
89 static void write_documents (struct pfm_writer *,
90 const struct dictionary *);
92 static void format_trig_double (long double, int base_10_precision, char[]);
93 static char *format_trig_int (int, bool force_sign, char[]);
95 /* Returns default options for writing a portable file. */
96 struct pfm_write_options
97 pfm_writer_default_options (void)
99 struct pfm_write_options opts;
100 opts.create_writeable = true;
101 opts.type = PFM_COMM;
102 opts.digits = DBL_DIG;
106 /* Writes the dictionary DICT to portable file HANDLE according
107 to the given OPTS. Returns nonzero only if successful. DICT
108 will not be modified, except to assign short names. */
110 pfm_open_writer (struct file_handle *fh, struct dictionary *dict,
111 struct pfm_write_options opts)
113 struct pfm_writer *w = NULL;
117 /* Initialize data structures. */
118 w = xmalloc (sizeof *w);
127 w->var_cnt = dict_get_var_cnt (dict);
128 w->vars = xnmalloc (w->var_cnt, sizeof *w->vars);
129 for (i = 0; i < w->var_cnt; i++)
131 const struct variable *dv = dict_get_var (dict, i);
132 struct pfm_var *pv = &w->vars[i];
133 pv->width = MIN (var_get_width (dv), MAX_POR_WIDTH);
134 pv->fv = var_get_case_index (dv);
137 w->digits = opts.digits;
140 msg (ME, _("Invalid decimal digits count %d. Treating as %d."),
146 /* TRANSLATORS: this fragment will be interpolated into
147 messages in fh_lock() that identify types of files. */
148 w->lock = fh_lock (fh, FH_REF_FILE, N_("portable file"), FH_ACC_WRITE, true);
153 mode = S_IRUSR | S_IRGRP | S_IROTH;
154 if (opts.create_writeable)
155 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
156 w->rf = replace_file_start (fh_get_file_name (fh), "w", mode,
160 msg (ME, _("Error opening \"%s\" for writing as a portable file: %s."),
161 fh_get_file_name (fh), strerror (errno));
165 /* Write file header. */
167 write_version_data (w);
168 write_variables (w, dict);
169 write_value_labels (w, dict);
170 if (dict_get_document_line_cnt (dict) > 0)
171 write_documents (w, dict);
172 buf_write (w, "F", 1);
173 if (ferror (w->file))
175 return casewriter_create (dict_get_next_value_idx (dict),
176 &por_file_casewriter_class, w);
183 /* Write NBYTES starting at BUF to the portable file represented by
184 H. Break lines properly every 80 characters. */
186 buf_write (struct pfm_writer *w, const void *buf_, size_t nbytes)
188 const char *buf = buf_;
190 if (ferror (w->file))
193 assert (buf != NULL);
194 while (nbytes + w->lc >= 80)
196 size_t n = 80 - w->lc;
199 fwrite (buf, n, 1, w->file);
200 fwrite ("\r\n", 2, 1, w->file);
206 fwrite (buf, nbytes, 1, w->file);
211 /* Write D to the portable file as a floating-point field. */
213 write_float (struct pfm_writer *w, double d)
216 format_trig_double (d, floor (d) == d ? DBL_DIG : w->digits, buffer);
217 buf_write (w, buffer, strlen (buffer));
219 buf_write (w, "/", 1);
222 /* Write N to the portable file as an integer field. */
224 write_int (struct pfm_writer *w, int n)
227 format_trig_int (n, false, buffer);
228 buf_write (w, buffer, strlen (buffer));
229 buf_write (w, "/", 1);
232 /* Write S to the portable file as a string field. */
234 write_string (struct pfm_writer *w, const char *s)
236 size_t n = strlen (s);
237 write_int (w, (int) n);
241 /* Write file header. */
243 write_header (struct pfm_writer *w)
245 static const char spss2ascii[256] =
247 "0000000000000000000000000000000000000000000000000000000000000000"
248 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ."
249 "<(+|&[]!$*);^-/|,%_>?`:$@'=\"000000~-0000123456789000-()0{}\\00000"
250 "0000000000000000000000000000000000000000000000000000000000000000"
254 for (i = 0; i < 5; i++)
255 buf_write (w, "ASCII SPSS PORT FILE ", 40);
257 buf_write (w, spss2ascii, 256);
258 buf_write (w, "SPSSPORT", 8);
261 /* Writes version, date, and identification records. */
263 write_version_data (struct pfm_writer *w)
271 if ((time_t) -1 == time (&t))
273 tm.tm_sec = tm.tm_min = tm.tm_hour = tm.tm_mon = tm.tm_year = 0;
278 tmp = localtime (&t);
280 sprintf (date_str, "%04d%02d%02d",
281 tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday);
282 sprintf (time_str, "%02d%02d%02d", tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
283 buf_write (w, "A", 1);
284 write_string (w, date_str);
285 write_string (w, time_str);
287 /* Product identification. */
288 buf_write (w, "1", 1);
289 write_string (w, version);
291 /* Subproduct identification. */
292 buf_write (w, "3", 1);
293 write_string (w, host_system);
296 /* Write format F to file H. The format is first resized to fit
297 a value of the given WIDTH, which is handy in case F
298 represents a string longer than 255 bytes and thus WIDTH is
299 truncated to 255 bytes. */
301 write_format (struct pfm_writer *w, struct fmt_spec f, int width)
303 fmt_resize (&f, width);
304 write_int (w, fmt_to_io (f.type));
309 /* Write value V for variable VV to file H. */
311 write_value (struct pfm_writer *w, union value *v, struct variable *vv)
313 if (var_is_numeric (vv))
314 write_float (w, v->f);
317 int width = MIN (var_get_width (vv), MAX_POR_WIDTH);
318 write_int (w, width);
319 buf_write (w, v->s, width);
323 /* Write variable records. */
325 write_variables (struct pfm_writer *w, struct dictionary *dict)
329 short_names_assign (dict);
331 if (dict_get_weight (dict) != NULL)
333 buf_write (w, "6", 1);
334 write_string (w, var_get_short_name (dict_get_weight (dict), 0));
337 buf_write (w, "4", 1);
338 write_int (w, dict_get_var_cnt (dict));
341 for (i = 0; i < dict_get_var_cnt (dict); i++)
343 struct variable *v = dict_get_var (dict, i);
344 struct missing_values mv;
345 int width = MIN (var_get_width (v), MAX_POR_WIDTH);
347 buf_write (w, "7", 1);
348 write_int (w, width);
349 write_string (w, var_get_short_name (v, 0));
350 write_format (w, *var_get_print_format (v), width);
351 write_format (w, *var_get_write_format (v), width);
353 /* Write missing values. */
354 mv_copy (&mv, var_get_missing_values (v));
355 while (mv_has_range (&mv))
358 mv_pop_range (&mv, &x, &y);
361 buf_write (w, "9", 1);
364 else if (y == HIGHEST)
366 buf_write (w, "A", 1);
371 buf_write (w, "B", 1);
376 while (mv_has_value (&mv))
379 mv_pop_value (&mv, &value);
380 buf_write (w, "8", 1);
381 write_value (w, &value, v);
384 /* Write variable label. */
385 if (var_get_label (v) != NULL)
387 buf_write (w, "C", 1);
388 write_string (w, var_get_label (v));
393 /* Write value labels to disk. FIXME: Inefficient. */
395 write_value_labels (struct pfm_writer *w, const struct dictionary *dict)
399 for (i = 0; i < dict_get_var_cnt (dict); i++)
401 struct val_labs_iterator *j;
402 struct variable *v = dict_get_var (dict, i);
403 const struct val_labs *val_labs = var_get_value_labels (v);
406 if (val_labs == NULL)
409 buf_write (w, "D", 1);
411 write_string (w, var_get_short_name (v, 0));
412 write_int (w, val_labs_count (val_labs));
414 for (vl = val_labs_first_sorted (val_labs, &j); vl != NULL;
415 vl = val_labs_next (val_labs, &j))
417 write_value (w, &vl->value, v);
418 write_string (w, vl->label);
423 /* Write documents in DICT to portable file W. */
425 write_documents (struct pfm_writer *w, const struct dictionary *dict)
427 size_t line_cnt = dict_get_document_line_cnt (dict);
428 struct string line = DS_EMPTY_INITIALIZER;
431 buf_write (w, "E", 1);
432 write_int (w, line_cnt);
433 for (i = 0; i < line_cnt; i++)
435 dict_get_document_line (dict, i, &line);
436 write_string (w, ds_cstr (&line));
441 /* Writes case C to the portable file represented by WRITER. */
443 por_file_casewriter_write (struct casewriter *writer, void *w_,
446 struct pfm_writer *w = w_;
449 if (!ferror (w->file))
451 for (i = 0; i < w->var_cnt; i++)
453 struct pfm_var *v = &w->vars[i];
456 write_float (w, case_num_idx (c, v->fv));
459 write_int (w, v->width);
460 buf_write (w, case_str_idx (c, v->fv), v->width);
465 casewriter_force_error (writer);
471 por_file_casewriter_destroy (struct casewriter *writer, void *w_)
473 struct pfm_writer *w = w_;
474 if (!close_writer (w))
475 casewriter_force_error (writer);
478 /* Closes a portable file after we're done with it.
479 Returns true if successful, false if an I/O error occurred. */
481 close_writer (struct pfm_writer *w)
492 memset (buf, 'Z', sizeof buf);
493 buf_write (w, buf, w->lc >= 80 ? 80 : 80 - w->lc);
495 ok = !ferror (w->file);
496 if (fclose (w->file) == EOF)
500 msg (ME, _("An I/O error occurred writing portable file \"%s\"."),
501 fh_get_file_name (w->fh));
503 if (ok ? !replace_file_commit (w->rf) : !replace_file_abort (w->rf))
516 /* Base-30 conversion.
518 Portable files represent numbers in base-30 format, so we need
519 to be able to convert real and integer number to that base.
520 Older versions of PSPP used libgmp to do so, but this added a
521 big library dependency to do just one thing. Now we do it
522 ourselves internally.
524 Important fact: base 30 is called "trigesimal". */
526 /* Conversion base. */
527 #define BASE 30 /* As an integer. */
528 #define LDBASE ((long double) BASE) /* As a long double. */
530 /* This is floor(log30(2**31)), the minimum number of trigesimal
531 digits that a `long int' can hold. */
534 /* pow_tab[i] = pow (30, pow (2, i)) */
535 static long double pow_tab[16];
537 /* Initializes pow_tab[]. */
541 static bool did_init = false;
545 /* Only initialize once. */
550 /* Set each element of pow_tab[] until we run out of numerical
553 for (power = 30.0L; power < DBL_MAX; power *= power)
555 assert (i < sizeof pow_tab / sizeof *pow_tab);
556 pow_tab[i++] = power;
560 /* Returns 30**EXPONENT, for 0 <= EXPONENT <= log30(DBL_MAX). */
562 pow30_nonnegative (int exponent)
567 assert (exponent >= 0);
568 assert (exponent < 1L << (sizeof pow_tab / sizeof *pow_tab));
571 for (i = 0; exponent > 0; exponent >>= 1, i++)
578 /* Returns 30**EXPONENT, for log30(DBL_MIN) <= EXPONENT <=
584 return pow30_nonnegative (exponent);
586 return 1.L / pow30_nonnegative (-exponent);
589 /* Returns the character corresponding to TRIG. */
591 trig_to_char (int trig)
593 assert (trig >= 0 && trig < 30);
594 return "0123456789ABCDEFGHIJKLMNOPQRST"[trig];
597 /* Formats the TRIG_CNT trigs in TRIGS[], writing them as
598 null-terminated STRING. The trigesimal point is inserted
599 after TRIG_PLACES characters have been printed, if necessary
600 adding extra zeros at either end for correctness. Returns the
601 character after the formatted number. */
603 format_trig_digits (char *string,
604 const char trigs[], int trig_cnt, int trig_places)
609 while (trig_places++ < 0)
613 while (trig_cnt-- > 0)
615 if (trig_places-- == 0)
617 *string++ = trig_to_char (*trigs++);
619 while (trig_places-- > 0)
625 /* Helper function for format_trig_int() that formats VALUE as a
626 trigesimal integer at CP. VALUE must be nonnegative.
627 Returns the character following the formatted integer. */
629 recurse_format_trig_int (char *cp, int value)
631 int trig = value % BASE;
634 cp = recurse_format_trig_int (cp, value);
635 *cp++ = trig_to_char (trig);
639 /* Formats VALUE as a trigesimal integer in null-terminated
640 STRING[]. VALUE must be in the range -DBL_MAX...DBL_MAX. If
641 FORCE_SIGN is true, a sign is always inserted; otherwise, a
642 sign is only inserted if VALUE is negative. */
644 format_trig_int (int value, bool force_sign, char string[])
655 /* Format integer. */
656 string = recurse_format_trig_int (string, value);
661 /* Determines whether the TRIG_CNT trigesimals in TRIGS[] warrant
662 rounding up or down. Returns true if TRIGS[] represents a
663 value greater than half, false if less than half. If TRIGS[]
664 is exactly half, examines TRIGS[-1] and returns true if odd,
665 false if even ("round to even"). */
667 should_round_up (const char trigs[], int trig_cnt)
669 assert (trig_cnt > 0);
671 if (*trigs < BASE / 2)
673 /* Less than half: round down. */
676 else if (*trigs > BASE / 2)
678 /* Greater than half: round up. */
683 /* Approximately half: look more closely. */
685 for (i = 1; i < trig_cnt; i++)
688 /* Slightly greater than half: round up. */
692 /* Exactly half: round to even. */
693 return trigs[-1] % 2;
697 /* Rounds up the rightmost trig in the TRIG_CNT trigs in TRIGS[],
698 carrying to the left as necessary. Returns true if
699 successful, false on failure (due to a carry out of the
700 leftmost position). */
702 try_round_up (char *trigs, int trig_cnt)
706 char *round_trig = trigs + --trig_cnt;
707 if (*round_trig != BASE - 1)
709 /* Round this trig up to the next value. */
714 /* Carry over to the next trig to the left. */
718 /* Ran out of trigs to carry. */
722 /* Converts VALUE to trigesimal format in string OUTPUT[] with the
723 equivalent of at least BASE_10_PRECISION decimal digits of
724 precision. The output format may use conventional or
725 scientific notation. Missing, infinite, and extreme values
726 are represented with "*.". */
728 format_trig_double (long double value, int base_10_precision, char output[])
730 /* Original VALUE was negative? */
733 /* Number of significant trigesimals. */
734 int base_30_precision;
736 /* Base-2 significand and exponent for original VALUE. */
740 /* VALUE as a set of trigesimals. */
741 char buffer[DBL_DIG + 16];
745 /* Number of trigesimal places for trigs.
746 trigs[0] has coefficient 30**(trig_places - 1),
747 trigs[1] has coefficient 30**(trig_places - 2),
749 In other words, the trigesimal point is just before trigs[0].
753 /* Number of trigesimal places left to write into BUFFER. */
758 /* Handle special cases. */
764 /* Make VALUE positive. */
773 /* Adjust VALUE to roughly 30**3, by shifting the trigesimal
774 point left or right as necessary. We approximate the
775 base-30 exponent by obtaining the base-2 exponent, then
776 multiplying by log30(2). This approximation is sufficient
777 to ensure that the adjusted VALUE is always in the range
778 0...30**6, an invariant of the loop below. */
780 base_2_sig = frexp (value, &base_2_exp);
781 if (errno != 0 || !isfinite (base_2_sig))
783 if (base_2_exp == 0 && base_2_sig == 0.)
785 if (base_2_exp <= INT_MIN / 20379L || base_2_exp >= INT_MAX / 20379L)
787 trig_places = (base_2_exp * 20379L / 100000L) + CHUNK_SIZE / 2;
788 value *= pow30 (CHUNK_SIZE - trig_places);
790 /* Dump all the trigs to buffer[], CHUNK_SIZE at a time. */
793 for (trigs_to_output = DIV_RND_UP (DBL_DIG * 2, 3) + 1 + (CHUNK_SIZE / 2);
795 trigs_to_output -= CHUNK_SIZE)
800 /* The current chunk is just the integer part of VALUE,
801 truncated to the nearest integer. The chunk fits in a
804 assert (pow30 (CHUNK_SIZE) <= LONG_MAX);
805 assert (chunk >= 0 && chunk < pow30 (CHUNK_SIZE));
809 /* Append the chunk, in base 30, to trigs[]. */
810 for (trigs_left = CHUNK_SIZE; chunk > 0 && trigs_left > 0; )
812 trigs[trig_cnt + --trigs_left] = chunk % 30;
815 while (trigs_left > 0)
816 trigs[trig_cnt + --trigs_left] = 0;
817 trig_cnt += CHUNK_SIZE;
819 /* Proceed to the next chunk. */
822 value *= pow (LDBASE, CHUNK_SIZE);
825 /* Strip leading zeros. */
826 while (trig_cnt > 1 && *trigs == 0)
833 /* Round to requested precision, conservatively estimating the
834 required base-30 precision as 2/3 of the base-10 precision
835 (log30(10) = .68). */
836 assert (base_10_precision > 0);
837 if (base_10_precision > LDBL_DIG)
838 base_10_precision = LDBL_DIG;
839 base_30_precision = DIV_RND_UP (base_10_precision * 2, 3);
840 if (trig_cnt > base_30_precision)
842 if (should_round_up (trigs + base_30_precision,
843 trig_cnt - base_30_precision))
845 /* Try to round up. */
846 if (try_round_up (trigs, base_30_precision))
848 /* Rounding up worked. */
849 trig_cnt = base_30_precision;
853 /* Couldn't round up because we ran out of trigs to
854 carry into. Do the carry here instead. */
863 trig_cnt = base_30_precision;
868 /* No rounding required: fewer digits available than
872 /* Strip trailing zeros. */
873 while (trig_cnt > 1 && trigs[trig_cnt - 1] == 0)
879 if (trig_places >= -1 && trig_places < trig_cnt + 3)
881 /* Use conventional notation. */
882 format_trig_digits (output, trigs, trig_cnt, trig_places);
886 /* Use scientific notation. */
888 op = format_trig_digits (output, trigs, trig_cnt, trig_cnt);
889 op = format_trig_int (trig_places - trig_cnt, true, op);
894 strcpy (output, "0");
898 strcpy (output, "*.");
902 static const struct casewriter_class por_file_casewriter_class =
904 por_file_casewriter_write,
905 por_file_casewriter_destroy,