本文整理匯總了Golang中io.Copyn函數的典型用法代碼示例。如果您正苦於以下問題:Golang Copyn函數的具體用法?Golang Copyn怎麽用?Golang Copyn使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Copyn函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestECBEncrypter
func TestECBEncrypter(t *testing.T) {
var plain, crypt [256]byte
for i := 0; i < len(plain); i++ {
plain[i] = byte(i)
}
b := new(bytes.Buffer)
for block := 1; block <= 64; block *= 2 {
// compute encrypted version
delta := byte(0)
for i := 0; i < len(crypt); i++ {
if i%block == 0 {
delta++
}
crypt[i] = plain[i] + delta
}
for frag := 0; frag < 2; frag++ {
c := &IncCipher{block, 0, true}
b.Reset()
r := bytes.NewBuffer(&plain)
w := NewECBEncrypter(c, b)
// copy plain into w in increasingly large chunks: 1, 1, 2, 4, 8, ...
// if frag != 0, move the 1 to the end to cause fragmentation.
if frag == 0 {
_, err := io.Copyn(w, r, 1)
if err != nil {
t.Errorf("block=%d frag=0: first Copyn: %s", block, err)
continue
}
}
for n := 1; n <= len(plain)/2; n *= 2 {
_, err := io.Copyn(w, r, int64(n))
if err != nil {
t.Errorf("block=%d frag=%d: Copyn %d: %s", block, frag, n, err)
}
}
if frag != 0 {
_, err := io.Copyn(w, r, 1)
if err != nil {
t.Errorf("block=%d frag=1: last Copyn: %s", block, err)
continue
}
}
// check output
data := b.Bytes()
if len(data) != len(crypt) {
t.Errorf("block=%d frag=%d: want %d bytes, got %d", block, frag, len(crypt), len(data))
continue
}
if string(data) != string(&crypt) {
t.Errorf("block=%d frag=%d: want %x got %x", block, frag, data, crypt)
}
}
}
}
示例2: testXorWriter
func testXorWriter(t *testing.T, maxio int) {
var plain, crypt [256]byte
for i := 0; i < len(plain); i++ {
plain[i] = byte(i)
}
b := new(bytes.Buffer)
for block := 1; block <= 64 && block <= maxio; block *= 2 {
// compute encrypted version
n := byte(0)
for i := 0; i < len(crypt); i++ {
if i%block == 0 {
n++
}
crypt[i] = plain[i] ^ n
n++
}
for frag := 0; frag < 2; frag++ {
test := fmt.Sprintf("block=%d frag=%d maxio=%d", block, frag, maxio)
b.Reset()
r := bytes.NewBuffer(plain[0:])
s := newIncStream(block)
w := newXorWriter(s, b)
// copy plain into w in increasingly large chunks: 1, 1, 2, 4, 8, ...
// if frag != 0, move the 1 to the end to cause fragmentation.
if frag == 0 {
_, err := io.Copyn(w, r, 1)
if err != nil {
t.Errorf("%s: first Copyn: %s", test, err)
continue
}
}
for n := 1; n <= len(plain)/2; n *= 2 {
_, err := io.Copyn(w, r, int64(n))
if err != nil {
t.Errorf("%s: Copyn %d: %s", test, n, err)
}
}
// check output
crypt := crypt[0 : len(crypt)-frag]
data := b.Bytes()
if len(data) != len(crypt) {
t.Errorf("%s: want %d bytes, got %d", test, len(crypt), len(data))
continue
}
if string(data) != string(crypt) {
t.Errorf("%s: want %x got %x", test, data, crypt)
}
}
}
}
示例3: Create
func (self *TarwFS) Create(name string, flags, mode uint32) (file fuse.File, eno fuse.Status) {
//log.Printf("Create:%s", name)
self.lock.Lock()
_, exists := self.isDir[name]
if !exists {
self.files[name] = &os.FileInfo{Mode: mode | syscall.S_IFREG}
self.isDir[name] = false
self.lock.Unlock()
start := time.Seconds()
file = newFile(func(r io.Reader, rlen int64) (err os.Error) {
self.lock.Lock()
err = self.w.WriteHeader(&tar.Header{
Typeflag: tar.TypeReg,
Name: name,
Mode: int64(mode),
Size: rlen,
Ctime: start,
Mtime: time.Seconds(),
Atime: time.Seconds(),
})
if err == nil {
_, err = io.Copyn(self.w, r, rlen)
}
self.lock.Unlock()
return
})
eno = fuse.OK
} else {
self.lock.Unlock()
eno = fuse.EINVAL
}
return
}
示例4: Execute
func (cl *CommitLog) Execute(mutation Mutation) {
typ := reflect.TypeOf(mutation)
mutInfo, found := cl.mutationsType[typ]
if !found {
log.Fatal("CommitLog: Tried to execute an unknown mutation: %s of type %s", mutation, typ)
}
// write the modification into a buffer
buf := buffer.New()
buf.WriteUint8(mutInfo.id) // mutation id
mutation.Serialize(buf) // mutation record
buf.WriteInt64(buf.Size + 8) // record length
// write record to disk
buf.Seek(0, 0)
cl.fdMutex.Lock()
cl.fd.Seek(cl.writePtr, 0)
io.Copyn(cl.fd, buf, buf.Size)
// update commit log write pointer
cl.fd.Seek(HEADER_WRITE_POS, 0)
cl.writePtr += buf.Size
cl.typedFd.WriteInt64(cl.writePtr)
cl.fdMutex.Unlock()
// execute the mutation
mutation.Execute()
}
示例5: WriteBinaryFromReader
func (p *TBinaryProtocol) WriteBinaryFromReader(reader io.Reader, size int) TProtocolException {
e := p.WriteI32(int32(size))
if e != nil {
return e
}
_, err := io.Copyn(p.trans, reader, int64(size))
return NewTProtocolExceptionFromOsError(err)
}
示例6: serveFile
func serveFile(c *ServiceContext, file string) bool {
var err os.Error
var f *os.File
var t *time.Time
var modified int64
file = path.Clean(file)
if f, err = os.Open(file, os.O_RDONLY, 0); err != nil {
c.Status(404)
return false
}
defer f.Close()
stat, _ := f.Stat()
modified = stat.Mtime_ns / 1e9
if v, ok := c.Req.Header["If_Modified_Since"]; ok {
v = v[0:len(v)-3] + "UTC"
if t, err = time.Parse(v, time.RFC1123); err != nil {
fmt.Fprintf(os.Stderr, "Unrecognized time format in If_Modified_Since header: %s", v)
return false
}
if modified > t.Seconds() {
c.Status(200)
} else {
c.Status(304)
}
return true
}
if ctype := mime.TypeByExtension(path.Ext(file)); ctype != "" {
c.SetHeaders(200, 2592000, ctype, modified)
} else {
var data []byte
var num int64
buf := bytes.NewBuffer(data)
if num, err = io.Copyn(buf, f, 1024); err != nil {
c.Status(500)
return false
}
data = buf.Bytes()
if isText(data[0:num]) {
c.SetHeaders(200, 2592000, "text/plain; charset=utf-8", modified)
} else {
c.SetHeaders(200, 2592000, "application/octet-stream", modified)
}
}
_, err = c.SendReadWriter(f)
return err == nil
}
示例7: skipUnread
// Skip any unread bytes in the existing file entry, as well as any alignment padding.
func (tr *Reader) skipUnread() {
nr := tr.nb + tr.pad // number of bytes to skip
if sr, ok := tr.r.(io.Seeker); ok {
_, tr.err = sr.Seek(nr, 1)
} else {
_, tr.err = io.Copyn(ignoreWriter{}, tr.r, nr)
}
tr.nb, tr.pad = 0, 0
}
示例8: skipUnread
// Skip any unread bytes in the existing file entry, as well as any alignment padding.
func (tr *Reader) skipUnread() {
nr := tr.nb + tr.pad // number of bytes to skip
tr.nb, tr.pad = 0, 0
if sr, ok := tr.r.(io.Seeker); ok {
if _, err := sr.Seek(nr, os.SEEK_CUR); err == nil {
return
}
}
_, tr.err = io.Copyn(ignoreWriter{}, tr.r, nr)
}
示例9: Exec
func (ltc *LocalTempCopy) Exec(srcStore fs.BlockStore) (err os.Error) {
_, err = ltc.Temp.localFh.Seek(ltc.LocalOffset, 0)
if err != nil {
return err
}
_, err = ltc.Temp.tempFh.Seek(ltc.TempOffset, 0)
if err != nil {
return err
}
_, err = io.Copyn(ltc.Temp.tempFh, ltc.Temp.localFh, ltc.Length)
return err
}
示例10: Data
func (me *ZipFile) Data() []byte {
zf := (*me)
rc, err := zf.Open()
if err != nil {
panic(err)
}
dest := bytes.NewBuffer(make([]byte, 0, me.UncompressedSize))
_, err = io.Copyn(dest, rc, int64(me.UncompressedSize))
if err != nil {
panic(err)
}
return dest.Bytes()
}
示例11: echoClient
func echoClient(c net.Conn) {
// Close the socket when the function returns
defer c.Close()
// Copy from Stdin to the socket (Untill EOF is received)
nr, err := io.Copy(c, os.Stdin)
if err != nil {
panic("Copy os.Stdio -> c: ", err.String())
}
// Copy from the socket to Stdout
nw, err := io.Copyn(os.Stdout, c, nr)
if err != nil {
panic("Copy c -> os.Stdout: ", err.String())
} else if nr != nw {
panic("nr != nw")
}
}
示例12: main
func main() {
goopt.Parse(func() []string { return []string{} })
if len(goopt.Args) < 1 {
fmt.Println("You need to provide a go file argument.")
os.Exit(1)
}
if *outname == "FILENAME" {
*outname = goopt.Args[0][0 : len(goopt.Args[0])-3]
}
fs := make([]string, len(goopt.Args)+1)
for i, f := range goopt.Args {
fs[i] = f
}
fs[len(goopt.Args)] = "testing.go"
makeSource("testing.go")
e := compile.Compile(*outname, fs)
if e != nil {
fmt.Println(e)
os.Exit(1)
}
if e != nil {
return
}
fi, err := os.Stat(*outname)
if err != nil {
return
}
enc0, err := os.Open(*outname+".encrypted", os.O_WRONLY+os.O_TRUNC+os.O_CREAT, 0644)
if err != nil {
return
}
enc, err := crypt.Encrypt(key, privatekey, enc0, fi.Size, sequence)
if err != nil {
return
}
plain, err := os.Open(*outname, os.O_RDONLY, 0644)
if err != nil {
return
}
_, err = io.Copyn(enc, plain, fi.Size)
if err != nil {
return
}
}
示例13: Read
// Read reads the body of a part, after its headers and before the
// next part (if any) begins.
func (bp *Part) Read(p []byte) (n int, err os.Error) {
if bp.buffer.Len() >= len(p) {
// Internal buffer of unconsumed data is large enough for
// the read request. No need to parse more at the moment.
return bp.buffer.Read(p)
}
peek, err := bp.mr.bufReader.Peek(4096) // TODO(bradfitz): add buffer size accessor
unexpectedEof := err == os.EOF
if err != nil && !unexpectedEof {
return 0, fmt.Errorf("multipart: Part Read: %v", err)
}
if peek == nil {
panic("nil peek buf")
}
// Search the peek buffer for "\r\n--boundary". If found,
// consume everything up to the boundary. If not, consume only
// as much of the peek buffer as cannot hold the boundary
// string.
nCopy := 0
foundBoundary := false
if idx := bytes.Index(peek, bp.mr.nlDashBoundary); idx != -1 {
nCopy = idx
foundBoundary = true
} else if safeCount := len(peek) - len(bp.mr.nlDashBoundary); safeCount > 0 {
nCopy = safeCount
} else if unexpectedEof {
// If we've run out of peek buffer and the boundary
// wasn't found (and can't possibly fit), we must have
// hit the end of the file unexpectedly.
return 0, io.ErrUnexpectedEOF
}
if nCopy > 0 {
if _, err := io.Copyn(bp.buffer, bp.mr.bufReader, int64(nCopy)); err != nil {
return 0, err
}
}
n, err = bp.buffer.Read(p)
if err == os.EOF && !foundBoundary {
// If the boundary hasn't been reached there's more to
// read, so don't pass through an EOF from the buffer
err = nil
}
return
}
示例14: readInto
func (store *localBase) readInto(path string, from int64, length int64, writer io.Writer) (int64, os.Error) {
fh, err := os.Open(path)
if fh == nil {
return 0, err
}
_, err = fh.Seek(from, 0)
if err != nil {
return 0, err
}
n, err := io.Copyn(writer, fh, length)
if err != nil {
return n, err
}
return n, nil
}
示例15: isSchemaPicker
func isSchemaPicker(thenSto, elseSto blobserver.Storage) storageFunc {
return func(src io.Reader) (dest blobserver.Storage, overRead []byte, err os.Error) {
// TODO: make decision earlier, by parsing JSON as it comes in,
// not after we have up to 1 MB.
var buf bytes.Buffer
_, err = io.Copyn(&buf, src, 1<<20)
if err != nil && err != os.EOF {
return
}
ss := new(schema.Superset)
if err = json.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(ss); err != nil {
log.Printf("cond: json parse failure => not schema => else")
return elseSto, buf.Bytes(), nil
}
if ss.Type == "" {
log.Printf("cond: json => but not schema => else")
return elseSto, buf.Bytes(), nil
}
log.Printf("cond: json => schema => then")
return thenSto, buf.Bytes(), nil
}
}