summaryrefslogtreecommitdiffstats
path: root/pbn_shift.c
blob: 7712f84347b34b78651e43d897be76ea091f3bdb (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/* ----------------------------------------------------------------------- *
 *
 *   Copyright 2007 H. Peter Anvin - All Rights Reserved
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as
 *   published by the Free Software Foundation, Inc.,
 *   59 Temple Place Ste 330, Boston MA 02111-1307, USA; version 2.1,
 *   incorporated herein by reference.
 *
 * ----------------------------------------------------------------------- */

/*
 * pbn_shift.c
 */

#include <string.h>
#include "pbn.h"

struct pbn *pbn_shl(struct pbn *src, int shift)
{
    int bits, len;
    pbn_limb_t b, c;
    int i;
    int sw, sb;
    struct pbn *dst;

    if (src->bits == 0 || shift == 0)
	return src;		/* Source was zero or shift was zero */

    if (shift < 0)
	return pbn_shr(src, -shift);

    bits = src->bits + shift;
    len = (bits+PBN_LIMB_BITS-1)/PBN_LIMB_BITS;

    dst = pbn_cow(src, len);
    dst->bits = bits;		/* This is guaranteed accurate */

    sw = shift / PBN_LIMB_BITS;
    sb = shift % PBN_LIMB_BITS;

    if (sb == 0) {
	/* Particularly simple case... */
	memmove(&dst->num[sw], &dst->num[0], (len-sw)*sizeof(pbn_limb_t));
    } else {
	b = dst->num[len-sw-1];
	for (i = len-sw-1; i > 0; i--) {
	    /* b == dst->num[i] */
	    c = dst->num[i-1];
	    dst->num[i+sw] = (b << sb) | (c >> (PBN_LIMB_BITS-sb));
	    b = c;
	}
	dst->num[sw] = b << sb;
    }

    if (sw)
	memset(&dst->num[0], 0, sw*sizeof(pbn_limb_t));

    return dst;
}

struct pbn *pbn_shr(struct pbn *src, int shift)
{
    int len;
    pbn_limb_t b, c;
    int i;
    int sw, sb;
    struct pbn *dst;

    if (src->bits == 0 || shift == 0)
	return src;		/* Source was zero or shift was zero */

    if (shift < 0)
	return pbn_shl(src, -shift);

    len = src->len;
    dst = pbn_cow(src, len);	/* Leave at its old size */

    if (shift > dst->bits) {
	dst->bits = dst->minus = 0; /* Zero result */
	sw = len;		    /* Zero it all */
    } else {
	dst->bits -= shift;

	sw = shift / PBN_LIMB_BITS;
	sb = shift % PBN_LIMB_BITS;

	if (sb == 0) {
	    /* Particularly simple case... */
	    memmove(&dst->num[0], &dst->num[sw], (len-sw)*sizeof(pbn_limb_t));
	} else {
	    c = dst->num[sw];
	    for (i = sw; i < len-1; i++) {
		/* c == dst->num[i] */
		b = dst->num[i+1];
		dst->num[i-sw] = (c >> sb) | (b << (PBN_LIMB_BITS-sb));
		c = b;
	    }
	    dst->num[len-sw-1] = c >> sb;
	}
    }

    if (sw)
	memset(&dst->num[len-sw], 0, sw*sizeof(pbn_limb_t));

    return dst;
}