forked from NyaanNyaan/library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compress.py
72 lines (60 loc) · 1.61 KB
/
compress.py
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
import os
from enum import Enum
class State(Enum):
CODE = 1
C_COMMENT = 2
CPP_COMMENT = 3
STRING_LITERAL = 4
def remove_garbage(text):
result = []
prev = ''
prevprev = ''
state = State.CODE
for ch in text:
if state == State.C_COMMENT:
if prevprev != '\\' and prev == '*' and ch == '/':
state = State.CODE
prevprev = prev = ''
elif ch == '\n':
result.append('\n')
prevprev = prev = ''
else:
prevprev, prev = prev, ch
continue
# Skip to the end of the line (C++ style comment)
if state == State.CPP_COMMENT:
if ch == '\n': # End comment
state = State.CODE
result.append('\n')
prevprev = prev = ''
continue
if state == State.STRING_LITERAL:
if prev != '\\' and ch == '"':
state = State.CODE
result.append(prev)
prevprev, prev = prev, ch
continue
if prevprev != '\\' and prev == '/' and ch == '*':
state = State.C_COMMENT
prevprev = prev = ''
continue
if prevprev != '\\' and prev == '/' and ch == '/':
state = State.CPP_COMMENT
prevprev = prev = ''
continue
if prev:
if prev != ' ' or ch != ' ':
result.append(prev)
if ch == '"':
state = State.STRING_LITERAL
prevprev, prev = prev, ch
if prev:
result.append(prev)
return ''.join(result)
if __name__ == '__main__':
p = os.path.join(os.getcwd(), "unused", "a.cpp")
with open(p, "r", encoding='utf-8') as f:
content = f.read()
compressed = remove_garbage(content)
with open(p, "w", encoding='utf-8') as f:
f.write(compressed)