|
| 1 | +(* |
| 2 | + * Copyright (c) 2010-2011 Anil Madhavapeddy <[email protected]> |
| 3 | + * |
| 4 | + * Permission to use, copy, modify, and distribute this software for any |
| 5 | + * purpose with or without fee is hereby granted, provided that the above |
| 6 | + * copyright notice and this permission notice appear in all copies. |
| 7 | + * |
| 8 | + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
| 9 | + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 10 | + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |
| 11 | + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 12 | + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
| 13 | + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |
| 14 | + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 15 | + *) |
| 16 | + |
| 17 | +let rec finalise_checksum cs = |
| 18 | + assert (cs >= 0); |
| 19 | + if cs < 0x10000 then |
| 20 | + lnot cs land 0xffff |
| 21 | + else |
| 22 | + finalise_checksum ((cs land 0xffff) + (cs lsr 16)) |
| 23 | + |
| 24 | +let ones_complement (buffer: Cstruct.t) = |
| 25 | + let len = Cstruct.len buffer in |
| 26 | + let rec do_checksum checksum offset = |
| 27 | + if offset + 1 < len then ( |
| 28 | + let checksum = checksum + Cstruct.BE.get_uint16 buffer offset in |
| 29 | + do_checksum checksum (offset + 2) |
| 30 | + ) else if offset + 1 = len then ( |
| 31 | + let checksum = checksum + (Cstruct.get_uint8 buffer offset lsl 8) in |
| 32 | + finalise_checksum checksum |
| 33 | + ) else |
| 34 | + finalise_checksum checksum |
| 35 | + in |
| 36 | + do_checksum 0 0 |
| 37 | + |
| 38 | +let ones_complement_list buffers = |
| 39 | + let rec do_checksum checksum offset len buffer buffers = |
| 40 | + if offset + 1 < len then ( |
| 41 | + let checksum = checksum + Cstruct.BE.get_uint16 buffer offset in |
| 42 | + do_checksum checksum (offset + 2) len buffer buffers |
| 43 | + ) else ( |
| 44 | + let extra_single_byte = offset + 1 = len in |
| 45 | + match buffers with |
| 46 | + | [] -> |
| 47 | + let checksum = |
| 48 | + checksum + |
| 49 | + if extra_single_byte then Cstruct.get_uint8 buffer offset lsl 8 else 0 |
| 50 | + in |
| 51 | + finalise_checksum checksum |
| 52 | + | next_buffer :: buffers -> |
| 53 | + let checksum = |
| 54 | + checksum + |
| 55 | + if extra_single_byte |
| 56 | + then Cstruct.get_uint8 next_buffer 0 + (Cstruct.get_uint8 buffer offset lsl 8) |
| 57 | + else 0 |
| 58 | + in |
| 59 | + let offset = if extra_single_byte then 1 else 0 in |
| 60 | + let len = Cstruct.len next_buffer in |
| 61 | + do_checksum checksum offset len next_buffer buffers |
| 62 | + ) |
| 63 | + in |
| 64 | + match buffers with |
| 65 | + | buffer :: buffers -> |
| 66 | + let len = Cstruct.len buffer in |
| 67 | + do_checksum 0 0 len buffer buffers |
| 68 | + | [] -> finalise_checksum 0 |
0 commit comments