summaryrefslogtreecommitdiffstats
path: root/catalog/common.py
blob: 6e4729a86e3055cab33d328933422d4c1a25ffac (plain)
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
# Copyright (C) 2016 Santosh Sivaraj <santosiv@in.ibm.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

import struct
import csv
import os

PAGE_SIZE=4096

def quotechars(chars):
    return ''.join( ['.', c][c.isalnum()] for c in chars)

def hexdump(chars, sep, width):
    while chars:
        line = chars[:width]
        chars = chars[width:]
        line = line.ljust( width, '\000' )
        print "%s%s%s" % (sep.join( "%02x" % ord(c) for c in line ),
                          sep, quotechars(line))

def pack_text(text):
    # Won't be fun if all goes well.. so here we might get empty texts, if so
    # we just need to update the length field to the length of the length
    # field. See catalog proposal document if you don't get this.

    if text == None or len(text) == 0:
        text_bin = struct.pack(">H", 2)
    else:
        l = len(text) + 1 + 2 # a null byte included

        if l % 2 != 0:
            l += 2 - l % 2

        text_bin = struct.pack(">H%ds" % (l - 2), l, text)

    return text_bin

def pad16(dump):
    # default is 16 bit length, the old formula structure had a bug, mentioning
    # it as 32 bit structure length
    tlen = len(dump) + 2
    plen = 0
    if tlen % 16 != 0:
        plen = 16 - tlen % 16;
        tlen += plen

    slen = struct.pack(">H", tlen)

    padding = struct.pack("%dx" % (plen))

    return slen + dump + padding

def pad_page(dump, page_size):
    if len(dump) % page_size != 0:
        # pad the remaining page
        dump += struct.pack("%dx" % (PAGE_SIZE - len(dump) % PAGE_SIZE))

        return dump

def read_string(dump):
    nlen = struct.unpack_from(">H", dump)[0]

    if nlen == 0:
        print """ERROR: A string length can never be zero, it should be atleast of
length 2, which will always include the length of the length field.
Please check your offsets"""
        exit(1)

    name = struct.unpack_from(">%ds" % (nlen - 2), dump[2:])

    return name[0], nlen

def write_to_csv(csv_file, dict_list):
    f = open(csv_file, 'wt')
    try:
        writer = csv.writer(f, lineterminator=os.linesep)
        # dump the header
        writer.writerow((dict_list[0].keys()))
        for d in dict_list:
            writer.writerow((d.values()))
    finally:
        f.close()
OpenPOWER on IntegriCloud