A common pattern is an io.Reader that wraps another io.Reader
,
modifying the stream in some way.
For example, the gzip.NewReader function takes an io.Reader
(a
stream of gzipped data) and returns a *gzip.Reader
that also implements io.Reader
(a stream of
the decompressed data).
Implement a rot13Reader
that implements io.Reader
and
reads from an io.Reader
, modifying the stream by applying the ROT13substitution cipher to all alphabetical characters.
The rot13Reader
type is provided for you. Make it an io.Reader
by
implementing its Read
method.
加密方法:凯撒加密,key为13
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func Rot13(b byte) byte {
switch {
case 'A' <= b && b <= 'M':
b = b + 13
case 'M' < b && b <= 'Z':
b = b - 13
case 'a' <= b && b <= 'm':
b = b + 13
case 'm' < b && b <= 'z':
b = b - 13
}
return b
}
func (read *rot13Reader) Read(p []byte) (n int, err error){
n, err = read.r.Read(p)
for i, value := range p {
p[i] = Rot13(value)
}
return
}
func main() {
s := strings.NewReader(
"Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
有疑问加站长微信联系(非本文作者)