diff --git a/code/dbapi.py b/code/dbapi.py index 054cd0a..bf5d96a 100644 --- a/code/dbapi.py +++ b/code/dbapi.py @@ -1,4 +1,6 @@ +# -*- coding: utf-8 -*- import MySQLdb,json +import thread,time #in init function please change the config to fit your own requirement #fetchone(): return type: None/dict @@ -10,9 +12,12 @@ def __init__(self): self.host="localhost" self.user="comhelp" self.passwd="20140629" + #self.user="root" + #self.passwd="root" self.dbname="community" self.charset="utf8" self.db=MySQLdb.connect(host=self.host,user=self.user,passwd=self.passwd,db=self.dbname,charset=self.charset) + thread.start_new_thread(self.setDailyTask, ()) def getUserByUserId(self,userid): cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) @@ -32,6 +37,101 @@ def getUserByUserName(self,username): cursor.close() return result + def getHelperInfoByEid(self,eid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select user.name as username,user.id as uid from helper,user where helper.eid=%s and helper.usrid = user.id" + param=(eid,) + cursor.execute(sql,param) + result=cursor.fetchall() + cursor.close() + return result + + def updateUserstate(self,uid,state): + cursor = self.db.cursor() + sql = "update user set state = %s where id = %s" + param =(state,uid) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + return + + def updateUserCredit(self,uid,credit): + cursor = self.db.cursor() + sql = "update info set credit = %s where id = %s" + param = (credit,uid) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + cursor.close() + return + + def updateUseLBS(self,latitude,longitude,uid): + cursor = self.db.cursor() + sql = "update info set latitude = %s , longitude = %s where id = %s" + param =(latitude,longitude,uid) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + return + + #get user userfull info in user+info + #pre con: user exist + #after: return a dict result include all info of user + def getUserAllinfobyName(self,name): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + uid = self.getUserByUserName(name)['id'] + return self.getUsermessegeByUserId(uid) + + #get user all info in user+info + #pre con: user exist + #after: return a dict result include all info of user + def getUserInfobyName(self,name): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select * from user,info where user.name = %s and user.id = info.id" + param = (name,) + cursor.execute(sql,param) + result=cursor.fetchone() + cursor.close() + return result + + def getUserInfobyUid(self,uid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select * from user,info where user.id = %s and user.id = info.id" + param = (uid,) + cursor.execute(sql,param) + result=cursor.fetchone() + cursor.close() + return result + + def CheckRelationbyId(self,userid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select * from relation where usrid=%s" + param=(userid,) + cursor.execute(sql,param) + result=cursor.fetchall() + cursor.close() + return result + + def getUsermessegeByUserId(self,userid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select user.id,user.name,info.name as realname,info.sex,info.age,info.address,info.illness,info.credit,info.score,phone from user,info where user.id=%s and info.id=%s" + param=(userid,userid) + cursor.execute(sql,param) + result=cursor.fetchone() + cursor.close() + return result + + def getUserByEid(self,eid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select cid,user.id as uid from user,event where event.id= %s and event.usrid=user.id" + param=(eid,) + cursor.execute(sql,param) + result=cursor.fetchone() + cursor.close() + return result + def getEventByEventId(self,eventid): cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) sql="select * from event where id=%s" @@ -41,6 +141,19 @@ def getEventByEventId(self,eventid): cursor.close() return result + def getEventandUserByEventId(self,eventid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="""select user.name as username,user.id as userid,content,starttime as time,event.kind as kind,event.id as eventid, event.latitude as latitude,event.longitude as longitude,Video as video, audio from event,user + where event.id=%s and user.id = event.usrid""" + param=(eventid,) + cursor.execute(sql,param) + result=cursor.fetchone() + result['time'] = result['time'].strftime('%Y-%m-%d %H:%M:%S') + result['longitude'] = float(result['longitude']) + result['latitude'] = float(result['latitude']) + cursor.close() + return result + def getEventsByUserId(self,userid): cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) sql="select * from event where usrid=%s" @@ -54,7 +167,439 @@ def getEventsByUserName(self,username): user=self.getUserByUserName(username) if(not user): return [] - return self.getEventsByUserId(user["userid"]) + return self.getEventsByUserId(user["id"]) + + def getSupportBySid(self,sid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select * from support where id = %s" + param=(sid,) + cursor.execute(sql,param) + result=cursor.fetchone() + cursor.close() + return result + + #get supports by uid + def getSupportsbyUid(self,uid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select user.name,support.eid,support.content,support.time from support,user where usrid = user.id and usrid = %s" + param=(uid,) + cursor.execute(sql,param) + result=cursor.fetchall() + cursor.close() + return list(result) + + #get supports by username + def getSupportsbyUsername(self,username): + user=self.getUserByUserName(username) + if(not user): + return [] + return self.getSupportsbyUid(user["id"]) + + #insert follow uid->eid + def insertFollow(self,uid,eid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + cursor.execute("select now()") + currentTime=cursor.fetchone() + sql = "insert into follow(eid,usrid,time) values(%s,%s,%s)" + param = (eid,uid,currentTime['now()']) + state = 1 + try: + cursor.execute(sql,param) + self.db.commit() + state = 1 + except: + self.db.rollback() + state = 0 + cursor.close() + return state + + #delect follow uid->eid + def delectFollow(self,uid,eid): + cursor = self.db.cursor() + sql = "delete from follow where eid = %s and usrid = %s" + param = (eid,uid) + state = 1 + try: + cursor.execute(sql,param) + self.db.commit() + state = 1 + except: + self.db.rollback() + state = 0 + cursor.close() + return state + + #get follow by uid,eid + #if no recode,rerun None;else return dir + def getFollow(self,uid,eid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select * from follow where eid = %s and usrid = %s" + param = (eid,uid) + cursor.execute(sql,param) + result=cursor.fetchone() + cursor.close() + return result + + def getFollowerCidByEid(self,eid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select user.cid from follow,user where eid = %s and user.id = follow.usrid" + param = (eid,) + cursor.execute(sql,param) + result = [] + for row in cursor.fetchall(): + result.append(row['cid']) + cursor.close() + return result + + def getFollowsByEventId(self,eid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select count(*) as count from follow where eid = %s" + param = (eid,) + cursor.execute(sql,param) + result=cursor.fetchone() + cursor.close() + return result + + + def getHelpersCidbyEid(self,eid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select cid from helper,user where eid = %s and helper.usrid = user.id" + param=(eid,) + cursor.execute(sql,param) + result = [] + for row in cursor.fetchall(): + result.append(row['cid']) + cursor.close() + return result + + def getRelativesCidbyUid(self,uid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select user.cid from relation,user where usrid = %s and relation.cid = user.id" + param=(uid,) + cursor.execute(sql,param) + result = [] + for row in cursor.fetchall(): + result.append(row['cid']) + cursor.close() + return result + + def getRelativesIdbyUid(self,uid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select cid as id from relation where usrid = %s" + param=(uid,) + cursor.execute(sql,param) + result = cursor.fetchall() + cursor.close() + return list(result) + + def getHelpersIdbyUid(self,uid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select DISTINCT helper.usrid as id from event,helper where event.usrid = %s and event.id = helper.eid" + param=(uid,) + cursor.execute(sql,param) + result = cursor.fetchall() + cursor.close() + return list(result) + + #check if cardid exist + #exist return dict + #not exist return none + def getInfoBycardid(self,cardid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select * from info where cardid=%s" + param=(cardid,) + cursor.execute(sql,param) + result=cursor.fetchone() + cursor.close() + return result + + #register a new user + #pre condiction:no user.name,info.cardid duplicate + #after : insert new user,new info + def register(self,content): + cursor = self.db.cursor() + sql = "insert into user(name,kind,password) values(%s,%s,%s)" + param = (content["username"],content["kind"],content["password"]) + cursor.execute(sql,param) + self.db.commit() + + cursor.execute('SELECT LAST_INSERT_ID()') + result=cursor.fetchone() + print result[0] + + sql = "insert into info(id,cardid,name,sex,age,illness,score,phone,vocation) values(%s,%s,%s,%s,%s,%s,%s,%s,%s)" + param = (result[0],content["cardid"],content["realname"],content["sex"],content["age"],content["illness"],0,content["phone"],content["vocation"]) + cursor.execute(sql,param) + self.db.commit() + + cursor.close() + return result[0] + + def getRelationByUserId(self, u_id, r_id): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="SELECT * FROM relation WHERE usrid = '" + u_id + "' AND cid = '" + r_id + "'" + cursor.execute(sql) + row = int(cursor.rowcount) + cursor.close() + return row + + #update user cid by uid + def UpdateCidByuid(self,cid,uid): + cursor = self.db.cursor() + sql ="update user set cid = NULl where cid = %s" + param = (cid,) + cursor.execute(sql,param) + self.db.commit() + + sql = "update user set cid = %s where id = %s" + param = (cid,uid) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + return + + def UpdateInfotimebyUid(self,uid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + cursor.execute("select now()") + currentTime=cursor.fetchone() + sql ="update info set time = %s where id = %s" + print currentTime['now()'] + param = (currentTime['now()'],uid) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + cursor.close() + return + def updateUserbetagama(self,uid,beta,gama): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql ="update info set beta = %s, gama = %s where id = %s" + param = (beta,gama,uid) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + cursor.close() + return + + #get all relativeName by user.id + #return a list contain all relations(including uid) + def getAllRelativeNamebyUid(self,uid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select * from relation where usrid = %s and kind = %s" + param = (uid,1) + rlist = [] + rlist.append(uid) + cursor.execute(sql,param) + for row in cursor.fetchall(): + rlist.append(row["cid"]) + return rlist + + # change a event sate to 1 + #in order to end a event + def changeEventState(self,eid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + cursor.execute("select now()") + currentTime=cursor.fetchone() + sql ="update event set state= %s ,endtime = %s where id = %s" + param = (1,currentTime['now()'],eid) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + return currentTime['now()'] + + #cancle a user by user(id) + #pre condiction: uid exist + #after:delete all record of this user + def cancelUser(self,uid): + cursor = self.db.cursor() + sql = "delete from user where id = %s" + param = (uid,) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + return + + #get all events around user(latitude,longitude) inside distance + #pre con:user(latitude,longitude) exist,distance >=0 + #after:return a list contain event info or [] + def getEventAround(self,lon,lat,distance): + cursor = self.db. cursor(cursorclass=MySQLdb.cursors.DictCursor) + #sql = "select round(6378.138*2*asin(sqrt(pow(sin( (event.latitude*pi()/180-(%s)*pi()/180)/2),2)+cos(event.latitude*pi()/180)*cos((%s)*pi()/180)* pow(sin( (event.longitude*pi()/180-(%s)*pi()/180)/2),2)))) from event" + #param = (lat,lat,lon) + sql = """select event.id,user.name,event.kind,event.content,event.starttime,video,audio from event,user where + exists(select id from event where event.latitude <= (%s+1) and event.latitude >= (%s-1) and longitude <= (%s+1) and longitude>=(%s-1)) + and event.usrid = user.id + and event.state = 0 + and round(6378.138*2*asin(sqrt(pow(sin( (event.latitude*pi()/180-(%s)*pi()/180)/2),2)+cos(event.latitude*pi()/180)*cos((%s)*pi()/180)* pow(sin( (event.longitude*pi()/180-(%s)*pi()/180)/2),2)))) < %s + ORDER BY starttime DESC limit 15""" + param = (lat,lat,lon,lon,lat,lat,lon,distance) + cursor.execute(sql,param) + result = [] + for row in cursor.fetchall(): + row['starttime'] = row['starttime'].strftime('%Y-%m-%d %H:%M:%S') + result.append(row) + cursor.close() + return result + + #get all user(cid) around latitude,longitude inside distance(use for push) + #pre condiction:lon,lat exist,distance>=0 + #after :return a list coantain user.cid or [] + def getUserCidAround(self,lon,lat,distance): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = """select user.cid from user,info where + exists(select id from info where latitude <= (%s+1) and latitude >= (%s-1) and longitude <= (%s+1) and longitude>=(%s-1)) + and user.state = 1 + and user.id = info.id + and round(6378.138*2*asin(sqrt(pow(sin( (info.latitude*pi()/180-(%s)*pi()/180)/2),2)+cos(info.latitude*pi()/180)*cos((%s)*pi()/180)* pow(sin( (info.longitude*pi()/180-(%s)*pi()/180)/2),2)))) < %s""" + param = (lat,lat,lon,lon,lat,lat,lon,distance) + cursor.execute(sql,param) + result = [] + for row in cursor.fetchall(): + result.append(row['cid']) + cursor.close() + return result + + def getUserAround(self,lon,lat,distance): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = """select user.name as name from user,info where + exists(select id from info where latitude <= (%s+1) and latitude >= (%s-1) and longitude <= (%s+1) and longitude>=(%s-1)) + and user.id = info.id + and round(6378.138*2*asin(sqrt(pow(sin( (info.latitude*pi()/180-(%s)*pi()/180)/2),2)+cos(info.latitude*pi()/180)*cos((%s)*pi()/180)* pow(sin( (info.longitude*pi()/180-(%s)*pi()/180)/2),2)))) < %s""" + param = (lat,lat,lon,lon,lat,lat,lon,distance) + cursor.execute(sql,param) + sqlre = cursor.fetchall() + cursor.close + result = [] + if(sqlre): + for row in sqlre: + info = {} + info['username'] = row['name'] + result.append(info) + data={'state':1,'users':result} + else: + data={'state':0}#the user not exist,return state 0 + #result=json.dumps(data) + return data + + def getUserAroundbykind(self,lon,lat,distance,kind): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + if(kind == 1): + sql = """select user.id as id,user.name as name,info.credit as credit ,user.cid as cid from user,info where + exists(select id from info where latitude <= (%s+1) and latitude >= (%s-1) and longitude <= (%s+1) and longitude>=(%s-1)) + and user.id = info.id + and (age>=20 and age <=40) + and round(6378.138*2*asin(sqrt(pow(sin( (info.latitude*pi()/180-(%s)*pi()/180)/2),2)+cos(info.latitude*pi()/180)*cos((%s)*pi()/180)* pow(sin( (info.longitude*pi()/180-(%s)*pi()/180)/2),2)))) < %s""" + param = (lat,lat,lon,lon,lat,lat,lon,distance) + elif(kind == 2): + sql ="""select user.id as id,user.name as name,info.credit as credit ,user.cid as cid from user,info where + exists(select id from info where latitude <= (%s+1) and latitude >= (%s-1) and longitude <= (%s+1) and longitude>=(%s-1)) + and user.id = info.id + and (age>=20 and age <=50) + and round(6378.138*2*asin(sqrt(pow(sin( (info.latitude*pi()/180-(%s)*pi()/180)/2),2)+cos(info.latitude*pi()/180)*cos((%s)*pi()/180)* pow(sin( (info.longitude*pi()/180-(%s)*pi()/180)/2),2)))) < %s""" + param = (lat,lat,lon,lon,lat,lat,lon,distance) + else: + sql = """select user.id as id,user.name as name,info.credit as credit ,user.cid as cid from user,info where + exists(select id from info where latitude <= (%s+1) and latitude >= (%s-1) and longitude <= (%s+1) and longitude>=(%s-1)) + and user.id = info.id + and round(6378.138*2*asin(sqrt(pow(sin( (info.latitude*pi()/180-(%s)*pi()/180)/2),2)+cos(info.latitude*pi()/180)*cos((%s)*pi()/180)* pow(sin( (info.longitude*pi()/180-(%s)*pi()/180)/2),2)))) < %s""" + param = (lat,lat,lon,lon,lat,lat,lon,distance) + cursor.execute(sql,param) + sqlre = cursor.fetchall() + return list(sqlre) + + def getAroundbyvocationOrKind(self,lon,lat,vocation,u_kind,vocation_limit,u_limit): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = """(select user.cid as cid from user,info where + exists(select id from info where latitude <= (%s+1) and latitude >= (%s-1) and longitude <= (%s+1) and longitude>=(%s-1)) + and user.id = info.id + and (vocation = %s) + order by round(6378.138*2*asin(sqrt(pow(sin( (info.latitude*pi()/180-(%s)*pi()/180)/2),2)+cos(info.latitude*pi()/180)*cos((%s)*pi()/180)* pow(sin( (info.longitude*pi()/180-(%s)*pi()/180)/2),2)))) asc limit %s) + UNION + (select user.cid as cid from user,info where + exists(select id from info where latitude <= (%s+1) and latitude >= (%s-1) and longitude <= (%s+1) and longitude>=(%s-1)) + and user.id = info.id + and (kind = %s) + order by round(6378.138*2*asin(sqrt(pow(sin( (info.latitude*pi()/180-(%s)*pi()/180)/2),2)+cos(info.latitude*pi()/180)*cos((%s)*pi()/180)* pow(sin( (info.longitude*pi()/180-(%s)*pi()/180)/2),2)))) asc limit %s)""" + param = (lat,lat,lon,lon,vocation,lat,lat,lon,vocation_limit,lat,lat,lon,lon,u_kind,lat,lat,lon,u_limit) + cursor.execute(sql,param) + cursor.close + result = [] + for row in cursor.fetchall(): + result.append(row['cid']) + cursor.close() + return result + + #update user info by username,sex,age,phone,address,illness + #pre cond:uid exist + #after: update user info for what it pass + def updateUserinfo(self,uid,message): + cursor = self.db.cursor() + result = [] + if("realname" in message): + sql = "update info set name = %s where id = %s" + param = (message["realname"],uid) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + return {"state":2,"desc":"db access error username"} + result.append({"state":1,"desc":"update username success"}) + if("sex" in message): + sql = "update info set sex = %s where id = %s" + param = (message["sex"],uid) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + return {"state":2,"desc":"db access error sex"} + result.append({"state":1,"desc":"update sex success"}) + if("age" in message): + sql = "update info set age = %s where id = %s" + param = (message["age"],uid) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + return {"state":2,"desc":"db access error age"} + result.append({"state":1,"desc":"update age success"}) + if("phone" in message): + sql = "update info set phone = %s where id = %s" + param = (message["phone"],uid) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + return {"state":2,"desc":"db access error age"} + result.append({"state":1,"desc":"update age success"}) + if("address" in message): + sql = "update info set address = %s where id = %s" + param = (message["address"],uid) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + return {"state":2,"desc":"db access error address"} + result.append({"state":1,"desc":"update address success"}) + if("illness" in message): + sql = "update info set illness = %s where id = %s" + param = (message["illness"],uid) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + return {"state":2,"desc":"db access error illness"} + result.append({"state":1,"desc":"update illness success"}) + cursor.close() + return result '''Yeqin Zheng, 09/07/2014''' def getRelationByUsername(self, u_name, r_name): @@ -77,43 +622,573 @@ def deleteRelationByUsername(self, u_name, r_name): cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) sql="DELETE FROM relation WHERE usrid = '" + u_id + "' AND cid = '" + r_id + "'" cursor.execute(sql) + self.db.commit() cursor.close() - def addRelationByUsername(self, u_name, r_name): - result = self.getUserByUserName(u_name) - u_id = str(result["id"]) - result = self.getUserByUserName(r_name) - r_id = str(result["id"]) + def addRelationByUid(self, u_id, r_id,kind): cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) - sql="INSERT INTO relation (usrid, cid, kind) VALUES ('" + u_id + "', '" + r_id + "', '1')" - cursor.execute(sql) + sql="INSERT INTO relation(usrid, cid, kind) VALUES(%s,%s,%s)" + param=(u_id,r_id,kind) + cursor.execute(sql,param) + self.db.commit() + sql="INSERT INTO relation(usrid, cid, kind) VALUES(%s,%s,%s)" + param=(r_id,u_id,kind) + cursor.execute(sql,param) + self.db.commit() cursor.close() - def addtempRelationByUsername(self, u_name, r_name): + + def addtempRelationByUsername(self, u_name, r_name,kind,info): result = self.getUserByUserName(u_name) u_id = str(result["id"]) result = self.getUserByUserName(r_name) r_id = str(result["id"]) cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) - sql="INSERT INTO relation (usrid, cid, kind) VALUES ('" + u_id + "', '" + r_id + "', '1')" - cursor.execute(sql) + sql="INSERT INTO temprelation (uid, cid, kind,info) VALUES(%s,%s,%s,%s)" + param=(u_id,r_id,kind,info) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + cursor.close() + + def deletetemprelation(self,uid,cid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="delete from temprelation where uid = %s and cid =%s" + param=(uid,cid) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + cursor.close() + return + + def deletetemprelationwithkind(self,uid,cid,kind): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="delete from temprelation where uid = %s and cid =%s and kind = %s" + param=(uid,cid,kind) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() cursor.close() + return + + def gettemprelationbyCid(self,cid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select * from temprelation where cid =%s" + param=(cid,) + cursor.execute(sql,param) + result = cursor.fetchall() + return list(result) def addaidhelper(self, u_name, e_id): result = self.getUserByUserName(u_name) u_id = str(result["id"]) result = self.getEventByEventId(e_id) - if result["state"] == 0: - return "0" - else : + if(self.checkifUseraddHelper(u_id,e_id) is not None): + print "already add in,do not need add agagin" + return "2" + if result["state"] == 1: + print "current has benn end" + return "3" + else: cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) sql="INSERT INTO helper (eid, usrid) VALUES ('" + e_id + "', '" + u_id + "')" cursor.execute(sql) + self.db.commit() cursor.close() + print "user " +u_name +" add in "+ e_id return "1" + def checkifUseraddHelper(self,userid,eventid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select * from helper where eid=%s and usrid = %s" + param=(eventid,userid) + cursor.execute(sql,param) + result=cursor.fetchone() + print result + return result + + def deleteHelperbyUidEid(self,uid,eid): + cursor=self.db.cursor() + sql="delete from helper where eid = %s and usrid = %s" + param=(eid,uid) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + return + + + #Anton Zhong + def getUserIdByUserName(self,username): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select id from user where name=%s" + param=(username,) + cursor.execute(sql,param) + result=cursor.fetchone() + cursor.close() + return result + + def addEventByUserName(self,username,message): + usrid=self.getUserIdByUserName(username) + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + if(not usrid): + return {"state":2,"errorDesc":"No Such User: "+username} + else: + if(not("kind" in message and "content" in message)): + return {"state":3,"errorDesc":"Messge Incomplete"} + else: + cursor.execute("select now()") + currentTime=cursor.fetchone() + #sql = "select * from event where usrid = %s and kind = %s and latitude = %s and longitude = %s and TIMESTAMPDIFF(MINUTE,%s,starttime)<= 10" + #param = (usrid["id"],message["kind"],message['latitude'],message['longitude'],currentTime['now()']) + #cursor.execute(sql,param) + #if(cursor.fetchall()): + if(False): + return {"state":4,"errorDesc":"cannnot send the same message in 10 minute"} + sql="insert into event (usrid,kind,state,content,starttime,latitude,longitude) values (%s,%s,%s,%s,%s,%s,%s)" + param=(usrid["id"],message["kind"],0,message["content"],currentTime['now()'],message['latitude'],message['longitude']) + cursor.execute(sql,param) + self.db.commit() + + cursor.execute("select last_insert_id()") + eid = cursor.fetchone()["last_insert_id()"] + if(message['videosign'] =="1" and message['audiosign'] =="1"): + self.UpdateEventVideoAndAudio(eid) + elif(message['videosign'] =="1" and message['audiosign'] =="0"): + self.UpdateEventVideo(eid) + elif(message['videosign'] =="0" and message['audiosign'] =="1"): + self.UpdateEventAudio(eid) + return {"state":1,"errorDesc":"","eventid":eid} + cursor.close() + + def UpdateEventVideoAndAudio(self,eid): + cursor = self.db.cursor() + sql = "update event set video = %s,audio = %s where id = %s" + param = ('http://114.215.133.61:8080/static/Video/'+str(eid)+'/'+str(eid)+'.3gp','http://114.215.133.61:8080/static/Audio/'+str(eid)+'/'+str(eid)+'.amr',eid) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + return + + def UpdateEventVideo(self,eid): + cursor = self.db.cursor() + sql = "update event set video = %s where id = %s" + param = ('http://114.215.133.61:8080/static/Video/'+str(eid)+'/'+str(eid)+'.3gp',eid) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + return + + def UpdateEventAudio(self,eid): + cursor = self.db.cursor() + sql = "update event set audio = %s where id = %s" + param = ('http://114.215.133.61:8080/static/Audio/'+str(eid)+'/'+str(eid)+'.amr',eid) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + return + #07/09 + + #seach user by sex,age,kind and return the row of table user + # it has 8 options + def searchUserbySexAgeKind(self,content): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + if('sex' in content): + if('fromage' in content): + if('kind' in content): + sql="select user.id from user,info where info.sex=%s and info.age>=%s and info.age<=%s and user.kind=%s and user.id = info.id" + param=(content['sex'],content['fromage'],content['endage'],content['kind']) + else: + sql="select user.id from user,info where info.sex=%s and info.age>=%s and info.age<=%s and user.id = info.id" + param=(content['sex'],content['fromage'],content['endage']) + else: + if('kind' in content): + sql="select user.id from user,info where info.sex=%s and user.kind=%s and user.id = info.id" + param=(content['sex'],content['kind']) + else: + sql="select info.id from info,user where info.sex=%s and user.id = info.id" + param=(content['sex'],) + else: + if('fromage' in content): + if('kind' in content): + sql="select user.id from user,info where info.age>=%s and info.age<=%s and user.kind=%s and user.id = info.id" + param=(content['fromage'],content['endage'],content['kind']) + else: + sql="select user.id from user,info where info.age>=%s and info.age<=%s and user.id = info.id" + param=(content['fromage'],content['endage']) + else: + if('kind' in content): + sql="select user.id from user,info where user.kind=%s and user.id = info.id" + param=(content['kind'],) + else: + data=[{'state':0}]#input is null return state 0 + result=json.dumps(data) + return result + cursor.execute(sql,param) + result1=cursor.fetchall() + cursor.close() + if(result1): + userlist=[] + for x in result1: + info = {} + info['username'] = self.getUserByUserId(x['id'])['name'] + userlist.append(info) + data={'state':1,'users':userlist}#return the user table successly + else: + data={'state':0}#the user not exist,return state 0 + return data + + #update the password by userid and userpassword + def UpdatePassword(self,content): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + if(content['passwd']): + sql="update user set passwd=%s where id=%s" + param=(content['passwd'],content['id']) + cursor.execute(sql,param) + self.db.commit() + data=[{'state':1}]#update success return state 1 + result=json.dumps(data) + return result + + else: + data=[{'state':0}]#input is null return state 0 + result=json.dumps(data) + return result + cursor.close() + + + #Anton Zhong + def getHelperByEventIdAndUserName(self,eid,username): + usrid=self.getUserIdByUserName(username) + #No such user return none + if(not usrid): + return None + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select * from helper where eid=%s and usrid=%s" + param=(eid,usrid["id"]) + cursor.execute(sql,param) + result=cursor.fetchone() + cursor.close() + return result + + def checkHelperByEventIdAndUserName(self,eid,username): + usrid=self.getUserIdByUserName(username) + if(not usrid): + return False + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select usrid from helper where eid=%s" + param=(eid,) + cursor.execute(sql,param) + result=cursor.fetchone() + if(not result): + return False + return True + + def addSupportByEventIdAndUserName(self,eid,username,message): + #if(not self.checkHelperByEventIdAndUserName(eid,username)): + # return {"errorCode":403,"errorDesc":"No Such Helper"+str(username)+" in event "+str(eid)} + if(not ("content" in message) ): + return {"errorCode":403,"errorDesc":"Messge Incomplete"} + else: + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + cursor.execute("select now()") + currentTime=cursor.fetchone() + sql="insert into support (eid,usrid,content,time) values (%s,%s,%s,%s)" + param=(eid,self.getUserIdByUserName(username)["id"],message["content"],currentTime['now()']) + cursor.execute(sql,param) + self.db.commit() + cursor.execute("select last_insert_id()") + result=cursor.fetchone() + cursor.close() + return {"errorCode":200,"errorDesc":"","supportid":result["last_insert_id()"]} + + def setCreditByEventIdAndUserName(self,eid,username,credit): + if(not self.checkHelperByEventIdAndUserName(eid,username)): + return {"errorCode":403,"errorDesc":"No Such Helper "+str(username)+" in event "+str(eid)} + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="update helper set credit = %s where eid=%s and usrid=%s" + usrid=self.getUserIdByUserName(username) + param=(credit,eid,usrid["id"]) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + #self.updateUserCreditScore(eid,usrid["id"],credit) + return {"errorCode":200,"errorDesc":""} + #07/10 + + def getSupportsByEventId(self,eid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select * from support where eid=%s ORDER BY time DESC" + param=(eid,) + cursor.execute(sql,param) + result=[] + for item in cursor.fetchall(): + item['time'] = item['time'].strftime('%Y-%m-%d %H:%M:%S') + result.append(item) + return result + + #get record from previousEvent + #after:return None or dict + def getpreviousEvent(self,askid,helperid): + cursor=self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql="select * from previousEvent where askid=%s and helperid = %s" + param=(askid,helperid) + cursor.execute(sql,param) + result = cursor.fetchone() + return result + + #insert new record into previousEvent + #after:the table insert a new record + def insertpreviousEvent(self,askid,helperid,credit,eventstarttime): + cursor = self.db.cursor() + sql = "insert into previousEvent(askid,helperid,time,credit) values(%s,%s,%s,%s)" + param = (askid,helperid,eventstarttime,credit) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + cursor.close() + return + + #update the record in previousEvent + #after:update the record of (askid,helpid) + def updatepreviousEvent(self,askid,helperid,credit,eventstarttime): + cursor = self.db.cursor() + sql = "update previousEvent set credit = %s, time = %s where askid = %s and helperid = %s" + param = (credit,eventstarttime,askid,helperid) + try: + cursor.execute(sql,param) + self.db.commit() + except: + self.db.rollback() + cursor.close() + return + + def insertAuth(self, uid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "insert into auth(id, email_state, phone_state) values(%s, 'unauth', 'unauth')" + param = (uid,) + succeed = True + try: + cursor.execute(sql, param) + self.db.commit() + except Exception as e: + succeed = False + print(e) + finally: + cursor.close() + return succeed + + def getAuth(self, uid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select * from auth where id = %s" + param = (uid,) + cursor.execute(sql, param) + result = cursor.fetchone() + cursor.close() + return result + + def updateAuthState(self, uid, kind, newState): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "update auth set %s_state = '%s' where id = %%s" % (kind, newState) + param = (uid,) + cursor.execute(sql, param) + self.db.commit() + cursor.close() + + def updateAuthData(self, uid, kind, value): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "update auth set %s = %%s where id = %%s" % kind + param = (value, uid) + cursor.execute(sql, param) + self.db.commit() + cursor.close() + + # if in limit, return True. + def checkAuthCnt(self, uid, kind, limits): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select * from auth_cnt where id = %%s and kind = \"%s\"" % kind + param = (uid,) + cursor.execute(sql, param) + result = cursor.fetchone() + if result is None: + sql = "insert into auth_cnt(id, kind, cnt) values(%%s, \"%s\", 0)" % kind + cursor.execute(sql, param) + cursor.close() + return True + sql = "select * from auth_cnt where id = %%s and kind = \"%s\" and cnt <= %s" % (kind, limits) + cursor.execute(sql, param) + result = cursor.fetchone() + cursor.close() + if result is None: + return False + else: + return True + + def incAuthCnt(self, uid, kind): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "update auth_cnt set cnt = cnt + 1 where id = %%s and kind = \"%s\"" % kind + param = (uid,) + cursor.execute(sql, param) + self.db.commit() + cursor.close() + + def addEmailCode(self, uid, code, period): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select * from email_code where id = %s" + param = (uid,) + cursor.execute(sql, param) + result = cursor.fetchone() + if result is None: + sql = "insert into email_code(id, code, expire_in) values(%%s, %%s, unix_timestamp() + %s)" % period + param = (uid, code) + else: + sql = "update email_code set code = %%s, expire_in = unix_timestamp() + %s where id = %%s" % period + param = (code, uid) + cursor.execute(sql, param) + self.db.commit() + cursor.close() + + def checkEmailCode(self, uid, code): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select * from email_code where id = %s and code = %s and expire_in > unix_timestamp()" + param = (uid, code) + cursor.execute(sql, param) + result = cursor.fetchone() + if result is None: + return False + else: + return True + + def deleteEmailCode(self, uid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "delete from email_code where id = %s" + param = (uid,) + cursor.execute(sql, param) + self.db.commit() + cursor.close() + + def setDailyTask(self): + while True: + time.sleep(24 * 3600) + self.clearAuthTempData() + + def clearAuthTempData(self): + # clear auth_cnt table + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "delete from auth_cnt" + cursor.execute(sql) + self.db.commit() + # clear out date email code records + sql = "delete from email_code where expire_in < unix_timestamp()" + cursor.execute(sql) + self.db.commit() + cursor.close() + + def addPhoneCode(self, uid, code, period): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select * from phone_code where id = %s" + param = (uid,) + cursor.execute(sql, param) + result = cursor.fetchone() + if result is None: + sql = "insert into phone_code(id, code, expire_in) values(%%s, %%s, unix_timestamp() + %s)" % period + param = (uid, code) + else: + sql = "update phone_code set code = %%s, expire_in = unix_timestamp() + %s where id = %%s" % period + param = (code, uid) + cursor.execute(sql, param) + self.db.commit() + cursor.close() + pass + + def checkPhoneCode(self, uid, code): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select * from phone_code where id = %s and code = %s and expire_in > unix_timestamp()" + param = (uid, code) + cursor.execute(sql, param) + result = cursor.fetchone() + if result is None: + return False + else: + return True + + def deletePhoneCode(self, uid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "delete from phone_code where id = %s" + param = (uid,) + cursor.execute(sql, param) + self.db.commit() + cursor.close() + + def operateScoreById(self,uid,score_op): + cursor = self.db.cursor() + if score_op > 0: + sql = "update info set score = score+%s where id = %s" + else: + sql = "update info set score = score-%s where id = %s" + param = (abs(score_op),uid) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + + def addScoreInfoById(self,uid): + cursor = self.db.cursor() + sql = "insert into score_info(id,login_time) values(%s,%s)" + param = (uid,"2000-01-01 00:00:00") + cursor.execute(sql,param) + self.db.commit() + cursor.close() + + def operateScoreInfoById(self,uid,cond,score_op): + cursor = self.db.cursor() + if score_op > 0: + sql = "update score_info set score"+str(cond)+" = score"+str(cond)+"+%s where id = %s" + else: + sql = "update score_info set score"+str(cond)+" = score"+str(cond)+"-%s where id = %s" + param = (abs(score_op),uid) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + + def getScoreInfoById(self,uid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select * from score_info where id = %s" + param = (uid,) + cursor.execute(sql, param) + result = cursor.fetchone() + if result is None: + return None + else: + return result + + def setScoreTimeById(self,uid,curTime): + cursor = self.db.cursor() + sql = "update score_info set login_time = %s where id = %s" + param = (curTime,uid) + cursor.execute(sql,param) + self.db.commit() + cursor.close() + + def getGreatestHelperId(self,eid): + cursor = self.db.cursor(cursorclass=MySQLdb.cursors.DictCursor) + sql = "select max(credit) from helper where eid = %s" + param = (eid,) + cursor.execute(sql, param) + cre = cursor.fetchone() + cre = cre['max(credit)'] + sql = "select usrid from helper where eid = %s and credit = %s" + param = (eid,cre) + cursor.execute(sql, param) + result = cursor.fetchall() + return result - '''.''' def __del__(self): self.db.close() diff --git a/code/handler/AddaidHandler.py b/code/handler/AddaidHandler.py deleted file mode 100644 index 4237333..0000000 --- a/code/handler/AddaidHandler.py +++ /dev/null @@ -1,17 +0,0 @@ -'''Yeqin Zheng, 09/07/2014''' -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os, json, sys -sys.path.append("..") -import dbapi - -''' Add a helper to an event. Succeed with "1" returned, else with "0". ''' - -class AddaidHandler(tornado.web.RequestHandler): - def post(self): - u_name = self.get_argument('u_name') - e_id = self.get_argument('e_id') - - result = self.application.dbapi.addaidhelper(u_name, e_id) - self.write("{'state': " + result + "}") \ No newline at end of file diff --git a/code/handler/AddrelativesHandler.py b/code/handler/AddrelativesHandler.py deleted file mode 100644 index 644d877..0000000 --- a/code/handler/AddrelativesHandler.py +++ /dev/null @@ -1,24 +0,0 @@ -'''Yeqin Zheng, 09/07/2014''' -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os, json, sys -sys.path.append("..") -import dbapi - -''' Add a relation between two users. Succeed with "1" returned, else with "0". ''' - -class AddrelativesHandler(tornado.web.RequestHandler): - def post(self): - u_name = self.get_argument('u_name') - r_name = self.get_argument('r_name') - - row = self.application.dbapi.getRelationByUsername(u_name, r_name) - if row == 0: - self.application.dbapi.addRelationByUsername(u_name, r_name) - self.application.dbapi.addtempRelationByUsername(u_name, r_name) - add_message = {'state': 1} - else: - add_message = {'state': 0} - - self.write(add_message) diff --git a/code/handler/AuthenHandler.py b/code/handler/AuthenHandler.py deleted file mode 100644 index 87385eb..0000000 --- a/code/handler/AuthenHandler.py +++ /dev/null @@ -1,7 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,dbapi -class AuthenHandler(tornado.web.RequestHandler): - def post(self): - self.write("AuthenHandler") diff --git a/code/handler/Authorize.py b/code/handler/Authorize.py new file mode 100644 index 0000000..fdc2c18 --- /dev/null +++ b/code/handler/Authorize.py @@ -0,0 +1,346 @@ +# encoding: utf-8 +__author__ = 'Administrator' + +import tornado.web +import json +import random +import smtplib +from email.mime.text import MIMEText +from CHRequestHandler import CHRequestHandler, LackParamsException, NoUserException +# +# errorcode: +# 1: 缺少参数 +# 2: 用户名错误,用户不存在 +# +# 查询用户的认证状态 +# +class AuthStateHandler(tornado.web.RequestHandler): + def post(self): + print("mark 2") + content = self.request.body + j = json.loads(content) + if j.has_key("username"): + username = j["username"] + else: + error = { + "error": "lack params", + "request": "querauthstate", + "error_code": 1 + } + self.write(json.dumps(error)) + print("no username supplied") + return + user_record = self.application.dbapi.getUserByUserName(username) + if user_record is None: + error = { + "error": "no such user", + "request": "queryauthstate", + "error_code": 2 + } + self.write(json.dumps(error)) + print("no such user") + return + uid = user_record["id"] + auth_record = self.application.dbapi.getAuth(uid) + if auth_record is None: + self.application.dbapi.insertAuth(uid) + auth_record = self.application.dbapi.getAuth(uid) + result = { + "email": auth_record["email"], + "email_state": auth_record["email_state"], + "phone": auth_record["phone"], + "phone_state": auth_record["phone_state"] + } + print("mark 1") + resultstr = json.dumps(result) + print(resultstr) + self.write(resultstr) + + + +# +# params: +# username +# email +# error_code: +# prefix: 10000 +class RequestEmailAuthHandler(tornado.web.RequestHandler): + codechars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW0123456789" + + host = "114.215.133.61:8080" + mail_host = "smtp.163.com" + mail_user = "CommunityHelp" + mail_pass = "community" + mail_postfix = "163.com" + me = mail_user + "<" + mail_user + "@" + mail_postfix + ">" + msg_content_template = u""" + + + + + + +

社区居民求助系统邮箱验证

+

您好!

+

您已经成功发出了邮箱验证请求。

+

点击以下链接即可完成邮箱验证。如果无法点击,请手动复制网址到浏览器打开。

+

http://%s/api/authemail?username=%s&code=%s

+

请注意,本次验证的有效期为2天。在发送邮件之后的2天内任何时间都可以点击验证。

+

如果超过三天还没有点击该链接,则验证将过期。您需要重新请求邮箱验证。

+

每个用户每天可以请求10次邮箱验证。如果超过10次,请第二天再试。

+ + """ + msg_subject = "社区居民求助系统邮箱验证" + + def post(self): + # get param + content = self.request.body + j = json.loads(content) + if j.has_key("username"): + username = j["username"] + else: + error = { + "error": "lack params", + "request": "requestemailauth", + "error_code": 1 + } + self.write(json.dumps(error)) + print("lack username") + return + # get uid + user_record = self.application.dbapi.getUserByUserName(username) + if user_record is None: + error = { + "error": "no such user", + "request": "requestemailauth", + "error_code": 2 + } + self.write(json.dumps(error)) + print("no such user") + return + uid = user_record["id"] + # get auth record + auth_record = self.application.dbapi.getAuth(uid) + if auth_record is None: + print "mark 2.1" + self.application.dbapi.insertAuth(uid) + print "mark 2.2" + auth_record = self.application.dbapi.getAuth(uid) + # if authed, return error + if auth_record["email_state"] == "authed": + error = { + "error": "authed", + "request": "requestemailauth", + "error_code": 10001 + } + self.write(json.dumps(error)) + return + # find email + if j.has_key("email"): + email = j["email"] + self.application.dbapi.updateAuthData(uid, "email", email) + elif auth_record["email"] != "": + email = auth_record["email"] + else: + error = { + "error": "lack params", + "request": "requestemailauth", + "error_code": 1 + } + self.write(json.dumps(error)) + return + # check request times + if not self.application.dbapi.checkAuthCnt(uid, "email", 10): + error = { + "error": "reach request limits", + "request": "requestemailauth", + "error_code": 10002 + } + self.write(json.dumps(error)) + return + # update auth count + self.application.dbapi.incAuthCnt(uid, "email") + # send email + code = self.getCode(50) + if not self.sendAuthEmail(email, username, code): + error = { + "error": "send email failed", + "request": "requestemailauth", + "error_code": 10003 + } + self.write(json.dumps(error)) + return + # insert email code record + period = 2 * 24 * 3600 + self.application.dbapi.addEmailCode(uid, code, period) + # update auth state + self.application.dbapi.updateAuthState(uid, "email", "authing") + result = { + "result": "OK" + } + self.write(json.dumps(result)) + + def getCode(self, num): + code = "" + for i in range(0, num): + code += random.choice(RequestEmailAuthHandler.codechars) + return code + + def fillMsg(self, username, code): + msg_content = RequestEmailAuthHandler.msg_content_template % (RequestEmailAuthHandler.host, username, code, RequestEmailAuthHandler.host, username, code) + return msg_content + + def sendAuthEmail(self, email, username, code): + msg_content = self.fillMsg(username, code) + msg = MIMEText(msg_content, _subtype = "html", _charset="utf-8") + msg["Subject"] = RequestEmailAuthHandler.msg_subject + msg["From"] = RequestEmailAuthHandler.me + msg["To"] = email + try: + s = smtplib.SMTP() + s.connect(RequestEmailAuthHandler.mail_host) + s.login(RequestEmailAuthHandler.mail_user, RequestEmailAuthHandler.mail_pass) + s.sendmail(RequestEmailAuthHandler.me, email, msg.as_string()) + s.close() + return True + except Exception as e: + return False + print str(e) +# params: +# username +# code +# error_code: +# prefix: 20000 +class AuthEmailHandler(tornado.web.RequestHandler): + def get(self): + try: + username = self.get_argument("username") + code = self.get_argument("code") + except: + error = { + "error": "lack params", + "request": "requestemailauth", + "error_code": 1 + } + self.write(json.dumps(error)) + return + # get uid + user_record = self.application.dbapi.getUserByUserName(username) + if user_record is None: + error = { + "error": "no such user", + "request": "authemail", + "error_code": 1 + } + self.write(json.dumps(error)) + print("no such user") + return + uid = user_record["id"] + if self.application.dbapi.checkEmailCode(uid, code): + self.application.dbapi.updateAuthState(uid, "email", "authed") + self.application.dbapi.deleteEmailCode(uid) + result = { + "result":"OK" + } + self.write(json.dumps(result)) + return + else: + error = { + "error": "email auth code error", + "request": "authemail", + "error_code": 20001 + } + self.write(json.dumps(error)) + return + +# 30001 已认证 +# 30002 超过验证次数 +# 30003 发送短信错误 +class RequestPhoneAuthHandler(CHRequestHandler): + codechars = "0123456789" + + def post(self): + try: + j = self.getParams(["username", "phone"]) + uid = self.getUserId(j["username"]) + phone = j["phone"] + except LackParamsException: + self.writeError(1, "requestphoneauth") + return + except NoUserException: + self.writeError(2, "requestphoneauth") + return + auth_record = self.application.dbapi.getAuth(uid) + if auth_record is None: + self.application.dbapi.insertAuth(uid) + auth_record = self.application.dbapi.getAuth(uid) + if auth_record["phone_state"] == "authed": + self.writeError(30001, "requestphoneauth") + return + if not self.application.dbapi.checkAuthCnt(uid, "phone", 10): + self.writeError(30002, "requestphoneauth") + return + self.application.dbapi.incAuthCnt(uid, "phone") + code = self.getCode(6) + minutes = 10 + if not self.sendSMS(phone, code, minutes): + self.writeError(30003, "requestphoneauth") + period = minutes * 60 + self.application.dbapi.addPhoneCode(uid, code, period) + self.application.dbapi.updateAuthData(uid, "phone", phone) + self.application.dbapi.updateAuthState(uid, "phone", "authing") + self.writeOK() + + + def getCode(self, num): + code = "" + for i in range(0, num): + code += random.choice(RequestPhoneAuthHandler.codechars) + return code + + def sendSMS(self, phone, code, minutes): + datas = [code, minutes] + return sendTemplateSMS(phone, datas, 1) + +from CCPRestSDK import * + +accountSid = "aaf98f89476703de01477c05267506ef" +accountToken = "6b34f62bcc964167a6997286bb9a3f2f" +appId = "aaf98f89476703de01477fc1dda307b1" +serverIP = "sandboxapp.cloopen.com" +serverPort = "8883" +softVersion = "2013-12-26" + +def sendTemplateSMS(to, datas, temId): + rest = REST(serverIP, serverPort, softVersion) + rest.setAccount(accountSid, accountToken) + rest.setAppId(appId) + result = rest.sendTemplateSMS(to, datas, temId) + if result["statusCode"] == "000000": + return True + else: + return False + + +# 40001 验证失败 +class AuthPhoneHandler(CHRequestHandler): + + def post(self): + try: + j = self.getParams(["username", "code"]) + uid = self.getUserId(j["username"]) + code = j["code"] + except LackParamsException: + self.writeError(1, "authphone") + return + except NoUserException: + self.writeError(2, "authphone") + return + if self.application.dbapi.checkPhoneCode(uid, code): + self.application.dbapi.updateAuthState(uid, "phone", "authed") + self.application.dbapi.deletePhoneCode(uid) + self.writeOK() + return + else: + self.writeError(40001, "authphone") + return diff --git a/code/handler/CCPRestSDK.py b/code/handler/CCPRestSDK.py new file mode 100644 index 0000000..5944842 --- /dev/null +++ b/code/handler/CCPRestSDK.py @@ -0,0 +1,656 @@ + #-*- coding: UTF-8 -*- + # Copyright (c) 2014 The CCP project authors. All Rights Reserved. + # + # Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license + # that can be found in the LICENSE file in the root of the web site. + # + # http://www.yuntongxun.com + # + # An additional intellectual property rights grant can be found + # in the file PATENTS. All contributing project authors may + # be found in the AUTHORS file in the root of the source tree. + +import md5 +import base64 +import datetime +import urllib2 +import json +from xmltojson import xmltojson +from xml.dom import minidom + +class REST: + + AccountSid='' + AccountToken='' + AppId='' + SubAccountSid='' + SubAccountToken='' + VoIPAccount='' + VoIPPassword='' + ServerIP='' + ServerPort='' + SoftVersion='' + Iflog=True #是否打印日志 + Batch='' #时间戳 + BodyType = 'json'#包体格式,可填值:json 、xml + + # 初始化 + # @param serverIP 必选参数 服务器地址 + # @param serverPort 必选参数 服务器端口 + # @param softVersion 必选参数 REST版本号 + def __init__(self,ServerIP,ServerPort,SoftVersion): + + self.ServerIP = ServerIP; + self.ServerPort = ServerPort; + self.SoftVersion = SoftVersion; + + + # 设置主帐号 + # @param AccountSid 必选参数 主帐号 + # @param AccountToken 必选参数 主帐号Token + + def setAccount(self,AccountSid,AccountToken): + self.AccountSid = AccountSid; + self.AccountToken = AccountToken; + + + # 设置子帐号 + # + # @param SubAccountSid 必选参数 子帐号 + # @param SubAccountToken 必选参数 子帐号Token + # @param VoIPAccount 必选参数 VoIP帐号 + # @param VoIPPassword 必选参数 VoIP密码 + + def setSubAccount(self,SubAccountSid,SubAccountToken,VoIPAccount,VoIPPassword): + self.SubAccountSid = SubAccountSid; + self.SubAccountToken = SubAccountToken; + self.VoIPAccount = VoIPAccount; + self.VoIPPassword = VoIPPassword; + + # 设置应用ID + # + # @param AppId 必选参数 应用ID + + def setAppId(self,AppId): + self.AppId = AppId; + + def log(self,url,body,data): + print('这是请求的URL:') + print (url); + print('这是请求包体:') + print (body); + print('这是响应包体:') + print (data); + print('********************************') + + + # 创建子账号 + # @param friendlyName 必选参数 子帐号名称 + def CreateSubAccount(self, friendlyName): + + self.accAuth() + nowdate = datetime.datetime.now() + self.Batch = nowdate.strftime("%Y%m%d%H%M%S") + #生成sig + signature = self.AccountSid + self.AccountToken + self.Batch; + sig = md5.new(signature).hexdigest().upper() + #拼接URL + url = "https://"+self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/SubAccounts?sig=" + sig + #生成auth + src = self.AccountSid + ":" + self.Batch; + auth = base64.encodestring(src).strip() + req = urllib2.Request(url) + self.setHttpHeader(req) + req.add_header("Authorization", auth) + #xml格式 + body ='''%s\ + %s\ + \ + '''%(self.AppId, friendlyName) + + if self.BodyType == 'json': + #json格式 + body = '''{"friendlyName": "%s", "appId": "%s"}'''%(friendlyName,self.AppId) + data='' + req.add_data(body) + try: + res = urllib2.urlopen(req); + data = res.read() + res.close() + + if self.BodyType=='json': + #json格式 + locations = json.loads(data) + else: + #xml格式 + xtj=xmltojson() + locations=xtj.main(data) + if self.Iflog: + self.log(url,body,data) + return locations + except Exception, error: + if self.Iflog: + self.log(url,body,data) + return {'172001':'网络错误'} + + # 获取子帐号 + # @param startNo 可选参数 开始的序号,默认从0开始 + # @param offset 可选参数 一次查询的最大条数,最小是1条,最大是100条 + def getSubAccounts(self, startNo,offset): + + self.accAuth() + nowdate = datetime.datetime.now() + self.Batch = nowdate.strftime("%Y%m%d%H%M%S") + #生成sig + signature = self.AccountSid + self.AccountToken + self.Batch; + sig = md5.new(signature).hexdigest().upper() + #拼接URL + url = "https://"+self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/GetSubAccounts?sig=" + sig + #生成auth + src = self.AccountSid + ":" + self.Batch; + auth = base64.encodestring(src).strip() + req = urllib2.Request(url) + self.setHttpHeader(req) + req.add_header("Authorization", auth) + #xml格式 + body ='''%s\ + %s%s\ + \ + '''%(self.AppId, startNo, offset) + + if self.BodyType == 'json': + #json格式 + body = '''{"appId": "%s", "startNo": "%s", "offset": "%s"}'''%(self.AppId,startNo,offset) + data='' + req.add_data(body) + try: + res = urllib2.urlopen(req); + data = res.read() + res.close() + + if self.BodyType=='json': + #json格式 + locations = json.loads(data) + else: + #xml格式 + xtj=xmltojson() + locations=xtj.main(data) + if self.Iflog: + self.log(url,body,data) + return locations + except Exception, error: + if self.Iflog: + self.log(url,body,data) + return {'172001':'网络错误'} + + # 子帐号信息查询 + # @param friendlyName 必选参数 子帐号名称 + + def querySubAccount(self, friendlyName): + + self.accAuth() + nowdate = datetime.datetime.now() + self.Batch = nowdate.strftime("%Y%m%d%H%M%S") + #生成sig + signature = self.AccountSid + self.AccountToken + self.Batch; + sig = md5.new(signature).hexdigest().upper() + #拼接URL + url = "https://"+self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/QuerySubAccountByName?sig=" + sig + #生成auth + src = self.AccountSid + ":" + self.Batch; + auth = base64.encodestring(src).strip() + req = urllib2.Request(url) + self.setHttpHeader(req) + + req.add_header("Authorization", auth) + + #创建包体 + body ='''%s\ + %s\ + \ + '''%(self.AppId, friendlyName) + if self.BodyType == 'json': + + body = '''{"friendlyName": "%s", "appId": "%s"}'''%(friendlyName,self.AppId) + data='' + req.add_data(body) + try: + res = urllib2.urlopen(req); + data = res.read() + res.close() + + if self.BodyType=='json': + #json格式 + locations = json.loads(data) + else: + #xml格式 + xtj=xmltojson() + locations=xtj.main(data) + if self.Iflog: + self.log(url,body,data) + return locations + except Exception, error: + if self.Iflog: + self.log(url,body,data) + return {'172001':'网络错误'} + + # 发送模板短信 + # @param to 必选参数 短信接收彿手机号码集合,用英文逗号分开 + # @param datas 可选参数 内容数据 + # @param tempId 必选参数 模板Id + def sendTemplateSMS(self, to,datas,tempId): + + self.accAuth() + nowdate = datetime.datetime.now() + self.Batch = nowdate.strftime("%Y%m%d%H%M%S") + #生成sig + signature = self.AccountSid + self.AccountToken + self.Batch; + sig = md5.new(signature).hexdigest().upper() + #拼接URL + url = "https://"+self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/SMS/TemplateSMS?sig=" + sig + #生成auth + src = self.AccountSid + ":" + self.Batch; + auth = base64.encodestring(src).strip() + req = urllib2.Request(url) + self.setHttpHeader(req) + req.add_header("Authorization", auth) + #创建包体 + b='' + for a in datas: + b+='%s'%(a) + + body =''+b+'%s%s%s\ + \ + '%(to, tempId,self.AppId) + if self.BodyType == 'json': + # if this model is Json ..then do next code + b='[' + for a in datas: + b+='"%s",'%(a) + b+=']' + body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}'''%(to,b,tempId,self.AppId) + req.add_data(body) + data='' + try: + res = urllib2.urlopen(req); + data = res.read() + res.close() + + if self.BodyType=='json': + #json格式 + locations = json.loads(data) + else: + #xml格式 + xtj=xmltojson() + locations=xtj.main(data) + if self.Iflog: + self.log(url,body,data) + return locations + except Exception, error: + if self.Iflog: + self.log(url,body,data) + return {'172001':'网络错误'} + + # 双向回呼 + # @param fromPhone 必选参数 主叫电话号码 + # @param to 必选参数 被叫电话号码 + # @param customerSerNum 可选参数 被叫侧显示的客服号码 + # @param fromSerNum 可选参数 主叫侧显示的号码 + # @param promptTone 可选参数 第三方自定义回拨提示音 + + def callBack(self,fromPhone,to,customerSerNum,fromSerNum,promptTone): + + self.subAuth() + nowdate = datetime.datetime.now() + self.Batch = nowdate.strftime("%Y%m%d%H%M%S") + #生成sig + signature = self.SubAccountSid + self.SubAccountToken + self.Batch; + sig = md5.new(signature).hexdigest().upper() + #拼接URL + url = "https://"+self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/SubAccounts/" + self.SubAccountSid + "/Calls/Callback?sig=" + sig + #生成auth + src = self.SubAccountSid + ":" + self.Batch; + auth = base64.encodestring(src).strip() + req = urllib2.Request(url) + self.setHttpHeader(req) + + req.add_header("Authorization", auth) + + #创建包体 + body ='''\ + %s%s%s%s%s\ + \ + '''%(fromPhone, to,customerSerNum,fromSerNum,promptTone) + if self.BodyType == 'json': + body = '''{"from": "%s", "to": "%s","customerSerNum": "%s","fromSerNum": "%s","promptTone": "%s"}'''%(fromPhone, to,customerSerNum,fromSerNum,promptTone) + req.add_data(body) + data='' + try: + res = urllib2.urlopen(req); + data = res.read() + res.close() + if self.BodyType=='json': + #json格式 + locations = json.loads(data) + else: + #xml格式 + xtj=xmltojson() + locations=xtj.main(data) + if self.Iflog: + self.log(url,body,data) + return locations + except Exception, error: + if self.Iflog: + self.log(url,body,data) + return {'172001':'网络错误'} + # 营销外呼 + # @param to 必选参数 被叫号码 + # @param mediaName 可选参数 语音文件名称,格式 wav。与mediaTxt不能同时为空。当不为空时mediaTxt属性失效。 + # @param mediaTxt 可选参数 文本内容 + # @param displayNum 可选参数 显示的主叫号码 + # @param playTimes 可选参数 循环播放次数,1-3次,默认播放1次。 + # @param respUrl 可选参数 营销外呼状态通知回调地址,云通讯平台将向该Url地址发送呼叫结果通知。 + + def landingCall(self,to,mediaName,mediaTxt,displayNum,playTimes,respUrl): + + self.accAuth() + nowdate = datetime.datetime.now() + self.Batch = nowdate.strftime("%Y%m%d%H%M%S") + #生成sig + signature = self.AccountSid + self.AccountToken + self.Batch; + sig = md5.new(signature).hexdigest().upper() + #拼接URL + url = "https://"+self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/Calls/LandingCalls?sig=" + sig + #生成auth + src = self.AccountSid + ":" + self.Batch; + auth = base64.encodestring(src).strip() + req = urllib2.Request(url) + self.setHttpHeader(req) + req.add_header("Authorization", auth) + + #创建包体 + body ='''\ + %s%s%s%s%s\ + %s%s\ + '''%(to, mediaName,mediaTxt,self.AppId,displayNum,playTimes,respUrl) + if self.BodyType == 'json': + body = '''{"to": "%s", "mediaName": "%s","mediaTxt": "%s","appId": "%s","displayNum": "%s","playTimes": "%s","respUrl": "%s"}'''%(to, mediaName,mediaTxt,self.AppId,displayNum,playTimes,respUrl) + req.add_data(body) + data='' + try: + res = urllib2.urlopen(req); + data = res.read() + res.close() + + if self.BodyType=='json': + #json格式 + locations = json.loads(data) + else: + #xml格式 + xtj=xmltojson() + locations=xtj.main(data) + if self.Iflog: + self.log(url,body,data) + return locations + except Exception, error: + if self.Iflog: + self.log(url,body,data) + return {'172001':'网络错误'} + + # 语音验证码 + # @param verifyCode 必选参数 验证码内容,为数字和英文字母,不区分大小写,长度4-8位 + # @param playTimes 可选参数 播放次数,1-3次 + # @param to 必选参数 接收号码 + # @param displayNum 可选参数 显示的主叫号码 + # @param respUrl 可选参数 语音验证码状态通知回调地址,云通讯平台将向该Url地址发送呼叫结果通知 + + def voiceVerify(self,verifyCode,playTimes,to,displayNum,respUrl): + + self.accAuth() + nowdate = datetime.datetime.now() + self.Batch = nowdate.strftime("%Y%m%d%H%M%S") + #生成sig + signature = self.AccountSid + self.AccountToken + self.Batch; + sig = md5.new(signature).hexdigest().upper() + #拼接URL + url = "https://"+self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/Calls/VoiceVerify?sig=" + sig + #生成auth + src = self.AccountSid + ":" + self.Batch; + auth = base64.encodestring(src).strip() + req = urllib2.Request(url) + self.setHttpHeader(req) + + req.add_header("Authorization", auth) + + #创建包体 + body ='''\ + %s%s%s%s%s\ + %s\ + '''%(self.AppId,verifyCode,playTimes,to,respUrl,displayNum) + if self.BodyType == 'json': + # if this model is Json ..then do next code + body = '''{"appId": "%s", "verifyCode": "%s","playTimes": "%s","to": "%s","respUrl": "%s","displayNum": "%s"}'''%(self.AppId,verifyCode,playTimes,to,respUrl,displayNum) + req.add_data(body) + data='' + try: + res = urllib2.urlopen(req); + data = res.read() + res.close() + + if self.BodyType=='json': + #json格式 + locations = json.loads(data) + else: + #xml格式 + xtj=xmltojson() + locations=xtj.main(data) + if self.Iflog: + self.log(url,body,data) + return locations + except Exception, error: + if self.Iflog: + self.log(url,body,data) + return {'172001':'网络错误'} + + # IVR外呼 + # @param number 必选参数 待呼叫号码,为Dial节点的属性 + # @param userdata 可选参数 用户数据,在通知中返回,只允许填写数字字符,为Dial节点的属性 + # @param record 可选参数 是否录音,可填项为true和false,默认值为false不录音,为Dial节点的属性 + + def ivrDial(self,number,userdata,record): + + self.accAuth() + nowdate = datetime.datetime.now() + self.Batch = nowdate.strftime("%Y%m%d%H%M%S") + #生成sig + signature = self.AccountSid + self.AccountToken + self.Batch; + sig = md5.new(signature).hexdigest().upper() + #拼接URL + url = "https://"+self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/ivr/dial?sig=" + sig + #生成auth + src = self.AccountSid + ":" + self.Batch; + auth = base64.encodestring(src).strip() + req = urllib2.Request(url) + req.add_header("Accept", "application/xml") + req.add_header("Content-Type", "application/xml;charset=utf-8") + req.add_header("Authorization", auth) + + #创建包体 + body =''' + + %s + + + '''%(self.AppId,number,userdata,record) + req.add_data(body) + data='' + try: + res = urllib2.urlopen(req); + data = res.read() + res.close() + xtj=xmltojson() + locations=xtj.main(data) + if self.Iflog: + self.log(url,body,data) + return locations + except Exception, error: + if self.Iflog: + self.log(url,body,data) + return {'172001':'网络错误'} + + + # 话单下载 + # @param date 必选参数 day 代表前一天的数据(从00:00 – 23:59);week代表前一周的数据(周一 到周日);month表示上一个月的数据(上个月表示当前月减1,如果今天是4月10号,则查询结果是3月份的数据) + # @param keywords 可选参数 客户的查询条件,由客户自行定义并提供给云通讯平台。默认不填忽略此参数 + def billRecords(self,date,keywords): + + self.accAuth() + nowdate = datetime.datetime.now() + self.Batch = nowdate.strftime("%Y%m%d%H%M%S") + #生成sig + signature = self.AccountSid + self.AccountToken + self.Batch; + sig = md5.new(signature).hexdigest().upper() + #拼接URL + url = "https://"+self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/BillRecords?sig=" + sig + #生成auth + src = self.AccountSid + ":" + self.Batch; + auth = base64.encodestring(src).strip() + req = urllib2.Request(url) + self.setHttpHeader(req) + req.add_header("Authorization", auth) + + #创建包体 + body ='''\ + %s%s%s\ + \ + '''%(self.AppId,date,keywords) + if self.BodyType == 'json': + # if this model is Json ..then do next code + body = '''{"appId": "%s", "date": "%s","keywords": "%s"}'''%(self.AppId,date,keywords) + req.add_data(body) + data='' + try: + res = urllib2.urlopen(req); + data = res.read() + + res.close() + + if self.BodyType=='json': + #json格式 + locations = json.loads(data) + else: + #xml格式 + xtj=xmltojson() + locations=xtj.main(data) + if self.Iflog: + self.log(url,body,data) + return locations + except Exception, error: + if self.Iflog: + self.log(url,body,data) + return {'172001':'网络错误'} + + # 主帐号信息查询 + + def queryAccountInfo(self): + + self.accAuth() + nowdate = datetime.datetime.now() + self.Batch = nowdate.strftime("%Y%m%d%H%M%S") + #生成sig + signature = self.AccountSid + self.AccountToken + self.Batch; + sig = md5.new(signature).hexdigest().upper() + #拼接URL + url = "https://"+self.ServerIP + ":" + self.ServerPort + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/AccountInfo?sig=" + sig + #生成auth + src = self.AccountSid + ":" + self.Batch; + auth = base64.encodestring(src).strip() + req = urllib2.Request(url) + self.setHttpHeader(req) + body='' + req.add_header("Authorization", auth) + data='' + try: + res = urllib2.urlopen(req); + data = res.read() + res.close() + + if self.BodyType=='json': + #json格式 + locations = json.loads(data) + else: + #xml格式 + xtj=xmltojson() + locations=xtj.main(data) + if self.Iflog: + self.log(url,body,data) + return locations + except Exception, error: + if self.Iflog: + self.log(url,body,data) + return {'172001':'网络错误'} + + #子帐号鉴权 + def subAuth(self): + if(self.ServerIP==""): + print('172004'); + print('IP为空'); + + if(self.ServerPort<=0): + print('172005'); + print('端口错误(小于等于0)'); + + if(self.SoftVersion==""): + print('172013'); + print('版本号为空'); + + if(self.SubAccountSid==""): + print('172008'); + print('子帐号为空'); + + if(self.SubAccountToken==""): + print('172009'); + print('子帐号令牌为空'); + + if(self.AppId==""): + print('172012'); + print('应用ID为空'); + + #主帐号鉴权 + def accAuth(self): + if(self.ServerIP==""): + print('172004'); + print('IP为空'); + + if(self.ServerPort<=0): + print('172005'); + print('端口错误(小于等于0)'); + + if(self.SoftVersion==""): + print('172013'); + print('版本号为空'); + + if(self.AccountSid==""): + print('172006'); + print('主帐号为空'); + + if(self.AccountToken==""): + print('172007'); + print('主帐号令牌为空'); + + if(self.AppId==""): + print('172012'); + print('应用ID为空'); + + + + #设置包头 + def setHttpHeader(self,req): + if self.BodyType == 'json': + req.add_header("Accept", "application/json") + req.add_header("Content-Type", "application/json;charset=utf-8") + + else: + req.add_header("Accept", "application/xml") + req.add_header("Content-Type", "application/xml;charset=utf-8") + \ No newline at end of file diff --git a/code/handler/CHRequestHandler.py b/code/handler/CHRequestHandler.py new file mode 100644 index 0000000..89c3125 --- /dev/null +++ b/code/handler/CHRequestHandler.py @@ -0,0 +1,41 @@ +__author__ = 'Administrator' + +import tornado.web +import json + +class NoUserException(Exception): + def __init__(self): + pass + +class LackParamsException(Exception): + def __init__(self): + pass + +class CHRequestHandler(tornado.web.RequestHandler): + def getUserId(self, username): + record = self.application.dbapi.getUserByUserName(username) + if record is None: + raise NoUserException() + return record["id"] + + def getParams(self, essentials = []): + j = json.loads(self.request.body) + for k in essentials: + if not j.has_key(k): + raise LackParamsException() + return j + + def writeError(self, error_code, apiname): + error = { + "result": "error", + "request": apiname, + "error_code": error_code + } + self.write(json.dumps(error)) + + def writeOK(self): + result = { + "result": "ok" + } + self.write(result) + diff --git a/code/handler/CancelHandler.py b/code/handler/CancelHandler.py deleted file mode 100644 index 752746e..0000000 --- a/code/handler/CancelHandler.py +++ /dev/null @@ -1,7 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,dbapi -class CancelHandler(tornado.web.RequestHandler): - def post(self): - self.write("CancelHandler") diff --git a/code/handler/CheckrelativesHandler.py b/code/handler/CheckrelativesHandler.py deleted file mode 100644 index 9745dd5..0000000 --- a/code/handler/CheckrelativesHandler.py +++ /dev/null @@ -1,7 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,dbapi -class CheckrelativesHandler(tornado.web.RequestHandler): - def post(self): - self.write("CheckrelativesHandler") diff --git a/code/handler/DeleterelativesHandler.py b/code/handler/DeleterelativesHandler.py deleted file mode 100644 index e5df91c..0000000 --- a/code/handler/DeleterelativesHandler.py +++ /dev/null @@ -1,25 +0,0 @@ -'''Yeqin Zheng, 09/07/2014''' -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os, json, sys -sys.path.append("..") -import dbapi - -''' Delete a relation between two users. Succeed with "1" returned, else with "0". ''' - -class DeleterelativesHandler(tornado.web.RequestHandler): - def post(self): - #self.write(u_id + r_id) - u_name = self.get_argument('u_name') - r_name = self.get_argument('r_name') - - row = self.application.dbapi.getRelationByUsername(u_name, r_name) - #self.write(row2) - if row == 0 : - delete_message = {'state': 0} - else : - self.application.dbapi.deleteRelationByUsername(u_name, r_name) - delete_message = {'state': 1} - - self.write(delete_message) diff --git a/code/handler/EventHandler.py b/code/handler/EventHandler.py new file mode 100644 index 0000000..9b6886c --- /dev/null +++ b/code/handler/EventHandler.py @@ -0,0 +1,296 @@ +import tornado.ioloop +import tornado.web +import tornado.httpserver +from tornado.escape import * +from sets import Set +import json + +class HelpmessageHandler(tornado.web.RequestHandler): + def get(self): + self.write("

HelpmessageHandler

") + + def post(self): + content =self.request.body + #content='{"username":"test1","message":{"kind":1,"content":"TestContent", "video":"TestAssist","videosign":1,"audeo":"dsds","audiosign":1,"latitude":23.000000,"longitude":23.000000}}' + jobj=json.loads(content) + result = self.application.dbapi.addEventByUserName(jobj["username"],jobj["message"]) + self.write(json_encode(result)) + + if(jobj['message']['videosign'] =="1"): + print "test1" + self.application.util.setVideobyEid(result['eventid'],jobj['video']) + + if(jobj['message']['audiosign'] =="1"): + print "test2" + self.application.util.setAudiobyEid(result['eventid'],jobj['audio']) + + """if(result["state"] == 1): + eventinfo = self.application.dbapi.getEventandUserByEventId(result['eventid']) + eventinfo['audio'] = jobj['message']['videosign'] + eventinfo['video'] = jobj['message']['audiosign'] + print '{"type":"help","data":'+json_encode(eventinfo)+'}' + info = self.application.dbapi.getUserInfobyName(jobj["username"]) + cidlist = self.application.dbapi.getUserCidAround(info["longitude"],info["latitude"],5) + relativelist = self.application.dbapi.getRelativesCidbyUid(info['id']) + cidlist.extend(relativelist) + cidlist = list(Set(cidlist)) + cidlist.remove(info['cid']) + print cidlist + self.application.push.pushToList(cidlist,'{"type":"help","data":'+json_encode(eventinfo)+'}')""" + if(result["state"] == 1): + eventinfo = self.application.dbapi.getEventandUserByEventId(result['eventid']) + eventinfo['audio'] = jobj['message']['videosign'] + eventinfo['video'] = jobj['message']['audiosign'] + pushlist = [] + askuser = self.application.dbapi.getUserInfobyName(jobj["username"]) + relativelist = self.application.dbapi.getRelativesCidbyUid(askuser['id']) + print relativelist + pushlist.extend(relativelist) + friendlist = self.application.dbapi.getRelativesIdbyUid(askuser['id']) + hashelpaskuserlist = self.application.dbapi.getHelpersIdbyUid(askuser['id']) + distance = 3 + special = [] + if(jobj['message']['kind'] ==1):#anquan + print 1 + special = self.application.dbapi.getAroundbyvocationOrKind(askuser["longitude"],askuser["latitude"],1,4,20,5) + print special + pushlist.extend(special) + aroundhelpers = self.application.dbapi.getUserAroundbykind(askuser["longitude"],askuser["latitude"],distance,1) + while len(aroundhelpers) <= 50 and distance <= 7: + distance +=2 + aroundhelpers= self.application.dbapi.getUserAroundbykind(askuser["longitude"],askuser["latitude"],distance,1) + + + elif(jobj['message']['kind'] ==2): + print 2 + aroundhelpers = self.application.dbapi.getUserAroundbykind(askuser["longitude"],askuser["latitude"],distance,2) + while len(aroundhelpers) <= 10 and distance <= 7: + distance +=2 + aroundhelpers = self.application.dbapi.getUserAroundbykind(askuser["longitude"],askuser["latitude"],distance,2) + + else:#jiankang + print 3 + special = self.application.dbapi.getAroundbyvocationOrKind(askuser["longitude"],askuser["latitude"],1,5,10,5) + print special + pushlist.extend(special) + aroundhelpers = self.application.dbapi.getUserAroundbykind(askuser["longitude"],askuser["latitude"],distance,3) + while len(aroundhelpers) <= 20 and distance <= 5: + distance +=2 + aroundhelpers = self.application.dbapi.getUserAroundbykind(askuser["longitude"],askuser["latitude"],distance,3) + + predictlist = self.application.util.getPushlistByCredit(askuser,aroundhelpers,friendlist,hashelpaskuserlist,0.5,self.application.dbapi) + print predictlist + pushlist.extend(predictlist) + pushlist = list(Set(pushlist)) + if(askuser['cid'] in pushlist): + pushlist.remove(askuser['cid']) + print pushlist + self.application.push.pushToList(pushlist,'{"type":"help","data":'+json_encode(eventinfo)+'}') + return + +class EventHandler(tornado.web.RequestHandler): + def get(self): + self.write("

eventHandler

") + + def post(self): + content=self.request.body + #content='{"username":"test4","eventid":1}' + jobj=json.loads(content) + uid = self.application.dbapi.getUserByUserName(jobj['username'])["id"] + helpevent=self.application.dbapi.getEventandUserByEventId(jobj['eventid']) + print helpevent + result={} + if(helpevent): + helpevent['follows'] = self.application.dbapi.getFollowsByEventId(jobj['eventid'])['count'] + helpevent['helpers'] = len(self.application.dbapi.getHelpersCidbyEid(jobj['eventid'])) + result['event'] = helpevent + ishelper = self.application.dbapi.checkifUseraddHelper(uid,jobj['eventid']) + if(ishelper is None): + if(helpevent['username'] == jobj['username']): + result['ishelper'] = 1 + else: + result['ishelper'] = 0 + else: + result['ishelper'] = 1 + rNamelist = self.application.dbapi.getAllRelativeNamebyUid(helpevent['userid']) + print rNamelist + if(uid in rNamelist): + result['canend'] = 1 + else: + result['canend'] = 0 + if(self.application.dbapi.getFollow(uid,jobj['eventid']) is None): + if(helpevent['username'] == jobj['username']): + result['isfollow'] = 1 + else: + result['isfollow'] = 0 + else: + result['isfollow'] = 1 + print result + result['support']=self.application.dbapi.getSupportsByEventId(jobj['eventid']) + for support in result['support']: + user=self.application.dbapi.getUserByUserId(support['usrid']) + if(user): + support['username']=user['name']; + avatar=self.application.util.getAvatarbyUid(support['usrid']) + support['avatar']=avatar + self.write(json_encode(result)) + +'''Yeqin Zheng, 09/07/2014''' +''' Add a helper to an event. Succeed with "1" returned, else with "0". ''' +class AddaidHandler(tornado.web.RequestHandler): + def get(self): + self.write("

AddaidHandler

") + def post(self): + content = self.request.body + #content = '{"username":"test1","eventid":"4"}' + j = json.loads(content) + + result = self.application.dbapi.addaidhelper(j['username'], j['eventid']) + self.write("{'state': " + result + "}") + uid =self.application.dbapi.getUserByUserName(j['username'])['id'] + self.application.score.joinSupport(uid,self.application.dbapi) + + +class FinishHandler(tornado.web.RequestHandler): + def get(self): + self.write("

FinishHandler

") + + def post(self): + content =self.request.body + #content = '{"username":"test1","eventid":1}' + j = json.loads(content) + user = self.application.dbapi.getUserByUserName(j['username']) + event = self.application.dbapi.getEventandUserByEventId(j['eventid']) + if(event is None): + self.write("{'state':1}") + print "event not exist" + return + rNamelist = self.application.dbapi.getAllRelativeNamebyUid(event["userid"]) + if(user["id"] not in rNamelist): + self.write("{'state':2}") + print "user not relative or itself,can not update sate" + return + currenttime = self.application.dbapi.changeEventState(j['eventid']) + helpers = self.application.dbapi.getHelperInfoByEid(j['eventid']) + data = [] + for item in helpers: + info = {} + info['username'] = item['username'] + info['uid'] = item['uid'] + data.append(info) + self.application.dbapi.UpdateInfotimebyUid(item['uid']) + #data.append("{'username':" + str(item['username']) + ",'uid':"+ str(item['uid'])+"}") + writedata = {} + writedata['state'] = 3 + writedata['helpers'] = data + #push + pushlist = self.application.dbapi.getFollowerCidByEid(j['eventid']) + helperlist = self.application.dbapi.getHelpersCidbyEid(j['eventid']) + pushlist.extend(helperlist) + relativelist = self.application.dbapi.getRelativesCidbyUid(event["userid"]) + pushlist.extend(relativelist) + pushlist = list(Set(pushlist)) + if(user['cid'] in pushlist): + pushlist.remove(user['cid']) + pushdata = {} + data = {} + pushdata['type'] = "endhelp" + data['eventid'] = j['eventid'] + data['time'] = currenttime.strftime('%Y-%m-%d %H:%M:%S') + data['username'] = event['username'] + pushdata['data'] = data + self.application.push.pushToList(pushlist,json_encode(pushdata)) + self.write(json_encode(writedata)) + print "finsh an event" + return + + +class GivecreditHandler(tornado.web.RequestHandler): + def get(self): + self.write("

GivecreditHandler

") + def post(self): + content =self.request.body + #content='{"eventid":4,"helpername":"test2","credit":3}' + #content='{"eventid":1,"credits":[{"username":"test2","cridit":5},{"username":"test6","cridit":1}]}' + jobj=json.loads(content) + result=[] + event = self.application.dbapi.getEventByEventId(jobj['eventid']) + askuser = self.application.dbapi.getUserInfobyUid(event['usrid']) + for issue in jobj["credits"]: + temp = self.application.dbapi.setCreditByEventIdAndUserName(jobj["eventid"],issue["username"],issue["cridit"]) + result.append({"helpername":issue["username"],"result":temp}) + helper = self.application.dbapi.getUserInfobyName(issue['username']) + self.application.util.setCreditforHelper(event,askuser,helper,issue["cridit"],self.application.dbapi) + self.write(str(result)) + self.application.score.giveCredit(event['usrid'],jobj['eventid'],self.application.dbapi) + +class QuitaidHandler(tornado.web.RequestHandler): + def get(self): + self.write("

QuitaidHandler

") + + def post(self): + content =self.request.body + #content = '{"username":"oo11o","eventid":5}' + j = json.loads(content) + uid = self.application.dbapi.getUserByUserName(j['username'])['id'] + if(self.application.dbapi.getEventByEventId(j['eventid'])['state'] == 1): + print "current had been end,you can not quit" + self.write("{'state':3}") + return + + if(self.application.dbapi.checkifUseraddHelper(uid,j['eventid']) is None): + print "user " + j['username'] +" do not add the aid first" + self.write("{'state':2}") + return + self.application.dbapi.deleteHelperbyUidEid(uid,j['eventid']) + print "quit success" + self.write("{'state':1}") + application.score.quitSupport(uid,self.application.dbapi) + return + +class SendsupportHandler(tornado.web.RequestHandler): + def get(self): + self.write("

SendsupportHandler

") + + def post(self): + content =self.request.body + #content='{"username":"test1","eid":4,"message":{"content":"TestssCofffntent"}}' + jobj=json.loads(content) + user = self.application.dbapi.getUserByUserName(jobj['username']) + result=self.application.dbapi.addSupportByEventIdAndUserName(jobj["eid"],jobj["username"],jobj["message"]) + if(result['errorCode'] == 200): + pushlist = self.application.dbapi.getFollowerCidByEid(jobj['eid']) + relativelist =self.application.dbapi.getRelativesCidbyUid(user['id']) + pushlist.extend(relativelist) + pushlist = list(Set(pushlist)) + if(user['cid'] in pushlist): + pushlist.remove(user['cid']) + eventuser = self.application.dbapi.getUserByEid(jobj['eid']) + if(eventuser['uid'] !=user['id']): + pushlist.append(eventuser['cid']) + datatemp = self.application.dbapi.getSupportBySid(result['supportid']) + pushdata = {} + data = {} + pushdata['type'] = 'aid' + data['username'] = jobj['username'] + data['content'] = datatemp['content'] + data['time'] = datatemp['time'].strftime('%Y-%m-%d %H:%M:%S') + data['eventid'] = jobj['eid'] + pushdata['data'] = data + self.application.push.pushToList(pushlist,json_encode(pushdata)) + self.write(json_encode(result)) + self.application.score.sendSupport(user['id'],self.application.dbapi) + + +class SupportmessageHandler(tornado.web.RequestHandler): + def get(self): + self.write("

SupportmessageHandler

") + + def post(self): + content =self.request.body + content = '{"eventid": 3,"video": "ssssssssssssssss","audio":"ddddd"}' + j = json.loads(content) + if('video' in j): + self.application.util.setVideobyEid(j['eid'],j['video']) + if('audio' in j): + self.application.util.setAudiobyEid(j['eid'],j['video']) diff --git a/code/handler/FinishHandler.py b/code/handler/FinishHandler.py deleted file mode 100644 index d142506..0000000 --- a/code/handler/FinishHandler.py +++ /dev/null @@ -1,7 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,dbapi -class FinishHandler(tornado.web.RequestHandler): - def post(self): - self.write("FinishHandler") diff --git a/code/handler/FollowHandler.py b/code/handler/FollowHandler.py new file mode 100644 index 0000000..70c725e --- /dev/null +++ b/code/handler/FollowHandler.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +import tornado.ioloop +import tornado.web +import tornado.httpserver +import json + +class startFollowHandler(tornado.web.RequestHandler): + def get(self): + self.write("

startFollowHandler

") + + def post(self): + content =self.request.body + #content='{"eid":2,"username":"test2"}' + j=json.loads(content) + user=self.application.dbapi.getUserByUserName(j['username'])["id"] + if(user): + if(self.application.dbapi.getFollow(user,j['eid'])): + data={'state':3,'desc':"have been followed"}#have been followed + result=json.dumps(data) + else: + self.application.dbapi.insertFollow(user,j['eid']) + data={'state':1,'desc':"start follow success"}#start follow success + result=json.dumps(data) + else: + data={'state':2,'desc':"user no exist"}#user no exist + result=json.dumps(data) + self.write(result) + return + +class cancelFollowHandler(tornado.web.RequestHandler): + def get(self): + self.write("

cancelFollowHandler

") + + def post(self): + content =self.request.body + #content='{"eid":2,"username":"test2"}' + j=json.loads(content) + user=self.application.dbapi.getUserByUserName(j['username'])["id"] + if(user): + if(self.application.dbapi.getFollow(user,j['eid'])): + self.application.dbapi.delectFollow(user,j['eid']) + data={'state':1,'desc':"delete follow success"}#delete follow success + result=json.dumps(data) + else: + data={'state':3,'desc':"have no follow"}#have no follow + result=json.dumps(data) + else: + data={'state':2,'desc':"user no exist"}#user no exist + result=json.dumps(data) + self.write(result) + return diff --git a/code/handler/GetArroundEvent.py b/code/handler/GetArroundEvent.py new file mode 100644 index 0000000..839739f --- /dev/null +++ b/code/handler/GetArroundEvent.py @@ -0,0 +1,24 @@ +import tornado.ioloop +import tornado.web +import tornado.httpserver +from tornado.escape import * +import json + +class GetArroundEvent(tornado.web.RequestHandler): + def get(self): + self.write("

GetArroundEvent

") + + def post(self): + content =self.request.body + j=json.loads(content) + user = self.application.dbapi.getUserInfobyName(j['username']) + if(user is None): + self.write("{'state':2}") + print "username not exist" + return + result = self.application.dbapi.getEventAround(user['longitude'],user['latitude'],5) + print result + for item in result: + item['avatar'] = self.application.util.getAvatar(item['name'],self.application.dbapi) + self.write("{'state':1,aids:"+json_encode(result)+"}") + return diff --git a/code/handler/GivecreditHandler.py b/code/handler/GivecreditHandler.py deleted file mode 100644 index ce09dff..0000000 --- a/code/handler/GivecreditHandler.py +++ /dev/null @@ -1,7 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,dbapi -class GivecreditHandler(tornado.web.RequestHandler): - def post(self): - self.write("GivecreditHandler") diff --git a/code/handler/HelpmessageHandler.py b/code/handler/HelpmessageHandler.py deleted file mode 100644 index 7c906bb..0000000 --- a/code/handler/HelpmessageHandler.py +++ /dev/null @@ -1,7 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,dbapi -class HelpmessageHandler(tornado.web.RequestHandler): - def post(self): - self.write("HelpmessageHandler") diff --git a/code/handler/HistoryHandler.py b/code/handler/HistoryHandler.py index 38cbd69..8e79d2b 100644 --- a/code/handler/HistoryHandler.py +++ b/code/handler/HistoryHandler.py @@ -1,7 +1,36 @@ +# -*- coding: utf-8 -*- import tornado.ioloop import tornado.web import tornado.httpserver -import os,dbapi +from tornado.escape import * +import json + class HistoryHandler(tornado.web.RequestHandler): - def post(self): - self.write("HistoryHandler") + def get(self): + self.write("

historyHandler

") + + def post(self): + content =self.request.body + #content='{"name":"test3"}' + jobj=json.loads(content) + user = self.application.dbapi.getUserByUserName(jobj['username']) + if(user is None): + self.write('{"state":2,"decs":"User not exist"}') + return + uid = user['id'] + events=self.application.dbapi.getEventsByUserId(uid) + for item in events: + item['longitude'] = float(item['longitude']) + item['latitude'] = float(item['latitude']) + item['starttime'] = item['starttime'].strftime('%Y-%m-%d %H:%M:%S') + if(item['endtime'] is None): + item['endtime'] = "" + else: + item['endtime'] = item['endtime'].strftime('%Y-%m-%d %H:%M:%S') + #result=self.application.dbapi.getEventsByUserName(jobj['name']) + supports = self.application.dbapi.getSupportsbyUid(uid) + for item in supports: + item['time'] = item['time'].strftime('%Y-%m-%d %H:%M:%S') + print json_encode(events),json_encode(supports) + self.write('{"state":1,"events":'+json_encode(events)+',"supports":'+json_encode(supports)+'}') + return diff --git a/code/handler/LoginHandler.py b/code/handler/LoginHandler.py deleted file mode 100644 index bf9c90b..0000000 --- a/code/handler/LoginHandler.py +++ /dev/null @@ -1,7 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,dbapi -class LoginHandler(tornado.web.RequestHandler): - def post(self): - self.write("login") diff --git a/code/handler/LogoutHandler.py b/code/handler/LogoutHandler.py deleted file mode 100644 index 212d295..0000000 --- a/code/handler/LogoutHandler.py +++ /dev/null @@ -1,7 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,dbapi -class LogoutHandler(tornado.web.RequestHandler): - def post(self): - self.write("LogoutHandler") diff --git a/code/handler/QuitaidHandler.py b/code/handler/QuitaidHandler.py deleted file mode 100644 index 83434c6..0000000 --- a/code/handler/QuitaidHandler.py +++ /dev/null @@ -1,7 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,dbapi -class QuitaidHandler(tornado.web.RequestHandler): - def post(self): - self.write("QuitaidHandler") diff --git a/code/handler/RegisterHandler.py b/code/handler/RegisterHandler.py deleted file mode 100644 index ca1f57f..0000000 --- a/code/handler/RegisterHandler.py +++ /dev/null @@ -1,7 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,dbapi -class RegisterHandler(tornado.web.RequestHandler): - def post(self): - self.write("RegisterHandler") diff --git a/code/handler/RelativesHandler.py b/code/handler/RelativesHandler.py new file mode 100644 index 0000000..c6ac8a3 --- /dev/null +++ b/code/handler/RelativesHandler.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +'''Yeqin Zheng, 09/07/2014''' +import tornado.ioloop +import tornado.web +import tornado.httpserver +from tornado.escape import * +import json + +''' Add a relation between two users. Succeed with "1" returned, else with "0". ''' + +class AddrelativesHandler(tornado.web.RequestHandler): + def get(self): + self.write("

AddrelativesHandler

") + + def post(self): + content =self.request.body + #content = '{"u_name":"test1","r_name":"test5","info":"i am",'kind':}' + j = json.loads(content) + row = self.application.dbapi.getRelationByUsername(j['u_name'], j['r_name']) + if row == 0: + self.application.dbapi.addtempRelationByUsername(j['u_name'], j['r_name'],j['kind'],j['info']) + #push data + cid = self.application.dbapi.getUserByUserName(j['r_name'])['cid'] + pushdata = {} + datainside = {} + pushdata['type'] = "invite" + datainside['username'] = j['u_name'] + datainside['info'] = j['info'] + datainside['type'] = j['kind'] + pushdata['data'] = datainside + self.application.push.pushToSingle(cid,json_encode(pushdata)) + add_message = {'state': 1} + print "add relative success" + else: + add_message = {'state': 0} + print "two already has relative relation" + self.write(add_message) + return + +class CheckrelativesHandler(tornado.web.RequestHandler): + def get(self): + self.write("

CheckrelativesHandler

") + + def post(self): + content =self.request.body + #content = '{"username":"test1"}' + j = json.loads(content) + userid=self.application.dbapi.getUserByUserName(j['username'])["id"] + re=self.application.dbapi.CheckRelationbyId(userid) + if re!=(): + relatives=[] + for row in re: + info=self.application.dbapi.getUsermessegeByUserId(row["cid"]) + info['kind'] = row['kind'] + info['avatar'] = self.application.util.getAvatarbyUid(info['id']) + #relatives.append('{"info":'+str(info)+',"avatar":'+self.application.util.getAvatarbyUid(info['id'])+'}') + relatives.append(info) + data={'state':1,'relatives':relatives} + else: + data={'state':1,'relatives':'[]'} + self.write(json_encode(data)) + +'''Yeqin Zheng, 09/07/2014''' +''' Delete a relation between two users. Succeed with "1" returned, else with "0". ''' +class DeleterelativesHandler(tornado.web.RequestHandler): + def get(self): + self.write("

DeleterelativesHandler

") + + def post(self): + content =self.request.body + #content = '{"username1":"ooo","username2":"11oo"}' + j = json.loads(content) + row = self.application.dbapi.getRelationByUsername(j['username1'],j['username2']) + if row == 0 : + delete_message = {'state': 0} + print "two has no relations" + else : + self.application.dbapi.deleteRelationByUsername(j['username1'],j['username2']) + print "delete relations success" + delete_message = {'state': 1} + + self.write(delete_message) + return + +class AgreerelativesHandler(tornado.web.RequestHandler): + def get(self): + self.write("

AgreerelativesHandler

") + + def post(self): + content =self.request.body + #content = '{"u_name":"ooo","c_name":"11oo","kind": ,"agree":1(1同意,0不同意)}' + j = json.loads(content) + user = self.application.dbapi.getUserByUserName(j['u_name']) + cid = self.application.dbapi.getUserByUserName(j['c_name'])['id'] + if(j['agree'] == "1"): + self.application.dbapi.deletetemprelation(user['id'],cid) + self.application.dbapi.addRelationByUid(user['id'],cid,j['kind']) + print "agree 1" + pushdata = {} + pushdata['type'] = "agree" + data = {} + data['userid'] = user['id'] + data['username'] = user['name'] + data['type'] = j['kind'] + self.application.push.pushToSingle(user['cid'],json_encode(pushdata)) + state = {'state':1} + else: + self.application.dbapi.deletetemprelationwithkind(user['id'],cid,j['kind']) + print "agree 0" + state = {'state':1} + self.write(json_encode(state)) + return + +class ValidationHandler(tornado.web.RequestHandler): + def get(self): + self.write("

ValidationHandler

") + + def post(self): + content =self.request.body + #content = '{"username":"test6"}' + j = json.loads(content) + user = self.application.dbapi.getUserByUserName(j['username']) + validations = self.application.dbapi.gettemprelationbyCid(user['id']) + result={} + if len(validations): + result['state'] = 1 + for item in validations: + print item + item['u_name'] = self.application.dbapi.getUserByUserId(item['uid'])['name'] + else: + result['state'] = 0 + result['validations'] = validations + self.write(json_encode(result)) + return diff --git a/code/handler/SendsupportHandler.py b/code/handler/SendsupportHandler.py deleted file mode 100644 index 19d6d73..0000000 --- a/code/handler/SendsupportHandler.py +++ /dev/null @@ -1,7 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,dbapi -class SendsupportHandler(tornado.web.RequestHandler): - def post(self): - self.write("SendsupportHandler") diff --git a/code/handler/SupportmessageHandler.py b/code/handler/SupportmessageHandler.py deleted file mode 100644 index 9fd7c28..0000000 --- a/code/handler/SupportmessageHandler.py +++ /dev/null @@ -1,7 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,dbapi -class SupportmessageHandler(tornado.web.RequestHandler): - def post(self): - self.write("SupportmessageHandler") diff --git a/code/handler/ThirdPartHandlers.py b/code/handler/ThirdPartHandlers.py new file mode 100644 index 0000000..91742da --- /dev/null +++ b/code/handler/ThirdPartHandlers.py @@ -0,0 +1,165 @@ +# coding: utf-8 +# Filename: handlers.py +__author__ = 'Administrator' + +import tornado.web +import json,os,base64 +import urllib +from CHRequestHandler import CHRequestHandler, LackParamsException, NoUserException + +# 2014-07-17 +# +# post: access_token, platform +# return: result +# actions: +# visit get_token_info +# check for binding +# create new user +# bind user +# update user state +# 我需要与前后台协商,除了本地登录之外,在增加第三方专用的返回值。这里就将就一下 +# error code +# 50001 访问授权api失败 +# 50002 不支持的平台 +# 50003 授权过期 +class ThirdPartyLoginHandler(CHRequestHandler): + platformapi = { "sinaweibo": "https://api.weibo.com/oauth2/get_token_info" } + requestname = "thirdpartylogin" + + def post(self): + try: + j = self.getParams(["platformname", "access_token", "latitude", "longitude"]) + except LackParamsException: + self.writeError(1, ThirdPartyLoginHandler.requestname) + return + url = ThirdPartyLoginHandler.platformapi.get(j["platformname"]) + if url is None: + self.writeError(50002, ThirdPartyLoginHandler.requestname) + return + data = "access_token=" + j["access_token"] + try: + resultstr = urllib.urlopen(url, data).read() + except IOError: + self.writeError(50001, ThirdPartyLoginHandler.requestname) + return + # 解析返回值,这里依旧只考虑了新浪微博 + result = json.loads(resultstr) + expire_in = result["expire_in"] + # 如果令牌超时,则驳回请求 + if expire_in <= 0: + # 返回state:1 + self.writeError(50003, ThirdPartyLoginHandler.requestname) + return + # 第三方不需要在本系统中设置用户名,因此自动生成一个作为第三方用户的唯一标识 + username = "*" + j["platformname"] + ("%i" % result["uid"]) + # 这里做简单处理:直接将星号+platform+uid作为用户名,不设密码 + # 其他用户不允许第一个符号是星号。一般的用户名只允许出现字母,数字,空格,和下划线。 + # 首先检查是否已经注册过 + try: + uid = self.getUserId(username) + except NoUserException: + newUser = {"username": username, + "kind": 1, + "password": "", + "cardid": 0, + "realname": "", + "sex": 0, + "age": 0, + "address": "", + "phone": "", + "vocation": 3, + "illness": ""} + uid = self.application.dbapi.register(newUser) + avatar=open(os.path.abspath('./static/avatar/default.png'),"rb"); + filestring=base64.standard_b64encode(avatar.read()) + self.application.util.setAvatarbyUid(uid,filestring) + self.application.score.userRegister(uid,self.application.dbapi) + self.application.dbapi.updateUseLBS(j['latitude'],j['longitude'],uid) + self.application.dbapi.updateUserstate(uid, 1) # 登录状态为数字1 + self.writeOK() + return + +# 在第三方登录成功之后,第三方用户状态就与本地用户相同了。这里的登出过程也几乎没有区别 +class ThirdPartyLogoutHandler(tornado.web.RequestHandler): + # 数据库的所有操作都没有进行用户是否已经登录的检查。 + # 鉴于这种检查时普遍操作,可能会作为任何一项需要特权的操作的前置操作,仅仅需要修改少数类,因此这里不做检查,等待小组长修复该bug + # 这里需要将访问方式改为post。之前考虑失误。显然应该是post + def post(self): + # 这与正常的登出一模一样。直接copy代码。 + # 这里用到了username。按照我的预想,是不需要username的。但是第一版可以简单设计。 + # 这需要我修改几处anroid代码 + # 其他人采用json格式传输数据。我这里并没有采用,而是直接使用参数传递。 + username = "*" + self.get_argument("platform") + self.get_argument("uid") + print("username: " + username) + # 因为假设所有的特权操作都经过了检查,因此不必考虑用户不存在的情况 + record = self.application.dbapi.getUserByUserName(username) + uid = record["id"] + self.application.dbapi.updateUserstate(uid, 0) + self.write("{'state':1}") + self.write("Third Party Logout Test") + +# 50001 访问平台授权服务器错误 +# 50002 不支持的平台 +# 50003 授权超时 +class ThirdPartyRemoveAccountHandler(CHRequestHandler): + platformapi = { "sinaweibo": "https://api.weibo.com/oauth2/get_token_info" } + requestname = "thirdpartyremoveaccount" + + # 与前面一个一样,这里的get也是不对的,需要改为post + def post(self): + try: + j = self.getParams(["platformname", "access_token"]) + except LackParamsException: + self.writeError(1, ThirdPartyLoginHandler.requestname) + return + url = ThirdPartyLoginHandler.platformapi.get(j["platformname"]) + if url is None: + self.writeError(50002, ThirdPartyLoginHandler.requestname) + return + data = "access_token=" + j["access_token"] + try: + resultstr = urllib.urlopen(url, data).read() + except IOError: + self.writeError(50001, ThirdPartyLoginHandler.requestname) + return + # 解析返回值,这里依旧只考虑了新浪微博 + result = json.loads(resultstr) + expire_in = result["expire_in"] + # 如果令牌超时,则驳回请求 + if expire_in <= 0: + # 返回state:1 + self.writeError(50003, ThirdPartyLoginHandler.requestname) + return + # 第三方不需要在本系统中设置用户名,因此自动生成一个作为第三方用户的唯一标识 + username = "*" + j["platformname"] + ("%i" % result["uid"]) + # 这里做简单处理:直接将星号+platform+uid作为用户名,不设密码 + # 其他用户不允许第一个符号是星号。一般的用户名只允许出现字母,数字,空格,和下划线。 + # 首先检查是否已经注册过 + try: + uid = self.getUserId(username) + except NoUserException: + self.writeError(2, ThirdPartyRemoveAccountHandler.requestname) + return + self.application.dbapi.cancelUser(uid) + # 用户已删除,这是返回登录成功的返回值,暗示了用户已删除 + print("delete user") + self.writeOK() + +class ThirdPartyFillUserInfoHandler(tornado.web.RequestHandler): + def post(self): + username = "*" + self.get_argument("platform") + self.get_argument("uid") + newUserInfo = { + "sex": self.get_argument("sex"), + "address": self.get_argument("address") + } + user = self.application.dbapi.getUserByUserName(username) + if(user is None): + self.write("{'state':1}") + print "username not exist" + return + print("username: " + username) + print("sex: " + newUserInfo["sex"]) + print("address: " + newUserInfo["address"]) + result = self.application.dbapi.updateUserinfo(user['id'], newUserInfo) + self.write("{'result':"+ str(result)+"}") + print("UpdateUserInfo success") diff --git a/code/handler/UserHandler.py b/code/handler/UserHandler.py new file mode 100644 index 0000000..9e35881 --- /dev/null +++ b/code/handler/UserHandler.py @@ -0,0 +1,199 @@ +# -*- coding: utf-8 -*- +import tornado.ioloop +import tornado.web +import tornado.httpserver +from tornado.escape import * +import json,os,base64 + +class RegisterHandler(tornado.web.RequestHandler): + def get(self): + self.write("

RegisterHandler

") + + def post(self): + content =self.request.body + #content = '{"username": "test1","password": "1","kind": 1, "cardid":"test" ,"realname":"1","sex":1,"age":1, "address":"1","illness":"1","phone":"11"}' + j = json.loads(content) + if(self.application.dbapi.getUserByUserName(j['username']) is not None): + self.write("{'state':1}") + print "username exist" + return + if(self.application.dbapi.getInfoBycardid(j['cardid']) is not None): + self.write("{'state':2}") + print "cardid exist" + return + uid = self.application.dbapi.register(j) + self.write("{'state':3}") + print("Register success") + + if('file' in j): + self.application.util.setAvatar(j['username'],j['file'],self.application.dbapi) + else: + avatar=open(os.path.abspath('./static/avatar/default.png'),"rb"); + filestring=base64.standard_b64encode(avatar.read()) + self.application.util.setAvatar(j['username'],filestring,self.application.dbapi) + self.application.score.userRegister(uid,self.application.dbapi) + return + +class LoginHandler(tornado.web.RequestHandler): + def get(self): + self.write("

LoginHandler

") + + def post(self): + content = self.request.body + #content = '{"username":"12","password":"1","latitude":23.000000,"longitude":23.000000}' + j = json.loads(content) + if(j['username'].strip()=='' or j['username'].strip()[0]== '*'): + self.write("{'state':1}") + print "username is illegal" + return + + user = self.application.dbapi.getUserByUserName(j['username']) + if(user is None): + self.write("{'state':1}") + print "username not exist" + return + if(user["password"]!= j['password']): + self.write("{'state':2}") + print "passwd incorrect" + return + if("latitude" in j): + self.application.dbapi.updateUseLBS(j['latitude'],j['longitude'],user['id']) + self.application.dbapi.updateUserstate(user['id'],1) + result = {} + result['state'] = 3 + result['userid'] = user['id'] + self.write(json_encode(result)) + print("Login success") + self.application.score.userLogin(user['id'],self.application.dbapi) + return + +class UpdateCid(tornado.web.RequestHandler): + def get(self): + self.write("

UpdateCid

") + + def post(self): + content = self.request.body + j = json.loads(content) + user = self.application.dbapi.getUserByUserName(j['username']) + if(user is None): + self.write("{'state':2}") + print "username not exist" + return + self.application.dbapi.UpdateCidByuid(j['cid'],user['id']) + self.write("{'state':1}") + print("Login success") + return + +class LogoutHandler(tornado.web.RequestHandler): + def get(self): + self.write("

LogoutHandler

") + + def post(self): + content =self.request.body + print content + #content = '{"username":"11oo"}' + j = json.loads(content) + uid = self.application.dbapi.getUserByUserName(j['username'])['id'] + self.application.dbapi.updateUserstate(uid,0) + self.write("{'state':1}") + print("Logout success") + self.application.score.checkOnlineHours(uid,self.application.dbapi) + return + +class AuthenHandler(tornado.web.RequestHandler): + def get(self): + self.write("

AuthenHandler

") + + def post(self): + #self.write("AuthenHandler") + print "start" + content='{"username":"test1","message":{"kind":1}}' + jobj=json.loads(content) + askuser = self.application.dbapi.getUserInfobyName(jobj["username"]) + print self.application.dbapi.getAroundbyvocationOrKind(askuser["longitude"],askuser["latitude"],1,5,10,5) + #print askuser + aroundhelpers = self.application.dbapi.getUserAroundbykind(askuser["longitude"],askuser["latitude"],5,jobj['message']['kind']) + #print aroundhelpers + friendlist = self.application.dbapi.getRelativesIdbyUid(askuser['id']) + #print friendlist + hashelpaskuserlist = self.application.dbapi.getHelpersIdbyUid(askuser['id']) + #print hashelpaskuserlist + pushlist = self.application.util.getPushlistByCredit(askuser,aroundhelpers,friendlist,hashelpaskuserlist,0.2,self.application.dbapi) + #print pushlist + print "lall" + return + + +class CancelHandler(tornado.web.RequestHandler): + def get(self): + self.write("

CancelHandler

") + + def post(self): + content = self.request.body + print content + #content = '{"username":"test","password":"test"}' + j = json.loads(content) + if(j['username'].strip()=='' ): + self.write("{'state':1}") + print "username is null" + return + user = self.application.dbapi.getUserByUserName(j['username']) + if(user is None): + self.write("{'state':1}") + print "username not exist,can not cancel" + return + if(user["password"]!= j['password']): + self.write("{'state':2}") + print "passwd incorrect,can not cancel" + return + self.application.dbapi.cancelUser(user['id']) + self.write("{'state':3}") + print("cancel success") + return + +class SearchHandler(tornado.web.RequestHandler): + def get(self): + self.write("

SearchHandler

") + + def post(self): + content =self.request.body + print content + #content = '{"searchtype":"2","fromage":"20","endage":"30"}' + j = json.loads(content) + if(j['searchtype'] == "exactSearch"): + user = self.application.dbapi.getUserByUserName(j['username']) + if(user is not None): + users = [] + username = {} + username['username'] = user['name'] + users.append(username) + result ={} + result['state'] = 1 + result['users'] = users + else: + result = {'state': 0} + elif(j['searchtype'] == "keywordSearch"): + result = self.application.dbapi.searchUserbySexAgeKind(j) + else: + result = self.application.dbapi.getUserAround(j['longitude'],j['latitude'],5) + print result + self.write(json_encode(result)) + print("Login success") + return + +class GetAvatarHandler(tornado.web.RequestHandler): + def get(self): + self.write("

CancelHandler

") + + def post(self): + content =self.request.body + print content + #content = '{"uid":"test","username":"testname"}' + j = json.loads(content) + result = {} + if('uid' in j): + result['avatar'] = self.application.util.getAvatarbyUid(j['uid']) + else: + result['avatar'] = self.application.util.getAvatar(j['username'],self.application.dbapi) + self.write(json_encode(result)) + return diff --git a/code/handler/UserInfoHandler.py b/code/handler/UserInfoHandler.py new file mode 100644 index 0000000..16b95de --- /dev/null +++ b/code/handler/UserInfoHandler.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +import tornado.ioloop +import tornado.web +import tornado.httpserver +from tornado.escape import * +import json + +class UpdateUserInfoHandler(tornado.web.RequestHandler): + def get(self): + self.write("

UpdateUserInfoHandler

") + + def post(self): + content =self.request.body + #content = '{"username":"dasda1","changemessage":{"age":15,"illness":"我是小啊小苹果"}}' + j = json.loads(content) + user = self.application.dbapi.getUserByUserName(j['username']) + if(user is None): + self.write("{'state':1}") + print "username not exist" + return + if('avatar' in j): + self.application.util.setAvatar(j['username'],j['avatar'],self.application.dbapi) + result = self.application.dbapi.updateUserinfo(user['id'],j['changemessage']) + if(isinstance(result,list)): + state = 1 + else: + state =2 + self.write("{'state':"+ str(state)+"}") + print("UpdateUserInfo success") + return + +class GetUserInfoHandler(tornado.web.RequestHandler): + def get(self): + self.write("

GetUserInfoHandler

") + + def post(self): + content =self.request.body + #content = '{"username":"test1"}' + j = json.loads(content) + user = self.application.dbapi.getUserByUserName(j['username']) + if(user is None): + self.write("{'state':1}") + print "username not exist" + return + result = self.application.dbapi.getUsermessegeByUserId(user['id']) + result['credit'] = 5 * result['credit'] + scorelimit = self.application.score.getRankByScore(result['score']) + + result['scoreMin'] = scorelimit['scoreMin'] + result['scoreMax'] = scorelimit['scoreMax'] + result['scoreLevel'] = scorelimit['scoreLevel'] + print result + self.write("{'result':"+ json_encode(result)+"}") + print("GetUserInfo success") + return diff --git a/code/handler/__init__.py b/code/handler/__init__.py index 9540260..b8fad30 100644 --- a/code/handler/__init__.py +++ b/code/handler/__init__.py @@ -1,16 +1,10 @@ -__all__ = ["RegisterHandler", - "LoginHandler", - "AuthenHandler", - "LogoutHandler", - "CancelHandler", - "CheckrelativesHandler", - "DeleterelativesHandler", - "AddrelativesHandler", - "HistoryHandler", - "HelpmessageHandler", - "SupportmessageHandler", - "FinishHandler", - "GivecreditHandler", - "AddaidHandler", - "SendsupportHandler", - "QuitaidHandler"] +__all__ = [ + "UserHandler", + "RelativesHandler", + "HistoryHandler", + "EventHandler", + "UserInfoHandler", + "FollowHandler", + "GetArroundEvent", + "ThirdPartHandlers", + "Authorize"] diff --git a/code/handler/xmltojson.py b/code/handler/xmltojson.py new file mode 100644 index 0000000..6c5336a --- /dev/null +++ b/code/handler/xmltojson.py @@ -0,0 +1,134 @@ +# -*- coding: utf-8 -*- +#python xml.etree.ElementTree + +import os +import xml.etree.ElementTree as ET +from xml.dom import minidom + +class xmltojson: + #global var + #show log + SHOW_LOG = True + #XML file + XML_PATH = None + a={} + m=[] + + def get_root(self,path): + '''parse the XML file,and get the tree of the XML file + finally,return the root element of the tree. + if the XML file dose not exist,then print the information''' + #if os.path.exists(path): + #if SHOW_LOG: + #print('start to parse the file : [{}]'.format(path)) + tree = ET.fromstring(path) + return tree + #else: + #print('the path [{}] dose not exist!'.format(path)) + + def get_element_tag(self,element): + '''return the element tag if the element is not None.''' + if element is not None: + + return element.tag + else: + print('the element is None!') + + def get_element_attrib(self,element): + '''return the element attrib if the element is not None.''' + if element is not None: + + return element.attrib + else: + print('the element is None!') + + def get_element_text(self,element): + '''return the text of the element.''' + if element is not None: + return element.text + else: + print('the element is None!') + + def get_element_children(self,element): + '''return the element children if the element is not None.''' + if element is not None: + + return [c for c in element] + else: + print('the element is None!') + + def get_elements_tag(self,elements): + '''return the list of tags of element's tag''' + if elements is not None: + tags = [] + for e in elements: + tags.append(e.tag) + return tags + else: + print('the elements is None!') + + def get_elements_attrib(self,elements): + '''return the list of attribs of element's attrib''' + if elements is not None: + attribs = [] + for a in elements: + attribs.append(a.attrib) + return attribs + else: + print('the elements is None!') + + def get_elements_text(self,elements): + '''return the dict of element''' + if elements is not None: + text = [] + for t in elements: + text.append(t.text) + return dict(zip(self.get_elements_tag(elements), text)) + else: + print('the elements is None!') + + + + def main(self,xml): + + #root + root = self.get_root(xml) + + #children + children = self.get_element_children(root) + + children_tags = self.get_elements_tag(children) + + children_attribs = self.get_elements_attrib(children) + + i=0 + + #获取二级元素的每一个子节点的名称和值 + for c in children: + p=0 + c_children = self.get_element_children(c) + dict_text = self.get_elements_text(c_children) + if dict_text : + if children_tags[i] =='TemplateSMS': + self.a['templateSMS']=dict_text + else : + if children_tags[i]=='SubAccount': + k=0 + + for x in children: + if children_tags[k]=='totalCount': + self.m.append(dict_text) + self.a['SubAccount']=self.m + p=1 + k=k+1 + if p==0: + self.a[children_tags[i]]=dict_text + else: + self.a[children_tags[i]]=dict_text + + + else: + self.a[children_tags[i]]=c.text + i=i+1 + return self.a + diff --git a/code/index.html b/code/index.html deleted file mode 100644 index 34ff401..0000000 --- a/code/index.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - Test - - -
- - - - - - - -
- - - /api/addrelatives -
- - - - - -
- - /api/deleterelatives -
- - - - - -
- - /api/addaid -
- - - - - -
- - - - - - \ No newline at end of file diff --git a/code/main.py b/code/main.py index 2ccc35d..3528967 100644 --- a/code/main.py +++ b/code/main.py @@ -1,39 +1,10 @@ import tornado.ioloop import tornado.web import tornado.httpserver -import os,MySQLdb,dbapi +import os,MySQLdb,dbapi,util,score from handler import * - -#Change the handler class and make it to fit your requirement -#class historyHandler(tornado.web.RequestHandler): -# def get(self): -# self.render("index.html") - -# def post(self): -# username=self.get_argument("username") -# print self.application.dbapi.getEventById(1) - -#register url handler -#class RegisterHandler(tornado.web.RequestHandler): -# def post(self): - #content = self.get_argument("content") -# content = '{"username": "haha","password": 111111,"kind": 1, "cardid":11301 ,"realname":"hiii","sex":1,"age":41, "address":"iii","illness":"hijiiii"}' -# j = json.loads(content) -# if(self.application.dbapi.hasuserName(j['username'])): -# return {'state':1} -# if(self.application.dbapi.hascardid(j['cardid'])): -# return {'state':2} -# self.application.dbapi.regist(j) -# return {'state':3} - -#login url handler -class IndexHandler(tornado.web.RequestHandler): - def get(self): - self.render("index.html") - -#class authentication - - +from push import * +from xml.dom.minidom import parse,parseString class app(tornado.web.Application): def __init__(self): @@ -41,26 +12,55 @@ def __init__(self): "static_path": os.path.join(os.path.dirname(__file__), "static"), "debug": True } - handlers=[(r"/",IndexHandler), - (r"/api/login",LoginHandler.LoginHandler), - (r"/api/register",RegisterHandler.RegisterHandler), - (r"/api/userauthentication",AuthenHandler.AuthenHandler), - (r"/api/logout",LogoutHandler.LogoutHandler), - (r"/api/cancel",CancelHandler.CancelHandler), - (r"/api/checkrelatives",CheckrelativesHandler.CheckrelativesHandler), - (r"/api/deleterelatives",DeleterelativesHandler.DeleterelativesHandler), - (r"/api/addrelatives",AddrelativesHandler.AddrelativesHandler), - (r"/api/history",HistoryHandler.HistoryHandler), - (r"/api/helpmessage",HelpmessageHandler.HelpmessageHandler), - (r"/api/supportmessage",SupportmessageHandler.SupportmessageHandler), - (r"/api/finish",FinishHandler.FinishHandler), - (r"/api/givecredit",GivecreditHandler.GivecreditHandler), - (r"/api/addaid",AddaidHandler.AddaidHandler), - (r"/api/sendsupport",SendsupportHandler.SendsupportHandler), - (r"/api/quitaid",QuitaidHandler.QuitaidHandler) - ] + handlers=[ + (r"/api/login",UserHandler.LoginHandler), + (r"/api/register",UserHandler.RegisterHandler), + (r"/api/userauthentication",UserHandler.AuthenHandler), + (r"/api/logout",UserHandler.LogoutHandler), + (r"/api/cancel",UserHandler.CancelHandler), + (r"/api/updatecid",UserHandler.UpdateCid), + (r"/api/search",UserHandler.SearchHandler), + (r"/api/getavatar",UserHandler.GetAvatarHandler), + + (r"/api/checkrelatives",RelativesHandler.CheckrelativesHandler), + (r"/api/deleterelatives",RelativesHandler.DeleterelativesHandler), + (r"/api/addrelatives",RelativesHandler.AddrelativesHandler), + (r"/api/agreerelatives",RelativesHandler.AgreerelativesHandler), + (r"/api/getvalidation",RelativesHandler.ValidationHandler), + + (r"/api/history",HistoryHandler.HistoryHandler), + + (r"/api/helpmessage",EventHandler.HelpmessageHandler), + (r"/api/supportmessage",EventHandler.SupportmessageHandler), + (r"/api/finish",EventHandler.FinishHandler), + (r"/api/givecredit",EventHandler.GivecreditHandler), + (r"/api/addaid",EventHandler.AddaidHandler), + (r"/api/sendsupport",EventHandler.SendsupportHandler), + (r"/api/quitaid",EventHandler.QuitaidHandler), + (r"/api/event",EventHandler.EventHandler), + + (r"/api/getuserinfo",UserInfoHandler.GetUserInfoHandler), + (r"/api/updateuserinfo",UserInfoHandler.UpdateUserInfoHandler), + + (r"/api/getAround",GetArroundEvent.GetArroundEvent), + + (r"/api/startfollow",FollowHandler.startFollowHandler), + (r"/api/cancelfollow",FollowHandler.cancelFollowHandler), + + (r"/api/thirdpartylogin",ThirdPartHandlers.ThirdPartyLoginHandler), + (r"/api/thirdpartyremoveaccount",ThirdPartHandlers.ThirdPartyRemoveAccountHandler), + (r"/api/thirdpartyfilluserinfo",ThirdPartHandlers.ThirdPartyFillUserInfoHandler), + + (r"/api/authstate", Authorize.AuthStateHandler), + (r"/api/requestemailauth", Authorize.RequestEmailAuthHandler), + (r"/api/authemail", Authorize.AuthEmailHandler), + (r"/api/requestphoneauth", Authorize.RequestPhoneAuthHandler), + (r"/api/authphone", Authorize.AuthPhoneHandler)] tornado.web.Application.__init__(self,handlers,**settings) self.dbapi=dbapi.dbapi() + self.util=util.util() + self.push = Push() + self.score=score.score() if __name__=="__main__": diff --git a/code/push/__init__.py b/code/push/__init__.py new file mode 100644 index 0000000..a32bd9d --- /dev/null +++ b/code/push/__init__.py @@ -0,0 +1,92 @@ +__all__=["Push"] + +from igt_push import * +from igetui.template import * +from igetui.template.igt_base_template import * +from igetui.template.igt_transmission_template import * +from igetui.template.igt_link_template import * +from igetui.template.igt_notification_template import * +from igetui.template.igt_notypopload_template import * +from igetui.igt_message import * +from igetui.igt_target import * +from igetui.template import * + +class Push: + + __APPKEY = "r3Gm2zkRsb8QLMq2U92Bi8" + __APPID = "0yZq9kruSq8zvSpYB2UiA1" + __MASTERSECRET = "h8Ppk4heNR6MACNWjN3XB2" + __HOST = 'http://sdk.open.api.igexin.com/apiex.htm' + + + __TEMPLATE = TransmissionTemplate() + + def __init__(self): + + self.__TEMPLATE = TransmissionTemplate() + self.__TEMPLATE.transmissionType = 2 + self.__TEMPLATE.appId = self.__APPID + self.__TEMPLATE.appKey = self.__APPKEY + + def pushToSingle(self, CID, content): + push = IGeTui(self.__HOST, self.__APPKEY, self.__MASTERSECRET) + + self.__TEMPLATE.transmissionContent = content + + message = IGtSingleMessage() + message.isOffline = True + message.offlineExpireTime = 1000 * 3600 * 12 + message.data = self.__TEMPLATE + + target = Target() + target.appId = self.__APPID + target.clientId = CID + + ret = push.pushMessageToSingle(message, target) + return ret + + def pushToList(self, CIDList, content, details=False): + push = IGeTui(self.__HOST, self.__APPKEY, self.__MASTERSECRET) + + self.__TEMPLATE.transmissionContent = content + + os.environ['needDetails'] = 'true' if details else 'false' + + message = IGtListMessage() + message.data = self.__TEMPLATE + message.isOffline = True + message.offlineExpireTime = 1000 * 3600 * 12 + + targets = []; + + for index in range(len(CIDList)): + target = Target() + target.appId = self.__APPID + target.clientId = CIDList[index] + targets.append(target) + + contentId = push.getContentId(message) + ret = push.pushMessageToList(contentId, targets) + return ret + + def pushToAll(self, content): + push = IGeTui(self.__HOST, self.__APPKEY, self.__MASTERSECRET) + + self.__TEMPLATE.transmissionContent = content + + message = IGtAppMessage() + message.data = self.__TEMPLATE + message.isOffline = True + message.offlineExpireTime = 1000 * 3600 * 12 + message.appIdList.extend([self.__APPID]) + + ret = push.pushMessageToApp(message) + return ret + + def getUserStatus(self, CID): + push = IGeTui(self.__HOST, self.__APPKEY, self.__MASTERSECRET) + return push.getClientIdStatus(self.__APPID, CID) + + def stopTask(self): + push = IGeTui(self.__HOST, self.__APPKEY, self.__MASTERSECRET) + return push.stop("OSA-0226_50RYYPFmos9eQEHZrkAf27") diff --git a/code/push/get_push_result.py b/code/push/get_push_result.py new file mode 100644 index 0000000..ce3223c --- /dev/null +++ b/code/push/get_push_result.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +#数据将在30分钟之后提供查询 +#最后更新时间为2013.10.22 +import hashlib +import urllib, urllib2, json +def getPushResult(url,appKey,masterSecret,taskId): + params = {} + params["action"] = "getPushMsgResult" + params["appkey"] = appKey + params["taskId"] = taskId + sign = createSign(params,masterSecret) + params["sign"] = sign + rep = httpPost(url,params) + return rep +def createSign(params,masterSecret): + sign = masterSecret + for (k,v) in params.items(): + sign = sign+k+v + return hashlib.md5(sign).hexdigest() +def httpPost(url, params): + data_json = json.dumps(params) + req = urllib2.Request(url, data_json) + res_stream = urllib2.urlopen(req, timeout = 60) + page_str = res_stream.read() + page_dict = eval(page_str) + return page_dict +rep = getPushResult("http://sdk.open.api.igexin.com/api.htm","tpDVam96sY8pxhwBupJ462","TBokfpttQJ6aHIhBE9y867","GT_1017_gJs4GvJxZV77gdgBKsuvO9") +print rep + + + diff --git a/code/push/google/__init__.py b/code/push/google/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/code/push/google/__init__.py @@ -0,0 +1 @@ + diff --git a/template/static/tornado_static_path b/code/push/google/protobuf/__init__.py similarity index 100% rename from template/static/tornado_static_path rename to code/push/google/protobuf/__init__.py diff --git a/code/push/google/protobuf/compiler/__init__.py b/code/push/google/protobuf/compiler/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/code/push/google/protobuf/compiler/plugin_pb2.py b/code/push/google/protobuf/compiler/plugin_pb2.py new file mode 100644 index 0000000..77cc07a --- /dev/null +++ b/code/push/google/protobuf/compiler/plugin_pb2.py @@ -0,0 +1,166 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/compiler/plugin.proto + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + + +import google.protobuf.descriptor_pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/compiler/plugin.proto', + package='google.protobuf.compiler', + serialized_pb='\n%google/protobuf/compiler/plugin.proto\x12\x18google.protobuf.compiler\x1a google/protobuf/descriptor.proto\"}\n\x14\x43odeGeneratorRequest\x12\x18\n\x10\x66ile_to_generate\x18\x01 \x03(\t\x12\x11\n\tparameter\x18\x02 \x01(\t\x12\x38\n\nproto_file\x18\x0f \x03(\x0b\x32$.google.protobuf.FileDescriptorProto\"\xaa\x01\n\x15\x43odeGeneratorResponse\x12\r\n\x05\x65rror\x18\x01 \x01(\t\x12\x42\n\x04\x66ile\x18\x0f \x03(\x0b\x32\x34.google.protobuf.compiler.CodeGeneratorResponse.File\x1a>\n\x04\x46ile\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x17\n\x0finsertion_point\x18\x02 \x01(\t\x12\x0f\n\x07\x63ontent\x18\x0f \x01(\tB,\n\x1c\x63om.google.protobuf.compilerB\x0cPluginProtos') + + + + +_CODEGENERATORREQUEST = _descriptor.Descriptor( + name='CodeGeneratorRequest', + full_name='google.protobuf.compiler.CodeGeneratorRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='file_to_generate', full_name='google.protobuf.compiler.CodeGeneratorRequest.file_to_generate', index=0, + number=1, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='parameter', full_name='google.protobuf.compiler.CodeGeneratorRequest.parameter', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='proto_file', full_name='google.protobuf.compiler.CodeGeneratorRequest.proto_file', index=2, + number=15, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=101, + serialized_end=226, +) + + +_CODEGENERATORRESPONSE_FILE = _descriptor.Descriptor( + name='File', + full_name='google.protobuf.compiler.CodeGeneratorResponse.File', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.compiler.CodeGeneratorResponse.File.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='insertion_point', full_name='google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='content', full_name='google.protobuf.compiler.CodeGeneratorResponse.File.content', index=2, + number=15, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=337, + serialized_end=399, +) + +_CODEGENERATORRESPONSE = _descriptor.Descriptor( + name='CodeGeneratorResponse', + full_name='google.protobuf.compiler.CodeGeneratorResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='error', full_name='google.protobuf.compiler.CodeGeneratorResponse.error', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='file', full_name='google.protobuf.compiler.CodeGeneratorResponse.file', index=1, + number=15, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_CODEGENERATORRESPONSE_FILE, ], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=229, + serialized_end=399, +) + +_CODEGENERATORREQUEST.fields_by_name['proto_file'].message_type = google.protobuf.descriptor_pb2._FILEDESCRIPTORPROTO +_CODEGENERATORRESPONSE_FILE.containing_type = _CODEGENERATORRESPONSE; +_CODEGENERATORRESPONSE.fields_by_name['file'].message_type = _CODEGENERATORRESPONSE_FILE +DESCRIPTOR.message_types_by_name['CodeGeneratorRequest'] = _CODEGENERATORREQUEST +DESCRIPTOR.message_types_by_name['CodeGeneratorResponse'] = _CODEGENERATORRESPONSE + +class CodeGeneratorRequest(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _CODEGENERATORREQUEST + + # @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorRequest) + +class CodeGeneratorResponse(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class File(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _CODEGENERATORRESPONSE_FILE + + # @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorResponse.File) + DESCRIPTOR = _CODEGENERATORRESPONSE + + # @@protoc_insertion_point(class_scope:google.protobuf.compiler.CodeGeneratorResponse) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), '\n\034com.google.protobuf.compilerB\014PluginProtos') +# @@protoc_insertion_point(module_scope) diff --git a/code/push/google/protobuf/descriptor.py b/code/push/google/protobuf/descriptor.py new file mode 100644 index 0000000..b6984d7 --- /dev/null +++ b/code/push/google/protobuf/descriptor.py @@ -0,0 +1,713 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Descriptors essentially contain exactly the information found in a .proto +file, in types that make this information accessible in Python. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + + +from push.google.protobuf.internal import api_implementation + + +if api_implementation.Type() == 'cpp': + if api_implementation.Version() == 2: + from google.protobuf.internal.cpp import _message + else: + from google.protobuf.internal import cpp_message + + +class Error(Exception): + """Base error for this module.""" + + +class TypeTransformationError(Error): + """Error transforming between python proto type and corresponding C++ type.""" + + +class DescriptorBase(object): + + """Descriptors base class. + + This class is the base of all descriptor classes. It provides common options + related functionaility. + + Attributes: + has_options: True if the descriptor has non-default options. Usually it + is not necessary to read this -- just call GetOptions() which will + happily return the default instance. However, it's sometimes useful + for efficiency, and also useful inside the protobuf implementation to + avoid some bootstrapping issues. + """ + + def __init__(self, options, options_class_name): + """Initialize the descriptor given its options message and the name of the + class of the options message. The name of the class is required in case + the options message is None and has to be created. + """ + self._options = options + self._options_class_name = options_class_name + + # Does this descriptor have non-default options? + self.has_options = options is not None + + def _SetOptions(self, options, options_class_name): + """Sets the descriptor's options + + This function is used in generated proto2 files to update descriptor + options. It must not be used outside proto2. + """ + self._options = options + self._options_class_name = options_class_name + + # Does this descriptor have non-default options? + self.has_options = options is not None + + def GetOptions(self): + """Retrieves descriptor options. + + This method returns the options set or creates the default options for the + descriptor. + """ + if self._options: + return self._options + from google.protobuf import descriptor_pb2 + try: + options_class = getattr(descriptor_pb2, self._options_class_name) + except AttributeError: + raise RuntimeError('Unknown options class name %s!' % + (self._options_class_name)) + self._options = options_class() + return self._options + + +class _NestedDescriptorBase(DescriptorBase): + """Common class for descriptors that can be nested.""" + + def __init__(self, options, options_class_name, name, full_name, + file, containing_type, serialized_start=None, + serialized_end=None): + """Constructor. + + Args: + options: Protocol message options or None + to use default message options. + options_class_name: (str) The class name of the above options. + + name: (str) Name of this protocol message type. + full_name: (str) Fully-qualified name of this protocol message type, + which will include protocol "package" name and the name of any + enclosing types. + file: (FileDescriptor) Reference to file info. + containing_type: if provided, this is a nested descriptor, with this + descriptor as parent, otherwise None. + serialized_start: The start index (inclusive) in block in the + file.serialized_pb that describes this descriptor. + serialized_end: The end index (exclusive) in block in the + file.serialized_pb that describes this descriptor. + """ + super(_NestedDescriptorBase, self).__init__( + options, options_class_name) + + self.name = name + # TODO(falk): Add function to calculate full_name instead of having it in + # memory? + self.full_name = full_name + self.file = file + self.containing_type = containing_type + + self._serialized_start = serialized_start + self._serialized_end = serialized_end + + def GetTopLevelContainingType(self): + """Returns the root if this is a nested type, or itself if its the root.""" + desc = self + while desc.containing_type is not None: + desc = desc.containing_type + return desc + + def CopyToProto(self, proto): + """Copies this to the matching proto in descriptor_pb2. + + Args: + proto: An empty proto instance from descriptor_pb2. + + Raises: + Error: If self couldnt be serialized, due to to few constructor arguments. + """ + if (self.file is not None and + self._serialized_start is not None and + self._serialized_end is not None): + proto.ParseFromString(self.file.serialized_pb[ + self._serialized_start:self._serialized_end]) + else: + raise Error('Descriptor does not contain serialization.') + + +class Descriptor(_NestedDescriptorBase): + + """Descriptor for a protocol message type. + + A Descriptor instance has the following attributes: + + name: (str) Name of this protocol message type. + full_name: (str) Fully-qualified name of this protocol message type, + which will include protocol "package" name and the name of any + enclosing types. + + containing_type: (Descriptor) Reference to the descriptor of the + type containing us, or None if this is top-level. + + fields: (list of FieldDescriptors) Field descriptors for all + fields in this type. + fields_by_number: (dict int -> FieldDescriptor) Same FieldDescriptor + objects as in |fields|, but indexed by "number" attribute in each + FieldDescriptor. + fields_by_name: (dict str -> FieldDescriptor) Same FieldDescriptor + objects as in |fields|, but indexed by "name" attribute in each + FieldDescriptor. + + nested_types: (list of Descriptors) Descriptor references + for all protocol message types nested within this one. + nested_types_by_name: (dict str -> Descriptor) Same Descriptor + objects as in |nested_types|, but indexed by "name" attribute + in each Descriptor. + + enum_types: (list of EnumDescriptors) EnumDescriptor references + for all enums contained within this type. + enum_types_by_name: (dict str ->EnumDescriptor) Same EnumDescriptor + objects as in |enum_types|, but indexed by "name" attribute + in each EnumDescriptor. + enum_values_by_name: (dict str -> EnumValueDescriptor) Dict mapping + from enum value name to EnumValueDescriptor for that value. + + extensions: (list of FieldDescriptor) All extensions defined directly + within this message type (NOT within a nested type). + extensions_by_name: (dict, string -> FieldDescriptor) Same FieldDescriptor + objects as |extensions|, but indexed by "name" attribute of each + FieldDescriptor. + + is_extendable: Does this type define any extension ranges? + + options: (descriptor_pb2.MessageOptions) Protocol message options or None + to use default message options. + + file: (FileDescriptor) Reference to file descriptor. + """ + + def __init__(self, name, full_name, filename, containing_type, fields, + nested_types, enum_types, extensions, options=None, + is_extendable=True, extension_ranges=None, file=None, + serialized_start=None, serialized_end=None): + """Arguments to __init__() are as described in the description + of Descriptor fields above. + + Note that filename is an obsolete argument, that is not used anymore. + Please use file.name to access this as an attribute. + """ + super(Descriptor, self).__init__( + options, 'MessageOptions', name, full_name, file, + containing_type, serialized_start=serialized_start, + serialized_end=serialized_start) + + # We have fields in addition to fields_by_name and fields_by_number, + # so that: + # 1. Clients can index fields by "order in which they're listed." + # 2. Clients can easily iterate over all fields with the terse + # syntax: for f in descriptor.fields: ... + self.fields = fields + for field in self.fields: + field.containing_type = self + self.fields_by_number = dict((f.number, f) for f in fields) + self.fields_by_name = dict((f.name, f) for f in fields) + + self.nested_types = nested_types + self.nested_types_by_name = dict((t.name, t) for t in nested_types) + + self.enum_types = enum_types + for enum_type in self.enum_types: + enum_type.containing_type = self + self.enum_types_by_name = dict((t.name, t) for t in enum_types) + self.enum_values_by_name = dict( + (v.name, v) for t in enum_types for v in t.values) + + self.extensions = extensions + for extension in self.extensions: + extension.extension_scope = self + self.extensions_by_name = dict((f.name, f) for f in extensions) + self.is_extendable = is_extendable + self.extension_ranges = extension_ranges + + self._serialized_start = serialized_start + self._serialized_end = serialized_end + + def EnumValueName(self, enum, value): + """Returns the string name of an enum value. + + This is just a small helper method to simplify a common operation. + + Args: + enum: string name of the Enum. + value: int, value of the enum. + + Returns: + string name of the enum value. + + Raises: + KeyError if either the Enum doesn't exist or the value is not a valid + value for the enum. + """ + return self.enum_types_by_name[enum].values_by_number[value].name + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.DescriptorProto. + + Args: + proto: An empty descriptor_pb2.DescriptorProto. + """ + # This function is overriden to give a better doc comment. + super(Descriptor, self).CopyToProto(proto) + + +# TODO(robinson): We should have aggressive checking here, +# for example: +# * If you specify a repeated field, you should not be allowed +# to specify a default value. +# * [Other examples here as needed]. +# +# TODO(robinson): for this and other *Descriptor classes, we +# might also want to lock things down aggressively (e.g., +# prevent clients from setting the attributes). Having +# stronger invariants here in general will reduce the number +# of runtime checks we must do in reflection.py... +class FieldDescriptor(DescriptorBase): + + """Descriptor for a single field in a .proto file. + + A FieldDescriptor instance has the following attributes: + + name: (str) Name of this field, exactly as it appears in .proto. + full_name: (str) Name of this field, including containing scope. This is + particularly relevant for extensions. + index: (int) Dense, 0-indexed index giving the order that this + field textually appears within its message in the .proto file. + number: (int) Tag number declared for this field in the .proto file. + + type: (One of the TYPE_* constants below) Declared type. + cpp_type: (One of the CPPTYPE_* constants below) C++ type used to + represent this field. + + label: (One of the LABEL_* constants below) Tells whether this + field is optional, required, or repeated. + has_default_value: (bool) True if this field has a default value defined, + otherwise false. + default_value: (Varies) Default value of this field. Only + meaningful for non-repeated scalar fields. Repeated fields + should always set this to [], and non-repeated composite + fields should always set this to None. + + containing_type: (Descriptor) Descriptor of the protocol message + type that contains this field. Set by the Descriptor constructor + if we're passed into one. + Somewhat confusingly, for extension fields, this is the + descriptor of the EXTENDED message, not the descriptor + of the message containing this field. (See is_extension and + extension_scope below). + message_type: (Descriptor) If a composite field, a descriptor + of the message type contained in this field. Otherwise, this is None. + enum_type: (EnumDescriptor) If this field contains an enum, a + descriptor of that enum. Otherwise, this is None. + + is_extension: True iff this describes an extension field. + extension_scope: (Descriptor) Only meaningful if is_extension is True. + Gives the message that immediately contains this extension field. + Will be None iff we're a top-level (file-level) extension field. + + options: (descriptor_pb2.FieldOptions) Protocol message field options or + None to use default field options. + """ + + # Must be consistent with C++ FieldDescriptor::Type enum in + # descriptor.h. + # + # TODO(robinson): Find a way to eliminate this repetition. + TYPE_DOUBLE = 1 + TYPE_FLOAT = 2 + TYPE_INT64 = 3 + TYPE_UINT64 = 4 + TYPE_INT32 = 5 + TYPE_FIXED64 = 6 + TYPE_FIXED32 = 7 + TYPE_BOOL = 8 + TYPE_STRING = 9 + TYPE_GROUP = 10 + TYPE_MESSAGE = 11 + TYPE_BYTES = 12 + TYPE_UINT32 = 13 + TYPE_ENUM = 14 + TYPE_SFIXED32 = 15 + TYPE_SFIXED64 = 16 + TYPE_SINT32 = 17 + TYPE_SINT64 = 18 + MAX_TYPE = 18 + + # Must be consistent with C++ FieldDescriptor::CppType enum in + # descriptor.h. + # + # TODO(robinson): Find a way to eliminate this repetition. + CPPTYPE_INT32 = 1 + CPPTYPE_INT64 = 2 + CPPTYPE_UINT32 = 3 + CPPTYPE_UINT64 = 4 + CPPTYPE_DOUBLE = 5 + CPPTYPE_FLOAT = 6 + CPPTYPE_BOOL = 7 + CPPTYPE_ENUM = 8 + CPPTYPE_STRING = 9 + CPPTYPE_MESSAGE = 10 + MAX_CPPTYPE = 10 + + _PYTHON_TO_CPP_PROTO_TYPE_MAP = { + TYPE_DOUBLE: CPPTYPE_DOUBLE, + TYPE_FLOAT: CPPTYPE_FLOAT, + TYPE_ENUM: CPPTYPE_ENUM, + TYPE_INT64: CPPTYPE_INT64, + TYPE_SINT64: CPPTYPE_INT64, + TYPE_SFIXED64: CPPTYPE_INT64, + TYPE_UINT64: CPPTYPE_UINT64, + TYPE_FIXED64: CPPTYPE_UINT64, + TYPE_INT32: CPPTYPE_INT32, + TYPE_SFIXED32: CPPTYPE_INT32, + TYPE_SINT32: CPPTYPE_INT32, + TYPE_UINT32: CPPTYPE_UINT32, + TYPE_FIXED32: CPPTYPE_UINT32, + TYPE_BYTES: CPPTYPE_STRING, + TYPE_STRING: CPPTYPE_STRING, + TYPE_BOOL: CPPTYPE_BOOL, + TYPE_MESSAGE: CPPTYPE_MESSAGE, + TYPE_GROUP: CPPTYPE_MESSAGE + } + + # Must be consistent with C++ FieldDescriptor::Label enum in + # descriptor.h. + # + # TODO(robinson): Find a way to eliminate this repetition. + LABEL_OPTIONAL = 1 + LABEL_REQUIRED = 2 + LABEL_REPEATED = 3 + MAX_LABEL = 3 + + def __init__(self, name, full_name, index, number, type, cpp_type, label, + default_value, message_type, enum_type, containing_type, + is_extension, extension_scope, options=None, + has_default_value=True): + """The arguments are as described in the description of FieldDescriptor + attributes above. + + Note that containing_type may be None, and may be set later if necessary + (to deal with circular references between message types, for example). + Likewise for extension_scope. + """ + super(FieldDescriptor, self).__init__(options, 'FieldOptions') + self.name = name + self.full_name = full_name + self.index = index + self.number = number + self.type = type + self.cpp_type = cpp_type + self.label = label + self.has_default_value = has_default_value + self.default_value = default_value + self.containing_type = containing_type + self.message_type = message_type + self.enum_type = enum_type + self.is_extension = is_extension + self.extension_scope = extension_scope + if api_implementation.Type() == 'cpp': + if is_extension: + if api_implementation.Version() == 2: + self._cdescriptor = _message.GetExtensionDescriptor(full_name) + else: + self._cdescriptor = cpp_message.GetExtensionDescriptor(full_name) + else: + if api_implementation.Version() == 2: + self._cdescriptor = _message.GetFieldDescriptor(full_name) + else: + self._cdescriptor = cpp_message.GetFieldDescriptor(full_name) + else: + self._cdescriptor = None + + @staticmethod + def ProtoTypeToCppProtoType(proto_type): + """Converts from a Python proto type to a C++ Proto Type. + + The Python ProtocolBuffer classes specify both the 'Python' datatype and the + 'C++' datatype - and they're not the same. This helper method should + translate from one to another. + + Args: + proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*) + Returns: + descriptor.FieldDescriptor.CPPTYPE_*, the C++ type. + Raises: + TypeTransformationError: when the Python proto type isn't known. + """ + try: + return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type] + except KeyError: + raise TypeTransformationError('Unknown proto_type: %s' % proto_type) + + +class EnumDescriptor(_NestedDescriptorBase): + + """Descriptor for an enum defined in a .proto file. + + An EnumDescriptor instance has the following attributes: + + name: (str) Name of the enum type. + full_name: (str) Full name of the type, including package name + and any enclosing type(s). + + values: (list of EnumValueDescriptors) List of the values + in this enum. + values_by_name: (dict str -> EnumValueDescriptor) Same as |values|, + but indexed by the "name" field of each EnumValueDescriptor. + values_by_number: (dict int -> EnumValueDescriptor) Same as |values|, + but indexed by the "number" field of each EnumValueDescriptor. + containing_type: (Descriptor) Descriptor of the immediate containing + type of this enum, or None if this is an enum defined at the + top level in a .proto file. Set by Descriptor's constructor + if we're passed into one. + file: (FileDescriptor) Reference to file descriptor. + options: (descriptor_pb2.EnumOptions) Enum options message or + None to use default enum options. + """ + + def __init__(self, name, full_name, filename, values, + containing_type=None, options=None, file=None, + serialized_start=None, serialized_end=None): + """Arguments are as described in the attribute description above. + + Note that filename is an obsolete argument, that is not used anymore. + Please use file.name to access this as an attribute. + """ + super(EnumDescriptor, self).__init__( + options, 'EnumOptions', name, full_name, file, + containing_type, serialized_start=serialized_start, + serialized_end=serialized_start) + + self.values = values + for value in self.values: + value.type = self + self.values_by_name = dict((v.name, v) for v in values) + self.values_by_number = dict((v.number, v) for v in values) + + self._serialized_start = serialized_start + self._serialized_end = serialized_end + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.EnumDescriptorProto. + + Args: + proto: An empty descriptor_pb2.EnumDescriptorProto. + """ + # This function is overriden to give a better doc comment. + super(EnumDescriptor, self).CopyToProto(proto) + + +class EnumValueDescriptor(DescriptorBase): + + """Descriptor for a single value within an enum. + + name: (str) Name of this value. + index: (int) Dense, 0-indexed index giving the order that this + value appears textually within its enum in the .proto file. + number: (int) Actual number assigned to this enum value. + type: (EnumDescriptor) EnumDescriptor to which this value + belongs. Set by EnumDescriptor's constructor if we're + passed into one. + options: (descriptor_pb2.EnumValueOptions) Enum value options message or + None to use default enum value options options. + """ + + def __init__(self, name, index, number, type=None, options=None): + """Arguments are as described in the attribute description above.""" + super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions') + self.name = name + self.index = index + self.number = number + self.type = type + + +class ServiceDescriptor(_NestedDescriptorBase): + + """Descriptor for a service. + + name: (str) Name of the service. + full_name: (str) Full name of the service, including package name. + index: (int) 0-indexed index giving the order that this services + definition appears withing the .proto file. + methods: (list of MethodDescriptor) List of methods provided by this + service. + options: (descriptor_pb2.ServiceOptions) Service options message or + None to use default service options. + file: (FileDescriptor) Reference to file info. + """ + + def __init__(self, name, full_name, index, methods, options=None, file=None, + serialized_start=None, serialized_end=None): + super(ServiceDescriptor, self).__init__( + options, 'ServiceOptions', name, full_name, file, + None, serialized_start=serialized_start, + serialized_end=serialized_end) + self.index = index + self.methods = methods + # Set the containing service for each method in this service. + for method in self.methods: + method.containing_service = self + + def FindMethodByName(self, name): + """Searches for the specified method, and returns its descriptor.""" + for method in self.methods: + if name == method.name: + return method + return None + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.ServiceDescriptorProto. + + Args: + proto: An empty descriptor_pb2.ServiceDescriptorProto. + """ + # This function is overriden to give a better doc comment. + super(ServiceDescriptor, self).CopyToProto(proto) + + +class MethodDescriptor(DescriptorBase): + + """Descriptor for a method in a service. + + name: (str) Name of the method within the service. + full_name: (str) Full name of method. + index: (int) 0-indexed index of the method inside the service. + containing_service: (ServiceDescriptor) The service that contains this + method. + input_type: The descriptor of the message that this method accepts. + output_type: The descriptor of the message that this method returns. + options: (descriptor_pb2.MethodOptions) Method options message or + None to use default method options. + """ + + def __init__(self, name, full_name, index, containing_service, + input_type, output_type, options=None): + """The arguments are as described in the description of MethodDescriptor + attributes above. + + Note that containing_service may be None, and may be set later if necessary. + """ + super(MethodDescriptor, self).__init__(options, 'MethodOptions') + self.name = name + self.full_name = full_name + self.index = index + self.containing_service = containing_service + self.input_type = input_type + self.output_type = output_type + + +class FileDescriptor(DescriptorBase): + """Descriptor for a file. Mimics the descriptor_pb2.FileDescriptorProto. + + name: name of file, relative to root of source tree. + package: name of the package + serialized_pb: (str) Byte string of serialized + descriptor_pb2.FileDescriptorProto. + """ + + def __init__(self, name, package, options=None, serialized_pb=None): + """Constructor.""" + super(FileDescriptor, self).__init__(options, 'FileOptions') + + self.message_types_by_name = {} + self.name = name + self.package = package + self.serialized_pb = serialized_pb + if (api_implementation.Type() == 'cpp' and + self.serialized_pb is not None): + if api_implementation.Version() == 2: + _message.BuildFile(self.serialized_pb) + else: + cpp_message.BuildFile(self.serialized_pb) + + def CopyToProto(self, proto): + """Copies this to a descriptor_pb2.FileDescriptorProto. + + Args: + proto: An empty descriptor_pb2.FileDescriptorProto. + """ + proto.ParseFromString(self.serialized_pb) + + +def _ParseOptions(message, string): + """Parses serialized options. + + This helper function is used to parse serialized options in generated + proto2 files. It must not be used outside proto2. + """ + message.ParseFromString(string) + return message + + +def MakeDescriptor(desc_proto, package=''): + """Make a protobuf Descriptor given a DescriptorProto protobuf. + + Args: + desc_proto: The descriptor_pb2.DescriptorProto protobuf message. + package: Optional package name for the new message Descriptor (string). + + Returns: + A Descriptor for protobuf messages. + """ + full_message_name = [desc_proto.name] + if package: full_message_name.insert(0, package) + fields = [] + for field_proto in desc_proto.field: + full_name = '.'.join(full_message_name + [field_proto.name]) + field = FieldDescriptor( + field_proto.name, full_name, field_proto.number - 1, + field_proto.number, field_proto.type, + FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type), + field_proto.label, None, None, None, None, False, None, + has_default_value=False) + fields.append(field) + + desc_name = '.'.join(full_message_name) + return Descriptor(desc_proto.name, desc_name, None, None, fields, + [], [], []) diff --git a/code/push/google/protobuf/descriptor_database.py b/code/push/google/protobuf/descriptor_database.py new file mode 100644 index 0000000..8665d3c --- /dev/null +++ b/code/push/google/protobuf/descriptor_database.py @@ -0,0 +1,120 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Provides a container for DescriptorProtos.""" + +__author__ = 'matthewtoia@google.com (Matt Toia)' + + +class DescriptorDatabase(object): + """A container accepting FileDescriptorProtos and maps DescriptorProtos.""" + + def __init__(self): + self._file_desc_protos_by_file = {} + self._file_desc_protos_by_symbol = {} + + def Add(self, file_desc_proto): + """Adds the FileDescriptorProto and its types to this database. + + Args: + file_desc_proto: The FileDescriptorProto to add. + """ + + self._file_desc_protos_by_file[file_desc_proto.name] = file_desc_proto + package = file_desc_proto.package + for message in file_desc_proto.message_type: + self._file_desc_protos_by_symbol.update( + (name, file_desc_proto) for name in _ExtractSymbols(message, package)) + for enum in file_desc_proto.enum_type: + self._file_desc_protos_by_symbol[ + '.'.join((package, enum.name))] = file_desc_proto + + def FindFileByName(self, name): + """Finds the file descriptor proto by file name. + + Typically the file name is a relative path ending to a .proto file. The + proto with the given name will have to have been added to this database + using the Add method or else an error will be raised. + + Args: + name: The file name to find. + + Returns: + The file descriptor proto matching the name. + + Raises: + KeyError if no file by the given name was added. + """ + + return self._file_desc_protos_by_file[name] + + def FindFileContainingSymbol(self, symbol): + """Finds the file descriptor proto containing the specified symbol. + + The symbol should be a fully qualified name including the file descriptor's + package and any containing messages. Some examples: + + 'some.package.name.Message' + 'some.package.name.Message.NestedEnum' + + The file descriptor proto containing the specified symbol must be added to + this database using the Add method or else an error will be raised. + + Args: + symbol: The fully qualified symbol name. + + Returns: + The file descriptor proto containing the symbol. + + Raises: + KeyError if no file contains the specified symbol. + """ + + return self._file_desc_protos_by_symbol[symbol] + + +def _ExtractSymbols(desc_proto, package): + """Pulls out all the symbols from a descriptor proto. + + Args: + desc_proto: The proto to extract symbols from. + package: The package containing the descriptor type. + + Yields: + The fully qualified name found in the descriptor. + """ + + message_name = '.'.join((package, desc_proto.name)) + yield message_name + for nested_type in desc_proto.nested_type: + for symbol in _ExtractSymbols(nested_type, message_name): + yield symbol + for enum_type in desc_proto.enum_type: + yield '.'.join((message_name, enum_type.name)) diff --git a/code/push/google/protobuf/descriptor_pb2.py b/code/push/google/protobuf/descriptor_pb2.py new file mode 100644 index 0000000..2b4d54c --- /dev/null +++ b/code/push/google/protobuf/descriptor_pb2.py @@ -0,0 +1,1346 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/descriptor.proto + +from push.google.protobuf import descriptor as _descriptor +from push.google.protobuf import message as _message +from push.google.protobuf import reflection as _reflection +# @@protoc_insertion_point(imports) + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/descriptor.proto', + package='google.protobuf', + serialized_pb='\n google/protobuf/descriptor.proto\x12\x0fgoogle.protobuf\"G\n\x11\x46ileDescriptorSet\x12\x32\n\x04\x66ile\x18\x01 \x03(\x0b\x32$.google.protobuf.FileDescriptorProto\"\xcb\x03\n\x13\x46ileDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0f\n\x07package\x18\x02 \x01(\t\x12\x12\n\ndependency\x18\x03 \x03(\t\x12\x19\n\x11public_dependency\x18\n \x03(\x05\x12\x17\n\x0fweak_dependency\x18\x0b \x03(\x05\x12\x36\n\x0cmessage_type\x18\x04 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x05 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12\x38\n\x07service\x18\x06 \x03(\x0b\x32\'.google.protobuf.ServiceDescriptorProto\x12\x38\n\textension\x18\x07 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12-\n\x07options\x18\x08 \x01(\x0b\x32\x1c.google.protobuf.FileOptions\x12\x39\n\x10source_code_info\x18\t \x01(\x0b\x32\x1f.google.protobuf.SourceCodeInfo\"\xa9\x03\n\x0f\x44\x65scriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x34\n\x05\x66ield\x18\x02 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x38\n\textension\x18\x06 \x03(\x0b\x32%.google.protobuf.FieldDescriptorProto\x12\x35\n\x0bnested_type\x18\x03 \x03(\x0b\x32 .google.protobuf.DescriptorProto\x12\x37\n\tenum_type\x18\x04 \x03(\x0b\x32$.google.protobuf.EnumDescriptorProto\x12H\n\x0f\x65xtension_range\x18\x05 \x03(\x0b\x32/.google.protobuf.DescriptorProto.ExtensionRange\x12\x30\n\x07options\x18\x07 \x01(\x0b\x32\x1f.google.protobuf.MessageOptions\x1a,\n\x0e\x45xtensionRange\x12\r\n\x05start\x18\x01 \x01(\x05\x12\x0b\n\x03\x65nd\x18\x02 \x01(\x05\"\x94\x05\n\x14\x46ieldDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x03 \x01(\x05\x12:\n\x05label\x18\x04 \x01(\x0e\x32+.google.protobuf.FieldDescriptorProto.Label\x12\x38\n\x04type\x18\x05 \x01(\x0e\x32*.google.protobuf.FieldDescriptorProto.Type\x12\x11\n\ttype_name\x18\x06 \x01(\t\x12\x10\n\x08\x65xtendee\x18\x02 \x01(\t\x12\x15\n\rdefault_value\x18\x07 \x01(\t\x12.\n\x07options\x18\x08 \x01(\x0b\x32\x1d.google.protobuf.FieldOptions\"\xb6\x02\n\x04Type\x12\x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nTYPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYTES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"C\n\x05Label\x12\x12\n\x0eLABEL_OPTIONAL\x10\x01\x12\x12\n\x0eLABEL_REQUIRED\x10\x02\x12\x12\n\x0eLABEL_REPEATED\x10\x03\"\x8c\x01\n\x13\x45numDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x38\n\x05value\x18\x02 \x03(\x0b\x32).google.protobuf.EnumValueDescriptorProto\x12-\n\x07options\x18\x03 \x01(\x0b\x32\x1c.google.protobuf.EnumOptions\"l\n\x18\x45numValueDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06number\x18\x02 \x01(\x05\x12\x32\n\x07options\x18\x03 \x01(\x0b\x32!.google.protobuf.EnumValueOptions\"\x90\x01\n\x16ServiceDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x36\n\x06method\x18\x02 \x03(\x0b\x32&.google.protobuf.MethodDescriptorProto\x12\x30\n\x07options\x18\x03 \x01(\x0b\x32\x1f.google.protobuf.ServiceOptions\"\x7f\n\x15MethodDescriptorProto\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x12\n\ninput_type\x18\x02 \x01(\t\x12\x13\n\x0boutput_type\x18\x03 \x01(\t\x12/\n\x07options\x18\x04 \x01(\x0b\x32\x1e.google.protobuf.MethodOptions\"\xe9\x03\n\x0b\x46ileOptions\x12\x14\n\x0cjava_package\x18\x01 \x01(\t\x12\x1c\n\x14java_outer_classname\x18\x08 \x01(\t\x12\"\n\x13java_multiple_files\x18\n \x01(\x08:\x05\x66\x61lse\x12,\n\x1djava_generate_equals_and_hash\x18\x14 \x01(\x08:\x05\x66\x61lse\x12\x46\n\x0coptimize_for\x18\t \x01(\x0e\x32).google.protobuf.FileOptions.OptimizeMode:\x05SPEED\x12\x12\n\ngo_package\x18\x0b \x01(\t\x12\"\n\x13\x63\x63_generic_services\x18\x10 \x01(\x08:\x05\x66\x61lse\x12$\n\x15java_generic_services\x18\x11 \x01(\x08:\x05\x66\x61lse\x12\"\n\x13py_generic_services\x18\x12 \x01(\x08:\x05\x66\x61lse\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption\":\n\x0cOptimizeMode\x12\t\n\x05SPEED\x10\x01\x12\r\n\tCODE_SIZE\x10\x02\x12\x10\n\x0cLITE_RUNTIME\x10\x03*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xb8\x01\n\x0eMessageOptions\x12&\n\x17message_set_wire_format\x18\x01 \x01(\x08:\x05\x66\x61lse\x12.\n\x1fno_standard_descriptor_accessor\x18\x02 \x01(\x08:\x05\x66\x61lse\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xbe\x02\n\x0c\x46ieldOptions\x12:\n\x05\x63type\x18\x01 \x01(\x0e\x32#.google.protobuf.FieldOptions.CType:\x06STRING\x12\x0e\n\x06packed\x18\x02 \x01(\x08\x12\x13\n\x04lazy\x18\x05 \x01(\x08:\x05\x66\x61lse\x12\x19\n\ndeprecated\x18\x03 \x01(\x08:\x05\x66\x61lse\x12\x1c\n\x14\x65xperimental_map_key\x18\t \x01(\t\x12\x13\n\x04weak\x18\n \x01(\x08:\x05\x66\x61lse\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption\"/\n\x05\x43Type\x12\n\n\x06STRING\x10\x00\x12\x08\n\x04\x43ORD\x10\x01\x12\x10\n\x0cSTRING_PIECE\x10\x02*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"x\n\x0b\x45numOptions\x12\x19\n\x0b\x61llow_alias\x18\x02 \x01(\x08:\x04true\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"b\n\x10\x45numValueOptions\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"`\n\x0eServiceOptions\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"_\n\rMethodOptions\x12\x43\n\x14uninterpreted_option\x18\xe7\x07 \x03(\x0b\x32$.google.protobuf.UninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\x9e\x02\n\x13UninterpretedOption\x12;\n\x04name\x18\x02 \x03(\x0b\x32-.google.protobuf.UninterpretedOption.NamePart\x12\x18\n\x10identifier_value\x18\x03 \x01(\t\x12\x1a\n\x12positive_int_value\x18\x04 \x01(\x04\x12\x1a\n\x12negative_int_value\x18\x05 \x01(\x03\x12\x14\n\x0c\x64ouble_value\x18\x06 \x01(\x01\x12\x14\n\x0cstring_value\x18\x07 \x01(\x0c\x12\x17\n\x0f\x61ggregate_value\x18\x08 \x01(\t\x1a\x33\n\x08NamePart\x12\x11\n\tname_part\x18\x01 \x02(\t\x12\x14\n\x0cis_extension\x18\x02 \x02(\x08\"\xb1\x01\n\x0eSourceCodeInfo\x12:\n\x08location\x18\x01 \x03(\x0b\x32(.google.protobuf.SourceCodeInfo.Location\x1a\x63\n\x08Location\x12\x10\n\x04path\x18\x01 \x03(\x05\x42\x02\x10\x01\x12\x10\n\x04span\x18\x02 \x03(\x05\x42\x02\x10\x01\x12\x18\n\x10leading_comments\x18\x03 \x01(\t\x12\x19\n\x11trailing_comments\x18\x04 \x01(\tB)\n\x13\x63om.google.protobufB\x10\x44\x65scriptorProtosH\x01') + + + +_FIELDDESCRIPTORPROTO_TYPE = _descriptor.EnumDescriptor( + name='Type', + full_name='google.protobuf.FieldDescriptorProto.Type', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='TYPE_DOUBLE', index=0, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_FLOAT', index=1, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_INT64', index=2, number=3, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_UINT64', index=3, number=4, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_INT32', index=4, number=5, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_FIXED64', index=5, number=6, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_FIXED32', index=6, number=7, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_BOOL', index=7, number=8, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_STRING', index=8, number=9, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_GROUP', index=9, number=10, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_MESSAGE', index=10, number=11, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_BYTES', index=11, number=12, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_UINT32', index=12, number=13, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_ENUM', index=13, number=14, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_SFIXED32', index=14, number=15, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_SFIXED64', index=15, number=16, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_SINT32', index=16, number=17, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TYPE_SINT64', index=17, number=18, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=1298, + serialized_end=1608, +) + +_FIELDDESCRIPTORPROTO_LABEL = _descriptor.EnumDescriptor( + name='Label', + full_name='google.protobuf.FieldDescriptorProto.Label', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='LABEL_OPTIONAL', index=0, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='LABEL_REQUIRED', index=1, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='LABEL_REPEATED', index=2, number=3, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=1610, + serialized_end=1677, +) + +_FILEOPTIONS_OPTIMIZEMODE = _descriptor.EnumDescriptor( + name='OptimizeMode', + full_name='google.protobuf.FileOptions.OptimizeMode', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='SPEED', index=0, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='CODE_SIZE', index=1, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='LITE_RUNTIME', index=2, number=3, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=2629, + serialized_end=2687, +) + +_FIELDOPTIONS_CTYPE = _descriptor.EnumDescriptor( + name='CType', + full_name='google.protobuf.FieldOptions.CType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='STRING', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='CORD', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='STRING_PIECE', index=2, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=3148, + serialized_end=3195, +) + + +_FILEDESCRIPTORSET = _descriptor.Descriptor( + name='FileDescriptorSet', + full_name='google.protobuf.FileDescriptorSet', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='file', full_name='google.protobuf.FileDescriptorSet.file', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=53, + serialized_end=124, +) + + +_FILEDESCRIPTORPROTO = _descriptor.Descriptor( + name='FileDescriptorProto', + full_name='google.protobuf.FileDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.FileDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='package', full_name='google.protobuf.FileDescriptorProto.package', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dependency', full_name='google.protobuf.FileDescriptorProto.dependency', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='public_dependency', full_name='google.protobuf.FileDescriptorProto.public_dependency', index=3, + number=10, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weak_dependency', full_name='google.protobuf.FileDescriptorProto.weak_dependency', index=4, + number=11, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='message_type', full_name='google.protobuf.FileDescriptorProto.message_type', index=5, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enum_type', full_name='google.protobuf.FileDescriptorProto.enum_type', index=6, + number=5, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='service', full_name='google.protobuf.FileDescriptorProto.service', index=7, + number=6, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='extension', full_name='google.protobuf.FileDescriptorProto.extension', index=8, + number=7, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.FileDescriptorProto.options', index=9, + number=8, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='source_code_info', full_name='google.protobuf.FileDescriptorProto.source_code_info', index=10, + number=9, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=127, + serialized_end=586, +) + + +_DESCRIPTORPROTO_EXTENSIONRANGE = _descriptor.Descriptor( + name='ExtensionRange', + full_name='google.protobuf.DescriptorProto.ExtensionRange', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='start', full_name='google.protobuf.DescriptorProto.ExtensionRange.start', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='end', full_name='google.protobuf.DescriptorProto.ExtensionRange.end', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=970, + serialized_end=1014, +) + +_DESCRIPTORPROTO = _descriptor.Descriptor( + name='DescriptorProto', + full_name='google.protobuf.DescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.DescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='field', full_name='google.protobuf.DescriptorProto.field', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='extension', full_name='google.protobuf.DescriptorProto.extension', index=2, + number=6, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='nested_type', full_name='google.protobuf.DescriptorProto.nested_type', index=3, + number=3, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enum_type', full_name='google.protobuf.DescriptorProto.enum_type', index=4, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='extension_range', full_name='google.protobuf.DescriptorProto.extension_range', index=5, + number=5, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.DescriptorProto.options', index=6, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_DESCRIPTORPROTO_EXTENSIONRANGE, ], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=589, + serialized_end=1014, +) + + +_FIELDDESCRIPTORPROTO = _descriptor.Descriptor( + name='FieldDescriptorProto', + full_name='google.protobuf.FieldDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.FieldDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='number', full_name='google.protobuf.FieldDescriptorProto.number', index=1, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='label', full_name='google.protobuf.FieldDescriptorProto.label', index=2, + number=4, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type', full_name='google.protobuf.FieldDescriptorProto.type', index=3, + number=5, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type_name', full_name='google.protobuf.FieldDescriptorProto.type_name', index=4, + number=6, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='extendee', full_name='google.protobuf.FieldDescriptorProto.extendee', index=5, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_value', full_name='google.protobuf.FieldDescriptorProto.default_value', index=6, + number=7, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.FieldDescriptorProto.options', index=7, + number=8, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _FIELDDESCRIPTORPROTO_TYPE, + _FIELDDESCRIPTORPROTO_LABEL, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1017, + serialized_end=1677, +) + + +_ENUMDESCRIPTORPROTO = _descriptor.Descriptor( + name='EnumDescriptorProto', + full_name='google.protobuf.EnumDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.EnumDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='value', full_name='google.protobuf.EnumDescriptorProto.value', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.EnumDescriptorProto.options', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1680, + serialized_end=1820, +) + + +_ENUMVALUEDESCRIPTORPROTO = _descriptor.Descriptor( + name='EnumValueDescriptorProto', + full_name='google.protobuf.EnumValueDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.EnumValueDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='number', full_name='google.protobuf.EnumValueDescriptorProto.number', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.EnumValueDescriptorProto.options', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1822, + serialized_end=1930, +) + + +_SERVICEDESCRIPTORPROTO = _descriptor.Descriptor( + name='ServiceDescriptorProto', + full_name='google.protobuf.ServiceDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.ServiceDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='method', full_name='google.protobuf.ServiceDescriptorProto.method', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.ServiceDescriptorProto.options', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1933, + serialized_end=2077, +) + + +_METHODDESCRIPTORPROTO = _descriptor.Descriptor( + name='MethodDescriptorProto', + full_name='google.protobuf.MethodDescriptorProto', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.MethodDescriptorProto.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='input_type', full_name='google.protobuf.MethodDescriptorProto.input_type', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='output_type', full_name='google.protobuf.MethodDescriptorProto.output_type', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='options', full_name='google.protobuf.MethodDescriptorProto.options', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2079, + serialized_end=2206, +) + + +_FILEOPTIONS = _descriptor.Descriptor( + name='FileOptions', + full_name='google.protobuf.FileOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='java_package', full_name='google.protobuf.FileOptions.java_package', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='java_outer_classname', full_name='google.protobuf.FileOptions.java_outer_classname', index=1, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='java_multiple_files', full_name='google.protobuf.FileOptions.java_multiple_files', index=2, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='java_generate_equals_and_hash', full_name='google.protobuf.FileOptions.java_generate_equals_and_hash', index=3, + number=20, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optimize_for', full_name='google.protobuf.FileOptions.optimize_for', index=4, + number=9, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='go_package', full_name='google.protobuf.FileOptions.go_package', index=5, + number=11, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cc_generic_services', full_name='google.protobuf.FileOptions.cc_generic_services', index=6, + number=16, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='java_generic_services', full_name='google.protobuf.FileOptions.java_generic_services', index=7, + number=17, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='py_generic_services', full_name='google.protobuf.FileOptions.py_generic_services', index=8, + number=18, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.FileOptions.uninterpreted_option', index=9, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _FILEOPTIONS_OPTIMIZEMODE, + ], + options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + serialized_start=2209, + serialized_end=2698, +) + + +_MESSAGEOPTIONS = _descriptor.Descriptor( + name='MessageOptions', + full_name='google.protobuf.MessageOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='message_set_wire_format', full_name='google.protobuf.MessageOptions.message_set_wire_format', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='no_standard_descriptor_accessor', full_name='google.protobuf.MessageOptions.no_standard_descriptor_accessor', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.MessageOptions.uninterpreted_option', index=2, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + serialized_start=2701, + serialized_end=2885, +) + + +_FIELDOPTIONS = _descriptor.Descriptor( + name='FieldOptions', + full_name='google.protobuf.FieldOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='ctype', full_name='google.protobuf.FieldOptions.ctype', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='packed', full_name='google.protobuf.FieldOptions.packed', index=1, + number=2, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='lazy', full_name='google.protobuf.FieldOptions.lazy', index=2, + number=5, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='deprecated', full_name='google.protobuf.FieldOptions.deprecated', index=3, + number=3, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='experimental_map_key', full_name='google.protobuf.FieldOptions.experimental_map_key', index=4, + number=9, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='weak', full_name='google.protobuf.FieldOptions.weak', index=5, + number=10, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.FieldOptions.uninterpreted_option', index=6, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _FIELDOPTIONS_CTYPE, + ], + options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + serialized_start=2888, + serialized_end=3206, +) + + +_ENUMOPTIONS = _descriptor.Descriptor( + name='EnumOptions', + full_name='google.protobuf.EnumOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='allow_alias', full_name='google.protobuf.EnumOptions.allow_alias', index=0, + number=2, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.EnumOptions.uninterpreted_option', index=1, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + serialized_start=3208, + serialized_end=3328, +) + + +_ENUMVALUEOPTIONS = _descriptor.Descriptor( + name='EnumValueOptions', + full_name='google.protobuf.EnumValueOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.EnumValueOptions.uninterpreted_option', index=0, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + serialized_start=3330, + serialized_end=3428, +) + + +_SERVICEOPTIONS = _descriptor.Descriptor( + name='ServiceOptions', + full_name='google.protobuf.ServiceOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.ServiceOptions.uninterpreted_option', index=0, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + serialized_start=3430, + serialized_end=3526, +) + + +_METHODOPTIONS = _descriptor.Descriptor( + name='MethodOptions', + full_name='google.protobuf.MethodOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='uninterpreted_option', full_name='google.protobuf.MethodOptions.uninterpreted_option', index=0, + number=999, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + serialized_start=3528, + serialized_end=3623, +) + + +_UNINTERPRETEDOPTION_NAMEPART = _descriptor.Descriptor( + name='NamePart', + full_name='google.protobuf.UninterpretedOption.NamePart', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name_part', full_name='google.protobuf.UninterpretedOption.NamePart.name_part', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='is_extension', full_name='google.protobuf.UninterpretedOption.NamePart.is_extension', index=1, + number=2, type=8, cpp_type=7, label=2, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3861, + serialized_end=3912, +) + +_UNINTERPRETEDOPTION = _descriptor.Descriptor( + name='UninterpretedOption', + full_name='google.protobuf.UninterpretedOption', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.protobuf.UninterpretedOption.name', index=0, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='identifier_value', full_name='google.protobuf.UninterpretedOption.identifier_value', index=1, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='positive_int_value', full_name='google.protobuf.UninterpretedOption.positive_int_value', index=2, + number=4, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='negative_int_value', full_name='google.protobuf.UninterpretedOption.negative_int_value', index=3, + number=5, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='double_value', full_name='google.protobuf.UninterpretedOption.double_value', index=4, + number=6, type=1, cpp_type=5, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='string_value', full_name='google.protobuf.UninterpretedOption.string_value', index=5, + number=7, type=12, cpp_type=9, label=1, + has_default_value=False, default_value="", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='aggregate_value', full_name='google.protobuf.UninterpretedOption.aggregate_value', index=6, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_UNINTERPRETEDOPTION_NAMEPART, ], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3626, + serialized_end=3912, +) + + +_SOURCECODEINFO_LOCATION = _descriptor.Descriptor( + name='Location', + full_name='google.protobuf.SourceCodeInfo.Location', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='path', full_name='google.protobuf.SourceCodeInfo.Location.path', index=0, + number=1, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='span', full_name='google.protobuf.SourceCodeInfo.Location.span', index=1, + number=2, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='leading_comments', full_name='google.protobuf.SourceCodeInfo.Location.leading_comments', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='trailing_comments', full_name='google.protobuf.SourceCodeInfo.Location.trailing_comments', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3993, + serialized_end=4092, +) + +_SOURCECODEINFO = _descriptor.Descriptor( + name='SourceCodeInfo', + full_name='google.protobuf.SourceCodeInfo', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='location', full_name='google.protobuf.SourceCodeInfo.location', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_SOURCECODEINFO_LOCATION, ], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3915, + serialized_end=4092, +) + +_FILEDESCRIPTORSET.fields_by_name['file'].message_type = _FILEDESCRIPTORPROTO +_FILEDESCRIPTORPROTO.fields_by_name['message_type'].message_type = _DESCRIPTORPROTO +_FILEDESCRIPTORPROTO.fields_by_name['enum_type'].message_type = _ENUMDESCRIPTORPROTO +_FILEDESCRIPTORPROTO.fields_by_name['service'].message_type = _SERVICEDESCRIPTORPROTO +_FILEDESCRIPTORPROTO.fields_by_name['extension'].message_type = _FIELDDESCRIPTORPROTO +_FILEDESCRIPTORPROTO.fields_by_name['options'].message_type = _FILEOPTIONS +_FILEDESCRIPTORPROTO.fields_by_name['source_code_info'].message_type = _SOURCECODEINFO +_DESCRIPTORPROTO_EXTENSIONRANGE.containing_type = _DESCRIPTORPROTO; +_DESCRIPTORPROTO.fields_by_name['field'].message_type = _FIELDDESCRIPTORPROTO +_DESCRIPTORPROTO.fields_by_name['extension'].message_type = _FIELDDESCRIPTORPROTO +_DESCRIPTORPROTO.fields_by_name['nested_type'].message_type = _DESCRIPTORPROTO +_DESCRIPTORPROTO.fields_by_name['enum_type'].message_type = _ENUMDESCRIPTORPROTO +_DESCRIPTORPROTO.fields_by_name['extension_range'].message_type = _DESCRIPTORPROTO_EXTENSIONRANGE +_DESCRIPTORPROTO.fields_by_name['options'].message_type = _MESSAGEOPTIONS +_FIELDDESCRIPTORPROTO.fields_by_name['label'].enum_type = _FIELDDESCRIPTORPROTO_LABEL +_FIELDDESCRIPTORPROTO.fields_by_name['type'].enum_type = _FIELDDESCRIPTORPROTO_TYPE +_FIELDDESCRIPTORPROTO.fields_by_name['options'].message_type = _FIELDOPTIONS +_FIELDDESCRIPTORPROTO_TYPE.containing_type = _FIELDDESCRIPTORPROTO; +_FIELDDESCRIPTORPROTO_LABEL.containing_type = _FIELDDESCRIPTORPROTO; +_ENUMDESCRIPTORPROTO.fields_by_name['value'].message_type = _ENUMVALUEDESCRIPTORPROTO +_ENUMDESCRIPTORPROTO.fields_by_name['options'].message_type = _ENUMOPTIONS +_ENUMVALUEDESCRIPTORPROTO.fields_by_name['options'].message_type = _ENUMVALUEOPTIONS +_SERVICEDESCRIPTORPROTO.fields_by_name['method'].message_type = _METHODDESCRIPTORPROTO +_SERVICEDESCRIPTORPROTO.fields_by_name['options'].message_type = _SERVICEOPTIONS +_METHODDESCRIPTORPROTO.fields_by_name['options'].message_type = _METHODOPTIONS +_FILEOPTIONS.fields_by_name['optimize_for'].enum_type = _FILEOPTIONS_OPTIMIZEMODE +_FILEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION +_FILEOPTIONS_OPTIMIZEMODE.containing_type = _FILEOPTIONS; +_MESSAGEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION +_FIELDOPTIONS.fields_by_name['ctype'].enum_type = _FIELDOPTIONS_CTYPE +_FIELDOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION +_FIELDOPTIONS_CTYPE.containing_type = _FIELDOPTIONS; +_ENUMOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION +_ENUMVALUEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION +_SERVICEOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION +_METHODOPTIONS.fields_by_name['uninterpreted_option'].message_type = _UNINTERPRETEDOPTION +_UNINTERPRETEDOPTION_NAMEPART.containing_type = _UNINTERPRETEDOPTION; +_UNINTERPRETEDOPTION.fields_by_name['name'].message_type = _UNINTERPRETEDOPTION_NAMEPART +_SOURCECODEINFO_LOCATION.containing_type = _SOURCECODEINFO; +_SOURCECODEINFO.fields_by_name['location'].message_type = _SOURCECODEINFO_LOCATION +DESCRIPTOR.message_types_by_name['FileDescriptorSet'] = _FILEDESCRIPTORSET +DESCRIPTOR.message_types_by_name['FileDescriptorProto'] = _FILEDESCRIPTORPROTO +DESCRIPTOR.message_types_by_name['DescriptorProto'] = _DESCRIPTORPROTO +DESCRIPTOR.message_types_by_name['FieldDescriptorProto'] = _FIELDDESCRIPTORPROTO +DESCRIPTOR.message_types_by_name['EnumDescriptorProto'] = _ENUMDESCRIPTORPROTO +DESCRIPTOR.message_types_by_name['EnumValueDescriptorProto'] = _ENUMVALUEDESCRIPTORPROTO +DESCRIPTOR.message_types_by_name['ServiceDescriptorProto'] = _SERVICEDESCRIPTORPROTO +DESCRIPTOR.message_types_by_name['MethodDescriptorProto'] = _METHODDESCRIPTORPROTO +DESCRIPTOR.message_types_by_name['FileOptions'] = _FILEOPTIONS +DESCRIPTOR.message_types_by_name['MessageOptions'] = _MESSAGEOPTIONS +DESCRIPTOR.message_types_by_name['FieldOptions'] = _FIELDOPTIONS +DESCRIPTOR.message_types_by_name['EnumOptions'] = _ENUMOPTIONS +DESCRIPTOR.message_types_by_name['EnumValueOptions'] = _ENUMVALUEOPTIONS +DESCRIPTOR.message_types_by_name['ServiceOptions'] = _SERVICEOPTIONS +DESCRIPTOR.message_types_by_name['MethodOptions'] = _METHODOPTIONS +DESCRIPTOR.message_types_by_name['UninterpretedOption'] = _UNINTERPRETEDOPTION +DESCRIPTOR.message_types_by_name['SourceCodeInfo'] = _SOURCECODEINFO + +class FileDescriptorSet(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _FILEDESCRIPTORSET + + # @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorSet) + +class FileDescriptorProto(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _FILEDESCRIPTORPROTO + + # @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorProto) + +class DescriptorProto(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class ExtensionRange(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _DESCRIPTORPROTO_EXTENSIONRANGE + + # @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto.ExtensionRange) + DESCRIPTOR = _DESCRIPTORPROTO + + # @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto) + +class FieldDescriptorProto(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _FIELDDESCRIPTORPROTO + + # @@protoc_insertion_point(class_scope:google.protobuf.FieldDescriptorProto) + +class EnumDescriptorProto(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _ENUMDESCRIPTORPROTO + + # @@protoc_insertion_point(class_scope:google.protobuf.EnumDescriptorProto) + +class EnumValueDescriptorProto(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _ENUMVALUEDESCRIPTORPROTO + + # @@protoc_insertion_point(class_scope:google.protobuf.EnumValueDescriptorProto) + +class ServiceDescriptorProto(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _SERVICEDESCRIPTORPROTO + + # @@protoc_insertion_point(class_scope:google.protobuf.ServiceDescriptorProto) + +class MethodDescriptorProto(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _METHODDESCRIPTORPROTO + + # @@protoc_insertion_point(class_scope:google.protobuf.MethodDescriptorProto) + +class FileOptions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _FILEOPTIONS + + # @@protoc_insertion_point(class_scope:google.protobuf.FileOptions) + +class MessageOptions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _MESSAGEOPTIONS + + # @@protoc_insertion_point(class_scope:google.protobuf.MessageOptions) + +class FieldOptions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _FIELDOPTIONS + + # @@protoc_insertion_point(class_scope:google.protobuf.FieldOptions) + +class EnumOptions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _ENUMOPTIONS + + # @@protoc_insertion_point(class_scope:google.protobuf.EnumOptions) + +class EnumValueOptions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _ENUMVALUEOPTIONS + + # @@protoc_insertion_point(class_scope:google.protobuf.EnumValueOptions) + +class ServiceOptions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _SERVICEOPTIONS + + # @@protoc_insertion_point(class_scope:google.protobuf.ServiceOptions) + +class MethodOptions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _METHODOPTIONS + + # @@protoc_insertion_point(class_scope:google.protobuf.MethodOptions) + +class UninterpretedOption(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class NamePart(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _UNINTERPRETEDOPTION_NAMEPART + + # @@protoc_insertion_point(class_scope:google.protobuf.UninterpretedOption.NamePart) + DESCRIPTOR = _UNINTERPRETEDOPTION + + # @@protoc_insertion_point(class_scope:google.protobuf.UninterpretedOption) + +class SourceCodeInfo(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class Location(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _SOURCECODEINFO_LOCATION + + # @@protoc_insertion_point(class_scope:google.protobuf.SourceCodeInfo.Location) + DESCRIPTOR = _SOURCECODEINFO + + # @@protoc_insertion_point(class_scope:google.protobuf.SourceCodeInfo) + + +# @@protoc_insertion_point(module_scope) diff --git a/code/push/google/protobuf/descriptor_pool.py b/code/push/google/protobuf/descriptor_pool.py new file mode 100644 index 0000000..8f1f445 --- /dev/null +++ b/code/push/google/protobuf/descriptor_pool.py @@ -0,0 +1,527 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Provides DescriptorPool to use as a container for proto2 descriptors. + +The DescriptorPool is used in conjection with a DescriptorDatabase to maintain +a collection of protocol buffer descriptors for use when dynamically creating +message types at runtime. + +For most applications protocol buffers should be used via modules generated by +the protocol buffer compiler tool. This should only be used when the type of +protocol buffers used in an application or library cannot be predetermined. + +Below is a straightforward example on how to use this class: + + pool = DescriptorPool() + file_descriptor_protos = [ ... ] + for file_descriptor_proto in file_descriptor_protos: + pool.Add(file_descriptor_proto) + my_message_descriptor = pool.FindMessageTypeByName('some.package.MessageType') + +The message descriptor can be used in conjunction with the message_factory +module in order to create a protocol buffer class that can be encoded and +decoded. +""" + +__author__ = 'matthewtoia@google.com (Matt Toia)' + +from google.protobuf import descriptor_pb2 +from google.protobuf import descriptor +from google.protobuf import descriptor_database + + +class DescriptorPool(object): + """A collection of protobufs dynamically constructed by descriptor protos.""" + + def __init__(self, descriptor_db=None): + """Initializes a Pool of proto buffs. + + The descriptor_db argument to the constructor is provided to allow + specialized file descriptor proto lookup code to be triggered on demand. An + example would be an implementation which will read and compile a file + specified in a call to FindFileByName() and not require the call to Add() + at all. Results from this database will be cached internally here as well. + + Args: + descriptor_db: A secondary source of file descriptors. + """ + + self._internal_db = descriptor_database.DescriptorDatabase() + self._descriptor_db = descriptor_db + self._descriptors = {} + self._enum_descriptors = {} + self._file_descriptors = {} + + def Add(self, file_desc_proto): + """Adds the FileDescriptorProto and its types to this pool. + + Args: + file_desc_proto: The FileDescriptorProto to add. + """ + + self._internal_db.Add(file_desc_proto) + + def FindFileByName(self, file_name): + """Gets a FileDescriptor by file name. + + Args: + file_name: The path to the file to get a descriptor for. + + Returns: + A FileDescriptor for the named file. + + Raises: + KeyError: if the file can not be found in the pool. + """ + + try: + file_proto = self._internal_db.FindFileByName(file_name) + except KeyError as error: + if self._descriptor_db: + file_proto = self._descriptor_db.FindFileByName(file_name) + else: + raise error + if not file_proto: + raise KeyError('Cannot find a file named %s' % file_name) + return self._ConvertFileProtoToFileDescriptor(file_proto) + + def FindFileContainingSymbol(self, symbol): + """Gets the FileDescriptor for the file containing the specified symbol. + + Args: + symbol: The name of the symbol to search for. + + Returns: + A FileDescriptor that contains the specified symbol. + + Raises: + KeyError: if the file can not be found in the pool. + """ + + try: + file_proto = self._internal_db.FindFileContainingSymbol(symbol) + except KeyError as error: + if self._descriptor_db: + file_proto = self._descriptor_db.FindFileContainingSymbol(symbol) + else: + raise error + if not file_proto: + raise KeyError('Cannot find a file containing %s' % symbol) + return self._ConvertFileProtoToFileDescriptor(file_proto) + + def FindMessageTypeByName(self, full_name): + """Loads the named descriptor from the pool. + + Args: + full_name: The full name of the descriptor to load. + + Returns: + The descriptor for the named type. + """ + + full_name = full_name.lstrip('.') # fix inconsistent qualified name formats + if full_name not in self._descriptors: + self.FindFileContainingSymbol(full_name) + return self._descriptors[full_name] + + def FindEnumTypeByName(self, full_name): + """Loads the named enum descriptor from the pool. + + Args: + full_name: The full name of the enum descriptor to load. + + Returns: + The enum descriptor for the named type. + """ + + full_name = full_name.lstrip('.') # fix inconsistent qualified name formats + if full_name not in self._enum_descriptors: + self.FindFileContainingSymbol(full_name) + return self._enum_descriptors[full_name] + + def _ConvertFileProtoToFileDescriptor(self, file_proto): + """Creates a FileDescriptor from a proto or returns a cached copy. + + This method also has the side effect of loading all the symbols found in + the file into the appropriate dictionaries in the pool. + + Args: + file_proto: The proto to convert. + + Returns: + A FileDescriptor matching the passed in proto. + """ + + if file_proto.name not in self._file_descriptors: + file_descriptor = descriptor.FileDescriptor( + name=file_proto.name, + package=file_proto.package, + options=file_proto.options, + serialized_pb=file_proto.SerializeToString()) + scope = {} + dependencies = list(self._GetDeps(file_proto)) + + for dependency in dependencies: + dep_desc = self.FindFileByName(dependency.name) + dep_proto = descriptor_pb2.FileDescriptorProto.FromString( + dep_desc.serialized_pb) + package = '.' + dep_proto.package + package_prefix = package + '.' + + def _strip_package(symbol): + if symbol.startswith(package_prefix): + return symbol[len(package_prefix):] + return symbol + + symbols = list(self._ExtractSymbols(dep_proto.message_type, package)) + scope.update(symbols) + scope.update((_strip_package(k), v) for k, v in symbols) + + symbols = list(self._ExtractEnums(dep_proto.enum_type, package)) + scope.update(symbols) + scope.update((_strip_package(k), v) for k, v in symbols) + + for message_type in file_proto.message_type: + message_desc = self._ConvertMessageDescriptor( + message_type, file_proto.package, file_descriptor, scope) + file_descriptor.message_types_by_name[message_desc.name] = message_desc + for enum_type in file_proto.enum_type: + self._ConvertEnumDescriptor(enum_type, file_proto.package, + file_descriptor, None, scope) + for desc_proto in self._ExtractMessages(file_proto.message_type): + self._SetFieldTypes(desc_proto, scope) + + for desc_proto in file_proto.message_type: + desc = scope[desc_proto.name] + file_descriptor.message_types_by_name[desc_proto.name] = desc + self.Add(file_proto) + self._file_descriptors[file_proto.name] = file_descriptor + + return self._file_descriptors[file_proto.name] + + def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None, + scope=None): + """Adds the proto to the pool in the specified package. + + Args: + desc_proto: The descriptor_pb2.DescriptorProto protobuf message. + package: The package the proto should be located in. + file_desc: The file containing this message. + scope: Dict mapping short and full symbols to message and enum types. + + Returns: + The added descriptor. + """ + + if package: + desc_name = '.'.join((package, desc_proto.name)) + else: + desc_name = desc_proto.name + + if file_desc is None: + file_name = None + else: + file_name = file_desc.name + + if scope is None: + scope = {} + + nested = [ + self._ConvertMessageDescriptor(nested, desc_name, file_desc, scope) + for nested in desc_proto.nested_type] + enums = [ + self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, scope) + for enum in desc_proto.enum_type] + fields = [self._MakeFieldDescriptor(field, desc_name, index) + for index, field in enumerate(desc_proto.field)] + extensions = [self._MakeFieldDescriptor(extension, desc_name, True) + for index, extension in enumerate(desc_proto.extension)] + extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range] + if extension_ranges: + is_extendable = True + else: + is_extendable = False + desc = descriptor.Descriptor( + name=desc_proto.name, + full_name=desc_name, + filename=file_name, + containing_type=None, + fields=fields, + nested_types=nested, + enum_types=enums, + extensions=extensions, + options=desc_proto.options, + is_extendable=is_extendable, + extension_ranges=extension_ranges, + file=file_desc, + serialized_start=None, + serialized_end=None) + for nested in desc.nested_types: + nested.containing_type = desc + for enum in desc.enum_types: + enum.containing_type = desc + scope[desc_proto.name] = desc + scope['.' + desc_name] = desc + self._descriptors[desc_name] = desc + return desc + + def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None, + containing_type=None, scope=None): + """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf. + + Args: + enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message. + package: Optional package name for the new message EnumDescriptor. + file_desc: The file containing the enum descriptor. + containing_type: The type containing this enum. + scope: Scope containing available types. + + Returns: + The added descriptor + """ + + if package: + enum_name = '.'.join((package, enum_proto.name)) + else: + enum_name = enum_proto.name + + if file_desc is None: + file_name = None + else: + file_name = file_desc.name + + values = [self._MakeEnumValueDescriptor(value, index) + for index, value in enumerate(enum_proto.value)] + desc = descriptor.EnumDescriptor(name=enum_proto.name, + full_name=enum_name, + filename=file_name, + file=file_desc, + values=values, + containing_type=containing_type, + options=enum_proto.options) + scope[enum_proto.name] = desc + scope['.%s' % enum_name] = desc + self._enum_descriptors[enum_name] = desc + return desc + + def _MakeFieldDescriptor(self, field_proto, message_name, index, + is_extension=False): + """Creates a field descriptor from a FieldDescriptorProto. + + For message and enum type fields, this method will do a look up + in the pool for the appropriate descriptor for that type. If it + is unavailable, it will fall back to the _source function to + create it. If this type is still unavailable, construction will + fail. + + Args: + field_proto: The proto describing the field. + message_name: The name of the containing message. + index: Index of the field + is_extension: Indication that this field is for an extension. + + Returns: + An initialized FieldDescriptor object + """ + + if message_name: + full_name = '.'.join((message_name, field_proto.name)) + else: + full_name = field_proto.name + + return descriptor.FieldDescriptor( + name=field_proto.name, + full_name=full_name, + index=index, + number=field_proto.number, + type=field_proto.type, + cpp_type=None, + message_type=None, + enum_type=None, + containing_type=None, + label=field_proto.label, + has_default_value=False, + default_value=None, + is_extension=is_extension, + extension_scope=None, + options=field_proto.options) + + def _SetFieldTypes(self, desc_proto, scope): + """Sets the field's type, cpp_type, message_type and enum_type. + + Args: + desc_proto: The message descriptor to update. + scope: Enclosing scope of available types. + """ + + desc = scope[desc_proto.name] + for field_proto, field_desc in zip(desc_proto.field, desc.fields): + if field_proto.type_name: + type_name = field_proto.type_name + if type_name not in scope: + type_name = '.' + type_name + desc = scope[type_name] + else: + desc = None + + if not field_proto.HasField('type'): + if isinstance(desc, descriptor.Descriptor): + field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE + else: + field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM + + field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType( + field_proto.type) + + if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE + or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP): + field_desc.message_type = desc + + if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: + field_desc.enum_type = desc + + if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED: + field_desc.has_default = False + field_desc.default_value = [] + elif field_proto.HasField('default_value'): + field_desc.has_default = True + if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or + field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT): + field_desc.default_value = float(field_proto.default_value) + elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING: + field_desc.default_value = field_proto.default_value + elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL: + field_desc.default_value = field_proto.default_value.lower() == 'true' + elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: + field_desc.default_value = field_desc.enum_type.values_by_name[ + field_proto.default_value].index + else: + field_desc.default_value = int(field_proto.default_value) + else: + field_desc.has_default = False + field_desc.default_value = None + + field_desc.type = field_proto.type + + for nested_type in desc_proto.nested_type: + self._SetFieldTypes(nested_type, scope) + + def _MakeEnumValueDescriptor(self, value_proto, index): + """Creates a enum value descriptor object from a enum value proto. + + Args: + value_proto: The proto describing the enum value. + index: The index of the enum value. + + Returns: + An initialized EnumValueDescriptor object. + """ + + return descriptor.EnumValueDescriptor( + name=value_proto.name, + index=index, + number=value_proto.number, + options=value_proto.options, + type=None) + + def _ExtractSymbols(self, desc_protos, package): + """Pulls out all the symbols from descriptor protos. + + Args: + desc_protos: The protos to extract symbols from. + package: The package containing the descriptor type. + Yields: + A two element tuple of the type name and descriptor object. + """ + + for desc_proto in desc_protos: + if package: + message_name = '.'.join((package, desc_proto.name)) + else: + message_name = desc_proto.name + message_desc = self.FindMessageTypeByName(message_name) + yield (message_name, message_desc) + for symbol in self._ExtractSymbols(desc_proto.nested_type, message_name): + yield symbol + for symbol in self._ExtractEnums(desc_proto.enum_type, message_name): + yield symbol + + def _ExtractEnums(self, enum_protos, package): + """Pulls out all the symbols from enum protos. + + Args: + enum_protos: The protos to extract symbols from. + package: The package containing the enum type. + + Yields: + A two element tuple of the type name and enum descriptor object. + """ + + for enum_proto in enum_protos: + if package: + enum_name = '.'.join((package, enum_proto.name)) + else: + enum_name = enum_proto.name + enum_desc = self.FindEnumTypeByName(enum_name) + yield (enum_name, enum_desc) + + def _ExtractMessages(self, desc_protos): + """Pulls out all the message protos from descriptos. + + Args: + desc_protos: The protos to extract symbols from. + + Yields: + Descriptor protos. + """ + + for desc_proto in desc_protos: + yield desc_proto + for message in self._ExtractMessages(desc_proto.nested_type): + yield message + + def _GetDeps(self, file_proto): + """Recursively finds dependencies for file protos. + + Args: + file_proto: The proto to get dependencies from. + + Yields: + Each direct and indirect dependency. + """ + + for dependency in file_proto.dependency: + dep_desc = self.FindFileByName(dependency) + dep_proto = descriptor_pb2.FileDescriptorProto.FromString( + dep_desc.serialized_pb) + yield dep_proto + for parent_dep in self._GetDeps(dep_proto): + yield parent_dep diff --git a/code/push/google/protobuf/internal/__init__.py b/code/push/google/protobuf/internal/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/code/push/google/protobuf/internal/api_implementation.py b/code/push/google/protobuf/internal/api_implementation.py new file mode 100644 index 0000000..ce02a32 --- /dev/null +++ b/code/push/google/protobuf/internal/api_implementation.py @@ -0,0 +1,87 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +""" +This module is the central entity that determines which implementation of the +API is used. +""" + +__author__ = 'petar@google.com (Petar Petrov)' + +import os +# This environment variable can be used to switch to a certain implementation +# of the Python API. Right now only 'python' and 'cpp' are valid values. Any +# other value will be ignored. +_implementation_type = os.getenv('PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION', + 'python') + + +if _implementation_type != 'python': + # For now, by default use the pure-Python implementation. + # The code below checks if the C extension is available and + # uses it if it is available. + _implementation_type = 'cpp' + ## Determine automatically which implementation to use. + #try: + # from google.protobuf.internal import cpp_message + # _implementation_type = 'cpp' + #except ImportError, e: + # _implementation_type = 'python' + + +# This environment variable can be used to switch between the two +# 'cpp' implementations. Right now only 1 and 2 are valid values. Any +# other value will be ignored. +_implementation_version_str = os.getenv( + 'PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION_VERSION', + '1') + + +if _implementation_version_str not in ('1', '2'): + raise ValueError( + "unsupported PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION_VERSION: '" + + _implementation_version_str + "' (supported versions: 1, 2)" + ) + + +_implementation_version = int(_implementation_version_str) + + + +# Usage of this function is discouraged. Clients shouldn't care which +# implementation of the API is in use. Note that there is no guarantee +# that differences between APIs will be maintained. +# Please don't use this function if possible. +def Type(): + return _implementation_type + +# See comment on 'Type' above. +def Version(): + return _implementation_version diff --git a/code/push/google/protobuf/internal/containers.py b/code/push/google/protobuf/internal/containers.py new file mode 100644 index 0000000..34b35f8 --- /dev/null +++ b/code/push/google/protobuf/internal/containers.py @@ -0,0 +1,269 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Contains container classes to represent different protocol buffer types. + +This file defines container classes which represent categories of protocol +buffer field types which need extra maintenance. Currently these categories +are: + - Repeated scalar fields - These are all repeated fields which aren't + composite (e.g. they are of simple types like int32, string, etc). + - Repeated composite fields - Repeated fields which are composite. This + includes groups and nested messages. +""" + +__author__ = 'petar@google.com (Petar Petrov)' + + +class BaseContainer(object): + + """Base container class.""" + + # Minimizes memory usage and disallows assignment to other attributes. + __slots__ = ['_message_listener', '_values'] + + def __init__(self, message_listener): + """ + Args: + message_listener: A MessageListener implementation. + The RepeatedScalarFieldContainer will call this object's + Modified() method when it is modified. + """ + self._message_listener = message_listener + self._values = [] + + def __getitem__(self, key): + """Retrieves item by the specified key.""" + return self._values[key] + + def __len__(self): + """Returns the number of elements in the container.""" + return len(self._values) + + def __ne__(self, other): + """Checks if another instance isn't equal to this one.""" + # The concrete classes should define __eq__. + return not self == other + + def __hash__(self): + raise TypeError('unhashable object') + + def __repr__(self): + return repr(self._values) + + def sort(self, *args, **kwargs): + # Continue to support the old sort_function keyword argument. + # This is expected to be a rare occurrence, so use LBYL to avoid + # the overhead of actually catching KeyError. + if 'sort_function' in kwargs: + kwargs['cmp'] = kwargs.pop('sort_function') + self._values.sort(*args, **kwargs) + + +class RepeatedScalarFieldContainer(BaseContainer): + + """Simple, type-checked, list-like container for holding repeated scalars.""" + + # Disallows assignment to other attributes. + __slots__ = ['_type_checker'] + + def __init__(self, message_listener, type_checker): + """ + Args: + message_listener: A MessageListener implementation. + The RepeatedScalarFieldContainer will call this object's + Modified() method when it is modified. + type_checker: A type_checkers.ValueChecker instance to run on elements + inserted into this container. + """ + super(RepeatedScalarFieldContainer, self).__init__(message_listener) + self._type_checker = type_checker + + def append(self, value): + """Appends an item to the list. Similar to list.append().""" + self._type_checker.CheckValue(value) + self._values.append(value) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def insert(self, key, value): + """Inserts the item at the specified position. Similar to list.insert().""" + self._type_checker.CheckValue(value) + self._values.insert(key, value) + if not self._message_listener.dirty: + self._message_listener.Modified() + + def extend(self, elem_seq): + """Extends by appending the given sequence. Similar to list.extend().""" + if not elem_seq: + return + + new_values = [] + for elem in elem_seq: + self._type_checker.CheckValue(elem) + new_values.append(elem) + self._values.extend(new_values) + self._message_listener.Modified() + + def MergeFrom(self, other): + """Appends the contents of another repeated field of the same type to this + one. We do not check the types of the individual fields. + """ + self._values.extend(other._values) + self._message_listener.Modified() + + def remove(self, elem): + """Removes an item from the list. Similar to list.remove().""" + self._values.remove(elem) + self._message_listener.Modified() + + def __setitem__(self, key, value): + """Sets the item on the specified position.""" + self._type_checker.CheckValue(value) + self._values[key] = value + self._message_listener.Modified() + + def __getslice__(self, start, stop): + """Retrieves the subset of items from between the specified indices.""" + return self._values[start:stop] + + def __setslice__(self, start, stop, values): + """Sets the subset of items from between the specified indices.""" + new_values = [] + for value in values: + self._type_checker.CheckValue(value) + new_values.append(value) + self._values[start:stop] = new_values + self._message_listener.Modified() + + def __delitem__(self, key): + """Deletes the item at the specified position.""" + del self._values[key] + self._message_listener.Modified() + + def __delslice__(self, start, stop): + """Deletes the subset of items from between the specified indices.""" + del self._values[start:stop] + self._message_listener.Modified() + + def __eq__(self, other): + """Compares the current instance with another one.""" + if self is other: + return True + # Special case for the same type which should be common and fast. + if isinstance(other, self.__class__): + return other._values == self._values + # We are presumably comparing against some other sequence type. + return other == self._values + + +class RepeatedCompositeFieldContainer(BaseContainer): + + """Simple, list-like container for holding repeated composite fields.""" + + # Disallows assignment to other attributes. + __slots__ = ['_message_descriptor'] + + def __init__(self, message_listener, message_descriptor): + """ + Note that we pass in a descriptor instead of the generated directly, + since at the time we construct a _RepeatedCompositeFieldContainer we + haven't yet necessarily initialized the type that will be contained in the + container. + + Args: + message_listener: A MessageListener implementation. + The RepeatedCompositeFieldContainer will call this object's + Modified() method when it is modified. + message_descriptor: A Descriptor instance describing the protocol type + that should be present in this container. We'll use the + _concrete_class field of this descriptor when the client calls add(). + """ + super(RepeatedCompositeFieldContainer, self).__init__(message_listener) + self._message_descriptor = message_descriptor + + def add(self, **kwargs): + """Adds a new element at the end of the list and returns it. Keyword + arguments may be used to initialize the element. + """ + new_element = self._message_descriptor._concrete_class(**kwargs) + new_element._SetListener(self._message_listener) + self._values.append(new_element) + if not self._message_listener.dirty: + self._message_listener.Modified() + return new_element + + def extend(self, elem_seq): + """Extends by appending the given sequence of elements of the same type + as this one, copying each individual message. + """ + message_class = self._message_descriptor._concrete_class + listener = self._message_listener + values = self._values + for message in elem_seq: + new_element = message_class() + new_element._SetListener(listener) + new_element.MergeFrom(message) + values.append(new_element) + listener.Modified() + + def MergeFrom(self, other): + """Appends the contents of another repeated field of the same type to this + one, copying each individual message. + """ + self.extend(other._values) + + def remove(self, elem): + """Removes an item from the list. Similar to list.remove().""" + self._values.remove(elem) + self._message_listener.Modified() + + def __getslice__(self, start, stop): + """Retrieves the subset of items from between the specified indices.""" + return self._values[start:stop] + + def __delitem__(self, key): + """Deletes the item at the specified position.""" + del self._values[key] + self._message_listener.Modified() + + def __delslice__(self, start, stop): + """Deletes the subset of items from between the specified indices.""" + del self._values[start:stop] + self._message_listener.Modified() + + def __eq__(self, other): + """Compares the current instance with another one.""" + if self is other: + return True + if not isinstance(other, self.__class__): + raise TypeError('Can only compare repeated composite fields against ' + 'other repeated composite fields.') + return self._values == other._values diff --git a/code/push/google/protobuf/internal/cpp_message.py b/code/push/google/protobuf/internal/cpp_message.py new file mode 100644 index 0000000..23ab9ba --- /dev/null +++ b/code/push/google/protobuf/internal/cpp_message.py @@ -0,0 +1,663 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Contains helper functions used to create protocol message classes from +Descriptor objects at runtime backed by the protocol buffer C++ API. +""" + +__author__ = 'petar@google.com (Petar Petrov)' + +import copy_reg +import operator +from google.protobuf.internal import _net_proto2___python +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import message + + +_LABEL_REPEATED = _net_proto2___python.LABEL_REPEATED +_LABEL_OPTIONAL = _net_proto2___python.LABEL_OPTIONAL +_CPPTYPE_MESSAGE = _net_proto2___python.CPPTYPE_MESSAGE +_TYPE_MESSAGE = _net_proto2___python.TYPE_MESSAGE + + +def GetDescriptorPool(): + """Creates a new DescriptorPool C++ object.""" + return _net_proto2___python.NewCDescriptorPool() + + +_pool = GetDescriptorPool() + + +def GetFieldDescriptor(full_field_name): + """Searches for a field descriptor given a full field name.""" + return _pool.FindFieldByName(full_field_name) + + +def BuildFile(content): + """Registers a new proto file in the underlying C++ descriptor pool.""" + _net_proto2___python.BuildFile(content) + + +def GetExtensionDescriptor(full_extension_name): + """Searches for extension descriptor given a full field name.""" + return _pool.FindExtensionByName(full_extension_name) + + +def NewCMessage(full_message_name): + """Creates a new C++ protocol message by its name.""" + return _net_proto2___python.NewCMessage(full_message_name) + + +def ScalarProperty(cdescriptor): + """Returns a scalar property for the given descriptor.""" + + def Getter(self): + return self._cmsg.GetScalar(cdescriptor) + + def Setter(self, value): + self._cmsg.SetScalar(cdescriptor, value) + + return property(Getter, Setter) + + +def CompositeProperty(cdescriptor, message_type): + """Returns a Python property the given composite field.""" + + def Getter(self): + sub_message = self._composite_fields.get(cdescriptor.name, None) + if sub_message is None: + cmessage = self._cmsg.NewSubMessage(cdescriptor) + sub_message = message_type._concrete_class(__cmessage=cmessage) + self._composite_fields[cdescriptor.name] = sub_message + return sub_message + + return property(Getter) + + +class RepeatedScalarContainer(object): + """Container for repeated scalar fields.""" + + __slots__ = ['_message', '_cfield_descriptor', '_cmsg'] + + def __init__(self, msg, cfield_descriptor): + self._message = msg + self._cmsg = msg._cmsg + self._cfield_descriptor = cfield_descriptor + + def append(self, value): + self._cmsg.AddRepeatedScalar( + self._cfield_descriptor, value) + + def extend(self, sequence): + for element in sequence: + self.append(element) + + def insert(self, key, value): + values = self[slice(None, None, None)] + values.insert(key, value) + self._cmsg.AssignRepeatedScalar(self._cfield_descriptor, values) + + def remove(self, value): + values = self[slice(None, None, None)] + values.remove(value) + self._cmsg.AssignRepeatedScalar(self._cfield_descriptor, values) + + def __setitem__(self, key, value): + values = self[slice(None, None, None)] + values[key] = value + self._cmsg.AssignRepeatedScalar(self._cfield_descriptor, values) + + def __getitem__(self, key): + return self._cmsg.GetRepeatedScalar(self._cfield_descriptor, key) + + def __delitem__(self, key): + self._cmsg.DeleteRepeatedField(self._cfield_descriptor, key) + + def __len__(self): + return len(self[slice(None, None, None)]) + + def __eq__(self, other): + if self is other: + return True + if not operator.isSequenceType(other): + raise TypeError( + 'Can only compare repeated scalar fields against sequences.') + # We are presumably comparing against some other sequence type. + return other == self[slice(None, None, None)] + + def __ne__(self, other): + return not self == other + + def __hash__(self): + raise TypeError('unhashable object') + + def sort(self, *args, **kwargs): + # Maintain compatibility with the previous interface. + if 'sort_function' in kwargs: + kwargs['cmp'] = kwargs.pop('sort_function') + self._cmsg.AssignRepeatedScalar(self._cfield_descriptor, + sorted(self, *args, **kwargs)) + + +def RepeatedScalarProperty(cdescriptor): + """Returns a Python property the given repeated scalar field.""" + + def Getter(self): + container = self._composite_fields.get(cdescriptor.name, None) + if container is None: + container = RepeatedScalarContainer(self, cdescriptor) + self._composite_fields[cdescriptor.name] = container + return container + + def Setter(self, new_value): + raise AttributeError('Assignment not allowed to repeated field ' + '"%s" in protocol message object.' % cdescriptor.name) + + doc = 'Magic attribute generated for "%s" proto field.' % cdescriptor.name + return property(Getter, Setter, doc=doc) + + +class RepeatedCompositeContainer(object): + """Container for repeated composite fields.""" + + __slots__ = ['_message', '_subclass', '_cfield_descriptor', '_cmsg'] + + def __init__(self, msg, cfield_descriptor, subclass): + self._message = msg + self._cmsg = msg._cmsg + self._subclass = subclass + self._cfield_descriptor = cfield_descriptor + + def add(self, **kwargs): + cmessage = self._cmsg.AddMessage(self._cfield_descriptor) + return self._subclass(__cmessage=cmessage, __owner=self._message, **kwargs) + + def extend(self, elem_seq): + """Extends by appending the given sequence of elements of the same type + as this one, copying each individual message. + """ + for message in elem_seq: + self.add().MergeFrom(message) + + def remove(self, value): + # TODO(protocol-devel): This is inefficient as it needs to generate a + # message pointer for each message only to do index(). Move this to a C++ + # extension function. + self.__delitem__(self[slice(None, None, None)].index(value)) + + def MergeFrom(self, other): + for message in other[:]: + self.add().MergeFrom(message) + + def __getitem__(self, key): + cmessages = self._cmsg.GetRepeatedMessage( + self._cfield_descriptor, key) + subclass = self._subclass + if not isinstance(cmessages, list): + return subclass(__cmessage=cmessages, __owner=self._message) + + return [subclass(__cmessage=m, __owner=self._message) for m in cmessages] + + def __delitem__(self, key): + self._cmsg.DeleteRepeatedField( + self._cfield_descriptor, key) + + def __len__(self): + return self._cmsg.FieldLength(self._cfield_descriptor) + + def __eq__(self, other): + """Compares the current instance with another one.""" + if self is other: + return True + if not isinstance(other, self.__class__): + raise TypeError('Can only compare repeated composite fields against ' + 'other repeated composite fields.') + messages = self[slice(None, None, None)] + other_messages = other[slice(None, None, None)] + return messages == other_messages + + def __hash__(self): + raise TypeError('unhashable object') + + def sort(self, cmp=None, key=None, reverse=False, **kwargs): + # Maintain compatibility with the old interface. + if cmp is None and 'sort_function' in kwargs: + cmp = kwargs.pop('sort_function') + + # The cmp function, if provided, is passed the results of the key function, + # so we only need to wrap one of them. + if key is None: + index_key = self.__getitem__ + else: + index_key = lambda i: key(self[i]) + + # Sort the list of current indexes by the underlying object. + indexes = range(len(self)) + indexes.sort(cmp=cmp, key=index_key, reverse=reverse) + + # Apply the transposition. + for dest, src in enumerate(indexes): + if dest == src: + continue + self._cmsg.SwapRepeatedFieldElements(self._cfield_descriptor, dest, src) + # Don't swap the same value twice. + indexes[src] = src + + +def RepeatedCompositeProperty(cdescriptor, message_type): + """Returns a Python property for the given repeated composite field.""" + + def Getter(self): + container = self._composite_fields.get(cdescriptor.name, None) + if container is None: + container = RepeatedCompositeContainer( + self, cdescriptor, message_type._concrete_class) + self._composite_fields[cdescriptor.name] = container + return container + + def Setter(self, new_value): + raise AttributeError('Assignment not allowed to repeated field ' + '"%s" in protocol message object.' % cdescriptor.name) + + doc = 'Magic attribute generated for "%s" proto field.' % cdescriptor.name + return property(Getter, Setter, doc=doc) + + +class ExtensionDict(object): + """Extension dictionary added to each protocol message.""" + + def __init__(self, msg): + self._message = msg + self._cmsg = msg._cmsg + self._values = {} + + def __setitem__(self, extension, value): + from google.protobuf import descriptor + if not isinstance(extension, descriptor.FieldDescriptor): + raise KeyError('Bad extension %r.' % (extension,)) + cdescriptor = extension._cdescriptor + if (cdescriptor.label != _LABEL_OPTIONAL or + cdescriptor.cpp_type == _CPPTYPE_MESSAGE): + raise TypeError('Extension %r is repeated and/or a composite type.' % ( + extension.full_name,)) + self._cmsg.SetScalar(cdescriptor, value) + self._values[extension] = value + + def __getitem__(self, extension): + from google.protobuf import descriptor + if not isinstance(extension, descriptor.FieldDescriptor): + raise KeyError('Bad extension %r.' % (extension,)) + + cdescriptor = extension._cdescriptor + if (cdescriptor.label != _LABEL_REPEATED and + cdescriptor.cpp_type != _CPPTYPE_MESSAGE): + return self._cmsg.GetScalar(cdescriptor) + + ext = self._values.get(extension, None) + if ext is not None: + return ext + + ext = self._CreateNewHandle(extension) + self._values[extension] = ext + return ext + + def ClearExtension(self, extension): + from google.protobuf import descriptor + if not isinstance(extension, descriptor.FieldDescriptor): + raise KeyError('Bad extension %r.' % (extension,)) + self._cmsg.ClearFieldByDescriptor(extension._cdescriptor) + if extension in self._values: + del self._values[extension] + + def HasExtension(self, extension): + from google.protobuf import descriptor + if not isinstance(extension, descriptor.FieldDescriptor): + raise KeyError('Bad extension %r.' % (extension,)) + return self._cmsg.HasFieldByDescriptor(extension._cdescriptor) + + def _FindExtensionByName(self, name): + """Tries to find a known extension with the specified name. + + Args: + name: Extension full name. + + Returns: + Extension field descriptor. + """ + return self._message._extensions_by_name.get(name, None) + + def _CreateNewHandle(self, extension): + cdescriptor = extension._cdescriptor + if (cdescriptor.label != _LABEL_REPEATED and + cdescriptor.cpp_type == _CPPTYPE_MESSAGE): + cmessage = self._cmsg.NewSubMessage(cdescriptor) + return extension.message_type._concrete_class(__cmessage=cmessage) + + if cdescriptor.label == _LABEL_REPEATED: + if cdescriptor.cpp_type == _CPPTYPE_MESSAGE: + return RepeatedCompositeContainer( + self._message, cdescriptor, extension.message_type._concrete_class) + else: + return RepeatedScalarContainer(self._message, cdescriptor) + # This shouldn't happen! + assert False + return None + + +def NewMessage(bases, message_descriptor, dictionary): + """Creates a new protocol message *class*.""" + _AddClassAttributesForNestedExtensions(message_descriptor, dictionary) + _AddEnumValues(message_descriptor, dictionary) + _AddDescriptors(message_descriptor, dictionary) + return bases + + +def InitMessage(message_descriptor, cls): + """Constructs a new message instance (called before instance's __init__).""" + cls._extensions_by_name = {} + _AddInitMethod(message_descriptor, cls) + _AddMessageMethods(message_descriptor, cls) + _AddPropertiesForExtensions(message_descriptor, cls) + copy_reg.pickle(cls, lambda obj: (cls, (), obj.__getstate__())) + + +def _AddDescriptors(message_descriptor, dictionary): + """Sets up a new protocol message class dictionary. + + Args: + message_descriptor: A Descriptor instance describing this message type. + dictionary: Class dictionary to which we'll add a '__slots__' entry. + """ + dictionary['__descriptors'] = {} + for field in message_descriptor.fields: + dictionary['__descriptors'][field.name] = GetFieldDescriptor( + field.full_name) + + dictionary['__slots__'] = list(dictionary['__descriptors'].iterkeys()) + [ + '_cmsg', '_owner', '_composite_fields', 'Extensions', '_HACK_REFCOUNTS'] + + +def _AddEnumValues(message_descriptor, dictionary): + """Sets class-level attributes for all enum fields defined in this message. + + Args: + message_descriptor: Descriptor object for this message type. + dictionary: Class dictionary that should be populated. + """ + for enum_type in message_descriptor.enum_types: + dictionary[enum_type.name] = enum_type_wrapper.EnumTypeWrapper(enum_type) + for enum_value in enum_type.values: + dictionary[enum_value.name] = enum_value.number + + +def _AddClassAttributesForNestedExtensions(message_descriptor, dictionary): + """Adds class attributes for the nested extensions.""" + extension_dict = message_descriptor.extensions_by_name + for extension_name, extension_field in extension_dict.iteritems(): + assert extension_name not in dictionary + dictionary[extension_name] = extension_field + + +def _AddInitMethod(message_descriptor, cls): + """Adds an __init__ method to cls.""" + + # Create and attach message field properties to the message class. + # This can be done just once per message class, since property setters and + # getters are passed the message instance. + # This makes message instantiation extremely fast, and at the same time it + # doesn't require the creation of property objects for each message instance, + # which saves a lot of memory. + for field in message_descriptor.fields: + field_cdescriptor = cls.__descriptors[field.name] + if field.label == _LABEL_REPEATED: + if field.cpp_type == _CPPTYPE_MESSAGE: + value = RepeatedCompositeProperty(field_cdescriptor, field.message_type) + else: + value = RepeatedScalarProperty(field_cdescriptor) + elif field.cpp_type == _CPPTYPE_MESSAGE: + value = CompositeProperty(field_cdescriptor, field.message_type) + else: + value = ScalarProperty(field_cdescriptor) + setattr(cls, field.name, value) + + # Attach a constant with the field number. + constant_name = field.name.upper() + '_FIELD_NUMBER' + setattr(cls, constant_name, field.number) + + def Init(self, **kwargs): + """Message constructor.""" + cmessage = kwargs.pop('__cmessage', None) + if cmessage: + self._cmsg = cmessage + else: + self._cmsg = NewCMessage(message_descriptor.full_name) + + # Keep a reference to the owner, as the owner keeps a reference to the + # underlying protocol buffer message. + owner = kwargs.pop('__owner', None) + if owner: + self._owner = owner + + if message_descriptor.is_extendable: + self.Extensions = ExtensionDict(self) + else: + # Reference counting in the C++ code is broken and depends on + # the Extensions reference to keep this object alive during unit + # tests (see b/4856052). Remove this once b/4945904 is fixed. + self._HACK_REFCOUNTS = self + self._composite_fields = {} + + for field_name, field_value in kwargs.iteritems(): + field_cdescriptor = self.__descriptors.get(field_name, None) + if not field_cdescriptor: + raise ValueError('Protocol message has no "%s" field.' % field_name) + if field_cdescriptor.label == _LABEL_REPEATED: + if field_cdescriptor.cpp_type == _CPPTYPE_MESSAGE: + field_name = getattr(self, field_name) + for val in field_value: + field_name.add().MergeFrom(val) + else: + getattr(self, field_name).extend(field_value) + elif field_cdescriptor.cpp_type == _CPPTYPE_MESSAGE: + getattr(self, field_name).MergeFrom(field_value) + else: + setattr(self, field_name, field_value) + + Init.__module__ = None + Init.__doc__ = None + cls.__init__ = Init + + +def _IsMessageSetExtension(field): + """Checks if a field is a message set extension.""" + return (field.is_extension and + field.containing_type.has_options and + field.containing_type.GetOptions().message_set_wire_format and + field.type == _TYPE_MESSAGE and + field.message_type == field.extension_scope and + field.label == _LABEL_OPTIONAL) + + +def _AddMessageMethods(message_descriptor, cls): + """Adds the methods to a protocol message class.""" + if message_descriptor.is_extendable: + + def ClearExtension(self, extension): + self.Extensions.ClearExtension(extension) + + def HasExtension(self, extension): + return self.Extensions.HasExtension(extension) + + def HasField(self, field_name): + return self._cmsg.HasField(field_name) + + def ClearField(self, field_name): + child_cmessage = None + if field_name in self._composite_fields: + child_field = self._composite_fields[field_name] + del self._composite_fields[field_name] + + child_cdescriptor = self.__descriptors[field_name] + # TODO(anuraag): Support clearing repeated message fields as well. + if (child_cdescriptor.label != _LABEL_REPEATED and + child_cdescriptor.cpp_type == _CPPTYPE_MESSAGE): + child_field._owner = None + child_cmessage = child_field._cmsg + + if child_cmessage is not None: + self._cmsg.ClearField(field_name, child_cmessage) + else: + self._cmsg.ClearField(field_name) + + def Clear(self): + cmessages_to_release = [] + for field_name, child_field in self._composite_fields.iteritems(): + child_cdescriptor = self.__descriptors[field_name] + # TODO(anuraag): Support clearing repeated message fields as well. + if (child_cdescriptor.label != _LABEL_REPEATED and + child_cdescriptor.cpp_type == _CPPTYPE_MESSAGE): + child_field._owner = None + cmessages_to_release.append((child_cdescriptor, child_field._cmsg)) + self._composite_fields.clear() + self._cmsg.Clear(cmessages_to_release) + + def IsInitialized(self, errors=None): + if self._cmsg.IsInitialized(): + return True + if errors is not None: + errors.extend(self.FindInitializationErrors()); + return False + + def SerializeToString(self): + if not self.IsInitialized(): + raise message.EncodeError( + 'Message %s is missing required fields: %s' % ( + self._cmsg.full_name, ','.join(self.FindInitializationErrors()))) + return self._cmsg.SerializeToString() + + def SerializePartialToString(self): + return self._cmsg.SerializePartialToString() + + def ParseFromString(self, serialized): + self.Clear() + self.MergeFromString(serialized) + + def MergeFromString(self, serialized): + byte_size = self._cmsg.MergeFromString(serialized) + if byte_size < 0: + raise message.DecodeError('Unable to merge from string.') + return byte_size + + def MergeFrom(self, msg): + if not isinstance(msg, cls): + raise TypeError( + "Parameter to MergeFrom() must be instance of same class: " + "expected %s got %s." % (cls.__name__, type(msg).__name__)) + self._cmsg.MergeFrom(msg._cmsg) + + def CopyFrom(self, msg): + self._cmsg.CopyFrom(msg._cmsg) + + def ByteSize(self): + return self._cmsg.ByteSize() + + def SetInParent(self): + return self._cmsg.SetInParent() + + def ListFields(self): + all_fields = [] + field_list = self._cmsg.ListFields() + fields_by_name = cls.DESCRIPTOR.fields_by_name + for is_extension, field_name in field_list: + if is_extension: + extension = cls._extensions_by_name[field_name] + all_fields.append((extension, self.Extensions[extension])) + else: + field_descriptor = fields_by_name[field_name] + all_fields.append( + (field_descriptor, getattr(self, field_name))) + all_fields.sort(key=lambda item: item[0].number) + return all_fields + + def FindInitializationErrors(self): + return self._cmsg.FindInitializationErrors() + + def __str__(self): + return self._cmsg.DebugString() + + def __eq__(self, other): + if self is other: + return True + if not isinstance(other, self.__class__): + return False + return self.ListFields() == other.ListFields() + + def __ne__(self, other): + return not self == other + + def __hash__(self): + raise TypeError('unhashable object') + + def __unicode__(self): + # Lazy import to prevent circular import when text_format imports this file. + from google.protobuf import text_format + return text_format.MessageToString(self, as_utf8=True).decode('utf-8') + + # Attach the local methods to the message class. + for key, value in locals().copy().iteritems(): + if key not in ('key', 'value', '__builtins__', '__name__', '__doc__'): + setattr(cls, key, value) + + # Static methods: + + def RegisterExtension(extension_handle): + extension_handle.containing_type = cls.DESCRIPTOR + cls._extensions_by_name[extension_handle.full_name] = extension_handle + + if _IsMessageSetExtension(extension_handle): + # MessageSet extension. Also register under type name. + cls._extensions_by_name[ + extension_handle.message_type.full_name] = extension_handle + cls.RegisterExtension = staticmethod(RegisterExtension) + + def FromString(string): + msg = cls() + msg.MergeFromString(string) + return msg + cls.FromString = staticmethod(FromString) + + + +def _AddPropertiesForExtensions(message_descriptor, cls): + """Adds properties for all fields in this protocol message type.""" + extension_dict = message_descriptor.extensions_by_name + for extension_name, extension_field in extension_dict.iteritems(): + constant_name = extension_name.upper() + '_FIELD_NUMBER' + setattr(cls, constant_name, extension_field.number) diff --git a/code/push/google/protobuf/internal/decoder.py b/code/push/google/protobuf/internal/decoder.py new file mode 100644 index 0000000..9ad5a29 --- /dev/null +++ b/code/push/google/protobuf/internal/decoder.py @@ -0,0 +1,720 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Code for decoding protocol buffer primitives. + +This code is very similar to encoder.py -- read the docs for that module first. + +A "decoder" is a function with the signature: + Decode(buffer, pos, end, message, field_dict) +The arguments are: + buffer: The string containing the encoded message. + pos: The current position in the string. + end: The position in the string where the current message ends. May be + less than len(buffer) if we're reading a sub-message. + message: The message object into which we're parsing. + field_dict: message._fields (avoids a hashtable lookup). +The decoder reads the field and stores it into field_dict, returning the new +buffer position. A decoder for a repeated field may proactively decode all of +the elements of that field, if they appear consecutively. + +Note that decoders may throw any of the following: + IndexError: Indicates a truncated message. + struct.error: Unpacking of a fixed-width field failed. + message.DecodeError: Other errors. + +Decoders are expected to raise an exception if they are called with pos > end. +This allows callers to be lax about bounds checking: it's fineto read past +"end" as long as you are sure that someone else will notice and throw an +exception later on. + +Something up the call stack is expected to catch IndexError and struct.error +and convert them to message.DecodeError. + +Decoders are constructed using decoder constructors with the signature: + MakeDecoder(field_number, is_repeated, is_packed, key, new_default) +The arguments are: + field_number: The field number of the field we want to decode. + is_repeated: Is the field a repeated field? (bool) + is_packed: Is the field a packed field? (bool) + key: The key to use when looking up the field within field_dict. + (This is actually the FieldDescriptor but nothing in this + file should depend on that.) + new_default: A function which takes a message object as a parameter and + returns a new instance of the default value for this field. + (This is called for repeated fields and sub-messages, when an + instance does not already exist.) + +As with encoders, we define a decoder constructor for every type of field. +Then, for every field of every message class we construct an actual decoder. +That decoder goes into a dict indexed by tag, so when we decode a message +we repeatedly read a tag, look up the corresponding decoder, and invoke it. +""" + +__author__ = 'kenton@google.com (Kenton Varda)' + +import struct +from push.google.protobuf.internal import encoder +from push.google.protobuf.internal import wire_format +from push.google.protobuf import message + + +# This will overflow and thus become IEEE-754 "infinity". We would use +# "float('inf')" but it doesn't work on Windows pre-Python-2.6. +_POS_INF = 1e10000 +_NEG_INF = -_POS_INF +_NAN = _POS_INF * 0 + + +# This is not for optimization, but rather to avoid conflicts with local +# variables named "message". +_DecodeError = message.DecodeError + + +def _VarintDecoder(mask): + """Return an encoder for a basic varint value (does not include tag). + + Decoded values will be bitwise-anded with the given mask before being + returned, e.g. to limit them to 32 bits. The returned decoder does not + take the usual "end" parameter -- the caller is expected to do bounds checking + after the fact (often the caller can defer such checking until later). The + decoder returns a (value, new_pos) pair. + """ + + local_ord = ord + def DecodeVarint(buffer, pos): + result = 0 + shift = 0 + while 1: + b = local_ord(buffer[pos]) + result |= ((b & 0x7f) << shift) + pos += 1 + if not (b & 0x80): + result &= mask + return (result, pos) + shift += 7 + if shift >= 64: + raise _DecodeError('Too many bytes when decoding varint.') + return DecodeVarint + + +def _SignedVarintDecoder(mask): + """Like _VarintDecoder() but decodes signed values.""" + + local_ord = ord + def DecodeVarint(buffer, pos): + result = 0 + shift = 0 + while 1: + b = local_ord(buffer[pos]) + result |= ((b & 0x7f) << shift) + pos += 1 + if not (b & 0x80): + if result > 0x7fffffffffffffff: + result -= (1 << 64) + result |= ~mask + else: + result &= mask + return (result, pos) + shift += 7 + if shift >= 64: + raise _DecodeError('Too many bytes when decoding varint.') + return DecodeVarint + + +_DecodeVarint = _VarintDecoder((1 << 64) - 1) +_DecodeSignedVarint = _SignedVarintDecoder((1 << 64) - 1) + +# Use these versions for values which must be limited to 32 bits. +_DecodeVarint32 = _VarintDecoder((1 << 32) - 1) +_DecodeSignedVarint32 = _SignedVarintDecoder((1 << 32) - 1) + + +def ReadTag(buffer, pos): + """Read a tag from the buffer, and return a (tag_bytes, new_pos) tuple. + + We return the raw bytes of the tag rather than decoding them. The raw + bytes can then be used to look up the proper decoder. This effectively allows + us to trade some work that would be done in pure-python (decoding a varint) + for work that is done in C (searching for a byte string in a hash table). + In a low-level language it would be much cheaper to decode the varint and + use that, but not in Python. + """ + + start = pos + while ord(buffer[pos]) & 0x80: + pos += 1 + pos += 1 + return (buffer[start:pos], pos) + + +# -------------------------------------------------------------------- + + +def _SimpleDecoder(wire_type, decode_value): + """Return a constructor for a decoder for fields of a particular type. + + Args: + wire_type: The field's wire type. + decode_value: A function which decodes an individual value, e.g. + _DecodeVarint() + """ + + def SpecificDecoder(field_number, is_repeated, is_packed, key, new_default): + if is_packed: + local_DecodeVarint = _DecodeVarint + def DecodePackedField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + (endpoint, pos) = local_DecodeVarint(buffer, pos) + endpoint += pos + if endpoint > end: + raise _DecodeError('Truncated message.') + while pos < endpoint: + (element, pos) = decode_value(buffer, pos) + value.append(element) + if pos > endpoint: + del value[-1] # Discard corrupt value. + raise _DecodeError('Packed element was truncated.') + return pos + return DecodePackedField + elif is_repeated: + tag_bytes = encoder.TagBytes(field_number, wire_type) + tag_len = len(tag_bytes) + def DecodeRepeatedField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + (element, new_pos) = decode_value(buffer, pos) + value.append(element) + # Predict that the next tag is another copy of the same repeated + # field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos >= end: + # Prediction failed. Return. + if new_pos > end: + raise _DecodeError('Truncated message.') + return new_pos + return DecodeRepeatedField + else: + def DecodeField(buffer, pos, end, message, field_dict): + (field_dict[key], pos) = decode_value(buffer, pos) + if pos > end: + del field_dict[key] # Discard corrupt value. + raise _DecodeError('Truncated message.') + return pos + return DecodeField + + return SpecificDecoder + + +def _ModifiedDecoder(wire_type, decode_value, modify_value): + """Like SimpleDecoder but additionally invokes modify_value on every value + before storing it. Usually modify_value is ZigZagDecode. + """ + + # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but + # not enough to make a significant difference. + + def InnerDecode(buffer, pos): + (result, new_pos) = decode_value(buffer, pos) + return (modify_value(result), new_pos) + return _SimpleDecoder(wire_type, InnerDecode) + + +def _StructPackDecoder(wire_type, format): + """Return a constructor for a decoder for a fixed-width field. + + Args: + wire_type: The field's wire type. + format: The format string to pass to struct.unpack(). + """ + + value_size = struct.calcsize(format) + local_unpack = struct.unpack + + # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but + # not enough to make a significant difference. + + # Note that we expect someone up-stack to catch struct.error and convert + # it to _DecodeError -- this way we don't have to set up exception- + # handling blocks every time we parse one value. + + def InnerDecode(buffer, pos): + new_pos = pos + value_size + result = local_unpack(format, buffer[pos:new_pos])[0] + return (result, new_pos) + return _SimpleDecoder(wire_type, InnerDecode) + + +def _FloatDecoder(): + """Returns a decoder for a float field. + + This code works around a bug in struct.unpack for non-finite 32-bit + floating-point values. + """ + + local_unpack = struct.unpack + + def InnerDecode(buffer, pos): + # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign + # bit, bits 2-9 represent the exponent, and bits 10-32 are the significand. + new_pos = pos + 4 + float_bytes = buffer[pos:new_pos] + + # If this value has all its exponent bits set, then it's non-finite. + # In Python 2.4, struct.unpack will convert it to a finite 64-bit value. + # To avoid that, we parse it specially. + if ((float_bytes[3] in '\x7F\xFF') + and (float_bytes[2] >= '\x80')): + # If at least one significand bit is set... + if float_bytes[0:3] != '\x00\x00\x80': + return (_NAN, new_pos) + # If sign bit is set... + if float_bytes[3] == '\xFF': + return (_NEG_INF, new_pos) + return (_POS_INF, new_pos) + + # Note that we expect someone up-stack to catch struct.error and convert + # it to _DecodeError -- this way we don't have to set up exception- + # handling blocks every time we parse one value. + result = local_unpack('= '\xF0') + and (double_bytes[0:7] != '\x00\x00\x00\x00\x00\x00\xF0')): + return (_NAN, new_pos) + + # Note that we expect someone up-stack to catch struct.error and convert + # it to _DecodeError -- this way we don't have to set up exception- + # handling blocks every time we parse one value. + result = local_unpack(' end: + raise _DecodeError('Truncated string.') + value.append(local_unicode(buffer[pos:new_pos], 'utf-8')) + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + return DecodeRepeatedField + else: + def DecodeField(buffer, pos, end, message, field_dict): + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated string.') + field_dict[key] = local_unicode(buffer[pos:new_pos], 'utf-8') + return new_pos + return DecodeField + + +def BytesDecoder(field_number, is_repeated, is_packed, key, new_default): + """Returns a decoder for a bytes field.""" + + local_DecodeVarint = _DecodeVarint + + assert not is_packed + if is_repeated: + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_LENGTH_DELIMITED) + tag_len = len(tag_bytes) + def DecodeRepeatedField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated string.') + value.append(buffer[pos:new_pos]) + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + return DecodeRepeatedField + else: + def DecodeField(buffer, pos, end, message, field_dict): + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated string.') + field_dict[key] = buffer[pos:new_pos] + return new_pos + return DecodeField + + +def GroupDecoder(field_number, is_repeated, is_packed, key, new_default): + """Returns a decoder for a group field.""" + + end_tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_END_GROUP) + end_tag_len = len(end_tag_bytes) + + assert not is_packed + if is_repeated: + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_START_GROUP) + tag_len = len(tag_bytes) + def DecodeRepeatedField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read sub-message. + pos = value.add()._InternalParse(buffer, pos, end) + # Read end tag. + new_pos = pos+end_tag_len + if buffer[pos:new_pos] != end_tag_bytes or new_pos > end: + raise _DecodeError('Missing group end tag.') + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + return DecodeRepeatedField + else: + def DecodeField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read sub-message. + pos = value._InternalParse(buffer, pos, end) + # Read end tag. + new_pos = pos+end_tag_len + if buffer[pos:new_pos] != end_tag_bytes or new_pos > end: + raise _DecodeError('Missing group end tag.') + return new_pos + return DecodeField + + +def MessageDecoder(field_number, is_repeated, is_packed, key, new_default): + """Returns a decoder for a message field.""" + + local_DecodeVarint = _DecodeVarint + + assert not is_packed + if is_repeated: + tag_bytes = encoder.TagBytes(field_number, + wire_format.WIRETYPE_LENGTH_DELIMITED) + tag_len = len(tag_bytes) + def DecodeRepeatedField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + while 1: + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read length. + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated message.') + # Read sub-message. + if value.add()._InternalParse(buffer, pos, new_pos) != new_pos: + # The only reason _InternalParse would return early is if it + # encountered an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + # Predict that the next tag is another copy of the same repeated field. + pos = new_pos + tag_len + if buffer[new_pos:pos] != tag_bytes or new_pos == end: + # Prediction failed. Return. + return new_pos + return DecodeRepeatedField + else: + def DecodeField(buffer, pos, end, message, field_dict): + value = field_dict.get(key) + if value is None: + value = field_dict.setdefault(key, new_default(message)) + # Read length. + (size, pos) = local_DecodeVarint(buffer, pos) + new_pos = pos + size + if new_pos > end: + raise _DecodeError('Truncated message.') + # Read sub-message. + if value._InternalParse(buffer, pos, new_pos) != new_pos: + # The only reason _InternalParse would return early is if it encountered + # an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + return new_pos + return DecodeField + + +# -------------------------------------------------------------------- + +MESSAGE_SET_ITEM_TAG = encoder.TagBytes(1, wire_format.WIRETYPE_START_GROUP) + +def MessageSetItemDecoder(extensions_by_number): + """Returns a decoder for a MessageSet item. + + The parameter is the _extensions_by_number map for the message class. + + The message set message looks like this: + message MessageSet { + repeated group Item = 1 { + required int32 type_id = 2; + required string message = 3; + } + } + """ + + type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT) + message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED) + item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP) + + local_ReadTag = ReadTag + local_DecodeVarint = _DecodeVarint + local_SkipField = SkipField + + def DecodeItem(buffer, pos, end, message, field_dict): + message_set_item_start = pos + type_id = -1 + message_start = -1 + message_end = -1 + + # Technically, type_id and message can appear in any order, so we need + # a little loop here. + while 1: + (tag_bytes, pos) = local_ReadTag(buffer, pos) + if tag_bytes == type_id_tag_bytes: + (type_id, pos) = local_DecodeVarint(buffer, pos) + elif tag_bytes == message_tag_bytes: + (size, message_start) = local_DecodeVarint(buffer, pos) + pos = message_end = message_start + size + elif tag_bytes == item_end_tag_bytes: + break + else: + pos = SkipField(buffer, pos, end, tag_bytes) + if pos == -1: + raise _DecodeError('Missing group end tag.') + + if pos > end: + raise _DecodeError('Truncated message.') + + if type_id == -1: + raise _DecodeError('MessageSet item missing type_id.') + if message_start == -1: + raise _DecodeError('MessageSet item missing message.') + + extension = extensions_by_number.get(type_id) + if extension is not None: + value = field_dict.get(extension) + if value is None: + value = field_dict.setdefault( + extension, extension.message_type._concrete_class()) + if value._InternalParse(buffer, message_start,message_end) != message_end: + # The only reason _InternalParse would return early is if it encountered + # an end-group tag. + raise _DecodeError('Unexpected end-group tag.') + else: + if not message._unknown_fields: + message._unknown_fields = [] + message._unknown_fields.append((MESSAGE_SET_ITEM_TAG, + buffer[message_set_item_start:pos])) + + return pos + + return DecodeItem + +# -------------------------------------------------------------------- +# Optimization is not as heavy here because calls to SkipField() are rare, +# except for handling end-group tags. + +def _SkipVarint(buffer, pos, end): + """Skip a varint value. Returns the new position.""" + + while ord(buffer[pos]) & 0x80: + pos += 1 + pos += 1 + if pos > end: + raise _DecodeError('Truncated message.') + return pos + +def _SkipFixed64(buffer, pos, end): + """Skip a fixed64 value. Returns the new position.""" + + pos += 8 + if pos > end: + raise _DecodeError('Truncated message.') + return pos + +def _SkipLengthDelimited(buffer, pos, end): + """Skip a length-delimited value. Returns the new position.""" + + (size, pos) = _DecodeVarint(buffer, pos) + pos += size + if pos > end: + raise _DecodeError('Truncated message.') + return pos + +def _SkipGroup(buffer, pos, end): + """Skip sub-group. Returns the new position.""" + + while 1: + (tag_bytes, pos) = ReadTag(buffer, pos) + new_pos = SkipField(buffer, pos, end, tag_bytes) + if new_pos == -1: + return pos + pos = new_pos + +def _EndGroup(buffer, pos, end): + """Skipping an END_GROUP tag returns -1 to tell the parent loop to break.""" + + return -1 + +def _SkipFixed32(buffer, pos, end): + """Skip a fixed32 value. Returns the new position.""" + + pos += 4 + if pos > end: + raise _DecodeError('Truncated message.') + return pos + +def _RaiseInvalidWireType(buffer, pos, end): + """Skip function for unknown wire types. Raises an exception.""" + + raise _DecodeError('Tag had invalid wire type.') + +def _FieldSkipper(): + """Constructs the SkipField function.""" + + WIRETYPE_TO_SKIPPER = [ + _SkipVarint, + _SkipFixed64, + _SkipLengthDelimited, + _SkipGroup, + _EndGroup, + _SkipFixed32, + _RaiseInvalidWireType, + _RaiseInvalidWireType, + ] + + wiretype_mask = wire_format.TAG_TYPE_MASK + local_ord = ord + + def SkipField(buffer, pos, end, tag_bytes): + """Skips a field with the specified tag. + + |pos| should point to the byte immediately after the tag. + + Returns: + The new position (after the tag value), or -1 if the tag is an end-group + tag (in which case the calling loop should break). + """ + + # The wire type is always in the first byte since varints are little-endian. + wire_type = local_ord(tag_bytes[0]) & wiretype_mask + return WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end) + + return SkipField + +SkipField = _FieldSkipper() diff --git a/code/push/google/protobuf/internal/descriptor_database_test.py b/code/push/google/protobuf/internal/descriptor_database_test.py new file mode 100644 index 0000000..d0ca789 --- /dev/null +++ b/code/push/google/protobuf/internal/descriptor_database_test.py @@ -0,0 +1,63 @@ +#! /usr/bin/python +# +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Tests for google.protobuf.descriptor_database.""" + +__author__ = 'matthewtoia@google.com (Matt Toia)' + +import unittest +from google.protobuf import descriptor_pb2 +from google.protobuf.internal import factory_test2_pb2 +from google.protobuf import descriptor_database + + +class DescriptorDatabaseTest(unittest.TestCase): + + def testAdd(self): + db = descriptor_database.DescriptorDatabase() + file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString( + factory_test2_pb2.DESCRIPTOR.serialized_pb) + db.Add(file_desc_proto) + + self.assertEquals(file_desc_proto, db.FindFileByName( + 'net/proto2/python/internal/factory_test2.proto')) + self.assertEquals(file_desc_proto, db.FindFileContainingSymbol( + 'net.proto2.python.internal.Factory2Message')) + self.assertEquals(file_desc_proto, db.FindFileContainingSymbol( + 'net.proto2.python.internal.Factory2Message.NestedFactory2Message')) + self.assertEquals(file_desc_proto, db.FindFileContainingSymbol( + 'net.proto2.python.internal.Factory2Enum')) + self.assertEquals(file_desc_proto, db.FindFileContainingSymbol( + 'net.proto2.python.internal.Factory2Message.NestedFactory2Enum')) + +if __name__ == '__main__': + unittest.main() diff --git a/code/push/google/protobuf/internal/descriptor_pool_test.py b/code/push/google/protobuf/internal/descriptor_pool_test.py new file mode 100644 index 0000000..a615d78 --- /dev/null +++ b/code/push/google/protobuf/internal/descriptor_pool_test.py @@ -0,0 +1,220 @@ +#! /usr/bin/python +# +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Tests for google.protobuf.descriptor_pool.""" + +__author__ = 'matthewtoia@google.com (Matt Toia)' + +import unittest +from google.protobuf import descriptor_pb2 +from google.protobuf.internal import factory_test1_pb2 +from google.protobuf.internal import factory_test2_pb2 +from google.protobuf import descriptor +from google.protobuf import descriptor_database +from google.protobuf import descriptor_pool + + +class DescriptorPoolTest(unittest.TestCase): + + def setUp(self): + self.pool = descriptor_pool.DescriptorPool() + self.factory_test1_fd = descriptor_pb2.FileDescriptorProto.FromString( + factory_test1_pb2.DESCRIPTOR.serialized_pb) + self.factory_test2_fd = descriptor_pb2.FileDescriptorProto.FromString( + factory_test2_pb2.DESCRIPTOR.serialized_pb) + self.pool.Add(self.factory_test1_fd) + self.pool.Add(self.factory_test2_fd) + + def testFindFileByName(self): + name1 = 'net/proto2/python/internal/factory_test1.proto' + file_desc1 = self.pool.FindFileByName(name1) + self.assertIsInstance(file_desc1, descriptor.FileDescriptor) + self.assertEquals(name1, file_desc1.name) + self.assertEquals('net.proto2.python.internal', file_desc1.package) + self.assertIn('Factory1Message', file_desc1.message_types_by_name) + + name2 = 'net/proto2/python/internal/factory_test2.proto' + file_desc2 = self.pool.FindFileByName(name2) + self.assertIsInstance(file_desc2, descriptor.FileDescriptor) + self.assertEquals(name2, file_desc2.name) + self.assertEquals('net.proto2.python.internal', file_desc2.package) + self.assertIn('Factory2Message', file_desc2.message_types_by_name) + + def testFindFileByNameFailure(self): + try: + self.pool.FindFileByName('Does not exist') + self.fail('Expected KeyError') + except KeyError: + pass + + def testFindFileContainingSymbol(self): + file_desc1 = self.pool.FindFileContainingSymbol( + 'net.proto2.python.internal.Factory1Message') + self.assertIsInstance(file_desc1, descriptor.FileDescriptor) + self.assertEquals('net/proto2/python/internal/factory_test1.proto', + file_desc1.name) + self.assertEquals('net.proto2.python.internal', file_desc1.package) + self.assertIn('Factory1Message', file_desc1.message_types_by_name) + + file_desc2 = self.pool.FindFileContainingSymbol( + 'net.proto2.python.internal.Factory2Message') + self.assertIsInstance(file_desc2, descriptor.FileDescriptor) + self.assertEquals('net/proto2/python/internal/factory_test2.proto', + file_desc2.name) + self.assertEquals('net.proto2.python.internal', file_desc2.package) + self.assertIn('Factory2Message', file_desc2.message_types_by_name) + + def testFindFileContainingSymbolFailure(self): + try: + self.pool.FindFileContainingSymbol('Does not exist') + self.fail('Expected KeyError') + except KeyError: + pass + + def testFindMessageTypeByName(self): + msg1 = self.pool.FindMessageTypeByName( + 'net.proto2.python.internal.Factory1Message') + self.assertIsInstance(msg1, descriptor.Descriptor) + self.assertEquals('Factory1Message', msg1.name) + self.assertEquals('net.proto2.python.internal.Factory1Message', + msg1.full_name) + self.assertEquals(None, msg1.containing_type) + + nested_msg1 = msg1.nested_types[0] + self.assertEquals('NestedFactory1Message', nested_msg1.name) + self.assertEquals(msg1, nested_msg1.containing_type) + + nested_enum1 = msg1.enum_types[0] + self.assertEquals('NestedFactory1Enum', nested_enum1.name) + self.assertEquals(msg1, nested_enum1.containing_type) + + self.assertEquals(nested_msg1, msg1.fields_by_name[ + 'nested_factory_1_message'].message_type) + self.assertEquals(nested_enum1, msg1.fields_by_name[ + 'nested_factory_1_enum'].enum_type) + + msg2 = self.pool.FindMessageTypeByName( + 'net.proto2.python.internal.Factory2Message') + self.assertIsInstance(msg2, descriptor.Descriptor) + self.assertEquals('Factory2Message', msg2.name) + self.assertEquals('net.proto2.python.internal.Factory2Message', + msg2.full_name) + self.assertIsNone(msg2.containing_type) + + nested_msg2 = msg2.nested_types[0] + self.assertEquals('NestedFactory2Message', nested_msg2.name) + self.assertEquals(msg2, nested_msg2.containing_type) + + nested_enum2 = msg2.enum_types[0] + self.assertEquals('NestedFactory2Enum', nested_enum2.name) + self.assertEquals(msg2, nested_enum2.containing_type) + + self.assertEquals(nested_msg2, msg2.fields_by_name[ + 'nested_factory_2_message'].message_type) + self.assertEquals(nested_enum2, msg2.fields_by_name[ + 'nested_factory_2_enum'].enum_type) + + self.assertTrue(msg2.fields_by_name['int_with_default'].has_default) + self.assertEquals( + 1776, msg2.fields_by_name['int_with_default'].default_value) + + self.assertTrue(msg2.fields_by_name['double_with_default'].has_default) + self.assertEquals( + 9.99, msg2.fields_by_name['double_with_default'].default_value) + + self.assertTrue(msg2.fields_by_name['string_with_default'].has_default) + self.assertEquals( + 'hello world', msg2.fields_by_name['string_with_default'].default_value) + + self.assertTrue(msg2.fields_by_name['bool_with_default'].has_default) + self.assertFalse(msg2.fields_by_name['bool_with_default'].default_value) + + self.assertTrue(msg2.fields_by_name['enum_with_default'].has_default) + self.assertEquals( + 1, msg2.fields_by_name['enum_with_default'].default_value) + + msg3 = self.pool.FindMessageTypeByName( + 'net.proto2.python.internal.Factory2Message.NestedFactory2Message') + self.assertEquals(nested_msg2, msg3) + + def testFindMessageTypeByNameFailure(self): + try: + self.pool.FindMessageTypeByName('Does not exist') + self.fail('Expected KeyError') + except KeyError: + pass + + def testFindEnumTypeByName(self): + enum1 = self.pool.FindEnumTypeByName( + 'net.proto2.python.internal.Factory1Enum') + self.assertIsInstance(enum1, descriptor.EnumDescriptor) + self.assertEquals(0, enum1.values_by_name['FACTORY_1_VALUE_0'].number) + self.assertEquals(1, enum1.values_by_name['FACTORY_1_VALUE_1'].number) + + nested_enum1 = self.pool.FindEnumTypeByName( + 'net.proto2.python.internal.Factory1Message.NestedFactory1Enum') + self.assertIsInstance(nested_enum1, descriptor.EnumDescriptor) + self.assertEquals( + 0, nested_enum1.values_by_name['NESTED_FACTORY_1_VALUE_0'].number) + self.assertEquals( + 1, nested_enum1.values_by_name['NESTED_FACTORY_1_VALUE_1'].number) + + enum2 = self.pool.FindEnumTypeByName( + 'net.proto2.python.internal.Factory2Enum') + self.assertIsInstance(enum2, descriptor.EnumDescriptor) + self.assertEquals(0, enum2.values_by_name['FACTORY_2_VALUE_0'].number) + self.assertEquals(1, enum2.values_by_name['FACTORY_2_VALUE_1'].number) + + nested_enum2 = self.pool.FindEnumTypeByName( + 'net.proto2.python.internal.Factory2Message.NestedFactory2Enum') + self.assertIsInstance(nested_enum2, descriptor.EnumDescriptor) + self.assertEquals( + 0, nested_enum2.values_by_name['NESTED_FACTORY_2_VALUE_0'].number) + self.assertEquals( + 1, nested_enum2.values_by_name['NESTED_FACTORY_2_VALUE_1'].number) + + def testFindEnumTypeByNameFailure(self): + try: + self.pool.FindEnumTypeByName('Does not exist') + self.fail('Expected KeyError') + except KeyError: + pass + + def testUserDefinedDB(self): + db = descriptor_database.DescriptorDatabase() + self.pool = descriptor_pool.DescriptorPool(db) + db.Add(self.factory_test1_fd) + db.Add(self.factory_test2_fd) + self.testFindMessageTypeByName() + +if __name__ == '__main__': + unittest.main() diff --git a/code/push/google/protobuf/internal/descriptor_test.py b/code/push/google/protobuf/internal/descriptor_test.py new file mode 100644 index 0000000..c74f882 --- /dev/null +++ b/code/push/google/protobuf/internal/descriptor_test.py @@ -0,0 +1,613 @@ +#! /usr/bin/python +# +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Unittest for google.protobuf.internal.descriptor.""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import unittest +from google.protobuf import unittest_custom_options_pb2 +from google.protobuf import unittest_import_pb2 +from google.protobuf import unittest_pb2 +from google.protobuf import descriptor_pb2 +from google.protobuf import descriptor +from google.protobuf import text_format + + +TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII = """ +name: 'TestEmptyMessage' +""" + + +class DescriptorTest(unittest.TestCase): + + def setUp(self): + self.my_file = descriptor.FileDescriptor( + name='some/filename/some.proto', + package='protobuf_unittest' + ) + self.my_enum = descriptor.EnumDescriptor( + name='ForeignEnum', + full_name='protobuf_unittest.ForeignEnum', + filename=None, + file=self.my_file, + values=[ + descriptor.EnumValueDescriptor(name='FOREIGN_FOO', index=0, number=4), + descriptor.EnumValueDescriptor(name='FOREIGN_BAR', index=1, number=5), + descriptor.EnumValueDescriptor(name='FOREIGN_BAZ', index=2, number=6), + ]) + self.my_message = descriptor.Descriptor( + name='NestedMessage', + full_name='protobuf_unittest.TestAllTypes.NestedMessage', + filename=None, + file=self.my_file, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='bb', + full_name='protobuf_unittest.TestAllTypes.NestedMessage.bb', + index=0, number=1, + type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None), + ], + nested_types=[], + enum_types=[ + self.my_enum, + ], + extensions=[]) + self.my_method = descriptor.MethodDescriptor( + name='Bar', + full_name='protobuf_unittest.TestService.Bar', + index=0, + containing_service=None, + input_type=None, + output_type=None) + self.my_service = descriptor.ServiceDescriptor( + name='TestServiceWithOptions', + full_name='protobuf_unittest.TestServiceWithOptions', + file=self.my_file, + index=0, + methods=[ + self.my_method + ]) + + def testEnumValueName(self): + self.assertEqual(self.my_message.EnumValueName('ForeignEnum', 4), + 'FOREIGN_FOO') + + self.assertEqual( + self.my_message.enum_types_by_name[ + 'ForeignEnum'].values_by_number[4].name, + self.my_message.EnumValueName('ForeignEnum', 4)) + + def testEnumFixups(self): + self.assertEqual(self.my_enum, self.my_enum.values[0].type) + + def testContainingTypeFixups(self): + self.assertEqual(self.my_message, self.my_message.fields[0].containing_type) + self.assertEqual(self.my_message, self.my_enum.containing_type) + + def testContainingServiceFixups(self): + self.assertEqual(self.my_service, self.my_method.containing_service) + + def testGetOptions(self): + self.assertEqual(self.my_enum.GetOptions(), + descriptor_pb2.EnumOptions()) + self.assertEqual(self.my_enum.values[0].GetOptions(), + descriptor_pb2.EnumValueOptions()) + self.assertEqual(self.my_message.GetOptions(), + descriptor_pb2.MessageOptions()) + self.assertEqual(self.my_message.fields[0].GetOptions(), + descriptor_pb2.FieldOptions()) + self.assertEqual(self.my_method.GetOptions(), + descriptor_pb2.MethodOptions()) + self.assertEqual(self.my_service.GetOptions(), + descriptor_pb2.ServiceOptions()) + + def testSimpleCustomOptions(self): + file_descriptor = unittest_custom_options_pb2.DESCRIPTOR + message_descriptor =\ + unittest_custom_options_pb2.TestMessageWithCustomOptions.DESCRIPTOR + field_descriptor = message_descriptor.fields_by_name["field1"] + enum_descriptor = message_descriptor.enum_types_by_name["AnEnum"] + enum_value_descriptor =\ + message_descriptor.enum_values_by_name["ANENUM_VAL2"] + service_descriptor =\ + unittest_custom_options_pb2.TestServiceWithCustomOptions.DESCRIPTOR + method_descriptor = service_descriptor.FindMethodByName("Foo") + + file_options = file_descriptor.GetOptions() + file_opt1 = unittest_custom_options_pb2.file_opt1 + self.assertEqual(9876543210, file_options.Extensions[file_opt1]) + message_options = message_descriptor.GetOptions() + message_opt1 = unittest_custom_options_pb2.message_opt1 + self.assertEqual(-56, message_options.Extensions[message_opt1]) + field_options = field_descriptor.GetOptions() + field_opt1 = unittest_custom_options_pb2.field_opt1 + self.assertEqual(8765432109, field_options.Extensions[field_opt1]) + field_opt2 = unittest_custom_options_pb2.field_opt2 + self.assertEqual(42, field_options.Extensions[field_opt2]) + enum_options = enum_descriptor.GetOptions() + enum_opt1 = unittest_custom_options_pb2.enum_opt1 + self.assertEqual(-789, enum_options.Extensions[enum_opt1]) + enum_value_options = enum_value_descriptor.GetOptions() + enum_value_opt1 = unittest_custom_options_pb2.enum_value_opt1 + self.assertEqual(123, enum_value_options.Extensions[enum_value_opt1]) + + service_options = service_descriptor.GetOptions() + service_opt1 = unittest_custom_options_pb2.service_opt1 + self.assertEqual(-9876543210, service_options.Extensions[service_opt1]) + method_options = method_descriptor.GetOptions() + method_opt1 = unittest_custom_options_pb2.method_opt1 + self.assertEqual(unittest_custom_options_pb2.METHODOPT1_VAL2, + method_options.Extensions[method_opt1]) + + def testDifferentCustomOptionTypes(self): + kint32min = -2**31 + kint64min = -2**63 + kint32max = 2**31 - 1 + kint64max = 2**63 - 1 + kuint32max = 2**32 - 1 + kuint64max = 2**64 - 1 + + message_descriptor =\ + unittest_custom_options_pb2.CustomOptionMinIntegerValues.DESCRIPTOR + message_options = message_descriptor.GetOptions() + self.assertEqual(False, message_options.Extensions[ + unittest_custom_options_pb2.bool_opt]) + self.assertEqual(kint32min, message_options.Extensions[ + unittest_custom_options_pb2.int32_opt]) + self.assertEqual(kint64min, message_options.Extensions[ + unittest_custom_options_pb2.int64_opt]) + self.assertEqual(0, message_options.Extensions[ + unittest_custom_options_pb2.uint32_opt]) + self.assertEqual(0, message_options.Extensions[ + unittest_custom_options_pb2.uint64_opt]) + self.assertEqual(kint32min, message_options.Extensions[ + unittest_custom_options_pb2.sint32_opt]) + self.assertEqual(kint64min, message_options.Extensions[ + unittest_custom_options_pb2.sint64_opt]) + self.assertEqual(0, message_options.Extensions[ + unittest_custom_options_pb2.fixed32_opt]) + self.assertEqual(0, message_options.Extensions[ + unittest_custom_options_pb2.fixed64_opt]) + self.assertEqual(kint32min, message_options.Extensions[ + unittest_custom_options_pb2.sfixed32_opt]) + self.assertEqual(kint64min, message_options.Extensions[ + unittest_custom_options_pb2.sfixed64_opt]) + + message_descriptor =\ + unittest_custom_options_pb2.CustomOptionMaxIntegerValues.DESCRIPTOR + message_options = message_descriptor.GetOptions() + self.assertEqual(True, message_options.Extensions[ + unittest_custom_options_pb2.bool_opt]) + self.assertEqual(kint32max, message_options.Extensions[ + unittest_custom_options_pb2.int32_opt]) + self.assertEqual(kint64max, message_options.Extensions[ + unittest_custom_options_pb2.int64_opt]) + self.assertEqual(kuint32max, message_options.Extensions[ + unittest_custom_options_pb2.uint32_opt]) + self.assertEqual(kuint64max, message_options.Extensions[ + unittest_custom_options_pb2.uint64_opt]) + self.assertEqual(kint32max, message_options.Extensions[ + unittest_custom_options_pb2.sint32_opt]) + self.assertEqual(kint64max, message_options.Extensions[ + unittest_custom_options_pb2.sint64_opt]) + self.assertEqual(kuint32max, message_options.Extensions[ + unittest_custom_options_pb2.fixed32_opt]) + self.assertEqual(kuint64max, message_options.Extensions[ + unittest_custom_options_pb2.fixed64_opt]) + self.assertEqual(kint32max, message_options.Extensions[ + unittest_custom_options_pb2.sfixed32_opt]) + self.assertEqual(kint64max, message_options.Extensions[ + unittest_custom_options_pb2.sfixed64_opt]) + + message_descriptor =\ + unittest_custom_options_pb2.CustomOptionOtherValues.DESCRIPTOR + message_options = message_descriptor.GetOptions() + self.assertEqual(-100, message_options.Extensions[ + unittest_custom_options_pb2.int32_opt]) + self.assertAlmostEqual(12.3456789, message_options.Extensions[ + unittest_custom_options_pb2.float_opt], 6) + self.assertAlmostEqual(1.234567890123456789, message_options.Extensions[ + unittest_custom_options_pb2.double_opt]) + self.assertEqual("Hello, \"World\"", message_options.Extensions[ + unittest_custom_options_pb2.string_opt]) + self.assertEqual("Hello\0World", message_options.Extensions[ + unittest_custom_options_pb2.bytes_opt]) + dummy_enum = unittest_custom_options_pb2.DummyMessageContainingEnum + self.assertEqual( + dummy_enum.TEST_OPTION_ENUM_TYPE2, + message_options.Extensions[unittest_custom_options_pb2.enum_opt]) + + message_descriptor =\ + unittest_custom_options_pb2.SettingRealsFromPositiveInts.DESCRIPTOR + message_options = message_descriptor.GetOptions() + self.assertAlmostEqual(12, message_options.Extensions[ + unittest_custom_options_pb2.float_opt], 6) + self.assertAlmostEqual(154, message_options.Extensions[ + unittest_custom_options_pb2.double_opt]) + + message_descriptor =\ + unittest_custom_options_pb2.SettingRealsFromNegativeInts.DESCRIPTOR + message_options = message_descriptor.GetOptions() + self.assertAlmostEqual(-12, message_options.Extensions[ + unittest_custom_options_pb2.float_opt], 6) + self.assertAlmostEqual(-154, message_options.Extensions[ + unittest_custom_options_pb2.double_opt]) + + def testComplexExtensionOptions(self): + descriptor =\ + unittest_custom_options_pb2.VariousComplexOptions.DESCRIPTOR + options = descriptor.GetOptions() + self.assertEqual(42, options.Extensions[ + unittest_custom_options_pb2.complex_opt1].foo) + self.assertEqual(324, options.Extensions[ + unittest_custom_options_pb2.complex_opt1].Extensions[ + unittest_custom_options_pb2.quux]) + self.assertEqual(876, options.Extensions[ + unittest_custom_options_pb2.complex_opt1].Extensions[ + unittest_custom_options_pb2.corge].qux) + self.assertEqual(987, options.Extensions[ + unittest_custom_options_pb2.complex_opt2].baz) + self.assertEqual(654, options.Extensions[ + unittest_custom_options_pb2.complex_opt2].Extensions[ + unittest_custom_options_pb2.grault]) + self.assertEqual(743, options.Extensions[ + unittest_custom_options_pb2.complex_opt2].bar.foo) + self.assertEqual(1999, options.Extensions[ + unittest_custom_options_pb2.complex_opt2].bar.Extensions[ + unittest_custom_options_pb2.quux]) + self.assertEqual(2008, options.Extensions[ + unittest_custom_options_pb2.complex_opt2].bar.Extensions[ + unittest_custom_options_pb2.corge].qux) + self.assertEqual(741, options.Extensions[ + unittest_custom_options_pb2.complex_opt2].Extensions[ + unittest_custom_options_pb2.garply].foo) + self.assertEqual(1998, options.Extensions[ + unittest_custom_options_pb2.complex_opt2].Extensions[ + unittest_custom_options_pb2.garply].Extensions[ + unittest_custom_options_pb2.quux]) + self.assertEqual(2121, options.Extensions[ + unittest_custom_options_pb2.complex_opt2].Extensions[ + unittest_custom_options_pb2.garply].Extensions[ + unittest_custom_options_pb2.corge].qux) + self.assertEqual(1971, options.Extensions[ + unittest_custom_options_pb2.ComplexOptionType2 + .ComplexOptionType4.complex_opt4].waldo) + self.assertEqual(321, options.Extensions[ + unittest_custom_options_pb2.complex_opt2].fred.waldo) + self.assertEqual(9, options.Extensions[ + unittest_custom_options_pb2.complex_opt3].qux) + self.assertEqual(22, options.Extensions[ + unittest_custom_options_pb2.complex_opt3].complexoptiontype5.plugh) + self.assertEqual(24, options.Extensions[ + unittest_custom_options_pb2.complexopt6].xyzzy) + + # Check that aggregate options were parsed and saved correctly in + # the appropriate descriptors. + def testAggregateOptions(self): + file_descriptor = unittest_custom_options_pb2.DESCRIPTOR + message_descriptor =\ + unittest_custom_options_pb2.AggregateMessage.DESCRIPTOR + field_descriptor = message_descriptor.fields_by_name["fieldname"] + enum_descriptor = unittest_custom_options_pb2.AggregateEnum.DESCRIPTOR + enum_value_descriptor = enum_descriptor.values_by_name["VALUE"] + service_descriptor =\ + unittest_custom_options_pb2.AggregateService.DESCRIPTOR + method_descriptor = service_descriptor.FindMethodByName("Method") + + # Tests for the different types of data embedded in fileopt + file_options = file_descriptor.GetOptions().Extensions[ + unittest_custom_options_pb2.fileopt] + self.assertEqual(100, file_options.i) + self.assertEqual("FileAnnotation", file_options.s) + self.assertEqual("NestedFileAnnotation", file_options.sub.s) + self.assertEqual("FileExtensionAnnotation", file_options.file.Extensions[ + unittest_custom_options_pb2.fileopt].s) + self.assertEqual("EmbeddedMessageSetElement", file_options.mset.Extensions[ + unittest_custom_options_pb2.AggregateMessageSetElement + .message_set_extension].s) + + # Simple tests for all the other types of annotations + self.assertEqual( + "MessageAnnotation", + message_descriptor.GetOptions().Extensions[ + unittest_custom_options_pb2.msgopt].s) + self.assertEqual( + "FieldAnnotation", + field_descriptor.GetOptions().Extensions[ + unittest_custom_options_pb2.fieldopt].s) + self.assertEqual( + "EnumAnnotation", + enum_descriptor.GetOptions().Extensions[ + unittest_custom_options_pb2.enumopt].s) + self.assertEqual( + "EnumValueAnnotation", + enum_value_descriptor.GetOptions().Extensions[ + unittest_custom_options_pb2.enumvalopt].s) + self.assertEqual( + "ServiceAnnotation", + service_descriptor.GetOptions().Extensions[ + unittest_custom_options_pb2.serviceopt].s) + self.assertEqual( + "MethodAnnotation", + method_descriptor.GetOptions().Extensions[ + unittest_custom_options_pb2.methodopt].s) + + def testNestedOptions(self): + nested_message =\ + unittest_custom_options_pb2.NestedOptionType.NestedMessage.DESCRIPTOR + self.assertEqual(1001, nested_message.GetOptions().Extensions[ + unittest_custom_options_pb2.message_opt1]) + nested_field = nested_message.fields_by_name["nested_field"] + self.assertEqual(1002, nested_field.GetOptions().Extensions[ + unittest_custom_options_pb2.field_opt1]) + outer_message =\ + unittest_custom_options_pb2.NestedOptionType.DESCRIPTOR + nested_enum = outer_message.enum_types_by_name["NestedEnum"] + self.assertEqual(1003, nested_enum.GetOptions().Extensions[ + unittest_custom_options_pb2.enum_opt1]) + nested_enum_value = outer_message.enum_values_by_name["NESTED_ENUM_VALUE"] + self.assertEqual(1004, nested_enum_value.GetOptions().Extensions[ + unittest_custom_options_pb2.enum_value_opt1]) + nested_extension = outer_message.extensions_by_name["nested_extension"] + self.assertEqual(1005, nested_extension.GetOptions().Extensions[ + unittest_custom_options_pb2.field_opt2]) + + def testFileDescriptorReferences(self): + self.assertEqual(self.my_enum.file, self.my_file) + self.assertEqual(self.my_message.file, self.my_file) + + def testFileDescriptor(self): + self.assertEqual(self.my_file.name, 'some/filename/some.proto') + self.assertEqual(self.my_file.package, 'protobuf_unittest') + + +class DescriptorCopyToProtoTest(unittest.TestCase): + """Tests for CopyTo functions of Descriptor.""" + + def _AssertProtoEqual(self, actual_proto, expected_class, expected_ascii): + expected_proto = expected_class() + text_format.Merge(expected_ascii, expected_proto) + + self.assertEqual( + actual_proto, expected_proto, + 'Not equal,\nActual:\n%s\nExpected:\n%s\n' + % (str(actual_proto), str(expected_proto))) + + def _InternalTestCopyToProto(self, desc, expected_proto_class, + expected_proto_ascii): + actual = expected_proto_class() + desc.CopyToProto(actual) + self._AssertProtoEqual( + actual, expected_proto_class, expected_proto_ascii) + + def testCopyToProto_EmptyMessage(self): + self._InternalTestCopyToProto( + unittest_pb2.TestEmptyMessage.DESCRIPTOR, + descriptor_pb2.DescriptorProto, + TEST_EMPTY_MESSAGE_DESCRIPTOR_ASCII) + + def testCopyToProto_NestedMessage(self): + TEST_NESTED_MESSAGE_ASCII = """ + name: 'NestedMessage' + field: < + name: 'bb' + number: 1 + label: 1 # Optional + type: 5 # TYPE_INT32 + > + """ + + self._InternalTestCopyToProto( + unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR, + descriptor_pb2.DescriptorProto, + TEST_NESTED_MESSAGE_ASCII) + + def testCopyToProto_ForeignNestedMessage(self): + TEST_FOREIGN_NESTED_ASCII = """ + name: 'TestForeignNested' + field: < + name: 'foreign_nested' + number: 1 + label: 1 # Optional + type: 11 # TYPE_MESSAGE + type_name: '.protobuf_unittest.TestAllTypes.NestedMessage' + > + """ + + self._InternalTestCopyToProto( + unittest_pb2.TestForeignNested.DESCRIPTOR, + descriptor_pb2.DescriptorProto, + TEST_FOREIGN_NESTED_ASCII) + + def testCopyToProto_ForeignEnum(self): + TEST_FOREIGN_ENUM_ASCII = """ + name: 'ForeignEnum' + value: < + name: 'FOREIGN_FOO' + number: 4 + > + value: < + name: 'FOREIGN_BAR' + number: 5 + > + value: < + name: 'FOREIGN_BAZ' + number: 6 + > + """ + + self._InternalTestCopyToProto( + unittest_pb2._FOREIGNENUM, + descriptor_pb2.EnumDescriptorProto, + TEST_FOREIGN_ENUM_ASCII) + + def testCopyToProto_Options(self): + TEST_DEPRECATED_FIELDS_ASCII = """ + name: 'TestDeprecatedFields' + field: < + name: 'deprecated_int32' + number: 1 + label: 1 # Optional + type: 5 # TYPE_INT32 + options: < + deprecated: true + > + > + """ + + self._InternalTestCopyToProto( + unittest_pb2.TestDeprecatedFields.DESCRIPTOR, + descriptor_pb2.DescriptorProto, + TEST_DEPRECATED_FIELDS_ASCII) + + def testCopyToProto_AllExtensions(self): + TEST_EMPTY_MESSAGE_WITH_EXTENSIONS_ASCII = """ + name: 'TestEmptyMessageWithExtensions' + extension_range: < + start: 1 + end: 536870912 + > + """ + + self._InternalTestCopyToProto( + unittest_pb2.TestEmptyMessageWithExtensions.DESCRIPTOR, + descriptor_pb2.DescriptorProto, + TEST_EMPTY_MESSAGE_WITH_EXTENSIONS_ASCII) + + def testCopyToProto_SeveralExtensions(self): + TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII = """ + name: 'TestMultipleExtensionRanges' + extension_range: < + start: 42 + end: 43 + > + extension_range: < + start: 4143 + end: 4244 + > + extension_range: < + start: 65536 + end: 536870912 + > + """ + + self._InternalTestCopyToProto( + unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR, + descriptor_pb2.DescriptorProto, + TEST_MESSAGE_WITH_SEVERAL_EXTENSIONS_ASCII) + + def testCopyToProto_FileDescriptor(self): + UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII = (""" + name: 'google/protobuf/unittest_import.proto' + package: 'protobuf_unittest_import' + dependency: 'google/protobuf/unittest_import_public.proto' + message_type: < + name: 'ImportMessage' + field: < + name: 'd' + number: 1 + label: 1 # Optional + type: 5 # TYPE_INT32 + > + > + """ + + """enum_type: < + name: 'ImportEnum' + value: < + name: 'IMPORT_FOO' + number: 7 + > + value: < + name: 'IMPORT_BAR' + number: 8 + > + value: < + name: 'IMPORT_BAZ' + number: 9 + > + > + options: < + java_package: 'com.google.protobuf.test' + optimize_for: 1 # SPEED + > + public_dependency: 0 + """) + + self._InternalTestCopyToProto( + unittest_import_pb2.DESCRIPTOR, + descriptor_pb2.FileDescriptorProto, + UNITTEST_IMPORT_FILE_DESCRIPTOR_ASCII) + + def testCopyToProto_ServiceDescriptor(self): + TEST_SERVICE_ASCII = """ + name: 'TestService' + method: < + name: 'Foo' + input_type: '.protobuf_unittest.FooRequest' + output_type: '.protobuf_unittest.FooResponse' + > + method: < + name: 'Bar' + input_type: '.protobuf_unittest.BarRequest' + output_type: '.protobuf_unittest.BarResponse' + > + """ + + self._InternalTestCopyToProto( + unittest_pb2.TestService.DESCRIPTOR, + descriptor_pb2.ServiceDescriptorProto, + TEST_SERVICE_ASCII) + + +class MakeDescriptorTest(unittest.TestCase): + def testMakeDescriptorWithUnsignedIntField(self): + file_descriptor_proto = descriptor_pb2.FileDescriptorProto() + file_descriptor_proto.name = 'Foo' + message_type = file_descriptor_proto.message_type.add() + message_type.name = file_descriptor_proto.name + field = message_type.field.add() + field.number = 1 + field.name = 'uint64_field' + field.label = descriptor.FieldDescriptor.LABEL_REQUIRED + field.type = descriptor.FieldDescriptor.TYPE_UINT64 + result = descriptor.MakeDescriptor(message_type) + self.assertEqual(result.fields[0].cpp_type, + descriptor.FieldDescriptor.CPPTYPE_UINT64) + + +if __name__ == '__main__': + unittest.main() diff --git a/code/push/google/protobuf/internal/encoder.py b/code/push/google/protobuf/internal/encoder.py new file mode 100644 index 0000000..8f624a1 --- /dev/null +++ b/code/push/google/protobuf/internal/encoder.py @@ -0,0 +1,769 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Code for encoding protocol message primitives. + +Contains the logic for encoding every logical protocol field type +into one of the 5 physical wire types. + +This code is designed to push the Python interpreter's performance to the +limits. + +The basic idea is that at startup time, for every field (i.e. every +FieldDescriptor) we construct two functions: a "sizer" and an "encoder". The +sizer takes a value of this field's type and computes its byte size. The +encoder takes a writer function and a value. It encodes the value into byte +strings and invokes the writer function to write those strings. Typically the +writer function is the write() method of a cStringIO. + +We try to do as much work as possible when constructing the writer and the +sizer rather than when calling them. In particular: +* We copy any needed global functions to local variables, so that we do not need + to do costly global table lookups at runtime. +* Similarly, we try to do any attribute lookups at startup time if possible. +* Every field's tag is encoded to bytes at startup, since it can't change at + runtime. +* Whatever component of the field size we can compute at startup, we do. +* We *avoid* sharing code if doing so would make the code slower and not sharing + does not burden us too much. For example, encoders for repeated fields do + not just call the encoders for singular fields in a loop because this would + add an extra function call overhead for every loop iteration; instead, we + manually inline the single-value encoder into the loop. +* If a Python function lacks a return statement, Python actually generates + instructions to pop the result of the last statement off the stack, push + None onto the stack, and then return that. If we really don't care what + value is returned, then we can save two instructions by returning the + result of the last statement. It looks funny but it helps. +* We assume that type and bounds checking has happened at a higher level. +""" + +__author__ = 'kenton@google.com (Kenton Varda)' + +import struct +from push.google.protobuf.internal import wire_format + + +# This will overflow and thus become IEEE-754 "infinity". We would use +# "float('inf')" but it doesn't work on Windows pre-Python-2.6. +_POS_INF = 1e10000 +_NEG_INF = -_POS_INF + + +def _VarintSize(value): + """Compute the size of a varint value.""" + if value <= 0x7f: return 1 + if value <= 0x3fff: return 2 + if value <= 0x1fffff: return 3 + if value <= 0xfffffff: return 4 + if value <= 0x7ffffffff: return 5 + if value <= 0x3ffffffffff: return 6 + if value <= 0x1ffffffffffff: return 7 + if value <= 0xffffffffffffff: return 8 + if value <= 0x7fffffffffffffff: return 9 + return 10 + + +def _SignedVarintSize(value): + """Compute the size of a signed varint value.""" + if value < 0: return 10 + if value <= 0x7f: return 1 + if value <= 0x3fff: return 2 + if value <= 0x1fffff: return 3 + if value <= 0xfffffff: return 4 + if value <= 0x7ffffffff: return 5 + if value <= 0x3ffffffffff: return 6 + if value <= 0x1ffffffffffff: return 7 + if value <= 0xffffffffffffff: return 8 + if value <= 0x7fffffffffffffff: return 9 + return 10 + + +def _TagSize(field_number): + """Returns the number of bytes required to serialize a tag with this field + number.""" + # Just pass in type 0, since the type won't affect the tag+type size. + return _VarintSize(wire_format.PackTag(field_number, 0)) + + +# -------------------------------------------------------------------- +# In this section we define some generic sizers. Each of these functions +# takes parameters specific to a particular field type, e.g. int32 or fixed64. +# It returns another function which in turn takes parameters specific to a +# particular field, e.g. the field number and whether it is repeated or packed. +# Look at the next section to see how these are used. + + +def _SimpleSizer(compute_value_size): + """A sizer which uses the function compute_value_size to compute the size of + each value. Typically compute_value_size is _VarintSize.""" + + def SpecificSizer(field_number, is_repeated, is_packed): + tag_size = _TagSize(field_number) + if is_packed: + local_VarintSize = _VarintSize + def PackedFieldSize(value): + result = 0 + for element in value: + result += compute_value_size(element) + return result + local_VarintSize(result) + tag_size + return PackedFieldSize + elif is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + result += compute_value_size(element) + return result + return RepeatedFieldSize + else: + def FieldSize(value): + return tag_size + compute_value_size(value) + return FieldSize + + return SpecificSizer + + +def _ModifiedSizer(compute_value_size, modify_value): + """Like SimpleSizer, but modify_value is invoked on each value before it is + passed to compute_value_size. modify_value is typically ZigZagEncode.""" + + def SpecificSizer(field_number, is_repeated, is_packed): + tag_size = _TagSize(field_number) + if is_packed: + local_VarintSize = _VarintSize + def PackedFieldSize(value): + result = 0 + for element in value: + result += compute_value_size(modify_value(element)) + return result + local_VarintSize(result) + tag_size + return PackedFieldSize + elif is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + result += compute_value_size(modify_value(element)) + return result + return RepeatedFieldSize + else: + def FieldSize(value): + return tag_size + compute_value_size(modify_value(value)) + return FieldSize + + return SpecificSizer + + +def _FixedSizer(value_size): + """Like _SimpleSizer except for a fixed-size field. The input is the size + of one value.""" + + def SpecificSizer(field_number, is_repeated, is_packed): + tag_size = _TagSize(field_number) + if is_packed: + local_VarintSize = _VarintSize + def PackedFieldSize(value): + result = len(value) * value_size + return result + local_VarintSize(result) + tag_size + return PackedFieldSize + elif is_repeated: + element_size = value_size + tag_size + def RepeatedFieldSize(value): + return len(value) * element_size + return RepeatedFieldSize + else: + field_size = value_size + tag_size + def FieldSize(value): + return field_size + return FieldSize + + return SpecificSizer + + +# ==================================================================== +# Here we declare a sizer constructor for each field type. Each "sizer +# constructor" is a function that takes (field_number, is_repeated, is_packed) +# as parameters and returns a sizer, which in turn takes a field value as +# a parameter and returns its encoded size. + + +Int32Sizer = Int64Sizer = EnumSizer = _SimpleSizer(_SignedVarintSize) + +UInt32Sizer = UInt64Sizer = _SimpleSizer(_VarintSize) + +SInt32Sizer = SInt64Sizer = _ModifiedSizer( + _SignedVarintSize, wire_format.ZigZagEncode) + +Fixed32Sizer = SFixed32Sizer = FloatSizer = _FixedSizer(4) +Fixed64Sizer = SFixed64Sizer = DoubleSizer = _FixedSizer(8) + +BoolSizer = _FixedSizer(1) + + +def StringSizer(field_number, is_repeated, is_packed): + """Returns a sizer for a string field.""" + + tag_size = _TagSize(field_number) + local_VarintSize = _VarintSize + local_len = len + assert not is_packed + if is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + l = local_len(element.encode('utf-8')) + result += local_VarintSize(l) + l + return result + return RepeatedFieldSize + else: + def FieldSize(value): + l = local_len(value.encode('utf-8')) + return tag_size + local_VarintSize(l) + l + return FieldSize + + +def BytesSizer(field_number, is_repeated, is_packed): + """Returns a sizer for a bytes field.""" + + tag_size = _TagSize(field_number) + local_VarintSize = _VarintSize + local_len = len + assert not is_packed + if is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + l = local_len(element) + result += local_VarintSize(l) + l + return result + return RepeatedFieldSize + else: + def FieldSize(value): + l = local_len(value) + return tag_size + local_VarintSize(l) + l + return FieldSize + + +def GroupSizer(field_number, is_repeated, is_packed): + """Returns a sizer for a group field.""" + + tag_size = _TagSize(field_number) * 2 + assert not is_packed + if is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + result += element.ByteSize() + return result + return RepeatedFieldSize + else: + def FieldSize(value): + return tag_size + value.ByteSize() + return FieldSize + + +def MessageSizer(field_number, is_repeated, is_packed): + """Returns a sizer for a message field.""" + + tag_size = _TagSize(field_number) + local_VarintSize = _VarintSize + assert not is_packed + if is_repeated: + def RepeatedFieldSize(value): + result = tag_size * len(value) + for element in value: + l = element.ByteSize() + result += local_VarintSize(l) + l + return result + return RepeatedFieldSize + else: + def FieldSize(value): + l = value.ByteSize() + return tag_size + local_VarintSize(l) + l + return FieldSize + + +# -------------------------------------------------------------------- +# MessageSet is special. + + +def MessageSetItemSizer(field_number): + """Returns a sizer for extensions of MessageSet. + + The message set message looks like this: + message MessageSet { + repeated group Item = 1 { + required int32 type_id = 2; + required string message = 3; + } + } + """ + static_size = (_TagSize(1) * 2 + _TagSize(2) + _VarintSize(field_number) + + _TagSize(3)) + local_VarintSize = _VarintSize + + def FieldSize(value): + l = value.ByteSize() + return static_size + local_VarintSize(l) + l + + return FieldSize + + +# ==================================================================== +# Encoders! + + +def _VarintEncoder(): + """Return an encoder for a basic varint value (does not include tag).""" + + local_chr = chr + def EncodeVarint(write, value): + bits = value & 0x7f + value >>= 7 + while value: + write(local_chr(0x80|bits)) + bits = value & 0x7f + value >>= 7 + return write(local_chr(bits)) + + return EncodeVarint + + +def _SignedVarintEncoder(): + """Return an encoder for a basic signed varint value (does not include + tag).""" + + local_chr = chr + def EncodeSignedVarint(write, value): + if value < 0: + value += (1 << 64) + bits = value & 0x7f + value >>= 7 + while value: + write(local_chr(0x80|bits)) + bits = value & 0x7f + value >>= 7 + return write(local_chr(bits)) + + return EncodeSignedVarint + + +_EncodeVarint = _VarintEncoder() +_EncodeSignedVarint = _SignedVarintEncoder() + + +def _VarintBytes(value): + """Encode the given integer as a varint and return the bytes. This is only + called at startup time so it doesn't need to be fast.""" + + pieces = [] + _EncodeVarint(pieces.append, value) + return "".join(pieces) + + +def TagBytes(field_number, wire_type): + """Encode the given tag and return the bytes. Only called at startup.""" + + return _VarintBytes(wire_format.PackTag(field_number, wire_type)) + +# -------------------------------------------------------------------- +# As with sizers (see above), we have a number of common encoder +# implementations. + + +def _SimpleEncoder(wire_type, encode_value, compute_value_size): + """Return a constructor for an encoder for fields of a particular type. + + Args: + wire_type: The field's wire type, for encoding tags. + encode_value: A function which encodes an individual value, e.g. + _EncodeVarint(). + compute_value_size: A function which computes the size of an individual + value, e.g. _VarintSize(). + """ + + def SpecificEncoder(field_number, is_repeated, is_packed): + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value): + write(tag_bytes) + size = 0 + for element in value: + size += compute_value_size(element) + local_EncodeVarint(write, size) + for element in value: + encode_value(write, element) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value): + for element in value: + write(tag_bytes) + encode_value(write, element) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value): + write(tag_bytes) + return encode_value(write, value) + return EncodeField + + return SpecificEncoder + + +def _ModifiedEncoder(wire_type, encode_value, compute_value_size, modify_value): + """Like SimpleEncoder but additionally invokes modify_value on every value + before passing it to encode_value. Usually modify_value is ZigZagEncode.""" + + def SpecificEncoder(field_number, is_repeated, is_packed): + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value): + write(tag_bytes) + size = 0 + for element in value: + size += compute_value_size(modify_value(element)) + local_EncodeVarint(write, size) + for element in value: + encode_value(write, modify_value(element)) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value): + for element in value: + write(tag_bytes) + encode_value(write, modify_value(element)) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value): + write(tag_bytes) + return encode_value(write, modify_value(value)) + return EncodeField + + return SpecificEncoder + + +def _StructPackEncoder(wire_type, format): + """Return a constructor for an encoder for a fixed-width field. + + Args: + wire_type: The field's wire type, for encoding tags. + format: The format string to pass to struct.pack(). + """ + + value_size = struct.calcsize(format) + + def SpecificEncoder(field_number, is_repeated, is_packed): + local_struct_pack = struct.pack + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value): + write(tag_bytes) + local_EncodeVarint(write, len(value) * value_size) + for element in value: + write(local_struct_pack(format, element)) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value): + for element in value: + write(tag_bytes) + write(local_struct_pack(format, element)) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value): + write(tag_bytes) + return write(local_struct_pack(format, value)) + return EncodeField + + return SpecificEncoder + + +def _FloatingPointEncoder(wire_type, format): + """Return a constructor for an encoder for float fields. + + This is like StructPackEncoder, but catches errors that may be due to + passing non-finite floating-point values to struct.pack, and makes a + second attempt to encode those values. + + Args: + wire_type: The field's wire type, for encoding tags. + format: The format string to pass to struct.pack(). + """ + + value_size = struct.calcsize(format) + if value_size == 4: + def EncodeNonFiniteOrRaise(write, value): + # Remember that the serialized form uses little-endian byte order. + if value == _POS_INF: + write('\x00\x00\x80\x7F') + elif value == _NEG_INF: + write('\x00\x00\x80\xFF') + elif value != value: # NaN + write('\x00\x00\xC0\x7F') + else: + raise + elif value_size == 8: + def EncodeNonFiniteOrRaise(write, value): + if value == _POS_INF: + write('\x00\x00\x00\x00\x00\x00\xF0\x7F') + elif value == _NEG_INF: + write('\x00\x00\x00\x00\x00\x00\xF0\xFF') + elif value != value: # NaN + write('\x00\x00\x00\x00\x00\x00\xF8\x7F') + else: + raise + else: + raise ValueError('Can\'t encode floating-point values that are ' + '%d bytes long (only 4 or 8)' % value_size) + + def SpecificEncoder(field_number, is_repeated, is_packed): + local_struct_pack = struct.pack + if is_packed: + tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) + local_EncodeVarint = _EncodeVarint + def EncodePackedField(write, value): + write(tag_bytes) + local_EncodeVarint(write, len(value) * value_size) + for element in value: + # This try/except block is going to be faster than any code that + # we could write to check whether element is finite. + try: + write(local_struct_pack(format, element)) + except SystemError: + EncodeNonFiniteOrRaise(write, element) + return EncodePackedField + elif is_repeated: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeRepeatedField(write, value): + for element in value: + write(tag_bytes) + try: + write(local_struct_pack(format, element)) + except SystemError: + EncodeNonFiniteOrRaise(write, element) + return EncodeRepeatedField + else: + tag_bytes = TagBytes(field_number, wire_type) + def EncodeField(write, value): + write(tag_bytes) + try: + write(local_struct_pack(format, value)) + except SystemError: + EncodeNonFiniteOrRaise(write, value) + return EncodeField + + return SpecificEncoder + + +# ==================================================================== +# Here we declare an encoder constructor for each field type. These work +# very similarly to sizer constructors, described earlier. + + +Int32Encoder = Int64Encoder = EnumEncoder = _SimpleEncoder( + wire_format.WIRETYPE_VARINT, _EncodeSignedVarint, _SignedVarintSize) + +UInt32Encoder = UInt64Encoder = _SimpleEncoder( + wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize) + +SInt32Encoder = SInt64Encoder = _ModifiedEncoder( + wire_format.WIRETYPE_VARINT, _EncodeVarint, _VarintSize, + wire_format.ZigZagEncode) + +# Note that Python conveniently guarantees that when using the '<' prefix on +# formats, they will also have the same size across all platforms (as opposed +# to without the prefix, where their sizes depend on the C compiler's basic +# type sizes). +Fixed32Encoder = _StructPackEncoder(wire_format.WIRETYPE_FIXED32, ' 0) + self.assertTrue(isinf(message.neg_inf_double)) + self.assertTrue(message.neg_inf_double < 0) + self.assertTrue(isnan(message.nan_double)) + + self.assertTrue(isinf(message.inf_float)) + self.assertTrue(message.inf_float > 0) + self.assertTrue(isinf(message.neg_inf_float)) + self.assertTrue(message.neg_inf_float < 0) + self.assertTrue(isnan(message.nan_float)) + self.assertEqual("? ? ?? ?? ??? ??/ ??-", message.cpp_trigraph) + + def testHasDefaultValues(self): + desc = unittest_pb2.TestAllTypes.DESCRIPTOR + + expected_has_default_by_name = { + 'optional_int32': False, + 'repeated_int32': False, + 'optional_nested_message': False, + 'default_int32': True, + } + + has_default_by_name = dict( + [(f.name, f.has_default_value) + for f in desc.fields + if f.name in expected_has_default_by_name]) + self.assertEqual(expected_has_default_by_name, has_default_by_name) + + def testContainingTypeBehaviorForExtensions(self): + self.assertEqual(unittest_pb2.optional_int32_extension.containing_type, + unittest_pb2.TestAllExtensions.DESCRIPTOR) + self.assertEqual(unittest_pb2.TestRequired.single.containing_type, + unittest_pb2.TestAllExtensions.DESCRIPTOR) + + def testExtensionScope(self): + self.assertEqual(unittest_pb2.optional_int32_extension.extension_scope, + None) + self.assertEqual(unittest_pb2.TestRequired.single.extension_scope, + unittest_pb2.TestRequired.DESCRIPTOR) + + def testIsExtension(self): + self.assertTrue(unittest_pb2.optional_int32_extension.is_extension) + self.assertTrue(unittest_pb2.TestRequired.single.is_extension) + + message_descriptor = unittest_pb2.TestRequired.DESCRIPTOR + non_extension_descriptor = message_descriptor.fields_by_name['a'] + self.assertTrue(not non_extension_descriptor.is_extension) + + def testOptions(self): + proto = unittest_mset_pb2.TestMessageSet() + self.assertTrue(proto.DESCRIPTOR.GetOptions().message_set_wire_format) + + def testMessageWithCustomOptions(self): + proto = unittest_custom_options_pb2.TestMessageWithCustomOptions() + enum_options = proto.DESCRIPTOR.enum_types_by_name['AnEnum'].GetOptions() + self.assertTrue(enum_options is not None) + # TODO(gps): We really should test for the presense of the enum_opt1 + # extension and for its value to be set to -789. + + def testNestedTypes(self): + self.assertEquals( + set(unittest_pb2.TestAllTypes.DESCRIPTOR.nested_types), + set([ + unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR, + unittest_pb2.TestAllTypes.OptionalGroup.DESCRIPTOR, + unittest_pb2.TestAllTypes.RepeatedGroup.DESCRIPTOR, + ])) + self.assertEqual(unittest_pb2.TestEmptyMessage.DESCRIPTOR.nested_types, []) + self.assertEqual( + unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.nested_types, []) + + def testContainingType(self): + self.assertTrue( + unittest_pb2.TestEmptyMessage.DESCRIPTOR.containing_type is None) + self.assertTrue( + unittest_pb2.TestAllTypes.DESCRIPTOR.containing_type is None) + self.assertEqual( + unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.containing_type, + unittest_pb2.TestAllTypes.DESCRIPTOR) + self.assertEqual( + unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR.containing_type, + unittest_pb2.TestAllTypes.DESCRIPTOR) + self.assertEqual( + unittest_pb2.TestAllTypes.RepeatedGroup.DESCRIPTOR.containing_type, + unittest_pb2.TestAllTypes.DESCRIPTOR) + + def testContainingTypeInEnumDescriptor(self): + self.assertTrue(unittest_pb2._FOREIGNENUM.containing_type is None) + self.assertEqual(unittest_pb2._TESTALLTYPES_NESTEDENUM.containing_type, + unittest_pb2.TestAllTypes.DESCRIPTOR) + + def testPackage(self): + self.assertEqual( + unittest_pb2.TestAllTypes.DESCRIPTOR.file.package, + 'protobuf_unittest') + desc = unittest_pb2.TestAllTypes.NestedMessage.DESCRIPTOR + self.assertEqual(desc.file.package, 'protobuf_unittest') + self.assertEqual( + unittest_import_pb2.ImportMessage.DESCRIPTOR.file.package, + 'protobuf_unittest_import') + + self.assertEqual( + unittest_pb2._FOREIGNENUM.file.package, 'protobuf_unittest') + self.assertEqual( + unittest_pb2._TESTALLTYPES_NESTEDENUM.file.package, + 'protobuf_unittest') + self.assertEqual( + unittest_import_pb2._IMPORTENUM.file.package, + 'protobuf_unittest_import') + + def testExtensionRange(self): + self.assertEqual( + unittest_pb2.TestAllTypes.DESCRIPTOR.extension_ranges, []) + self.assertEqual( + unittest_pb2.TestAllExtensions.DESCRIPTOR.extension_ranges, + [(1, MAX_EXTENSION)]) + self.assertEqual( + unittest_pb2.TestMultipleExtensionRanges.DESCRIPTOR.extension_ranges, + [(42, 43), (4143, 4244), (65536, MAX_EXTENSION)]) + + def testFileDescriptor(self): + self.assertEqual(unittest_pb2.DESCRIPTOR.name, + 'google/protobuf/unittest.proto') + self.assertEqual(unittest_pb2.DESCRIPTOR.package, 'protobuf_unittest') + self.assertFalse(unittest_pb2.DESCRIPTOR.serialized_pb is None) + + def testNoGenericServices(self): + self.assertTrue(hasattr(unittest_no_generic_services_pb2, "TestMessage")) + self.assertTrue(hasattr(unittest_no_generic_services_pb2, "FOO")) + self.assertTrue(hasattr(unittest_no_generic_services_pb2, "test_extension")) + + # Make sure unittest_no_generic_services_pb2 has no services subclassing + # Proto2 Service class. + if hasattr(unittest_no_generic_services_pb2, "TestService"): + self.assertFalse(issubclass(unittest_no_generic_services_pb2.TestService, + service.Service)) + + def testMessageTypesByName(self): + file_type = unittest_pb2.DESCRIPTOR + self.assertEqual( + unittest_pb2._TESTALLTYPES, + file_type.message_types_by_name[unittest_pb2._TESTALLTYPES.name]) + + # Nested messages shouldn't be included in the message_types_by_name + # dictionary (like in the C++ API). + self.assertFalse( + unittest_pb2._TESTALLTYPES_NESTEDMESSAGE.name in + file_type.message_types_by_name) + + def testPublicImports(self): + # Test public imports as embedded message. + all_type_proto = unittest_pb2.TestAllTypes() + self.assertEqual(0, all_type_proto.optional_public_import_message.e) + + # PublicImportMessage is actually defined in unittest_import_public_pb2 + # module, and is public imported by unittest_import_pb2 module. + public_import_proto = unittest_import_pb2.PublicImportMessage() + self.assertEqual(0, public_import_proto.e) + self.assertTrue(unittest_import_public_pb2.PublicImportMessage is + unittest_import_pb2.PublicImportMessage) + + def testBadIdentifiers(self): + # We're just testing that the code was imported without problems. + message = test_bad_identifiers_pb2.TestBadIdentifiers() + self.assertEqual(message.Extensions[test_bad_identifiers_pb2.message], + "foo") + self.assertEqual(message.Extensions[test_bad_identifiers_pb2.descriptor], + "bar") + self.assertEqual(message.Extensions[test_bad_identifiers_pb2.reflection], + "baz") + self.assertEqual(message.Extensions[test_bad_identifiers_pb2.service], + "qux") + +if __name__ == '__main__': + unittest.main() diff --git a/code/push/google/protobuf/internal/message_cpp_test.py b/code/push/google/protobuf/internal/message_cpp_test.py new file mode 100644 index 0000000..0d84b32 --- /dev/null +++ b/code/push/google/protobuf/internal/message_cpp_test.py @@ -0,0 +1,45 @@ +#! /usr/bin/python +# +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Tests for google.protobuf.internal.message_cpp.""" + +__author__ = 'shahms@google.com (Shahms King)' + +import os +os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp' + +import unittest +from google.protobuf.internal.message_test import * + + +if __name__ == '__main__': + unittest.main() diff --git a/code/push/google/protobuf/internal/message_factory_test.py b/code/push/google/protobuf/internal/message_factory_test.py new file mode 100644 index 0000000..0bc9be9 --- /dev/null +++ b/code/push/google/protobuf/internal/message_factory_test.py @@ -0,0 +1,113 @@ +#! /usr/bin/python +# +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Tests for google.protobuf.message_factory.""" + +__author__ = 'matthewtoia@google.com (Matt Toia)' + +import unittest +from google.protobuf import descriptor_pb2 +from google.protobuf.internal import factory_test1_pb2 +from google.protobuf.internal import factory_test2_pb2 +from google.protobuf import descriptor_database +from google.protobuf import descriptor_pool +from google.protobuf import message_factory + + +class MessageFactoryTest(unittest.TestCase): + + def setUp(self): + self.factory_test1_fd = descriptor_pb2.FileDescriptorProto.FromString( + factory_test1_pb2.DESCRIPTOR.serialized_pb) + self.factory_test2_fd = descriptor_pb2.FileDescriptorProto.FromString( + factory_test2_pb2.DESCRIPTOR.serialized_pb) + + def _ExerciseDynamicClass(self, cls): + msg = cls() + msg.mandatory = 42 + msg.nested_factory_2_enum = 0 + msg.nested_factory_2_message.value = 'nested message value' + msg.factory_1_message.factory_1_enum = 1 + msg.factory_1_message.nested_factory_1_enum = 0 + msg.factory_1_message.nested_factory_1_message.value = ( + 'nested message value') + msg.factory_1_message.scalar_value = 22 + msg.factory_1_message.list_value.extend(['one', 'two', 'three']) + msg.factory_1_message.list_value.append('four') + msg.factory_1_enum = 1 + msg.nested_factory_1_enum = 0 + msg.nested_factory_1_message.value = 'nested message value' + msg.circular_message.mandatory = 1 + msg.circular_message.circular_message.mandatory = 2 + msg.circular_message.scalar_value = 'one deep' + msg.scalar_value = 'zero deep' + msg.list_value.extend(['four', 'three', 'two']) + msg.list_value.append('one') + msg.grouped.add() + msg.grouped[0].part_1 = 'hello' + msg.grouped[0].part_2 = 'world' + msg.grouped.add(part_1='testing', part_2='123') + msg.loop.loop.mandatory = 2 + msg.loop.loop.loop.loop.mandatory = 4 + serialized = msg.SerializeToString() + converted = factory_test2_pb2.Factory2Message.FromString(serialized) + reserialized = converted.SerializeToString() + self.assertEquals(serialized, reserialized) + result = cls.FromString(reserialized) + self.assertEquals(msg, result) + + def testGetPrototype(self): + db = descriptor_database.DescriptorDatabase() + pool = descriptor_pool.DescriptorPool(db) + db.Add(self.factory_test1_fd) + db.Add(self.factory_test2_fd) + factory = message_factory.MessageFactory() + cls = factory.GetPrototype(pool.FindMessageTypeByName( + 'net.proto2.python.internal.Factory2Message')) + self.assertIsNot(cls, factory_test2_pb2.Factory2Message) + self._ExerciseDynamicClass(cls) + cls2 = factory.GetPrototype(pool.FindMessageTypeByName( + 'net.proto2.python.internal.Factory2Message')) + self.assertIs(cls, cls2) + + def testGetMessages(self): + messages = message_factory.GetMessages([self.factory_test2_fd, + self.factory_test1_fd]) + self.assertContainsSubset( + ['net.proto2.python.internal.Factory2Message', + 'net.proto2.python.internal.Factory1Message'], + messages.keys()) + self._ExerciseDynamicClass( + messages['net.proto2.python.internal.Factory2Message']) + +if __name__ == '__main__': + unittest.main() diff --git a/code/push/google/protobuf/internal/message_listener.py b/code/push/google/protobuf/internal/message_listener.py new file mode 100644 index 0000000..1080234 --- /dev/null +++ b/code/push/google/protobuf/internal/message_listener.py @@ -0,0 +1,78 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Defines a listener interface for observing certain +state transitions on Message objects. + +Also defines a null implementation of this interface. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + + +class MessageListener(object): + + """Listens for modifications made to a message. Meant to be registered via + Message._SetListener(). + + Attributes: + dirty: If True, then calling Modified() would be a no-op. This can be + used to avoid these calls entirely in the common case. + """ + + def Modified(self): + """Called every time the message is modified in such a way that the parent + message may need to be updated. This currently means either: + (a) The message was modified for the first time, so the parent message + should henceforth mark the message as present. + (b) The message's cached byte size became dirty -- i.e. the message was + modified for the first time after a previous call to ByteSize(). + Therefore the parent should also mark its byte size as dirty. + Note that (a) implies (b), since new objects start out with a client cached + size (zero). However, we document (a) explicitly because it is important. + + Modified() will *only* be called in response to one of these two events -- + not every time the sub-message is modified. + + Note that if the listener's |dirty| attribute is true, then calling + Modified at the moment would be a no-op, so it can be skipped. Performance- + sensitive callers should check this attribute directly before calling since + it will be true most of the time. + """ + + raise NotImplementedError + + +class NullMessageListener(object): + + """No-op MessageListener implementation.""" + + def Modified(self): + pass diff --git a/code/push/google/protobuf/internal/message_test.py b/code/push/google/protobuf/internal/message_test.py new file mode 100644 index 0000000..53e9d50 --- /dev/null +++ b/code/push/google/protobuf/internal/message_test.py @@ -0,0 +1,494 @@ +#! /usr/bin/python +# +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Tests python protocol buffers against the golden message. + +Note that the golden messages exercise every known field type, thus this +test ends up exercising and verifying nearly all of the parsing and +serialization code in the whole library. + +TODO(kenton): Merge with wire_format_test? It doesn't make a whole lot of +sense to call this a test of the "message" module, which only declares an +abstract interface. +""" + +__author__ = 'gps@google.com (Gregory P. Smith)' + +import copy +import math +import operator +import pickle + +import unittest +from google.protobuf import unittest_import_pb2 +from google.protobuf import unittest_pb2 +from google.protobuf.internal import api_implementation +from google.protobuf.internal import test_util +from google.protobuf import message + +# Python pre-2.6 does not have isinf() or isnan() functions, so we have +# to provide our own. +def isnan(val): + # NaN is never equal to itself. + return val != val +def isinf(val): + # Infinity times zero equals NaN. + return not isnan(val) and isnan(val * 0) +def IsPosInf(val): + return isinf(val) and (val > 0) +def IsNegInf(val): + return isinf(val) and (val < 0) + +class MessageTest(unittest.TestCase): + + def testGoldenMessage(self): + golden_data = test_util.GoldenFile('golden_message').read() + golden_message = unittest_pb2.TestAllTypes() + golden_message.ParseFromString(golden_data) + test_util.ExpectAllFieldsSet(self, golden_message) + self.assertEqual(golden_data, golden_message.SerializeToString()) + golden_copy = copy.deepcopy(golden_message) + self.assertEqual(golden_data, golden_copy.SerializeToString()) + + def testGoldenExtensions(self): + golden_data = test_util.GoldenFile('golden_message').read() + golden_message = unittest_pb2.TestAllExtensions() + golden_message.ParseFromString(golden_data) + all_set = unittest_pb2.TestAllExtensions() + test_util.SetAllExtensions(all_set) + self.assertEquals(all_set, golden_message) + self.assertEqual(golden_data, golden_message.SerializeToString()) + golden_copy = copy.deepcopy(golden_message) + self.assertEqual(golden_data, golden_copy.SerializeToString()) + + def testGoldenPackedMessage(self): + golden_data = test_util.GoldenFile('golden_packed_fields_message').read() + golden_message = unittest_pb2.TestPackedTypes() + golden_message.ParseFromString(golden_data) + all_set = unittest_pb2.TestPackedTypes() + test_util.SetAllPackedFields(all_set) + self.assertEquals(all_set, golden_message) + self.assertEqual(golden_data, all_set.SerializeToString()) + golden_copy = copy.deepcopy(golden_message) + self.assertEqual(golden_data, golden_copy.SerializeToString()) + + def testGoldenPackedExtensions(self): + golden_data = test_util.GoldenFile('golden_packed_fields_message').read() + golden_message = unittest_pb2.TestPackedExtensions() + golden_message.ParseFromString(golden_data) + all_set = unittest_pb2.TestPackedExtensions() + test_util.SetAllPackedExtensions(all_set) + self.assertEquals(all_set, golden_message) + self.assertEqual(golden_data, all_set.SerializeToString()) + golden_copy = copy.deepcopy(golden_message) + self.assertEqual(golden_data, golden_copy.SerializeToString()) + + def testPickleSupport(self): + golden_data = test_util.GoldenFile('golden_message').read() + golden_message = unittest_pb2.TestAllTypes() + golden_message.ParseFromString(golden_data) + pickled_message = pickle.dumps(golden_message) + + unpickled_message = pickle.loads(pickled_message) + self.assertEquals(unpickled_message, golden_message) + + def testPickleIncompleteProto(self): + golden_message = unittest_pb2.TestRequired(a=1) + pickled_message = pickle.dumps(golden_message) + + unpickled_message = pickle.loads(pickled_message) + self.assertEquals(unpickled_message, golden_message) + self.assertEquals(unpickled_message.a, 1) + # This is still an incomplete proto - so serializing should fail + self.assertRaises(message.EncodeError, unpickled_message.SerializeToString) + + def testPositiveInfinity(self): + golden_data = ('\x5D\x00\x00\x80\x7F' + '\x61\x00\x00\x00\x00\x00\x00\xF0\x7F' + '\xCD\x02\x00\x00\x80\x7F' + '\xD1\x02\x00\x00\x00\x00\x00\x00\xF0\x7F') + golden_message = unittest_pb2.TestAllTypes() + golden_message.ParseFromString(golden_data) + self.assertTrue(IsPosInf(golden_message.optional_float)) + self.assertTrue(IsPosInf(golden_message.optional_double)) + self.assertTrue(IsPosInf(golden_message.repeated_float[0])) + self.assertTrue(IsPosInf(golden_message.repeated_double[0])) + self.assertEqual(golden_data, golden_message.SerializeToString()) + + def testNegativeInfinity(self): + golden_data = ('\x5D\x00\x00\x80\xFF' + '\x61\x00\x00\x00\x00\x00\x00\xF0\xFF' + '\xCD\x02\x00\x00\x80\xFF' + '\xD1\x02\x00\x00\x00\x00\x00\x00\xF0\xFF') + golden_message = unittest_pb2.TestAllTypes() + golden_message.ParseFromString(golden_data) + self.assertTrue(IsNegInf(golden_message.optional_float)) + self.assertTrue(IsNegInf(golden_message.optional_double)) + self.assertTrue(IsNegInf(golden_message.repeated_float[0])) + self.assertTrue(IsNegInf(golden_message.repeated_double[0])) + self.assertEqual(golden_data, golden_message.SerializeToString()) + + def testNotANumber(self): + golden_data = ('\x5D\x00\x00\xC0\x7F' + '\x61\x00\x00\x00\x00\x00\x00\xF8\x7F' + '\xCD\x02\x00\x00\xC0\x7F' + '\xD1\x02\x00\x00\x00\x00\x00\x00\xF8\x7F') + golden_message = unittest_pb2.TestAllTypes() + golden_message.ParseFromString(golden_data) + self.assertTrue(isnan(golden_message.optional_float)) + self.assertTrue(isnan(golden_message.optional_double)) + self.assertTrue(isnan(golden_message.repeated_float[0])) + self.assertTrue(isnan(golden_message.repeated_double[0])) + + # The protocol buffer may serialize to any one of multiple different + # representations of a NaN. Rather than verify a specific representation, + # verify the serialized string can be converted into a correctly + # behaving protocol buffer. + serialized = golden_message.SerializeToString() + message = unittest_pb2.TestAllTypes() + message.ParseFromString(serialized) + self.assertTrue(isnan(message.optional_float)) + self.assertTrue(isnan(message.optional_double)) + self.assertTrue(isnan(message.repeated_float[0])) + self.assertTrue(isnan(message.repeated_double[0])) + + def testPositiveInfinityPacked(self): + golden_data = ('\xA2\x06\x04\x00\x00\x80\x7F' + '\xAA\x06\x08\x00\x00\x00\x00\x00\x00\xF0\x7F') + golden_message = unittest_pb2.TestPackedTypes() + golden_message.ParseFromString(golden_data) + self.assertTrue(IsPosInf(golden_message.packed_float[0])) + self.assertTrue(IsPosInf(golden_message.packed_double[0])) + self.assertEqual(golden_data, golden_message.SerializeToString()) + + def testNegativeInfinityPacked(self): + golden_data = ('\xA2\x06\x04\x00\x00\x80\xFF' + '\xAA\x06\x08\x00\x00\x00\x00\x00\x00\xF0\xFF') + golden_message = unittest_pb2.TestPackedTypes() + golden_message.ParseFromString(golden_data) + self.assertTrue(IsNegInf(golden_message.packed_float[0])) + self.assertTrue(IsNegInf(golden_message.packed_double[0])) + self.assertEqual(golden_data, golden_message.SerializeToString()) + + def testNotANumberPacked(self): + golden_data = ('\xA2\x06\x04\x00\x00\xC0\x7F' + '\xAA\x06\x08\x00\x00\x00\x00\x00\x00\xF8\x7F') + golden_message = unittest_pb2.TestPackedTypes() + golden_message.ParseFromString(golden_data) + self.assertTrue(isnan(golden_message.packed_float[0])) + self.assertTrue(isnan(golden_message.packed_double[0])) + + serialized = golden_message.SerializeToString() + message = unittest_pb2.TestPackedTypes() + message.ParseFromString(serialized) + self.assertTrue(isnan(message.packed_float[0])) + self.assertTrue(isnan(message.packed_double[0])) + + def testExtremeFloatValues(self): + message = unittest_pb2.TestAllTypes() + + # Most positive exponent, no significand bits set. + kMostPosExponentNoSigBits = math.pow(2, 127) + message.optional_float = kMostPosExponentNoSigBits + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_float == kMostPosExponentNoSigBits) + + # Most positive exponent, one significand bit set. + kMostPosExponentOneSigBit = 1.5 * math.pow(2, 127) + message.optional_float = kMostPosExponentOneSigBit + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_float == kMostPosExponentOneSigBit) + + # Repeat last two cases with values of same magnitude, but negative. + message.optional_float = -kMostPosExponentNoSigBits + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_float == -kMostPosExponentNoSigBits) + + message.optional_float = -kMostPosExponentOneSigBit + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_float == -kMostPosExponentOneSigBit) + + # Most negative exponent, no significand bits set. + kMostNegExponentNoSigBits = math.pow(2, -127) + message.optional_float = kMostNegExponentNoSigBits + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_float == kMostNegExponentNoSigBits) + + # Most negative exponent, one significand bit set. + kMostNegExponentOneSigBit = 1.5 * math.pow(2, -127) + message.optional_float = kMostNegExponentOneSigBit + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_float == kMostNegExponentOneSigBit) + + # Repeat last two cases with values of the same magnitude, but negative. + message.optional_float = -kMostNegExponentNoSigBits + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_float == -kMostNegExponentNoSigBits) + + message.optional_float = -kMostNegExponentOneSigBit + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_float == -kMostNegExponentOneSigBit) + + def testExtremeDoubleValues(self): + message = unittest_pb2.TestAllTypes() + + # Most positive exponent, no significand bits set. + kMostPosExponentNoSigBits = math.pow(2, 1023) + message.optional_double = kMostPosExponentNoSigBits + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_double == kMostPosExponentNoSigBits) + + # Most positive exponent, one significand bit set. + kMostPosExponentOneSigBit = 1.5 * math.pow(2, 1023) + message.optional_double = kMostPosExponentOneSigBit + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_double == kMostPosExponentOneSigBit) + + # Repeat last two cases with values of same magnitude, but negative. + message.optional_double = -kMostPosExponentNoSigBits + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_double == -kMostPosExponentNoSigBits) + + message.optional_double = -kMostPosExponentOneSigBit + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_double == -kMostPosExponentOneSigBit) + + # Most negative exponent, no significand bits set. + kMostNegExponentNoSigBits = math.pow(2, -1023) + message.optional_double = kMostNegExponentNoSigBits + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_double == kMostNegExponentNoSigBits) + + # Most negative exponent, one significand bit set. + kMostNegExponentOneSigBit = 1.5 * math.pow(2, -1023) + message.optional_double = kMostNegExponentOneSigBit + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_double == kMostNegExponentOneSigBit) + + # Repeat last two cases with values of the same magnitude, but negative. + message.optional_double = -kMostNegExponentNoSigBits + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_double == -kMostNegExponentNoSigBits) + + message.optional_double = -kMostNegExponentOneSigBit + message.ParseFromString(message.SerializeToString()) + self.assertTrue(message.optional_double == -kMostNegExponentOneSigBit) + + def testSortingRepeatedScalarFieldsDefaultComparator(self): + """Check some different types with the default comparator.""" + message = unittest_pb2.TestAllTypes() + + # TODO(mattp): would testing more scalar types strengthen test? + message.repeated_int32.append(1) + message.repeated_int32.append(3) + message.repeated_int32.append(2) + message.repeated_int32.sort() + self.assertEqual(message.repeated_int32[0], 1) + self.assertEqual(message.repeated_int32[1], 2) + self.assertEqual(message.repeated_int32[2], 3) + + message.repeated_float.append(1.1) + message.repeated_float.append(1.3) + message.repeated_float.append(1.2) + message.repeated_float.sort() + self.assertAlmostEqual(message.repeated_float[0], 1.1) + self.assertAlmostEqual(message.repeated_float[1], 1.2) + self.assertAlmostEqual(message.repeated_float[2], 1.3) + + message.repeated_string.append('a') + message.repeated_string.append('c') + message.repeated_string.append('b') + message.repeated_string.sort() + self.assertEqual(message.repeated_string[0], 'a') + self.assertEqual(message.repeated_string[1], 'b') + self.assertEqual(message.repeated_string[2], 'c') + + message.repeated_bytes.append('a') + message.repeated_bytes.append('c') + message.repeated_bytes.append('b') + message.repeated_bytes.sort() + self.assertEqual(message.repeated_bytes[0], 'a') + self.assertEqual(message.repeated_bytes[1], 'b') + self.assertEqual(message.repeated_bytes[2], 'c') + + def testSortingRepeatedScalarFieldsCustomComparator(self): + """Check some different types with custom comparator.""" + message = unittest_pb2.TestAllTypes() + + message.repeated_int32.append(-3) + message.repeated_int32.append(-2) + message.repeated_int32.append(-1) + message.repeated_int32.sort(lambda x,y: cmp(abs(x), abs(y))) + self.assertEqual(message.repeated_int32[0], -1) + self.assertEqual(message.repeated_int32[1], -2) + self.assertEqual(message.repeated_int32[2], -3) + + message.repeated_string.append('aaa') + message.repeated_string.append('bb') + message.repeated_string.append('c') + message.repeated_string.sort(lambda x,y: cmp(len(x), len(y))) + self.assertEqual(message.repeated_string[0], 'c') + self.assertEqual(message.repeated_string[1], 'bb') + self.assertEqual(message.repeated_string[2], 'aaa') + + def testSortingRepeatedCompositeFieldsCustomComparator(self): + """Check passing a custom comparator to sort a repeated composite field.""" + message = unittest_pb2.TestAllTypes() + + message.repeated_nested_message.add().bb = 1 + message.repeated_nested_message.add().bb = 3 + message.repeated_nested_message.add().bb = 2 + message.repeated_nested_message.add().bb = 6 + message.repeated_nested_message.add().bb = 5 + message.repeated_nested_message.add().bb = 4 + message.repeated_nested_message.sort(lambda x,y: cmp(x.bb, y.bb)) + self.assertEqual(message.repeated_nested_message[0].bb, 1) + self.assertEqual(message.repeated_nested_message[1].bb, 2) + self.assertEqual(message.repeated_nested_message[2].bb, 3) + self.assertEqual(message.repeated_nested_message[3].bb, 4) + self.assertEqual(message.repeated_nested_message[4].bb, 5) + self.assertEqual(message.repeated_nested_message[5].bb, 6) + + def testRepeatedCompositeFieldSortArguments(self): + """Check sorting a repeated composite field using list.sort() arguments.""" + message = unittest_pb2.TestAllTypes() + + get_bb = operator.attrgetter('bb') + cmp_bb = lambda a, b: cmp(a.bb, b.bb) + message.repeated_nested_message.add().bb = 1 + message.repeated_nested_message.add().bb = 3 + message.repeated_nested_message.add().bb = 2 + message.repeated_nested_message.add().bb = 6 + message.repeated_nested_message.add().bb = 5 + message.repeated_nested_message.add().bb = 4 + message.repeated_nested_message.sort(key=get_bb) + self.assertEqual([k.bb for k in message.repeated_nested_message], + [1, 2, 3, 4, 5, 6]) + message.repeated_nested_message.sort(key=get_bb, reverse=True) + self.assertEqual([k.bb for k in message.repeated_nested_message], + [6, 5, 4, 3, 2, 1]) + message.repeated_nested_message.sort(sort_function=cmp_bb) + self.assertEqual([k.bb for k in message.repeated_nested_message], + [1, 2, 3, 4, 5, 6]) + message.repeated_nested_message.sort(cmp=cmp_bb, reverse=True) + self.assertEqual([k.bb for k in message.repeated_nested_message], + [6, 5, 4, 3, 2, 1]) + + def testRepeatedScalarFieldSortArguments(self): + """Check sorting a scalar field using list.sort() arguments.""" + message = unittest_pb2.TestAllTypes() + + abs_cmp = lambda a, b: cmp(abs(a), abs(b)) + message.repeated_int32.append(-3) + message.repeated_int32.append(-2) + message.repeated_int32.append(-1) + message.repeated_int32.sort(key=abs) + self.assertEqual(list(message.repeated_int32), [-1, -2, -3]) + message.repeated_int32.sort(key=abs, reverse=True) + self.assertEqual(list(message.repeated_int32), [-3, -2, -1]) + message.repeated_int32.sort(sort_function=abs_cmp) + self.assertEqual(list(message.repeated_int32), [-1, -2, -3]) + message.repeated_int32.sort(cmp=abs_cmp, reverse=True) + self.assertEqual(list(message.repeated_int32), [-3, -2, -1]) + + len_cmp = lambda a, b: cmp(len(a), len(b)) + message.repeated_string.append('aaa') + message.repeated_string.append('bb') + message.repeated_string.append('c') + message.repeated_string.sort(key=len) + self.assertEqual(list(message.repeated_string), ['c', 'bb', 'aaa']) + message.repeated_string.sort(key=len, reverse=True) + self.assertEqual(list(message.repeated_string), ['aaa', 'bb', 'c']) + message.repeated_string.sort(sort_function=len_cmp) + self.assertEqual(list(message.repeated_string), ['c', 'bb', 'aaa']) + message.repeated_string.sort(cmp=len_cmp, reverse=True) + self.assertEqual(list(message.repeated_string), ['aaa', 'bb', 'c']) + + def testParsingMerge(self): + """Check the merge behavior when a required or optional field appears + multiple times in the input.""" + messages = [ + unittest_pb2.TestAllTypes(), + unittest_pb2.TestAllTypes(), + unittest_pb2.TestAllTypes() ] + messages[0].optional_int32 = 1 + messages[1].optional_int64 = 2 + messages[2].optional_int32 = 3 + messages[2].optional_string = 'hello' + + merged_message = unittest_pb2.TestAllTypes() + merged_message.optional_int32 = 3 + merged_message.optional_int64 = 2 + merged_message.optional_string = 'hello' + + generator = unittest_pb2.TestParsingMerge.RepeatedFieldsGenerator() + generator.field1.extend(messages) + generator.field2.extend(messages) + generator.field3.extend(messages) + generator.ext1.extend(messages) + generator.ext2.extend(messages) + generator.group1.add().field1.MergeFrom(messages[0]) + generator.group1.add().field1.MergeFrom(messages[1]) + generator.group1.add().field1.MergeFrom(messages[2]) + generator.group2.add().field1.MergeFrom(messages[0]) + generator.group2.add().field1.MergeFrom(messages[1]) + generator.group2.add().field1.MergeFrom(messages[2]) + + data = generator.SerializeToString() + parsing_merge = unittest_pb2.TestParsingMerge() + parsing_merge.ParseFromString(data) + + # Required and optional fields should be merged. + self.assertEqual(parsing_merge.required_all_types, merged_message) + self.assertEqual(parsing_merge.optional_all_types, merged_message) + self.assertEqual(parsing_merge.optionalgroup.optional_group_all_types, + merged_message) + self.assertEqual(parsing_merge.Extensions[ + unittest_pb2.TestParsingMerge.optional_ext], + merged_message) + + # Repeated fields should not be merged. + self.assertEqual(len(parsing_merge.repeated_all_types), 3) + self.assertEqual(len(parsing_merge.repeatedgroup), 3) + self.assertEqual(len(parsing_merge.Extensions[ + unittest_pb2.TestParsingMerge.repeated_ext]), 3) + + + def testSortEmptyRepeatedCompositeContainer(self): + """Exercise a scenario that has led to segfaults in the past. + """ + m = unittest_pb2.TestAllTypes() + m.repeated_nested_message.sort() + + +if __name__ == '__main__': + unittest.main() diff --git a/code/push/google/protobuf/internal/more_extensions.proto b/code/push/google/protobuf/internal/more_extensions.proto new file mode 100644 index 0000000..e2d9701 --- /dev/null +++ b/code/push/google/protobuf/internal/more_extensions.proto @@ -0,0 +1,58 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: robinson@google.com (Will Robinson) + + +package google.protobuf.internal; + + +message TopLevelMessage { + optional ExtendedMessage submessage = 1; +} + + +message ExtendedMessage { + extensions 1 to max; +} + + +message ForeignMessage { + optional int32 foreign_message_int = 1; +} + + +extend ExtendedMessage { + optional int32 optional_int_extension = 1; + optional ForeignMessage optional_message_extension = 2; + + repeated int32 repeated_int_extension = 3; + repeated ForeignMessage repeated_message_extension = 4; +} diff --git a/code/push/google/protobuf/internal/more_extensions_dynamic.proto b/code/push/google/protobuf/internal/more_extensions_dynamic.proto new file mode 100644 index 0000000..df98ac4 --- /dev/null +++ b/code/push/google/protobuf/internal/more_extensions_dynamic.proto @@ -0,0 +1,49 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: jasonh@google.com (Jason Hsueh) +// +// This file is used to test a corner case in the CPP implementation where the +// generated C++ type is available for the extendee, but the extension is +// defined in a file whose C++ type is not in the binary. + + +import "google/protobuf/internal/more_extensions.proto"; + +package google.protobuf.internal; + +message DynamicMessageType { + optional int32 a = 1; +} + +extend ExtendedMessage { + optional int32 dynamic_int32_extension = 100; + optional DynamicMessageType dynamic_message_extension = 101; +} diff --git a/code/push/google/protobuf/internal/more_extensions_dynamic_pb2.py b/code/push/google/protobuf/internal/more_extensions_dynamic_pb2.py new file mode 100644 index 0000000..b9d331f --- /dev/null +++ b/code/push/google/protobuf/internal/more_extensions_dynamic_pb2.py @@ -0,0 +1,77 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/internal/more_extensions_dynamic.proto + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + + +import google.protobuf.internal.more_extensions_pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/internal/more_extensions_dynamic.proto', + package='google.protobuf.internal', + serialized_pb='\n6google/protobuf/internal/more_extensions_dynamic.proto\x12\x18google.protobuf.internal\x1a.google/protobuf/internal/more_extensions.proto\"\x1f\n\x12\x44ynamicMessageType\x12\t\n\x01\x61\x18\x01 \x01(\x05:J\n\x17\x64ynamic_int32_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x64 \x01(\x05:z\n\x19\x64ynamic_message_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x65 \x01(\x0b\x32,.google.protobuf.internal.DynamicMessageType') + + +DYNAMIC_INT32_EXTENSION_FIELD_NUMBER = 100 +dynamic_int32_extension = _descriptor.FieldDescriptor( + name='dynamic_int32_extension', full_name='google.protobuf.internal.dynamic_int32_extension', index=0, + number=100, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DYNAMIC_MESSAGE_EXTENSION_FIELD_NUMBER = 101 +dynamic_message_extension = _descriptor.FieldDescriptor( + name='dynamic_message_extension', full_name='google.protobuf.internal.dynamic_message_extension', index=1, + number=101, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) + + +_DYNAMICMESSAGETYPE = _descriptor.Descriptor( + name='DynamicMessageType', + full_name='google.protobuf.internal.DynamicMessageType', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='google.protobuf.internal.DynamicMessageType.a', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=132, + serialized_end=163, +) + +DESCRIPTOR.message_types_by_name['DynamicMessageType'] = _DYNAMICMESSAGETYPE + +class DynamicMessageType(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _DYNAMICMESSAGETYPE + + # @@protoc_insertion_point(class_scope:google.protobuf.internal.DynamicMessageType) + +google.protobuf.internal.more_extensions_pb2.ExtendedMessage.RegisterExtension(dynamic_int32_extension) +dynamic_message_extension.message_type = _DYNAMICMESSAGETYPE +google.protobuf.internal.more_extensions_pb2.ExtendedMessage.RegisterExtension(dynamic_message_extension) + +# @@protoc_insertion_point(module_scope) diff --git a/code/push/google/protobuf/internal/more_extensions_pb2.py b/code/push/google/protobuf/internal/more_extensions_pb2.py new file mode 100644 index 0000000..03594bb --- /dev/null +++ b/code/push/google/protobuf/internal/more_extensions_pb2.py @@ -0,0 +1,159 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/internal/more_extensions.proto + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/internal/more_extensions.proto', + package='google.protobuf.internal', + serialized_pb='\n.google/protobuf/internal/more_extensions.proto\x12\x18google.protobuf.internal\"P\n\x0fTopLevelMessage\x12=\n\nsubmessage\x18\x01 \x01(\x0b\x32).google.protobuf.internal.ExtendedMessage\"\x1b\n\x0f\x45xtendedMessage*\x08\x08\x01\x10\x80\x80\x80\x80\x02\"-\n\x0e\x46oreignMessage\x12\x1b\n\x13\x66oreign_message_int\x18\x01 \x01(\x05:I\n\x16optional_int_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x01 \x01(\x05:w\n\x1aoptional_message_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x02 \x01(\x0b\x32(.google.protobuf.internal.ForeignMessage:I\n\x16repeated_int_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x03 \x03(\x05:w\n\x1arepeated_message_extension\x12).google.protobuf.internal.ExtendedMessage\x18\x04 \x03(\x0b\x32(.google.protobuf.internal.ForeignMessage') + + +OPTIONAL_INT_EXTENSION_FIELD_NUMBER = 1 +optional_int_extension = _descriptor.FieldDescriptor( + name='optional_int_extension', full_name='google.protobuf.internal.optional_int_extension', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_MESSAGE_EXTENSION_FIELD_NUMBER = 2 +optional_message_extension = _descriptor.FieldDescriptor( + name='optional_message_extension', full_name='google.protobuf.internal.optional_message_extension', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_INT_EXTENSION_FIELD_NUMBER = 3 +repeated_int_extension = _descriptor.FieldDescriptor( + name='repeated_int_extension', full_name='google.protobuf.internal.repeated_int_extension', index=2, + number=3, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_MESSAGE_EXTENSION_FIELD_NUMBER = 4 +repeated_message_extension = _descriptor.FieldDescriptor( + name='repeated_message_extension', full_name='google.protobuf.internal.repeated_message_extension', index=3, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) + + +_TOPLEVELMESSAGE = _descriptor.Descriptor( + name='TopLevelMessage', + full_name='google.protobuf.internal.TopLevelMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='submessage', full_name='google.protobuf.internal.TopLevelMessage.submessage', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=76, + serialized_end=156, +) + + +_EXTENDEDMESSAGE = _descriptor.Descriptor( + name='ExtendedMessage', + full_name='google.protobuf.internal.ExtendedMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(1, 536870912), ], + serialized_start=158, + serialized_end=185, +) + + +_FOREIGNMESSAGE = _descriptor.Descriptor( + name='ForeignMessage', + full_name='google.protobuf.internal.ForeignMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='foreign_message_int', full_name='google.protobuf.internal.ForeignMessage.foreign_message_int', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=187, + serialized_end=232, +) + +_TOPLEVELMESSAGE.fields_by_name['submessage'].message_type = _EXTENDEDMESSAGE +DESCRIPTOR.message_types_by_name['TopLevelMessage'] = _TOPLEVELMESSAGE +DESCRIPTOR.message_types_by_name['ExtendedMessage'] = _EXTENDEDMESSAGE +DESCRIPTOR.message_types_by_name['ForeignMessage'] = _FOREIGNMESSAGE + +class TopLevelMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TOPLEVELMESSAGE + + # @@protoc_insertion_point(class_scope:google.protobuf.internal.TopLevelMessage) + +class ExtendedMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _EXTENDEDMESSAGE + + # @@protoc_insertion_point(class_scope:google.protobuf.internal.ExtendedMessage) + +class ForeignMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _FOREIGNMESSAGE + + # @@protoc_insertion_point(class_scope:google.protobuf.internal.ForeignMessage) + +ExtendedMessage.RegisterExtension(optional_int_extension) +optional_message_extension.message_type = _FOREIGNMESSAGE +ExtendedMessage.RegisterExtension(optional_message_extension) +ExtendedMessage.RegisterExtension(repeated_int_extension) +repeated_message_extension.message_type = _FOREIGNMESSAGE +ExtendedMessage.RegisterExtension(repeated_message_extension) + +# @@protoc_insertion_point(module_scope) diff --git a/code/push/google/protobuf/internal/more_messages.proto b/code/push/google/protobuf/internal/more_messages.proto new file mode 100644 index 0000000..c701b44 --- /dev/null +++ b/code/push/google/protobuf/internal/more_messages.proto @@ -0,0 +1,51 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: robinson@google.com (Will Robinson) + + +package google.protobuf.internal; + +// A message where tag numbers are listed out of order, to allow us to test our +// canonicalization of serialized output, which should always be in tag order. +// We also mix in some extensions for extra fun. +message OutOfOrderFields { + optional sint32 optional_sint32 = 5; + extensions 4 to 4; + optional uint32 optional_uint32 = 3; + extensions 2 to 2; + optional int32 optional_int32 = 1; +}; + + +extend OutOfOrderFields { + optional uint64 optional_uint64 = 4; + optional int64 optional_int64 = 2; +} diff --git a/code/push/google/protobuf/internal/more_messages_pb2.py b/code/push/google/protobuf/internal/more_messages_pb2.py new file mode 100644 index 0000000..41f6ba3 --- /dev/null +++ b/code/push/google/protobuf/internal/more_messages_pb2.py @@ -0,0 +1,89 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/internal/more_messages.proto + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/internal/more_messages.proto', + package='google.protobuf.internal', + serialized_pb='\n,google/protobuf/internal/more_messages.proto\x12\x18google.protobuf.internal\"h\n\x10OutOfOrderFields\x12\x17\n\x0foptional_sint32\x18\x05 \x01(\x11\x12\x17\n\x0foptional_uint32\x18\x03 \x01(\r\x12\x16\n\x0eoptional_int32\x18\x01 \x01(\x05*\x04\x08\x04\x10\x05*\x04\x08\x02\x10\x03:C\n\x0foptional_uint64\x12*.google.protobuf.internal.OutOfOrderFields\x18\x04 \x01(\x04:B\n\x0eoptional_int64\x12*.google.protobuf.internal.OutOfOrderFields\x18\x02 \x01(\x03') + + +OPTIONAL_UINT64_FIELD_NUMBER = 4 +optional_uint64 = _descriptor.FieldDescriptor( + name='optional_uint64', full_name='google.protobuf.internal.optional_uint64', index=0, + number=4, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_INT64_FIELD_NUMBER = 2 +optional_int64 = _descriptor.FieldDescriptor( + name='optional_int64', full_name='google.protobuf.internal.optional_int64', index=1, + number=2, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) + + +_OUTOFORDERFIELDS = _descriptor.Descriptor( + name='OutOfOrderFields', + full_name='google.protobuf.internal.OutOfOrderFields', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='optional_sint32', full_name='google.protobuf.internal.OutOfOrderFields.optional_sint32', index=0, + number=5, type=17, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_uint32', full_name='google.protobuf.internal.OutOfOrderFields.optional_uint32', index=1, + number=3, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_int32', full_name='google.protobuf.internal.OutOfOrderFields.optional_int32', index=2, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(4, 5), (2, 3), ], + serialized_start=74, + serialized_end=178, +) + +DESCRIPTOR.message_types_by_name['OutOfOrderFields'] = _OUTOFORDERFIELDS + +class OutOfOrderFields(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _OUTOFORDERFIELDS + + # @@protoc_insertion_point(class_scope:google.protobuf.internal.OutOfOrderFields) + +OutOfOrderFields.RegisterExtension(optional_uint64) +OutOfOrderFields.RegisterExtension(optional_int64) + +# @@protoc_insertion_point(module_scope) diff --git a/code/push/google/protobuf/internal/python_message.py b/code/push/google/protobuf/internal/python_message.py new file mode 100644 index 0000000..b006434 --- /dev/null +++ b/code/push/google/protobuf/internal/python_message.py @@ -0,0 +1,1150 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# This code is meant to work on Python 2.4 and above only. +# +# TODO(robinson): Helpers for verbose, common checks like seeing if a +# descriptor's cpp_type is CPPTYPE_MESSAGE. + +"""Contains a metaclass and helper functions used to create +protocol message classes from Descriptor objects at runtime. + +Recall that a metaclass is the "type" of a class. +(A class is to a metaclass what an instance is to a class.) + +In this case, we use the GeneratedProtocolMessageType metaclass +to inject all the useful functionality into the classes +output by the protocol compiler at compile-time. + +The upshot of all this is that the real implementation +details for ALL pure-Python protocol buffers are *here in +this file*. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + +try: + from cStringIO import StringIO +except ImportError: + from StringIO import StringIO +import copy_reg +import struct +import weakref + +# We use "as" to avoid name collisions with variables. +from push.google.protobuf.internal import containers +from push.google.protobuf.internal import decoder +from push.google.protobuf.internal import encoder +from push.google.protobuf.internal import enum_type_wrapper +from push.google.protobuf.internal import message_listener as message_listener_mod +from push.google.protobuf.internal import type_checkers +from push.google.protobuf.internal import wire_format +from push.google.protobuf import descriptor as descriptor_mod +from push.google.protobuf import message as message_mod +from push.google.protobuf import text_format + +_FieldDescriptor = descriptor_mod.FieldDescriptor + + +def NewMessage(bases, descriptor, dictionary): + _AddClassAttributesForNestedExtensions(descriptor, dictionary) + _AddSlots(descriptor, dictionary) + return bases + + +def InitMessage(descriptor, cls): + cls._decoders_by_tag = {} + cls._extensions_by_name = {} + cls._extensions_by_number = {} + if (descriptor.has_options and + descriptor.GetOptions().message_set_wire_format): + cls._decoders_by_tag[decoder.MESSAGE_SET_ITEM_TAG] = ( + decoder.MessageSetItemDecoder(cls._extensions_by_number)) + + # Attach stuff to each FieldDescriptor for quick lookup later on. + for field in descriptor.fields: + _AttachFieldHelpers(cls, field) + + _AddEnumValues(descriptor, cls) + _AddInitMethod(descriptor, cls) + _AddPropertiesForFields(descriptor, cls) + _AddPropertiesForExtensions(descriptor, cls) + _AddStaticMethods(cls) + _AddMessageMethods(descriptor, cls) + _AddPrivateHelperMethods(cls) + copy_reg.pickle(cls, lambda obj: (cls, (), obj.__getstate__())) + + +# Stateless helpers for GeneratedProtocolMessageType below. +# Outside clients should not access these directly. +# +# I opted not to make any of these methods on the metaclass, to make it more +# clear that I'm not really using any state there and to keep clients from +# thinking that they have direct access to these construction helpers. + + +def _PropertyName(proto_field_name): + """Returns the name of the public property attribute which + clients can use to get and (in some cases) set the value + of a protocol message field. + + Args: + proto_field_name: The protocol message field name, exactly + as it appears (or would appear) in a .proto file. + """ + # TODO(robinson): Escape Python keywords (e.g., yield), and test this support. + # nnorwitz makes my day by writing: + # """ + # FYI. See the keyword module in the stdlib. This could be as simple as: + # + # if keyword.iskeyword(proto_field_name): + # return proto_field_name + "_" + # return proto_field_name + # """ + # Kenton says: The above is a BAD IDEA. People rely on being able to use + # getattr() and setattr() to reflectively manipulate field values. If we + # rename the properties, then every such user has to also make sure to apply + # the same transformation. Note that currently if you name a field "yield", + # you can still access it just fine using getattr/setattr -- it's not even + # that cumbersome to do so. + # TODO(kenton): Remove this method entirely if/when everyone agrees with my + # position. + return proto_field_name + + +def _VerifyExtensionHandle(message, extension_handle): + """Verify that the given extension handle is valid.""" + + if not isinstance(extension_handle, _FieldDescriptor): + raise KeyError('HasExtension() expects an extension handle, got: %s' % + extension_handle) + + if not extension_handle.is_extension: + raise KeyError('"%s" is not an extension.' % extension_handle.full_name) + + if not extension_handle.containing_type: + raise KeyError('"%s" is missing a containing_type.' + % extension_handle.full_name) + + if extension_handle.containing_type is not message.DESCRIPTOR: + raise KeyError('Extension "%s" extends message type "%s", but this ' + 'message is of type "%s".' % + (extension_handle.full_name, + extension_handle.containing_type.full_name, + message.DESCRIPTOR.full_name)) + + +def _AddSlots(message_descriptor, dictionary): + """Adds a __slots__ entry to dictionary, containing the names of all valid + attributes for this message type. + + Args: + message_descriptor: A Descriptor instance describing this message type. + dictionary: Class dictionary to which we'll add a '__slots__' entry. + """ + dictionary['__slots__'] = ['_cached_byte_size', + '_cached_byte_size_dirty', + '_fields', + '_unknown_fields', + '_is_present_in_parent', + '_listener', + '_listener_for_children', + '__weakref__'] + + +def _IsMessageSetExtension(field): + return (field.is_extension and + field.containing_type.has_options and + field.containing_type.GetOptions().message_set_wire_format and + field.type == _FieldDescriptor.TYPE_MESSAGE and + field.message_type == field.extension_scope and + field.label == _FieldDescriptor.LABEL_OPTIONAL) + + +def _AttachFieldHelpers(cls, field_descriptor): + is_repeated = (field_descriptor.label == _FieldDescriptor.LABEL_REPEATED) + is_packed = (field_descriptor.has_options and + field_descriptor.GetOptions().packed) + + if _IsMessageSetExtension(field_descriptor): + field_encoder = encoder.MessageSetItemEncoder(field_descriptor.number) + sizer = encoder.MessageSetItemSizer(field_descriptor.number) + else: + field_encoder = type_checkers.TYPE_TO_ENCODER[field_descriptor.type]( + field_descriptor.number, is_repeated, is_packed) + sizer = type_checkers.TYPE_TO_SIZER[field_descriptor.type]( + field_descriptor.number, is_repeated, is_packed) + + field_descriptor._encoder = field_encoder + field_descriptor._sizer = sizer + field_descriptor._default_constructor = _DefaultValueConstructorForField( + field_descriptor) + + def AddDecoder(wiretype, is_packed): + tag_bytes = encoder.TagBytes(field_descriptor.number, wiretype) + cls._decoders_by_tag[tag_bytes] = ( + type_checkers.TYPE_TO_DECODER[field_descriptor.type]( + field_descriptor.number, is_repeated, is_packed, + field_descriptor, field_descriptor._default_constructor)) + + AddDecoder(type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type], + False) + + if is_repeated and wire_format.IsTypePackable(field_descriptor.type): + # To support wire compatibility of adding packed = true, add a decoder for + # packed values regardless of the field's options. + AddDecoder(wire_format.WIRETYPE_LENGTH_DELIMITED, True) + + +def _AddClassAttributesForNestedExtensions(descriptor, dictionary): + extension_dict = descriptor.extensions_by_name + for extension_name, extension_field in extension_dict.iteritems(): + assert extension_name not in dictionary + dictionary[extension_name] = extension_field + + +def _AddEnumValues(descriptor, cls): + """Sets class-level attributes for all enum fields defined in this message. + + Also exporting a class-level object that can name enum values. + + Args: + descriptor: Descriptor object for this message type. + cls: Class we're constructing for this message type. + """ + for enum_type in descriptor.enum_types: + setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type)) + for enum_value in enum_type.values: + setattr(cls, enum_value.name, enum_value.number) + + +def _DefaultValueConstructorForField(field): + """Returns a function which returns a default value for a field. + + Args: + field: FieldDescriptor object for this field. + + The returned function has one argument: + message: Message instance containing this field, or a weakref proxy + of same. + + That function in turn returns a default value for this field. The default + value may refer back to |message| via a weak reference. + """ + + if field.label == _FieldDescriptor.LABEL_REPEATED: + if field.has_default_value and field.default_value != []: + raise ValueError('Repeated field default value not empty list: %s' % ( + field.default_value)) + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + # We can't look at _concrete_class yet since it might not have + # been set. (Depends on order in which we initialize the classes). + message_type = field.message_type + def MakeRepeatedMessageDefault(message): + return containers.RepeatedCompositeFieldContainer( + message._listener_for_children, field.message_type) + return MakeRepeatedMessageDefault + else: + type_checker = type_checkers.GetTypeChecker(field.cpp_type, field.type) + def MakeRepeatedScalarDefault(message): + return containers.RepeatedScalarFieldContainer( + message._listener_for_children, type_checker) + return MakeRepeatedScalarDefault + + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + # _concrete_class may not yet be initialized. + message_type = field.message_type + def MakeSubMessageDefault(message): + result = message_type._concrete_class() + result._SetListener(message._listener_for_children) + return result + return MakeSubMessageDefault + + def MakeScalarDefault(message): + # TODO(protobuf-team): This may be broken since there may not be + # default_value. Combine with has_default_value somehow. + return field.default_value + return MakeScalarDefault + + +def _AddInitMethod(message_descriptor, cls): + """Adds an __init__ method to cls.""" + fields = message_descriptor.fields + def init(self, **kwargs): + self._cached_byte_size = 0 + self._cached_byte_size_dirty = len(kwargs) > 0 + self._fields = {} + # _unknown_fields is () when empty for efficiency, and will be turned into + # a list if fields are added. + self._unknown_fields = () + self._is_present_in_parent = False + self._listener = message_listener_mod.NullMessageListener() + self._listener_for_children = _Listener(self) + for field_name, field_value in kwargs.iteritems(): + field = _GetFieldByName(message_descriptor, field_name) + if field is None: + raise TypeError("%s() got an unexpected keyword argument '%s'" % + (message_descriptor.name, field_name)) + if field.label == _FieldDescriptor.LABEL_REPEATED: + copy = field._default_constructor(self) + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: # Composite + for val in field_value: + copy.add().MergeFrom(val) + else: # Scalar + copy.extend(field_value) + self._fields[field] = copy + elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + copy = field._default_constructor(self) + copy.MergeFrom(field_value) + self._fields[field] = copy + else: + setattr(self, field_name, field_value) + + init.__module__ = None + init.__doc__ = None + cls.__init__ = init + + +def _GetFieldByName(message_descriptor, field_name): + """Returns a field descriptor by field name. + + Args: + message_descriptor: A Descriptor describing all fields in message. + field_name: The name of the field to retrieve. + Returns: + The field descriptor associated with the field name. + """ + try: + return message_descriptor.fields_by_name[field_name] + except KeyError: + raise ValueError('Protocol message has no "%s" field.' % field_name) + + +def _AddPropertiesForFields(descriptor, cls): + """Adds properties for all fields in this protocol message type.""" + for field in descriptor.fields: + _AddPropertiesForField(field, cls) + + if descriptor.is_extendable: + # _ExtensionDict is just an adaptor with no state so we allocate a new one + # every time it is accessed. + cls.Extensions = property(lambda self: _ExtensionDict(self)) + + +def _AddPropertiesForField(field, cls): + """Adds a public property for a protocol message field. + Clients can use this property to get and (in the case + of non-repeated scalar fields) directly set the value + of a protocol message field. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + # Catch it if we add other types that we should + # handle specially here. + assert _FieldDescriptor.MAX_CPPTYPE == 10 + + constant_name = field.name.upper() + "_FIELD_NUMBER" + setattr(cls, constant_name, field.number) + + if field.label == _FieldDescriptor.LABEL_REPEATED: + _AddPropertiesForRepeatedField(field, cls) + elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + _AddPropertiesForNonRepeatedCompositeField(field, cls) + else: + _AddPropertiesForNonRepeatedScalarField(field, cls) + + +def _AddPropertiesForRepeatedField(field, cls): + """Adds a public property for a "repeated" protocol message field. Clients + can use this property to get the value of the field, which will be either a + _RepeatedScalarFieldContainer or _RepeatedCompositeFieldContainer (see + below). + + Note that when clients add values to these containers, we perform + type-checking in the case of repeated scalar fields, and we also set any + necessary "has" bits as a side-effect. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + proto_field_name = field.name + property_name = _PropertyName(proto_field_name) + + def getter(self): + field_value = self._fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + + # Atomically check if another thread has preempted us and, if not, swap + # in the new object we just created. If someone has preempted us, we + # take that object and discard ours. + # WARNING: We are relying on setdefault() being atomic. This is true + # in CPython but we haven't investigated others. This warning appears + # in several other locations in this file. + field_value = self._fields.setdefault(field, field_value) + return field_value + getter.__module__ = None + getter.__doc__ = 'Getter for %s.' % proto_field_name + + # We define a setter just so we can throw an exception with a more + # helpful error message. + def setter(self, new_value): + raise AttributeError('Assignment not allowed to repeated field ' + '"%s" in protocol message object.' % proto_field_name) + + doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name + setattr(cls, property_name, property(getter, setter, doc=doc)) + + +def _AddPropertiesForNonRepeatedScalarField(field, cls): + """Adds a public property for a nonrepeated, scalar protocol message field. + Clients can use this property to get and directly set the value of the field. + Note that when the client sets the value of a field by using this property, + all necessary "has" bits are set as a side-effect, and we also perform + type-checking. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + proto_field_name = field.name + property_name = _PropertyName(proto_field_name) + type_checker = type_checkers.GetTypeChecker(field.cpp_type, field.type) + default_value = field.default_value + valid_values = set() + + def getter(self): + # TODO(protobuf-team): This may be broken since there may not be + # default_value. Combine with has_default_value somehow. + return self._fields.get(field, default_value) + getter.__module__ = None + getter.__doc__ = 'Getter for %s.' % proto_field_name + def setter(self, new_value): + type_checker.CheckValue(new_value) + self._fields[field] = new_value + # Check _cached_byte_size_dirty inline to improve performance, since scalar + # setters are called frequently. + if not self._cached_byte_size_dirty: + self._Modified() + + setter.__module__ = None + setter.__doc__ = 'Setter for %s.' % proto_field_name + + # Add a property to encapsulate the getter/setter. + doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name + setattr(cls, property_name, property(getter, setter, doc=doc)) + + +def _AddPropertiesForNonRepeatedCompositeField(field, cls): + """Adds a public property for a nonrepeated, composite protocol message field. + A composite field is a "group" or "message" field. + + Clients can use this property to get the value of the field, but cannot + assign to the property directly. + + Args: + field: A FieldDescriptor for this field. + cls: The class we're constructing. + """ + # TODO(robinson): Remove duplication with similar method + # for non-repeated scalars. + proto_field_name = field.name + property_name = _PropertyName(proto_field_name) + + # TODO(komarek): Can anyone explain to me why we cache the message_type this + # way, instead of referring to field.message_type inside of getter(self)? + # What if someone sets message_type later on (which makes for simpler + # dyanmic proto descriptor and class creation code). + message_type = field.message_type + + def getter(self): + field_value = self._fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = message_type._concrete_class() # use field.message_type? + field_value._SetListener(self._listener_for_children) + + # Atomically check if another thread has preempted us and, if not, swap + # in the new object we just created. If someone has preempted us, we + # take that object and discard ours. + # WARNING: We are relying on setdefault() being atomic. This is true + # in CPython but we haven't investigated others. This warning appears + # in several other locations in this file. + field_value = self._fields.setdefault(field, field_value) + return field_value + getter.__module__ = None + getter.__doc__ = 'Getter for %s.' % proto_field_name + + # We define a setter just so we can throw an exception with a more + # helpful error message. + def setter(self, new_value): + raise AttributeError('Assignment not allowed to composite field ' + '"%s" in protocol message object.' % proto_field_name) + + # Add a property to encapsulate the getter. + doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name + setattr(cls, property_name, property(getter, setter, doc=doc)) + + +def _AddPropertiesForExtensions(descriptor, cls): + """Adds properties for all fields in this protocol message type.""" + extension_dict = descriptor.extensions_by_name + for extension_name, extension_field in extension_dict.iteritems(): + constant_name = extension_name.upper() + "_FIELD_NUMBER" + setattr(cls, constant_name, extension_field.number) + + +def _AddStaticMethods(cls): + # TODO(robinson): This probably needs to be thread-safe(?) + def RegisterExtension(extension_handle): + extension_handle.containing_type = cls.DESCRIPTOR + _AttachFieldHelpers(cls, extension_handle) + + # Try to insert our extension, failing if an extension with the same number + # already exists. + actual_handle = cls._extensions_by_number.setdefault( + extension_handle.number, extension_handle) + if actual_handle is not extension_handle: + raise AssertionError( + 'Extensions "%s" and "%s" both try to extend message type "%s" with ' + 'field number %d.' % + (extension_handle.full_name, actual_handle.full_name, + cls.DESCRIPTOR.full_name, extension_handle.number)) + + cls._extensions_by_name[extension_handle.full_name] = extension_handle + + handle = extension_handle # avoid line wrapping + if _IsMessageSetExtension(handle): + # MessageSet extension. Also register under type name. + cls._extensions_by_name[ + extension_handle.message_type.full_name] = extension_handle + + cls.RegisterExtension = staticmethod(RegisterExtension) + + def FromString(s): + message = cls() + message.MergeFromString(s) + return message + cls.FromString = staticmethod(FromString) + + +def _IsPresent(item): + """Given a (FieldDescriptor, value) tuple from _fields, return true if the + value should be included in the list returned by ListFields().""" + + if item[0].label == _FieldDescriptor.LABEL_REPEATED: + return bool(item[1]) + elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + return item[1]._is_present_in_parent + else: + return True + + +def _AddListFieldsMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def ListFields(self): + all_fields = [item for item in self._fields.iteritems() if _IsPresent(item)] + all_fields.sort(key = lambda item: item[0].number) + return all_fields + + cls.ListFields = ListFields + + +def _AddHasFieldMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + singular_fields = {} + for field in message_descriptor.fields: + if field.label != _FieldDescriptor.LABEL_REPEATED: + singular_fields[field.name] = field + + def HasField(self, field_name): + try: + field = singular_fields[field_name] + except KeyError: + raise ValueError( + 'Protocol message has no singular "%s" field.' % field_name) + + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + value = self._fields.get(field) + return value is not None and value._is_present_in_parent + else: + return field in self._fields + cls.HasField = HasField + + +def _AddClearFieldMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def ClearField(self, field_name): + try: + field = message_descriptor.fields_by_name[field_name] + except KeyError: + raise ValueError('Protocol message has no "%s" field.' % field_name) + + if field in self._fields: + # Note: If the field is a sub-message, its listener will still point + # at us. That's fine, because the worst than can happen is that it + # will call _Modified() and invalidate our byte size. Big deal. + del self._fields[field] + + # Always call _Modified() -- even if nothing was changed, this is + # a mutating method, and thus calling it should cause the field to become + # present in the parent message. + self._Modified() + + cls.ClearField = ClearField + + +def _AddClearExtensionMethod(cls): + """Helper for _AddMessageMethods().""" + def ClearExtension(self, extension_handle): + _VerifyExtensionHandle(self, extension_handle) + + # Similar to ClearField(), above. + if extension_handle in self._fields: + del self._fields[extension_handle] + self._Modified() + cls.ClearExtension = ClearExtension + + +def _AddClearMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def Clear(self): + # Clear fields. + self._fields = {} + self._unknown_fields = () + self._Modified() + cls.Clear = Clear + + +def _AddHasExtensionMethod(cls): + """Helper for _AddMessageMethods().""" + def HasExtension(self, extension_handle): + _VerifyExtensionHandle(self, extension_handle) + if extension_handle.label == _FieldDescriptor.LABEL_REPEATED: + raise KeyError('"%s" is repeated.' % extension_handle.full_name) + + if extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + value = self._fields.get(extension_handle) + return value is not None and value._is_present_in_parent + else: + return extension_handle in self._fields + cls.HasExtension = HasExtension + + +def _AddEqualsMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def __eq__(self, other): + if (not isinstance(other, message_mod.Message) or + other.DESCRIPTOR != self.DESCRIPTOR): + return False + + if self is other: + return True + + if not self.ListFields() == other.ListFields(): + return False + + # Sort unknown fields because their order shouldn't affect equality test. + unknown_fields = list(self._unknown_fields) + unknown_fields.sort() + other_unknown_fields = list(other._unknown_fields) + other_unknown_fields.sort() + + return unknown_fields == other_unknown_fields + + cls.__eq__ = __eq__ + + +def _AddStrMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def __str__(self): + return text_format.MessageToString(self) + cls.__str__ = __str__ + + +def _AddUnicodeMethod(unused_message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def __unicode__(self): + return text_format.MessageToString(self, as_utf8=True).decode('utf-8') + cls.__unicode__ = __unicode__ + + +def _AddSetListenerMethod(cls): + """Helper for _AddMessageMethods().""" + def SetListener(self, listener): + if listener is None: + self._listener = message_listener_mod.NullMessageListener() + else: + self._listener = listener + cls._SetListener = SetListener + + +def _BytesForNonRepeatedElement(value, field_number, field_type): + """Returns the number of bytes needed to serialize a non-repeated element. + The returned byte count includes space for tag information and any + other additional space associated with serializing value. + + Args: + value: Value we're serializing. + field_number: Field number of this value. (Since the field number + is stored as part of a varint-encoded tag, this has an impact + on the total bytes required to serialize the value). + field_type: The type of the field. One of the TYPE_* constants + within FieldDescriptor. + """ + try: + fn = type_checkers.TYPE_TO_BYTE_SIZE_FN[field_type] + return fn(field_number, value) + except KeyError: + raise message_mod.EncodeError('Unrecognized field type: %d' % field_type) + + +def _AddByteSizeMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def ByteSize(self): + if not self._cached_byte_size_dirty: + return self._cached_byte_size + + size = 0 + for field_descriptor, field_value in self.ListFields(): + size += field_descriptor._sizer(field_value) + + for tag_bytes, value_bytes in self._unknown_fields: + size += len(tag_bytes) + len(value_bytes) + + self._cached_byte_size = size + self._cached_byte_size_dirty = False + self._listener_for_children.dirty = False + return size + + cls.ByteSize = ByteSize + + +def _AddSerializeToStringMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def SerializeToString(self): + # Check if the message has all of its required fields set. + errors = [] + if not self.IsInitialized(): + raise message_mod.EncodeError( + 'Message %s is missing required fields: %s' % ( + self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors()))) + return self.SerializePartialToString() + cls.SerializeToString = SerializeToString + + +def _AddSerializePartialToStringMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + + def SerializePartialToString(self): + out = StringIO() + self._InternalSerialize(out.write) + return out.getvalue() + cls.SerializePartialToString = SerializePartialToString + + def InternalSerialize(self, write_bytes): + for field_descriptor, field_value in self.ListFields(): + field_descriptor._encoder(write_bytes, field_value) + for tag_bytes, value_bytes in self._unknown_fields: + write_bytes(tag_bytes) + write_bytes(value_bytes) + cls._InternalSerialize = InternalSerialize + + +def _AddMergeFromStringMethod(message_descriptor, cls): + """Helper for _AddMessageMethods().""" + def MergeFromString(self, serialized): + length = len(serialized) + try: + if self._InternalParse(serialized, 0, length) != length: + # The only reason _InternalParse would return early is if it + # encountered an end-group tag. + raise message_mod.DecodeError('Unexpected end-group tag.') + except IndexError: + raise message_mod.DecodeError('Truncated message.') + except struct.error, e: + raise message_mod.DecodeError(e) + return length # Return this for legacy reasons. + cls.MergeFromString = MergeFromString + + local_ReadTag = decoder.ReadTag + local_SkipField = decoder.SkipField + decoders_by_tag = cls._decoders_by_tag + + def InternalParse(self, buffer, pos, end): + self._Modified() + field_dict = self._fields + unknown_field_list = self._unknown_fields + while pos != end: + (tag_bytes, new_pos) = local_ReadTag(buffer, pos) + field_decoder = decoders_by_tag.get(tag_bytes) + if field_decoder is None: + value_start_pos = new_pos + new_pos = local_SkipField(buffer, new_pos, end, tag_bytes) + if new_pos == -1: + return pos + if not unknown_field_list: + unknown_field_list = self._unknown_fields = [] + unknown_field_list.append((tag_bytes, buffer[value_start_pos:new_pos])) + pos = new_pos + else: + pos = field_decoder(buffer, new_pos, end, self, field_dict) + return pos + cls._InternalParse = InternalParse + + +def _AddIsInitializedMethod(message_descriptor, cls): + """Adds the IsInitialized and FindInitializationError methods to the + protocol message class.""" + + required_fields = [field for field in message_descriptor.fields + if field.label == _FieldDescriptor.LABEL_REQUIRED] + + def IsInitialized(self, errors=None): + """Checks if all required fields of a message are set. + + Args: + errors: A list which, if provided, will be populated with the field + paths of all missing required fields. + + Returns: + True iff the specified message has all required fields set. + """ + + # Performance is critical so we avoid HasField() and ListFields(). + + for field in required_fields: + if (field not in self._fields or + (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and + not self._fields[field]._is_present_in_parent)): + if errors is not None: + errors.extend(self.FindInitializationErrors()) + return False + + for field, value in self._fields.iteritems(): + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + if field.label == _FieldDescriptor.LABEL_REPEATED: + for element in value: + if not element.IsInitialized(): + if errors is not None: + errors.extend(self.FindInitializationErrors()) + return False + elif value._is_present_in_parent and not value.IsInitialized(): + if errors is not None: + errors.extend(self.FindInitializationErrors()) + return False + + return True + + cls.IsInitialized = IsInitialized + + def FindInitializationErrors(self): + """Finds required fields which are not initialized. + + Returns: + A list of strings. Each string is a path to an uninitialized field from + the top-level message, e.g. "foo.bar[5].baz". + """ + + errors = [] # simplify things + + for field in required_fields: + if not self.HasField(field.name): + errors.append(field.name) + + for field, value in self.ListFields(): + if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + if field.is_extension: + name = "(%s)" % field.full_name + else: + name = field.name + + if field.label == _FieldDescriptor.LABEL_REPEATED: + for i in xrange(len(value)): + element = value[i] + prefix = "%s[%d]." % (name, i) + sub_errors = element.FindInitializationErrors() + errors += [ prefix + error for error in sub_errors ] + else: + prefix = name + "." + sub_errors = value.FindInitializationErrors() + errors += [ prefix + error for error in sub_errors ] + + return errors + + cls.FindInitializationErrors = FindInitializationErrors + + +def _AddMergeFromMethod(cls): + LABEL_REPEATED = _FieldDescriptor.LABEL_REPEATED + CPPTYPE_MESSAGE = _FieldDescriptor.CPPTYPE_MESSAGE + + def MergeFrom(self, msg): + if not isinstance(msg, cls): + raise TypeError( + "Parameter to MergeFrom() must be instance of same class: " + "expected %s got %s." % (cls.__name__, type(msg).__name__)) + + assert msg is not self + self._Modified() + + fields = self._fields + + for field, value in msg._fields.iteritems(): + if field.label == LABEL_REPEATED: + field_value = fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + fields[field] = field_value + field_value.MergeFrom(value) + elif field.cpp_type == CPPTYPE_MESSAGE: + if value._is_present_in_parent: + field_value = fields.get(field) + if field_value is None: + # Construct a new object to represent this field. + field_value = field._default_constructor(self) + fields[field] = field_value + field_value.MergeFrom(value) + else: + self._fields[field] = value + + if msg._unknown_fields: + if not self._unknown_fields: + self._unknown_fields = [] + self._unknown_fields.extend(msg._unknown_fields) + + cls.MergeFrom = MergeFrom + + +def _AddMessageMethods(message_descriptor, cls): + """Adds implementations of all Message methods to cls.""" + _AddListFieldsMethod(message_descriptor, cls) + _AddHasFieldMethod(message_descriptor, cls) + _AddClearFieldMethod(message_descriptor, cls) + if message_descriptor.is_extendable: + _AddClearExtensionMethod(cls) + _AddHasExtensionMethod(cls) + _AddClearMethod(message_descriptor, cls) + _AddEqualsMethod(message_descriptor, cls) + _AddStrMethod(message_descriptor, cls) + _AddUnicodeMethod(message_descriptor, cls) + _AddSetListenerMethod(cls) + _AddByteSizeMethod(message_descriptor, cls) + _AddSerializeToStringMethod(message_descriptor, cls) + _AddSerializePartialToStringMethod(message_descriptor, cls) + _AddMergeFromStringMethod(message_descriptor, cls) + _AddIsInitializedMethod(message_descriptor, cls) + _AddMergeFromMethod(cls) + + +def _AddPrivateHelperMethods(cls): + """Adds implementation of private helper methods to cls.""" + + def Modified(self): + """Sets the _cached_byte_size_dirty bit to true, + and propagates this to our listener iff this was a state change. + """ + + # Note: Some callers check _cached_byte_size_dirty before calling + # _Modified() as an extra optimization. So, if this method is ever + # changed such that it does stuff even when _cached_byte_size_dirty is + # already true, the callers need to be updated. + if not self._cached_byte_size_dirty: + self._cached_byte_size_dirty = True + self._listener_for_children.dirty = True + self._is_present_in_parent = True + self._listener.Modified() + + cls._Modified = Modified + cls.SetInParent = Modified + + +class _Listener(object): + + """MessageListener implementation that a parent message registers with its + child message. + + In order to support semantics like: + + foo.bar.baz.qux = 23 + assert foo.HasField('bar') + + ...child objects must have back references to their parents. + This helper class is at the heart of this support. + """ + + def __init__(self, parent_message): + """Args: + parent_message: The message whose _Modified() method we should call when + we receive Modified() messages. + """ + # This listener establishes a back reference from a child (contained) object + # to its parent (containing) object. We make this a weak reference to avoid + # creating cyclic garbage when the client finishes with the 'parent' object + # in the tree. + if isinstance(parent_message, weakref.ProxyType): + self._parent_message_weakref = parent_message + else: + self._parent_message_weakref = weakref.proxy(parent_message) + + # As an optimization, we also indicate directly on the listener whether + # or not the parent message is dirty. This way we can avoid traversing + # up the tree in the common case. + self.dirty = False + + def Modified(self): + if self.dirty: + return + try: + # Propagate the signal to our parents iff this is the first field set. + self._parent_message_weakref._Modified() + except ReferenceError: + # We can get here if a client has kept a reference to a child object, + # and is now setting a field on it, but the child's parent has been + # garbage-collected. This is not an error. + pass + + +# TODO(robinson): Move elsewhere? This file is getting pretty ridiculous... +# TODO(robinson): Unify error handling of "unknown extension" crap. +# TODO(robinson): Support iteritems()-style iteration over all +# extensions with the "has" bits turned on? +class _ExtensionDict(object): + + """Dict-like container for supporting an indexable "Extensions" + field on proto instances. + + Note that in all cases we expect extension handles to be + FieldDescriptors. + """ + + def __init__(self, extended_message): + """extended_message: Message instance for which we are the Extensions dict. + """ + + self._extended_message = extended_message + + def __getitem__(self, extension_handle): + """Returns the current value of the given extension handle.""" + + _VerifyExtensionHandle(self._extended_message, extension_handle) + + result = self._extended_message._fields.get(extension_handle) + if result is not None: + return result + + if extension_handle.label == _FieldDescriptor.LABEL_REPEATED: + result = extension_handle._default_constructor(self._extended_message) + elif extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: + result = extension_handle.message_type._concrete_class() + try: + result._SetListener(self._extended_message._listener_for_children) + except ReferenceError: + pass + else: + # Singular scalar -- just return the default without inserting into the + # dict. + return extension_handle.default_value + + # Atomically check if another thread has preempted us and, if not, swap + # in the new object we just created. If someone has preempted us, we + # take that object and discard ours. + # WARNING: We are relying on setdefault() being atomic. This is true + # in CPython but we haven't investigated others. This warning appears + # in several other locations in this file. + result = self._extended_message._fields.setdefault( + extension_handle, result) + + return result + + def __eq__(self, other): + if not isinstance(other, self.__class__): + return False + + my_fields = self._extended_message.ListFields() + other_fields = other._extended_message.ListFields() + + # Get rid of non-extension fields. + my_fields = [ field for field in my_fields if field.is_extension ] + other_fields = [ field for field in other_fields if field.is_extension ] + + return my_fields == other_fields + + def __ne__(self, other): + return not self == other + + def __hash__(self): + raise TypeError('unhashable object') + + # Note that this is only meaningful for non-repeated, scalar extension + # fields. Note also that we may have to call _Modified() when we do + # successfully set a field this way, to set any necssary "has" bits in the + # ancestors of the extended message. + def __setitem__(self, extension_handle, value): + """If extension_handle specifies a non-repeated, scalar extension + field, sets the value of that field. + """ + + _VerifyExtensionHandle(self._extended_message, extension_handle) + + if (extension_handle.label == _FieldDescriptor.LABEL_REPEATED or + extension_handle.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE): + raise TypeError( + 'Cannot assign to extension "%s" because it is a repeated or ' + 'composite type.' % extension_handle.full_name) + + # It's slightly wasteful to lookup the type checker each time, + # but we expect this to be a vanishingly uncommon case anyway. + type_checker = type_checkers.GetTypeChecker( + extension_handle.cpp_type, extension_handle.type) + type_checker.CheckValue(value) + self._extended_message._fields[extension_handle] = value + self._extended_message._Modified() + + def _FindExtensionByName(self, name): + """Tries to find a known extension with the specified name. + + Args: + name: Extension full name. + + Returns: + Extension field descriptor. + """ + return self._extended_message._extensions_by_name.get(name, None) diff --git a/code/push/google/protobuf/internal/reflection_cpp_generated_test.py b/code/push/google/protobuf/internal/reflection_cpp_generated_test.py new file mode 100644 index 0000000..2a0a512 --- /dev/null +++ b/code/push/google/protobuf/internal/reflection_cpp_generated_test.py @@ -0,0 +1,91 @@ +#! /usr/bin/python +# -*- coding: utf-8 -*- +# +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Unittest for reflection.py, which tests the generated C++ implementation.""" + +__author__ = 'jasonh@google.com (Jason Hsueh)' + +import os +os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp' + +import unittest +from google.protobuf.internal import api_implementation +from google.protobuf.internal import more_extensions_dynamic_pb2 +from google.protobuf.internal import more_extensions_pb2 +from google.protobuf.internal.reflection_test import * + + +class ReflectionCppTest(unittest.TestCase): + def testImplementationSetting(self): + self.assertEqual('cpp', api_implementation.Type()) + + def testExtensionOfGeneratedTypeInDynamicFile(self): + """Tests that a file built dynamically can extend a generated C++ type. + + The C++ implementation uses a DescriptorPool that has the generated + DescriptorPool as an underlay. Typically, a type can only find + extensions in its own pool. With the python C-extension, the generated C++ + extendee may be available, but not the extension. This tests that the + C-extension implements the correct special handling to make such extensions + available. + """ + pb1 = more_extensions_pb2.ExtendedMessage() + # Test that basic accessors work. + self.assertFalse( + pb1.HasExtension(more_extensions_dynamic_pb2.dynamic_int32_extension)) + self.assertFalse( + pb1.HasExtension(more_extensions_dynamic_pb2.dynamic_message_extension)) + pb1.Extensions[more_extensions_dynamic_pb2.dynamic_int32_extension] = 17 + pb1.Extensions[more_extensions_dynamic_pb2.dynamic_message_extension].a = 24 + self.assertTrue( + pb1.HasExtension(more_extensions_dynamic_pb2.dynamic_int32_extension)) + self.assertTrue( + pb1.HasExtension(more_extensions_dynamic_pb2.dynamic_message_extension)) + + # Now serialize the data and parse to a new message. + pb2 = more_extensions_pb2.ExtendedMessage() + pb2.MergeFromString(pb1.SerializeToString()) + + self.assertTrue( + pb2.HasExtension(more_extensions_dynamic_pb2.dynamic_int32_extension)) + self.assertTrue( + pb2.HasExtension(more_extensions_dynamic_pb2.dynamic_message_extension)) + self.assertEqual( + 17, pb2.Extensions[more_extensions_dynamic_pb2.dynamic_int32_extension]) + self.assertEqual( + 24, + pb2.Extensions[more_extensions_dynamic_pb2.dynamic_message_extension].a) + + +if __name__ == '__main__': + unittest.main() diff --git a/code/push/google/protobuf/internal/reflection_test.py b/code/push/google/protobuf/internal/reflection_test.py new file mode 100644 index 0000000..ed28646 --- /dev/null +++ b/code/push/google/protobuf/internal/reflection_test.py @@ -0,0 +1,2671 @@ +#! /usr/bin/python +# -*- coding: utf-8 -*- +# +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Unittest for reflection.py, which also indirectly tests the output of the +pure-Python protocol compiler. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import gc +import operator +import struct + +import unittest +from google.protobuf import unittest_import_pb2 +from google.protobuf import unittest_mset_pb2 +from google.protobuf import unittest_pb2 +from google.protobuf import descriptor_pb2 +from google.protobuf import descriptor +from google.protobuf import message +from google.protobuf import reflection +from google.protobuf.internal import api_implementation +from google.protobuf.internal import more_extensions_pb2 +from google.protobuf.internal import more_messages_pb2 +from google.protobuf.internal import wire_format +from google.protobuf.internal import test_util +from google.protobuf.internal import decoder + + +class _MiniDecoder(object): + """Decodes a stream of values from a string. + + Once upon a time we actually had a class called decoder.Decoder. Then we + got rid of it during a redesign that made decoding much, much faster overall. + But a couple tests in this file used it to check that the serialized form of + a message was correct. So, this class implements just the methods that were + used by said tests, so that we don't have to rewrite the tests. + """ + + def __init__(self, bytes): + self._bytes = bytes + self._pos = 0 + + def ReadVarint(self): + result, self._pos = decoder._DecodeVarint(self._bytes, self._pos) + return result + + ReadInt32 = ReadVarint + ReadInt64 = ReadVarint + ReadUInt32 = ReadVarint + ReadUInt64 = ReadVarint + + def ReadSInt64(self): + return wire_format.ZigZagDecode(self.ReadVarint()) + + ReadSInt32 = ReadSInt64 + + def ReadFieldNumberAndWireType(self): + return wire_format.UnpackTag(self.ReadVarint()) + + def ReadFloat(self): + result = struct.unpack("".', + text_format.Merge, text, message) + + text = 'RepeatedGroup: {' + self.assertRaisesWithMessage( + text_format.ParseError, '1:16 : Expected "}".', + text_format.Merge, text, message) + + def testMergeEmptyGroup(self): + message = unittest_pb2.TestAllTypes() + text = 'OptionalGroup: {}' + text_format.Merge(text, message) + self.assertTrue(message.HasField('optionalgroup')) + + message.Clear() + + message = unittest_pb2.TestAllTypes() + text = 'OptionalGroup: <>' + text_format.Merge(text, message) + self.assertTrue(message.HasField('optionalgroup')) + + def testMergeBadEnumValue(self): + message = unittest_pb2.TestAllTypes() + text = 'optional_nested_enum: BARR' + self.assertRaisesWithMessage( + text_format.ParseError, + ('1:23 : Enum type "protobuf_unittest.TestAllTypes.NestedEnum" ' + 'has no value named BARR.'), + text_format.Merge, text, message) + + message = unittest_pb2.TestAllTypes() + text = 'optional_nested_enum: 100' + self.assertRaisesWithMessage( + text_format.ParseError, + ('1:23 : Enum type "protobuf_unittest.TestAllTypes.NestedEnum" ' + 'has no value with number 100.'), + text_format.Merge, text, message) + + def testMergeBadIntValue(self): + message = unittest_pb2.TestAllTypes() + text = 'optional_int32: bork' + self.assertRaisesWithMessage( + text_format.ParseError, + ('1:17 : Couldn\'t parse integer: bork'), + text_format.Merge, text, message) + + def testMergeStringFieldUnescape(self): + message = unittest_pb2.TestAllTypes() + text = r'''repeated_string: "\xf\x62" + repeated_string: "\\xf\\x62" + repeated_string: "\\\xf\\\x62" + repeated_string: "\\\\xf\\\\x62" + repeated_string: "\\\\\xf\\\\\x62" + repeated_string: "\x5cx20"''' + text_format.Merge(text, message) + + SLASH = '\\' + self.assertEqual('\x0fb', message.repeated_string[0]) + self.assertEqual(SLASH + 'xf' + SLASH + 'x62', message.repeated_string[1]) + self.assertEqual(SLASH + '\x0f' + SLASH + 'b', message.repeated_string[2]) + self.assertEqual(SLASH + SLASH + 'xf' + SLASH + SLASH + 'x62', + message.repeated_string[3]) + self.assertEqual(SLASH + SLASH + '\x0f' + SLASH + SLASH + 'b', + message.repeated_string[4]) + self.assertEqual(SLASH + 'x20', message.repeated_string[5]) + + def assertRaisesWithMessage(self, e_class, e, func, *args, **kwargs): + """Same as assertRaises, but also compares the exception message.""" + if hasattr(e_class, '__name__'): + exc_name = e_class.__name__ + else: + exc_name = str(e_class) + + try: + func(*args, **kwargs) + except e_class as expr: + if str(expr) != e: + msg = '%s raised, but with wrong message: "%s" instead of "%s"' + raise self.failureException(msg % (exc_name, + str(expr).encode('string_escape'), + e.encode('string_escape'))) + return + else: + raise self.failureException('%s not raised' % exc_name) + + +class TokenizerTest(unittest.TestCase): + + def testSimpleTokenCases(self): + text = ('identifier1:"string1"\n \n\n' + 'identifier2 : \n \n123 \n identifier3 :\'string\'\n' + 'identifiER_4 : 1.1e+2 ID5:-0.23 ID6:\'aaaa\\\'bbbb\'\n' + 'ID7 : "aa\\"bb"\n\n\n\n ID8: {A:inf B:-inf C:true D:false}\n' + 'ID9: 22 ID10: -111111111111111111 ID11: -22\n' + 'ID12: 2222222222222222222 ID13: 1.23456f ID14: 1.2e+2f ' + 'false_bool: 0 true_BOOL:t \n true_bool1: 1 false_BOOL1:f ' ) + tokenizer = text_format._Tokenizer(text) + methods = [(tokenizer.ConsumeIdentifier, 'identifier1'), + ':', + (tokenizer.ConsumeString, 'string1'), + (tokenizer.ConsumeIdentifier, 'identifier2'), + ':', + (tokenizer.ConsumeInt32, 123), + (tokenizer.ConsumeIdentifier, 'identifier3'), + ':', + (tokenizer.ConsumeString, 'string'), + (tokenizer.ConsumeIdentifier, 'identifiER_4'), + ':', + (tokenizer.ConsumeFloat, 1.1e+2), + (tokenizer.ConsumeIdentifier, 'ID5'), + ':', + (tokenizer.ConsumeFloat, -0.23), + (tokenizer.ConsumeIdentifier, 'ID6'), + ':', + (tokenizer.ConsumeString, 'aaaa\'bbbb'), + (tokenizer.ConsumeIdentifier, 'ID7'), + ':', + (tokenizer.ConsumeString, 'aa\"bb'), + (tokenizer.ConsumeIdentifier, 'ID8'), + ':', + '{', + (tokenizer.ConsumeIdentifier, 'A'), + ':', + (tokenizer.ConsumeFloat, float('inf')), + (tokenizer.ConsumeIdentifier, 'B'), + ':', + (tokenizer.ConsumeFloat, -float('inf')), + (tokenizer.ConsumeIdentifier, 'C'), + ':', + (tokenizer.ConsumeBool, True), + (tokenizer.ConsumeIdentifier, 'D'), + ':', + (tokenizer.ConsumeBool, False), + '}', + (tokenizer.ConsumeIdentifier, 'ID9'), + ':', + (tokenizer.ConsumeUint32, 22), + (tokenizer.ConsumeIdentifier, 'ID10'), + ':', + (tokenizer.ConsumeInt64, -111111111111111111), + (tokenizer.ConsumeIdentifier, 'ID11'), + ':', + (tokenizer.ConsumeInt32, -22), + (tokenizer.ConsumeIdentifier, 'ID12'), + ':', + (tokenizer.ConsumeUint64, 2222222222222222222), + (tokenizer.ConsumeIdentifier, 'ID13'), + ':', + (tokenizer.ConsumeFloat, 1.23456), + (tokenizer.ConsumeIdentifier, 'ID14'), + ':', + (tokenizer.ConsumeFloat, 1.2e+2), + (tokenizer.ConsumeIdentifier, 'false_bool'), + ':', + (tokenizer.ConsumeBool, False), + (tokenizer.ConsumeIdentifier, 'true_BOOL'), + ':', + (tokenizer.ConsumeBool, True), + (tokenizer.ConsumeIdentifier, 'true_bool1'), + ':', + (tokenizer.ConsumeBool, True), + (tokenizer.ConsumeIdentifier, 'false_BOOL1'), + ':', + (tokenizer.ConsumeBool, False)] + + i = 0 + while not tokenizer.AtEnd(): + m = methods[i] + if type(m) == str: + token = tokenizer.token + self.assertEqual(token, m) + tokenizer.NextToken() + else: + self.assertEqual(m[1], m[0]()) + i += 1 + + def testConsumeIntegers(self): + # This test only tests the failures in the integer parsing methods as well + # as the '0' special cases. + int64_max = (1 << 63) - 1 + uint32_max = (1 << 32) - 1 + text = '-1 %d %d' % (uint32_max + 1, int64_max + 1) + tokenizer = text_format._Tokenizer(text) + self.assertRaises(text_format.ParseError, tokenizer.ConsumeUint32) + self.assertRaises(text_format.ParseError, tokenizer.ConsumeUint64) + self.assertEqual(-1, tokenizer.ConsumeInt32()) + + self.assertRaises(text_format.ParseError, tokenizer.ConsumeUint32) + self.assertRaises(text_format.ParseError, tokenizer.ConsumeInt32) + self.assertEqual(uint32_max + 1, tokenizer.ConsumeInt64()) + + self.assertRaises(text_format.ParseError, tokenizer.ConsumeInt64) + self.assertEqual(int64_max + 1, tokenizer.ConsumeUint64()) + self.assertTrue(tokenizer.AtEnd()) + + text = '-0 -0 0 0' + tokenizer = text_format._Tokenizer(text) + self.assertEqual(0, tokenizer.ConsumeUint32()) + self.assertEqual(0, tokenizer.ConsumeUint64()) + self.assertEqual(0, tokenizer.ConsumeUint32()) + self.assertEqual(0, tokenizer.ConsumeUint64()) + self.assertTrue(tokenizer.AtEnd()) + + def testConsumeByteString(self): + text = '"string1\'' + tokenizer = text_format._Tokenizer(text) + self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString) + + text = 'string1"' + tokenizer = text_format._Tokenizer(text) + self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString) + + text = '\n"\\xt"' + tokenizer = text_format._Tokenizer(text) + self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString) + + text = '\n"\\"' + tokenizer = text_format._Tokenizer(text) + self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString) + + text = '\n"\\x"' + tokenizer = text_format._Tokenizer(text) + self.assertRaises(text_format.ParseError, tokenizer.ConsumeByteString) + + def testConsumeBool(self): + text = 'not-a-bool' + tokenizer = text_format._Tokenizer(text) + self.assertRaises(text_format.ParseError, tokenizer.ConsumeBool) + + +if __name__ == '__main__': + unittest.main() diff --git a/code/push/google/protobuf/internal/type_checkers.py b/code/push/google/protobuf/internal/type_checkers.py new file mode 100644 index 0000000..09bf5e4 --- /dev/null +++ b/code/push/google/protobuf/internal/type_checkers.py @@ -0,0 +1,286 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Provides type checking routines. + +This module defines type checking utilities in the forms of dictionaries: + +VALUE_CHECKERS: A dictionary of field types and a value validation object. +TYPE_TO_BYTE_SIZE_FN: A dictionary with field types and a size computing + function. +TYPE_TO_SERIALIZE_METHOD: A dictionary with field types and serialization + function. +FIELD_TYPE_TO_WIRE_TYPE: A dictionary with field typed and their + coresponding wire types. +TYPE_TO_DESERIALIZE_METHOD: A dictionary with field types and deserialization + function. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + +from push.google.protobuf.internal import decoder +from push.google.protobuf.internal import encoder +from push.google.protobuf.internal import wire_format +from push.google.protobuf import descriptor + +_FieldDescriptor = descriptor.FieldDescriptor + + +def GetTypeChecker(cpp_type, field_type): + """Returns a type checker for a message field of the specified types. + + Args: + cpp_type: C++ type of the field (see descriptor.py). + field_type: Protocol message field type (see descriptor.py). + + Returns: + An instance of TypeChecker which can be used to verify the types + of values assigned to a field of the specified type. + """ + if (cpp_type == _FieldDescriptor.CPPTYPE_STRING and + field_type == _FieldDescriptor.TYPE_STRING): + return UnicodeValueChecker() + return _VALUE_CHECKERS[cpp_type] + + +# None of the typecheckers below make any attempt to guard against people +# subclassing builtin types and doing weird things. We're not trying to +# protect against malicious clients here, just people accidentally shooting +# themselves in the foot in obvious ways. + +class TypeChecker(object): + + """Type checker used to catch type errors as early as possible + when the client is setting scalar fields in protocol messages. + """ + + def __init__(self, *acceptable_types): + self._acceptable_types = acceptable_types + + def CheckValue(self, proposed_value): + if not isinstance(proposed_value, self._acceptable_types): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), self._acceptable_types)) + raise TypeError(message) + + +# IntValueChecker and its subclasses perform integer type-checks +# and bounds-checks. +class IntValueChecker(object): + + """Checker used for integer fields. Performs type-check and range check.""" + + def CheckValue(self, proposed_value): + if not isinstance(proposed_value, (int, long)): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), (int, long))) + raise TypeError(message) + if not self._MIN <= proposed_value <= self._MAX: + raise ValueError('Value out of range: %d' % proposed_value) + + +class UnicodeValueChecker(object): + + """Checker used for string fields.""" + + def CheckValue(self, proposed_value): + if not isinstance(proposed_value, (str, unicode)): + message = ('%.1024r has type %s, but expected one of: %s' % + (proposed_value, type(proposed_value), (str, unicode))) + raise TypeError(message) + + # If the value is of type 'str' make sure that it is in 7-bit ASCII + # encoding. + if isinstance(proposed_value, str): + try: + unicode(proposed_value, 'ascii') + except UnicodeDecodeError: + raise ValueError('%.1024r has type str, but isn\'t in 7-bit ASCII ' + 'encoding. Non-ASCII strings must be converted to ' + 'unicode objects before being added.' % + (proposed_value)) + + +class Int32ValueChecker(IntValueChecker): + # We're sure to use ints instead of longs here since comparison may be more + # efficient. + _MIN = -2147483648 + _MAX = 2147483647 + + +class Uint32ValueChecker(IntValueChecker): + _MIN = 0 + _MAX = (1 << 32) - 1 + + +class Int64ValueChecker(IntValueChecker): + _MIN = -(1 << 63) + _MAX = (1 << 63) - 1 + + +class Uint64ValueChecker(IntValueChecker): + _MIN = 0 + _MAX = (1 << 64) - 1 + + +# Type-checkers for all scalar CPPTYPEs. +_VALUE_CHECKERS = { + _FieldDescriptor.CPPTYPE_INT32: Int32ValueChecker(), + _FieldDescriptor.CPPTYPE_INT64: Int64ValueChecker(), + _FieldDescriptor.CPPTYPE_UINT32: Uint32ValueChecker(), + _FieldDescriptor.CPPTYPE_UINT64: Uint64ValueChecker(), + _FieldDescriptor.CPPTYPE_DOUBLE: TypeChecker( + float, int, long), + _FieldDescriptor.CPPTYPE_FLOAT: TypeChecker( + float, int, long), + _FieldDescriptor.CPPTYPE_BOOL: TypeChecker(bool, int), + _FieldDescriptor.CPPTYPE_ENUM: Int32ValueChecker(), + _FieldDescriptor.CPPTYPE_STRING: TypeChecker(str), + } + + +# Map from field type to a function F, such that F(field_num, value) +# gives the total byte size for a value of the given type. This +# byte size includes tag information and any other additional space +# associated with serializing "value". +TYPE_TO_BYTE_SIZE_FN = { + _FieldDescriptor.TYPE_DOUBLE: wire_format.DoubleByteSize, + _FieldDescriptor.TYPE_FLOAT: wire_format.FloatByteSize, + _FieldDescriptor.TYPE_INT64: wire_format.Int64ByteSize, + _FieldDescriptor.TYPE_UINT64: wire_format.UInt64ByteSize, + _FieldDescriptor.TYPE_INT32: wire_format.Int32ByteSize, + _FieldDescriptor.TYPE_FIXED64: wire_format.Fixed64ByteSize, + _FieldDescriptor.TYPE_FIXED32: wire_format.Fixed32ByteSize, + _FieldDescriptor.TYPE_BOOL: wire_format.BoolByteSize, + _FieldDescriptor.TYPE_STRING: wire_format.StringByteSize, + _FieldDescriptor.TYPE_GROUP: wire_format.GroupByteSize, + _FieldDescriptor.TYPE_MESSAGE: wire_format.MessageByteSize, + _FieldDescriptor.TYPE_BYTES: wire_format.BytesByteSize, + _FieldDescriptor.TYPE_UINT32: wire_format.UInt32ByteSize, + _FieldDescriptor.TYPE_ENUM: wire_format.EnumByteSize, + _FieldDescriptor.TYPE_SFIXED32: wire_format.SFixed32ByteSize, + _FieldDescriptor.TYPE_SFIXED64: wire_format.SFixed64ByteSize, + _FieldDescriptor.TYPE_SINT32: wire_format.SInt32ByteSize, + _FieldDescriptor.TYPE_SINT64: wire_format.SInt64ByteSize + } + + +# Maps from field types to encoder constructors. +TYPE_TO_ENCODER = { + _FieldDescriptor.TYPE_DOUBLE: encoder.DoubleEncoder, + _FieldDescriptor.TYPE_FLOAT: encoder.FloatEncoder, + _FieldDescriptor.TYPE_INT64: encoder.Int64Encoder, + _FieldDescriptor.TYPE_UINT64: encoder.UInt64Encoder, + _FieldDescriptor.TYPE_INT32: encoder.Int32Encoder, + _FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Encoder, + _FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Encoder, + _FieldDescriptor.TYPE_BOOL: encoder.BoolEncoder, + _FieldDescriptor.TYPE_STRING: encoder.StringEncoder, + _FieldDescriptor.TYPE_GROUP: encoder.GroupEncoder, + _FieldDescriptor.TYPE_MESSAGE: encoder.MessageEncoder, + _FieldDescriptor.TYPE_BYTES: encoder.BytesEncoder, + _FieldDescriptor.TYPE_UINT32: encoder.UInt32Encoder, + _FieldDescriptor.TYPE_ENUM: encoder.EnumEncoder, + _FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Encoder, + _FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Encoder, + _FieldDescriptor.TYPE_SINT32: encoder.SInt32Encoder, + _FieldDescriptor.TYPE_SINT64: encoder.SInt64Encoder, + } + + +# Maps from field types to sizer constructors. +TYPE_TO_SIZER = { + _FieldDescriptor.TYPE_DOUBLE: encoder.DoubleSizer, + _FieldDescriptor.TYPE_FLOAT: encoder.FloatSizer, + _FieldDescriptor.TYPE_INT64: encoder.Int64Sizer, + _FieldDescriptor.TYPE_UINT64: encoder.UInt64Sizer, + _FieldDescriptor.TYPE_INT32: encoder.Int32Sizer, + _FieldDescriptor.TYPE_FIXED64: encoder.Fixed64Sizer, + _FieldDescriptor.TYPE_FIXED32: encoder.Fixed32Sizer, + _FieldDescriptor.TYPE_BOOL: encoder.BoolSizer, + _FieldDescriptor.TYPE_STRING: encoder.StringSizer, + _FieldDescriptor.TYPE_GROUP: encoder.GroupSizer, + _FieldDescriptor.TYPE_MESSAGE: encoder.MessageSizer, + _FieldDescriptor.TYPE_BYTES: encoder.BytesSizer, + _FieldDescriptor.TYPE_UINT32: encoder.UInt32Sizer, + _FieldDescriptor.TYPE_ENUM: encoder.EnumSizer, + _FieldDescriptor.TYPE_SFIXED32: encoder.SFixed32Sizer, + _FieldDescriptor.TYPE_SFIXED64: encoder.SFixed64Sizer, + _FieldDescriptor.TYPE_SINT32: encoder.SInt32Sizer, + _FieldDescriptor.TYPE_SINT64: encoder.SInt64Sizer, + } + + +# Maps from field type to a decoder constructor. +TYPE_TO_DECODER = { + _FieldDescriptor.TYPE_DOUBLE: decoder.DoubleDecoder, + _FieldDescriptor.TYPE_FLOAT: decoder.FloatDecoder, + _FieldDescriptor.TYPE_INT64: decoder.Int64Decoder, + _FieldDescriptor.TYPE_UINT64: decoder.UInt64Decoder, + _FieldDescriptor.TYPE_INT32: decoder.Int32Decoder, + _FieldDescriptor.TYPE_FIXED64: decoder.Fixed64Decoder, + _FieldDescriptor.TYPE_FIXED32: decoder.Fixed32Decoder, + _FieldDescriptor.TYPE_BOOL: decoder.BoolDecoder, + _FieldDescriptor.TYPE_STRING: decoder.StringDecoder, + _FieldDescriptor.TYPE_GROUP: decoder.GroupDecoder, + _FieldDescriptor.TYPE_MESSAGE: decoder.MessageDecoder, + _FieldDescriptor.TYPE_BYTES: decoder.BytesDecoder, + _FieldDescriptor.TYPE_UINT32: decoder.UInt32Decoder, + _FieldDescriptor.TYPE_ENUM: decoder.EnumDecoder, + _FieldDescriptor.TYPE_SFIXED32: decoder.SFixed32Decoder, + _FieldDescriptor.TYPE_SFIXED64: decoder.SFixed64Decoder, + _FieldDescriptor.TYPE_SINT32: decoder.SInt32Decoder, + _FieldDescriptor.TYPE_SINT64: decoder.SInt64Decoder, + } + +# Maps from field type to expected wiretype. +FIELD_TYPE_TO_WIRE_TYPE = { + _FieldDescriptor.TYPE_DOUBLE: wire_format.WIRETYPE_FIXED64, + _FieldDescriptor.TYPE_FLOAT: wire_format.WIRETYPE_FIXED32, + _FieldDescriptor.TYPE_INT64: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_UINT64: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_INT32: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_FIXED64: wire_format.WIRETYPE_FIXED64, + _FieldDescriptor.TYPE_FIXED32: wire_format.WIRETYPE_FIXED32, + _FieldDescriptor.TYPE_BOOL: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_STRING: + wire_format.WIRETYPE_LENGTH_DELIMITED, + _FieldDescriptor.TYPE_GROUP: wire_format.WIRETYPE_START_GROUP, + _FieldDescriptor.TYPE_MESSAGE: + wire_format.WIRETYPE_LENGTH_DELIMITED, + _FieldDescriptor.TYPE_BYTES: + wire_format.WIRETYPE_LENGTH_DELIMITED, + _FieldDescriptor.TYPE_UINT32: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_ENUM: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_SFIXED32: wire_format.WIRETYPE_FIXED32, + _FieldDescriptor.TYPE_SFIXED64: wire_format.WIRETYPE_FIXED64, + _FieldDescriptor.TYPE_SINT32: wire_format.WIRETYPE_VARINT, + _FieldDescriptor.TYPE_SINT64: wire_format.WIRETYPE_VARINT, + } diff --git a/code/push/google/protobuf/internal/unknown_fields_test.py b/code/push/google/protobuf/internal/unknown_fields_test.py new file mode 100644 index 0000000..84984b4 --- /dev/null +++ b/code/push/google/protobuf/internal/unknown_fields_test.py @@ -0,0 +1,170 @@ +#! /usr/bin/python +# -*- coding: utf-8 -*- +# +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Test for preservation of unknown fields in the pure Python implementation.""" + +__author__ = 'bohdank@google.com (Bohdan Koval)' + +import unittest +from google.protobuf import unittest_mset_pb2 +from google.protobuf import unittest_pb2 +from google.protobuf.internal import encoder +from google.protobuf.internal import test_util +from google.protobuf.internal import type_checkers + + +class UnknownFieldsTest(unittest.TestCase): + + def setUp(self): + self.descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR + self.all_fields = unittest_pb2.TestAllTypes() + test_util.SetAllFields(self.all_fields) + self.all_fields_data = self.all_fields.SerializeToString() + self.empty_message = unittest_pb2.TestEmptyMessage() + self.empty_message.ParseFromString(self.all_fields_data) + self.unknown_fields = self.empty_message._unknown_fields + + def GetField(self, name): + field_descriptor = self.descriptor.fields_by_name[name] + wire_type = type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type] + field_tag = encoder.TagBytes(field_descriptor.number, wire_type) + for tag_bytes, value in self.unknown_fields: + if tag_bytes == field_tag: + decoder = unittest_pb2.TestAllTypes._decoders_by_tag[tag_bytes] + result_dict = {} + decoder(value, 0, len(value), self.all_fields, result_dict) + return result_dict[field_descriptor] + + def testVarint(self): + value = self.GetField('optional_int32') + self.assertEqual(self.all_fields.optional_int32, value) + + def testFixed32(self): + value = self.GetField('optional_fixed32') + self.assertEqual(self.all_fields.optional_fixed32, value) + + def testFixed64(self): + value = self.GetField('optional_fixed64') + self.assertEqual(self.all_fields.optional_fixed64, value) + + def testLengthDelimited(self): + value = self.GetField('optional_string') + self.assertEqual(self.all_fields.optional_string, value) + + def testGroup(self): + value = self.GetField('optionalgroup') + self.assertEqual(self.all_fields.optionalgroup, value) + + def testSerialize(self): + data = self.empty_message.SerializeToString() + + # Don't use assertEqual because we don't want to dump raw binary data to + # stdout. + self.assertTrue(data == self.all_fields_data) + + def testCopyFrom(self): + message = unittest_pb2.TestEmptyMessage() + message.CopyFrom(self.empty_message) + self.assertEqual(self.unknown_fields, message._unknown_fields) + + def testMergeFrom(self): + message = unittest_pb2.TestAllTypes() + message.optional_int32 = 1 + message.optional_uint32 = 2 + source = unittest_pb2.TestEmptyMessage() + source.ParseFromString(message.SerializeToString()) + + message.ClearField('optional_int32') + message.optional_int64 = 3 + message.optional_uint32 = 4 + destination = unittest_pb2.TestEmptyMessage() + destination.ParseFromString(message.SerializeToString()) + unknown_fields = destination._unknown_fields[:] + + destination.MergeFrom(source) + self.assertEqual(unknown_fields + source._unknown_fields, + destination._unknown_fields) + + def testClear(self): + self.empty_message.Clear() + self.assertEqual(0, len(self.empty_message._unknown_fields)) + + def testByteSize(self): + self.assertEqual(self.all_fields.ByteSize(), self.empty_message.ByteSize()) + + def testUnknownExtensions(self): + message = unittest_pb2.TestEmptyMessageWithExtensions() + message.ParseFromString(self.all_fields_data) + self.assertEqual(self.empty_message._unknown_fields, + message._unknown_fields) + + def testListFields(self): + # Make sure ListFields doesn't return unknown fields. + self.assertEqual(0, len(self.empty_message.ListFields())) + + def testSerializeMessageSetWireFormatUnknownExtension(self): + # Create a message using the message set wire format with an unknown + # message. + raw = unittest_mset_pb2.RawMessageSet() + + # Add an unknown extension. + item = raw.item.add() + item.type_id = 1545009 + message1 = unittest_mset_pb2.TestMessageSetExtension1() + message1.i = 12345 + item.message = message1.SerializeToString() + + serialized = raw.SerializeToString() + + # Parse message using the message set wire format. + proto = unittest_mset_pb2.TestMessageSet() + proto.MergeFromString(serialized) + + # Verify that the unknown extension is serialized unchanged + reserialized = proto.SerializeToString() + new_raw = unittest_mset_pb2.RawMessageSet() + new_raw.MergeFromString(reserialized) + self.assertEqual(raw, new_raw) + + def testEquals(self): + message = unittest_pb2.TestEmptyMessage() + message.ParseFromString(self.all_fields_data) + self.assertEqual(self.empty_message, message) + + self.all_fields.ClearField('optional_string') + message.ParseFromString(self.all_fields.SerializeToString()) + self.assertNotEqual(self.empty_message, message) + + +if __name__ == '__main__': + unittest.main() diff --git a/code/push/google/protobuf/internal/wire_format.py b/code/push/google/protobuf/internal/wire_format.py new file mode 100644 index 0000000..ef73377 --- /dev/null +++ b/code/push/google/protobuf/internal/wire_format.py @@ -0,0 +1,268 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Constants and static functions to support protocol buffer wire format.""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import struct +from push.google.protobuf import descriptor +from push.google.protobuf import message + + +TAG_TYPE_BITS = 3 # Number of bits used to hold type info in a proto tag. +TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1 # 0x7 + +# These numbers identify the wire type of a protocol buffer value. +# We use the least-significant TAG_TYPE_BITS bits of the varint-encoded +# tag-and-type to store one of these WIRETYPE_* constants. +# These values must match WireType enum in google/protobuf/wire_format.h. +WIRETYPE_VARINT = 0 +WIRETYPE_FIXED64 = 1 +WIRETYPE_LENGTH_DELIMITED = 2 +WIRETYPE_START_GROUP = 3 +WIRETYPE_END_GROUP = 4 +WIRETYPE_FIXED32 = 5 +_WIRETYPE_MAX = 5 + + +# Bounds for various integer types. +INT32_MAX = int((1 << 31) - 1) +INT32_MIN = int(-(1 << 31)) +UINT32_MAX = (1 << 32) - 1 + +INT64_MAX = (1 << 63) - 1 +INT64_MIN = -(1 << 63) +UINT64_MAX = (1 << 64) - 1 + +# "struct" format strings that will encode/decode the specified formats. +FORMAT_UINT32_LITTLE_ENDIAN = '> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK) + + +def ZigZagEncode(value): + """ZigZag Transform: Encodes signed integers so that they can be + effectively used with varint encoding. See wire_format.h for + more details. + """ + if value >= 0: + return value << 1 + return (value << 1) ^ (~0) + + +def ZigZagDecode(value): + """Inverse of ZigZagEncode().""" + if not value & 0x1: + return value >> 1 + return (value >> 1) ^ (~0) + + + +# The *ByteSize() functions below return the number of bytes required to +# serialize "field number + type" information and then serialize the value. + + +def Int32ByteSize(field_number, int32): + return Int64ByteSize(field_number, int32) + + +def Int32ByteSizeNoTag(int32): + return _VarUInt64ByteSizeNoTag(0xffffffffffffffff & int32) + + +def Int64ByteSize(field_number, int64): + # Have to convert to uint before calling UInt64ByteSize(). + return UInt64ByteSize(field_number, 0xffffffffffffffff & int64) + + +def UInt32ByteSize(field_number, uint32): + return UInt64ByteSize(field_number, uint32) + + +def UInt64ByteSize(field_number, uint64): + return TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(uint64) + + +def SInt32ByteSize(field_number, int32): + return UInt32ByteSize(field_number, ZigZagEncode(int32)) + + +def SInt64ByteSize(field_number, int64): + return UInt64ByteSize(field_number, ZigZagEncode(int64)) + + +def Fixed32ByteSize(field_number, fixed32): + return TagByteSize(field_number) + 4 + + +def Fixed64ByteSize(field_number, fixed64): + return TagByteSize(field_number) + 8 + + +def SFixed32ByteSize(field_number, sfixed32): + return TagByteSize(field_number) + 4 + + +def SFixed64ByteSize(field_number, sfixed64): + return TagByteSize(field_number) + 8 + + +def FloatByteSize(field_number, flt): + return TagByteSize(field_number) + 4 + + +def DoubleByteSize(field_number, double): + return TagByteSize(field_number) + 8 + + +def BoolByteSize(field_number, b): + return TagByteSize(field_number) + 1 + + +def EnumByteSize(field_number, enum): + return UInt32ByteSize(field_number, enum) + + +def StringByteSize(field_number, string): + return BytesByteSize(field_number, string.encode('utf-8')) + + +def BytesByteSize(field_number, b): + return (TagByteSize(field_number) + + _VarUInt64ByteSizeNoTag(len(b)) + + len(b)) + + +def GroupByteSize(field_number, message): + return (2 * TagByteSize(field_number) # START and END group. + + message.ByteSize()) + + +def MessageByteSize(field_number, message): + return (TagByteSize(field_number) + + _VarUInt64ByteSizeNoTag(message.ByteSize()) + + message.ByteSize()) + + +def MessageSetItemByteSize(field_number, msg): + # First compute the sizes of the tags. + # There are 2 tags for the beginning and ending of the repeated group, that + # is field number 1, one with field number 2 (type_id) and one with field + # number 3 (message). + total_size = (2 * TagByteSize(1) + TagByteSize(2) + TagByteSize(3)) + + # Add the number of bytes for type_id. + total_size += _VarUInt64ByteSizeNoTag(field_number) + + message_size = msg.ByteSize() + + # The number of bytes for encoding the length of the message. + total_size += _VarUInt64ByteSizeNoTag(message_size) + + # The size of the message. + total_size += message_size + return total_size + + +def TagByteSize(field_number): + """Returns the bytes required to serialize a tag with this field number.""" + # Just pass in type 0, since the type won't affect the tag+type size. + return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0)) + + +# Private helper function for the *ByteSize() functions above. + +def _VarUInt64ByteSizeNoTag(uint64): + """Returns the number of bytes required to serialize a single varint + using boundary value comparisons. (unrolled loop optimization -WPierce) + uint64 must be unsigned. + """ + if uint64 <= 0x7f: return 1 + if uint64 <= 0x3fff: return 2 + if uint64 <= 0x1fffff: return 3 + if uint64 <= 0xfffffff: return 4 + if uint64 <= 0x7ffffffff: return 5 + if uint64 <= 0x3ffffffffff: return 6 + if uint64 <= 0x1ffffffffffff: return 7 + if uint64 <= 0xffffffffffffff: return 8 + if uint64 <= 0x7fffffffffffffff: return 9 + if uint64 > UINT64_MAX: + raise message.EncodeError('Value out of range: %d' % uint64) + return 10 + + +NON_PACKABLE_TYPES = ( + descriptor.FieldDescriptor.TYPE_STRING, + descriptor.FieldDescriptor.TYPE_GROUP, + descriptor.FieldDescriptor.TYPE_MESSAGE, + descriptor.FieldDescriptor.TYPE_BYTES +) + + +def IsTypePackable(field_type): + """Return true iff packable = true is valid for fields of this type. + + Args: + field_type: a FieldDescriptor::Type value. + + Returns: + True iff fields of this type are packable. + """ + return field_type not in NON_PACKABLE_TYPES diff --git a/code/push/google/protobuf/internal/wire_format_test.py b/code/push/google/protobuf/internal/wire_format_test.py new file mode 100644 index 0000000..7600778 --- /dev/null +++ b/code/push/google/protobuf/internal/wire_format_test.py @@ -0,0 +1,253 @@ +#! /usr/bin/python +# +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Test for google.protobuf.internal.wire_format.""" + +__author__ = 'robinson@google.com (Will Robinson)' + +import unittest +from google.protobuf import message +from google.protobuf.internal import wire_format + + +class WireFormatTest(unittest.TestCase): + + def testPackTag(self): + field_number = 0xabc + tag_type = 2 + self.assertEqual((field_number << 3) | tag_type, + wire_format.PackTag(field_number, tag_type)) + PackTag = wire_format.PackTag + # Number too high. + self.assertRaises(message.EncodeError, PackTag, field_number, 6) + # Number too low. + self.assertRaises(message.EncodeError, PackTag, field_number, -1) + + def testUnpackTag(self): + # Test field numbers that will require various varint sizes. + for expected_field_number in (1, 15, 16, 2047, 2048): + for expected_wire_type in range(6): # Highest-numbered wiretype is 5. + field_number, wire_type = wire_format.UnpackTag( + wire_format.PackTag(expected_field_number, expected_wire_type)) + self.assertEqual(expected_field_number, field_number) + self.assertEqual(expected_wire_type, wire_type) + + self.assertRaises(TypeError, wire_format.UnpackTag, None) + self.assertRaises(TypeError, wire_format.UnpackTag, 'abc') + self.assertRaises(TypeError, wire_format.UnpackTag, 0.0) + self.assertRaises(TypeError, wire_format.UnpackTag, object()) + + def testZigZagEncode(self): + Z = wire_format.ZigZagEncode + self.assertEqual(0, Z(0)) + self.assertEqual(1, Z(-1)) + self.assertEqual(2, Z(1)) + self.assertEqual(3, Z(-2)) + self.assertEqual(4, Z(2)) + self.assertEqual(0xfffffffe, Z(0x7fffffff)) + self.assertEqual(0xffffffff, Z(-0x80000000)) + self.assertEqual(0xfffffffffffffffe, Z(0x7fffffffffffffff)) + self.assertEqual(0xffffffffffffffff, Z(-0x8000000000000000)) + + self.assertRaises(TypeError, Z, None) + self.assertRaises(TypeError, Z, 'abcd') + self.assertRaises(TypeError, Z, 0.0) + self.assertRaises(TypeError, Z, object()) + + def testZigZagDecode(self): + Z = wire_format.ZigZagDecode + self.assertEqual(0, Z(0)) + self.assertEqual(-1, Z(1)) + self.assertEqual(1, Z(2)) + self.assertEqual(-2, Z(3)) + self.assertEqual(2, Z(4)) + self.assertEqual(0x7fffffff, Z(0xfffffffe)) + self.assertEqual(-0x80000000, Z(0xffffffff)) + self.assertEqual(0x7fffffffffffffff, Z(0xfffffffffffffffe)) + self.assertEqual(-0x8000000000000000, Z(0xffffffffffffffff)) + + self.assertRaises(TypeError, Z, None) + self.assertRaises(TypeError, Z, 'abcd') + self.assertRaises(TypeError, Z, 0.0) + self.assertRaises(TypeError, Z, object()) + + def NumericByteSizeTestHelper(self, byte_size_fn, value, expected_value_size): + # Use field numbers that cause various byte sizes for the tag information. + for field_number, tag_bytes in ((15, 1), (16, 2), (2047, 2), (2048, 3)): + expected_size = expected_value_size + tag_bytes + actual_size = byte_size_fn(field_number, value) + self.assertEqual(expected_size, actual_size, + 'byte_size_fn: %s, field_number: %d, value: %r\n' + 'Expected: %d, Actual: %d'% ( + byte_size_fn, field_number, value, expected_size, actual_size)) + + def testByteSizeFunctions(self): + # Test all numeric *ByteSize() functions. + NUMERIC_ARGS = [ + # Int32ByteSize(). + [wire_format.Int32ByteSize, 0, 1], + [wire_format.Int32ByteSize, 127, 1], + [wire_format.Int32ByteSize, 128, 2], + [wire_format.Int32ByteSize, -1, 10], + # Int64ByteSize(). + [wire_format.Int64ByteSize, 0, 1], + [wire_format.Int64ByteSize, 127, 1], + [wire_format.Int64ByteSize, 128, 2], + [wire_format.Int64ByteSize, -1, 10], + # UInt32ByteSize(). + [wire_format.UInt32ByteSize, 0, 1], + [wire_format.UInt32ByteSize, 127, 1], + [wire_format.UInt32ByteSize, 128, 2], + [wire_format.UInt32ByteSize, wire_format.UINT32_MAX, 5], + # UInt64ByteSize(). + [wire_format.UInt64ByteSize, 0, 1], + [wire_format.UInt64ByteSize, 127, 1], + [wire_format.UInt64ByteSize, 128, 2], + [wire_format.UInt64ByteSize, wire_format.UINT64_MAX, 10], + # SInt32ByteSize(). + [wire_format.SInt32ByteSize, 0, 1], + [wire_format.SInt32ByteSize, -1, 1], + [wire_format.SInt32ByteSize, 1, 1], + [wire_format.SInt32ByteSize, -63, 1], + [wire_format.SInt32ByteSize, 63, 1], + [wire_format.SInt32ByteSize, -64, 1], + [wire_format.SInt32ByteSize, 64, 2], + # SInt64ByteSize(). + [wire_format.SInt64ByteSize, 0, 1], + [wire_format.SInt64ByteSize, -1, 1], + [wire_format.SInt64ByteSize, 1, 1], + [wire_format.SInt64ByteSize, -63, 1], + [wire_format.SInt64ByteSize, 63, 1], + [wire_format.SInt64ByteSize, -64, 1], + [wire_format.SInt64ByteSize, 64, 2], + # Fixed32ByteSize(). + [wire_format.Fixed32ByteSize, 0, 4], + [wire_format.Fixed32ByteSize, wire_format.UINT32_MAX, 4], + # Fixed64ByteSize(). + [wire_format.Fixed64ByteSize, 0, 8], + [wire_format.Fixed64ByteSize, wire_format.UINT64_MAX, 8], + # SFixed32ByteSize(). + [wire_format.SFixed32ByteSize, 0, 4], + [wire_format.SFixed32ByteSize, wire_format.INT32_MIN, 4], + [wire_format.SFixed32ByteSize, wire_format.INT32_MAX, 4], + # SFixed64ByteSize(). + [wire_format.SFixed64ByteSize, 0, 8], + [wire_format.SFixed64ByteSize, wire_format.INT64_MIN, 8], + [wire_format.SFixed64ByteSize, wire_format.INT64_MAX, 8], + # FloatByteSize(). + [wire_format.FloatByteSize, 0.0, 4], + [wire_format.FloatByteSize, 1000000000.0, 4], + [wire_format.FloatByteSize, -1000000000.0, 4], + # DoubleByteSize(). + [wire_format.DoubleByteSize, 0.0, 8], + [wire_format.DoubleByteSize, 1000000000.0, 8], + [wire_format.DoubleByteSize, -1000000000.0, 8], + # BoolByteSize(). + [wire_format.BoolByteSize, False, 1], + [wire_format.BoolByteSize, True, 1], + # EnumByteSize(). + [wire_format.EnumByteSize, 0, 1], + [wire_format.EnumByteSize, 127, 1], + [wire_format.EnumByteSize, 128, 2], + [wire_format.EnumByteSize, wire_format.UINT32_MAX, 5], + ] + for args in NUMERIC_ARGS: + self.NumericByteSizeTestHelper(*args) + + # Test strings and bytes. + for byte_size_fn in (wire_format.StringByteSize, wire_format.BytesByteSize): + # 1 byte for tag, 1 byte for length, 3 bytes for contents. + self.assertEqual(5, byte_size_fn(10, 'abc')) + # 2 bytes for tag, 1 byte for length, 3 bytes for contents. + self.assertEqual(6, byte_size_fn(16, 'abc')) + # 2 bytes for tag, 2 bytes for length, 128 bytes for contents. + self.assertEqual(132, byte_size_fn(16, 'a' * 128)) + + # Test UTF-8 string byte size calculation. + # 1 byte for tag, 1 byte for length, 8 bytes for content. + self.assertEqual(10, wire_format.StringByteSize( + 5, unicode('\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'))) + + class MockMessage(object): + def __init__(self, byte_size): + self.byte_size = byte_size + def ByteSize(self): + return self.byte_size + + message_byte_size = 10 + mock_message = MockMessage(byte_size=message_byte_size) + # Test groups. + # (2 * 1) bytes for begin and end tags, plus message_byte_size. + self.assertEqual(2 + message_byte_size, + wire_format.GroupByteSize(1, mock_message)) + # (2 * 2) bytes for begin and end tags, plus message_byte_size. + self.assertEqual(4 + message_byte_size, + wire_format.GroupByteSize(16, mock_message)) + + # Test messages. + # 1 byte for tag, plus 1 byte for length, plus contents. + self.assertEqual(2 + mock_message.byte_size, + wire_format.MessageByteSize(1, mock_message)) + # 2 bytes for tag, plus 1 byte for length, plus contents. + self.assertEqual(3 + mock_message.byte_size, + wire_format.MessageByteSize(16, mock_message)) + # 2 bytes for tag, plus 2 bytes for length, plus contents. + mock_message.byte_size = 128 + self.assertEqual(4 + mock_message.byte_size, + wire_format.MessageByteSize(16, mock_message)) + + + # Test message set item byte size. + # 4 bytes for tags, plus 1 byte for length, plus 1 byte for type_id, + # plus contents. + mock_message.byte_size = 10 + self.assertEqual(mock_message.byte_size + 6, + wire_format.MessageSetItemByteSize(1, mock_message)) + + # 4 bytes for tags, plus 2 bytes for length, plus 1 byte for type_id, + # plus contents. + mock_message.byte_size = 128 + self.assertEqual(mock_message.byte_size + 7, + wire_format.MessageSetItemByteSize(1, mock_message)) + + # 4 bytes for tags, plus 2 bytes for length, plus 2 byte for type_id, + # plus contents. + self.assertEqual(mock_message.byte_size + 8, + wire_format.MessageSetItemByteSize(128, mock_message)) + + # Too-long varint. + self.assertRaises(message.EncodeError, + wire_format.UInt64ByteSize, 1, 1 << 128) + + +if __name__ == '__main__': + unittest.main() diff --git a/code/push/google/protobuf/message.py b/code/push/google/protobuf/message.py new file mode 100644 index 0000000..6ec2f8b --- /dev/null +++ b/code/push/google/protobuf/message.py @@ -0,0 +1,280 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# TODO(robinson): We should just make these methods all "pure-virtual" and move +# all implementation out, into reflection.py for now. + + +"""Contains an abstract base class for protocol messages.""" + +__author__ = 'robinson@google.com (Will Robinson)' + + +class Error(Exception): pass +class DecodeError(Error): pass +class EncodeError(Error): pass + + +class Message(object): + + """Abstract base class for protocol messages. + + Protocol message classes are almost always generated by the protocol + compiler. These generated types subclass Message and implement the methods + shown below. + + TODO(robinson): Link to an HTML document here. + + TODO(robinson): Document that instances of this class will also + have an Extensions attribute with __getitem__ and __setitem__. + Again, not sure how to best convey this. + + TODO(robinson): Document that the class must also have a static + RegisterExtension(extension_field) method. + Not sure how to best express at this point. + """ + + # TODO(robinson): Document these fields and methods. + + __slots__ = [] + + DESCRIPTOR = None + + def __deepcopy__(self, memo=None): + clone = type(self)() + clone.MergeFrom(self) + return clone + + def __eq__(self, other_msg): + """Recursively compares two messages by value and structure.""" + raise NotImplementedError + + def __ne__(self, other_msg): + # Can't just say self != other_msg, since that would infinitely recurse. :) + return not self == other_msg + + def __hash__(self): + raise TypeError('unhashable object') + + def __str__(self): + """Outputs a human-readable representation of the message.""" + raise NotImplementedError + + def __unicode__(self): + """Outputs a human-readable representation of the message.""" + raise NotImplementedError + + def MergeFrom(self, other_msg): + """Merges the contents of the specified message into current message. + + This method merges the contents of the specified message into the current + message. Singular fields that are set in the specified message overwrite + the corresponding fields in the current message. Repeated fields are + appended. Singular sub-messages and groups are recursively merged. + + Args: + other_msg: Message to merge into the current message. + """ + raise NotImplementedError + + def CopyFrom(self, other_msg): + """Copies the content of the specified message into the current message. + + The method clears the current message and then merges the specified + message using MergeFrom. + + Args: + other_msg: Message to copy into the current one. + """ + if self is other_msg: + return + self.Clear() + self.MergeFrom(other_msg) + + def Clear(self): + """Clears all data that was set in the message.""" + raise NotImplementedError + + def SetInParent(self): + """Mark this as present in the parent. + + This normally happens automatically when you assign a field of a + sub-message, but sometimes you want to make the sub-message + present while keeping it empty. If you find yourself using this, + you may want to reconsider your design.""" + raise NotImplementedError + + def IsInitialized(self): + """Checks if the message is initialized. + + Returns: + The method returns True if the message is initialized (i.e. all of its + required fields are set). + """ + raise NotImplementedError + + # TODO(robinson): MergeFromString() should probably return None and be + # implemented in terms of a helper that returns the # of bytes read. Our + # deserialization routines would use the helper when recursively + # deserializing, but the end user would almost always just want the no-return + # MergeFromString(). + + def MergeFromString(self, serialized): + """Merges serialized protocol buffer data into this message. + + When we find a field in |serialized| that is already present + in this message: + - If it's a "repeated" field, we append to the end of our list. + - Else, if it's a scalar, we overwrite our field. + - Else, (it's a nonrepeated composite), we recursively merge + into the existing composite. + + TODO(robinson): Document handling of unknown fields. + + Args: + serialized: Any object that allows us to call buffer(serialized) + to access a string of bytes using the buffer interface. + + TODO(robinson): When we switch to a helper, this will return None. + + Returns: + The number of bytes read from |serialized|. + For non-group messages, this will always be len(serialized), + but for messages which are actually groups, this will + generally be less than len(serialized), since we must + stop when we reach an END_GROUP tag. Note that if + we *do* stop because of an END_GROUP tag, the number + of bytes returned does not include the bytes + for the END_GROUP tag information. + """ + raise NotImplementedError + + def ParseFromString(self, serialized): + """Like MergeFromString(), except we clear the object first.""" + self.Clear() + self.MergeFromString(serialized) + + def SerializeToString(self): + """Serializes the protocol message to a binary string. + + Returns: + A binary string representation of the message if all of the required + fields in the message are set (i.e. the message is initialized). + + Raises: + message.EncodeError if the message isn't initialized. + """ + raise NotImplementedError + + def SerializePartialToString(self): + """Serializes the protocol message to a binary string. + + This method is similar to SerializeToString but doesn't check if the + message is initialized. + + Returns: + A string representation of the partial message. + """ + raise NotImplementedError + + # TODO(robinson): Decide whether we like these better + # than auto-generated has_foo() and clear_foo() methods + # on the instances themselves. This way is less consistent + # with C++, but it makes reflection-type access easier and + # reduces the number of magically autogenerated things. + # + # TODO(robinson): Be sure to document (and test) exactly + # which field names are accepted here. Are we case-sensitive? + # What do we do with fields that share names with Python keywords + # like 'lambda' and 'yield'? + # + # nnorwitz says: + # """ + # Typically (in python), an underscore is appended to names that are + # keywords. So they would become lambda_ or yield_. + # """ + def ListFields(self): + """Returns a list of (FieldDescriptor, value) tuples for all + fields in the message which are not empty. A singular field is non-empty + if HasField() would return true, and a repeated field is non-empty if + it contains at least one element. The fields are ordered by field + number""" + raise NotImplementedError + + def HasField(self, field_name): + """Checks if a certain field is set for the message. Note if the + field_name is not defined in the message descriptor, ValueError will be + raised.""" + raise NotImplementedError + + def ClearField(self, field_name): + raise NotImplementedError + + def HasExtension(self, extension_handle): + raise NotImplementedError + + def ClearExtension(self, extension_handle): + raise NotImplementedError + + def ByteSize(self): + """Returns the serialized size of this message. + Recursively calls ByteSize() on all contained messages. + """ + raise NotImplementedError + + def _SetListener(self, message_listener): + """Internal method used by the protocol message implementation. + Clients should not call this directly. + + Sets a listener that this message will call on certain state transitions. + + The purpose of this method is to register back-edges from children to + parents at runtime, for the purpose of setting "has" bits and + byte-size-dirty bits in the parent and ancestor objects whenever a child or + descendant object is modified. + + If the client wants to disconnect this Message from the object tree, she + explicitly sets callback to None. + + If message_listener is None, unregisters any existing listener. Otherwise, + message_listener must implement the MessageListener interface in + internal/message_listener.py, and we discard any listener registered + via a previous _SetListener() call. + """ + raise NotImplementedError + + def __getstate__(self): + """Support the pickle protocol.""" + return dict(serialized=self.SerializePartialToString()) + + def __setstate__(self, state): + """Support the pickle protocol.""" + self.__init__() + self.ParseFromString(state['serialized']) diff --git a/code/push/google/protobuf/message_factory.py b/code/push/google/protobuf/message_factory.py new file mode 100644 index 0000000..36e2fef --- /dev/null +++ b/code/push/google/protobuf/message_factory.py @@ -0,0 +1,113 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Provides a factory class for generating dynamic messages.""" + +__author__ = 'matthewtoia@google.com (Matt Toia)' + +from google.protobuf import descriptor_database +from google.protobuf import descriptor_pool +from google.protobuf import message +from google.protobuf import reflection + + +class MessageFactory(object): + """Factory for creating Proto2 messages from descriptors in a pool.""" + + def __init__(self): + """Initializes a new factory.""" + self._classes = {} + + def GetPrototype(self, descriptor): + """Builds a proto2 message class based on the passed in descriptor. + + Passing a descriptor with a fully qualified name matching a previous + invocation will cause the same class to be returned. + + Args: + descriptor: The descriptor to build from. + + Returns: + A class describing the passed in descriptor. + """ + + if descriptor.full_name not in self._classes: + result_class = reflection.GeneratedProtocolMessageType( + descriptor.name.encode('ascii', 'ignore'), + (message.Message,), + {'DESCRIPTOR': descriptor}) + self._classes[descriptor.full_name] = result_class + for field in descriptor.fields: + if field.message_type: + self.GetPrototype(field.message_type) + return self._classes[descriptor.full_name] + + +_DB = descriptor_database.DescriptorDatabase() +_POOL = descriptor_pool.DescriptorPool(_DB) +_FACTORY = MessageFactory() + + +def GetMessages(file_protos): + """Builds a dictionary of all the messages available in a set of files. + + Args: + file_protos: A sequence of file protos to build messages out of. + + Returns: + A dictionary containing all the message types in the files mapping the + fully qualified name to a Message subclass for the descriptor. + """ + + result = {} + for file_proto in file_protos: + _DB.Add(file_proto) + for file_proto in file_protos: + for desc in _GetAllDescriptors(file_proto.message_type, file_proto.package): + result[desc.full_name] = _FACTORY.GetPrototype(desc) + return result + + +def _GetAllDescriptors(desc_protos, package): + """Gets all levels of nested message types as a flattened list of descriptors. + + Args: + desc_protos: The descriptor protos to process. + package: The package where the protos are defined. + + Yields: + Each message descriptor for each nested type. + """ + + for desc_proto in desc_protos: + name = '.'.join((package, desc_proto.name)) + yield _POOL.FindMessageTypeByName(name) + for nested_desc in _GetAllDescriptors(desc_proto.nested_type, name): + yield nested_desc diff --git a/code/push/google/protobuf/pyext/python-proto2.cc b/code/push/google/protobuf/pyext/python-proto2.cc new file mode 100644 index 0000000..eebb752 --- /dev/null +++ b/code/push/google/protobuf/pyext/python-proto2.cc @@ -0,0 +1,1717 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: petar@google.com (Petar Petrov) + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +/* Is 64bit */ +#define IS_64BIT (SIZEOF_LONG == 8) + +#define FIELD_BELONGS_TO_MESSAGE(field_descriptor, message) \ + ((message)->GetDescriptor() == (field_descriptor)->containing_type()) + +#define FIELD_IS_REPEATED(field_descriptor) \ + ((field_descriptor)->label() == google::protobuf::FieldDescriptor::LABEL_REPEATED) + +#define GOOGLE_CHECK_GET_INT32(arg, value) \ + int32 value; \ + if (!CheckAndGetInteger(arg, &value, kint32min_py, kint32max_py)) { \ + return NULL; \ + } + +#define GOOGLE_CHECK_GET_INT64(arg, value) \ + int64 value; \ + if (!CheckAndGetInteger(arg, &value, kint64min_py, kint64max_py)) { \ + return NULL; \ + } + +#define GOOGLE_CHECK_GET_UINT32(arg, value) \ + uint32 value; \ + if (!CheckAndGetInteger(arg, &value, kPythonZero, kuint32max_py)) { \ + return NULL; \ + } + +#define GOOGLE_CHECK_GET_UINT64(arg, value) \ + uint64 value; \ + if (!CheckAndGetInteger(arg, &value, kPythonZero, kuint64max_py)) { \ + return NULL; \ + } + +#define GOOGLE_CHECK_GET_FLOAT(arg, value) \ + float value; \ + if (!CheckAndGetFloat(arg, &value)) { \ + return NULL; \ + } \ + +#define GOOGLE_CHECK_GET_DOUBLE(arg, value) \ + double value; \ + if (!CheckAndGetDouble(arg, &value)) { \ + return NULL; \ + } + +#define GOOGLE_CHECK_GET_BOOL(arg, value) \ + bool value; \ + if (!CheckAndGetBool(arg, &value)) { \ + return NULL; \ + } + +#define C(str) const_cast(str) + +// --- Globals: + +// Constants used for integer type range checking. +static PyObject* kPythonZero; +static PyObject* kint32min_py; +static PyObject* kint32max_py; +static PyObject* kuint32max_py; +static PyObject* kint64min_py; +static PyObject* kint64max_py; +static PyObject* kuint64max_py; + +namespace google { +namespace protobuf { +namespace python { + +// --- Support Routines: + +static void AddConstants(PyObject* module) { + struct NameValue { + char* name; + int32 value; + } constants[] = { + // Labels: + {"LABEL_OPTIONAL", google::protobuf::FieldDescriptor::LABEL_OPTIONAL}, + {"LABEL_REQUIRED", google::protobuf::FieldDescriptor::LABEL_REQUIRED}, + {"LABEL_REPEATED", google::protobuf::FieldDescriptor::LABEL_REPEATED}, + // CPP types: + {"CPPTYPE_MESSAGE", google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE}, + // Field Types: + {"TYPE_MESSAGE", google::protobuf::FieldDescriptor::TYPE_MESSAGE}, + // End. + {NULL, 0} + }; + + for (NameValue* constant = constants; + constant->name != NULL; constant++) { + PyModule_AddIntConstant(module, constant->name, constant->value); + } +} + +// --- CMessage Custom Type: + +// ------ Type Forward Declaration: + +struct CMessage; +struct CMessage_Type; + +static void CMessageDealloc(CMessage* self); +static int CMessageInit(CMessage* self, PyObject *args, PyObject *kwds); +static PyObject* CMessageStr(CMessage* self); + +static PyObject* CMessage_AddMessage(CMessage* self, PyObject* args); +static PyObject* CMessage_AddRepeatedScalar(CMessage* self, PyObject* args); +static PyObject* CMessage_AssignRepeatedScalar(CMessage* self, PyObject* args); +static PyObject* CMessage_ByteSize(CMessage* self, PyObject* args); +static PyObject* CMessage_Clear(CMessage* self, PyObject* args); +static PyObject* CMessage_ClearField(CMessage* self, PyObject* args); +static PyObject* CMessage_ClearFieldByDescriptor( + CMessage* self, PyObject* args); +static PyObject* CMessage_CopyFrom(CMessage* self, PyObject* args); +static PyObject* CMessage_DebugString(CMessage* self, PyObject* args); +static PyObject* CMessage_DeleteRepeatedField(CMessage* self, PyObject* args); +static PyObject* CMessage_Equals(CMessage* self, PyObject* args); +static PyObject* CMessage_FieldLength(CMessage* self, PyObject* args); +static PyObject* CMessage_FindInitializationErrors(CMessage* self); +static PyObject* CMessage_GetRepeatedMessage(CMessage* self, PyObject* args); +static PyObject* CMessage_GetRepeatedScalar(CMessage* self, PyObject* args); +static PyObject* CMessage_GetScalar(CMessage* self, PyObject* args); +static PyObject* CMessage_HasField(CMessage* self, PyObject* args); +static PyObject* CMessage_HasFieldByDescriptor(CMessage* self, PyObject* args); +static PyObject* CMessage_IsInitialized(CMessage* self, PyObject* args); +static PyObject* CMessage_ListFields(CMessage* self, PyObject* args); +static PyObject* CMessage_MergeFrom(CMessage* self, PyObject* args); +static PyObject* CMessage_MergeFromString(CMessage* self, PyObject* args); +static PyObject* CMessage_MutableMessage(CMessage* self, PyObject* args); +static PyObject* CMessage_NewSubMessage(CMessage* self, PyObject* args); +static PyObject* CMessage_SetScalar(CMessage* self, PyObject* args); +static PyObject* CMessage_SerializePartialToString( + CMessage* self, PyObject* args); +static PyObject* CMessage_SerializeToString(CMessage* self, PyObject* args); +static PyObject* CMessage_SetInParent(CMessage* self, PyObject* args); +static PyObject* CMessage_SwapRepeatedFieldElements( + CMessage* self, PyObject* args); + +// ------ Object Definition: + +typedef struct CMessage { + PyObject_HEAD + + struct CMessage* parent; // NULL if wasn't created from another message. + CFieldDescriptor* parent_field; + const char* full_name; + google::protobuf::Message* message; + bool free_message; + bool read_only; +} CMessage; + +// ------ Method Table: + +#define CMETHOD(name, args, doc) \ + { C(#name), (PyCFunction)CMessage_##name, args, C(doc) } +static PyMethodDef CMessageMethods[] = { + CMETHOD(AddMessage, METH_O, + "Adds a new message to a repeated composite field."), + CMETHOD(AddRepeatedScalar, METH_VARARGS, + "Adds a scalar to a repeated scalar field."), + CMETHOD(AssignRepeatedScalar, METH_VARARGS, + "Clears and sets the values of a repeated scalar field."), + CMETHOD(ByteSize, METH_NOARGS, + "Returns the size of the message in bytes."), + CMETHOD(Clear, METH_O, + "Clears a protocol message."), + CMETHOD(ClearField, METH_VARARGS, + "Clears a protocol message field by name."), + CMETHOD(ClearFieldByDescriptor, METH_O, + "Clears a protocol message field by descriptor."), + CMETHOD(CopyFrom, METH_O, + "Copies a protocol message into the current message."), + CMETHOD(DebugString, METH_NOARGS, + "Returns the debug string of a protocol message."), + CMETHOD(DeleteRepeatedField, METH_VARARGS, + "Deletes a slice of values from a repeated field."), + CMETHOD(Equals, METH_O, + "Checks if two protocol messages are equal (by identity)."), + CMETHOD(FieldLength, METH_O, + "Returns the number of elements in a repeated field."), + CMETHOD(FindInitializationErrors, METH_NOARGS, + "Returns the initialization errors of a message."), + CMETHOD(GetRepeatedMessage, METH_VARARGS, + "Returns a message from a repeated composite field."), + CMETHOD(GetRepeatedScalar, METH_VARARGS, + "Returns a scalar value from a repeated scalar field."), + CMETHOD(GetScalar, METH_O, + "Returns the scalar value of a field."), + CMETHOD(HasField, METH_O, + "Checks if a message field is set."), + CMETHOD(HasFieldByDescriptor, METH_O, + "Checks if a message field is set by given its descriptor"), + CMETHOD(IsInitialized, METH_NOARGS, + "Checks if all required fields of a protocol message are set."), + CMETHOD(ListFields, METH_NOARGS, + "Lists all set fields of a message."), + CMETHOD(MergeFrom, METH_O, + "Merges a protocol message into the current message."), + CMETHOD(MergeFromString, METH_O, + "Merges a serialized message into the current message."), + CMETHOD(MutableMessage, METH_O, + "Returns a new instance of a nested protocol message."), + CMETHOD(NewSubMessage, METH_O, + "Creates and returns a python message given the descriptor of a " + "composite field of the current message."), + CMETHOD(SetScalar, METH_VARARGS, + "Sets the value of a singular scalar field."), + CMETHOD(SerializePartialToString, METH_VARARGS, + "Serializes the message to a string, even if it isn't initialized."), + CMETHOD(SerializeToString, METH_NOARGS, + "Serializes the message to a string, only for initialized messages."), + CMETHOD(SetInParent, METH_NOARGS, + "Sets the has bit of the given field in its parent message."), + CMETHOD(SwapRepeatedFieldElements, METH_VARARGS, + "Swaps the elements in two positions in a repeated field."), + { NULL, NULL } +}; +#undef CMETHOD + +static PyMemberDef CMessageMembers[] = { + { C("full_name"), T_STRING, offsetof(CMessage, full_name), 0, "Full name" }, + { NULL } +}; + +// ------ Type Definition: + +// The definition for the type object that captures the type of CMessage +// in Python. +PyTypeObject CMessage_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, + C("google.protobuf.internal." + "_net_proto2___python." + "CMessage"), // tp_name + sizeof(CMessage), // tp_basicsize + 0, // tp_itemsize + (destructor)CMessageDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + (reprfunc)CMessageStr, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + C("A ProtocolMessage"), // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + CMessageMethods, // tp_methods + CMessageMembers, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + (initproc)CMessageInit, // tp_init + PyType_GenericAlloc, // tp_alloc + PyType_GenericNew, // tp_new + PyObject_Del, // tp_free +}; + +// ------ Helper Functions: + +static void FormatTypeError(PyObject* arg, char* expected_types) { + PyObject* repr = PyObject_Repr(arg); + PyErr_Format(PyExc_TypeError, + "%.100s has type %.100s, but expected one of: %s", + PyString_AS_STRING(repr), + arg->ob_type->tp_name, + expected_types); + Py_DECREF(repr); +} + +template +static bool CheckAndGetInteger( + PyObject* arg, T* value, PyObject* min, PyObject* max) { + bool is_long = PyLong_Check(arg); + if (!PyInt_Check(arg) && !is_long) { + FormatTypeError(arg, "int, long"); + return false; + } + + if (PyObject_Compare(min, arg) > 0 || PyObject_Compare(max, arg) < 0) { + PyObject* s = PyObject_Str(arg); + PyErr_Format(PyExc_ValueError, + "Value out of range: %s", + PyString_AS_STRING(s)); + Py_DECREF(s); + return false; + } + if (is_long) { + if (min == kPythonZero) { + *value = static_cast(PyLong_AsUnsignedLongLong(arg)); + } else { + *value = static_cast(PyLong_AsLongLong(arg)); + } + } else { + *value = static_cast(PyInt_AsLong(arg)); + } + return true; +} + +static bool CheckAndGetDouble(PyObject* arg, double* value) { + if (!PyInt_Check(arg) && !PyLong_Check(arg) && + !PyFloat_Check(arg)) { + FormatTypeError(arg, "int, long, float"); + return false; + } + *value = PyFloat_AsDouble(arg); + return true; +} + +static bool CheckAndGetFloat(PyObject* arg, float* value) { + double double_value; + if (!CheckAndGetDouble(arg, &double_value)) { + return false; + } + *value = static_cast(double_value); + return true; +} + +static bool CheckAndGetBool(PyObject* arg, bool* value) { + if (!PyInt_Check(arg) && !PyBool_Check(arg) && !PyLong_Check(arg)) { + FormatTypeError(arg, "int, long, bool"); + return false; + } + *value = static_cast(PyInt_AsLong(arg)); + return true; +} + +google::protobuf::DynamicMessageFactory* global_message_factory = NULL; +static const google::protobuf::Message* CreateMessage(const char* message_type) { + string message_name(message_type); + const google::protobuf::Descriptor* descriptor = + GetDescriptorPool()->FindMessageTypeByName(message_name); + if (descriptor == NULL) { + return NULL; + } + return global_message_factory->GetPrototype(descriptor); +} + +static void ReleaseSubMessage(google::protobuf::Message* message, + const google::protobuf::FieldDescriptor* field_descriptor, + CMessage* child_cmessage) { + Message* released_message = message->GetReflection()->ReleaseMessage( + message, field_descriptor, global_message_factory); + GOOGLE_DCHECK(child_cmessage->message != NULL); + // ReleaseMessage will return NULL which differs from + // child_cmessage->message, if the field does not exist. In this case, + // the latter points to the default instance via a const_cast<>, so we + // have to reset it to a new mutable object since we are taking ownership. + if (released_message == NULL) { + const Message* prototype = global_message_factory->GetPrototype( + child_cmessage->message->GetDescriptor()); + GOOGLE_DCHECK(prototype != NULL); + child_cmessage->message = prototype->New(); + } + child_cmessage->parent = NULL; + child_cmessage->parent_field = NULL; + child_cmessage->free_message = true; + child_cmessage->read_only = false; +} + +static bool CheckAndSetString( + PyObject* arg, google::protobuf::Message* message, + const google::protobuf::FieldDescriptor* descriptor, + const google::protobuf::Reflection* reflection, + bool append, + int index) { + GOOGLE_DCHECK(descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING || + descriptor->type() == google::protobuf::FieldDescriptor::TYPE_BYTES); + if (descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING) { + if (!PyString_Check(arg) && !PyUnicode_Check(arg)) { + FormatTypeError(arg, "str, unicode"); + return false; + } + + if (PyString_Check(arg)) { + PyObject* unicode = PyUnicode_FromEncodedObject(arg, "ascii", NULL); + if (unicode == NULL) { + PyObject* repr = PyObject_Repr(arg); + PyErr_Format(PyExc_ValueError, + "%s has type str, but isn't in 7-bit ASCII " + "encoding. Non-ASCII strings must be converted to " + "unicode objects before being added.", + PyString_AS_STRING(repr)); + Py_DECREF(repr); + return false; + } else { + Py_DECREF(unicode); + } + } + } else if (!PyString_Check(arg)) { + FormatTypeError(arg, "str"); + return false; + } + + PyObject* encoded_string = NULL; + if (descriptor->type() == google::protobuf::FieldDescriptor::TYPE_STRING) { + if (PyString_Check(arg)) { + encoded_string = PyString_AsEncodedObject(arg, "utf-8", NULL); + } else { + encoded_string = PyUnicode_AsEncodedObject(arg, "utf-8", NULL); + } + } else { + // In this case field type is "bytes". + encoded_string = arg; + Py_INCREF(encoded_string); + } + + if (encoded_string == NULL) { + return false; + } + + char* value; + Py_ssize_t value_len; + if (PyString_AsStringAndSize(encoded_string, &value, &value_len) < 0) { + Py_DECREF(encoded_string); + return false; + } + + string value_string(value, value_len); + if (append) { + reflection->AddString(message, descriptor, value_string); + } else if (index < 0) { + reflection->SetString(message, descriptor, value_string); + } else { + reflection->SetRepeatedString(message, descriptor, index, value_string); + } + Py_DECREF(encoded_string); + return true; +} + +static PyObject* ToStringObject( + const google::protobuf::FieldDescriptor* descriptor, string value) { + if (descriptor->type() != google::protobuf::FieldDescriptor::TYPE_STRING) { + return PyString_FromStringAndSize(value.c_str(), value.length()); + } + + PyObject* result = PyUnicode_DecodeUTF8(value.c_str(), value.length(), NULL); + // If the string can't be decoded in UTF-8, just return a string object that + // contains the raw bytes. This can't happen if the value was assigned using + // the members of the Python message object, but can happen if the values were + // parsed from the wire (binary). + if (result == NULL) { + PyErr_Clear(); + result = PyString_FromStringAndSize(value.c_str(), value.length()); + } + return result; +} + +static void AssureWritable(CMessage* self) { + if (self == NULL || + self->parent == NULL || + self->parent_field == NULL) { + return; + } + + if (!self->read_only) { + return; + } + + AssureWritable(self->parent); + + google::protobuf::Message* message = self->parent->message; + const google::protobuf::Reflection* reflection = message->GetReflection(); + self->message = reflection->MutableMessage( + message, self->parent_field->descriptor, global_message_factory); + self->read_only = false; +} + +static PyObject* InternalGetScalar( + google::protobuf::Message* message, + const google::protobuf::FieldDescriptor* field_descriptor) { + const google::protobuf::Reflection* reflection = message->GetReflection(); + + if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) { + PyErr_SetString( + PyExc_KeyError, "Field does not belong to message!"); + return NULL; + } + + PyObject* result = NULL; + switch (field_descriptor->cpp_type()) { + case google::protobuf::FieldDescriptor::CPPTYPE_INT32: { + int32 value = reflection->GetInt32(*message, field_descriptor); + result = PyInt_FromLong(value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_INT64: { + int64 value = reflection->GetInt64(*message, field_descriptor); +#if IS_64BIT + result = PyInt_FromLong(value); +#else + result = PyLong_FromLongLong(value); +#endif + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: { + uint32 value = reflection->GetUInt32(*message, field_descriptor); +#if IS_64BIT + result = PyInt_FromLong(value); +#else + result = PyLong_FromLongLong(value); +#endif + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: { + uint64 value = reflection->GetUInt64(*message, field_descriptor); +#if IS_64BIT + if (value <= static_cast(kint64max)) { + result = PyInt_FromLong(static_cast(value)); + } +#else + if (value <= static_cast(kint32max)) { + result = PyInt_FromLong(static_cast(value)); + } +#endif + else { // NOLINT + result = PyLong_FromUnsignedLongLong(value); + } + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: { + float value = reflection->GetFloat(*message, field_descriptor); + result = PyFloat_FromDouble(value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: { + double value = reflection->GetDouble(*message, field_descriptor); + result = PyFloat_FromDouble(value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: { + bool value = reflection->GetBool(*message, field_descriptor); + result = PyBool_FromLong(value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_STRING: { + string value = reflection->GetString(*message, field_descriptor); + result = ToStringObject(field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: { + if (!message->GetReflection()->HasField(*message, field_descriptor)) { + // Look for the value in the unknown fields. + google::protobuf::UnknownFieldSet* unknown_field_set = + message->GetReflection()->MutableUnknownFields(message); + for (int i = 0; i < unknown_field_set->field_count(); ++i) { + if (unknown_field_set->field(i).number() == + field_descriptor->number()) { + result = PyInt_FromLong(unknown_field_set->field(i).varint()); + break; + } + } + } + + if (result == NULL) { + const google::protobuf::EnumValueDescriptor* enum_value = + message->GetReflection()->GetEnum(*message, field_descriptor); + result = PyInt_FromLong(enum_value->number()); + } + break; + } + default: + PyErr_Format( + PyExc_SystemError, "Getting a value from a field of unknown type %d", + field_descriptor->cpp_type()); + } + + return result; +} + +static PyObject* InternalSetScalar( + google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field_descriptor, + PyObject* arg) { + const google::protobuf::Reflection* reflection = message->GetReflection(); + + if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) { + PyErr_SetString( + PyExc_KeyError, "Field does not belong to message!"); + return NULL; + } + + switch (field_descriptor->cpp_type()) { + case google::protobuf::FieldDescriptor::CPPTYPE_INT32: { + GOOGLE_CHECK_GET_INT32(arg, value); + reflection->SetInt32(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_INT64: { + GOOGLE_CHECK_GET_INT64(arg, value); + reflection->SetInt64(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: { + GOOGLE_CHECK_GET_UINT32(arg, value); + reflection->SetUInt32(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: { + GOOGLE_CHECK_GET_UINT64(arg, value); + reflection->SetUInt64(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: { + GOOGLE_CHECK_GET_FLOAT(arg, value); + reflection->SetFloat(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: { + GOOGLE_CHECK_GET_DOUBLE(arg, value); + reflection->SetDouble(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: { + GOOGLE_CHECK_GET_BOOL(arg, value); + reflection->SetBool(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_STRING: { + if (!CheckAndSetString( + arg, message, field_descriptor, reflection, false, -1)) { + return NULL; + } + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: { + GOOGLE_CHECK_GET_INT32(arg, value); + const google::protobuf::EnumDescriptor* enum_descriptor = + field_descriptor->enum_type(); + const google::protobuf::EnumValueDescriptor* enum_value = + enum_descriptor->FindValueByNumber(value); + if (enum_value != NULL) { + reflection->SetEnum(message, field_descriptor, enum_value); + } else { + bool added = false; + // Add the value to the unknown fields. + google::protobuf::UnknownFieldSet* unknown_field_set = + message->GetReflection()->MutableUnknownFields(message); + for (int i = 0; i < unknown_field_set->field_count(); ++i) { + if (unknown_field_set->field(i).number() == + field_descriptor->number()) { + unknown_field_set->mutable_field(i)->set_varint(value); + added = true; + break; + } + } + + if (!added) { + unknown_field_set->AddVarint(field_descriptor->number(), value); + } + reflection->ClearField(message, field_descriptor); + } + break; + } + default: + PyErr_Format( + PyExc_SystemError, "Setting value to a field of unknown type %d", + field_descriptor->cpp_type()); + } + + Py_RETURN_NONE; +} + +static PyObject* InternalAddRepeatedScalar( + google::protobuf::Message* message, const google::protobuf::FieldDescriptor* field_descriptor, + PyObject* arg) { + + if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) { + PyErr_SetString( + PyExc_KeyError, "Field does not belong to message!"); + return NULL; + } + + const google::protobuf::Reflection* reflection = message->GetReflection(); + switch (field_descriptor->cpp_type()) { + case google::protobuf::FieldDescriptor::CPPTYPE_INT32: { + GOOGLE_CHECK_GET_INT32(arg, value); + reflection->AddInt32(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_INT64: { + GOOGLE_CHECK_GET_INT64(arg, value); + reflection->AddInt64(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: { + GOOGLE_CHECK_GET_UINT32(arg, value); + reflection->AddUInt32(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: { + GOOGLE_CHECK_GET_UINT64(arg, value); + reflection->AddUInt64(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: { + GOOGLE_CHECK_GET_FLOAT(arg, value); + reflection->AddFloat(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: { + GOOGLE_CHECK_GET_DOUBLE(arg, value); + reflection->AddDouble(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: { + GOOGLE_CHECK_GET_BOOL(arg, value); + reflection->AddBool(message, field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_STRING: { + if (!CheckAndSetString( + arg, message, field_descriptor, reflection, true, -1)) { + return NULL; + } + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: { + GOOGLE_CHECK_GET_INT32(arg, value); + const google::protobuf::EnumDescriptor* enum_descriptor = + field_descriptor->enum_type(); + const google::protobuf::EnumValueDescriptor* enum_value = + enum_descriptor->FindValueByNumber(value); + if (enum_value != NULL) { + reflection->AddEnum(message, field_descriptor, enum_value); + } else { + PyObject* s = PyObject_Str(arg); + PyErr_Format(PyExc_ValueError, "Unknown enum value: %s", + PyString_AS_STRING(s)); + Py_DECREF(s); + return NULL; + } + break; + } + default: + PyErr_Format( + PyExc_SystemError, "Adding value to a field of unknown type %d", + field_descriptor->cpp_type()); + } + + Py_RETURN_NONE; +} + +static PyObject* InternalGetRepeatedScalar( + CMessage* cmessage, const google::protobuf::FieldDescriptor* field_descriptor, + int index) { + google::protobuf::Message* message = cmessage->message; + const google::protobuf::Reflection* reflection = message->GetReflection(); + + int field_size = reflection->FieldSize(*message, field_descriptor); + if (index < 0) { + index = field_size + index; + } + if (index < 0 || index >= field_size) { + PyErr_Format(PyExc_IndexError, + "list assignment index (%d) out of range", index); + return NULL; + } + + PyObject* result = NULL; + switch (field_descriptor->cpp_type()) { + case google::protobuf::FieldDescriptor::CPPTYPE_INT32: { + int32 value = reflection->GetRepeatedInt32( + *message, field_descriptor, index); + result = PyInt_FromLong(value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_INT64: { + int64 value = reflection->GetRepeatedInt64( + *message, field_descriptor, index); + result = PyLong_FromLongLong(value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: { + uint32 value = reflection->GetRepeatedUInt32( + *message, field_descriptor, index); + result = PyLong_FromLongLong(value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: { + uint64 value = reflection->GetRepeatedUInt64( + *message, field_descriptor, index); + result = PyLong_FromUnsignedLongLong(value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: { + float value = reflection->GetRepeatedFloat( + *message, field_descriptor, index); + result = PyFloat_FromDouble(value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: { + double value = reflection->GetRepeatedDouble( + *message, field_descriptor, index); + result = PyFloat_FromDouble(value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: { + bool value = reflection->GetRepeatedBool( + *message, field_descriptor, index); + result = PyBool_FromLong(value ? 1 : 0); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: { + const google::protobuf::EnumValueDescriptor* enum_value = + message->GetReflection()->GetRepeatedEnum( + *message, field_descriptor, index); + result = PyInt_FromLong(enum_value->number()); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_STRING: { + string value = reflection->GetRepeatedString( + *message, field_descriptor, index); + result = ToStringObject(field_descriptor, value); + break; + } + case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE: { + CMessage* py_cmsg = PyObject_New(CMessage, &CMessage_Type); + if (py_cmsg == NULL) { + return NULL; + } + const google::protobuf::Message& msg = reflection->GetRepeatedMessage( + *message, field_descriptor, index); + py_cmsg->parent = cmessage; + py_cmsg->full_name = field_descriptor->full_name().c_str(); + py_cmsg->message = const_cast(&msg); + py_cmsg->free_message = false; + py_cmsg->read_only = false; + result = reinterpret_cast(py_cmsg); + break; + } + default: + PyErr_Format( + PyExc_SystemError, + "Getting value from a repeated field of unknown type %d", + field_descriptor->cpp_type()); + } + + return result; +} + +static PyObject* InternalGetRepeatedScalarSlice( + CMessage* cmessage, const google::protobuf::FieldDescriptor* field_descriptor, + PyObject* slice) { + Py_ssize_t from; + Py_ssize_t to; + Py_ssize_t step; + Py_ssize_t length; + bool return_list = false; + google::protobuf::Message* message = cmessage->message; + + if (PyInt_Check(slice)) { + from = to = PyInt_AsLong(slice); + } else if (PyLong_Check(slice)) { + from = to = PyLong_AsLong(slice); + } else if (PySlice_Check(slice)) { + const google::protobuf::Reflection* reflection = message->GetReflection(); + length = reflection->FieldSize(*message, field_descriptor); + PySlice_GetIndices( + reinterpret_cast(slice), length, &from, &to, &step); + return_list = true; + } else { + PyErr_SetString(PyExc_TypeError, "list indices must be integers"); + return NULL; + } + + if (!return_list) { + return InternalGetRepeatedScalar(cmessage, field_descriptor, from); + } + + PyObject* list = PyList_New(0); + if (list == NULL) { + return NULL; + } + + if (from <= to) { + if (step < 0) return list; + for (Py_ssize_t index = from; index < to; index += step) { + if (index < 0 || index >= length) break; + PyObject* s = InternalGetRepeatedScalar( + cmessage, field_descriptor, index); + PyList_Append(list, s); + Py_DECREF(s); + } + } else { + if (step > 0) return list; + for (Py_ssize_t index = from; index > to; index += step) { + if (index < 0 || index >= length) break; + PyObject* s = InternalGetRepeatedScalar( + cmessage, field_descriptor, index); + PyList_Append(list, s); + Py_DECREF(s); + } + } + return list; +} + +// ------ C Constructor/Destructor: + +static int CMessageInit(CMessage* self, PyObject *args, PyObject *kwds) { + self->message = NULL; + return 0; +} + +static void CMessageDealloc(CMessage* self) { + if (self->free_message) { + if (self->read_only) { + PyErr_WriteUnraisable(reinterpret_cast(self)); + } + delete self->message; + } + self->ob_type->tp_free(reinterpret_cast(self)); +} + +// ------ Methods: + +static PyObject* CMessage_Clear(CMessage* self, PyObject* arg) { + AssureWritable(self); + google::protobuf::Message* message = self->message; + + // This block of code is equivalent to the following: + // for cfield_descriptor, child_cmessage in arg: + // ReleaseSubMessage(cfield_descriptor, child_cmessage) + if (!PyList_Check(arg)) { + PyErr_SetString(PyExc_TypeError, "Must be a list"); + return NULL; + } + PyObject* messages_to_clear = arg; + Py_ssize_t num_messages_to_clear = PyList_GET_SIZE(messages_to_clear); + for(int i = 0; i < num_messages_to_clear; ++i) { + PyObject* message_tuple = PyList_GET_ITEM(messages_to_clear, i); + if (!PyTuple_Check(message_tuple) || PyTuple_GET_SIZE(message_tuple) != 2) { + PyErr_SetString(PyExc_TypeError, "Must be a tuple of size 2"); + return NULL; + } + + PyObject* py_cfield_descriptor = PyTuple_GET_ITEM(message_tuple, 0); + PyObject* py_child_cmessage = PyTuple_GET_ITEM(message_tuple, 1); + if (!PyObject_TypeCheck(py_cfield_descriptor, &CFieldDescriptor_Type) || + !PyObject_TypeCheck(py_child_cmessage, &CMessage_Type)) { + PyErr_SetString(PyExc_ValueError, "Invalid Tuple"); + return NULL; + } + + CFieldDescriptor* cfield_descriptor = reinterpret_cast( + py_cfield_descriptor); + CMessage* child_cmessage = reinterpret_cast(py_child_cmessage); + ReleaseSubMessage(message, cfield_descriptor->descriptor, child_cmessage); + } + + message->Clear(); + Py_RETURN_NONE; +} + +static PyObject* CMessage_IsInitialized(CMessage* self, PyObject* args) { + return PyBool_FromLong(self->message->IsInitialized() ? 1 : 0); +} + +static PyObject* CMessage_HasField(CMessage* self, PyObject* arg) { + char* field_name; + if (PyString_AsStringAndSize(arg, &field_name, NULL) < 0) { + return NULL; + } + + google::protobuf::Message* message = self->message; + const google::protobuf::Descriptor* descriptor = message->GetDescriptor(); + const google::protobuf::FieldDescriptor* field_descriptor = + descriptor->FindFieldByName(field_name); + if (field_descriptor == NULL) { + PyErr_Format(PyExc_ValueError, "Unknown field %s.", field_name); + return NULL; + } + + bool has_field = + message->GetReflection()->HasField(*message, field_descriptor); + return PyBool_FromLong(has_field ? 1 : 0); +} + +static PyObject* CMessage_HasFieldByDescriptor(CMessage* self, PyObject* arg) { + CFieldDescriptor* cfield_descriptor = NULL; + if (!PyObject_TypeCheck(reinterpret_cast(arg), + &CFieldDescriptor_Type)) { + PyErr_SetString(PyExc_TypeError, "Must be a field descriptor"); + return NULL; + } + cfield_descriptor = reinterpret_cast(arg); + + google::protobuf::Message* message = self->message; + const google::protobuf::FieldDescriptor* field_descriptor = + cfield_descriptor->descriptor; + + if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) { + PyErr_SetString(PyExc_KeyError, + "Field does not belong to message!"); + return NULL; + } + + if (FIELD_IS_REPEATED(field_descriptor)) { + PyErr_SetString(PyExc_KeyError, + "Field is repeated. A singular method is required."); + return NULL; + } + + bool has_field = + message->GetReflection()->HasField(*message, field_descriptor); + return PyBool_FromLong(has_field ? 1 : 0); +} + +static PyObject* CMessage_ClearFieldByDescriptor( + CMessage* self, PyObject* arg) { + CFieldDescriptor* cfield_descriptor = NULL; + if (!PyObject_TypeCheck(reinterpret_cast(arg), + &CFieldDescriptor_Type)) { + PyErr_SetString(PyExc_TypeError, "Must be a field descriptor"); + return NULL; + } + cfield_descriptor = reinterpret_cast(arg); + + google::protobuf::Message* message = self->message; + const google::protobuf::FieldDescriptor* field_descriptor = + cfield_descriptor->descriptor; + + if (!FIELD_BELONGS_TO_MESSAGE(field_descriptor, message)) { + PyErr_SetString(PyExc_KeyError, + "Field does not belong to message!"); + return NULL; + } + + message->GetReflection()->ClearField(message, field_descriptor); + Py_RETURN_NONE; +} + +static PyObject* CMessage_ClearField(CMessage* self, PyObject* args) { + char* field_name; + CMessage* child_cmessage = NULL; + if (!PyArg_ParseTuple(args, C("s|O!:ClearField"), &field_name, + &CMessage_Type, &child_cmessage)) { + return NULL; + } + + google::protobuf::Message* message = self->message; + const google::protobuf::Descriptor* descriptor = message->GetDescriptor(); + const google::protobuf::FieldDescriptor* field_descriptor = + descriptor->FindFieldByName(field_name); + if (field_descriptor == NULL) { + PyErr_Format(PyExc_ValueError, "Unknown field %s.", field_name); + return NULL; + } + + if (child_cmessage != NULL && !FIELD_IS_REPEATED(field_descriptor)) { + ReleaseSubMessage(message, field_descriptor, child_cmessage); + } else { + message->GetReflection()->ClearField(message, field_descriptor); + } + Py_RETURN_NONE; +} + +static PyObject* CMessage_GetScalar(CMessage* self, PyObject* arg) { + CFieldDescriptor* cdescriptor = NULL; + if (!PyObject_TypeCheck(reinterpret_cast(arg), + &CFieldDescriptor_Type)) { + PyErr_SetString(PyExc_TypeError, "Must be a field descriptor"); + return NULL; + } + cdescriptor = reinterpret_cast(arg); + + google::protobuf::Message* message = self->message; + return InternalGetScalar(message, cdescriptor->descriptor); +} + +static PyObject* CMessage_GetRepeatedScalar(CMessage* self, PyObject* args) { + CFieldDescriptor* cfield_descriptor; + PyObject* slice; + if (!PyArg_ParseTuple(args, C("O!O:GetRepeatedScalar"), + &CFieldDescriptor_Type, &cfield_descriptor, &slice)) { + return NULL; + } + + return InternalGetRepeatedScalarSlice( + self, cfield_descriptor->descriptor, slice); +} + +static PyObject* CMessage_AssignRepeatedScalar(CMessage* self, PyObject* args) { + CFieldDescriptor* cfield_descriptor; + PyObject* slice; + if (!PyArg_ParseTuple(args, C("O!O:AssignRepeatedScalar"), + &CFieldDescriptor_Type, &cfield_descriptor, &slice)) { + return NULL; + } + + AssureWritable(self); + google::protobuf::Message* message = self->message; + message->GetReflection()->ClearField(message, cfield_descriptor->descriptor); + + PyObject* iter = PyObject_GetIter(slice); + PyObject* next; + while ((next = PyIter_Next(iter)) != NULL) { + if (InternalAddRepeatedScalar( + message, cfield_descriptor->descriptor, next) == NULL) { + Py_DECREF(next); + Py_DECREF(iter); + return NULL; + } + Py_DECREF(next); + } + Py_DECREF(iter); + Py_RETURN_NONE; +} + +static PyObject* CMessage_DeleteRepeatedField(CMessage* self, PyObject* args) { + CFieldDescriptor* cfield_descriptor; + PyObject* slice; + if (!PyArg_ParseTuple(args, C("O!O:DeleteRepeatedField"), + &CFieldDescriptor_Type, &cfield_descriptor, &slice)) { + return NULL; + } + AssureWritable(self); + + Py_ssize_t length, from, to, step, slice_length; + google::protobuf::Message* message = self->message; + const google::protobuf::FieldDescriptor* field_descriptor = + cfield_descriptor->descriptor; + const google::protobuf::Reflection* reflection = message->GetReflection(); + int min, max; + length = reflection->FieldSize(*message, field_descriptor); + + if (PyInt_Check(slice) || PyLong_Check(slice)) { + from = to = PyLong_AsLong(slice); + if (from < 0) { + from = to = length + from; + } + step = 1; + min = max = from; + + // Range check. + if (from < 0 || from >= length) { + PyErr_Format(PyExc_IndexError, "list assignment index out of range"); + return NULL; + } + } else if (PySlice_Check(slice)) { + from = to = step = slice_length = 0; + PySlice_GetIndicesEx( + reinterpret_cast(slice), + length, &from, &to, &step, &slice_length); + if (from < to) { + min = from; + max = to - 1; + } else { + min = to + 1; + max = from; + } + } else { + PyErr_SetString(PyExc_TypeError, "list indices must be integers"); + return NULL; + } + + Py_ssize_t i = from; + std::vector to_delete(length, false); + while (i >= min && i <= max) { + to_delete[i] = true; + i += step; + } + + to = 0; + for (i = 0; i < length; ++i) { + if (!to_delete[i]) { + if (i != to) { + reflection->SwapElements(message, field_descriptor, i, to); + } + ++to; + } + } + + while (i > to) { + reflection->RemoveLast(message, field_descriptor); + --i; + } + + Py_RETURN_NONE; +} + + +static PyObject* CMessage_SetScalar(CMessage* self, PyObject* args) { + CFieldDescriptor* cfield_descriptor; + PyObject* arg; + if (!PyArg_ParseTuple(args, C("O!O:SetScalar"), + &CFieldDescriptor_Type, &cfield_descriptor, &arg)) { + return NULL; + } + AssureWritable(self); + + return InternalSetScalar(self->message, cfield_descriptor->descriptor, arg); +} + +static PyObject* CMessage_AddRepeatedScalar(CMessage* self, PyObject* args) { + CFieldDescriptor* cfield_descriptor; + PyObject* value; + if (!PyArg_ParseTuple(args, C("O!O:AddRepeatedScalar"), + &CFieldDescriptor_Type, &cfield_descriptor, &value)) { + return NULL; + } + AssureWritable(self); + + return InternalAddRepeatedScalar( + self->message, cfield_descriptor->descriptor, value); +} + +static PyObject* CMessage_FieldLength(CMessage* self, PyObject* arg) { + CFieldDescriptor* cfield_descriptor; + if (!PyObject_TypeCheck(reinterpret_cast(arg), + &CFieldDescriptor_Type)) { + PyErr_SetString(PyExc_TypeError, "Must be a field descriptor"); + return NULL; + } + cfield_descriptor = reinterpret_cast(arg); + + google::protobuf::Message* message = self->message; + int length = message->GetReflection()->FieldSize( + *message, cfield_descriptor->descriptor); + return PyInt_FromLong(length); +} + +static PyObject* CMessage_DebugString(CMessage* self, PyObject* args) { + return PyString_FromString(self->message->DebugString().c_str()); +} + +static PyObject* CMessage_SerializeToString(CMessage* self, PyObject* args) { + int size = self->message->ByteSize(); + if (size <= 0) { + return PyString_FromString(""); + } + PyObject* result = PyString_FromStringAndSize(NULL, size); + if (result == NULL) { + return NULL; + } + char* buffer = PyString_AS_STRING(result); + self->message->SerializeWithCachedSizesToArray( + reinterpret_cast(buffer)); + return result; +} + +static PyObject* CMessage_SerializePartialToString( + CMessage* self, PyObject* args) { + string contents; + self->message->SerializePartialToString(&contents); + return PyString_FromStringAndSize(contents.c_str(), contents.size()); +} + +static PyObject* CMessageStr(CMessage* self) { + char str[1024]; + str[sizeof(str) - 1] = 0; + snprintf(str, sizeof(str) - 1, "CMessage: <%p>", self->message); + return PyString_FromString(str); +} + +static PyObject* CMessage_MergeFrom(CMessage* self, PyObject* arg) { + CMessage* other_message; + if (!PyObject_TypeCheck(reinterpret_cast(arg), &CMessage_Type)) { + PyErr_SetString(PyExc_TypeError, "Must be a message"); + return NULL; + } + + other_message = reinterpret_cast(arg); + if (other_message->message->GetDescriptor() != + self->message->GetDescriptor()) { + PyErr_Format(PyExc_TypeError, + "Tried to merge from a message with a different type. " + "to: %s, from: %s", + self->message->GetDescriptor()->full_name().c_str(), + other_message->message->GetDescriptor()->full_name().c_str()); + return NULL; + } + AssureWritable(self); + + self->message->MergeFrom(*other_message->message); + Py_RETURN_NONE; +} + +static PyObject* CMessage_CopyFrom(CMessage* self, PyObject* arg) { + CMessage* other_message; + if (!PyObject_TypeCheck(reinterpret_cast(arg), &CMessage_Type)) { + PyErr_SetString(PyExc_TypeError, "Must be a message"); + return NULL; + } + + other_message = reinterpret_cast(arg); + if (other_message->message->GetDescriptor() != + self->message->GetDescriptor()) { + PyErr_Format(PyExc_TypeError, + "Tried to copy from a message with a different type. " + "to: %s, from: %s", + self->message->GetDescriptor()->full_name().c_str(), + other_message->message->GetDescriptor()->full_name().c_str()); + return NULL; + } + + AssureWritable(self); + + self->message->CopyFrom(*other_message->message); + Py_RETURN_NONE; +} + +static PyObject* CMessage_MergeFromString(CMessage* self, PyObject* arg) { + const void* data; + Py_ssize_t data_length; + if (PyObject_AsReadBuffer(arg, &data, &data_length) < 0) { + return NULL; + } + + AssureWritable(self); + google::protobuf::io::CodedInputStream input( + reinterpret_cast(data), data_length); + input.SetExtensionRegistry(GetDescriptorPool(), global_message_factory); + bool success = self->message->MergePartialFromCodedStream(&input); + if (success) { + return PyInt_FromLong(self->message->ByteSize()); + } else { + return PyInt_FromLong(-1); + } +} + +static PyObject* CMessage_ByteSize(CMessage* self, PyObject* args) { + return PyLong_FromLong(self->message->ByteSize()); +} + +static PyObject* CMessage_SetInParent(CMessage* self, PyObject* args) { + AssureWritable(self); + Py_RETURN_NONE; +} + +static PyObject* CMessage_SwapRepeatedFieldElements( + CMessage* self, PyObject* args) { + CFieldDescriptor* cfield_descriptor; + int index1, index2; + if (!PyArg_ParseTuple(args, C("O!ii:SwapRepeatedFieldElements"), + &CFieldDescriptor_Type, &cfield_descriptor, + &index1, &index2)) { + return NULL; + } + + google::protobuf::Message* message = self->message; + const google::protobuf::Reflection* reflection = message->GetReflection(); + + reflection->SwapElements( + message, cfield_descriptor->descriptor, index1, index2); + Py_RETURN_NONE; +} + +static PyObject* CMessage_AddMessage(CMessage* self, PyObject* arg) { + CFieldDescriptor* cfield_descriptor; + if (!PyObject_TypeCheck(reinterpret_cast(arg), + &CFieldDescriptor_Type)) { + PyErr_SetString(PyExc_TypeError, "Must be a field descriptor"); + return NULL; + } + cfield_descriptor = reinterpret_cast(arg); + AssureWritable(self); + + CMessage* py_cmsg = PyObject_New(CMessage, &CMessage_Type); + if (py_cmsg == NULL) { + return NULL; + } + + google::protobuf::Message* message = self->message; + const google::protobuf::Reflection* reflection = message->GetReflection(); + google::protobuf::Message* sub_message = + reflection->AddMessage(message, cfield_descriptor->descriptor); + + py_cmsg->parent = NULL; + py_cmsg->full_name = sub_message->GetDescriptor()->full_name().c_str(); + py_cmsg->message = sub_message; + py_cmsg->free_message = false; + py_cmsg->read_only = false; + return reinterpret_cast(py_cmsg); +} + +static PyObject* CMessage_GetRepeatedMessage(CMessage* self, PyObject* args) { + CFieldDescriptor* cfield_descriptor; + PyObject* slice; + if (!PyArg_ParseTuple(args, C("O!O:GetRepeatedMessage"), + &CFieldDescriptor_Type, &cfield_descriptor, &slice)) { + return NULL; + } + + return InternalGetRepeatedScalarSlice( + self, cfield_descriptor->descriptor, slice); +} + +static PyObject* CMessage_NewSubMessage(CMessage* self, PyObject* arg) { + CFieldDescriptor* cfield_descriptor; + if (!PyObject_TypeCheck(reinterpret_cast(arg), + &CFieldDescriptor_Type)) { + PyErr_SetString(PyExc_TypeError, "Must be a field descriptor"); + return NULL; + } + cfield_descriptor = reinterpret_cast(arg); + + CMessage* py_cmsg = PyObject_New(CMessage, &CMessage_Type); + if (py_cmsg == NULL) { + return NULL; + } + + google::protobuf::Message* message = self->message; + const google::protobuf::Reflection* reflection = message->GetReflection(); + const google::protobuf::Message& sub_message = + reflection->GetMessage(*message, cfield_descriptor->descriptor, + global_message_factory); + + py_cmsg->full_name = sub_message.GetDescriptor()->full_name().c_str(); + py_cmsg->parent = self; + py_cmsg->parent_field = cfield_descriptor; + py_cmsg->message = const_cast(&sub_message); + py_cmsg->free_message = false; + py_cmsg->read_only = true; + return reinterpret_cast(py_cmsg); +} + +static PyObject* CMessage_MutableMessage(CMessage* self, PyObject* arg) { + CFieldDescriptor* cfield_descriptor; + if (!PyObject_TypeCheck(reinterpret_cast(arg), + &CFieldDescriptor_Type)) { + PyErr_SetString(PyExc_TypeError, "Must be a field descriptor"); + return NULL; + } + cfield_descriptor = reinterpret_cast(arg); + AssureWritable(self); + + CMessage* py_cmsg = PyObject_New(CMessage, &CMessage_Type); + if (py_cmsg == NULL) { + return NULL; + } + + google::protobuf::Message* message = self->message; + const google::protobuf::Reflection* reflection = message->GetReflection(); + google::protobuf::Message* mutable_message = + reflection->MutableMessage(message, cfield_descriptor->descriptor, + global_message_factory); + + py_cmsg->full_name = mutable_message->GetDescriptor()->full_name().c_str(); + py_cmsg->message = mutable_message; + py_cmsg->free_message = false; + py_cmsg->read_only = false; + return reinterpret_cast(py_cmsg); +} + +static PyObject* CMessage_Equals(CMessage* self, PyObject* arg) { + CMessage* other_message; + if (!PyObject_TypeCheck(reinterpret_cast(arg), &CMessage_Type)) { + PyErr_SetString(PyExc_TypeError, "Must be a message"); + return NULL; + } + other_message = reinterpret_cast(arg); + + if (other_message->message == self->message) { + return PyBool_FromLong(1); + } + + if (other_message->message->GetDescriptor() != + self->message->GetDescriptor()) { + return PyBool_FromLong(0); + } + + return PyBool_FromLong(1); +} + +static PyObject* CMessage_ListFields(CMessage* self, PyObject* args) { + google::protobuf::Message* message = self->message; + const google::protobuf::Reflection* reflection = message->GetReflection(); + vector fields; + reflection->ListFields(*message, &fields); + + PyObject* list = PyList_New(fields.size()); + if (list == NULL) { + return NULL; + } + + for (unsigned int i = 0; i < fields.size(); ++i) { + bool is_extension = fields[i]->is_extension(); + PyObject* t = PyTuple_New(2); + if (t == NULL) { + Py_DECREF(list); + return NULL; + } + + PyObject* is_extension_object = PyBool_FromLong(is_extension ? 1 : 0); + + PyObject* field_name; + const string* s; + if (is_extension) { + s = &fields[i]->full_name(); + } else { + s = &fields[i]->name(); + } + field_name = PyString_FromStringAndSize(s->c_str(), s->length()); + if (field_name == NULL) { + Py_DECREF(list); + Py_DECREF(t); + return NULL; + } + + PyTuple_SET_ITEM(t, 0, is_extension_object); + PyTuple_SET_ITEM(t, 1, field_name); + PyList_SET_ITEM(list, i, t); + } + + return list; +} + +static PyObject* CMessage_FindInitializationErrors(CMessage* self) { + google::protobuf::Message* message = self->message; + vector errors; + message->FindInitializationErrors(&errors); + + PyObject* error_list = PyList_New(errors.size()); + if (error_list == NULL) { + return NULL; + } + for (unsigned int i = 0; i < errors.size(); ++i) { + const string& error = errors[i]; + PyObject* error_string = PyString_FromStringAndSize( + error.c_str(), error.length()); + if (error_string == NULL) { + Py_DECREF(error_list); + return NULL; + } + PyList_SET_ITEM(error_list, i, error_string); + } + return error_list; +} + +// ------ Python Constructor: + +PyObject* Python_NewCMessage(PyObject* ignored, PyObject* arg) { + const char* message_type = PyString_AsString(arg); + if (message_type == NULL) { + return NULL; + } + + const google::protobuf::Message* message = CreateMessage(message_type); + if (message == NULL) { + PyErr_Format(PyExc_TypeError, "Couldn't create message of type %s!", + message_type); + return NULL; + } + + CMessage* py_cmsg = PyObject_New(CMessage, &CMessage_Type); + if (py_cmsg == NULL) { + return NULL; + } + py_cmsg->message = message->New(); + py_cmsg->free_message = true; + py_cmsg->full_name = message->GetDescriptor()->full_name().c_str(); + py_cmsg->read_only = false; + py_cmsg->parent = NULL; + py_cmsg->parent_field = NULL; + return reinterpret_cast(py_cmsg); +} + +// --- Module Functions (exposed to Python): + +PyMethodDef methods[] = { + { C("NewCMessage"), (PyCFunction)Python_NewCMessage, + METH_O, + C("Creates a new C++ protocol message, given its full name.") }, + { C("NewCDescriptorPool"), (PyCFunction)Python_NewCDescriptorPool, + METH_NOARGS, + C("Creates a new C++ descriptor pool.") }, + { C("BuildFile"), (PyCFunction)Python_BuildFile, + METH_O, + C("Registers a new protocol buffer file in the global C++ descriptor " + "pool.") }, + {NULL} +}; + +// --- Exposing the C proto living inside Python proto to C code: + +extern const Message* (*GetCProtoInsidePyProtoPtr)(PyObject* msg); +extern Message* (*MutableCProtoInsidePyProtoPtr)(PyObject* msg); + +static const google::protobuf::Message* GetCProtoInsidePyProtoImpl(PyObject* msg) { + PyObject* c_msg_obj = PyObject_GetAttrString(msg, "_cmsg"); + if (c_msg_obj == NULL) { + PyErr_Clear(); + return NULL; + } + Py_DECREF(c_msg_obj); + if (!PyObject_TypeCheck(c_msg_obj, &CMessage_Type)) { + return NULL; + } + CMessage* c_msg = reinterpret_cast(c_msg_obj); + return c_msg->message; +} + +static google::protobuf::Message* MutableCProtoInsidePyProtoImpl(PyObject* msg) { + PyObject* c_msg_obj = PyObject_GetAttrString(msg, "_cmsg"); + if (c_msg_obj == NULL) { + PyErr_Clear(); + return NULL; + } + Py_DECREF(c_msg_obj); + if (!PyObject_TypeCheck(c_msg_obj, &CMessage_Type)) { + return NULL; + } + CMessage* c_msg = reinterpret_cast(c_msg_obj); + AssureWritable(c_msg); + return c_msg->message; +} + +// --- Module Init Function: + +static const char module_docstring[] = +"python-proto2 is a module that can be used to enhance proto2 Python API\n" +"performance.\n" +"\n" +"It provides access to the protocol buffers C++ reflection API that\n" +"implements the basic protocol buffer functions."; + +extern "C" { + void init_net_proto2___python() { + // Initialize constants. + kPythonZero = PyInt_FromLong(0); + kint32min_py = PyInt_FromLong(kint32min); + kint32max_py = PyInt_FromLong(kint32max); + kuint32max_py = PyLong_FromLongLong(kuint32max); + kint64min_py = PyLong_FromLongLong(kint64min); + kint64max_py = PyLong_FromLongLong(kint64max); + kuint64max_py = PyLong_FromUnsignedLongLong(kuint64max); + + global_message_factory = new DynamicMessageFactory(GetDescriptorPool()); + global_message_factory->SetDelegateToGeneratedFactory(true); + + // Export our functions to Python. + PyObject *m; + m = Py_InitModule3(C("_net_proto2___python"), methods, C(module_docstring)); + if (m == NULL) { + return; + } + + AddConstants(m); + + CMessage_Type.tp_new = PyType_GenericNew; + if (PyType_Ready(&CMessage_Type) < 0) { + return; + } + + if (!InitDescriptor()) { + return; + } + + // Override {Get,Mutable}CProtoInsidePyProto. + GetCProtoInsidePyProtoPtr = GetCProtoInsidePyProtoImpl; + MutableCProtoInsidePyProtoPtr = MutableCProtoInsidePyProtoImpl; + } +} + +} // namespace python +} // namespace protobuf +} // namespace google diff --git a/code/push/google/protobuf/pyext/python_descriptor.cc b/code/push/google/protobuf/pyext/python_descriptor.cc new file mode 100644 index 0000000..5e3e9ea --- /dev/null +++ b/code/push/google/protobuf/pyext/python_descriptor.cc @@ -0,0 +1,337 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: petar@google.com (Petar Petrov) + +#include +#include + +#include +#include + +#define C(str) const_cast(str) + +namespace google { +namespace protobuf { +namespace python { + + +static void CFieldDescriptorDealloc(CFieldDescriptor* self); + +static google::protobuf::DescriptorPool* g_descriptor_pool = NULL; + +static PyObject* CFieldDescriptor_GetFullName( + CFieldDescriptor* self, void *closure) { + Py_XINCREF(self->full_name); + return self->full_name; +} + +static PyObject* CFieldDescriptor_GetName( + CFieldDescriptor *self, void *closure) { + Py_XINCREF(self->name); + return self->name; +} + +static PyObject* CFieldDescriptor_GetCppType( + CFieldDescriptor *self, void *closure) { + Py_XINCREF(self->cpp_type); + return self->cpp_type; +} + +static PyObject* CFieldDescriptor_GetLabel( + CFieldDescriptor *self, void *closure) { + Py_XINCREF(self->label); + return self->label; +} + +static PyObject* CFieldDescriptor_GetID( + CFieldDescriptor *self, void *closure) { + Py_XINCREF(self->id); + return self->id; +} + + +static PyGetSetDef CFieldDescriptorGetters[] = { + { C("full_name"), + (getter)CFieldDescriptor_GetFullName, NULL, "Full name", NULL}, + { C("name"), + (getter)CFieldDescriptor_GetName, NULL, "last name", NULL}, + { C("cpp_type"), + (getter)CFieldDescriptor_GetCppType, NULL, "C++ Type", NULL}, + { C("label"), + (getter)CFieldDescriptor_GetLabel, NULL, "Label", NULL}, + { C("id"), + (getter)CFieldDescriptor_GetID, NULL, "ID", NULL}, + {NULL} +}; + +PyTypeObject CFieldDescriptor_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, + C("google.protobuf.internal." + "_net_proto2___python." + "CFieldDescriptor"), // tp_name + sizeof(CFieldDescriptor), // tp_basicsize + 0, // tp_itemsize + (destructor)CFieldDescriptorDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + C("A Field Descriptor"), // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + 0, // tp_methods + 0, // tp_members + CFieldDescriptorGetters, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + PyType_GenericAlloc, // tp_alloc + PyType_GenericNew, // tp_new + PyObject_Del, // tp_free +}; + +static void CFieldDescriptorDealloc(CFieldDescriptor* self) { + Py_DECREF(self->full_name); + Py_DECREF(self->name); + Py_DECREF(self->cpp_type); + Py_DECREF(self->label); + Py_DECREF(self->id); + self->ob_type->tp_free(reinterpret_cast(self)); +} + +typedef struct { + PyObject_HEAD + + const google::protobuf::DescriptorPool* pool; +} CDescriptorPool; + +static void CDescriptorPoolDealloc(CDescriptorPool* self); + +static PyObject* CDescriptorPool_NewCDescriptor( + const google::protobuf::FieldDescriptor* field_descriptor) { + CFieldDescriptor* cfield_descriptor = PyObject_New( + CFieldDescriptor, &CFieldDescriptor_Type); + if (cfield_descriptor == NULL) { + return NULL; + } + cfield_descriptor->descriptor = field_descriptor; + + cfield_descriptor->full_name = PyString_FromString( + field_descriptor->full_name().c_str()); + cfield_descriptor->name = PyString_FromString( + field_descriptor->name().c_str()); + cfield_descriptor->cpp_type = PyLong_FromLong(field_descriptor->cpp_type()); + cfield_descriptor->label = PyLong_FromLong(field_descriptor->label()); + cfield_descriptor->id = PyLong_FromVoidPtr(cfield_descriptor); + return reinterpret_cast(cfield_descriptor); +} + +static PyObject* CDescriptorPool_FindFieldByName( + CDescriptorPool* self, PyObject* arg) { + const char* full_field_name = PyString_AsString(arg); + if (full_field_name == NULL) { + return NULL; + } + + const google::protobuf::FieldDescriptor* field_descriptor = NULL; + + field_descriptor = self->pool->FindFieldByName(full_field_name); + + + if (field_descriptor == NULL) { + PyErr_Format(PyExc_TypeError, "Couldn't find field %.200s", + full_field_name); + return NULL; + } + + return CDescriptorPool_NewCDescriptor(field_descriptor); +} + +static PyObject* CDescriptorPool_FindExtensionByName( + CDescriptorPool* self, PyObject* arg) { + const char* full_field_name = PyString_AsString(arg); + if (full_field_name == NULL) { + return NULL; + } + + const google::protobuf::FieldDescriptor* field_descriptor = + self->pool->FindExtensionByName(full_field_name); + if (field_descriptor == NULL) { + PyErr_Format(PyExc_TypeError, "Couldn't find field %.200s", + full_field_name); + return NULL; + } + + return CDescriptorPool_NewCDescriptor(field_descriptor); +} + +static PyMethodDef CDescriptorPoolMethods[] = { + { C("FindFieldByName"), + (PyCFunction)CDescriptorPool_FindFieldByName, + METH_O, + C("Searches for a field descriptor by full name.") }, + { C("FindExtensionByName"), + (PyCFunction)CDescriptorPool_FindExtensionByName, + METH_O, + C("Searches for extension descriptor by full name.") }, + {NULL} +}; + +PyTypeObject CDescriptorPool_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, + C("google.protobuf.internal." + "_net_proto2___python." + "CFieldDescriptor"), // tp_name + sizeof(CDescriptorPool), // tp_basicsize + 0, // tp_itemsize + (destructor)CDescriptorPoolDealloc, // tp_dealloc + 0, // tp_print + 0, // tp_getattr + 0, // tp_setattr + 0, // tp_compare + 0, // tp_repr + 0, // tp_as_number + 0, // tp_as_sequence + 0, // tp_as_mapping + 0, // tp_hash + 0, // tp_call + 0, // tp_str + 0, // tp_getattro + 0, // tp_setattro + 0, // tp_as_buffer + Py_TPFLAGS_DEFAULT, // tp_flags + C("A Descriptor Pool"), // tp_doc + 0, // tp_traverse + 0, // tp_clear + 0, // tp_richcompare + 0, // tp_weaklistoffset + 0, // tp_iter + 0, // tp_iternext + CDescriptorPoolMethods, // tp_methods + 0, // tp_members + 0, // tp_getset + 0, // tp_base + 0, // tp_dict + 0, // tp_descr_get + 0, // tp_descr_set + 0, // tp_dictoffset + 0, // tp_init + PyType_GenericAlloc, // tp_alloc + PyType_GenericNew, // tp_new + PyObject_Del, // tp_free +}; + +static void CDescriptorPoolDealloc(CDescriptorPool* self) { + self->ob_type->tp_free(reinterpret_cast(self)); +} + +google::protobuf::DescriptorPool* GetDescriptorPool() { + if (g_descriptor_pool == NULL) { + g_descriptor_pool = new google::protobuf::DescriptorPool( + google::protobuf::DescriptorPool::generated_pool()); + } + return g_descriptor_pool; +} + +PyObject* Python_NewCDescriptorPool(PyObject* ignored, PyObject* args) { + CDescriptorPool* cdescriptor_pool = PyObject_New( + CDescriptorPool, &CDescriptorPool_Type); + if (cdescriptor_pool == NULL) { + return NULL; + } + cdescriptor_pool->pool = GetDescriptorPool(); + return reinterpret_cast(cdescriptor_pool); +} + +PyObject* Python_BuildFile(PyObject* ignored, PyObject* arg) { + char* message_type; + Py_ssize_t message_len; + + if (PyString_AsStringAndSize(arg, &message_type, &message_len) < 0) { + return NULL; + } + + google::protobuf::FileDescriptorProto file_proto; + if (!file_proto.ParseFromArray(message_type, message_len)) { + PyErr_SetString(PyExc_TypeError, "Couldn't parse file content!"); + return NULL; + } + + if (google::protobuf::DescriptorPool::generated_pool()->FindFileByName( + file_proto.name()) != NULL) { + Py_RETURN_NONE; + } + + const google::protobuf::FileDescriptor* descriptor = GetDescriptorPool()->BuildFile( + file_proto); + if (descriptor == NULL) { + PyErr_SetString(PyExc_TypeError, + "Couldn't build proto file into descriptor pool!"); + return NULL; + } + + Py_RETURN_NONE; +} + +bool InitDescriptor() { + CFieldDescriptor_Type.tp_new = PyType_GenericNew; + if (PyType_Ready(&CFieldDescriptor_Type) < 0) + return false; + + CDescriptorPool_Type.tp_new = PyType_GenericNew; + if (PyType_Ready(&CDescriptorPool_Type) < 0) + return false; + return true; +} + +} // namespace python +} // namespace protobuf +} // namespace google diff --git a/code/push/google/protobuf/pyext/python_descriptor.h b/code/push/google/protobuf/pyext/python_descriptor.h new file mode 100644 index 0000000..5232680 --- /dev/null +++ b/code/push/google/protobuf/pyext/python_descriptor.h @@ -0,0 +1,87 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: petar@google.com (Petar Petrov) + +#ifndef GOOGLE_PROTOBUF_PYTHON_DESCRIPTOR_H__ +#define GOOGLE_PROTOBUF_PYTHON_DESCRIPTOR_H__ + +#include +#include + +#include + +#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN) +typedef int Py_ssize_t; +#define PY_SSIZE_T_MAX INT_MAX +#define PY_SSIZE_T_MIN INT_MIN +#endif + +namespace google { +namespace protobuf { +namespace python { + +typedef struct { + PyObject_HEAD + + // The proto2 descriptor that this object represents. + const google::protobuf::FieldDescriptor* descriptor; + + // Full name of the field (PyString). + PyObject* full_name; + + // Name of the field (PyString). + PyObject* name; + + // C++ type of the field (PyLong). + PyObject* cpp_type; + + // Name of the field (PyLong). + PyObject* label; + + // Identity of the descriptor (PyLong used as a poiner). + PyObject* id; +} CFieldDescriptor; + +extern PyTypeObject CFieldDescriptor_Type; + +extern PyTypeObject CDescriptorPool_Type; + + +PyObject* Python_NewCDescriptorPool(PyObject* ignored, PyObject* args); +PyObject* Python_BuildFile(PyObject* ignored, PyObject* args); +bool InitDescriptor(); +google::protobuf::DescriptorPool* GetDescriptorPool(); + +} // namespace python +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_PYTHON_DESCRIPTOR_H__ diff --git a/code/push/google/protobuf/pyext/python_protobuf.cc b/code/push/google/protobuf/pyext/python_protobuf.cc new file mode 100644 index 0000000..1b1ab5d --- /dev/null +++ b/code/push/google/protobuf/pyext/python_protobuf.cc @@ -0,0 +1,63 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: qrczak@google.com (Marcin Kowalczyk) + +#include + +namespace google { +namespace protobuf { +namespace python { + +static const Message* GetCProtoInsidePyProtoStub(PyObject* msg) { + return NULL; +} +static Message* MutableCProtoInsidePyProtoStub(PyObject* msg) { + return NULL; +} + +// This is initialized with a default, stub implementation. +// If python-google.protobuf.cc is loaded, the function pointer is overridden +// with a full implementation. +const Message* (*GetCProtoInsidePyProtoPtr)(PyObject* msg) = + GetCProtoInsidePyProtoStub; +Message* (*MutableCProtoInsidePyProtoPtr)(PyObject* msg) = + MutableCProtoInsidePyProtoStub; + +const Message* GetCProtoInsidePyProto(PyObject* msg) { + return GetCProtoInsidePyProtoPtr(msg); +} +Message* MutableCProtoInsidePyProto(PyObject* msg) { + return MutableCProtoInsidePyProtoPtr(msg); +} + +} // namespace python +} // namespace protobuf +} // namespace google diff --git a/code/push/google/protobuf/pyext/python_protobuf.h b/code/push/google/protobuf/pyext/python_protobuf.h new file mode 100644 index 0000000..c5b0b1c --- /dev/null +++ b/code/push/google/protobuf/pyext/python_protobuf.h @@ -0,0 +1,57 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: qrczak@google.com (Marcin Kowalczyk) +// +// This module exposes the C proto inside the given Python proto, in +// case the Python proto is implemented with a C proto. + +#ifndef GOOGLE_PROTOBUF_PYTHON_PYTHON_PROTOBUF_H__ +#define GOOGLE_PROTOBUF_PYTHON_PYTHON_PROTOBUF_H__ + +#include + +namespace google { +namespace protobuf { + +class Message; + +namespace python { + +// Return the pointer to the C proto inside the given Python proto, +// or NULL when this is not a Python proto implemented with a C proto. +const Message* GetCProtoInsidePyProto(PyObject* msg); +Message* MutableCProtoInsidePyProto(PyObject* msg); + +} // namespace python +} // namespace protobuf + +} // namespace google +#endif // GOOGLE_PROTOBUF_PYTHON_PYTHON_PROTOBUF_H__ diff --git a/code/push/google/protobuf/reflection.py b/code/push/google/protobuf/reflection.py new file mode 100644 index 0000000..c696725 --- /dev/null +++ b/code/push/google/protobuf/reflection.py @@ -0,0 +1,169 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# This code is meant to work on Python 2.4 and above only. + +"""Contains a metaclass and helper functions used to create +protocol message classes from Descriptor objects at runtime. + +Recall that a metaclass is the "type" of a class. +(A class is to a metaclass what an instance is to a class.) + +In this case, we use the GeneratedProtocolMessageType metaclass +to inject all the useful functionality into the classes +output by the protocol compiler at compile-time. + +The upshot of all this is that the real implementation +details for ALL pure-Python protocol buffers are *here in +this file*. +""" + +__author__ = 'robinson@google.com (Will Robinson)' + + +from push.google.protobuf.internal import api_implementation +from push.google.protobuf import descriptor as descriptor_mod +from push.google.protobuf import message + +_FieldDescriptor = descriptor_mod.FieldDescriptor + + +if api_implementation.Type() == 'cpp': + if api_implementation.Version() == 2: + from google.protobuf.internal.cpp import cpp_message + _NewMessage = cpp_message.NewMessage + _InitMessage = cpp_message.InitMessage + else: + from google.protobuf.internal import cpp_message + _NewMessage = cpp_message.NewMessage + _InitMessage = cpp_message.InitMessage +else: + from push.google.protobuf.internal import python_message + _NewMessage = python_message.NewMessage + _InitMessage = python_message.InitMessage + + +class GeneratedProtocolMessageType(type): + + """Metaclass for protocol message classes created at runtime from Descriptors. + + We add implementations for all methods described in the Message class. We + also create properties to allow getting/setting all fields in the protocol + message. Finally, we create slots to prevent users from accidentally + "setting" nonexistent fields in the protocol message, which then wouldn't get + serialized / deserialized properly. + + The protocol compiler currently uses this metaclass to create protocol + message classes at runtime. Clients can also manually create their own + classes at runtime, as in this example: + + mydescriptor = Descriptor(.....) + class MyProtoClass(Message): + __metaclass__ = GeneratedProtocolMessageType + DESCRIPTOR = mydescriptor + myproto_instance = MyProtoClass() + myproto.foo_field = 23 + ... + """ + + # Must be consistent with the protocol-compiler code in + # proto2/compiler/internal/generator.*. + _DESCRIPTOR_KEY = 'DESCRIPTOR' + + def __new__(cls, name, bases, dictionary): + """Custom allocation for runtime-generated class types. + + We override __new__ because this is apparently the only place + where we can meaningfully set __slots__ on the class we're creating(?). + (The interplay between metaclasses and slots is not very well-documented). + + Args: + name: Name of the class (ignored, but required by the + metaclass protocol). + bases: Base classes of the class we're constructing. + (Should be message.Message). We ignore this field, but + it's required by the metaclass protocol + dictionary: The class dictionary of the class we're + constructing. dictionary[_DESCRIPTOR_KEY] must contain + a Descriptor object describing this protocol message + type. + + Returns: + Newly-allocated class. + """ + descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] + bases = _NewMessage(bases, descriptor, dictionary) + superclass = super(GeneratedProtocolMessageType, cls) + + new_class = superclass.__new__(cls, name, bases, dictionary) + setattr(descriptor, '_concrete_class', new_class) + return new_class + + def __init__(cls, name, bases, dictionary): + """Here we perform the majority of our work on the class. + We add enum getters, an __init__ method, implementations + of all Message methods, and properties for all fields + in the protocol type. + + Args: + name: Name of the class (ignored, but required by the + metaclass protocol). + bases: Base classes of the class we're constructing. + (Should be message.Message). We ignore this field, but + it's required by the metaclass protocol + dictionary: The class dictionary of the class we're + constructing. dictionary[_DESCRIPTOR_KEY] must contain + a Descriptor object describing this protocol message + type. + """ + descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] + _InitMessage(descriptor, cls) + superclass = super(GeneratedProtocolMessageType, cls) + superclass.__init__(name, bases, dictionary) + + +def ParseMessage(descriptor, byte_str): + """Generate a new Message instance from this Descriptor and a byte string. + + Args: + descriptor: Protobuf Descriptor object + byte_str: Serialized protocol buffer byte string + + Returns: + Newly created protobuf Message object. + """ + + class _ResultClass(message.Message): + __metaclass__ = GeneratedProtocolMessageType + DESCRIPTOR = descriptor + + new_msg = _ResultClass() + new_msg.ParseFromString(byte_str) + return new_msg diff --git a/code/push/google/protobuf/service.py b/code/push/google/protobuf/service.py new file mode 100644 index 0000000..180b70e --- /dev/null +++ b/code/push/google/protobuf/service.py @@ -0,0 +1,226 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""DEPRECATED: Declares the RPC service interfaces. + +This module declares the abstract interfaces underlying proto2 RPC +services. These are intended to be independent of any particular RPC +implementation, so that proto2 services can be used on top of a variety +of implementations. Starting with version 2.3.0, RPC implementations should +not try to build on these, but should instead provide code generator plugins +which generate code specific to the particular RPC implementation. This way +the generated code can be more appropriate for the implementation in use +and can avoid unnecessary layers of indirection. +""" + +__author__ = 'petar@google.com (Petar Petrov)' + + +class RpcException(Exception): + """Exception raised on failed blocking RPC method call.""" + pass + + +class Service(object): + + """Abstract base interface for protocol-buffer-based RPC services. + + Services themselves are abstract classes (implemented either by servers or as + stubs), but they subclass this base interface. The methods of this + interface can be used to call the methods of the service without knowing + its exact type at compile time (analogous to the Message interface). + """ + + def GetDescriptor(): + """Retrieves this service's descriptor.""" + raise NotImplementedError + + def CallMethod(self, method_descriptor, rpc_controller, + request, done): + """Calls a method of the service specified by method_descriptor. + + If "done" is None then the call is blocking and the response + message will be returned directly. Otherwise the call is asynchronous + and "done" will later be called with the response value. + + In the blocking case, RpcException will be raised on error. + + Preconditions: + * method_descriptor.service == GetDescriptor + * request is of the exact same classes as returned by + GetRequestClass(method). + * After the call has started, the request must not be modified. + * "rpc_controller" is of the correct type for the RPC implementation being + used by this Service. For stubs, the "correct type" depends on the + RpcChannel which the stub is using. + + Postconditions: + * "done" will be called when the method is complete. This may be + before CallMethod() returns or it may be at some point in the future. + * If the RPC failed, the response value passed to "done" will be None. + Further details about the failure can be found by querying the + RpcController. + """ + raise NotImplementedError + + def GetRequestClass(self, method_descriptor): + """Returns the class of the request message for the specified method. + + CallMethod() requires that the request is of a particular subclass of + Message. GetRequestClass() gets the default instance of this required + type. + + Example: + method = service.GetDescriptor().FindMethodByName("Foo") + request = stub.GetRequestClass(method)() + request.ParseFromString(input) + service.CallMethod(method, request, callback) + """ + raise NotImplementedError + + def GetResponseClass(self, method_descriptor): + """Returns the class of the response message for the specified method. + + This method isn't really needed, as the RpcChannel's CallMethod constructs + the response protocol message. It's provided anyway in case it is useful + for the caller to know the response type in advance. + """ + raise NotImplementedError + + +class RpcController(object): + + """An RpcController mediates a single method call. + + The primary purpose of the controller is to provide a way to manipulate + settings specific to the RPC implementation and to find out about RPC-level + errors. The methods provided by the RpcController interface are intended + to be a "least common denominator" set of features which we expect all + implementations to support. Specific implementations may provide more + advanced features (e.g. deadline propagation). + """ + + # Client-side methods below + + def Reset(self): + """Resets the RpcController to its initial state. + + After the RpcController has been reset, it may be reused in + a new call. Must not be called while an RPC is in progress. + """ + raise NotImplementedError + + def Failed(self): + """Returns true if the call failed. + + After a call has finished, returns true if the call failed. The possible + reasons for failure depend on the RPC implementation. Failed() must not + be called before a call has finished. If Failed() returns true, the + contents of the response message are undefined. + """ + raise NotImplementedError + + def ErrorText(self): + """If Failed is true, returns a human-readable description of the error.""" + raise NotImplementedError + + def StartCancel(self): + """Initiate cancellation. + + Advises the RPC system that the caller desires that the RPC call be + canceled. The RPC system may cancel it immediately, may wait awhile and + then cancel it, or may not even cancel the call at all. If the call is + canceled, the "done" callback will still be called and the RpcController + will indicate that the call failed at that time. + """ + raise NotImplementedError + + # Server-side methods below + + def SetFailed(self, reason): + """Sets a failure reason. + + Causes Failed() to return true on the client side. "reason" will be + incorporated into the message returned by ErrorText(). If you find + you need to return machine-readable information about failures, you + should incorporate it into your response protocol buffer and should + NOT call SetFailed(). + """ + raise NotImplementedError + + def IsCanceled(self): + """Checks if the client cancelled the RPC. + + If true, indicates that the client canceled the RPC, so the server may + as well give up on replying to it. The server should still call the + final "done" callback. + """ + raise NotImplementedError + + def NotifyOnCancel(self, callback): + """Sets a callback to invoke on cancel. + + Asks that the given callback be called when the RPC is canceled. The + callback will always be called exactly once. If the RPC completes without + being canceled, the callback will be called after completion. If the RPC + has already been canceled when NotifyOnCancel() is called, the callback + will be called immediately. + + NotifyOnCancel() must be called no more than once per request. + """ + raise NotImplementedError + + +class RpcChannel(object): + + """Abstract interface for an RPC channel. + + An RpcChannel represents a communication line to a service which can be used + to call that service's methods. The service may be running on another + machine. Normally, you should not use an RpcChannel directly, but instead + construct a stub {@link Service} wrapping it. Example: + + Example: + RpcChannel channel = rpcImpl.Channel("remotehost.example.com:1234") + RpcController controller = rpcImpl.Controller() + MyService service = MyService_Stub(channel) + service.MyMethod(controller, request, callback) + """ + + def CallMethod(self, method_descriptor, rpc_controller, + request, response_class, done): + """Calls the method identified by the descriptor. + + Call the given method of the remote service. The signature of this + procedure looks the same as Service.CallMethod(), but the requirements + are less strict in one important way: the request object doesn't have to + be of any specific class as long as its descriptor is method.input_type. + """ + raise NotImplementedError diff --git a/code/push/google/protobuf/service_reflection.py b/code/push/google/protobuf/service_reflection.py new file mode 100644 index 0000000..851e83e --- /dev/null +++ b/code/push/google/protobuf/service_reflection.py @@ -0,0 +1,284 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Contains metaclasses used to create protocol service and service stub +classes from ServiceDescriptor objects at runtime. + +The GeneratedServiceType and GeneratedServiceStubType metaclasses are used to +inject all useful functionality into the classes output by the protocol +compiler at compile-time. +""" + +__author__ = 'petar@google.com (Petar Petrov)' + + +class GeneratedServiceType(type): + + """Metaclass for service classes created at runtime from ServiceDescriptors. + + Implementations for all methods described in the Service class are added here + by this class. We also create properties to allow getting/setting all fields + in the protocol message. + + The protocol compiler currently uses this metaclass to create protocol service + classes at runtime. Clients can also manually create their own classes at + runtime, as in this example: + + mydescriptor = ServiceDescriptor(.....) + class MyProtoService(service.Service): + __metaclass__ = GeneratedServiceType + DESCRIPTOR = mydescriptor + myservice_instance = MyProtoService() + ... + """ + + _DESCRIPTOR_KEY = 'DESCRIPTOR' + + def __init__(cls, name, bases, dictionary): + """Creates a message service class. + + Args: + name: Name of the class (ignored, but required by the metaclass + protocol). + bases: Base classes of the class being constructed. + dictionary: The class dictionary of the class being constructed. + dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object + describing this protocol service type. + """ + # Don't do anything if this class doesn't have a descriptor. This happens + # when a service class is subclassed. + if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary: + return + descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY] + service_builder = _ServiceBuilder(descriptor) + service_builder.BuildService(cls) + + +class GeneratedServiceStubType(GeneratedServiceType): + + """Metaclass for service stubs created at runtime from ServiceDescriptors. + + This class has similar responsibilities as GeneratedServiceType, except that + it creates the service stub classes. + """ + + _DESCRIPTOR_KEY = 'DESCRIPTOR' + + def __init__(cls, name, bases, dictionary): + """Creates a message service stub class. + + Args: + name: Name of the class (ignored, here). + bases: Base classes of the class being constructed. + dictionary: The class dictionary of the class being constructed. + dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object + describing this protocol service type. + """ + super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary) + # Don't do anything if this class doesn't have a descriptor. This happens + # when a service stub is subclassed. + if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary: + return + descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY] + service_stub_builder = _ServiceStubBuilder(descriptor) + service_stub_builder.BuildServiceStub(cls) + + +class _ServiceBuilder(object): + + """This class constructs a protocol service class using a service descriptor. + + Given a service descriptor, this class constructs a class that represents + the specified service descriptor. One service builder instance constructs + exactly one service class. That means all instances of that class share the + same builder. + """ + + def __init__(self, service_descriptor): + """Initializes an instance of the service class builder. + + Args: + service_descriptor: ServiceDescriptor to use when constructing the + service class. + """ + self.descriptor = service_descriptor + + def BuildService(self, cls): + """Constructs the service class. + + Args: + cls: The class that will be constructed. + """ + + # CallMethod needs to operate with an instance of the Service class. This + # internal wrapper function exists only to be able to pass the service + # instance to the method that does the real CallMethod work. + def _WrapCallMethod(srvc, method_descriptor, + rpc_controller, request, callback): + return self._CallMethod(srvc, method_descriptor, + rpc_controller, request, callback) + self.cls = cls + cls.CallMethod = _WrapCallMethod + cls.GetDescriptor = staticmethod(lambda: self.descriptor) + cls.GetDescriptor.__doc__ = "Returns the service descriptor." + cls.GetRequestClass = self._GetRequestClass + cls.GetResponseClass = self._GetResponseClass + for method in self.descriptor.methods: + setattr(cls, method.name, self._GenerateNonImplementedMethod(method)) + + def _CallMethod(self, srvc, method_descriptor, + rpc_controller, request, callback): + """Calls the method described by a given method descriptor. + + Args: + srvc: Instance of the service for which this method is called. + method_descriptor: Descriptor that represent the method to call. + rpc_controller: RPC controller to use for this method's execution. + request: Request protocol message. + callback: A callback to invoke after the method has completed. + """ + if method_descriptor.containing_service != self.descriptor: + raise RuntimeError( + 'CallMethod() given method descriptor for wrong service type.') + method = getattr(srvc, method_descriptor.name) + return method(rpc_controller, request, callback) + + def _GetRequestClass(self, method_descriptor): + """Returns the class of the request protocol message. + + Args: + method_descriptor: Descriptor of the method for which to return the + request protocol message class. + + Returns: + A class that represents the input protocol message of the specified + method. + """ + if method_descriptor.containing_service != self.descriptor: + raise RuntimeError( + 'GetRequestClass() given method descriptor for wrong service type.') + return method_descriptor.input_type._concrete_class + + def _GetResponseClass(self, method_descriptor): + """Returns the class of the response protocol message. + + Args: + method_descriptor: Descriptor of the method for which to return the + response protocol message class. + + Returns: + A class that represents the output protocol message of the specified + method. + """ + if method_descriptor.containing_service != self.descriptor: + raise RuntimeError( + 'GetResponseClass() given method descriptor for wrong service type.') + return method_descriptor.output_type._concrete_class + + def _GenerateNonImplementedMethod(self, method): + """Generates and returns a method that can be set for a service methods. + + Args: + method: Descriptor of the service method for which a method is to be + generated. + + Returns: + A method that can be added to the service class. + """ + return lambda inst, rpc_controller, request, callback: ( + self._NonImplementedMethod(method.name, rpc_controller, callback)) + + def _NonImplementedMethod(self, method_name, rpc_controller, callback): + """The body of all methods in the generated service class. + + Args: + method_name: Name of the method being executed. + rpc_controller: RPC controller used to execute this method. + callback: A callback which will be invoked when the method finishes. + """ + rpc_controller.SetFailed('Method %s not implemented.' % method_name) + callback(None) + + +class _ServiceStubBuilder(object): + + """Constructs a protocol service stub class using a service descriptor. + + Given a service descriptor, this class constructs a suitable stub class. + A stub is just a type-safe wrapper around an RpcChannel which emulates a + local implementation of the service. + + One service stub builder instance constructs exactly one class. It means all + instances of that class share the same service stub builder. + """ + + def __init__(self, service_descriptor): + """Initializes an instance of the service stub class builder. + + Args: + service_descriptor: ServiceDescriptor to use when constructing the + stub class. + """ + self.descriptor = service_descriptor + + def BuildServiceStub(self, cls): + """Constructs the stub class. + + Args: + cls: The class that will be constructed. + """ + + def _ServiceStubInit(stub, rpc_channel): + stub.rpc_channel = rpc_channel + self.cls = cls + cls.__init__ = _ServiceStubInit + for method in self.descriptor.methods: + setattr(cls, method.name, self._GenerateStubMethod(method)) + + def _GenerateStubMethod(self, method): + return (lambda inst, rpc_controller, request, callback=None: + self._StubMethod(inst, method, rpc_controller, request, callback)) + + def _StubMethod(self, stub, method_descriptor, + rpc_controller, request, callback): + """The body of all service methods in the generated stub class. + + Args: + stub: Stub instance. + method_descriptor: Descriptor of the invoked method. + rpc_controller: Rpc controller to execute the method. + request: Request protocol message. + callback: A callback to execute when the method finishes. + Returns: + Response message (in case of blocking call). + """ + return stub.rpc_channel.CallMethod( + method_descriptor, rpc_controller, request, + method_descriptor.output_type._concrete_class, callback) diff --git a/code/push/google/protobuf/text_format.py b/code/push/google/protobuf/text_format.py new file mode 100644 index 0000000..3260d09 --- /dev/null +++ b/code/push/google/protobuf/text_format.py @@ -0,0 +1,739 @@ +# Protocol Buffers - Google's data interchange format +# Copyright 2008 Google Inc. All rights reserved. +# http://code.google.com/p/protobuf/ +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of Google Inc. nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +"""Contains routines for printing protocol messages in text format.""" + +__author__ = 'kenton@google.com (Kenton Varda)' + +import cStringIO +import re + +from collections import deque +from push.google.protobuf.internal import type_checkers +from push.google.protobuf import descriptor + +__all__ = [ 'MessageToString', 'PrintMessage', 'PrintField', + 'PrintFieldValue', 'Merge' ] + + +_INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(), + type_checkers.Int32ValueChecker(), + type_checkers.Uint64ValueChecker(), + type_checkers.Int64ValueChecker()) +_FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?', re.IGNORECASE) +_FLOAT_NAN = re.compile('nanf?', re.IGNORECASE) + + +class ParseError(Exception): + """Thrown in case of ASCII parsing error.""" + + +def MessageToString(message, as_utf8=False, as_one_line=False): + out = cStringIO.StringIO() + PrintMessage(message, out, as_utf8=as_utf8, as_one_line=as_one_line) + result = out.getvalue() + out.close() + if as_one_line: + return result.rstrip() + return result + + +def PrintMessage(message, out, indent=0, as_utf8=False, as_one_line=False): + for field, value in message.ListFields(): + if field.label == descriptor.FieldDescriptor.LABEL_REPEATED: + for element in value: + PrintField(field, element, out, indent, as_utf8, as_one_line) + else: + PrintField(field, value, out, indent, as_utf8, as_one_line) + + +def PrintField(field, value, out, indent=0, as_utf8=False, as_one_line=False): + """Print a single field name/value pair. For repeated fields, the value + should be a single element.""" + + out.write(' ' * indent); + if field.is_extension: + out.write('[') + if (field.containing_type.GetOptions().message_set_wire_format and + field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and + field.message_type == field.extension_scope and + field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL): + out.write(field.message_type.full_name) + else: + out.write(field.full_name) + out.write(']') + elif field.type == descriptor.FieldDescriptor.TYPE_GROUP: + # For groups, use the capitalized name. + out.write(field.message_type.name) + else: + out.write(field.name) + + if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + # The colon is optional in this case, but our cross-language golden files + # don't include it. + out.write(': ') + + PrintFieldValue(field, value, out, indent, as_utf8, as_one_line) + if as_one_line: + out.write(' ') + else: + out.write('\n') + + +def PrintFieldValue(field, value, out, indent=0, + as_utf8=False, as_one_line=False): + """Print a single field value (not including name). For repeated fields, + the value should be a single element.""" + + if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + if as_one_line: + out.write(' { ') + PrintMessage(value, out, indent, as_utf8, as_one_line) + out.write('}') + else: + out.write(' {\n') + PrintMessage(value, out, indent + 2, as_utf8, as_one_line) + out.write(' ' * indent + '}') + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: + enum_value = field.enum_type.values_by_number.get(value, None) + if enum_value is not None: + out.write(enum_value.name) + else: + out.write(str(value)) + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING: + out.write('\"') + if type(value) is unicode: + out.write(_CEscape(value.encode('utf-8'), as_utf8)) + else: + out.write(_CEscape(value, as_utf8)) + out.write('\"') + elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: + if value: + out.write("true") + else: + out.write("false") + else: + out.write(str(value)) + + +def Merge(text, message): + """Merges an ASCII representation of a protocol message into a message. + + Args: + text: Message ASCII representation. + message: A protocol buffer message to merge into. + + Raises: + ParseError: On ASCII parsing problems. + """ + tokenizer = _Tokenizer(text) + while not tokenizer.AtEnd(): + _MergeField(tokenizer, message) + + +def _MergeField(tokenizer, message): + """Merges a single protocol message field into a message. + + Args: + tokenizer: A tokenizer to parse the field name and values. + message: A protocol message to record the data. + + Raises: + ParseError: In case of ASCII parsing problems. + """ + message_descriptor = message.DESCRIPTOR + if tokenizer.TryConsume('['): + name = [tokenizer.ConsumeIdentifier()] + while tokenizer.TryConsume('.'): + name.append(tokenizer.ConsumeIdentifier()) + name = '.'.join(name) + + if not message_descriptor.is_extendable: + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" does not have extensions.' % + message_descriptor.full_name) + field = message.Extensions._FindExtensionByName(name) + if not field: + raise tokenizer.ParseErrorPreviousToken( + 'Extension "%s" not registered.' % name) + elif message_descriptor != field.containing_type: + raise tokenizer.ParseErrorPreviousToken( + 'Extension "%s" does not extend message type "%s".' % ( + name, message_descriptor.full_name)) + tokenizer.Consume(']') + else: + name = tokenizer.ConsumeIdentifier() + field = message_descriptor.fields_by_name.get(name, None) + + # Group names are expected to be capitalized as they appear in the + # .proto file, which actually matches their type names, not their field + # names. + if not field: + field = message_descriptor.fields_by_name.get(name.lower(), None) + if field and field.type != descriptor.FieldDescriptor.TYPE_GROUP: + field = None + + if (field and field.type == descriptor.FieldDescriptor.TYPE_GROUP and + field.message_type.name != name): + field = None + + if not field: + raise tokenizer.ParseErrorPreviousToken( + 'Message type "%s" has no field named "%s".' % ( + message_descriptor.full_name, name)) + + if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: + tokenizer.TryConsume(':') + + if tokenizer.TryConsume('<'): + end_token = '>' + else: + tokenizer.Consume('{') + end_token = '}' + + if field.label == descriptor.FieldDescriptor.LABEL_REPEATED: + if field.is_extension: + sub_message = message.Extensions[field].add() + else: + sub_message = getattr(message, field.name).add() + else: + if field.is_extension: + sub_message = message.Extensions[field] + else: + sub_message = getattr(message, field.name) + sub_message.SetInParent() + + while not tokenizer.TryConsume(end_token): + if tokenizer.AtEnd(): + raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token)) + _MergeField(tokenizer, sub_message) + else: + _MergeScalarField(tokenizer, message, field) + + +def _MergeScalarField(tokenizer, message, field): + """Merges a single protocol message scalar field into a message. + + Args: + tokenizer: A tokenizer to parse the field value. + message: A protocol message to record the data. + field: The descriptor of the field to be merged. + + Raises: + ParseError: In case of ASCII parsing problems. + RuntimeError: On runtime errors. + """ + tokenizer.Consume(':') + value = None + + if field.type in (descriptor.FieldDescriptor.TYPE_INT32, + descriptor.FieldDescriptor.TYPE_SINT32, + descriptor.FieldDescriptor.TYPE_SFIXED32): + value = tokenizer.ConsumeInt32() + elif field.type in (descriptor.FieldDescriptor.TYPE_INT64, + descriptor.FieldDescriptor.TYPE_SINT64, + descriptor.FieldDescriptor.TYPE_SFIXED64): + value = tokenizer.ConsumeInt64() + elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32, + descriptor.FieldDescriptor.TYPE_FIXED32): + value = tokenizer.ConsumeUint32() + elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64, + descriptor.FieldDescriptor.TYPE_FIXED64): + value = tokenizer.ConsumeUint64() + elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT, + descriptor.FieldDescriptor.TYPE_DOUBLE): + value = tokenizer.ConsumeFloat() + elif field.type == descriptor.FieldDescriptor.TYPE_BOOL: + value = tokenizer.ConsumeBool() + elif field.type == descriptor.FieldDescriptor.TYPE_STRING: + value = tokenizer.ConsumeString() + elif field.type == descriptor.FieldDescriptor.TYPE_BYTES: + value = tokenizer.ConsumeByteString() + elif field.type == descriptor.FieldDescriptor.TYPE_ENUM: + value = tokenizer.ConsumeEnum(field) + else: + raise RuntimeError('Unknown field type %d' % field.type) + + if field.label == descriptor.FieldDescriptor.LABEL_REPEATED: + if field.is_extension: + message.Extensions[field].append(value) + else: + getattr(message, field.name).append(value) + else: + if field.is_extension: + message.Extensions[field] = value + else: + setattr(message, field.name, value) + + +class _Tokenizer(object): + """Protocol buffer ASCII representation tokenizer. + + This class handles the lower level string parsing by splitting it into + meaningful tokens. + + It was directly ported from the Java protocol buffer API. + """ + + _WHITESPACE = re.compile('(\\s|(#.*$))+', re.MULTILINE) + _TOKEN = re.compile( + '[a-zA-Z_][0-9a-zA-Z_+-]*|' # an identifier + '[0-9+-][0-9a-zA-Z_.+-]*|' # a number + '\"([^\"\n\\\\]|\\\\.)*(\"|\\\\?$)|' # a double-quoted string + '\'([^\'\n\\\\]|\\\\.)*(\'|\\\\?$)') # a single-quoted string + _IDENTIFIER = re.compile('\w+') + + def __init__(self, text_message): + self._text_message = text_message + + self._position = 0 + self._line = -1 + self._column = 0 + self._token_start = None + self.token = '' + self._lines = deque(text_message.split('\n')) + self._current_line = '' + self._previous_line = 0 + self._previous_column = 0 + self._SkipWhitespace() + self.NextToken() + + def AtEnd(self): + """Checks the end of the text was reached. + + Returns: + True iff the end was reached. + """ + return self.token == '' + + def _PopLine(self): + while len(self._current_line) <= self._column: + if not self._lines: + self._current_line = '' + return + self._line += 1 + self._column = 0 + self._current_line = self._lines.popleft() + + def _SkipWhitespace(self): + while True: + self._PopLine() + match = self._WHITESPACE.match(self._current_line, self._column) + if not match: + break + length = len(match.group(0)) + self._column += length + + def TryConsume(self, token): + """Tries to consume a given piece of text. + + Args: + token: Text to consume. + + Returns: + True iff the text was consumed. + """ + if self.token == token: + self.NextToken() + return True + return False + + def Consume(self, token): + """Consumes a piece of text. + + Args: + token: Text to consume. + + Raises: + ParseError: If the text couldn't be consumed. + """ + if not self.TryConsume(token): + raise self._ParseError('Expected "%s".' % token) + + def ConsumeIdentifier(self): + """Consumes protocol message field identifier. + + Returns: + Identifier string. + + Raises: + ParseError: If an identifier couldn't be consumed. + """ + result = self.token + if not self._IDENTIFIER.match(result): + raise self._ParseError('Expected identifier.') + self.NextToken() + return result + + def ConsumeInt32(self): + """Consumes a signed 32bit integer number. + + Returns: + The integer parsed. + + Raises: + ParseError: If a signed 32bit integer couldn't be consumed. + """ + try: + result = ParseInteger(self.token, is_signed=True, is_long=False) + except ValueError, e: + raise self._ParseError(str(e)) + self.NextToken() + return result + + def ConsumeUint32(self): + """Consumes an unsigned 32bit integer number. + + Returns: + The integer parsed. + + Raises: + ParseError: If an unsigned 32bit integer couldn't be consumed. + """ + try: + result = ParseInteger(self.token, is_signed=False, is_long=False) + except ValueError, e: + raise self._ParseError(str(e)) + self.NextToken() + return result + + def ConsumeInt64(self): + """Consumes a signed 64bit integer number. + + Returns: + The integer parsed. + + Raises: + ParseError: If a signed 64bit integer couldn't be consumed. + """ + try: + result = ParseInteger(self.token, is_signed=True, is_long=True) + except ValueError, e: + raise self._ParseError(str(e)) + self.NextToken() + return result + + def ConsumeUint64(self): + """Consumes an unsigned 64bit integer number. + + Returns: + The integer parsed. + + Raises: + ParseError: If an unsigned 64bit integer couldn't be consumed. + """ + try: + result = ParseInteger(self.token, is_signed=False, is_long=True) + except ValueError, e: + raise self._ParseError(str(e)) + self.NextToken() + return result + + def ConsumeFloat(self): + """Consumes an floating point number. + + Returns: + The number parsed. + + Raises: + ParseError: If a floating point number couldn't be consumed. + """ + try: + result = ParseFloat(self.token) + except ValueError, e: + raise self._ParseError(str(e)) + self.NextToken() + return result + + def ConsumeBool(self): + """Consumes a boolean value. + + Returns: + The bool parsed. + + Raises: + ParseError: If a boolean value couldn't be consumed. + """ + try: + result = ParseBool(self.token) + except ValueError, e: + raise self._ParseError(str(e)) + self.NextToken() + return result + + def ConsumeString(self): + """Consumes a string value. + + Returns: + The string parsed. + + Raises: + ParseError: If a string value couldn't be consumed. + """ + bytes = self.ConsumeByteString() + try: + return unicode(bytes, 'utf-8') + except UnicodeDecodeError, e: + raise self._StringParseError(e) + + def ConsumeByteString(self): + """Consumes a byte array value. + + Returns: + The array parsed (as a string). + + Raises: + ParseError: If a byte array value couldn't be consumed. + """ + list = [self._ConsumeSingleByteString()] + while len(self.token) > 0 and self.token[0] in ('\'', '"'): + list.append(self._ConsumeSingleByteString()) + return "".join(list) + + def _ConsumeSingleByteString(self): + """Consume one token of a string literal. + + String literals (whether bytes or text) can come in multiple adjacent + tokens which are automatically concatenated, like in C or Python. This + method only consumes one token. + """ + text = self.token + if len(text) < 1 or text[0] not in ('\'', '"'): + raise self._ParseError('Expected string.') + + if len(text) < 2 or text[-1] != text[0]: + raise self._ParseError('String missing ending quote.') + + try: + result = _CUnescape(text[1:-1]) + except ValueError, e: + raise self._ParseError(str(e)) + self.NextToken() + return result + + def ConsumeEnum(self, field): + try: + result = ParseEnum(field, self.token) + except ValueError, e: + raise self._ParseError(str(e)) + self.NextToken() + return result + + def ParseErrorPreviousToken(self, message): + """Creates and *returns* a ParseError for the previously read token. + + Args: + message: A message to set for the exception. + + Returns: + A ParseError instance. + """ + return ParseError('%d:%d : %s' % ( + self._previous_line + 1, self._previous_column + 1, message)) + + def _ParseError(self, message): + """Creates and *returns* a ParseError for the current token.""" + return ParseError('%d:%d : %s' % ( + self._line + 1, self._column + 1, message)) + + def _StringParseError(self, e): + return self._ParseError('Couldn\'t parse string: ' + str(e)) + + def NextToken(self): + """Reads the next meaningful token.""" + self._previous_line = self._line + self._previous_column = self._column + + self._column += len(self.token) + self._SkipWhitespace() + + if not self._lines and len(self._current_line) <= self._column: + self.token = '' + return + + match = self._TOKEN.match(self._current_line, self._column) + if match: + token = match.group(0) + self.token = token + else: + self.token = self._current_line[self._column] + + +# text.encode('string_escape') does not seem to satisfy our needs as it +# encodes unprintable characters using two-digit hex escapes whereas our +# C++ unescaping function allows hex escapes to be any length. So, +# "\0011".encode('string_escape') ends up being "\\x011", which will be +# decoded in C++ as a single-character string with char code 0x11. +def _CEscape(text, as_utf8): + def escape(c): + o = ord(c) + if o == 10: return r"\n" # optional escape + if o == 13: return r"\r" # optional escape + if o == 9: return r"\t" # optional escape + if o == 39: return r"\'" # optional escape + + if o == 34: return r'\"' # necessary escape + if o == 92: return r"\\" # necessary escape + + # necessary escapes + if not as_utf8 and (o >= 127 or o < 32): return "\\%03o" % o + return c + return "".join([escape(c) for c in text]) + + +_CUNESCAPE_HEX = re.compile(r'(\\+)x([0-9a-fA-F])(?![0-9a-fA-F])') + + +def _CUnescape(text): + def ReplaceHex(m): + # Only replace the match if the number of leading back slashes is odd. i.e. + # the slash itself is not escaped. + if len(m.group(1)) & 1: + return m.group(1) + 'x0' + m.group(2) + return m.group(0) + + # This is required because the 'string_escape' encoding doesn't + # allow single-digit hex escapes (like '\xf'). + result = _CUNESCAPE_HEX.sub(ReplaceHex, text) + return result.decode('string_escape') + + +def ParseInteger(text, is_signed=False, is_long=False): + """Parses an integer. + + Args: + text: The text to parse. + is_signed: True if a signed integer must be parsed. + is_long: True if a long integer must be parsed. + + Returns: + The integer value. + + Raises: + ValueError: Thrown Iff the text is not a valid integer. + """ + # Do the actual parsing. Exception handling is propagated to caller. + try: + result = int(text, 0) + except ValueError: + raise ValueError('Couldn\'t parse integer: %s' % text) + + # Check if the integer is sane. Exceptions handled by callers. + checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)] + checker.CheckValue(result) + return result + + +def ParseFloat(text): + """Parse a floating point number. + + Args: + text: Text to parse. + + Returns: + The number parsed. + + Raises: + ValueError: If a floating point number couldn't be parsed. + """ + try: + # Assume Python compatible syntax. + return float(text) + except ValueError: + # Check alternative spellings. + if _FLOAT_INFINITY.match(text): + if text[0] == '-': + return float('-inf') + else: + return float('inf') + elif _FLOAT_NAN.match(text): + return float('nan') + else: + # assume '1.0f' format + try: + return float(text.rstrip('f')) + except ValueError: + raise ValueError('Couldn\'t parse float: %s' % text) + + +def ParseBool(text): + """Parse a boolean value. + + Args: + text: Text to parse. + + Returns: + Boolean values parsed + + Raises: + ValueError: If text is not a valid boolean. + """ + if text in ('true', 't', '1'): + return True + elif text in ('false', 'f', '0'): + return False + else: + raise ValueError('Expected "true" or "false".') + + +def ParseEnum(field, value): + """Parse an enum value. + + The value can be specified by a number (the enum value), or by + a string literal (the enum name). + + Args: + field: Enum field descriptor. + value: String value. + + Returns: + Enum value number. + + Raises: + ValueError: If the enum value could not be parsed. + """ + enum_descriptor = field.enum_type + try: + number = int(value, 0) + except ValueError: + # Identifier. + enum_value = enum_descriptor.values_by_name.get(value, None) + if enum_value is None: + raise ValueError( + 'Enum type "%s" has no value named %s.' % ( + enum_descriptor.full_name, value)) + else: + # Numeric value. + enum_value = enum_descriptor.values_by_number.get(number, None) + if enum_value is None: + raise ValueError( + 'Enum type "%s" has no value with number %d.' % ( + enum_descriptor.full_name, number)) + return enum_value.number diff --git a/code/push/google/protobuf/unittest_custom_options_pb2.py b/code/push/google/protobuf/unittest_custom_options_pb2.py new file mode 100644 index 0000000..7386e39 --- /dev/null +++ b/code/push/google/protobuf/unittest_custom_options_pb2.py @@ -0,0 +1,1486 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/unittest_custom_options.proto + +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import service as _service +from google.protobuf import service_reflection +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + + +import google.protobuf.descriptor_pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/unittest_custom_options.proto', + package='protobuf_unittest', + serialized_pb='\n-google/protobuf/unittest_custom_options.proto\x12\x11protobuf_unittest\x1a google/protobuf/descriptor.proto\"\x8d\x01\n\x1cTestMessageWithCustomOptions\x12\x1e\n\x06\x66ield1\x18\x01 \x01(\tB\x0e\x08\x01\xc1\xe0\xc3\x1d-\xe1u\n\x02\x00\x00\x00\";\n\x06\x41nEnum\x12\x0f\n\x0b\x41NENUM_VAL1\x10\x01\x12\x16\n\x0b\x41NENUM_VAL2\x10\x02\x1a\x05\xb0\x86\xfa\x05{\x1a\x08\xc5\xf6\xc9\x1d\xeb\xfc\xff\xff:\x10\x08\x00\xe0\xe9\xc2\x1d\xc8\xff\xff\xff\xff\xff\xff\xff\xff\x01\"\x18\n\x16\x43ustomOptionFooRequest\"\x19\n\x17\x43ustomOptionFooResponse\"\x1e\n\x1c\x43ustomOptionFooClientMessage\"\x1e\n\x1c\x43ustomOptionFooServerMessage\"m\n\x1a\x44ummyMessageContainingEnum\"O\n\x0cTestEnumType\x12\x1a\n\x16TEST_OPTION_ENUM_TYPE1\x10\x16\x12#\n\x16TEST_OPTION_ENUM_TYPE2\x10\xe9\xff\xff\xff\xff\xff\xff\xff\xff\x01\"!\n\x1f\x44ummyMessageInvalidAsOptionType\"\x8a\x01\n\x1c\x43ustomOptionMinIntegerValues:j\xd0\xde\xb2\x1d\x00\xe8\xc6\xb2\x1d\x80\x80\x80\x80\xf8\xff\xff\xff\xff\x01\xb0\xbc\xb2\x1d\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01\x80\x93\xb2\x1d\x00\xf8\xf5\xb0\x1d\x00\x80\xc4\xb0\x1d\xff\xff\xff\xff\x0f\xf8\x97\xb0\x1d\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x9d\xf5\xaf\x1d\x00\x00\x00\x00\x91\xee\xaf\x1d\x00\x00\x00\x00\x00\x00\x00\x00\xad\x8d\xaf\x1d\x00\x00\x00\x80\x99\xd6\xa8\x1d\x00\x00\x00\x00\x00\x00\x00\x80\"\x91\x01\n\x1c\x43ustomOptionMaxIntegerValues:q\xd0\xde\xb2\x1d\x01\xe8\xc6\xb2\x1d\xff\xff\xff\xff\x07\xb0\xbc\xb2\x1d\xff\xff\xff\xff\xff\xff\xff\xff\x7f\x80\x93\xb2\x1d\xff\xff\xff\xff\x0f\xf8\xf5\xb0\x1d\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x80\xc4\xb0\x1d\xfe\xff\xff\xff\x0f\xf8\x97\xb0\x1d\xfe\xff\xff\xff\xff\xff\xff\xff\xff\x01\x9d\xf5\xaf\x1d\xff\xff\xff\xff\x91\xee\xaf\x1d\xff\xff\xff\xff\xff\xff\xff\xff\xad\x8d\xaf\x1d\xff\xff\xff\x7f\x99\xd6\xa8\x1d\xff\xff\xff\xff\xff\xff\xff\x7f\"n\n\x17\x43ustomOptionOtherValues:S\xe8\xc6\xb2\x1d\x9c\xff\xff\xff\xff\xff\xff\xff\xff\x01\xf5\xdf\xa3\x1d\xe7\x87\x45\x41\xe9\xdc\xa2\x1d\xfbY\x8c\x42\xca\xc0\xf3?\xaa\xdc\xa2\x1d\x0eHello, \"World\"\xb2\xd9\xa2\x1d\x0bHello\x00World\x88\xd9\xa2\x1d\xe9\xff\xff\xff\xff\xff\xff\xff\xff\x01\"4\n\x1cSettingRealsFromPositiveInts:\x14\xf5\xdf\xa3\x1d\x00\x00@A\xe9\xdc\xa2\x1d\x00\x00\x00\x00\x00@c@\"4\n\x1cSettingRealsFromNegativeInts:\x14\xf5\xdf\xa3\x1d\x00\x00@\xc1\xe9\xdc\xa2\x1d\x00\x00\x00\x00\x00@c\xc0\"G\n\x12\x43omplexOptionType1\x12\x0b\n\x03\x66oo\x18\x01 \x01(\x05\x12\x0c\n\x04\x66oo2\x18\x02 \x01(\x05\x12\x0c\n\x04\x66oo3\x18\x03 \x01(\x05*\x08\x08\x64\x10\x80\x80\x80\x80\x02\"\xc1\x02\n\x12\x43omplexOptionType2\x12\x32\n\x03\x62\x61r\x18\x01 \x01(\x0b\x32%.protobuf_unittest.ComplexOptionType1\x12\x0b\n\x03\x62\x61z\x18\x02 \x01(\x05\x12\x46\n\x04\x66red\x18\x03 \x01(\x0b\x32\x38.protobuf_unittest.ComplexOptionType2.ComplexOptionType4\x1a\x97\x01\n\x12\x43omplexOptionType4\x12\r\n\x05waldo\x18\x01 \x01(\x05\x32r\n\x0c\x63omplex_opt4\x12\x1f.google.protobuf.MessageOptions\x18\x8a\xf5\xd1\x03 \x01(\x0b\x32\x38.protobuf_unittest.ComplexOptionType2.ComplexOptionType4*\x08\x08\x64\x10\x80\x80\x80\x80\x02\"\x9c\x01\n\x12\x43omplexOptionType3\x12\x0b\n\x03qux\x18\x01 \x01(\x05\x12T\n\x12\x63omplexoptiontype5\x18\x02 \x01(\n28.protobuf_unittest.ComplexOptionType3.ComplexOptionType5\x1a#\n\x12\x43omplexOptionType5\x12\r\n\x05plugh\x18\x03 \x01(\x05\"\x1f\n\x0b\x43omplexOpt6\x12\x10\n\x05xyzzy\x18\xdf\xbf\xcf\x03 \x01(\x05\"\xd0\x01\n\x15VariousComplexOptions:\xb6\x01\xa2\xe2\x95\x1d\x02\x08*\xa2\xe2\x95\x1d\x06\xd8\x85\x9e\x1d\xc4\x02\xa2\xe2\x95\x1d\x08\x92\xf5\x9d\x1d\x03\x08\xec\x06\xaa\xfd\x90\x1d\x03\x10\xdb\x07\xaa\xfd\x90\x1d\x06\xf8\xe6\x97\x1d\x8e\x05\xaa\xfd\x90\x1d\x05\n\x03\x08\xe7\x05\xaa\xfd\x90\x1d\x08\n\x06\xd8\x85\x9e\x1d\xcf\x0f\xaa\xfd\x90\x1d\n\n\x08\x92\xf5\x9d\x1d\x03\x08\xd8\x0f\xaa\xfd\x90\x1d\x08\xc2\xac\x97\x1d\x03\x08\xe5\x05\xaa\xfd\x90\x1d\x0b\xc2\xac\x97\x1d\x06\xd8\x85\x9e\x1d\xce\x0f\xaa\xfd\x90\x1d\r\xc2\xac\x97\x1d\x08\x92\xf5\x9d\x1d\x03\x08\xc9\x10\xd2\xa8\x8f\x1d\x03\x08\xb3\x0f\xaa\xfd\x90\x1d\x05\x1a\x03\x08\xc1\x02\xfa\xde\x90\x1d\x02\x08\t\xfa\xde\x90\x1d\x04\x13\x18\x16\x14\xe3\xdc\xfc\x1c\xf8\xfd\xfb\x1c\x18\xe4\xdc\xfc\x1c\"#\n\x13\x41ggregateMessageSet*\x08\x08\x04\x10\xff\xff\xff\xff\x07:\x02\x08\x01\"\xa0\x01\n\x1a\x41ggregateMessageSetElement\x12\t\n\x01s\x18\x01 \x01(\t2w\n\x15message_set_extension\x12&.protobuf_unittest.AggregateMessageSet\x18\xf6\xeb\xae\x07 \x01(\x0b\x32-.protobuf_unittest.AggregateMessageSetElement\"\xfd\x01\n\tAggregate\x12\t\n\x01i\x18\x01 \x01(\x05\x12\t\n\x01s\x18\x02 \x01(\t\x12)\n\x03sub\x18\x03 \x01(\x0b\x32\x1c.protobuf_unittest.Aggregate\x12*\n\x04\x66ile\x18\x04 \x01(\x0b\x32\x1c.google.protobuf.FileOptions\x12\x34\n\x04mset\x18\x05 \x01(\x0b\x32&.protobuf_unittest.AggregateMessageSet2M\n\x06nested\x12\x1c.google.protobuf.FileOptions\x18\xa7\xd1\xb0\x07 \x01(\x0b\x32\x1c.protobuf_unittest.Aggregate\"Y\n\x10\x41ggregateMessage\x12)\n\tfieldname\x18\x01 \x01(\x05\x42\x16\xf2\xa1\x87;\x11\x12\x0f\x46ieldAnnotation:\x1a\xc2\xd1\x86;\x15\x08\x65\x12\x11MessageAnnotation\"\xc9\x01\n\x10NestedOptionType\x1a;\n\rNestedMessage\x12\"\n\x0cnested_field\x18\x01 \x01(\x05\x42\x0c\xc1\xe0\xc3\x1d\xea\x03\x00\x00\x00\x00\x00\x00:\x06\xe0\xe9\xc2\x1d\xe9\x07\"5\n\nNestedEnum\x12\x1d\n\x11NESTED_ENUM_VALUE\x10\x01\x1a\x06\xb0\x86\xfa\x05\xec\x07\x1a\x08\xc5\xf6\xc9\x1d\xeb\x03\x00\x00\x32\x41\n\x10nested_extension\x12\x1c.google.protobuf.FileOptions\x18\xfd\xf8\xe2\x03 \x01(\x05\x42\x06\xc8\x8b\xca\x1d\xed\x07*6\n\nMethodOpt1\x12\x13\n\x0fMETHODOPT1_VAL1\x10\x01\x12\x13\n\x0fMETHODOPT1_VAL2\x10\x02*M\n\rAggregateEnum\x12%\n\x05VALUE\x10\x01\x1a\x1a\xca\xfc\x89;\x15\x12\x13\x45numValueAnnotation\x1a\x15\x92\x95\x88;\x10\x12\x0e\x45numAnnotation2\x8e\x01\n\x1cTestServiceWithCustomOptions\x12\x63\n\x03\x46oo\x12).protobuf_unittest.CustomOptionFooRequest\x1a*.protobuf_unittest.CustomOptionFooResponse\"\x05\xe0\xfa\x8c\x1e\x02\x1a\t\x90\xb2\x8b\x1e\xd3\xdb\x80\xcbI2\x99\x01\n\x10\x41ggregateService\x12k\n\x06Method\x12#.protobuf_unittest.AggregateMessage\x1a#.protobuf_unittest.AggregateMessage\"\x17\xca\xc8\x96;\x12\x12\x10MethodAnnotation\x1a\x18\xca\xfb\x8e;\x13\x12\x11ServiceAnnotation:2\n\tfile_opt1\x12\x1c.google.protobuf.FileOptions\x18\x8e\x9d\xd8\x03 \x01(\x04:8\n\x0cmessage_opt1\x12\x1f.google.protobuf.MessageOptions\x18\x9c\xad\xd8\x03 \x01(\x05:4\n\nfield_opt1\x12\x1d.google.protobuf.FieldOptions\x18\x88\xbc\xd8\x03 \x01(\x06:8\n\nfield_opt2\x12\x1d.google.protobuf.FieldOptions\x18\xb9\xa1\xd9\x03 \x01(\x05:\x02\x34\x32:2\n\tenum_opt1\x12\x1c.google.protobuf.EnumOptions\x18\xe8\x9e\xd9\x03 \x01(\x0f:<\n\x0f\x65num_value_opt1\x12!.google.protobuf.EnumValueOptions\x18\xe6\xa0_ \x01(\x05:8\n\x0cservice_opt1\x12\x1f.google.protobuf.ServiceOptions\x18\xa2\xb6\xe1\x03 \x01(\x12:U\n\x0bmethod_opt1\x12\x1e.google.protobuf.MethodOptions\x18\xac\xcf\xe1\x03 \x01(\x0e\x32\x1d.protobuf_unittest.MethodOpt1:4\n\x08\x62ool_opt\x12\x1f.google.protobuf.MessageOptions\x18\xea\xab\xd6\x03 \x01(\x08:5\n\tint32_opt\x12\x1f.google.protobuf.MessageOptions\x18\xed\xa8\xd6\x03 \x01(\x05:5\n\tint64_opt\x12\x1f.google.protobuf.MessageOptions\x18\xc6\xa7\xd6\x03 \x01(\x03:6\n\nuint32_opt\x12\x1f.google.protobuf.MessageOptions\x18\xb0\xa2\xd6\x03 \x01(\r:6\n\nuint64_opt\x12\x1f.google.protobuf.MessageOptions\x18\xdf\x8e\xd6\x03 \x01(\x04:6\n\nsint32_opt\x12\x1f.google.protobuf.MessageOptions\x18\xc0\x88\xd6\x03 \x01(\x11:6\n\nsint64_opt\x12\x1f.google.protobuf.MessageOptions\x18\xff\x82\xd6\x03 \x01(\x12:7\n\x0b\x66ixed32_opt\x12\x1f.google.protobuf.MessageOptions\x18\xd3\xfe\xd5\x03 \x01(\x07:7\n\x0b\x66ixed64_opt\x12\x1f.google.protobuf.MessageOptions\x18\xe2\xfd\xd5\x03 \x01(\x06:8\n\x0csfixed32_opt\x12\x1f.google.protobuf.MessageOptions\x18\xd5\xf1\xd5\x03 \x01(\x0f:8\n\x0csfixed64_opt\x12\x1f.google.protobuf.MessageOptions\x18\xe3\x8a\xd5\x03 \x01(\x10:5\n\tfloat_opt\x12\x1f.google.protobuf.MessageOptions\x18\xfe\xbb\xd4\x03 \x01(\x02:6\n\ndouble_opt\x12\x1f.google.protobuf.MessageOptions\x18\xcd\xab\xd4\x03 \x01(\x01:6\n\nstring_opt\x12\x1f.google.protobuf.MessageOptions\x18\xc5\xab\xd4\x03 \x01(\t:5\n\tbytes_opt\x12\x1f.google.protobuf.MessageOptions\x18\x96\xab\xd4\x03 \x01(\x0c:p\n\x08\x65num_opt\x12\x1f.google.protobuf.MessageOptions\x18\x91\xab\xd4\x03 \x01(\x0e\x32:.protobuf_unittest.DummyMessageContainingEnum.TestEnumType:p\n\x10message_type_opt\x12\x1f.google.protobuf.MessageOptions\x18\xaf\xf2\xd3\x03 \x01(\x0b\x32\x32.protobuf_unittest.DummyMessageInvalidAsOptionType:6\n\x04quux\x12%.protobuf_unittest.ComplexOptionType1\x18\xdb\xe0\xd3\x03 \x01(\x05:^\n\x05\x63orge\x12%.protobuf_unittest.ComplexOptionType1\x18\xd2\xde\xd3\x03 \x01(\x0b\x32%.protobuf_unittest.ComplexOptionType3:8\n\x06grault\x12%.protobuf_unittest.ComplexOptionType2\x18\xef\xfc\xd2\x03 \x01(\x05:_\n\x06garply\x12%.protobuf_unittest.ComplexOptionType2\x18\xc8\xf5\xd2\x03 \x01(\x0b\x32%.protobuf_unittest.ComplexOptionType1:_\n\x0c\x63omplex_opt1\x12\x1f.google.protobuf.MessageOptions\x18\xa4\xdc\xd2\x03 \x01(\x0b\x32%.protobuf_unittest.ComplexOptionType1:_\n\x0c\x63omplex_opt2\x12\x1f.google.protobuf.MessageOptions\x18\xd5\x8f\xd2\x03 \x01(\x0b\x32%.protobuf_unittest.ComplexOptionType2:_\n\x0c\x63omplex_opt3\x12\x1f.google.protobuf.MessageOptions\x18\xef\x8b\xd2\x03 \x01(\x0b\x32%.protobuf_unittest.ComplexOptionType3:W\n\x0b\x63omplexopt6\x12\x1f.google.protobuf.MessageOptions\x18\xcc\xcb\xcf\x03 \x01(\n2\x1e.protobuf_unittest.ComplexOpt6:N\n\x07\x66ileopt\x12\x1c.google.protobuf.FileOptions\x18\xcf\xdd\xb0\x07 \x01(\x0b\x32\x1c.protobuf_unittest.Aggregate:P\n\x06msgopt\x12\x1f.google.protobuf.MessageOptions\x18\x98\xea\xb0\x07 \x01(\x0b\x32\x1c.protobuf_unittest.Aggregate:P\n\x08\x66ieldopt\x12\x1d.google.protobuf.FieldOptions\x18\x9e\xf4\xb0\x07 \x01(\x0b\x32\x1c.protobuf_unittest.Aggregate:N\n\x07\x65numopt\x12\x1c.google.protobuf.EnumOptions\x18\xd2\x82\xb1\x07 \x01(\x0b\x32\x1c.protobuf_unittest.Aggregate:V\n\nenumvalopt\x12!.google.protobuf.EnumValueOptions\x18\xc9\x9f\xb1\x07 \x01(\x0b\x32\x1c.protobuf_unittest.Aggregate:T\n\nserviceopt\x12\x1f.google.protobuf.ServiceOptions\x18\xb9\xef\xb1\x07 \x01(\x0b\x32\x1c.protobuf_unittest.Aggregate:R\n\tmethodopt\x12\x1e.google.protobuf.MethodOptions\x18\x89\xe9\xb2\x07 \x01(\x0b\x32\x1c.protobuf_unittest.AggregateB\x87\x01\x80\x01\x01\x88\x01\x01\x90\x01\x01\xf0\xe8\xc1\x1d\xea\xad\xc0\xe5$\xfa\xec\x85;p\x08\x64\x12\x0e\x46ileAnnotation\x1a\x16\x12\x14NestedFileAnnotation\"\x1e\xfa\xec\x85;\x19\x12\x17\x46ileExtensionAnnotation*$\x0b\x10\xf6\xeb\xae\x07\x1a\x1b\n\x19\x45mbeddedMessageSetElement\x0c') + +_METHODOPT1 = _descriptor.EnumDescriptor( + name='MethodOpt1', + full_name='protobuf_unittest.MethodOpt1', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='METHODOPT1_VAL1', index=0, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='METHODOPT1_VAL2', index=1, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=2569, + serialized_end=2623, +) + +MethodOpt1 = enum_type_wrapper.EnumTypeWrapper(_METHODOPT1) +_AGGREGATEENUM = _descriptor.EnumDescriptor( + name='AggregateEnum', + full_name='protobuf_unittest.AggregateEnum', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='VALUE', index=0, number=1, + options=_descriptor._ParseOptions(descriptor_pb2.EnumValueOptions(), '\312\374\211;\025\022\023EnumValueAnnotation'), + type=None), + ], + containing_type=None, + options=_descriptor._ParseOptions(descriptor_pb2.EnumOptions(), '\222\225\210;\020\022\016EnumAnnotation'), + serialized_start=2625, + serialized_end=2702, +) + +AggregateEnum = enum_type_wrapper.EnumTypeWrapper(_AGGREGATEENUM) +METHODOPT1_VAL1 = 1 +METHODOPT1_VAL2 = 2 +VALUE = 1 + +FILE_OPT1_FIELD_NUMBER = 7736974 +file_opt1 = _descriptor.FieldDescriptor( + name='file_opt1', full_name='protobuf_unittest.file_opt1', index=0, + number=7736974, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +MESSAGE_OPT1_FIELD_NUMBER = 7739036 +message_opt1 = _descriptor.FieldDescriptor( + name='message_opt1', full_name='protobuf_unittest.message_opt1', index=1, + number=7739036, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +FIELD_OPT1_FIELD_NUMBER = 7740936 +field_opt1 = _descriptor.FieldDescriptor( + name='field_opt1', full_name='protobuf_unittest.field_opt1', index=2, + number=7740936, type=6, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +FIELD_OPT2_FIELD_NUMBER = 7753913 +field_opt2 = _descriptor.FieldDescriptor( + name='field_opt2', full_name='protobuf_unittest.field_opt2', index=3, + number=7753913, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=42, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +ENUM_OPT1_FIELD_NUMBER = 7753576 +enum_opt1 = _descriptor.FieldDescriptor( + name='enum_opt1', full_name='protobuf_unittest.enum_opt1', index=4, + number=7753576, type=15, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +ENUM_VALUE_OPT1_FIELD_NUMBER = 1560678 +enum_value_opt1 = _descriptor.FieldDescriptor( + name='enum_value_opt1', full_name='protobuf_unittest.enum_value_opt1', index=5, + number=1560678, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +SERVICE_OPT1_FIELD_NUMBER = 7887650 +service_opt1 = _descriptor.FieldDescriptor( + name='service_opt1', full_name='protobuf_unittest.service_opt1', index=6, + number=7887650, type=18, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +METHOD_OPT1_FIELD_NUMBER = 7890860 +method_opt1 = _descriptor.FieldDescriptor( + name='method_opt1', full_name='protobuf_unittest.method_opt1', index=7, + number=7890860, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +BOOL_OPT_FIELD_NUMBER = 7706090 +bool_opt = _descriptor.FieldDescriptor( + name='bool_opt', full_name='protobuf_unittest.bool_opt', index=8, + number=7706090, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +INT32_OPT_FIELD_NUMBER = 7705709 +int32_opt = _descriptor.FieldDescriptor( + name='int32_opt', full_name='protobuf_unittest.int32_opt', index=9, + number=7705709, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +INT64_OPT_FIELD_NUMBER = 7705542 +int64_opt = _descriptor.FieldDescriptor( + name='int64_opt', full_name='protobuf_unittest.int64_opt', index=10, + number=7705542, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +UINT32_OPT_FIELD_NUMBER = 7704880 +uint32_opt = _descriptor.FieldDescriptor( + name='uint32_opt', full_name='protobuf_unittest.uint32_opt', index=11, + number=7704880, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +UINT64_OPT_FIELD_NUMBER = 7702367 +uint64_opt = _descriptor.FieldDescriptor( + name='uint64_opt', full_name='protobuf_unittest.uint64_opt', index=12, + number=7702367, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +SINT32_OPT_FIELD_NUMBER = 7701568 +sint32_opt = _descriptor.FieldDescriptor( + name='sint32_opt', full_name='protobuf_unittest.sint32_opt', index=13, + number=7701568, type=17, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +SINT64_OPT_FIELD_NUMBER = 7700863 +sint64_opt = _descriptor.FieldDescriptor( + name='sint64_opt', full_name='protobuf_unittest.sint64_opt', index=14, + number=7700863, type=18, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +FIXED32_OPT_FIELD_NUMBER = 7700307 +fixed32_opt = _descriptor.FieldDescriptor( + name='fixed32_opt', full_name='protobuf_unittest.fixed32_opt', index=15, + number=7700307, type=7, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +FIXED64_OPT_FIELD_NUMBER = 7700194 +fixed64_opt = _descriptor.FieldDescriptor( + name='fixed64_opt', full_name='protobuf_unittest.fixed64_opt', index=16, + number=7700194, type=6, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +SFIXED32_OPT_FIELD_NUMBER = 7698645 +sfixed32_opt = _descriptor.FieldDescriptor( + name='sfixed32_opt', full_name='protobuf_unittest.sfixed32_opt', index=17, + number=7698645, type=15, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +SFIXED64_OPT_FIELD_NUMBER = 7685475 +sfixed64_opt = _descriptor.FieldDescriptor( + name='sfixed64_opt', full_name='protobuf_unittest.sfixed64_opt', index=18, + number=7685475, type=16, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +FLOAT_OPT_FIELD_NUMBER = 7675390 +float_opt = _descriptor.FieldDescriptor( + name='float_opt', full_name='protobuf_unittest.float_opt', index=19, + number=7675390, type=2, cpp_type=6, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DOUBLE_OPT_FIELD_NUMBER = 7673293 +double_opt = _descriptor.FieldDescriptor( + name='double_opt', full_name='protobuf_unittest.double_opt', index=20, + number=7673293, type=1, cpp_type=5, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +STRING_OPT_FIELD_NUMBER = 7673285 +string_opt = _descriptor.FieldDescriptor( + name='string_opt', full_name='protobuf_unittest.string_opt', index=21, + number=7673285, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +BYTES_OPT_FIELD_NUMBER = 7673238 +bytes_opt = _descriptor.FieldDescriptor( + name='bytes_opt', full_name='protobuf_unittest.bytes_opt', index=22, + number=7673238, type=12, cpp_type=9, label=1, + has_default_value=False, default_value="", + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +ENUM_OPT_FIELD_NUMBER = 7673233 +enum_opt = _descriptor.FieldDescriptor( + name='enum_opt', full_name='protobuf_unittest.enum_opt', index=23, + number=7673233, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=22, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +MESSAGE_TYPE_OPT_FIELD_NUMBER = 7665967 +message_type_opt = _descriptor.FieldDescriptor( + name='message_type_opt', full_name='protobuf_unittest.message_type_opt', index=24, + number=7665967, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +QUUX_FIELD_NUMBER = 7663707 +quux = _descriptor.FieldDescriptor( + name='quux', full_name='protobuf_unittest.quux', index=25, + number=7663707, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +CORGE_FIELD_NUMBER = 7663442 +corge = _descriptor.FieldDescriptor( + name='corge', full_name='protobuf_unittest.corge', index=26, + number=7663442, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +GRAULT_FIELD_NUMBER = 7650927 +grault = _descriptor.FieldDescriptor( + name='grault', full_name='protobuf_unittest.grault', index=27, + number=7650927, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +GARPLY_FIELD_NUMBER = 7649992 +garply = _descriptor.FieldDescriptor( + name='garply', full_name='protobuf_unittest.garply', index=28, + number=7649992, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +COMPLEX_OPT1_FIELD_NUMBER = 7646756 +complex_opt1 = _descriptor.FieldDescriptor( + name='complex_opt1', full_name='protobuf_unittest.complex_opt1', index=29, + number=7646756, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +COMPLEX_OPT2_FIELD_NUMBER = 7636949 +complex_opt2 = _descriptor.FieldDescriptor( + name='complex_opt2', full_name='protobuf_unittest.complex_opt2', index=30, + number=7636949, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +COMPLEX_OPT3_FIELD_NUMBER = 7636463 +complex_opt3 = _descriptor.FieldDescriptor( + name='complex_opt3', full_name='protobuf_unittest.complex_opt3', index=31, + number=7636463, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +COMPLEXOPT6_FIELD_NUMBER = 7595468 +complexopt6 = _descriptor.FieldDescriptor( + name='complexopt6', full_name='protobuf_unittest.complexopt6', index=32, + number=7595468, type=10, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +FILEOPT_FIELD_NUMBER = 15478479 +fileopt = _descriptor.FieldDescriptor( + name='fileopt', full_name='protobuf_unittest.fileopt', index=33, + number=15478479, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +MSGOPT_FIELD_NUMBER = 15480088 +msgopt = _descriptor.FieldDescriptor( + name='msgopt', full_name='protobuf_unittest.msgopt', index=34, + number=15480088, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +FIELDOPT_FIELD_NUMBER = 15481374 +fieldopt = _descriptor.FieldDescriptor( + name='fieldopt', full_name='protobuf_unittest.fieldopt', index=35, + number=15481374, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +ENUMOPT_FIELD_NUMBER = 15483218 +enumopt = _descriptor.FieldDescriptor( + name='enumopt', full_name='protobuf_unittest.enumopt', index=36, + number=15483218, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +ENUMVALOPT_FIELD_NUMBER = 15486921 +enumvalopt = _descriptor.FieldDescriptor( + name='enumvalopt', full_name='protobuf_unittest.enumvalopt', index=37, + number=15486921, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +SERVICEOPT_FIELD_NUMBER = 15497145 +serviceopt = _descriptor.FieldDescriptor( + name='serviceopt', full_name='protobuf_unittest.serviceopt', index=38, + number=15497145, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +METHODOPT_FIELD_NUMBER = 15512713 +methodopt = _descriptor.FieldDescriptor( + name='methodopt', full_name='protobuf_unittest.methodopt', index=39, + number=15512713, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) + +_TESTMESSAGEWITHCUSTOMOPTIONS_ANENUM = _descriptor.EnumDescriptor( + name='AnEnum', + full_name='protobuf_unittest.TestMessageWithCustomOptions.AnEnum', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='ANENUM_VAL1', index=0, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='ANENUM_VAL2', index=1, number=2, + options=_descriptor._ParseOptions(descriptor_pb2.EnumValueOptions(), '\260\206\372\005{'), + type=None), + ], + containing_type=None, + options=_descriptor._ParseOptions(descriptor_pb2.EnumOptions(), '\305\366\311\035\353\374\377\377'), + serialized_start=167, + serialized_end=226, +) + +_DUMMYMESSAGECONTAININGENUM_TESTENUMTYPE = _descriptor.EnumDescriptor( + name='TestEnumType', + full_name='protobuf_unittest.DummyMessageContainingEnum.TestEnumType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='TEST_OPTION_ENUM_TYPE1', index=0, number=22, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TEST_OPTION_ENUM_TYPE2', index=1, number=-23, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=393, + serialized_end=472, +) + +_NESTEDOPTIONTYPE_NESTEDENUM = _descriptor.EnumDescriptor( + name='NestedEnum', + full_name='protobuf_unittest.NestedOptionType.NestedEnum', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='NESTED_ENUM_VALUE', index=0, number=1, + options=_descriptor._ParseOptions(descriptor_pb2.EnumValueOptions(), '\260\206\372\005\354\007'), + type=None), + ], + containing_type=None, + options=_descriptor._ParseOptions(descriptor_pb2.EnumOptions(), '\305\366\311\035\353\003\000\000'), + serialized_start=2447, + serialized_end=2500, +) + + +_TESTMESSAGEWITHCUSTOMOPTIONS = _descriptor.Descriptor( + name='TestMessageWithCustomOptions', + full_name='protobuf_unittest.TestMessageWithCustomOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='field1', full_name='protobuf_unittest.TestMessageWithCustomOptions.field1', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001\301\340\303\035-\341u\n\002\000\000\000')), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _TESTMESSAGEWITHCUSTOMOPTIONS_ANENUM, + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\010\000\340\351\302\035\310\377\377\377\377\377\377\377\377\001'), + is_extendable=False, + extension_ranges=[], + serialized_start=103, + serialized_end=244, +) + + +_CUSTOMOPTIONFOOREQUEST = _descriptor.Descriptor( + name='CustomOptionFooRequest', + full_name='protobuf_unittest.CustomOptionFooRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=246, + serialized_end=270, +) + + +_CUSTOMOPTIONFOORESPONSE = _descriptor.Descriptor( + name='CustomOptionFooResponse', + full_name='protobuf_unittest.CustomOptionFooResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=272, + serialized_end=297, +) + + +_CUSTOMOPTIONFOOCLIENTMESSAGE = _descriptor.Descriptor( + name='CustomOptionFooClientMessage', + full_name='protobuf_unittest.CustomOptionFooClientMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=299, + serialized_end=329, +) + + +_CUSTOMOPTIONFOOSERVERMESSAGE = _descriptor.Descriptor( + name='CustomOptionFooServerMessage', + full_name='protobuf_unittest.CustomOptionFooServerMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=331, + serialized_end=361, +) + + +_DUMMYMESSAGECONTAININGENUM = _descriptor.Descriptor( + name='DummyMessageContainingEnum', + full_name='protobuf_unittest.DummyMessageContainingEnum', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _DUMMYMESSAGECONTAININGENUM_TESTENUMTYPE, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=363, + serialized_end=472, +) + + +_DUMMYMESSAGEINVALIDASOPTIONTYPE = _descriptor.Descriptor( + name='DummyMessageInvalidAsOptionType', + full_name='protobuf_unittest.DummyMessageInvalidAsOptionType', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=474, + serialized_end=507, +) + + +_CUSTOMOPTIONMININTEGERVALUES = _descriptor.Descriptor( + name='CustomOptionMinIntegerValues', + full_name='protobuf_unittest.CustomOptionMinIntegerValues', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\320\336\262\035\000\350\306\262\035\200\200\200\200\370\377\377\377\377\001\260\274\262\035\200\200\200\200\200\200\200\200\200\001\200\223\262\035\000\370\365\260\035\000\200\304\260\035\377\377\377\377\017\370\227\260\035\377\377\377\377\377\377\377\377\377\001\235\365\257\035\000\000\000\000\221\356\257\035\000\000\000\000\000\000\000\000\255\215\257\035\000\000\000\200\231\326\250\035\000\000\000\000\000\000\000\200'), + is_extendable=False, + extension_ranges=[], + serialized_start=510, + serialized_end=648, +) + + +_CUSTOMOPTIONMAXINTEGERVALUES = _descriptor.Descriptor( + name='CustomOptionMaxIntegerValues', + full_name='protobuf_unittest.CustomOptionMaxIntegerValues', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\320\336\262\035\001\350\306\262\035\377\377\377\377\007\260\274\262\035\377\377\377\377\377\377\377\377\177\200\223\262\035\377\377\377\377\017\370\365\260\035\377\377\377\377\377\377\377\377\377\001\200\304\260\035\376\377\377\377\017\370\227\260\035\376\377\377\377\377\377\377\377\377\001\235\365\257\035\377\377\377\377\221\356\257\035\377\377\377\377\377\377\377\377\255\215\257\035\377\377\377\177\231\326\250\035\377\377\377\377\377\377\377\177'), + is_extendable=False, + extension_ranges=[], + serialized_start=651, + serialized_end=796, +) + + +_CUSTOMOPTIONOTHERVALUES = _descriptor.Descriptor( + name='CustomOptionOtherValues', + full_name='protobuf_unittest.CustomOptionOtherValues', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\350\306\262\035\234\377\377\377\377\377\377\377\377\001\365\337\243\035\347\207EA\351\334\242\035\373Y\214B\312\300\363?\252\334\242\035\016Hello, \"World\"\262\331\242\035\013Hello\000World\210\331\242\035\351\377\377\377\377\377\377\377\377\001'), + is_extendable=False, + extension_ranges=[], + serialized_start=798, + serialized_end=908, +) + + +_SETTINGREALSFROMPOSITIVEINTS = _descriptor.Descriptor( + name='SettingRealsFromPositiveInts', + full_name='protobuf_unittest.SettingRealsFromPositiveInts', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\365\337\243\035\000\000@A\351\334\242\035\000\000\000\000\000@c@'), + is_extendable=False, + extension_ranges=[], + serialized_start=910, + serialized_end=962, +) + + +_SETTINGREALSFROMNEGATIVEINTS = _descriptor.Descriptor( + name='SettingRealsFromNegativeInts', + full_name='protobuf_unittest.SettingRealsFromNegativeInts', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\365\337\243\035\000\000@\301\351\334\242\035\000\000\000\000\000@c\300'), + is_extendable=False, + extension_ranges=[], + serialized_start=964, + serialized_end=1016, +) + + +_COMPLEXOPTIONTYPE1 = _descriptor.Descriptor( + name='ComplexOptionType1', + full_name='protobuf_unittest.ComplexOptionType1', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='foo', full_name='protobuf_unittest.ComplexOptionType1.foo', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='foo2', full_name='protobuf_unittest.ComplexOptionType1.foo2', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='foo3', full_name='protobuf_unittest.ComplexOptionType1.foo3', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(100, 536870912), ], + serialized_start=1018, + serialized_end=1089, +) + + +_COMPLEXOPTIONTYPE2_COMPLEXOPTIONTYPE4 = _descriptor.Descriptor( + name='ComplexOptionType4', + full_name='protobuf_unittest.ComplexOptionType2.ComplexOptionType4', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='waldo', full_name='protobuf_unittest.ComplexOptionType2.ComplexOptionType4.waldo', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + _descriptor.FieldDescriptor( + name='complex_opt4', full_name='protobuf_unittest.ComplexOptionType2.ComplexOptionType4.complex_opt4', index=0, + number=7633546, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None), + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1252, + serialized_end=1403, +) + +_COMPLEXOPTIONTYPE2 = _descriptor.Descriptor( + name='ComplexOptionType2', + full_name='protobuf_unittest.ComplexOptionType2', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='bar', full_name='protobuf_unittest.ComplexOptionType2.bar', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='baz', full_name='protobuf_unittest.ComplexOptionType2.baz', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='fred', full_name='protobuf_unittest.ComplexOptionType2.fred', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_COMPLEXOPTIONTYPE2_COMPLEXOPTIONTYPE4, ], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(100, 536870912), ], + serialized_start=1092, + serialized_end=1413, +) + + +_COMPLEXOPTIONTYPE3_COMPLEXOPTIONTYPE5 = _descriptor.Descriptor( + name='ComplexOptionType5', + full_name='protobuf_unittest.ComplexOptionType3.ComplexOptionType5', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='plugh', full_name='protobuf_unittest.ComplexOptionType3.ComplexOptionType5.plugh', index=0, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1537, + serialized_end=1572, +) + +_COMPLEXOPTIONTYPE3 = _descriptor.Descriptor( + name='ComplexOptionType3', + full_name='protobuf_unittest.ComplexOptionType3', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='qux', full_name='protobuf_unittest.ComplexOptionType3.qux', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='complexoptiontype5', full_name='protobuf_unittest.ComplexOptionType3.complexoptiontype5', index=1, + number=2, type=10, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_COMPLEXOPTIONTYPE3_COMPLEXOPTIONTYPE5, ], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1416, + serialized_end=1572, +) + + +_COMPLEXOPT6 = _descriptor.Descriptor( + name='ComplexOpt6', + full_name='protobuf_unittest.ComplexOpt6', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='xyzzy', full_name='protobuf_unittest.ComplexOpt6.xyzzy', index=0, + number=7593951, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1574, + serialized_end=1605, +) + + +_VARIOUSCOMPLEXOPTIONS = _descriptor.Descriptor( + name='VariousComplexOptions', + full_name='protobuf_unittest.VariousComplexOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\242\342\225\035\002\010*\242\342\225\035\006\330\205\236\035\304\002\242\342\225\035\010\222\365\235\035\003\010\354\006\252\375\220\035\003\020\333\007\252\375\220\035\006\370\346\227\035\216\005\252\375\220\035\005\n\003\010\347\005\252\375\220\035\010\n\006\330\205\236\035\317\017\252\375\220\035\n\n\010\222\365\235\035\003\010\330\017\252\375\220\035\010\302\254\227\035\003\010\345\005\252\375\220\035\013\302\254\227\035\006\330\205\236\035\316\017\252\375\220\035\r\302\254\227\035\010\222\365\235\035\003\010\311\020\322\250\217\035\003\010\263\017\252\375\220\035\005\032\003\010\301\002\372\336\220\035\002\010\t\372\336\220\035\004\023\030\026\024\343\334\374\034\370\375\373\034\030\344\334\374\034'), + is_extendable=False, + extension_ranges=[], + serialized_start=1608, + serialized_end=1816, +) + + +_AGGREGATEMESSAGESET = _descriptor.Descriptor( + name='AggregateMessageSet', + full_name='protobuf_unittest.AggregateMessageSet', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\010\001'), + is_extendable=True, + extension_ranges=[(4, 2147483647), ], + serialized_start=1818, + serialized_end=1853, +) + + +_AGGREGATEMESSAGESETELEMENT = _descriptor.Descriptor( + name='AggregateMessageSetElement', + full_name='protobuf_unittest.AggregateMessageSetElement', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='s', full_name='protobuf_unittest.AggregateMessageSetElement.s', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + _descriptor.FieldDescriptor( + name='message_set_extension', full_name='protobuf_unittest.AggregateMessageSetElement.message_set_extension', index=0, + number=15447542, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None), + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1856, + serialized_end=2016, +) + + +_AGGREGATE = _descriptor.Descriptor( + name='Aggregate', + full_name='protobuf_unittest.Aggregate', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='i', full_name='protobuf_unittest.Aggregate.i', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='s', full_name='protobuf_unittest.Aggregate.s', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sub', full_name='protobuf_unittest.Aggregate.sub', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='file', full_name='protobuf_unittest.Aggregate.file', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='mset', full_name='protobuf_unittest.Aggregate.mset', index=4, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + _descriptor.FieldDescriptor( + name='nested', full_name='protobuf_unittest.Aggregate.nested', index=0, + number=15476903, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None), + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2019, + serialized_end=2272, +) + + +_AGGREGATEMESSAGE = _descriptor.Descriptor( + name='AggregateMessage', + full_name='protobuf_unittest.AggregateMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='fieldname', full_name='protobuf_unittest.AggregateMessage.fieldname', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\362\241\207;\021\022\017FieldAnnotation')), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\302\321\206;\025\010e\022\021MessageAnnotation'), + is_extendable=False, + extension_ranges=[], + serialized_start=2274, + serialized_end=2363, +) + + +_NESTEDOPTIONTYPE_NESTEDMESSAGE = _descriptor.Descriptor( + name='NestedMessage', + full_name='protobuf_unittest.NestedOptionType.NestedMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='nested_field', full_name='protobuf_unittest.NestedOptionType.NestedMessage.nested_field', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\301\340\303\035\352\003\000\000\000\000\000\000')), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\340\351\302\035\351\007'), + is_extendable=False, + extension_ranges=[], + serialized_start=2386, + serialized_end=2445, +) + +_NESTEDOPTIONTYPE = _descriptor.Descriptor( + name='NestedOptionType', + full_name='protobuf_unittest.NestedOptionType', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + _descriptor.FieldDescriptor( + name='nested_extension', full_name='protobuf_unittest.NestedOptionType.nested_extension', index=0, + number=7912573, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\310\213\312\035\355\007')), + ], + nested_types=[_NESTEDOPTIONTYPE_NESTEDMESSAGE, ], + enum_types=[ + _NESTEDOPTIONTYPE_NESTEDENUM, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2366, + serialized_end=2567, +) + +_TESTMESSAGEWITHCUSTOMOPTIONS_ANENUM.containing_type = _TESTMESSAGEWITHCUSTOMOPTIONS; +_DUMMYMESSAGECONTAININGENUM_TESTENUMTYPE.containing_type = _DUMMYMESSAGECONTAININGENUM; +_COMPLEXOPTIONTYPE2_COMPLEXOPTIONTYPE4.containing_type = _COMPLEXOPTIONTYPE2; +_COMPLEXOPTIONTYPE2.fields_by_name['bar'].message_type = _COMPLEXOPTIONTYPE1 +_COMPLEXOPTIONTYPE2.fields_by_name['fred'].message_type = _COMPLEXOPTIONTYPE2_COMPLEXOPTIONTYPE4 +_COMPLEXOPTIONTYPE3_COMPLEXOPTIONTYPE5.containing_type = _COMPLEXOPTIONTYPE3; +_COMPLEXOPTIONTYPE3.fields_by_name['complexoptiontype5'].message_type = _COMPLEXOPTIONTYPE3_COMPLEXOPTIONTYPE5 +_AGGREGATE.fields_by_name['sub'].message_type = _AGGREGATE +_AGGREGATE.fields_by_name['file'].message_type = google.protobuf.descriptor_pb2._FILEOPTIONS +_AGGREGATE.fields_by_name['mset'].message_type = _AGGREGATEMESSAGESET +_NESTEDOPTIONTYPE_NESTEDMESSAGE.containing_type = _NESTEDOPTIONTYPE; +_NESTEDOPTIONTYPE_NESTEDENUM.containing_type = _NESTEDOPTIONTYPE; +DESCRIPTOR.message_types_by_name['TestMessageWithCustomOptions'] = _TESTMESSAGEWITHCUSTOMOPTIONS +DESCRIPTOR.message_types_by_name['CustomOptionFooRequest'] = _CUSTOMOPTIONFOOREQUEST +DESCRIPTOR.message_types_by_name['CustomOptionFooResponse'] = _CUSTOMOPTIONFOORESPONSE +DESCRIPTOR.message_types_by_name['CustomOptionFooClientMessage'] = _CUSTOMOPTIONFOOCLIENTMESSAGE +DESCRIPTOR.message_types_by_name['CustomOptionFooServerMessage'] = _CUSTOMOPTIONFOOSERVERMESSAGE +DESCRIPTOR.message_types_by_name['DummyMessageContainingEnum'] = _DUMMYMESSAGECONTAININGENUM +DESCRIPTOR.message_types_by_name['DummyMessageInvalidAsOptionType'] = _DUMMYMESSAGEINVALIDASOPTIONTYPE +DESCRIPTOR.message_types_by_name['CustomOptionMinIntegerValues'] = _CUSTOMOPTIONMININTEGERVALUES +DESCRIPTOR.message_types_by_name['CustomOptionMaxIntegerValues'] = _CUSTOMOPTIONMAXINTEGERVALUES +DESCRIPTOR.message_types_by_name['CustomOptionOtherValues'] = _CUSTOMOPTIONOTHERVALUES +DESCRIPTOR.message_types_by_name['SettingRealsFromPositiveInts'] = _SETTINGREALSFROMPOSITIVEINTS +DESCRIPTOR.message_types_by_name['SettingRealsFromNegativeInts'] = _SETTINGREALSFROMNEGATIVEINTS +DESCRIPTOR.message_types_by_name['ComplexOptionType1'] = _COMPLEXOPTIONTYPE1 +DESCRIPTOR.message_types_by_name['ComplexOptionType2'] = _COMPLEXOPTIONTYPE2 +DESCRIPTOR.message_types_by_name['ComplexOptionType3'] = _COMPLEXOPTIONTYPE3 +DESCRIPTOR.message_types_by_name['ComplexOpt6'] = _COMPLEXOPT6 +DESCRIPTOR.message_types_by_name['VariousComplexOptions'] = _VARIOUSCOMPLEXOPTIONS +DESCRIPTOR.message_types_by_name['AggregateMessageSet'] = _AGGREGATEMESSAGESET +DESCRIPTOR.message_types_by_name['AggregateMessageSetElement'] = _AGGREGATEMESSAGESETELEMENT +DESCRIPTOR.message_types_by_name['Aggregate'] = _AGGREGATE +DESCRIPTOR.message_types_by_name['AggregateMessage'] = _AGGREGATEMESSAGE +DESCRIPTOR.message_types_by_name['NestedOptionType'] = _NESTEDOPTIONTYPE + +class TestMessageWithCustomOptions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTMESSAGEWITHCUSTOMOPTIONS + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestMessageWithCustomOptions) + +class CustomOptionFooRequest(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _CUSTOMOPTIONFOOREQUEST + + # @@protoc_insertion_point(class_scope:protobuf_unittest.CustomOptionFooRequest) + +class CustomOptionFooResponse(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _CUSTOMOPTIONFOORESPONSE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.CustomOptionFooResponse) + +class CustomOptionFooClientMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _CUSTOMOPTIONFOOCLIENTMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.CustomOptionFooClientMessage) + +class CustomOptionFooServerMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _CUSTOMOPTIONFOOSERVERMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.CustomOptionFooServerMessage) + +class DummyMessageContainingEnum(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _DUMMYMESSAGECONTAININGENUM + + # @@protoc_insertion_point(class_scope:protobuf_unittest.DummyMessageContainingEnum) + +class DummyMessageInvalidAsOptionType(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _DUMMYMESSAGEINVALIDASOPTIONTYPE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.DummyMessageInvalidAsOptionType) + +class CustomOptionMinIntegerValues(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _CUSTOMOPTIONMININTEGERVALUES + + # @@protoc_insertion_point(class_scope:protobuf_unittest.CustomOptionMinIntegerValues) + +class CustomOptionMaxIntegerValues(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _CUSTOMOPTIONMAXINTEGERVALUES + + # @@protoc_insertion_point(class_scope:protobuf_unittest.CustomOptionMaxIntegerValues) + +class CustomOptionOtherValues(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _CUSTOMOPTIONOTHERVALUES + + # @@protoc_insertion_point(class_scope:protobuf_unittest.CustomOptionOtherValues) + +class SettingRealsFromPositiveInts(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _SETTINGREALSFROMPOSITIVEINTS + + # @@protoc_insertion_point(class_scope:protobuf_unittest.SettingRealsFromPositiveInts) + +class SettingRealsFromNegativeInts(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _SETTINGREALSFROMNEGATIVEINTS + + # @@protoc_insertion_point(class_scope:protobuf_unittest.SettingRealsFromNegativeInts) + +class ComplexOptionType1(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _COMPLEXOPTIONTYPE1 + + # @@protoc_insertion_point(class_scope:protobuf_unittest.ComplexOptionType1) + +class ComplexOptionType2(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class ComplexOptionType4(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _COMPLEXOPTIONTYPE2_COMPLEXOPTIONTYPE4 + + # @@protoc_insertion_point(class_scope:protobuf_unittest.ComplexOptionType2.ComplexOptionType4) + DESCRIPTOR = _COMPLEXOPTIONTYPE2 + + # @@protoc_insertion_point(class_scope:protobuf_unittest.ComplexOptionType2) + +class ComplexOptionType3(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class ComplexOptionType5(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _COMPLEXOPTIONTYPE3_COMPLEXOPTIONTYPE5 + + # @@protoc_insertion_point(class_scope:protobuf_unittest.ComplexOptionType3.ComplexOptionType5) + DESCRIPTOR = _COMPLEXOPTIONTYPE3 + + # @@protoc_insertion_point(class_scope:protobuf_unittest.ComplexOptionType3) + +class ComplexOpt6(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _COMPLEXOPT6 + + # @@protoc_insertion_point(class_scope:protobuf_unittest.ComplexOpt6) + +class VariousComplexOptions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _VARIOUSCOMPLEXOPTIONS + + # @@protoc_insertion_point(class_scope:protobuf_unittest.VariousComplexOptions) + +class AggregateMessageSet(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _AGGREGATEMESSAGESET + + # @@protoc_insertion_point(class_scope:protobuf_unittest.AggregateMessageSet) + +class AggregateMessageSetElement(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _AGGREGATEMESSAGESETELEMENT + + # @@protoc_insertion_point(class_scope:protobuf_unittest.AggregateMessageSetElement) + +class Aggregate(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _AGGREGATE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.Aggregate) + +class AggregateMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _AGGREGATEMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.AggregateMessage) + +class NestedOptionType(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class NestedMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _NESTEDOPTIONTYPE_NESTEDMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.NestedOptionType.NestedMessage) + DESCRIPTOR = _NESTEDOPTIONTYPE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.NestedOptionType) + +google.protobuf.descriptor_pb2.FileOptions.RegisterExtension(file_opt1) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(message_opt1) +google.protobuf.descriptor_pb2.FieldOptions.RegisterExtension(field_opt1) +google.protobuf.descriptor_pb2.FieldOptions.RegisterExtension(field_opt2) +google.protobuf.descriptor_pb2.EnumOptions.RegisterExtension(enum_opt1) +google.protobuf.descriptor_pb2.EnumValueOptions.RegisterExtension(enum_value_opt1) +google.protobuf.descriptor_pb2.ServiceOptions.RegisterExtension(service_opt1) +method_opt1.enum_type = _METHODOPT1 +google.protobuf.descriptor_pb2.MethodOptions.RegisterExtension(method_opt1) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(bool_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(int32_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(int64_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(uint32_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(uint64_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(sint32_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(sint64_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(fixed32_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(fixed64_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(sfixed32_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(sfixed64_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(float_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(double_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(string_opt) +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(bytes_opt) +enum_opt.enum_type = _DUMMYMESSAGECONTAININGENUM_TESTENUMTYPE +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(enum_opt) +message_type_opt.message_type = _DUMMYMESSAGEINVALIDASOPTIONTYPE +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(message_type_opt) +ComplexOptionType1.RegisterExtension(quux) +corge.message_type = _COMPLEXOPTIONTYPE3 +ComplexOptionType1.RegisterExtension(corge) +ComplexOptionType2.RegisterExtension(grault) +garply.message_type = _COMPLEXOPTIONTYPE1 +ComplexOptionType2.RegisterExtension(garply) +complex_opt1.message_type = _COMPLEXOPTIONTYPE1 +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(complex_opt1) +complex_opt2.message_type = _COMPLEXOPTIONTYPE2 +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(complex_opt2) +complex_opt3.message_type = _COMPLEXOPTIONTYPE3 +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(complex_opt3) +complexopt6.message_type = _COMPLEXOPT6 +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(complexopt6) +fileopt.message_type = _AGGREGATE +google.protobuf.descriptor_pb2.FileOptions.RegisterExtension(fileopt) +msgopt.message_type = _AGGREGATE +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(msgopt) +fieldopt.message_type = _AGGREGATE +google.protobuf.descriptor_pb2.FieldOptions.RegisterExtension(fieldopt) +enumopt.message_type = _AGGREGATE +google.protobuf.descriptor_pb2.EnumOptions.RegisterExtension(enumopt) +enumvalopt.message_type = _AGGREGATE +google.protobuf.descriptor_pb2.EnumValueOptions.RegisterExtension(enumvalopt) +serviceopt.message_type = _AGGREGATE +google.protobuf.descriptor_pb2.ServiceOptions.RegisterExtension(serviceopt) +methodopt.message_type = _AGGREGATE +google.protobuf.descriptor_pb2.MethodOptions.RegisterExtension(methodopt) +_COMPLEXOPTIONTYPE2_COMPLEXOPTIONTYPE4.extensions_by_name['complex_opt4'].message_type = _COMPLEXOPTIONTYPE2_COMPLEXOPTIONTYPE4 +google.protobuf.descriptor_pb2.MessageOptions.RegisterExtension(_COMPLEXOPTIONTYPE2_COMPLEXOPTIONTYPE4.extensions_by_name['complex_opt4']) +_AGGREGATEMESSAGESETELEMENT.extensions_by_name['message_set_extension'].message_type = _AGGREGATEMESSAGESETELEMENT +AggregateMessageSet.RegisterExtension(_AGGREGATEMESSAGESETELEMENT.extensions_by_name['message_set_extension']) +_AGGREGATE.extensions_by_name['nested'].message_type = _AGGREGATE +google.protobuf.descriptor_pb2.FileOptions.RegisterExtension(_AGGREGATE.extensions_by_name['nested']) +google.protobuf.descriptor_pb2.FileOptions.RegisterExtension(_NESTEDOPTIONTYPE.extensions_by_name['nested_extension']) + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), '\200\001\001\210\001\001\220\001\001\360\350\301\035\352\255\300\345$\372\354\205;p\010d\022\016FileAnnotation\032\026\022\024NestedFileAnnotation\"\036\372\354\205;\031\022\027FileExtensionAnnotation*$\013\020\366\353\256\007\032\033\n\031EmbeddedMessageSetElement\014') +_AGGREGATEENUM.has_options = True +_AGGREGATEENUM._options = _descriptor._ParseOptions(descriptor_pb2.EnumOptions(), '\222\225\210;\020\022\016EnumAnnotation') +_AGGREGATEENUM.values_by_name["VALUE"].has_options = True +_AGGREGATEENUM.values_by_name["VALUE"]._options = _descriptor._ParseOptions(descriptor_pb2.EnumValueOptions(), '\312\374\211;\025\022\023EnumValueAnnotation') +_TESTMESSAGEWITHCUSTOMOPTIONS_ANENUM.has_options = True +_TESTMESSAGEWITHCUSTOMOPTIONS_ANENUM._options = _descriptor._ParseOptions(descriptor_pb2.EnumOptions(), '\305\366\311\035\353\374\377\377') +_TESTMESSAGEWITHCUSTOMOPTIONS_ANENUM.values_by_name["ANENUM_VAL2"].has_options = True +_TESTMESSAGEWITHCUSTOMOPTIONS_ANENUM.values_by_name["ANENUM_VAL2"]._options = _descriptor._ParseOptions(descriptor_pb2.EnumValueOptions(), '\260\206\372\005{') +_TESTMESSAGEWITHCUSTOMOPTIONS.fields_by_name['field1'].has_options = True +_TESTMESSAGEWITHCUSTOMOPTIONS.fields_by_name['field1']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001\301\340\303\035-\341u\n\002\000\000\000') +_TESTMESSAGEWITHCUSTOMOPTIONS.has_options = True +_TESTMESSAGEWITHCUSTOMOPTIONS._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\010\000\340\351\302\035\310\377\377\377\377\377\377\377\377\001') +_CUSTOMOPTIONMININTEGERVALUES.has_options = True +_CUSTOMOPTIONMININTEGERVALUES._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\320\336\262\035\000\350\306\262\035\200\200\200\200\370\377\377\377\377\001\260\274\262\035\200\200\200\200\200\200\200\200\200\001\200\223\262\035\000\370\365\260\035\000\200\304\260\035\377\377\377\377\017\370\227\260\035\377\377\377\377\377\377\377\377\377\001\235\365\257\035\000\000\000\000\221\356\257\035\000\000\000\000\000\000\000\000\255\215\257\035\000\000\000\200\231\326\250\035\000\000\000\000\000\000\000\200') +_CUSTOMOPTIONMAXINTEGERVALUES.has_options = True +_CUSTOMOPTIONMAXINTEGERVALUES._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\320\336\262\035\001\350\306\262\035\377\377\377\377\007\260\274\262\035\377\377\377\377\377\377\377\377\177\200\223\262\035\377\377\377\377\017\370\365\260\035\377\377\377\377\377\377\377\377\377\001\200\304\260\035\376\377\377\377\017\370\227\260\035\376\377\377\377\377\377\377\377\377\001\235\365\257\035\377\377\377\377\221\356\257\035\377\377\377\377\377\377\377\377\255\215\257\035\377\377\377\177\231\326\250\035\377\377\377\377\377\377\377\177') +_CUSTOMOPTIONOTHERVALUES.has_options = True +_CUSTOMOPTIONOTHERVALUES._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\350\306\262\035\234\377\377\377\377\377\377\377\377\001\365\337\243\035\347\207EA\351\334\242\035\373Y\214B\312\300\363?\252\334\242\035\016Hello, \"World\"\262\331\242\035\013Hello\000World\210\331\242\035\351\377\377\377\377\377\377\377\377\001') +_SETTINGREALSFROMPOSITIVEINTS.has_options = True +_SETTINGREALSFROMPOSITIVEINTS._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\365\337\243\035\000\000@A\351\334\242\035\000\000\000\000\000@c@') +_SETTINGREALSFROMNEGATIVEINTS.has_options = True +_SETTINGREALSFROMNEGATIVEINTS._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\365\337\243\035\000\000@\301\351\334\242\035\000\000\000\000\000@c\300') +_VARIOUSCOMPLEXOPTIONS.has_options = True +_VARIOUSCOMPLEXOPTIONS._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\242\342\225\035\002\010*\242\342\225\035\006\330\205\236\035\304\002\242\342\225\035\010\222\365\235\035\003\010\354\006\252\375\220\035\003\020\333\007\252\375\220\035\006\370\346\227\035\216\005\252\375\220\035\005\n\003\010\347\005\252\375\220\035\010\n\006\330\205\236\035\317\017\252\375\220\035\n\n\010\222\365\235\035\003\010\330\017\252\375\220\035\010\302\254\227\035\003\010\345\005\252\375\220\035\013\302\254\227\035\006\330\205\236\035\316\017\252\375\220\035\r\302\254\227\035\010\222\365\235\035\003\010\311\020\322\250\217\035\003\010\263\017\252\375\220\035\005\032\003\010\301\002\372\336\220\035\002\010\t\372\336\220\035\004\023\030\026\024\343\334\374\034\370\375\373\034\030\344\334\374\034') +_AGGREGATEMESSAGESET.has_options = True +_AGGREGATEMESSAGESET._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\010\001') +_AGGREGATEMESSAGE.fields_by_name['fieldname'].has_options = True +_AGGREGATEMESSAGE.fields_by_name['fieldname']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\362\241\207;\021\022\017FieldAnnotation') +_AGGREGATEMESSAGE.has_options = True +_AGGREGATEMESSAGE._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\302\321\206;\025\010e\022\021MessageAnnotation') +_NESTEDOPTIONTYPE_NESTEDMESSAGE.fields_by_name['nested_field'].has_options = True +_NESTEDOPTIONTYPE_NESTEDMESSAGE.fields_by_name['nested_field']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\301\340\303\035\352\003\000\000\000\000\000\000') +_NESTEDOPTIONTYPE_NESTEDMESSAGE.has_options = True +_NESTEDOPTIONTYPE_NESTEDMESSAGE._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\340\351\302\035\351\007') +_NESTEDOPTIONTYPE_NESTEDENUM.has_options = True +_NESTEDOPTIONTYPE_NESTEDENUM._options = _descriptor._ParseOptions(descriptor_pb2.EnumOptions(), '\305\366\311\035\353\003\000\000') +_NESTEDOPTIONTYPE_NESTEDENUM.values_by_name["NESTED_ENUM_VALUE"].has_options = True +_NESTEDOPTIONTYPE_NESTEDENUM.values_by_name["NESTED_ENUM_VALUE"]._options = _descriptor._ParseOptions(descriptor_pb2.EnumValueOptions(), '\260\206\372\005\354\007') +_NESTEDOPTIONTYPE.extensions_by_name['nested_extension'].has_options = True +_NESTEDOPTIONTYPE.extensions_by_name['nested_extension']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\310\213\312\035\355\007') + +_TESTSERVICEWITHCUSTOMOPTIONS = _descriptor.ServiceDescriptor( + name='TestServiceWithCustomOptions', + full_name='protobuf_unittest.TestServiceWithCustomOptions', + file=DESCRIPTOR, + index=0, + options=_descriptor._ParseOptions(descriptor_pb2.ServiceOptions(), '\220\262\213\036\323\333\200\313I'), + serialized_start=2705, + serialized_end=2847, + methods=[ + _descriptor.MethodDescriptor( + name='Foo', + full_name='protobuf_unittest.TestServiceWithCustomOptions.Foo', + index=0, + containing_service=None, + input_type=_CUSTOMOPTIONFOOREQUEST, + output_type=_CUSTOMOPTIONFOORESPONSE, + options=_descriptor._ParseOptions(descriptor_pb2.MethodOptions(), '\340\372\214\036\002'), + ), +]) + +class TestServiceWithCustomOptions(_service.Service): + __metaclass__ = service_reflection.GeneratedServiceType + DESCRIPTOR = _TESTSERVICEWITHCUSTOMOPTIONS +class TestServiceWithCustomOptions_Stub(TestServiceWithCustomOptions): + __metaclass__ = service_reflection.GeneratedServiceStubType + DESCRIPTOR = _TESTSERVICEWITHCUSTOMOPTIONS + + +_AGGREGATESERVICE = _descriptor.ServiceDescriptor( + name='AggregateService', + full_name='protobuf_unittest.AggregateService', + file=DESCRIPTOR, + index=1, + options=_descriptor._ParseOptions(descriptor_pb2.ServiceOptions(), '\312\373\216;\023\022\021ServiceAnnotation'), + serialized_start=2850, + serialized_end=3003, + methods=[ + _descriptor.MethodDescriptor( + name='Method', + full_name='protobuf_unittest.AggregateService.Method', + index=0, + containing_service=None, + input_type=_AGGREGATEMESSAGE, + output_type=_AGGREGATEMESSAGE, + options=_descriptor._ParseOptions(descriptor_pb2.MethodOptions(), '\312\310\226;\022\022\020MethodAnnotation'), + ), +]) + +class AggregateService(_service.Service): + __metaclass__ = service_reflection.GeneratedServiceType + DESCRIPTOR = _AGGREGATESERVICE +class AggregateService_Stub(AggregateService): + __metaclass__ = service_reflection.GeneratedServiceStubType + DESCRIPTOR = _AGGREGATESERVICE + +# @@protoc_insertion_point(module_scope) diff --git a/code/push/google/protobuf/unittest_import_pb2.py b/code/push/google/protobuf/unittest_import_pb2.py new file mode 100644 index 0000000..8a9dc3d --- /dev/null +++ b/code/push/google/protobuf/unittest_import_pb2.py @@ -0,0 +1,91 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/unittest_import.proto + +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + + +import google.protobuf.unittest_import_public_pb2 + +from google.protobuf.unittest_import_public_pb2 import * + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/unittest_import.proto', + package='protobuf_unittest_import', + serialized_pb='\n%google/protobuf/unittest_import.proto\x12\x18protobuf_unittest_import\x1a,google/protobuf/unittest_import_public.proto\"\x1a\n\rImportMessage\x12\t\n\x01\x64\x18\x01 \x01(\x05*<\n\nImportEnum\x12\x0e\n\nIMPORT_FOO\x10\x07\x12\x0e\n\nIMPORT_BAR\x10\x08\x12\x0e\n\nIMPORT_BAZ\x10\tB\x1c\n\x18\x63om.google.protobuf.testH\x01P\x00') + +_IMPORTENUM = _descriptor.EnumDescriptor( + name='ImportEnum', + full_name='protobuf_unittest_import.ImportEnum', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='IMPORT_FOO', index=0, number=7, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='IMPORT_BAR', index=1, number=8, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='IMPORT_BAZ', index=2, number=9, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=141, + serialized_end=201, +) + +ImportEnum = enum_type_wrapper.EnumTypeWrapper(_IMPORTENUM) +IMPORT_FOO = 7 +IMPORT_BAR = 8 +IMPORT_BAZ = 9 + + + +_IMPORTMESSAGE = _descriptor.Descriptor( + name='ImportMessage', + full_name='protobuf_unittest_import.ImportMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='d', full_name='protobuf_unittest_import.ImportMessage.d', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=113, + serialized_end=139, +) + +DESCRIPTOR.message_types_by_name['ImportMessage'] = _IMPORTMESSAGE + +class ImportMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _IMPORTMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest_import.ImportMessage) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), '\n\030com.google.protobuf.testH\001') +# @@protoc_insertion_point(module_scope) diff --git a/code/push/google/protobuf/unittest_import_public_pb2.py b/code/push/google/protobuf/unittest_import_public_pb2.py new file mode 100644 index 0000000..251116b --- /dev/null +++ b/code/push/google/protobuf/unittest_import_public_pb2.py @@ -0,0 +1,59 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/unittest_import_public.proto + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/unittest_import_public.proto', + package='protobuf_unittest_import', + serialized_pb='\n,google/protobuf/unittest_import_public.proto\x12\x18protobuf_unittest_import\" \n\x13PublicImportMessage\x12\t\n\x01\x65\x18\x01 \x01(\x05\x42\x1a\n\x18\x63om.google.protobuf.test') + + + + +_PUBLICIMPORTMESSAGE = _descriptor.Descriptor( + name='PublicImportMessage', + full_name='protobuf_unittest_import.PublicImportMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='e', full_name='protobuf_unittest_import.PublicImportMessage.e', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=74, + serialized_end=106, +) + +DESCRIPTOR.message_types_by_name['PublicImportMessage'] = _PUBLICIMPORTMESSAGE + +class PublicImportMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _PUBLICIMPORTMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest_import.PublicImportMessage) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), '\n\030com.google.protobuf.test') +# @@protoc_insertion_point(module_scope) diff --git a/code/push/google/protobuf/unittest_mset_pb2.py b/code/push/google/protobuf/unittest_mset_pb2.py new file mode 100644 index 0000000..a42b768 --- /dev/null +++ b/code/push/google/protobuf/unittest_mset_pb2.py @@ -0,0 +1,255 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/unittest_mset.proto + +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/unittest_mset.proto', + package='protobuf_unittest', + serialized_pb='\n#google/protobuf/unittest_mset.proto\x12\x11protobuf_unittest\"\x1e\n\x0eTestMessageSet*\x08\x08\x04\x10\xff\xff\xff\xff\x07:\x02\x08\x01\"Q\n\x17TestMessageSetContainer\x12\x36\n\x0bmessage_set\x18\x01 \x01(\x0b\x32!.protobuf_unittest.TestMessageSet\"\x96\x01\n\x18TestMessageSetExtension1\x12\t\n\x01i\x18\x0f \x01(\x05\x32o\n\x15message_set_extension\x12!.protobuf_unittest.TestMessageSet\x18\xb0\xa6^ \x01(\x0b\x32+.protobuf_unittest.TestMessageSetExtension1\"\x98\x01\n\x18TestMessageSetExtension2\x12\x0b\n\x03str\x18\x19 \x01(\t2o\n\x15message_set_extension\x12!.protobuf_unittest.TestMessageSet\x18\xf9\xbb^ \x01(\x0b\x32+.protobuf_unittest.TestMessageSetExtension2\"n\n\rRawMessageSet\x12\x33\n\x04item\x18\x01 \x03(\n2%.protobuf_unittest.RawMessageSet.Item\x1a(\n\x04Item\x12\x0f\n\x07type_id\x18\x02 \x02(\x05\x12\x0f\n\x07message\x18\x03 \x02(\x0c\x42\x02H\x01') + + + + +_TESTMESSAGESET = _descriptor.Descriptor( + name='TestMessageSet', + full_name='protobuf_unittest.TestMessageSet', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\010\001'), + is_extendable=True, + extension_ranges=[(4, 2147483647), ], + serialized_start=58, + serialized_end=88, +) + + +_TESTMESSAGESETCONTAINER = _descriptor.Descriptor( + name='TestMessageSetContainer', + full_name='protobuf_unittest.TestMessageSetContainer', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='message_set', full_name='protobuf_unittest.TestMessageSetContainer.message_set', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=90, + serialized_end=171, +) + + +_TESTMESSAGESETEXTENSION1 = _descriptor.Descriptor( + name='TestMessageSetExtension1', + full_name='protobuf_unittest.TestMessageSetExtension1', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='i', full_name='protobuf_unittest.TestMessageSetExtension1.i', index=0, + number=15, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + _descriptor.FieldDescriptor( + name='message_set_extension', full_name='protobuf_unittest.TestMessageSetExtension1.message_set_extension', index=0, + number=1545008, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None), + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=174, + serialized_end=324, +) + + +_TESTMESSAGESETEXTENSION2 = _descriptor.Descriptor( + name='TestMessageSetExtension2', + full_name='protobuf_unittest.TestMessageSetExtension2', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='str', full_name='protobuf_unittest.TestMessageSetExtension2.str', index=0, + number=25, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + _descriptor.FieldDescriptor( + name='message_set_extension', full_name='protobuf_unittest.TestMessageSetExtension2.message_set_extension', index=0, + number=1547769, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None), + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=327, + serialized_end=479, +) + + +_RAWMESSAGESET_ITEM = _descriptor.Descriptor( + name='Item', + full_name='protobuf_unittest.RawMessageSet.Item', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='type_id', full_name='protobuf_unittest.RawMessageSet.Item.type_id', index=0, + number=2, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='message', full_name='protobuf_unittest.RawMessageSet.Item.message', index=1, + number=3, type=12, cpp_type=9, label=2, + has_default_value=False, default_value="", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=551, + serialized_end=591, +) + +_RAWMESSAGESET = _descriptor.Descriptor( + name='RawMessageSet', + full_name='protobuf_unittest.RawMessageSet', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='item', full_name='protobuf_unittest.RawMessageSet.item', index=0, + number=1, type=10, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_RAWMESSAGESET_ITEM, ], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=481, + serialized_end=591, +) + +_TESTMESSAGESETCONTAINER.fields_by_name['message_set'].message_type = _TESTMESSAGESET +_RAWMESSAGESET_ITEM.containing_type = _RAWMESSAGESET; +_RAWMESSAGESET.fields_by_name['item'].message_type = _RAWMESSAGESET_ITEM +DESCRIPTOR.message_types_by_name['TestMessageSet'] = _TESTMESSAGESET +DESCRIPTOR.message_types_by_name['TestMessageSetContainer'] = _TESTMESSAGESETCONTAINER +DESCRIPTOR.message_types_by_name['TestMessageSetExtension1'] = _TESTMESSAGESETEXTENSION1 +DESCRIPTOR.message_types_by_name['TestMessageSetExtension2'] = _TESTMESSAGESETEXTENSION2 +DESCRIPTOR.message_types_by_name['RawMessageSet'] = _RAWMESSAGESET + +class TestMessageSet(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTMESSAGESET + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestMessageSet) + +class TestMessageSetContainer(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTMESSAGESETCONTAINER + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestMessageSetContainer) + +class TestMessageSetExtension1(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTMESSAGESETEXTENSION1 + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestMessageSetExtension1) + +class TestMessageSetExtension2(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTMESSAGESETEXTENSION2 + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestMessageSetExtension2) + +class RawMessageSet(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class Item(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _RAWMESSAGESET_ITEM + + # @@protoc_insertion_point(class_scope:protobuf_unittest.RawMessageSet.Item) + DESCRIPTOR = _RAWMESSAGESET + + # @@protoc_insertion_point(class_scope:protobuf_unittest.RawMessageSet) + +_TESTMESSAGESETEXTENSION1.extensions_by_name['message_set_extension'].message_type = _TESTMESSAGESETEXTENSION1 +TestMessageSet.RegisterExtension(_TESTMESSAGESETEXTENSION1.extensions_by_name['message_set_extension']) +_TESTMESSAGESETEXTENSION2.extensions_by_name['message_set_extension'].message_type = _TESTMESSAGESETEXTENSION2 +TestMessageSet.RegisterExtension(_TESTMESSAGESETEXTENSION2.extensions_by_name['message_set_extension']) + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), 'H\001') +_TESTMESSAGESET.has_options = True +_TESTMESSAGESET._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), '\010\001') +# @@protoc_insertion_point(module_scope) diff --git a/code/push/google/protobuf/unittest_no_generic_services_pb2.py b/code/push/google/protobuf/unittest_no_generic_services_pb2.py new file mode 100644 index 0000000..baa7189 --- /dev/null +++ b/code/push/google/protobuf/unittest_no_generic_services_pb2.py @@ -0,0 +1,86 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/unittest_no_generic_services.proto + +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + + + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/unittest_no_generic_services.proto', + package='google.protobuf.no_generic_services_test', + serialized_pb='\n2google/protobuf/unittest_no_generic_services.proto\x12(google.protobuf.no_generic_services_test\"#\n\x0bTestMessage\x12\t\n\x01\x61\x18\x01 \x01(\x05*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02*\x13\n\x08TestEnum\x12\x07\n\x03\x46OO\x10\x01\x32\x82\x01\n\x0bTestService\x12s\n\x03\x46oo\x12\x35.google.protobuf.no_generic_services_test.TestMessage\x1a\x35.google.protobuf.no_generic_services_test.TestMessage:N\n\x0etest_extension\x12\x35.google.protobuf.no_generic_services_test.TestMessage\x18\xe8\x07 \x01(\x05') + +_TESTENUM = _descriptor.EnumDescriptor( + name='TestEnum', + full_name='google.protobuf.no_generic_services_test.TestEnum', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='FOO', index=0, number=1, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=133, + serialized_end=152, +) + +TestEnum = enum_type_wrapper.EnumTypeWrapper(_TESTENUM) +FOO = 1 + +TEST_EXTENSION_FIELD_NUMBER = 1000 +test_extension = _descriptor.FieldDescriptor( + name='test_extension', full_name='google.protobuf.no_generic_services_test.test_extension', index=0, + number=1000, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) + + +_TESTMESSAGE = _descriptor.Descriptor( + name='TestMessage', + full_name='google.protobuf.no_generic_services_test.TestMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='google.protobuf.no_generic_services_test.TestMessage.a', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + serialized_start=96, + serialized_end=131, +) + +DESCRIPTOR.message_types_by_name['TestMessage'] = _TESTMESSAGE + +class TestMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTMESSAGE + + # @@protoc_insertion_point(class_scope:google.protobuf.no_generic_services_test.TestMessage) + +TestMessage.RegisterExtension(test_extension) + +# @@protoc_insertion_point(module_scope) diff --git a/code/push/google/protobuf/unittest_pb2.py b/code/push/google/protobuf/unittest_pb2.py new file mode 100644 index 0000000..b17eab9 --- /dev/null +++ b/code/push/google/protobuf/unittest_pb2.py @@ -0,0 +1,4440 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/protobuf/unittest.proto + +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import service as _service +from google.protobuf import service_reflection +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + + +import google.protobuf.unittest_import_pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/protobuf/unittest.proto', + package='protobuf_unittest', + serialized_pb='\n\x1egoogle/protobuf/unittest.proto\x12\x11protobuf_unittest\x1a%google/protobuf/unittest_import.proto\"\xb6\x17\n\x0cTestAllTypes\x12\x16\n\x0eoptional_int32\x18\x01 \x01(\x05\x12\x16\n\x0eoptional_int64\x18\x02 \x01(\x03\x12\x17\n\x0foptional_uint32\x18\x03 \x01(\r\x12\x17\n\x0foptional_uint64\x18\x04 \x01(\x04\x12\x17\n\x0foptional_sint32\x18\x05 \x01(\x11\x12\x17\n\x0foptional_sint64\x18\x06 \x01(\x12\x12\x18\n\x10optional_fixed32\x18\x07 \x01(\x07\x12\x18\n\x10optional_fixed64\x18\x08 \x01(\x06\x12\x19\n\x11optional_sfixed32\x18\t \x01(\x0f\x12\x19\n\x11optional_sfixed64\x18\n \x01(\x10\x12\x16\n\x0eoptional_float\x18\x0b \x01(\x02\x12\x17\n\x0foptional_double\x18\x0c \x01(\x01\x12\x15\n\roptional_bool\x18\r \x01(\x08\x12\x17\n\x0foptional_string\x18\x0e \x01(\t\x12\x16\n\x0eoptional_bytes\x18\x0f \x01(\x0c\x12\x44\n\roptionalgroup\x18\x10 \x01(\n2-.protobuf_unittest.TestAllTypes.OptionalGroup\x12N\n\x17optional_nested_message\x18\x12 \x01(\x0b\x32-.protobuf_unittest.TestAllTypes.NestedMessage\x12\x43\n\x18optional_foreign_message\x18\x13 \x01(\x0b\x32!.protobuf_unittest.ForeignMessage\x12H\n\x17optional_import_message\x18\x14 \x01(\x0b\x32\'.protobuf_unittest_import.ImportMessage\x12H\n\x14optional_nested_enum\x18\x15 \x01(\x0e\x32*.protobuf_unittest.TestAllTypes.NestedEnum\x12=\n\x15optional_foreign_enum\x18\x16 \x01(\x0e\x32\x1e.protobuf_unittest.ForeignEnum\x12\x42\n\x14optional_import_enum\x18\x17 \x01(\x0e\x32$.protobuf_unittest_import.ImportEnum\x12!\n\x15optional_string_piece\x18\x18 \x01(\tB\x02\x08\x02\x12\x19\n\roptional_cord\x18\x19 \x01(\tB\x02\x08\x01\x12U\n\x1eoptional_public_import_message\x18\x1a \x01(\x0b\x32-.protobuf_unittest_import.PublicImportMessage\x12P\n\x15optional_lazy_message\x18\x1b \x01(\x0b\x32-.protobuf_unittest.TestAllTypes.NestedMessageB\x02(\x01\x12\x16\n\x0erepeated_int32\x18\x1f \x03(\x05\x12\x16\n\x0erepeated_int64\x18 \x03(\x03\x12\x17\n\x0frepeated_uint32\x18! \x03(\r\x12\x17\n\x0frepeated_uint64\x18\" \x03(\x04\x12\x17\n\x0frepeated_sint32\x18# \x03(\x11\x12\x17\n\x0frepeated_sint64\x18$ \x03(\x12\x12\x18\n\x10repeated_fixed32\x18% \x03(\x07\x12\x18\n\x10repeated_fixed64\x18& \x03(\x06\x12\x19\n\x11repeated_sfixed32\x18\' \x03(\x0f\x12\x19\n\x11repeated_sfixed64\x18( \x03(\x10\x12\x16\n\x0erepeated_float\x18) \x03(\x02\x12\x17\n\x0frepeated_double\x18* \x03(\x01\x12\x15\n\rrepeated_bool\x18+ \x03(\x08\x12\x17\n\x0frepeated_string\x18, \x03(\t\x12\x16\n\x0erepeated_bytes\x18- \x03(\x0c\x12\x44\n\rrepeatedgroup\x18. \x03(\n2-.protobuf_unittest.TestAllTypes.RepeatedGroup\x12N\n\x17repeated_nested_message\x18\x30 \x03(\x0b\x32-.protobuf_unittest.TestAllTypes.NestedMessage\x12\x43\n\x18repeated_foreign_message\x18\x31 \x03(\x0b\x32!.protobuf_unittest.ForeignMessage\x12H\n\x17repeated_import_message\x18\x32 \x03(\x0b\x32\'.protobuf_unittest_import.ImportMessage\x12H\n\x14repeated_nested_enum\x18\x33 \x03(\x0e\x32*.protobuf_unittest.TestAllTypes.NestedEnum\x12=\n\x15repeated_foreign_enum\x18\x34 \x03(\x0e\x32\x1e.protobuf_unittest.ForeignEnum\x12\x42\n\x14repeated_import_enum\x18\x35 \x03(\x0e\x32$.protobuf_unittest_import.ImportEnum\x12!\n\x15repeated_string_piece\x18\x36 \x03(\tB\x02\x08\x02\x12\x19\n\rrepeated_cord\x18\x37 \x03(\tB\x02\x08\x01\x12P\n\x15repeated_lazy_message\x18\x39 \x03(\x0b\x32-.protobuf_unittest.TestAllTypes.NestedMessageB\x02(\x01\x12\x19\n\rdefault_int32\x18= \x01(\x05:\x02\x34\x31\x12\x19\n\rdefault_int64\x18> \x01(\x03:\x02\x34\x32\x12\x1a\n\x0e\x64\x65\x66\x61ult_uint32\x18? \x01(\r:\x02\x34\x33\x12\x1a\n\x0e\x64\x65\x66\x61ult_uint64\x18@ \x01(\x04:\x02\x34\x34\x12\x1b\n\x0e\x64\x65\x66\x61ult_sint32\x18\x41 \x01(\x11:\x03-45\x12\x1a\n\x0e\x64\x65\x66\x61ult_sint64\x18\x42 \x01(\x12:\x02\x34\x36\x12\x1b\n\x0f\x64\x65\x66\x61ult_fixed32\x18\x43 \x01(\x07:\x02\x34\x37\x12\x1b\n\x0f\x64\x65\x66\x61ult_fixed64\x18\x44 \x01(\x06:\x02\x34\x38\x12\x1c\n\x10\x64\x65\x66\x61ult_sfixed32\x18\x45 \x01(\x0f:\x02\x34\x39\x12\x1d\n\x10\x64\x65\x66\x61ult_sfixed64\x18\x46 \x01(\x10:\x03-50\x12\x1b\n\rdefault_float\x18G \x01(\x02:\x04\x35\x31.5\x12\x1d\n\x0e\x64\x65\x66\x61ult_double\x18H \x01(\x01:\x05\x35\x32\x30\x30\x30\x12\x1a\n\x0c\x64\x65\x66\x61ult_bool\x18I \x01(\x08:\x04true\x12\x1d\n\x0e\x64\x65\x66\x61ult_string\x18J \x01(\t:\x05hello\x12\x1c\n\rdefault_bytes\x18K \x01(\x0c:\x05world\x12L\n\x13\x64\x65\x66\x61ult_nested_enum\x18Q \x01(\x0e\x32*.protobuf_unittest.TestAllTypes.NestedEnum:\x03\x42\x41R\x12I\n\x14\x64\x65\x66\x61ult_foreign_enum\x18R \x01(\x0e\x32\x1e.protobuf_unittest.ForeignEnum:\x0b\x46OREIGN_BAR\x12M\n\x13\x64\x65\x66\x61ult_import_enum\x18S \x01(\x0e\x32$.protobuf_unittest_import.ImportEnum:\nIMPORT_BAR\x12%\n\x14\x64\x65\x66\x61ult_string_piece\x18T \x01(\t:\x03\x61\x62\x63\x42\x02\x08\x02\x12\x1d\n\x0c\x64\x65\x66\x61ult_cord\x18U \x01(\t:\x03\x31\x32\x33\x42\x02\x08\x01\x1a\x1b\n\rNestedMessage\x12\n\n\x02\x62\x62\x18\x01 \x01(\x05\x1a\x1a\n\rOptionalGroup\x12\t\n\x01\x61\x18\x11 \x01(\x05\x1a\x1a\n\rRepeatedGroup\x12\t\n\x01\x61\x18/ \x01(\x05\"\'\n\nNestedEnum\x12\x07\n\x03\x46OO\x10\x01\x12\x07\n\x03\x42\x41R\x10\x02\x12\x07\n\x03\x42\x41Z\x10\x03\"4\n\x14TestDeprecatedFields\x12\x1c\n\x10\x64\x65precated_int32\x18\x01 \x01(\x05\x42\x02\x18\x01\"\x1b\n\x0e\x46oreignMessage\x12\t\n\x01\x63\x18\x01 \x01(\x05\"\x1d\n\x11TestAllExtensions*\x08\x08\x01\x10\x80\x80\x80\x80\x02\"$\n\x17OptionalGroup_extension\x12\t\n\x01\x61\x18\x11 \x01(\x05\"$\n\x17RepeatedGroup_extension\x12\t\n\x01\x61\x18/ \x01(\x05\"P\n\x13TestNestedExtension29\n\x04test\x12$.protobuf_unittest.TestAllExtensions\x18\xea\x07 \x01(\t:\x04test\"\xd5\x05\n\x0cTestRequired\x12\t\n\x01\x61\x18\x01 \x02(\x05\x12\x0e\n\x06\x64ummy2\x18\x02 \x01(\x05\x12\t\n\x01\x62\x18\x03 \x02(\x05\x12\x0e\n\x06\x64ummy4\x18\x04 \x01(\x05\x12\x0e\n\x06\x64ummy5\x18\x05 \x01(\x05\x12\x0e\n\x06\x64ummy6\x18\x06 \x01(\x05\x12\x0e\n\x06\x64ummy7\x18\x07 \x01(\x05\x12\x0e\n\x06\x64ummy8\x18\x08 \x01(\x05\x12\x0e\n\x06\x64ummy9\x18\t \x01(\x05\x12\x0f\n\x07\x64ummy10\x18\n \x01(\x05\x12\x0f\n\x07\x64ummy11\x18\x0b \x01(\x05\x12\x0f\n\x07\x64ummy12\x18\x0c \x01(\x05\x12\x0f\n\x07\x64ummy13\x18\r \x01(\x05\x12\x0f\n\x07\x64ummy14\x18\x0e \x01(\x05\x12\x0f\n\x07\x64ummy15\x18\x0f \x01(\x05\x12\x0f\n\x07\x64ummy16\x18\x10 \x01(\x05\x12\x0f\n\x07\x64ummy17\x18\x11 \x01(\x05\x12\x0f\n\x07\x64ummy18\x18\x12 \x01(\x05\x12\x0f\n\x07\x64ummy19\x18\x13 \x01(\x05\x12\x0f\n\x07\x64ummy20\x18\x14 \x01(\x05\x12\x0f\n\x07\x64ummy21\x18\x15 \x01(\x05\x12\x0f\n\x07\x64ummy22\x18\x16 \x01(\x05\x12\x0f\n\x07\x64ummy23\x18\x17 \x01(\x05\x12\x0f\n\x07\x64ummy24\x18\x18 \x01(\x05\x12\x0f\n\x07\x64ummy25\x18\x19 \x01(\x05\x12\x0f\n\x07\x64ummy26\x18\x1a \x01(\x05\x12\x0f\n\x07\x64ummy27\x18\x1b \x01(\x05\x12\x0f\n\x07\x64ummy28\x18\x1c \x01(\x05\x12\x0f\n\x07\x64ummy29\x18\x1d \x01(\x05\x12\x0f\n\x07\x64ummy30\x18\x1e \x01(\x05\x12\x0f\n\x07\x64ummy31\x18\x1f \x01(\x05\x12\x0f\n\x07\x64ummy32\x18 \x01(\x05\x12\t\n\x01\x63\x18! \x02(\x05\x32V\n\x06single\x12$.protobuf_unittest.TestAllExtensions\x18\xe8\x07 \x01(\x0b\x32\x1f.protobuf_unittest.TestRequired2U\n\x05multi\x12$.protobuf_unittest.TestAllExtensions\x18\xe9\x07 \x03(\x0b\x32\x1f.protobuf_unittest.TestRequired\"\x9a\x01\n\x13TestRequiredForeign\x12\x39\n\x10optional_message\x18\x01 \x01(\x0b\x32\x1f.protobuf_unittest.TestRequired\x12\x39\n\x10repeated_message\x18\x02 \x03(\x0b\x32\x1f.protobuf_unittest.TestRequired\x12\r\n\x05\x64ummy\x18\x03 \x01(\x05\"Z\n\x11TestForeignNested\x12\x45\n\x0e\x66oreign_nested\x18\x01 \x01(\x0b\x32-.protobuf_unittest.TestAllTypes.NestedMessage\"\x12\n\x10TestEmptyMessage\"*\n\x1eTestEmptyMessageWithExtensions*\x08\x08\x01\x10\x80\x80\x80\x80\x02\"7\n\x1bTestMultipleExtensionRanges*\x04\x08*\x10+*\x06\x08\xaf \x10\x94!*\n\x08\x80\x80\x04\x10\x80\x80\x80\x80\x02\"4\n\x18TestReallyLargeTagNumber\x12\t\n\x01\x61\x18\x01 \x01(\x05\x12\r\n\x02\x62\x62\x18\xff\xff\xff\x7f \x01(\x05\"U\n\x14TestRecursiveMessage\x12\x32\n\x01\x61\x18\x01 \x01(\x0b\x32\'.protobuf_unittest.TestRecursiveMessage\x12\t\n\x01i\x18\x02 \x01(\x05\"K\n\x14TestMutualRecursionA\x12\x33\n\x02\x62\x62\x18\x01 \x01(\x0b\x32\'.protobuf_unittest.TestMutualRecursionB\"b\n\x14TestMutualRecursionB\x12\x32\n\x01\x61\x18\x01 \x01(\x0b\x32\'.protobuf_unittest.TestMutualRecursionA\x12\x16\n\x0eoptional_int32\x18\x02 \x01(\x05\"\xb3\x01\n\x12TestDupFieldNumber\x12\t\n\x01\x61\x18\x01 \x01(\x05\x12\x36\n\x03\x66oo\x18\x02 \x01(\n2).protobuf_unittest.TestDupFieldNumber.Foo\x12\x36\n\x03\x62\x61r\x18\x03 \x01(\n2).protobuf_unittest.TestDupFieldNumber.Bar\x1a\x10\n\x03\x46oo\x12\t\n\x01\x61\x18\x01 \x01(\x05\x1a\x10\n\x03\x42\x61r\x12\t\n\x01\x61\x18\x01 \x01(\x05\"L\n\x10TestEagerMessage\x12\x38\n\x0bsub_message\x18\x01 \x01(\x0b\x32\x1f.protobuf_unittest.TestAllTypesB\x02(\x00\"K\n\x0fTestLazyMessage\x12\x38\n\x0bsub_message\x18\x01 \x01(\x0b\x32\x1f.protobuf_unittest.TestAllTypesB\x02(\x01\"\x80\x02\n\x18TestNestedMessageHasBits\x12Z\n\x17optional_nested_message\x18\x01 \x01(\x0b\x32\x39.protobuf_unittest.TestNestedMessageHasBits.NestedMessage\x1a\x87\x01\n\rNestedMessage\x12$\n\x1cnestedmessage_repeated_int32\x18\x01 \x03(\x05\x12P\n%nestedmessage_repeated_foreignmessage\x18\x02 \x03(\x0b\x32!.protobuf_unittest.ForeignMessage\"\xe5\x03\n\x17TestCamelCaseFieldNames\x12\x16\n\x0ePrimitiveField\x18\x01 \x01(\x05\x12\x13\n\x0bStringField\x18\x02 \x01(\t\x12\x31\n\tEnumField\x18\x03 \x01(\x0e\x32\x1e.protobuf_unittest.ForeignEnum\x12\x37\n\x0cMessageField\x18\x04 \x01(\x0b\x32!.protobuf_unittest.ForeignMessage\x12\x1c\n\x10StringPieceField\x18\x05 \x01(\tB\x02\x08\x02\x12\x15\n\tCordField\x18\x06 \x01(\tB\x02\x08\x01\x12\x1e\n\x16RepeatedPrimitiveField\x18\x07 \x03(\x05\x12\x1b\n\x13RepeatedStringField\x18\x08 \x03(\t\x12\x39\n\x11RepeatedEnumField\x18\t \x03(\x0e\x32\x1e.protobuf_unittest.ForeignEnum\x12?\n\x14RepeatedMessageField\x18\n \x03(\x0b\x32!.protobuf_unittest.ForeignMessage\x12$\n\x18RepeatedStringPieceField\x18\x0b \x03(\tB\x02\x08\x02\x12\x1d\n\x11RepeatedCordField\x18\x0c \x03(\tB\x02\x08\x01\"U\n\x12TestFieldOrderings\x12\x11\n\tmy_string\x18\x0b \x01(\t\x12\x0e\n\x06my_int\x18\x01 \x01(\x03\x12\x10\n\x08my_float\x18\x65 \x01(\x02*\x04\x08\x02\x10\x0b*\x04\x08\x0c\x10\x65\"\x8e\x07\n\x18TestExtremeDefaultValues\x12?\n\rescaped_bytes\x18\x01 \x01(\x0c:(\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\\'\\\"\\376\x12 \n\x0clarge_uint32\x18\x02 \x01(\r:\n4294967295\x12*\n\x0clarge_uint64\x18\x03 \x01(\x04:\x14\x31\x38\x34\x34\x36\x37\x34\x34\x30\x37\x33\x37\x30\x39\x35\x35\x31\x36\x31\x35\x12 \n\x0bsmall_int32\x18\x04 \x01(\x05:\x0b-2147483647\x12)\n\x0bsmall_int64\x18\x05 \x01(\x03:\x14-9223372036854775807\x12\'\n\x12really_small_int32\x18\x15 \x01(\x05:\x0b-2147483648\x12\x30\n\x12really_small_int64\x18\x16 \x01(\x03:\x14-9223372036854775808\x12\x18\n\x0butf8_string\x18\x06 \x01(\t:\x03\xe1\x88\xb4\x12\x15\n\nzero_float\x18\x07 \x01(\x02:\x01\x30\x12\x14\n\tone_float\x18\x08 \x01(\x02:\x01\x31\x12\x18\n\x0bsmall_float\x18\t \x01(\x02:\x03\x31.5\x12\x1e\n\x12negative_one_float\x18\n \x01(\x02:\x02-1\x12\x1c\n\x0enegative_float\x18\x0b \x01(\x02:\x04-1.5\x12\x1a\n\x0blarge_float\x18\x0c \x01(\x02:\x05\x32\x65+08\x12$\n\x14small_negative_float\x18\r \x01(\x02:\x06-8e-28\x12\x17\n\ninf_double\x18\x0e \x01(\x01:\x03inf\x12\x1c\n\x0eneg_inf_double\x18\x0f \x01(\x01:\x04-inf\x12\x17\n\nnan_double\x18\x10 \x01(\x01:\x03nan\x12\x16\n\tinf_float\x18\x11 \x01(\x02:\x03inf\x12\x1b\n\rneg_inf_float\x18\x12 \x01(\x02:\x04-inf\x12\x16\n\tnan_float\x18\x13 \x01(\x02:\x03nan\x12+\n\x0c\x63pp_trigraph\x18\x14 \x01(\t:\x15? ? ?? ?? ??? ??/ ??-\x12 \n\x10string_with_zero\x18\x17 \x01(\t:\x06hel\x00lo\x12\"\n\x0f\x62ytes_with_zero\x18\x18 \x01(\x0c:\twor\\000ld\x12(\n\x16string_piece_with_zero\x18\x19 \x01(\t:\x04\x61\x62\x00\x63\x42\x02\x08\x02\x12 \n\x0e\x63ord_with_zero\x18\x1a \x01(\t:\x04\x31\x32\x00\x33\x42\x02\x08\x01\"K\n\x11SparseEnumMessage\x12\x36\n\x0bsparse_enum\x18\x01 \x01(\x0e\x32!.protobuf_unittest.TestSparseEnum\"\x19\n\tOneString\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\t\"\x1a\n\nMoreString\x12\x0c\n\x04\x64\x61ta\x18\x01 \x03(\t\"\x18\n\x08OneBytes\x12\x0c\n\x04\x64\x61ta\x18\x01 \x01(\x0c\"\x19\n\tMoreBytes\x12\x0c\n\x04\x64\x61ta\x18\x01 \x03(\x0c\"\xaa\x03\n\x0fTestPackedTypes\x12\x18\n\x0cpacked_int32\x18Z \x03(\x05\x42\x02\x10\x01\x12\x18\n\x0cpacked_int64\x18[ \x03(\x03\x42\x02\x10\x01\x12\x19\n\rpacked_uint32\x18\\ \x03(\rB\x02\x10\x01\x12\x19\n\rpacked_uint64\x18] \x03(\x04\x42\x02\x10\x01\x12\x19\n\rpacked_sint32\x18^ \x03(\x11\x42\x02\x10\x01\x12\x19\n\rpacked_sint64\x18_ \x03(\x12\x42\x02\x10\x01\x12\x1a\n\x0epacked_fixed32\x18` \x03(\x07\x42\x02\x10\x01\x12\x1a\n\x0epacked_fixed64\x18\x61 \x03(\x06\x42\x02\x10\x01\x12\x1b\n\x0fpacked_sfixed32\x18\x62 \x03(\x0f\x42\x02\x10\x01\x12\x1b\n\x0fpacked_sfixed64\x18\x63 \x03(\x10\x42\x02\x10\x01\x12\x18\n\x0cpacked_float\x18\x64 \x03(\x02\x42\x02\x10\x01\x12\x19\n\rpacked_double\x18\x65 \x03(\x01\x42\x02\x10\x01\x12\x17\n\x0bpacked_bool\x18\x66 \x03(\x08\x42\x02\x10\x01\x12\x37\n\x0bpacked_enum\x18g \x03(\x0e\x32\x1e.protobuf_unittest.ForeignEnumB\x02\x10\x01\"\xc8\x03\n\x11TestUnpackedTypes\x12\x1a\n\x0eunpacked_int32\x18Z \x03(\x05\x42\x02\x10\x00\x12\x1a\n\x0eunpacked_int64\x18[ \x03(\x03\x42\x02\x10\x00\x12\x1b\n\x0funpacked_uint32\x18\\ \x03(\rB\x02\x10\x00\x12\x1b\n\x0funpacked_uint64\x18] \x03(\x04\x42\x02\x10\x00\x12\x1b\n\x0funpacked_sint32\x18^ \x03(\x11\x42\x02\x10\x00\x12\x1b\n\x0funpacked_sint64\x18_ \x03(\x12\x42\x02\x10\x00\x12\x1c\n\x10unpacked_fixed32\x18` \x03(\x07\x42\x02\x10\x00\x12\x1c\n\x10unpacked_fixed64\x18\x61 \x03(\x06\x42\x02\x10\x00\x12\x1d\n\x11unpacked_sfixed32\x18\x62 \x03(\x0f\x42\x02\x10\x00\x12\x1d\n\x11unpacked_sfixed64\x18\x63 \x03(\x10\x42\x02\x10\x00\x12\x1a\n\x0eunpacked_float\x18\x64 \x03(\x02\x42\x02\x10\x00\x12\x1b\n\x0funpacked_double\x18\x65 \x03(\x01\x42\x02\x10\x00\x12\x19\n\runpacked_bool\x18\x66 \x03(\x08\x42\x02\x10\x00\x12\x39\n\runpacked_enum\x18g \x03(\x0e\x32\x1e.protobuf_unittest.ForeignEnumB\x02\x10\x00\" \n\x14TestPackedExtensions*\x08\x08\x01\x10\x80\x80\x80\x80\x02\"\x99\x04\n\x15TestDynamicExtensions\x12\x19\n\x10scalar_extension\x18\xd0\x0f \x01(\x07\x12\x37\n\x0e\x65num_extension\x18\xd1\x0f \x01(\x0e\x32\x1e.protobuf_unittest.ForeignEnum\x12Y\n\x16\x64ynamic_enum_extension\x18\xd2\x0f \x01(\x0e\x32\x38.protobuf_unittest.TestDynamicExtensions.DynamicEnumType\x12=\n\x11message_extension\x18\xd3\x0f \x01(\x0b\x32!.protobuf_unittest.ForeignMessage\x12_\n\x19\x64ynamic_message_extension\x18\xd4\x0f \x01(\x0b\x32;.protobuf_unittest.TestDynamicExtensions.DynamicMessageType\x12\x1b\n\x12repeated_extension\x18\xd5\x0f \x03(\t\x12\x1d\n\x10packed_extension\x18\xd6\x0f \x03(\x11\x42\x02\x10\x01\x1a,\n\x12\x44ynamicMessageType\x12\x16\n\rdynamic_field\x18\xb4\x10 \x01(\x05\"G\n\x0f\x44ynamicEnumType\x12\x10\n\x0b\x44YNAMIC_FOO\x10\x98\x11\x12\x10\n\x0b\x44YNAMIC_BAR\x10\x99\x11\x12\x10\n\x0b\x44YNAMIC_BAZ\x10\x9a\x11\"\xc0\x01\n#TestRepeatedScalarDifferentTagSizes\x12\x18\n\x10repeated_fixed32\x18\x0c \x03(\x07\x12\x16\n\x0erepeated_int32\x18\r \x03(\x05\x12\x19\n\x10repeated_fixed64\x18\xfe\x0f \x03(\x06\x12\x17\n\x0erepeated_int64\x18\xff\x0f \x03(\x03\x12\x18\n\x0erepeated_float\x18\xfe\xff\x0f \x03(\x02\x12\x19\n\x0frepeated_uint64\x18\xff\xff\x0f \x03(\x04\"\xf7\t\n\x10TestParsingMerge\x12;\n\x12required_all_types\x18\x01 \x02(\x0b\x32\x1f.protobuf_unittest.TestAllTypes\x12;\n\x12optional_all_types\x18\x02 \x01(\x0b\x32\x1f.protobuf_unittest.TestAllTypes\x12;\n\x12repeated_all_types\x18\x03 \x03(\x0b\x32\x1f.protobuf_unittest.TestAllTypes\x12H\n\roptionalgroup\x18\n \x01(\n21.protobuf_unittest.TestParsingMerge.OptionalGroup\x12H\n\rrepeatedgroup\x18\x14 \x03(\n21.protobuf_unittest.TestParsingMerge.RepeatedGroup\x1a\xaa\x04\n\x17RepeatedFieldsGenerator\x12/\n\x06\x66ield1\x18\x01 \x03(\x0b\x32\x1f.protobuf_unittest.TestAllTypes\x12/\n\x06\x66ield2\x18\x02 \x03(\x0b\x32\x1f.protobuf_unittest.TestAllTypes\x12/\n\x06\x66ield3\x18\x03 \x03(\x0b\x32\x1f.protobuf_unittest.TestAllTypes\x12R\n\x06group1\x18\n \x03(\n2B.protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.Group1\x12R\n\x06group2\x18\x14 \x03(\n2B.protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.Group2\x12.\n\x04\x65xt1\x18\xe8\x07 \x03(\x0b\x32\x1f.protobuf_unittest.TestAllTypes\x12.\n\x04\x65xt2\x18\xe9\x07 \x03(\x0b\x32\x1f.protobuf_unittest.TestAllTypes\x1a\x39\n\x06Group1\x12/\n\x06\x66ield1\x18\x0b \x01(\x0b\x32\x1f.protobuf_unittest.TestAllTypes\x1a\x39\n\x06Group2\x12/\n\x06\x66ield1\x18\x15 \x01(\x0b\x32\x1f.protobuf_unittest.TestAllTypes\x1aR\n\rOptionalGroup\x12\x41\n\x18optional_group_all_types\x18\x0b \x01(\x0b\x32\x1f.protobuf_unittest.TestAllTypes\x1aR\n\rRepeatedGroup\x12\x41\n\x18repeated_group_all_types\x18\x15 \x01(\x0b\x32\x1f.protobuf_unittest.TestAllTypes*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\x32[\n\x0coptional_ext\x12#.protobuf_unittest.TestParsingMerge\x18\xe8\x07 \x01(\x0b\x32\x1f.protobuf_unittest.TestAllTypes2[\n\x0crepeated_ext\x12#.protobuf_unittest.TestParsingMerge\x18\xe9\x07 \x03(\x0b\x32\x1f.protobuf_unittest.TestAllTypes\"D\n\x1bTestCommentInjectionMessage\x12%\n\x01\x61\x18\x01 \x01(\t:\x1a*/ <- Neither should this.\"\x0c\n\nFooRequest\"\r\n\x0b\x46ooResponse\"\x12\n\x10\x46ooClientMessage\"\x12\n\x10\x46ooServerMessage\"\x0c\n\nBarRequest\"\r\n\x0b\x42\x61rResponse*@\n\x0b\x46oreignEnum\x12\x0f\n\x0b\x46OREIGN_FOO\x10\x04\x12\x0f\n\x0b\x46OREIGN_BAR\x10\x05\x12\x0f\n\x0b\x46OREIGN_BAZ\x10\x06*K\n\x14TestEnumWithDupValue\x12\x08\n\x04\x46OO1\x10\x01\x12\x08\n\x04\x42\x41R1\x10\x02\x12\x07\n\x03\x42\x41Z\x10\x03\x12\x08\n\x04\x46OO2\x10\x01\x12\x08\n\x04\x42\x41R2\x10\x02\x1a\x02\x10\x01*\x89\x01\n\x0eTestSparseEnum\x12\x0c\n\x08SPARSE_A\x10{\x12\x0e\n\x08SPARSE_B\x10\xa6\xe7\x03\x12\x0f\n\x08SPARSE_C\x10\xb2\xb1\x80\x06\x12\x15\n\x08SPARSE_D\x10\xf1\xff\xff\xff\xff\xff\xff\xff\xff\x01\x12\x15\n\x08SPARSE_E\x10\xb4\xde\xfc\xff\xff\xff\xff\xff\xff\x01\x12\x0c\n\x08SPARSE_F\x10\x00\x12\x0c\n\x08SPARSE_G\x10\x02\x32\x99\x01\n\x0bTestService\x12\x44\n\x03\x46oo\x12\x1d.protobuf_unittest.FooRequest\x1a\x1e.protobuf_unittest.FooResponse\x12\x44\n\x03\x42\x61r\x12\x1d.protobuf_unittest.BarRequest\x1a\x1e.protobuf_unittest.BarResponse:F\n\x18optional_int32_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x01 \x01(\x05:F\n\x18optional_int64_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x02 \x01(\x03:G\n\x19optional_uint32_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x03 \x01(\r:G\n\x19optional_uint64_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x04 \x01(\x04:G\n\x19optional_sint32_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x05 \x01(\x11:G\n\x19optional_sint64_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x06 \x01(\x12:H\n\x1aoptional_fixed32_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x07 \x01(\x07:H\n\x1aoptional_fixed64_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x08 \x01(\x06:I\n\x1boptional_sfixed32_extension\x12$.protobuf_unittest.TestAllExtensions\x18\t \x01(\x0f:I\n\x1boptional_sfixed64_extension\x12$.protobuf_unittest.TestAllExtensions\x18\n \x01(\x10:F\n\x18optional_float_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x0b \x01(\x02:G\n\x19optional_double_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x0c \x01(\x01:E\n\x17optional_bool_extension\x12$.protobuf_unittest.TestAllExtensions\x18\r \x01(\x08:G\n\x19optional_string_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x0e \x01(\t:F\n\x18optional_bytes_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x0f \x01(\x0c:q\n\x17optionalgroup_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x10 \x01(\n2*.protobuf_unittest.OptionalGroup_extension:~\n!optional_nested_message_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x12 \x01(\x0b\x32-.protobuf_unittest.TestAllTypes.NestedMessage:s\n\"optional_foreign_message_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x13 \x01(\x0b\x32!.protobuf_unittest.ForeignMessage:x\n!optional_import_message_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x14 \x01(\x0b\x32\'.protobuf_unittest_import.ImportMessage:x\n\x1eoptional_nested_enum_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x15 \x01(\x0e\x32*.protobuf_unittest.TestAllTypes.NestedEnum:m\n\x1foptional_foreign_enum_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x16 \x01(\x0e\x32\x1e.protobuf_unittest.ForeignEnum:r\n\x1eoptional_import_enum_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x17 \x01(\x0e\x32$.protobuf_unittest_import.ImportEnum:Q\n\x1foptional_string_piece_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x18 \x01(\tB\x02\x08\x02:I\n\x17optional_cord_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x19 \x01(\tB\x02\x08\x01:\x85\x01\n(optional_public_import_message_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x1a \x01(\x0b\x32-.protobuf_unittest_import.PublicImportMessage:\x80\x01\n\x1foptional_lazy_message_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x1b \x01(\x0b\x32-.protobuf_unittest.TestAllTypes.NestedMessageB\x02(\x01:F\n\x18repeated_int32_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x1f \x03(\x05:F\n\x18repeated_int64_extension\x12$.protobuf_unittest.TestAllExtensions\x18 \x03(\x03:G\n\x19repeated_uint32_extension\x12$.protobuf_unittest.TestAllExtensions\x18! \x03(\r:G\n\x19repeated_uint64_extension\x12$.protobuf_unittest.TestAllExtensions\x18\" \x03(\x04:G\n\x19repeated_sint32_extension\x12$.protobuf_unittest.TestAllExtensions\x18# \x03(\x11:G\n\x19repeated_sint64_extension\x12$.protobuf_unittest.TestAllExtensions\x18$ \x03(\x12:H\n\x1arepeated_fixed32_extension\x12$.protobuf_unittest.TestAllExtensions\x18% \x03(\x07:H\n\x1arepeated_fixed64_extension\x12$.protobuf_unittest.TestAllExtensions\x18& \x03(\x06:I\n\x1brepeated_sfixed32_extension\x12$.protobuf_unittest.TestAllExtensions\x18\' \x03(\x0f:I\n\x1brepeated_sfixed64_extension\x12$.protobuf_unittest.TestAllExtensions\x18( \x03(\x10:F\n\x18repeated_float_extension\x12$.protobuf_unittest.TestAllExtensions\x18) \x03(\x02:G\n\x19repeated_double_extension\x12$.protobuf_unittest.TestAllExtensions\x18* \x03(\x01:E\n\x17repeated_bool_extension\x12$.protobuf_unittest.TestAllExtensions\x18+ \x03(\x08:G\n\x19repeated_string_extension\x12$.protobuf_unittest.TestAllExtensions\x18, \x03(\t:F\n\x18repeated_bytes_extension\x12$.protobuf_unittest.TestAllExtensions\x18- \x03(\x0c:q\n\x17repeatedgroup_extension\x12$.protobuf_unittest.TestAllExtensions\x18. \x03(\n2*.protobuf_unittest.RepeatedGroup_extension:~\n!repeated_nested_message_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x30 \x03(\x0b\x32-.protobuf_unittest.TestAllTypes.NestedMessage:s\n\"repeated_foreign_message_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x31 \x03(\x0b\x32!.protobuf_unittest.ForeignMessage:x\n!repeated_import_message_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x32 \x03(\x0b\x32\'.protobuf_unittest_import.ImportMessage:x\n\x1erepeated_nested_enum_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x33 \x03(\x0e\x32*.protobuf_unittest.TestAllTypes.NestedEnum:m\n\x1frepeated_foreign_enum_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x34 \x03(\x0e\x32\x1e.protobuf_unittest.ForeignEnum:r\n\x1erepeated_import_enum_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x35 \x03(\x0e\x32$.protobuf_unittest_import.ImportEnum:Q\n\x1frepeated_string_piece_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x36 \x03(\tB\x02\x08\x02:I\n\x17repeated_cord_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x37 \x03(\tB\x02\x08\x01:\x80\x01\n\x1frepeated_lazy_message_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x39 \x03(\x0b\x32-.protobuf_unittest.TestAllTypes.NestedMessageB\x02(\x01:I\n\x17\x64\x65\x66\x61ult_int32_extension\x12$.protobuf_unittest.TestAllExtensions\x18= \x01(\x05:\x02\x34\x31:I\n\x17\x64\x65\x66\x61ult_int64_extension\x12$.protobuf_unittest.TestAllExtensions\x18> \x01(\x03:\x02\x34\x32:J\n\x18\x64\x65\x66\x61ult_uint32_extension\x12$.protobuf_unittest.TestAllExtensions\x18? \x01(\r:\x02\x34\x33:J\n\x18\x64\x65\x66\x61ult_uint64_extension\x12$.protobuf_unittest.TestAllExtensions\x18@ \x01(\x04:\x02\x34\x34:K\n\x18\x64\x65\x66\x61ult_sint32_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x41 \x01(\x11:\x03-45:J\n\x18\x64\x65\x66\x61ult_sint64_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x42 \x01(\x12:\x02\x34\x36:K\n\x19\x64\x65\x66\x61ult_fixed32_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x43 \x01(\x07:\x02\x34\x37:K\n\x19\x64\x65\x66\x61ult_fixed64_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x44 \x01(\x06:\x02\x34\x38:L\n\x1a\x64\x65\x66\x61ult_sfixed32_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x45 \x01(\x0f:\x02\x34\x39:M\n\x1a\x64\x65\x66\x61ult_sfixed64_extension\x12$.protobuf_unittest.TestAllExtensions\x18\x46 \x01(\x10:\x03-50:K\n\x17\x64\x65\x66\x61ult_float_extension\x12$.protobuf_unittest.TestAllExtensions\x18G \x01(\x02:\x04\x35\x31.5:M\n\x18\x64\x65\x66\x61ult_double_extension\x12$.protobuf_unittest.TestAllExtensions\x18H \x01(\x01:\x05\x35\x32\x30\x30\x30:J\n\x16\x64\x65\x66\x61ult_bool_extension\x12$.protobuf_unittest.TestAllExtensions\x18I \x01(\x08:\x04true:M\n\x18\x64\x65\x66\x61ult_string_extension\x12$.protobuf_unittest.TestAllExtensions\x18J \x01(\t:\x05hello:L\n\x17\x64\x65\x66\x61ult_bytes_extension\x12$.protobuf_unittest.TestAllExtensions\x18K \x01(\x0c:\x05world:|\n\x1d\x64\x65\x66\x61ult_nested_enum_extension\x12$.protobuf_unittest.TestAllExtensions\x18Q \x01(\x0e\x32*.protobuf_unittest.TestAllTypes.NestedEnum:\x03\x42\x41R:y\n\x1e\x64\x65\x66\x61ult_foreign_enum_extension\x12$.protobuf_unittest.TestAllExtensions\x18R \x01(\x0e\x32\x1e.protobuf_unittest.ForeignEnum:\x0b\x46OREIGN_BAR:}\n\x1d\x64\x65\x66\x61ult_import_enum_extension\x12$.protobuf_unittest.TestAllExtensions\x18S \x01(\x0e\x32$.protobuf_unittest_import.ImportEnum:\nIMPORT_BAR:U\n\x1e\x64\x65\x66\x61ult_string_piece_extension\x12$.protobuf_unittest.TestAllExtensions\x18T \x01(\t:\x03\x61\x62\x63\x42\x02\x08\x02:M\n\x16\x64\x65\x66\x61ult_cord_extension\x12$.protobuf_unittest.TestAllExtensions\x18U \x01(\t:\x03\x31\x32\x33\x42\x02\x08\x01:B\n\x13my_extension_string\x12%.protobuf_unittest.TestFieldOrderings\x18\x32 \x01(\t:?\n\x10my_extension_int\x12%.protobuf_unittest.TestFieldOrderings\x18\x05 \x01(\x05:K\n\x16packed_int32_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18Z \x03(\x05\x42\x02\x10\x01:K\n\x16packed_int64_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18[ \x03(\x03\x42\x02\x10\x01:L\n\x17packed_uint32_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18\\ \x03(\rB\x02\x10\x01:L\n\x17packed_uint64_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18] \x03(\x04\x42\x02\x10\x01:L\n\x17packed_sint32_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18^ \x03(\x11\x42\x02\x10\x01:L\n\x17packed_sint64_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18_ \x03(\x12\x42\x02\x10\x01:M\n\x18packed_fixed32_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18` \x03(\x07\x42\x02\x10\x01:M\n\x18packed_fixed64_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18\x61 \x03(\x06\x42\x02\x10\x01:N\n\x19packed_sfixed32_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18\x62 \x03(\x0f\x42\x02\x10\x01:N\n\x19packed_sfixed64_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18\x63 \x03(\x10\x42\x02\x10\x01:K\n\x16packed_float_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18\x64 \x03(\x02\x42\x02\x10\x01:L\n\x17packed_double_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18\x65 \x03(\x01\x42\x02\x10\x01:J\n\x15packed_bool_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18\x66 \x03(\x08\x42\x02\x10\x01:j\n\x15packed_enum_extension\x12\'.protobuf_unittest.TestPackedExtensions\x18g \x03(\x0e\x32\x1e.protobuf_unittest.ForeignEnumB\x02\x10\x01\x42\x1a\x42\rUnittestProtoH\x01\x80\x01\x01\x88\x01\x01\x90\x01\x01') + +_FOREIGNENUM = _descriptor.EnumDescriptor( + name='ForeignEnum', + full_name='protobuf_unittest.ForeignEnum', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='FOREIGN_FOO', index=0, number=4, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FOREIGN_BAR', index=1, number=5, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FOREIGN_BAZ', index=2, number=6, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=10149, + serialized_end=10213, +) + +ForeignEnum = enum_type_wrapper.EnumTypeWrapper(_FOREIGNENUM) +_TESTENUMWITHDUPVALUE = _descriptor.EnumDescriptor( + name='TestEnumWithDupValue', + full_name='protobuf_unittest.TestEnumWithDupValue', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='FOO1', index=0, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='BAR1', index=1, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='BAZ', index=2, number=3, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FOO2', index=3, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='BAR2', index=4, number=2, + options=None, + type=None), + ], + containing_type=None, + options=_descriptor._ParseOptions(descriptor_pb2.EnumOptions(), '\020\001'), + serialized_start=10215, + serialized_end=10290, +) + +TestEnumWithDupValue = enum_type_wrapper.EnumTypeWrapper(_TESTENUMWITHDUPVALUE) +_TESTSPARSEENUM = _descriptor.EnumDescriptor( + name='TestSparseEnum', + full_name='protobuf_unittest.TestSparseEnum', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='SPARSE_A', index=0, number=123, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='SPARSE_B', index=1, number=62374, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='SPARSE_C', index=2, number=12589234, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='SPARSE_D', index=3, number=-15, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='SPARSE_E', index=4, number=-53452, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='SPARSE_F', index=5, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='SPARSE_G', index=6, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=10293, + serialized_end=10430, +) + +TestSparseEnum = enum_type_wrapper.EnumTypeWrapper(_TESTSPARSEENUM) +FOREIGN_FOO = 4 +FOREIGN_BAR = 5 +FOREIGN_BAZ = 6 +FOO1 = 1 +BAR1 = 2 +BAZ = 3 +FOO2 = 1 +BAR2 = 2 +SPARSE_A = 123 +SPARSE_B = 62374 +SPARSE_C = 12589234 +SPARSE_D = -15 +SPARSE_E = -53452 +SPARSE_F = 0 +SPARSE_G = 2 + +OPTIONAL_INT32_EXTENSION_FIELD_NUMBER = 1 +optional_int32_extension = _descriptor.FieldDescriptor( + name='optional_int32_extension', full_name='protobuf_unittest.optional_int32_extension', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_INT64_EXTENSION_FIELD_NUMBER = 2 +optional_int64_extension = _descriptor.FieldDescriptor( + name='optional_int64_extension', full_name='protobuf_unittest.optional_int64_extension', index=1, + number=2, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_UINT32_EXTENSION_FIELD_NUMBER = 3 +optional_uint32_extension = _descriptor.FieldDescriptor( + name='optional_uint32_extension', full_name='protobuf_unittest.optional_uint32_extension', index=2, + number=3, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_UINT64_EXTENSION_FIELD_NUMBER = 4 +optional_uint64_extension = _descriptor.FieldDescriptor( + name='optional_uint64_extension', full_name='protobuf_unittest.optional_uint64_extension', index=3, + number=4, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_SINT32_EXTENSION_FIELD_NUMBER = 5 +optional_sint32_extension = _descriptor.FieldDescriptor( + name='optional_sint32_extension', full_name='protobuf_unittest.optional_sint32_extension', index=4, + number=5, type=17, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_SINT64_EXTENSION_FIELD_NUMBER = 6 +optional_sint64_extension = _descriptor.FieldDescriptor( + name='optional_sint64_extension', full_name='protobuf_unittest.optional_sint64_extension', index=5, + number=6, type=18, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_FIXED32_EXTENSION_FIELD_NUMBER = 7 +optional_fixed32_extension = _descriptor.FieldDescriptor( + name='optional_fixed32_extension', full_name='protobuf_unittest.optional_fixed32_extension', index=6, + number=7, type=7, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_FIXED64_EXTENSION_FIELD_NUMBER = 8 +optional_fixed64_extension = _descriptor.FieldDescriptor( + name='optional_fixed64_extension', full_name='protobuf_unittest.optional_fixed64_extension', index=7, + number=8, type=6, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_SFIXED32_EXTENSION_FIELD_NUMBER = 9 +optional_sfixed32_extension = _descriptor.FieldDescriptor( + name='optional_sfixed32_extension', full_name='protobuf_unittest.optional_sfixed32_extension', index=8, + number=9, type=15, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_SFIXED64_EXTENSION_FIELD_NUMBER = 10 +optional_sfixed64_extension = _descriptor.FieldDescriptor( + name='optional_sfixed64_extension', full_name='protobuf_unittest.optional_sfixed64_extension', index=9, + number=10, type=16, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_FLOAT_EXTENSION_FIELD_NUMBER = 11 +optional_float_extension = _descriptor.FieldDescriptor( + name='optional_float_extension', full_name='protobuf_unittest.optional_float_extension', index=10, + number=11, type=2, cpp_type=6, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_DOUBLE_EXTENSION_FIELD_NUMBER = 12 +optional_double_extension = _descriptor.FieldDescriptor( + name='optional_double_extension', full_name='protobuf_unittest.optional_double_extension', index=11, + number=12, type=1, cpp_type=5, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_BOOL_EXTENSION_FIELD_NUMBER = 13 +optional_bool_extension = _descriptor.FieldDescriptor( + name='optional_bool_extension', full_name='protobuf_unittest.optional_bool_extension', index=12, + number=13, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_STRING_EXTENSION_FIELD_NUMBER = 14 +optional_string_extension = _descriptor.FieldDescriptor( + name='optional_string_extension', full_name='protobuf_unittest.optional_string_extension', index=13, + number=14, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_BYTES_EXTENSION_FIELD_NUMBER = 15 +optional_bytes_extension = _descriptor.FieldDescriptor( + name='optional_bytes_extension', full_name='protobuf_unittest.optional_bytes_extension', index=14, + number=15, type=12, cpp_type=9, label=1, + has_default_value=False, default_value="", + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONALGROUP_EXTENSION_FIELD_NUMBER = 16 +optionalgroup_extension = _descriptor.FieldDescriptor( + name='optionalgroup_extension', full_name='protobuf_unittest.optionalgroup_extension', index=15, + number=16, type=10, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER = 18 +optional_nested_message_extension = _descriptor.FieldDescriptor( + name='optional_nested_message_extension', full_name='protobuf_unittest.optional_nested_message_extension', index=16, + number=18, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_FOREIGN_MESSAGE_EXTENSION_FIELD_NUMBER = 19 +optional_foreign_message_extension = _descriptor.FieldDescriptor( + name='optional_foreign_message_extension', full_name='protobuf_unittest.optional_foreign_message_extension', index=17, + number=19, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_IMPORT_MESSAGE_EXTENSION_FIELD_NUMBER = 20 +optional_import_message_extension = _descriptor.FieldDescriptor( + name='optional_import_message_extension', full_name='protobuf_unittest.optional_import_message_extension', index=18, + number=20, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_NESTED_ENUM_EXTENSION_FIELD_NUMBER = 21 +optional_nested_enum_extension = _descriptor.FieldDescriptor( + name='optional_nested_enum_extension', full_name='protobuf_unittest.optional_nested_enum_extension', index=19, + number=21, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_FOREIGN_ENUM_EXTENSION_FIELD_NUMBER = 22 +optional_foreign_enum_extension = _descriptor.FieldDescriptor( + name='optional_foreign_enum_extension', full_name='protobuf_unittest.optional_foreign_enum_extension', index=20, + number=22, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=4, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_IMPORT_ENUM_EXTENSION_FIELD_NUMBER = 23 +optional_import_enum_extension = _descriptor.FieldDescriptor( + name='optional_import_enum_extension', full_name='protobuf_unittest.optional_import_enum_extension', index=21, + number=23, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=7, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_STRING_PIECE_EXTENSION_FIELD_NUMBER = 24 +optional_string_piece_extension = _descriptor.FieldDescriptor( + name='optional_string_piece_extension', full_name='protobuf_unittest.optional_string_piece_extension', index=22, + number=24, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002')) +OPTIONAL_CORD_EXTENSION_FIELD_NUMBER = 25 +optional_cord_extension = _descriptor.FieldDescriptor( + name='optional_cord_extension', full_name='protobuf_unittest.optional_cord_extension', index=23, + number=25, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001')) +OPTIONAL_PUBLIC_IMPORT_MESSAGE_EXTENSION_FIELD_NUMBER = 26 +optional_public_import_message_extension = _descriptor.FieldDescriptor( + name='optional_public_import_message_extension', full_name='protobuf_unittest.optional_public_import_message_extension', index=24, + number=26, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +OPTIONAL_LAZY_MESSAGE_EXTENSION_FIELD_NUMBER = 27 +optional_lazy_message_extension = _descriptor.FieldDescriptor( + name='optional_lazy_message_extension', full_name='protobuf_unittest.optional_lazy_message_extension', index=25, + number=27, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '(\001')) +REPEATED_INT32_EXTENSION_FIELD_NUMBER = 31 +repeated_int32_extension = _descriptor.FieldDescriptor( + name='repeated_int32_extension', full_name='protobuf_unittest.repeated_int32_extension', index=26, + number=31, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_INT64_EXTENSION_FIELD_NUMBER = 32 +repeated_int64_extension = _descriptor.FieldDescriptor( + name='repeated_int64_extension', full_name='protobuf_unittest.repeated_int64_extension', index=27, + number=32, type=3, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_UINT32_EXTENSION_FIELD_NUMBER = 33 +repeated_uint32_extension = _descriptor.FieldDescriptor( + name='repeated_uint32_extension', full_name='protobuf_unittest.repeated_uint32_extension', index=28, + number=33, type=13, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_UINT64_EXTENSION_FIELD_NUMBER = 34 +repeated_uint64_extension = _descriptor.FieldDescriptor( + name='repeated_uint64_extension', full_name='protobuf_unittest.repeated_uint64_extension', index=29, + number=34, type=4, cpp_type=4, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_SINT32_EXTENSION_FIELD_NUMBER = 35 +repeated_sint32_extension = _descriptor.FieldDescriptor( + name='repeated_sint32_extension', full_name='protobuf_unittest.repeated_sint32_extension', index=30, + number=35, type=17, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_SINT64_EXTENSION_FIELD_NUMBER = 36 +repeated_sint64_extension = _descriptor.FieldDescriptor( + name='repeated_sint64_extension', full_name='protobuf_unittest.repeated_sint64_extension', index=31, + number=36, type=18, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_FIXED32_EXTENSION_FIELD_NUMBER = 37 +repeated_fixed32_extension = _descriptor.FieldDescriptor( + name='repeated_fixed32_extension', full_name='protobuf_unittest.repeated_fixed32_extension', index=32, + number=37, type=7, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_FIXED64_EXTENSION_FIELD_NUMBER = 38 +repeated_fixed64_extension = _descriptor.FieldDescriptor( + name='repeated_fixed64_extension', full_name='protobuf_unittest.repeated_fixed64_extension', index=33, + number=38, type=6, cpp_type=4, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_SFIXED32_EXTENSION_FIELD_NUMBER = 39 +repeated_sfixed32_extension = _descriptor.FieldDescriptor( + name='repeated_sfixed32_extension', full_name='protobuf_unittest.repeated_sfixed32_extension', index=34, + number=39, type=15, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_SFIXED64_EXTENSION_FIELD_NUMBER = 40 +repeated_sfixed64_extension = _descriptor.FieldDescriptor( + name='repeated_sfixed64_extension', full_name='protobuf_unittest.repeated_sfixed64_extension', index=35, + number=40, type=16, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_FLOAT_EXTENSION_FIELD_NUMBER = 41 +repeated_float_extension = _descriptor.FieldDescriptor( + name='repeated_float_extension', full_name='protobuf_unittest.repeated_float_extension', index=36, + number=41, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_DOUBLE_EXTENSION_FIELD_NUMBER = 42 +repeated_double_extension = _descriptor.FieldDescriptor( + name='repeated_double_extension', full_name='protobuf_unittest.repeated_double_extension', index=37, + number=42, type=1, cpp_type=5, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_BOOL_EXTENSION_FIELD_NUMBER = 43 +repeated_bool_extension = _descriptor.FieldDescriptor( + name='repeated_bool_extension', full_name='protobuf_unittest.repeated_bool_extension', index=38, + number=43, type=8, cpp_type=7, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_STRING_EXTENSION_FIELD_NUMBER = 44 +repeated_string_extension = _descriptor.FieldDescriptor( + name='repeated_string_extension', full_name='protobuf_unittest.repeated_string_extension', index=39, + number=44, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_BYTES_EXTENSION_FIELD_NUMBER = 45 +repeated_bytes_extension = _descriptor.FieldDescriptor( + name='repeated_bytes_extension', full_name='protobuf_unittest.repeated_bytes_extension', index=40, + number=45, type=12, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATEDGROUP_EXTENSION_FIELD_NUMBER = 46 +repeatedgroup_extension = _descriptor.FieldDescriptor( + name='repeatedgroup_extension', full_name='protobuf_unittest.repeatedgroup_extension', index=41, + number=46, type=10, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_NESTED_MESSAGE_EXTENSION_FIELD_NUMBER = 48 +repeated_nested_message_extension = _descriptor.FieldDescriptor( + name='repeated_nested_message_extension', full_name='protobuf_unittest.repeated_nested_message_extension', index=42, + number=48, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_FOREIGN_MESSAGE_EXTENSION_FIELD_NUMBER = 49 +repeated_foreign_message_extension = _descriptor.FieldDescriptor( + name='repeated_foreign_message_extension', full_name='protobuf_unittest.repeated_foreign_message_extension', index=43, + number=49, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_IMPORT_MESSAGE_EXTENSION_FIELD_NUMBER = 50 +repeated_import_message_extension = _descriptor.FieldDescriptor( + name='repeated_import_message_extension', full_name='protobuf_unittest.repeated_import_message_extension', index=44, + number=50, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_NESTED_ENUM_EXTENSION_FIELD_NUMBER = 51 +repeated_nested_enum_extension = _descriptor.FieldDescriptor( + name='repeated_nested_enum_extension', full_name='protobuf_unittest.repeated_nested_enum_extension', index=45, + number=51, type=14, cpp_type=8, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_FOREIGN_ENUM_EXTENSION_FIELD_NUMBER = 52 +repeated_foreign_enum_extension = _descriptor.FieldDescriptor( + name='repeated_foreign_enum_extension', full_name='protobuf_unittest.repeated_foreign_enum_extension', index=46, + number=52, type=14, cpp_type=8, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_IMPORT_ENUM_EXTENSION_FIELD_NUMBER = 53 +repeated_import_enum_extension = _descriptor.FieldDescriptor( + name='repeated_import_enum_extension', full_name='protobuf_unittest.repeated_import_enum_extension', index=47, + number=53, type=14, cpp_type=8, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +REPEATED_STRING_PIECE_EXTENSION_FIELD_NUMBER = 54 +repeated_string_piece_extension = _descriptor.FieldDescriptor( + name='repeated_string_piece_extension', full_name='protobuf_unittest.repeated_string_piece_extension', index=48, + number=54, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002')) +REPEATED_CORD_EXTENSION_FIELD_NUMBER = 55 +repeated_cord_extension = _descriptor.FieldDescriptor( + name='repeated_cord_extension', full_name='protobuf_unittest.repeated_cord_extension', index=49, + number=55, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001')) +REPEATED_LAZY_MESSAGE_EXTENSION_FIELD_NUMBER = 57 +repeated_lazy_message_extension = _descriptor.FieldDescriptor( + name='repeated_lazy_message_extension', full_name='protobuf_unittest.repeated_lazy_message_extension', index=50, + number=57, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '(\001')) +DEFAULT_INT32_EXTENSION_FIELD_NUMBER = 61 +default_int32_extension = _descriptor.FieldDescriptor( + name='default_int32_extension', full_name='protobuf_unittest.default_int32_extension', index=51, + number=61, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=41, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_INT64_EXTENSION_FIELD_NUMBER = 62 +default_int64_extension = _descriptor.FieldDescriptor( + name='default_int64_extension', full_name='protobuf_unittest.default_int64_extension', index=52, + number=62, type=3, cpp_type=2, label=1, + has_default_value=True, default_value=42, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_UINT32_EXTENSION_FIELD_NUMBER = 63 +default_uint32_extension = _descriptor.FieldDescriptor( + name='default_uint32_extension', full_name='protobuf_unittest.default_uint32_extension', index=53, + number=63, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=43, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_UINT64_EXTENSION_FIELD_NUMBER = 64 +default_uint64_extension = _descriptor.FieldDescriptor( + name='default_uint64_extension', full_name='protobuf_unittest.default_uint64_extension', index=54, + number=64, type=4, cpp_type=4, label=1, + has_default_value=True, default_value=44, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_SINT32_EXTENSION_FIELD_NUMBER = 65 +default_sint32_extension = _descriptor.FieldDescriptor( + name='default_sint32_extension', full_name='protobuf_unittest.default_sint32_extension', index=55, + number=65, type=17, cpp_type=1, label=1, + has_default_value=True, default_value=-45, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_SINT64_EXTENSION_FIELD_NUMBER = 66 +default_sint64_extension = _descriptor.FieldDescriptor( + name='default_sint64_extension', full_name='protobuf_unittest.default_sint64_extension', index=56, + number=66, type=18, cpp_type=2, label=1, + has_default_value=True, default_value=46, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_FIXED32_EXTENSION_FIELD_NUMBER = 67 +default_fixed32_extension = _descriptor.FieldDescriptor( + name='default_fixed32_extension', full_name='protobuf_unittest.default_fixed32_extension', index=57, + number=67, type=7, cpp_type=3, label=1, + has_default_value=True, default_value=47, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_FIXED64_EXTENSION_FIELD_NUMBER = 68 +default_fixed64_extension = _descriptor.FieldDescriptor( + name='default_fixed64_extension', full_name='protobuf_unittest.default_fixed64_extension', index=58, + number=68, type=6, cpp_type=4, label=1, + has_default_value=True, default_value=48, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_SFIXED32_EXTENSION_FIELD_NUMBER = 69 +default_sfixed32_extension = _descriptor.FieldDescriptor( + name='default_sfixed32_extension', full_name='protobuf_unittest.default_sfixed32_extension', index=59, + number=69, type=15, cpp_type=1, label=1, + has_default_value=True, default_value=49, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_SFIXED64_EXTENSION_FIELD_NUMBER = 70 +default_sfixed64_extension = _descriptor.FieldDescriptor( + name='default_sfixed64_extension', full_name='protobuf_unittest.default_sfixed64_extension', index=60, + number=70, type=16, cpp_type=2, label=1, + has_default_value=True, default_value=-50, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_FLOAT_EXTENSION_FIELD_NUMBER = 71 +default_float_extension = _descriptor.FieldDescriptor( + name='default_float_extension', full_name='protobuf_unittest.default_float_extension', index=61, + number=71, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=51.5, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_DOUBLE_EXTENSION_FIELD_NUMBER = 72 +default_double_extension = _descriptor.FieldDescriptor( + name='default_double_extension', full_name='protobuf_unittest.default_double_extension', index=62, + number=72, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=52000, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_BOOL_EXTENSION_FIELD_NUMBER = 73 +default_bool_extension = _descriptor.FieldDescriptor( + name='default_bool_extension', full_name='protobuf_unittest.default_bool_extension', index=63, + number=73, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_STRING_EXTENSION_FIELD_NUMBER = 74 +default_string_extension = _descriptor.FieldDescriptor( + name='default_string_extension', full_name='protobuf_unittest.default_string_extension', index=64, + number=74, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("hello", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_BYTES_EXTENSION_FIELD_NUMBER = 75 +default_bytes_extension = _descriptor.FieldDescriptor( + name='default_bytes_extension', full_name='protobuf_unittest.default_bytes_extension', index=65, + number=75, type=12, cpp_type=9, label=1, + has_default_value=True, default_value="world", + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_NESTED_ENUM_EXTENSION_FIELD_NUMBER = 81 +default_nested_enum_extension = _descriptor.FieldDescriptor( + name='default_nested_enum_extension', full_name='protobuf_unittest.default_nested_enum_extension', index=66, + number=81, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=2, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_FOREIGN_ENUM_EXTENSION_FIELD_NUMBER = 82 +default_foreign_enum_extension = _descriptor.FieldDescriptor( + name='default_foreign_enum_extension', full_name='protobuf_unittest.default_foreign_enum_extension', index=67, + number=82, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=5, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_IMPORT_ENUM_EXTENSION_FIELD_NUMBER = 83 +default_import_enum_extension = _descriptor.FieldDescriptor( + name='default_import_enum_extension', full_name='protobuf_unittest.default_import_enum_extension', index=68, + number=83, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +DEFAULT_STRING_PIECE_EXTENSION_FIELD_NUMBER = 84 +default_string_piece_extension = _descriptor.FieldDescriptor( + name='default_string_piece_extension', full_name='protobuf_unittest.default_string_piece_extension', index=69, + number=84, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("abc", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002')) +DEFAULT_CORD_EXTENSION_FIELD_NUMBER = 85 +default_cord_extension = _descriptor.FieldDescriptor( + name='default_cord_extension', full_name='protobuf_unittest.default_cord_extension', index=70, + number=85, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("123", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001')) +MY_EXTENSION_STRING_FIELD_NUMBER = 50 +my_extension_string = _descriptor.FieldDescriptor( + name='my_extension_string', full_name='protobuf_unittest.my_extension_string', index=71, + number=50, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +MY_EXTENSION_INT_FIELD_NUMBER = 5 +my_extension_int = _descriptor.FieldDescriptor( + name='my_extension_int', full_name='protobuf_unittest.my_extension_int', index=72, + number=5, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None) +PACKED_INT32_EXTENSION_FIELD_NUMBER = 90 +packed_int32_extension = _descriptor.FieldDescriptor( + name='packed_int32_extension', full_name='protobuf_unittest.packed_int32_extension', index=73, + number=90, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_INT64_EXTENSION_FIELD_NUMBER = 91 +packed_int64_extension = _descriptor.FieldDescriptor( + name='packed_int64_extension', full_name='protobuf_unittest.packed_int64_extension', index=74, + number=91, type=3, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_UINT32_EXTENSION_FIELD_NUMBER = 92 +packed_uint32_extension = _descriptor.FieldDescriptor( + name='packed_uint32_extension', full_name='protobuf_unittest.packed_uint32_extension', index=75, + number=92, type=13, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_UINT64_EXTENSION_FIELD_NUMBER = 93 +packed_uint64_extension = _descriptor.FieldDescriptor( + name='packed_uint64_extension', full_name='protobuf_unittest.packed_uint64_extension', index=76, + number=93, type=4, cpp_type=4, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_SINT32_EXTENSION_FIELD_NUMBER = 94 +packed_sint32_extension = _descriptor.FieldDescriptor( + name='packed_sint32_extension', full_name='protobuf_unittest.packed_sint32_extension', index=77, + number=94, type=17, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_SINT64_EXTENSION_FIELD_NUMBER = 95 +packed_sint64_extension = _descriptor.FieldDescriptor( + name='packed_sint64_extension', full_name='protobuf_unittest.packed_sint64_extension', index=78, + number=95, type=18, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_FIXED32_EXTENSION_FIELD_NUMBER = 96 +packed_fixed32_extension = _descriptor.FieldDescriptor( + name='packed_fixed32_extension', full_name='protobuf_unittest.packed_fixed32_extension', index=79, + number=96, type=7, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_FIXED64_EXTENSION_FIELD_NUMBER = 97 +packed_fixed64_extension = _descriptor.FieldDescriptor( + name='packed_fixed64_extension', full_name='protobuf_unittest.packed_fixed64_extension', index=80, + number=97, type=6, cpp_type=4, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_SFIXED32_EXTENSION_FIELD_NUMBER = 98 +packed_sfixed32_extension = _descriptor.FieldDescriptor( + name='packed_sfixed32_extension', full_name='protobuf_unittest.packed_sfixed32_extension', index=81, + number=98, type=15, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_SFIXED64_EXTENSION_FIELD_NUMBER = 99 +packed_sfixed64_extension = _descriptor.FieldDescriptor( + name='packed_sfixed64_extension', full_name='protobuf_unittest.packed_sfixed64_extension', index=82, + number=99, type=16, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_FLOAT_EXTENSION_FIELD_NUMBER = 100 +packed_float_extension = _descriptor.FieldDescriptor( + name='packed_float_extension', full_name='protobuf_unittest.packed_float_extension', index=83, + number=100, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_DOUBLE_EXTENSION_FIELD_NUMBER = 101 +packed_double_extension = _descriptor.FieldDescriptor( + name='packed_double_extension', full_name='protobuf_unittest.packed_double_extension', index=84, + number=101, type=1, cpp_type=5, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_BOOL_EXTENSION_FIELD_NUMBER = 102 +packed_bool_extension = _descriptor.FieldDescriptor( + name='packed_bool_extension', full_name='protobuf_unittest.packed_bool_extension', index=85, + number=102, type=8, cpp_type=7, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) +PACKED_ENUM_EXTENSION_FIELD_NUMBER = 103 +packed_enum_extension = _descriptor.FieldDescriptor( + name='packed_enum_extension', full_name='protobuf_unittest.packed_enum_extension', index=86, + number=103, type=14, cpp_type=8, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')) + +_TESTALLTYPES_NESTEDENUM = _descriptor.EnumDescriptor( + name='NestedEnum', + full_name='protobuf_unittest.TestAllTypes.NestedEnum', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='FOO', index=0, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='BAR', index=1, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='BAZ', index=2, number=3, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=3052, + serialized_end=3091, +) + +_TESTDYNAMICEXTENSIONS_DYNAMICENUMTYPE = _descriptor.EnumDescriptor( + name='DynamicEnumType', + full_name='protobuf_unittest.TestDynamicExtensions.DynamicEnumType', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='DYNAMIC_FOO', index=0, number=2200, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='DYNAMIC_BAR', index=1, number=2201, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='DYNAMIC_BAZ', index=2, number=2202, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=8439, + serialized_end=8510, +) + + +_TESTALLTYPES_NESTEDMESSAGE = _descriptor.Descriptor( + name='NestedMessage', + full_name='protobuf_unittest.TestAllTypes.NestedMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='bb', full_name='protobuf_unittest.TestAllTypes.NestedMessage.bb', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2967, + serialized_end=2994, +) + +_TESTALLTYPES_OPTIONALGROUP = _descriptor.Descriptor( + name='OptionalGroup', + full_name='protobuf_unittest.TestAllTypes.OptionalGroup', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='protobuf_unittest.TestAllTypes.OptionalGroup.a', index=0, + number=17, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2996, + serialized_end=3022, +) + +_TESTALLTYPES_REPEATEDGROUP = _descriptor.Descriptor( + name='RepeatedGroup', + full_name='protobuf_unittest.TestAllTypes.RepeatedGroup', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='protobuf_unittest.TestAllTypes.RepeatedGroup.a', index=0, + number=47, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3024, + serialized_end=3050, +) + +_TESTALLTYPES = _descriptor.Descriptor( + name='TestAllTypes', + full_name='protobuf_unittest.TestAllTypes', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='optional_int32', full_name='protobuf_unittest.TestAllTypes.optional_int32', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_int64', full_name='protobuf_unittest.TestAllTypes.optional_int64', index=1, + number=2, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_uint32', full_name='protobuf_unittest.TestAllTypes.optional_uint32', index=2, + number=3, type=13, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_uint64', full_name='protobuf_unittest.TestAllTypes.optional_uint64', index=3, + number=4, type=4, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_sint32', full_name='protobuf_unittest.TestAllTypes.optional_sint32', index=4, + number=5, type=17, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_sint64', full_name='protobuf_unittest.TestAllTypes.optional_sint64', index=5, + number=6, type=18, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_fixed32', full_name='protobuf_unittest.TestAllTypes.optional_fixed32', index=6, + number=7, type=7, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_fixed64', full_name='protobuf_unittest.TestAllTypes.optional_fixed64', index=7, + number=8, type=6, cpp_type=4, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_sfixed32', full_name='protobuf_unittest.TestAllTypes.optional_sfixed32', index=8, + number=9, type=15, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_sfixed64', full_name='protobuf_unittest.TestAllTypes.optional_sfixed64', index=9, + number=10, type=16, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_float', full_name='protobuf_unittest.TestAllTypes.optional_float', index=10, + number=11, type=2, cpp_type=6, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_double', full_name='protobuf_unittest.TestAllTypes.optional_double', index=11, + number=12, type=1, cpp_type=5, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_bool', full_name='protobuf_unittest.TestAllTypes.optional_bool', index=12, + number=13, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_string', full_name='protobuf_unittest.TestAllTypes.optional_string', index=13, + number=14, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_bytes', full_name='protobuf_unittest.TestAllTypes.optional_bytes', index=14, + number=15, type=12, cpp_type=9, label=1, + has_default_value=False, default_value="", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optionalgroup', full_name='protobuf_unittest.TestAllTypes.optionalgroup', index=15, + number=16, type=10, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_nested_message', full_name='protobuf_unittest.TestAllTypes.optional_nested_message', index=16, + number=18, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_foreign_message', full_name='protobuf_unittest.TestAllTypes.optional_foreign_message', index=17, + number=19, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_import_message', full_name='protobuf_unittest.TestAllTypes.optional_import_message', index=18, + number=20, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_nested_enum', full_name='protobuf_unittest.TestAllTypes.optional_nested_enum', index=19, + number=21, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_foreign_enum', full_name='protobuf_unittest.TestAllTypes.optional_foreign_enum', index=20, + number=22, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=4, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_import_enum', full_name='protobuf_unittest.TestAllTypes.optional_import_enum', index=21, + number=23, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=7, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_string_piece', full_name='protobuf_unittest.TestAllTypes.optional_string_piece', index=22, + number=24, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002')), + _descriptor.FieldDescriptor( + name='optional_cord', full_name='protobuf_unittest.TestAllTypes.optional_cord', index=23, + number=25, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001')), + _descriptor.FieldDescriptor( + name='optional_public_import_message', full_name='protobuf_unittest.TestAllTypes.optional_public_import_message', index=24, + number=26, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_lazy_message', full_name='protobuf_unittest.TestAllTypes.optional_lazy_message', index=25, + number=27, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '(\001')), + _descriptor.FieldDescriptor( + name='repeated_int32', full_name='protobuf_unittest.TestAllTypes.repeated_int32', index=26, + number=31, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_int64', full_name='protobuf_unittest.TestAllTypes.repeated_int64', index=27, + number=32, type=3, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_uint32', full_name='protobuf_unittest.TestAllTypes.repeated_uint32', index=28, + number=33, type=13, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_uint64', full_name='protobuf_unittest.TestAllTypes.repeated_uint64', index=29, + number=34, type=4, cpp_type=4, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_sint32', full_name='protobuf_unittest.TestAllTypes.repeated_sint32', index=30, + number=35, type=17, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_sint64', full_name='protobuf_unittest.TestAllTypes.repeated_sint64', index=31, + number=36, type=18, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_fixed32', full_name='protobuf_unittest.TestAllTypes.repeated_fixed32', index=32, + number=37, type=7, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_fixed64', full_name='protobuf_unittest.TestAllTypes.repeated_fixed64', index=33, + number=38, type=6, cpp_type=4, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_sfixed32', full_name='protobuf_unittest.TestAllTypes.repeated_sfixed32', index=34, + number=39, type=15, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_sfixed64', full_name='protobuf_unittest.TestAllTypes.repeated_sfixed64', index=35, + number=40, type=16, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_float', full_name='protobuf_unittest.TestAllTypes.repeated_float', index=36, + number=41, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_double', full_name='protobuf_unittest.TestAllTypes.repeated_double', index=37, + number=42, type=1, cpp_type=5, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_bool', full_name='protobuf_unittest.TestAllTypes.repeated_bool', index=38, + number=43, type=8, cpp_type=7, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_string', full_name='protobuf_unittest.TestAllTypes.repeated_string', index=39, + number=44, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_bytes', full_name='protobuf_unittest.TestAllTypes.repeated_bytes', index=40, + number=45, type=12, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeatedgroup', full_name='protobuf_unittest.TestAllTypes.repeatedgroup', index=41, + number=46, type=10, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_nested_message', full_name='protobuf_unittest.TestAllTypes.repeated_nested_message', index=42, + number=48, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_foreign_message', full_name='protobuf_unittest.TestAllTypes.repeated_foreign_message', index=43, + number=49, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_import_message', full_name='protobuf_unittest.TestAllTypes.repeated_import_message', index=44, + number=50, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_nested_enum', full_name='protobuf_unittest.TestAllTypes.repeated_nested_enum', index=45, + number=51, type=14, cpp_type=8, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_foreign_enum', full_name='protobuf_unittest.TestAllTypes.repeated_foreign_enum', index=46, + number=52, type=14, cpp_type=8, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_import_enum', full_name='protobuf_unittest.TestAllTypes.repeated_import_enum', index=47, + number=53, type=14, cpp_type=8, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_string_piece', full_name='protobuf_unittest.TestAllTypes.repeated_string_piece', index=48, + number=54, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002')), + _descriptor.FieldDescriptor( + name='repeated_cord', full_name='protobuf_unittest.TestAllTypes.repeated_cord', index=49, + number=55, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001')), + _descriptor.FieldDescriptor( + name='repeated_lazy_message', full_name='protobuf_unittest.TestAllTypes.repeated_lazy_message', index=50, + number=57, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '(\001')), + _descriptor.FieldDescriptor( + name='default_int32', full_name='protobuf_unittest.TestAllTypes.default_int32', index=51, + number=61, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=41, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_int64', full_name='protobuf_unittest.TestAllTypes.default_int64', index=52, + number=62, type=3, cpp_type=2, label=1, + has_default_value=True, default_value=42, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_uint32', full_name='protobuf_unittest.TestAllTypes.default_uint32', index=53, + number=63, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=43, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_uint64', full_name='protobuf_unittest.TestAllTypes.default_uint64', index=54, + number=64, type=4, cpp_type=4, label=1, + has_default_value=True, default_value=44, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_sint32', full_name='protobuf_unittest.TestAllTypes.default_sint32', index=55, + number=65, type=17, cpp_type=1, label=1, + has_default_value=True, default_value=-45, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_sint64', full_name='protobuf_unittest.TestAllTypes.default_sint64', index=56, + number=66, type=18, cpp_type=2, label=1, + has_default_value=True, default_value=46, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_fixed32', full_name='protobuf_unittest.TestAllTypes.default_fixed32', index=57, + number=67, type=7, cpp_type=3, label=1, + has_default_value=True, default_value=47, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_fixed64', full_name='protobuf_unittest.TestAllTypes.default_fixed64', index=58, + number=68, type=6, cpp_type=4, label=1, + has_default_value=True, default_value=48, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_sfixed32', full_name='protobuf_unittest.TestAllTypes.default_sfixed32', index=59, + number=69, type=15, cpp_type=1, label=1, + has_default_value=True, default_value=49, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_sfixed64', full_name='protobuf_unittest.TestAllTypes.default_sfixed64', index=60, + number=70, type=16, cpp_type=2, label=1, + has_default_value=True, default_value=-50, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_float', full_name='protobuf_unittest.TestAllTypes.default_float', index=61, + number=71, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=51.5, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_double', full_name='protobuf_unittest.TestAllTypes.default_double', index=62, + number=72, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=52000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_bool', full_name='protobuf_unittest.TestAllTypes.default_bool', index=63, + number=73, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_string', full_name='protobuf_unittest.TestAllTypes.default_string', index=64, + number=74, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("hello", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_bytes', full_name='protobuf_unittest.TestAllTypes.default_bytes', index=65, + number=75, type=12, cpp_type=9, label=1, + has_default_value=True, default_value="world", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_nested_enum', full_name='protobuf_unittest.TestAllTypes.default_nested_enum', index=66, + number=81, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=2, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_foreign_enum', full_name='protobuf_unittest.TestAllTypes.default_foreign_enum', index=67, + number=82, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=5, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_import_enum', full_name='protobuf_unittest.TestAllTypes.default_import_enum', index=68, + number=83, type=14, cpp_type=8, label=1, + has_default_value=True, default_value=8, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='default_string_piece', full_name='protobuf_unittest.TestAllTypes.default_string_piece', index=69, + number=84, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("abc", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002')), + _descriptor.FieldDescriptor( + name='default_cord', full_name='protobuf_unittest.TestAllTypes.default_cord', index=70, + number=85, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("123", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001')), + ], + extensions=[ + ], + nested_types=[_TESTALLTYPES_NESTEDMESSAGE, _TESTALLTYPES_OPTIONALGROUP, _TESTALLTYPES_REPEATEDGROUP, ], + enum_types=[ + _TESTALLTYPES_NESTEDENUM, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=93, + serialized_end=3091, +) + + +_TESTDEPRECATEDFIELDS = _descriptor.Descriptor( + name='TestDeprecatedFields', + full_name='protobuf_unittest.TestDeprecatedFields', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='deprecated_int32', full_name='protobuf_unittest.TestDeprecatedFields.deprecated_int32', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\030\001')), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3093, + serialized_end=3145, +) + + +_FOREIGNMESSAGE = _descriptor.Descriptor( + name='ForeignMessage', + full_name='protobuf_unittest.ForeignMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='c', full_name='protobuf_unittest.ForeignMessage.c', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3147, + serialized_end=3174, +) + + +_TESTALLEXTENSIONS = _descriptor.Descriptor( + name='TestAllExtensions', + full_name='protobuf_unittest.TestAllExtensions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(1, 536870912), ], + serialized_start=3176, + serialized_end=3205, +) + + +_OPTIONALGROUP_EXTENSION = _descriptor.Descriptor( + name='OptionalGroup_extension', + full_name='protobuf_unittest.OptionalGroup_extension', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='protobuf_unittest.OptionalGroup_extension.a', index=0, + number=17, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3207, + serialized_end=3243, +) + + +_REPEATEDGROUP_EXTENSION = _descriptor.Descriptor( + name='RepeatedGroup_extension', + full_name='protobuf_unittest.RepeatedGroup_extension', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='protobuf_unittest.RepeatedGroup_extension.a', index=0, + number=47, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3245, + serialized_end=3281, +) + + +_TESTNESTEDEXTENSION = _descriptor.Descriptor( + name='TestNestedExtension', + full_name='protobuf_unittest.TestNestedExtension', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + _descriptor.FieldDescriptor( + name='test', full_name='protobuf_unittest.TestNestedExtension.test', index=0, + number=1002, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("test", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None), + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3283, + serialized_end=3363, +) + + +_TESTREQUIRED = _descriptor.Descriptor( + name='TestRequired', + full_name='protobuf_unittest.TestRequired', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='protobuf_unittest.TestRequired.a', index=0, + number=1, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy2', full_name='protobuf_unittest.TestRequired.dummy2', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='b', full_name='protobuf_unittest.TestRequired.b', index=2, + number=3, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy4', full_name='protobuf_unittest.TestRequired.dummy4', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy5', full_name='protobuf_unittest.TestRequired.dummy5', index=4, + number=5, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy6', full_name='protobuf_unittest.TestRequired.dummy6', index=5, + number=6, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy7', full_name='protobuf_unittest.TestRequired.dummy7', index=6, + number=7, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy8', full_name='protobuf_unittest.TestRequired.dummy8', index=7, + number=8, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy9', full_name='protobuf_unittest.TestRequired.dummy9', index=8, + number=9, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy10', full_name='protobuf_unittest.TestRequired.dummy10', index=9, + number=10, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy11', full_name='protobuf_unittest.TestRequired.dummy11', index=10, + number=11, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy12', full_name='protobuf_unittest.TestRequired.dummy12', index=11, + number=12, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy13', full_name='protobuf_unittest.TestRequired.dummy13', index=12, + number=13, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy14', full_name='protobuf_unittest.TestRequired.dummy14', index=13, + number=14, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy15', full_name='protobuf_unittest.TestRequired.dummy15', index=14, + number=15, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy16', full_name='protobuf_unittest.TestRequired.dummy16', index=15, + number=16, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy17', full_name='protobuf_unittest.TestRequired.dummy17', index=16, + number=17, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy18', full_name='protobuf_unittest.TestRequired.dummy18', index=17, + number=18, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy19', full_name='protobuf_unittest.TestRequired.dummy19', index=18, + number=19, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy20', full_name='protobuf_unittest.TestRequired.dummy20', index=19, + number=20, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy21', full_name='protobuf_unittest.TestRequired.dummy21', index=20, + number=21, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy22', full_name='protobuf_unittest.TestRequired.dummy22', index=21, + number=22, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy23', full_name='protobuf_unittest.TestRequired.dummy23', index=22, + number=23, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy24', full_name='protobuf_unittest.TestRequired.dummy24', index=23, + number=24, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy25', full_name='protobuf_unittest.TestRequired.dummy25', index=24, + number=25, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy26', full_name='protobuf_unittest.TestRequired.dummy26', index=25, + number=26, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy27', full_name='protobuf_unittest.TestRequired.dummy27', index=26, + number=27, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy28', full_name='protobuf_unittest.TestRequired.dummy28', index=27, + number=28, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy29', full_name='protobuf_unittest.TestRequired.dummy29', index=28, + number=29, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy30', full_name='protobuf_unittest.TestRequired.dummy30', index=29, + number=30, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy31', full_name='protobuf_unittest.TestRequired.dummy31', index=30, + number=31, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy32', full_name='protobuf_unittest.TestRequired.dummy32', index=31, + number=32, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='c', full_name='protobuf_unittest.TestRequired.c', index=32, + number=33, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + _descriptor.FieldDescriptor( + name='single', full_name='protobuf_unittest.TestRequired.single', index=0, + number=1000, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='multi', full_name='protobuf_unittest.TestRequired.multi', index=1, + number=1001, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None), + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3366, + serialized_end=4091, +) + + +_TESTREQUIREDFOREIGN = _descriptor.Descriptor( + name='TestRequiredForeign', + full_name='protobuf_unittest.TestRequiredForeign', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='optional_message', full_name='protobuf_unittest.TestRequiredForeign.optional_message', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_message', full_name='protobuf_unittest.TestRequiredForeign.repeated_message', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dummy', full_name='protobuf_unittest.TestRequiredForeign.dummy', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=4094, + serialized_end=4248, +) + + +_TESTFOREIGNNESTED = _descriptor.Descriptor( + name='TestForeignNested', + full_name='protobuf_unittest.TestForeignNested', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='foreign_nested', full_name='protobuf_unittest.TestForeignNested.foreign_nested', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=4250, + serialized_end=4340, +) + + +_TESTEMPTYMESSAGE = _descriptor.Descriptor( + name='TestEmptyMessage', + full_name='protobuf_unittest.TestEmptyMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=4342, + serialized_end=4360, +) + + +_TESTEMPTYMESSAGEWITHEXTENSIONS = _descriptor.Descriptor( + name='TestEmptyMessageWithExtensions', + full_name='protobuf_unittest.TestEmptyMessageWithExtensions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(1, 536870912), ], + serialized_start=4362, + serialized_end=4404, +) + + +_TESTMULTIPLEEXTENSIONRANGES = _descriptor.Descriptor( + name='TestMultipleExtensionRanges', + full_name='protobuf_unittest.TestMultipleExtensionRanges', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(42, 43), (4143, 4244), (65536, 536870912), ], + serialized_start=4406, + serialized_end=4461, +) + + +_TESTREALLYLARGETAGNUMBER = _descriptor.Descriptor( + name='TestReallyLargeTagNumber', + full_name='protobuf_unittest.TestReallyLargeTagNumber', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='protobuf_unittest.TestReallyLargeTagNumber.a', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='bb', full_name='protobuf_unittest.TestReallyLargeTagNumber.bb', index=1, + number=268435455, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=4463, + serialized_end=4515, +) + + +_TESTRECURSIVEMESSAGE = _descriptor.Descriptor( + name='TestRecursiveMessage', + full_name='protobuf_unittest.TestRecursiveMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='protobuf_unittest.TestRecursiveMessage.a', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='i', full_name='protobuf_unittest.TestRecursiveMessage.i', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=4517, + serialized_end=4602, +) + + +_TESTMUTUALRECURSIONA = _descriptor.Descriptor( + name='TestMutualRecursionA', + full_name='protobuf_unittest.TestMutualRecursionA', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='bb', full_name='protobuf_unittest.TestMutualRecursionA.bb', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=4604, + serialized_end=4679, +) + + +_TESTMUTUALRECURSIONB = _descriptor.Descriptor( + name='TestMutualRecursionB', + full_name='protobuf_unittest.TestMutualRecursionB', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='protobuf_unittest.TestMutualRecursionB.a', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_int32', full_name='protobuf_unittest.TestMutualRecursionB.optional_int32', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=4681, + serialized_end=4779, +) + + +_TESTDUPFIELDNUMBER_FOO = _descriptor.Descriptor( + name='Foo', + full_name='protobuf_unittest.TestDupFieldNumber.Foo', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='protobuf_unittest.TestDupFieldNumber.Foo.a', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=4927, + serialized_end=4943, +) + +_TESTDUPFIELDNUMBER_BAR = _descriptor.Descriptor( + name='Bar', + full_name='protobuf_unittest.TestDupFieldNumber.Bar', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='protobuf_unittest.TestDupFieldNumber.Bar.a', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=4945, + serialized_end=4961, +) + +_TESTDUPFIELDNUMBER = _descriptor.Descriptor( + name='TestDupFieldNumber', + full_name='protobuf_unittest.TestDupFieldNumber', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='protobuf_unittest.TestDupFieldNumber.a', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='foo', full_name='protobuf_unittest.TestDupFieldNumber.foo', index=1, + number=2, type=10, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='bar', full_name='protobuf_unittest.TestDupFieldNumber.bar', index=2, + number=3, type=10, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_TESTDUPFIELDNUMBER_FOO, _TESTDUPFIELDNUMBER_BAR, ], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=4782, + serialized_end=4961, +) + + +_TESTEAGERMESSAGE = _descriptor.Descriptor( + name='TestEagerMessage', + full_name='protobuf_unittest.TestEagerMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='sub_message', full_name='protobuf_unittest.TestEagerMessage.sub_message', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '(\000')), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=4963, + serialized_end=5039, +) + + +_TESTLAZYMESSAGE = _descriptor.Descriptor( + name='TestLazyMessage', + full_name='protobuf_unittest.TestLazyMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='sub_message', full_name='protobuf_unittest.TestLazyMessage.sub_message', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '(\001')), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=5041, + serialized_end=5116, +) + + +_TESTNESTEDMESSAGEHASBITS_NESTEDMESSAGE = _descriptor.Descriptor( + name='NestedMessage', + full_name='protobuf_unittest.TestNestedMessageHasBits.NestedMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='nestedmessage_repeated_int32', full_name='protobuf_unittest.TestNestedMessageHasBits.NestedMessage.nestedmessage_repeated_int32', index=0, + number=1, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='nestedmessage_repeated_foreignmessage', full_name='protobuf_unittest.TestNestedMessageHasBits.NestedMessage.nestedmessage_repeated_foreignmessage', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=5240, + serialized_end=5375, +) + +_TESTNESTEDMESSAGEHASBITS = _descriptor.Descriptor( + name='TestNestedMessageHasBits', + full_name='protobuf_unittest.TestNestedMessageHasBits', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='optional_nested_message', full_name='protobuf_unittest.TestNestedMessageHasBits.optional_nested_message', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_TESTNESTEDMESSAGEHASBITS_NESTEDMESSAGE, ], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=5119, + serialized_end=5375, +) + + +_TESTCAMELCASEFIELDNAMES = _descriptor.Descriptor( + name='TestCamelCaseFieldNames', + full_name='protobuf_unittest.TestCamelCaseFieldNames', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='PrimitiveField', full_name='protobuf_unittest.TestCamelCaseFieldNames.PrimitiveField', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='StringField', full_name='protobuf_unittest.TestCamelCaseFieldNames.StringField', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='EnumField', full_name='protobuf_unittest.TestCamelCaseFieldNames.EnumField', index=2, + number=3, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=4, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='MessageField', full_name='protobuf_unittest.TestCamelCaseFieldNames.MessageField', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='StringPieceField', full_name='protobuf_unittest.TestCamelCaseFieldNames.StringPieceField', index=4, + number=5, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002')), + _descriptor.FieldDescriptor( + name='CordField', full_name='protobuf_unittest.TestCamelCaseFieldNames.CordField', index=5, + number=6, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001')), + _descriptor.FieldDescriptor( + name='RepeatedPrimitiveField', full_name='protobuf_unittest.TestCamelCaseFieldNames.RepeatedPrimitiveField', index=6, + number=7, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='RepeatedStringField', full_name='protobuf_unittest.TestCamelCaseFieldNames.RepeatedStringField', index=7, + number=8, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='RepeatedEnumField', full_name='protobuf_unittest.TestCamelCaseFieldNames.RepeatedEnumField', index=8, + number=9, type=14, cpp_type=8, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='RepeatedMessageField', full_name='protobuf_unittest.TestCamelCaseFieldNames.RepeatedMessageField', index=9, + number=10, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='RepeatedStringPieceField', full_name='protobuf_unittest.TestCamelCaseFieldNames.RepeatedStringPieceField', index=10, + number=11, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002')), + _descriptor.FieldDescriptor( + name='RepeatedCordField', full_name='protobuf_unittest.TestCamelCaseFieldNames.RepeatedCordField', index=11, + number=12, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001')), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=5378, + serialized_end=5863, +) + + +_TESTFIELDORDERINGS = _descriptor.Descriptor( + name='TestFieldOrderings', + full_name='protobuf_unittest.TestFieldOrderings', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='my_string', full_name='protobuf_unittest.TestFieldOrderings.my_string', index=0, + number=11, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='my_int', full_name='protobuf_unittest.TestFieldOrderings.my_int', index=1, + number=1, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='my_float', full_name='protobuf_unittest.TestFieldOrderings.my_float', index=2, + number=101, type=2, cpp_type=6, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(2, 11), (12, 101), ], + serialized_start=5865, + serialized_end=5950, +) + + +_TESTEXTREMEDEFAULTVALUES = _descriptor.Descriptor( + name='TestExtremeDefaultValues', + full_name='protobuf_unittest.TestExtremeDefaultValues', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='escaped_bytes', full_name='protobuf_unittest.TestExtremeDefaultValues.escaped_bytes', index=0, + number=1, type=12, cpp_type=9, label=1, + has_default_value=True, default_value="\000\001\007\010\014\n\r\t\013\\\'\"\376", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='large_uint32', full_name='protobuf_unittest.TestExtremeDefaultValues.large_uint32', index=1, + number=2, type=13, cpp_type=3, label=1, + has_default_value=True, default_value=4294967295, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='large_uint64', full_name='protobuf_unittest.TestExtremeDefaultValues.large_uint64', index=2, + number=3, type=4, cpp_type=4, label=1, + has_default_value=True, default_value=18446744073709551615, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='small_int32', full_name='protobuf_unittest.TestExtremeDefaultValues.small_int32', index=3, + number=4, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=-2147483647, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='small_int64', full_name='protobuf_unittest.TestExtremeDefaultValues.small_int64', index=4, + number=5, type=3, cpp_type=2, label=1, + has_default_value=True, default_value=-9223372036854775807, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='really_small_int32', full_name='protobuf_unittest.TestExtremeDefaultValues.really_small_int32', index=5, + number=21, type=5, cpp_type=1, label=1, + has_default_value=True, default_value=-2147483648, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='really_small_int64', full_name='protobuf_unittest.TestExtremeDefaultValues.really_small_int64', index=6, + number=22, type=3, cpp_type=2, label=1, + has_default_value=True, default_value=-9223372036854775808, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='utf8_string', full_name='protobuf_unittest.TestExtremeDefaultValues.utf8_string', index=7, + number=6, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("\341\210\264", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='zero_float', full_name='protobuf_unittest.TestExtremeDefaultValues.zero_float', index=8, + number=7, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='one_float', full_name='protobuf_unittest.TestExtremeDefaultValues.one_float', index=9, + number=8, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='small_float', full_name='protobuf_unittest.TestExtremeDefaultValues.small_float', index=10, + number=9, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=1.5, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='negative_one_float', full_name='protobuf_unittest.TestExtremeDefaultValues.negative_one_float', index=11, + number=10, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=-1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='negative_float', full_name='protobuf_unittest.TestExtremeDefaultValues.negative_float', index=12, + number=11, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=-1.5, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='large_float', full_name='protobuf_unittest.TestExtremeDefaultValues.large_float', index=13, + number=12, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=2e+08, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='small_negative_float', full_name='protobuf_unittest.TestExtremeDefaultValues.small_negative_float', index=14, + number=13, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=-8e-28, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='inf_double', full_name='protobuf_unittest.TestExtremeDefaultValues.inf_double', index=15, + number=14, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=1e10000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='neg_inf_double', full_name='protobuf_unittest.TestExtremeDefaultValues.neg_inf_double', index=16, + number=15, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=-1e10000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='nan_double', full_name='protobuf_unittest.TestExtremeDefaultValues.nan_double', index=17, + number=16, type=1, cpp_type=5, label=1, + has_default_value=True, default_value=(1e10000 * 0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='inf_float', full_name='protobuf_unittest.TestExtremeDefaultValues.inf_float', index=18, + number=17, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=1e10000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='neg_inf_float', full_name='protobuf_unittest.TestExtremeDefaultValues.neg_inf_float', index=19, + number=18, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=-1e10000, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='nan_float', full_name='protobuf_unittest.TestExtremeDefaultValues.nan_float', index=20, + number=19, type=2, cpp_type=6, label=1, + has_default_value=True, default_value=(1e10000 * 0), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cpp_trigraph', full_name='protobuf_unittest.TestExtremeDefaultValues.cpp_trigraph', index=21, + number=20, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("? ? ?? ?? ??? ??/ ??-", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='string_with_zero', full_name='protobuf_unittest.TestExtremeDefaultValues.string_with_zero', index=22, + number=23, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("hel\000lo", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='bytes_with_zero', full_name='protobuf_unittest.TestExtremeDefaultValues.bytes_with_zero', index=23, + number=24, type=12, cpp_type=9, label=1, + has_default_value=True, default_value="wor\000ld", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='string_piece_with_zero', full_name='protobuf_unittest.TestExtremeDefaultValues.string_piece_with_zero', index=24, + number=25, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("ab\000c", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002')), + _descriptor.FieldDescriptor( + name='cord_with_zero', full_name='protobuf_unittest.TestExtremeDefaultValues.cord_with_zero', index=25, + number=26, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("12\0003", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001')), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=5953, + serialized_end=6863, +) + + +_SPARSEENUMMESSAGE = _descriptor.Descriptor( + name='SparseEnumMessage', + full_name='protobuf_unittest.SparseEnumMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='sparse_enum', full_name='protobuf_unittest.SparseEnumMessage.sparse_enum', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=123, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=6865, + serialized_end=6940, +) + + +_ONESTRING = _descriptor.Descriptor( + name='OneString', + full_name='protobuf_unittest.OneString', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='data', full_name='protobuf_unittest.OneString.data', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=6942, + serialized_end=6967, +) + + +_MORESTRING = _descriptor.Descriptor( + name='MoreString', + full_name='protobuf_unittest.MoreString', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='data', full_name='protobuf_unittest.MoreString.data', index=0, + number=1, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=6969, + serialized_end=6995, +) + + +_ONEBYTES = _descriptor.Descriptor( + name='OneBytes', + full_name='protobuf_unittest.OneBytes', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='data', full_name='protobuf_unittest.OneBytes.data', index=0, + number=1, type=12, cpp_type=9, label=1, + has_default_value=False, default_value="", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=6997, + serialized_end=7021, +) + + +_MOREBYTES = _descriptor.Descriptor( + name='MoreBytes', + full_name='protobuf_unittest.MoreBytes', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='data', full_name='protobuf_unittest.MoreBytes.data', index=0, + number=1, type=12, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=7023, + serialized_end=7048, +) + + +_TESTPACKEDTYPES = _descriptor.Descriptor( + name='TestPackedTypes', + full_name='protobuf_unittest.TestPackedTypes', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='packed_int32', full_name='protobuf_unittest.TestPackedTypes.packed_int32', index=0, + number=90, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_int64', full_name='protobuf_unittest.TestPackedTypes.packed_int64', index=1, + number=91, type=3, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_uint32', full_name='protobuf_unittest.TestPackedTypes.packed_uint32', index=2, + number=92, type=13, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_uint64', full_name='protobuf_unittest.TestPackedTypes.packed_uint64', index=3, + number=93, type=4, cpp_type=4, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_sint32', full_name='protobuf_unittest.TestPackedTypes.packed_sint32', index=4, + number=94, type=17, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_sint64', full_name='protobuf_unittest.TestPackedTypes.packed_sint64', index=5, + number=95, type=18, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_fixed32', full_name='protobuf_unittest.TestPackedTypes.packed_fixed32', index=6, + number=96, type=7, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_fixed64', full_name='protobuf_unittest.TestPackedTypes.packed_fixed64', index=7, + number=97, type=6, cpp_type=4, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_sfixed32', full_name='protobuf_unittest.TestPackedTypes.packed_sfixed32', index=8, + number=98, type=15, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_sfixed64', full_name='protobuf_unittest.TestPackedTypes.packed_sfixed64', index=9, + number=99, type=16, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_float', full_name='protobuf_unittest.TestPackedTypes.packed_float', index=10, + number=100, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_double', full_name='protobuf_unittest.TestPackedTypes.packed_double', index=11, + number=101, type=1, cpp_type=5, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_bool', full_name='protobuf_unittest.TestPackedTypes.packed_bool', index=12, + number=102, type=8, cpp_type=7, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + _descriptor.FieldDescriptor( + name='packed_enum', full_name='protobuf_unittest.TestPackedTypes.packed_enum', index=13, + number=103, type=14, cpp_type=8, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=7051, + serialized_end=7477, +) + + +_TESTUNPACKEDTYPES = _descriptor.Descriptor( + name='TestUnpackedTypes', + full_name='protobuf_unittest.TestUnpackedTypes', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='unpacked_int32', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_int32', index=0, + number=90, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_int64', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_int64', index=1, + number=91, type=3, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_uint32', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_uint32', index=2, + number=92, type=13, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_uint64', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_uint64', index=3, + number=93, type=4, cpp_type=4, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_sint32', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_sint32', index=4, + number=94, type=17, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_sint64', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_sint64', index=5, + number=95, type=18, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_fixed32', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_fixed32', index=6, + number=96, type=7, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_fixed64', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_fixed64', index=7, + number=97, type=6, cpp_type=4, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_sfixed32', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_sfixed32', index=8, + number=98, type=15, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_sfixed64', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_sfixed64', index=9, + number=99, type=16, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_float', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_float', index=10, + number=100, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_double', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_double', index=11, + number=101, type=1, cpp_type=5, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_bool', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_bool', index=12, + number=102, type=8, cpp_type=7, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + _descriptor.FieldDescriptor( + name='unpacked_enum', full_name='protobuf_unittest.TestUnpackedTypes.unpacked_enum', index=13, + number=103, type=14, cpp_type=8, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000')), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=7480, + serialized_end=7936, +) + + +_TESTPACKEDEXTENSIONS = _descriptor.Descriptor( + name='TestPackedExtensions', + full_name='protobuf_unittest.TestPackedExtensions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(1, 536870912), ], + serialized_start=7938, + serialized_end=7970, +) + + +_TESTDYNAMICEXTENSIONS_DYNAMICMESSAGETYPE = _descriptor.Descriptor( + name='DynamicMessageType', + full_name='protobuf_unittest.TestDynamicExtensions.DynamicMessageType', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='dynamic_field', full_name='protobuf_unittest.TestDynamicExtensions.DynamicMessageType.dynamic_field', index=0, + number=2100, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=8393, + serialized_end=8437, +) + +_TESTDYNAMICEXTENSIONS = _descriptor.Descriptor( + name='TestDynamicExtensions', + full_name='protobuf_unittest.TestDynamicExtensions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='scalar_extension', full_name='protobuf_unittest.TestDynamicExtensions.scalar_extension', index=0, + number=2000, type=7, cpp_type=3, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='enum_extension', full_name='protobuf_unittest.TestDynamicExtensions.enum_extension', index=1, + number=2001, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=4, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dynamic_enum_extension', full_name='protobuf_unittest.TestDynamicExtensions.dynamic_enum_extension', index=2, + number=2002, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=2200, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='message_extension', full_name='protobuf_unittest.TestDynamicExtensions.message_extension', index=3, + number=2003, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='dynamic_message_extension', full_name='protobuf_unittest.TestDynamicExtensions.dynamic_message_extension', index=4, + number=2004, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_extension', full_name='protobuf_unittest.TestDynamicExtensions.repeated_extension', index=5, + number=2005, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='packed_extension', full_name='protobuf_unittest.TestDynamicExtensions.packed_extension', index=6, + number=2006, type=17, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=_descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001')), + ], + extensions=[ + ], + nested_types=[_TESTDYNAMICEXTENSIONS_DYNAMICMESSAGETYPE, ], + enum_types=[ + _TESTDYNAMICEXTENSIONS_DYNAMICENUMTYPE, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=7973, + serialized_end=8510, +) + + +_TESTREPEATEDSCALARDIFFERENTTAGSIZES = _descriptor.Descriptor( + name='TestRepeatedScalarDifferentTagSizes', + full_name='protobuf_unittest.TestRepeatedScalarDifferentTagSizes', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='repeated_fixed32', full_name='protobuf_unittest.TestRepeatedScalarDifferentTagSizes.repeated_fixed32', index=0, + number=12, type=7, cpp_type=3, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_int32', full_name='protobuf_unittest.TestRepeatedScalarDifferentTagSizes.repeated_int32', index=1, + number=13, type=5, cpp_type=1, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_fixed64', full_name='protobuf_unittest.TestRepeatedScalarDifferentTagSizes.repeated_fixed64', index=2, + number=2046, type=6, cpp_type=4, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_int64', full_name='protobuf_unittest.TestRepeatedScalarDifferentTagSizes.repeated_int64', index=3, + number=2047, type=3, cpp_type=2, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_float', full_name='protobuf_unittest.TestRepeatedScalarDifferentTagSizes.repeated_float', index=4, + number=262142, type=2, cpp_type=6, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_uint64', full_name='protobuf_unittest.TestRepeatedScalarDifferentTagSizes.repeated_uint64', index=5, + number=262143, type=4, cpp_type=4, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=8513, + serialized_end=8705, +) + + +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR_GROUP1 = _descriptor.Descriptor( + name='Group1', + full_name='protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.Group1', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='field1', full_name='protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.Group1.field1', index=0, + number=11, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=9498, + serialized_end=9555, +) + +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR_GROUP2 = _descriptor.Descriptor( + name='Group2', + full_name='protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.Group2', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='field1', full_name='protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.Group2.field1', index=0, + number=21, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=9557, + serialized_end=9614, +) + +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR = _descriptor.Descriptor( + name='RepeatedFieldsGenerator', + full_name='protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='field1', full_name='protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.field1', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='field2', full_name='protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.field2', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='field3', full_name='protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.field3', index=2, + number=3, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='group1', full_name='protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.group1', index=3, + number=10, type=10, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='group2', full_name='protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.group2', index=4, + number=20, type=10, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ext1', full_name='protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.ext1', index=5, + number=1000, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ext2', full_name='protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.ext2', index=6, + number=1001, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR_GROUP1, _TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR_GROUP2, ], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=9060, + serialized_end=9614, +) + +_TESTPARSINGMERGE_OPTIONALGROUP = _descriptor.Descriptor( + name='OptionalGroup', + full_name='protobuf_unittest.TestParsingMerge.OptionalGroup', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='optional_group_all_types', full_name='protobuf_unittest.TestParsingMerge.OptionalGroup.optional_group_all_types', index=0, + number=11, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=9616, + serialized_end=9698, +) + +_TESTPARSINGMERGE_REPEATEDGROUP = _descriptor.Descriptor( + name='RepeatedGroup', + full_name='protobuf_unittest.TestParsingMerge.RepeatedGroup', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='repeated_group_all_types', full_name='protobuf_unittest.TestParsingMerge.RepeatedGroup.repeated_group_all_types', index=0, + number=21, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=9700, + serialized_end=9782, +) + +_TESTPARSINGMERGE = _descriptor.Descriptor( + name='TestParsingMerge', + full_name='protobuf_unittest.TestParsingMerge', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='required_all_types', full_name='protobuf_unittest.TestParsingMerge.required_all_types', index=0, + number=1, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optional_all_types', full_name='protobuf_unittest.TestParsingMerge.optional_all_types', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_all_types', full_name='protobuf_unittest.TestParsingMerge.repeated_all_types', index=2, + number=3, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='optionalgroup', full_name='protobuf_unittest.TestParsingMerge.optionalgroup', index=3, + number=10, type=10, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeatedgroup', full_name='protobuf_unittest.TestParsingMerge.repeatedgroup', index=4, + number=20, type=10, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + _descriptor.FieldDescriptor( + name='optional_ext', full_name='protobuf_unittest.TestParsingMerge.optional_ext', index=0, + number=1000, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='repeated_ext', full_name='protobuf_unittest.TestParsingMerge.repeated_ext', index=1, + number=1001, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=True, extension_scope=None, + options=None), + ], + nested_types=[_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR, _TESTPARSINGMERGE_OPTIONALGROUP, _TESTPARSINGMERGE_REPEATEDGROUP, ], + enum_types=[ + ], + options=None, + is_extendable=True, + extension_ranges=[(1000, 536870912), ], + serialized_start=8708, + serialized_end=9979, +) + + +_TESTCOMMENTINJECTIONMESSAGE = _descriptor.Descriptor( + name='TestCommentInjectionMessage', + full_name='protobuf_unittest.TestCommentInjectionMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='a', full_name='protobuf_unittest.TestCommentInjectionMessage.a', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=True, default_value=unicode("*/ <- Neither should this.", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=9981, + serialized_end=10049, +) + + +_FOOREQUEST = _descriptor.Descriptor( + name='FooRequest', + full_name='protobuf_unittest.FooRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=10051, + serialized_end=10063, +) + + +_FOORESPONSE = _descriptor.Descriptor( + name='FooResponse', + full_name='protobuf_unittest.FooResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=10065, + serialized_end=10078, +) + + +_FOOCLIENTMESSAGE = _descriptor.Descriptor( + name='FooClientMessage', + full_name='protobuf_unittest.FooClientMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=10080, + serialized_end=10098, +) + + +_FOOSERVERMESSAGE = _descriptor.Descriptor( + name='FooServerMessage', + full_name='protobuf_unittest.FooServerMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=10100, + serialized_end=10118, +) + + +_BARREQUEST = _descriptor.Descriptor( + name='BarRequest', + full_name='protobuf_unittest.BarRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=10120, + serialized_end=10132, +) + + +_BARRESPONSE = _descriptor.Descriptor( + name='BarResponse', + full_name='protobuf_unittest.BarResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=10134, + serialized_end=10147, +) + +_TESTALLTYPES_NESTEDMESSAGE.containing_type = _TESTALLTYPES; +_TESTALLTYPES_OPTIONALGROUP.containing_type = _TESTALLTYPES; +_TESTALLTYPES_REPEATEDGROUP.containing_type = _TESTALLTYPES; +_TESTALLTYPES.fields_by_name['optionalgroup'].message_type = _TESTALLTYPES_OPTIONALGROUP +_TESTALLTYPES.fields_by_name['optional_nested_message'].message_type = _TESTALLTYPES_NESTEDMESSAGE +_TESTALLTYPES.fields_by_name['optional_foreign_message'].message_type = _FOREIGNMESSAGE +_TESTALLTYPES.fields_by_name['optional_import_message'].message_type = google.protobuf.unittest_import_pb2._IMPORTMESSAGE +_TESTALLTYPES.fields_by_name['optional_nested_enum'].enum_type = _TESTALLTYPES_NESTEDENUM +_TESTALLTYPES.fields_by_name['optional_foreign_enum'].enum_type = _FOREIGNENUM +_TESTALLTYPES.fields_by_name['optional_import_enum'].enum_type = google.protobuf.unittest_import_pb2._IMPORTENUM +_TESTALLTYPES.fields_by_name['optional_public_import_message'].message_type = google.protobuf.unittest_import_public_pb2._PUBLICIMPORTMESSAGE +_TESTALLTYPES.fields_by_name['optional_lazy_message'].message_type = _TESTALLTYPES_NESTEDMESSAGE +_TESTALLTYPES.fields_by_name['repeatedgroup'].message_type = _TESTALLTYPES_REPEATEDGROUP +_TESTALLTYPES.fields_by_name['repeated_nested_message'].message_type = _TESTALLTYPES_NESTEDMESSAGE +_TESTALLTYPES.fields_by_name['repeated_foreign_message'].message_type = _FOREIGNMESSAGE +_TESTALLTYPES.fields_by_name['repeated_import_message'].message_type = google.protobuf.unittest_import_pb2._IMPORTMESSAGE +_TESTALLTYPES.fields_by_name['repeated_nested_enum'].enum_type = _TESTALLTYPES_NESTEDENUM +_TESTALLTYPES.fields_by_name['repeated_foreign_enum'].enum_type = _FOREIGNENUM +_TESTALLTYPES.fields_by_name['repeated_import_enum'].enum_type = google.protobuf.unittest_import_pb2._IMPORTENUM +_TESTALLTYPES.fields_by_name['repeated_lazy_message'].message_type = _TESTALLTYPES_NESTEDMESSAGE +_TESTALLTYPES.fields_by_name['default_nested_enum'].enum_type = _TESTALLTYPES_NESTEDENUM +_TESTALLTYPES.fields_by_name['default_foreign_enum'].enum_type = _FOREIGNENUM +_TESTALLTYPES.fields_by_name['default_import_enum'].enum_type = google.protobuf.unittest_import_pb2._IMPORTENUM +_TESTALLTYPES_NESTEDENUM.containing_type = _TESTALLTYPES; +_TESTREQUIREDFOREIGN.fields_by_name['optional_message'].message_type = _TESTREQUIRED +_TESTREQUIREDFOREIGN.fields_by_name['repeated_message'].message_type = _TESTREQUIRED +_TESTFOREIGNNESTED.fields_by_name['foreign_nested'].message_type = _TESTALLTYPES_NESTEDMESSAGE +_TESTRECURSIVEMESSAGE.fields_by_name['a'].message_type = _TESTRECURSIVEMESSAGE +_TESTMUTUALRECURSIONA.fields_by_name['bb'].message_type = _TESTMUTUALRECURSIONB +_TESTMUTUALRECURSIONB.fields_by_name['a'].message_type = _TESTMUTUALRECURSIONA +_TESTDUPFIELDNUMBER_FOO.containing_type = _TESTDUPFIELDNUMBER; +_TESTDUPFIELDNUMBER_BAR.containing_type = _TESTDUPFIELDNUMBER; +_TESTDUPFIELDNUMBER.fields_by_name['foo'].message_type = _TESTDUPFIELDNUMBER_FOO +_TESTDUPFIELDNUMBER.fields_by_name['bar'].message_type = _TESTDUPFIELDNUMBER_BAR +_TESTEAGERMESSAGE.fields_by_name['sub_message'].message_type = _TESTALLTYPES +_TESTLAZYMESSAGE.fields_by_name['sub_message'].message_type = _TESTALLTYPES +_TESTNESTEDMESSAGEHASBITS_NESTEDMESSAGE.fields_by_name['nestedmessage_repeated_foreignmessage'].message_type = _FOREIGNMESSAGE +_TESTNESTEDMESSAGEHASBITS_NESTEDMESSAGE.containing_type = _TESTNESTEDMESSAGEHASBITS; +_TESTNESTEDMESSAGEHASBITS.fields_by_name['optional_nested_message'].message_type = _TESTNESTEDMESSAGEHASBITS_NESTEDMESSAGE +_TESTCAMELCASEFIELDNAMES.fields_by_name['EnumField'].enum_type = _FOREIGNENUM +_TESTCAMELCASEFIELDNAMES.fields_by_name['MessageField'].message_type = _FOREIGNMESSAGE +_TESTCAMELCASEFIELDNAMES.fields_by_name['RepeatedEnumField'].enum_type = _FOREIGNENUM +_TESTCAMELCASEFIELDNAMES.fields_by_name['RepeatedMessageField'].message_type = _FOREIGNMESSAGE +_SPARSEENUMMESSAGE.fields_by_name['sparse_enum'].enum_type = _TESTSPARSEENUM +_TESTPACKEDTYPES.fields_by_name['packed_enum'].enum_type = _FOREIGNENUM +_TESTUNPACKEDTYPES.fields_by_name['unpacked_enum'].enum_type = _FOREIGNENUM +_TESTDYNAMICEXTENSIONS_DYNAMICMESSAGETYPE.containing_type = _TESTDYNAMICEXTENSIONS; +_TESTDYNAMICEXTENSIONS.fields_by_name['enum_extension'].enum_type = _FOREIGNENUM +_TESTDYNAMICEXTENSIONS.fields_by_name['dynamic_enum_extension'].enum_type = _TESTDYNAMICEXTENSIONS_DYNAMICENUMTYPE +_TESTDYNAMICEXTENSIONS.fields_by_name['message_extension'].message_type = _FOREIGNMESSAGE +_TESTDYNAMICEXTENSIONS.fields_by_name['dynamic_message_extension'].message_type = _TESTDYNAMICEXTENSIONS_DYNAMICMESSAGETYPE +_TESTDYNAMICEXTENSIONS_DYNAMICENUMTYPE.containing_type = _TESTDYNAMICEXTENSIONS; +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR_GROUP1.fields_by_name['field1'].message_type = _TESTALLTYPES +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR_GROUP1.containing_type = _TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR; +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR_GROUP2.fields_by_name['field1'].message_type = _TESTALLTYPES +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR_GROUP2.containing_type = _TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR; +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR.fields_by_name['field1'].message_type = _TESTALLTYPES +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR.fields_by_name['field2'].message_type = _TESTALLTYPES +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR.fields_by_name['field3'].message_type = _TESTALLTYPES +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR.fields_by_name['group1'].message_type = _TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR_GROUP1 +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR.fields_by_name['group2'].message_type = _TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR_GROUP2 +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR.fields_by_name['ext1'].message_type = _TESTALLTYPES +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR.fields_by_name['ext2'].message_type = _TESTALLTYPES +_TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR.containing_type = _TESTPARSINGMERGE; +_TESTPARSINGMERGE_OPTIONALGROUP.fields_by_name['optional_group_all_types'].message_type = _TESTALLTYPES +_TESTPARSINGMERGE_OPTIONALGROUP.containing_type = _TESTPARSINGMERGE; +_TESTPARSINGMERGE_REPEATEDGROUP.fields_by_name['repeated_group_all_types'].message_type = _TESTALLTYPES +_TESTPARSINGMERGE_REPEATEDGROUP.containing_type = _TESTPARSINGMERGE; +_TESTPARSINGMERGE.fields_by_name['required_all_types'].message_type = _TESTALLTYPES +_TESTPARSINGMERGE.fields_by_name['optional_all_types'].message_type = _TESTALLTYPES +_TESTPARSINGMERGE.fields_by_name['repeated_all_types'].message_type = _TESTALLTYPES +_TESTPARSINGMERGE.fields_by_name['optionalgroup'].message_type = _TESTPARSINGMERGE_OPTIONALGROUP +_TESTPARSINGMERGE.fields_by_name['repeatedgroup'].message_type = _TESTPARSINGMERGE_REPEATEDGROUP +DESCRIPTOR.message_types_by_name['TestAllTypes'] = _TESTALLTYPES +DESCRIPTOR.message_types_by_name['TestDeprecatedFields'] = _TESTDEPRECATEDFIELDS +DESCRIPTOR.message_types_by_name['ForeignMessage'] = _FOREIGNMESSAGE +DESCRIPTOR.message_types_by_name['TestAllExtensions'] = _TESTALLEXTENSIONS +DESCRIPTOR.message_types_by_name['OptionalGroup_extension'] = _OPTIONALGROUP_EXTENSION +DESCRIPTOR.message_types_by_name['RepeatedGroup_extension'] = _REPEATEDGROUP_EXTENSION +DESCRIPTOR.message_types_by_name['TestNestedExtension'] = _TESTNESTEDEXTENSION +DESCRIPTOR.message_types_by_name['TestRequired'] = _TESTREQUIRED +DESCRIPTOR.message_types_by_name['TestRequiredForeign'] = _TESTREQUIREDFOREIGN +DESCRIPTOR.message_types_by_name['TestForeignNested'] = _TESTFOREIGNNESTED +DESCRIPTOR.message_types_by_name['TestEmptyMessage'] = _TESTEMPTYMESSAGE +DESCRIPTOR.message_types_by_name['TestEmptyMessageWithExtensions'] = _TESTEMPTYMESSAGEWITHEXTENSIONS +DESCRIPTOR.message_types_by_name['TestMultipleExtensionRanges'] = _TESTMULTIPLEEXTENSIONRANGES +DESCRIPTOR.message_types_by_name['TestReallyLargeTagNumber'] = _TESTREALLYLARGETAGNUMBER +DESCRIPTOR.message_types_by_name['TestRecursiveMessage'] = _TESTRECURSIVEMESSAGE +DESCRIPTOR.message_types_by_name['TestMutualRecursionA'] = _TESTMUTUALRECURSIONA +DESCRIPTOR.message_types_by_name['TestMutualRecursionB'] = _TESTMUTUALRECURSIONB +DESCRIPTOR.message_types_by_name['TestDupFieldNumber'] = _TESTDUPFIELDNUMBER +DESCRIPTOR.message_types_by_name['TestEagerMessage'] = _TESTEAGERMESSAGE +DESCRIPTOR.message_types_by_name['TestLazyMessage'] = _TESTLAZYMESSAGE +DESCRIPTOR.message_types_by_name['TestNestedMessageHasBits'] = _TESTNESTEDMESSAGEHASBITS +DESCRIPTOR.message_types_by_name['TestCamelCaseFieldNames'] = _TESTCAMELCASEFIELDNAMES +DESCRIPTOR.message_types_by_name['TestFieldOrderings'] = _TESTFIELDORDERINGS +DESCRIPTOR.message_types_by_name['TestExtremeDefaultValues'] = _TESTEXTREMEDEFAULTVALUES +DESCRIPTOR.message_types_by_name['SparseEnumMessage'] = _SPARSEENUMMESSAGE +DESCRIPTOR.message_types_by_name['OneString'] = _ONESTRING +DESCRIPTOR.message_types_by_name['MoreString'] = _MORESTRING +DESCRIPTOR.message_types_by_name['OneBytes'] = _ONEBYTES +DESCRIPTOR.message_types_by_name['MoreBytes'] = _MOREBYTES +DESCRIPTOR.message_types_by_name['TestPackedTypes'] = _TESTPACKEDTYPES +DESCRIPTOR.message_types_by_name['TestUnpackedTypes'] = _TESTUNPACKEDTYPES +DESCRIPTOR.message_types_by_name['TestPackedExtensions'] = _TESTPACKEDEXTENSIONS +DESCRIPTOR.message_types_by_name['TestDynamicExtensions'] = _TESTDYNAMICEXTENSIONS +DESCRIPTOR.message_types_by_name['TestRepeatedScalarDifferentTagSizes'] = _TESTREPEATEDSCALARDIFFERENTTAGSIZES +DESCRIPTOR.message_types_by_name['TestParsingMerge'] = _TESTPARSINGMERGE +DESCRIPTOR.message_types_by_name['TestCommentInjectionMessage'] = _TESTCOMMENTINJECTIONMESSAGE +DESCRIPTOR.message_types_by_name['FooRequest'] = _FOOREQUEST +DESCRIPTOR.message_types_by_name['FooResponse'] = _FOORESPONSE +DESCRIPTOR.message_types_by_name['FooClientMessage'] = _FOOCLIENTMESSAGE +DESCRIPTOR.message_types_by_name['FooServerMessage'] = _FOOSERVERMESSAGE +DESCRIPTOR.message_types_by_name['BarRequest'] = _BARREQUEST +DESCRIPTOR.message_types_by_name['BarResponse'] = _BARRESPONSE + +class TestAllTypes(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class NestedMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTALLTYPES_NESTEDMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestAllTypes.NestedMessage) + + class OptionalGroup(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTALLTYPES_OPTIONALGROUP + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestAllTypes.OptionalGroup) + + class RepeatedGroup(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTALLTYPES_REPEATEDGROUP + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestAllTypes.RepeatedGroup) + DESCRIPTOR = _TESTALLTYPES + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestAllTypes) + +class TestDeprecatedFields(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTDEPRECATEDFIELDS + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestDeprecatedFields) + +class ForeignMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _FOREIGNMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.ForeignMessage) + +class TestAllExtensions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTALLEXTENSIONS + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestAllExtensions) + +class OptionalGroup_extension(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _OPTIONALGROUP_EXTENSION + + # @@protoc_insertion_point(class_scope:protobuf_unittest.OptionalGroup_extension) + +class RepeatedGroup_extension(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _REPEATEDGROUP_EXTENSION + + # @@protoc_insertion_point(class_scope:protobuf_unittest.RepeatedGroup_extension) + +class TestNestedExtension(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTNESTEDEXTENSION + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestNestedExtension) + +class TestRequired(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTREQUIRED + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestRequired) + +class TestRequiredForeign(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTREQUIREDFOREIGN + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestRequiredForeign) + +class TestForeignNested(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTFOREIGNNESTED + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestForeignNested) + +class TestEmptyMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTEMPTYMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestEmptyMessage) + +class TestEmptyMessageWithExtensions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTEMPTYMESSAGEWITHEXTENSIONS + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestEmptyMessageWithExtensions) + +class TestMultipleExtensionRanges(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTMULTIPLEEXTENSIONRANGES + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestMultipleExtensionRanges) + +class TestReallyLargeTagNumber(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTREALLYLARGETAGNUMBER + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestReallyLargeTagNumber) + +class TestRecursiveMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTRECURSIVEMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestRecursiveMessage) + +class TestMutualRecursionA(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTMUTUALRECURSIONA + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestMutualRecursionA) + +class TestMutualRecursionB(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTMUTUALRECURSIONB + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestMutualRecursionB) + +class TestDupFieldNumber(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class Foo(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTDUPFIELDNUMBER_FOO + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestDupFieldNumber.Foo) + + class Bar(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTDUPFIELDNUMBER_BAR + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestDupFieldNumber.Bar) + DESCRIPTOR = _TESTDUPFIELDNUMBER + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestDupFieldNumber) + +class TestEagerMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTEAGERMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestEagerMessage) + +class TestLazyMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTLAZYMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestLazyMessage) + +class TestNestedMessageHasBits(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class NestedMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTNESTEDMESSAGEHASBITS_NESTEDMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestNestedMessageHasBits.NestedMessage) + DESCRIPTOR = _TESTNESTEDMESSAGEHASBITS + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestNestedMessageHasBits) + +class TestCamelCaseFieldNames(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTCAMELCASEFIELDNAMES + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestCamelCaseFieldNames) + +class TestFieldOrderings(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTFIELDORDERINGS + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestFieldOrderings) + +class TestExtremeDefaultValues(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTEXTREMEDEFAULTVALUES + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestExtremeDefaultValues) + +class SparseEnumMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _SPARSEENUMMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.SparseEnumMessage) + +class OneString(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _ONESTRING + + # @@protoc_insertion_point(class_scope:protobuf_unittest.OneString) + +class MoreString(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _MORESTRING + + # @@protoc_insertion_point(class_scope:protobuf_unittest.MoreString) + +class OneBytes(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _ONEBYTES + + # @@protoc_insertion_point(class_scope:protobuf_unittest.OneBytes) + +class MoreBytes(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _MOREBYTES + + # @@protoc_insertion_point(class_scope:protobuf_unittest.MoreBytes) + +class TestPackedTypes(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTPACKEDTYPES + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestPackedTypes) + +class TestUnpackedTypes(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTUNPACKEDTYPES + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestUnpackedTypes) + +class TestPackedExtensions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTPACKEDEXTENSIONS + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestPackedExtensions) + +class TestDynamicExtensions(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class DynamicMessageType(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTDYNAMICEXTENSIONS_DYNAMICMESSAGETYPE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestDynamicExtensions.DynamicMessageType) + DESCRIPTOR = _TESTDYNAMICEXTENSIONS + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestDynamicExtensions) + +class TestRepeatedScalarDifferentTagSizes(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTREPEATEDSCALARDIFFERENTTAGSIZES + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestRepeatedScalarDifferentTagSizes) + +class TestParsingMerge(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class RepeatedFieldsGenerator(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + + class Group1(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR_GROUP1 + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.Group1) + + class Group2(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR_GROUP2 + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator.Group2) + DESCRIPTOR = _TESTPARSINGMERGE_REPEATEDFIELDSGENERATOR + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestParsingMerge.RepeatedFieldsGenerator) + + class OptionalGroup(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTPARSINGMERGE_OPTIONALGROUP + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestParsingMerge.OptionalGroup) + + class RepeatedGroup(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTPARSINGMERGE_REPEATEDGROUP + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestParsingMerge.RepeatedGroup) + DESCRIPTOR = _TESTPARSINGMERGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestParsingMerge) + +class TestCommentInjectionMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TESTCOMMENTINJECTIONMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.TestCommentInjectionMessage) + +class FooRequest(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _FOOREQUEST + + # @@protoc_insertion_point(class_scope:protobuf_unittest.FooRequest) + +class FooResponse(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _FOORESPONSE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.FooResponse) + +class FooClientMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _FOOCLIENTMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.FooClientMessage) + +class FooServerMessage(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _FOOSERVERMESSAGE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.FooServerMessage) + +class BarRequest(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _BARREQUEST + + # @@protoc_insertion_point(class_scope:protobuf_unittest.BarRequest) + +class BarResponse(_message.Message): + __metaclass__ = _reflection.GeneratedProtocolMessageType + DESCRIPTOR = _BARRESPONSE + + # @@protoc_insertion_point(class_scope:protobuf_unittest.BarResponse) + +TestAllExtensions.RegisterExtension(optional_int32_extension) +TestAllExtensions.RegisterExtension(optional_int64_extension) +TestAllExtensions.RegisterExtension(optional_uint32_extension) +TestAllExtensions.RegisterExtension(optional_uint64_extension) +TestAllExtensions.RegisterExtension(optional_sint32_extension) +TestAllExtensions.RegisterExtension(optional_sint64_extension) +TestAllExtensions.RegisterExtension(optional_fixed32_extension) +TestAllExtensions.RegisterExtension(optional_fixed64_extension) +TestAllExtensions.RegisterExtension(optional_sfixed32_extension) +TestAllExtensions.RegisterExtension(optional_sfixed64_extension) +TestAllExtensions.RegisterExtension(optional_float_extension) +TestAllExtensions.RegisterExtension(optional_double_extension) +TestAllExtensions.RegisterExtension(optional_bool_extension) +TestAllExtensions.RegisterExtension(optional_string_extension) +TestAllExtensions.RegisterExtension(optional_bytes_extension) +optionalgroup_extension.message_type = _OPTIONALGROUP_EXTENSION +TestAllExtensions.RegisterExtension(optionalgroup_extension) +optional_nested_message_extension.message_type = _TESTALLTYPES_NESTEDMESSAGE +TestAllExtensions.RegisterExtension(optional_nested_message_extension) +optional_foreign_message_extension.message_type = _FOREIGNMESSAGE +TestAllExtensions.RegisterExtension(optional_foreign_message_extension) +optional_import_message_extension.message_type = google.protobuf.unittest_import_pb2._IMPORTMESSAGE +TestAllExtensions.RegisterExtension(optional_import_message_extension) +optional_nested_enum_extension.enum_type = _TESTALLTYPES_NESTEDENUM +TestAllExtensions.RegisterExtension(optional_nested_enum_extension) +optional_foreign_enum_extension.enum_type = _FOREIGNENUM +TestAllExtensions.RegisterExtension(optional_foreign_enum_extension) +optional_import_enum_extension.enum_type = google.protobuf.unittest_import_pb2._IMPORTENUM +TestAllExtensions.RegisterExtension(optional_import_enum_extension) +TestAllExtensions.RegisterExtension(optional_string_piece_extension) +TestAllExtensions.RegisterExtension(optional_cord_extension) +optional_public_import_message_extension.message_type = google.protobuf.unittest_import_public_pb2._PUBLICIMPORTMESSAGE +TestAllExtensions.RegisterExtension(optional_public_import_message_extension) +optional_lazy_message_extension.message_type = _TESTALLTYPES_NESTEDMESSAGE +TestAllExtensions.RegisterExtension(optional_lazy_message_extension) +TestAllExtensions.RegisterExtension(repeated_int32_extension) +TestAllExtensions.RegisterExtension(repeated_int64_extension) +TestAllExtensions.RegisterExtension(repeated_uint32_extension) +TestAllExtensions.RegisterExtension(repeated_uint64_extension) +TestAllExtensions.RegisterExtension(repeated_sint32_extension) +TestAllExtensions.RegisterExtension(repeated_sint64_extension) +TestAllExtensions.RegisterExtension(repeated_fixed32_extension) +TestAllExtensions.RegisterExtension(repeated_fixed64_extension) +TestAllExtensions.RegisterExtension(repeated_sfixed32_extension) +TestAllExtensions.RegisterExtension(repeated_sfixed64_extension) +TestAllExtensions.RegisterExtension(repeated_float_extension) +TestAllExtensions.RegisterExtension(repeated_double_extension) +TestAllExtensions.RegisterExtension(repeated_bool_extension) +TestAllExtensions.RegisterExtension(repeated_string_extension) +TestAllExtensions.RegisterExtension(repeated_bytes_extension) +repeatedgroup_extension.message_type = _REPEATEDGROUP_EXTENSION +TestAllExtensions.RegisterExtension(repeatedgroup_extension) +repeated_nested_message_extension.message_type = _TESTALLTYPES_NESTEDMESSAGE +TestAllExtensions.RegisterExtension(repeated_nested_message_extension) +repeated_foreign_message_extension.message_type = _FOREIGNMESSAGE +TestAllExtensions.RegisterExtension(repeated_foreign_message_extension) +repeated_import_message_extension.message_type = google.protobuf.unittest_import_pb2._IMPORTMESSAGE +TestAllExtensions.RegisterExtension(repeated_import_message_extension) +repeated_nested_enum_extension.enum_type = _TESTALLTYPES_NESTEDENUM +TestAllExtensions.RegisterExtension(repeated_nested_enum_extension) +repeated_foreign_enum_extension.enum_type = _FOREIGNENUM +TestAllExtensions.RegisterExtension(repeated_foreign_enum_extension) +repeated_import_enum_extension.enum_type = google.protobuf.unittest_import_pb2._IMPORTENUM +TestAllExtensions.RegisterExtension(repeated_import_enum_extension) +TestAllExtensions.RegisterExtension(repeated_string_piece_extension) +TestAllExtensions.RegisterExtension(repeated_cord_extension) +repeated_lazy_message_extension.message_type = _TESTALLTYPES_NESTEDMESSAGE +TestAllExtensions.RegisterExtension(repeated_lazy_message_extension) +TestAllExtensions.RegisterExtension(default_int32_extension) +TestAllExtensions.RegisterExtension(default_int64_extension) +TestAllExtensions.RegisterExtension(default_uint32_extension) +TestAllExtensions.RegisterExtension(default_uint64_extension) +TestAllExtensions.RegisterExtension(default_sint32_extension) +TestAllExtensions.RegisterExtension(default_sint64_extension) +TestAllExtensions.RegisterExtension(default_fixed32_extension) +TestAllExtensions.RegisterExtension(default_fixed64_extension) +TestAllExtensions.RegisterExtension(default_sfixed32_extension) +TestAllExtensions.RegisterExtension(default_sfixed64_extension) +TestAllExtensions.RegisterExtension(default_float_extension) +TestAllExtensions.RegisterExtension(default_double_extension) +TestAllExtensions.RegisterExtension(default_bool_extension) +TestAllExtensions.RegisterExtension(default_string_extension) +TestAllExtensions.RegisterExtension(default_bytes_extension) +default_nested_enum_extension.enum_type = _TESTALLTYPES_NESTEDENUM +TestAllExtensions.RegisterExtension(default_nested_enum_extension) +default_foreign_enum_extension.enum_type = _FOREIGNENUM +TestAllExtensions.RegisterExtension(default_foreign_enum_extension) +default_import_enum_extension.enum_type = google.protobuf.unittest_import_pb2._IMPORTENUM +TestAllExtensions.RegisterExtension(default_import_enum_extension) +TestAllExtensions.RegisterExtension(default_string_piece_extension) +TestAllExtensions.RegisterExtension(default_cord_extension) +TestFieldOrderings.RegisterExtension(my_extension_string) +TestFieldOrderings.RegisterExtension(my_extension_int) +TestPackedExtensions.RegisterExtension(packed_int32_extension) +TestPackedExtensions.RegisterExtension(packed_int64_extension) +TestPackedExtensions.RegisterExtension(packed_uint32_extension) +TestPackedExtensions.RegisterExtension(packed_uint64_extension) +TestPackedExtensions.RegisterExtension(packed_sint32_extension) +TestPackedExtensions.RegisterExtension(packed_sint64_extension) +TestPackedExtensions.RegisterExtension(packed_fixed32_extension) +TestPackedExtensions.RegisterExtension(packed_fixed64_extension) +TestPackedExtensions.RegisterExtension(packed_sfixed32_extension) +TestPackedExtensions.RegisterExtension(packed_sfixed64_extension) +TestPackedExtensions.RegisterExtension(packed_float_extension) +TestPackedExtensions.RegisterExtension(packed_double_extension) +TestPackedExtensions.RegisterExtension(packed_bool_extension) +packed_enum_extension.enum_type = _FOREIGNENUM +TestPackedExtensions.RegisterExtension(packed_enum_extension) +TestAllExtensions.RegisterExtension(_TESTNESTEDEXTENSION.extensions_by_name['test']) +_TESTREQUIRED.extensions_by_name['single'].message_type = _TESTREQUIRED +TestAllExtensions.RegisterExtension(_TESTREQUIRED.extensions_by_name['single']) +_TESTREQUIRED.extensions_by_name['multi'].message_type = _TESTREQUIRED +TestAllExtensions.RegisterExtension(_TESTREQUIRED.extensions_by_name['multi']) +_TESTPARSINGMERGE.extensions_by_name['optional_ext'].message_type = _TESTALLTYPES +TestParsingMerge.RegisterExtension(_TESTPARSINGMERGE.extensions_by_name['optional_ext']) +_TESTPARSINGMERGE.extensions_by_name['repeated_ext'].message_type = _TESTALLTYPES +TestParsingMerge.RegisterExtension(_TESTPARSINGMERGE.extensions_by_name['repeated_ext']) + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), 'B\rUnittestProtoH\001\200\001\001\210\001\001\220\001\001') +_TESTENUMWITHDUPVALUE.has_options = True +_TESTENUMWITHDUPVALUE._options = _descriptor._ParseOptions(descriptor_pb2.EnumOptions(), '\020\001') +optional_string_piece_extension.has_options = True +optional_string_piece_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002') +optional_cord_extension.has_options = True +optional_cord_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001') +optional_lazy_message_extension.has_options = True +optional_lazy_message_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '(\001') +repeated_string_piece_extension.has_options = True +repeated_string_piece_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002') +repeated_cord_extension.has_options = True +repeated_cord_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001') +repeated_lazy_message_extension.has_options = True +repeated_lazy_message_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '(\001') +default_string_piece_extension.has_options = True +default_string_piece_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002') +default_cord_extension.has_options = True +default_cord_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001') +packed_int32_extension.has_options = True +packed_int32_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_int64_extension.has_options = True +packed_int64_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_uint32_extension.has_options = True +packed_uint32_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_uint64_extension.has_options = True +packed_uint64_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_sint32_extension.has_options = True +packed_sint32_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_sint64_extension.has_options = True +packed_sint64_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_fixed32_extension.has_options = True +packed_fixed32_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_fixed64_extension.has_options = True +packed_fixed64_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_sfixed32_extension.has_options = True +packed_sfixed32_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_sfixed64_extension.has_options = True +packed_sfixed64_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_float_extension.has_options = True +packed_float_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_double_extension.has_options = True +packed_double_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_bool_extension.has_options = True +packed_bool_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +packed_enum_extension.has_options = True +packed_enum_extension._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTALLTYPES.fields_by_name['optional_string_piece'].has_options = True +_TESTALLTYPES.fields_by_name['optional_string_piece']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002') +_TESTALLTYPES.fields_by_name['optional_cord'].has_options = True +_TESTALLTYPES.fields_by_name['optional_cord']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001') +_TESTALLTYPES.fields_by_name['optional_lazy_message'].has_options = True +_TESTALLTYPES.fields_by_name['optional_lazy_message']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '(\001') +_TESTALLTYPES.fields_by_name['repeated_string_piece'].has_options = True +_TESTALLTYPES.fields_by_name['repeated_string_piece']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002') +_TESTALLTYPES.fields_by_name['repeated_cord'].has_options = True +_TESTALLTYPES.fields_by_name['repeated_cord']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001') +_TESTALLTYPES.fields_by_name['repeated_lazy_message'].has_options = True +_TESTALLTYPES.fields_by_name['repeated_lazy_message']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '(\001') +_TESTALLTYPES.fields_by_name['default_string_piece'].has_options = True +_TESTALLTYPES.fields_by_name['default_string_piece']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002') +_TESTALLTYPES.fields_by_name['default_cord'].has_options = True +_TESTALLTYPES.fields_by_name['default_cord']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001') +_TESTDEPRECATEDFIELDS.fields_by_name['deprecated_int32'].has_options = True +_TESTDEPRECATEDFIELDS.fields_by_name['deprecated_int32']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\030\001') +_TESTEAGERMESSAGE.fields_by_name['sub_message'].has_options = True +_TESTEAGERMESSAGE.fields_by_name['sub_message']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '(\000') +_TESTLAZYMESSAGE.fields_by_name['sub_message'].has_options = True +_TESTLAZYMESSAGE.fields_by_name['sub_message']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '(\001') +_TESTCAMELCASEFIELDNAMES.fields_by_name['StringPieceField'].has_options = True +_TESTCAMELCASEFIELDNAMES.fields_by_name['StringPieceField']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002') +_TESTCAMELCASEFIELDNAMES.fields_by_name['CordField'].has_options = True +_TESTCAMELCASEFIELDNAMES.fields_by_name['CordField']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001') +_TESTCAMELCASEFIELDNAMES.fields_by_name['RepeatedStringPieceField'].has_options = True +_TESTCAMELCASEFIELDNAMES.fields_by_name['RepeatedStringPieceField']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002') +_TESTCAMELCASEFIELDNAMES.fields_by_name['RepeatedCordField'].has_options = True +_TESTCAMELCASEFIELDNAMES.fields_by_name['RepeatedCordField']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001') +_TESTEXTREMEDEFAULTVALUES.fields_by_name['string_piece_with_zero'].has_options = True +_TESTEXTREMEDEFAULTVALUES.fields_by_name['string_piece_with_zero']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\002') +_TESTEXTREMEDEFAULTVALUES.fields_by_name['cord_with_zero'].has_options = True +_TESTEXTREMEDEFAULTVALUES.fields_by_name['cord_with_zero']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\010\001') +_TESTPACKEDTYPES.fields_by_name['packed_int32'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_int32']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_int64'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_int64']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_uint32'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_uint32']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_uint64'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_uint64']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_sint32'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_sint32']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_sint64'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_sint64']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_fixed32'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_fixed32']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_fixed64'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_fixed64']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_sfixed32'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_sfixed32']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_sfixed64'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_sfixed64']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_float'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_float']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_double'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_double']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_bool'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_bool']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTPACKEDTYPES.fields_by_name['packed_enum'].has_options = True +_TESTPACKEDTYPES.fields_by_name['packed_enum']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_int32'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_int32']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_int64'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_int64']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_uint32'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_uint32']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_uint64'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_uint64']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_sint32'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_sint32']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_sint64'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_sint64']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_fixed32'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_fixed32']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_fixed64'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_fixed64']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_sfixed32'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_sfixed32']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_sfixed64'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_sfixed64']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_float'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_float']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_double'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_double']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_bool'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_bool']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTUNPACKEDTYPES.fields_by_name['unpacked_enum'].has_options = True +_TESTUNPACKEDTYPES.fields_by_name['unpacked_enum']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\000') +_TESTDYNAMICEXTENSIONS.fields_by_name['packed_extension'].has_options = True +_TESTDYNAMICEXTENSIONS.fields_by_name['packed_extension']._options = _descriptor._ParseOptions(descriptor_pb2.FieldOptions(), '\020\001') + +_TESTSERVICE = _descriptor.ServiceDescriptor( + name='TestService', + full_name='protobuf_unittest.TestService', + file=DESCRIPTOR, + index=0, + options=None, + serialized_start=10433, + serialized_end=10586, + methods=[ + _descriptor.MethodDescriptor( + name='Foo', + full_name='protobuf_unittest.TestService.Foo', + index=0, + containing_service=None, + input_type=_FOOREQUEST, + output_type=_FOORESPONSE, + options=None, + ), + _descriptor.MethodDescriptor( + name='Bar', + full_name='protobuf_unittest.TestService.Bar', + index=1, + containing_service=None, + input_type=_BARREQUEST, + output_type=_BARRESPONSE, + options=None, + ), +]) + +class TestService(_service.Service): + __metaclass__ = service_reflection.GeneratedServiceType + DESCRIPTOR = _TESTSERVICE +class TestService_Stub(TestService): + __metaclass__ = service_reflection.GeneratedServiceStubType + DESCRIPTOR = _TESTSERVICE + +# @@protoc_insertion_point(module_scope) diff --git a/code/push/igetui/__init__.py b/code/push/igetui/__init__.py new file mode 100644 index 0000000..4365a5b --- /dev/null +++ b/code/push/igetui/__init__.py @@ -0,0 +1,2 @@ +__author__ = 'wei' +__all__=["igt_message", "igt_target"] diff --git a/code/push/igetui/igt_message.py b/code/push/igetui/igt_message.py new file mode 100644 index 0000000..096d0db --- /dev/null +++ b/code/push/igetui/igt_message.py @@ -0,0 +1,24 @@ +__author__ = 'wei' + +from push.igetui.template.igt_base_template import * +class IGtMessage: + def __init__(self): + self.isOffline = False + self.offlineExpireTime = 0 + self.data = BaseTemplate() + +class IGtSingleMessage(IGtMessage) : + def __init__(self): + IGtMessage.__init__(self) + +class IGtListMessage(IGtMessage): + def __init__(self): + IGtMessage.__init__(self) + +class IGtAppMessage(IGtMessage): + def __init__(self): + IGtMessage.__init__(self) + self.appIdList = [] + self.phoneTypeList = [] + self.provinceList = [] + self.tagList = [] diff --git a/code/push/igetui/igt_target.py b/code/push/igetui/igt_target.py new file mode 100644 index 0000000..032fa0e --- /dev/null +++ b/code/push/igetui/igt_target.py @@ -0,0 +1,6 @@ +__author__ = 'wei' + +class Target : + def __init__(self): + self.appId = "" + self.clientId = "" \ No newline at end of file diff --git a/code/push/igetui/template/__init__.py b/code/push/igetui/template/__init__.py new file mode 100644 index 0000000..6f0b00f --- /dev/null +++ b/code/push/igetui/template/__init__.py @@ -0,0 +1,2 @@ +__author__ = 'wei' +__all__=["igt_base_template", "igt_link_template", "igt_notification_template", "igt_transmission_template" ] \ No newline at end of file diff --git a/code/push/igetui/template/igt_base_template.py b/code/push/igetui/template/igt_base_template.py new file mode 100644 index 0000000..7ddfa6d --- /dev/null +++ b/code/push/igetui/template/igt_base_template.py @@ -0,0 +1,103 @@ +#coding: utf-8 + +from push.protobuf import * +import json + + +class BaseTemplate: + def __init__(self): + self.appKey = "" + self.appId = "" + self.pushInfo = None + + def getTransparent(self): + transparent = gt_req_pb2.Transparent() + transparent.id = "" + transparent.action = "pushmessage" + transparent.taskId = "" + transparent.appKey = self.appKey + transparent.appId = self.appId + transparent.messageId = "" + transparent.pushInfo.CopyFrom(self.getPushInfo()) + actionChains = self.getActionChains() + for actionChain in actionChains: + tmp = transparent.actionChain.add() + tmp.CopyFrom(actionChain) + return transparent + + def getActionChains(self): + return [] + + def getPushInfo(self): + if self.pushInfo is None: + self.pushInfo = gt_req_pb2.PushInfo() + self.pushInfo.message = "" + self.pushInfo.actionKey = "" + self.pushInfo.sound = "" + self.pushInfo.badge = "" + return self.pushInfo + + def setPushInfo(self, actionLocKey, badge, message, sound, payload, locKey, locArgs, launchImage): + self.pushInfo = gt_req_pb2.PushInfo() + self.pushInfo.actionLocKey = actionLocKey + self.pushInfo.badge = str(badge) + self.pushInfo.message = message.decode("utf-8") + self.pushInfo.sound = sound + self.pushInfo.payload = payload + self.pushInfo.locKey = locKey + self.pushInfo.locArgs = locArgs + self.pushInfo.launchImage = launchImage + + isValidate = self.validatePayload(locKey, locArgs, message, actionLocKey, launchImage, str(badge), sound, payload) + if isValidate is False: + payloadLen = self.validatePayloadLength(locKey, locArgs, message, actionLocKey, launchImage, str(badge), sound, payload) + raise Exception("PushInfo length over limit: " + str(payloadLen) + ". Allowed: 256.") + + + def processPayload(self, locKey, locArgs, message, actionLocKey, launchImage, badge, sound, payload): + map = {} + apnsMap = {} + alertMap = {} + + if sound is not None and len(sound) > 0: + apnsMap["sound"] = sound + else: + apnsMap["sound"] = "default" + if launchImage is not None and len(launchImage) > 0: + alertMap["launch-image"] = launchImage + if locKey is not None and len(locKey) > 0: + alertMap["loc-key"] = locKey + if locArgs is not None and len(locArgs) > 0: + alertMap["loc-args"] = locArgs.split(",") + elif message is not None and len(message) > 0: + alertMap["body"] = message + + if actionLocKey is not None and len(actionLocKey) > 0: + alertMap["action-loc-key"] = actionLocKey + + apnsMap["badge"] = self.toInt(badge, 0) + + if payload is not None and len(payload) > 0: + map["payload"] = payload + + map["aps"] = apnsMap + apnsMap["alert"] = alertMap + return map + + def validatePayload(self, locKey, locArgs, message, actionLocKey, launchImage, badge, sound, payload): + map = self.processPayload(locKey, locArgs, message, actionLocKey, launchImage, badge, sound, payload) + jsonData = json.dumps(map, separators=(',', ':'), ensure_ascii=False) + if len(jsonData)>256: + return False + return True + + def validatePayloadLength(self, locKey, locArgs, message, actionLocKey, launchImage, badge, sound, payload): + map = self.processPayload(locKey, locArgs, message, actionLocKey, launchImage, badge, sound, payload) + jsonData = json.dumps(map, separators=(',', ':'), ensure_ascii=False) + return len(jsonData) + + def toInt(self, strr, defaultValue): + if strr is None or strr == "": + return defaultValue + return int(strr) + diff --git a/code/push/igetui/template/igt_link_template.py b/code/push/igetui/template/igt_link_template.py new file mode 100644 index 0000000..3f859de --- /dev/null +++ b/code/push/igetui/template/igt_link_template.py @@ -0,0 +1,59 @@ +__author__ = 'wei' + +from push.protobuf import * +import igt_base_template + +class LinkTemplate(igt_base_template.BaseTemplate): + def __init__(self): + igt_base_template.BaseTemplate.__init__(self) + self.text = "" + self.title = "" + self.logo = "" + self.logoURL = "" + self.url = "" + self.isRing = True + self.isVibrate = True + self.isClearable = True + self.pushType = "NotifyMsg" + + def getActionChains(self): + #set actionchain + actionChain1 = gt_req_pb2.ActionChain() + actionChain1.actionId = 1 + actionChain1.type = gt_req_pb2.ActionChain.Goto + actionChain1.next = 10000 + + #start up app + actionChain2 = gt_req_pb2.ActionChain() + actionChain2.actionId = 10000 + actionChain2.type = gt_req_pb2.ActionChain.notification + actionChain2.title = self.title + actionChain2.text = self.text + actionChain2.logo = self.logo + actionChain2.logoURL = self.logoURL + actionChain2.ring = self.isRing + actionChain2.clearable = self.isClearable + actionChain2.buzz = self.isVibrate + actionChain2.next = 10010 + + #goto + actionChain3 = gt_req_pb2.ActionChain() + actionChain3.actionId = 10010 + actionChain3.type = gt_req_pb2.ActionChain.Goto + actionChain3.next = 10030 + + #start web + actionChain4 = gt_req_pb2.ActionChain() + actionChain4.actionId = 10030 + actionChain4.type = gt_req_pb2.ActionChain.startweb + actionChain4.url = self.url + actionChain4.next = 100 + + #end + actionChain5 = gt_req_pb2.ActionChain() + actionChain5.actionId = 100 + actionChain5.type = gt_req_pb2.ActionChain.eoa + + actionChains = [actionChain1, actionChain2, actionChain3, actionChain4, actionChain5] + + return actionChains diff --git a/code/push/igetui/template/igt_notification_template.py b/code/push/igetui/template/igt_notification_template.py new file mode 100644 index 0000000..4f2919c --- /dev/null +++ b/code/push/igetui/template/igt_notification_template.py @@ -0,0 +1,69 @@ +__author__ = 'wei' + +from push.protobuf import * +import igt_base_template + +class NotificationTemplate(igt_base_template.BaseTemplate): + def __init__(self): + igt_base_template.BaseTemplate.__init__(self) + self.text = "" + self.title = "" + self.logo = "" + self.logoURL = "" + self.transmissionType = 0 + self.transmissionContent = "" + self.isRing = True + self.isVibrate = True + self.isClearable = True + self.pushType = "NotifyMsg" + + def getActionChains(self): + #set actionchain + actionChain1 = gt_req_pb2.ActionChain() + actionChain1.actionId = 1 + actionChain1.type = gt_req_pb2.ActionChain.Goto + actionChain1.next = 10000 + + #notification + actionChain2 = gt_req_pb2.ActionChain() + actionChain2.actionId = 10000 + actionChain2.type = gt_req_pb2.ActionChain.notification + actionChain2.title = self.title + actionChain2.text = self.text + actionChain2.logo = self.logo + actionChain2.logoURL = self.logoURL + actionChain2.ring = self.isRing + actionChain2.clearable = self.isClearable + actionChain2.buzz = self.isVibrate + actionChain2.next = 10010 + + #goto + actionChain3 = gt_req_pb2.ActionChain() + actionChain3.actionId = 10010 + actionChain3.type = gt_req_pb2.ActionChain.Goto + actionChain3.next = 10030 + + #appStartUp + appStartUp = gt_req_pb2.AppStartUp() + appStartUp.android = "" + appStartUp.symbia = "" + appStartUp.ios = "" + + #start web + actionChain4 = gt_req_pb2.ActionChain() + actionChain4.actionId = 10030 + actionChain4.type = gt_req_pb2.ActionChain.startapp + actionChain4.appid = ""; + actionChain4.autostart = (True if self.transmissionType == 1 else False) + actionChain4.appstartupid.CopyFrom(appStartUp) + actionChain4.failedAction = 100 + actionChain4.next = 100 + + #end + actionChain5 = gt_req_pb2.ActionChain() + actionChain5.actionId = 100 + actionChain5.type = gt_req_pb2.ActionChain.eoa + + actionChains = [actionChain1, actionChain2, actionChain3, actionChain4, actionChain5] + + return actionChains diff --git a/code/push/igetui/template/igt_notypopload_template.py b/code/push/igetui/template/igt_notypopload_template.py new file mode 100644 index 0000000..53b5778 --- /dev/null +++ b/code/push/igetui/template/igt_notypopload_template.py @@ -0,0 +1,92 @@ +__author__ = 'Kevin' + +from push.protobuf import * +import igt_base_template + +class NotyPopLoadTemplate(igt_base_template.BaseTemplate): + def __init__(self): + igt_base_template.BaseTemplate.__init__(self) + self.notyIcon = "" + self.logoUrl = "" + self.notyTitle = "" + self.notyContent = "" + self.isRing = True + self.isVibrate = True + self.isClearable = True + self.popTitle = "" + self.popContent = "" + self.popImage = "" + self.popButton1 = "" + self.popButton2 = "" + self.loadIcon = "" + self.loadTitle = "" + self.loadUrl = "" + self.transmissionType = 0 + self.transmissionContent = "" + self.isAutoInstall = False + self.isActive = False + self.pushType = "NotyPopLoadMsg" + + def getActionChains(self): + #set actionChain + actionChain1 = gt_req_pb2.ActionChain() + actionChain1.actionId = 1 + actionChain1.type = gt_req_pb2.ActionChain.Goto + actionChain1.next = 10000 + + #notification + actionChain2 = gt_req_pb2.ActionChain() + actionChain2.actionId = 10000 + actionChain2.type = gt_req_pb2.ActionChain.notification + actionChain2.title = self.notyTitle + actionChain2.text = self.notyContent + actionChain2.logo = self.notyIcon + actionChain2.logoURL = self.logoUrl + actionChain2.ring = self.isRing + actionChain2.clearable = self.isClearable + actionChain2.buzz = self.isVibrate + actionChain2.next = 10010 + + actionChain3 = gt_req_pb2.ActionChain() + actionChain3.actionId = 10010 + actionChain3.type = gt_req_pb2.ActionChain.Goto + actionChain3.next = 10020 + + actionChain4 = gt_req_pb2.ActionChain() + button1 = actionChain4.buttons.add() + button1.text = self.popButton1 + button1.next = 10040 + button2 = actionChain4.buttons.add() + button2.text = self.popButton2 + button2.next = 100 + + actionChain4.actionId = 10020 + actionChain4.type = gt_req_pb2.ActionChain.popup + actionChain4.title = self.popTitle + actionChain4.text = self.popContent + actionChain4.img = self.popImage + actionChain4.next = 6 + + + appStartUp = gt_req_pb2.AppStartUp() + appStartUp.android = "" + appStartUp.symbia = "" + appStartUp.ios = "" + actionChain5 = gt_req_pb2.ActionChain() + actionChain5.actionId = 10040 + actionChain5.type = gt_req_pb2.ActionChain.appdownload + actionChain5.name = self.loadTitle + actionChain5.url = self.loadUrl + actionChain5.logo = self.loadIcon + actionChain5.autoInstall = self.isAutoInstall + actionChain5.autostart = self.isActive + actionChain5.appstartupid.MergeFrom(appStartUp) + actionChain5.next = 6 + + #end + actionChain6 = gt_req_pb2.ActionChain() + actionChain6.actionId = 100 + actionChain6.type = gt_req_pb2.ActionChain.eoa + + actionChains = [actionChain1, actionChain2, actionChain3, actionChain4, actionChain5, actionChain6] + return actionChains diff --git a/code/push/igetui/template/igt_transmission_template.py b/code/push/igetui/template/igt_transmission_template.py new file mode 100644 index 0000000..d67a97c --- /dev/null +++ b/code/push/igetui/template/igt_transmission_template.py @@ -0,0 +1,46 @@ +__author__ = 'wei' + +from push.protobuf import * +import igt_base_template + + +class TransmissionTemplate(igt_base_template.BaseTemplate): + def __init__(self): + igt_base_template.BaseTemplate.__init__(self) + self.transmissionType = 0 + self.transmissionContent = "" + self.pushType = "TransmissionMsg" + + def getActionChains(self): + + + #set actionChain + actionChain1 = gt_req_pb2.ActionChain() + actionChain1.actionId = 1; + actionChain1.type = gt_req_pb2.ActionChain.Goto + actionChain1.next = 10030 + + #appStartUp + appStartUp = gt_req_pb2.AppStartUp() + appStartUp.android = "" + appStartUp.symbia = "" + appStartUp.ios = "" + + #start up app + actionChain2 = gt_req_pb2.ActionChain() + actionChain2.actionId = 10030 + actionChain2.type = gt_req_pb2.ActionChain.startapp + actionChain2.appid = ""; + actionChain2.autostart = (True if self.transmissionType == 1 else False) + actionChain2.appstartupid.CopyFrom(appStartUp) + actionChain2.failedAction = 100 + actionChain2.next = 100 + + #end + actionChain3 = gt_req_pb2.ActionChain() + actionChain3.actionId = 100 + actionChain3.type = gt_req_pb2.ActionChain.eoa + + actionChains = [actionChain1, actionChain2, actionChain3] + return actionChains + diff --git a/code/push/igt_push.py b/code/push/igt_push.py new file mode 100644 index 0000000..92f053b --- /dev/null +++ b/code/push/igt_push.py @@ -0,0 +1,163 @@ +# -*- coding: utf-8 -*- +__author__ = 'wei' + +import hashlib +import time +import urllib, urllib2, json +import base64 +import os + + +class IGeTui: + def __init__(self, host, appKey, masterSecret): + self.host = host + self.appKey = appKey + self.masterSecret = masterSecret + + def connect(self): + timenow = self.getCurrentTime() + sign = self.getSign(self.appKey, timenow, self.masterSecret) + params = {} + params['action'] = 'connect' + params['appkey'] = self.appKey + params['timeStamp'] = timenow + params['sign'] = sign + + rep = self.httpPost(params) + + if 'success' == (rep['result']): + return True + + print rep + raise Exception(str(rep) + "appKey or masterSecret is auth failed.") + return False + + def pushMessageToSingle(self, message, target): + params = {} + params['action'] = "pushMessageToSingleAction" + params['appkey'] = self.appKey + transparent = message.data.getTransparent() + params['clientData'] = base64.encodestring(transparent.SerializeToString()) + params['transmissionContent'] = message.data.transmissionContent + params['isOffline'] = message.isOffline + params['offlineExpireTime'] = message.offlineExpireTime + params['appId'] = target.appId + params['clientId'] = target.clientId + params['type'] = 2 #default is message + params['pushType'] = message.data.pushType + return self.httpPostJson(params) + + def pushMessageToApp(self, message): + params = {} + params['action'] = "pushMessageToAppAction" + params['appkey'] = self.appKey + + transparent = message.data.getTransparent() + params['clientData'] = base64.encodestring(transparent.SerializeToString()) + params['transmissionContent'] = message.data.transmissionContent + params['isOffline'] = message.isOffline + params['offlineExpireTime'] = message.offlineExpireTime + params['appIdList'] = message.appIdList + params['phoneTypeList'] = message.phoneTypeList + params['provinceList'] = message.provinceList + params['type'] = 2 # default is message + params['pushType'] = message.data.pushType + params['tagList'] = message.tagList + + return self.httpPostJson(params) + + def pushMessageToList(self, contentId, targets): + params = {} + params['action'] = 'pushMessageToListAction' + params['appkey'] = self.appKey + params['contentId'] = contentId + needDetails = os.getenv("needDetails","false") + params['needDetails'] = needDetails + targetList = [] + for target in targets: + appId = target.appId + clientId = target.clientId + target = {"appId": appId, "clientId": clientId} + targetList.append(target) + + params['targetList'] = targetList + params['type'] = 2 + return self.httpPostJson(params) + + def stop(self, contentId): + params = {} + params['action'] = 'stopTaskAction' + params['appkey'] = self.appKey + params['contentId'] = contentId + + ret = self.httpPostJson(params) + if ret["result"]=='ok': + return True + return False + + def getClientIdStatus(self, appId, clientId): + params = {} + params['action'] = 'getClientIdStatusAction' + params['appkey'] = self.appKey + params['appId'] = appId + params['clientId'] = clientId + + return self.httpPostJson(params) + + def getContentId(self, message): + params = {} + params['action'] = "getContentIdAction" + params['appkey'] = self.appKey + transparent = message.data.getTransparent() + params['clientData'] = base64.encodestring(transparent.SerializeToString()) + params['transmissionContent'] = message.data.transmissionContent + params["isOffline"] = message.isOffline + params["offlineExpireTime"] = message.offlineExpireTime + params["pushType"] = message.data.pushType + ret = self.httpPostJson(params) + + return ret['contentId'] if ret['result'] == 'ok' else ' ' + + def cancelContentId(self, contentId): + params = {} + params['action'] = 'cancleContentIdAction' + params['contentId'] = contentId + ret = self.httpPostJson() + return True if ret['result'] == 'ok' else False + + def getCurrentTime(self): + return (int)(time.time() * 1000) + + def getSign(self, appKey, timeStamp, masterSecret): + rawValue = appKey + str(timeStamp) + masterSecret + return hashlib.md5(rawValue.encode()).hexdigest() + + def httpPostJson(self, params): + params['version'] = '3.0.0.0' + ret = self.httpPost(params) + if ret is not None and "sign_error" == ret["result"]: + self.connect() + ret = self.httpPost(params) + return ret + + def httpPost(self, params): + #如果通过代理访问我们接口,需要自行配置代理,示例如下: + #opener = urllib2.build_opener(urllib2.ProxyHandler({'http':'192.168.1.108:808'}), urllib2.HTTPHandler(debuglevel=1)) + #urllib2.install_opener(opener) + data_json = json.dumps(params) + req = urllib2.Request(self.host, data_json) + retry_time_limit = 3 + isFail = True + tryTime = 0 + while isFail and tryTime < retry_time_limit: + try: + res_stream = urllib2.urlopen(req, timeout=60) + isFail = False + except: + isFail = True + tryTime += 1 + print("try " + str(tryTime) + " time failed, time out.") + + page_str = res_stream.read() + page_dict = eval(page_str) + return page_dict diff --git a/code/push/protobuf/__init__.py b/code/push/protobuf/__init__.py new file mode 100644 index 0000000..c8c481d --- /dev/null +++ b/code/push/protobuf/__init__.py @@ -0,0 +1,2 @@ +__author__ = 'wei' +__all__=["gt_req_pb2" ] \ No newline at end of file diff --git a/code/push/protobuf/gt_req_pb2.py b/code/push/protobuf/gt_req_pb2.py new file mode 100644 index 0000000..4549212 --- /dev/null +++ b/code/push/protobuf/gt_req_pb2.py @@ -0,0 +1,1925 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! + +from push.google.protobuf import descriptor +from push.google.protobuf import message +from push.google.protobuf import reflection +from push.google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + + + +DESCRIPTOR = descriptor.FileDescriptor( + name='gt_req.proto', + package='', + serialized_pb='\n\x0cgt_req.proto\"H\n\x06GtAuth\x12\x0c\n\x04sign\x18\x01 \x02(\t\x12\x0e\n\x06\x61ppkey\x18\x02 \x02(\t\x12\x11\n\ttimestamp\x18\x03 \x02(\x03\x12\r\n\x05seqId\x18\x04 \x01(\t\"\xdc\x01\n\x0cGtAuthResult\x12\x0c\n\x04\x63ode\x18\x01 \x02(\x05\x12\x17\n\x0fredirectAddress\x18\x02 \x01(\t\x12\r\n\x05seqId\x18\x03 \x01(\t\x12\x0c\n\x04info\x18\x04 \x01(\t\"\x87\x01\n\x10GtAuthResultCode\x12\r\n\tsuccessed\x10\x00\x12\x11\n\rfailed_noSign\x10\x01\x12\x13\n\x0f\x66\x61iled_noAppkey\x10\x02\x12\x16\n\x12\x66\x61iled_noTimestamp\x10\x03\x12\x16\n\x12\x66\x61iled_AuthIllegal\x10\x04\x12\x0c\n\x08redirect\x10\x05\"/\n\x0bReqServList\x12\r\n\x05seqId\x18\x01 \x01(\t\x12\x11\n\ttimestamp\x18\x03 \x02(\x03\"|\n\x11ReqServListResult\x12\x0c\n\x04\x63ode\x18\x01 \x02(\x05\x12\x0c\n\x04host\x18\x02 \x03(\t\x12\r\n\x05seqId\x18\x03 \x01(\t\"<\n\x15ReqServHostResultCode\x12\r\n\tsuccessed\x10\x00\x12\n\n\x06\x66\x61iled\x10\x01\x12\x08\n\x04\x62usy\x10\x02\".\n\x0ePushListResult\x12\x1c\n\x07results\x18\x01 \x03(\x0b\x32\x0b.PushResult\"\xad\x02\n\nPushResult\x12\'\n\x06result\x18\x01 \x02(\x0e\x32\x17.PushResult.EPushResult\x12\x0e\n\x06taskId\x18\x02 \x02(\t\x12\x11\n\tmessageId\x18\x03 \x02(\t\x12\r\n\x05seqId\x18\x04 \x02(\t\x12\x0e\n\x06target\x18\x05 \x02(\t\x12\x0c\n\x04info\x18\x06 \x01(\t\x12\x0f\n\x07traceId\x18\x07 \x01(\t\"\x94\x01\n\x0b\x45PushResult\x12\x14\n\x10successed_online\x10\x00\x12\x15\n\x11successed_offline\x10\x01\x12\x14\n\x10successed_ignore\x10\x02\x12\n\n\x06\x66\x61iled\x10\x03\x12\x08\n\x04\x62usy\x10\x04\x12\x16\n\x12success_startBatch\x10\x05\x12\x14\n\x10success_endBatch\x10\x06\"Z\n\x13PushOSSingleMessage\x12\r\n\x05seqId\x18\x01 \x02(\t\x12\x1b\n\x07message\x18\x02 \x02(\x0b\x32\n.OSMessage\x12\x17\n\x06target\x18\x03 \x02(\x0b\x32\x07.Target\"\\\n\x14PushMMPSingleMessage\x12\r\n\x05seqId\x18\x01 \x02(\t\x12\x1c\n\x07message\x18\x02 \x02(\x0b\x32\x0b.MMPMessage\x12\x17\n\x06target\x18\x03 \x02(\x0b\x32\x07.Target\"T\n\x11StartMMPBatchTask\x12\x1c\n\x07message\x18\x01 \x02(\x0b\x32\x0b.MMPMessage\x12\x12\n\x06\x65xpire\x18\x02 \x02(\x03:\x02\x37\x32\x12\r\n\x05seqId\x18\x03 \x01(\t\"C\n\x10StartOSBatchTask\x12\x1b\n\x07message\x18\x01 \x02(\x0b\x32\n.OSMessage\x12\x12\n\x06\x65xpire\x18\x02 \x02(\x03:\x02\x37\x32\"J\n\x0fPushListMessage\x12\r\n\x05seqId\x18\x01 \x02(\t\x12\x0e\n\x06taskId\x18\x02 \x02(\t\x12\x18\n\x07targets\x18\x03 \x03(\x0b\x32\x07.Target\"-\n\x0c\x45ndBatchTask\x12\x0e\n\x06taskId\x18\x01 \x02(\t\x12\r\n\x05seqId\x18\x02 \x01(\t\"\x80\x01\n\x11PushMMPAppMessage\x12\x1c\n\x07message\x18\x01 \x02(\x0b\x32\x0b.MMPMessage\x12\x11\n\tappIdList\x18\x02 \x03(\t\x12\x15\n\rphoneTypeList\x18\x03 \x03(\t\x12\x14\n\x0cprovinceList\x18\x04 \x03(\t\x12\r\n\x05seqId\x18\x05 \x01(\t\"\xa6\x01\n\x0cServerNotify\x12&\n\x04type\x18\x01 \x02(\x0e\x32\x18.ServerNotify.NotifyType\x12\x0c\n\x04info\x18\x02 \x01(\t\x12\x11\n\textradata\x18\x03 \x01(\x0c\x12\r\n\x05seqId\x18\x04 \x01(\t\">\n\nNotifyType\x12\n\n\x06normal\x10\x00\x12\x15\n\x11serverListChanged\x10\x01\x12\r\n\texception\x10\x02\"1\n\x12ServerNotifyResult\x12\r\n\x05seqId\x18\x01 \x02(\t\x12\x0c\n\x04info\x18\x02 \x01(\t\"\xab\x01\n\tOSMessage\x12\x11\n\tisOffline\x18\x02 \x02(\x08\x12\x1c\n\x11offlineExpireTime\x18\x03 \x02(\x03:\x01\x31\x12!\n\x0btransparent\x18\x04 \x01(\x0b\x32\x0c.Transparent\x12\x11\n\textraData\x18\x05 \x01(\t\x12\x0f\n\x07msgType\x18\x06 \x01(\x05\x12\x14\n\x0cmsgTraceFlag\x18\x07 \x01(\x05\x12\x10\n\x08priority\x18\x08 \x01(\x05\"\xae\x01\n\nMMPMessage\x12!\n\x0btransparent\x18\x02 \x01(\x0b\x32\x0c.Transparent\x12\x11\n\textraData\x18\x03 \x01(\t\x12\x0f\n\x07msgType\x18\x04 \x01(\x05\x12\x14\n\x0cmsgTraceFlag\x18\x05 \x01(\x05\x12\x18\n\x10msgOfflineExpire\x18\x06 \x01(\x03\x12\x17\n\tisOffline\x18\x07 \x01(\x08:\x04true\x12\x10\n\x08priority\x18\x08 \x01(\x05\"\xab\x01\n\x0bTransparent\x12\n\n\x02id\x18\x01 \x02(\t\x12\x0e\n\x06\x61\x63tion\x18\x02 \x02(\t\x12\x0e\n\x06taskId\x18\x03 \x02(\t\x12\x0e\n\x06\x61ppKey\x18\x04 \x02(\t\x12\r\n\x05\x61ppId\x18\x05 \x02(\t\x12\x11\n\tmessageId\x18\x06 \x02(\t\x12\x1b\n\x08pushInfo\x18\x07 \x01(\x0b\x32\t.PushInfo\x12!\n\x0b\x61\x63tionChain\x18\x08 \x03(\x0b\x32\x0c.ActionChain\"\xa9\x01\n\x08PushInfo\x12\x0f\n\x07message\x18\x01 \x01(\t\x12\x11\n\tactionKey\x18\x02 \x01(\t\x12\r\n\x05sound\x18\x03 \x01(\t\x12\r\n\x05\x62\x61\x64ge\x18\x04 \x01(\t\x12\x0f\n\x07payload\x18\x05 \x01(\t\x12\x0e\n\x06locKey\x18\x06 \x01(\t\x12\x0f\n\x07locArgs\x18\x07 \x01(\t\x12\x14\n\x0c\x61\x63tionLocKey\x18\x08 \x01(\t\x12\x13\n\x0blaunchImage\x18\t \x01(\t\"\x84\t\n\x0b\x41\x63tionChain\x12\x10\n\x08\x61\x63tionId\x18\x01 \x02(\x05\x12\x1f\n\x04type\x18\x02 \x02(\x0e\x32\x11.ActionChain.Type\x12\x0c\n\x04next\x18\x03 \x01(\x05\x12\x0c\n\x04logo\x18\x64 \x01(\t\x12\x0f\n\x07logoURL\x18\x65 \x01(\t\x12\r\n\x05title\x18\x66 \x01(\t\x12\x0c\n\x04text\x18g \x01(\t\x12\x11\n\tclearable\x18h \x01(\x08\x12\x0c\n\x04ring\x18i \x01(\x08\x12\x0c\n\x04\x62uzz\x18j \x01(\x08\x12\x11\n\tbannerURL\x18k \x01(\t\x12\x0b\n\x03img\x18x \x01(\t\x12\x18\n\x07\x62uttons\x18y \x03(\x0b\x32\x07.Button\x12\x0e\n\x05\x61ppid\x18\x8c\x01 \x01(\t\x12\"\n\x0c\x61ppstartupid\x18\x8d\x01 \x01(\x0b\x32\x0b.AppStartUp\x12\x12\n\tautostart\x18\x8e\x01 \x01(\x08\x12\x15\n\x0c\x66\x61iledAction\x18\x8f\x01 \x01(\x05\x12\x0c\n\x03url\x18\xa0\x01 \x01(\t\x12\x10\n\x07withcid\x18\xa1\x01 \x01(\t\x12\x1e\n\x0eis_withnettype\x18\xa2\x01 \x01(\x08:\x05\x66\x61lse\x12\x10\n\x07\x61\x64\x64ress\x18\xb4\x01 \x01(\t\x12\x10\n\x07\x63ontent\x18\xb5\x01 \x01(\t\x12\x0b\n\x02\x63t\x18\xb6\x01 \x01(\x03\x12\x19\n\x04\x66lag\x18\xb7\x01 \x01(\x0e\x32\n.SMSStatus\x12\x18\n\x0fsuccessedAction\x18\xc8\x01 \x01(\x05\x12\x1a\n\x11uninstalledAction\x18\xc9\x01 \x01(\x05\x12\r\n\x04name\x18\xdc\x01 \x01(\t\x12\x14\n\x0b\x61utoInstall\x18\xdf\x01 \x01(\x08\x12\x19\n\x10wifiAutodownload\x18\xe1\x01 \x01(\x08\x12\x16\n\rforceDownload\x18\xe2\x01 \x01(\x08\x12\x15\n\x0cshowProgress\x18\xe3\x01 \x01(\x08\x12\r\n\x04post\x18\xf1\x01 \x01(\t\x12\x10\n\x07headers\x18\xf2\x01 \x01(\t\x12\x12\n\tgroupable\x18\x84\x02 \x01(\x08\x12\x11\n\x08mmsTitle\x18\x98\x02 \x01(\t\x12\x0f\n\x06mmsURL\x18\x99\x02 \x01(\t\x12\x10\n\x07preload\x18\xac\x02 \x01(\x08\x12\x0f\n\x06taskid\x18\xc0\x02 \x01(\t\x12\x11\n\x08\x64uration\x18\xd4\x02 \x01(\x03\x12\r\n\x04\x64\x61te\x18\xe8\x02 \x01(\t\"\xe0\x02\n\x04Type\x12\x08\n\x04Goto\x10\x00\x12\x10\n\x0cnotification\x10\x01\x12\t\n\x05popup\x10\x02\x12\x0c\n\x08startapp\x10\x03\x12\x0c\n\x08startweb\x10\x04\x12\x0c\n\x08smsinbox\x10\x05\x12\x0c\n\x08\x63heckapp\x10\x06\x12\x07\n\x03\x65oa\x10\x07\x12\x0f\n\x0b\x61ppdownload\x10\x08\x12\x0c\n\x08startsms\x10\t\x12\r\n\thttpproxy\x10\n\x12\r\n\tsmsinbox2\x10\x0b\x12\r\n\tmmsinbox2\x10\x0c\x12\x0c\n\x08popupweb\x10\r\x12\x08\n\x04\x64ial\x10\x0e\x12\x11\n\rreportbindapp\x10\x0f\x12\x16\n\x12reportaddphoneinfo\x10\x10\x12\x11\n\rreportapplist\x10\x11\x12\x11\n\rterminatetask\x10\x12\x12\r\n\treportapp\x10\x13\x12\r\n\tenablelog\x10\x14\x12\x0e\n\ndisablelog\x10\x15\x12\r\n\tuploadlog\x10\x16\":\n\nAppStartUp\x12\x0f\n\x07\x61ndroid\x18\x01 \x01(\t\x12\x0e\n\x06symbia\x18\x02 \x01(\t\x12\x0b\n\x03ios\x18\x03 \x01(\t\"$\n\x06\x42utton\x12\x0c\n\x04text\x18\x01 \x01(\t\x12\x0c\n\x04next\x18\x02 \x01(\x05\")\n\x06Target\x12\r\n\x05\x61ppId\x18\x01 \x02(\t\x12\x10\n\x08\x63lientId\x18\x02 \x02(\t*\xc9\x02\n\x05\x43mdID\x12\r\n\tGTHEARDBT\x10\x00\x12\n\n\x06GTAUTH\x10\x01\x12\x11\n\rGTAUTH_RESULT\x10\x02\x12\x0f\n\x0bREQSERVHOST\x10\x03\x12\x15\n\x11REQSERVHOSTRESULT\x10\x04\x12\x0e\n\nPUSHRESULT\x10\x05\x12\x17\n\x13PUSHOSSINGLEMESSAGE\x10\x06\x12\x18\n\x14PUSHMMPSINGLEMESSAGE\x10\x07\x12\x15\n\x11STARTMMPBATCHTASK\x10\x08\x12\x14\n\x10STARTOSBATCHTASK\x10\t\x12\x13\n\x0fPUSHLISTMESSAGE\x10\n\x12\x10\n\x0c\x45NDBATCHTASK\x10\x0b\x12\x15\n\x11PUSHMMPAPPMESSAGE\x10\x0c\x12\x10\n\x0cSERVERNOTIFY\x10\r\x12\x12\n\x0ePUSHLISTRESULT\x10\x0e\x12\x16\n\x12SERVERNOTIFYRESULT\x10\x0f*!\n\tSMSStatus\x12\n\n\x06unread\x10\x00\x12\x08\n\x04read\x10\x01\x42\x02H\x01') + +_CMDID = descriptor.EnumDescriptor( + name='CmdID', + full_name='CmdID', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='GTHEARDBT', index=0, number=0, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='GTAUTH', index=1, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='GTAUTH_RESULT', index=2, number=2, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='REQSERVHOST', index=3, number=3, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='REQSERVHOSTRESULT', index=4, number=4, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='PUSHRESULT', index=5, number=5, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='PUSHOSSINGLEMESSAGE', index=6, number=6, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='PUSHMMPSINGLEMESSAGE', index=7, number=7, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='STARTMMPBATCHTASK', index=8, number=8, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='STARTOSBATCHTASK', index=9, number=9, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='PUSHLISTMESSAGE', index=10, number=10, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='ENDBATCHTASK', index=11, number=11, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='PUSHMMPAPPMESSAGE', index=12, number=12, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='SERVERNOTIFY', index=13, number=13, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='PUSHLISTRESULT', index=14, number=14, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='SERVERNOTIFYRESULT', index=15, number=15, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=3653, + serialized_end=3982, +) + + +_SMSSTATUS = descriptor.EnumDescriptor( + name='SMSStatus', + full_name='SMSStatus', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='unread', index=0, number=0, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='read', index=1, number=1, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=3984, + serialized_end=4017, +) + + +GTHEARDBT = 0 +GTAUTH = 1 +GTAUTH_RESULT = 2 +REQSERVHOST = 3 +REQSERVHOSTRESULT = 4 +PUSHRESULT = 5 +PUSHOSSINGLEMESSAGE = 6 +PUSHMMPSINGLEMESSAGE = 7 +STARTMMPBATCHTASK = 8 +STARTOSBATCHTASK = 9 +PUSHLISTMESSAGE = 10 +ENDBATCHTASK = 11 +PUSHMMPAPPMESSAGE = 12 +SERVERNOTIFY = 13 +PUSHLISTRESULT = 14 +SERVERNOTIFYRESULT = 15 +unread = 0 +read = 1 + + +_GTAUTHRESULT_GTAUTHRESULTCODE = descriptor.EnumDescriptor( + name='GtAuthResultCode', + full_name='GtAuthResult.GtAuthResultCode', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='successed', index=0, number=0, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='failed_noSign', index=1, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='failed_noAppkey', index=2, number=2, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='failed_noTimestamp', index=3, number=3, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='failed_AuthIllegal', index=4, number=4, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='redirect', index=5, number=5, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=176, + serialized_end=311, +) + +_REQSERVLISTRESULT_REQSERVHOSTRESULTCODE = descriptor.EnumDescriptor( + name='ReqServHostResultCode', + full_name='ReqServListResult.ReqServHostResultCode', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='successed', index=0, number=0, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='failed', index=1, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='busy', index=2, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=426, + serialized_end=486, +) + +_PUSHRESULT_EPUSHRESULT = descriptor.EnumDescriptor( + name='EPushResult', + full_name='PushResult.EPushResult', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='successed_online', index=0, number=0, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='successed_offline', index=1, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='successed_ignore', index=2, number=2, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='failed', index=3, number=3, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='busy', index=4, number=4, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='success_startBatch', index=5, number=5, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='success_endBatch', index=6, number=6, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=690, + serialized_end=838, +) + +_SERVERNOTIFY_NOTIFYTYPE = descriptor.EnumDescriptor( + name='NotifyType', + full_name='ServerNotify.NotifyType', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='normal', index=0, number=0, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='serverListChanged', index=1, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='exception', index=2, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=1540, + serialized_end=1602, +) + +_ACTIONCHAIN_TYPE = descriptor.EnumDescriptor( + name='Type', + full_name='ActionChain.Type', + filename=None, + file=DESCRIPTOR, + values=[ + descriptor.EnumValueDescriptor( + name='Goto', index=0, number=0, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='notification', index=1, number=1, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='popup', index=2, number=2, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='startapp', index=3, number=3, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='startweb', index=4, number=4, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='smsinbox', index=5, number=5, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='checkapp', index=6, number=6, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='eoa', index=7, number=7, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='appdownload', index=8, number=8, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='startsms', index=9, number=9, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='httpproxy', index=10, number=10, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='smsinbox2', index=11, number=11, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='mmsinbox2', index=12, number=12, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='popupweb', index=13, number=13, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='dial', index=14, number=14, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='reportbindapp', index=15, number=15, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='reportaddphoneinfo', index=16, number=16, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='reportapplist', index=17, number=17, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='terminatetask', index=18, number=18, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='reportapp', index=19, number=19, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='enablelog', index=20, number=20, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='disablelog', index=21, number=21, + options=None, + type=None), + descriptor.EnumValueDescriptor( + name='uploadlog', index=22, number=22, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=3157, + serialized_end=3509, +) + + +_GTAUTH = descriptor.Descriptor( + name='GtAuth', + full_name='GtAuth', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='sign', full_name='GtAuth.sign', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='appkey', full_name='GtAuth.appkey', index=1, + number=2, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='timestamp', full_name='GtAuth.timestamp', index=2, + number=3, type=3, cpp_type=2, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='seqId', full_name='GtAuth.seqId', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=16, + serialized_end=88, +) + + +_GTAUTHRESULT = descriptor.Descriptor( + name='GtAuthResult', + full_name='GtAuthResult', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='code', full_name='GtAuthResult.code', index=0, + number=1, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='redirectAddress', full_name='GtAuthResult.redirectAddress', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='seqId', full_name='GtAuthResult.seqId', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='info', full_name='GtAuthResult.info', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _GTAUTHRESULT_GTAUTHRESULTCODE, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=91, + serialized_end=311, +) + + +_REQSERVLIST = descriptor.Descriptor( + name='ReqServList', + full_name='ReqServList', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='seqId', full_name='ReqServList.seqId', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='timestamp', full_name='ReqServList.timestamp', index=1, + number=3, type=3, cpp_type=2, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=313, + serialized_end=360, +) + + +_REQSERVLISTRESULT = descriptor.Descriptor( + name='ReqServListResult', + full_name='ReqServListResult', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='code', full_name='ReqServListResult.code', index=0, + number=1, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='host', full_name='ReqServListResult.host', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='seqId', full_name='ReqServListResult.seqId', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _REQSERVLISTRESULT_REQSERVHOSTRESULTCODE, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=362, + serialized_end=486, +) + + +_PUSHLISTRESULT = descriptor.Descriptor( + name='PushListResult', + full_name='PushListResult', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='results', full_name='PushListResult.results', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=488, + serialized_end=534, +) + + +_PUSHRESULT = descriptor.Descriptor( + name='PushResult', + full_name='PushResult', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='result', full_name='PushResult.result', index=0, + number=1, type=14, cpp_type=8, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='taskId', full_name='PushResult.taskId', index=1, + number=2, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='messageId', full_name='PushResult.messageId', index=2, + number=3, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='seqId', full_name='PushResult.seqId', index=3, + number=4, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='target', full_name='PushResult.target', index=4, + number=5, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='info', full_name='PushResult.info', index=5, + number=6, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='traceId', full_name='PushResult.traceId', index=6, + number=7, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _PUSHRESULT_EPUSHRESULT, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=537, + serialized_end=838, +) + + +_PUSHOSSINGLEMESSAGE = descriptor.Descriptor( + name='PushOSSingleMessage', + full_name='PushOSSingleMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='seqId', full_name='PushOSSingleMessage.seqId', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='message', full_name='PushOSSingleMessage.message', index=1, + number=2, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='target', full_name='PushOSSingleMessage.target', index=2, + number=3, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=840, + serialized_end=930, +) + + +_PUSHMMPSINGLEMESSAGE = descriptor.Descriptor( + name='PushMMPSingleMessage', + full_name='PushMMPSingleMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='seqId', full_name='PushMMPSingleMessage.seqId', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='message', full_name='PushMMPSingleMessage.message', index=1, + number=2, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='target', full_name='PushMMPSingleMessage.target', index=2, + number=3, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=932, + serialized_end=1024, +) + + +_STARTMMPBATCHTASK = descriptor.Descriptor( + name='StartMMPBatchTask', + full_name='StartMMPBatchTask', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='message', full_name='StartMMPBatchTask.message', index=0, + number=1, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='expire', full_name='StartMMPBatchTask.expire', index=1, + number=2, type=3, cpp_type=2, label=2, + has_default_value=True, default_value=72, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='seqId', full_name='StartMMPBatchTask.seqId', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1026, + serialized_end=1110, +) + + +_STARTOSBATCHTASK = descriptor.Descriptor( + name='StartOSBatchTask', + full_name='StartOSBatchTask', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='message', full_name='StartOSBatchTask.message', index=0, + number=1, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='expire', full_name='StartOSBatchTask.expire', index=1, + number=2, type=3, cpp_type=2, label=2, + has_default_value=True, default_value=72, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1112, + serialized_end=1179, +) + + +_PUSHLISTMESSAGE = descriptor.Descriptor( + name='PushListMessage', + full_name='PushListMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='seqId', full_name='PushListMessage.seqId', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='taskId', full_name='PushListMessage.taskId', index=1, + number=2, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='targets', full_name='PushListMessage.targets', index=2, + number=3, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1181, + serialized_end=1255, +) + + +_ENDBATCHTASK = descriptor.Descriptor( + name='EndBatchTask', + full_name='EndBatchTask', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='taskId', full_name='EndBatchTask.taskId', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='seqId', full_name='EndBatchTask.seqId', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1257, + serialized_end=1302, +) + + +_PUSHMMPAPPMESSAGE = descriptor.Descriptor( + name='PushMMPAppMessage', + full_name='PushMMPAppMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='message', full_name='PushMMPAppMessage.message', index=0, + number=1, type=11, cpp_type=10, label=2, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='appIdList', full_name='PushMMPAppMessage.appIdList', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='phoneTypeList', full_name='PushMMPAppMessage.phoneTypeList', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='provinceList', full_name='PushMMPAppMessage.provinceList', index=3, + number=4, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='seqId', full_name='PushMMPAppMessage.seqId', index=4, + number=5, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1305, + serialized_end=1433, +) + + +_SERVERNOTIFY = descriptor.Descriptor( + name='ServerNotify', + full_name='ServerNotify', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='type', full_name='ServerNotify.type', index=0, + number=1, type=14, cpp_type=8, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='info', full_name='ServerNotify.info', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='extradata', full_name='ServerNotify.extradata', index=2, + number=3, type=12, cpp_type=9, label=1, + has_default_value=False, default_value="", + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='seqId', full_name='ServerNotify.seqId', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _SERVERNOTIFY_NOTIFYTYPE, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1436, + serialized_end=1602, +) + + +_SERVERNOTIFYRESULT = descriptor.Descriptor( + name='ServerNotifyResult', + full_name='ServerNotifyResult', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='seqId', full_name='ServerNotifyResult.seqId', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='info', full_name='ServerNotifyResult.info', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1604, + serialized_end=1653, +) + + +_OSMESSAGE = descriptor.Descriptor( + name='OSMessage', + full_name='OSMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='isOffline', full_name='OSMessage.isOffline', index=0, + number=2, type=8, cpp_type=7, label=2, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='offlineExpireTime', full_name='OSMessage.offlineExpireTime', index=1, + number=3, type=3, cpp_type=2, label=2, + has_default_value=True, default_value=1, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='transparent', full_name='OSMessage.transparent', index=2, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='extraData', full_name='OSMessage.extraData', index=3, + number=5, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='msgType', full_name='OSMessage.msgType', index=4, + number=6, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='msgTraceFlag', full_name='OSMessage.msgTraceFlag', index=5, + number=7, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='priority', full_name='OSMessage.priority', index=6, + number=8, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1656, + serialized_end=1827, +) + + +_MMPMESSAGE = descriptor.Descriptor( + name='MMPMessage', + full_name='MMPMessage', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='transparent', full_name='MMPMessage.transparent', index=0, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='extraData', full_name='MMPMessage.extraData', index=1, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='msgType', full_name='MMPMessage.msgType', index=2, + number=4, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='msgTraceFlag', full_name='MMPMessage.msgTraceFlag', index=3, + number=5, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='msgOfflineExpire', full_name='MMPMessage.msgOfflineExpire', index=4, + number=6, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='isOffline', full_name='MMPMessage.isOffline', index=5, + number=7, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=True, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='priority', full_name='MMPMessage.priority', index=6, + number=8, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=1830, + serialized_end=2004, +) + + +_TRANSPARENT = descriptor.Descriptor( + name='Transparent', + full_name='Transparent', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='id', full_name='Transparent.id', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='action', full_name='Transparent.action', index=1, + number=2, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='taskId', full_name='Transparent.taskId', index=2, + number=3, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='appKey', full_name='Transparent.appKey', index=3, + number=4, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='appId', full_name='Transparent.appId', index=4, + number=5, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='messageId', full_name='Transparent.messageId', index=5, + number=6, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='pushInfo', full_name='Transparent.pushInfo', index=6, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='actionChain', full_name='Transparent.actionChain', index=7, + number=8, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2007, + serialized_end=2178, +) + + +_PUSHINFO = descriptor.Descriptor( + name='PushInfo', + full_name='PushInfo', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='message', full_name='PushInfo.message', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='actionKey', full_name='PushInfo.actionKey', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='sound', full_name='PushInfo.sound', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='badge', full_name='PushInfo.badge', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='payload', full_name='PushInfo.payload', index=4, + number=5, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='locKey', full_name='PushInfo.locKey', index=5, + number=6, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='locArgs', full_name='PushInfo.locArgs', index=6, + number=7, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='actionLocKey', full_name='PushInfo.actionLocKey', index=7, + number=8, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='launchImage', full_name='PushInfo.launchImage', index=8, + number=9, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2181, + serialized_end=2350, +) + + +_ACTIONCHAIN = descriptor.Descriptor( + name='ActionChain', + full_name='ActionChain', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='actionId', full_name='ActionChain.actionId', index=0, + number=1, type=5, cpp_type=1, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='type', full_name='ActionChain.type', index=1, + number=2, type=14, cpp_type=8, label=2, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='next', full_name='ActionChain.next', index=2, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='logo', full_name='ActionChain.logo', index=3, + number=100, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='logoURL', full_name='ActionChain.logoURL', index=4, + number=101, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='title', full_name='ActionChain.title', index=5, + number=102, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='text', full_name='ActionChain.text', index=6, + number=103, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='clearable', full_name='ActionChain.clearable', index=7, + number=104, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='ring', full_name='ActionChain.ring', index=8, + number=105, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='buzz', full_name='ActionChain.buzz', index=9, + number=106, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='bannerURL', full_name='ActionChain.bannerURL', index=10, + number=107, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='img', full_name='ActionChain.img', index=11, + number=120, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='buttons', full_name='ActionChain.buttons', index=12, + number=121, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='appid', full_name='ActionChain.appid', index=13, + number=140, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='appstartupid', full_name='ActionChain.appstartupid', index=14, + number=141, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='autostart', full_name='ActionChain.autostart', index=15, + number=142, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='failedAction', full_name='ActionChain.failedAction', index=16, + number=143, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='url', full_name='ActionChain.url', index=17, + number=160, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='withcid', full_name='ActionChain.withcid', index=18, + number=161, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='is_withnettype', full_name='ActionChain.is_withnettype', index=19, + number=162, type=8, cpp_type=7, label=1, + has_default_value=True, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='address', full_name='ActionChain.address', index=20, + number=180, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='content', full_name='ActionChain.content', index=21, + number=181, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='ct', full_name='ActionChain.ct', index=22, + number=182, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='flag', full_name='ActionChain.flag', index=23, + number=183, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='successedAction', full_name='ActionChain.successedAction', index=24, + number=200, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='uninstalledAction', full_name='ActionChain.uninstalledAction', index=25, + number=201, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='name', full_name='ActionChain.name', index=26, + number=220, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='autoInstall', full_name='ActionChain.autoInstall', index=27, + number=223, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='wifiAutodownload', full_name='ActionChain.wifiAutodownload', index=28, + number=225, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='forceDownload', full_name='ActionChain.forceDownload', index=29, + number=226, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='showProgress', full_name='ActionChain.showProgress', index=30, + number=227, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='post', full_name='ActionChain.post', index=31, + number=241, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='headers', full_name='ActionChain.headers', index=32, + number=242, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='groupable', full_name='ActionChain.groupable', index=33, + number=260, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='mmsTitle', full_name='ActionChain.mmsTitle', index=34, + number=280, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='mmsURL', full_name='ActionChain.mmsURL', index=35, + number=281, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='preload', full_name='ActionChain.preload', index=36, + number=300, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='taskid', full_name='ActionChain.taskid', index=37, + number=320, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='duration', full_name='ActionChain.duration', index=38, + number=340, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='date', full_name='ActionChain.date', index=39, + number=360, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _ACTIONCHAIN_TYPE, + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=2353, + serialized_end=3509, +) + + +_APPSTARTUP = descriptor.Descriptor( + name='AppStartUp', + full_name='AppStartUp', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='android', full_name='AppStartUp.android', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='symbia', full_name='AppStartUp.symbia', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='ios', full_name='AppStartUp.ios', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3511, + serialized_end=3569, +) + + +_BUTTON = descriptor.Descriptor( + name='Button', + full_name='Button', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='text', full_name='Button.text', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='next', full_name='Button.next', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3571, + serialized_end=3607, +) + + +_TARGET = descriptor.Descriptor( + name='Target', + full_name='Target', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + descriptor.FieldDescriptor( + name='appId', full_name='Target.appId', index=0, + number=1, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + descriptor.FieldDescriptor( + name='clientId', full_name='Target.clientId', index=1, + number=2, type=9, cpp_type=9, label=2, + has_default_value=False, default_value=unicode("", "utf-8"), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + extension_ranges=[], + serialized_start=3609, + serialized_end=3650, +) + +_GTAUTHRESULT_GTAUTHRESULTCODE.containing_type = _GTAUTHRESULT; +_REQSERVLISTRESULT_REQSERVHOSTRESULTCODE.containing_type = _REQSERVLISTRESULT; +_PUSHLISTRESULT.fields_by_name['results'].message_type = _PUSHRESULT +_PUSHRESULT.fields_by_name['result'].enum_type = _PUSHRESULT_EPUSHRESULT +_PUSHRESULT_EPUSHRESULT.containing_type = _PUSHRESULT; +_PUSHOSSINGLEMESSAGE.fields_by_name['message'].message_type = _OSMESSAGE +_PUSHOSSINGLEMESSAGE.fields_by_name['target'].message_type = _TARGET +_PUSHMMPSINGLEMESSAGE.fields_by_name['message'].message_type = _MMPMESSAGE +_PUSHMMPSINGLEMESSAGE.fields_by_name['target'].message_type = _TARGET +_STARTMMPBATCHTASK.fields_by_name['message'].message_type = _MMPMESSAGE +_STARTOSBATCHTASK.fields_by_name['message'].message_type = _OSMESSAGE +_PUSHLISTMESSAGE.fields_by_name['targets'].message_type = _TARGET +_PUSHMMPAPPMESSAGE.fields_by_name['message'].message_type = _MMPMESSAGE +_SERVERNOTIFY.fields_by_name['type'].enum_type = _SERVERNOTIFY_NOTIFYTYPE +_SERVERNOTIFY_NOTIFYTYPE.containing_type = _SERVERNOTIFY; +_OSMESSAGE.fields_by_name['transparent'].message_type = _TRANSPARENT +_MMPMESSAGE.fields_by_name['transparent'].message_type = _TRANSPARENT +_TRANSPARENT.fields_by_name['pushInfo'].message_type = _PUSHINFO +_TRANSPARENT.fields_by_name['actionChain'].message_type = _ACTIONCHAIN +_ACTIONCHAIN.fields_by_name['type'].enum_type = _ACTIONCHAIN_TYPE +_ACTIONCHAIN.fields_by_name['buttons'].message_type = _BUTTON +_ACTIONCHAIN.fields_by_name['appstartupid'].message_type = _APPSTARTUP +_ACTIONCHAIN.fields_by_name['flag'].enum_type = _SMSSTATUS +_ACTIONCHAIN_TYPE.containing_type = _ACTIONCHAIN; +DESCRIPTOR.message_types_by_name['GtAuth'] = _GTAUTH +DESCRIPTOR.message_types_by_name['GtAuthResult'] = _GTAUTHRESULT +DESCRIPTOR.message_types_by_name['ReqServList'] = _REQSERVLIST +DESCRIPTOR.message_types_by_name['ReqServListResult'] = _REQSERVLISTRESULT +DESCRIPTOR.message_types_by_name['PushListResult'] = _PUSHLISTRESULT +DESCRIPTOR.message_types_by_name['PushResult'] = _PUSHRESULT +DESCRIPTOR.message_types_by_name['PushOSSingleMessage'] = _PUSHOSSINGLEMESSAGE +DESCRIPTOR.message_types_by_name['PushMMPSingleMessage'] = _PUSHMMPSINGLEMESSAGE +DESCRIPTOR.message_types_by_name['StartMMPBatchTask'] = _STARTMMPBATCHTASK +DESCRIPTOR.message_types_by_name['StartOSBatchTask'] = _STARTOSBATCHTASK +DESCRIPTOR.message_types_by_name['PushListMessage'] = _PUSHLISTMESSAGE +DESCRIPTOR.message_types_by_name['EndBatchTask'] = _ENDBATCHTASK +DESCRIPTOR.message_types_by_name['PushMMPAppMessage'] = _PUSHMMPAPPMESSAGE +DESCRIPTOR.message_types_by_name['ServerNotify'] = _SERVERNOTIFY +DESCRIPTOR.message_types_by_name['ServerNotifyResult'] = _SERVERNOTIFYRESULT +DESCRIPTOR.message_types_by_name['OSMessage'] = _OSMESSAGE +DESCRIPTOR.message_types_by_name['MMPMessage'] = _MMPMESSAGE +DESCRIPTOR.message_types_by_name['Transparent'] = _TRANSPARENT +DESCRIPTOR.message_types_by_name['PushInfo'] = _PUSHINFO +DESCRIPTOR.message_types_by_name['ActionChain'] = _ACTIONCHAIN +DESCRIPTOR.message_types_by_name['AppStartUp'] = _APPSTARTUP +DESCRIPTOR.message_types_by_name['Button'] = _BUTTON +DESCRIPTOR.message_types_by_name['Target'] = _TARGET + +class GtAuth(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _GTAUTH + + # @@protoc_insertion_point(class_scope:GtAuth) + +class GtAuthResult(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _GTAUTHRESULT + + # @@protoc_insertion_point(class_scope:GtAuthResult) + +class ReqServList(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _REQSERVLIST + + # @@protoc_insertion_point(class_scope:ReqServList) + +class ReqServListResult(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _REQSERVLISTRESULT + + # @@protoc_insertion_point(class_scope:ReqServListResult) + +class PushListResult(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _PUSHLISTRESULT + + # @@protoc_insertion_point(class_scope:PushListResult) + +class PushResult(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _PUSHRESULT + + # @@protoc_insertion_point(class_scope:PushResult) + +class PushOSSingleMessage(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _PUSHOSSINGLEMESSAGE + + # @@protoc_insertion_point(class_scope:PushOSSingleMessage) + +class PushMMPSingleMessage(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _PUSHMMPSINGLEMESSAGE + + # @@protoc_insertion_point(class_scope:PushMMPSingleMessage) + +class StartMMPBatchTask(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _STARTMMPBATCHTASK + + # @@protoc_insertion_point(class_scope:StartMMPBatchTask) + +class StartOSBatchTask(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _STARTOSBATCHTASK + + # @@protoc_insertion_point(class_scope:StartOSBatchTask) + +class PushListMessage(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _PUSHLISTMESSAGE + + # @@protoc_insertion_point(class_scope:PushListMessage) + +class EndBatchTask(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _ENDBATCHTASK + + # @@protoc_insertion_point(class_scope:EndBatchTask) + +class PushMMPAppMessage(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _PUSHMMPAPPMESSAGE + + # @@protoc_insertion_point(class_scope:PushMMPAppMessage) + +class ServerNotify(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _SERVERNOTIFY + + # @@protoc_insertion_point(class_scope:ServerNotify) + +class ServerNotifyResult(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _SERVERNOTIFYRESULT + + # @@protoc_insertion_point(class_scope:ServerNotifyResult) + +class OSMessage(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _OSMESSAGE + + # @@protoc_insertion_point(class_scope:OSMessage) + +class MMPMessage(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _MMPMESSAGE + + # @@protoc_insertion_point(class_scope:MMPMessage) + +class Transparent(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TRANSPARENT + + # @@protoc_insertion_point(class_scope:Transparent) + +class PushInfo(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _PUSHINFO + + # @@protoc_insertion_point(class_scope:PushInfo) + +class ActionChain(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _ACTIONCHAIN + + # @@protoc_insertion_point(class_scope:ActionChain) + +class AppStartUp(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _APPSTARTUP + + # @@protoc_insertion_point(class_scope:AppStartUp) + +class Button(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _BUTTON + + # @@protoc_insertion_point(class_scope:Button) + +class Target(message.Message): + __metaclass__ = reflection.GeneratedProtocolMessageType + DESCRIPTOR = _TARGET + + # @@protoc_insertion_point(class_scope:Target) + +# @@protoc_insertion_point(module_scope) diff --git a/code/score.py b/code/score.py new file mode 100644 index 0000000..7a1366b --- /dev/null +++ b/code/score.py @@ -0,0 +1,116 @@ +import os,xml.etree.ElementTree as ET +import time +from datetime import datetime +class score: + def __init__(self): + _config=ET.parse(os.path.abspath("./static/config.xml")) + root=_config.getroot() + levels=root.findall("./score/level") + ops=root.findall("./ops/op") + + self.config=dict() + for level in levels: + num=int(level[0].text) + minScore=int(level[1].text) + maxScore="INF" if level[2].text=="INF" else int(level[2].text) + + + self.config[num]=dict() + self.config[num]['min']=minScore + self.config[num]['max']=maxScore + + self.ops=dict() + for op in ops: + cond=int(op[0].text) + score_op=int(op[1].text) + score_max="INF" if op[2].text=="INF" else int(op[2].text) + + self.ops[cond]=dict() + self.ops[cond]['op']=score_op + self.ops[cond]['max']=score_max + + def getRankByScore(self,s): + for num in self.config: + if (self.config[num]['max']=="INF" or s<=self.config[num]['max']) and s>=self.config[num]['min']: + result=dict() + result['scoreMin']=self.config[num]['min'] + result['scoreMax']=self.config[num]['max'] + result['scoreLevel']=num + return result + print "error in getRankByScore("+str(s)+")" + + # 1:new user login for the first time +5/5 + # 2:user login for the first time every day +1/1 + # 3:caller give helper credit +2/50 + # 4:helper join in support +3/Infinity + # 5:helper send support message +1/30 + # 6:user online for more than 12 hours a day +2/2 + + # 7:helper earn the highest credit in a event +5/Infinity + # allow more than one helper earn it in the same event + + # 8:send harmful support message -10/Infinity + # 9:send useless event message -20/Infinity + # 10:helper quit the event while the event does not end -1/Infinity + # 11:caller give no credit to the helper after the event end for five days -10/infinity + + def updateScoreByCase(self,uid,cond,dbapi): + if cond in self.ops: + info = dbapi.getScoreInfoById(uid) + score_op = self.ops[cond]["op"] + if info is not None: + name = "score"+str(cond) + if self.ops[cond]["max"]=="INF": + dbapi.operateScoreById(uid,score_op) + dbapi.operateScoreInfoById(uid,cond,score_op) + elif abs(info[name]+self.ops[cond]["op"]) <= abs(self.ops[cond]["max"]): + dbapi.operateScoreById(uid,score_op) + dbapi.operateScoreInfoById(uid,cond,score_op) + else: + return False + + return True + else: + return False + + def userRegister(self,uid,dbapi): + dbapi.addScoreInfoById(uid) + return self.updateScoreByCase(uid,1,dbapi) + + def userLogin(self,uid,dbapi): + info = dbapi.getScoreInfoById(uid) + if info is not None: + if info['login_time'].strftime("%Y-%m-%d %H:%M:%S") == "2000-01-01 00:00:00": + dbapi.setScoreTimeById(uid,time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())) + return self.updateScoreByCase(uid,2,dbapi) + else: + return False + else: + return False + + def giveCredit(self,uid,eid,dbapi): + self.updateScoreByCase(uid,3,dbapi) + #condition 7 + helpers = dbapi.getGreatestHelperId(eid) + for helper in helpers: + self.updateScoreByCase(helper['usrid'],7,dbapi) + + + def joinSupport(self,uid,dbapi): + return self.updateScoreByCase(uid,4,dbapi) + + def sendSupport(self,uid,dbapi): + return self.updateScoreByCase(uid,5,dbapi) + + def checkOnlineHours(self,uid,dbapi): + info = dbapi.getScoreInfoById(uid) + if info is not None: + if datetime.fromtimestamp(time.time()).hour - info['login_time'].hour >= 12: + return self.updateScoreByCase(uid,6,dbapi) + + def quitSupport(self,uid,dbapi): + return self.updateScoreByCase(uid,10,dbapi) + +if __name__ == '__main__': + test=score() + print test.getRankByScore(700) \ No newline at end of file diff --git a/code/static/avatar/default.png b/code/static/avatar/default.png new file mode 100644 index 0000000..4b2bbd5 Binary files /dev/null and b/code/static/avatar/default.png differ diff --git a/code/static/config.xml b/code/static/config.xml new file mode 100644 index 0000000..99a7f4f --- /dev/null +++ b/code/static/config.xml @@ -0,0 +1,124 @@ + + + + + + 1 + 0 + 100 + + + 2 + 101 + 300 + + + 3 + 301 + 800 + + + 4 + 801 + 1500 + + + 5 + 1501 + 2200 + + + 6 + 2201 + 3000 + + + 7 + 3001 + 4000 + + + 8 + 4001 + 5000 + + + 9 + 5001 + 6000 + + + 10 + 6001 + INF + + + + + 1 + 5 + 5 + new user register + + + 2 + 1 + 1 + user login for the first time every day + + + 3 + 2 + 50 + user give helper credit + + + 4 + 3 + INF + helper join in support + + + 5 + 1 + 30 + helper send support message + + + 6 + 2 + 2 + user online for more than 12 hours in a day + + + 7 + 5 + INF + helper earn the highest credit in a event(allow more than one helper earn it in the same event) + + + 8 + -10 + INF + send harmful support message + + + 9 + -20 + INF + send useless event message + + + 10 + -1 + INF + helper quit the event while the event does not end + + + 11 + -10 + INF + caller give no credit to the helper after the event end for five days + + + \ No newline at end of file diff --git a/code/util.py b/code/util.py new file mode 100644 index 0000000..123bf7c --- /dev/null +++ b/code/util.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +import json,os,base64 +import datetime + +class util: + def setAvatar(self,username,filestring,dbapi): + userid=dbapi.getUserByUserName(username)['id'] + avatar=open(os.path.abspath('./static/avatar/'+str(userid)+".png"),"wb") + avatar.write(base64.standard_b64decode(filestring)) + avatar.close() + + def getAvatar(self,username,dbapi): + userid=dbapi.getUserByUserName(username)['id'] + avatar=open(os.path.abspath('./static/avatar/'+str(userid)+".png"),"rb") + result="" + result=base64.standard_b64encode(avatar.read()) + avatar.close() + return result + + def setAvatarbyUid(self,uid,filestring): + avatar=open(os.path.abspath('./static/avatar/'+str(uid)+".png"),"wb") + avatar.write(base64.standard_b64decode(filestring)) + avatar.close() + + def getAvatarbyUid(self,uid): + avatar=open(os.path.abspath('./static/avatar/'+str(uid)+".png"),"rb") + result="" + result=base64.standard_b64encode(avatar.read()) + avatar.close() + return result + + def setVideobyEid(self,uid,videostring): + newdir ='./static/Video/'+str(uid) + os.mkdir(newdir) + video=open(os.path.abspath('./static/Video/'+str(uid)+'/'+str(uid)+'.3gp'),"wb") + video.write(base64.standard_b64decode(videostring)) + video.close() + + def setAudiobyEid(self,uid,videostring): + newdir = './static/Audio/'+str(uid) + os.mkdir(newdir) + audio=open(os.path.abspath('./static/Audio/'+str(uid)+'/'+str(uid)+'.amr'),"wb") + audio.write(base64.standard_b64decode(videostring)) + audio.close() + + def setCreditforHelper(self,event,askuser,helper,credit,dbapi): + + credit = float(credit) + credit *= (2 * 0.1) + T_preCredit = dbapi.getpreviousEvent(askuser['id'], helper['id']) + + helperReputation = helper['credit'] + Reputation = 0 + + #helperReputation = T_preCredit['credit'] + + if helper['time'] == None: + Reputation = (credit + helperReputation) / 2 + else: + timeInterval = (datetime.datetime.now() - helper['time']).days + if credit <= 0.4: + helper['beta'] /= 2 + helper['gama'] /= 2 + factor = 1 / pow(timeInterval * 2 + 1, 1 / 3.0) + Reputation = helper['beta'] * factor * helperReputation + (1 - helper['beta'] * factor) * credit + else: + helper['beta'] += helper['gama'] + if helper['beta'] > 0.5: + helper['beta'] = 0.5 + factor = 1 / pow(timeInterval + 1, 1 / 3.0) + Reputation = (1 - helper['beta']) * factor * helperReputation + (1 - ((1 - helper['beta']) * factor)) * credit + + dbapi.updateUserCredit(helper['id'], Reputation) + dbapi.updateUserbetagama(helper['id'], helper['beta'],helper['gama']) + + if T_preCredit == None: + dbapi.insertpreviousEvent(askuser['id'], helper['id'], credit, event['endtime']) + else: + dbapi.updatepreviousEvent(askuser['id'], helper['id'], credit, event['endtime']) + + + def getPushlistByCredit(self,askuser,aroundhelpers,friendlist,hashelpaskuserlist,percent,dbapi): + pushlist = [] + lastpushlist = [] + for helper in aroundhelpers: + jv = 0.0 + helperReputation = 0.0 + hisCr = 0.0 + if friendlist is not None: + friend_helper_list = [] + for friend in friendlist: + if dbapi.getpreviousEvent(friend['id'], helper['id']) is not None: + friend_helper_list.append(friend) + if friend_helper_list is not None: + tv = [] + fv = [] + for f in friend_helper_list: + T_preCredit = dbapi.getpreviousEvent(f['id'], helper['id']) + fv.append(T_preCredit['credit']) + CmmNds = [] + for hashelpaskuser in hashelpaskuserlist: + if dbapi.getpreviousEvent(f['id'], hashelpaskuser['id']) is not None: + CmmNds.append(hashelpaskuser) + + para1 = 0.0 + para2 = 0.0 + para3 = 0.0 + + if CmmNds is not None: + for Mi in CmmNds: + T_preCredit1 = dbapi.getpreviousEvent(askuser['id'], Mi['id']) + T_preCredit2 = dbapi.getpreviousEvent(f['id'], Mi['id']) + para1 += (T_preCredit1['credit'] * T_preCredit2['credit']) + para2 += pow(T_preCredit1['credit'], 2.0) + para3 += pow(T_preCredit2['credit'], 2.0) + temp = pow(para2, 1 / 2.0) * pow(para3, 1 / 2.0) + if temp == 0: + temp = 0.000001 + tv.append(para1 / temp) + jv = 0.0 + sumOf_tv = 0.0 + sumOf_fv = 0.0 + for TV in tv: + sumOf_tv += TV + for FV in fv: + sumOf_fv += FV + if sumOf_tv != 0.0: + jv = (sumOf_fv * sumOf_tv) / sumOf_tv + + helperReputation = helper['credit'] + T_preCredit3 = dbapi.getpreviousEvent(askuser['id'], helper['id']) + if T_preCredit3 is not None: + hisCr = T_preCredit3['credit'] + + last_credit = jv + helperReputation + hisCr + pushlist.append((helper['name'],helper['cid'], last_credit)) + + pushlist.sort(key = lambda x: x[2], reverse = True) + count = 0 + for person in pushlist: + if count >= (len(pushlist) * percent): + break + lastpushlist.append(person) + count += 1 + + pushlist = [] + for item in lastpushlist: + pushlist.append(item[1]) + return pushlist diff --git a/code/zyq/api8030.py b/code/zyq/api8030.py deleted file mode 100644 index ceb0ae7..0000000 --- a/code/zyq/api8030.py +++ /dev/null @@ -1,65 +0,0 @@ -#encoding=utf-8 -import tornado.httpserver -import tornado.ioloop -import tornado.options -import tornado.web - -import MySQLdb -import json -import re - -from tornado.options import define, options -define("port", default=8030, help="run on the given port", type=int) - -class Application(tornado.web.Application): - def __init__(self): - handlers = [(r"/api/deleterelatives/u_id=([0-9]+)&r_id=([0-9]+)", DeleteRelatives), - (r"/api/addrelatives/u_id=([0-9]+)&r_id=([0-9]+)", AddRelatives)] - self.db = MySQLdb.connect(host='localhost',user='comhelp',passwd='20140629',db="community",charset='utf8') - tornado.web.Application.__init__(self, handlers, debug=True) - -class DeleteRelatives(tornado.web.RequestHandler): - def get(self, u_id, r_id): - cursor = self.application.db.cursor(MySQLdb.cursors.DictCursor) - #self.write(u_id + r_id) - cursor.execute("SELECT * FROM relation WHERE usrid = '" + u_id + "' AND cid = '" + r_id + "'") - row = int(cursor.rowcount) - #self.write(row2) - if row == 0 : - delete_message = {'state': 0} - else : - cursor.execute("DELETE FROM relation WHERE usrid = '" + u_id + "' AND cid = '" + r_id + "'") - row = int(cursor.rowcount) - delete_message = {'state': 1} - - self.response.headers['Content-Type'] = "application/json" - self.response.out.write(json.dumps(delete_message)) - self.write(delete_message) - -class AddRelatives(tornado.web.RequestHandler): - def get(self, u_id, r_id): - cursor = self.application.db.cursor(MySQLdb.cursors.DictCursor) - cursor.execute("SELECT * FROM relation WHERE usrid = '" + u_id + "' AND cid = '" + r_id + "'") - row = int(cursor.rowcount) - if row == 0: - sql = "INSERT INTO relation (usrid, cid, kind) VALUES ('" + u_id + "', '" + r_id + "', '1')" - self.write(sql) - try: - cursor.execute(sql) - self.application.db.commit() - add_message = {'state': 1} - except: - self.application.db.rollback() - add_message = {'state': 2} - else: - add_message = {'state': 0} - - self.response.headers['Content-Type'] = "application/json" - self.response.out.write(json.dumps(add_message)) - self.write(add_message) - -if __name__ == "__main__": - tornado.options.parse_command_line() - http_server = tornado.httpserver.HTTPServer(Application()) - http_server.listen(options.port) - tornado.ioloop.IOLoop.instance().start() \ No newline at end of file diff --git a/db.sql b/db.sql index be93cf1..75f8603 100644 --- a/db.sql +++ b/db.sql @@ -1,68 +1,88 @@ -drop table IF EXISTS tpu; +drop event IF EXISTS init_score_info; +drop procedure IF EXISTS init_func; +drop table IF EXISTS score_info; +drop table IF EXISTS previousEvent; +drop table IF EXISTS tpu; +drop table IF EXISTS auth; +drop table IF EXISTS previousEvent; +drop table IF EXISTS email_code; +drop table IF EXISTS phone_code; +drop table IF EXISTS auth_cnt; drop table IF EXISTS support; drop table IF EXISTS helper; +drop table IF EXISTS follow; +drop table IF EXISTS temprelation; drop table IF EXISTS event; drop table IF EXISTS relation; drop table IF EXISTS info; drop table IF EXISTS user; +SET GLOBAL event_scheduler = 1; /* 用户表 id:自增id name:登录用户名 -kind:用户类型(普通用户,认证用户,第三方机构等) -info:用户具体信息(对应info表中的id) +kind:用户类型(普通用户1,志愿者2,小区保安3,安全机构4,医疗机构5,其它机构6等) password:用户密码(md5加密) +cid:推送令牌 +state:在线状态0-不在线,1-表示在线 */ CREATE TABLE user ( id int NOT NULL AUTO_INCREMENT, name varchar(50) NOT NULL, kind int NOT NULL, - info int, password varchar(30), + cid varchar(40), + state int DEFAULT 0, primary key(id), unique(name) -); -. +)DEFAULT CHARSET=utf8; + /* 用户信息表(用户头像放在统一文件夹下,以id为标识符) id:对应用户id cardid:身份证号 -phone:电话 name:用户昵称 -sex:性别 +sex:性别 (男1,女2) age:年龄 +vocation:职业是(医务相关人员:1,警察、消防等政府相关人员:2,其他:3) +phone:电话 address:地址 illness:病史 credit:用户信誉度(根据参与的所有事件评分-综合得出) score:用户积分(根据参与的所有事件-系统自动累积) -latitude:经度 -longitude:纬度 +latitude:纬度 +longitude:经度 */ CREATE TABLE info ( id int NOT NULL, - cardid varchar(50) NOT NULL, + cardid varchar(50) NOT NULL, name varchar(50) NOT NULL, sex int, age int, + vocation int, + phone varchar(25), address varchar(255), illness varchar(255), - credit int, + credit double DEFAULT 0.4, score int, - latitude DECIMAL, - longitude DECIMAL, + latitude DECIMAL(12,7), + longitude DECIMAL(12,7), + beta float DEFAULT 0.5, + gama float DEFAULT 0.05, + time datetime, primary key(id), - foreign key(id) references user(id) -); + foreign key(id) references user(id) ON DELETE CASCADE +)DEFAULT CHARSET=utf8; /* 用户单向关系表 id:自增id usrid:用户id oid:对应用户id -kind:关系类型(关注好友,亲友等等) +kind:关系类型(关注好友2,亲友1等等) */ CREATE TABLE relation ( @@ -71,18 +91,23 @@ CREATE TABLE relation cid int NOT NULL, kind int NOT NULL, primary key(id), - foreign key(usrid) references user(id), + foreign key(usrid) references user(id) ON DELETE CASCADE, foreign key(cid) references user(id) -); + ON DELETE CASCADE +)DEFAULT CHARSET=utf8; /* 事件表 id:自增id usrid:求助者id -kind:事件类型(安全,生活,健康) -state:事件状态(求助中,结束) -content:事件求助信息(包含位置,事件内容,时间等) +kind:事件类型(安全1,生活2,健康3) +state:事件状态(求助中0,结束1) +content:事件求助信息(事件内容等) assist:事件辅助信息(包含图片,语音等) +latitude:纬度 +longitude:经度 +starttime 求助开始时间, +endtime 求助结束时间, */ CREATE TABLE event ( @@ -90,11 +115,16 @@ CREATE TABLE event usrid int NOT NULL, kind int NOT NULL, state int NOT NULL, - content blob NOT NULL, - assist blob, + content blob, + video varchar(255) DEFAULT 0, + audio varchar(255) DEFAULT 0, + latitude DECIMAL(12,7), + longitude DECIMAL(12,7), + starttime datetime, + endtime datetime, primary key(id), - foreign key(usrid) references user(id) -); + foreign key(usrid) references user(id) ON DELETE CASCADE +)DEFAULT CHARSET=utf8; /* 事件<>帮客关系表 @@ -111,9 +141,20 @@ CREATE TABLE helper usrid int NOT NULL, credit int, primary key(id), - foreign key(eid) references event(id), - foreign key(usrid) references user(id) -); + foreign key(eid) references event(id) ON DELETE CASCADE, + foreign key(usrid) references user(id) ON DELETE CASCADE +)DEFAULT CHARSET=utf8; + + + CREATE TABLE follow +( + eid int NOT NULL, + usrid int NOT NULL, + time datetime, + primary key(eid,usrid), + foreign key(eid) references event(id) ON DELETE CASCADE, + foreign key(usrid) references user(id) ON DELETE CASCADE +)DEFAULT CHARSET=utf8; /* 事件<>援助信息表 @@ -122,6 +163,7 @@ id:自增id eid:事件id usrid:帮客的用户id content:援助信息内容 +time 信息发送时间 */ CREATE TABLE support ( @@ -129,10 +171,11 @@ CREATE TABLE support eid int NOT NULL, usrid int NOT NULL, content blob NOT NULL, + time datetime, primary key(id), - foreign key(eid) references event(id), - foreign key(usrid) references user(id) -); + foreign key(eid) references event(id) ON DELETE CASCADE, + foreign key(usrid) references user(id) ON DELETE CASCADE +)DEFAULT CHARSET=utf8; /* 第三方登录的绑定关系表 @@ -142,23 +185,197 @@ CREATE TABLE tpu id varchar(255) NOT NULL, usrid int NOT NULL, primary key(id), - foreign key(usrid) references user(id) + foreign key(usrid) references user(id) ON DELETE CASCADE )ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; /* 临时用户关系表 -id:自增id -uid:用户id +uid:请求者用户id oid:对应用户id kind:关系类型(关注好友,亲友等等) */ CREATE TABLE temprelation ( - id int NOT NULL AUTO_INCREMENT, uid int NOT NULL, cid int NOT NULL, kind int NOT NULL, + info varchar(100) DEFAULT "invite", + primary key(uid,cid,kind), + foreign key(uid) references user(id) ON DELETE CASCADE, + foreign key(cid) references user(id) ON DELETE CASCADE +)ENGINE=InnoDB DEFAULT CHARSET=utf8; + +/* +用户认证表 +id:用户标识 +email:邮箱 +email_state:邮箱认证状态 +phone:手机号 +phone_state:手机认证状态 +*/ +CREATE TABLE auth ( + id int NOT NULL, + email varchar(50), + email_state enum("unauth", "authing", "authed") NOT NULL, + phone varchar(20), + phone_state enum("unauth", "authing", "authed") NOT NULL, primary key(id), - foreign key(uid) references user(id), - foreign key(cid) references user(id) -); \ No newline at end of file + foreign key(id) references user(id) ON DELETE CASCADE +) DEFAULT CHARSET = utf8; + +/* +邮箱随机码表 +id:用户标识 +code:随机码 +expire_in:过期时间 +*/ +CREATE TABLE email_code ( + id int NOT NULL, + code varchar(50) NOT NULL, + expire_in int NOT NULL, + primary key(id), + foreign key(id) references user(id) ON DELETE CASCADE +) DEFAULT CHARSET = utf8; + +/* +请求验证次数表: +id:用户标识 +kind:email/phone,请求验证的类型 +count:目前已经请求的次数 +*/ +CREATE TABLE auth_cnt ( + id int NOT NULL, + kind enum("email", "phone") NOT NULL, + cnt int NOT NULL, + primary key(id, kind), + foreign key(id) references user(id) ON DELETE CASCADE +) DEFAULT CHARSET = utf8; + +/* +手机验证码表 +id:用户标识 +code:验证码 +expire_in:过期时间 +*/ +CREATE TABLE phone_code ( + id int NOT NULL, + code varchar(6) NOT NULL, + expire_in int NOT NULL, + primary key(id), + foreign key(id) references user(id) ON DELETE CASCADE +) DEFAULT CHARSET = utf8; + +/* +计算信誉度辅助表: +askid:求助者id +helperid:帮客id +credit:信誉度(前一个事件的) +time:发出求助的时间 +*/ +CREATE TABLE previousEvent( + askid int NOT NULL, + helperid int NOT NULL, + time datetime, + credit double, + primary key(askid, helperid), + foreign key(askid) references user(id) ON DELETE CASCADE, + foreign key(helperid) references user(id) ON DELETE CASCADE +) DEFAULT CHARSET = utf8; + +/* +本日获得积分详情表: +每天将重置此表为默认值 +*/ +CREATE TABLE score_info( + id int NOT NULL, + login_time datetime NOT NULL, + score1 int DEFAULT 0, + score2 int DEFAULT 0, + score3 int DEFAULT 0, + score4 int DEFAULT 0, + score5 int DEFAULT 0, + score6 int DEFAULT 0, + score7 int DEFAULT 0, + score8 int DEFAULT 0, + score9 int DEFAULT 0, + score10 int DEFAULT 0, + score11 int DEFAULT 0, + primary key(id), + foreign key(id) references user(id) ON DELETE CASCADE ON UPDATE CASCADE +) DEFAULT CHARSET = utf8; + +/* +更新积分详情表事件 +*/ +delimiter // +CREATE + PROCEDURE init_func() + BEGIN UPDATE score_info SET login_time="2000-01-01 00:00:00", score1=0, score2=0, score3=0, score4=0, score5=0, score6=0, score7=0, score8=0, score9=0, score10=0, score11=0; END// + +delimiter ; + +CREATE + EVENT IF NOT EXISTS init_score_info + ON SCHEDULE EVERY 1 DAY STARTS (CONCAT(CURRENT_DATE(),' 00:00:00')) + ON COMPLETION PRESERVE + DO CALL init_func(); + +/* +添加6用户(3男3女): +*/ +insert into user(name,kind,password,state) values("test1",1,"1",1); +insert into user(name,kind,password,state) values("test2",2,"t2",1); +insert into user(name,kind,password,state) values("test3",3,"3",1); +insert into user(name,kind,password,state) values("test4",1,"4",0); +insert into user(name,kind,password,state) values("test5",2,"5",1); +insert into user(name,kind,password,state) values("test6",3,"6",0); + +insert into info(id,cardid,name,sex,age,address,illness,credit,score,latitude,longitude) values(1,"test1cardid","realtest1",1,21,"Guangzhou","illness",0,0,23.070000,113.400000); +insert into info(id,cardid,name,sex,age,address,illness,credit,score,latitude,longitude) values(2,"test2cardid","realtest2",1,25,"Guangzhou","illness",0,0,23.070000,113.400000); +insert into info(id,cardid,name,sex,age,address,illness,credit,score,latitude,longitude) values(3,"test3cardid","realtest3",1,46,"Guangzhou","illness",0,0,23.070000,113.400000); +insert into info(id,cardid,name,sex,age,address,illness,credit,score,latitude,longitude) values(4,"test4cardid","realtest4",2,21,"Guangzhou","illness",0,0,23.070000,113.400000); +insert into info(id,cardid,name,sex,age,address,illness,credit,score,latitude,longitude) values(5,"test5cardid","realtest5",2,15,"Guangzhou","illness",0,0,23.070000,113.400000); +insert into info(id,cardid,name,sex,age,address,illness,credit,score,latitude,longitude) values(6,"test6cardid","realtest6",2,65,"Guangzhou","illness",0,0,23.070000,113.400000); +/* +绑定关系1->2,1->4,2->6,2->5: +*/ +insert into relation(usrid,cid,kind) values(1,2,1); +insert into relation(usrid,cid,kind) values(1,4,2); +insert into relation(usrid,cid,kind) values(2,6,1); +insert into relation(usrid,cid,kind) values(2,5,2); +/* +添加3事件: +事件1:1发起 安全1 +事件1:3发起 生活2 +事件1:6发起 健康3 +*/ +insert into event(usrid,kind,state,content,latitude,longitude,starttime) values(1,1,0,"event1",23.070000,113.400000,"2014-07-14 16:55:54"); +insert into event(usrid,kind,state,content,latitude,longitude,starttime) values(3,2,0,"event2",23.070000,113.400000,"2014-07-15 08:45:54"); +insert into event(usrid,kind,state,content,latitude,longitude,starttime) values(6,3,0,"event3",23.070000,113.400000,"2014-07-15 08:00:54"); + +/* +添加helper +1,2,4,6 +2,1,5 +3,2,3,5 +*/ +insert into helper(eid,usrid) values(1,2); +insert into helper(eid,usrid) values(1,4); +insert into helper(eid,usrid) values(1,6); +insert into helper(eid,usrid) values(2,1); +insert into helper(eid,usrid) values(3,5); +insert into helper(eid,usrid) values(3,2); +insert into helper(eid,usrid) values(3,3); +insert into helper(eid,usrid) values(3,5); + +/*添加辅助信息 +1:2发,6发 +2:5发 +3:3发,5发*/ +insert into support(eid,usrid,content,time) values(1,2,"2援助事件1","2014-07-14 17:00:54"); +insert into support(eid,usrid,content,time) values(1,2,"6援助事件1","2014-07-14 17:12:54"); + +insert into support(eid,usrid,content,time) values(2,5,"5援助事件2","2014-07-15 09:10:54"); + +insert into support(eid,usrid,content,time) values(3,3,"3援助事件3","2014-07-15 08:10:54"); +insert into support(eid,usrid,content,time) values(3,5,"5援助事件4","2014-07-15 08:10:54"); diff --git a/doc/newAPI.doc b/doc/newAPI.doc new file mode 100644 index 0000000..60f70c4 Binary files /dev/null and b/doc/newAPI.doc differ diff --git a/template/dbapi.py b/template/dbapi.py deleted file mode 100644 index 8b95d3d..0000000 --- a/template/dbapi.py +++ /dev/null @@ -1,33 +0,0 @@ -import MySQLdb - -class dbapi: - def __init__(self): - #Change the database config to fit you own pc - self.host="localhost" - self.user="root" - self.passwd="root" - self.dbname="community" - self.charset="utf8" - self.db=MySQLdb.connect(host=self.host,user=self.user,passwd=self.passwd,db=self.dbname,charset=self.charset) - - #Get event By event's id - def getEventById(self,eventid): - cursor=self.db.cursor() - sql="""select * from event where id=%s""" - #Param must to tuple!1 - param=(eventid,) - cursor.execute(sql,param) - result=cursor.fetchall() - cursor.close() - return result - - def getEventsByUserId(self,userid): - cursor=self.db.cursor() - cursor.close() - return 0 - - def write(self): - return "FKU" - - def __del__(self): - self.db.close() diff --git a/template/history.py b/template/history.py deleted file mode 100644 index 091fb51..0000000 --- a/template/history.py +++ /dev/null @@ -1,29 +0,0 @@ -import tornado.ioloop -import tornado.web -import tornado.httpserver -import os,MySQLdb,dbapi - -#Change the handler class and make it to fit your requirement -class historyHandler(tornado.web.RequestHandler): - def get(self): - self.render("index.html") - - def post(self): - username=self.get_argument("username") - print self.application.dbapi.getEventById(1) - -class app(tornado.web.Application): - def __init__(self): - settings={ - "static_path": os.path.join(os.path.dirname(__file__), "static"), - "debug": True, - } - handlers=[(r"/api/history",historyHandler),] - tornado.web.Application.__init__(self,handlers,**settings) - self.dbapi=dbapi.dbapi() - - -if __name__=="__main__": - server=tornado.httpserver.HTTPServer(app()) - server.listen(8080) - tornado.ioloop.IOLoop.instance().start() \ No newline at end of file diff --git a/template/index.html b/template/index.html deleted file mode 100644 index 189e6ff..0000000 --- a/template/index.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - Test - - -
- - - - - - - -
- - \ No newline at end of file diff --git "a/\346\226\207\346\241\243/\345\220\216\345\217\260API\346\226\207\346\241\243.doc" "b/\346\226\207\346\241\243/\345\220\216\345\217\260API\346\226\207\346\241\243.doc" deleted file mode 100644 index c0188a3..0000000 Binary files "a/\346\226\207\346\241\243/\345\220\216\345\217\260API\346\226\207\346\241\243.doc" and /dev/null differ