1 /*
2  * %CopyrightBegin%
3  *
4  * Copyright Ericsson AB 1998-2016. All Rights Reserved.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * %CopyrightEnd%
19  */
20 #include "eidef.h"
21 #include "eiext.h"
22 #include "putget.h"
23 
24 #define abs(p) (((p)<0) ? -(p) : p)
25 
26 /* long -> erl_integer */
27 /* note that this is the only place where data is stored Little Endian */
28 
29 #ifndef EI_64BIT
ei_encode_long(char * buf,int * index,long p)30 int ei_encode_long(char *buf, int *index, long p)
31 {
32   char *s = buf + *index;
33   char *s0 = s;
34 
35   if ((p < 256) && (p >= 0)) {
36     if (!buf) s += 2;
37     else {
38       put8(s,ERL_SMALL_INTEGER_EXT);
39       put8(s,(p & 0xff));
40     }
41   }
42   else if ((p <= ERL_MAX) && (p >= ERL_MIN)) {
43     /* FIXME: Non optimal, could use (p <= LONG_MAX) && (p >= LONG_MIN)
44        and skip next case */
45     if (!buf) s += 5;
46     else {
47       put8(s,ERL_INTEGER_EXT);
48       put32be(s,p);
49     }
50   }
51   else {
52     if (!buf) s += 7;
53     else {
54       put8(s,ERL_SMALL_BIG_EXT);
55       put8(s,4);	         /* len = four bytes */
56       put8(s, p < 0);            /* save sign separately */
57       put32le(s, abs(p));        /* OBS: Little Endian, and p now positive */
58     }
59   }
60 
61   *index += s-s0;
62 
63   return 0;
64 }
65 #endif /* EI_64BIT */
66