Source file tour/solutions/rot13.go

     1  //go:build OMIT
     2  
     3  // Copyright 2012 The Go Authors.  All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  package main
     8  
     9  import (
    10  	"io"
    11  	"os"
    12  	"strings"
    13  )
    14  
    15  func rot13(b byte) byte {
    16  	var a, z byte
    17  	switch {
    18  	case 'a' <= b && b <= 'z':
    19  		a, z = 'a', 'z'
    20  	case 'A' <= b && b <= 'Z':
    21  		a, z = 'A', 'Z'
    22  	default:
    23  		return b
    24  	}
    25  	return (b-a+13)%(z-a+1) + a
    26  }
    27  
    28  type rot13Reader struct {
    29  	r io.Reader
    30  }
    31  
    32  func (r rot13Reader) Read(p []byte) (n int, err error) {
    33  	n, err = r.r.Read(p)
    34  	for i := 0; i < n; i++ {
    35  		p[i] = rot13(p[i])
    36  	}
    37  	return
    38  }
    39  
    40  func main() {
    41  	s := strings.NewReader(
    42  		"Lbh penpxrq gur pbqr!")
    43  	r := rot13Reader{s}
    44  	io.Copy(os.Stdout, &r)
    45  }
    46  

View as plain text