Example #1
0
func TestKeyMappingInt64(t *testing.T) {
	for i := 0; i < 10000; i++ {
		num := rand.Int63()
		if i%5 != 0 {
			num = -num
		}
		key, mask := sbitlocation(num)
		if bitcount(mask) != 1 {
			t.Errorf("Expected exactly one bit in mask; found %v", bitcount(mask))
		}
		dcnum := imemberval(key, getbits(mask)[0])
		switch tp := dcnum.(type) {
		case int64:
			if num >= 0 {
				t.Errorf("Expected type \"uint64\": got %v", reflect.Typeof(tp))
			}
			if num != tp {
				t.Errorf("Expected type %v: got %v (%v,%v)", num, tp, key, mask)
			}
		case uint64:
			if num < 0 {
				t.Errorf("Expected type \"int64\": got %v", reflect.Typeof(tp))
			}
			if uint64(num) != tp {
				t.Errorf("Expected type %v: got %v", num, tp)
			}
		default:
			t.Errorf("Expected type \"(u)int64\": got %v", reflect.Typeof(tp))
		}
	}
}
func TestMakeSet(t *testing.T) {
	set := New()
	if reflect.Typeof(set).String() != "*heteroset.Set" {
		t.Errorf("Expected type \"*heteroset.Set\": got %v", reflect.Typeof(set).String())
	}
	if set.Cardinality() != 0 {
		t.Errorf("Expected bitcount 0: got %v", set.Cardinality())
	}
	if set.root != nil {
		t.Errorf("Root is not nil")
	}
	has := set.Has(Int(1))
	if has {
		t.Errorf("Unexpectedly has Int")
	}
	if max_depth(set.root) != 0 {
		t.Errorf("Expected 0 max depth got: %v", max_depth(set.root))
	}
	has = set.Has(Real(1.0))
	if has {
		t.Errorf("Unexpectedly has Real")
	}
	if max_depth(set.root) != 0 {
		t.Errorf("Expected 0 max depth got: %v", max_depth(set.root))
	}
}
func init() {
	var iop, uop decOp
	switch reflect.Typeof(int(0)).Bits() {
	case 32:
		iop = decInt32
		uop = decUint32
	case 64:
		iop = decInt64
		uop = decUint64
	default:
		panic("gob: unknown size of int/uint")
	}
	decOpMap[reflect.Int] = iop
	decOpMap[reflect.Uint] = uop

	// Finally uintptr
	switch reflect.Typeof(uintptr(0)).Bits() {
	case 32:
		uop = decUint32
	case 64:
		uop = decUint64
	default:
		panic("gob: unknown size of uintptr")
	}
	decOpMap[reflect.Uintptr] = uop
}
Example #4
0
func newSysChans(p *proxyImpl) *sysChans {
	sc := new(sysChans)
	sc.proxy = p
	r := p.router
	sc.pubSubInfo = make(chan *genericMsg, DefCmdChanBufSize)
	sc.sysRecvChans = newRecvChanBundle(p, ScopeLocal, MemberRemote)
	sc.sysSendChans = newSendChanBundle(p, ScopeLocal, MemberRemote)
	//
	pubSubChanType := reflect.Typeof(make(chan *IdChanInfoMsg)).(*reflect.ChanType)
	connChanType := reflect.Typeof(make(chan *ConnInfoMsg)).(*reflect.ChanType)
	readyChanType := reflect.Typeof(make(chan *ConnReadyMsg)).(*reflect.ChanType)

	sc.sysRecvChans.AddRecver(r.SysID(PubId), newGenericMsgChan(r.SysID(PubId), sc.pubSubInfo, false), -1 /*no flow control*/)
	sc.sysRecvChans.AddRecver(r.SysID(UnPubId), newGenericMsgChan(r.SysID(UnPubId), sc.pubSubInfo, false), -1 /*no flow control*/)
	sc.sysRecvChans.AddRecver(r.SysID(SubId), newGenericMsgChan(r.SysID(SubId), sc.pubSubInfo, false), -1 /*no flow control*/)
	sc.sysRecvChans.AddRecver(r.SysID(UnSubId), newGenericMsgChan(r.SysID(UnSubId), sc.pubSubInfo, false), -1 /*no flow control*/)

	sc.sysSendChans.AddSender(r.SysID(ConnId), connChanType)
	sc.sysSendChans.AddSender(r.SysID(DisconnId), connChanType)
	sc.sysSendChans.AddSender(r.SysID(ErrorId), connChanType)
	sc.sysSendChans.AddSender(r.SysID(ReadyId), readyChanType)
	sc.sysSendChans.AddSender(r.SysID(PubId), pubSubChanType)
	sc.sysSendChans.AddSender(r.SysID(UnPubId), pubSubChanType)
	sc.sysSendChans.AddSender(r.SysID(SubId), pubSubChanType)
	sc.sysSendChans.AddSender(r.SysID(UnSubId), pubSubChanType)
	return sc
}
Example #5
0
// ImportNValues imports a channel of the given type and specified direction
// and then receives or transmits up to n values on that channel.  A value of
// n==0 implies an unbounded number of values.  The channel to be bound to
// the remote site's channel is provided in the call and may be of arbitrary
// channel type.
// Despite the literal signature, the effective signature is
//	ImportNValues(name string, chT chan T, dir Dir, pT T)
// where T must be a struct, pointer to struct, etc.  pT may be more indirect
// than the value type of the channel (e.g.  chan T, pT *T) but it must be a
// pointer.
// Example usage:
//	imp, err := NewImporter("tcp", "netchanserver.mydomain.com:1234")
//	if err != nil { log.Exit(err) }
//	ch := make(chan myType)
//	err := imp.ImportNValues("name", ch, Recv, new(myType), 1)
//	if err != nil { log.Exit(err) }
//	fmt.Printf("%+v\n", <-ch)
// (TODO: Can we eliminate the need for pT?)
func (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, pT interface{}, n int) os.Error {
	ch, err := checkChan(chT, dir)
	if err != nil {
		return err
	}
	// Make sure pT is a pointer (to a pointer...) to a struct.
	rt := reflect.Typeof(pT)
	if _, ok := rt.(*reflect.PtrType); !ok {
		return os.ErrorString("not a pointer:" + rt.String())
	}
	if _, ok := reflect.Indirect(reflect.NewValue(pT)).(*reflect.StructValue); !ok {
		return os.ErrorString("not a pointer to a struct:" + rt.String())
	}
	imp.chanLock.Lock()
	defer imp.chanLock.Unlock()
	_, present := imp.chans[name]
	if present {
		return os.ErrorString("channel name already being imported:" + name)
	}
	ptr := reflect.MakeZero(reflect.Typeof(pT)).(*reflect.PtrValue)
	imp.chans[name] = &importChan{ch, dir, ptr, n}
	// Tell the other side about this channel.
	req := new(request)
	req.name = name
	req.dir = dir
	req.count = n
	if err := imp.encode(req, nil); err != nil {
		log.Stderr("importer request encode:", err)
		return err
	}
	return nil
}
Example #6
0
func main() {
	// check that reflect paths are correct,
	// meaning that reflect data for v0, v1 didn't get confused.

	// path is full (rooted) path name.  check suffix for gc, prefix for gccgo
	if s := reflect.Typeof(v0).PkgPath(); !strings.HasSuffix(s, "/bug0") && !strings.HasPrefix(s, "bug0") {
		panicln("bad v0 path", len(s), s)
	}
	if s := reflect.Typeof(v1).PkgPath(); !strings.HasSuffix(s, "/bug1") && !strings.HasPrefix(s, "bug1") {
		panicln("bad v1 path", s)
	}

	// check that dynamic interface check doesn't get confused
	var i interface{} = t0(0)
	if _, ok := i.(I1); ok {
		panicln("used t0 as i1")
	}
	if _, ok := i.(p1.I); ok {
		panicln("used t0 as p1.I")
	}

	i = t1(1)
	if _, ok := i.(I0); ok {
		panicln("used t1 as i0")
	}
	if _, ok := i.(p0.I); ok {
		panicln("used t1 as p0.I")
	}

	// check that type switch works.
	// the worry is that if p0.T and p1.T have the same hash,
	// the binary search will handle one of them incorrectly.
	for j := 0; j < 3; j++ {
		switch j {
		case 0:
			i = p0.T{}
		case 1:
			i = p1.T{}
		case 2:
			i = 3.14
		}
		switch k := i.(type) {
		case p0.T:
			if j != 0 {
				panicln("type switch p0.T")
			}
		case p1.T:
			if j != 1 {
				panicln("type switch p1.T")
			}
		default:
			if j != 2 {
				panicln("type switch default", j)
			}
		}
	}
}
Example #7
0
func init() {
	kindEncoder = map[reflect.Kind]encoderFunc{
		reflect.Array:     encodeArrayOrSlice,
		reflect.Bool:      encodeBool,
		reflect.Float32:   encodeFloat,
		reflect.Float64:   encodeFloat,
		reflect.Int32:     encodeInt,
		reflect.Int64:     func(e *encodeState, name string, value reflect.Value) { encodeInt64(e, kindInt64, name, value) },
		reflect.Int:       encodeInt,
		reflect.Interface: encodeInterfaceOrPtr,
		reflect.Map:       encodeMap,
		reflect.Ptr:       encodeInterfaceOrPtr,
		reflect.Slice:     encodeArrayOrSlice,
		reflect.String:    func(e *encodeState, name string, value reflect.Value) { encodeString(e, kindString, name, value) },
		reflect.Struct:    encodeStruct,
	}
	typeEncoder = map[reflect.Type]encoderFunc{
		typeDoc:                         encodeDoc,
		typeBSONData:                    encodeBSONData,
		reflect.Typeof(Code("")):        func(e *encodeState, name string, value reflect.Value) { encodeString(e, kindCode, name, value) },
		reflect.Typeof(CodeWithScope{}): encodeCodeWithScope,
		reflect.Typeof(DateTime(0)):     func(e *encodeState, name string, value reflect.Value) { encodeInt64(e, kindDateTime, name, value) },
		reflect.Typeof(MinMax(0)):       encodeMinMax,
		reflect.Typeof(ObjectId{}):      encodeObjectId,
		reflect.Typeof(Regexp{}):        encodeRegexp,
		reflect.Typeof(Symbol("")):      func(e *encodeState, name string, value reflect.Value) { encodeString(e, kindSymbol, name, value) },
		reflect.Typeof(Timestamp(0)):    func(e *encodeState, name string, value reflect.Value) { encodeInt64(e, kindTimestamp, name, value) },
		reflect.Typeof([]byte{}):        encodeByteSlice,
	}
}
Example #8
0
func TestConversion(t *testing.T) {
	var cs *cloud2dStr
	if err := xml.Unmarshal(strings.NewReader(test_aida_string), &cs); err != nil {
		t.Errorf("xml.Unmarshal: %q", err)
	}
	c := cs.Convert()
	fmt.Println(reflect.Typeof(cs))
	fmt.Println(reflect.Typeof(c))
	fmt.Println(reflect.Typeof(cs).Name())
	fmt.Println(reflect.Typeof(c).Name())
}
Example #9
0
func cmp_type(a, b interface{}) int {
	ta := reflect.Typeof(a)
	tb := reflect.Typeof(b)
	if ta == tb {
		return 0
	}
	if cp := cmp_string(ta.PkgPath(), tb.PkgPath()); cp != 0 {
		return cp
	}
	return cmp_string(ta.Name(), tb.Name())
}
Example #10
0
func TestMakeSetWithMembers(t *testing.T) {
	set := Make(-1, 28, 18, 28, 9)
	if reflect.Typeof(set).String() != "*bitset.Set" {
		t.Errorf("Expected type \"*bitset.Set\": got %v", reflect.Typeof(set).String())
	}
	if set.bitcount != 4 {
		t.Errorf("Expected bitcount 4: got %v", set.bitcount)
	}
	if set.bits == nil {
		t.Errorf("Bit map unitialized")
	}
}
Example #11
0
// Reregister some basic types to check registration is idempotent.
func TestReregistration(t *testing.T) {
	newtyp := getTypeUnlocked("int", reflect.Typeof(int(0)))
	if newtyp != tInt.gobType() {
		t.Errorf("reregistration of %s got new type", newtyp.string())
	}
	newtyp = getTypeUnlocked("uint", reflect.Typeof(uint(0)))
	if newtyp != tUint.gobType() {
		t.Errorf("reregistration of %s got new type", newtyp.string())
	}
	newtyp = getTypeUnlocked("string", reflect.Typeof("hello"))
	if newtyp != tString.gobType() {
		t.Errorf("reregistration of %s got new type", newtyp.string())
	}
}
Example #12
0
func init() {
	kindDecoder = map[reflect.Kind]decoderFunc{
		reflect.Bool:      decodeBool,
		reflect.Float32:   decodeFloat,
		reflect.Float64:   decodeFloat,
		reflect.Int32:     decodeInt,
		reflect.Int64:     decodeInt,
		reflect.Int:       decodeInt,
		reflect.Interface: decodeInterface,
		reflect.Map:       decodeMap,
		reflect.String:    decodeString,
		reflect.Struct:    decodeStruct,
		reflect.Slice:     decodeSlice,
		reflect.Array:     decodeArray,
	}
	typeDecoder = map[reflect.Type]decoderFunc{
		reflect.Typeof(BSONData{}):                   decodeBSONData,
		reflect.Typeof(DateTime(0)):                  decodeDateTime,
		reflect.Typeof(MinMax(0)):                    decodeMinMax,
		reflect.Typeof(ObjectId{}):                   decodeObjectId,
		reflect.Typeof(Symbol("")):                   decodeString,
		reflect.Typeof(Timestamp(0)):                 decodeTimestamp,
		reflect.Typeof([]byte{}):                     decodeByteSlice,
		reflect.Typeof(make(map[string]interface{})): decodeMapStringInterface,
	}
}
Example #13
0
func TestEndToEnd(t *testing.T) {
	type T2 struct {
		t string
	}
	s1 := "string1"
	s2 := "string2"
	type T1 struct {
		a, b, c int
		n       *[3]float
		strs    *[2]string
		int64s  *[]int64
		s       string
		y       []byte
		t       *T2
	}
	t1 := &T1{
		a:      17,
		b:      18,
		c:      -5,
		n:      &[3]float{1.5, 2.5, 3.5},
		strs:   &[2]string{s1, s2},
		int64s: &[]int64{77, 89, 123412342134},
		s:      "Now is the time",
		y:      strings.Bytes("hello, sailor"),
		t:      &T2{"this is T2"},
	}
	b := new(bytes.Buffer)
	encode(b, t1)
	var _t1 T1
	decode(b, getTypeInfoNoError(reflect.Typeof(_t1)).id, &_t1)
	if !reflect.DeepEqual(t1, &_t1) {
		t.Errorf("encode expected %v got %v", *t1, _t1)
	}
}
Example #14
0
func init() {
	sampleValues = []interface{}{
		true,
		false,
		int(42), int8(42), int16(42), int32(42), int64(42),
		uint(42), uint8(42), uint16(42), uint32(42), uint64(42),
		float32(42), float64(42),
		complex(42, 42), complex64(42), complex128(42),
		"42",
		struct{ Field int }{Field: 42},
		&struct{ Field int }{Field: 42},
		reflect.Typeof(struct{ Field int }{Field: 42}),
		make(chan int, 42),
		func() int { return 42 },
		map[string]int{"forty": 40, "two": 2, "forty-two": 42},
		[]int{40, 41, 42},
		[...]int{40, 41, 42},
		[42]int{2: 40, 40: 2},
		nil,
		uninitialized,
		uninitialized._chan,
		uninitialized._func,
		uninitialized._interface,
		uninitialized._map,
		uninitialized._pointer,
		uninitialized._slice,
	}
}
Example #15
0
func printItems(m Dict) {
	typ := reflect.Typeof(m)
	fmt.Printf("Dumping map(type=%s)...\n", typ.String())
	for item := range m.Iter() {
		fmt.Printf("%s: %d\n", item.key, item.val.(int))
	}
}
Example #16
0
func Get(conn *sqlite.Conn, kind interface{}, id string) interface{} {
	result := reflect.NewValue(kind)
	tableType := reflect.Typeof(kind).(*reflect.StructType)
	numColumns := tableType.NumField()
	schemaArray := make([]string, numColumns)
	things := make([]interface{}, numColumns)
	_ = unsafe.Unreflect

	for i := 0; i < numColumns; i++ {
		name := tableType.Field(i).Name
		schemaArray[i] = strings.ToLower(name)
		field := result.(*reflect.StructValue).Field(i)
		k := field.Interface()
		things[i] = k
		fmt.Printf("%v.", k)
	}
	str := "SELECT " + strings.Join(schemaArray, ", ") + " FROM " + tableType.Name() + " WHERE id = ?"

	stmt, _ := conn.Prepare(str)
	HandleError(stmt.Exec(id))

	if stmt.Next() {
		HandleError(stmt.Scan(things...))
	}
	return result
}
Example #17
0
File: web.go Project: tjweir/web.go
func init() {
	contextType = reflect.Typeof(Context{})

	cwd := os.Getenv("PWD")
	templateDir = path.Join(cwd, "templates")
	staticDir = path.Join(cwd, "static")
}
Example #18
0
func logSamples(t *testing.T, matcher *base.Matcher) {
	t.Logf("Sample results for: %v\n", matcher)
	t.Logf("\ton true: %v\n", matcher.Match(true))
	t.Logf("\ton false: %v\n", matcher.Match(false))
	t.Logf("\ton int: %v\n", matcher.Match(42))
	t.Logf("\ton uint: %v\n", matcher.Match(uint(42)))
	t.Logf("\ton float: %v\n", matcher.Match(42.0))
	t.Logf("\ton string: %v\n", matcher.Match("foobar"))
	t.Logf("\ton struct: %v\n", matcher.Match(struct{ Field int }{Field: 42}))
	t.Logf("\ton type: %v\n", matcher.Match(reflect.Typeof(uninitialized)))

	t.Logf("\ton channel: %v\n", matcher.Match(make(chan int, 1)))
	t.Logf("\ton function: %v\n", matcher.Match(func() int { return 1 }))
	t.Logf("\ton function: %v\n", matcher.Match(interface{}(nil)))
	t.Logf("\ton map: %v\n", matcher.Match(map[int]string{1: "one", 2: "two"}))
	t.Logf("\ton pointer: %v\n", matcher.Match(&struct{ Field int }{Field: 42}))
	t.Logf("\ton slice: %v\n", matcher.Match([]int{1}))

	t.Logf("\ton nil: %v\n", matcher.Match(nil))
	t.Logf("\ton nil channel: %v\n", matcher.Match(uninitialized._chan))
	t.Logf("\ton nil function: %v\n", matcher.Match(uninitialized._func))
	t.Logf("\ton nil interface: %v\n", matcher.Match(uninitialized._interface))
	t.Logf("\ton nil map: %v\n", matcher.Match(uninitialized._map))
	t.Logf("\ton nil pointer: %v\n", matcher.Match(uninitialized._pointer))
	t.Logf("\ton nil slice: %v\n", matcher.Match(uninitialized._slice))
}
Example #19
0
func TestIgnoredFields(t *testing.T) {
	var it0 IT0
	it0.a = 17
	it0.b = "hello"
	it0.c = 3.14159
	it0.ignore_d = []int{1, 2, 3}
	it0.ignore_e[0] = 1.0
	it0.ignore_e[1] = 2.0
	it0.ignore_e[2] = 3.0
	it0.ignore_f = true
	it0.ignore_g = "pay no attention"
	it0.ignore_h = strings.Bytes("to the curtain")
	it0.ignore_i = &RT1{3.1, "hi", 7, "hello"}

	b := new(bytes.Buffer)
	encode(b, it0)
	rt0Id := getTypeInfoNoError(reflect.Typeof(it0)).id
	var rt1 RT1
	// Wire type is IT0, local type is RT1.
	err := decode(b, rt0Id, &rt1)
	if err != nil {
		t.Error("error: ", err)
	}
	if int(it0.a) != rt1.a || it0.b != rt1.b || it0.c != rt1.c {
		t.Errorf("rt1->rt0: expected %v; got %v", it0, rt1)
	}
}
Example #20
0
// Encode transmits the data item represented by the empty interface value,
// guaranteeing that all necessary type information has been transmitted first.
func (enc *Encoder) Encode(e interface{}) os.Error {
	if enc.state.b.Len() > 0 || enc.countState.b.Len() > 0 {
		panicln("Encoder: buffer not empty")
	}
	rt, _ := indirect(reflect.Typeof(e))

	// Make sure we're single-threaded through here.
	enc.mutex.Lock()
	defer enc.mutex.Unlock()

	// Make sure the type is known to the other side.
	// First, have we already sent this type?
	if _, alreadySent := enc.sent[rt]; !alreadySent {
		// No, so send it.
		enc.sendType(rt, true)
		if enc.state.err != nil {
			enc.state.b.Reset()
			enc.countState.b.Reset()
			return enc.state.err
		}
	}

	// Identify the type of this top-level value.
	encodeInt(enc.state, int64(enc.sent[rt]))

	// Encode the object.
	encode(enc.state.b, e)
	enc.send()

	return enc.state.err
}
Example #21
0
func (self *Controller) AddHandler(regexp string, fun interface{}) {
	self.callbacks.Push(&callback{
		regexp,
		reflect.NewValue(fun).(*reflect.FuncValue),
		reflect.Typeof(fun).(*reflect.FuncType),
	})
}
Example #22
0
func (b *structBuilder) Key(k string) Builder {
	if b == nil {
		return nobuilder
	}
	switch v := reflect.Indirect(b.val).(type) {
	case *reflect.StructValue:
		t := v.Type().(*reflect.StructType)
		// Case-insensitive field lookup.
		k = strings.ToLower(k)
		for i := 0; i < t.NumField(); i++ {
			if strings.ToLower(t.Field(i).Name) == k {
				return &structBuilder{val: v.Field(i)}
			}
		}
	case *reflect.MapValue:
		t := v.Type().(*reflect.MapType)
		if t.Key() != reflect.Typeof(k) {
			break
		}
		key := reflect.NewValue(k)
		elem := v.Elem(key)
		if elem == nil {
			v.SetElem(key, reflect.MakeZero(t.Elem()))
			elem = v.Elem(key)
		}
		return &structBuilder{val: elem, map_: v, key: key}
	}
	return nobuilder
}
Example #23
0
func init() {
	// Some magic numbers to make sure there are no surprises.
	checkId(7, tWireType)
	checkId(9, mustGetTypeInfo(reflect.Typeof(commonType{})).id)
	checkId(11, mustGetTypeInfo(reflect.Typeof(structType{})).id)
	checkId(12, mustGetTypeInfo(reflect.Typeof(fieldType{})).id)
	builtinIdToType = make(map[typeId]gobType)
	for k, v := range idToType {
		builtinIdToType[k] = v
	}
	// Move the id space upwards to allow for growth in the predefined world
	// without breaking existing files.
	if nextId > firstUserId {
		panic(fmt.Sprintln("nextId too large:", nextId))
	}
	nextId = firstUserId
}
Example #24
0
func compare(a, b map[string]reflect.Type) bool {

	ok := true

	for k, v := range b {
		if _, present := a[k]; !present {
			ok = false
			break
		}

		if reflect.Typeof(a[k]) != reflect.Typeof(v) {
			ok = false
			break
		}
	}
	return ok
}
Example #25
0
func TestMakeSet(t *testing.T) {
	set := Make()
	if reflect.Typeof(set).String() != "*bitset.Set" {
		t.Errorf("Expected type \"*bitset.Set\": got %v", reflect.Typeof(set).String())
	}
	if set.bitcount != 0 {
		t.Errorf("Expected bitcount 0: got %v", set.bitcount)
	}
	if set.bits == nil {
		t.Errorf("Bit map unitialized")
	}
	//if set.bits.Len() != 0 {
	if len(set.bits) != 0 {
		//t.Errorf("Expected len(bits) 0: got %v", set.bits.Len());
		t.Errorf("Expected len(bits) 0: got %v", len(set.bits))
	}
}
Example #26
0
// ImportNValues imports a channel of the given type and specified direction
// and then receives or transmits up to n values on that channel.  A value of
// n==0 implies an unbounded number of values.  The channel to be bound to
// the remote site's channel is provided in the call and may be of arbitrary
// channel type.
// Despite the literal signature, the effective signature is
//	ImportNValues(name string, chT chan T, dir Dir, pT T, n int) os.Error
// where T must be a struct, pointer to struct, etc.  pT may be more indirect
// than the value type of the channel (e.g.  chan T, pT *T) but it must be a
// pointer.
// Example usage:
//	imp, err := NewImporter("tcp", "netchanserver.mydomain.com:1234")
//	if err != nil { log.Exit(err) }
//	ch := make(chan myType)
//	err := imp.ImportNValues("name", ch, Recv, new(myType), 1)
//	if err != nil { log.Exit(err) }
//	fmt.Printf("%+v\n", <-ch)
// TODO: fix gob interface so we can eliminate the need for pT, and for structs.
func (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, pT interface{}, n int) os.Error {
	ch, err := checkChan(chT, dir)
	if err != nil {
		return err
	}
	// Make sure pT is a pointer (to a pointer...) to a struct.
	rt := reflect.Typeof(pT)
	if _, ok := rt.(*reflect.PtrType); !ok {
		return os.ErrorString("not a pointer:" + rt.String())
	}
	if _, ok := reflect.Indirect(reflect.NewValue(pT)).(*reflect.StructValue); !ok {
		return os.ErrorString("not a pointer to a struct:" + rt.String())
	}
	imp.chanLock.Lock()
	defer imp.chanLock.Unlock()
	_, present := imp.chans[name]
	if present {
		return os.ErrorString("channel name already being imported:" + name)
	}
	ptr := reflect.MakeZero(reflect.Typeof(pT)).(*reflect.PtrValue)
	imp.chans[name] = &importChan{ch, dir, ptr}
	// Tell the other side about this channel.
	hdr := new(header)
	hdr.name = name
	hdr.payloadType = payRequest
	req := new(request)
	req.dir = dir
	req.count = n
	if err := imp.encode(hdr, payRequest, req); err != nil {
		log.Stderr("importer request encode:", err)
		return err
	}
	if dir == Send {
		go func() {
			for i := 0; n == 0 || i < n; i++ {
				val := ch.Recv()
				if err := imp.encode(hdr, payData, val.Interface()); err != nil {
					log.Stderr("error encoding client response:", err)
					return
				}
			}
		}()
	}
	return nil
}
Example #27
0
func TestStructType(t *testing.T) {
	sstruct := getTypeUnlocked("Foo", reflect.Typeof(Foo{}))
	str := sstruct.string()
	// If we can print it correctly, we built it correctly.
	expected := "Foo = struct { A int; B int; C string; D bytes; E float; F float; G Bar = struct { X string; }; H Bar; I Foo; }"
	if str != expected {
		t.Errorf("struct printed as %q; expected %q", str, expected)
	}
}
Example #28
0
func (p *pp) unknownType(v interface{}) {
	if v == nil {
		p.buf.Write(nilAngleBytes)
		return
	}
	p.buf.WriteByte('?')
	p.buf.WriteString(reflect.Typeof(v).String())
	p.buf.WriteByte('?')
}
Example #29
0
func TestStructType(t *testing.T) {
	sstruct := getTypeUnlocked("Foo", reflect.Typeof(Foo{}))
	str := sstruct.string()
	// If we can print it correctly, we built it correctly.
	expected := "Foo = struct { a int; b int; c string; d bytes; e float; f float; g Bar = struct { x string; }; h Bar; i Foo; }"
	if str != expected {
		t.Errorf("struct printed as %q; expected %q", str, expected)
	}
}
Example #30
0
// RegisterName is like Register but uses the provided name rather than the
// type's default.
func RegisterName(name string, value interface{}) {
	if name == "" {
		// reserved for nil
		panic("attempt to register empty name")
	}
	rt, _ := indirect(reflect.Typeof(value))
	// Check for incompatible duplicates.
	if t, ok := nameToConcreteType[name]; ok && t != rt {
		panic("gob: registering duplicate types for " + name)
	}
	if n, ok := concreteTypeToName[rt]; ok && n != name {
		panic("gob: registering duplicate names for " + rt.String())
	}
	// Store the name and type provided by the user....
	nameToConcreteType[name] = reflect.Typeof(value)
	// but the flattened type in the type table, since that's what decode needs.
	concreteTypeToName[rt] = name
}