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"
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)
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 struct fh_lock *lock; /* Lock on file handle. */
61 FILE *file; /* File stream. */
62 struct replace_file *rf; /* Ticket for replacing output file. */
64 int lc; /* Number of characters on this line so far. */
66 size_t var_cnt; /* Number of variables. */
67 struct pfm_var *vars; /* Variables. */
69 int digits; /* Digits of precision. */
72 /* A variable to write to the portable file. */
75 int width; /* 0=numeric, otherwise string var width. */
76 int fv; /* Starting case index. */
79 static struct casewriter_class por_file_casewriter_class;
81 static bool close_writer (struct pfm_writer *);
82 static void buf_write (struct pfm_writer *, const void *, size_t);
83 static void write_header (struct pfm_writer *);
84 static void write_version_data (struct pfm_writer *);
85 static void write_variables (struct pfm_writer *, struct dictionary *);
86 static void write_value_labels (struct pfm_writer *,
87 const struct dictionary *);
88 static void write_documents (struct pfm_writer *,
89 const struct dictionary *);
91 static void format_trig_double (long double, int base_10_precision, char[]);
92 static char *format_trig_int (int, bool force_sign, char[]);
94 /* Returns default options for writing a portable file. */
95 struct pfm_write_options
96 pfm_writer_default_options (void)
98 struct pfm_write_options opts;
99 opts.create_writeable = true;
100 opts.type = PFM_COMM;
101 opts.digits = DBL_DIG;
105 /* Writes the dictionary DICT to portable file HANDLE according
106 to the given OPTS. Returns nonzero only if successful. DICT
107 will not be modified, except to assign short names. */
109 pfm_open_writer (struct file_handle *fh, struct dictionary *dict,
110 struct pfm_write_options opts)
112 struct pfm_writer *w = NULL;
116 /* Initialize data structures. */
117 w = xmalloc (sizeof *w);
126 w->var_cnt = dict_get_var_cnt (dict);
127 w->vars = xnmalloc (w->var_cnt, sizeof *w->vars);
128 for (i = 0; i < w->var_cnt; i++)
130 const struct variable *dv = dict_get_var (dict, i);
131 struct pfm_var *pv = &w->vars[i];
132 pv->width = MIN (var_get_width (dv), MAX_POR_WIDTH);
133 pv->fv = var_get_case_index (dv);
136 w->digits = opts.digits;
139 msg (ME, _("Invalid decimal digits count %d. Treating as %d."),
145 w->lock = fh_lock (fh, FH_REF_FILE, "portable file", FH_ACC_WRITE, true);
150 mode = S_IRUSR | S_IRGRP | S_IROTH;
151 if (opts.create_writeable)
152 mode |= S_IWUSR | S_IWGRP | S_IWOTH;
153 w->rf = replace_file_start (fh_get_file_name (fh), "w", mode,
157 msg (ME, _("Error opening \"%s\" for writing as a portable file: %s."),
158 fh_get_file_name (fh), strerror (errno));
162 /* Write file header. */
164 write_version_data (w);
165 write_variables (w, dict);
166 write_value_labels (w, dict);
167 if (dict_get_document_line_cnt (dict) > 0)
168 write_documents (w, dict);
169 buf_write (w, "F", 1);
170 if (ferror (w->file))
172 return casewriter_create (dict_get_next_value_idx (dict),
173 &por_file_casewriter_class, w);
180 /* Write NBYTES starting at BUF to the portable file represented by
181 H. Break lines properly every 80 characters. */
183 buf_write (struct pfm_writer *w, const void *buf_, size_t nbytes)
185 const char *buf = buf_;
187 if (ferror (w->file))
190 assert (buf != NULL);
191 while (nbytes + w->lc >= 80)
193 size_t n = 80 - w->lc;
196 fwrite (buf, n, 1, w->file);
197 fwrite ("\r\n", 2, 1, w->file);
203 fwrite (buf, nbytes, 1, w->file);
208 /* Write D to the portable file as a floating-point field. */
210 write_float (struct pfm_writer *w, double d)
213 format_trig_double (d, floor (d) == d ? DBL_DIG : w->digits, buffer);
214 buf_write (w, buffer, strlen (buffer));
215 buf_write (w, "/", 1);
218 /* Write N to the portable file as an integer field. */
220 write_int (struct pfm_writer *w, int n)
223 format_trig_int (n, false, buffer);
224 buf_write (w, buffer, strlen (buffer));
225 buf_write (w, "/", 1);
228 /* Write S to the portable file as a string field. */
230 write_string (struct pfm_writer *w, const char *s)
232 size_t n = strlen (s);
233 write_int (w, (int) n);
237 /* Write file header. */
239 write_header (struct pfm_writer *w)
241 static const char spss2ascii[256] =
243 "0000000000000000000000000000000000000000000000000000000000000000"
244 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ."
245 "<(+|&[]!$*);^-/|,%_>?`:$@'=\"000000~-0000123456789000-()0{}\\00000"
246 "0000000000000000000000000000000000000000000000000000000000000000"
250 for (i = 0; i < 5; i++)
251 buf_write (w, "ASCII SPSS PORT FILE ", 40);
253 buf_write (w, spss2ascii, 256);
254 buf_write (w, "SPSSPORT", 8);
257 /* Writes version, date, and identification records. */
259 write_version_data (struct pfm_writer *w)
267 if ((time_t) -1 == time (&t))
269 tm.tm_sec = tm.tm_min = tm.tm_hour = tm.tm_mon = tm.tm_year = 0;
274 tmp = localtime (&t);
276 sprintf (date_str, "%04d%02d%02d",
277 tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday);
278 sprintf (time_str, "%02d%02d%02d", tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
279 buf_write (w, "A", 1);
280 write_string (w, date_str);
281 write_string (w, time_str);
283 /* Product identification. */
284 buf_write (w, "1", 1);
285 write_string (w, version);
287 /* Subproduct identification. */
288 buf_write (w, "3", 1);
289 write_string (w, host_system);
292 /* Write format F to file H. The format is first resized to fit
293 a value of the given WIDTH, which is handy in case F
294 represents a string longer than 255 bytes and thus WIDTH is
295 truncated to 255 bytes. */
297 write_format (struct pfm_writer *w, struct fmt_spec f, int width)
299 fmt_resize (&f, width);
300 write_int (w, fmt_to_io (f.type));
305 /* Write value V for variable VV to file H. */
307 write_value (struct pfm_writer *w, union value *v, struct variable *vv)
309 if (var_is_numeric (vv))
310 write_float (w, v->f);
313 int width = MIN (var_get_width (vv), MAX_POR_WIDTH);
314 write_int (w, width);
315 buf_write (w, v->s, width);
319 /* Write variable records. */
321 write_variables (struct pfm_writer *w, struct dictionary *dict)
325 short_names_assign (dict);
327 if (dict_get_weight (dict) != NULL)
329 buf_write (w, "6", 1);
330 write_string (w, var_get_short_name (dict_get_weight (dict), 0));
333 buf_write (w, "4", 1);
334 write_int (w, dict_get_var_cnt (dict));
337 for (i = 0; i < dict_get_var_cnt (dict); i++)
339 struct variable *v = dict_get_var (dict, i);
340 struct missing_values mv;
341 int width = MIN (var_get_width (v), MAX_POR_WIDTH);
343 buf_write (w, "7", 1);
344 write_int (w, width);
345 write_string (w, var_get_short_name (v, 0));
346 write_format (w, *var_get_print_format (v), width);
347 write_format (w, *var_get_write_format (v), width);
349 /* Write missing values. */
350 mv_copy (&mv, var_get_missing_values (v));
351 while (mv_has_range (&mv))
354 mv_pop_range (&mv, &x, &y);
357 buf_write (w, "9", 1);
360 else if (y == HIGHEST)
362 buf_write (w, "A", 1);
367 buf_write (w, "B", 1);
372 while (mv_has_value (&mv))
375 mv_pop_value (&mv, &value);
376 buf_write (w, "8", 1);
377 write_value (w, &value, v);
380 /* Write variable label. */
381 if (var_get_label (v) != NULL)
383 buf_write (w, "C", 1);
384 write_string (w, var_get_label (v));
389 /* Write value labels to disk. FIXME: Inefficient. */
391 write_value_labels (struct pfm_writer *w, const struct dictionary *dict)
395 for (i = 0; i < dict_get_var_cnt (dict); i++)
397 struct val_labs_iterator *j;
398 struct variable *v = dict_get_var (dict, i);
399 const struct val_labs *val_labs = var_get_value_labels (v);
402 if (val_labs == NULL)
405 buf_write (w, "D", 1);
407 write_string (w, var_get_short_name (v, 0));
408 write_int (w, val_labs_count (val_labs));
410 for (vl = val_labs_first_sorted (val_labs, &j); vl != NULL;
411 vl = val_labs_next (val_labs, &j))
413 write_value (w, &vl->value, v);
414 write_string (w, vl->label);
419 /* Write documents in DICT to portable file W. */
421 write_documents (struct pfm_writer *w, const struct dictionary *dict)
423 size_t line_cnt = dict_get_document_line_cnt (dict);
424 struct string line = DS_EMPTY_INITIALIZER;
427 buf_write (w, "E", 1);
428 write_int (w, line_cnt);
429 for (i = 0; i < line_cnt; i++)
431 dict_get_document_line (dict, i, &line);
432 write_string (w, ds_cstr (&line));
437 /* Writes case C to the portable file represented by WRITER. */
439 por_file_casewriter_write (struct casewriter *writer, void *w_,
442 struct pfm_writer *w = w_;
445 if (!ferror (w->file))
447 for (i = 0; i < w->var_cnt; i++)
449 struct pfm_var *v = &w->vars[i];
452 write_float (w, case_num_idx (c, v->fv));
455 write_int (w, v->width);
456 buf_write (w, case_str_idx (c, v->fv), v->width);
461 casewriter_force_error (writer);
467 por_file_casewriter_destroy (struct casewriter *writer, void *w_)
469 struct pfm_writer *w = w_;
470 if (!close_writer (w))
471 casewriter_force_error (writer);
474 /* Closes a portable file after we're done with it.
475 Returns true if successful, false if an I/O error occurred. */
477 close_writer (struct pfm_writer *w)
488 memset (buf, 'Z', sizeof buf);
489 buf_write (w, buf, w->lc >= 80 ? 80 : 80 - w->lc);
491 ok = !ferror (w->file);
492 if (fclose (w->file) == EOF)
496 msg (ME, _("An I/O error occurred writing portable file \"%s\"."),
497 fh_get_file_name (w->fh));
499 if (ok ? !replace_file_commit (w->rf) : !replace_file_abort (w->rf))
512 /* Base-30 conversion.
514 Portable files represent numbers in base-30 format, so we need
515 to be able to convert real and integer number to that base.
516 Older versions of PSPP used libgmp to do so, but this added a
517 big library dependency to do just one thing. Now we do it
518 ourselves internally.
520 Important fact: base 30 is called "trigesimal". */
522 /* Conversion base. */
523 #define BASE 30 /* As an integer. */
524 #define LDBASE ((long double) BASE) /* As a long double. */
526 /* This is floor(log30(2**31)), the minimum number of trigesimal
527 digits that a `long int' can hold. */
530 /* pow_tab[i] = pow (30, pow (2, i)) */
531 static long double pow_tab[16];
533 /* Initializes pow_tab[]. */
537 static bool did_init = false;
541 /* Only initialize once. */
546 /* Set each element of pow_tab[] until we run out of numerical
549 for (power = 30.0L; power < DBL_MAX; power *= power)
551 assert (i < sizeof pow_tab / sizeof *pow_tab);
552 pow_tab[i++] = power;
556 /* Returns 30**EXPONENT, for 0 <= EXPONENT <= log30(DBL_MAX). */
558 pow30_nonnegative (int exponent)
563 assert (exponent >= 0);
564 assert (exponent < 1L << (sizeof pow_tab / sizeof *pow_tab));
567 for (i = 0; exponent > 0; exponent >>= 1, i++)
574 /* Returns 30**EXPONENT, for log30(DBL_MIN) <= EXPONENT <=
580 return pow30_nonnegative (exponent);
582 return 1.L / pow30_nonnegative (-exponent);
585 /* Returns the character corresponding to TRIG. */
587 trig_to_char (int trig)
589 assert (trig >= 0 && trig < 30);
590 return "0123456789ABCDEFGHIJKLMNOPQRST"[trig];
593 /* Formats the TRIG_CNT trigs in TRIGS[], writing them as
594 null-terminated STRING. The trigesimal point is inserted
595 after TRIG_PLACES characters have been printed, if necessary
596 adding extra zeros at either end for correctness. Returns the
597 character after the formatted number. */
599 format_trig_digits (char *string,
600 const char trigs[], int trig_cnt, int trig_places)
605 while (trig_places++ < 0)
609 while (trig_cnt-- > 0)
611 if (trig_places-- == 0)
613 *string++ = trig_to_char (*trigs++);
615 while (trig_places-- > 0)
621 /* Helper function for format_trig_int() that formats VALUE as a
622 trigesimal integer at CP. VALUE must be nonnegative.
623 Returns the character following the formatted integer. */
625 recurse_format_trig_int (char *cp, int value)
627 int trig = value % BASE;
630 cp = recurse_format_trig_int (cp, value);
631 *cp++ = trig_to_char (trig);
635 /* Formats VALUE as a trigesimal integer in null-terminated
636 STRING[]. VALUE must be in the range -DBL_MAX...DBL_MAX. If
637 FORCE_SIGN is true, a sign is always inserted; otherwise, a
638 sign is only inserted if VALUE is negative. */
640 format_trig_int (int value, bool force_sign, char string[])
651 /* Format integer. */
652 string = recurse_format_trig_int (string, value);
657 /* Determines whether the TRIG_CNT trigesimals in TRIGS[] warrant
658 rounding up or down. Returns true if TRIGS[] represents a
659 value greater than half, false if less than half. If TRIGS[]
660 is exactly half, examines TRIGS[-1] and returns true if odd,
661 false if even ("round to even"). */
663 should_round_up (const char trigs[], int trig_cnt)
665 assert (trig_cnt > 0);
667 if (*trigs < BASE / 2)
669 /* Less than half: round down. */
672 else if (*trigs > BASE / 2)
674 /* Greater than half: round up. */
679 /* Approximately half: look more closely. */
681 for (i = 1; i < trig_cnt; i++)
684 /* Slightly greater than half: round up. */
688 /* Exactly half: round to even. */
689 return trigs[-1] % 2;
693 /* Rounds up the rightmost trig in the TRIG_CNT trigs in TRIGS[],
694 carrying to the left as necessary. Returns true if
695 successful, false on failure (due to a carry out of the
696 leftmost position). */
698 try_round_up (char *trigs, int trig_cnt)
702 char *round_trig = trigs + --trig_cnt;
703 if (*round_trig != BASE - 1)
705 /* Round this trig up to the next value. */
710 /* Carry over to the next trig to the left. */
714 /* Ran out of trigs to carry. */
718 /* Converts VALUE to trigesimal format in string OUTPUT[] with the
719 equivalent of at least BASE_10_PRECISION decimal digits of
720 precision. The output format may use conventional or
721 scientific notation. Missing, infinite, and extreme values
722 are represented with "*.". */
724 format_trig_double (long double value, int base_10_precision, char output[])
726 /* Original VALUE was negative? */
729 /* Number of significant trigesimals. */
730 int base_30_precision;
732 /* Base-2 significand and exponent for original VALUE. */
736 /* VALUE as a set of trigesimals. */
737 char buffer[DBL_DIG + 16];
741 /* Number of trigesimal places for trigs.
742 trigs[0] has coefficient 30**(trig_places - 1),
743 trigs[1] has coefficient 30**(trig_places - 2),
745 In other words, the trigesimal point is just before trigs[0].
749 /* Number of trigesimal places left to write into BUFFER. */
754 /* Handle special cases. */
760 /* Make VALUE positive. */
769 /* Adjust VALUE to roughly 30**3, by shifting the trigesimal
770 point left or right as necessary. We approximate the
771 base-30 exponent by obtaining the base-2 exponent, then
772 multiplying by log30(2). This approximation is sufficient
773 to ensure that the adjusted VALUE is always in the range
774 0...30**6, an invariant of the loop below. */
776 base_2_sig = frexp (value, &base_2_exp);
777 if (errno != 0 || !finite (base_2_sig))
779 if (base_2_exp == 0 && base_2_sig == 0.)
781 if (base_2_exp <= INT_MIN / 20379L || base_2_exp >= INT_MAX / 20379L)
783 trig_places = (base_2_exp * 20379L / 100000L) + CHUNK_SIZE / 2;
784 value *= pow30 (CHUNK_SIZE - trig_places);
786 /* Dump all the trigs to buffer[], CHUNK_SIZE at a time. */
789 for (trigs_to_output = DIV_RND_UP (DBL_DIG * 2, 3) + 1 + (CHUNK_SIZE / 2);
791 trigs_to_output -= CHUNK_SIZE)
796 /* The current chunk is just the integer part of VALUE,
797 truncated to the nearest integer. The chunk fits in a
800 assert (pow30 (CHUNK_SIZE) <= LONG_MAX);
801 assert (chunk >= 0 && chunk < pow30 (CHUNK_SIZE));
805 /* Append the chunk, in base 30, to trigs[]. */
806 for (trigs_left = CHUNK_SIZE; chunk > 0 && trigs_left > 0; )
808 trigs[trig_cnt + --trigs_left] = chunk % 30;
811 while (trigs_left > 0)
812 trigs[trig_cnt + --trigs_left] = 0;
813 trig_cnt += CHUNK_SIZE;
815 /* Proceed to the next chunk. */
818 value *= pow (LDBASE, CHUNK_SIZE);
821 /* Strip leading zeros. */
822 while (trig_cnt > 1 && *trigs == 0)
829 /* Round to requested precision, conservatively estimating the
830 required base-30 precision as 2/3 of the base-10 precision
831 (log30(10) = .68). */
832 assert (base_10_precision > 0);
833 if (base_10_precision > LDBL_DIG)
834 base_10_precision = LDBL_DIG;
835 base_30_precision = DIV_RND_UP (base_10_precision * 2, 3);
836 if (trig_cnt > base_30_precision)
838 if (should_round_up (trigs + base_30_precision,
839 trig_cnt - base_30_precision))
841 /* Try to round up. */
842 if (try_round_up (trigs, base_30_precision))
844 /* Rounding up worked. */
845 trig_cnt = base_30_precision;
849 /* Couldn't round up because we ran out of trigs to
850 carry into. Do the carry here instead. */
859 trig_cnt = base_30_precision;
864 /* No rounding required: fewer digits available than
868 /* Strip trailing zeros. */
869 while (trig_cnt > 1 && trigs[trig_cnt - 1] == 0)
875 if (trig_places >= -1 && trig_places < trig_cnt + 3)
877 /* Use conventional notation. */
878 format_trig_digits (output, trigs, trig_cnt, trig_places);
882 /* Use scientific notation. */
884 op = format_trig_digits (output, trigs, trig_cnt, trig_cnt);
885 op = format_trig_int (trig_places - trig_cnt, true, op);
890 strcpy (output, "0");
894 strcpy (output, "*.");
898 static struct casewriter_class por_file_casewriter_class =
900 por_file_casewriter_write,
901 por_file_casewriter_destroy,