1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-2000, 2006-2014 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/>. */
19 #include "data/sys-file-writer.h"
20 #include "data/sys-file-private.h"
30 #include "data/attributes.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/make-file.h"
38 #include "data/missing-values.h"
39 #include "data/mrset.h"
40 #include "data/settings.h"
41 #include "data/short-names.h"
42 #include "data/value-labels.h"
43 #include "data/variable.h"
44 #include "data/varset.h"
45 #include "libpspp/float-format.h"
46 #include "libpspp/i18n.h"
47 #include "libpspp/integer-format.h"
48 #include "libpspp/message.h"
49 #include "libpspp/misc.h"
50 #include "libpspp/str.h"
51 #include "libpspp/string-array.h"
52 #include "libpspp/version.h"
54 #include "gl/xmemdup0.h"
55 #include "gl/minmax.h"
56 #include "gl/unlocked-io.h"
57 #include "gl/xalloc.h"
60 #define _(msgid) gettext (msgid)
61 #define N_(msgid) (msgid)
63 /* Compression bias used by PSPP. Values between (1 -
64 COMPRESSION_BIAS) and (251 - COMPRESSION_BIAS) inclusive can be
66 #define COMPRESSION_BIAS 100
68 /* System file writer. */
71 struct file_handle *fh; /* File handle. */
72 struct fh_lock *lock; /* Mutual exclusion for file. */
73 FILE *file; /* File stream. */
74 struct replace_file *rf; /* Ticket for replacing output file. */
76 enum any_compression compression;
77 casenumber n_cases; /* Number of cases written so far. */
78 uint8_t space; /* ' ' in the file's character encoding. */
80 /* Simple compression buffering.
82 Compressed data is output as a series of 8-byte elements, with 1 to 9
83 such elements clustered together. The first element in a cluster is 8
84 1-byte opcodes. Some opcodes call for an additional element in the
85 cluster (hence, if there are eight such opcodes, then the cluster
86 contains a full 9 elements).
88 cbuf[] holds a cluster at a time. */
90 int n_opcodes; /* Number of opcodes in cbuf[0] so far. */
91 int n_elements; /* Number of elements in cbuf[] so far. */
93 /* ZLIB compression. */
94 z_stream zstream; /* ZLIB deflater. */
96 struct zblock *blocks;
97 size_t n_blocks, allocated_blocks;
100 struct sfm_var *sfm_vars; /* Variables. */
101 size_t sfm_n_vars; /* Number of variables. */
102 size_t n_segments; /* Number of variables including extra segments
103 for long string variables. */
108 unsigned int uncompressed_size;
109 unsigned int compressed_size;
112 static const struct casewriter_class sys_file_casewriter_class;
114 static void write_header (struct sfm_writer *, const struct dictionary *);
115 static void write_variable (struct sfm_writer *, const struct variable *);
116 static void write_value_labels (struct sfm_writer *,
117 const struct dictionary *);
118 static void write_integer_info_record (struct sfm_writer *,
119 const struct dictionary *);
120 static void write_float_info_record (struct sfm_writer *);
122 static void write_longvar_table (struct sfm_writer *w,
123 const struct dictionary *dict);
125 static void write_encoding_record (struct sfm_writer *w,
126 const struct dictionary *);
128 static void write_vls_length_table (struct sfm_writer *w,
129 const struct dictionary *dict);
131 static void write_long_string_value_labels (struct sfm_writer *,
132 const struct dictionary *);
133 static void write_long_string_missing_values (struct sfm_writer *,
134 const struct dictionary *);
136 static void write_varsets (struct sfm_writer *, const struct dictionary *);
137 static void write_mrsets (struct sfm_writer *, const struct dictionary *,
140 static void write_variable_display_parameters (struct sfm_writer *w,
141 const struct dictionary *dict);
143 static void write_documents (struct sfm_writer *, const struct dictionary *);
145 static void write_data_file_attributes (struct sfm_writer *,
146 const struct dictionary *);
147 static void write_variable_attributes (struct sfm_writer *,
148 const struct dictionary *);
150 static void write_int (struct sfm_writer *, int32_t);
151 static void write_int64 (struct sfm_writer *, int64_t);
152 static inline void convert_double_to_output_format (double, uint8_t[8]);
153 static void write_float (struct sfm_writer *, double);
154 static void write_string (struct sfm_writer *, const char *, size_t);
155 static void write_utf8_string (struct sfm_writer *, const char *encoding,
156 const char *string, size_t width);
157 static void write_utf8_record (struct sfm_writer *, const char *encoding,
158 const struct string *content, int subtype);
159 static void write_string_record (struct sfm_writer *,
160 const struct substring content, int subtype);
161 static void write_bytes (struct sfm_writer *, const void *, size_t);
162 static void write_zeros (struct sfm_writer *, size_t);
163 static void write_spaces (struct sfm_writer *, size_t);
164 static void write_value (struct sfm_writer *, const union value *, int width);
166 static void write_case_uncompressed (struct sfm_writer *,
167 const struct ccase *);
168 static void write_case_compressed (struct sfm_writer *, const struct ccase *);
169 static void flush_compressed (struct sfm_writer *);
170 static void put_cmp_opcode (struct sfm_writer *, uint8_t);
171 static void put_cmp_number (struct sfm_writer *, double);
172 static void put_cmp_string (struct sfm_writer *, const void *, size_t);
174 static bool start_zstream (struct sfm_writer *);
175 static void finish_zstream (struct sfm_writer *);
176 static void write_ztrailer (struct sfm_writer *);
178 static bool write_error (const struct sfm_writer *);
179 static bool close_writer (struct sfm_writer *);
181 /* Returns default options for writing a system file. */
182 struct sfm_write_options
183 sfm_writer_default_options (void)
185 struct sfm_write_options opts;
186 opts.compression = (settings_get_scompression ()
189 opts.create_writeable = true;
194 /* Opens the system file designated by file handle FH for writing
195 cases from dictionary D according to the given OPTS.
197 No reference to D is retained, so it may be modified or
198 destroyed at will after this function returns. D is not
199 modified by this function, except to assign short names. */
201 sfm_open_writer (struct file_handle *fh, struct dictionary *d,
202 struct sfm_write_options opts)
204 struct encoding_info encoding_info;
209 if (opts.version != 2 && opts.version != 3)
211 msg (ME, _("Unknown system file version %d. Treating as version %d."),
216 /* Create and initialize writer. */
217 struct sfm_writer *w = XZALLOC (struct sfm_writer);
223 /* Use the requested compression, except that no EBCDIC-based ZLIB compressed
224 files have been observed, so drop back to simple compression for those
226 w->compression = opts.compression;
227 if (w->compression == ANY_COMP_ZLIB
228 && is_encoding_ebcdic_compatible (dict_get_encoding (d)))
229 w->compression = ANY_COMP_SIMPLE;
233 w->n_opcodes = w->n_elements = 0;
234 memset (w->cbuf[0], 0, 8);
236 /* Figure out how to map in-memory case data to on-disk case
237 data. Also count the number of segments. Very long strings
238 occupy multiple segments, otherwise each variable only takes
240 w->n_segments = sfm_dictionary_to_sfm_vars (d, &w->sfm_vars, &w->sfm_n_vars);
242 /* Open file handle as an exclusive writer. */
243 /* TRANSLATORS: this fragment will be interpolated into
244 messages in fh_lock() that identify types of files. */
245 w->lock = fh_lock (fh, FH_REF_FILE, N_("system file"), FH_ACC_WRITE, true);
249 /* Create the file on disk. */
251 if (opts.create_writeable)
253 w->rf = replace_file_start (fh, "wb", mode, &w->file);
256 msg (ME, _("Error opening `%s' for writing as a system file: %s."),
257 fh_get_file_name (fh), strerror (errno));
261 get_encoding_info (&encoding_info, dict_get_encoding (d));
262 w->space = encoding_info.space[0];
264 /* Write the file header. */
267 /* Write basic variable info. */
268 short_names_assign (d);
269 for (i = 0; i < dict_get_n_vars (d); i++)
270 write_variable (w, dict_get_var (d, i));
272 write_value_labels (w, d);
274 if (dict_get_document_n_lines (d) > 0)
275 write_documents (w, d);
277 write_integer_info_record (w, d);
278 write_float_info_record (w);
280 write_varsets (w, d);
281 write_mrsets (w, d, true);
283 write_variable_display_parameters (w, d);
285 if (opts.version >= 3)
286 write_longvar_table (w, d);
288 write_vls_length_table (w, d);
290 write_long_string_value_labels (w, d);
291 write_long_string_missing_values (w, d);
293 if (opts.version >= 3)
295 if (attrset_count (dict_get_attributes (d)))
296 write_data_file_attributes (w, d);
297 write_variable_attributes (w, d);
300 write_mrsets (w, d, false);
302 write_encoding_record (w, d);
304 /* Write end-of-headers record. */
308 if (w->compression == ANY_COMP_ZLIB)
310 w->zstream.zalloc = Z_NULL;
311 w->zstream.zfree = Z_NULL;
312 w->zstream.opaque = Z_NULL;
313 w->zstart = ftello (w->file);
315 write_int64 (w, w->zstart);
325 return casewriter_create (dict_get_proto (d), &sys_file_casewriter_class, w);
332 /* Returns value of X truncated to two least-significant digits. */
343 /* Calculates the offset of data for TARGET_VAR from the
344 beginning of each case's data for dictionary D. The return
345 value is in "octs" (8-byte units). */
347 calc_oct_idx (const struct dictionary *d, struct variable *target_var)
353 for (i = 0; i < dict_get_n_vars (d); i++)
355 struct variable *var = dict_get_var (d, i);
356 if (var == target_var)
358 oct_idx += sfm_width_to_octs (var_get_width (var));
363 /* Write the sysfile_header header to system file W. */
365 write_header (struct sfm_writer *w, const struct dictionary *d)
367 const char *dict_encoding = dict_get_encoding (d);
369 const char *file_label;
370 struct variable *weight;
374 /* Record-type code. */
375 if (is_encoding_ebcdic_compatible (dict_encoding))
376 write_string (w, EBCDIC_MAGIC, 4);
377 else if (w->compression == ANY_COMP_ZLIB)
378 write_string (w, ASCII_ZMAGIC, 4);
380 write_string (w, ASCII_MAGIC, 4);
382 /* Product identification. */
383 snprintf (prod_name, sizeof prod_name, "@(#) SPSS DATA FILE %s - %s",
384 version, host_system);
385 write_utf8_string (w, dict_encoding, prod_name, 60);
390 /* Number of `union value's per case. */
391 write_int (w, calc_oct_idx (d, NULL));
394 write_int (w, (w->compression == ANY_COMP_NONE ? 0
395 : w->compression == ANY_COMP_SIMPLE ? 1
398 /* Weight variable. */
399 weight = dict_get_weight (d);
400 write_int (w, weight != NULL ? calc_oct_idx (d, weight) + 1 : 0);
402 /* Number of cases. We don't know this in advance, so we write
403 -1 to indicate an unknown number of cases. Later we can
404 come back and overwrite it with the true value. */
407 /* Compression bias. */
408 write_float (w, COMPRESSION_BIAS);
410 /* Creation date and time. */
411 char *creation_date, *creation_time;
412 if (time (&t) == (time_t) -1)
414 creation_date = xstrdup ("01 Jan 70");
415 creation_time = xstrdup ("00:00:00");
419 static const char *const month_name[12] =
421 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
422 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
424 struct tm *tmp = localtime (&t);
425 int day = rerange (tmp->tm_mday);
426 int mon = rerange (tmp->tm_mon + 1);
427 int year = rerange (tmp->tm_year);
428 int hour = rerange (tmp->tm_hour + 1);
429 int min = rerange (tmp->tm_min + 1);
430 int sec = rerange (tmp->tm_sec + 1);
432 creation_date = xasprintf ("%02d %s %02d",
433 day, month_name[mon - 1], year);
434 creation_time = xasprintf ("%02d:%02d:%02d", hour - 1, min - 1, sec - 1);
436 write_utf8_string (w, dict_encoding, creation_date, 9);
437 write_utf8_string (w, dict_encoding, creation_time, 8);
438 free (creation_time);
439 free (creation_date);
442 file_label = dict_get_label (d);
443 if (file_label == NULL)
445 write_utf8_string (w, dict_encoding, file_label, 64);
451 /* Write format spec FMT to W, after adjusting it to be
452 compatible with the given WIDTH. */
454 write_format (struct sfm_writer *w, struct fmt_spec fmt, int width)
456 assert (fmt_check_output (fmt));
457 assert (sfm_width_to_segments (width) == 1);
460 fmt_resize (&fmt, width);
461 write_int (w, (fmt_to_io (fmt.type) << 16) | (fmt.w << 8) | fmt.d);
464 /* Write a string continuation variable record for each 8-byte
465 section beyond the initial 8 bytes, for a variable of the
468 write_variable_continuation_records (struct sfm_writer *w, int width)
472 assert (sfm_width_to_segments (width) == 1);
473 for (position = 8; position < width; position += 8)
475 write_int (w, 2); /* Record type. */
476 write_int (w, -1); /* Width. */
477 write_int (w, 0); /* No variable label. */
478 write_int (w, 0); /* No missing values. */
479 write_int (w, 0); /* Print format. */
480 write_int (w, 0); /* Write format. */
481 write_zeros (w, 8); /* Name. */
485 /* Write the variable record(s) for variable V to system file
488 write_variable (struct sfm_writer *w, const struct variable *v)
490 int width = var_get_width (v);
491 int n_segments = sfm_width_to_segments (width);
492 int seg0_width = sfm_segment_alloc_width (width, 0);
493 const char *encoding = var_get_encoding (v);
500 write_int (w, seg0_width);
502 /* Variable has a variable label? */
503 write_int (w, var_has_label (v));
505 /* Number of missing values. If there is a range, then the
506 range counts as 2 missing values and causes the number to be
509 Missing values for long string variables are written in a separate
511 enum { MAX_SHORT_STRING = 8 };
512 if (width <= MAX_SHORT_STRING)
514 const struct missing_values *mv = var_get_missing_values (v);
515 if (mv_has_range (mv))
516 write_int (w, -2 - mv_n_values (mv));
518 write_int (w, mv_n_values (mv));
523 /* Print and write formats. */
524 write_format (w, var_get_print_format (v), seg0_width);
525 write_format (w, var_get_write_format (v), seg0_width);
528 The full name is in a translation table written
530 write_utf8_string (w, encoding, var_get_short_name (v, 0), 8);
533 if (var_has_label (v))
535 char *label = recode_string (encoding, UTF8, var_get_label (v), -1);
536 size_t label_len = MIN (strlen (label), 255);
537 size_t padded_len = ROUND_UP (label_len, 4);
538 write_int (w, label_len);
539 write_string (w, label, padded_len);
543 /* Write the missing values, if any, range first. */
544 if (width <= MAX_SHORT_STRING)
546 const struct missing_values *mv = var_get_missing_values (v);
547 if (mv_has_range (mv))
550 mv_get_range (mv, &x, &y);
554 for (i = 0; i < mv_n_values (mv); i++)
555 write_value (w, mv_get_value (mv, i), width);
558 write_variable_continuation_records (w, seg0_width);
560 /* Write additional segments for very long string variables. */
561 for (i = 1; i < n_segments; i++)
563 int seg_width = sfm_segment_alloc_width (width, i);
564 struct fmt_spec fmt = fmt_for_output (FMT_A, MAX (seg_width, 1), 0);
566 write_int (w, 2); /* Variable record. */
567 write_int (w, seg_width); /* Width. */
568 write_int (w, 0); /* No variable label. */
569 write_int (w, 0); /* No missing values. */
570 write_format (w, fmt, seg_width); /* Print format. */
571 write_format (w, fmt, seg_width); /* Write format. */
572 write_utf8_string (w, encoding, var_get_short_name (v, i), 8);
574 write_variable_continuation_records (w, seg_width);
578 /* Writes the value labels to system file W.
580 Value labels for long string variables are written separately,
581 by write_long_string_value_labels. */
583 write_value_labels (struct sfm_writer *w, const struct dictionary *d)
587 struct hmap_node hmap_node;
588 const struct val_labs *val_labs;
590 size_t n_indexes, allocated_indexes;
593 size_t n_sets, allocated_sets;
594 struct label_set **sets;
595 struct hmap same_sets;
599 n_sets = allocated_sets = 0;
601 hmap_init (&same_sets);
604 for (i = 0; i < dict_get_n_vars (d); i++)
606 struct variable *v = dict_get_var (d, i);
608 if (var_has_value_labels (v) && var_get_width (v) <= 8)
610 const struct val_labs *val_labs = var_get_value_labels (v);
611 unsigned int hash = val_labs_hash (val_labs, 0);
612 struct label_set *set;
614 HMAP_FOR_EACH_WITH_HASH (set, struct label_set, hmap_node,
617 if (val_labs_equal (set->val_labs, val_labs))
619 if (set->n_indexes >= set->allocated_indexes)
620 set->indexes = x2nrealloc (set->indexes,
621 &set->allocated_indexes,
622 sizeof *set->indexes);
623 set->indexes[set->n_indexes++] = idx;
628 set = xmalloc (sizeof *set);
629 set->val_labs = val_labs;
630 set->indexes = xmalloc (sizeof *set->indexes);
631 set->indexes[0] = idx;
633 set->allocated_indexes = 1;
634 hmap_insert (&same_sets, &set->hmap_node, hash);
636 if (n_sets >= allocated_sets)
637 sets = x2nrealloc (sets, &allocated_sets, sizeof *sets);
638 sets[n_sets++] = set;
642 idx += sfm_width_to_octs (var_get_width (v));
645 for (i = 0; i < n_sets; i++)
647 const struct label_set *set = sets[i];
648 const struct val_labs *val_labs = set->val_labs;
649 size_t n_labels = val_labs_count (val_labs);
650 int width = val_labs_get_width (val_labs);
651 const struct val_lab **labels;
654 /* Value label record. */
655 write_int (w, 3); /* Record type. */
656 write_int (w, n_labels);
657 labels = val_labs_sorted (val_labs);
658 for (j = 0; j < n_labels; j++)
660 const struct val_lab *vl = labels[j];
661 char *label = recode_string (dict_get_encoding (d), UTF8,
662 val_lab_get_escaped_label (vl), -1);
663 uint8_t len = MIN (strlen (label), 255);
665 write_value (w, val_lab_get_value (vl), width);
666 write_bytes (w, &len, 1);
667 write_bytes (w, label, len);
668 write_zeros (w, REM_RND_UP (len + 1, 8));
673 /* Value label variable record. */
674 write_int (w, 4); /* Record type. */
675 write_int (w, set->n_indexes);
676 for (j = 0; j < set->n_indexes; j++)
677 write_int (w, set->indexes[j] + 1);
680 for (i = 0; i < n_sets; i++)
682 struct label_set *set = sets[i];
688 hmap_destroy (&same_sets);
691 /* Writes record type 6, document record. */
693 write_documents (struct sfm_writer *w, const struct dictionary *d)
695 const struct string_array *docs = dict_get_documents (d);
696 const char *enc = dict_get_encoding (d);
699 write_int (w, 6); /* Record type. */
700 write_int (w, docs->n);
701 for (i = 0; i < docs->n; i++)
703 char *s = recode_string (enc, "UTF-8", docs->strings[i], -1);
704 size_t s_len = strlen (s);
705 size_t write_len = MIN (s_len, DOC_LINE_LENGTH);
707 write_bytes (w, s, write_len);
708 write_spaces (w, DOC_LINE_LENGTH - write_len);
714 put_attrset (struct string *string, const struct attrset *attrs)
716 const struct attribute *attr;
717 struct attrset_iterator i;
719 for (attr = attrset_first (attrs, &i); attr != NULL;
720 attr = attrset_next (attrs, &i))
722 size_t n_values = attribute_get_n_values (attr);
725 ds_put_cstr (string, attribute_get_name (attr));
726 ds_put_byte (string, '(');
727 for (j = 0; j < n_values; j++)
728 ds_put_format (string, "'%s'\n", attribute_get_value (attr, j));
729 ds_put_byte (string, ')');
734 write_data_file_attributes (struct sfm_writer *w,
735 const struct dictionary *d)
737 struct string s = DS_EMPTY_INITIALIZER;
738 put_attrset (&s, dict_get_attributes (d));
739 write_utf8_record (w, dict_get_encoding (d), &s, 17);
744 add_role_attribute (enum var_role role, struct attrset *attrs)
746 struct attribute *attr;
776 attrset_delete (attrs, "$@Role");
778 attr = attribute_create ("$@Role");
779 attribute_add_value (attr, s);
780 attrset_add (attrs, attr);
784 write_variable_attributes (struct sfm_writer *w, const struct dictionary *d)
786 struct string s = DS_EMPTY_INITIALIZER;
787 size_t n_vars = dict_get_n_vars (d);
788 size_t n_attrsets = 0;
791 for (i = 0; i < n_vars; i++)
793 struct variable *v = dict_get_var (d, i);
794 struct attrset attrs;
796 attrset_clone (&attrs, var_get_attributes (v));
798 add_role_attribute (var_get_role (v), &attrs);
800 ds_put_byte (&s, '/');
801 ds_put_format (&s, "%s:", var_get_name (v));
802 put_attrset (&s, &attrs);
803 attrset_destroy (&attrs);
806 write_utf8_record (w, dict_get_encoding (d), &s, 18);
810 /* Write variable sets. */
812 write_varsets (struct sfm_writer *w, const struct dictionary *dict)
814 const char *encoding = dict_get_encoding (dict);
816 if (is_encoding_ebcdic_compatible (encoding))
822 size_t n_varsets = dict_get_n_varsets (dict);
826 struct string s = DS_EMPTY_INITIALIZER;
827 for (size_t i = 0; i < n_varsets; i++)
829 const struct varset *varset = dict_get_varset (dict, i);
831 char *name = recode_string (encoding, "UTF-8", varset->name, -1);
832 ds_put_format (&s, "%s= ", name);
835 for (size_t j = 0; j < varset->n_vars; j++)
838 ds_put_byte (&s, ' ');
840 const char *name_utf8 = var_get_name (varset->vars[j]);
841 char *name = recode_string (encoding, "UTF-8", name_utf8, -1);
842 ds_put_cstr (&s, name);
845 ds_put_byte (&s, '\n');
848 if (!ds_is_empty (&s))
849 write_string_record (w, ds_ss (&s), 5);
853 /* Write multiple response sets. If PRE_V14 is true, writes sets supported by
854 SPSS before release 14, otherwise writes sets supported only by later
857 write_mrsets (struct sfm_writer *w, const struct dictionary *dict,
860 const char *encoding = dict_get_encoding (dict);
861 struct string s = DS_EMPTY_INITIALIZER;
865 if (is_encoding_ebcdic_compatible (encoding))
871 n_mrsets = dict_get_n_mrsets (dict);
875 for (i = 0; i < n_mrsets; i++)
877 const struct mrset *mrset = dict_get_mrset (dict, i);
881 if ((mrset->type != MRSET_MD || mrset->cat_source != MRSET_COUNTEDVALUES)
885 name = recode_string (encoding, "UTF-8", mrset->name, -1);
886 ds_put_format (&s, "%s=", name);
889 if (mrset->type == MRSET_MD)
893 if (mrset->cat_source == MRSET_COUNTEDVALUES)
894 ds_put_format (&s, "E %d ", mrset->label_from_var_label ? 11 : 1);
896 ds_put_byte (&s, 'D');
898 if (mrset->width == 0)
899 counted = xasprintf ("%.0f", mrset->counted.f);
901 counted = xmemdup0 (mrset->counted.s, mrset->width);
902 ds_put_format (&s, "%zu %s", strlen (counted), counted);
906 ds_put_byte (&s, 'C');
907 ds_put_byte (&s, ' ');
909 if (mrset->label && !mrset->label_from_var_label)
911 char *label = recode_string (encoding, "UTF-8", mrset->label, -1);
912 ds_put_format (&s, "%zu %s", strlen (label), label);
916 ds_put_cstr (&s, "0 ");
918 for (j = 0; j < mrset->n_vars; j++)
920 const char *short_name_utf8 = var_get_short_name (mrset->vars[j], 0);
921 char *lower_name_utf8 = utf8_to_lower (short_name_utf8);
922 char *short_name = recode_string (encoding, "UTF-8",
923 lower_name_utf8, -1);
924 ds_put_format (&s, " %s", short_name);
926 free (lower_name_utf8);
928 ds_put_byte (&s, '\n');
931 if (!ds_is_empty (&s))
932 write_string_record (w, ds_ss (&s), pre_v14 ? 7 : 19);
936 /* Write the alignment, width and scale values. */
938 write_variable_display_parameters (struct sfm_writer *w,
939 const struct dictionary *dict)
943 write_int (w, 7); /* Record type. */
944 write_int (w, 11); /* Record subtype. */
945 write_int (w, 4); /* Data item (int32) size. */
946 write_int (w, w->n_segments * 3); /* Number of data items. */
948 for (i = 0; i < dict_get_n_vars (dict); ++i)
950 struct variable *v = dict_get_var (dict, i);
951 int width = var_get_width (v);
952 int n_segments = sfm_width_to_segments (width);
953 int measure = (var_get_measure (v) == MEASURE_NOMINAL ? 1
954 : var_get_measure (v) == MEASURE_ORDINAL ? 2
956 int alignment = (var_get_alignment (v) == ALIGN_LEFT ? 0
957 : var_get_alignment (v) == ALIGN_RIGHT ? 1
961 for (i = 0; i < n_segments; i++)
963 int width_left = width - sfm_segment_effective_offset (width, i);
964 write_int (w, measure);
965 write_int (w, (i == 0 ? var_get_display_width (v)
966 : var_default_display_width (width_left)));
967 write_int (w, alignment);
972 /* Writes the table of lengths for very long string variables. */
974 write_vls_length_table (struct sfm_writer *w,
975 const struct dictionary *dict)
980 ds_init_empty (&map);
981 for (i = 0; i < dict_get_n_vars (dict); ++i)
983 const struct variable *v = dict_get_var (dict, i);
984 if (sfm_width_to_segments (var_get_width (v)) > 1)
985 ds_put_format (&map, "%s=%05d%c\t",
986 var_get_short_name (v, 0), var_get_width (v), 0);
988 if (!ds_is_empty (&map))
989 write_utf8_record (w, dict_get_encoding (dict), &map, 14);
994 write_long_string_value_labels (struct sfm_writer *w,
995 const struct dictionary *dict)
997 const char *encoding = dict_get_encoding (dict);
998 size_t n_vars = dict_get_n_vars (dict);
1001 /* Figure out the size in advance. */
1003 for (i = 0; i < n_vars; i++)
1005 struct variable *var = dict_get_var (dict, i);
1006 const struct val_labs *val_labs = var_get_value_labels (var);
1007 int width = var_get_width (var);
1008 const struct val_lab *val_lab;
1010 if (val_labs_count (val_labs) == 0 || width < 9)
1014 size += recode_string_len (encoding, "UTF-8", var_get_name (var), -1);
1015 for (val_lab = val_labs_first (val_labs); val_lab != NULL;
1016 val_lab = val_labs_next (val_labs, val_lab))
1019 size += recode_string_len (encoding, "UTF-8",
1020 val_lab_get_escaped_label (val_lab), -1);
1026 write_int (w, 7); /* Record type. */
1027 write_int (w, 21); /* Record subtype */
1028 write_int (w, 1); /* Data item (byte) size. */
1029 write_int (w, size); /* Number of data items. */
1031 for (i = 0; i < n_vars; i++)
1033 struct variable *var = dict_get_var (dict, i);
1034 const struct val_labs *val_labs = var_get_value_labels (var);
1035 int width = var_get_width (var);
1036 const struct val_lab *val_lab;
1039 if (val_labs_count (val_labs) == 0 || width < 9)
1042 var_name = recode_string (encoding, "UTF-8", var_get_name (var), -1);
1043 write_int (w, strlen (var_name));
1044 write_bytes (w, var_name, strlen (var_name));
1047 write_int (w, width);
1048 write_int (w, val_labs_count (val_labs));
1049 for (val_lab = val_labs_first (val_labs); val_lab != NULL;
1050 val_lab = val_labs_next (val_labs, val_lab))
1055 write_int (w, width);
1056 write_bytes (w, val_lab_get_value (val_lab)->s, width);
1058 label = recode_string (var_get_encoding (var), "UTF-8",
1059 val_lab_get_escaped_label (val_lab), -1);
1060 len = strlen (label);
1062 write_bytes (w, label, len);
1069 write_long_string_missing_values (struct sfm_writer *w,
1070 const struct dictionary *dict)
1072 const char *encoding = dict_get_encoding (dict);
1073 size_t n_vars = dict_get_n_vars (dict);
1076 /* Figure out the size in advance. */
1078 for (i = 0; i < n_vars; i++)
1080 struct variable *var = dict_get_var (dict, i);
1081 const struct missing_values *mv = var_get_missing_values (var);
1082 int width = var_get_width (var);
1084 if (mv_is_empty (mv) || width < 9)
1088 size += recode_string_len (encoding, "UTF-8", var_get_name (var), -1);
1091 size += mv_n_values (mv) * 8;
1096 write_int (w, 7); /* Record type. */
1097 write_int (w, 22); /* Record subtype */
1098 write_int (w, 1); /* Data item (byte) size. */
1099 write_int (w, size); /* Number of data items. */
1101 for (i = 0; i < n_vars; i++)
1103 struct variable *var = dict_get_var (dict, i);
1104 const struct missing_values *mv = var_get_missing_values (var);
1105 int width = var_get_width (var);
1106 uint8_t n_missing_values;
1110 if (mv_is_empty (mv) || width < 9)
1113 var_name = recode_string (encoding, "UTF-8", var_get_name (var), -1);
1114 write_int (w, strlen (var_name));
1115 write_bytes (w, var_name, strlen (var_name));
1118 n_missing_values = mv_n_values (mv);
1119 write_bytes (w, &n_missing_values, 1);
1123 for (j = 0; j < n_missing_values; j++)
1125 const union value *value = mv_get_value (mv, j);
1126 write_bytes (w, value->s, 8);
1132 write_encoding_record (struct sfm_writer *w,
1133 const struct dictionary *d)
1135 /* IANA says "...character set names may be up to 40 characters taken
1136 from the printable characters of US-ASCII," so character set names
1137 don't need to be recoded to be in UTF-8.
1139 We convert encoding names to uppercase because SPSS writes encoding
1140 names in uppercase. */
1141 char *encoding = xstrdup (dict_get_encoding (d));
1142 str_uppercase (encoding);
1143 write_string_record (w, ss_cstr (encoding), 20);
1147 /* Writes the long variable name table. */
1149 write_longvar_table (struct sfm_writer *w, const struct dictionary *dict)
1154 ds_init_empty (&map);
1155 for (i = 0; i < dict_get_n_vars (dict); i++)
1157 struct variable *v = dict_get_var (dict, i);
1159 ds_put_byte (&map, '\t');
1160 ds_put_format (&map, "%s=%s",
1161 var_get_short_name (v, 0), var_get_name (v));
1163 write_utf8_record (w, dict_get_encoding (dict), &map, 13);
1167 /* Write integer information record. */
1169 write_integer_info_record (struct sfm_writer *w,
1170 const struct dictionary *d)
1172 const char *dict_encoding = dict_get_encoding (d);
1173 int version_component[3];
1177 /* Parse the version string. */
1178 memset (version_component, 0, sizeof version_component);
1179 sscanf (bare_version, "%d.%d.%d",
1180 &version_component[0], &version_component[1], &version_component[2]);
1182 /* Figure out the floating-point format. */
1183 if (FLOAT_NATIVE_64_BIT == FLOAT_IEEE_DOUBLE_LE
1184 || FLOAT_NATIVE_64_BIT == FLOAT_IEEE_DOUBLE_BE)
1186 else if (FLOAT_NATIVE_64_BIT == FLOAT_Z_LONG)
1188 else if (FLOAT_NATIVE_64_BIT == FLOAT_VAX_D)
1193 /* Choose codepage. */
1194 codepage = sys_get_codepage_from_encoding (dict_encoding);
1197 /* The codepage is unknown. Choose a default.
1199 For an EBCDIC-compatible encoding, use the value for EBCDIC.
1201 For an ASCII-compatible encoding, default to "7-bit ASCII", because
1202 many files use this codepage number regardless of their actual
1205 if (is_encoding_ascii_compatible (dict_encoding))
1207 else if (is_encoding_ebcdic_compatible (dict_encoding))
1212 write_int (w, 7); /* Record type. */
1213 write_int (w, 3); /* Record subtype. */
1214 write_int (w, 4); /* Data item (int32) size. */
1215 write_int (w, 8); /* Number of data items. */
1216 write_int (w, version_component[0]);
1217 write_int (w, version_component[1]);
1218 write_int (w, version_component[2]);
1219 write_int (w, -1); /* Machine code. */
1220 write_int (w, float_format);
1221 write_int (w, 1); /* Compression code. */
1222 write_int (w, INTEGER_NATIVE == INTEGER_MSB_FIRST ? 1 : 2);
1223 write_int (w, codepage);
1226 /* Write floating-point information record. */
1228 write_float_info_record (struct sfm_writer *w)
1230 write_int (w, 7); /* Record type. */
1231 write_int (w, 4); /* Record subtype. */
1232 write_int (w, 8); /* Data item (flt64) size. */
1233 write_int (w, 3); /* Number of data items. */
1234 write_float (w, SYSMIS); /* System-missing value. */
1235 write_float (w, HIGHEST); /* Value used for HIGHEST in missing values. */
1236 write_float (w, LOWEST); /* Value used for LOWEST in missing values. */
1239 /* Writes case C to system file W. */
1241 sys_file_casewriter_write (struct casewriter *writer, void *w_,
1244 struct sfm_writer *w = w_;
1246 if (ferror (w->file))
1248 casewriter_force_error (writer);
1255 if (w->compression == ANY_COMP_NONE)
1256 write_case_uncompressed (w, c);
1258 write_case_compressed (w, c);
1263 /* Destroys system file writer W. */
1265 sys_file_casewriter_destroy (struct casewriter *writer, void *w_)
1267 struct sfm_writer *w = w_;
1268 if (!close_writer (w))
1269 casewriter_force_error (writer);
1272 /* Returns true if an I/O error has occurred on WRITER, false otherwise. */
1274 write_error (const struct sfm_writer *writer)
1276 return ferror (writer->file);
1279 /* Closes a system file after we're done with it.
1280 Returns true if successful, false if an I/O error occurred. */
1282 close_writer (struct sfm_writer *w)
1290 if (w->file != NULL)
1293 flush_compressed (w);
1294 if (w->compression == ANY_COMP_ZLIB)
1301 ok = !write_error (w);
1303 /* Seek back to the beginning and update the number of cases.
1304 This is just a courtesy to later readers, so there's no need
1305 to check return values or report errors. */
1306 if (ok && w->n_cases <= INT32_MAX && !fseeko (w->file, 80, SEEK_SET))
1308 write_int (w, w->n_cases);
1312 if (fclose (w->file) == EOF)
1316 msg (ME, _("An I/O error occurred writing system file `%s'."),
1317 fh_get_file_name (w->fh));
1319 if (ok ? !replace_file_commit (w->rf) : !replace_file_abort (w->rf))
1325 fh_unlock (w->lock);
1334 /* System file writer casewriter class. */
1335 static const struct casewriter_class sys_file_casewriter_class =
1337 sys_file_casewriter_write,
1338 sys_file_casewriter_destroy,
1342 /* Writes case C to system file W, without compressing it. */
1344 write_case_uncompressed (struct sfm_writer *w, const struct ccase *c)
1348 for (i = 0; i < w->sfm_n_vars; i++)
1350 struct sfm_var *v = &w->sfm_vars[i];
1352 if (v->var_width == 0)
1353 write_float (w, case_num_idx (c, v->case_index));
1356 write_bytes (w, case_str_idx (c, v->case_index) + v->offset,
1358 write_spaces (w, v->padding);
1363 /* Writes case C to system file W, with compression. */
1365 write_case_compressed (struct sfm_writer *w, const struct ccase *c)
1369 for (i = 0; i < w->sfm_n_vars; i++)
1371 struct sfm_var *v = &w->sfm_vars[i];
1373 if (v->var_width == 0)
1375 double d = case_num_idx (c, v->case_index);
1377 put_cmp_opcode (w, 255);
1378 else if (d >= 1 - COMPRESSION_BIAS
1379 && d <= 251 - COMPRESSION_BIAS
1381 put_cmp_opcode (w, (int) d + COMPRESSION_BIAS);
1383 put_cmp_number (w, d);
1387 int offset = v->offset;
1390 /* This code properly deals with a width that is not a
1391 multiple of 8, by ensuring that the final partial
1392 oct (8 byte unit) is treated as padded with spaces
1394 for (width = v->segment_width; width > 0; width -= 8, offset += 8)
1396 const void *data = case_str_idx (c, v->case_index) + offset;
1397 int chunk_size = MIN (width, 8);
1398 if (!memcmp (data, " ", chunk_size))
1399 put_cmp_opcode (w, 254);
1401 put_cmp_string (w, data, chunk_size);
1404 /* This code deals properly with padding that is not a
1405 multiple of 8 bytes, by discarding the remainder,
1406 which was already effectively padded with spaces in
1407 the previous loop. (Note that v->width + v->padding
1408 is always a multiple of 8.) */
1409 for (padding = v->padding / 8; padding > 0; padding--)
1410 put_cmp_opcode (w, 254);
1416 start_zstream (struct sfm_writer *w)
1420 error = deflateInit (&w->zstream, 1);
1423 msg (ME, _("Failed to initialize ZLIB for compression (%s)."),
1431 finish_zstream (struct sfm_writer *w)
1433 struct zblock *block;
1436 assert (w->zstream.total_in <= ZBLOCK_SIZE);
1438 w->zstream.next_in = NULL;
1439 w->zstream.avail_in = 0;
1444 w->zstream.next_out = buf;
1445 w->zstream.avail_out = sizeof buf;
1446 error = deflate (&w->zstream, Z_FINISH);
1447 write_bytes (w, buf, w->zstream.next_out - buf);
1449 while (error == Z_OK);
1451 if (error != Z_STREAM_END)
1452 msg (ME, _("Failed to complete ZLIB stream compression (%s)."),
1455 if (w->n_blocks >= w->allocated_blocks)
1456 w->blocks = x2nrealloc (w->blocks, &w->allocated_blocks,
1458 block = &w->blocks[w->n_blocks++];
1459 block->uncompressed_size = w->zstream.total_in;
1460 block->compressed_size = w->zstream.total_out;
1461 deflateEnd (&w->zstream);
1465 write_zlib (struct sfm_writer *w, const void *data_, unsigned int n)
1467 const uint8_t *data = data_;
1473 if (w->zstream.total_in >= ZBLOCK_SIZE)
1479 chunk = MIN (n, ZBLOCK_SIZE - w->zstream.total_in);
1481 w->zstream.next_in = CONST_CAST (uint8_t *, data);
1482 w->zstream.avail_in = chunk;
1488 w->zstream.next_out = buf;
1489 w->zstream.avail_out = sizeof buf;
1490 error = deflate (&w->zstream, Z_NO_FLUSH);
1491 write_bytes (w, buf, w->zstream.next_out - buf);
1494 msg (ME, _("ZLIB stream compression failed (%s)."),
1499 while (w->zstream.avail_in > 0 || w->zstream.avail_out == 0);
1506 write_ztrailer (struct sfm_writer *w)
1508 long long int uncompressed_ofs;
1509 long long int compressed_ofs;
1510 const struct zblock *block;
1512 write_int64 (w, -COMPRESSION_BIAS);
1514 write_int (w, ZBLOCK_SIZE);
1515 write_int (w, w->n_blocks);
1517 uncompressed_ofs = w->zstart;
1518 compressed_ofs = w->zstart + 24;
1519 for (block = w->blocks; block < &w->blocks[w->n_blocks]; block++)
1521 write_int64 (w, uncompressed_ofs);
1522 write_int64 (w, compressed_ofs);
1523 write_int (w, block->uncompressed_size);
1524 write_int (w, block->compressed_size);
1526 uncompressed_ofs += block->uncompressed_size;
1527 compressed_ofs += block->compressed_size;
1530 if (!fseeko (w->file, w->zstart + 8, SEEK_SET))
1532 write_int64 (w, compressed_ofs);
1533 write_int64 (w, 24 + (w->n_blocks * 24));
1536 msg (ME, _("%s: Seek failed (%s)."),
1537 fh_get_file_name (w->fh), strerror (errno));
1540 /* Flushes buffered compressed opcodes and data to W. */
1542 flush_compressed (struct sfm_writer *w)
1546 unsigned int n = 8 * (1 + w->n_elements);
1547 if (w->compression == ANY_COMP_SIMPLE)
1548 write_bytes (w, w->cbuf, n);
1550 write_zlib (w, w->cbuf, n);
1552 w->n_opcodes = w->n_elements = 0;
1553 memset (w->cbuf[0], 0, 8);
1557 /* Appends OPCODE to the buffered set of compression opcodes in
1558 W. Flushes the compression buffer beforehand if necessary. */
1560 put_cmp_opcode (struct sfm_writer *w, uint8_t opcode)
1562 if (w->n_opcodes >= 8)
1563 flush_compressed (w);
1565 w->cbuf[0][w->n_opcodes++] = opcode;
1568 /* Appends NUMBER to the buffered compression data in W. */
1570 put_cmp_number (struct sfm_writer *w, double number)
1572 put_cmp_opcode (w, 253);
1573 convert_double_to_output_format (number, w->cbuf[++w->n_elements]);
1576 /* Appends SIZE bytes of DATA to the buffered compression data in
1577 W, followed by enough spaces to pad the output data to exactly
1578 8 bytes (thus, SIZE must be no greater than 8). */
1580 put_cmp_string (struct sfm_writer *w, const void *data, size_t size)
1584 put_cmp_opcode (w, 253);
1586 memset (w->cbuf[w->n_elements], w->space, 8);
1587 memcpy (w->cbuf[w->n_elements], data, size);
1590 /* Writes 32-bit integer X to the output file for writer W. */
1592 write_int (struct sfm_writer *w, int32_t x)
1594 write_bytes (w, &x, sizeof x);
1597 /* Writes 64-bit integer X to the output file for writer W. */
1599 write_int64 (struct sfm_writer *w, int64_t x)
1601 write_bytes (w, &x, sizeof x);
1604 /* Converts NATIVE to the 64-bit format used in output files in
1607 convert_double_to_output_format (double native, uint8_t output[8])
1609 /* If "double" is not a 64-bit type, then convert it to a
1610 64-bit type. Otherwise just copy it. */
1611 if (FLOAT_NATIVE_DOUBLE != FLOAT_NATIVE_64_BIT)
1612 float_convert (FLOAT_NATIVE_DOUBLE, &native, FLOAT_NATIVE_64_BIT, output);
1614 memcpy (output, &native, sizeof native);
1617 /* Writes floating-point number X to the output file for writer
1620 write_float (struct sfm_writer *w, double x)
1623 convert_double_to_output_format (x, output);
1624 write_bytes (w, output, sizeof output);
1627 /* Writes contents of VALUE with the given WIDTH to W, padding
1628 with zeros to a multiple of 8 bytes.
1629 To avoid a branch, and because we don't actually need to
1630 support it, WIDTH must be no bigger than 8. */
1632 write_value (struct sfm_writer *w, const union value *value, int width)
1634 assert (width <= 8);
1636 write_float (w, value->f);
1639 write_bytes (w, value->s, width);
1640 write_zeros (w, 8 - width);
1644 /* Writes null-terminated STRING in a field of the given WIDTH to W. If STRING
1645 is longer than WIDTH, it is truncated; if STRING is shorter than WIDTH, it
1646 is padded on the right with spaces. */
1648 write_string (struct sfm_writer *w, const char *string, size_t width)
1650 size_t data_bytes = MIN (strlen (string), width);
1651 size_t pad_bytes = width - data_bytes;
1652 write_bytes (w, string, data_bytes);
1653 while (pad_bytes-- > 0)
1654 putc (w->space, w->file);
1657 /* Recodes null-terminated UTF-8 encoded STRING into ENCODING, and writes the
1658 recoded version in a field of the given WIDTH to W. The string is truncated
1659 or padded on the right with spaces to exactly WIDTH bytes. */
1661 write_utf8_string (struct sfm_writer *w, const char *encoding,
1662 const char *string, size_t width)
1664 char *s = recode_string (encoding, "UTF-8", string, -1);
1665 write_string (w, s, width);
1669 /* Writes a record with type 7, subtype SUBTYPE that contains CONTENT recoded
1670 from UTF-8 encoded into ENCODING. */
1672 write_utf8_record (struct sfm_writer *w, const char *encoding,
1673 const struct string *content, int subtype)
1677 s = recode_substring_pool (encoding, "UTF-8", ds_ss (content), NULL);
1678 write_string_record (w, s, subtype);
1682 /* Writes a record with type 7, subtype SUBTYPE that contains the string
1685 write_string_record (struct sfm_writer *w,
1686 const struct substring content, int subtype)
1689 write_int (w, subtype);
1691 write_int (w, ss_length (content));
1692 write_bytes (w, ss_data (content), ss_length (content));
1695 /* Writes SIZE bytes of DATA to W's output file. */
1697 write_bytes (struct sfm_writer *w, const void *data, size_t size)
1699 fwrite (data, 1, size, w->file);
1702 /* Writes N zeros to W's output file. */
1704 write_zeros (struct sfm_writer *w, size_t n)
1710 /* Writes N spaces to W's output file. */
1712 write_spaces (struct sfm_writer *w, size_t n)
1715 putc (w->space, w->file);