Change license from GPLv2+ to GPLv3+.
[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 /* Compares A and B, which both have the given WIDTH, and returns
34    a strcmp()-type result.
35    Only the short string portion of longer strings are
36    compared. */
37 int
38 compare_values (const union value *a, const union value *b, int width)
39 {
40   return (width == 0
41           ? (a->f < b->f ? -1 : a->f > b->f)
42           : memcmp (a->s, b->s, MIN (MAX_SHORT_STRING, width)));
43 }
44
45 /* Create a hash of V, which has the given WIDTH.
46    Only the short string portion of a longer string is hashed. */
47 unsigned
48 hash_value (const union value *v, int width)
49 {
50   return (width == 0
51           ? hsh_hash_double (v->f)
52           : hsh_hash_bytes (v->s, MIN (MAX_SHORT_STRING, width)));
53 }
54
55 /* Copies SRC to DST, given that they both contain data of the
56    given WIDTH. */
57 void
58 value_copy (union value *dst, const union value *src, int width)
59 {
60   if (width == 0)
61     dst->f = src->f;
62   else
63     memcpy (dst->s, src->s, width);
64 }
65
66 /* Sets V to the system-missing value for data of the given
67    WIDTH. */
68 void
69 value_set_missing (union value *v, int width)
70 {
71   if (width == 0)
72     v->f = SYSMIS;
73   else
74     memset (v->s, ' ', width);
75 }