Ejemplo n.º 1
0
func TestNodeSnapshotBad(t *testing.T) {
	buf := bytes.NewBuffer([]byte{})
	gob.NewEncoder(buf).Encode(uint64(1))
	seqnPart := buf.String()

	buf = bytes.NewBuffer([]byte{})
	gob.NewEncoder(buf).Encode(emptyDir)
	valPart := buf.String()
	valPart = valPart[0 : len(valPart)/2]

	m := seqnPart + valPart
	n, e := emptyDir.apply(1, m)
	assert.Equal(t, emptyDir, n)
	assert.Equal(t, Event{2, "", "", "", m, io.ErrUnexpectedEOF, n}, e)
}
Ejemplo n.º 2
0
func (block *Block) GobEncode() ([]byte, error) {
	buffer := bytes.NewBuffer([]byte{})
	encoder := gob.NewEncoder(buffer)

	var err error
	err = encoder.EncodeValue(reflect.ValueOf(gobNodeVersion))
	if err != nil {
		return nil, err
	}

	err = encoder.EncodeValue(reflect.ValueOf(&block.position))
	if err != nil {
		return nil, err
	}
	encoder.EncodeValue(reflect.ValueOf(&block.weak))
	if err != nil {
		return nil, err
	}
	encoder.EncodeValue(reflect.ValueOf(&block.strong))
	if err != nil {
		return nil, err
	}

	return buffer.Bytes(), nil
}
Ejemplo n.º 3
0
func (dir *Dir) GobEncode() ([]byte, error) {
	buffer := bytes.NewBuffer([]byte{})
	encoder := gob.NewEncoder(buffer)

	var err error
	err = encoder.EncodeValue(reflect.ValueOf(gobNodeVersion))
	if err != nil {
		return nil, err
	}

	err = encoder.EncodeValue(reflect.ValueOf(&dir.name))
	if err != nil {
		return nil, err
	}
	err = encoder.EncodeValue(reflect.ValueOf(&dir.mode))
	if err != nil {
		return nil, err
	}
	err = encoder.EncodeValue(reflect.ValueOf(&dir.strong))
	if err != nil {
		return nil, err
	}
	err = encoder.EncodeValue(reflect.ValueOf(&dir.SubDirs))
	if err != nil {
		return nil, err
	}
	err = encoder.EncodeValue(reflect.ValueOf(&dir.Files))
	if err != nil {
		return nil, err
	}

	return buffer.Bytes(), nil
}
Ejemplo n.º 4
0
func (k *Key) GobEncode() ([]byte, error) {
	buf := new(bytes.Buffer)
	if err := gob.NewEncoder(buf).Encode(keyToGobKey(k)); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
Ejemplo n.º 5
0
// Encipher a message
func EncipherMsg(plaintext []byte, pubkey *CipherMsgPubKey) ([]byte, os.Error) {
	msg := &U_CipherMsg{
		Text: make([]byte, len(plaintext)),
	}
	n := copy(msg.Text, plaintext)
	if n != len(plaintext) {
		panic("crypto, copy text")
	}
	urand := NewTimedRand()
	seed := make([]byte, cipherMsgSeedLen)
	n, _ = urand.Read(seed)
	if n != len(seed) {
		panic("crypto,gen seed")
	}
	cseed, err := EncryptShortMsg(pubkey.rsa, seed, []byte(""))
	if err != nil {
		return nil, err
	}
	msg.Seed = cseed
	rc, err := rc4.NewCipher(seed)
	if err != nil {
		panic("rc4tube")
	}
	rc.XORKeyStream(msg.Text)
	var w bytes.Buffer
	enc := gob.NewEncoder(&w)
	err = enc.Encode(msg)
	if err != nil {
		return nil, err
	}
	return w.Bytes(), nil
}
Ejemplo n.º 6
0
func (server *Server) handleFreezeRequest(freq *freezeRequest, fs *frozenServer) {
	pr, pw := io.Pipe()

	freq.readCloser = pr
	freq.done <- true

	zw, err := gzip.NewWriterLevel(pw, gzip.BestCompression)
	if err != nil {
		if err = pw.CloseWithError(err); err != nil {
			log.Panicf("Unable to close PipeWriter: %v", err.String())
		}
		return
	}

	enc := gob.NewEncoder(zw)
	err = enc.Encode(fs)
	if err != nil {
		if err = pw.CloseWithError(err); err != nil {
			log.Panicf("Unable to close PipeWriter: %v", err.String())
		}
	}

	if err = pw.CloseWithError(zw.Close()); err != nil {
		log.Panicf("Unable to close PipeWriter: %v", err.String())
	}
}
Ejemplo n.º 7
0
func RetrieveActDetails(c appengine.Context, actId int) (res *ActDetail, err os.Error) {
	var d DSActDetail
	if itm, err := memcache.Get(c, "actId__"+strconv.Itoa(actId)); err != nil && err != memcache.ErrCacheMiss {
		return nil, err
	} else if err == nil {
		// Cache hit
		buf := bytes.NewBuffer(itm.Value)
		dec := gob.NewDecoder(buf)
		dec.Decode(&d)
	} else {
		// Cache miss
		key := datastore.NewKey(c, "DSActDetail", "", int64(actId), nil)
		if err := datastore.Get(c, key, &d); err == datastore.ErrNoSuchEntity {
			return &ActDetail{ActId: actId}, nil
		} else if err != nil {
			return nil, err
		}
		buf := bytes.NewBufferString("")
		enc := gob.NewEncoder(buf)
		enc.Encode(d)

		itm := &memcache.Item{
			Key:   "actId__" + strconv.Itoa(actId),
			Value: buf.Bytes(),
		}

		err = memcache.Set(c, itm)
		c.Debugf("Request cache to memcache")
	}
	return d.fromDS(), nil
}
Ejemplo n.º 8
0
func (p QueryParameter) Bind(s *Statement, value interface{}) (e os.Error) {
	var rv Errno
	switch v := value.(type) {
	case nil:
		rv = Errno(C.sqlite3_bind_null(s.cptr, C.int(p)))
	case int:
		rv = Errno(C.sqlite3_bind_int(s.cptr, C.int(p), C.int(v)))
	case string:
		rv = Errno(C.gosqlite3_bind_text(s.cptr, C.int(p), C.CString(v), C.int(len(v))))
	case int64:
		rv = Errno(C.sqlite3_bind_int64(s.cptr, C.int(p), C.sqlite3_int64(v)))
	case float32:
		rv = Errno(C.sqlite3_bind_double(s.cptr, C.int(p), C.double(v)))
	case float64:
		rv = Errno(C.sqlite3_bind_double(s.cptr, C.int(p), C.double(v)))
	default:
		buffer := new(bytes.Buffer)
		encoder := gob.NewEncoder(buffer)
		if encoder.Encode(value) != nil {
			rv = ENCODER
		} else {
			rawbuffer := string(buffer.Bytes())
			rv = Errno(C.gosqlite3_bind_blob(s.cptr, C.int(p), unsafe.Pointer(C.CString(rawbuffer)), C.int(len(rawbuffer))))
		}
	}
	if rv != OK {
		e = rv
	}
	return
}
Ejemplo n.º 9
0
func (c *FlatHaveCache) Save() {
	c.mu.Lock()
	defer c.mu.Unlock()
	if len(c.dirty) == 0 {
		cachelog.Printf("FlatHaveCache: Save, but nothing dirty")
		return
	}

	f, err := os.OpenFile(c.filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600)
	if err != nil {
		log.Fatalf("FlatHaveCache OpenFile: %v", err)
	}
	defer f.Close()
	e := gob.NewEncoder(f)
	write := func(v interface{}) {
		if err := e.Encode(v); err != nil {
			panic("Encode: " + err.String())
		}
	}
	for k, _ := range c.dirty {
		write(k)
	}
	c.dirty = make(map[string]bool)
	cachelog.Printf("FlatHaveCache: saved")
}
Ejemplo n.º 10
0
func main() {
	data, _ := ioutil.ReadFile("/space/raxml/VINCENT/RAxML_bipartitions.1604.BEST.WITH")

	n, _ := Parse(StringPI(string(data)), 0)
	//n,_ := Parse( StringPI(" (bla:.1,bla2:2.1,(bla32:1.2,bla34:0.7)100:3.4);"), 0 );

	PrintTree(n, os.Stdout)
	fmt.Println()
	PrintTree(n.Back, os.Stdout)
	fmt.Println()

	i := make([]int, 4)
	i[0] = 72
	i[1] = 105
	i[2] = 32
	i[3] = 9731 // Unicode snowman
	var s string = string(i)
	fmt.Printf("%s has length %d bytes.\n", s, len(s))

	buf := bytes.NewBuffer(nil)

	enc := gob.NewEncoder(buf)
	enc.Encode(n)

	os.Stdout.Write(buf.Bytes())
}
func gobMarshal(v interface{}) ([]byte, os.Error) {
	var buf bytes.Buffer
	if err := gob.NewEncoder(&buf).Encode(v); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
Ejemplo n.º 12
0
func (file *File) GobEncode() ([]byte, error) {
	buffer := bytes.NewBuffer([]byte{})
	encoder := gob.NewEncoder(buffer)

	var err error
	err = encoder.EncodeValue(reflect.ValueOf(gobNodeVersion))
	if err != nil {
		return nil, err
	}

	err = encoder.EncodeValue(reflect.ValueOf(&file.name))
	if err != nil {
		return nil, err
	}
	err = encoder.EncodeValue(reflect.ValueOf(&file.mode))
	if err != nil {
		return nil, err
	}
	err = encoder.EncodeValue(reflect.ValueOf(&file.strong))
	if err != nil {
		return nil, err
	}
	err = encoder.EncodeValue(reflect.ValueOf(&file.Size))
	if err != nil {
		return nil, err
	}
	err = encoder.EncodeValue(reflect.ValueOf(&file.Blocks))
	if err != nil {
		return nil, err
	}

	return buffer.Bytes(), nil
}
Ejemplo n.º 13
0
func TestRatGobEncoding(t *testing.T) {
	var medium bytes.Buffer
	enc := gob.NewEncoder(&medium)
	dec := gob.NewDecoder(&medium)
	for i, test := range gobEncodingTests {
		for j := 0; j < 4; j++ {
			medium.Reset() // empty buffer for each test case (in case of failures)
			stest := test
			if j&1 != 0 {
				// negative numbers
				stest = "-" + test
			}
			if j%2 != 0 {
				// fractions
				stest = stest + "." + test
			}
			var tx Rat
			tx.SetString(stest)
			if err := enc.Encode(&tx); err != nil {
				t.Errorf("#%d%c: encoding failed: %s", i, 'a'+j, err)
			}
			var rx Rat
			if err := dec.Decode(&rx); err != nil {
				t.Errorf("#%d%c: decoding failed: %s", i, 'a'+j, err)
			}
			if rx.Cmp(&tx) != 0 {
				t.Errorf("#%d%c: transmission failed: got %s want %s", i, 'a'+j, &rx, &tx)
			}
		}
	}
}
Ejemplo n.º 14
0
func TestSnapshotBad(t *testing.T) {
	buf := bytes.NewBuffer([]byte{})
	gob.NewEncoder(buf).Encode(uint64(1))
	seqnPart := buf.String()

	buf = bytes.NewBuffer([]byte{})
	gob.NewEncoder(buf).Encode(emptyDir)
	valPart := buf.String()
	valPart = valPart[0 : len(valPart)/2]

	st := New()
	st.Ops <- Op{1, seqnPart + valPart}
	st.Sync(1)

	// check that we aren't leaking memory
	assert.Equal(t, 0, len(st.todo))
}
Ejemplo n.º 15
0
// serialize encodes a session value using gob.
func serialize(session SessionData) ([]byte, error) {
	b := bytes.NewBuffer(nil)
	e := gob.NewEncoder(b)
	if err := e.Encode(session); err != nil {
		return nil, err
	}
	return b.Bytes(), nil
}
Ejemplo n.º 16
0
func (Tgene *TGene) Save(file io.Writer) {
	enc := gob.NewEncoder(file)
	err := enc.Encode(Tgene)
	if err != nil {
		panic(err.String())
	}
	return
}
Ejemplo n.º 17
0
func TestMe(t *testing.T) {
	if len(Recipe_list) == 0 {
		t.Error(":(")
	}
	e := gob.NewEncoder(os.Stdout)
	//r := Recipe_list[0]
	e.Encode(Recipe_list)
}
Ejemplo n.º 18
0
// Call invokes a delayed function.
// Note that the function will be executed later.
func (f *Function) Call(c appengine.Context, args ...interface{}) {
	if f.err != nil {
		c.Errorf("delay: func is invalid: %v", f.err)
		return
	}

	nArgs := len(args) + 1 // +1 for the appengine.Context
	ft := f.fv.Type()
	minArgs := ft.NumIn()
	if ft.IsVariadic() {
		minArgs--
	}
	if nArgs < minArgs {
		c.Errorf("delay: too few arguments to func: %d < %d", nArgs, minArgs)
		return
	}
	if !ft.IsVariadic() && nArgs > minArgs {
		c.Errorf("delay: too many arguments to func: %d > %d", nArgs, minArgs)
		return
	}

	// Check arg types.
	for i := 1; i < nArgs; i++ {
		at := reflect.TypeOf(args[i-1])
		var dt reflect.Type
		if i < minArgs {
			// not a variadic arg
			dt = ft.In(i)
		} else {
			// a variadic arg
			dt = ft.In(minArgs).Elem()
		}
		if !at.AssignableTo(dt) {
			c.Errorf("delay: argument %d has wrong type: %v is not assignable to %v", i, at, dt)
			return
		}
	}

	inv := invocation{
		Key:  f.key,
		Args: args,
	}

	buf := new(bytes.Buffer)
	if err := gob.NewEncoder(buf).Encode(inv); err != nil {
		c.Errorf("delay: gob encoding failed: %v", err)
		return
	}

	task := &taskqueue.Task{
		Path:    path,
		Payload: buf.Bytes(),
	}
	if _, err := taskqueueAdder(c, task, queue); err != nil {
		c.Errorf("delay: taskqueue.Add failed: %v", err)
		return
	}
}
Ejemplo n.º 19
0
// Write the game database in a fast binary Go-specific format
func WriteGob(filename string, database *Database) {
	f, err := os.Open(filename, os.O_WRONLY|os.O_TRUNC|os.O_CREAT, 0x1a4) // 0644
	if err != nil {
		panic(fmt.Sprintf("error saving %s: %s", filename, err))
	}

	e := gob.NewEncoder(f)
	e.Encode(database)
}
Ejemplo n.º 20
0
func putMetaInfo(fin, fout *os.File, cb []cbRecord) {
	var meta nMeta
	meta.Cb = make([]cbRecord, 256)
	for k, v := range cb {
		meta.Cb[k] = v
	}
	meta.Fsize = GetFileSize(fin)
	PanicIf(gob.NewEncoder(fout).Encode(meta))
}
Ejemplo n.º 21
0
func newEncodeDecodeCloser(rwc io.ReadWriteCloser) *EncodeDecodeCloser {
	p := prof.NewReadWriteCloser(rwc)
	return &EncodeDecodeCloser{
		p,
		gob.NewEncoder(p),
		gob.NewDecoder(p),
		p,
	}
}
Ejemplo n.º 22
0
// NewClient returns a new Client to handle requests to the
// set of services at the other end of the connection.
func NewClient(conn io.ReadWriteCloser) *Client {
	client := new(Client);
	client.conn = conn;
	client.enc = gob.NewEncoder(conn);
	client.dec = gob.NewDecoder(conn);
	client.pending = make(map[uint64]*Call);
	go client.input();
	return client;
}
Ejemplo n.º 23
0
func saveToken(file string, token *oauth.Token) {
	f, err := os.Create(file)
	if err != nil {
		log.Printf("Warning: failed to cache oauth token: %v", err)
		return
	}
	defer f.Close()
	gob.NewEncoder(f).Encode(token)
}
Ejemplo n.º 24
0
func MakeFileWriter(fileprefix string) (*FileWriter, os.Error) {
	w := &FileWriter{prefix: fileprefix}
	err := w.recycle()
	if err != nil {
		return nil, err
	}
	w.enc = gob.NewEncoder(w)
	return w, nil
}
Ejemplo n.º 25
0
func (t *LunchTracker) persist(poll LunchPoll) {
	file, err := os.Open(*dataFile, os.O_WRONLY|os.O_CREATE, 0600)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	encode := gob.NewEncoder(file)
	encode.Encode(poll)
}
Ejemplo n.º 26
0
// Encodes the entire storage state, including the current sequence number, as
// a mutation. This mutation can be applied to an empty store to reproduce the
// state of `s`.
//
// Returns the sequence number of the snapshot and the mutation itself.
//
// A snapshot must be applied at sequence number 1. Once a snapshot has been
// applied, the store's sequence number will be set to `seqn`.
//
// Note that applying a snapshot does not send notifications.
func (st *Store) Snapshot() (seqn uint64, mutation string) {
	w := new(bytes.Buffer)

	// WARNING: Be sure to read the pointer value of st.state only once. If you
	// need multiple accesses, copy the pointer first.
	ss := st.state

	err := gob.NewEncoder(w).Encode(ss.ver)
	if err != nil {
		panic(err)
	}

	err = gob.NewEncoder(w).Encode(ss.root)
	if err != nil {
		panic(err)
	}

	return ss.ver, w.String()
}
Ejemplo n.º 27
0
func NewTube(rwc io.ReadWriteCloser, r *bufio.Reader) *Tube {
	if r == nil {
		r = bufio.NewReader(rwc)
	}
	return &Tube{
		ReadWriteCloser: rwc,
		Reader:          r,
		Encoder:         gob.NewEncoder(rwc),
		Decoder:         gob.NewDecoder(r),
	}
}
Ejemplo n.º 28
0
func Dial() *rpc.Client {
	httpClient := &http.Client{}
	buf := &bytes.Buffer{}
	codec := &Codec{
		client: httpClient,
		enc:    gob.NewEncoder(buf),
		encBuf: buf,
	}
	codec.m.Lock()
	return rpc.NewClientWithCodec(codec)
}
Ejemplo n.º 29
0
func TestGobbable(t *testing.T) {
	tg := treegen.New()
	treeSpec := tg.D("foo",
		tg.D("bar",
			tg.D("aleph",
				tg.F("A", tg.B(42, 65537)),
				tg.F("a", tg.B(42, 65537))),
			tg.D("beth",
				tg.F("B", tg.B(43, 65537)),
				tg.F("b", tg.B(43, 65537))),
			tg.D("jimmy",
				tg.F("G", tg.B(44, 65537)),
				tg.F("g", tg.B(44, 65537)))),
		tg.D("baz",
			tg.D("uno",
				tg.F("1", tg.B(1, 65537)),
				tg.F("I", tg.B(1, 65537))),
			tg.D("dos",
				tg.F("2", tg.B(11, 65537)),
				tg.F("II", tg.B(11, 65537))),
			tg.D("tres",
				tg.F("3", tg.B(111, 65537)),
				tg.F("III", tg.B(111, 65537)))))

	path := treegen.TestTree(t, treeSpec)
	defer os.RemoveAll(path)

	foo, err := IndexDir(filepath.Join(path, "foo"))
	assert.Tf(t, err == nil, "%v", err)

	node, found := foo.Resolve(filepath.Join("bar", "aleph", "A"))
	assert.Equal(t, filepath.Join("bar", "aleph", "A"), RelPath(node))

	bufferEnc := bytes.NewBuffer([]byte{})
	encoder := gob.NewEncoder(bufferEnc)
	err = encoder.Encode(foo)
	assert.Tf(t, err == nil, "%v", err)

	bufferDec := bytes.NewBuffer(bufferEnc.Bytes())
	decoder := gob.NewDecoder(bufferDec)

	decFoo := &Dir{}
	err = decoder.Decode(decFoo)
	assert.Tf(t, err == nil, "%v", err)

	node, found = decFoo.Resolve(filepath.Join("bar", "aleph", "A"))
	assert.T(t, found)
	_, isFile := node.(*File)
	assert.T(t, isFile)

	assert.T(t, node.Parent() != nil)
	assert.Equal(t, filepath.Join("bar", "aleph", "A"), RelPath(node))
}
Ejemplo n.º 30
0
func (s *URLStore) saveLoop(filename string) {
	f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		log.Fatal("URLStore:", err)
	}
	e := gob.NewEncoder(f)
	for {
		r := <-s.save
		if err := e.Encode(r); err != nil {
			log.Println("URLStore:", err)
		}
	}
}