1#!/usr/bin/env python 2""" Python Character Mapping Codec for ROT13. 3 4 See http://ucsub.colorado.edu/~kominek/rot13/ for details. 5 6 Written by Marc-Andre Lemburg (mal@lemburg.com). 7 8"""#" 9 10import codecs 11 12### Codec APIs 13 14class Codec(codecs.Codec): 15 16 def encode(self,input,errors='strict'): 17 return codecs.charmap_encode(input,errors,encoding_map) 18 19 def decode(self,input,errors='strict'): 20 return codecs.charmap_decode(input,errors,decoding_map) 21 22class IncrementalEncoder(codecs.IncrementalEncoder): 23 def encode(self, input, final=False): 24 return codecs.charmap_encode(input,self.errors,encoding_map)[0] 25 26class IncrementalDecoder(codecs.IncrementalDecoder): 27 def decode(self, input, final=False): 28 return codecs.charmap_decode(input,self.errors,decoding_map)[0] 29 30class StreamWriter(Codec,codecs.StreamWriter): 31 pass 32 33class StreamReader(Codec,codecs.StreamReader): 34 pass 35 36### encodings module API 37 38def getregentry(): 39 return codecs.CodecInfo( 40 name='rot-13', 41 encode=Codec().encode, 42 decode=Codec().decode, 43 incrementalencoder=IncrementalEncoder, 44 incrementaldecoder=IncrementalDecoder, 45 streamwriter=StreamWriter, 46 streamreader=StreamReader, 47 _is_text_encoding=False, 48 ) 49 50### Decoding Map 51 52decoding_map = codecs.make_identity_dict(range(256)) 53decoding_map.update({ 54 0x0041: 0x004e, 55 0x0042: 0x004f, 56 0x0043: 0x0050, 57 0x0044: 0x0051, 58 0x0045: 0x0052, 59 0x0046: 0x0053, 60 0x0047: 0x0054, 61 0x0048: 0x0055, 62 0x0049: 0x0056, 63 0x004a: 0x0057, 64 0x004b: 0x0058, 65 0x004c: 0x0059, 66 0x004d: 0x005a, 67 0x004e: 0x0041, 68 0x004f: 0x0042, 69 0x0050: 0x0043, 70 0x0051: 0x0044, 71 0x0052: 0x0045, 72 0x0053: 0x0046, 73 0x0054: 0x0047, 74 0x0055: 0x0048, 75 0x0056: 0x0049, 76 0x0057: 0x004a, 77 0x0058: 0x004b, 78 0x0059: 0x004c, 79 0x005a: 0x004d, 80 0x0061: 0x006e, 81 0x0062: 0x006f, 82 0x0063: 0x0070, 83 0x0064: 0x0071, 84 0x0065: 0x0072, 85 0x0066: 0x0073, 86 0x0067: 0x0074, 87 0x0068: 0x0075, 88 0x0069: 0x0076, 89 0x006a: 0x0077, 90 0x006b: 0x0078, 91 0x006c: 0x0079, 92 0x006d: 0x007a, 93 0x006e: 0x0061, 94 0x006f: 0x0062, 95 0x0070: 0x0063, 96 0x0071: 0x0064, 97 0x0072: 0x0065, 98 0x0073: 0x0066, 99 0x0074: 0x0067, 100 0x0075: 0x0068, 101 0x0076: 0x0069, 102 0x0077: 0x006a, 103 0x0078: 0x006b, 104 0x0079: 0x006c, 105 0x007a: 0x006d, 106}) 107 108### Encoding Map 109 110encoding_map = codecs.make_encoding_map(decoding_map) 111 112### Filter API 113 114def rot13(infile, outfile): 115 outfile.write(infile.read().encode('rot-13')) 116 117if __name__ == '__main__': 118 import sys 119 rot13(sys.stdin, sys.stdout) 120