Go Language exercise:rot13 Reader

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

A common pattern is an IO. Reader that wraps another io.Reader , modifying the stream in some.

For example, the gzip. Newreader function takes an io.Reader (a stream of gzipped data) and returns a that *gzip.Reader also implements io.Reader (a stream of t He decompressed data).

Implement a rot13Reader , implements io.Reader and reads from an io.Reader , modifying the stream by applying the Rot13substitution CI Pher to all alphabetical characters.

The rot13Reader type is provided. Make it a by io.Reader implementing it Read method.

Encryption method: Caesar encryption, key is 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)
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.