libsocket
framing.cpp
Go to the documentation of this file.
1 #include <string.h>
2 #include <string>
3 
4 #include <framing.hpp>
5 
6 /*
7  The committers of the libsocket project, all rights reserved
8  (c) 2016, dermesser <lbo@spheniscida.de>
9 
10  Redistribution and use in source and binary forms, with or without
11  modification, are permitted provided that the following conditions are met:
12 
13  1. Redistributions of source code must retain the above copyright notice,
14  this list of conditions and the following disclaimer.
15  2. Redistributions in binary form must reproduce the above copyright notice,
16  this list of conditions and the following disclaimer in the documentation
17  and/or other materials provided with the distribution.
18 
19  THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS “AS IS” AND ANY
20  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
23  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 */
31 
40 namespace libsocket {
41 void encode_uint32(uint32_t n, char* dst) {
42  for (int i = 3; i >= 0; i--) {
43  dst[i] = n >> (8 * (3 - i));
44  }
45 }
46 
47 uint32_t decode_uint32(const char* src) {
48  uint32_t result = 0;
49  // We store unsigned numbers in signed chars; convert, otherwise the MSB
50  // being set would be interpreted as sign and taken over to uint32_t's MSB.
51  const unsigned char* src_ = (const unsigned char*)src;
52 
53  for (int i = 3; i >= 0; i--) {
54  result |= uint32_t(src_[i]) << (8 * (3 - i));
55  }
56 
57  return result;
58 }
59 } // namespace libsocket
60 
Contains libsocket elements.
Definition: dgramclient.hpp:41
Declarations of framing functions.