blob: f0b4186dc877a71891c96b52603c115d3cc68dee [file] [log] [blame]
Georg Brandl02524622010-12-02 18:06:51 +00001#!/usr/bin/env python
2""" Python Character Mapping Codec for ROT13.
3
R David Murraye5cb8362014-03-13 20:54:30 -04004This codec de/encodes from str to str.
Georg Brandl02524622010-12-02 18:06:51 +00005
6Written by Marc-Andre Lemburg (mal@lemburg.com).
7"""
8
9import codecs
10
11### Codec APIs
12
13class Codec(codecs.Codec):
14 def encode(self, input, errors='strict'):
15 return (input.translate(rot13_map), len(input))
16
17 def decode(self, input, errors='strict'):
18 return (input.translate(rot13_map), len(input))
19
20class IncrementalEncoder(codecs.IncrementalEncoder):
21 def encode(self, input, final=False):
22 return input.translate(rot13_map)
23
24class IncrementalDecoder(codecs.IncrementalDecoder):
25 def decode(self, input, final=False):
26 return input.translate(rot13_map)
27
28class StreamWriter(Codec,codecs.StreamWriter):
29 pass
30
31class StreamReader(Codec,codecs.StreamReader):
32 pass
33
34### encodings module API
35
36def getregentry():
37 return codecs.CodecInfo(
38 name='rot-13',
39 encode=Codec().encode,
40 decode=Codec().decode,
41 incrementalencoder=IncrementalEncoder,
42 incrementaldecoder=IncrementalDecoder,
43 streamwriter=StreamWriter,
44 streamreader=StreamReader,
Serhiy Storchaka94ee3892014-02-24 14:43:03 +020045 _is_text_encoding=False,
Georg Brandl02524622010-12-02 18:06:51 +000046 )
47
48### Map
49
50rot13_map = codecs.make_identity_dict(range(256))
51rot13_map.update({
52 0x0041: 0x004e,
53 0x0042: 0x004f,
54 0x0043: 0x0050,
55 0x0044: 0x0051,
56 0x0045: 0x0052,
57 0x0046: 0x0053,
58 0x0047: 0x0054,
59 0x0048: 0x0055,
60 0x0049: 0x0056,
61 0x004a: 0x0057,
62 0x004b: 0x0058,
63 0x004c: 0x0059,
64 0x004d: 0x005a,
65 0x004e: 0x0041,
66 0x004f: 0x0042,
67 0x0050: 0x0043,
68 0x0051: 0x0044,
69 0x0052: 0x0045,
70 0x0053: 0x0046,
71 0x0054: 0x0047,
72 0x0055: 0x0048,
73 0x0056: 0x0049,
74 0x0057: 0x004a,
75 0x0058: 0x004b,
76 0x0059: 0x004c,
77 0x005a: 0x004d,
78 0x0061: 0x006e,
79 0x0062: 0x006f,
80 0x0063: 0x0070,
81 0x0064: 0x0071,
82 0x0065: 0x0072,
83 0x0066: 0x0073,
84 0x0067: 0x0074,
85 0x0068: 0x0075,
86 0x0069: 0x0076,
87 0x006a: 0x0077,
88 0x006b: 0x0078,
89 0x006c: 0x0079,
90 0x006d: 0x007a,
91 0x006e: 0x0061,
92 0x006f: 0x0062,
93 0x0070: 0x0063,
94 0x0071: 0x0064,
95 0x0072: 0x0065,
96 0x0073: 0x0066,
97 0x0074: 0x0067,
98 0x0075: 0x0068,
99 0x0076: 0x0069,
100 0x0077: 0x006a,
101 0x0078: 0x006b,
102 0x0079: 0x006c,
103 0x007a: 0x006d,
104})
105
106### Filter API
107
108def rot13(infile, outfile):
Serhiy Storchakaa39938f2014-04-13 17:07:04 +0300109 outfile.write(codecs.encode(infile.read(), 'rot-13'))
Georg Brandl02524622010-12-02 18:06:51 +0000110
111if __name__ == '__main__':
112 import sys
113 rot13(sys.stdin, sys.stdout)