cd52f147ca3a0f4fd924c40861788cfc22081623
[pspp-builds.git] / src / data / value.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>. */
16
17 #include <config.h>
18 #include "value.h"
19
20 #include <libpspp/hash.h>
21 #include <libpspp/str.h>
22
23 #include "xalloc.h"
24
25 /* Duplicate a value.
26    The caller is responsible for freeing the returned value. */
27 union value *
28 value_dup (const union value *val, int width)
29 {
30   return xmemdup (val, MAX (width, sizeof *val));
31 }
32
33
34 /* Create a value of specified width.
35    The caller is responsible for freeing the returned value. */
36 union value *
37 value_create (int width)
38 {
39   return xnmalloc (value_cnt_from_width (width), sizeof (union value));
40 }
41
42
43 /* Compares A and B, which both have the given WIDTH, and returns
44    a strcmp()-type result.
45    Only the short string portion of longer strings are
46    compared. */
47 int
48 compare_values (const union value *a, const union value *b, int width)
49 {
50   return (width == 0
51           ? (a->f < b->f ? -1 : a->f > b->f)
52           : memcmp (a->s, b->s, MIN (MAX_SHORT_STRING, width)));
53 }
54
55 /* Create a hash of V, which has the given WIDTH.
56    Only the short string portion of a longer string is hashed. */
57 unsigned
58 hash_value (const union value *v, int width)
59 {
60   return (width == 0
61           ? hsh_hash_double (v->f)
62           : hsh_hash_bytes (v->s, MIN (MAX_SHORT_STRING, width)));
63 }
64
65 /* Copies SRC to DST, given that they both contain data of the
66    given WIDTH. */
67 void
68 value_copy (union value *dst, const union value *src, int width)
69 {
70   if (width == 0)
71     dst->f = src->f;
72   else
73     memcpy (dst->s, src->s, width);
74 }
75
76 /* Sets V to the system-missing value for data of the given
77    WIDTH. */
78 void
79 value_set_missing (union value *v, int width)
80 {
81   if (width == 0)
82     v->f = SYSMIS;
83   else
84     memset (v->s, ' ', width);
85 }