summaryrefslogtreecommitdiffstats
path: root/mpi-patches/add-mp-set-intptr
blob: 87e4ebb43739d9ebd802ead126d894d4490a88eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
Index: mpi-1.8.6/mpi.c
===================================================================
--- mpi-1.8.6.orig/mpi.c	2011-12-10 18:20:55.000000000 -0800
+++ mpi-1.8.6/mpi.c	2011-12-10 19:40:53.000000000 -0800
@@ -528,6 +528,59 @@
 
 /* }}} */
 
+mp_err mp_set_intptr(mp_int *mp, int_ptr_t z)
+{
+  int_ptr_t v = z > 0 ? z : -z;
+
+  if (sizeof z > sizeof (mp_digit)) {
+    int            ix, shift;
+    const int      nd = (sizeof v + sizeof (mp_digit) - 1) / sizeof (mp_digit);
+
+    ARGCHK(mp != NULL, MP_BADARG);
+
+    mp_zero(mp);
+
+    if(z == 0)
+      return MP_OKAY;  /* shortcut for zero */
+
+    s_mp_grow(mp, nd);
+
+    USED(mp) = nd;
+
+    for (ix = 0, shift = 0; ix < nd; ix++, shift += MP_DIGIT_BIT)
+    {
+	DIGIT(mp, ix) = (v >> shift) & MP_DIGIT_MAX;
+    }
+  } else {
+    mp_set(mp, v);
+  }
+
+  if(z < 0)
+    SIGN(mp) = MP_NEG;
+
+  return MP_OKAY;
+}
+
+/*
+ * No checks here: assumes that the mp is in range!
+ */
+mp_err mp_get_intptr(mp_int *mp, int_ptr_t *z)
+{
+  int_ptr_t out = 0;
+
+#if MP_DIGIT_SIZE < SIZEOF_PTR
+  int ix;
+  int nd = USED(mp);
+  for (ix = 0; ix < nd; ix++, out <<= MP_DIGIT_BIT)
+    out = DIGIT(mp, ix);
+#else
+  out = DIGIT(mp, 0);
+#endif
+
+  *z = (SIGN(mp) == MP_NEG) ? -out : out;
+  return MP_OKAY;
+}
+
 /*------------------------------------------------------------------------*/
 /* {{{ Digit arithmetic */
 
Index: mpi-1.8.6/mpi.h
===================================================================
--- mpi-1.8.6.orig/mpi.h	2011-12-10 18:19:39.000000000 -0800
+++ mpi-1.8.6/mpi.h	2011-12-10 19:39:58.000000000 -0800
@@ -94,6 +94,8 @@
 void   mp_zero(mp_int *mp);
 void   mp_set(mp_int *mp, mp_digit d);
 mp_err mp_set_int(mp_int *mp, long z);
+mp_err mp_set_intptr(mp_int *mp, int_ptr_t z);
+mp_err mp_get_intptr(mp_int *mp, int_ptr_t *z);
 
 /*------------------------------------------------------------------------*/
 /* Single digit arithmetic                                                */