File: crc32.py

package info (click to toggle)
2ping 4.5-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 492 kB
  • sloc: python: 3,304; makefile: 44; sh: 4
file content (89 lines) | stat: -rw-r--r-- 2,155 bytes parent folder | download | duplicates (4)
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
# 2ping - A bi-directional ping utility
# Copyright (C) 2010-2020 Ryan Finnie
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

import binascii
import copy
import sys

digest_size = 4


class CRC32:
    digest_size = 4
    block_size = 64
    _crc = 0

    def __init__(self, buf=None):
        if buf is not None:
            self.update(buf)

    def copy(self):
        return copy.copy(self)

    def update(self, buf):
        self._crc = binascii.crc32(buf, self._crc)

    def clear(self):
        self._crc = 0

    def digest(self):
        i = self._crc & 0xFFFFFFFF
        out = bytearray()
        while i >= 256:
            out.insert(0, i & 0xFF)
            i = i >> 8
        out.insert(0, i)
        out_len = len(out)
        if out_len < 4:
            out = bytearray(4 - out_len) + out
        return out

    def hexdigest(self):
        return self.digest().hex()


def new(buf=None):
    return CRC32(buf)


def main(argv):
    if argv is None:
        argv = sys.argv

    files = argv[1:]
    if len(files) == 0:
        files = ["-"]

    for file in files:
        c = new()
        if file == "-":
            for buf in sys.stdin.buffer.readlines():
                c.update(buf)
        else:
            with open(file, "rb") as f:
                for buf in f.readlines():
                    c.update(buf)
        print("{}\t{}".format(c.hexdigest(), file))


def module_init():
    if __name__ == "__main__":
        sys.exit(main(sys.argv))


module_init()