friendev EtherDune TCP/IP library
/home/jander/temp/etherdune/Checksum.cpp
Go to the documentation of this file.
1 // EtherDune IP Checksum module
2 // Author: Javier Peletier <jm@friendev.com>
3 // Summary: memory-efficient algorithm to calculate total and partial network checksums
4 //
5 // Copyright (c) 2015 All Rights Reserved, http://friendev.com
6 //
7 // This source is subject to the GPLv2 license.
8 // Please see the License.txt file for more information.
9 // All other rights reserved.
10 //
11 // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
12 // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
13 // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
14 // PARTICULAR PURPOSE.
15 
16 
17 #include "Checksum.h"
18 
25 uint16_t Checksum::add(uint16_t a, uint16_t b)
26 {
27  a += b;
28 
29  if (a<b)
30  a++;
31 
32  return a;
33 }
34 
43 uint16_t Checksum::add(uint16_t a, uint16_t b, bool odd)
44 {
45  if (odd)
46  b = (b << 8) | (b >> 8);
47 
48  return add(a, b);
49 
50 }
51 
52 
59 uint16_t Checksum::calc(uint16_t len, const uint8_t *data)
60 {
61  uint16_t sum = 0;
62  const uint16_t *dataptr;
63  const uint16_t *last;
64 
65  dataptr = (uint16_t*)data;
66  last = dataptr + (len >> 1);
67 
68  while (dataptr < last)
69  {
70  sum = add(sum, *dataptr);
71  dataptr++;
72  }
73 
74  if (len & 1)
75  sum = add(sum, *((uint8_t*)dataptr));
76 
77  return sum;
78 
79 }
80 
89 uint16_t Checksum::calc(uint16_t checksum, uint16_t len, const uint8_t *data)
90 {
91  return add(checksum, calc(len, data));
92 }
static uint16_t calc(uint16_t len, const uint8_t *data)
Calculates the checksum of the specified buffer in memory
Definition: Checksum.cpp:59
static uint16_t add(uint16_t a, uint16_t b)
Adds two checksums, taking carry into account.
Definition: Checksum.cpp:25