Repository: dolotech/Texas-Hold-em-Poker Branch: master Commit: 51e16f131349 Files: 476 Total size: 3.9 MB Directory structure: gitextract_4hhyd0iz/ ├── .gitignore ├── README.md ├── bin/ │ ├── build-linux.sh │ ├── build-win.sh │ ├── client/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── assets/ │ │ │ ├── Scene/ │ │ │ │ ├── main.fire │ │ │ │ └── main.fire.meta │ │ │ ├── Scene.meta │ │ │ ├── Script/ │ │ │ │ ├── Common.js │ │ │ │ ├── Common.js.meta │ │ │ │ ├── CountDown.js │ │ │ │ ├── CountDown.js.meta │ │ │ │ ├── Encoding.js │ │ │ │ ├── Encoding.js.meta │ │ │ │ ├── main.js │ │ │ │ └── main.js.meta │ │ │ ├── Script.meta │ │ │ ├── resources/ │ │ │ │ ├── GameMain_6p.plist │ │ │ │ ├── GameMain_6p.plist.meta │ │ │ │ ├── GameMain_6p.png.meta │ │ │ │ ├── audio/ │ │ │ │ │ ├── audio_allinWin.wav.meta │ │ │ │ │ ├── audio_check.wav.meta │ │ │ │ │ ├── audio_chipsToPot.wav.meta │ │ │ │ │ ├── audio_chipsToTable.wav.meta │ │ │ │ │ ├── audio_distributeCard.wav.meta │ │ │ │ │ ├── audio_fold.wav.meta │ │ │ │ │ ├── audio_normalWin.wav.meta │ │ │ │ │ ├── audio_pokerClick.caf │ │ │ │ │ ├── audio_pokerClick.caf.meta │ │ │ │ │ ├── audio_pokerClick.mp3.meta │ │ │ │ │ ├── audio_timeout.wav.meta │ │ │ │ │ └── audio_yourTurn.wav.meta │ │ │ │ ├── audio.meta │ │ │ │ ├── game_cards.plist │ │ │ │ ├── game_cards.plist.meta │ │ │ │ ├── game_cards.png.meta │ │ │ │ ├── game_cards_6p.plist │ │ │ │ ├── game_cards_6p.plist.meta │ │ │ │ ├── game_cards_6p.png.meta │ │ │ │ ├── game_desk_bg.jpg.meta │ │ │ │ ├── game_desk_bg_6p.jpg.meta │ │ │ │ ├── splash.gif.meta │ │ │ │ └── splash.png.meta │ │ │ └── resources.meta │ │ ├── creator.d.ts │ │ ├── jsconfig.json │ │ └── project.json │ └── client.html └── src/ ├── github.com/ │ ├── davecgh/ │ │ └── go-spew/ │ │ ├── LICENSE │ │ └── spew/ │ │ ├── bypass.go │ │ ├── bypasssafe.go │ │ ├── common.go │ │ ├── config.go │ │ ├── doc.go │ │ ├── dump.go │ │ ├── format.go │ │ └── spew.go │ ├── dolotech/ │ │ ├── leaf/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── TUTORIAL_EN.md │ │ │ ├── TUTORIAL_ZH.md │ │ │ ├── chanrpc/ │ │ │ │ ├── chanrpc.go │ │ │ │ └── example_test.go │ │ │ ├── conf/ │ │ │ │ └── conf.go │ │ │ ├── gate/ │ │ │ │ ├── agent.go │ │ │ │ └── gate.go │ │ │ ├── leaf.go │ │ │ ├── module/ │ │ │ │ ├── go_test.go │ │ │ │ ├── module.go │ │ │ │ └── skeleton.go │ │ │ ├── network/ │ │ │ │ ├── agent.go │ │ │ │ ├── conn.go │ │ │ │ ├── json/ │ │ │ │ │ └── json.go │ │ │ │ ├── processor.go │ │ │ │ ├── protobuf/ │ │ │ │ │ └── protobuf.go │ │ │ │ ├── tcp_client.go │ │ │ │ ├── tcp_conn.go │ │ │ │ ├── tcp_msg.go │ │ │ │ ├── tcp_server.go │ │ │ │ ├── ws_client.go │ │ │ │ ├── ws_conn.go │ │ │ │ └── ws_server.go │ │ │ ├── room/ │ │ │ │ ├── interface.go │ │ │ │ ├── msg_loop.go │ │ │ │ └── room_list.go │ │ │ ├── timer/ │ │ │ │ ├── cronexpr.go │ │ │ │ ├── example_test.go │ │ │ │ └── timer.go │ │ │ └── version.go │ │ └── lib/ │ │ ├── README.md │ │ ├── csv/ │ │ │ ├── bench_test.go │ │ │ ├── cfield.go │ │ │ ├── csv.go │ │ │ ├── csv_test.go │ │ │ ├── decode.go │ │ │ ├── decode_test.go │ │ │ ├── encode.go │ │ │ ├── encode_test.go │ │ │ ├── example_marshal_test.go │ │ │ └── example_test.go │ │ ├── db/ │ │ │ ├── client.go │ │ │ └── client_test.go │ │ ├── filter/ │ │ │ ├── filter.go │ │ │ ├── readme.txt │ │ │ └── trie.go │ │ ├── goevent/ │ │ │ └── go_event.go │ │ ├── grpool/ │ │ │ ├── grpool.go │ │ │ └── grpool_test.go │ │ ├── pse/ │ │ │ ├── pse_darwin.go │ │ │ ├── pse_freebsd.go │ │ │ ├── pse_linux.go │ │ │ ├── pse_rumprun.go │ │ │ ├── pse_solaris.go │ │ │ ├── pse_test.go │ │ │ ├── pse_windows.go │ │ │ └── pse_windows_test.go │ │ ├── route/ │ │ │ ├── route_msg.go │ │ │ └── router_test.go │ │ └── utils/ │ │ ├── aes.go │ │ ├── debug.go │ │ ├── helper.go │ │ ├── list.go │ │ ├── map.go │ │ ├── map_list_test.go │ │ ├── queue.go │ │ ├── random.go │ │ ├── sign.go │ │ ├── stack.go │ │ ├── string_2_bytes.go │ │ ├── string_2_bytes_test.go │ │ ├── structandmap.go │ │ ├── timer_queue.go │ │ ├── utils.go │ │ ├── utils_test.go │ │ ├── waitgroup.go │ │ └── xxtea.go │ ├── go-xorm/ │ │ ├── core/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── benchmark.sh │ │ │ ├── cache.go │ │ │ ├── column.go │ │ │ ├── converstion.go │ │ │ ├── db.go │ │ │ ├── dialect.go │ │ │ ├── driver.go │ │ │ ├── error.go │ │ │ ├── filter.go │ │ │ ├── ilogger.go │ │ │ ├── index.go │ │ │ ├── mapper.go │ │ │ ├── pk.go │ │ │ ├── scan.go │ │ │ ├── table.go │ │ │ └── type.go │ │ └── xorm/ │ │ ├── CONTRIBUTING.md │ │ ├── LICENSE │ │ ├── README.md │ │ ├── README_CN.md │ │ ├── VERSION │ │ ├── doc.go │ │ ├── engine.go │ │ ├── error.go │ │ ├── gen_reserved.sh │ │ ├── goracle_driver.go │ │ ├── helpers.go │ │ ├── logger.go │ │ ├── lru_cacher.go │ │ ├── memory_store.go │ │ ├── mssql_dialect.go │ │ ├── mymysql_driver.go │ │ ├── mysql_dialect.go │ │ ├── mysql_driver.go │ │ ├── oci8_driver.go │ │ ├── odbc_driver.go │ │ ├── oracle_dialect.go │ │ ├── pg_reserved.txt │ │ ├── postgres_dialect.go │ │ ├── pq_driver.go │ │ ├── processors.go │ │ ├── rows.go │ │ ├── session.go │ │ ├── sqlite3_dialect.go │ │ ├── sqlite3_driver.go │ │ ├── statement.go │ │ ├── syslogger.go │ │ ├── types.go │ │ └── xorm.go │ ├── golang/ │ │ ├── glog/ │ │ │ ├── glog.go │ │ │ ├── glog_file.go │ │ │ └── glog_test.go │ │ └── protobuf/ │ │ ├── .gitignore │ │ ├── .travis.yml │ │ ├── AUTHORS │ │ ├── CONTRIBUTORS │ │ ├── LICENSE │ │ ├── Make.protobuf │ │ ├── Makefile │ │ ├── README.md │ │ ├── _conformance/ │ │ │ ├── Makefile │ │ │ ├── conformance.go │ │ │ └── conformance_proto/ │ │ │ ├── conformance.pb.go │ │ │ └── conformance.proto │ │ ├── descriptor/ │ │ │ ├── descriptor.go │ │ │ └── descriptor_test.go │ │ ├── jsonpb/ │ │ │ ├── jsonpb.go │ │ │ ├── jsonpb_test.go │ │ │ └── jsonpb_test_proto/ │ │ │ ├── Makefile │ │ │ ├── more_test_objects.pb.go │ │ │ ├── more_test_objects.proto │ │ │ ├── test_objects.pb.go │ │ │ └── test_objects.proto │ │ ├── proto/ │ │ │ ├── Makefile │ │ │ ├── all_test.go │ │ │ ├── any_test.go │ │ │ ├── clone.go │ │ │ ├── clone_test.go │ │ │ ├── decode.go │ │ │ ├── decode_test.go │ │ │ ├── discard.go │ │ │ ├── encode.go │ │ │ ├── encode_test.go │ │ │ ├── equal.go │ │ │ ├── equal_test.go │ │ │ ├── extensions.go │ │ │ ├── extensions_test.go │ │ │ ├── lib.go │ │ │ ├── map_test.go │ │ │ ├── message_set.go │ │ │ ├── message_set_test.go │ │ │ ├── pointer_reflect.go │ │ │ ├── pointer_unsafe.go │ │ │ ├── properties.go │ │ │ ├── proto3_proto/ │ │ │ │ ├── proto3.pb.go │ │ │ │ └── proto3.proto │ │ │ ├── proto3_test.go │ │ │ ├── size2_test.go │ │ │ ├── size_test.go │ │ │ ├── testdata/ │ │ │ │ ├── Makefile │ │ │ │ ├── golden_test.go │ │ │ │ ├── test.pb.go │ │ │ │ └── test.proto │ │ │ ├── text.go │ │ │ ├── text_parser.go │ │ │ ├── text_parser_test.go │ │ │ └── text_test.go │ │ ├── protoc-gen-go/ │ │ │ ├── Makefile │ │ │ ├── descriptor/ │ │ │ │ ├── Makefile │ │ │ │ ├── descriptor.pb.go │ │ │ │ └── descriptor.proto │ │ │ ├── doc.go │ │ │ ├── generator/ │ │ │ │ ├── Makefile │ │ │ │ ├── generator.go │ │ │ │ └── name_test.go │ │ │ ├── grpc/ │ │ │ │ └── grpc.go │ │ │ ├── link_grpc.go │ │ │ ├── main.go │ │ │ ├── plugin/ │ │ │ │ ├── Makefile │ │ │ │ ├── plugin.pb.go │ │ │ │ ├── plugin.pb.golden │ │ │ │ └── plugin.proto │ │ │ └── testdata/ │ │ │ ├── Makefile │ │ │ ├── extension_base.proto │ │ │ ├── extension_extra.proto │ │ │ ├── extension_test.go │ │ │ ├── extension_user.proto │ │ │ ├── grpc.proto │ │ │ ├── imp.pb.go.golden │ │ │ ├── imp.proto │ │ │ ├── imp2.proto │ │ │ ├── imp3.proto │ │ │ ├── main_test.go │ │ │ ├── multi/ │ │ │ │ ├── multi1.proto │ │ │ │ ├── multi2.proto │ │ │ │ └── multi3.proto │ │ │ ├── my_test/ │ │ │ │ ├── test.pb.go │ │ │ │ ├── test.pb.go.golden │ │ │ │ └── test.proto │ │ │ └── proto3.proto │ │ └── ptypes/ │ │ ├── any/ │ │ │ ├── any.pb.go │ │ │ └── any.proto │ │ ├── any.go │ │ ├── any_test.go │ │ ├── doc.go │ │ ├── duration/ │ │ │ ├── duration.pb.go │ │ │ └── duration.proto │ │ ├── duration.go │ │ ├── duration_test.go │ │ ├── empty/ │ │ │ ├── empty.pb.go │ │ │ └── empty.proto │ │ ├── regen.sh │ │ ├── struct/ │ │ │ ├── struct.pb.go │ │ │ └── struct.proto │ │ ├── timestamp/ │ │ │ ├── timestamp.pb.go │ │ │ └── timestamp.proto │ │ ├── timestamp.go │ │ ├── timestamp_test.go │ │ └── wrappers/ │ │ ├── wrappers.pb.go │ │ └── wrappers.proto │ ├── gorilla/ │ │ └── websocket/ │ │ ├── .gitignore │ │ ├── .travis.yml │ │ ├── AUTHORS │ │ ├── LICENSE │ │ ├── README.md │ │ ├── client.go │ │ ├── client_clone.go │ │ ├── client_clone_legacy.go │ │ ├── client_server_test.go │ │ ├── client_test.go │ │ ├── compression.go │ │ ├── compression_test.go │ │ ├── conn.go │ │ ├── conn_broadcast_test.go │ │ ├── conn_read.go │ │ ├── conn_read_legacy.go │ │ ├── conn_test.go │ │ ├── conn_write.go │ │ ├── conn_write_legacy.go │ │ ├── doc.go │ │ ├── example_test.go │ │ ├── examples/ │ │ │ ├── autobahn/ │ │ │ │ ├── README.md │ │ │ │ ├── fuzzingclient.json │ │ │ │ └── server.go │ │ │ ├── chat/ │ │ │ │ ├── README.md │ │ │ │ ├── client.go │ │ │ │ ├── home.html │ │ │ │ ├── hub.go │ │ │ │ └── main.go │ │ │ ├── command/ │ │ │ │ ├── README.md │ │ │ │ ├── home.html │ │ │ │ └── main.go │ │ │ ├── echo/ │ │ │ │ ├── README.md │ │ │ │ ├── client.go │ │ │ │ └── server.go │ │ │ └── filewatch/ │ │ │ ├── README.md │ │ │ └── main.go │ │ ├── json.go │ │ ├── json_test.go │ │ ├── mask.go │ │ ├── mask_safe.go │ │ ├── mask_test.go │ │ ├── prepared.go │ │ ├── prepared_test.go │ │ ├── proxy.go │ │ ├── server.go │ │ ├── server_test.go │ │ ├── util.go │ │ ├── util_test.go │ │ └── x_net_proxy.go │ ├── labstack/ │ │ └── gommon/ │ │ ├── bytes/ │ │ │ ├── README.md │ │ │ ├── bytes.go │ │ │ └── bytes_test.go │ │ ├── color/ │ │ │ ├── README.md │ │ │ ├── color.go │ │ │ └── color_test.go │ │ ├── gommon.go │ │ ├── log/ │ │ │ ├── README.md │ │ │ ├── color.go │ │ │ ├── log.go │ │ │ ├── log_test.go │ │ │ └── white.go │ │ └── random/ │ │ ├── random.go │ │ └── random_test.go │ ├── lib/ │ │ └── pq/ │ │ ├── CONTRIBUTING.md │ │ ├── LICENSE.md │ │ ├── README.md │ │ ├── buf.go │ │ ├── conn.go │ │ ├── copy.go │ │ ├── doc.go │ │ ├── encode.go │ │ ├── error.go │ │ ├── notify.go │ │ ├── oid/ │ │ │ ├── doc.go │ │ │ ├── gen.go │ │ │ └── types.go │ │ ├── url.go │ │ ├── user_posix.go │ │ └── user_windows.go │ └── stretchr/ │ └── testify/ │ ├── Gopkg.toml │ ├── LICENSE │ ├── README.md │ ├── _codegen/ │ │ └── main.go │ ├── assert/ │ │ ├── assertion_format.go │ │ ├── assertion_format.go.tmpl │ │ ├── assertion_forward.go │ │ ├── assertion_forward.go.tmpl │ │ ├── assertions.go │ │ ├── assertions_test.go │ │ ├── doc.go │ │ ├── errors.go │ │ ├── forward_assertions.go │ │ ├── forward_assertions_test.go │ │ ├── http_assertions.go │ │ └── http_assertions_test.go │ ├── doc.go │ ├── http/ │ │ ├── doc.go │ │ ├── test_response_writer.go │ │ └── test_round_tripper.go │ ├── mock/ │ │ ├── doc.go │ │ ├── mock.go │ │ └── mock_test.go │ ├── package_test.go │ ├── require/ │ │ ├── doc.go │ │ ├── forward_requirements.go │ │ ├── forward_requirements_test.go │ │ ├── require.go │ │ ├── require.go.tmpl │ │ ├── require_forward.go │ │ ├── require_forward.go.tmpl │ │ ├── requirements.go │ │ └── requirements_test.go │ ├── suite/ │ │ ├── doc.go │ │ ├── interfaces.go │ │ ├── suite.go │ │ └── suite_test.go │ └── vendor/ │ └── github.com/ │ ├── davecgh/ │ │ └── go-spew/ │ │ ├── LICENSE │ │ └── spew/ │ │ ├── bypass.go │ │ ├── bypasssafe.go │ │ ├── common.go │ │ ├── config.go │ │ ├── doc.go │ │ ├── dump.go │ │ ├── format.go │ │ └── spew.go │ ├── pmezard/ │ │ └── go-difflib/ │ │ ├── LICENSE │ │ └── difflib/ │ │ └── difflib.go │ └── stretchr/ │ └── objx/ │ ├── LICENSE │ ├── accessors.go │ ├── constants.go │ ├── conversions.go │ ├── doc.go │ ├── map.go │ ├── mutations.go │ ├── security.go │ ├── tests.go │ ├── type_specific_codegen.go │ └── value.go ├── main.go └── server/ ├── algorithm/ │ ├── 7462.txt │ ├── Pocker Rule.html │ ├── cards.go │ ├── cards_test.go │ ├── constan.go │ ├── dealer.go │ ├── dealer_test.go │ ├── flush_test.go │ ├── pk.go │ ├── sort.go │ ├── sort_test.go │ └── tostring.go ├── base/ │ └── skeleton.go ├── conf/ │ └── conf.go ├── game/ │ ├── external.go │ └── internal/ │ ├── chanrpc.go │ ├── game_rule.go │ ├── module.go │ ├── occupant.go │ ├── pot.go │ ├── pot_test.go │ ├── room.go │ ├── room_internal_handler.go │ └── room_test.go ├── gate/ │ ├── external.go │ ├── internal/ │ │ └── module.go │ └── router.go ├── login/ │ ├── external.go │ └── internal/ │ ├── handler.go │ └── module.go ├── model/ │ ├── constan.go │ ├── room_data.go │ ├── room_data_test.go │ ├── room_list_test.go │ ├── user_data.go │ └── user_data_test.go └── protocol/ └── protocol.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .idea/* pkg/* bin/game.exe bin/game ================================================ FILE: README.md ================================================ # 德州扑克服务器Go实现 ## 核心算法: ```go type Cards []byte // todo 两对和四张起脚牌的判定 var StraightMask = []uint16{15872, 7936, 3968, 1984, 992, 496, 248, 124, 62, 31} //顺子(Straight,亦称“蛇”) //此牌由五张顺序扑克牌组成。 //平手牌:如果不止一人抓到此牌,则五张牌中点数最大的赢得此局, // 如果所有牌点数都相同,平分彩池。 func (this *Cards) straight() uint32 { var handvalue uint16 for _, v := range (*this) { value := v & 0xF if value == 0xE { handvalue |= 1 } handvalue |= (1 << (value - 1 ) ) } for i := uint8(0); i < 10; i++ { if handvalue&StraightMask[i] == StraightMask[i] { return En(STRAIGHT, uint32(10-i+4)) } } return 0 } //同花顺(Straight Flush) //五张同花色的连续牌。 //平手牌:如果摊牌时有两副或多副同花顺,连续牌的头张牌大的获得筹码。 //如果是两副或多副相同的连续牌,平分筹码。 func (this *Cards) straightFlush() uint32 { cards := *this for i := byte(0); i < SUITSIZE; i++ { var handvalue uint16 for _, v := range cards { if (v >> 4) == i { value := v & 0xF if value == 0xE { handvalue |= 1 } handvalue |= (1 << (value - 1 ) ) } } for i := uint8(0); i < 10; i++ { if handvalue&StraightMask[i] == StraightMask[i] { return En(STRAIGHT_FLUSH, uint32(10-i+4)) } } } return 0 } //皇家同花顺(Royal Flush) //同花色的A, K, Q, J和10。 //平手牌:在摊牌的时候有两副多副皇家同花顺时,平分筹码。 func (this *Cards) royalFlush() uint32 { cards := *this for i := byte(0); i < SUITSIZE; i++ { var handvalue uint16 for _, v := range cards { if (v >> 4) == i { value := v & 0xF if value == 0xE { handvalue |= 1 } handvalue |= (1 << (value - 1 ) ) } } if handvalue&StraightMask[0] == StraightMask[0] { return En(ROYAL_FLUSH, 0) } } return 0 } //四条(Four of a Kind,亦称“铁支”、“四张”或“炸弹”) //其中四张是相同点数但不同花的扑克牌,第五张是随意的一张牌。 //平手牌:如果两组或者更多组摊牌,则四张牌中的最大者赢局,如果一组人持有的四张牌是一样的, //那么第五张牌最大者赢局(起脚牌,2张起手牌中小的那张就叫做起脚牌)。如果起脚牌也一样,平分彩池。 func (this *Cards) four(counter *ValueCounter) uint32 { cards := *this if counter.Get(cards[len(cards)-1]) == 4 { return En(FOUR, ToValue(cards)) } return 0 } //满堂彩(Fullhouse,葫芦,三带二) //由三张相同点数及任何两张其他相同点数的扑克牌组成。 //平手牌:如果两组或者更多组摊牌,那么三张相同点数中较大者赢局。 //如果三张牌都一样,则两张牌中点数较大者赢局,如果所有的牌都一样,则平分彩池。 func (this *Cards) fullFouse(counter *ValueCounter) uint32 { cards := *this length := len(cards) if length >= 5 { if cards[length-1]&0xF == cards[length-2]&0xF && cards[length-3]&0xF == cards[length-1]&0xF && cards[length-4]&0xF == cards[length-5]&0xF { return En(FULL_HOUSE, ToValue(cards)) } } return 0 } //同花(Flush,简称“花”) //此牌由五张不按顺序但相同花的扑克牌组成。 //平手牌:如果不止一人抓到此牌相,则牌点最高的人赢得该局, //如果最大点相同,则由第二、第三、第四或者第五张牌来决定胜负,如果所有的牌都相同,平分彩池。 func (this *Cards) flush() uint32 { cards := *this for i := byte(0); i < SUITSIZE; i++ { var count uint8 for _, v := range cards { if (v >> 4) == i { count ++ if count == 5 { var handvalue uint16 for _, v1 := range cards { if (v1 >> 4) == i { value := v1 & 0xF if value == 0xE { handvalue |= 1 } handvalue |= (1 << (value - 1 ) ) } } return En(FLUSH, uint32(handvalue)) } } } } return 0 } //三条(Three of a kind,亦称“三张”) //由三张相同点数和两张不同点数的扑克组成。 //平手牌:如果不止一人抓到此牌,则三张牌中最大点数者赢局, //如果三张牌都相同,比较第四张牌,必要时比较第五张,点数大的人赢局。如果所有牌都相同,则平分彩池。 func (this *Cards) three(counter *ValueCounter) uint32 { cards := *this if counter.Get(cards[len(cards)-1]) == 3 { return En(THREE, ToValue(cards)) } return 0 } //两对(Two Pairs) //两对点数相同但两两不同的扑克和随意的一张牌组成。 //平手牌:如果不止一人抓大此牌相,牌点比较大的人赢,如果比较大的牌点相同,那么较小牌点中的较大者赢, //如果两对牌点相同,那么第五张牌点较大者赢(起脚牌,2张起手牌中小的那张就叫做起脚牌)。如果起脚牌也相同,则平分彩池。 func (this *Cards) twoPair() uint32 { cards := *this length := len(cards) if length >= 4 { if cards[length-1]&0xF == cards[length-2]&0xF && cards[length-3]&0xF == cards[length-4]&0xF { return En(TWO_PAIR, ToValue(cards)) } } return 0 } //一对(One Pair) //由两张相同点数的扑克牌和另三张随意的牌组成。 //平手牌:如果不止一人抓到此牌,则两张牌中点数大的赢,如果对牌都一样,则比较另外三张牌中大的赢, //如果另外三张牌中较大的也一样则比较第二大的和第三大的,如果所有的牌都一样,则平分彩池。 func (this *Cards) onePair() uint32 { cards := *this length := len(cards) if length >= 2 { if cards[length-1]&0xF == cards[length-2]&0xF { return En(ONE_PAIR, ToValue(cards)) } } return 0 } func ToValue(cards []byte) uint32 { var res uint32 for i := len(cards) - 1; i >= 0; i-- { res *= 10 res += uint32(cards[i] & 0xF) } return res } func De(v uint32) (uint8, uint32) { return uint8(v >> 24), v & 0xFFFFFF } func En(t uint8, v uint32) uint32 { v1 := v | ( uint32(t) << 24) return v1 } ``` ================================================ FILE: bin/build-linux.sh ================================================ #!/bin/bash # usage ./build-linux.sh 1.0.13 curDir=`pwd` GREEN="\e[1;32m" RESET="\e[0m" echo -e "${GREEN} current dir is $curDir ${RESET}" d=`date "+%Y-%m-%d-%H-%M-%S"` echo -e "${GREEN} mkpkg_time is $d ${RESET}" pkg_version=$1 echo -e "${GREEN} pkg_version is $pkg_version ${RESET}" cd $curDir/.. STRING_GAME=`git log | head -n 1 | awk '{print $2}'` echo -e "${GREEN} game commit is $STRING_GAME ${RESET}" cd $curDir/.. echo `pwd` cd $curDir/.. export GOPATH=`pwd` export GOARCH=amd64 export GOOS=linux cd bin go build -o game -ldflags "-X main.Commit=$STRING_GAME -X 'main.BUILD_TIME=`date`' -X main.VERSION=$1 -s -w" ../src/main.go read -p "Press any key to continue." var ================================================ FILE: bin/build-win.sh ================================================ #!/bin/bash # usage ./build-linux.sh 1.0.13 curDir=`pwd` GREEN="\e[1;32m" RESET="\e[0m" echo -e "${GREEN} current dir is $curDir ${RESET}" d=`date "+%Y-%m-%d-%H-%M-%S"` echo -e "${GREEN} mkpkg_time is $d ${RESET}" pkg_version=$1 echo -e "${GREEN} pkg_version is $pkg_version ${RESET}" cd $curDir/.. STRING_GAME=`git log | head -n 1 | awk '{print $2}'` echo -e "${GREEN} game commit is $STRING_GAME ${RESET}" cd $curDir/.. echo `pwd` cd $curDir/.. export GOPATH=`pwd` #export GOARCH=amd64 #export GOOS=linux cd bin go build -o game.exe -ldflags "-X main.Commit=$STRING_GAME -X 'main.BUILD_TIME=`date`' -X main.VERSION=$1 -s -w" ../src/main.go read -p "Press any key to continue." var ================================================ FILE: bin/client/.gitignore ================================================ #IDE /library /local /build /temp /.idea /settings ================================================ FILE: bin/client/README.md ================================================ # Cocos Creator 写的一个德州扑克的游戏回放,仅供参考 ================================================ FILE: bin/client/assets/Scene/main.fire ================================================ [ { "__type__": "cc.SceneAsset", "_name": "", "_objFlags": 0, "_rawFiles": null, "scene": { "__id__": 1 } }, { "__type__": "cc.Scene", "_name": "main", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": null, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 0 }, "_children": [ { "__id__": 2 } ], "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "b1a3242c-6595-42df-a0fc-e177f727763d" }, { "__type__": "cc.Node", "_name": "Canvas", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 1 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 1000, "height": 1560 }, "_children": [ { "__id__": 3 }, { "__id__": 113 }, { "__id__": 114 }, { "__id__": 115 }, { "__id__": 116 }, { "__id__": 117 }, { "__id__": 118 }, { "__id__": 124 } ], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 500, "y": 780 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "87318gAtAVE5YV5wEAYBbcX", "_active": true, "_components": [ { "__id__": 126 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "table_bg", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 2 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 1130, "height": 1560 }, "_children": [ { "__id__": 4 }, { "__id__": 14 }, { "__id__": 23 }, { "__id__": 33 }, { "__id__": 43 }, { "__id__": 53 }, { "__id__": 63 }, { "__id__": 73 }, { "__id__": 83 }, { "__id__": 93 }, { "__id__": 96 }, { "__id__": 99 }, { "__id__": 102 }, { "__id__": 103 }, { "__id__": 104 }, { "__id__": 105 }, { "__id__": 106 }, { "__id__": 107 }, { "__id__": 108 }, { "__id__": 109 }, { "__id__": 110 } ], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "6a97a8/GAFHTrJP5XWtPkx+", "_active": true, "_components": [ { "__id__": 111 }, { "__id__": 112 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "seat_0", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 120, "height": 120 }, "_children": [ { "__id__": 5 }, { "__id__": 6 }, { "__id__": 9 }, { "__id__": 12 } ], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -400 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "a77cbKPk7hJC4cLSMT0rUGm", "_active": true, "_components": [ { "__id__": 13 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "game_tip", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 4 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 126, "height": 66 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 57, "y": 25 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "e6321VmItNCOq39iH20y4D0", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "nick", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 4 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": 80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "b5985lBCBtArp9Et9uVxeuV", "_active": true, "_components": [ { "__id__": 7 } ], "_prefab": { "__id__": 8 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 6 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 6 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "chips", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 4 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "d7f9ekaZJNIPrjltUVmLBBo", "_active": true, "_components": [ { "__id__": 10 } ], "_prefab": { "__id__": 11 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 9 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 9 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "dealer", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 4 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 49, "height": 49 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "79758mNFOpDLrMwtBnAvIg+", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 4 }, "_enabled": true, "_spriteFrame": { "__uuid__": "d79f84c5-d5e1-4aad-b902-431289fb7b91" }, "_type": 0, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "aae22d42-a9cf-43f5-8c35-5348d3f98f75" } }, { "__type__": "cc.Node", "_name": "seat_1", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 120, "height": 120 }, "_children": [ { "__id__": 15 }, { "__id__": 16 }, { "__id__": 19 }, { "__id__": 21 } ], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -390, "y": -150 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "8eaf6bTIINJz4hs4ELd7LIC", "_active": true, "_components": [ { "__id__": 22 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "game_tip", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 14 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 84, "height": 44 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 57, "y": 25 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "962c2ULwpBJaoIwjW1zWooB", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "nick", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 14 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": 80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "177242DBgJOW5LB5ocvKbHd", "_active": true, "_components": [ { "__id__": 17 } ], "_prefab": { "__id__": 18 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 16 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 16 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "chips", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 14 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "c4e04pvk+1AQZ3b+Qo5WlBj", "_active": true, "_components": [ { "__id__": 20 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 19 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.Node", "_name": "dealer", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 14 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 49, "height": 49 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "fff0dgsq5dCCYzVoSa0NLFH", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 14 }, "_enabled": true, "_spriteFrame": { "__uuid__": "d79f84c5-d5e1-4aad-b902-431289fb7b91" }, "_type": 0, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "aae22d42-a9cf-43f5-8c35-5348d3f98f75" } }, { "__type__": "cc.Node", "_name": "seat_2", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 120, "height": 120 }, "_children": [ { "__id__": 24 }, { "__id__": 25 }, { "__id__": 28 }, { "__id__": 31 } ], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -390, "y": 130 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "d4dacl6zv5Ow4WGZ2PaTaKH", "_active": true, "_components": [ { "__id__": 32 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "game_tip", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 23 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 84, "height": 44 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 57, "y": 25 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "c0373XWaEZKVoEMveh6Byv0", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "nick", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 23 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": 80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "c4a51CETARKJ7Hupl1PiIH3", "_active": true, "_components": [ { "__id__": 26 } ], "_prefab": { "__id__": 27 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 25 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 25 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "chips", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 23 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "d7e1eLUZwBPQKIq6c+a2ZtB", "_active": true, "_components": [ { "__id__": 29 } ], "_prefab": { "__id__": 30 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 28 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 28 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "dealer", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 23 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 49, "height": 49 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "fa223AJdGpFGoH5iZ35SGZp", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 23 }, "_enabled": true, "_spriteFrame": { "__uuid__": "d79f84c5-d5e1-4aad-b902-431289fb7b91" }, "_type": 0, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "aae22d42-a9cf-43f5-8c35-5348d3f98f75" } }, { "__type__": "cc.Node", "_name": "seat_3", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 120, "height": 120 }, "_children": [ { "__id__": 34 }, { "__id__": 35 }, { "__id__": 38 }, { "__id__": 41 } ], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -390, "y": 390 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "a16d3140NtLsrxjigsyOQfh", "_active": true, "_components": [ { "__id__": 42 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "game_tip", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 33 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 84, "height": 44 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 45, "y": 25 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "95104GXzj9EvI7iZP12FXqA", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "nick", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 33 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": 80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "d74793N9JZJsaBnAMHgCIPx", "_active": true, "_components": [ { "__id__": 36 } ], "_prefab": { "__id__": 37 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 35 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 35 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "chips", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 33 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "27356QU50RDEouIwSE8tKuc", "_active": true, "_components": [ { "__id__": 39 } ], "_prefab": { "__id__": 40 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 38 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 38 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "dealer", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 33 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 49, "height": 49 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "d3c63DFPAhEvb5HPeZXBiqq", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 33 }, "_enabled": true, "_spriteFrame": { "__uuid__": "d79f84c5-d5e1-4aad-b902-431289fb7b91" }, "_type": 0, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "aae22d42-a9cf-43f5-8c35-5348d3f98f75" } }, { "__type__": "cc.Node", "_name": "seat_4", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 120, "height": 120 }, "_children": [ { "__id__": 44 }, { "__id__": 45 }, { "__id__": 48 }, { "__id__": 51 } ], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -175, "y": 620 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "bf93f39ZKVKzLx2Z0FUAVUV", "_active": true, "_components": [ { "__id__": 52 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "game_tip", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 43 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 84, "height": 44 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 57, "y": 25 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "d4efaYy8DxK47KmObsV2Zv0", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "nick", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 43 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": 80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "0f71a4d0ihDMJd9Iv/1UQyb", "_active": true, "_components": [ { "__id__": 46 } ], "_prefab": { "__id__": 47 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 45 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 45 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "chips", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 43 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "65c4a5Jz9JJl45WlN4LSGiY", "_active": true, "_components": [ { "__id__": 49 } ], "_prefab": { "__id__": 50 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 48 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 48 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "dealer", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 43 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 49, "height": 49 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 70, "y": -120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "45095damKtPRJVVq1Ng0pCF", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 43 }, "_enabled": true, "_spriteFrame": { "__uuid__": "d79f84c5-d5e1-4aad-b902-431289fb7b91" }, "_type": 0, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "aae22d42-a9cf-43f5-8c35-5348d3f98f75" } }, { "__type__": "cc.Node", "_name": "seat_5", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 120, "height": 120 }, "_children": [ { "__id__": 54 }, { "__id__": 55 }, { "__id__": 58 }, { "__id__": 61 } ], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 175, "y": 620 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "7be73w6tbdBNo4WHG0mlL7U", "_active": true, "_components": [ { "__id__": 62 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "game_tip", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 53 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 84, "height": 44 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 57, "y": 25 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "6f98bsA9AxN84J5Aqf7k9ge", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "nick", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 53 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": 80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "7b5f9DG+iJCE51ng0jOR4Ph", "_active": true, "_components": [ { "__id__": 56 } ], "_prefab": { "__id__": 57 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 55 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 55 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "chips", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 53 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 30 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "d9410bRjjNBIpapyHQeAgXY", "_active": true, "_components": [ { "__id__": 59 } ], "_prefab": { "__id__": 60 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 58 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 30, "_lineHeight": 30, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 58 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "dealer", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 53 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 49, "height": 49 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 70, "y": -120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "65249M1zoNCuLBfLiaGQ14t", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 53 }, "_enabled": true, "_spriteFrame": { "__uuid__": "d79f84c5-d5e1-4aad-b902-431289fb7b91" }, "_type": 0, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "aae22d42-a9cf-43f5-8c35-5348d3f98f75" } }, { "__type__": "cc.Node", "_name": "seat_6", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 120, "height": 120 }, "_children": [ { "__id__": 64 }, { "__id__": 65 }, { "__id__": 68 }, { "__id__": 71 } ], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 390, "y": 370 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "8b241vXXqhO4J9ETIF7kyNs", "_active": true, "_components": [ { "__id__": 72 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "game_tip", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 63 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 84, "height": 44 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -57, "y": 25 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "13e059qeMhMJoGCrpG7TOQ5", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "nick", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 63 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": 80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "75b76qW2hVKyr4u0xEL5p8N", "_active": true, "_components": [ { "__id__": 66 } ], "_prefab": { "__id__": 67 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 65 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 65 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "chips", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 63 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "101aeHhphhCuY3xCjkDA5Qy", "_active": true, "_components": [ { "__id__": 69 } ], "_prefab": { "__id__": 70 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 68 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 68 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "dealer", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 63 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 49, "height": 49 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "ce9bbv6DkhHnpGLs0p3Ryj8", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 63 }, "_enabled": true, "_spriteFrame": { "__uuid__": "d79f84c5-d5e1-4aad-b902-431289fb7b91" }, "_type": 0, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "aae22d42-a9cf-43f5-8c35-5348d3f98f75" } }, { "__type__": "cc.Node", "_name": "seat_7", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 120, "height": 120 }, "_children": [ { "__id__": 74 }, { "__id__": 75 }, { "__id__": 78 }, { "__id__": 81 } ], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 390, "y": 120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "84471vfDJxDVpxYeb5w9SYZ", "_active": true, "_components": [ { "__id__": 82 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "game_tip", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 73 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 84, "height": 44 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -57, "y": 25 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "4bfd5Oguv1GFoP0ZH9zZDwt", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "nick", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 73 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": 80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "eea181g0MBJK7pCa4i8LrUI", "_active": true, "_components": [ { "__id__": 76 } ], "_prefab": { "__id__": 77 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 75 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 75 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "chips", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 73 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "b5df1+V6p1B6qQHct0iNb5x", "_active": true, "_components": [ { "__id__": 79 } ], "_prefab": { "__id__": 80 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 78 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 78 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "dealer", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 73 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 49, "height": 49 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "a8f09ejpfZMz7MVBhrBTSd9", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 73 }, "_enabled": true, "_spriteFrame": { "__uuid__": "d79f84c5-d5e1-4aad-b902-431289fb7b91" }, "_type": 0, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "aae22d42-a9cf-43f5-8c35-5348d3f98f75" } }, { "__type__": "cc.Node", "_name": "seat_8", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 120, "height": 120 }, "_children": [ { "__id__": 84 }, { "__id__": 85 }, { "__id__": 88 }, { "__id__": 91 } ], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 390, "y": -150 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "db9baRfhdhG2Jd+E6yd9PLS", "_active": true, "_components": [ { "__id__": 92 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "game_tip", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 83 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 84, "height": 44 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -57, "y": 25 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "fd559/cArpGureRfY2KpGUM", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "nick", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 83 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": 80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "93285anWC9B3o8gQVYDumlQ", "_active": true, "_components": [ { "__id__": 86 } ], "_prefab": { "__id__": 87 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 85 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 85 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "chips", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 83 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 30 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "70704I7fddPjrHX0g2pZ0jM", "_active": true, "_components": [ { "__id__": 89 } ], "_prefab": { "__id__": 90 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 88 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 30, "_lineHeight": 30, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 88 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "dealer", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 83 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 49, "height": 49 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "30296IaWKZCgZQC5QW9wx2Q", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 83 }, "_enabled": true, "_spriteFrame": { "__uuid__": "d79f84c5-d5e1-4aad-b902-431289fb7b91" }, "_type": 0, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "aae22d42-a9cf-43f5-8c35-5348d3f98f75" } }, { "__type__": "cc.Node", "_name": "table_name", "_objFlags": 0, "_opacity": 100, "_color": { "__type__": "cc.Color", "r": 0, "g": 0, "b": 0, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -90 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "97213vbSklNu5yDYLowSVHv", "_active": true, "_components": [ { "__id__": 94 } ], "_prefab": { "__id__": 95 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 93 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 93 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "table_sb", "_objFlags": 0, "_opacity": 100, "_color": { "__type__": "cc.Color", "r": 0, "g": 0, "b": 0, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "761e9iWpWlKpZWglCafBzGB", "_active": true, "_components": [ { "__id__": 97 } ], "_prefab": { "__id__": 98 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 96 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 96 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "table_code", "_objFlags": 0, "_opacity": 100, "_color": { "__type__": "cc.Color", "r": 0, "g": 0, "b": 0, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -150 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "595b9sZGmZJVIz744IUjFK1", "_active": true, "_components": [ { "__id__": 100 } ], "_prefab": { "__id__": 101 }, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 99 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": false, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 99 }, "asset": { "__uuid__": "27756ebb-3d33-44b0-9b96-e858fadd4dd4" }, "fileId": "d1cddH/doRNQ4Aodz8556bh" }, { "__type__": "cc.Node", "_name": "chip_0", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 39, "height": 41 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": -200 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "b34b8yrHDNM3qON31vbAbb6", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "chip_1", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 39, "height": 41 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -250, "y": -150 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "10b5d6zB5VOFJ8CtGl8Nd0z", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "chip_2", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 39, "height": 41 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -250, "y": 120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "a7165YJkzBHoKvKHWXyh5jz", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "chip_3", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 39, "height": 41 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -250, "y": 370 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "b95fbuF4plGLa8acAbzF7kj", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "chip_4", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 39, "height": 41 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -175, "y": 450 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "fb9a2suBehPNqtNzkQdCIWY", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "chip_5", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 39, "height": 41 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 175, "y": 450 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "dfcd4NG8nxAsJ4ulKgUoEfq", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "chip_6", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 39, "height": 41 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 250, "y": 370 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "1875bUQ1ltHIrDDTG0+Y3oP", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "chip_7", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 39, "height": 41 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 250, "y": 120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "f939fyrLvNHcb1o/S68syx+", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "chip_8", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 3 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 39, "height": 41 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 250, "y": -150 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "c29a0hhCtFOtLyKhsq0nHax", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 3 }, "_enabled": true, "_spriteFrame": { "__uuid__": "d5e079ed-488b-4fd5-8bc3-b3e082b34d96" }, "_type": 1, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": null }, { "__type__": "cc.Layout", "_name": "", "_objFlags": 0, "node": { "__id__": 3 }, "_enabled": true, "_layoutSize": { "__type__": "cc.Size", "width": 1130, "height": 1560 }, "_resize": 0, "_N$layoutType": 0, "_N$cellSize": { "__type__": "cc.Size", "width": 40, "height": 40 }, "_N$startAxis": 0, "_N$padding": 0, "_N$spacingX": 0, "_N$spacingY": 0, "_N$verticalDirection": 1, "_N$horizontalDirection": 0 }, { "__type__": "cc.Node", "_name": "card0", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 2 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 0 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -170, "y": -10 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "ca588XWyEVDIK8moOgxwnrm", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "card1", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 2 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 0 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -170, "y": -10 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "3cbe6OFjcNHK7fXsno5sXom", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "card2", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 2 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 0 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -170, "y": -10 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "167adzrdW5BM7Yx0rxc2ABx", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "card3", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 2 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 0 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 101, "y": -10 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "417c4ciIrxAYI2qbNu25uRY", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "card4", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 2 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 0 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 192, "y": -10 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "c8528G8OaZH4qY7cTUAxkwB", "_active": true, "_components": [], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "sound", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 2 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 128, "height": 128 }, "_children": [ { "__id__": 119 } ], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": -377, "y": -607 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "f13a5PxN+tM0LRToQ5jBGcA", "_active": true, "_components": [ { "__id__": 121 }, { "__id__": 122 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Node", "_name": "sound_tips", "_objFlags": 0, "_opacity": 0, "_color": { "__type__": "cc.Color", "r": 220, "g": 238, "b": 11, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 118 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 25 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": 88 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "daabcnNxuJMuIwLimc6980Z", "_active": true, "_components": [ { "__id__": 120 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 119 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 40, "_fontSize": 25, "_lineHeight": 25, "_enableWrapText": true, "_N$file": null, "_isSystemFontUsed": true, "_N$string": "", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$overflow": 0 }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 118 }, "_enabled": true, "_spriteFrame": { "__uuid__": "78f76275-b201-4017-8f0f-70664c14a542" }, "_type": 0, "_sizeMode": 1, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "aae22d42-a9cf-43f5-8c35-5348d3f98f75" } }, { "__type__": "cc.Button", "_name": "", "_objFlags": 0, "node": { "__id__": 118 }, "_enabled": true, "transition": 0, "pressedColor": { "__type__": "cc.Color", "r": 211, "g": 211, "b": 211, "a": 255 }, "hoverColor": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "duration": 0.1, "pressedSprite": null, "hoverSprite": null, "clickEvents": [ { "__id__": 123 } ], "_N$interactable": true, "_N$normalColor": { "__type__": "cc.Color", "r": 214, "g": 214, "b": 214, "a": 255 }, "_N$disabledColor": { "__type__": "cc.Color", "r": 124, "g": 124, "b": 124, "a": 255 }, "_N$normalSprite": null, "_N$disabledSprite": null, "_N$target": { "__id__": 118 } }, { "__type__": "cc.ClickEvent", "target": { "__id__": 124 }, "component": "main", "handler": "set_mute" }, { "__type__": "cc.Node", "_name": "Main", "_objFlags": 0, "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_parent": { "__id__": 2 }, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 0 }, "_children": [], "_rotationX": 0, "_rotationY": 0, "_scaleX": 1, "_scaleY": 1, "_position": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_tag": -1, "_opacityModifyRGB": false, "_reorderChildDirty": false, "_id": "7d6b9Jtb9RNbbKkh4/IG5cv", "_active": true, "_components": [ { "__id__": 125 } ], "_prefab": null, "groupIndex": 0 }, { "__type__": "ba49cogWFZADYkzvB39Ug3B", "_name": "", "_objFlags": 0, "node": { "__id__": 124 }, "_enabled": true, "seat": [], "Lang": null, "SourceSuffix": null, "GameMain": null, "GameCards": null, "audio_chipsToTable": null, "audio_check": null, "audio_fold": null, "audio_distributeCard": null, "open_fixedThinkTime": 0, "fixedThinkTime": 2, "open_mute": 0, "is_mobile": 0, "fontStyle": null, "countdown_execution_interval": 0.1, "countdown_repeat_num": 0, "countdown_long_time": 0, "countdown_cycle_time": 15, "countdown_node": null, "countdown_task": null, "countdown_over_task": null, "actions": null, "i": 0, "ws": null, "hand_data": null, "data": null, "card": [ { "__id__": 113 }, { "__id__": 114 }, { "__id__": 115 }, { "__id__": 116 }, { "__id__": 117 } ], "inpot": null, "table_chips_inpot": 0, "table_chips": [], "table_tips": [], "game_card_turn": 0, "game_card_river": 0, "cleanNode": [], "cleanSp": [], "game_start": 0 }, { "__type__": "cc.Canvas", "_name": "", "_objFlags": 0, "node": { "__id__": 2 }, "_enabled": true, "_designResolution": { "__type__": "cc.Size", "width": 1000, "height": 1560 }, "_fitWidth": false, "_fitHeight": true } ] ================================================ FILE: bin/client/assets/Scene/main.fire.meta ================================================ { "ver": "1.0.0", "uuid": "b1a3242c-6595-42df-a0fc-e177f727763d", "subMetas": {} } ================================================ FILE: bin/client/assets/Scene.meta ================================================ { "ver": "1.0.1", "uuid": "a6716ca2-df58-41aa-b8d3-8ca203720a85", "isGroup": false, "subMetas": {} } ================================================ FILE: bin/client/assets/Script/Common.js ================================================ cc.Class({ extends: cc.Component, properties: { seat:{ default:[], type:cc.Node }, Lang:null,//语言版本 SourceSuffix:null,//资源后缀 GameMain:null,//游戏资源 GameCards:null,//游戏的牌中的资源 audio_chipsToTable:null,//下注的音频 audio_check:null,//check的音频 audio_fold:null,//fold的音频 audio_distributeCard:null,//翻牌的声音 open_fixedThinkTime:0,//开启固定思考时间的设置0-否1-开启 fixedThinkTime:2,//固定思考时间,配合open_fixedThinkTime使用,单位:秒 open_mute:0,//是否开启静音模式0-否1-是 is_mobile:0,//是否是手机访问0-否1-是 fontStyle:null,//字体样式 //websocket ws:null, }, //web socket连接 wsstart:function(){ var me=this; var ws = new WebSocket("ws://127.0.0.1:3564"); ws.binaryType = "arraybuffer" ; var decoder = new TextDecoder('utf-8') ws.onopen = function (event) { me.ws = ws; console.log("Send Text WS was opened."); }; ws.onmessage = function (event) { console.log("response text msg: " + event.data); var input = event.data; var data = JSON.parse(decoder.decode(event.data)); console.log("server response"); console.log(data); }; ws.onerror = function (event) { console.log("Send Text fired an error"); }; ws.onclose = function (event) { console.log("WebSocket instance closed."); }; //setTimeout(function () { // if(me.ws!=null){ // cc.log(me.ws.readyState); // if (me.ws.readyState === WebSocket.OPEN) { // cc.log("send message to server3000"); // me.ws.send(JSON.stringify({Ai: { // Ai_id: '123456', // Hand:[1,2] // }})) // } // else { // console.log("WebSocket instance wasn't ready..."); // } // }else{ // cc.log("ws is null"); // } //}, 3000); }, sit_down:function(){ //加载游戏资源图片 var me = this; me.is_mobile = this.isMobile(); if(me.is_mobile == 1){ me.fontStyle={ "table_name":{"fontSize":30,"lineHeight":30}, "table_sb":{"fontSize":30,"lineHeight":30}, "table_code":{"fontSize":30,"lineHeight":30}, "nick":{"fontSize":30,"lineHeight":30}, "chips":{"fontSize":30,"lineHeight":30}, "chip":{"fontSize":30,"lineHeight":30}, "pot":{"fontSize":30,"lineHeight":30} }; }else{ me.fontStyle={ "table_name":{"fontSize":25,"lineHeight":25}, "table_sb":{"fontSize":25,"lineHeight":25}, "table_code":{"fontSize":25,"lineHeight":25}, "nick":{"fontSize":25,"lineHeight":25}, "chips":{"fontSize":25,"lineHeight":25}, "chip":{"fontSize":25,"lineHeight":25}, "pot":{"fontSize":25,"lineHeight":25} }; } cc.loader.loadRes("game_cards",cc.SpriteAtlas,function(err,atlas){ me.GameCards = atlas; }); //加载游戏音频 if(this.open_mute == 0){ cc.loader.loadRes("audio/audio_chipsToTable", function (err, assets) { me.audio_chipsToTable = assets; }); cc.loader.loadRes("audio/audio_check", function (err, assets) { me.audio_check = assets; }); cc.loader.loadRes("audio/audio_fold", function (err, assets) { me.audio_fold = assets; }); cc.loader.loadRes("audio/audio_distributeCard", function (err, assets) { me.audio_distributeCard = assets; }); } var table_data = this.hand_data; table_data['table_name']=table_data['table_name']?table_data['table_name']:""; table_data['table_code']=table_data['table_code']?table_data['table_code']:""; var node_table_bg = cc.find("Canvas/table_bg"); //异步加载头像,不能放在循环内 var load_avatar = function(url,sprite_user){ cc.loader.load(url,function(err,tex){ var frame = new cc.SpriteFrame(tex,cc.Rect(0, 0, 87, 123)); sprite_user.spriteFrame = frame; }); }; cc.loader.loadRes("GameMain_6p",cc.SpriteAtlas,function(err,atlas){ me.GameMain = atlas; var sb_data = null;//小盲的数据 var bb_data = null;//大盲的数据 //坐下 for(var k in table_data['players']){ var v = table_data['players'][k]; var seat_node = node_table_bg.getChildByName("seat_"+v['chair_id']); var node_size = seat_node.getContentSize();//获取node的尺寸 //名字 var label_nick = seat_node.getChildByName("nick").getComponent(cc.Label); label_nick.string = me.getLength(v['nick'])>10?me.cutStr(v['nick'],7):v['nick']; label_nick.fontSize = me.fontStyle['nick']['fontSize']; label_nick.lineHeight = me.fontStyle['nick']['lineHeight']; //带入的筹码 var label_chips = seat_node.getChildByName("chips").getComponent(cc.Label); label_chips.string = v['remain_chip']+v['table_chip']; label_chips.fontSize = me.fontStyle['chips']['fontSize']; label_chips.lineHeight = me.fontStyle['chips']['lineHeight']; //头像 var node_mark = new cc.Node(); node_mark.name='avatar'; var mask_user = node_mark.addComponent(cc.Mask); mask_user.type = cc.Mask.ELLIPSE; node_mark.width = node_size['width']-15; node_mark.height = node_size['height']-15; node_mark.setPosition(0.5,0.5); node_mark.parent = seat_node; var node_user = new cc.Node(); var sprite_user = node_user.addComponent(cc.Sprite); node_user.parent = node_mark; if(v['avatar'] != null && v['avatar']!=""){ node_user.scale = (node_size['width']-15)/120; load_avatar(v['avatar'],sprite_user); }else{ sprite_user.spriteFrame = me.GameMain.getSpriteFrame("game_seat_valid"); } seat_node.getChildByName("game_tip").setLocalZOrder(2); if(v['chair_id'] == table_data['start']['sb_chair']){ sb_data = v; }else if(v['chair_id'] == table_data['start']['bb_chair']){ bb_data = v; } } //牌局名字 var label = node_table_bg.getChildByName("table_name").getComponent(cc.Label); label.string = "§ " + table_data['table_name'] + " §"; label.fontSize = me.fontStyle['table_name']['fontSize']; label.lineHeight = me.fontStyle['table_name']['lineHeight']; //牌局号,如果是快速牌局显示牌局号,如果是俱乐部牌局,显示盲注 if(parseInt(table_data['table_code'])!=0){ var label_table_code = node_table_bg.getChildByName("table_code").getComponent(cc.Label); label_table_code.string = table_data['table_code']; label_table_code.fontSize = me.fontStyle['table_code']['fontSize']; label_table_code.lineHeight = me.fontStyle['table_code']['lineHeight']; } //盲注 var label_table_sb = node_table_bg.getChildByName("table_sb").getComponent(cc.Label); label_table_sb.string = me.ConvertLang("blind")+" "+sb_data['table_chip']+"/"+bb_data['table_chip']; label_table_sb.fontSize = me.fontStyle['table_sb']['fontSize']; label_table_sb.lineHeight = me.fontStyle['table_sb']['lineHeight']; //删除加载图片 var splash = document.getElementById('splash'); if(undefined!=splash){ splash.style.display = 'none'; } }); }, //监听座位点击事件 onSeat:function(){ cc.log("onSeat init"); var node_table_bg = cc.find("Canvas/table_bg"); for(var i=0;i<9;i++){ //var v = table_data['players'][k]; var seat_node = node_table_bg.getChildByName("seat_"+i); seat_node.on("mouseup",function(event){ this.seatClick (event); },this); } }, //点击座位坐下 未完成 seatClick:function(e){ var me = this; var rName = cc.random0To1(); var v={}; v["nick"] = "波霸"+rName; v["remain_chip"] = "1000"; v["table_chip"] = "10"; //v["avatar"] = "/1_5734451068aaa.jpg"; v["avatar"] = ""; if(me.ws){ //请求后台坐下 if (me.ws.readyState === WebSocket.OPEN) { cc.log("send message to server3000"); me.ws.send(JSON.stringify({C2S_Join: { UserId: '123456', UserName:v["nick"], TableId:'22222', UserToken:'33333', }})); me.ws.send(JSON.stringify({C2S_Login: { UserAccount: "tian", UserName: "nick", UserPassword: "123456", }})); } else { this.wsstart(); console.log("WebSocket instance wasn't ready..."); } }; var seatName = e.currentTarget._name; var node_table_bg = cc.find("Canvas/table_bg"); var seat_node = node_table_bg.getChildByName(seatName); var node_size = seat_node.getContentSize();//获取node的尺寸 //名字 var label_nick = seat_node.getChildByName("nick").getComponent(cc.Label); label_nick.string = me.getLength(v['nick'])>10?me.cutStr(v['nick'],7):v['nick']; label_nick.fontSize = 30; label_nick.lineHeight = 30; //带入的筹码 var label_chips = seat_node.getChildByName("chips").getComponent(cc.Label); label_chips.string = v['remain_chip']+v['table_chip']; label_chips.fontSize = 30; label_chips.lineHeight = 30; //头像 var node_mark = new cc.Node(); node_mark.name='avatar'; var mask_user = node_mark.addComponent(cc.Mask); mask_user.type = cc.Mask.ELLIPSE; node_mark.width = node_size['width']-15; node_mark.height = node_size['height']-15; node_mark.setPosition(0.5,0.5); node_mark.parent = seat_node; var node_user = new cc.Node(); var sprite_user = node_user.addComponent(cc.Sprite); node_user.parent = node_mark; if(v['avatar'] != null && v['avatar']!=""){ //异步加载头像,不能放在循环内 var load_avatar = function(url,sprite_user){ cc.loader.load(url,function(err,tex){ var frame = new cc.SpriteFrame(tex,cc.Rect(0, 0, 87, 123)); sprite_user.spriteFrame = frame; }); }; node_user.scale = (node_size['width']-15)/120; load_avatar(v['avatar'],sprite_user); }else{ if(this.GameMain == null){ cc.loader.loadRes("GameMain_6p",cc.SpriteAtlas,function(err,atlas){ this.GameMain = atlas; sprite_user.spriteFrame = this.GameMain.getSpriteFrame("game_seat_valid"); }); }else{ sprite_user.spriteFrame = this.GameMain.getSpriteFrame("game_seat_valid"); } } seat_node.getChildByName("game_tip").setLocalZOrder(2); }, //js获取当前url的参数 getQueryString:function(name){ if(undefined==window.location){ return null; }; var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if(r!=null){ return unescape(r[2]); }else{ return null; } }, //获取字符串长度 getLength:function (str) { ///获得字符串实际长度,中文2,英文1 ///要获得长度的字符串 var realLength = 0, len = str.length, charCode = -1; for (var i = 0; i < len; i++) { charCode = str.charCodeAt(i); if (charCode >= 0 && charCode <= 128) realLength += 1; else realLength += 2; } return realLength; }, //s截取字符串,中英文都能用@param str:需要截取的字符串@param len: 需要截取的长度 cutStr:function (str, len) { var str_length = 0; var str_len = str.length; var str_cut = new String(); for (var i = 0; i < str_len; i++) { var a = str.charAt(i); str_length++; if (escape(a).length > 4) { //中文字符的长度经编码之后大于4 str_length++; } str_cut = str_cut.concat(a); if (str_length >= len) { str_cut = str_cut.concat("..."); return str_cut; } } //如果给定字符串小于指定长度,则返回源字符串; if (str_length < len) { return str; } }, //开启静音模式status:0-关闭1-开启 set_mute:function(){ var sprite_url = ""; if(this.open_mute == 1){ this.open_mute = 0; sprite_url='open_audio'; }else{ this.open_mute = 1; sprite_url='close_audio'; } var fast_forward =cc.find("Canvas/sound"); var sprite = fast_forward.getComponent(cc.Sprite); sprite.spriteFrame = this.GameMain.getSpriteFrame(sprite_url); }, //判断是否是手机访问 isMobile:function(){ var ua = navigator.userAgent; var ipad = ua.match(/(iPad).*OS\s([\d_]+)/), isIphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/), isAndroid = ua.match(/(Android)\s+([\d.]+)/), isMobile = isIphone || isAndroid; var bool = isMobile === null?0:1; return bool; }, //语言翻译 ConvertLang:function(key){ var config_lang={}; config_lang['zh-cn']={"pot":"底池","blind":"盲注","mute":"静音","no_think":"忽略思考时间"}; config_lang['zh-tw']={"pot":"底池","blind":"盲注","mute":"靜音","no_think":"忽略思考時間"}; config_lang['thai-th']={"pot":"กองกลาง","blind":"Stakes","mute":"ปิดเสียง","no_think":"fast-forwward"}; config_lang['en-us']={"pot":"Pot","blind":"Stakes","mute":"Mute","no_think":"fast-forwward"}; config_lang['ko']={"pot":"바닥풀 ","blind":"맹주","mute":"정음 ","no_think":"忽略思考时间"}; return config_lang[this.Lang][key]; }, //多语言替换座位 //ReplaceSeat:function(){ // if(this.Lang == 'thai-th'){ // for(var i=0;i<9;i++){ // cc.find("Canvas/table_bg/seat_"+i).getComponent(cc.Sprite).setVisible(false); // } // cc.loader.loadRes("GameMain_th_6p",cc.SpriteAtlas,function(err,atlas){ // var game_seat_empty = atlas.getSpriteFrame("game_seat_empty"); // for(var i=0;i<9;i++){ // var sprite = cc.find("Canvas/table_bg/seat_"+i).getComponent(cc.Sprite) // sprite.spriteFrame = game_seat_empty; // sprite.setVisible(true); // } // }); // } //} }); ================================================ FILE: bin/client/assets/Script/Common.js.meta ================================================ { "ver": "1.0.2", "uuid": "b91d4d1c-d6e8-4abe-8ab4-226f9e1dce57", "isPlugin": false, "subMetas": {} } ================================================ FILE: bin/client/assets/Script/CountDown.js ================================================ var Common = require('Common'); cc.Class({ extends: Common, properties: { //倒计时 countdown_execution_interval:0.1,//执行间隔 countdown_repeat_num:0,//重复了多少次 countdown_long_time:0,//倒计时时长,单位:秒 countdown_cycle_time:15,//倒计时一圈的时间,单位:秒 countdown_node:{ default:null, type:cc.Node },//倒计时,遮罩层所在的node countdown_task:null,//倒计时执行任务,是一个function,方便销毁定时器 countdown_over_task:null,//倒计时结束,是一个function,执行完毕,最后会执行这个 //动作列表 actions:null, //正在进行的动作 i:0, //该牌局的是数据 hand_data:null }, //添加倒计时的进度条 add_countdown:function(seat_number,long_time){ var me = this; var action_num = this.i-1;//当前第几个动作 if(parseInt(long_time) == 0 ){ this.scheduleOnce(function(){ me.scheduleOnce(this.countdown_over_task,0); },1); var action_type = this.open_fixedThinkTime == 1?1:0;//动作状态 0-正常1-快进 //判断是否有正在进行的其他动作 this.scheduleOnce(function(){ this.start_others(action_type,0,action_num); },0.5); return false; }else{ //判断是否开启固定思考模式 if(me.open_fixedThinkTime == 1){ long_time = me.fixedThinkTime; } } var node_table_bg = cc.find("Canvas/table_bg"); //初始化 this.countdown_repeat_num = 0; this.countdown_long_time = 0; this.countdown_cycle_time = 15; if(this.countdown_task!= null){ this.unschedule(this.countdown_task);//删除定时任务 this.countdown_node.destroy();//删除该节点 } var seat = node_table_bg.getChildByName("seat_"+seat_number);//获取该作为的节点 //倒计时遮罩层 var node = new cc.Node(); node.scale = 0.85; //node.setPosition(seat_position); //node.parent = node_table_bg; node.parent = seat; node.setPosition(0.5,0.5); node.setLocalZOrder(3); var sprite = node.addComponent(cc.Sprite); sprite.type = cc.Sprite.Type.FILLED; sprite.fillType = cc.Sprite.FillType.RADIAL; sprite.fillCenter = new cc.Vec2(0.5,0.5); sprite.fillStart = 0.25; sprite.fillRange = 0; var frame = this.GameMain.getSpriteFrame("game_progress_frame"); sprite.spriteFrame = frame; //倒计时文字 var node2 = new cc.Node(); node2.name = "time"; var label = node2.addComponent(cc.Label); label.string = this.countdown_cycle_time + "s"; label.fontSize = 30;//设置字体大小 node2.parent = node; //node2.color = new cc.Color(0, 0, 0);//设置字体颜色 node2.setPosition(0,-10); this.countdown_node = node; this.countdown_long_time = long_time;//执行时长 this.countdown_task = function(){ this.start_countdown(1,action_num); }; this.schedule(this.countdown_task,this.countdown_execution_interval); }, //倒计时开始 direction(方向):1-顺时针2-逆时针 start_countdown:function(direction,action_num){ this.countdown_repeat_num++;//已经执行了多少次 var full_cycle = 1;//一个整圈 var speed = full_cycle / this.countdown_cycle_time;//速度 var sprite = this.countdown_node.getComponent(cc.Sprite); var fillRange = sprite.fillRange; var cost_time = this.countdown_execution_interval * this.countdown_repeat_num;//耗时 if(parseInt(cost_time) == cost_time ){ var time_node = this.countdown_node.getChildByName("time"); var time_label = time_node.getComponent(cc.Label); time_label.string = (parseInt(time_label.string) - 1)+"s"; } if(direction == 2){ //逆时针 fillRange = cost_time < this.countdown_long_time ? fillRange += (this.countdown_execution_interval * speed):0; }else{ //顺时针 fillRange = cost_time < this.countdown_long_time ? fillRange -= (this.countdown_execution_interval * speed):0; } sprite.fillRange = fillRange; //如果开启固定思考时间的设置,并且这个过程的执行时间大于思考时间时,直接结束倒计时 var action_type = 0;//动作状态 0-正常1-快进 if(this.open_fixedThinkTime == 1 && this.countdown_long_time >= this.fixedThinkTime){ fillRange = 0; action_type = 1; } //判断是否有正在进行的其他动作 this.start_others(action_type,cost_time,action_num); if(fillRange == 0){ this.unschedule(this.countdown_task);//删除定时任务 this.countdown_node.destroy();//删除该节点 this.countdown_task = null; //如果执行完毕,判断是否有下一步动作,如果有,执行下一步 if(this.countdown_over_task != null){ this.scheduleOnce(this.countdown_over_task,0); } } }, //延长时间 delay_countdown:function(seat_number,duration){ var remain_time = parseInt(this.countdown_cycle_time - duration);//剩余的时间 var total_time = 15 + remain_time; this.countdown_cycle_time = total_time; //一圈的总耗时 this.countdown_repeat_num = 0; //已经执行了多少 if(this.countdown_task!= null){ this.unschedule(this.countdown_task);//删除定时任务 this.countdown_node.destroy();//删除该节点 } //延时 var node_table_bg = cc.find("Canvas/table_bg"); var seat = node_table_bg.getChildByName("seat_"+seat_number);//获取该作为的节点 //倒计时遮罩层 var node = new cc.Node(); node.scale = 0.85; node.parent = seat; node.setPosition(0.5,0.5); node.setLocalZOrder(3); var sprite = node.addComponent(cc.Sprite); sprite.type = cc.Sprite.Type.FILLED; sprite.fillType = cc.Sprite.FillType.RADIAL; sprite.fillCenter = new cc.Vec2(0.5,0.5); sprite.fillStart = 0.25; sprite.fillRange = 0; var frame = this.GameMain.getSpriteFrame("game_progress_frame"); sprite.spriteFrame = frame; //倒计时文字 var node2 = new cc.Node(); node2.name = "time"; var label = node2.addComponent(cc.Label); label.string = this.countdown_cycle_time + "s"; label.fontSize = 30;//设置字体大小 node2.parent = node; node2.setPosition(0,-10); this.countdown_node = node; this.countdown_task = function(){ this.start_countdown(1); }; this.schedule(this.countdown_task,this.countdown_execution_interval); var me = this; this.countdown_over_task = function(){ me.actionend(); }; }, //开始执行其他动作:type:0-正常1-快进 cost:已经执行了多少秒,action_num是之前的this.i-1 start_others:function(type,cost_time,action_num){ //判断等待动作时,是否有其他人进行的动作 var current_action = this.actions[action_num]; if(current_action!=undefined && current_action['others']!=undefined && current_action['others']!=null){ for(var key in current_action['others']){ var other_key = current_action['others'][key]; var duration = current_action['duration']-(current_action['timestamp']-this.hand_data['others'][other_key]['timestamp']); if(duration<0){ cc.log("时间间隔为负,请检查数据"); } if(type == 0 && parseInt(cost_time) == cost_time && cost_time == duration){ //正常流程,待到整点时,进行判断是否有其他的动作 this.other_quit(this.hand_data['others'][other_key]['chair_id']); } //duration=cost_time){ //快进时,判断等待动作时,是否有其他人进行的动作(未执行过的) this.other_quit(this.hand_data['others'][other_key]['chair_id']); } } } }, //ajax 请求 reqstart:function(){ var hand_id = this.getQueryString("hand_id"); var url=""; //hand_id = 32634; //hand_id = 32928; //hand_id = 33305; //hand_id = 33308; //hand_id=33310; //hand_id=33509; if(hand_id != null){ var host_name = window.location.host; var reg = /^localhost:/; if(reg.test(host_name)==true){ url = "http://qa-api.kkpoker.com:8090/Html/get_mongo_data/hand_id/"+hand_id; }else{ url = "http://" + host_name + "/Html/get_mongo_data/hand_id/"+hand_id; } }else{ //测试数据 url="http://172.16.0.210:2016/info.php"; } var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.send(); var me=this; xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { var response = eval('(' + xhr.responseText + ')'); response = me.sorting_data(response); var len = response["actions"].length; for(var i=0;i0 && data['CMD']==9999 && data['chair_id'] == action_result[action_result_len-1]['chair_id']){ action_result[action_result_len-1]['timestamp']=data['timestamp']; data = null; } //有可能同时做的动作,其他人都没正在做动作 if(data != null && data['chair_id']!=0){ action_result.push(data); } if(other_is_sum_up == 1){ var sort_num = action_result.length - 1; //把other动作绑定到action动作当中 if(action_result[sort_num]['others']==undefined){ action_result[sort_num]['others']=[other_result.length-1]; }else{ action_result[sort_num]['others'].push(other_result.length-1); } } } //再次归纳action动作 var action_result2 = []; for(var i=0;i0){ if(action_result2.length>0){ action_result[i]['chair_id'] = action_result2[action_result2.length-1]['current_action_chair']; //修正:如果发现chair_id=99,无效的操作人,找到这个命令的其他操作的人,座位为当前这个人 if(action_result[i]['chair_id']==99 && action_result[i]['others']!=undefined){ action_result[i]['chair_id'] = hand_data['others'][action_result[i]['others'][0]]['chair_id']; } } }else if(action_result[i]['CMD']==9999 && action_result[i]['chair_id']==99 & action_result.length == 1){ //修正:当只有一个9999的动作时,当时正在进行的动作是小盲在思考 action_result[i]['chair_id'] = hand_data['start']['sb_chair']; } if(is_in==1){ action_result2.push(action_result[i]); } } hand_data['actions']=action_result2; hand_data['others']=other_result; return hand_data; } }); ================================================ FILE: bin/client/assets/Script/CountDown.js.meta ================================================ { "ver": "1.0.2", "uuid": "ac50a2dc-5c7b-450e-8387-93e1500ca396", "isPlugin": false, "subMetas": {} } ================================================ FILE: bin/client/assets/Script/Encoding.js ================================================ // This is free and unencumbered software released into the public domain. // See LICENSE.md for more information. // If we're in node require encoding-indexes and attach it to the global. /** * @fileoverview Global |this| required for resolving indexes in node. * @suppress {globalThis} */ if (typeof module !== "undefined" && module.exports) { this["encoding-indexes"] = require("./encoding-indexes.js")["encoding-indexes"]; } (function(global) { 'use strict'; // // Utilities // /** * @param {number} a The number to test. * @param {number} min The minimum value in the range, inclusive. * @param {number} max The maximum value in the range, inclusive. * @return {boolean} True if a >= min and a <= max. */ function inRange(a, min, max) { return min <= a && a <= max; } /** * @param {number} n The numerator. * @param {number} d The denominator. * @return {number} The result of the integer division of n by d. */ function div(n, d) { return Math.floor(n / d); } /** * @param {*} o * @return {Object} */ function ToDictionary(o) { if (o === undefined) return {}; if (o === Object(o)) return o; throw TypeError('Could not convert argument to dictionary'); } /** * @param {string} string Input string of UTF-16 code units. * @return {!Array.} Code points. */ function stringToCodePoints(string) { // https://heycam.github.io/webidl/#dfn-obtain-unicode // 1. Let S be the DOMString value. var s = String(string); // 2. Let n be the length of S. var n = s.length; // 3. Initialize i to 0. var i = 0; // 4. Initialize U to be an empty sequence of Unicode characters. var u = []; // 5. While i < n: while (i < n) { // 1. Let c be the code unit in S at index i. var c = s.charCodeAt(i); // 2. Depending on the value of c: // c < 0xD800 or c > 0xDFFF if (c < 0xD800 || c > 0xDFFF) { // Append to U the Unicode character with code point c. u.push(c); } // 0xDC00 ≤ c ≤ 0xDFFF else if (0xDC00 <= c && c <= 0xDFFF) { // Append to U a U+FFFD REPLACEMENT CHARACTER. u.push(0xFFFD); } // 0xD800 ≤ c ≤ 0xDBFF else if (0xD800 <= c && c <= 0xDBFF) { // 1. If i = n−1, then append to U a U+FFFD REPLACEMENT // CHARACTER. if (i === n - 1) { u.push(0xFFFD); } // 2. Otherwise, i < n−1: else { // 1. Let d be the code unit in S at index i+1. var d = string.charCodeAt(i + 1); // 2. If 0xDC00 ≤ d ≤ 0xDFFF, then: if (0xDC00 <= d && d <= 0xDFFF) { // 1. Let a be c & 0x3FF. var a = c & 0x3FF; // 2. Let b be d & 0x3FF. var b = d & 0x3FF; // 3. Append to U the Unicode character with code point // 2^16+2^10*a+b. u.push(0x10000 + (a << 10) + b); // 4. Set i to i+1. i += 1; } // 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a // U+FFFD REPLACEMENT CHARACTER. else { u.push(0xFFFD); } } } // 3. Set i to i+1. i += 1; } // 6. Return U. return u; } /** * @param {!Array.} code_points Array of code points. * @return {string} string String of UTF-16 code units. */ function codePointsToString(code_points) { var s = ''; for (var i = 0; i < code_points.length; ++i) { var cp = code_points[i]; if (cp <= 0xFFFF) { s += String.fromCharCode(cp); } else { cp -= 0x10000; s += String.fromCharCode((cp >> 10) + 0xD800, (cp & 0x3FF) + 0xDC00); } } return s; } // // Implementation of Encoding specification // https://encoding.spec.whatwg.org/ // // // 3. Terminology // /** * End-of-stream is a special token that signifies no more tokens * are in the stream. * @const */ var end_of_stream = -1; /** * A stream represents an ordered sequence of tokens. * * @constructor * @param {!(Array.|Uint8Array)} tokens Array of tokens that provide the * stream. */ function Stream(tokens) { /** @type {!Array.} */ this.tokens = [].slice.call(tokens); } Stream.prototype = { /** * @return {boolean} True if end-of-stream has been hit. */ endOfStream: function() { return !this.tokens.length; }, /** * When a token is read from a stream, the first token in the * stream must be returned and subsequently removed, and * end-of-stream must be returned otherwise. * * @return {number} Get the next token from the stream, or * end_of_stream. */ read: function() { if (!this.tokens.length) return end_of_stream; return this.tokens.shift(); }, /** * When one or more tokens are prepended to a stream, those tokens * must be inserted, in given order, before the first token in the * stream. * * @param {(number|!Array.)} token The token(s) to prepend to the stream. */ prepend: function(token) { if (Array.isArray(token)) { var tokens = /**@type {!Array.}*/(token); while (tokens.length) this.tokens.unshift(tokens.pop()); } else { this.tokens.unshift(token); } }, /** * When one or more tokens are pushed to a stream, those tokens * must be inserted, in given order, after the last token in the * stream. * * @param {(number|!Array.)} token The tokens(s) to prepend to the stream. */ push: function(token) { if (Array.isArray(token)) { var tokens = /**@type {!Array.}*/(token); while (tokens.length) this.tokens.push(tokens.shift()); } else { this.tokens.push(token); } } }; // // 4. Encodings // // 4.1 Encoders and decoders /** @const */ var finished = -1; /** * @param {boolean} fatal If true, decoding errors raise an exception. * @param {number=} opt_code_point Override the standard fallback code point. * @return {number} The code point to insert on a decoding error. */ function decoderError(fatal, opt_code_point) { if (fatal) throw TypeError('Decoder error'); return opt_code_point || 0xFFFD; } /** * @param {number} code_point The code point that could not be encoded. * @return {number} Always throws, no value is actually returned. */ function encoderError(code_point) { throw TypeError('The code point ' + code_point + ' could not be encoded.'); } /** @interface */ function Decoder() {} Decoder.prototype = { /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point, or |finished|. */ handler: function(stream, bite) {} }; /** @interface */ function Encoder() {} Encoder.prototype = { /** * @param {Stream} stream The stream of code points being encoded. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.)} Byte(s) to emit, or |finished|. */ handler: function(stream, code_point) {} }; // 4.2 Names and labels // TODO: Define @typedef for Encoding: {name:string,labels:Array.} // https://github.com/google/closure-compiler/issues/247 /** * @param {string} label The encoding label. * @return {?{name:string,labels:Array.}} */ function getEncoding(label) { // 1. Remove any leading and trailing ASCII whitespace from label. label = String(label).trim().toLowerCase(); // 2. If label is an ASCII case-insensitive match for any of the // labels listed in the table below, return the corresponding // encoding, and failure otherwise. if (Object.prototype.hasOwnProperty.call(label_to_encoding, label)) { return label_to_encoding[label]; } return null; } /** * Encodings table: https://encoding.spec.whatwg.org/encodings.json * @const * @type {!Array.<{ * heading: string, * encodings: Array.<{name:string,labels:Array.}> * }>} */ var encodings = [ { "encodings": [ { "labels": [ "unicode-1-1-utf-8", "utf-8", "utf8" ], "name": "utf-8" } ], "heading": "The Encoding" }, { "encodings": [ { "labels": [ "866", "cp866", "csibm866", "ibm866" ], "name": "ibm866" }, { "labels": [ "csisolatin2", "iso-8859-2", "iso-ir-101", "iso8859-2", "iso88592", "iso_8859-2", "iso_8859-2:1987", "l2", "latin2" ], "name": "iso-8859-2" }, { "labels": [ "csisolatin3", "iso-8859-3", "iso-ir-109", "iso8859-3", "iso88593", "iso_8859-3", "iso_8859-3:1988", "l3", "latin3" ], "name": "iso-8859-3" }, { "labels": [ "csisolatin4", "iso-8859-4", "iso-ir-110", "iso8859-4", "iso88594", "iso_8859-4", "iso_8859-4:1988", "l4", "latin4" ], "name": "iso-8859-4" }, { "labels": [ "csisolatincyrillic", "cyrillic", "iso-8859-5", "iso-ir-144", "iso8859-5", "iso88595", "iso_8859-5", "iso_8859-5:1988" ], "name": "iso-8859-5" }, { "labels": [ "arabic", "asmo-708", "csiso88596e", "csiso88596i", "csisolatinarabic", "ecma-114", "iso-8859-6", "iso-8859-6-e", "iso-8859-6-i", "iso-ir-127", "iso8859-6", "iso88596", "iso_8859-6", "iso_8859-6:1987" ], "name": "iso-8859-6" }, { "labels": [ "csisolatingreek", "ecma-118", "elot_928", "greek", "greek8", "iso-8859-7", "iso-ir-126", "iso8859-7", "iso88597", "iso_8859-7", "iso_8859-7:1987", "sun_eu_greek" ], "name": "iso-8859-7" }, { "labels": [ "csiso88598e", "csisolatinhebrew", "hebrew", "iso-8859-8", "iso-8859-8-e", "iso-ir-138", "iso8859-8", "iso88598", "iso_8859-8", "iso_8859-8:1988", "visual" ], "name": "iso-8859-8" }, { "labels": [ "csiso88598i", "iso-8859-8-i", "logical" ], "name": "iso-8859-8-i" }, { "labels": [ "csisolatin6", "iso-8859-10", "iso-ir-157", "iso8859-10", "iso885910", "l6", "latin6" ], "name": "iso-8859-10" }, { "labels": [ "iso-8859-13", "iso8859-13", "iso885913" ], "name": "iso-8859-13" }, { "labels": [ "iso-8859-14", "iso8859-14", "iso885914" ], "name": "iso-8859-14" }, { "labels": [ "csisolatin9", "iso-8859-15", "iso8859-15", "iso885915", "iso_8859-15", "l9" ], "name": "iso-8859-15" }, { "labels": [ "iso-8859-16" ], "name": "iso-8859-16" }, { "labels": [ "cskoi8r", "koi", "koi8", "koi8-r", "koi8_r" ], "name": "koi8-r" }, { "labels": [ "koi8-ru", "koi8-u" ], "name": "koi8-u" }, { "labels": [ "csmacintosh", "mac", "macintosh", "x-mac-roman" ], "name": "macintosh" }, { "labels": [ "dos-874", "iso-8859-11", "iso8859-11", "iso885911", "tis-620", "windows-874" ], "name": "windows-874" }, { "labels": [ "cp1250", "windows-1250", "x-cp1250" ], "name": "windows-1250" }, { "labels": [ "cp1251", "windows-1251", "x-cp1251" ], "name": "windows-1251" }, { "labels": [ "ansi_x3.4-1968", "ascii", "cp1252", "cp819", "csisolatin1", "ibm819", "iso-8859-1", "iso-ir-100", "iso8859-1", "iso88591", "iso_8859-1", "iso_8859-1:1987", "l1", "latin1", "us-ascii", "windows-1252", "x-cp1252" ], "name": "windows-1252" }, { "labels": [ "cp1253", "windows-1253", "x-cp1253" ], "name": "windows-1253" }, { "labels": [ "cp1254", "csisolatin5", "iso-8859-9", "iso-ir-148", "iso8859-9", "iso88599", "iso_8859-9", "iso_8859-9:1989", "l5", "latin5", "windows-1254", "x-cp1254" ], "name": "windows-1254" }, { "labels": [ "cp1255", "windows-1255", "x-cp1255" ], "name": "windows-1255" }, { "labels": [ "cp1256", "windows-1256", "x-cp1256" ], "name": "windows-1256" }, { "labels": [ "cp1257", "windows-1257", "x-cp1257" ], "name": "windows-1257" }, { "labels": [ "cp1258", "windows-1258", "x-cp1258" ], "name": "windows-1258" }, { "labels": [ "x-mac-cyrillic", "x-mac-ukrainian" ], "name": "x-mac-cyrillic" } ], "heading": "Legacy single-byte encodings" }, { "encodings": [ { "labels": [ "chinese", "csgb2312", "csiso58gb231280", "gb2312", "gb_2312", "gb_2312-80", "gbk", "iso-ir-58", "x-gbk" ], "name": "gbk" }, { "labels": [ "gb18030" ], "name": "gb18030" } ], "heading": "Legacy multi-byte Chinese (simplified) encodings" }, { "encodings": [ { "labels": [ "big5", "big5-hkscs", "cn-big5", "csbig5", "x-x-big5" ], "name": "big5" } ], "heading": "Legacy multi-byte Chinese (traditional) encodings" }, { "encodings": [ { "labels": [ "cseucpkdfmtjapanese", "euc-jp", "x-euc-jp" ], "name": "euc-jp" }, { "labels": [ "csiso2022jp", "iso-2022-jp" ], "name": "iso-2022-jp" }, { "labels": [ "csshiftjis", "ms932", "ms_kanji", "shift-jis", "shift_jis", "sjis", "windows-31j", "x-sjis" ], "name": "shift_jis" } ], "heading": "Legacy multi-byte Japanese encodings" }, { "encodings": [ { "labels": [ "cseuckr", "csksc56011987", "euc-kr", "iso-ir-149", "korean", "ks_c_5601-1987", "ks_c_5601-1989", "ksc5601", "ksc_5601", "windows-949" ], "name": "euc-kr" } ], "heading": "Legacy multi-byte Korean encodings" }, { "encodings": [ { "labels": [ "csiso2022kr", "hz-gb-2312", "iso-2022-cn", "iso-2022-cn-ext", "iso-2022-kr" ], "name": "replacement" }, { "labels": [ "utf-16be" ], "name": "utf-16be" }, { "labels": [ "utf-16", "utf-16le" ], "name": "utf-16le" }, { "labels": [ "x-user-defined" ], "name": "x-user-defined" } ], "heading": "Legacy miscellaneous encodings" } ]; // Label to encoding registry. /** @type {Object.}>} */ var label_to_encoding = {}; encodings.forEach(function(category) { category.encodings.forEach(function(encoding) { encoding.labels.forEach(function(label) { label_to_encoding[label] = encoding; }); }); }); // Registry of of encoder/decoder factories, by encoding name. /** @type {Object.} */ var encoders = {}; /** @type {Object.} */ var decoders = {}; // // 5. Indexes // /** * @param {number} pointer The |pointer| to search for. * @param {(!Array.|undefined)} index The |index| to search within. * @return {?number} The code point corresponding to |pointer| in |index|, * or null if |code point| is not in |index|. */ function indexCodePointFor(pointer, index) { if (!index) return null; return index[pointer] || null; } /** * @param {number} code_point The |code point| to search for. * @param {!Array.} index The |index| to search within. * @return {?number} The first pointer corresponding to |code point| in * |index|, or null if |code point| is not in |index|. */ function indexPointerFor(code_point, index) { var pointer = index.indexOf(code_point); return pointer === -1 ? null : pointer; } /** * @param {string} name Name of the index. * @return {(!Array.|!Array.>)} * */ function index(name) { if (!('encoding-indexes' in global)) { throw Error("Indexes missing." + " Did you forget to include encoding-indexes.js?"); } return global['encoding-indexes'][name]; } /** * @param {number} pointer The |pointer| to search for in the gb18030 index. * @return {?number} The code point corresponding to |pointer| in |index|, * or null if |code point| is not in the gb18030 index. */ function indexGB18030RangesCodePointFor(pointer) { // 1. If pointer is greater than 39419 and less than 189000, or // pointer is greater than 1237575, return null. if ((pointer > 39419 && pointer < 189000) || (pointer > 1237575)) return null; // 2. Let offset be the last pointer in index gb18030 ranges that // is equal to or less than pointer and let code point offset be // its corresponding code point. var offset = 0; var code_point_offset = 0; var idx = index('gb18030'); var i; for (i = 0; i < idx.length; ++i) { /** @type {!Array.} */ var entry = idx[i]; if (entry[0] <= pointer) { offset = entry[0]; code_point_offset = entry[1]; } else { break; } } // 3. Return a code point whose value is code point offset + // pointer − offset. return code_point_offset + pointer - offset; } /** * @param {number} code_point The |code point| to locate in the gb18030 index. * @return {number} The first pointer corresponding to |code point| in the * gb18030 index. */ function indexGB18030RangesPointerFor(code_point) { // 1. Let offset be the last code point in index gb18030 ranges // that is equal to or less than code point and let pointer offset // be its corresponding pointer. var offset = 0; var pointer_offset = 0; var idx = index('gb18030'); var i; for (i = 0; i < idx.length; ++i) { /** @type {!Array.} */ var entry = idx[i]; if (entry[1] <= code_point) { offset = entry[1]; pointer_offset = entry[0]; } else { break; } } // 2. Return a pointer whose value is pointer offset + code point // − offset. return pointer_offset + code_point - offset; } /** * @param {number} code_point The |code_point| to search for in the shift_jis index. * @return {?number} The code point corresponding to |pointer| in |index|, * or null if |code point| is not in the shift_jis index. */ function indexShiftJISPointerFor(code_point) { // 1. Let index be index jis0208 excluding all pointers in the // range 8272 to 8835. var pointer = indexPointerFor(code_point, index('jis0208')); if (pointer === null || inRange(pointer, 8272, 8835)) return null; // 2. Return the index pointer for code point in index. return pointer; } /** * @param {number} code_point The |code_point| to search for in the big5 index. * @return {?number} The code point corresponding to |pointer| in |index|, * or null if |code point| is not in the big5 index. */ function indexBig5PointerFor(code_point) { // 1. Let index be index big5. var index_ = index('big5'); // 2. If code point is U+2550, U+255E, U+2561, U+256A, U+5341, or // U+5345, return the last pointer corresponding to code point in // index. if (code_point === 0x2550 || code_point === 0x255E || code_point === 0x2561 || code_point === 0x256A || code_point === 0x5341 || code_point === 0x5345) { return index.lastIndexOf(code_point); } // 3. Return the index pointer for code point in index. return indexPointerFor(code_point, index_); } // // 7. API // /** @const */ var DEFAULT_ENCODING = 'utf-8'; // 7.1 Interface TextDecoder /** * @constructor * @param {string=} encoding The label of the encoding; * defaults to 'utf-8'. * @param {Object=} options */ function TextDecoder(encoding, options) { if (!(this instanceof TextDecoder)) { return new TextDecoder(encoding, options); } encoding = encoding !== undefined ? String(encoding) : DEFAULT_ENCODING; options = ToDictionary(options); /** @private */ this._encoding = getEncoding(encoding); if (this._encoding === null || this._encoding.name === 'replacement') throw RangeError('Unknown encoding: ' + encoding); if (!decoders[this._encoding.name]) { throw Error('Decoder not present.' + ' Did you forget to include encoding-indexes.js?'); } /** @private @type {boolean} */ this._streaming = false; /** @private @type {boolean} */ this._BOMseen = false; /** @private @type {?Decoder} */ this._decoder = null; /** @private @type {boolean} */ this._fatal = Boolean(options['fatal']); /** @private @type {boolean} */ this._ignoreBOM = Boolean(options['ignoreBOM']); if (Object.defineProperty) { Object.defineProperty(this, 'encoding', {value: this._encoding.name}); Object.defineProperty(this, 'fatal', {value: this._fatal}); Object.defineProperty(this, 'ignoreBOM', {value: this._ignoreBOM}); } else { this.encoding = this._encoding.name; this.fatal = this._fatal; this.ignoreBOM = this._ignoreBOM; } return this; } TextDecoder.prototype = { /** * @param {ArrayBufferView=} input The buffer of bytes to decode. * @param {Object=} options * @return {string} The decoded string. */ decode: function decode(input, options) { var bytes; if (typeof input === 'object' && input instanceof ArrayBuffer) { bytes = new Uint8Array(input); } else if (typeof input === 'object' && 'buffer' in input && input.buffer instanceof ArrayBuffer) { bytes = new Uint8Array(input.buffer, input.byteOffset, input.byteLength); } else { bytes = new Uint8Array(0); } options = ToDictionary(options); if (!this._streaming) { this._decoder = decoders[this._encoding.name]({fatal: this._fatal}); this._BOMseen = false; } this._streaming = Boolean(options['stream']); var input_stream = new Stream(bytes); var code_points = []; /** @type {?(number|!Array.)} */ var result; while (!input_stream.endOfStream()) { result = this._decoder.handler(input_stream, input_stream.read()); if (result === finished) break; if (result === null) continue; if (Array.isArray(result)) code_points.push.apply(code_points, /**@type {!Array.}*/(result)); else code_points.push(result); } if (!this._streaming) { do { result = this._decoder.handler(input_stream, input_stream.read()); if (result === finished) break; if (result === null) continue; if (Array.isArray(result)) code_points.push.apply(code_points, /**@type {!Array.}*/(result)); else code_points.push(result); } while (!input_stream.endOfStream()); this._decoder = null; } if (code_points.length) { // If encoding is one of utf-8, utf-16be, and utf-16le, and // ignore BOM flag and BOM seen flag are unset, run these // subsubsteps: if (['utf-8', 'utf-16le', 'utf-16be'].indexOf(this.encoding) !== -1 && !this._ignoreBOM && !this._BOMseen) { // If token is U+FEFF, set BOM seen flag. if (code_points[0] === 0xFEFF) { this._BOMseen = true; code_points.shift(); } else { // Otherwise, if token is not end-of-stream, set BOM seen // flag and append token to output. this._BOMseen = true; } } } return codePointsToString(code_points); } }; // 7.2 Interface TextEncoder /** * @constructor * @param {string=} encoding The label of the encoding; * defaults to 'utf-8'. * @param {Object=} options */ function TextEncoder(encoding, options) { if (!(this instanceof TextEncoder)) return new TextEncoder(encoding, options); encoding = encoding !== undefined ? String(encoding) : DEFAULT_ENCODING; options = ToDictionary(options); /** @private */ this._encoding = getEncoding(encoding); if (this._encoding === null || this._encoding.name === 'replacement') throw RangeError('Unknown encoding: ' + encoding); var allowLegacyEncoding = Boolean(options['NONSTANDARD_allowLegacyEncoding']); var isLegacyEncoding = (this._encoding.name !== 'utf-8' && this._encoding.name !== 'utf-16le' && this._encoding.name !== 'utf-16be'); if (this._encoding === null || (isLegacyEncoding && !allowLegacyEncoding)) throw RangeError('Unknown encoding: ' + encoding); if (!encoders[this._encoding.name]) { throw Error('Encoder not present.' + ' Did you forget to include encoding-indexes.js?'); } /** @private @type {boolean} */ this._streaming = false; /** @private @type {?Encoder} */ this._encoder = null; /** @private @type {{fatal: boolean}} */ this._options = {fatal: Boolean(options['fatal'])}; if (Object.defineProperty) Object.defineProperty(this, 'encoding', {value: this._encoding.name}); else this.encoding = this._encoding.name; return this; } TextEncoder.prototype = { /** * @param {string=} opt_string The string to encode. * @param {Object=} options * @return {Uint8Array} Encoded bytes, as a Uint8Array. */ encode: function encode(opt_string, options) { opt_string = opt_string ? String(opt_string) : ''; options = ToDictionary(options); // NOTE: This option is nonstandard. None of the encodings // permitted for encoding (i.e. UTF-8, UTF-16) are stateful, // so streaming is not necessary. if (!this._streaming) this._encoder = encoders[this._encoding.name](this._options); this._streaming = Boolean(options['stream']); var bytes = []; var input_stream = new Stream(stringToCodePoints(opt_string)); /** @type {?(number|!Array.)} */ var result; while (!input_stream.endOfStream()) { result = this._encoder.handler(input_stream, input_stream.read()); if (result === finished) break; if (Array.isArray(result)) bytes.push.apply(bytes, /**@type {!Array.}*/(result)); else bytes.push(result); } if (!this._streaming) { while (true) { result = this._encoder.handler(input_stream, input_stream.read()); if (result === finished) break; if (Array.isArray(result)) bytes.push.apply(bytes, /**@type {!Array.}*/(result)); else bytes.push(result); } this._encoder = null; } return new Uint8Array(bytes); } }; // // 8. The encoding // // 8.1 utf-8 /** * @constructor * @implements {Decoder} * @param {{fatal: boolean}} options */ function UTF8Decoder(options) { var fatal = options.fatal; // utf-8's decoder's has an associated utf-8 code point, utf-8 // bytes seen, and utf-8 bytes needed (all initially 0), a utf-8 // lower boundary (initially 0x80), and a utf-8 upper boundary // (initially 0xBF). var /** @type {number} */ utf8_code_point = 0, /** @type {number} */ utf8_bytes_seen = 0, /** @type {number} */ utf8_bytes_needed = 0, /** @type {number} */ utf8_lower_boundary = 0x80, /** @type {number} */ utf8_upper_boundary = 0xBF; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and utf-8 bytes needed is not 0, // set utf-8 bytes needed to 0 and return error. if (bite === end_of_stream && utf8_bytes_needed !== 0) { utf8_bytes_needed = 0; return decoderError(fatal); } // 2. If byte is end-of-stream, return finished. if (bite === end_of_stream) return finished; // 3. If utf-8 bytes needed is 0, based on byte: if (utf8_bytes_needed === 0) { // 0x00 to 0x7F if (inRange(bite, 0x00, 0x7F)) { // Return a code point whose value is byte. return bite; } // 0xC2 to 0xDF if (inRange(bite, 0xC2, 0xDF)) { // Set utf-8 bytes needed to 1 and utf-8 code point to byte // − 0xC0. utf8_bytes_needed = 1; utf8_code_point = bite - 0xC0; } // 0xE0 to 0xEF else if (inRange(bite, 0xE0, 0xEF)) { // 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0. if (bite === 0xE0) utf8_lower_boundary = 0xA0; // 2. If byte is 0xED, set utf-8 upper boundary to 0x9F. if (bite === 0xED) utf8_upper_boundary = 0x9F; // 3. Set utf-8 bytes needed to 2 and utf-8 code point to // byte − 0xE0. utf8_bytes_needed = 2; utf8_code_point = bite - 0xE0; } // 0xF0 to 0xF4 else if (inRange(bite, 0xF0, 0xF4)) { // 1. If byte is 0xF0, set utf-8 lower boundary to 0x90. if (bite === 0xF0) utf8_lower_boundary = 0x90; // 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F. if (bite === 0xF4) utf8_upper_boundary = 0x8F; // 3. Set utf-8 bytes needed to 3 and utf-8 code point to // byte − 0xF0. utf8_bytes_needed = 3; utf8_code_point = bite - 0xF0; } // Otherwise else { // Return error. return decoderError(fatal); } // Then (byte is in the range 0xC2 to 0xF4) set utf-8 code // point to utf-8 code point << (6 × utf-8 bytes needed) and // return continue. utf8_code_point = utf8_code_point << (6 * utf8_bytes_needed); return null; } // 4. If byte is not in the range utf-8 lower boundary to utf-8 // upper boundary, run these substeps: if (!inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) { // 1. Set utf-8 code point, utf-8 bytes needed, and utf-8 // bytes seen to 0, set utf-8 lower boundary to 0x80, and set // utf-8 upper boundary to 0xBF. utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0; utf8_lower_boundary = 0x80; utf8_upper_boundary = 0xBF; // 2. Prepend byte to stream. stream.prepend(bite); // 3. Return error. return decoderError(fatal); } // 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary // to 0xBF. utf8_lower_boundary = 0x80; utf8_upper_boundary = 0xBF; // 6. Increase utf-8 bytes seen by one and set utf-8 code point // to utf-8 code point + (byte − 0x80) << (6 × (utf-8 bytes // needed − utf-8 bytes seen)). utf8_bytes_seen += 1; utf8_code_point += (bite - 0x80) << (6 * (utf8_bytes_needed - utf8_bytes_seen)); // 7. If utf-8 bytes seen is not equal to utf-8 bytes needed, // continue. if (utf8_bytes_seen !== utf8_bytes_needed) return null; // 8. Let code point be utf-8 code point. var code_point = utf8_code_point; // 9. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes // seen to 0. utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0; // 10. Return a code point whose value is code point. return code_point; }; } /** * @constructor * @implements {Encoder} * @param {{fatal: boolean}} options */ function UTF8Encoder(options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is in the range U+0000 to U+007F, return a // byte whose value is code point. if (inRange(code_point, 0x0000, 0x007f)) return code_point; // 3. Set count and offset based on the range code point is in: var count, offset; // U+0080 to U+07FF: 1 and 0xC0 if (inRange(code_point, 0x0080, 0x07FF)) { count = 1; offset = 0xC0; } // U+0800 to U+FFFF: 2 and 0xE0 else if (inRange(code_point, 0x0800, 0xFFFF)) { count = 2; offset = 0xE0; } // U+10000 to U+10FFFF: 3 and 0xF0 else if (inRange(code_point, 0x10000, 0x10FFFF)) { count = 3; offset = 0xF0; } // 4.Let bytes be a byte sequence whose first byte is (code // point >> (6 × count)) + offset. var bytes = [(code_point >> (6 * count)) + offset]; // 5. Run these substeps while count is greater than 0: while (count > 0) { // 1. Set temp to code point >> (6 × (count − 1)). var temp = code_point >> (6 * (count - 1)); // 2. Append to bytes 0x80 | (temp & 0x3F). bytes.push(0x80 | (temp & 0x3F)); // 3. Decrease count by one. count -= 1; } // 6. Return bytes bytes, in order. return bytes; }; } /** @param {{fatal: boolean}} options */ encoders['utf-8'] = function(options) { return new UTF8Encoder(options); }; /** @param {{fatal: boolean}} options */ decoders['utf-8'] = function(options) { return new UTF8Decoder(options); }; // // 9. Legacy single-byte encodings // // 9.1 single-byte decoder /** * @constructor * @implements {Decoder} * @param {!Array.} index The encoding index. * @param {{fatal: boolean}} options */ function SingleByteDecoder(index, options) { var fatal = options.fatal; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream, return finished. if (bite === end_of_stream) return finished; // 2. If byte is in the range 0x00 to 0x7F, return a code point // whose value is byte. if (inRange(bite, 0x00, 0x7F)) return bite; // 3. Let code point be the index code point for byte − 0x80 in // index single-byte. var code_point = index[bite - 0x80]; // 4. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 5. Return a code point whose value is code point. return code_point; }; } // 9.2 single-byte encoder /** * @constructor * @implements {Encoder} * @param {!Array.} index The encoding index. * @param {{fatal: boolean}} options */ function SingleByteEncoder(index, options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is in the range U+0000 to U+007F, return a // byte whose value is code point. if (inRange(code_point, 0x0000, 0x007F)) return code_point; // 3. Let pointer be the index pointer for code point in index // single-byte. var pointer = indexPointerFor(code_point, index); // 4. If pointer is null, return error with code point. if (pointer === null) encoderError(code_point); // 5. Return a byte whose value is pointer + 0x80. return pointer + 0x80; }; } (function() { if (!('encoding-indexes' in global)) return; encodings.forEach(function(category) { if (category.heading !== 'Legacy single-byte encodings') return; category.encodings.forEach(function(encoding) { var name = encoding.name; var idx = index(name); /** @param {{fatal: boolean}} options */ decoders[name] = function(options) { return new SingleByteDecoder(idx, options); }; /** @param {{fatal: boolean}} options */ encoders[name] = function(options) { return new SingleByteEncoder(idx, options); }; }); }); }()); // // 10. Legacy multi-byte Chinese (simplified) encodings // // 10.1 gbk // 10.1.1 gbk decoder // gbk's decoder is gb18030's decoder. /** @param {{fatal: boolean}} options */ decoders['gbk'] = function(options) { return new GB18030Decoder(options); }; // 10.1.2 gbk encoder // gbk's encoder is gb18030's encoder with its gbk flag set. /** @param {{fatal: boolean}} options */ encoders['gbk'] = function(options) { return new GB18030Encoder(options, true); }; // 10.2 gb18030 // 10.2.1 gb18030 decoder /** * @constructor * @implements {Decoder} * @param {{fatal: boolean}} options */ function GB18030Decoder(options) { var fatal = options.fatal; // gb18030's decoder has an associated gb18030 first, gb18030 // second, and gb18030 third (all initially 0x00). var /** @type {number} */ gb18030_first = 0x00, /** @type {number} */ gb18030_second = 0x00, /** @type {number} */ gb18030_third = 0x00; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and gb18030 first, gb18030 // second, and gb18030 third are 0x00, return finished. if (bite === end_of_stream && gb18030_first === 0x00 && gb18030_second === 0x00 && gb18030_third === 0x00) { return finished; } // 2. If byte is end-of-stream, and gb18030 first, gb18030 // second, or gb18030 third is not 0x00, set gb18030 first, // gb18030 second, and gb18030 third to 0x00, and return error. if (bite === end_of_stream && (gb18030_first !== 0x00 || gb18030_second !== 0x00 || gb18030_third !== 0x00)) { gb18030_first = 0x00; gb18030_second = 0x00; gb18030_third = 0x00; decoderError(fatal); } var code_point; // 3. If gb18030 third is not 0x00, run these substeps: if (gb18030_third !== 0x00) { // 1. Let code point be null. code_point = null; // 2. If byte is in the range 0x30 to 0x39, set code point to // the index gb18030 ranges code point for (((gb18030 first − // 0x81) × 10 + gb18030 second − 0x30) × 126 + gb18030 third − // 0x81) × 10 + byte − 0x30. if (inRange(bite, 0x30, 0x39)) { code_point = indexGB18030RangesCodePointFor( (((gb18030_first - 0x81) * 10 + (gb18030_second - 0x30)) * 126 + (gb18030_third - 0x81)) * 10 + bite - 0x30); } // 3. Let buffer be a byte sequence consisting of gb18030 // second, gb18030 third, and byte, in order. var buffer = [gb18030_second, gb18030_third, bite]; // 4. Set gb18030 first, gb18030 second, and gb18030 third to // 0x00. gb18030_first = 0x00; gb18030_second = 0x00; gb18030_third = 0x00; // 5. If code point is null, prepend buffer to stream and // return error. if (code_point === null) { stream.prepend(buffer); return decoderError(fatal); } // 6. Return a code point whose value is code point. return code_point; } // 4. If gb18030 second is not 0x00, run these substeps: if (gb18030_second !== 0x00) { // 1. If byte is in the range 0x81 to 0xFE, set gb18030 third // to byte and return continue. if (inRange(bite, 0x81, 0xFE)) { gb18030_third = bite; return null; } // 2. Prepend gb18030 second followed by byte to stream, set // gb18030 first and gb18030 second to 0x00, and return error. stream.prepend([gb18030_second, bite]); gb18030_first = 0x00; gb18030_second = 0x00; return decoderError(fatal); } // 5. If gb18030 first is not 0x00, run these substeps: if (gb18030_first !== 0x00) { // 1. If byte is in the range 0x30 to 0x39, set gb18030 second // to byte and return continue. if (inRange(bite, 0x30, 0x39)) { gb18030_second = bite; return null; } // 2. Let lead be gb18030 first, let pointer be null, and set // gb18030 first to 0x00. var lead = gb18030_first; var pointer = null; gb18030_first = 0x00; // 3. Let offset be 0x40 if byte is less than 0x7F and 0x41 // otherwise. var offset = bite < 0x7F ? 0x40 : 0x41; // 4. If byte is in the range 0x40 to 0x7E or 0x80 to 0xFE, // set pointer to (lead − 0x81) × 190 + (byte − offset). if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFE)) pointer = (lead - 0x81) * 190 + (bite - offset); // 5. Let code point be null if pointer is null and the index // code point for pointer in index gb18030 otherwise. code_point = pointer === null ? null : indexCodePointFor(pointer, index('gb18030')); // 6. If code point is null and byte is in the range 0x00 to // 0x7F, prepend byte to stream. if (code_point === null && inRange(bite, 0x00, 0x7F)) stream.prepend(bite); // 7. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 8. Return a code point whose value is code point. return code_point; } // 6. If byte is in the range 0x00 to 0x7F, return a code point // whose value is byte. if (inRange(bite, 0x00, 0x7F)) return bite; // 7. If byte is 0x80, return code point U+20AC. if (bite === 0x80) return 0x20AC; // 8. If byte is in the range 0x81 to 0xFE, set gb18030 first to // byte and return continue. if (inRange(bite, 0x81, 0xFE)) { gb18030_first = bite; return null; } // 9. Return error. return decoderError(fatal); }; } // 10.2.2 gb18030 encoder /** * @constructor * @implements {Encoder} * @param {{fatal: boolean}} options * @param {boolean=} gbk_flag */ function GB18030Encoder(options, gbk_flag) { var fatal = options.fatal; // gb18030's decoder has an associated gbk flag (initially unset). /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is in the range U+0000 to U+007F, return a // byte whose value is code point. if (inRange(code_point, 0x0000, 0x007F)) { return code_point; } // 3. If the gbk flag is set and code point is U+20AC, return // byte 0x80. if (gbk_flag && code_point === 0x20AC) return 0x80; // 4. Let pointer be the index pointer for code point in index // gb18030. var pointer = indexPointerFor(code_point, index('gb18030')); // 5. If pointer is not null, run these substeps: if (pointer !== null) { // 1. Let lead be pointer / 190 + 0x81. var lead = div(pointer, 190) + 0x81; // 2. Let trail be pointer % 190. var trail = pointer % 190; // 3. Let offset be 0x40 if trail is less than 0x3F and 0x41 otherwise. var offset = trail < 0x3F ? 0x40 : 0x41; // 4. Return two bytes whose values are lead and trail + offset. return [lead, trail + offset]; } // 6. If gbk flag is set, return error with code point. if (gbk_flag) return encoderError(code_point); // 7. Set pointer to the index gb18030 ranges pointer for code // point. pointer = indexGB18030RangesPointerFor(code_point); // 8. Let byte1 be pointer / 10 / 126 / 10. var byte1 = div(div(div(pointer, 10), 126), 10); // 9. Set pointer to pointer − byte1 × 10 × 126 × 10. pointer = pointer - byte1 * 10 * 126 * 10; // 10. Let byte2 be pointer / 10 / 126. var byte2 = div(div(pointer, 10), 126); // 11. Set pointer to pointer − byte2 × 10 × 126. pointer = pointer - byte2 * 10 * 126; // 12. Let byte3 be pointer / 10. var byte3 = div(pointer, 10); // 13. Let byte4 be pointer − byte3 × 10. var byte4 = pointer - byte3 * 10; // 14. Return four bytes whose values are byte1 + 0x81, byte2 + // 0x30, byte3 + 0x81, byte4 + 0x30. return [byte1 + 0x81, byte2 + 0x30, byte3 + 0x81, byte4 + 0x30]; }; } /** @param {{fatal: boolean}} options */ encoders['gb18030'] = function(options) { return new GB18030Encoder(options); }; /** @param {{fatal: boolean}} options */ decoders['gb18030'] = function(options) { return new GB18030Decoder(options); }; // // 11. Legacy multi-byte Chinese (traditional) encodings // // 11.1 big5 /** * @constructor * @implements {Decoder} * @param {{fatal: boolean}} options */ function Big5Decoder(options) { var fatal = options.fatal; // big5's decoder has an associated big5 lead (initially 0x00). var /** @type {number} */ big5_lead = 0x00; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and big5 lead is not 0x00, set // big5 lead to 0x00 and return error. if (bite === end_of_stream && big5_lead !== 0x00) { big5_lead = 0x00; return decoderError(fatal); } // 2. If byte is end-of-stream and big5 lead is 0x00, return // finished. if (bite === end_of_stream && big5_lead === 0x00) return finished; // 3. If big5 lead is not 0x00, let lead be big5 lead, let // pointer be null, set big5 lead to 0x00, and then run these // substeps: if (big5_lead !== 0x00) { var lead = big5_lead; var pointer = null; big5_lead = 0x00; // 1. Let offset be 0x40 if byte is less than 0x7F and 0x62 // otherwise. var offset = bite < 0x7F ? 0x40 : 0x62; // 2. If byte is in the range 0x40 to 0x7E or 0xA1 to 0xFE, // set pointer to (lead − 0x81) × 157 + (byte − offset). if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0xA1, 0xFE)) pointer = (lead - 0x81) * 157 + (bite - offset); // 3. If there is a row in the table below whose first column // is pointer, return the two code points listed in its second // column // Pointer | Code points // --------+-------------- // 1133 | U+00CA U+0304 // 1135 | U+00CA U+030C // 1164 | U+00EA U+0304 // 1166 | U+00EA U+030C switch (pointer) { case 1133: return [0x00CA, 0x0304]; case 1135: return [0x00CA, 0x030C]; case 1164: return [0x00EA, 0x0304]; case 1166: return [0x00EA, 0x030C]; } // 4. Let code point be null if pointer is null and the index // code point for pointer in index big5 otherwise. var code_point = (pointer === null) ? null : indexCodePointFor(pointer, index('big5')); // 5. If code point is null and byte is in the range 0x00 to // 0x7F, prepend byte to stream. if (code_point === null && inRange(bite, 0x00, 0x7F)) stream.prepend(bite); // 6. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 7. Return a code point whose value is code point. return code_point; } // 4. If byte is in the range 0x00 to 0x7F, return a code point // whose value is byte. if (inRange(bite, 0x00, 0x7F)) return bite; // 5. If byte is in the range 0x81 to 0xFE, set big5 lead to // byte and return continue. if (inRange(bite, 0x81, 0xFE)) { big5_lead = bite; return null; } // 6. Return error. return decoderError(fatal); }; } /** * @constructor * @implements {Encoder} * @param {{fatal: boolean}} options */ function Big5Encoder(options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is in the range U+0000 to U+007F, return a // byte whose value is code point. if (inRange(code_point, 0x0000, 0x007F)) return code_point; // 3. Let pointer be the index big5 pointer for code point. var pointer = indexBig5PointerFor(code_point, index('big5')); // 4. If pointer is null, return error with code point. if (pointer === null) return encoderError(code_point); // 5. Let lead be pointer / 157 + 0x81. var lead = div(pointer, 157) + 0x81; // 6. If lead is less than 0xA1, return error with code point. if (lead < 0xA1) return encoderError(code_point); // 7. Let trail be pointer % 157. var trail = pointer % 157; // 8. Let offset be 0x40 if trail is less than 0x3F and 0x62 // otherwise. var offset = trail < 0x3F ? 0x40 : 0x62; // Return two bytes whose values are lead and trail + offset. return [lead, trail + offset]; }; } /** @param {{fatal: boolean}} options */ encoders['big5'] = function(options) { return new Big5Encoder(options); }; /** @param {{fatal: boolean}} options */ decoders['big5'] = function(options) { return new Big5Decoder(options); }; // // 12. Legacy multi-byte Japanese encodings // // 12.1 euc-jp /** * @constructor * @implements {Decoder} * @param {{fatal: boolean}} options */ function EUCJPDecoder(options) { var fatal = options.fatal; // euc-jp's decoder has an associated euc-jp jis0212 flag // (initially unset) and euc-jp lead (initially 0x00). var /** @type {boolean} */ eucjp_jis0212_flag = false, /** @type {number} */ eucjp_lead = 0x00; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and euc-jp lead is not 0x00, set // euc-jp lead to 0x00, and return error. if (bite === end_of_stream && eucjp_lead !== 0x00) { eucjp_lead = 0x00; return decoderError(fatal); } // 2. If byte is end-of-stream and euc-jp lead is 0x00, return // finished. if (bite === end_of_stream && eucjp_lead === 0x00) return finished; // 3. If euc-jp lead is 0x8E and byte is in the range 0xA1 to // 0xDF, set euc-jp lead to 0x00 and return a code point whose // value is 0xFF61 + byte − 0xA1. if (eucjp_lead === 0x8E && inRange(bite, 0xA1, 0xDF)) { eucjp_lead = 0x00; return 0xFF61 + bite - 0xA1; } // 4. If euc-jp lead is 0x8F and byte is in the range 0xA1 to // 0xFE, set the euc-jp jis0212 flag, set euc-jp lead to byte, // and return continue. if (eucjp_lead === 0x8F && inRange(bite, 0xA1, 0xFE)) { eucjp_jis0212_flag = true; eucjp_lead = bite; return null; } // 5. If euc-jp lead is not 0x00, let lead be euc-jp lead, set // euc-jp lead to 0x00, and run these substeps: if (eucjp_lead !== 0x00) { var lead = eucjp_lead; eucjp_lead = 0x00; // 1. Let code point be null. var code_point = null; // 2. If lead and byte are both in the range 0xA1 to 0xFE, set // code point to the index code point for (lead − 0xA1) × 94 + // byte − 0xA1 in index jis0208 if the euc-jp jis0212 flag is // unset and in index jis0212 otherwise. if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) { code_point = indexCodePointFor( (lead - 0xA1) * 94 + (bite - 0xA1), index(!eucjp_jis0212_flag ? 'jis0208' : 'jis0212')); } // 3. Unset the euc-jp jis0212 flag. eucjp_jis0212_flag = false; // 4. If byte is not in the range 0xA1 to 0xFE, prepend byte // to stream. if (!inRange(bite, 0xA1, 0xFE)) stream.prepend(bite); // 5. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 6. Return a code point whose value is code point. return code_point; } // 6. If byte is in the range 0x00 to 0x7F, return a code point // whose value is byte. if (inRange(bite, 0x00, 0x7F)) return bite; // 7. If byte is 0x8E, 0x8F, or in the range 0xA1 to 0xFE, set // euc-jp lead to byte and return continue. if (bite === 0x8E || bite === 0x8F || inRange(bite, 0xA1, 0xFE)) { eucjp_lead = bite; return null; } // 8. Return error. return decoderError(fatal); }; } /** * @constructor * @implements {Encoder} * @param {{fatal: boolean}} options */ function EUCJPEncoder(options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is in the range U+0000 to U+007F, return a // byte whose value is code point. if (inRange(code_point, 0x0000, 0x007F)) return code_point; // 3. If code point is U+00A5, return byte 0x5C. if (code_point === 0x00A5) return 0x5C; // 4. If code point is U+203E, return byte 0x7E. if (code_point === 0x203E) return 0x7E; // 5. If code point is in the range U+FF61 to U+FF9F, return two // bytes whose values are 0x8E and code point − 0xFF61 + 0xA1. if (inRange(code_point, 0xFF61, 0xFF9F)) return [0x8E, code_point - 0xFF61 + 0xA1]; // 6. If code point is U+2022, set it to U+FF0D. if (code_point === 0x2022) code_point = 0xFF0D; // 7. Let pointer be the index pointer for code point in index // jis0208. var pointer = indexPointerFor(code_point, index('jis0208')); // 8. If pointer is null, return error with code point. if (pointer === null) return encoderError(code_point); // 9. Let lead be pointer / 94 + 0xA1. var lead = div(pointer, 94) + 0xA1; // 10. Let trail be pointer % 94 + 0xA1. var trail = pointer % 94 + 0xA1; // 11. Return two bytes whose values are lead and trail. return [lead, trail]; }; } /** @param {{fatal: boolean}} options */ encoders['euc-jp'] = function(options) { return new EUCJPEncoder(options); }; /** @param {{fatal: boolean}} options */ decoders['euc-jp'] = function(options) { return new EUCJPDecoder(options); }; // 12.2 iso-2022-jp /** * @constructor * @implements {Decoder} * @param {{fatal: boolean}} options */ function ISO2022JPDecoder(options) { var fatal = options.fatal; /** @enum */ var states = { ASCII: 0, Roman: 1, Katakana: 2, LeadByte: 3, TrailByte: 4, EscapeStart: 5, Escape: 6 }; // iso-2022-jp's decoder has an associated iso-2022-jp decoder // state (initially ASCII), iso-2022-jp decoder output state // (initially ASCII), iso-2022-jp lead (initially 0x00), and // iso-2022-jp output flag (initially unset). var /** @type {number} */ iso2022jp_decoder_state = states.ASCII, /** @type {number} */ iso2022jp_decoder_output_state = states.ASCII, /** @type {number} */ iso2022jp_lead = 0x00, /** @type {boolean} */ iso2022jp_output_flag = false; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // switching on iso-2022-jp decoder state: switch (iso2022jp_decoder_state) { default: case states.ASCII: // ASCII // Based on byte: // 0x1B if (bite === 0x1B) { // Set iso-2022-jp decoder state to escape start and return // continue. iso2022jp_decoder_state = states.EscapeStart; return null; } // 0x00 to 0x7F, excluding 0x0E, 0x0F, and 0x1B if (inRange(bite, 0x00, 0x7F) && bite !== 0x0E && bite !== 0x0F && bite !== 0x1B) { // Unset the iso-2022-jp output flag and return a code point // whose value is byte. iso2022jp_output_flag = false; return bite; } // end-of-stream if (bite === end_of_stream) { // Return finished. return finished; } // Otherwise // Unset the iso-2022-jp output flag and return error. iso2022jp_output_flag = false; return decoderError(fatal); case states.Roman: // Roman // Based on byte: // 0x1B if (bite === 0x1B) { // Set iso-2022-jp decoder state to escape start and return // continue. iso2022jp_decoder_state = states.EscapeStart; return null; } // 0x5C if (bite === 0x5C) { // Unset the iso-2022-jp output flag and return code point // U+00A5. iso2022jp_output_flag = false; return 0x00A5; } // 0x7E if (bite === 0x7E) { // Unset the iso-2022-jp output flag and return code point // U+203E. iso2022jp_output_flag = false; return 0x203E; } // 0x00 to 0x7F, excluding 0x0E, 0x0F, 0x1B, 0x5C, and 0x7E if (inRange(bite, 0x00, 0x7F) && bite !== 0x0E && bite !== 0x0F && bite !== 0x1B && bite !== 0x5C && bite !== 0x7E) { // Unset the iso-2022-jp output flag and return a code point // whose value is byte. iso2022jp_output_flag = false; return bite; } // end-of-stream if (bite === end_of_stream) { // Return finished. return finished; } // Otherwise // Unset the iso-2022-jp output flag and return error. iso2022jp_output_flag = false; return decoderError(fatal); case states.Katakana: // Katakana // Based on byte: // 0x1B if (bite === 0x1B) { // Set iso-2022-jp decoder state to escape start and return // continue. iso2022jp_decoder_state = states.EscapeStart; return null; } // 0x21 to 0x5F if (inRange(bite, 0x21, 0x5F)) { // Unset the iso-2022-jp output flag and return a code point // whose value is 0xFF61 + byte − 0x21. iso2022jp_output_flag = false; return 0xFF61 + bite - 0x21; } // end-of-stream if (bite === end_of_stream) { // Return finished. return finished; } // Otherwise // Unset the iso-2022-jp output flag and return error. iso2022jp_output_flag = false; return decoderError(fatal); case states.LeadByte: // Lead byte // Based on byte: // 0x1B if (bite === 0x1B) { // Set iso-2022-jp decoder state to escape start and return // continue. iso2022jp_decoder_state = states.EscapeStart; return null; } // 0x21 to 0x7E if (inRange(bite, 0x21, 0x7E)) { // Unset the iso-2022-jp output flag, set iso-2022-jp lead // to byte, iso-2022-jp decoder state to trail byte, and // return continue. iso2022jp_output_flag = false; iso2022jp_lead = bite; iso2022jp_decoder_state = states.TrailByte; return null; } // end-of-stream if (bite === end_of_stream) { // Return finished. return finished; } // Otherwise // Unset the iso-2022-jp output flag and return error. iso2022jp_output_flag = false; return decoderError(fatal); case states.TrailByte: // Trail byte // Based on byte: // 0x1B if (bite === 0x1B) { // Set iso-2022-jp decoder state to escape start and return // continue. iso2022jp_decoder_state = states.EscapeStart; return decoderError(fatal); } // 0x21 to 0x7E if (inRange(bite, 0x21, 0x7E)) { // 1. Set the iso-2022-jp decoder state to lead byte. iso2022jp_decoder_state = states.LeadByte; // 2. Let pointer be (iso-2022-jp lead − 0x21) × 94 + byte − 0x21. var pointer = (iso2022jp_lead - 0x21) * 94 + bite - 0x21; // 3. Let code point be the index code point for pointer in index jis0208. var code_point = indexCodePointFor(pointer, index('jis0208')); // 4. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 5. Return a code point whose value is code point. return code_point; } // end-of-stream if (bite === end_of_stream) { // Set the iso-2022-jp decoder state to lead byte, prepend // byte to stream, and return error. iso2022jp_decoder_state = states.LeadByte; stream.prepend(bite); return decoderError(fatal); } // Otherwise // Set iso-2022-jp decoder state to lead byte and return // error. iso2022jp_decoder_state = states.LeadByte; return decoderError(fatal); case states.EscapeStart: // Escape start // 1. If byte is either 0x24 or 0x28, set iso-2022-jp lead to // byte, iso-2022-jp decoder state to escape, and return // continue. if (bite === 0x24 || bite === 0x28) { iso2022jp_lead = bite; iso2022jp_decoder_state = states.Escape; return null; } // 2. Prepend byte to stream. stream.prepend(bite); // 3. Unset the iso-2022-jp output flag, set iso-2022-jp // decoder state to iso-2022-jp decoder output state, and // return error. iso2022jp_output_flag = false; iso2022jp_decoder_state = iso2022jp_decoder_output_state; return decoderError(fatal); case states.Escape: // Escape // 1. Let lead be iso-2022-jp lead and set iso-2022-jp lead to // 0x00. var lead = iso2022jp_lead; iso2022jp_lead = 0x00; // 2. Let state be null. var state = null; // 3. If lead is 0x28 and byte is 0x42, set state to ASCII. if (lead === 0x28 && bite === 0x42) state = states.ASCII; // 4. If lead is 0x28 and byte is 0x4A, set state to Roman. if (lead === 0x28 && bite === 0x4A) state = states.Roman; // 5. If lead is 0x28 and byte is 0x49, set state to Katakana. if (lead === 0x28 && bite === 0x49) state = states.Katakana; // 6. If lead is 0x24 and byte is either 0x40 or 0x42, set // state to lead byte. if (lead === 0x24 && (bite === 0x40 || bite === 0x42)) state = states.LeadByte; // 7. If state is non-null, run these substeps: if (state !== null) { // 1. Set iso-2022-jp decoder state and iso-2022-jp decoder // output state to states. iso2022jp_decoder_state = iso2022jp_decoder_state = state; // 2. Let output flag be the iso-2022-jp output flag. var output_flag = iso2022jp_output_flag; // 3. Set the iso-2022-jp output flag. iso2022jp_output_flag = true; // 4. Return continue, if output flag is unset, and error // otherwise. return !output_flag ? null : decoderError(fatal); } // 8. Prepend lead and byte to stream. stream.prepend([lead, bite]); // 9. Unset the iso-2022-jp output flag, set iso-2022-jp // decoder state to iso-2022-jp decoder output state and // return error. iso2022jp_output_flag = false; iso2022jp_decoder_state = iso2022jp_decoder_output_state; return decoderError(fatal); } }; } /** * @constructor * @implements {Encoder} * @param {{fatal: boolean}} options */ function ISO2022JPEncoder(options) { var fatal = options.fatal; // iso-2022-jp's encoder has an associated iso-2022-jp encoder // state which is one of ASCII, Roman, and jis0208 (initially // ASCII). /** @enum */ var states = { ASCII: 0, Roman: 1, jis0208: 2 }; var /** @type {number} */ iso2022jp_state = states.ASCII; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream and iso-2022-jp encoder // state is not ASCII, prepend code point to stream, set // iso-2022-jp encoder state to ASCII, and return three bytes // 0x1B 0x28 0x42. if (code_point === end_of_stream && iso2022jp_state !== states.ASCII) { stream.prepend(code_point); return [0x1B, 0x28, 0x42]; } // 2. If code point is end-of-stream and iso-2022-jp encoder // state is ASCII, return finished. if (code_point === end_of_stream && iso2022jp_state === states.ASCII) return finished; // 3. If iso-2022-jp encoder state is ASCII and code point is in // the range U+0000 to U+007F, return a byte whose value is code // point. if (iso2022jp_state === states.ASCII && inRange(code_point, 0x0000, 0x007F)) return code_point; // 4. If iso-2022-jp encoder state is Roman and code point is in // the range U+0000 to U+007F, excluding U+005C and U+007E, or // is U+00A5 or U+203E, run these substeps: if (iso2022jp_state === states.Roman && inRange(code_point, 0x0000, 0x007F) && code_point !== 0x005C && code_point !== 0x007E) { // 1. If code point is in the range U+0000 to U+007F, return a // byte whose value is code point. if (inRange(code_point, 0x0000, 0x007F)) return code_point; // 2. If code point is U+00A5, return byte 0x5C. if (code_point === 0x00A5) return 0x5C; // 3. If code point is U+203E, return byte 0x7E. if (code_point === 0x203E) return 0x7E; } // 5. If code point is in the range U+0000 to U+007F, and // iso-2022-jp encoder state is not ASCII, prepend code point to // stream, set iso-2022-jp encoder state to ASCII, and return // three bytes 0x1B 0x28 0x42. if (inRange(code_point, 0x0000, 0x007F) && iso2022jp_state !== states.ASCII) { stream.prepend(code_point); iso2022jp_state = states.ASCII; return [0x1B, 0x28, 0x42]; } // 6. If code point is either U+00A5 or U+203E, and iso-2022-jp // encoder state is not Roman, prepend code point to stream, set // iso-2022-jp encoder state to Roman, and return three bytes // 0x1B 0x28 0x4A. if ((code_point === 0x00A5 || code_point === 0x203E) && iso2022jp_state !== states.Roman) { stream.prepend(code_point); iso2022jp_state = states.Roman; return [0x1B, 0x28, 0x4A]; } // 7. If code point is U+2022, set it to U+FF0D. if (code_point === 0x2022) code_point = 0xFF0D; // 8. Let pointer be the index pointer for code point in index // jis0208. var pointer = indexPointerFor(code_point, index('jis0208')); // 9. If pointer is null, return error with code point. if (pointer === null) return encoderError(code_point); // 10. If iso-2022-jp encoder state is not jis0208, prepend code // point to stream, set iso-2022-jp encoder state to jis0208, // and return three bytes 0x1B 0x24 0x42. if (iso2022jp_state !== states.jis0208) { stream.prepend(code_point); iso2022jp_state = states.jis0208; return [0x1B, 0x24, 0x42]; } // 11. Let lead be pointer / 94 + 0x21. var lead = div(pointer, 94) + 0x21; // 12. Let trail be pointer % 94 + 0x21. var trail = pointer % 94 + 0x21; // 13. Return two bytes whose values are lead and trail. return [lead, trail]; }; } /** @param {{fatal: boolean}} options */ encoders['iso-2022-jp'] = function(options) { return new ISO2022JPEncoder(options); }; /** @param {{fatal: boolean}} options */ decoders['iso-2022-jp'] = function(options) { return new ISO2022JPDecoder(options); }; // 12.3 shift_jis /** * @constructor * @implements {Decoder} * @param {{fatal: boolean}} options */ function ShiftJISDecoder(options) { var fatal = options.fatal; // shift_jis's decoder has an associated shift_jis lead (initially // 0x00). var /** @type {number} */ shiftjis_lead = 0x00; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and shift_jis lead is not 0x00, // set shift_jis lead to 0x00 and return error. if (bite === end_of_stream && shiftjis_lead !== 0x00) { shiftjis_lead = 0x00; return decoderError(fatal); } // 2. If byte is end-of-stream and shift_jis lead is 0x00, // return finished. if (bite === end_of_stream && shiftjis_lead === 0x00) return finished; // 3. If shift_jis lead is not 0x00, let lead be shift_jis lead, // let pointer be null, set shift_jis lead to 0x00, and then run // these substeps: if (shiftjis_lead !== 0x00) { var lead = shiftjis_lead; var pointer = null; shiftjis_lead = 0x00; // 1. Let offset be 0x40, if byte is less than 0x7F, and 0x41 // otherwise. var offset = (bite < 0x7F) ? 0x40 : 0x41; // 2. Let lead offset be 0x81, if lead is less than 0xA0, and // 0xC1 otherwise. var lead_offset = (lead < 0xA0) ? 0x81 : 0xC1; // 3. If byte is in the range 0x40 to 0x7E or 0x80 to 0xFC, // set pointer to (lead − lead offset) × 188 + byte − offset. if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFC)) pointer = (lead - lead_offset) * 188 + bite - offset; // 4. Let code point be null, if pointer is null, and the // index code point for pointer in index jis0208 otherwise. var code_point = (pointer === null) ? null : indexCodePointFor(pointer, index('jis0208')); // 5. If code point is null and pointer is in the range 8836 // to 10528, return a code point whose value is 0xE000 + // pointer − 8836. if (code_point === null && pointer !== null && inRange(pointer, 8836, 10528)) return 0xE000 + pointer - 8836; // 6. If code point is null and byte is in the range 0x00 to // 0x7F, prepend byte to stream. if (code_point === null && inRange(bite, 0x00, 0x7F)) stream.prepend(bite); // 7. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 8. Return a code point whose value is code point. return code_point; } // 4. If byte is in the range 0x00 to 0x80, return a code point // whose value is byte. if (inRange(bite, 0x00, 0x80)) return bite; // 5. If byte is in the range 0xA1 to 0xDF, return a code point // whose value is 0xFF61 + byte − 0xA1. if (inRange(bite, 0xA1, 0xDF)) return 0xFF61 + bite - 0xA1; // 6. If byte is in the range 0x81 to 0x9F or 0xE0 to 0xFC, set // shift_jis lead to byte and return continue. if (inRange(bite, 0x81, 0x9F) || inRange(bite, 0xE0, 0xFC)) { shiftjis_lead = bite; return null; } // 7. Return error. return decoderError(fatal); }; } /** * @constructor * @implements {Encoder} * @param {{fatal: boolean}} options */ function ShiftJISEncoder(options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is in the range U+0000 to U+0080, return a // byte whose value is code point. if (inRange(code_point, 0x0000, 0x0080)) return code_point; // 3. If code point is U+00A5, return byte 0x5C. if (code_point === 0x00A5) return 0x5C; // 4. If code point is U+203E, return byte 0x7E. if (code_point === 0x203E) return 0x7E; // 5. If code point is in the range U+FF61 to U+FF9F, return a // byte whose value is code point − 0xFF61 + 0xA1. if (inRange(code_point, 0xFF61, 0xFF9F)) return code_point - 0xFF61 + 0xA1; // 6. If code point is U+2022, set it to U+FF0D. if (code_point === 0x2022) code_point = 0xFF0D; // 7. Let pointer be the index shift_jis pointer for code point. var pointer = indexShiftJISPointerFor(code_point); // 8. If pointer is null, return error with code point. if (pointer === null) return encoderError(code_point); // 9. Let lead be pointer / 188. var lead = div(pointer, 188); // 10. Let lead offset be 0x81, if lead is less than 0x1F, and // 0xC1 otherwise. var lead_offset = (lead < 0x1F) ? 0x81 : 0xC1; // 11. Let trail be pointer % 188. var trail = pointer % 188; // 12. Let offset be 0x40, if trail is less than 0x3F, and 0x41 // otherwise. var offset = (trail < 0x3F) ? 0x40 : 0x41; // 13. Return two bytes whose values are lead + lead offset and // trail + offset. return [lead + lead_offset, trail + offset]; }; } /** @param {{fatal: boolean}} options */ encoders['shift_jis'] = function(options) { return new ShiftJISEncoder(options); }; /** @param {{fatal: boolean}} options */ decoders['shift_jis'] = function(options) { return new ShiftJISDecoder(options); }; // // 13. Legacy multi-byte Korean encodings // // 13.1 euc-kr /** * @constructor * @implements {Decoder} * @param {{fatal: boolean}} options */ function EUCKRDecoder(options) { var fatal = options.fatal; // euc-kr's decoder has an associated euc-kr lead (initially 0x00). var /** @type {number} */ euckr_lead = 0x00; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and euc-kr lead is not 0x00, set // euc-kr lead to 0x00 and return error. if (bite === end_of_stream && euckr_lead !== 0) { euckr_lead = 0x00; return decoderError(fatal); } // 2. If byte is end-of-stream and euc-kr lead is 0x00, return // finished. if (bite === end_of_stream && euckr_lead === 0) return finished; // 3. If euc-kr lead is not 0x00, let lead be euc-kr lead, let // pointer be null, set euc-kr lead to 0x00, and then run these // substeps: if (euckr_lead !== 0x00) { var lead = euckr_lead; var pointer = null; euckr_lead = 0x00; // 1. If byte is in the range 0x41 to 0xFE, set pointer to // (lead − 0x81) × 190 + (byte − 0x41). if (inRange(bite, 0x41, 0xFE)) pointer = (lead - 0x81) * 190 + (bite - 0x41); // 2. Let code point be null, if pointer is null, and the // index code point for pointer in index euc-kr otherwise. var code_point = (pointer === null) ? null : indexCodePointFor(pointer, index('euc-kr')); // 3. If code point is null and byte is in the range 0x00 to // 0x7F, prepend byte to stream. if (pointer === null && inRange(bite, 0x00, 0x7F)) stream.prepend(bite); // 4. If code point is null, return error. if (code_point === null) return decoderError(fatal); // 5. Return a code point whose value is code point. return code_point; } // 4. If byte is in the range 0x00 to 0x7F, return a code point // whose value is byte. if (inRange(bite, 0x00, 0x7F)) return bite; // 5. If byte is in the range 0x81 to 0xFE, set euc-kr lead to // byte and return continue. if (inRange(bite, 0x81, 0xFE)) { euckr_lead = bite; return null; } // 6. Return error. return decoderError(fatal); }; } /** * @constructor * @implements {Encoder} * @param {{fatal: boolean}} options */ function EUCKREncoder(options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is in the range U+0000 to U+007F, return a // byte whose value is code point. if (inRange(code_point, 0x0000, 0x007F)) return code_point; // 3. Let pointer be the index pointer for code point in index // euc-kr. var pointer = indexPointerFor(code_point, index('euc-kr')); // 4. If pointer is null, return error with code point. if (pointer === null) return encoderError(code_point); // 5. Let lead be pointer / 190 + 0x81. var lead = div(pointer, 190) + 0x81; // 6. Let trail be pointer % 190 + 0x41. var trail = (pointer % 190) + 0x41; // 7. Return two bytes whose values are lead and trail. return [lead, trail]; }; } /** @param {{fatal: boolean}} options */ encoders['euc-kr'] = function(options) { return new EUCKREncoder(options); }; /** @param {{fatal: boolean}} options */ decoders['euc-kr'] = function(options) { return new EUCKRDecoder(options); }; // // 14. Legacy miscellaneous encodings // // 14.1 replacement // Not needed - API throws RangeError // 14.2 utf-16 /** * @param {number} code_unit * @param {boolean} utf16be * @return {!Array.} bytes */ function convertCodeUnitToBytes(code_unit, utf16be) { // 1. Let byte1 be code unit >> 8. var byte1 = code_unit >> 8; // 2. Let byte2 be code unit & 0x00FF. var byte2 = code_unit & 0x00FF; // 3. Then return the bytes in order: // utf-16be flag is set: byte1, then byte2. if (utf16be) return [byte1, byte2]; // utf-16be flag is unset: byte2, then byte1. return [byte2, byte1]; } /** * @constructor * @implements {Decoder} * @param {boolean} utf16_be True if big-endian, false if little-endian. * @param {{fatal: boolean}} options */ function UTF16Decoder(utf16_be, options) { var fatal = options.fatal; var /** @type {?number} */ utf16_lead_byte = null, /** @type {?number} */ utf16_lead_surrogate = null; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream and either utf-16 lead byte or // utf-16 lead surrogate is not null, set utf-16 lead byte and // utf-16 lead surrogate to null, and return error. if (bite === end_of_stream && (utf16_lead_byte !== null || utf16_lead_surrogate !== null)) { return decoderError(fatal); } // 2. If byte is end-of-stream and utf-16 lead byte and utf-16 // lead surrogate are null, return finished. if (bite === end_of_stream && utf16_lead_byte === null && utf16_lead_surrogate === null) { return finished; } // 3. If utf-16 lead byte is null, set utf-16 lead byte to byte // and return continue. if (utf16_lead_byte === null) { utf16_lead_byte = bite; return null; } // 4. Let code unit be the result of: var code_unit; if (utf16_be) { // utf-16be decoder flag is set // (utf-16 lead byte << 8) + byte. code_unit = (utf16_lead_byte << 8) + bite; } else { // utf-16be decoder flag is unset // (byte << 8) + utf-16 lead byte. code_unit = (bite << 8) + utf16_lead_byte; } // Then set utf-16 lead byte to null. utf16_lead_byte = null; // 5. If utf-16 lead surrogate is not null, let lead surrogate // be utf-16 lead surrogate, set utf-16 lead surrogate to null, // and then run these substeps: if (utf16_lead_surrogate !== null) { var lead_surrogate = utf16_lead_surrogate; utf16_lead_surrogate = null; // 1. If code unit is in the range U+DC00 to U+DFFF, return a // code point whose value is 0x10000 + ((lead surrogate − // 0xD800) << 10) + (code unit − 0xDC00). if (inRange(code_unit, 0xDC00, 0xDFFF)) { return 0x10000 + (lead_surrogate - 0xD800) * 0x400 + (code_unit - 0xDC00); } // 2. Prepend the sequence resulting of converting code unit // to bytes using utf-16be decoder flag to stream and return // error. stream.prepend(convertCodeUnitToBytes(code_unit, utf16_be)); return decoderError(fatal); } // 6. If code unit is in the range U+D800 to U+DBFF, set utf-16 // lead surrogate to code unit and return continue. if (inRange(code_unit, 0xD800, 0xDBFF)) { utf16_lead_surrogate = code_unit; return null; } // 7. If code unit is in the range U+DC00 to U+DFFF, return // error. if (inRange(code_unit, 0xDC00, 0xDFFF)) return decoderError(fatal); // 8. Return code point code unit. return code_unit; }; } /** * @constructor * @implements {Encoder} * @param {boolean} utf16_be True if big-endian, false if little-endian. * @param {{fatal: boolean}} options */ function UTF16Encoder(utf16_be, options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1. If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is in the range U+0000 to U+FFFF, return the // sequence resulting of converting code point to bytes using // utf-16be encoder flag. if (inRange(code_point, 0x0000, 0xFFFF)) return convertCodeUnitToBytes(code_point, utf16_be); // 3. Let lead be ((code point − 0x10000) >> 10) + 0xD800, // converted to bytes using utf-16be encoder flag. var lead = convertCodeUnitToBytes( ((code_point - 0x10000) >> 10) + 0xD800, utf16_be); // 4. Let trail be ((code point − 0x10000) & 0x3FF) + 0xDC00, // converted to bytes using utf-16be encoder flag. var trail = convertCodeUnitToBytes( ((code_point - 0x10000) & 0x3FF) + 0xDC00, utf16_be); // 5. Return a byte sequence of lead followed by trail. return lead.concat(trail); }; } // 14.3 utf-16be /** @param {{fatal: boolean}} options */ encoders['utf-16be'] = function(options) { return new UTF16Encoder(true, options); }; /** @param {{fatal: boolean}} options */ decoders['utf-16be'] = function(options) { return new UTF16Decoder(true, options); }; // 14.4 utf-16le /** @param {{fatal: boolean}} options */ encoders['utf-16le'] = function(options) { return new UTF16Encoder(false, options); }; /** @param {{fatal: boolean}} options */ decoders['utf-16le'] = function(options) { return new UTF16Decoder(false, options); }; // 14.5 x-user-defined /** * @constructor * @implements {Decoder} * @param {{fatal: boolean}} options */ function XUserDefinedDecoder(options) { var fatal = options.fatal; /** * @param {Stream} stream The stream of bytes being decoded. * @param {number} bite The next byte read from the stream. * @return {?(number|!Array.)} The next code point(s) * decoded, or null if not enough data exists in the input * stream to decode a complete code point. */ this.handler = function(stream, bite) { // 1. If byte is end-of-stream, return finished. if (bite === end_of_stream) return finished; // 2. If byte is in the range 0x00 to 0x7F, return a code point // whose value is byte. if (inRange(bite, 0x00, 0x7F)) return bite; // 3. Return a code point whose value is 0xF780 + byte − 0x80. return 0xF780 + bite - 0x80; }; } /** * @constructor * @implements {Encoder} * @param {{fatal: boolean}} options */ function XUserDefinedEncoder(options) { var fatal = options.fatal; /** * @param {Stream} stream Input stream. * @param {number} code_point Next code point read from the stream. * @return {(number|!Array.)} Byte(s) to emit. */ this.handler = function(stream, code_point) { // 1.If code point is end-of-stream, return finished. if (code_point === end_of_stream) return finished; // 2. If code point is in the range U+0000 to U+007F, return a // byte whose value is code point. if (inRange(code_point, 0x0000, 0x007F)) return code_point; // 3. If code point is in the range U+F780 to U+F7FF, return a // byte whose value is code point − 0xF780 + 0x80. if (inRange(code_point, 0xF780, 0xF7FF)) return code_point - 0xF780 + 0x80; // 4. Return error with code point. return encoderError(code_point); }; } /** @param {{fatal: boolean}} options */ encoders['x-user-defined'] = function(options) { return new XUserDefinedEncoder(options); }; /** @param {{fatal: boolean}} options */ decoders['x-user-defined'] = function(options) { return new XUserDefinedDecoder(options); }; if (!global['TextEncoder']) global['TextEncoder'] = TextEncoder; if (!global['TextDecoder']) global['TextDecoder'] = TextDecoder; }(this)); ================================================ FILE: bin/client/assets/Script/Encoding.js.meta ================================================ { "ver": "1.0.2", "uuid": "2d3ef493-9e65-47f1-a3cc-c30517fcd563", "isPlugin": true, "subMetas": {} } ================================================ FILE: bin/client/assets/Script/main.js ================================================ var CountDown = require('CountDown'); cc.Class({ extends: CountDown, properties: { data:null, card:{ default:[], type:cc.Node }, inpot:{ default: null, type: cc.Node }, //桌子上的筹码数量 table_chips_inpot:0, //桌子上需要收入底池的筹码节点 table_chips:{ default:[], type:[cc.Node] }, table_tips:{ default:[], type:[cc.Node] }, game_card_turn:0, game_card_river:0, cleanNode:{ default:[], type:cc.Node }, cleanSp:{ default:[], type:cc.Sprite }, //游戏是否在播放 0-未播放 1-正在播放 2-播放完毕 game_start:0, //t_sprite:{//定义一个cc的类型,并定义上常用属性 // default:null, // type:cc.SpriteFrame,//类型的定义 // url:cc.Texture2D, //Raw Asset(cc.Texture2D, cc.Font, cc.AudioClip) // enabled:true,//属性检查器中是否可见 // displayName:'himi',//属性检查器中属性的名字 // tooltip:"测试脚本",//属性检查器中停留此属性名称显示的提示文字 // readonly:false,//属性检查器中显示(readonly)且不可修改[当前有bug,设定只读也能修改] // serializable:true,//设置false就是临时变量 // editorOnly:false//导出项目前剔除此属性 //}, ////可以只定义 get 方法,这样相当于一份 readonly 的属性。[当前有bug,只设定get也能修改] //t_getSet:{ // default:12, // get:function(){return this.t_getSet},//get // set:function(value){this.t_getSet =value;}//set //}, }, // use this for initialization onLoad: function () { var me = this; me.is_mobile = this.isMobile(); if(me.is_mobile == 0){ var canvas = cc.find("Canvas"); canvas.width = 418; canvas.height = 738; } cc.game.config.showFPS=false; cc.director.setDisplayStats(false); this.eventListen(); //资源的后缀,方便加载不同资源 var lang = this.getQueryString("lang"); lang = lang?lang:"zh-cn"; //lang = 'en-us'; var config_lang = {"zh-cn":"cn","thai-th":"th","en-us":"en","zh-tw":"tw","ko":"ko"}; if(config_lang[lang] == null || config_lang[lang] == undefined){ lang = "zh-cn"; } this.Lang = lang; this.SourceSuffix = config_lang[lang]; //按钮的提示 var sound_tip = cc.find("Canvas/sound/sound_tips"); sound_tip.getComponent(cc.Label).string=this.ConvertLang("mute");//静音 //多语言替换座位 //this.ReplaceSeat(); //4. 先获取目标组件所在的节点,然后通过getComponent获取目标组件 //var _label = cc.find("Canvas/label").getComponent(cc.Label); //var _label = cc.find("Canvas/card_49").getComponent(cc.Sprite); //cc.log(_label instanceof cc.Sprite); // true // //--->>>复制节点/或者复制 prefab // //复制节点 // var lLabel = cc.instantiate(this.label); // lLabel.node.parent = this.node; // lLabel.node.setPosition(-200,0); // //复制prefab // var tPrefab = cc.instantiate(this.t_prefab); // tPrefab.parent = this.node; // tPrefab.setPosition(-210,100); // //--->>> 发射事件(事件手动触发) // this.node.on("tEmitFun",function (event){ // console.log("tEmitFun event:"+event.detail.himi+"|"+event.detail.say); // //-->>> 事件中断,如下函数阻止事件向当前父级进行事件传递 // // event.stopPropagation(); // }); // this.node.emit("tEmitFun",{himi:27,say:"hello,cc!"}); //牌局回放加载数据 //this.reqstart(); //websocket请求 this.wsstart(); this.onSeat(); }, eventListen:function(){ //当手指触点落在目标节点区域内时 var sound=cc.find("Canvas/sound"); sound.on("mouseenter",function(event){ sound.getChildByName("sound_tips").opacity=255; }); sound.on("mouseleave",function(event){ sound.getChildByName("sound_tips").opacity=0; }); sound.on("touchstart",function(event){ sound.getChildByName("sound_tips").opacity=255; }); sound.on("touchend",function(event){ sound.getChildByName("sound_tips").opacity=0; }); }, // 站起 5 // 离开房间 6 // flop发牌命令 9 // turn发牌命令 10 // river发牌命令 11 // check 12 // call 13 // raise 14 // fold 15 // 一手结束数据 16 // 发表情 17 // 发道具 18 // 延时操作 19 // 主动亮牌 24 // 牌局结束 25 // 发道具(可连发和群发) 35 // 聊天消息 36 // "CMD" : 13, // "chair_id" : 3, // "chip" : 1, // "current_action_chair" : 4, // "current_pot" : 4, // "pot" : 4, // "timestamp" : 1466422796, actionend:function(){ var i = this.i; this.i=i+1; if(i0){ duration=duration+1; this.scheduleOnce(function(){ this.tableToPot(0,0,this.table_chips_inpot); },duration); } switch(len) { case 1: duration=duration+1; var rivercard=[cards[0]]; this.scheduleOnce(function(){ this.riverstart(rivercard); },duration); break; case 2: duration=duration+1; var turnpcard=[cards[0]]; this.scheduleOnce(function(){ this.turnstart(turnpcard); },duration); duration=duration+2; var rivercard=[cards[1]]; this.scheduleOnce(function(){ this.riverstart(rivercard); },duration); break; case 5: duration=duration+1; var flopcard=[cards[0],cards[1],cards[2]]; this.scheduleOnce(function(){ this.flopstart(flopcard); },duration); duration=duration+3; var turnpcard=[cards[3]]; this.scheduleOnce(function(){ this.turnstart(turnpcard); },duration); duration=duration+1; var rivercard=[cards[4]]; this.scheduleOnce(function(){ this.riverstart(rivercard); },7); break; default: break; } duration=duration+1; this.scheduleOnce(function(){ this.end(); this.buttonenable(); },duration); }, //比牌结束显示输赢详情 endtip:function(sit,chips,card1,card2,cardType,new_chips) { var table_bg = this.node.parent.getChildByName("table_bg"); var pos = table_bg.getChildByName("seat_" + sit).getPosition(); var node = new cc.Node(); this.cleanNode.push(node); var lo = node.addComponent(cc.Layout); node.parent = this.node.parent; node.setPosition(pos); //node.setPosition(x,y); var font = 20;//上下label字体大小 var color = new cc.Color(0, 0, 0);//上下字体颜色 //牌型cardType var ctNode = new cc.Node(); var ctChip = ctNode.addComponent(cc.Sprite); ctNode.parent = node; ctNode.setPosition(0, -80); //显示当前的筹码数 var seat_chips_node = cc.find("Canvas/table_bg/seat_"+sit+"/chips"); var seat_chips_lable = seat_chips_node.getComponent(cc.Label); seat_chips_lable.string = new_chips; if (chips > 0) { this.potToWinner(pos); var lbNode = new cc.Node(); var lbChip = lbNode.addComponent(cc.Sprite); lbChip.spriteFrame = this.GameMain.getSpriteFrame('game_endhand'); lbNode.parent = node; lbNode.setPosition(0, 80); //营收文字 var lbbNode = new cc.Node(); var lbb = lbbNode.addComponent(cc.Label); lbb.string = "+" + chips; lbbNode.parent = lbNode; lbb.fontSize = font; lbbNode.color = color; lbbNode.setPosition(0, -10); } //2牌都亮时显示牌型 if (card1 > 0 && card2 > 0) { ctChip.spriteFrame = this.GameMain.getSpriteFrame('game_endhand'); //牌型文字 var ctlNode = new cc.Node(); var ctl = ctlNode.addComponent(cc.Label); ctl.string = cardType; ctlNode.parent = ctNode; ctl.fontSize = font; ctlNode.color = color; ctlNode.setPosition(0, -10); }; if (card1 == 0 && card2 == 0) { //不显示底牌 return false; }; //底牌 var c1Node = new cc.Node(); var c2Node = new cc.Node(); var c1Chip = c1Node.addComponent(cc.Sprite); var c2Chip = c2Node.addComponent(cc.Sprite); c1Node.scale = 0.6; c2Node.scale = 0.6; c1Node.parent = node; c2Node.parent = node; c1Node.setPosition(-28, 0); c2Node.setPosition(28, 0); if (card1 > 0 && card2 > 0) { if (card1 < 10) { var card_1 = 'card_0' + card1; } else { var card_1 = 'card_' + card1; } if(card2<10){ var card_2='card_0'+card2; }else{ var card_2='card_'+card2; } c1Chip.spriteFrame = this.GameCards.getSpriteFrame(card_1); c2Chip.spriteFrame = this.GameCards.getSpriteFrame(card_2); } else { if(card1 > 0 ){ //显示牌背 c1Chip.spriteFrame = this.GameCards.getSpriteFrame(card_1); //显示牌背 c2Chip.spriteFrame = this.GameMain.getSpriteFrame('game_card_reverse'); }else{ c2Chip.spriteFrame = this.GameCards.getSpriteFrame(card_2); //显示牌背 c1Chip.spriteFrame = this.GameMain.getSpriteFrame('game_card_reverse'); } } }, resetGame:function(){ //cc.game.restart(); this.resetSeat(); this.card[0].removeAllChildren(true); this.card[1].removeAllChildren(true); this.card[2].removeAllChildren(true); this.card[3].removeAllChildren(true); this.card[4].removeAllChildren(true); if("undefined" != typeof this.cleanNode){ var len=this.cleanNode.length; if(len>0){ for(var i=0;i0){ for(var i=0;i0){ for(var i=0;i0){ inpot=parseInt(inpotObj.string)+addNum; }; inpotObj.string = inpot; }else{ var sp = this.inpot.addComponent(cc.Sprite); sp.spriteFrame = this.GameMain.getSpriteFrame('game_inPot_frame'); var node=new cc.Node(); var lb = node.addComponent(cc.Label); lb.fontSize=25; if(addNum>0){ inpot = inpot+addNum; }; lb.string=inpot; //node.color = new cc.Color(0, 0, 0); node.name="inpot"; node.parent=this.inpot; node.setPosition(0,-12); } }, /** * 说明:flop三张牌移动效果 * card 公牌数组 */ flopstart:function(card){ var card1; if(card[0]<10){ card1='card_0'+card[0]; }else{ card1='card_'+card[0]; } var card2; if(card[1]<10){ card2='card_0'+card[1]; }else{ card2='card_'+card[1]; } var card3; if(card[2]<10){ card3='card_0'+card[2]; }else{ card3='card_'+card[2]; } var node1=new cc.Node(); //var node1=new cc.Node(); var mSf1 = node1.addComponent(cc.Sprite); var node2=new cc.Node(); var mSf2 = node2.addComponent(cc.Sprite); var node3=new cc.Node(); var mSf3 = node3.addComponent(cc.Sprite); mSf1.spriteFrame = this.GameCards.getSpriteFrame(card1); mSf2.spriteFrame = this.GameCards.getSpriteFrame(card2); mSf3.spriteFrame = this.GameCards.getSpriteFrame(card3); mSf1.enabled=true; //node1.active=true; //node1.parent = this.node.parent; //node1.setPosition(-200,50); mSf2.enabled=true; //node2.active=true; //node2.parent = this.node.parent; //node2.setPosition(-200,50); mSf3.enabled=true; //node3.active=true; //node3.parent = this.node.parent; //node3.setPosition(-200,50); //var action1=cc.moveTo(1, cc.p(-100, 50)); //var action2=cc.moveTo(2, cc.p(0, 50)); var action1=cc.moveTo(1, cc.p(90, 0)); var action2=cc.moveTo(2, cc.p(180, 0)); var action3=cc.callFunc(function(){ //flop结束 this.actionend(); },this); var seq=cc.sequence(action2,action3); var me = this; if(me.open_mute == 0){ if(me.audio_distributeCard == null){ cc.loader.loadRes("audio/audio_distributeCard", function (err, assets) { me.audio_distributeCard = assets; cc.audioEngine.playEffect(assets); node1.parent=this.card[0]; node2.parent=this.card[1]; node3.parent=this.card[2]; node1.runAction(action1); node2.runAction(seq); }); }else{ cc.audioEngine.playEffect(this.audio_distributeCard); node1.parent=this.card[0]; node2.parent=this.card[1]; node3.parent=this.card[2]; node1.runAction(action1); node2.runAction(seq); } }else{ node1.parent=this.card[0]; node2.parent=this.card[1]; node3.parent=this.card[2]; node1.runAction(action1); node2.runAction(seq); } }, /** * 说明:翻牌效果 * card 公牌数组 */ turnstart:function(card){ this.game_card_turn=card[0]; var node=new cc.Node(); var mSf = node.addComponent(cc.Sprite); var frame = this.GameMain.getSpriteFrame('game_card_reverse'); mSf.spriteFrame = frame; mSf.enabled=true; node.active=true; node.parent = this.node.parent; node.setPosition(101,-10); var turn = cc.callFunc(this.showturn, this, node); var action1=cc.rotateTo(0.3, 0, 180); var seq=cc.sequence(action1,turn); var me = this; if(me.open_mute == 0){ if(me.audio_distributeCard == null){ cc.loader.loadRes("audio/audio_distributeCard", function (err, assets) { me.audio_distributeCard = assets; node.runAction(seq); cc.audioEngine.playEffect(assets); }); }else{ node.runAction(seq); cc.audioEngine.playEffect(this.audio_distributeCard); } }else{ node.runAction(seq); } }, /** * 说明:翻牌效果 回调 * node 牌背节点 */ showturn:function(node){ var card1; if(this.game_card_turn<10){ card1='card_0'+this.game_card_turn; }else{ card1='card_'+this.game_card_turn; } var node1=new cc.Node(); node1.parent=this.card[3]; var mSf = node1.addComponent(cc.Sprite); mSf.spriteFrame = this.GameCards.getSpriteFrame(card1); if(cc.isValid(node)){ node.destroy(); } this.actionend(); }, //翻牌效果 riverstart:function(card){ this.game_card_river=card[0]; var node=new cc.Node(); var mSf = node.addComponent(cc.Sprite); var frame = this.GameMain.getSpriteFrame('game_card_reverse'); mSf.spriteFrame = frame; mSf.enabled=true; node.active=true; //node.parent = this.card[4]; node.parent=this.node.parent; node.setPosition(192,-10); var turn = cc.callFunc(this.showriver, this, node); var action1=cc.rotateTo(0.3, 0, 180); var seq=cc.sequence(action1,turn); var me = this; if(me.open_mute == 0){ if(me.audio_distributeCard == null){ cc.loader.loadRes("audio/audio_distributeCard", function (err, assets) { me.audio_distributeCard = assets; node.runAction(seq); cc.audioEngine.playEffect(assets); }); }else{ node.runAction(seq); cc.audioEngine.playEffect(this.audio_distributeCard); } }else{ node.runAction(seq); } }, //翻牌效果 回调 showriver:function(node){ var card1; if(this.game_card_river<10){ card1='card_0'+this.game_card_river; }else{ card1='card_'+this.game_card_river; } var node1=new cc.Node(); node1.parent=this.card[4]; var mSf = node1.addComponent(cc.Sprite); mSf.spriteFrame = this.GameCards.getSpriteFrame(card1); if(cc.isValid(node)){ node.destroy(); } this.actionend(); }, timestart:function(pos){ this.timer=new cc.Node(); this.timer.scale=1.2; var sp = this.timer.addComponent(cc.Sprite); sp.type = cc.Sprite.Type.FILLED; sp.fillType = cc.Sprite.FillType.RADIAL; sp.fillCenter = new cc.Vec2(0.5, 0.5); sp.fillStart = 0; sp.fillRange = 0; var frame1 = this.GameMain.getSpriteFrame('game_progress_frame'); sp.spriteFrame = frame1; this.timersp=sp; this.timer.parent=this.node.parent; this.timer.position=pos; this.timing=true; }, //延时操作 delay_think:function(seat_number,duration){ this.add_countdown(seat_number,duration); var me = this; var finished = function(){ me.delay_countdown(seat_number,duration); }; this.countdown_over_task = finished; }, update: function (dt) { }, //别人正在操作时,站起 other_quit:function(sit){ var finished = function(){ var table_bg = cc.find("Canvas/table_bg"); var seat=table_bg.getChildByName("seat_"+sit); //seat.enabled=false; //隐藏图像 seat.getChildByName("avatar").setOpacity(0); seat.getChildByName("nick").setOpacity(0); seat.getChildByName("chips").setOpacity(0); seat.getChildByName("hand_card").setOpacity(0); if(seat.getChildByName("game_tip").getComponent(cc.Sprite)!=null){ seat.getChildByName("game_tip").getComponent(cc.Sprite).destroy(); } }; finished(); }, }); ================================================ FILE: bin/client/assets/Script/main.js.meta ================================================ { "ver": "1.0.2", "uuid": "ba49ca20-5856-400d-8933-bc1dfd520dc1", "isPlugin": false, "subMetas": {} } ================================================ FILE: bin/client/assets/Script.meta ================================================ { "ver": "1.0.1", "uuid": "3af1e10d-442f-4956-9f83-2dec73688db7", "isGroup": false, "subMetas": {} } ================================================ FILE: bin/client/assets/resources/GameMain_6p.plist ================================================ frames close_audio.png frame {{1331,132},{128,128}} offset {0,0} rotated sourceColorRect {{0,0},{128,128}} sourceSize {128,128} forward_normal.png frame {{1219,2},{128,128}} offset {0,0} rotated sourceColorRect {{0,0},{128,128}} sourceSize {128,128} forward_unnormal.png frame {{1216,356},{128,128}} offset {0,0} rotated sourceColorRect {{0,0},{128,128}} sourceSize {128,128} game_addFriend_disable.png frame {{1517,2},{98,98}} offset {0,0} rotated sourceColorRect {{1,1},{98,98}} sourceSize {100,100} game_addFriend_normal.png frame {{1417,2},{98,98}} offset {0,0} rotated sourceColorRect {{1,1},{98,98}} sourceSize {100,100} game_addFriend_press.png frame {{1032,513},{98,98}} offset {0,0} rotated sourceColorRect {{1,1},{98,98}} sourceSize {100,100} game_allIn_normal.png frame {{848,198},{156,157}} offset {0,19} rotated sourceColorRect {{0,0},{156,157}} sourceSize {156,195} game_allIn_press.png frame {{690,199},{156,157}} offset {0,19} rotated sourceColorRect {{0,0},{156,157}} sourceSize {156,195} game_allIn_tip.png frame {{1349,2},{126,66}} offset {0,0} rotated sourceColorRect {{0,0},{126,66}} sourceSize {126,66} game_arrow_tip.png frame {{294,826},{18,24}} offset {0,0} rotated sourceColorRect {{0,0},{18,24}} sourceSize {18,24} game_audioPlaying_tip.png frame {{202,687},{120,40}} offset {0,0} rotated sourceColorRect {{0,0},{120,40}} sourceSize {120,40} game_audioProgress.png frame {{240,373},{312,36}} offset {0,0} rotated sourceColorRect {{0,0},{312,36}} sourceSize {312,36} game_audioProgress_frame.png frame {{202,373},{312,36}} offset {0,0} rotated sourceColorRect {{0,0},{312,36}} sourceSize {312,36} game_bigBlind_tip.png frame {{1538,297},{58,61}} offset {-2,6} rotated sourceColorRect {{8,4},{58,61}} sourceSize {78,81} game_cardHighlight_frame.png frame {{893,2},{134,184}} offset {-2,8} rotated sourceColorRect {{0,0},{134,184}} sourceSize {138,200} game_cardType_tip.png frame {{396,977},{32,32}} offset {0,0} rotated sourceColorRect {{1,1},{32,32}} sourceSize {34,34} game_card_mask.png frame {{720,358},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} game_card_reverse.png frame {{753,2},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} game_cartType_bg.png frame {{1029,2},{150,45}} offset {0,0} rotated sourceColorRect {{0,0},{150,45}} sourceSize {150,45} game_chat_bg.png frame {{2,1018},{756,921}} offset {0,0} rotated sourceColorRect {{0,0},{756,921}} sourceSize {756,921} game_chat_button_normal.png frame {{651,1941},{210,105}} offset {0,0} rotated sourceColorRect {{0,0},{210,105}} sourceSize {210,105} game_chat_button_press.png frame {{439,1941},{210,105}} offset {0,0} rotated sourceColorRect {{0,0},{210,105}} sourceSize {210,105} game_chat_emotion_noraml.png frame {{568,2},{369,120}} offset {0,0} rotated sourceColorRect {{0,0},{369,120}} sourceSize {369,120} game_chat_emotion_press.png frame {{446,2},{369,120}} offset {0,0} rotated sourceColorRect {{0,0},{369,120}} sourceSize {369,120} game_chat_icon_normal.png frame {{1889,159},{87,81}} offset {0,0} rotated sourceColorRect {{0,0},{87,81}} sourceSize {87,81} game_chat_icon_press.png frame {{1889,76},{87,81}} offset {0,0} rotated sourceColorRect {{0,0},{87,81}} sourceSize {87,81} game_chat_text_normal.png frame {{324,2},{369,120}} offset {0,0} rotated sourceColorRect {{0,0},{369,120}} sourceSize {369,120} game_chat_text_press.png frame {{202,2},{369,120}} offset {0,0} rotated sourceColorRect {{0,0},{369,120}} sourceSize {369,120} game_checkBox_normal.png frame {{1372,339},{57,57}} offset {0,0} rotated sourceColorRect {{0,0},{57,57}} sourceSize {57,57} game_checkBox_press.png frame {{1449,316},{57,57}} offset {0,0} rotated sourceColorRect {{0,0},{57,57}} sourceSize {57,57} game_chip_tip.png frame {{1610,234},{60,63}} offset {-1,5} rotated sourceColorRect {{8,4},{60,63}} sourceSize {78,81} game_close_normal.png frame {{1799,71},{88,88}} offset {0,0} rotated sourceColorRect {{0,0},{88,88}} sourceSize {88,88} game_close_press.png frame {{446,887},{88,88}} offset {0,0} rotated sourceColorRect {{0,0},{88,88}} sourceSize {88,88} game_dealer_tip.png frame {{1781,303},{49,49}} offset {0,0} rotated sourceColorRect {{1,1},{49,49}} sourceSize {51,51} game_decrease_disable.png frame {{1762,232},{69,69}} offset {0,0} rotated sourceColorRect {{0,0},{69,69}} sourceSize {69,69} game_decrease_normal.png frame {{1691,227},{69,69}} offset {0,0} rotated sourceColorRect {{0,0},{69,69}} sourceSize {69,69} game_decrease_press.png frame {{1762,161},{69,69}} offset {0,0} rotated sourceColorRect {{0,0},{69,69}} sourceSize {69,69} game_delay_disable.png frame {{1613,156},{76,76}} offset {0,-22} rotated sourceColorRect {{22,44},{76,76}} sourceSize {120,120} game_delay_normal.png frame {{1461,161},{76,76}} offset {0,-22} rotated sourceColorRect {{22,44},{76,76}} sourceSize {120,120} game_delay_press.png frame {{1294,277},{76,76}} offset {0,-22} rotated sourceColorRect {{22,44},{76,76}} sourceSize {120,120} game_dialogCancel_normal.png frame {{400,373},{300,120}} offset {0,0} rotated sourceColorRect {{0,0},{300,120}} sourceSize {300,120} game_dialogOK_normal.png frame {{324,675},{300,120}} offset {0,0} rotated sourceColorRect {{0,0},{300,120}} sourceSize {300,120} game_dialogRetry_normal.png frame {{278,373},{300,120}} offset {0,0} rotated sourceColorRect {{0,0},{300,120}} sourceSize {300,120} game_dialog_frame.png frame {{522,571},{100,100}} offset {0,0} rotated sourceColorRect {{0,0},{100,100}} sourceSize {100,100} game_editbox_bg.png frame {{2,1941},{435,105}} offset {0,0} rotated sourceColorRect {{0,0},{435,105}} sourceSize {435,105} game_emotion_normal.png frame {{1372,262},{75,75}} offset {0,0} rotated sourceColorRect {{0,0},{75,75}} sourceSize {75,75} game_emotion_press.png frame {{1461,239},{75,75}} offset {0,0} rotated sourceColorRect {{0,0},{75,75}} sourceSize {75,75} game_endhand.png frame {{1006,188},{150,45}} offset {0,0} rotated sourceColorRect {{0,0},{150,45}} sourceSize {150,45} game_female_tip.png frame {{1833,273},{54,54}} offset {0,0} rotated sourceColorRect {{1,1},{54,54}} sourceSize {56,56} game_handCard_cover_tip.png frame {{1207,277},{85,77}} offset {0,-1} rotated sourceColorRect {{0,2},{85,77}} sourceSize {85,79} game_handChips_tip.png frame {{952,357},{140,154}} offset {-2,-1} rotated sourceColorRect {{64,60},{140,154}} sourceSize {272,272} game_header_frame.png frame {{1053,154},{144,144}} offset {0,0} rotated sourceColorRect {{0,0},{144,144}} sourceSize {144,144} game_inPot_extra_frame.png frame {{1910,2},{72,90}} offset {-88,3} rotated sourceColorRect {{10,1},{72,90}} sourceSize {268,98} game_inPot_frame.png frame {{194,730},{268,98}} offset {0,0} rotated sourceColorRect {{0,0},{268,98}} sourceSize {268,98} game_increase_disable.png frame {{1691,156},{69,69}} offset {0,0} rotated sourceColorRect {{0,0},{69,69}} sourceSize {69,69} game_increase_normal.png frame {{1539,226},{69,69}} offset {0,0} rotated sourceColorRect {{0,0},{69,69}} sourceSize {69,69} game_increase_press.png frame {{1542,155},{69,69}} offset {0,0} rotated sourceColorRect {{0,0},{69,69}} sourceSize {69,69} game_male_tip.png frame {{1889,242},{54,54}} offset {0,0} rotated sourceColorRect {{1,1},{54,54}} sourceSize {56,56} game_microPhone_normal.png frame {{933,633},{77,138}} offset {-1,-36} rotated sourceColorRect {{58,72},{77,138}} sourceSize {195,210} game_microPhone_press.png frame {{446,675},{195,210}} offset {0,0} rotated sourceColorRect {{0,0},{195,210}} sourceSize {195,210} game_money_tip.png frame {{1995,289},{48,48}} offset {0,0} rotated sourceColorRect {{0,0},{48,48}} sourceSize {48,48} game_note_normal.png frame {{1094,357},{135,120}} offset {0,0} rotated sourceColorRect {{0,0},{135,120}} sourceSize {135,120} game_note_press.png frame {{1012,633},{135,120}} offset {0,0} rotated sourceColorRect {{0,0},{135,120}} sourceSize {135,120} game_owner_tip.png frame {{362,977},{32,32}} offset {0,0} rotated sourceColorRect {{1,1},{32,32}} sourceSize {34,34} game_playerAudioSwitch_disable.png frame {{932,533},{98,98}} offset {0,0} rotated sourceColorRect {{1,1},{98,98}} sourceSize {100,100} game_playerAudioSwitch_normal.png frame {{832,554},{98,98}} offset {0,0} rotated sourceColorRect {{1,1},{98,98}} sourceSize {100,100} game_playerAudioSwitch_press.png frame {{732,554},{98,98}} offset {0,0} rotated sourceColorRect {{1,1},{98,98}} sourceSize {100,100} game_popProgressClose_normal.png frame {{933,773},{94,94}} offset {0,0} rotated sourceColorRect {{0,0},{94,94}} sourceSize {94,94} game_preRecord_normal.png frame {{1708,68},{86,89}} offset {0,0} rotated sourceColorRect {{0,0},{86,89}} sourceSize {86,89} game_preRecord_press.png frame {{1617,68},{86,89}} offset {0,0} rotated sourceColorRect {{0,0},{86,89}} sourceSize {86,89} game_progress_frame.png frame {{1076,2},{141,141}} offset {0,0} rotated sourceColorRect {{0,0},{141,141}} sourceSize {141,141} game_progress_normal.png frame {{732,2},{195,19}} offset {0,0} rotated sourceColorRect {{0,0},{195,19}} sourceSize {195,19} game_progress_range.png frame {{711,2},{195,19}} offset {0,0} rotated sourceColorRect {{0,0},{195,19}} sourceSize {195,19} game_progress_yellow.png frame {{690,2},{195,19}} offset {0,0} rotated sourceColorRect {{0,0},{195,19}} sourceSize {195,19} game_property_01.png frame {{1542,102},{51,73}} offset {3,0} rotated sourceColorRect {{28,14},{51,73}} sourceSize {101,101} game_property_02.png frame {{1978,228},{59,65}} offset {2,1} rotated sourceColorRect {{23,17},{59,65}} sourceSize {101,101} game_property_03.png frame {{1130,300},{75,55}} offset {4,-3} rotated sourceColorRect {{17,26},{75,55}} sourceSize {101,101} game_property_03_disable.png frame {{1053,300},{75,55}} offset {4,-3} rotated sourceColorRect {{17,26},{75,55}} sourceSize {101,101} game_property_04.png frame {{1815,2},{67,93}} offset {3,3} rotated sourceColorRect {{20,1},{67,93}} sourceSize {101,101} game_property_05.png frame {{1461,102},{57,79}} offset {3,1} rotated sourceColorRect {{25,10},{57,79}} sourceSize {101,101} game_quit_tip.png frame {{328,977},{32,32}} offset {0,0} rotated sourceColorRect {{1,1},{32,32}} sourceSize {34,34} game_raise_allin.png frame {{841,654},{174,90}} offset {0,0} rotated sourceColorRect {{0,0},{174,90}} sourceSize {174,90} game_rebuy_tip.png frame {{294,977},{32,32}} offset {0,0} rotated sourceColorRect {{1,1},{32,32}} sourceSize {34,34} game_red_tip.png frame {{194,1000},{8,8}} offset {0,0} rotated sourceColorRect {{0,0},{8,8}} sourceSize {8,8} game_resume_normal.png frame {{643,672},{196,196}} offset {0,0} rotated sourceColorRect {{1,1},{196,196}} sourceSize {198,198} game_resume_press.png frame {{522,373},{196,196}} offset {0,0} rotated sourceColorRect {{1,1},{196,196}} sourceSize {198,198} game_seat_empty.png frame {{812,870},{144,144}} offset {0,0} rotated sourceColorRect {{0,0},{144,144}} sourceSize {144,144} game_seat_valid.png frame {{666,870},{144,144}} offset {0,0} rotated sourceColorRect {{0,0},{144,144}} sourceSize {144,144} game_showCard_tip.png frame {{2002,58},{54,40}} offset {0,0} rotated sourceColorRect {{0,0},{54,40}} sourceSize {54,40} game_sliderChip_frame.png frame {{760,1016},{174,90}} offset {0,0} rotated sourceColorRect {{0,0},{174,90}} sourceSize {174,90} game_sliderThumb_icon.png frame {{1673,298},{55,55}} offset {0,0} rotated sourceColorRect {{1,1},{55,55}} sourceSize {57,57} game_sliderThumb_tip.png frame {{624,571},{99,106}} offset {0,0} rotated sourceColorRect {{0,0},{99,106}} sourceSize {99,106} game_sliderTrack_normal.png frame {{294,846},{73,20}} offset {0,0} rotated sourceColorRect {{1,0},{73,20}} sourceSize {75,20} game_slider_mask.png frame {{2,2},{190,1014}} offset {0,0} rotated sourceColorRect {{0,0},{190,1014}} sourceSize {190,1014} game_slider_thumb.png frame {{860,357},{174,90}} offset {0,0} rotated sourceColorRect {{0,0},{174,90}} sourceSize {174,90} game_slider_track.png frame {{194,2},{6,726}} offset {0,0} rotated sourceColorRect {{0,0},{6,726}} sourceSize {6,726} game_smallBlind_tip.png frame {{1610,296},{58,61}} offset {-2,6} rotated sourceColorRect {{8,4},{58,61}} sourceSize {78,81} game_standUp_tip.png frame {{294,792},{32,24}} offset {0,0} rotated sourceColorRect {{1,5},{32,24}} sourceSize {34,34} game_store_chips_icon.png frame {{1730,303},{49,49}} offset {0,0} rotated sourceColorRect {{1,1},{49,49}} sourceSize {51,51} game_store_diamond_icon.png frame {{2002,2},{54,42}} offset {0,0} rotated sourceColorRect {{0,0},{54,42}} sourceSize {54,42} game_store_gold_icon.png frame {{1945,289},{48,48}} offset {0,0} rotated sourceColorRect {{0,0},{48,48}} sourceSize {48,48} game_switchRect_normal.png frame {{1833,217},{54,54}} offset {0,0} rotated sourceColorRect {{0,0},{54,54}} sourceSize {54,54} game_switchRect_press.png frame {{1833,161},{54,54}} offset {0,0} rotated sourceColorRect {{0,0},{54,54}} sourceSize {54,54} game_switch_off.png frame {{1717,2},{96,64}} offset {-3,0} rotated sourceColorRect {{0,0},{96,64}} sourceSize {102,64} game_switch_on.png frame {{1617,2},{98,64}} offset {2,0} rotated sourceColorRect {{4,0},{98,64}} sourceSize {102,64} game_tab_normal.png frame {{1978,171},{66,55}} offset {0,0} rotated sourceColorRect {{0,0},{66,55}} sourceSize {66,55} game_tab_press.png frame {{1978,114},{66,55}} offset {0,0} rotated sourceColorRect {{0,0},{66,55}} sourceSize {66,55} game_table_start_normal.png frame {{1199,145},{130,130}} offset {0,0} rotated sourceColorRect {{0,0},{130,130}} sourceSize {130,130} game_table_start_pause.png frame {{1132,494},{130,130}} offset {0,0} rotated sourceColorRect {{0,0},{130,130}} sourceSize {130,130} ic_device_energy.png frame {{294,729},{61,24}} offset {-4,1} rotated sourceColorRect {{3,2},{61,24}} sourceSize {75,30} ic_device_energy_mask.png frame {{430,977},{73,30}} offset {-1,0} rotated sourceColorRect {{0,0},{73,30}} sourceSize {75,30} open_audio.png frame {{536,887},{128,128}} offset {0,0} rotated sourceColorRect {{0,0},{128,128}} sourceSize {128,128} metadata format 2 realTextureFileName GameMain_6p.png size {2048,2048} smartupdate $TexturePacker:SmartUpdate:33c271ffe64f3100c9c9165a96400da3:1/1$ textureFileName GameMain_6p.png ================================================ FILE: bin/client/assets/resources/GameMain_6p.plist.meta ================================================ { "ver": "1.2.4", "uuid": "aae22d42-a9cf-43f5-8c35-5348d3f98f75", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "size": { "width": 2048, "height": 2048 }, "type": "Texture Packer", "subMetas": { "close_audio.png": { "ver": "1.0.3", "uuid": "5a6d9eac-2049-40cf-8f6b-4aed0edf810e", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1331, "trimY": 132, "width": 128, "height": 128, "rawWidth": 128, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "forward_normal.png": { "ver": "1.0.3", "uuid": "918886d9-7513-4688-88c8-5dc9b0f3d6bc", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1219, "trimY": 2, "width": 128, "height": 128, "rawWidth": 128, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "forward_unnormal.png": { "ver": "1.0.3", "uuid": "6f2efdbb-ef50-4a3e-bbeb-d2c71bb48420", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1216, "trimY": 356, "width": 128, "height": 128, "rawWidth": 128, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_addFriend_disable.png": { "ver": "1.0.3", "uuid": "06fa1d03-1dad-4ed0-98b7-c4d5d24241e0", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1517, "trimY": 2, "width": 98, "height": 98, "rawWidth": 100, "rawHeight": 100, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_addFriend_normal.png": { "ver": "1.0.3", "uuid": "6eb025b5-2a6b-4c08-8d01-605e9eedd25e", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1417, "trimY": 2, "width": 98, "height": 98, "rawWidth": 100, "rawHeight": 100, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_addFriend_press.png": { "ver": "1.0.3", "uuid": "547f41ec-dbf0-48d6-9cee-f7dc1fc610f3", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1032, "trimY": 513, "width": 98, "height": 98, "rawWidth": 100, "rawHeight": 100, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_allIn_normal.png": { "ver": "1.0.3", "uuid": "f16f71f5-4198-4a9f-829c-0e94fc9ca51d", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 19, "trimX": 848, "trimY": 198, "width": 156, "height": 157, "rawWidth": 156, "rawHeight": 195, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_allIn_press.png": { "ver": "1.0.3", "uuid": "7be574fd-64fb-492c-848c-15d442fbb7a2", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 19, "trimX": 690, "trimY": 199, "width": 156, "height": 157, "rawWidth": 156, "rawHeight": 195, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_allIn_tip.png": { "ver": "1.0.3", "uuid": "13276540-7890-400f-8ca7-5a7b1b5a6975", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 1349, "trimY": 2, "width": 126, "height": 66, "rawWidth": 126, "rawHeight": 66, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_arrow_tip.png": { "ver": "1.0.3", "uuid": "71587064-bf47-4803-983a-1d9b215d0383", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 294, "trimY": 826, "width": 18, "height": 24, "rawWidth": 18, "rawHeight": 24, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_audioPlaying_tip.png": { "ver": "1.0.3", "uuid": "f079d6dd-1b4f-4f6c-a84f-493ae0f0dc84", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 202, "trimY": 687, "width": 120, "height": 40, "rawWidth": 120, "rawHeight": 40, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_audioProgress.png": { "ver": "1.0.3", "uuid": "fb98a33f-373f-4a61-be0d-61f33899c886", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 240, "trimY": 373, "width": 312, "height": 36, "rawWidth": 312, "rawHeight": 36, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_audioProgress_frame.png": { "ver": "1.0.3", "uuid": "00d38cb1-7cce-42c3-ab58-cc7cfc371425", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 202, "trimY": 373, "width": 312, "height": 36, "rawWidth": 312, "rawHeight": 36, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_bigBlind_tip.png": { "ver": "1.0.3", "uuid": "283bcf52-e007-4892-83d8-03789e33756f", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": -2, "offsetY": 6, "trimX": 1538, "trimY": 297, "width": 58, "height": 61, "rawWidth": 78, "rawHeight": 81, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_cardHighlight_frame.png": { "ver": "1.0.3", "uuid": "f6344e10-a3e4-41dd-ac61-5cce915849de", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": -2, "offsetY": 8, "trimX": 893, "trimY": 2, "width": 134, "height": 184, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_cardType_tip.png": { "ver": "1.0.3", "uuid": "9222fa1e-ab4f-4202-b245-e4a16f53dc10", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 396, "trimY": 977, "width": 32, "height": 32, "rawWidth": 34, "rawHeight": 34, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_card_mask.png": { "ver": "1.0.3", "uuid": "2d18d9bc-f051-4e7d-9d24-efde56b8041a", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 3, "trimX": 720, "trimY": 358, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_card_reverse.png": { "ver": "1.0.3", "uuid": "b0711d0f-2165-46f4-8765-2c039b5c22df", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 3, "trimX": 753, "trimY": 2, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_cartType_bg.png": { "ver": "1.0.3", "uuid": "88364851-5792-4ad7-b3f9-104fa4f9053e", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 1029, "trimY": 2, "width": 150, "height": 45, "rawWidth": 150, "rawHeight": 45, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_chat_bg.png": { "ver": "1.0.3", "uuid": "14d267be-fab9-4b57-8e94-1f7b9d4bd7ab", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 2, "trimY": 1018, "width": 756, "height": 921, "rawWidth": 756, "rawHeight": 921, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_chat_button_normal.png": { "ver": "1.0.3", "uuid": "5a2671f0-8d3c-4f36-aaa5-86bc8484fc0a", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 651, "trimY": 1941, "width": 210, "height": 105, "rawWidth": 210, "rawHeight": 105, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_chat_button_press.png": { "ver": "1.0.3", "uuid": "6fe48cd7-ea25-4083-9611-a6dae9eb3853", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 439, "trimY": 1941, "width": 210, "height": 105, "rawWidth": 210, "rawHeight": 105, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_chat_emotion_noraml.png": { "ver": "1.0.3", "uuid": "0bbcd985-ffb1-4381-950a-c1436b045949", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 568, "trimY": 2, "width": 369, "height": 120, "rawWidth": 369, "rawHeight": 120, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_chat_emotion_press.png": { "ver": "1.0.3", "uuid": "7e1c3e98-9e45-45f3-9774-f1cd71531f26", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 446, "trimY": 2, "width": 369, "height": 120, "rawWidth": 369, "rawHeight": 120, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_chat_icon_normal.png": { "ver": "1.0.3", "uuid": "1a94cf27-128a-4e4e-8f9c-46f77ec8fc10", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1889, "trimY": 159, "width": 87, "height": 81, "rawWidth": 87, "rawHeight": 81, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_chat_icon_press.png": { "ver": "1.0.3", "uuid": "30775f52-ba79-4b08-8c38-f82d441d5f9d", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1889, "trimY": 76, "width": 87, "height": 81, "rawWidth": 87, "rawHeight": 81, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_chat_text_normal.png": { "ver": "1.0.3", "uuid": "f11495e9-1d7c-4406-a4b7-dba4245e698f", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 324, "trimY": 2, "width": 369, "height": 120, "rawWidth": 369, "rawHeight": 120, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_chat_text_press.png": { "ver": "1.0.3", "uuid": "21e416a1-052c-4a0b-b888-ce37a53db25b", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 202, "trimY": 2, "width": 369, "height": 120, "rawWidth": 369, "rawHeight": 120, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_checkBox_normal.png": { "ver": "1.0.3", "uuid": "c03ccda2-e561-42c9-8b3a-05393df80825", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1372, "trimY": 339, "width": 57, "height": 57, "rawWidth": 57, "rawHeight": 57, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_checkBox_press.png": { "ver": "1.0.3", "uuid": "cf6adc50-f489-40c9-98a8-666d74b286d3", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1449, "trimY": 316, "width": 57, "height": 57, "rawWidth": 57, "rawHeight": 57, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_chip_tip.png": { "ver": "1.0.3", "uuid": "bc5a9397-64cb-4152-92af-32ba9b4b71ee", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": -1, "offsetY": 5, "trimX": 1610, "trimY": 234, "width": 60, "height": 63, "rawWidth": 78, "rawHeight": 81, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_close_normal.png": { "ver": "1.0.3", "uuid": "c7ac034b-afed-4b4c-a9c6-23a1894fcff6", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1799, "trimY": 71, "width": 88, "height": 88, "rawWidth": 88, "rawHeight": 88, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_close_press.png": { "ver": "1.0.3", "uuid": "34f42c53-775a-4140-b359-0fe0fcd50e9d", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 446, "trimY": 887, "width": 88, "height": 88, "rawWidth": 88, "rawHeight": 88, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_dealer_tip.png": { "ver": "1.0.3", "uuid": "6f3f5919-3a90-418c-89d2-7c679b25c21c", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1781, "trimY": 303, "width": 49, "height": 49, "rawWidth": 51, "rawHeight": 51, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_decrease_disable.png": { "ver": "1.0.3", "uuid": "1131c21e-95cf-4252-aea4-0b2600b70aa7", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1762, "trimY": 232, "width": 69, "height": 69, "rawWidth": 69, "rawHeight": 69, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_decrease_normal.png": { "ver": "1.0.3", "uuid": "973521a3-02cb-4006-9ed4-3154a563def1", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1691, "trimY": 227, "width": 69, "height": 69, "rawWidth": 69, "rawHeight": 69, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_decrease_press.png": { "ver": "1.0.3", "uuid": "d481b983-1876-45b5-90c8-c46e12a8d83d", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1762, "trimY": 161, "width": 69, "height": 69, "rawWidth": 69, "rawHeight": 69, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_delay_disable.png": { "ver": "1.0.3", "uuid": "0615d0dc-8c59-489e-8354-1e3c0af03c2c", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": -22, "trimX": 1613, "trimY": 156, "width": 76, "height": 76, "rawWidth": 120, "rawHeight": 120, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_delay_normal.png": { "ver": "1.0.3", "uuid": "8245fc9c-f676-4df6-b475-0506a122699f", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": -22, "trimX": 1461, "trimY": 161, "width": 76, "height": 76, "rawWidth": 120, "rawHeight": 120, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_delay_press.png": { "ver": "1.0.3", "uuid": "99dc418a-dcf0-414e-abef-4c780f833593", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": -22, "trimX": 1294, "trimY": 277, "width": 76, "height": 76, "rawWidth": 120, "rawHeight": 120, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_dialogCancel_normal.png": { "ver": "1.0.3", "uuid": "249728b2-4a24-434d-a519-690cb6868af4", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 400, "trimY": 373, "width": 300, "height": 120, "rawWidth": 300, "rawHeight": 120, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_dialogOK_normal.png": { "ver": "1.0.3", "uuid": "2ebbea07-b637-4ada-a38b-32d269074e4a", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 324, "trimY": 675, "width": 300, "height": 120, "rawWidth": 300, "rawHeight": 120, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_dialogRetry_normal.png": { "ver": "1.0.3", "uuid": "76c490fa-8ea1-4185-a8dc-01e496ad82c0", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 278, "trimY": 373, "width": 300, "height": 120, "rawWidth": 300, "rawHeight": 120, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_dialog_frame.png": { "ver": "1.0.3", "uuid": "e8a8ec4e-6c81-4c2a-a324-a41dc7f2a266", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 522, "trimY": 571, "width": 100, "height": 100, "rawWidth": 100, "rawHeight": 100, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_editbox_bg.png": { "ver": "1.0.3", "uuid": "22d4037c-dbce-4c66-a5ea-d515eff4ec33", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 2, "trimY": 1941, "width": 435, "height": 105, "rawWidth": 435, "rawHeight": 105, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_emotion_normal.png": { "ver": "1.0.3", "uuid": "6ea645c5-9508-4cdd-81c9-83f9b01f997c", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1372, "trimY": 262, "width": 75, "height": 75, "rawWidth": 75, "rawHeight": 75, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_emotion_press.png": { "ver": "1.0.3", "uuid": "6c2343a8-000b-4874-9980-3c648c03a962", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1461, "trimY": 239, "width": 75, "height": 75, "rawWidth": 75, "rawHeight": 75, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_endhand.png": { "ver": "1.0.3", "uuid": "54f2fb6c-5068-4940-a76f-9687546eba8a", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 1006, "trimY": 188, "width": 150, "height": 45, "rawWidth": 150, "rawHeight": 45, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_female_tip.png": { "ver": "1.0.3", "uuid": "6ebafffd-11eb-4240-af02-b65ea110ac3a", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1833, "trimY": 273, "width": 54, "height": 54, "rawWidth": 56, "rawHeight": 56, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_handCard_cover_tip.png": { "ver": "1.0.3", "uuid": "698b0be6-5b7c-4a87-9410-d28619128f96", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": -1, "trimX": 1207, "trimY": 277, "width": 85, "height": 77, "rawWidth": 85, "rawHeight": 79, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_handChips_tip.png": { "ver": "1.0.3", "uuid": "183885c2-3206-4280-99cb-17033ea59e72", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": -2, "offsetY": -1, "trimX": 952, "trimY": 357, "width": 140, "height": 154, "rawWidth": 272, "rawHeight": 272, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_header_frame.png": { "ver": "1.0.3", "uuid": "2a2afb82-8e79-446d-9991-ece530ae026f", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1053, "trimY": 154, "width": 144, "height": 144, "rawWidth": 144, "rawHeight": 144, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_inPot_extra_frame.png": { "ver": "1.0.3", "uuid": "652fe52f-be3b-490e-bf4e-a8f2f10e3be9", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": -88, "offsetY": 3, "trimX": 1910, "trimY": 2, "width": 72, "height": 90, "rawWidth": 268, "rawHeight": 98, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_inPot_frame.png": { "ver": "1.0.3", "uuid": "dc4ba3f6-7f90-47a7-a28d-ee2dc5d0a289", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 194, "trimY": 730, "width": 268, "height": 98, "rawWidth": 268, "rawHeight": 98, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_increase_disable.png": { "ver": "1.0.3", "uuid": "6f139db2-5df9-4aa6-9ea7-0e1aa9344e7b", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1691, "trimY": 156, "width": 69, "height": 69, "rawWidth": 69, "rawHeight": 69, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_increase_normal.png": { "ver": "1.0.3", "uuid": "e98567f9-65ea-4ebe-9465-657dd9bcb043", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1539, "trimY": 226, "width": 69, "height": 69, "rawWidth": 69, "rawHeight": 69, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_increase_press.png": { "ver": "1.0.3", "uuid": "7eadc868-ed59-4d33-999b-dee048659d53", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1542, "trimY": 155, "width": 69, "height": 69, "rawWidth": 69, "rawHeight": 69, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_male_tip.png": { "ver": "1.0.3", "uuid": "fefe8553-fcd8-4e0f-bcb3-03c8d578afbd", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1889, "trimY": 242, "width": 54, "height": 54, "rawWidth": 56, "rawHeight": 56, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_microPhone_normal.png": { "ver": "1.0.3", "uuid": "d0b919d9-45cb-48b0-97bf-16a4787f0ee5", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": -1, "offsetY": -36, "trimX": 933, "trimY": 633, "width": 77, "height": 138, "rawWidth": 195, "rawHeight": 210, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_microPhone_press.png": { "ver": "1.0.3", "uuid": "d1a8b5d7-bfe1-44ee-a27b-d048691b5ff9", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 446, "trimY": 675, "width": 195, "height": 210, "rawWidth": 195, "rawHeight": 210, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_money_tip.png": { "ver": "1.0.3", "uuid": "1f50c13d-5579-4262-a6fb-9344f23af9c2", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1995, "trimY": 289, "width": 48, "height": 48, "rawWidth": 48, "rawHeight": 48, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_note_normal.png": { "ver": "1.0.3", "uuid": "fc7b5f4a-203f-43f3-baae-b6ef3d051bbc", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 1094, "trimY": 357, "width": 135, "height": 120, "rawWidth": 135, "rawHeight": 120, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_note_press.png": { "ver": "1.0.3", "uuid": "e410d477-1a87-41e5-8975-c021ec14003d", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 1012, "trimY": 633, "width": 135, "height": 120, "rawWidth": 135, "rawHeight": 120, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_owner_tip.png": { "ver": "1.0.3", "uuid": "37403df3-8929-4da4-8dd0-2495c44e2556", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 362, "trimY": 977, "width": 32, "height": 32, "rawWidth": 34, "rawHeight": 34, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_playerAudioSwitch_disable.png": { "ver": "1.0.3", "uuid": "9c8be3a6-f43e-4434-b568-137928be2df0", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 932, "trimY": 533, "width": 98, "height": 98, "rawWidth": 100, "rawHeight": 100, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_playerAudioSwitch_normal.png": { "ver": "1.0.3", "uuid": "959dfdbb-ae5a-41e5-a9cd-65d7819b0725", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 832, "trimY": 554, "width": 98, "height": 98, "rawWidth": 100, "rawHeight": 100, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_playerAudioSwitch_press.png": { "ver": "1.0.3", "uuid": "cefa671e-c8e0-454d-80e1-50828abc6630", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 732, "trimY": 554, "width": 98, "height": 98, "rawWidth": 100, "rawHeight": 100, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_popProgressClose_normal.png": { "ver": "1.0.3", "uuid": "c2d04227-02ab-4893-8a57-ab4312ace2ff", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 933, "trimY": 773, "width": 94, "height": 94, "rawWidth": 94, "rawHeight": 94, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_preRecord_normal.png": { "ver": "1.0.3", "uuid": "9048139c-dfdd-4f72-bb79-4d0dc9204e5e", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 1708, "trimY": 68, "width": 86, "height": 89, "rawWidth": 86, "rawHeight": 89, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_preRecord_press.png": { "ver": "1.0.3", "uuid": "dc7ebbfe-df79-4f95-9afa-658aee791add", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 1617, "trimY": 68, "width": 86, "height": 89, "rawWidth": 86, "rawHeight": 89, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_progress_frame.png": { "ver": "1.0.3", "uuid": "2b265350-b7b8-417d-a0db-d029bca9a934", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1076, "trimY": 2, "width": 141, "height": 141, "rawWidth": 141, "rawHeight": 141, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_progress_normal.png": { "ver": "1.0.3", "uuid": "f010326a-0696-46ba-a65a-e594b1b3d15e", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 732, "trimY": 2, "width": 195, "height": 19, "rawWidth": 195, "rawHeight": 19, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_progress_range.png": { "ver": "1.0.3", "uuid": "6e0679bf-4e65-49a3-980f-7045f76ed82f", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 711, "trimY": 2, "width": 195, "height": 19, "rawWidth": 195, "rawHeight": 19, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_progress_yellow.png": { "ver": "1.0.3", "uuid": "11c0bc5f-7864-44d7-b452-392ef8384c29", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 690, "trimY": 2, "width": 195, "height": 19, "rawWidth": 195, "rawHeight": 19, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_property_01.png": { "ver": "1.0.3", "uuid": "a5a2f46c-ce35-4c74-9a1f-3e8671244c50", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 3, "offsetY": 0, "trimX": 1542, "trimY": 102, "width": 51, "height": 73, "rawWidth": 101, "rawHeight": 101, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_property_02.png": { "ver": "1.0.3", "uuid": "14ea34a2-a2e8-4944-a4ef-e1114ad6a696", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 2, "offsetY": 1, "trimX": 1978, "trimY": 228, "width": 59, "height": 65, "rawWidth": 101, "rawHeight": 101, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_property_03.png": { "ver": "1.0.3", "uuid": "0117f7b2-c358-4e07-b70d-8e5ca6d077e6", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 4, "offsetY": -3, "trimX": 1130, "trimY": 300, "width": 75, "height": 55, "rawWidth": 101, "rawHeight": 101, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_property_03_disable.png": { "ver": "1.0.3", "uuid": "a69d6003-8bf3-4975-9a5a-e9f91f07f3c5", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 4, "offsetY": -3, "trimX": 1053, "trimY": 300, "width": 75, "height": 55, "rawWidth": 101, "rawHeight": 101, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_property_04.png": { "ver": "1.0.3", "uuid": "8796db4e-e6f3-45a4-bd68-905fd7f75774", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 3, "offsetY": 3, "trimX": 1815, "trimY": 2, "width": 67, "height": 93, "rawWidth": 101, "rawHeight": 101, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_property_05.png": { "ver": "1.0.3", "uuid": "646cd28c-29ea-4fda-9524-558664afd764", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 3, "offsetY": 1, "trimX": 1461, "trimY": 102, "width": 57, "height": 79, "rawWidth": 101, "rawHeight": 101, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_quit_tip.png": { "ver": "1.0.3", "uuid": "4090107f-680a-4a63-a8cf-dfe6efe40cd8", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 328, "trimY": 977, "width": 32, "height": 32, "rawWidth": 34, "rawHeight": 34, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_raise_allin.png": { "ver": "1.0.3", "uuid": "c0674d04-0da4-4771-ae5d-f6ab5ce1b424", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 841, "trimY": 654, "width": 174, "height": 90, "rawWidth": 174, "rawHeight": 90, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_rebuy_tip.png": { "ver": "1.0.3", "uuid": "f66d9267-0912-4c25-97cf-9638f7413f9e", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 294, "trimY": 977, "width": 32, "height": 32, "rawWidth": 34, "rawHeight": 34, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_red_tip.png": { "ver": "1.0.3", "uuid": "ee123787-dc9e-40c1-8c8d-0ae950ded83d", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 194, "trimY": 1000, "width": 8, "height": 8, "rawWidth": 8, "rawHeight": 8, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_resume_normal.png": { "ver": "1.0.3", "uuid": "202b0bea-bf32-460d-926a-1b1789ba5470", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 643, "trimY": 672, "width": 196, "height": 196, "rawWidth": 198, "rawHeight": 198, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_resume_press.png": { "ver": "1.0.3", "uuid": "28835667-1a62-4c4e-8848-1ea884858444", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 522, "trimY": 373, "width": 196, "height": 196, "rawWidth": 198, "rawHeight": 198, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_seat_empty.png": { "ver": "1.0.3", "uuid": "d79f84c5-d5e1-4aad-b902-431289fb7b91", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 812, "trimY": 870, "width": 144, "height": 144, "rawWidth": 144, "rawHeight": 144, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_seat_valid.png": { "ver": "1.0.3", "uuid": "33ad800b-2555-495c-8f08-dc28d28c8556", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 666, "trimY": 870, "width": 144, "height": 144, "rawWidth": 144, "rawHeight": 144, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_showCard_tip.png": { "ver": "1.0.3", "uuid": "97acef63-cca8-4ccd-b4d3-86c0116e0a8c", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 2002, "trimY": 58, "width": 54, "height": 40, "rawWidth": 54, "rawHeight": 40, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_sliderChip_frame.png": { "ver": "1.0.3", "uuid": "5c7a6c0c-b522-405f-a8c7-f37e796a4cd9", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 760, "trimY": 1016, "width": 174, "height": 90, "rawWidth": 174, "rawHeight": 90, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_sliderThumb_icon.png": { "ver": "1.0.3", "uuid": "a7228bc8-15e3-4b48-9728-9e20f0b09add", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1673, "trimY": 298, "width": 55, "height": 55, "rawWidth": 57, "rawHeight": 57, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_sliderThumb_tip.png": { "ver": "1.0.3", "uuid": "d259e938-c0fe-4757-aa32-06f8dfca2246", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 624, "trimY": 571, "width": 99, "height": 106, "rawWidth": 99, "rawHeight": 106, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_sliderTrack_normal.png": { "ver": "1.0.3", "uuid": "789d2a9c-9b96-4ef6-a9e3-dcfdb6884cc2", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 294, "trimY": 846, "width": 73, "height": 20, "rawWidth": 75, "rawHeight": 20, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_slider_mask.png": { "ver": "1.0.3", "uuid": "12a2d043-d9f2-42dd-9952-e4ee561316bb", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 2, "trimY": 2, "width": 190, "height": 1014, "rawWidth": 190, "rawHeight": 1014, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_slider_thumb.png": { "ver": "1.0.3", "uuid": "553eba4b-d913-477c-96b4-32ccb14241e3", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 860, "trimY": 357, "width": 174, "height": 90, "rawWidth": 174, "rawHeight": 90, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_slider_track.png": { "ver": "1.0.3", "uuid": "b7bce690-1405-4d5f-bc17-5d1892f822ba", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 194, "trimY": 2, "width": 6, "height": 726, "rawWidth": 6, "rawHeight": 726, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_smallBlind_tip.png": { "ver": "1.0.3", "uuid": "a2137fb8-a257-4bc4-ace1-93a9ad42b937", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": -2, "offsetY": 6, "trimX": 1610, "trimY": 296, "width": 58, "height": 61, "rawWidth": 78, "rawHeight": 81, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_standUp_tip.png": { "ver": "1.0.3", "uuid": "84625048-3af3-4f05-b099-981a1f5499e3", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 294, "trimY": 792, "width": 32, "height": 24, "rawWidth": 34, "rawHeight": 34, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_store_chips_icon.png": { "ver": "1.0.3", "uuid": "1e3171c6-07cb-47f7-8922-1b7c481c0083", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1730, "trimY": 303, "width": 49, "height": 49, "rawWidth": 51, "rawHeight": 51, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_store_diamond_icon.png": { "ver": "1.0.3", "uuid": "812e8587-6dec-4d6e-8236-5f3ea0f34844", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 0, "trimX": 2002, "trimY": 2, "width": 54, "height": 42, "rawWidth": 54, "rawHeight": 42, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_store_gold_icon.png": { "ver": "1.0.3", "uuid": "5e76cd28-d620-4c08-a314-edd662be61e1", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1945, "trimY": 289, "width": 48, "height": 48, "rawWidth": 48, "rawHeight": 48, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_switchRect_normal.png": { "ver": "1.0.3", "uuid": "99b03be5-a2a7-403d-b1e1-7244500910b3", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1833, "trimY": 217, "width": 54, "height": 54, "rawWidth": 54, "rawHeight": 54, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_switchRect_press.png": { "ver": "1.0.3", "uuid": "9165111e-4866-48ff-9bb4-2c02e8c8abcd", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1833, "trimY": 161, "width": 54, "height": 54, "rawWidth": 54, "rawHeight": 54, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_switch_off.png": { "ver": "1.0.3", "uuid": "87a15f39-7074-4454-9c14-bf525bc2f77b", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": -3, "offsetY": 0, "trimX": 1717, "trimY": 2, "width": 96, "height": 64, "rawWidth": 102, "rawHeight": 64, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_switch_on.png": { "ver": "1.0.3", "uuid": "e1835cbc-b99b-4c8f-ba65-3063b30ee96c", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 2, "offsetY": 0, "trimX": 1617, "trimY": 2, "width": 98, "height": 64, "rawWidth": 102, "rawHeight": 64, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_tab_normal.png": { "ver": "1.0.3", "uuid": "71f41efc-d2ba-4cba-90fe-1c64b663e0b0", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1978, "trimY": 171, "width": 66, "height": 55, "rawWidth": 66, "rawHeight": 55, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_tab_press.png": { "ver": "1.0.3", "uuid": "1b8b2a8e-bff4-4557-ae68-fc077493afc8", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1978, "trimY": 114, "width": 66, "height": 55, "rawWidth": 66, "rawHeight": 55, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_table_start_normal.png": { "ver": "1.0.3", "uuid": "1eaed224-281e-4973-af0f-02f2016578a1", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1199, "trimY": 145, "width": 130, "height": 130, "rawWidth": 130, "rawHeight": 130, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "game_table_start_pause.png": { "ver": "1.0.3", "uuid": "b3fda84e-ccf0-427b-a482-6cffb33001f7", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 1132, "trimY": 494, "width": 130, "height": 130, "rawWidth": 130, "rawHeight": 130, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "ic_device_energy.png": { "ver": "1.0.3", "uuid": "78824c80-c288-435d-907a-41cb5ac5b5e5", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": -4, "offsetY": 1, "trimX": 294, "trimY": 729, "width": 61, "height": 24, "rawWidth": 75, "rawHeight": 30, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "ic_device_energy_mask.png": { "ver": "1.0.3", "uuid": "6602686c-37ec-486c-a3b1-1bc814ac470c", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": -1, "offsetY": 0, "trimX": 430, "trimY": 977, "width": 73, "height": 30, "rawWidth": 75, "rawHeight": 30, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "open_audio.png": { "ver": "1.0.3", "uuid": "78f76275-b201-4017-8f0f-70664c14a542", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 536, "trimY": 887, "width": 128, "height": 128, "rawWidth": 128, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} } } } ================================================ FILE: bin/client/assets/resources/GameMain_6p.png.meta ================================================ { "ver": "1.0.0", "uuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "type": "sprite", "wrapMode": "clamp", "filterMode": "bilinear", "subMetas": { "GameMain_6p": { "ver": "1.0.3", "uuid": "2bd24592-8fab-4bf3-bb32-5774b2b60782", "rawTextureUuid": "9645f4c7-099e-4bac-9779-ac372a798d1b", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": -1, "offsetY": 0, "trimX": 2, "trimY": 2, "width": 2042, "height": 2044, "rawWidth": 2048, "rawHeight": 2048, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "subMetas": {} } } } ================================================ FILE: bin/client/assets/resources/audio/audio_allinWin.wav.meta ================================================ { "ver": "1.0.0", "uuid": "0dd8cf6f-e146-4622-8b8e-7c9dc5f77a48", "subMetas": {} } ================================================ FILE: bin/client/assets/resources/audio/audio_check.wav.meta ================================================ { "ver": "1.0.0", "uuid": "ae2e6fb2-2be9-4ced-a4e9-2ee56c9667ed", "subMetas": {} } ================================================ FILE: bin/client/assets/resources/audio/audio_chipsToPot.wav.meta ================================================ { "ver": "1.0.0", "uuid": "97c76f08-6b20-4757-aefb-5a95e710cb13", "subMetas": {} } ================================================ FILE: bin/client/assets/resources/audio/audio_chipsToTable.wav.meta ================================================ { "ver": "1.0.0", "uuid": "2773b2b7-4482-4133-9900-7fdcd308d2f9", "subMetas": {} } ================================================ FILE: bin/client/assets/resources/audio/audio_distributeCard.wav.meta ================================================ { "ver": "1.0.0", "uuid": "0b5c008e-cf15-4b8c-be63-8b1197cb1789", "subMetas": {} } ================================================ FILE: bin/client/assets/resources/audio/audio_fold.wav.meta ================================================ { "ver": "1.0.0", "uuid": "87dcf996-d47c-4b0e-a821-a1d034aad12b", "subMetas": {} } ================================================ FILE: bin/client/assets/resources/audio/audio_normalWin.wav.meta ================================================ { "ver": "1.0.0", "uuid": "e32b382b-4248-4a95-9c83-6e170adb4aa4", "subMetas": {} } ================================================ FILE: bin/client/assets/resources/audio/audio_pokerClick.caf.meta ================================================ { "ver": "1.0.0", "uuid": "2f80411a-9257-4450-aa30-4e860f2ff54b", "subMetas": {} } ================================================ FILE: bin/client/assets/resources/audio/audio_pokerClick.mp3.meta ================================================ { "ver": "1.0.0", "uuid": "b3e3bc15-0e5e-4d16-932c-08651a89045d", "subMetas": {} } ================================================ FILE: bin/client/assets/resources/audio/audio_timeout.wav.meta ================================================ { "ver": "1.0.0", "uuid": "3ef5c879-e7cd-4121-be05-a98fa397e548", "subMetas": {} } ================================================ FILE: bin/client/assets/resources/audio/audio_yourTurn.wav.meta ================================================ { "ver": "1.0.0", "uuid": "85960017-45b4-40f2-a17e-75cdfda31054", "subMetas": {} } ================================================ FILE: bin/client/assets/resources/audio.meta ================================================ { "ver": "1.0.1", "uuid": "0a834482-9f57-4f53-af0e-98a99ad7438a", "isGroup": false, "subMetas": {} } ================================================ FILE: bin/client/assets/resources/game_cards.plist ================================================ frames card_01.png frame {{488,362},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_02.png frame {{362,362},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_03.png frame {{272,812},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_04.png frame {{272,686},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_05.png frame {{272,560},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_06.png frame {{272,434},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_07.png frame {{902,308},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_08.png frame {{776,272},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_09.png frame {{650,272},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_10.png frame {{524,272},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_11.png frame {{398,272},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_12.png frame {{272,272},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_13.png frame {{902,182},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_17.png frame {{776,182},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_18.png frame {{650,182},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_19.png frame {{524,182},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_20.png frame {{398,182},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_21.png frame {{272,182},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_22.png frame {{182,812},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_23.png frame {{182,686},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_24.png frame {{182,560},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_25.png frame {{182,434},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_26.png frame {{182,308},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_27.png frame {{182,182},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_28.png frame {{812,92},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_29.png frame {{686,92},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_33.png frame {{560,92},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_34.png frame {{434,92},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_35.png frame {{308,92},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_36.png frame {{182,92},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_37.png frame {{92,848},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_38.png frame {{92,722},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_39.png frame {{92,596},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_40.png frame {{92,470},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_41.png frame {{92,344},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_42.png frame {{92,218},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_43.png frame {{92,92},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_44.png frame {{848,2},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_45.png frame {{722,2},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_49.png frame {{596,2},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_50.png frame {{470,2},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_51.png frame {{344,2},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_52.png frame {{218,2},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_53.png frame {{92,2},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_54.png frame {{2,884},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_55.png frame {{2,758},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_56.png frame {{2,632},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_57.png frame {{2,506},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_58.png frame {{2,380},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_59.png frame {{2,254},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_60.png frame {{2,128},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} card_61.png frame {{2,2},{88,124}} offset {0,2} rotated sourceColorRect {{0,0},{88,124}} sourceSize {88,128} metadata format 2 realTextureFileName game_cards.png size {1024,1024} smartupdate $TexturePacker:SmartUpdate:ca57ba6848db9930558064399bf24524:1/1$ textureFileName game_cards.png ================================================ FILE: bin/client/assets/resources/game_cards.plist.meta ================================================ { "ver": "1.2.4", "uuid": "24cba613-120c-4b54-8d58-0423cdcb5f42", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "size": { "width": 1024, "height": 1024 }, "type": "Texture Packer", "subMetas": { "card_01.png": { "ver": "1.0.3", "uuid": "710fd9e1-424c-4e26-b6f8-6bf5cddcc88f", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 488, "trimY": 362, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_02.png": { "ver": "1.0.3", "uuid": "60021324-38c4-4e2d-b476-bddf71440b6f", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 362, "trimY": 362, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_03.png": { "ver": "1.0.3", "uuid": "ca65478e-4be2-4b27-92bf-59f6d7ccc943", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 272, "trimY": 812, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_04.png": { "ver": "1.0.3", "uuid": "ad70143d-10ba-4433-af53-399b18937dac", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 272, "trimY": 686, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_05.png": { "ver": "1.0.3", "uuid": "5d0dccb1-3013-4513-885a-6d198ecd6251", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 272, "trimY": 560, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_06.png": { "ver": "1.0.3", "uuid": "56493729-68bc-44ce-83bf-edb99aa5b34c", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 272, "trimY": 434, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_07.png": { "ver": "1.0.3", "uuid": "1de8516b-2df4-4b99-a99f-cba2a689bc4b", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 902, "trimY": 308, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_08.png": { "ver": "1.0.3", "uuid": "19067e80-90a9-4011-901b-48b0ef454fea", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 776, "trimY": 272, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_09.png": { "ver": "1.0.3", "uuid": "5fa37595-0f18-4bf0-bb60-bfc195b829f1", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 650, "trimY": 272, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_10.png": { "ver": "1.0.3", "uuid": "5177086e-3b04-4e1a-b5ea-f45a0ae17d10", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 524, "trimY": 272, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_11.png": { "ver": "1.0.3", "uuid": "9f07ce45-6288-4e58-a6bd-f9698f91b578", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 398, "trimY": 272, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_12.png": { "ver": "1.0.3", "uuid": "a48065ab-695b-4002-9cfa-fc91ce203730", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 272, "trimY": 272, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_13.png": { "ver": "1.0.3", "uuid": "14a9ba6b-3c77-458d-8e17-52755be3f38d", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 902, "trimY": 182, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_17.png": { "ver": "1.0.3", "uuid": "6bf29666-2801-4cee-a868-bf5aeddba1a5", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 776, "trimY": 182, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_18.png": { "ver": "1.0.3", "uuid": "9803d74f-41e4-465f-8eef-b37e6b1ac678", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 650, "trimY": 182, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_19.png": { "ver": "1.0.3", "uuid": "fe62f56b-458d-47f9-9900-8970cf698f09", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 524, "trimY": 182, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_20.png": { "ver": "1.0.3", "uuid": "3dc76ec1-8260-41a6-b765-92924bb7b85a", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 398, "trimY": 182, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_21.png": { "ver": "1.0.3", "uuid": "75d40a23-bfb5-4c5b-8047-58877391c739", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 272, "trimY": 182, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_22.png": { "ver": "1.0.3", "uuid": "5e49eec7-5e0e-4c79-b062-a75bd567e23c", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 182, "trimY": 812, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_23.png": { "ver": "1.0.3", "uuid": "967eb70c-f36c-4d33-8745-9bc4bdb91175", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 182, "trimY": 686, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_24.png": { "ver": "1.0.3", "uuid": "b9008395-f202-4684-b72c-84d36c18fd66", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 182, "trimY": 560, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_25.png": { "ver": "1.0.3", "uuid": "2d646166-2154-40e0-84e0-dff694bed6ba", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 182, "trimY": 434, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_26.png": { "ver": "1.0.3", "uuid": "fb1f07c3-ff9e-4600-8262-737bd7f456f4", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 182, "trimY": 308, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_27.png": { "ver": "1.0.3", "uuid": "d23c78e7-03c8-4eae-8f28-0db8d19fed57", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 182, "trimY": 182, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_28.png": { "ver": "1.0.3", "uuid": "2e73f328-d817-4466-ad8a-9cb8c78d3114", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 812, "trimY": 92, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_29.png": { "ver": "1.0.3", "uuid": "7519f3d1-7a77-4210-a8fa-b762ac843541", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 686, "trimY": 92, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_33.png": { "ver": "1.0.3", "uuid": "b502c26b-5442-4837-8c49-f7a89c674bc4", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 560, "trimY": 92, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_34.png": { "ver": "1.0.3", "uuid": "cf13e52f-5553-458a-96e0-50fc091af3a2", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 434, "trimY": 92, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_35.png": { "ver": "1.0.3", "uuid": "cbb802f3-84b7-439f-81ad-dc9bd5788ca7", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 308, "trimY": 92, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_36.png": { "ver": "1.0.3", "uuid": "6461f6f1-206e-48a8-82a1-4e55d6e20188", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 182, "trimY": 92, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_37.png": { "ver": "1.0.3", "uuid": "9c1c98c8-104e-476a-97bf-052637cbf352", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 92, "trimY": 848, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_38.png": { "ver": "1.0.3", "uuid": "6e3d5190-a98f-461e-a824-be5f1289542a", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 92, "trimY": 722, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_39.png": { "ver": "1.0.3", "uuid": "7ec5d482-5ce6-4f02-8052-6c879143dba9", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 92, "trimY": 596, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_40.png": { "ver": "1.0.3", "uuid": "c825c6db-d5dc-408b-9548-68de826d4cb8", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 92, "trimY": 470, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_41.png": { "ver": "1.0.3", "uuid": "19e96350-ed5f-4e87-a52c-94b23ddc4605", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 92, "trimY": 344, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_42.png": { "ver": "1.0.3", "uuid": "cfd4425b-f703-4032-b457-4e5106396241", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 92, "trimY": 218, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_43.png": { "ver": "1.0.3", "uuid": "47ec5277-48cc-4ce8-9ff6-2e0023923792", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 92, "trimY": 92, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_44.png": { "ver": "1.0.3", "uuid": "28cd5893-be20-42e9-aedd-d681625b30a1", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 848, "trimY": 2, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_45.png": { "ver": "1.0.3", "uuid": "3ff81b67-3bc6-4e62-b5be-fa0dd489168c", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 722, "trimY": 2, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_49.png": { "ver": "1.0.3", "uuid": "b80de904-3b0a-4efc-896f-60d8a9223c07", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 596, "trimY": 2, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_50.png": { "ver": "1.0.3", "uuid": "896edd88-678f-4240-87c9-6f887b4d0331", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 470, "trimY": 2, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_51.png": { "ver": "1.0.3", "uuid": "1fb0a065-d936-43bf-9390-3b2f5e11e95a", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 344, "trimY": 2, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_52.png": { "ver": "1.0.3", "uuid": "a54562da-2f7c-441a-9529-6c0674893df7", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 218, "trimY": 2, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_53.png": { "ver": "1.0.3", "uuid": "bdfadbd6-b0d3-432a-949d-bfae11184783", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 2, "trimX": 92, "trimY": 2, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_54.png": { "ver": "1.0.3", "uuid": "1dc2818d-cd21-46cf-8fcd-1c16984a0dbd", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 2, "trimY": 884, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_55.png": { "ver": "1.0.3", "uuid": "70a818fd-dbb1-4cd8-847e-4dfa6aae16e3", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 2, "trimY": 758, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_56.png": { "ver": "1.0.3", "uuid": "2aeb81c3-c3e3-4cb4-bb18-0b0072014d82", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 2, "trimY": 632, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_57.png": { "ver": "1.0.3", "uuid": "63d5b6aa-b83d-4f16-8e26-ec6c34b59df6", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 2, "trimY": 506, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_58.png": { "ver": "1.0.3", "uuid": "e361aec7-044f-4706-9c5e-0258e755afa1", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 2, "trimY": 380, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_59.png": { "ver": "1.0.3", "uuid": "1efde8df-77e3-405b-af3c-63096abfa0b2", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 2, "trimY": 254, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_60.png": { "ver": "1.0.3", "uuid": "9e315073-086b-453e-812d-48d97211a2a6", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 2, "trimY": 128, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_61.png": { "ver": "1.0.3", "uuid": "0332df8f-a661-449a-941a-b0bd45cdb434", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 2, "trimX": 2, "trimY": 2, "width": 88, "height": 124, "rawWidth": 88, "rawHeight": 128, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} } } } ================================================ FILE: bin/client/assets/resources/game_cards.png.meta ================================================ { "ver": "1.0.0", "uuid": "24e07000-e189-4c09-8859-47cc25581533", "type": "sprite", "wrapMode": "clamp", "filterMode": "bilinear", "subMetas": { "game_cards": { "ver": "1.0.3", "uuid": "6d4aeaa5-b8e2-498e-9abc-f59b2acf5d75", "rawTextureUuid": "24e07000-e189-4c09-8859-47cc25581533", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": -16.5, "offsetY": 7.5, "trimX": 2, "trimY": 2, "width": 987, "height": 1005, "rawWidth": 1024, "rawHeight": 1024, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "subMetas": {} } } } ================================================ FILE: bin/client/assets/resources/game_cards_6p.plist ================================================ frames card_01.png frame {{590,1122},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_02.png frame {{394,1122},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_03.png frame {{198,1906},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_04.png frame {{142,1710},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_05.png frame {{142,1514},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_06.png frame {{142,1318},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_07.png frame {{142,1122},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_08.png frame {{2,1906},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_09.png frame {{2,1710},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_10.png frame {{2,1514},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_11.png frame {{2,1318},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_12.png frame {{2,1122},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_13.png frame {{786,982},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_17.png frame {{590,982},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_18.png frame {{394,982},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_19.png frame {{198,982},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_20.png frame {{2,982},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_21.png frame {{786,842},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_22.png frame {{590,842},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_23.png frame {{394,842},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_24.png frame {{198,842},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_25.png frame {{2,842},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_26.png frame {{786,702},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_27.png frame {{590,702},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_28.png frame {{394,702},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_29.png frame {{198,702},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_33.png frame {{2,702},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_34.png frame {{786,562},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_35.png frame {{590,562},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_36.png frame {{394,562},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_37.png frame {{198,562},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_38.png frame {{2,562},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_39.png frame {{786,422},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_40.png frame {{590,422},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_41.png frame {{394,422},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_42.png frame {{198,422},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_43.png frame {{2,422},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_44.png frame {{786,282},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_45.png frame {{590,282},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_49.png frame {{394,282},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_50.png frame {{198,282},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_51.png frame {{2,282},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_52.png frame {{786,142},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_53.png frame {{590,142},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_54.png frame {{394,142},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_55.png frame {{198,142},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_56.png frame {{2,142},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_57.png frame {{786,2},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_58.png frame {{590,2},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_59.png frame {{394,2},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_60.png frame {{198,2},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} card_61.png frame {{2,2},{138,194}} offset {0,3} rotated sourceColorRect {{0,0},{138,194}} sourceSize {138,200} metadata format 2 realTextureFileName game_cards_6p.png size {1024,2048} smartupdate $TexturePacker:SmartUpdate:78966e46f3c199dd5c77bd88fd0bd2d5:1/1$ textureFileName game_cards_6p.png ================================================ FILE: bin/client/assets/resources/game_cards_6p.plist.meta ================================================ { "ver": "1.2.4", "uuid": "2f6611b7-f699-4bc8-b740-5e5eb6600610", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "size": { "width": 1024, "height": 2048 }, "type": "Texture Packer", "subMetas": { "card_01.png": { "ver": "1.0.3", "uuid": "54e8dc54-b596-477c-a504-69542f80d305", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 590, "trimY": 1122, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_02.png": { "ver": "1.0.3", "uuid": "9187bd61-15fb-4d99-9a64-2b1f63946ce1", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 394, "trimY": 1122, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_03.png": { "ver": "1.0.3", "uuid": "ce2cdfd1-a75d-4739-acf7-583106f66ea7", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 198, "trimY": 1906, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_04.png": { "ver": "1.0.3", "uuid": "d701842c-c8ac-4d41-879b-a1a0c8265b86", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 3, "trimX": 142, "trimY": 1710, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_05.png": { "ver": "1.0.3", "uuid": "ac2e1783-1776-4e70-bf9d-dfde578fe2d0", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 3, "trimX": 142, "trimY": 1514, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_06.png": { "ver": "1.0.3", "uuid": "c78c71d2-f681-4882-98f3-4e7131a080ad", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 3, "trimX": 142, "trimY": 1318, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_07.png": { "ver": "1.0.3", "uuid": "c3e79061-7ee3-4c80-8ee1-804d59df0c34", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 3, "trimX": 142, "trimY": 1122, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_08.png": { "ver": "1.0.3", "uuid": "0447dc10-5d83-4940-9912-45afbb8fce89", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 1906, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_09.png": { "ver": "1.0.3", "uuid": "fa1e219c-daec-4000-8dc1-2a308d64cfbb", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 1710, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_10.png": { "ver": "1.0.3", "uuid": "9de98e7b-ba17-48ba-8ba1-34ad8c834f72", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 1514, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_11.png": { "ver": "1.0.3", "uuid": "2825cc16-297b-4baa-a21f-ccfe5548b7e2", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 1318, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_12.png": { "ver": "1.0.3", "uuid": "7ba9526c-45c5-4ceb-8d4f-317e4eedeebb", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 1122, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_13.png": { "ver": "1.0.3", "uuid": "03f80e2b-d85a-46c5-8615-584c266a65b0", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 786, "trimY": 982, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_17.png": { "ver": "1.0.3", "uuid": "a4f47186-c450-4cc5-8922-98ed2c3fc6ca", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 590, "trimY": 982, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_18.png": { "ver": "1.0.3", "uuid": "8214d788-91c8-4184-a431-b74fa2c7f41f", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 394, "trimY": 982, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_19.png": { "ver": "1.0.3", "uuid": "d381ee2b-de98-4c6d-bb16-38d26cb96805", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 198, "trimY": 982, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_20.png": { "ver": "1.0.3", "uuid": "7180543b-8b7f-4bef-8cb7-e53fef3da82c", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 982, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_21.png": { "ver": "1.0.3", "uuid": "84900ca8-de55-43cf-ba60-dff4a1b8df78", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 786, "trimY": 842, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_22.png": { "ver": "1.0.3", "uuid": "391bd8c6-8048-4363-8ec5-53e17d214138", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 590, "trimY": 842, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_23.png": { "ver": "1.0.3", "uuid": "f96c6fd8-ef92-4767-823c-9362885476cf", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 394, "trimY": 842, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_24.png": { "ver": "1.0.3", "uuid": "3e6c9875-47cb-455f-b0e1-96e47b047a3b", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 198, "trimY": 842, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_25.png": { "ver": "1.0.3", "uuid": "2f376a1c-2ef7-421e-a65c-8f5c2fcae6c1", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 842, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_26.png": { "ver": "1.0.3", "uuid": "a73192cc-cf13-4d97-bed9-509837813210", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 786, "trimY": 702, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_27.png": { "ver": "1.0.3", "uuid": "3814f894-9818-4288-841e-b1b91d4b05bb", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 590, "trimY": 702, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_28.png": { "ver": "1.0.3", "uuid": "e0349bdf-6d11-4d09-a164-ecb8f12bfcca", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 394, "trimY": 702, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_29.png": { "ver": "1.0.3", "uuid": "fad556ea-2052-4814-9010-59181a2cf99a", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 198, "trimY": 702, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_33.png": { "ver": "1.0.3", "uuid": "7355604b-898d-4e62-9bcd-6d637c79a69b", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 702, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_34.png": { "ver": "1.0.3", "uuid": "77163266-f626-405b-83cb-ca583444071c", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 786, "trimY": 562, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_35.png": { "ver": "1.0.3", "uuid": "f31ff1b6-be45-4007-a21d-ebc623ffa369", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 590, "trimY": 562, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_36.png": { "ver": "1.0.3", "uuid": "12e7acef-a761-477b-9195-56a24c8e2ed2", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 394, "trimY": 562, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_37.png": { "ver": "1.0.3", "uuid": "668bb150-6d54-45c9-8683-031335be773a", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 198, "trimY": 562, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_38.png": { "ver": "1.0.3", "uuid": "ce892dc4-8503-41ea-8319-08092895c18b", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 562, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_39.png": { "ver": "1.0.3", "uuid": "9b516a7d-3fad-47c1-82fc-a6b569d33e95", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 786, "trimY": 422, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_40.png": { "ver": "1.0.3", "uuid": "48a6d833-306b-4ecb-95af-29f2eb1d5e8e", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 590, "trimY": 422, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_41.png": { "ver": "1.0.3", "uuid": "a6bfa8b1-750a-4146-a764-5f5fdd1c1586", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 394, "trimY": 422, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_42.png": { "ver": "1.0.3", "uuid": "e09ecadf-506d-4066-bb94-4b20b4946b81", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 198, "trimY": 422, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_43.png": { "ver": "1.0.3", "uuid": "c84fa538-8c0e-46ea-a32b-4e376cb0e6cb", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 422, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_44.png": { "ver": "1.0.3", "uuid": "7527f58f-4a59-4bf3-b769-670ad8d0f170", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 786, "trimY": 282, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_45.png": { "ver": "1.0.3", "uuid": "4725b771-72c8-4e5f-934b-9dd2075f96e4", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 590, "trimY": 282, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_49.png": { "ver": "1.0.3", "uuid": "5e3c4a6b-f21d-4e55-a856-71461d266645", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 394, "trimY": 282, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_50.png": { "ver": "1.0.3", "uuid": "b15773a0-f63b-42fb-b6d3-bd7320e98eb3", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 198, "trimY": 282, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_51.png": { "ver": "1.0.3", "uuid": "03629d4b-187e-47bc-ab84-8a654241d691", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 282, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_52.png": { "ver": "1.0.3", "uuid": "35aa265b-e57d-4e13-b024-101f83f780dd", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 786, "trimY": 142, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_53.png": { "ver": "1.0.3", "uuid": "f2adb59d-9f54-4235-91c1-9b488062dc59", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 590, "trimY": 142, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_54.png": { "ver": "1.0.3", "uuid": "6f1d6b2b-a250-42e8-8133-6a310f155470", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 394, "trimY": 142, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_55.png": { "ver": "1.0.3", "uuid": "365b41d0-80b2-47ba-87af-310144f7ab7f", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 198, "trimY": 142, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_56.png": { "ver": "1.0.3", "uuid": "1f4feb1b-b0f7-43fd-b650-43cbdf5e1352", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 142, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_57.png": { "ver": "1.0.3", "uuid": "7180fd78-73ea-4de9-a90e-6a7da12a4587", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 786, "trimY": 2, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_58.png": { "ver": "1.0.3", "uuid": "679cd96c-8a90-4b50-a6a8-dd9266202c3c", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 590, "trimY": 2, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_59.png": { "ver": "1.0.3", "uuid": "5e393008-0af4-4d68-a464-36e9f5877bfb", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 394, "trimY": 2, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_60.png": { "ver": "1.0.3", "uuid": "8fdc8eea-0724-4846-8e0b-0870895ba155", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 198, "trimY": 2, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} }, "card_61.png": { "ver": "1.0.3", "uuid": "d1a1f943-b5cf-499b-adcc-73f618c548df", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": true, "offsetX": 0, "offsetY": 3, "trimX": 2, "trimY": 2, "width": 138, "height": 194, "rawWidth": 138, "rawHeight": 200, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "spriteType": "normal", "subMetas": {} } } } ================================================ FILE: bin/client/assets/resources/game_cards_6p.png.meta ================================================ { "ver": "1.0.0", "uuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "type": "sprite", "wrapMode": "clamp", "filterMode": "bilinear", "subMetas": { "game_cards_6p": { "ver": "1.0.3", "uuid": "a559bb08-bc8b-4bfb-b05b-c571d3af1144", "rawTextureUuid": "d3175df2-92cf-41d8-9e71-1fd53833ccb5", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": -21, "offsetY": 1.5, "trimX": 2, "trimY": 2, "width": 978, "height": 2041, "rawWidth": 1024, "rawHeight": 2048, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "subMetas": {} } } } ================================================ FILE: bin/client/assets/resources/game_desk_bg.jpg.meta ================================================ { "ver": "1.0.0", "uuid": "e1084d70-0b00-4041-8ccc-62b69fbf1716", "type": "sprite", "wrapMode": "clamp", "filterMode": "bilinear", "subMetas": { "game_desk_bg": { "ver": "1.0.3", "uuid": "433c3791-25ed-4e94-8894-72e7dad6af14", "rawTextureUuid": "e1084d70-0b00-4041-8ccc-62b69fbf1716", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 0, "trimY": 0, "width": 750, "height": 1334, "rawWidth": 750, "rawHeight": 1334, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "subMetas": {} } } } ================================================ FILE: bin/client/assets/resources/game_desk_bg_6p.jpg.meta ================================================ { "ver": "1.0.0", "uuid": "8eb63dd6-6d9b-47d8-8021-077beaf0c174", "type": "sprite", "wrapMode": "clamp", "filterMode": "bilinear", "subMetas": { "game_desk_bg_6p": { "ver": "1.0.3", "uuid": "d5e079ed-488b-4fd5-8bc3-b3e082b34d96", "rawTextureUuid": "8eb63dd6-6d9b-47d8-8021-077beaf0c174", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 0, "trimY": 0, "width": 1242, "height": 2208, "rawWidth": 1242, "rawHeight": 2208, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "subMetas": {} } } } ================================================ FILE: bin/client/assets/resources/splash.gif.meta ================================================ { "ver": "1.0.0", "uuid": "14855b17-56e8-473b-8923-ebbe56d4cc81", "subMetas": {} } ================================================ FILE: bin/client/assets/resources/splash.png.meta ================================================ { "ver": "1.0.0", "uuid": "ac7ab283-08d2-456d-b2fc-0a9ffe60330e", "type": "sprite", "wrapMode": "clamp", "filterMode": "bilinear", "subMetas": { "splash": { "ver": "1.0.3", "uuid": "ff6660f1-fbd2-4dad-901b-ba8dd3fe5acc", "rawTextureUuid": "ac7ab283-08d2-456d-b2fc-0a9ffe60330e", "trimType": "auto", "trimThreshold": 1, "rotated": false, "offsetX": 0, "offsetY": 0, "trimX": 0, "trimY": 0, "width": 687, "height": 324, "rawWidth": 687, "rawHeight": 324, "borderTop": 0, "borderBottom": 0, "borderLeft": 0, "borderRight": 0, "subMetas": {} } } } ================================================ FILE: bin/client/assets/resources.meta ================================================ { "ver": "1.0.1", "uuid": "1b5c7d50-37bb-4fb6-9e86-28af5dde70ef", "isGroup": false, "subMetas": {} } ================================================ FILE: bin/client/creator.d.ts ================================================ /** !#en The main namespace of Cocos2d-JS, all engine core classes, functions, properties and constants are defined in this namespace. !#zh Cocos 引擎的主要命名空间,引擎代码中所有的类,函数,属性和常量都在这个命名空间中定义。 */ declare module cc { /** !#en Init Debug setting. !#zh 设置调试模式。 */ export function _initDebugSetting(mode : DebugMode) : void; /** !#en Outputs an error message to the Cocos Creator Console (editor) or Web Console (runtime).
- In Cocos Creator, error is red.
- In Chrome, error have a red icon along with red message text.
!#zh 输出错误消息到 Cocos Creator 编辑器的 Console 或运行时页面端的 Console 中。
- 在 Cocos Creator 中,错误信息显示是红色的。
- 在 Chrome 中,错误信息有红色的图标以及红色的消息文本。
@param obj A JavaScript string containing zero or more substitution strings. @param subst JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ export function error(obj : Any, subst : Any) : void; /** !#en Outputs a warning message to the Cocos Creator Console (editor) or Web Console (runtime). - In Cocos Creator, warning is yellow. - In Chrome, warning have a yellow warning icon with the message text. !#zh 输出警告消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。
- 在 Cocos Creator 中,警告信息显示是黄色的。
- 在 Chrome 中,警告信息有着黄色的图标以及黄色的消息文本。
@param obj A JavaScript string containing zero or more substitution strings. @param subst JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ export function warn(obj : Any, subst : Any) : void; /** !#en Outputs a message to the Cocos Creator Console (editor) or Web Console (runtime). !#zh 输出一条消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。 @param obj A JavaScript string containing zero or more substitution strings. @param subst JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ export function log(obj : Any, subst : Any) : void; /** !#en Outputs an informational message to the Cocos Creator Console (editor) or Web Console (runtime). - In Cocos Creator, info is blue. - In Firefox and Chrome, a small "i" icon is displayed next to these items in the Web Console's log. !#zh 输出一条信息消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。 - 在 Cocos Creator 中,Info 信息显示是蓝色的。
- 在 Firefox 和 Chrome 中,Info 信息有着小 “i” 图标。 @param obj A JavaScript string containing zero or more substitution strings. @param subst JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ export function info(obj : any, subst : any) : void; /** !#en Creates an action with a Cardinal Spline array of points and tension. !#zh 按基数样条曲线轨迹移动到目标位置。 @param points array of control points @example ```js //create a cc.CardinalSplineTo var action1 = cc.cardinalSplineTo(3, array, 0); ``` */ export function cardinalSplineTo(duration : number, points : any[], tension : number) : ActionInterval; /** !#en Creates an action with a Cardinal Spline array of points and tension. !#zh 按基数样条曲线轨迹移动指定的距离。 */ export function cardinalSplineBy(duration : number, points : any[], tension : number) : ActionInterval; /** !#en Creates an action with a Cardinal Spline array of points and tension. !#zh 按 Catmull Rom 样条曲线轨迹移动到目标位置。 @example ```js var action1 = cc.catmullRomTo(3, array); ``` */ export function catmullRomTo(dt : number, points : any[]) : ActionInterval; /** !#en Creates an action with a Cardinal Spline array of points and tension. !#zh 按 Catmull Rom 样条曲线轨迹移动指定的距离。 @example ```js var action1 = cc.catmullRomBy(3, array); ``` */ export function catmullRomBy(dt : number, points : any[]) : ActionInterval; /** !#en Creates the speed action which changes the speed of an action, making it take longer (speed > 1) or less (speed < 1) time.
Useful to simulate 'slow motion' or 'fast forward' effect. !#zh 修改目标动作的速率。 @example ```js // change the target action speed; var action = cc.scaleTo(0.2, 1, 0.6); var newAction = cc.speed(action, 0.5); ``` */ export function speed(action : ActionInterval, speed : number) : Action; /** !#en Create a follow action which makes its target follows another node. !#zh 追踪目标节点的位置。 @example ```js // example // creates the action with a set boundary var followAction = cc.follow(targetNode, cc.rect(0, 0, screenWidth * 2 - 100, screenHeight)); node.runAction(followAction); // creates the action with no boundary set var followAction = cc.follow(targetNode); node.runAction(followAction); ``` */ export function follow(followedNode : Node, rect : Rect) : Action; /** !#en Creates the action easing object with the rate parameter.
From slow to fast. !#zh 创建 easeIn 缓动对象,由慢到快。 @example ```js // example action.easing(cc.easeIn(3.0)); ``` */ export function easeIn(rate : number) : any; /** !#en Creates the action easing object with the rate parameter.
From fast to slow. !#zh 创建 easeOut 缓动对象,由快到慢。 @example ```js // example action.easing(cc.easeOut(3.0)); ``` */ export function easeOut(rate : number) : any; /** !#en Creates the action easing object with the rate parameter.
Slow to fast then to slow. !#zh 创建 easeInOut 缓动对象,慢到快,然后慢。 @example ```js //The new usage action.easing(cc.easeInOut(3.0)); ``` */ export function easeInOut(rate : number) : any; /** !#en Creates the action easing object with the rate parameter.
Reference easeInExpo:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeExponentialIn 缓动对象。
EaseExponentialIn 是按指数函数缓动进入的动作。
参考 easeInExpo:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeExponentialIn()); ``` */ export function easeExponentialIn() : any; /** !#en Creates the action easing object.
Reference easeOutExpo:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeExponentialOut 缓动对象。
EaseExponentialOut 是按指数函数缓动退出的动作。
参考 easeOutExpo:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeExponentialOut()); ``` */ export function easeExponentialOut() : any; /** !#en Creates an EaseExponentialInOut action easing object.
Reference easeInOutExpo:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeExponentialInOut 缓动对象。
EaseExponentialInOut 是按指数函数缓动进入并退出的动作。
参考 easeInOutExpo:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeExponentialInOut()); ``` */ export function easeExponentialInOut() : any; /** !#en Creates an EaseSineIn action.
Reference easeInSine:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 EaseSineIn 缓动对象。
EaseSineIn 是按正弦函数缓动进入的动作。
参考 easeInSine:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeSineIn()); ``` */ export function easeSineIn() : any; /** !#en Creates an EaseSineOut action easing object.
Reference easeOutSine:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 EaseSineOut 缓动对象。
EaseSineIn 是按正弦函数缓动退出的动作。
参考 easeOutSine:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeSineOut()); ``` */ export function easeSineOut() : any; /** !#en Creates the action easing object.
Reference easeInOutSine:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeSineInOut 缓动对象。
EaseSineIn 是按正弦函数缓动进入并退出的动作。
参考 easeInOutSine:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeSineInOut()); ``` */ export function easeSineInOut() : any; /** !#en Creates the action easing obejct with the period in radians (default is 0.3).
Reference easeInElastic:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeElasticIn 缓动对象。
EaseElasticIn 是按弹性曲线缓动进入的动作。
参数 easeInElastic:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeElasticIn(3.0)); ``` */ export function easeElasticIn(period : number) : any; /** !#en Creates the action easing object with the period in radians (default is 0.3).
Reference easeOutElastic:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeElasticOut 缓动对象。
EaseElasticOut 是按弹性曲线缓动退出的动作。
参考 easeOutElastic:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeElasticOut(3.0)); ``` */ export function easeElasticOut(period : number) : any; /** !#en Creates the action easing object with the period in radians (default is 0.3).
Reference easeInOutElastic:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeElasticInOut 缓动对象。
EaseElasticInOut 是按弹性曲线缓动进入并退出的动作。
参考 easeInOutElastic:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js // example action.easing(cc.easeElasticInOut(3.0)); ``` */ export function easeElasticInOut(period : number) : any; /** !#en Creates the action easing object.
Eased bounce effect at the beginning. !#zh 创建 easeBounceIn 缓动对象。
EaseBounceIn 是按弹跳动作缓动进入的动作。 @example ```js // example action.easing(cc.easeBounceIn()); ``` */ export function easeBounceIn() : any; /** !#en Creates the action easing object.
Eased bounce effect at the ending. !#zh 创建 easeBounceOut 缓动对象。
EaseBounceOut 是按弹跳动作缓动退出的动作。 @example ```js // example action.easing(cc.easeBounceOut()); ``` */ export function easeBounceOut() : any; /** !#en Creates the action easing object.
Eased bounce effect at the begining and ending. !#zh 创建 easeBounceInOut 缓动对象。
EaseBounceInOut 是按弹跳动作缓动进入并退出的动作。 @example ```js // example action.easing(cc.easeBounceInOut()); ``` */ export function easeBounceInOut() : any; /** !#en Creates the action easing object.
In the opposite direction to move slowly, and then accelerated to the right direction. !#zh 创建 easeBackIn 缓动对象。
easeBackIn 是在相反的方向缓慢移动,然后加速到正确的方向。
@example ```js // example action.easing(cc.easeBackIn()); ``` */ export function easeBackIn() : any; /** !#en Creates the action easing object.
Fast moving more than the finish, and then slowly back to the finish. !#zh 创建 easeBackOut 缓动对象。
easeBackOut 快速移动超出目标,然后慢慢回到目标点。 @example ```js // example action.easing(cc.easeBackOut()); ``` */ export function easeBackOut() : any; /** !#en Creates the action easing object.
Begining of cc.EaseBackIn. Ending of cc.EaseBackOut. !#zh 创建 easeBackInOut 缓动对象。
@example ```js // example action.easing(cc.easeBackInOut()); ``` */ export function easeBackInOut() : any; /** !#en Creates the action easing object.
Into the 4 reference point.
To calculate the motion curve. !#zh 创建 easeBezierAction 缓动对象。
EaseBezierAction 是按贝塞尔曲线缓动的动作。 @param p0 The first bezier parameter @param p1 The second bezier parameter @param p2 The third bezier parameter @param p3 The fourth bezier parameter @example ```js // example action.easing(cc.easeBezierAction(0.5, 0.5, 1.0, 1.0)); ``` */ export function easeBezierAction(p0 : number, p1 : number, p2 : number, p3 : number) : any; /** !#en Creates the action easing object.
Reference easeInQuad:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuadraticActionIn 缓动对象。
EaseQuadraticIn是按二次函数缓动进入的动作。
参考 easeInQuad:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuadraticActionIn()); ``` */ export function easeQuadraticActionIn() : any; /** !#en Creates the action easing object.
Reference easeOutQuad:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuadraticActionOut 缓动对象。
EaseQuadraticOut 是按二次函数缓动退出的动作。
参考 easeOutQuad:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuadraticActionOut()); ``` */ export function easeQuadraticActionOut() : any; /** !#en Creates the action easing object.
Reference easeInOutQuad:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuadraticActionInOut 缓动对象。
EaseQuadraticInOut 是按二次函数缓动进入并退出的动作。
参考 easeInOutQuad:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuadraticActionInOut()); ``` */ export function easeQuadraticActionInOut() : any; /** !#en Creates the action easing object.
Reference easeIntQuart:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuarticActionIn 缓动对象。
EaseQuarticIn 是按四次函数缓动进入的动作。
参考 easeIntQuart:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuarticActionIn()); ``` */ export function easeQuarticActionIn() : any; /** !#en Creates the action easing object.
Reference easeOutQuart:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuarticActionOut 缓动对象。
EaseQuarticOut 是按四次函数缓动退出的动作。
参考 easeOutQuart:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.QuarticActionOut()); ``` */ export function easeQuarticActionOut() : any; /** !#en Creates the action easing object.
Reference easeInOutQuart:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuarticActionInOut 缓动对象。
EaseQuarticInOut 是按四次函数缓动进入并退出的动作。
参考 easeInOutQuart:http://www.zhihu.com/question/21981571/answer/19925418 */ export function easeQuarticActionInOut() : any; /** !#en Creates the action easing object.
Reference easeInQuint:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuinticActionIn 缓动对象。
EaseQuinticIn 是按五次函数缓动进的动作。
参考 easeInQuint:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuinticActionIn()); ``` */ export function easeQuinticActionIn() : any; /** !#en Creates the action easing object.
Reference easeOutQuint:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuinticActionOut 缓动对象。
EaseQuinticOut 是按五次函数缓动退出的动作 参考 easeOutQuint:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuadraticActionOut()); ``` */ export function easeQuinticActionOut() : any; /** !#en Creates the action easing object.
Reference easeInOutQuint:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeQuinticActionInOut 缓动对象。
EaseQuinticInOut是按五次函数缓动进入并退出的动作。
参考 easeInOutQuint:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeQuinticActionInOut()); ``` */ export function easeQuinticActionInOut() : any; /** !#en Creates the action easing object.
Reference easeInCirc:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeCircleActionIn 缓动对象。
EaseCircleIn是按圆形曲线缓动进入的动作。
参考 easeInCirc:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeCircleActionIn()); ``` */ export function easeCircleActionIn() : any; /** !#en Creates the action easing object.
Reference easeOutCirc:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeCircleActionOut 缓动对象。
EaseCircleOut是按圆形曲线缓动退出的动作。
参考 easeOutCirc:http://www.zhihu.com/question/21981571/answer/19925418 */ export function easeCircleActionOut() : any; /** !#en Creates the action easing object.
Reference easeInOutCirc:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeCircleActionInOut 缓动对象。
EaseCircleInOut 是按圆形曲线缓动进入并退出的动作。
参考 easeInOutCirc:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeCircleActionInOut()); ``` */ export function easeCircleActionInOut() : any; /** !#en Creates the action easing object.
Reference easeInCubic:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeCubicActionIn 缓动对象。
EaseCubicIn 是按三次函数缓动进入的动作。
参考 easeInCubic:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeCubicActionIn()); ``` */ export function easeCubicActionIn() : any; /** !#en Creates the action easing object.
Reference easeOutCubic:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeCubicActionOut 缓动对象。
EaseCubicOut 是按三次函数缓动退出的动作。
参考 easeOutCubic:http://www.zhihu.com/question/21981571/answer/19925418 @example ```js //example action.easing(cc.easeCubicActionOut()); ``` */ export function easeCubicActionOut() : any; /** !#en Creates the action easing object.
Reference easeInOutCubic:
http://www.zhihu.com/question/21981571/answer/19925418 !#zh 创建 easeCubicActionInOut 缓动对象。
EaseCubicInOut是按三次函数缓动进入并退出的动作。
参考 easeInOutCubic:http://www.zhihu.com/question/21981571/answer/19925418 */ export function easeCubicActionInOut() : any; /** !#en Show the Node. !#zh 立即显示。 @example ```js // example var showAction = cc.show(); ``` */ export function show() : ActionInstant; /** !#en Hide the node. !#zh 立即隐藏。 @example ```js // example var hideAction = cc.hide(); ``` */ export function hide() : ActionInstant; /** !#en Toggles the visibility of a node. !#zh 显隐状态切换。 @example ```js // example var toggleVisibilityAction = cc.toggleVisibility(); ``` */ export function toggleVisibility() : ActionInstant; /** !#en Create a RemoveSelf object with a flag indicate whether the target should be cleaned up while removing. !#zh 从父节点移除自身。 @example ```js // example var removeSelfAction = cc.removeSelf(); ``` */ export function removeSelf(isNeedCleanUp : boolean) : ActionInstant; /** !#en Create a FlipX action to flip or unflip the target. !#zh X轴翻转。 @param flip Indicate whether the target should be flipped or not @example ```js var flipXAction = cc.flipX(true); ``` */ export function flipX(flip : boolean) : ActionInstant; /** !#en Create a FlipY action to flip or unflip the target. !#zh Y轴翻转。 @example ```js var flipYAction = cc.flipY(true); ``` */ export function flipY(flip : boolean) : ActionInstant; /** !#en Creates a Place action with a position. !#zh 放置在目标位置。 @example ```js // example var placeAction = cc.place(cc.p(200, 200)); var placeAction = cc.place(200, 200); ``` */ export function place(pos : Vec2|number, y? : number) : ActionInstant; /** !#en Creates the action with the callback. !#zh 执行回调函数。 @param data data for function, it accepts all data types. @example ```js // example // CallFunc without data var finish = cc.callFunc(this.removeSprite, this); // CallFunc with data var finish = cc.callFunc(this.removeFromParentAndCleanup, this._grossini, true); ``` */ export function callFunc(selector : Function, selectorTarget? : any|void, data? : any|void) : ActionInstant; /** !#en Helper constructor to create an array of sequenceable actions The created action will run actions sequentially, one after another. !#zh 顺序执行动作,创建的动作将按顺序依次运行。 @example ```js // example // create sequence with actions var seq = cc.sequence(act1, act2); // create sequence with array var seq = cc.sequence(actArray); ``` */ export function sequence(tempArray : any[]|FiniteTimeAction) : ActionInterval; /** !#en Creates a Repeat action. Times is an unsigned integer between 1 and pow(2,30) !#zh 重复动作,可以按一定次数重复一个动,如果想永远重复一个动作请使用 repeatForever 动作来完成。 @example ```js // example var rep = cc.repeat(cc.sequence(jump2, jump1), 5); ``` */ export function repeat(action : FiniteTimeAction, times : number) : ActionInterval; /** !#en Create a acton which repeat forever !#zh 永远地重复一个动作,有限次数内重复一个动作请使用 repeat 动作。 @example ```js // example var repeat = cc.repeatForever(cc.rotateBy(1.0, 360)); ``` */ export function repeatForever(action : FiniteTimeAction) : ActionInterval; /** !#en Create a spawn action which runs several actions in parallel. !#zh 同步执行动作,同步执行一组动作。 @example ```js // example var action = cc.spawn(cc.jumpBy(2, cc.p(300, 0), 50, 4), cc.rotateBy(2, 720)); todo:It should be the direct use new ``` */ export function spawn(tempArray : any[]|FiniteTimeAction) : FiniteTimeAction; /** !#en Rotates a Node object to a certain angle by modifying its rotation property.
The direction will be decided by the shortest angle. !#zh 旋转到目标角度,通过逐帧修改它的 rotation 属性,旋转方向将由最短的角度决定。 @param duration duration in seconds @param deltaAngleX deltaAngleX in degrees. @param deltaAngleY deltaAngleY in degrees. @example ```js // example var rotateTo = cc.rotateTo(2, 61.0); ``` */ export function rotateTo(duration : number, deltaAngleX : number, deltaAngleY? : number) : ActionInterval; /** !#en Rotates a Node object clockwise a number of degrees by modifying its rotation property. Relative to its properties to modify. !#zh 旋转指定的角度。 @param duration duration in seconds @param deltaAngleX deltaAngleX in degrees @param deltaAngleY deltaAngleY in degrees @example ```js // example var actionBy = cc.rotateBy(2, 360); ``` */ export function rotateBy(duration : number, deltaAngleX : number, deltaAngleY? : number) : ActionInterval; /** !#en Moves a Node object x,y pixels by modifying its position property.
x and y are relative to the position of the object.
Several MoveBy actions can be concurrently called, and the resulting
movement will be the sum of individual movements. !#zh 移动指定的距离。 @param duration duration in seconds @example ```js // example var actionTo = cc.moveBy(2, cc.p(windowSize.width - 40, windowSize.height - 40)); ``` */ export function moveBy(duration : number, deltaPos : Vec2|number, deltaY : number) : ActionInterval; /** !#en Moves a Node object to the position x,y. x and y are absolute coordinates by modifying its position property.
Several MoveTo actions can be concurrently called, and the resulting
movement will be the sum of individual movements. !#zh 移动到目标位置。 @param duration duration in seconds @example ```js // example var actionBy = cc.moveTo(2, cc.p(80, 80)); ``` */ export function moveTo(duration : number, position : Vec2, y : number) : ActionInterval; /** !#en Create a action which skews a Node object to given angles by modifying its skewX and skewY properties. Changes to the specified value. !#zh 偏斜到目标角度。 @param t time in seconds @example ```js // example var actionTo = cc.skewTo(2, 37.2, -37.2); ``` */ export function skewTo(t : number, sx : number, sy : number) : ActionInterval; /** !#en Skews a Node object by skewX and skewY degrees.
Relative to its property modification. !#zh 偏斜指定的角度。 @param t time in seconds @param sx sx skew in degrees for X axis @param sy sy skew in degrees for Y axis @example ```js // example var actionBy = cc.skewBy(2, 0, -90); ``` */ export function skewBy(t : number, sx : number, sy : number) : ActionInterval; /** !#en Moves a Node object simulating a parabolic jump movement by modifying it's position property. Relative to its movement. !#zh 用跳跃的方式移动指定的距离。 @example ```js // example var actionBy = cc.jumpBy(2, cc.p(300, 0), 50, 4); var actionBy = cc.jumpBy(2, 300, 0, 50, 4); ``` */ export function jumpBy(duration : number, position : Vec2|number, y? : number, height : number, jumps : number) : ActionInterval; /** !#en Moves a Node object to a parabolic position simulating a jump movement by modifying its position property.
Jump to the specified location. !#zh 用跳跃的方式移动到目标位置。 @example ```js // example var actionTo = cc.jumpTo(2, cc.p(300, 300), 50, 4); var actionTo = cc.jumpTo(2, 300, 300, 50, 4); ``` */ export function jumpTo(duration : number, position : Vec2|number, y? : number, height : number, jumps : number) : ActionInterval; /** !#en An action that moves the target with a cubic Bezier curve by a certain distance. Relative to its movement. !#zh 按贝赛尔曲线轨迹移动指定的距离。 @param t time in seconds @param c Array of points @example ```js // example var bezier = [cc.p(0, windowSize.height / 2), cc.p(300, -windowSize.height / 2), cc.p(300, 100)]; var bezierForward = cc.bezierBy(3, bezier); ``` */ export function bezierBy(t : number, c : any[]) : ActionInterval; /** !#en An action that moves the target with a cubic Bezier curve to a destination point. !#zh 按贝赛尔曲线轨迹移动到目标位置。 @param c array of points @example ```js // example var bezier = [cc.p(0, windowSize.height / 2), cc.p(300, -windowSize.height / 2), cc.p(300, 100)]; var bezierTo = cc.bezierTo(2, bezier); ``` */ export function bezierTo(t : number, c : any[]) : ActionInterval; /** !#en Scales a Node object to a zoom factor by modifying it's scale property. !#zh 将节点大小缩放到指定的倍数。 @param sx scale parameter in X @param sy scale parameter in Y, if Null equal to sx @example ```js // example // It scales to 0.5 in both X and Y. var actionTo = cc.scaleTo(2, 0.5); // It scales to 0.5 in x and 2 in Y var actionTo = cc.scaleTo(2, 0.5, 2); ``` */ export function scaleTo(duration : number, sx : number, sy? : number) : ActionInterval; /** !#en Scales a Node object a zoom factor by modifying it's scale property. Relative to its changes. !#zh 按指定的倍数缩放节点大小。 @param duration duration in seconds @param sx sx scale parameter in X @param sy sy scale parameter in Y, if Null equal to sx @example ```js // example without sy, it scales by 2 both in X and Y var actionBy = cc.scaleBy(2, 2); //example with sy, it scales by 0.25 in X and 4.5 in Y var actionBy2 = cc.scaleBy(2, 0.25, 4.5); ``` */ export function scaleBy(duration : number, sx : number, sy? : number|void) : ActionInterval; /** !#en Blinks a Node object by modifying it's visible property. !#zh 闪烁(基于透明度)。 @param duration duration in seconds @param blinks blinks in times @example ```js // example var action = cc.blink(2, 10); ``` */ export function blink(duration : number, blinks : number) : ActionInterval; /** !#en Fades an object that implements the cc.RGBAProtocol protocol. It modifies the opacity from the current value to a custom one. !#zh 修改透明度到指定值。 @param opacity 0-255, 0 is transparent @example ```js // example var action = cc.fadeTo(1.0, 0); ``` */ export function fadeTo(duration : number, opacity : number) : ActionInterval; /** !#en Fades In an object that implements the cc.RGBAProtocol protocol. It modifies the opacity from 0 to 255. !#zh 渐显效果。 @param duration duration in seconds @example ```js //example var action = cc.fadeIn(1.0); ``` */ export function fadeIn(duration : number) : ActionInterval; /** !#en Fades Out an object that implements the cc.RGBAProtocol protocol. It modifies the opacity from 255 to 0. !#zh 渐隐效果。 @param d duration in seconds @example ```js // example var action = cc.fadeOut(1.0); ``` */ export function fadeOut(d : number) : ActionInterval; /** !#en Tints a Node that implements the cc.NodeRGB protocol from current tint to a custom one. !#zh 修改颜色到指定值。 @param red 0-255 @param green 0-255 @param blue 0-255 @example ```js // example var action = cc.tintTo(2, 255, 0, 255); ``` */ export function tintTo(duration : number, red : number, green : number, blue : number) : ActionInterval; /** !#en Tints a Node that implements the cc.NodeRGB protocol from current tint to a custom one. Relative to their own color change. !#zh 按照指定的增量修改颜色。 @param duration duration in seconds @example ```js // example var action = cc.tintBy(2, -127, -255, -127); ``` */ export function tintBy(duration : number, deltaRed : number, deltaGreen : number, deltaBlue : number) : ActionInterval; /** !#en Delays the action a certain amount of seconds. !#en 延迟指定的时间量。 @param d duration in seconds @example ```js // example var delay = cc.delayTime(1); ``` */ export function delayTime(d : number) : ActionInterval; /** !#en Executes an action in reverse order, from time=duration to time=0. !#zh 反转目标动作的时间轴。 @example ```js // example var reverse = cc.reverseTime(this); ``` */ export function reverseTime(action : FiniteTimeAction) : ActionInterval; /** !#en Create an action with the specified action and forced target. !#zh 用已有动作和一个新的目标节点创建动作。 */ export function targetedAction(target : Node, action : FiniteTimeAction) : ActionInterval; /** Constructor */ export function HashElement() : void; /** !#en cc.view is the shared view object. !#zh cc.view 是全局的视图对象。 */ export var view : View; /** !#en Director !#zh 导演类。 */ export var director : Director; /** !#en cc.winSize is the alias object for the size of the current game window. !#zh cc.winSize 为当前的游戏窗口的大小。 */ export var winSize : Size; export var game : Game; /** Checks whether subclass is child of superclass or equals to superclass */ export function isChildClassOf(subclass : Function, superclass : Function) : boolean; /** !#en Defines a CCClass using the given specification, please see [Class](/en/scripting/class/) for details. !#zh 定义一个 CCClass,传入参数必须是一个包含类型参数的字面量对象,具体用法请查阅[类型定义](/zh/scripting/class/)。 @example ```js // define base class var Node = cc.Class(); // define sub class var Sprite = cc.Class({ name: 'Sprite', extends: Node, ctor: function () { this.url = ""; this.id = 0; }, properties { width: { default: 128, type: 'Integer', tooltip: 'The width of sprite' }, height: 128, size: { get: function () { return cc.v2(this.width, this.height); } } }, load: function () { // load this.url }; }); // instantiate var obj = new Sprite(); obj.url = 'sprite.png'; obj.load(); // define static member Sprite.count = 0; Sprite.getBounds = function (spriteList) { // ... }; ``` */ export function Class(options : { name? : string; extends? : Function; ctor? : Function; properties? : any; statics? : any; mixins? : Function[]; editor? : any; update? : Function; lateUpdate? : Function; onLoad? : Function; start? : Function; onEnable? : Function; onDisable? : Function; onDestroy? : Function; onFocusInEditor? : Function; onLostFocusInEditor? : Function; onRestore? : Function; _getLocalBounds? : Function; }) : Function; /** whether enable accelerometer event */ export function setAccelerometerEnabled(isEnable : boolean) : void; /** set accelerometer interval value */ export function setAccelerometerInterval(interval : number) : void; /** !#en Checks whether the object is non-nil and not yet destroyed. !#zh 检查该对象是否不为 null 并且尚未销毁。 @example ```js cc.log(cc.isValid(target)); ``` */ export function isValid(value : any) : boolean; /** Specify that the input value must be integer in Inspector. Also used to indicates that the elements in array should be type integer. */ export var Integer : string; /** Indicates that the elements in array should be type double. */ export var Float : string; /** Indicates that the elements in array should be type boolean. */ export var Boolean : string; /** Indicates that the elements in array should be type string. */ export var String : string; /** !#en Deserialize json to cc.Asset !#zh 将 JSON 反序列化为对象实例。 当指定了 target 选项时,如果 target 引用的其它 asset 的 uuid 不变,则不会改变 target 对 asset 的引用, 也不会将 uuid 保存到 result 对象中。 @param data the serialized cc.Asset json string or json object. @param result additional loading result */ export function deserialize(data : string|any, result? : Details, options? : any) : any; /** !#en Clones the object original and returns the clone. See [Clone exists Entity](/en/scripting/create-destroy-entities/#instantiate) !#zh 复制给定的对象 详细用法可参考[复制已有Entity](/zh/scripting/create-destroy-entities/#instantiate) Instantiate 时,function 和 dom 等非可序列化对象会直接保留原有引用,Asset 会直接进行浅拷贝,可序列化类型会进行深拷贝。 对于 Entity / Component 等 Scene Object,如果对方也会被一起 Instantiate,则重定向到新的引用,否则保留为原来的引用。 @param original An existing object that you want to make a copy of. */ export function instantiate(original : any) : any; /** Finds a node by hierarchy path, the path is case-sensitive. It will traverse the hierarchy by splitting the path using '/' character. This function will still returns the node even if it is inactive. It is recommended to not use this function every frame instead cache the result at startup. */ export function find(path : string, referenceNode? : Node) : Node; /** !#en The convenience method to create a new {{#crossLink "Color/Color:method"}}cc.Color{{/crossLink}} Alpha channel is optional. Default value is 255. !#zh 通过该方法来创建一个新的 {{#crossLink "Color/Color:method"}}cc.Color{{/crossLink}} 对象。 Alpha 通道是可选的。默认值是 255。 @example ```js ----------------------- // 1. All channels seperately as parameters var color1 = new cc.Color(255, 255, 255, 255); // 2. Convert a hex string to a color var color2 = new cc.Color("#000000"); // 3. An color object as parameter var color3 = new cc.Color({r: 255, g: 255, b: 255, a: 255}); ``` */ export function color(r? : number, g? : number, b? : number, a? : number) : Color; /** !#en returns true if both ccColor3B are equal. Otherwise it returns false. !#zh 判断两个颜色对象的 RGB 部分是否相等,不比较透明度。 @example ```js cc.log(cc.colorEqual(cc.Color.RED, new cc.Color(255, 0, 0))); // true ``` */ export function colorEqual(color1: (r: number, g: number, b: number, a: number) => void, color2: (r: number, g: number, b: number, a: number) => void) : boolean; /** !#en convert a string of color for style to Color. e.g. "#ff06ff" to : cc.color(255,6,255)。 !#zh 16 进制转换为 Color @example ```js cc.hexToColor("#FFFF33"); // Color {r: 255, g: 255, b: 51, a: 255}; ``` */ export function hexToColor(hex : string) : Color; /** !#en convert Color to a string of color for style. e.g. cc.color(255,6,255) to : "#ff06ff" !#zh Color 转换为 16进制。 @example ```js var color = new cc.Color(255, 6, 255) cc.colorToHex(color); // #ff06ff; ``` */ export function colorToHex(color: (r: number, g: number, b: number, a: number) => void) : string; /** !#en Define an enum type.
If a enum item has a value of -1, it will be given an Integer number according to it's order in the list.
Otherwise it will use the value specified by user who writes the enum definition. !#zh 定义一个枚举类型。
用户可以把枚举值设为任意的整数,如果设为 -1,系统将会分配为上一个枚举值 + 1。 @param obj a JavaScript literal object containing enum names and values @example ```js var WrapMode = cc.Enum({ Repeat: -1, Clamp: -1 }); // Texture.WrapMode.Repeat == 0 // Texture.WrapMode.Clamp == 1 // Texture.WrapMode[0] == "Repeat" // Texture.WrapMode[1] == "Clamp" var FlagType = cc.Enum({ Flag1: 1, Flag2: 2, Flag3: 4, Flag4: 8, }); var AtlasSizeList = cc.Enum({ 128: 128, 256: 256, 512: 512, 1024: 1024, }); ``` */ export function Enum(obj : any) : any; /** !#en Returns opposite of Vec2. !#zh 返回相反的向量。 @example ```js cc.pNeg(cc.v2(10, 10));// Vec2 {x: -10, y: -10}; ``` */ export function pNeg(point : Vec2) : Vec2; /** !#en Calculates sum of two points. !#zh 返回两个向量的和。 @example ```js cc.pAdd(cc.v2(1, 1), cc.v2(2, 2));// Vec2 {x: 3, y: 3}; ``` */ export function pAdd(v1 : Vec2, v2 : Vec2) : Vec2; /** !#en Calculates difference of two points. !#zh 返回两个向量的差。 @example ```js cc.pSub(cc.v2(20, 20), cc.v2(5, 5)); // Vec2 {x: 15, y: 15}; ``` */ export function pSub(v1 : Vec2, v2 : Vec2) : Vec2; /** !#en Returns point multiplied by given factor. !#zh 向量缩放。 @example ```js cc.pMult(cc.v2(5, 5), 4); // Vec2 {x: 20, y: 20}; ``` */ export function pMult(point : Vec2, floatVar : number) : Vec2; /** !#en Calculates midpoint between two points. !#zh 两个向量之间的中心点。 @example ```js cc.pMidpoint(cc.v2(10, 10), cc.v2(5, 5)); // Vec2 {x: 7.5, y: 7.5}; ``` */ export function pMidpoint(v1 : Vec2, v2 : Vec2) : Vec2; /** !#en Calculates dot product of two points. !#zh 两个向量之间进行点乘。 @example ```js cc.pDot(cc.v2(20, 20), cc.v2(5, 5)); // 200; ``` */ export function pDot(v1 : Vec2, v2 : Vec2) : number; /** !#en Calculates cross product of two points. !#zh 两个向量之间进行叉乘。 @example ```js cc.pCross(cc.v2(20, 20), cc.v2(5, 5)); // 0; ``` */ export function pCross(v1 : Vec2, v2 : Vec2) : number; /** !#en Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) greater than 0. !#zh 返回逆时针旋转 90 度后的新向量。 @example ```js cc.pPerp(cc.v2(20, 20)); // Vec2 {x: -20, y: 20}; ``` */ export function pPerp(point : Vec2) : Vec2; /** !#en Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) smaller than 0. !#zh 将指定向量顺时针旋转 90 度并返回。 @example ```js cc.pRPerp(cc.v2(20, 20)); // Vec2 {x: 20, y: -20}; ``` */ export function pRPerp(point : Vec2) : Vec2; /** !#en Calculates the projection of v1 over v2. !#zh 返回 v1 在 v2 上的投影向量。 @example ```js var v1 = cc.v2(20, 20); var v2 = cc.v2(5, 5); cc.pProject(v1, v2); // Vec2 {x: 20, y: 20}; ``` */ export function pProject(v1 : Vec2, v2 : Vec2) : Vec2; /** !#en Calculates the square length of a cc.Vec2 (not calling sqrt() ). !#zh 返回指定向量长度的平方。 @example ```js cc.pLengthSQ(cc.v2(20, 20)); // 800; ``` */ export function pLengthSQ(v : Vec2) : number; /** !#en Calculates the square distance between two points (not calling sqrt() ). !#zh 返回两个点之间距离的平方。 @example ```js var point1 = cc.v2(20, 20); var point2 = cc.v2(5, 5); cc.pDistanceSQ(point1, point2); // 450; ``` */ export function pDistanceSQ(point1 : Vec2, point2 : Vec2) : number; /** !#en Calculates distance between point an origin. !#zh 返回指定向量的长度. @example ```js cc.pLength(cc.v2(20, 20)); // 28.284271247461902; ``` */ export function pLength(v : Vec2) : number; /** !#en Calculates the distance between two points. !#zh 返回指定 2 个向量之间的距离。 @example ```js var v1 = cc.v2(20, 20); var v2 = cc.v2(5, 5); cc.pDistance(v1, v2); // 21.213203435596427; ``` */ export function pDistance(v1 : Vec2, v2 : Vec2) : number; /** !#en Returns this vector with a magnitude of 1. !#zh 返回一个长度为 1 的标准化过后的向量。 @example ```js cc.pNormalize(cc.v2(20, 20)); // Vec2 {x: 0.7071067811865475, y: 0.7071067811865475}; ``` */ export function pNormalize(v : Vec2) : Vec2; /** !#en Converts radians to a normalized vector. !#zh 将弧度转换为一个标准化后的向量,返回坐标 x = cos(a) , y = sin(a)。 @example ```js cc.pForAngle(20); // Vec2 {x: 0.40808206181339196, y: 0.9129452507276277}; ``` */ export function pForAngle(a : number) : Vec2; /** !#en Converts a vector to radians. !#zh 返回指定向量的弧度。 @example ```js cc.pToAngle(cc.v2(20, 20)); // 0.7853981633974483; ``` */ export function pToAngle(v : Vec2) : number; /** !#en Clamp a value between from and to. !#zh 限定浮点数的最大最小值。
数值大于 max_inclusive 则返回 max_inclusive。
数值小于 min_inclusive 则返回 min_inclusive。
否则返回自身。 @example ```js var v1 = cc.clampf(20, 0, 20); // 20; var v2 = cc.clampf(-1, 0, 20); // 0; var v3 = cc.clampf(10, 0, 20); // 10; ``` */ export function clampf(value : number, min_inclusive : number, max_inclusive : number) : number; /** !#en Clamp a value between 0 and 1. !#zh 限定浮点数的取值范围为 0 ~ 1 之间。 @example ```js var v1 = cc.clampf(20); // 1; var v2 = cc.clampf(-1); // 0; var v3 = cc.clampf(0.5); // 0.5; ``` */ export function clamp01(value : number) : number; /** !#en Clamp a point between from and to. !#zh 返回指定限制区域后的向量。
向量大于 max_inclusive 则返回 max_inclusive。
向量小于 min_inclusive 则返回 min_inclusive。
否则返回自身。 @example ```js var min_inclusive = cc.v2(0, 0); var max_inclusive = cc.v2(20, 20); var v1 = cc.pClamp(cc.v2(20, 20), min_inclusive, max_inclusive); // Vec2 {x: 20, y: 20}; var v2 = cc.pClamp(cc.v2(0, 0), min_inclusive, max_inclusive); // Vec2 {x: 0, y: 0}; var v3 = cc.pClamp(cc.v2(10, 10), min_inclusive, max_inclusive); // Vec2 {x: 10, y: 10}; ``` */ export function pClamp(p : Vec2, min_inclusive : Vec2, max_inclusive : Vec2) : Vec2; /** !#en Quickly convert cc.Size to a cc.Vec2. !#zh 快速转换 cc.Size 为 cc.Vec2。 @example ```js cc.pFromSize(new cc.size(20, 20)); // Vec2 {x: 20, y: 20}; ``` */ export function pFromSize(s : Size) : Vec2; /** !#en Run a math operation function on each point component
Math.abs, Math.fllor, Math.ceil, Math.round. !#zh 通过运行指定的数学运算函数来计算指定的向量。 @example ```js cc.pCompOp(cc.p(-10, -10), Math.abs); // Vec2 {x: 10, y: 10}; ``` */ export function pCompOp(p : Vec2, opFunc : Function) : Vec2; /** !#en Linear Interpolation between two points a and b.
alpha == 0 ? a
alpha == 1 ? b
otherwise a value between a..b. !#zh 两个点 A 和 B 之间的线性插值。
alpha == 0 ? a
alpha == 1 ? b
否则这个数值在 a ~ b 之间。 @example ```js cc.pLerp(cc.v2(20, 20), cc.v2(5, 5), 0.5); // Vec2 {x: 12.5, y: 12.5}; ``` */ export function pLerp(a : Vec2, b : Vec2, alpha : number) : Vec2; /** !#en TODO !#zh 近似判断两个点是否相等。
判断 2 个向量是否在指定数值的范围之内,如果在则返回 true,反之则返回 false。 @example ```js var a = cc.v2(20, 20); var b = cc.v2(5, 5); var b1 = cc.pFuzzyEqual(a, b, 10); // false; var b2 = cc.pFuzzyEqual(a, b, 18); // true; ``` */ export function pFuzzyEqual(a : Vec2, b : Vec2, variance : number) : boolean; /** !#en Multiplies a nd b components, a.x*b.x, a.y*b.y. !#zh 计算两个向量的每个分量的乘积, a.x * b.x, a.y * b.y。 @example ```js cc.pCompMult(acc.v2(20, 20), cc.v2(5, 5)); // Vec2 {x: 100, y: 100}; ``` */ export function pCompMult(a : Vec2, b : Vec2) : Vec2; /** !#en TODO !#zh 返回两个向量之间带正负号的弧度。 */ export function pAngleSigned(a : Vec2, b : Vec2) : number; /** !#en TODO !#zh 获取当前向量与指定向量之间的弧度角。 */ export function pAngle(a : Vec2, b : Vec2) : number; /** !#en Rotates a point counter clockwise by the angle around a pivot. !#zh 返回给定向量围绕指定轴心顺时针旋转一定弧度后的结果。 @param v v is the point to rotate @param pivot pivot is the pivot, naturally @param angle angle is the angle of rotation cw in radians */ export function pRotateByAngle(v : Vec2, pivot : Vec2, angle : number) : Vec2; /** !#en A general line-line intersection test indicating successful intersection of a line
note that to truly test intersection for segments we have to make
sure that s & t lie within [0..1] and for rays, make sure s & t > 0
the hit point is p3 + t * (p4 - p3);
the hit point also is p1 + s * (p2 - p1); !#zh 返回 A 为起点 B 为终点线段 1 所在直线和 C 为起点 D 为终点线段 2 所在的直线是否相交,
如果相交返回 true,反之则为 false,参数 retP 是返回交点在线段 1、线段 2 上的比例。 @param A A is the startpoint for the first line P1 = (p1 - p2). @param B B is the endpoint for the first line P1 = (p1 - p2). @param C C is the startpoint for the second line P2 = (p3 - p4). @param D D is the endpoint for the second line P2 = (p3 - p4). @param retP retP.x is the range for a hitpoint in P1 (pa = p1 + s*(p2 - p1)),
retP.y is the range for a hitpoint in P3 (pa = p2 + t*(p4 - p3)). */ export function pLineIntersect(A : Vec2, B : Vec2, C : Vec2, D : Vec2, retP : Vec2) : boolean; /** !#en ccpSegmentIntersect return YES if Segment A-B intersects with segment C-D. !#zh 返回线段 A - B 和线段 C - D 是否相交。 */ export function pSegmentIntersect(A : Vec2, B : Vec2, C : Vec2, D : Vec2) : boolean; /** !#en ccpIntersectPoint return the intersection point of line A-B, C-D. !#zh 返回线段 A - B 和线段 C - D 的交点。 */ export function pIntersectPoint(A : Vec2, B : Vec2, C : Vec2, D : Vec2) : Vec2; /** !#en check to see if both points are equal. !#zh 检查指定的 2 个向量是否相等。 @param A A ccp a @param B B ccp b to be compared */ export function pSameAs(A : Vec2, B : Vec2) : boolean; /** !#en sets the position of the point to 0. !#zh 设置指定向量归 0。 */ export function pZeroIn(v : Vec2) : void; /** !#en copies the position of one point to another. !#zh 令 v1 向量等同于 v2。 */ export function pIn(v1 : Vec2, v2 : Vec2) : void; /** !#en multiplies the point with the given factor (inplace). !#zh 向量缩放,结果保存到第一个向量。 */ export function pMultIn(point : Vec2, floatVar : number) : void; /** !#en subtracts one point from another (inplace). !#zh 向量减法,结果保存到第一个向量。 */ export function pSubIn(v1 : Vec2, v2 : Vec2) : void; /** !#en adds one point to another (inplace). !#zh 向量加法,结果保存到第一个向量。 */ export function pAddIn(v1 : Vec2, v2 : Vec2) : void; /** !#en normalizes the point (inplace). !#zh 规范化 v 向量,设置 v 向量长度为 1。 */ export function pNormalizeIn(v : Vec2) : void; /** !#en The convenience method to create a new Rect. see {{#crossLink "Rect/Rect:method"}}cc.Rect{{/crossLink}} !#zh 该方法用来快速创建一个新的矩形。{{#crossLink "Rect/Rect:method"}}cc.Rect{{/crossLink}} @example ```js var a = new cc.rect(0 , 0, 10, 0); ``` */ export function rect(x? : Number[]|number, y? : number, w? : number, h? : number) : Rect; /** !#en Check whether a rect's value equals to another. !#zh 判断两个矩形是否相等。 @param rect1 !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param rect2 !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.rect(0, 0, 5, 5); cc.rectEqualToRect(a, b); // false; var c = new cc.rect(0, 0, 5, 5); cc.rectEqualToRect(b, c); // true; ``` */ export function rectEqualToRect(rect1: (x: number, y: number, w: number, h: number) => void, rect2: (x: number, y: number, w: number, h: number) => void) : boolean; /** !#en Check whether the rect1 contains rect2. !#zh 检查 rect1 矩形是否包含 rect2 矩形。
注意:如果要允许 rect1 和 rect2 的边界重合,应该用 cc.rectOverlapsRect @param rect1 !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param rect2 !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 0, 20, 20); var b = new cc.rect(10, 10, 20, 20); cc.rectContainsRect(a, b); // true; ``` */ export function rectContainsRect(rect1: (x: number, y: number, w: number, h: number) => void, rect2: (x: number, y: number, w: number, h: number) => void) : boolean; /** !#en Returns the rightmost x-value of a rect. !#zh 返回矩形在 x 轴上的最大值 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(10, 0, 20, 20); cc.rectGetMaxX(a); // 30; ``` */ export function rectGetMaxX(rect: (x: number, y: number, w: number, h: number) => void) : number; /** !#en Return the midpoint x-value of a rect. !#zh 返回矩形在 x 轴上的中点。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(10, 0, 20, 20); cc.rectGetMidX(a); // 20; ``` */ export function rectGetMidX(rect: (x: number, y: number, w: number, h: number) => void) : number; /** !#en Returns the leftmost x-value of a rect. !#zh 返回矩形在 x 轴上的最小值。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(10, 0, 20, 20); cc.rectGetMinX(a); // 10; ``` */ export function rectGetMinX(rect: (x: number, y: number, w: number, h: number) => void) : number; /** !#en Return the topmost y-value of a rect. !#zh 返回矩形在 y 轴上的最大值。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); cc.rectGetMaxY(a); // 30; ``` */ export function rectGetMaxY(rect: (x: number, y: number, w: number, h: number) => void) : number; /** !#en Return the midpoint y-value of `rect'. !#zh 返回矩形在 y 轴上的中点。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); cc.rectGetMidY(a); // 20; ``` */ export function rectGetMidY(rect: (x: number, y: number, w: number, h: number) => void) : number; /** !#en Return the bottommost y-value of a rect. !#zh 返回矩形在 y 轴上的最小值。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); cc.rectGetMinY(a); // 10; ``` */ export function rectGetMinY(rect: (x: number, y: number, w: number, h: number) => void) : number; /** !#en Check whether a rect contains a point. !#zh 检查一个矩形是否包含某个坐标点。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); var b = cc.v2(0, 10, 10, 10); cc.rectContainsPoint(a, b); // true; ``` */ export function rectContainsPoint(rect: (x: number, y: number, w: number, h: number) => void, point : Vec2) : boolean; /** !#en Check whether a rect intersect with another. !#zh 检查一个矩形是否与另一个相交。 @param rectA !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param rectB !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); var b = new cc.rect(0, 10, 10, 10); cc.rectIntersectsRect(a, b); // true; ``` */ export function rectIntersectsRect(rectA: (x: number, y: number, w: number, h: number) => void, rectB: (x: number, y: number, w: number, h: number) => void) : boolean; /** !#en Check whether a rect overlaps another. !#zh 检查一个矩形是否重叠另一个。 @param rectA !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param rectB !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); var b = new cc.rect(0, 10, 10, 10); cc.rectOverlapsRect(a, b); // true; ``` */ export function rectOverlapsRect(rectA: (x: number, y: number, w: number, h: number) => void, rectB: (x: number, y: number, w: number, h: number) => void) : boolean; /** !#en Returns the smallest rectangle that contains the two source rectangles. !#zh 返回一个包含两个指定矩形的最小矩形。 @param rectA !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param rectB !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); var b = new cc.rect(0, 10, 10, 10); cc.rectUnion(a, b); // Rect {x: 0, y: 10, width: 20, height: 20}; ``` */ export function rectUnion(rectA: (x: number, y: number, w: number, h: number) => void, rectB: (x: number, y: number, w: number, h: number) => void) : Rect; /** !#en Returns the overlapping portion of 2 rectangles. !#zh 返回 2 个矩形重叠的部分。 @param rectA !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param rectB !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 10, 20, 20); var b = new cc.rect(0, 10, 10, 10); cc.rectIntersection(a, b); // Rect {x: 0, y: 10, width: 10, height: 10}; ``` */ export function rectIntersection(rectA: (x: number, y: number, w: number, h: number) => void, rectB: (x: number, y: number, w: number, h: number) => void) : Rect; export function V3F_C4B_T2F_QuadZero() : V3F_C4B_T2F_Quad; /** */ export function V3F_C4B_T2F_QuadCopy(sourceQuad: (tl: V3F_C4B_T2F, bl: V3F_C4B_T2F, tr: V3F_C4B_T2F, br: V3F_C4B_T2F, arrayBuffer: any[], offset: number) => void) : V3F_C4B_T2F_Quad; /** */ export function V3F_C4B_T2F_QuadsCopy(sourceQuads : any[]) : any[]; /** !#en The convenience method to create a new {{#crossLink "Vec2"}}cc.Vec2{{/crossLink}}. !#zh 通过该简便的函数进行创建 {{#crossLink "Vec2"}}cc.Vec2{{/crossLink}} 对象。 @example ```js var v1 = cc.v2(); var v2 = cc.v2(0, 0); var v3 = cc.v2(v2); var v4 = cc.v2({x: 100, y: 100}); ``` */ export function v2(x? : number|any, y? : number) : Vec2; /** !#en The convenience method to creates a new {{#crossLink "Vec2"}}cc.Vec2{{/crossLink}}. !#zh 通过该简便的函数进行创建 {{#crossLink "Vec2"}}cc.Vec2{{/crossLink}} 对象。 @param x a Number or a size object @example ```js var point1 = cc.p(); var point2 = cc.p(100, 100); var point3 = cc.p(point2); var point4 = cc.p({x: 100, y: 100}); ``` */ export function p(x? : number|any, y? : number) : Vec2; /** !#en Check whether a point's value equals to another. !#zh 判断两个向量是否相等。 @param point1 !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @param point2 !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} */ export function pointEqualToPoint(point1: (x: number, y: number) => void, point2: (x: number, y: number) => void) : boolean; /** !#en Enum for debug modes. !#zh 调试模式 */ export enum DebugMode { NONE. = 0, INFO = 0, WARN = 0, ERROR = 0, INFO_FOR_WEB_PAGE = 0, WARN_FOR_WEB_PAGE = 0, ERROR_FOR_WEB_PAGE = 0, } /** !#en cc.audioEngine is the singleton object, it provide simple audio APIs. !#zn cc.audioengine是单例对象。
主要用来播放背景音乐和音效,背景音乐同一时间只能播放一个,而音效则可以同时播放多个。
注意:
在 Android 系统浏览器上,不同浏览器,不同版本的效果不尽相同。
比如说:大多数浏览器都需要用户物理交互才可以开始播放音效,有一些不支持 WebAudio,
有一些不支持多音轨播放。总之如果对音乐依赖比较强,请做尽可能多的测试。 */ export class audioEngine { /** !#en Play music. !#zh 播放指定音乐,并可以设置是否循环播放。
注意:音乐播放接口不支持多音轨,同一时间只能播放一个音乐。 @param url The path of the music file without filename extension. @param loop Whether the music loop or not. @param immediate Whether immediately play music. @example ```js //example cc.audioEngine.playMusic(path, false); ``` */ playMusic(url : string, loop : boolean, immediate : boolean) : void; /** !#en Stop playing music. !#zh 停止当前音乐。 @param releaseData If release the music data or not.As default value is false. @example ```js //example cc.audioEngine.stopMusic(); ``` */ stopMusic(releaseData? : boolean) : void; /** !#en Pause playing music. !#zh 暂停正在播放音乐。 @example ```js //example cc.audioEngine.pauseMusic(); ``` */ pauseMusic() : void; /** !#en Resume playing music. !#zh 恢复音乐播放。 @example ```js //example cc.audioEngine.resumeMusic(); ``` */ resumeMusic() : void; /** !#en Rewind playing music. !#zh 从头开始重新播放当前音乐。 @example ```js //example cc.audioEngine.rewindMusic(); ``` */ rewindMusic() : void; /** !#en The volume of the music max value is 1.0,the min value is 0.0 . !#zh 获取音量(0.0 ~ 1.0)。 @example ```js //example var volume = cc.audioEngine.getMusicVolume(); ``` */ getMusicVolume() : number; /** !#en Set the volume of music. !#zh 设置音量(0.0 ~ 1.0)。 @param volume Volume must be in 0.0~1.0 . @example ```js //example cc.audioEngine.setMusicVolume(0.5); ``` */ setMusicVolume(volume : number) : void; /** !#en Whether the music is playing. !#zh 音乐是否正在播放。 @example ```js //example if (cc.audioEngine.isMusicPlaying()) { cc.log("music is playing"); } else { cc.log("music is not playing"); } ``` */ isMusicPlaying() : boolean; /** !#en Play sound effect. !#zh 播放指定音效,并可以设置是否循环播放。
注意:在部分不支持多音轨的浏览器上,这个接口会失效,请使用 playMusic @param url The path of the sound effect with filename extension. @param loop Whether to loop the effect playing, default value is false @example ```js //example var soundId = cc.audioEngine.playEffect(path); ``` */ playEffect(url : string, loop : boolean, volume : boolean) : number; /** !#en Set the volume of sound effects. !#zh 设置音效音量(0.0 ~ 1.0)。 @param volume Volume must be in 0.0~1.0 . @example ```js //example cc.audioEngine.setEffectsVolume(0.5); ``` */ setEffectsVolume(volume : number) : void; /** !#en The volume of the effects max value is 1.0,the min value is 0.0 . !#zh 获取音效音量(0.0 ~ 1.0)。 @example ```js //example var effectVolume = cc.audioEngine.getEffectsVolume(); ``` */ getEffectsVolume() : number; /** !#en Pause playing sound effect. !#zh 暂停指定的音效。 @param audio The return value of function playEffect. @example ```js //example cc.audioEngine.pauseEffect(audioID); ``` */ pauseEffect(audio : number) : void; /** !#en Pause all playing sound effect. !#zh 暂停现在正在播放的所有音效。 @example ```js //example cc.audioEngine.pauseAllEffects(); ``` */ pauseAllEffects() : void; /** !#en Resume playing sound effect. !#zh 恢复播放指定的音效。 @param audioID The return value of function playEffect. */ resumeEffect(audioID : number) : void; /** !#en Resume all playing sound effect. !#zh 恢复播放所有之前暂停的所有音效。 @example ```js //example cc.audioEngine.resumeAllEffects(); ``` */ resumeAllEffects() : void; /** !#en Stop playing sound effect. !#zh 停止播放指定音效。 @param audioID The return value of function playEffect. @example ```js //example cc.audioEngine.stopEffect(audioID); ``` */ stopEffect(audioID : number) : void; /** !#en Stop all playing sound effects. !#zh 停止正在播放的所有音效。 @example ```js //example cc.audioEngine.stopAllEffects(); ``` */ stopAllEffects() : void; /** !#en Unload the preloaded effect from internal buffer. !#zh 卸载预加载的音效。 @example ```js //example cc.audioEngine.unloadEffect(EFFECT_FILE); ``` */ unloadEffect(url : string) : void; /** !#en End music and effects. !#zh 停止所有音乐和音效的播放。 */ end() : void; } /** !#en Class for animation data handling. !#zh 动画剪辑,用于存储动画数据。 */ export class AnimationClip extends Asset { constructor(); /** !#en Duration of this animation. !#zh 动画的持续时间。 */ duration : number; /** !#en FrameRate of this animation. !#zh 动画的帧速率。 */ sample : number; /** !#en Speed of this animation. !#zh 动画的播放速度。 */ speed : number; /** !#en WrapMode of this animation. !#zh 动画的循环模式。 */ wrapMode : WrapMode; /** !#en Curve data. !#zh 曲线数据。 */ curveData : any; /** !#en Event data. !#zh 事件数据。 */ events : any[]; /** !#en Crate clip with a set of sprite frames !#zh 使用一组序列帧图片来创建动画剪辑 */ sample : number; } /** !#en The AnimationState gives full control over animation playback process. In most cases the Animation Component is sufficient and easier to use. Use the AnimationState if you need full control. !#zh AnimationState 完全控制动画播放过程。
大多数情况下 动画组件 是足够和易于使用的。如果您需要更多的动画控制接口,请使用 AnimationState。 */ export class AnimationState extends AnimationNode { constructor(); /** */ AnimationState(clip : AnimationClip, name? : string) : AnimationState; /** !#en The clip that is being played by this animation state. !#zh 此动画状态正在播放的剪辑。 */ clip : AnimationClip; /** !#en The name of the playing animation. !#zh 动画的名字 */ name : string; } /** undefined */ export class Playable { constructor(); /** !#en Is playing or paused in play mode? !#zh 当前是否正在播放。 */ isPlaying : boolean; /** !#en Is currently paused? This can be true even if in edit mode(isPlaying == false). !#zh 当前是否正在暂停 */ isPaused : boolean; /** !#en Play this animation. !#zh 播放动画。 */ play() : void; /** !#en Stop this animation. !#zh 停止动画播放。 */ stop() : void; /** !#en Pause this animation. !#zh 暂停动画。 */ pause() : void; /** !#en Resume this animation. !#zh 重新播放动画。 */ resume() : void; /** !#en Perform a single frame step. !#zh 执行一帧动画。 */ step() : void; } /** !#en Specifies how time is treated when it is outside of the keyframe range of an Animation. !#zh 动画使用的循环模式。 */ export enum WrapMode { Default = 0, Normal = 0, Reverse = 0, Loop = 0, LoopReverse = 0, PingPong = 0, PingPongReverse = 0, } /** !#en The abstract interface for all playing animation. !#zh 所有播放动画的抽象接口。 */ export class AnimationNodeBase extends Playable { constructor(); /** !#en The curves list. !#zh 曲线列表。 */ curves : AnimCurve[]; /** !#en The start delay which represents the number of seconds from an animation's start time to the start of the active interval. !#zh 延迟多少秒播放。 */ delay : number; /** !#en The animation's iteration count property. A real number greater than or equal to zero (including positive infinity) representing the number of times to repeat the animation node. Values less than zero and NaN values are treated as the value 1.0 for the purpose of timing model calculations. !#zh 迭代次数,指动画播放多少次后结束, normalize time。 如 2.5(2次半) */ repeatCount : number; /** !#en The iteration duration of this animation in seconds. (length) !#zh 单次动画的持续时间,秒。 */ duration : number; /** !#en The animation's playback speed. 1 is normal playback speed. !#zh 播放速率。 */ speed : number; /** !#en Wrapping mode of the playing animation. !#zh 动画循环方式。 */ wrapMode : WrapMode; /** !#en The current time of this animation in seconds. !#zh 动画当前的时间,秒。 */ time : number; } /** !#en Base class cc.Action for action classes. !#zh Action 类是所有动作类型的基类。 */ export class Action { /** !#en to copy object with deep copy. returns a clone of action. !#zh 返回一个克隆的动作。 */ clone() : Action; /** !#en return true if the action has finished. !#zh 如果动作已完成就返回 true。 */ isDone() : boolean; /** !#en get the target. !#zh 获取当前目标节点。 */ getTarget() : Node; /** !#en The action will modify the target properties. !#zh 设置目标节点。 */ setTarget(target : Node) : void; /** !#en get the original target. !#zh 获取原始目标节点。 */ getOriginalTarget() : Node; /** !#en get tag number. !#zh 获取用于识别动作的标签。 */ getTag() : number; /** !#en set tag number. !#zh 设置标签,用于识别动作。 */ setTag(tag : number) : void; /** !#en Default Action tag. !#zh 默认动作标签。 */ TAG_INVALID : number; } /** !#en Base class actions that do have a finite time duration.
Possible actions:
- An action with a duration of 0 seconds.
- An action with a duration of 35.5 seconds. Infinite time actions are valid !#zh 有限时间动作,这种动作拥有时长 duration 属性。 */ export class FiniteTimeAction extends Action { /** !#en get duration of the action. (seconds). !#zh 获取动作以秒为单位的持续时间。 */ getDuration() : number; /** !#en set duration of the action. (seconds). !#zh 设置动作以秒为单位的持续时间。 */ setDuration(duration : number) : void; /** !#en Returns a reversed action.
For example:
- The action will be x coordinates of 0 move to 100.
- The reversed action will be x of 100 move to 0. - Will be rewritten !#zh 返回一个新的动作,执行与原动作完全相反的动作。 */ reverse() : void; /** !#en to copy object with deep copy. returns a clone of action. !#zh 返回一个克隆的动作。 */ clone() : FiniteTimeAction; } /** !#en Base class for Easing actions. !#zh 所有缓动动作基类,用于修饰 ActionInterval。 */ export class ActionEase extends ActionInterval { } /** !#en Base class for Easing actions with rate parameters !#zh 拥有速率属性的缓动动作基类。 */ export class EaseRateAction extends ActionEase { } /** !#en Ease Elastic abstract class. !#zh 弹性缓动动作基类。 */ export class EaseElastic extends ActionEase { } /** !#en cc.EaseBounce abstract class. !#zh 反弹缓动动作基类。 */ export class EaseBounce extends ActionEase { } /** !#en Instant actions are immediate actions. They don't have a duration like the ActionInterval actions. !#zh 即时动作,这种动作立即就会执行,继承自 FiniteTimeAction。 */ export class ActionInstant extends FiniteTimeAction { } /** !#en

An interval action is an action that takes place within a certain period of time.
It has an start time, and a finish time. The finish time is the parameter
duration plus the start time.

These CCActionInterval actions have some interesting properties, like:
- They can run normally (default)
- They can run reversed with the reverse method
- They can run with the time altered with the Accelerate, AccelDeccel and Speed actions.

For example, you can simulate a Ping Pong effect running the action normally and
then running it again in Reverse mode.

!#zh 时间间隔动作,这种动作在已定时间内完成,继承 FiniteTimeAction。 */ export class ActionInterval extends FiniteTimeAction { /** !#en Implementation of ease motion. !#zh 缓动运动。 @example action.easeing(cc.easeIn(3.0));,```js action.easeing(cc.easeIn(3.0)); ``` */ easing(easeObj : any) : ActionInterval; /** !#en Repeats an action a number of times. To repeat an action forever use the CCRepeatForever action. !#zh 重复动作可以按一定次数重复一个动作,使用 RepeatForever 动作来永远重复一个动作。 */ repeat(times : void) : ActionInterval; /** !#en Repeats an action for ever.
To repeat the an action for a limited number of times use the Repeat action.
!#zh 永远地重复一个动作,有限次数内重复一个动作请使用 Repeat 动作。 */ repeatForever() : ActionInterval; } /** !#en cc.MotionStreak manages a Ribbon based on it's motion in absolute space.
You construct it with a fadeTime, minimum segment size, texture path, texture
length and color. The fadeTime controls how long it takes each vertex in
the streak to fade out, the minimum segment size it how many pixels the
streak will move before adding a new ribbon segment, and the texture
length is the how many pixels the texture is stretched across. The texture
is vertically aligned along the streak segment. !#zh 运动轨迹,用于游戏对象的运动轨迹上实现拖尾渐隐效果。 */ export class MotionStreak extends Component { /** !#en !#zh 在编辑器模式下预览拖尾效果。 */ preview : boolean; /** !#en The fade time to fade. !#zh 拖尾的渐隐时间,以秒为单位。 */ fadeTime : number; /** !#en The minimum segment size. !#zh 拖尾之间最小距离。 */ minSeg : number; /** !#en The stroke's width. !#zh 拖尾的宽度。 */ stroke : number; /** !#en The texture of the MotionStreak. !#zh 拖尾的贴图。 */ texture : Texture2D; /** !#en The color of the MotionStreak. !#zh 拖尾的颜色 */ color : Color; /** !#en The fast Mode. !#zh 是否启用了快速模式。当启用快速模式,新的点会被更快地添加,但精度较低。 */ fastMode : boolean; /** !#en Remove all living segments of the ribbon. !#zh 删除当前所有的拖尾片段。 @example ```js // stop particle system. myParticleSystem.stopSystem(); ``` */ reset() : void; } /** !#en cc.ActionManager is a class that can manage actions.
Normally you won't need to use this class directly. 99% of the cases you will use the CCNode interface, which uses this class's singleton object. But there are some cases where you might need to use this class.
Examples:
- When you want to run an action where the target is different from a CCNode.
- When you want to pause / resume the actions
!#zh cc.ActionManager 是可以管理动作的单例类。
通常你并不需要直接使用这个类,99%的情况您将使用 CCNode 的接口。
但也有一些情况下,您可能需要使用这个类。
例如: - 当你想要运行一个动作,但目标不是 CCNode 类型时。
- 当你想要暂停/恢复动作时。
*/ export class ActionManager { /** !#en Adds an action with a target.
If the target is already present, then the action will be added to the existing target. If the target is not present, a new instance of this target will be created either paused or not, and the action will be added to the newly created target. When the target is paused, the queued actions won't be 'ticked'. !#zh 增加一个动作,同时还需要提供动作的目标对象,目标对象是否暂停作为参数。
如果目标已存在,动作将会被直接添加到现有的节点中。
如果目标不存在,将为这一目标创建一个新的实例,并将动作添加进去。
当目标状态的 paused 为 true,动作将不会被执行 */ addAction(action : Action, target : Node, paused : boolean) : void; /** !#en Removes all actions from all the targets. !#zh 移除所有对象的所有动作。 */ removeAllActions() : void; /** !#en Removes all actions from a certain target.
All the actions that belongs to the target will be removed. !#zh 移除指定对象上的所有动作。
属于该目标的所有的动作将被删除。 */ removeAllActionsFromTarget(target : any, forceDelete : boolean) : void; /** !#en Removes an action given an action reference. !#zh 移除指定的动作。 */ removeAction(action : Action) : void; /** !#en Removes an action given its tag and the target. !#zh 删除指定对象下特定标签的一个动作,将删除首个匹配到的动作。 */ removeActionByTag(tag : number, target : any) : void; /** !#en Gets an action given its tag an a target. !#zh 通过目标对象和标签获取一个动作。 */ getActionByTag(tag : number, target : any) : Action; /** !#en Returns the numbers of actions that are running in a certain target.
Composable actions are counted as 1 action.
Example:
- If you are running 1 Sequence of 7 actions, it will return 1.
- If you are running 7 Sequences of 2 actions, it will return 7. !#zh 返回指定对象下所有正在运行的动作数量。
组合动作被算作一个动作。
例如:
- 如果您正在运行 7 个动作组成的序列动作(Sequence),这个函数将返回 1。
- 如果你正在运行 2 个序列动作(Sequence)和 5 个普通动作,这个函数将返回 7。
*/ numberOfRunningActionsInTarget(target : any) : number; /** !#en Pauses the target: all running actions and newly added actions will be paused. !#zh 暂停指定对象:所有正在运行的动作和新添加的动作都将会暂停。 */ pauseTarget(target : any) : void; /** !#en Resumes the target. All queued actions will be resumed. !#zh 让指定目标恢复运行。在执行序列中所有被暂停的动作将重新恢复运行。 */ resumeTarget(target : any) : void; /** !#en Pauses all running actions, returning a list of targets whose actions were paused. !#zh 暂停所有正在运行的动作,返回一个包含了那些动作被暂停了的目标对象的列表。 */ pauseAllRunningActions() : any[]; /** !#en Resume a set of targets (convenience function to reverse a pauseAllRunningActions or pauseTargets call). !#zh 让一组指定对象恢复运行(用来逆转 pauseAllRunningActions 效果的便捷函数)。 */ resumeTargets(targetsToResume : any[]) : void; /** !#en Pause a set of targets. !#zh 暂停一组指定对象。 */ pauseTargets(targetsToPause : any[]) : void; /** !#en purges the shared action manager. It releases the retained instance.
because it uses this, so it can not be static. !#zh 清除共用的动作管理器。它释放了持有的实例。
因为它使用 this,因此它不能是静态的。 */ purgeSharedManager() : void; /** !#en The ActionManager update。 !#zh ActionManager 主循环。 @param dt delta time in seconds */ update(dt : number) : void; } /** !#en

ATTENTION: USE cc.director INSTEAD OF cc.Director.
cc.director is a singleton object which manage your game's logic flow.
Since the cc.director is a singleton, you don't need to call any constructor or create functions,
the standard way to use it is by calling:
- cc.director.methodName();
It creates and handle the main Window and manages how and when to execute the Scenes.

The cc.director is also responsible for:
- initializing the OpenGL context
- setting the OpenGL pixel format (default on is RGB565)
- setting the OpenGL buffer depth (default on is 0-bit)
- setting the color for clear screen (default one is BLACK)
- setting the projection (default one is 3D)
- setting the orientation (default one is Portrait)


The cc.director also sets the default OpenGL context:
- GL_TEXTURE_2D is enabled
- GL_VERTEX_ARRAY is enabled
- GL_COLOR_ARRAY is enabled
- GL_TEXTURE_COORD_ARRAY is enabled

cc.director also synchronizes timers with the refresh rate of the display.
Features and Limitations:
- Scheduled timers & drawing are synchronizes with the refresh rate of the display
- Only supports animation intervals of 1/60 1/30 & 1/15

!#zh

注意:用 cc.director 代替 cc.Director。
cc.director 一个管理你的游戏的逻辑流程的单例对象。
由于 cc.director 是一个单例,你不需要调用任何构造函数或创建函数,
使用它的标准方法是通过调用:
- cc.director.methodName();
它创建和处理主窗口并且管理什么时候执行场景。

cc.director 还负责:
- 初始化 OpenGL 环境。
- 设置OpenGL像素格式。(默认是 RGB565)
- 设置OpenGL缓冲区深度 (默认是 0-bit)
- 设置空白场景的颜色 (默认是 黑色)
- 设置投影 (默认是 3D)
- 设置方向 (默认是 Portrait)

cc.director 设置了 OpenGL 默认环境
- GL_TEXTURE_2D 启用。
- GL_VERTEX_ARRAY 启用。
- GL_COLOR_ARRAY 启用。
- GL_TEXTURE_COORD_ARRAY 启用。

cc.director 也同步定时器与显示器的刷新速率。
特点和局限性:
- 将计时器 & 渲染与显示器的刷新频率同步。
- 只支持动画的间隔 1/60 1/30 & 1/15。

*/ export class Director { /** !#en Converts an OpenGL coordinate to a view coordinate
Useful to convert node points to window points for calls such as glScissor
Implementation can be found in CCDirectorWebGL. !#zh 将触摸点的 WebGL View 坐标转换为屏幕坐标。 */ convertToUI(glPoint : Vec2) : Vec2; /** !#en Returns the size of the WebGL view in points.
It takes into account any possible rotation (device orientation) of the window. !#zh 获取视图的大小,以点为单位。 */ getWinSize() : Size; /** !#en Returns the size of the OpenGL view in pixels.
It takes into account any possible rotation (device orientation) of the window.
On Mac winSize and winSizeInPixels return the same value. !#zh 获取视图大小,以像素为单位。 */ getWinSizeInPixels() : Size; /** !#en Returns the visible size of the running scene. !#zh 获取运行场景的可见大小。 */ getVisibleSize() : Size; /** !#en Returns the visible origin of the running scene. !#zh 获取视图在游戏内容中的坐标原点。 */ getVisibleOrigin() : Vec2; /** !#en Pause the director's ticker. !#zh 暂停正在运行的场景,该暂停只会停止 Scheduler,但是不会停止渲染和 UI 响应。 */ pause() : void; /** !#en Run a scene. Replaces the running scene with a new one or enter the first scene.
The new scene will be launched immediately. !#zh 立刻切换指定场景。 @param scene The need run scene. @param onBeforeLoadScene The function invoked at the scene before loading. @param onLaunched The function invoked at the scene after launch. */ runSceneImmediate(scene : Scene, onBeforeLoadScene? : Function, onLaunched? : Function) : void; /** !#en Run a scene. Replaces the running scene with a new one or enter the first scene. The new scene will be launched at the end of the current frame. !#zh 运行指定场景。 @param scene The need run scene. @param onBeforeLoadScene The function invoked at the scene before loading. @param onLaunched The function invoked at the scene after launch. */ runScene(scene : Scene, onBeforeLoadScene? : Function, onLaunched? : Function) : void; /** !#en Loads the scene by its name. !#zh 通过场景名称进行加载场景。 @param sceneName The name of the scene to load. @param onLaunched callback, will be called after scene launched. */ loadScene(sceneName : string, onLaunched? : Function) : boolean; /** !#en Preloads the scene to reduces loading time. You can call this method at any time you want. After calling this method, you still need to launch the scene by `cc.director.loadScene`. It will be totally fine to call `cc.director.loadScene` at any time even if the preloading is not yet finished, the scene will be launched after loaded automatically. !#zh 预加载场景,你可以在任何时候调用这个方法。 调用完后,你仍然需要通过 `cc.director.loadScene` 来启动场景,因为这个方法不会执行场景加载操作。 就算预加载还没完成,你也可以直接调用 `cc.director.loadScene`,加载完成后场景就会启动。 @param sceneName The name of the scene to preload. @param onLoaded callback, will be called after scene loaded. */ preloadScene(sceneName : string, onLoaded: (error: Error) => void) : void; /** !#en Resume director after pause, if the current scene is not paused, nothing will happen. !#zh 恢复暂停场景,恢复 Scheduler,如果当前场景没有暂停将没任何事情发生。 */ resume() : void; /** !#en Enables or disables WebGL depth test.
Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js !#zh 启用/禁用深度测试(在 Canvas 渲染模式下不会生效)。 */ setDepthTest(on : boolean) : void; /** !#en set color for clear screen.
Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js !#zh 设置场景的默认擦除颜色(支持白色全透明,但不支持透明度为中间值)。 */ setClearColor(clearColor : Color) : void; /** !#en Sets an OpenGL projection.
Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js. !#zh 设置 OpenGL 投影。 */ setProjection(projection : number) : void; /** !#en Update the view port.
Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js. !#zh 设置视窗(请不要主动调用这个接口,除非你知道你在做什么)。 */ setViewport() : void; /** !#en Sets an OpenGL projection.
Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js. !#zh 获取 OpenGL 投影。 */ getProjection() : number; /** !#en Enables/disables OpenGL alpha blending.
Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js. !#zh 启用/禁用 透明度融合。 */ setAlphaBlending(on : boolean) : void; /** !#en Returns whether or not the replaced scene will receive the cleanup message.
If the new scene is pushed, then the old scene won't receive the "cleanup" message.
If the new scene replaces the old one, the it will receive the "cleanup" message. !#zh 更换场景时是否接收清理消息。
如果新场景是采用 push 方式进入的,那么旧的场景将不会接收到 “cleanup” 消息。
如果新场景取代旧的场景,它将会接收到 “cleanup” 消息。
*/ isSendCleanupToScene() : boolean; /** !#en Returns current logic Scene. !#zh 获取当前逻辑场景。 @example ```js // This will help you to get the Canvas node in scene cc.director.getScene().getChildByName('Canvas'); ``` */ getScene() : Scene; /** !#en Returns the FPS value. !#zh 获取单位帧执行时间。 */ getAnimationInterval() : number; /** !#en Returns whether or not to display the FPS informations. !#zh 获取是否显示 FPS 信息。 */ isDisplayStats() : boolean; /** !#en Sets whether display the FPS on the bottom-left corner. !#zh 设置是否在左下角显示 FPS。 */ setDisplayStats(displayStats : boolean) : void; /** !#en Returns seconds per frame. !#zh 获取实际记录的上一帧执行时间,可能与单位帧执行时间(AnimationInterval)有出入。 */ getSecondsPerFrame() : number; /** !#en Returns whether next delta time equals to zero. !#zh 返回下一个 “delta time” 是否等于零。 */ isNextDeltaTimeZero() : boolean; /** !#en Returns whether or not the Director is paused. !#zh 是否处于暂停状态。 */ isPaused() : boolean; /** !#en Returns how many frames were called since the director started. !#zh 获取 director 启动以来游戏运行的总帧数。 */ getTotalFrames() : number; /** !#en Returns the cc.Scheduler associated with this director. !#zh 获取和 director 相关联的 cc.Scheduler。 */ getScheduler() : Scheduler; /** !#en Sets the cc.Scheduler associated with this director. !#zh 设置和 director 相关联的 cc.Scheduler。 */ setScheduler(scheduler : Scheduler) : void; /** !#en Returns the cc.ActionManager associated with this director. !#zh 获取和 director 相关联的 cc.ActionManager(动作管理器)。 */ getActionManager() : ActionManager; /** !#en Sets the cc.ActionManager associated with this director. !#zh 设置和 director 相关联的 cc.ActionManager(动作管理器)。 */ setActionManager(actionManager : ActionManager) : void; /** Returns the cc.CollisionManager associated with this director. */ getCollisionManager() : CollisionManager; /** !#en Returns the delta time since last frame. !#zh 获取上一帧的 “delta time”。 */ getDeltaTime() : number; } /** !#en cc.game is the singleton object for game related functions. !#zh cc.game 是 Game 的实例,用来驱动整个游戏。 */ export class Game { /** !#en The outer frame of the game canvas, parent of cc.container. !#zh 游戏画布的外框,cc.container 的父类。 */ frame : any; /** !#en The container of game canvas, equals to cc.container. !#zh 游戏画布的容器。 */ container : any; /** !#en The canvas of the game, equals to cc._canvas. !#zh 游戏的画布。 */ canvas : any; /** !#en The current game configuration, including:
1. debugMode
"debugMode" possible values :
0 - No message will be printed.
1 - cc.error, cc.assert, cc.warn, cc.log will print in console.
2 - cc.error, cc.assert, cc.warn will print in console.
3 - cc.error, cc.assert will print in console.
4 - cc.error, cc.assert, cc.warn, cc.log will print on canvas, available only on web.
5 - cc.error, cc.assert, cc.warn will print on canvas, available only on web.
6 - cc.error, cc.assert will print on canvas, available only on web.
2. showFPS
Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide.
3. frameRate
"frameRate" set the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment.
4. id
"gameCanvas" sets the id of your canvas element on the web page, it's useful only on web.
5. renderMode
"renderMode" sets the renderer type, only useful on web :
0 - Automatically chosen by engine
1 - Forced to use canvas renderer
2 - Forced to use WebGL renderer, but this will be ignored on mobile browsers
6. scenes
"scenes" include available scenes in the current bundle.

Please DO NOT modify this object directly, it won't have any effect.
!#zh 当前的游戏配置,包括:
1. debugMode(debug 模式,但是在浏览器中这个选项会被忽略)
"debugMode" 各种设置选项的意义。
0 - 没有消息被打印出来。
1 - cc.error,cc.assert,cc.warn,cc.log 将打印在 console 中。
2 - cc.error,cc.assert,cc.warn 将打印在 console 中。
3 - cc.error,cc.assert 将打印在 console 中。
4 - cc.error,cc.assert,cc.warn,cc.log 将打印在 canvas 中(仅适用于 web 端)。
5 - cc.error,cc.assert,cc.warn 将打印在 canvas 中(仅适用于 web 端)。
6 - cc.error,cc.assert 将打印在 canvas 中(仅适用于 web 端)。
2. showFPS(显示 FPS)
当 showFPS 为 true 的时候界面的左下角将显示 fps 的信息,否则被隐藏。
3. frameRate (帧率)
“frameRate” 设置想要的帧率你的游戏,但真正的FPS取决于你的游戏实现和运行环境。
4. id
"gameCanvas" Web 页面上的 Canvas Element ID,仅适用于 web 端。
5. renderMode(渲染模式)
“renderMode” 设置渲染器类型,仅适用于 web 端:
0 - 通过引擎自动选择。
1 - 强制使用 canvas 渲染。 2 - 强制使用 WebGL 渲染,但是在部分 Android 浏览器中这个选项会被忽略。
6. scenes
“scenes” 当前包中可用场景。

注意:请不要直接修改这个对象,它不会有任何效果。 */ config : any; /** !#en Callback when the scripts of engine have been load. !#zh 当引擎完成启动后的回调函数。 */ onStart() : void; /** !#en Callback when game exits. !#zh 当游戏结束后的回调函数。 */ onStop() : void; /** !#en Set frameRate of game. !#zh 设置游戏帧率。 */ setFrameRate(frameRate : number) : void; /** !#en Run the game frame by frame. !#zh 执行一帧游戏循环。 */ step() : void; /** !#en Pause the game,pause main loop. !#zh 暂停游戏,暂停的是整个主循环。 */ pause() : void; /** !#en Resume the game from pause. !#zh 继续游戏,继续的是整个主循环。 */ resume() : void; /** !#en Check whether the game is paused. !#zh 判断游戏是否暂停。 */ isPaused() : boolean; /** !#en Restart game. !#zh 重新开始游戏 */ restart() : void; /** !#en Prepare game. !#zh 准备引擎,请不要直接调用这个函数。 */ prepare(cb : Function) : void; /** !#en Run game with configuration object and onStart function. !#zh 运行游戏,并且指定引擎配置和 onStart 的回调。 @param config Pass configuration object or onStart function @param onStart function to be executed after game initialized */ run(config? : any|Function, onStart? : Function) : void; /** !#en Add a persistent root node to the game, the persistent node won't be destroyed during scene transition.
The target node must be placed in the root level of hierarchy, otherwise this API won't have any effect. !#zh 声明常驻根节点,该节点不会被在场景切换中被销毁。
目标节点必须位于为层级的根节点,否则无效。 @param node The node to be made persistent */ addPersistRootNode(node : Node) : void; /** !#en Remove a persistent root node. !#zh 取消常驻根节点。 @param node The node to be removed from persistent node list */ removePersistRootNode(node : Node) : void; /** !#en Check whether the node is a persistent root node. !#zh 检查节点是否是常驻根节点。 @param node The node to be checked */ isPersistRootNode(node : Node) : boolean; } /** !#en Class of all entities in Cocos Creator scenes.
Node also inherits from {{#crossLink "EventTarget"}}Event Target{{/crossLink}}, it permits Node to dispatch events. For events supported by Node, please refer to {{#crossLink "Node.EventType"}}{{/crossLink}} !#zh Cocos Creator 场景中的所有节点类。节点也继承了 {{#crossLink "EventTarget"}}EventTarget{{/crossLink}},它允许节点发送事件。
支持的节点事件,请参阅 {{#crossLink "Node.EventType"}}{{/crossLink}}。 */ export class Node extends _BaseNode { /** !#en The local active state of this node.
Note that a Node may be inactive because a parent is not active, even if this returns true.
Use {{#crossLink "Node/activeInHierarchy:property"}}{{/crossLink}} if you want to check if the Node is actually treated as active in the scene. !#zh 当前节点的自身激活状态。
值得注意的是,一个节点的父节点如果不被激活,那么即使它自身设为激活,它仍然无法激活。
如果你想检查节点在场景中实际的激活状态可以使用 {{#crossLink "Node/activeInHierarchy:property"}}{{/crossLink}}。 */ active : boolean; /** !#en Indicates whether this node is active in the scene. !#zh 表示此节点是否在场景中激活。 */ activeInHierarchy : boolean; /** !#en Group index of node.
Which Group this node belongs to will resolve that this node's collision components can collide with which other collision componentns.
!#zh 节点的分组索引。
节点的分组将关系到节点的碰撞组件可以与哪些碰撞组件相碰撞。
*/ groupIndex : Integer; /** !#en Group of node.
Which Group this node belongs to will resolve that this node's collision components can collide with which other collision componentns.
!#zh 节点的分组。
节点的分组将关系到节点的碰撞组件可以与哪些碰撞组件相碰撞。
*/ group : string; /** !#en Returns the component of supplied type if the node has one attached, null if it doesn't.
You can also get component in the node by passing in the name of the script. !#zh 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
传入参数也可以是脚本的名称。 @example ```js // get sprite component. var sprite = node.getComponent(cc.Sprite); // get custom test calss. var test = node.getComponent("Test"); ``` */ getComponent(typeOrClassName : Function|string) : Component; /** !#en Returns all components of supplied type in the node. !#zh 返回节点上指定类型的所有组件。 @example ```js var sprites = node.getComponents(cc.Sprite); var tests = node.getComponents("Test"); ``` */ getComponents(typeOrClassName : Function|string) : Component[]; /** !#en Returns the component of supplied type in any of its children using depth first search. !#zh 递归查找所有子节点中第一个匹配指定类型的组件。 @example ```js var sprite = node.getComponentInChildren(cc.Sprite); var Test = node.getComponentInChildren("Test"); ``` */ getComponentInChildren(typeOrClassName : Function|string) : Component; /** !#en Returns all components of supplied type in any of its children. !#zh 递归查找所有子节点中指定类型的组件。 @example ```js var sprites = node.getComponentsInChildren(cc.Sprite); var tests = node.getComponentsInChildren("Test"); ``` */ getComponentsInChildren(typeOrClassName : Function|string) : Component[]; /** !#en Adds a component class to the node. You can also add component to node by passing in the name of the script. !#zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。 @param typeOrClassName The constructor or the class name of the component to add @example ```js var sprite = node.addComponent(cc.Sprite); var test = node.addComponent("Test"); ``` */ addComponent(typeOrClassName : Function|string) : Component; /** !#en Removes a component identified by the given name or removes the component object given. You can also use component.destroy() if you already have the reference. !#zh 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。 如果你已经获得组件引用,你也可以直接调用 component.destroy() @param component The need remove component. @example ```js node.removeComponent(cc.Sprite); var Test = require("Test"); node.removeComponent(Test); ``` */ removeComponent(component : string|Function|Component) : void; /** !#en Register a callback of a specific event type on Node.
Use this method to register touch or mouse event permit propagation based on scene graph, you can propagate the event to the parents or swallow it by calling stopPropagation on the event.
It's the recommended way to register touch/mouse event for Node, please do not use cc.eventManager directly for Node. !#zh 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的调用者。
同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。
推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。 @param type A string representing the event type to listen for. @param callback The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique). @param target The target to invoke the callback, can be null @param useCapture When set to true, the capture argument prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. @example ```js // add Node Touch Event node.on(cc.Node.EventType.TOUCH_START, callback, this.node); node.on(cc.Node.EventType.TOUCH_MOVE, callback, this.node); node.on(cc.Node.EventType.TOUCH_END, callback, this.node); node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this.node); ``` */ on(type : string, callback: (param: Event) => void, target? : any, useCapture : boolean) : Function; /** !#en Removes the callback previously registered with the same type, callback, target and or useCapture. This method is merely an alias to removeEventListener. !#zh 删除之前与同类型,回调,目标或 useCapture 注册的回调。 @param type A string representing the event type being removed. @param callback The callback to remove. @param target The target to invoke the callback, if it's not given, only callback without target will be removed @param useCapture Specifies whether the callback being removed was registered as a capturing callback or not. If not specified, useCapture defaults to false. If a callback was registered twice, one with capture and one without, each must be removed separately. Removal of a capturing callback does not affect a non-capturing version of the same listener, and vice versa. @example ```js // remove Node TOUCH_START Event. node.on(cc.Node.EventType.TOUCH_START, callback, this.node); node.off(cc.Node.EventType.TOUCH_START, callback, this.node); ``` */ off(type : string, callback : Function, target? : any, useCapture : boolean) : void; /** !#en Removes all callbacks previously registered with the same target. !#zh 移除目标上的所有注册事件。 @param target The target to be searched for all related callbacks @example ```js node.targetOff(target); ``` */ targetOff(target : any) : void; /** !#en Executes an action, and returns the action that is executed.
The node becomes the action's target. Refer to cc.Action's getTarget()
Calling runAction while the node is not active won't have any effect. !#zh 执行并返回该执行的动作。该节点将会变成动作的目标。
调用 runAction 时,节点自身处于不激活状态将不会有任何效果。 @example ```js var action = cc.scaleTo(0.2, 1, 0.6); node.runAction(action); ``` */ runAction(action : Action) : Action; /** !#en Stops and removes all actions from the running action list . !#zh 停止并且移除所有正在运行的动作列表。 @example ```js node.stopAllActions(); ``` */ stopAllActions() : void; /** !#en Stops and removes an action from the running action list. !#zh 停止并移除指定的动作。 @param action An action object to be removed. @example ```js var action = cc.scaleTo(0.2, 1, 0.6); node.stopAction(action); ``` */ stopAction(action : Action) : void; /** !#en Removes an action from the running action list by its tag. !#zh 停止并且移除指定标签的动作。 @param tag A tag that indicates the action to be removed. @example ```js node.stopAction(1); ``` */ stopActionByTag(tag : number) : void; /** !#en Returns an action from the running action list by its tag. !#zh 通过标签获取指定动作。 @example ```js var action = node.getActionByTag(1); ``` */ getActionByTag(tag : number) : Action; /** !#en Returns the numbers of actions that are running plus the ones that are schedule to run (actions in actionsToAdd and actions arrays).
Composable actions are counted as 1 action. Example:
If you are running 1 Sequence of 7 actions, it will return 1.
If you are running 7 Sequences of 2 actions, it will return 7.

!#zh 获取运行着的动作加上正在调度运行的动作的总数。
例如:
- 如果你正在运行 7 个动作中的 1 个 Sequence,它将返回 1。
- 如果你正在运行 2 个动作中的 7 个 Sequence,它将返回 7。
@example ```js var count = node.getNumberOfRunningActions(); cc.log("Running Action Count: " + count); ``` */ getNumberOfRunningActions() : number; } /** !#en cc.Scene is a subclass of cc.Node that is used only as an abstract concept.
cc.Scene and cc.Node are almost identical with the difference that users can not modify cc.Scene manually. !#zh cc.Scene 是 cc.Node 的子类,仅作为一个抽象的概念。
cc.Scene 和 cc.Node 有点不同,用户不应直接修改 cc.Scene。 */ export class Scene extends _BaseNode { } /** !#en Scheduler is responsible of triggering the scheduled callbacks.
You should not use NSTimer. Instead use this class.

There are 2 different types of callbacks (selectors):
- update callback: the 'update' callback will be called every frame. You can customize the priority.
- custom callback: A custom callback will be called every frame, or with a custom interval of time

The 'custom selectors' should be avoided when possible. It is faster, and consumes less memory to use the 'update callback'. * !#zh Scheduler 是负责触发回调函数的类。
通常情况下,建议使用 cc.director.getScheduler() 来获取系统定时器。
有两种不同类型的定时器:
- update 定时器:每一帧都会触发。您可以自定义优先级。
- 自定义定时器:自定义定时器可以每一帧或者自定义的时间间隔触发。
如果希望每帧都触发,应该使用 update 定时器,使用 update 定时器更快,而且消耗更少的内存。 */ export class Scheduler { /** !#en Modifies the time of all scheduled callbacks.
You can use this property to create a 'slow motion' or 'fast forward' effect.
Default is 1.0. To create a 'slow motion' effect, use values below 1.0.
To create a 'fast forward' effect, use values higher than 1.0.
Note:It will affect EVERY scheduled selector / action. !#zh 设置时间间隔的缩放比例。
您可以使用这个方法来创建一个 “slow motion(慢动作)” 或 “fast forward(快进)” 的效果。
默认是 1.0。要创建一个 “slow motion(慢动作)” 效果,使用值低于 1.0。
要使用 “fast forward(快进)” 效果,使用值大于 1.0。
注意:它影响该 Scheduler 下管理的所有定时器。 */ setTimeScale(timeScale : number) : void; /** !#en Returns time scale of scheduler. !#zh 获取时间间隔的缩放比例。 */ getTimeScale() : number; /** !#en 'update' the scheduler. (You should NEVER call this method, unless you know what you are doing.) !#zh update 调度函数。(不应该直接调用这个方法,除非完全了解这么做的结果) @param dt delta time */ update(dt : number) : void; /** !#en

The scheduled method will be called every 'interval' seconds.
If paused is YES, then it won't be called until it is resumed.
If 'interval' is 0, it will be called every frame, but if so, it recommended to use 'scheduleUpdateForTarget:' instead.
If the callback function is already scheduled, then only the interval parameter will be updated without re-scheduling it again.
repeat let the action be repeated repeat + 1 times, use cc.macro.REPEAT_FOREVER to let the action run continuously
delay is the amount of time the action will wait before it'll start

!#zh 指定回调函数,调用对象等信息来添加一个新的定时器。
当时间间隔达到指定值时,设置的回调函数将会被调用。
如果 paused 值为 true,那么直到 resume 被调用才开始计时。
如果 interval 值为 0,那么回调函数每一帧都会被调用,但如果是这样, 建议使用 scheduleUpdateForTarget 代替。
如果回调函数已经被定时器使用,那么只会更新之前定时器的时间间隔参数,不会设置新的定时器。
repeat 值可以让定时器触发 repeat + 1 次,使用 cc.macro.REPEAT_FOREVER 可以让定时器一直循环触发。
delay 值指定延迟时间,定时器会在延迟指定的时间之后开始计时。 @example ```js //register a schedule to scheduler var scheduler = cc.director.getScheduler(); scheduler.scheduleCallbackForTarget(this, function, interval, repeat, delay, !this._isRunning); ``` */ scheduleCallbackForTarget(target : any, callback_fn : Function, interval : number, repeat : number, delay : number, paused : boolean) : void; /** !#en The schedule !#zh 定时器 @example ```js //register a schedule to scheduler cc.director.getScheduler().schedule(callback, this, interval, !this._isRunning); ``` */ schedule(callback : Function, target : any, interval : number, repeat : number, delay : number, paused : boolean) : void; /** !#en Schedules the update callback for a given target, the callback will be invoked every frame after schedule started. !#zh 使用指定的优先级为指定的对象设置 update 定时器。 update 定时器每一帧都会被触发。优先级的值越低,定时器被触发的越早。 */ scheduleUpdate(target : any, priority : number, paused : boolean, updateFunc : Function) : void; /** !#en Unschedules a callback for a callback and a given target. If you want to unschedule the "update", use `unscheduleUpdate()` !#zh 根据指定的回调函数和调用对象。 如果需要取消 update 定时器,请使用 unscheduleUpdate()。 @param callback The callback to be unscheduled @param target The target bound to the callback. */ unschedule(callback : Function, target : any) : void; /** !#en Unschedules the update callback for a given target. !#zh 取消指定对象的 update 定时器。 @param target The target to be unscheduled. */ unscheduleUpdate(target : any) : void; /** !#en Unschedules all scheduled callbacks for a given target. This also includes the "update" callback. !#zh 取消指定对象的所有定时器,包括 update 定时器。 @param target The target to be unscheduled. */ unscheduleAllForTarget(target : any) : void; /** !#en Unschedules all scheduled callbacks from all targets including the system callbacks.
You should NEVER call this method, unless you know what you are doing. !#zh 取消所有对象的所有定时器,包括系统定时器。
不用调用此函数,除非你确定你在做什么。 */ unscheduleAll() : void; /** !#en Unschedules all callbacks from all targets with a minimum priority.
You should only call this with `PRIORITY_NON_SYSTEM_MIN` or higher. !#zh 取消所有优先级的值大于指定优先级的定时器。
你应该只取消优先级的值大于 PRIORITY_NON_SYSTEM_MIN 的定时器。 @param minPriority The minimum priority of selector to be unscheduled. Which means, all selectors which priority is higher than minPriority will be unscheduled. */ unscheduleAllWithMinPriority(minPriority : number) : void; /** !#en Checks whether a callback for a given target is scheduled. !#zh 检查指定的回调函数和回调对象组合是否存在定时器。 @param callback The callback to check. @param target The target of the callback. */ isScheduled(callback : Function, target : any) : boolean; /** !#en Pause all selectors from all targets.
You should NEVER call this method, unless you know what you are doing. !#zh 暂停所有对象的所有定时器。
不要调用这个方法,除非你知道你正在做什么。 */ pauseAllTargets() : void; /** !#en Pause all selectors from all targets with a minimum priority.
You should only call this with kCCPriorityNonSystemMin or higher. !#zh 暂停所有优先级的值大于指定优先级的定时器。
你应该只暂停优先级的值大于 PRIORITY_NON_SYSTEM_MIN 的定时器。 */ pauseAllTargetsWithMinPriority(minPriority : number) : void; /** !#en Resume selectors on a set of targets.
This can be useful for undoing a call to pauseAllCallbacks. !#zh 恢复指定数组中所有对象的定时器。
这个函数是 pauseAllCallbacks 的逆操作。 */ resumeTargets(targetsToResume : any[]) : void; /** !#en Pauses the target.
All scheduled selectors/update for a given target won't be 'ticked' until the target is resumed.
If the target is not present, nothing happens. !#zh 暂停指定对象的定时器。
指定对象的所有定时器都会被暂停。
如果指定的对象没有定时器,什么也不会发生。 */ pauseTarget(target : any) : void; /** !#en Resumes the target.
The 'target' will be unpaused, so all schedule selectors/update will be 'ticked' again.
If the target is not present, nothing happens. !#zh 恢复指定对象的所有定时器。
指定对象的所有定时器将继续工作。
如果指定的对象没有定时器,什么也不会发生。 */ resumeTarget(target : any) : void; /** !#en Returns whether or not the target is paused. !#zh 返回指定对象的定时器是否暂停了。 */ isTargetPaused(target : any) : boolean; /** !#en Schedules the 'update' callback_fn for a given target with a given priority.
The 'update' callback_fn will be called every frame.
The lower the priority, the earlier it is called. !#zh 为指定对象设置 update 定时器。
update 定时器每一帧都会被调用。
优先级的值越低,越早被调用。 @example ```js //register this object to scheduler var scheduler = cc.director.getScheduler(); scheduler.scheduleUpdateForTarget(this, priority, !this._isRunning ); ``` */ scheduleUpdateForTarget(target : any, priority : number, paused : boolean) : void; /** !#en Unschedule a callback function for a given target.
If you want to unschedule the "update", use unscheduleUpdateForTarget. !#zh 根据指定的回调函数和调用对象对象取消相应的定时器。
如果需要取消 update 定时器,请使用 unscheduleUpdateForTarget()。 @param callback callback[Function] or key[String] @example ```js //unschedule a callback of target var scheduler = cc.director.getScheduler(); scheduler.unscheduleCallbackForTarget(this, callback); ``` */ unscheduleCallbackForTarget(target : any, callback : Function) : void; /** !#en Unschedules the update callback function for a given target. !#zh 取消指定对象的所有定时器。 @example ```js //unschedules the "update" method. var scheduler = cc.director.getScheduler(); scheduler.unscheduleUpdateForTarget(this); ``` */ unscheduleUpdateForTarget(target : any) : void; /** !#en Unschedules all function callbacks for a given target.
This also includes the "update" callback function. !#zh 取消指定对象的所有定时器,包括 update 定时器。 */ unscheduleAllCallbacksForTarget(target : any) : void; /** !#en Unschedules all function callbacks from all targets.
You should NEVER call this method, unless you know what you are doing. !#zh 取消所有对象的所有定时器。
不要调用这个方法,除非你知道你正在做什么。 */ unscheduleAllCallbacks() : void; /** !#en Unschedules all function callbacks from all targets with a minimum priority.
You should only call this with kCCPriorityNonSystemMin or higher. !#zh 取消所有优先级的值大于指定优先级的所有对象的所有定时器。
你应该只暂停优先级的值大于 PRIORITY_NON_SYSTEM_MIN 的定时器。 */ unscheduleAllCallbacksWithMinPriority(minPriority : number) : void; /** !#en Priority level reserved for system services. !#zh 系统服务的优先级。 */ PRIORITY_SYSTEM : number; /** !#en Minimum priority level for user scheduling. !#zh 用户调度最低优先级。 */ PRIORITY_NON_SYSTEM : number; } /** Particle System base class.
Attributes of a Particle System:
- emmision rate of the particles
- Gravity Mode (Mode A):
- gravity
- direction
- speed +- variance
- tangential acceleration +- variance
- radial acceleration +- variance
- Radius Mode (Mode B):
- startRadius +- variance
- endRadius +- variance
- rotate +- variance
- Properties common to all modes:
- life +- life variance
- start spin +- variance
- end spin +- variance
- start size +- variance
- end size +- variance
- start color +- variance
- end color +- variance
- life +- variance
- blending function
- texture

cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).
'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d,
cocos2d uses a another approach, but the results are almost identical.
cocos2d supports all the variables used by Particle Designer plus a bit more:
- spinning particles (supported when using ParticleSystem)
- tangential acceleration (Gravity mode)
- radial acceleration (Gravity mode)
- radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only)
It is possible to customize any of the above mentioned properties in runtime. Example:
*/ export class ParticleSystem extends cc._RendererUnderSG { /** !#en Play particle in edit mode. !#zh 在编辑器模式下预览粒子,启用后选中粒子时,粒子将自动播放。 */ preview : boolean; /** !#en If set custom to true, then use custom properties insteadof read particle file. !#zh 是否自定义粒子属性。 */ custom : boolean; /** !#en The plist file. !#zh plist 格式的粒子配置文件。 */ file : string; /** . */ texture : Texture2D; /** !#en Current quantity of particles that are being simulated. !#zh 当前播放的粒子数量。 */ particleCount : number; /** !#en Specify the source Blend Factor. !#zh 指定原图混合模式。 */ srcBlendFactor : BlendFactor; /** !#en Specify the destination Blend Factor. !#zh 指定目标的混合模式。 */ dstBlendFactor : BlendFactor; /** !#en If set to true, the particle system will automatically start playing on onLoad. !#zh 如果设置为 true 运行时会自动发射粒子。 */ playOnLoad : boolean; /** !#en Indicate whether the owner node will be auto-removed when it has no particles left. !#zh 粒子播放完毕后自动销毁所在的节点。 */ autoRemoveOnFinish : boolean; /** !#en Indicate whether the particle system is activated. !#zh 是否激活粒子。 */ active : boolean; /** !#en Maximum particles of the system. !#zh 粒子最大数量。 */ totalParticles : number; /** !#en How many seconds the emitter wil run. -1 means 'forever'. !#zh 发射器生存时间,单位秒,-1表示持续发射。 */ duration : number; /** !#en Emission rate of the particles. !#zh 每秒发射的粒子数目。 */ emissionRate : number; /** !#en Life of each particle setter. !#zh 粒子的运行时间。 */ life : number; /** !#en Variation of life. !#zh 粒子的运行时间变化范围。 */ lifeVar : number; /** !#en Start color of each particle. !#zh 粒子初始颜色。 */ startColor : Color; /** !#en Variation of the start color. !#zh 粒子初始颜色变化范围。 */ startColorVar : Color; /** !#en Ending color of each particle. !#zh 粒子结束颜色。 */ endColor : Color; /** !#en Variation of the end color. !#zh 粒子结束颜色变化范围。 */ endColorVar : Color; /** !#en Angle of each particle setter. !#zh 粒子角度。 */ angle : number; /** !#en Variation of angle of each particle setter. !#zh 粒子角度变化范围。 */ angleVar : number; /** !#en Start size in pixels of each particle. !#zh 粒子的初始大小。 */ startSize : number; /** !#en Variation of start size in pixels. !#zh 粒子初始大小的变化范围。 */ startSizeVar : number; /** !#en End size in pixels of each particle. !#zh 粒子结束时的大小。 */ endSize : number; /** !#en Variation of end size in pixels. !#zh 粒子结束大小的变化范围。 */ endSizeVar : number; /** !#en Start angle of each particle. !#zh 粒子开始自旋角度。 */ startSpin : number; /** !#en Variation of start angle. !#zh 粒子开始自旋角度变化范围。 */ startSpinVar : number; /** !#en End angle of each particle. !#zh 粒子结束自旋角度。 */ endSpin : number; /** !#en Variation of end angle. !#zh 粒子结束自旋角度变化范围。 */ endSpinVar : number; /** !#en Source position of the emitter. !#zh 发射器位置。 */ sourcePos : Vec2; /** !#en Variation of source position. !#zh 发射器位置的变化范围。(横向和纵向) */ posVar : Vec2; /** !#en Particles movement type. !#zh 粒子位置类型。 */ positionType : ParticleSystem.PositionType; /** !#en Particles emitter modes. !#zh 发射器类型。 */ emitterMode : ParticleSystem.EmitterMode; /** !#en Gravity of the emitter. !#zh 重力。 */ gravity : Vec2; /** !#en Speed of the emitter. !#zh 速度。 */ speed : number; /** !#en Variation of the speed. !#zh 速度变化范围。 */ speedVar : number; /** !#en Tangential acceleration of each particle. Only available in 'Gravity' mode. !#zh 每个粒子的切向加速度,即垂直于重力方向的加速度,只有在重力模式下可用。 */ tangentialAccel : number; /** !#en Variation of the tangential acceleration. !#zh 每个粒子的切向加速度变化范围。 */ tangentialAccelVar : number; /** !#en Acceleration of each particle. Only available in 'Gravity' mode. !#zh 粒子径向加速度,即平行于重力方向的加速度,只有在重力模式下可用。 */ radialAccel : number; /** !#en Variation of the radial acceleration. !#zh 粒子径向加速度变化范围。 */ radialAccelVar : number; /** !#en Indicate whether the rotation of each particle equals to its direction. Only available in 'Gravity' mode. !#zh 每个粒子的旋转是否等于其方向,只有在重力模式下可用。 */ rotationIsDir : boolean; /** !#en Starting radius of the particles. Only available in 'Radius' mode. !#zh 初始半径,表示粒子出生时相对发射器的距离,只有在半径模式下可用。 */ startRadius : number; /** !#en Variation of the starting radius. !#zh 初始半径变化范围。 */ startRadiusVar : number; /** !#en Ending radius of the particles. Only available in 'Radius' mode. !#zh 结束半径,只有在半径模式下可用。 */ endRadius : number; /** !#en Variation of the ending radius. !#zh 结束半径变化范围。 */ endRadiusVar : number; /** !#en Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode. !#zh 粒子每秒围绕起始点的旋转角度,只有在半径模式下可用。 */ rotatePerS : number; /** !#en Variation of the degress to rotate a particle around the source pos per second. !#zh 粒子每秒围绕起始点的旋转角度变化范围。 */ rotatePerSVar : number; /** !#en The Particle emitter lives forever. !#zh 表示发射器永久存在 */ DURATION_INFINITY : number; /** !#en The starting size of the particle is equal to the ending size. !#zh 表示粒子的起始大小等于结束大小。 */ START_SIZE_EQUAL_TO_END_SIZE : number; /** !#en The starting radius of the particle is equal to the ending radius. !#zh 表示粒子的起始半径等于结束半径。 */ START_RADIUS_EQUAL_TO_END_RADIUS : number; /** !#en Add a particle to the emitter. !#zh 添加一个粒子到发射器中。 */ addParticle() : boolean; /** !#en Stop emitting particles. Running particles will continue to run until they die. !#zh 停止发射器发射粒子,发射出去的粒子将继续运行,直至粒子生命结束。 @example ```js // stop particle system. myParticleSystem.stopSystem(); ``` */ stopSystem() : void; /** !#en Kill all living particles. !#zh 杀死所有存在的粒子,然后重新启动粒子发射器。 @example ```js // play particle system. myParticleSystem.resetSystem(); ``` */ resetSystem() : void; /** !#en Whether or not the system is full. !#zh 发射器中粒子是否大于等于设置的总粒子数量。 */ isFull() : boolean; /** !#en

Sets a new CCSpriteFrame as particle.
WARNING: this method is experimental. Use setTextureWithRect instead.

!#zh

设置一个新的精灵帧为粒子。
警告:这个函数只是试验,请使用 setTextureWithRect 实现。

*/ setDisplayFrame(spriteFrame : SpriteFrame) : void; /** !#en Sets a new texture with a rect. The rect is in texture position and size. !#zh 设置一张新贴图和关联的矩形。 */ setTextureWithRect(texture : Texture2D, rect : Rect) : void; } /** !#en Render the TMX layer. !#zh 渲染 TMX layer。 */ export class TiledLayer extends _SGComponent { /** !#en Gets the layer name. !#zh 获取层的名称。 @example ```js var layerName = tiledLayer.getLayerName(); cc.log(layerName); ``` */ getLayerName() : string; /** !#en Set the layer name. !#zh 设置层的名称 @example ```js tiledLayer.setLayerName("New Layer"); ``` */ SetLayerName(layerName : string) : void; /** !#en Return the value for the specific property name. !#zh 获取指定属性名的值。 @example ```js var property = tiledLayer.getProperty("info"); cc.log(property); ``` */ getProperty(propertyName : string) : any; /** !#en Returns the position in pixels of a given tile coordinate. !#zh 获取指定 tile 的像素坐标。 @param pos position or x @example ```js var pos = tiledLayer.getPositionAt(cc.v2(0, 0)); cc.log("Pos: " + pos); var pos = tiledLayer.getPositionAt(0, 0); cc.log("Pos: " + pos); ``` */ getPositionAt(pos : Vec2|number, y? : number) : Vec2; /** !#en Removes a tile at given tile coordinate. !#zh 删除指定坐标上的 tile。 @param pos position or x @example ```js tiledLayer.removeTileAt(cc.v2(0, 0)); tiledLayer.removeTileAt(0, 0); ``` */ removeTileAt(pos : Vec2|number, y? : number) : void; /** !#en Sets the tile gid (gid = tile global id) at a given tile coordinate.
The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor . Tileset Mgr +1.
If a tile is already placed at that position, then it will be removed. !#zh 设置给定坐标的 tile 的 gid (gid = tile 全局 id), tile 的 GID 可以使用方法 “tileGIDAt” 来获得。
如果一个 tile 已经放在那个位置,那么它将被删除。 @param posOrX position or x @param flagsOrY flags or y @example ```js tiledLayer.setTileGID(1001, 10, 10, 1) ``` */ setTileGID(gid : number, posOrX : Vec2|number, flagsOrY : number, flags? : number) : void; /** !#en Returns the tile gid at a given tile coordinate.
if it returns 0, it means that the tile is empty.
This method requires the the tile map has not been previously released (eg. don't call layer.releaseMap())
!#zh 通过给定的 tile 坐标、flags(可选)返回 tile 的 GID.
如果它返回 0,则表示该 tile 为空。
该方法要求 tile 地图之前没有被释放过(如:没有调用过layer.releaseMap()). @param pos or x @example ```js var tileGid = tiledLayer.getTileGIDAt(0, 0); ``` */ getTileGIDAt(pos : Vec2|number, y? : number) : number; /** !#en Returns the tile (_ccsg.Sprite) at a given a tile coordinate.
The returned _ccsg.Sprite will be already added to the _ccsg.TMXLayer. Don't add it again.
The _ccsg.Sprite can be treated like any other _ccsg.Sprite: rotated, scaled, translated, opacity, color, etc.
You can remove either by calling:
- layer.removeChild(sprite, cleanup);
- or layer.removeTileAt(ccp(x,y)); !#zh 通过指定的 tile 坐标获取对应的 tile(Sprite)。 返回的 tile(Sprite) 应是已经添加到 TMXLayer,请不要重复添加。
这个 tile(Sprite) 如同其他的 Sprite 一样,可以旋转、缩放、翻转、透明化、设置颜色等。
你可以通过调用以下方法来对它进行删除:
1. layer.removeChild(sprite, cleanup);
2. 或 layer.removeTileAt(cc.v2(x,y)); @param pos or x @example ```js var title = tiledLayer.getTileAt(100, 100); cc.log(title); ``` */ getTileAt(pos : Vec2|number, y? : number) : _ccsg.Sprite; /** !#en Dealloc the map that contains the tile position from memory.
Unless you want to know at runtime the tiles positions, you can safely call this method.
If you are going to call layer.getTileGIDAt() then, don't release the map. !#zh 从内存中释放包含 tile 位置信息的地图。
除了在运行时想要知道 tiles 的位置信息外,你都可安全的调用此方法。
如果你之后还要调用 layer.tileGIDAt(), 请不要释放地图. @example ```js tiledLayer.releaseMap(); ``` */ releaseMap() : void; /** !#en Sets the untransformed size of the _ccsg.TMXLayer. !#zh 设置未转换的 layer 大小。 @param size The untransformed size of the _ccsg.TMXLayer or The untransformed size's width of the TMXLayer. @param height The untransformed size's height of the _ccsg.TMXLayer. @example ```js tiledLayer.setContentSize(100, 100); ``` */ setContentSize(size : Size|number, height? : number) : void; /** !#en Return texture of cc.SpriteBatchNode. !#zh 获取纹理。 @example ```js var texture = tiledLayer.getTexture(); cc.log("Texture: " + texture); ``` */ getTexture() : Texture2D; /** !#en Set the texture of cc.SpriteBatchNode. !#zh 设置纹理。 @example ```js tiledLayer.setTexture(texture); ``` */ setTexture(texture : Texture2D) : void; /** !#en Gets layer size. !#zh 获得层大小。 @example ```js var size = tiledLayer.getLayerSize(); cc.log("layer size: " + size); ``` */ getLayerSize() : Size; /** !#en Set layer size. !#zh 设置层大小。 @example ```js tiledLayer.setLayerSize(new cc.size(5, 5)); ``` */ setLayerSize(layerSize : Size) : void; /** !#en Size of the map's tile (could be different from the tile's size). !#zh 获取 tile 的大小( tile 的大小可能会有所不同)。 @example ```js var mapTileSize = tiledLayer.getMapTileSize(); cc.log("MapTile size: " + mapTileSize); ``` */ getMapTileSize() : Size; /** !#en Set the map tile size. !#zh 设置 tile 的大小。 @example ```js tiledLayer.setMapTileSize(new cc.size(10, 10)); ``` */ setMapTileSize(tileSize : Size) : void; /** !#en Pointer to the map of tiles. !#zh 获取地图 tiles。 @example ```js var tiles = tiledLayer.getTiles(); ``` */ getTiles() : any[]; /** !#en Pointer to the map of tiles. !#zh 设置地图 tiles @example ```js tiledLayer.setTiles(tiles); ``` */ setTiles(tiles : any[]) : void; /** !#en Tile set information for the layer. !#zh 获取 layer 的 Tileset 信息。 @example ```js var tileset = tiledLayer.getTileSet(); ``` */ getTileSet() : TMXTilesetInfo; /** !#en Tile set information for the layer. !#zh 设置 layer 的 Tileset 信息。 @example ```js tiledLayer.setTileSet(tileset); ``` */ setTileSet(tileset : TMXTilesetInfo) : void; /** !#en Layer orientation, which is the same as the map orientation. !#zh 获取 Layer 方向(同地图方向)。 @example ```js var orientation = tiledLayer.getLayerOrientation(); cc.log("Layer Orientation: " + orientation); ``` */ getLayerOrientation() : number; /** !#en Layer orientation, which is the same as the map orientation. !#zh 设置 Layer 方向(同地图方向)。 @example ```js tiledLayer.setLayerOrientation(TiledMap.Orientation.ORTHO); ``` */ setLayerOrientation(orientation : TiledMap.Orientation) : void; /** !#en properties from the layer. They can be added using Tiled. !#zh 获取 layer 的属性,可以使用 Tiled 编辑器添加属性。 @example ```js var properties = tiledLayer.getProperties(); cc.log("Properties: " + properties); ``` */ getProperties() : any[]; /** !#en properties from the layer. They can be added using Tiled. !#zh 设置层属性。 @example ```js tiledLayer.setLayerOrientation(properties); ``` */ setProperties(properties : any[]) : void; } /** !#en Renders a TMX Tile Map in the scene. !#zh 在场景中渲染一个 tmx 格式的 Tile Map。 */ export class TiledMap extends Component { /** !#en The TiledMap Asset. !#zh TiledMap 资源。 */ tmxAsset : cc.TiledMapAsset; /** !#en Gets the map size. !#zh 获取地图大小。 @example ```js var mapSize = tiledMap.getMapSize(); cc.log("Map Size: " + mapSize); ``` */ getMapSize() : Size; /** !#en Set the map size. !#zh 设置地图大小。 @example ```js tiledMap.setMapSize(new cc.size(960, 640)); ``` */ setMapSize(mapSize : Size) : void; /** !#en Gets the tile size. !#zh 获取地图背景中 tile 元素的大小。 @example ```js var tileSize = tiledMap.getTileSize(); cc.log("Tile Size: " + tileSize); ``` */ getTileSize() : Size; /** !#en Set the tile size. !#zh 设置地图背景中 tile 元素的大小。 @example ```js tiledMap.setTileSize(new cc.size(10, 10)); ``` */ setTileSize(tileSize : Size) : void; /** !#en map orientation. !#zh 获取地图方向。 @example ```js var mapOrientation = tiledMap.getMapOrientation(); cc.log("Map Orientation: " + mapOrientation); ``` */ getMapOrientation() : number; /** !#en map orientation. !#zh 设置地图方向。 @example ```js tiledMap.setMapOrientation(TiledMap.Orientation.ORTHO); ``` */ setMapOrientation(orientation : TiledMap.Orientation) : void; /** !#en object groups. !#zh 获取所有的对象层。 @example ```js var objGroups = titledMap.getObjectGroups(); for (var i = 0; i < objGroups.length; ++i) { cc.log("obj: " + objGroups[i]); } ``` */ getObjectGroups() : any[]; /** !#en object groups. !#zh 设置所有的对象层。 @example ```js titledMap.setObjectGroups(groups); ``` */ setObjectGroups(groups : any[]) : void; /** !#en Gets the map properties. !#zh 获取地图的属性。 @example ```js var properties = titledMap.getProperties(); for (var i = 0; i < properties.length; ++i) { cc.log("Properties: " + properties[i]); } ``` */ getProperties() : any[]; /** !#en Set the map properties. !#zh 设置地图的属性。 @example ```js titledMap.setProperties(properties); ``` */ setProperties(properties : any[]) : void; /** !#en Return All layers array. !#zh 返回包含所有 layer 的数组。 @example ```js var layers = titledMap.allLayers(); for (var i = 0; i < layers.length; ++i) { cc.log("Layers: " + layers[i]); } ``` */ allLayers() : Node[]; /** !#en return the cc.TiledLayer for the specific layer. !#zh 获取指定名称的 layer。 @example ```js var layer = titledMap.getLayer("Player"); cc.log(layer); ``` */ getLayer(layerName : string) : TiledLayer; /** !#en Return the TMXObjectGroup for the specific group. !#zh 获取指定的 TMXObjectGroup。 @example ```js var group = titledMap.getObjectGroup("Players"); cc.log("ObjectGroup: " + group); ``` */ getObjectGroup(groupName : string) : TMXObjectGroup; /** !#en Return the value for the specific property name. !#zh 通过属性名称,获取指定的属性。 @example ```js var property = titledMap.getProperty("info"); cc.log("Property: " + property); ``` */ getProperty(propertyName : string) : string; /** !#en Return properties dictionary for tile GID. !#zh 通过 GID ,获取指定的属性。 @example ```js var properties = titledMap.getPropertiesForGID(GID); cc.log("Properties: " + properties); ``` */ getPropertiesForGID(GID : number) : any; } /** !#en cc.NodePool is the cache pool designed for node type.
It can helps you to improve your game performance for objects which need frequent release and recreate operations
It's recommended to create cc.NodePool instances by node type, the type corresponds to node type in game design, not the class, for example, a prefab is a specific node type.
When you create a node pool, you can pass a Component which contains `unuse`, `reuse` functions to control the content of node.
Some common use case is :
1. Bullets in game (die very soon, massive creation and recreation, no side effect on other objects)
2. Blocks in candy crash (massive creation and recreation)
etc... !#zh cc.NodePool 是用于管理节点对象的对象缓存池。
它可以帮助您提高游戏性能,适用于优化对象的反复创建和销毁
建议为每种节点分别实例化一个缓冲池,这里的种类对应于游戏中的节点设计,一个 prefab 相当于一个种类的节点。
在创建缓冲池时,可以传入一个包含 unuse, reuse 函数的组件类型用于节点的回收和复用逻辑。
一些常见的用例是:
1.在游戏中的子弹(死亡很快,频繁创建,对其他对象无副作用)
2.糖果粉碎传奇中的木块(频繁创建)。 等等.... */ export class NodePool { /** @param poolHandlerComp The constructor or the class name of the component to control the unuse/reuse logic. */ constructor(poolHandlerComp : Function|string); /** !#en The pool handler component, it could be the class name or the constructor. !#zh 缓冲池处理组件,用于节点的回收和复用逻辑,这个属性可以是组件类名或组件的构造函数。 */ poolHandlerComp : Function|string; /** !#en The current available size in the pool !#zh 获取当前缓冲池的可用对象数量 */ size() : void; /** !#en Put a new Node into the pool. It will automatically remove the node from its parent without cleanup. It will also invoke unuse method of the poolHandlerComp if exist. !#zh 向缓冲池中存入一个不再需要的节点对象。 这个函数会自动将目标节点从父节点上移除,但是不会进行 cleanup 操作。 这个函数会调用 poolHandlerComp 的 unuse 函数,如果组件和函数都存在的话。 */ put() : void; /** !#en Get a obj from pool, if no available object in pool, null will be returned. This function will invoke the reuse function of poolHandlerComp if exist. !#zh 获取对象池中的对象,如果对象池没有可用对象,则返回空。 这个函数会调用 poolHandlerComp 的 reuse 函数,如果组件和函数都存在的话。 */ get() : any; } /** !#en Attention: In creator, it's strongly not recommended to use cc.pool to manager cc.Node. We provided {{#crossLink "NodePool"}}cc.NodePool{{/crossLink}} instead. cc.pool is a singleton object serves as an object cache pool.
It can helps you to improve your game performance for objects which need frequent release and recreate operations
!#zh 首先请注意,在 Creator 中我们强烈不建议使用 cc.pool 来管理 cc.Node 节点对象,请使用 {{#crossLink "NodePool"}}cc.NodePool{{/crossLink}} 代替 因为 cc.pool 是面向类来设计的,而 cc.Node 中使用 Component 来进行组合,它的类永远都一样,实际却千差万别。 cc.pool 是一个单例对象,用作为对象缓存池。
它可以帮助您提高游戏性能,适用于优化对象的反复创建和销毁
*/ export class pool { /** !#en Put the obj in pool. !#zh 加入对象到对象池中。 @param obj The need put in pool object. @example ```js --------------------------------- var sp = new _ccsg.Sprite("a.png"); this.addChild(sp); cc.pool.putInPool(sp); cc.pool.getFromPool(_ccsg.Sprite, "a.png"); ``` */ putInPool(obj : any) : void; /** !#en Check if this kind of obj has already in pool. !#zh 检查对象池中是否有指定对象的存在。 @param objClass The check object class. */ hasObject(objClass : any) : boolean; /** !#en Remove the obj if you want to delete it. !#zh 移除在对象池中指定的对象。 */ removeObject() : void; /** !#en Get the obj from pool. !#zh 获取对象池中的指定对象。 */ getFromPool() : any; /** !#en Remove all objs in pool and reset the pool. !#zh 移除对象池中的所有对象,并且重置对象池。 */ drainAllPools() : void; } /** !#en Base class for handling assets used in Fireball. This class can be instantiate. You may want to override:
- createNode
- cc.Object._serialize
- cc.Object._deserialize
!#zh 资源基类,该类可以被实例化。
您可能需要重写:
- createNode
- cc.Object._serialize
- cc.Object._deserialize
*/ export class Asset extends RawAsset { constructor(); /** !#en Returns the url of this asset's first raw file, if none of rawFile exists, it will returns an empty string. !#zh 返回该资源的原始文件的 URL,如果不支持 RAW 文件,它将返回一个空字符串。 */ rawUrl : string; /** !#en Returns the url of this asset's raw files, if none of rawFile exists, it will returns an empty array. !#zh 返回该资源的原文件的 URL 数组,如果不支持 RAW 文件,它将返回一个空数组。 */ rawUrls : String[]; /** !#en Create a new node using this asset in the scene.
If this type of asset dont have its corresponding node type, this method should be null. !#zh 使用该资产在场景中创建一个新节点。
如果这类资产没有相应的节点类型,该方法应该是空的。 */ createNode(callback: (error: string, node: any) => void) : void; } /** !#en Class for audio data handling. !#zh 音频资源类。 */ export class AudioClip extends RawAsset { constructor(); } /** !#en Class for BitmapFont handling. !#zh 位图字体资源类。 */ export class BitmapFont extends RawAsset { constructor(); } /** !#en Class for Font handling. !#zh 字体资源类。 */ export class Font extends RawAsset { constructor(); } /** !#en Class for prefab handling. !#zh 预制资源类。 */ export class Prefab extends Asset { constructor(); } /** !#en The base class for registering asset types. You may want to override: - createNode (static) !#zh 注册用的资源基类。
你可能要重写:
- createNode (static) */ export class RawAsset extends CCObject { /** !#en Create a new node in the scene.
If this type of asset dont have its corresponding node type, this method should be null. !#zh 在场景中创建一个新节点。
如果这类资源没有相应的节点类型,该方法应该是空的。 */ createNodeByInfo(Info : any, callback: (error: string, node: any) => void) : void; } /** !#en Class for scene handling. !#zh 场景资源类。 */ export class SceneAsset extends Asset { constructor(); } /** !#en Class for script handling. !#zh Script 资源类。 */ export class _Script extends Asset { constructor(); } /** !#en Class for JavaScript handling. !#zh JavaScript 资源类。 */ export class _JavaScript extends Asset { constructor(); } /** !#en Class for coffee script handling. !#zh CoffeeScript 资源类。 */ export class CoffeeScript extends Asset { constructor(); } /** !#en Class for sprite atlas handling. !#zh 精灵图集资源类。 */ export class SpriteAtlas extends RawAsset { constructor(); /** Returns the texture of the sprite atlas */ getTexture() : cc.Texture2D; /** Returns the sprite frame correspond to the given key in sprite atlas. */ getSpriteFrame(key : string) : cc.SpriteFrame; /** Returns the sprite frames in sprite atlas. */ getSpriteFrames() : [cc.SpriteFrame]; } /** !#en Class for TTFFont handling. !#zh TTF 字体资源类。 */ export class TTFFont extends Asset { constructor(); } /** !#en Class for text file. !#zh 文本资源类。 */ export class TextAsset extends Asset { constructor(); } /** !#en Box Collider. !#zh 包围盒碰撞组件 */ export class BoxCollider extends Component { /** !#en Position offset !#zh 位置偏移量 */ offset : Vec2; /** !#en Box size !#zh 包围盒大小 */ size : Size; } /** !#en Circle Collider. !#zh 圆形碰撞组件 */ export class CircleCollider extends Component { /** !#en Position offset !#zh 位置偏移量 */ offset : Vec2; /** !#en Circle radius !#zh 圆形半径 */ radius : number; } /** !#en Collider component base class. !#zh 碰撞组件基类 */ export class Collider extends Component { /** !#en Tag. If a node has several collider components, you can judge which type of collider is collided according to the tag. !#zh 标签。当一个节点上有多个碰撞组件时,在发生碰撞后,可以使用此标签来判断是节点上的哪个碰撞组件被碰撞了。 */ tag : Integer; } /** !#en A simple collision manager class. It will calculate whether the collider collides other colliders, if collides then call the callbacks. !#zh 一个简单的碰撞组件管理类,用于处理节点之间的碰撞组件是否产生了碰撞,并调用相应回调函数。 */ export class CollisionManager { /** !#en !#zh 是否开启碰撞管理,默认为不开启 */ enabled : boolean; /** !#en !#zh 是否绘制碰撞组件的包围盒,默认为不绘制 */ enabledDrawBoundingBox : boolean; /** !#en !#zh 是否绘制碰撞组件的形状,默认为不绘制 */ enabledDebugDraw : boolean; } /** !#en Intersection helper class !#zh 辅助类,用于测试形状与形状是否相交 */ export class Intersection { /** !#en Test line and line !#zh 测试线段与线段是否相交 @param a1 The start point of the first line @param a2 The end point of the first line @param b1 The start point of the second line @param b2 The end point of the second line */ lineLine(a1 : Vec2, a2 : Vec2, b1 : Vec2, b2 : Vec2) : boolean; /** !#en Test line and rect !#zh 测试线段与矩形是否相交 @param a1 The start point of the line @param a2 The end point of the line @param b The rect */ lineRect(a1 : Vec2, a2 : Vec2, b : Rect) : boolean; /** !#en Test line and polygon !#zh 测试线段与多边形是否相交 @param a1 The start point of the line @param a2 The end point of the line @param b The polygon, a set of points */ linePolygon(a1 : Vec2, a2 : Vec2, b : [Vec2]) : boolean; /** !#en Test rect and rect !#zh 测试矩形与矩形是否相交 @param a The first rect @param b The second rect */ rectRect(a : Rect, b : Rect) : boolean; /** !#en Test rect and polygon !#zh 测试矩形与多边形是否相交 @param a The rect @param b The polygon, a set of points */ rectPolygon(a : Rect, b : [Vec2]) : boolean; /** !#en Test polygon and polygon !#zh 测试多边形与多边形是否相交 @param a The first polygon, a set of points @param b The second polygon, a set of points */ polygonPolygon(a : [Vec2], b : [Vec2]) : boolean; /** !#en Test circle and circle !#zh 测试圆形与圆形是否相交 @param a Object contains position and radius @param b Object contains position and radius */ circleCircle(a : any, b : any) : boolean; /** !#en Test polygon and circle !#zh 测试矩形与圆形是否相交 @param polygon The Polygon, a set of points @param circle Object contains position and radius */ polygonCircle(polygon : [Vec2], circle : any) : boolean; /** !#en Test whether the point is in the polygon !#zh 测试一个点是否在一个多边形中 @param point The point @param polygon The polygon, a set of points */ pointInPolygon(point : Vec2, polygon : [Vec2]) : boolean; /** !#en Calculate the distance of point to line. !#zh 计算点到直线的距离。如果这是一条线段并且垂足不在线段内,则会计算点到线段端点的距离。 @param point The point @param start The start point of line @param end The end point of line @param isSegment whether this line is a segment */ pointLineDistance(point : Vec2, start : Vec2, end : Vec2, isSegment : boolean) : boolean; } /** !#en Polygon Collider. !#zh 多边形碰撞组件 */ export class PolygonCollider extends Component { /** !#en Position offset !#zh 位置偏移量 */ offset : Vec2; /** !#en Polygon points !#zh 多边形顶点数组 */ points : [Vec2]; } /** !#en The animation component is used to play back animations. !#zh Animation 组件用于播放动画。你能指定动画剪辑到动画组件并从脚本控制播放。 */ export class Animation extends CCComponent { /** !#en Animation will play the default clip when start game. !#zh 在勾选自动播放或调用 play() 时默认播放的动画剪辑。 */ defaultClip : AnimationClip; /** !#en Current played clip. !#zh 当前播放的动画剪辑。 */ currentClip : AnimationClip; /** !#en Whether the animation should auto play the default clip when start game. !#zh 是否在运行游戏后自动播放默认动画剪辑。 */ playOnLoad : boolean; /** !#en Get all the clips used in this animation. !#zh 获取动画组件上的所有动画剪辑。 */ getClips() : AnimationClip[]; /** !#en Plays an animation and stop other animations. !#zh 播放当前或者指定的动画,并且停止当前正在播放动画。 @param name The name of animation to play. If no name is supplied then the default animation will be played. @param startTime play an animation from startTime @example ```js var animCtrl = this.node.getComponent(cc.Animation); animCtrl.play("linear"); ``` */ play(name? : string, startTime? : number) : AnimationState; /** !#en Plays an additive animation, it will not stop other animations. If there are other animations playing, then will play several animations at the same time. !#zh 播放当前或者指定的动画(将不会停止当前播放的动画)。 @param name The name of animation to play. If no name is supplied then the default animation will be played. @param startTime play an animation from startTime @example ```js // linear_1 and linear_2 at the same time playing. var animCtrl = this.node.getComponent(cc.Animation); animCtrl.playAdditive("linear_1"); animCtrl.playAdditive("linear_2"); ``` */ playAdditive(name? : string, startTime? : number) : AnimationState; /** !#en Stops an animation named name. If no name is supplied then stops all playing animations that were started with this Animation.
Stopping an animation also Rewinds it to the Start. !#zh 停止当前或者指定的动画。如果没有指定名字,则停止所有动画。 @param name The animation to stop, if not supplied then stops all playing animations. */ stop(name? : string) : void; /** !#en Pauses an animation named name. If no name is supplied then pauses all playing animations that were started with this Animation. !#zh 暂停当前或者指定的动画。如果没有指定名字,则暂停当前正在播放的动画。 @param name The animation to pauses, if not supplied then pauses all playing animations. */ pause(name? : string) : void; /** !#en Resumes an animation named name. If no name is supplied then resumes all paused animations that were started with this Animation. !#zh 重新播放指定的动画,如果没有指定名字,则重新播放当前正在播放的动画。 @param name The animation to resumes, if not supplied then resumes all paused animations. */ resume(name? : string) : void; /** !#en Make an animation named name go to the specified time. If no name is supplied then make all animations go to the specified time. !#zh 设置指定动画的播放时间。如果没有指定名字,则设置所有动画的播放时间。 @param time The time to go to @param name Specified animation name, if not supplied then make all animations go to the time. */ setCurrentTime(time? : number, name? : string) : void; /** !#en Returns the animation state named name. If no animation with the specified name, the function will return null. !#zh 获取当前或者指定的动画状态,如果未找到指定动画剪辑则返回 null。 */ getAnimationState(name : string) : AnimationState; /** !#en Adds a clip to the animation with name newName. If a clip with that name already exists it will be replaced with the new clip. !#zh 添加动画剪辑,并且可以重新设置该动画剪辑的名称。 @param clip the clip to add */ addClip(clip : AnimationClip, newName? : string) : AnimationState; /** !#en Remove clip from the animation list. This will remove the clip and any animation states based on it. If there are animation states depand on the clip are playing or clip is defaultClip, it will not delete the clip. But if force is true, then will always remove the clip and any animation states based on it. If clip is defaultClip, defaultClip will be reset to null !#zh 从动画列表中移除指定的动画剪辑,
如果依赖于 clip 的 AnimationState 正在播放或者 clip 是 defaultClip 的话,默认是不会删除 clip 的。 但是如果 force 参数为 true,则会强制停止该动画,然后移除该动画剪辑和相关的动画。这时候如果 clip 是 defaultClip,defaultClip 将会被重置为 null。 @param force If force is true, then will always remove the clip and any animation states based on it. */ removeClip(clip : AnimationClip, force : boolean) : void; /** !#en Samples animations at the current state.
This is useful when you explicitly want to set up some animation state, and sample it once. !#zh 对当前动画进行采样。你可以手动将动画设置到某一个状态,然后采样一次。 */ sample() : void; } /** !#en Audio Source. !#zh 音频源组件,能对音频剪辑。 */ export class AudioSource extends Component { /** !#en Is the audio source playing (Read Only).
Note: isPlaying is not supported for Native platforms. !#zh 该音频剪辑是否正播放(只读)。
注意:Native 平台暂时不支持 isPlaying。 */ isPlaying : boolean; /** !#en The clip of the audio source. !#zh 默认要播放的音频剪辑。 */ clip : AudioClip; /** !#en The volume of the audio source. !#zh 音频源的音量(0.0 ~ 1.0)。 */ volume : number; /** !#en Is the audio source mute? !#zh 是否静音音频源。Mute 是设置音量为 0,取消静音是恢复原来的音量。 */ mute : boolean; /** !#en Is the audio source looping? !#zh 音频源是否循环播放? */ loop : boolean; /** !#en If set to true, the audio source will automatically start playing on onLoad. !#zh 如果设置为true,音频源将在 onLoad 时自动播放。 */ playOnLoad : boolean; /** !#en Plays the clip. !#zh 播放音频剪辑。 */ play() : void; /** !#en Stops the clip. !#zh 停止当前音频剪辑。 */ stop() : void; /** !#en Pause the clip. !#zh 暂停当前音频剪辑。 */ pause() : void; /** !#en Resume the clip. !#zh 恢复播放。 */ resume() : void; /** !#en Rewind playing music. !#zh 从头开始播放。 */ rewind() : void; } /** !#en Button has 3 Transition types When Button state changed: If Transition type is Button.Transition.NONE, Button will do nothing If Transition type is Button.Transition.COLOR, Button will change target's color If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite Button will trigger 5 events: Button.EVENT_TOUCH_DOWN Button.EVENT_TOUCH_UP Button.EVENT_HOVER_IN Button.EVENT_HOVER_MOVE Button.EVENT_HOVER_OUT !#zh 按钮组件。可以被按下,或者点击。
按钮可以通过修改 Transition 来设置按钮状态过渡的方式:
-Button.Transition.NONE // 不做任何过渡
-Button.Transition.COLOR // 进行颜色之间过渡
-Button.Transition.SPRITE // 进行精灵之间过渡
按钮可以绑定事件(但是必须要在按钮的 Node 上才能绑定事件):
// 以下事件可以在全平台上都触发
-cc.Node.EventType.TOUCH_START // 按下时事件
-cc.Node.EventType.TOUCH_Move // 按住移动后事件
-cc.Node.EventType.TOUCH_END // 按下后松开后事件
-cc.Node.EventType.TOUCH_CANCEL // 按下取消事件
// 以下事件只在 PC 平台上触发
-cc.Node.EventType.MOUSE_DOWN // 鼠标按下时事件
-cc.Node.EventType.MOUSE_MOVE // 鼠标按住移动后事件
-cc.Node.EventType.MOUSE_ENTER // 鼠标进入目标事件
-cc.Node.EventType.MOUSE_LEAVE // 鼠标离开目标事件
-cc.Node.EventType.MOUSE_UP // 鼠标松开事件
-cc.Node.EventType.MOUSE_WHEEL // 鼠标滚轮事件
*/ export class Button extends Component { /** !#en Whether the Button is disabled. If true, the Button will trigger event and do transition. !#zh 按钮事件是否被响应,如果为 false,则按钮将被禁用。 */ interactable : boolean; /** !#en Transition type !#zh 按钮状态改变时过渡方式。 */ transition : Button.Transition; /** !#en Normal state color. !#zh 普通状态下按钮所显示的颜色。 */ normalColor : Color; /** !#en Pressed state color !#zh 按下状态时按钮所显示的颜色。 */ pressedColor : Color; /** !#en Hover state color !#zh 悬停状态下按钮所显示的颜色。 */ hoverColor : Color; /** !#en Disabled state color !#zh 禁用状态下按钮所显示的颜色。 */ disabledColor : Color; /** !#en Color transition duration !#zh 颜色过渡时所需时间 */ duration : number; /** !#en Normal state sprite !#zh 普通状态下按钮所显示的 Sprite 。 */ normalSprite : SpriteFrame; /** !#en Pressed state sprite !#zh 按下状态时按钮所显示的 Sprite 。 */ pressedSprite : SpriteFrame; /** !#en Hover state sprite !#zh 悬停状态下按钮所显示的 Sprite 。 */ hoverSprite : SpriteFrame; /** !#en Disabled state sprite !#zh 禁用状态下按钮所显示的 Sprite 。 */ disabledSprite : SpriteFrame; /** !#en Transition target. When Button state changed: If Transition type is Button.Transition.NONE, Button will do nothing If Transition type is Button.Transition.COLOR, Button will change target's color If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite !#zh 需要过渡的目标。 当前按钮状态改变有: -如果 Transition type 选择 Button.Transition.NONE,按钮不做任何过渡。 -如果 Transition type 选择 Button.Transition.COLOR,按钮会对目标颜色进行颜色之间的过渡。 -如果 Transition type 选择 Button.Transition.NONE,按钮会对目标 Sprite 进行 Sprite 之间的过渡。 */ target : Node; /** !#en If Button is clicked, it will trigger event's handler !#zh 按钮的点击事件列表。 */ clickEvents : Component.EventHandler[]; } /** !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。 注:由于本节点的尺寸会跟随屏幕拉伸,所以 anchorPoint 只支持 (0.5, 0.5),否则适配不同屏幕时坐标会有偏差。 */ export class Canvas extends Component { /** !#en Current active canvas, the scene should only have one active canvas at the same time. !#zh 当前激活的画布组件,场景同一时间只能有一个激活的画布。 */ instance : Canvas; /** !#en The desigin resolution for current scene. !#zh 当前场景设计分辨率。 */ designResolution : cc.Size; /** !#en TODO !#zh: 是否优先将设计分辨率高度撑满视图高度。 */ fitHeight : boolean; /** !#en TODO !#zh: 是否优先将设计分辨率宽度撑满视图宽度。 */ fitWidth : boolean; } /** !#en Base class for everything attached to Node(Entity).

NOTE: Not allowed to use construction parameters for Component's subclasses, because Component is created by the engine. !#zh 所有附加到节点的基类。

注意:不允许使用组件的子类构造参数,因为组件是由引擎创建的。 */ export class Component extends Object { constructor(); /** !#en The node this component is attached to. A component is always attached to a node. !#zh 该组件被附加到的节点。组件总会附加到一个节点。 */ node : Node; /** !#en The uuid for editor. !#zh 组件的 uuid,用于编辑器。 */ uuid : string; /** !#en indicates whether this component is enabled or not. !#zh 表示该组件自身是否启用。 */ enabled : boolean; /** !#en indicates whether this component is enabled and its node is also active in the hierarchy. !#zh 表示该组件是否被启用并且所在的节点也处于激活状态。。 */ enabledInHierarchy : boolean; /** !#en TODO !#zh onLoad 是否被调用。 */ _isOnLoadCalled : boolean; /** !#en Update is called every frame, if the Component is enabled. !#zh 如果该组件启用,则每帧调用 update。 */ update() : void; /** !#en LateUpdate is called every frame, if the Component is enabled. !#zh 如果该组件启用,则每帧调用 LateUpdate。 */ lateUpdate() : void; /** !#en When attaching to an active node or its node first activated. !#zh 当附加到一个激活的节点上或者其节点第一次激活时候调用。 */ onLoad() : void; /** !#en Called before all scripts' update if the Component is enabled. !#zh 如果该组件启用,则在所有组件的 update 之前调用。 */ start() : void; /** !#en Called when this component becomes enabled and its node is active. !#zh 当该组件被启用,并且它的节点也激活时。 */ onEnable() : void; /** !#en Called when this component becomes disabled or its node becomes inactive. !#zh 当该组件被禁用或节点变为无效时调用。 */ onDisable() : void; /** !#en Called when this component will be destroyed. !#zh 当该组件被销毁时调用 */ onDestroy() : void; onFocusInEditor() : void; onLostFocusInEditor() : void; /** !#en Adds a component class to the node. You can also add component to node by passing in the name of the script. !#zh 向节点添加一个组件类,你还可以通过传入脚本的名称来添加组件。 @param typeOrTypename the constructor or the class name of the component to add @example ```js var sprite = node.addComponent(cc.Sprite); var test = node.addComponent("Test"); ``` */ addComponent(typeOrTypename : Function|string) : Component; /** !#en Returns the component of supplied type if the node has one attached, null if it doesn't.
You can also get component in the node by passing in the name of the script. !#zh 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
传入参数也可以是脚本的名称。 @example ```js // get sprite component. var sprite = node.getComponent(cc.Sprite); // get custom test calss. var test = node.getComponent("Test"); ``` */ getComponent(typeOrClassName : Function|string) : Component; /** !#en Returns all components of supplied Type in the node. !#zh 返回节点上指定类型的所有组件。 @example ```js var sprites = node.getComponents(cc.Sprite); var tests = node.getComponents("Test"); ``` */ getComponents(typeOrClassName : Function|string) : Component[]; /** !#en Returns the component of supplied type in any of its children using depth first search. !#zh 递归查找所有子节点中第一个匹配指定类型的组件。 @example ```js var sprite = node.getComponentInChildren(cc.Sprite); var Test = node.getComponentInChildren("Test"); ``` */ getComponentInChildren(typeOrClassName : Function|string) : Component; /** !#en Returns the components of supplied type in any of its children using depth first search. !#zh 递归查找所有子节点中指定类型的组件。 @example ```js var sprites = node.getComponentsInChildren(cc.Sprite); var tests = node.getComponentsInChildren("Test"); ``` */ getComponentsInChildren(typeOrClassName : Function|string) : Component[]; /** !#en If the component's bounding box is different from the node's, you can implement this method to supply a custom axis aligned bounding box (AABB), so the editor's scene view can perform hit test properly. !#zh 如果组件的包围盒与节点不同,您可以实现该方法以提供自定义的轴向对齐的包围盒(AABB), 以便编辑器的场景视图可以正确地执行点选测试。 @param out_rect the Rect to receive the bounding box */ _getLocalBounds(out_rect : Rect) : void; /** !#en onRestore is called after the user clicks the Reset item in the Inspector's context menu or performs an undo operation on this component.

If the component contains the "internal state", short for "temporary member variables which not included
in its CCClass properties", then you may need to implement this function.

The editor will call the getset accessors of your component to record/restore the component's state
for undo/redo operation. However, in extreme cases, it may not works well. Then you should implement
this function to manually synchronize your component's "internal states" with its public properties.
Once you implement this function, all the getset accessors of your component will not be called when
the user performs an undo/redo operation. Which means that only the properties with default value
will be recorded or restored by editor.

Similarly, the editor may failed to reset your component correctly in extreme cases. Then if you need
to support the reset menu, you should manually synchronize your component's "internal states" with its
properties in this function. Once you implement this function, all the getset accessors of your component
will not be called during reset operation. Which means that only the properties with default value
will be reset by editor. This function is only called in editor mode. !#zh onRestore 是用户在检查器菜单点击 Reset 时,对此组件执行撤消操作后调用的。

如果组件包含了“内部状态”(不在 CCClass 属性中定义的临时成员变量),那么你可能需要实现该方法。

编辑器执行撤销/重做操作时,将调用组件的 get set 来录制和还原组件的状态。 然而,在极端的情况下,它可能无法良好运作。
那么你就应该实现这个方法,手动根据组件的属性同步“内部状态”。 一旦你实现这个方法,当用户撤销或重做时,组件的所有 get set 都不会再被调用。 这意味着仅仅指定了默认值的属性将被编辑器记录和还原。

同样的,编辑可能无法在极端情况下正确地重置您的组件。
于是如果你需要支持组件重置菜单,你需要在该方法中手工同步组件属性到“内部状态”。
一旦你实现这个方法,组件的所有 get set 都不会在重置操作时被调用。 这意味着仅仅指定了默认值的属性将被编辑器重置。
此方法仅在编辑器下会被调用。 */ onRestore() : void; /** !#en Schedules a custom selector.
If the selector is already scheduled, then the interval parameter will be updated without scheduling it again. !#zh 调度一个自定义的回调函数。
如果回调函数已调度,那么将不会重复调度它,只会更新时间间隔参数。 @param callback The callback function @param interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead. @param repeat The selector will be executed (repeat + 1) times, you can use kCCRepeatForever for tick infinitely. @param delay The amount of time that the first tick will wait before execution. @example ```js var timeCallback = function (dt) { cc.log("time: " + dt); } this.schedule(timeCallback, 1); ``` */ schedule(callback : Function, interval? : number, repeat? : number, delay? : number) : void; /** !#en Schedules a callback function that runs only once, with a delay of 0 or larger. !#zh 调度一个只运行一次的回调函数,可以指定 0 让回调函数在下一帧立即执行或者在一定的延时之后执行。 @param callback A function wrapped as a selector @param delay The amount of time that the first tick will wait before execution. @example ```js var timeCallback = function (dt) { cc.log("time: " + dt); } this.scheduleOnce(timeCallback, 2); ``` */ scheduleOnce(callback : Function, delay? : number) : void; /** !#en Unschedules a custom callback function. !#zh 取消调度一个自定义的回调函数。 @param callback_fn A function wrapped as a selector @example ```js this.unschedule(_callback); ``` */ unschedule(callback_fn : Function) : void; /** !#en unschedule all scheduled callback functions: custom callback functions, and the 'update' callback function.
Actions are not affected by this method. !#zh 取消调度所有已调度的回调函数:定制的回调函数以及 'update' 回调函数。动作不受此方法影响。 @example ```js this.unscheduleAllCallbacks(); ``` */ unscheduleAllCallbacks() : void; } /** !#en cc.EditBox is a component for inputing text, you can use it to gather small amounts of text from users. !#zh EditBox 组件,用于获取用户的输入文本。 */ export class EditBox extends _RendererUnderSG { /** !#en Input string of EditBox. !#zh 输入框的初始输入内容,如果为空则会显示占位符的文本。 */ string : string; /** !#en The background image of EditBox. !#zh 输入框的背景图片 */ backGroundImage : SpriteFrame; /** !#en The return key type of EditBox. Note: it is meaningless for web platforms and desktop platforms. !#zh 指定移动设备上面回车按钮的样式。 注意:这个选项对 web 平台与 desktop 平台无效。 */ returnType : EditBox.KeyboardReturnType; /** !#en Set the input flags that are to be applied to the EditBox. !#zh 指定输入标志位,可以指定输入方式为密码或者单词首字母大写。 */ inputFlag : EditBox.InputFlag; /** !#en Set the input mode of the edit box. If you pass ANY, it will create a multiline EditBox. !#zh 指定输入模式: ANY表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式。 */ inputMode : EditBox.InputMode; /** !#en Font size of the input text. !#zh 输入框文本的字体大小 */ fontSize : number; /** !#en Change the lineHeight of displayed text. !#zh 输入框文本的行高。 */ lineHeight : number; /** !#en Font color of the input text. !#zh 输入框文本的颜色。 */ fontColor : Color; /** !#en The display text of placeholder. !#zh 输入框占位符的文本内容。 */ placeholder : string; /** !#en The font size of placeholder. !#zh 输入框占位符的字体大小。 */ placeholderFontSize : number; /** !#en The font color of placeholder. !#zh 输入框最大允许输入的字符个数。 */ placeholderFontColor : Color; /** !#en The maximize input length of EditBox. !#zh 输入框最大允许输入的字符个数。 */ maxLength : number; /** !#en The event handler to be called when EditBox began to edit text. !#zh 开始编辑文本输入框触发的事件回调。 */ editingDidBegin : Component.EventHandler; /** !#en The event handler to be called when EditBox text changes. !#zh 编辑文本输入框时触发的事件回调。 */ textChanged : Component.EventHandler; /** !#en The event handler to be called when EditBox edit ends. !#zh 结束编辑文本输入框时触发的事件回调。 */ editingDidEnded : Component.EventHandler; } /** !#en The Label Component. !#zh 文字标签组件 */ export class Label extends _RendererUnderSG { /** !#en Content string of label. !#zh 标签显示的文本内容。 */ string : string; /** !#en Horizontal Alignment of label. !#zh 文本内容的水平对齐方式。 */ horizontalAlign : Label.TextAlignment; /** !#en Vertical Alignment of label. !#zh 文本内容的垂直对齐方式。 */ verticalAlign : Label.VerticalTextAlignment; /** !#en Font size of label. !#zh 文本字体大小。 */ fontSize : number; /** !#en Line Height of label. !#zh 文本行高。 */ lineHeight : number; /** !#en Overflow of label. !#zh 文字显示超出范围时的处理方式。 */ overflow : Label.Overflow; /** !#en Whether auto wrap label when string width is large than label width. !#zh 是否自动换行。 */ enableWrapText : boolean; /** !#en The font of label. !#zh 文本字体。 */ font : cc.Font; /** !#en Whether use system font name or not. !#zh 是否使用系统字体。 */ isSystemFontUsed : boolean; } /** !#en Outline effect used to change the display, only used for TTF font !#zh 描边效果组件,用于字体描边,只能用于系统字体 */ export class LabelOutline extends Component { /** !#en Change the outline color !#zh 改变描边的颜色 */ color : Color; /** !#en Change the outline width !#zh 改变描边的宽度 */ width : number; } /** !#en The Layout is a container component, use it to arrange child elements easily. !#zh Layout 组件相当于一个容器,能自动对它的所有子节点进行统一排版。 */ export class Layout extends Component { /** !#en The layout type. !#zh 布局类型 */ type : Layout.Type; /** !#en The are three resize modes for Layout. None, resize Container and resize children. !#zh 缩放模式 */ resizeMode : Layout.ResizeMode; /** !#en The cell size for grid layout. !#zh 每个格子的大小,只有布局类型为 GRID 的时候才有效。 */ cellSize : Size; /** !#en The start axis for grid layout. If you choose horizontal, then children will layout horizontally at first, and then break line on demand. Choose vertical if you want to layout vertically at first . !#zh 起始轴方向类型,可进行水平和垂直布局排列,只有布局类型为 GRID 的时候才有效。 */ startAxis : Layout.AxisDirection; /** !#en The padding of layout, it only effect the layout in one direction. !#zh 容器内边距,只会在布局方向上生效。 */ padding : number; /** !#en The distance in x-axis between each element in layout. !#zh 子节点之间的水平间距。 */ spacingX : number; /** !#en The distance in y-axis between each element in layout. !#zh 子节点之间的垂直间距。 */ spacingY : number; /** !#en Only take effect in Vertical layout mode. This option changes the start element's positioning. !#zh 垂直排列子节点的方向。 */ verticalDirection : Layout.VerticalDirection; /** !#en Only take effect in Horizontal layout mode. This option changes the start element's positioning. !#zh 水平排列子节点的方向。 */ horizontalDirection : Layout.HorizontalDirection; } /** undefined */ export class Mask extends _RendererInSG { } /** !#en Visual indicator of progress in some operation. Displays a bar to the user representing how far the operation has progressed. !#zh 进度条组件,可用于显示加载资源时的进度。 */ export class ProgressBar extends Component { /** !#en The targeted Sprite which will be changed progressively. !#zh 用来显示进度条比例的 Sprite 对象。 */ barSprite : Sprite; /** !#en The progress mode, there are two modes supported now: horizontal and vertical. !#zh 进度条的模式 */ mode : ProgressBar.Mode; /** !#en The total width or height of the bar sprite. !#zh 进度条实际的总长度 */ totalLength : number; /** !#en The current progress of the bar sprite. The valid value is between 0-1. !#zh 当前进度值,该数值的区间是 0-1 之间。 */ progress : number; /** !#en Whether reverse the progress direction of the bar sprite. !#zh 进度条是否进行反方向变化。 */ reverse : boolean; } /** Rendering component in scene graph. Maintains a node which will be the scene graph of component's Node. */ export class _RendererInSG extends _SGComponent { } /** The base rendering component which will attach a leaf node to the cocos2d scene graph. */ export class _RendererUnderSG extends _SGComponent { } /** The base class for all rendering component in scene graph. You should override: - _createSgNode - _initSgNode */ export class _SGComponent extends Component { } /** !#en The Scrollbar control allows the user to scroll an image or other view that is too large to see completely !#zh 滚动条组件 */ export class Scrollbar extends Component { /** !#en The "handle" part of the scrollbar. !#zh 作为当前滚动区域位置显示的滑块 Sprite。 */ handle : cc.Sprite; /** !#en The direction of scrollbar. !#zh ScrollBar 的滚动方向。 */ direction : Scrollbar.Direction; /** !#en Whehter enable auto hide or not. !#zh 是否在没有滚动动作时自动隐藏 ScrollBar。 */ enableAutoHide : boolean; /** !#en The time to hide scrollbar when scroll finished. Note: This value is only useful when enableAutoHide is true. !#zh 没有滚动动作后经过多久会自动隐藏。 注意:只要当 “enableAutoHide” 为 true 时,才有效。 */ autoHideTime : number; } /** !#en Layout container for a view hierarchy that can be scrolled by the user, allowing it to be larger than the physical display. !#zh 滚动视图组件 */ export class ScrollView extends Component { /** !#en This is a reference to the UI element to be scrolled. !#zh 可滚动展示内容的节点。 */ content : Node; /** !#en Enable horizontal scroll. !#zh 是否开启水平滚动。 */ horizontal : boolean; /** !#en Enable vertical scroll. !#zh 是否开启垂直滚动。 */ vertical : boolean; /** !#en When inertia is set, the content will continue to move when touch ended. !#zh 是否开启滚动惯性。 */ inertia : boolean; /** !#en It determines how quickly the content stop moving. A value of 1 will stop the movement immediately. A value of 0 will never stop the movement until it reaches to the boundary of scrollview. !#zh 开启惯性后,在用户停止触摸后滚动多快停止,0表示永不停止,1表示立刻停止。 */ brake : number; /** !#en When elastic is set, the content will be bounce back when move out of boundary. !#zh 是否允许滚动内容超过边界,并在停止触摸后回弹。 */ elastic : boolean; /** !#en The elapse time of bouncing back. A value of 0 will bounce back immediately. !#zh 回弹持续的时间,0 表示将立即反弹。 */ bounceDuration : number; /** !#en The horizontal scrollbar reference. !#zh 水平滚动的 ScrollBar。 */ horizontalScrollBar : Scrollbar; /** !#en The vertical scrollbar reference. !#zh 垂直滚动的 ScrollBar。 */ verticalScrollBar : Scrollbar; /** !#en Scrollview events callback !#zh 滚动视图的事件回调函数 */ scrollEvents : Component.EventHandler[]; /** !#en Scroll the content to the bottom boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图底部。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the bottom boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the bottom of the view. scrollView.scrollToBottom(0.1); ``` */ scrollToBottom(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the top boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图顶部。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the top boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the top of the view. scrollView.scrollToTop(0.1); ``` */ scrollToTop(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the left boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图左边。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the left boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the left of the view. scrollView.scrollToLeft(0.1); ``` */ scrollToLeft(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the right boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图右边。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the right boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the right of the view. scrollView.scrollToRight(0.1); ``` */ scrollToRight(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the top left boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图左上角。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the top left boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the upper left corner of the view. scrollView.scrollToTopLeft(0.1); ``` */ scrollToTopLeft(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the top right boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图右上角。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the top right boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the top right corner of the view. scrollView.scrollToTopRight(0.1); ``` */ scrollToTopRight(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the bottom left boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图左下角。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the bottom left boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the lower left corner of the view. scrollView.scrollToBottomLeft(0.1); ``` */ scrollToBottomLeft(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the bottom right boundary of ScrollView. !#zh 视图内容将在规定时间内滚动到视图右下角。 @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the bottom right boundary immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to the lower right corner of the view. scrollView.scrollToBottomRight(0.1); ``` */ scrollToBottomRight(timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll with an offset related to the ScrollView's top left origin, if timeInSecond is omitted, then it will jump to the specific offset immediately. !#zh 视图内容在规定时间内将滚动到 ScrollView 相对左上角原点的偏移位置, 如果 timeInSecond参数不传,则立即滚动到指定偏移位置。 @param offset A Vec2, the value of which each axis between 0 and maxScrollOffset @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the specific offset of ScrollView immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to middle position in 0.1 second in x-axis var maxScrollOffset = this.getMaxScrollOffset(); scrollView.scrollToOffset(cc.p(maxScrollOffset.x / 2, 0), 0.1); ``` */ scrollToOffset(offset : Vec2, timeInSecond? : number, attenuated? : boolean) : void; /** !#en Get the positive offset value corresponds to the content's top left boundary. !#zh 获取滚动视图相对于左上角原点的当前滚动偏移 */ getScrollOffset() : Vec2; /** !#en Get the maximize available scroll offset !#zh 获取滚动视图最大可以滚动的偏移量 */ getMaxScrollOffset() : Vec2; /** !#en Scroll the content to the horizontal percent position of ScrollView. !#zh 视图内容在规定时间内将滚动到 ScrollView 水平方向的百分比位置上。 @param percent A value between 0 and 1. @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the horizontal percent position of ScrollView immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Scroll to middle position. scrollView.scrollToBottomRight(0.5, 0.1); ``` */ scrollToPercentHorizontal(percent : number, timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the percent position of ScrollView in any direction. !#zh 视图内容在规定时间内进行垂直方向和水平方向的滚动,并且滚动到指定百分比位置上。 @param anchor A point which will be clamp between cc.p(0,0) and cc.p(1,1). @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the percent position of ScrollView immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. @example ```js // Vertical scroll to the bottom of the view. scrollView.scrollTo(cc.p(0, 1), 0.1); // Horizontal scroll to view right. scrollView.scrollTo(cc.p(1, 0), 0.1); ``` */ scrollTo(anchor : Vec2, timeInSecond? : number, attenuated? : boolean) : void; /** !#en Scroll the content to the vertical percent position of ScrollView. !#zh 视图内容在规定时间内滚动到 ScrollView 垂直方向的百分比位置上。 @param percent A value between 0 and 1. @param timeInSecond Scroll time in second, if you don't pass timeInSecond, the content will jump to the vertical percent position of ScrollView immediately. @param attenuated Whether the scroll acceleration attenuated, default is true. // Scroll to middle position. scrollView.scrollToPercentVertical(0.5, 0.1); */ scrollToPercentVertical(percent : number, timeInSecond? : number, attenuated? : boolean) : void; /** !#en Modify the content position. !#zh 设置当前视图内容的坐标点。 @param position The position in content's parent space. */ setContentPosition(position : Vec2) : void; /** !#en Query the content's position in its parent space. !#zh 获取当前视图内容的坐标点。 */ getContentPosition() : Position; } /** !#en Renders a sprite in the scene. !#zh 该组件用于在场景中渲染精灵。 */ export class Sprite extends _RendererUnderSG { /** !#en The sprite frame of the sprite. !#zh 精灵的精灵帧 */ spriteFrame : SpriteFrame; /** !#en The sprite render type. !#zh 精灵渲染类型 */ type : Sprite.SpriteType; /** !#en The fill type, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. !#zh 精灵填充类型,仅渲染类型设置为 cc.Sprite.SpriteType.FILLED 时有效。 */ fillType : Sprite.FillType; /** !#en The fill Center, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. !#zh 填充中心点,仅渲染类型设置为 cc.Sprite.SpriteType.FILLED 时有效。 */ fillCenter : Vec2; /** !#en The fill Start, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. !#zh 填充起始点,仅渲染类型设置为 cc.Sprite.SpriteType.FILLED 时有效。 */ fillStart : number; /** !#en The fill Range, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”. !#zh 填充范围,仅渲染类型设置为 cc.Sprite.SpriteType.FILLED 时有效。 */ fillRange : number; /** !#en specify the frame is trimmed or not. !#zh 是否使用裁剪模式 */ trim : boolean; /** !#en specify the source Blend Factor. !#zh 指定原图的混合模式 */ srcBlendFactor : BlendFactor; /** !#en specify the destination Blend Factor. !#zh 指定目标的混合模式 */ dstBlendFactor : BlendFactor; /** !#en specify the size tracing mode. !#zh 精灵尺寸调整模式 */ sizeMode : Sprite.SizeMode; /** !#en Sets whether the sprite is visible or not. !#zh 设置精灵是否可见 @example ```js sprite.setVisible(false); ``` */ setVisible(visible : boolean) : void; /** !#en Query the sprite's original size. !#zh 获取精灵原始大小 @example ```js var originalSize = sprite.getOriginalSize(); cc.log("Original Size:" + originalSize); ``` */ getOriginalSize() : Size; /** !#en Change the left sprite's cap inset. !#zh 设置精灵左边框-用于九宫格。 @param insetLeft The values to use for the cap inset. @example ```js sprite.setInsetLeft(5); ``` */ setInsetLeft(insetLeft : number) : void; /** !#en Query the left sprite's cap inset. !#zh 获取精灵左边框 @example ```js var insetLeft = sprite.getInsetLeft(); cc.log("Inset Left:" + insetLeft); ``` */ getInsetLeft() : number; /** !#en Change the top sprite's cap inset. !#zh 设置精灵上边框-用于九宫格。 @param insetTop The values to use for the cap inset. @example ```js sprite.setInsetTop(5); ``` */ setInsetTop(insetTop : number) : void; /** !#en Query the top sprite's cap inset. !#zh 获取精灵上边框。 @example ```js var insetTop = sprite.getInsetTop(); cc.log("Inset Top:" + insetTop); ``` */ getInsetTop() : number; /** !#en Change the right sprite's cap inset. !#zh 设置精灵右边框-用于九宫格。 @param insetRight The values to use for the cap inset. @example ```js sprite.setInsetRight(5); ``` */ setInsetRight(insetRight : number) : void; /** !#en Query the right sprite's cap inset. !#zh 获取精灵右边框。 @example ```js var insetRight = sprite.getInsetRight(); cc.log("Inset Right:" + insetRight); ``` */ getInsetRight() : number; /** !#en Change the bottom sprite's cap inset. !#zh 设置精灵下边框-用于九宫格。 @param bottomInset The values to use for the cap inset. @example ```js sprite.setInsetBottom(5); ``` */ setInsetBottom(bottomInset : number) : void; /** !#en Query the bottom sprite's cap inset. !#zh 获取精灵下边框。 @example ```js var insetBottom = sprite.getInsetBottom(); cc.log("Inset Bottom:" + insetBottom); ``` */ getInsetBottom() : number; } /** !#en A distortion used to change the rendering of simple sprite.If will take effect after sprite component is added. !#zh 扭曲效果组件,用于改变SIMPLE类型sprite的渲染,只有当sprite组件已经添加后,才能起作用. */ export class SpriteDistortion extends Component { /** !#en Change the UV offset for distortion rendering. !#zh 在渲染时改变UV的整体偏移. */ offset : Vec2; /** !#en Change the UV scale for distortion rendering. !#zh 在渲染时改变UV的寻址系数 */ tiling : Vec2; } /** !#en cc.VideoPlayer is a component for playing videos, you can use it for showing videos in your game. !#zh Video 组件,用于在游戏中播放视频 */ export class VideoPlayer extends _RendererUnderSG { /** !#en The resource type of videoplayer, REMOTE for remote url and LOCAL for local file path. !#zh 视频来源:REMOTE 表示远程视频 URL,LOCAL 表示本地视频地址。 */ resourceType : VideoPlayer.ResourceType; /** !#en The remote URL of video. !#zh 远程视频的 URL */ remoteURL : string; /** !#en The local video full path. !#zh 本地视频的 URL */ video : string; /** !#en The current time when video start to play. !#zh 从当前时间点开始播放视频 */ currentTime : Float; /** !#en Whether keep the aspect ration of the original video. !#zh 是否保持视频原来的宽高比 */ keepAspectRatio : boolean; /** !#en Whether play video in fullscreen mode. !#zh 是否全屏播放视频 */ isFullscreen : boolean; /** !#en the video player's callback, it will be triggered when certain event occurs, like: playing, paused, stopped and completed. !#zh 视频播放回调函数,该回调函数会在特定情况被触发,比如播放中,暂时,停止和完成播放。 */ videoPlayerEvent : cc.Component.EventHandler[]; } /** !#en Stores and manipulate the anchoring based on its parent. Widget are used for GUI but can also be used for other things. !#zh Widget 组件,用于设置和适配其相对于父节点的边距,Widget 通常被用于 UI 界面,也可以用于其他地方。 */ export class Widget extends Component { /** !#en Whether to align the top. !#zh 是否对齐上边。 */ isAlignTop : boolean; /** !#en Vertically aligns the midpoint, This will open the other vertical alignment options cancel. !#zh 是否垂直方向对齐中点,开启此项会将垂直方向其他对齐选项取消。 */ isAlignVerticalCenter : boolean; /** !#en Whether to align the bottom. !#zh 是否对齐下边。 */ isAlignBottom : boolean; /** !#en Whether to align the left. !#zh 是否对齐左边 */ isAlignLeft : boolean; /** !#en Horizontal aligns the midpoint. This will open the other horizontal alignment options canceled. !#zh 是否水平方向对齐中点,开启此选项会将水平方向其他对齐选项取消。 */ isAlignHorizontalCenter : boolean; /** !#en Whether to align the right. !#zh 是否对齐右边。 */ isAlignRight : boolean; /** !#en Whether the stretched horizontally, when enable the left and right alignment will be stretched horizontally, the width setting is invalid (read only). !#zh 当前是否水平拉伸。当同时启用左右对齐时,节点将会被水平拉伸,此时节点的宽度只读。 */ isStretchWidth : boolean; /** !#en Whether the stretched vertically, when enable the left and right alignment will be stretched vertically, then height setting is invalid (read only) !#zh 当前是否垂直拉伸。当同时启用上下对齐时,节点将会被垂直拉伸,此时节点的高度只读。 */ isStretchHeight : boolean; /** !#en The margins between the top of this node and the top of parent node, the value can be negative, Only available in 'isAlignTop' open. !#zh 本节点顶边和父节点顶边的距离,可填写负值,只有在 isAlignTop 开启时才有作用。 */ top : number; /** !#en The margins between the bottom of this node and the bottom of parent node, the value can be negative, Only available in 'isAlignBottom' open. !#zh 本节点底边和父节点底边的距离,可填写负值,只有在 isAlignBottom 开启时才有作用。 */ bottom : number; /** !#en The margins between the left of this node and the left of parent node, the value can be negative, Only available in 'isAlignLeft' open. !#zh 本节点左边和父节点左边的距离,可填写负值,只有在 isAlignLeft 开启时才有作用。 */ left : number; /** !#en The margins between the right of this node and the right of parent node, the value can be negative, Only available in 'isAlignRight' open. !#zh 本节点右边和父节点右边的距离,可填写负值,只有在 isAlignRight 开启时才有作用。 */ right : number; /** !#en If true, top is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height. !#zh 如果为 true,"top" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。 */ isAbsoluteTop : boolean; /** !#en If true, bottom is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height. !#zh 如果为 true,"bottom" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。 */ isAbsoluteBottom : boolean; /** !#en If true, left is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width. !#zh 如果为 true,"left" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。 */ isAbsoluteLeft : boolean; /** !#en If true, right is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width. !#zh 如果为 true,"right" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。 */ isAbsoluteRight : boolean; /** !#en TODO !#zh 开启后仅会在 onEnable 的当帧结束时对齐一次,然后立刻禁用当前组件。 这样便于脚本或动画继续控制当前节点。 注意:onEnable 时所在的那一帧仍然会进行对齐。 */ isAlignOnce : boolean; } /** !#en EventTarget is an object to which an event is dispatched when something has occurred. Entity are the most common event targets, but other objects can be event targets too. Event targets are an important part of the Fireball event model. The event target serves as the focal point for how events flow through the scene graph. When an event such as a mouse click or a keypress occurs, Fireball dispatches an event object into the event flow from the root of the hierarchy. The event object then makes its way through the scene graph until it reaches the event target, at which point it begins its return trip through the scene graph. This round-trip journey to the event target is conceptually divided into three phases: - The capture phase comprises the journey from the root to the last node before the event target's node - The target phase comprises only the event target node - The bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the tree See also: http://www.w3.org/TR/DOM-Level-3-Events/#event-flow Event targets can implement the following methods: - _getCapturingTargets - _getBubblingTargets !#zh 事件目标是事件触发时,分派的事件对象,Node 是最常见的事件目标, 但是其他对象也可以是事件目标。
*/ export class EventTarget { /** !#en Register an callback of a specific event type on the EventTarget. This method is merely an alias to addEventListener. !#zh 注册事件目标的特定事件类型回调,仅仅是 addEventListener 的别名。 @param type A string representing the event type to listen for. @param callback The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique). @param target The target to invoke the callback, can be null @param useCapture When set to true, the capture argument prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. @example ```js node.on(cc.Node.EventType.TOUCH_END, function (event) { cc.log("this is callback"); }, node); ``` */ on(type : string, callback: (param: Event) => void, target : any, useCapture : boolean) : Function; /** !#en Removes the callback previously registered with the same type, callback, target and or useCapture. This method is merely an alias to removeEventListener. !#zh 删除之前与同类型,回调,目标或 useCapture 注册的回调,仅仅是 removeEventListener 的别名。 @param type A string representing the event type being removed. @param callback The callback to remove. @param target The target to invoke the callback, if it's not given, only callback without target will be removed @param useCapture Specifies whether the callback being removed was registered as a capturing callback or not. If not specified, useCapture defaults to false. If a callback was registered twice, one with capture and one without, each must be removed separately. Removal of a capturing callback does not affect a non-capturing version of the same listener, and vice versa. @example ```js // register touchEnd eventListener var touchEnd = node.on(cc.Node.EventType.TOUCH_END, function (event) { cc.log("this is callback"); }, node); // remove touchEnd eventListener node.off(cc.Node.EventType.TOUCH_END, touchEnd, node); ``` */ off(type : string, callback : Function, target : any, useCapture : boolean) : void; /** !#en Removes all callbacks previously registered with the same target. !#zh 删除指定目标上的所有注册回调。 @param target The target to be searched for all related callbacks */ targetOff(target : any) : void; /** !#en Register an callback of a specific event type on the EventTarget, the callback will remove itself after the first time it is triggered. !#zh 注册事件目标的特定事件类型回调,回调会在第一时间被触发后删除自身。 @param type A string representing the event type to listen for. @param callback The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique). @param target The target to invoke the callback, can be null @param useCapture When set to true, the capture argument prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. @example ```js node.once(cc.Node.EventType.TOUCH_END, function (event) { cc.log("this is callback"); }, node); ``` */ once(type : string, callback: (param: Event) => void, target : any, useCapture : boolean) : void; /** !#en Dispatches an event into the event flow. The event target is the EventTarget object upon which the dispatchEvent() method is called. !#zh 分发事件到事件流中。 @param event The Event object that is dispatched into the event flow */ dispatchEvent(event : Event) : void; /** !#en Send an event to this object directly, this method will not propagate the event to any other objects. The event will be created from the supplied message, you can get the "detail" argument from event.detail. !#zh 该对象直接发送事件, 这种方法不会对事件传播到任何其他对象。 @param message the message to send @param detail whatever argument the message needs */ emit(message : string, detail? : any) : void; } /** !#en Base class of all kinds of events. !#zh 包含事件相关信息的对象。 */ export class Event { constructor(); /** @param type The name of the event (case-sensitive), e.g. "click", "fire", or "submit" @param bubbles A boolean indicating whether the event bubbles up through the tree or not */ Event(type : string, bubbles : boolean) : Event; /** !#en The name of the event (case-sensitive), e.g. "click", "fire", or "submit". !#zh 事件类型。 */ type : string; /** !#en Indicate whether the event bubbles up through the tree or not. !#zh 表示该事件是否进行冒泡。 */ bubbles : boolean; /** !#en A reference to the target to which the event was originally dispatched. !#zh 最初事件触发的目标 */ target : any; /** !#en A reference to the currently registered target for the event. !#zh 当前目标 */ currentTarget : any; /** !#en Indicates which phase of the event flow is currently being evaluated. Returns an integer value represented by 4 constants: - Event.NONE = 0 - Event.CAPTURING_PHASE = 1 - Event.AT_TARGET = 2 - Event.BUBBLING_PHASE = 3 The phases are explained in the [section 3.1, Event dispatch and DOM event flow] (http://www.w3.org/TR/DOM-Level-3-Events/#event-flow), of the DOM Level 3 Events specification. !#zh 事件阶段 */ eventPhase : number; /** !#en Reset the event for being stored in the object pool. !#zh 重置对象池中存储的事件。 */ unuse() : string; /** !#en Reuse the event for being used again by the object pool. !#zh 用于对象池再次使用的事件。 */ reuse() : string; /** !#en Stops propagation for current event. !#zh 停止传递当前事件。 */ stopPropagation() : void; /** !#en Stops propagation for current event immediately, the event won't even be dispatched to the listeners attached in the current target. !#zh 立即停止当前事件的传递,事件甚至不会被分派到所连接的当前目标。 */ stopPropagationImmediate() : void; /** !#en Checks whether the event has been stopped. !#zh 检查该事件是否已经停止传递. */ isStopped() : boolean; /** !#en

Gets current target of the event
note: It only be available when the event listener is associated with node.
It returns 0 when the listener is associated with fixed priority.

!#zh 获取当前目标节点 */ getCurrentTarget() : Node; /** !#en Gets the event type. !#zh 获取事件类型 */ getType() : string; /** !#en Code for event without type. !#zh 没有类型的事件 */ NO_TYPE : string; /** !#en Events not currently dispatched are in this phase !#zh 尚未派发事件阶段 */ NONE : number; /** !#en The capturing phase comprises the journey from the root to the last node before the event target's node see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow !#zh 捕获阶段,包括事件目标节点之前从根节点到最后一个节点的过程。 */ CAPTURING_PHASE : number; /** !#en The target phase comprises only the event target node see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow !#zh 目标阶段仅包括事件目标节点。 */ AT_TARGET : number; /** !#en The bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the hierarchy see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow !#zh 冒泡阶段, 包括回程遇到到层次根节点的任何后续节点。 */ BUBBLING_PHASE : number; } /** !#en

The base class of event listener.
If you need custom listener which with different callback, you need to inherit this class.
For instance, you could refer to EventListenerAcceleration, EventListenerKeyboard,
EventListenerTouchOneByOne, EventListenerCustom.

!#zh 封装用户的事件处理逻辑。 注意:这是一个抽象类,开发者不应该直接实例化这个类,请参考 {{#crossLink "EventListener/create:method"}}cc.EventListener.create{{/crossLink}}。 */ export class EventListener { /** Constructor */ EventListener(type : number, listenerID : number, callback : number) : EventListner; /** !#en Checks whether the listener is available. !#zh 检测监听器是否有效 */ checkAvailable() : boolean; /** !#en Clones the listener, its subclasses have to override this method. !#zh 克隆监听器,它的子类必须重写此方法。 */ clone() : EventListener; /** !#en Enables or disables the listener !#zh 启用或禁用监听器。 */ setEnabled(enabled : boolean) : void; /** !#en Checks whether the listener is enabled !#zh 检查监听器是否可用。 */ isEnabled() : boolean; /** !#en The type code of unknown event listener. !#zh 未知的事件监听器类型 */ UNKNOWN : number; /** !#en The type code of keyboard event listener. !#zh 键盘事件监听器类型 */ KEYBOARD : number; /** !#en The type code of focus event listener. !#zh 加速器事件监听器类型 */ ACCELERATION : number; /** !#en Create a EventListener object with configuration including the event type, handlers and other parameters. In handlers, this refer to the event listener object itself. You can also pass custom parameters in the configuration object, all custom parameters will be polyfilled into the event listener object and can be accessed in handlers. !#zh 通过指定不同的 Event 对象来设置想要创建的事件监听器。 @param argObj a json object @example ```js // Create KEYBOARD EventListener. cc.EventListener.create({ event: cc.EventListener.KEYBOARD, onKeyPressed: function (keyCode, event) { cc.log('pressed key: ' + keyCode); }, onKeyReleased: function (keyCode, event) { cc.log('released key: ' + keyCode); } }); // Create ACCELERATION EventListener. cc.EventListener.create({ event: cc.EventListener.ACCELERATION, callback: function (acc, event) { cc.log('acc: ' + keyCode); } }); ``` */ create(argObj : any) : EventListener; } /** !#en

cc.eventManager is a singleton object which manages event listener subscriptions and event dispatching.

The EventListener list is managed in such way so that event listeners can be added and removed
while events are being dispatched.

!#zh 事件管理器,它主要管理事件监听器注册和派发系统事件。 原始设计中,它支持鼠标,触摸,键盘,陀螺仪和自定义事件。 在 Creator 的设计中,鼠标,触摸和自定义事件的监听和派发请参考 http://cocos.com/docs/creator/scripting/events.html。 */ export class eventManager { /** !#en Pauses all listeners which are associated the specified target. !#zh 暂停传入的 node 相关的所有监听器的事件响应。 */ pauseTarget(node : Node, recursive : boolean) : void; /** !#en Resumes all listeners which are associated the specified target. !#zh 恢复传入的 node 相关的所有监听器的事件响应。 */ resumeTarget(node : Node, recursive : boolean) : void; /** !#en

Adds a event listener for a specified event.
if the parameter "nodeOrPriority" is a node, it means to add a event listener for a specified event with the priority of scene graph.
if the parameter "nodeOrPriority" is a Number, it means to add a event listener for a specified event with the fixed priority.

!#zh 将事件监听器添加到事件管理器中。
如果参数 “nodeOrPriority” 是节点,优先级由 node 的渲染顺序决定,显示在上层的节点将优先收到事件。
如果参数 “nodeOrPriority” 是数字,优先级则固定为该参数的数值,数字越小,优先级越高。
@param listener The listener of a specified event or a object of some event parameters. @param nodeOrPriority The priority of the listener is based on the draw order of this node or fixedPriority The fixed priority of the listener. */ addListener(listener : EventListener|any, nodeOrPriority : Node|number) : EventListener; /** !#en Remove a listener. !#zh 移除一个已添加的监听器。 @param listener an event listener or a registered node target @example ```js // 1. remove eventManager add Listener; var mouseListener1 = cc.eventManager.addListener({ event: cc.EventListener.MOUSE, onMouseDown: function(keyCode, event){ }, onMouseUp: function(keyCode, event){ }, onMouseMove: function () { }, onMouseScroll: function () { } }, node); cc.eventManager.removeListener(mouseListener1); // 2. remove eventListener create Listener; var mouseListener2 = cc.EventListener.create({ event: cc.EventListener.MOUSE, onMouseDown: function(keyCode, event){ }, onMouseUp: function(keyCode, event){ }, onMouseMove: function () { }, onMouseScroll: function () { } }); cc.eventManager.removeListener(mouseListener2); ``` */ removeListener(listener: (type: number, listenerID: number, callback: number) => void) : void; /** !#en Removes all listeners with the same event listener type or removes all listeners of a node. !#zh 移除注册到 eventManager 中指定类型的所有事件监听器。
1. 如果传入的第一个参数类型是 Node,那么事件管理器将移除与该对象相关的所有事件监听器。 (如果第二参数 recursive 是 true 的话,就会连同该对象的子控件上所有的事件监听器也一并移除)
2. 如果传入的第一个参数类型是 Number(该类型 EventListener 中定义的事件类型), 那么事件管理器将移除该类型的所有事件监听器。
下列是目前存在监听器类型:
cc.EventListener.UNKNOWN
cc.EventListener.KEYBOARD
cc.EventListener.ACCELERATION,
@param listenerType listenerType or a node */ removeListeners(listenerType : number|Node, recursive : boolean) : void; /** !#en Removes all listeners !#zh 移除所有事件监听器。 */ removeAllListeners() : void; /** !#en Sets listener's priority with fixed value. !#zh 设置 FixedPriority 类型监听器的优先级。 @param listener Constructor */ setPriority(listener: (type: number, listenerID: number, callback: number) => void, fixedPriority : number) : void; /** !#en Whether to enable dispatching events !#zh 启用或禁用事件管理器,禁用后不会分发任何事件。 */ setEnabled(enabled : boolean) : void; /** !#en Checks whether dispatching events is enabled !#zh 检测事件管理器是否启用。 */ isEnabled() : boolean; } /** !#en The touch event class !#zh 封装了触摸相关的信息。 */ export class Touch { /** !#en Returns the current touch location in OpenGL coordinates.、 !#zh 获取当前触点位置。 */ getLocation() : Vec2; /** !#en Returns X axis location value. !#zh 获取当前触点 X 轴位置。 */ getLocationX() : number; /** !#en Returns Y axis location value. !#zh 获取当前触点 Y 轴位置。 */ getLocationY() : number; /** !#en Returns the previous touch location in OpenGL coordinates. !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 */ getPreviousLocation() : Vec2; /** !#en Returns the start touch location in OpenGL coordinates. !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 */ getStartLocation() : Vec2; /** !#en Returns the delta distance from the previous touche to the current one in screen coordinates. !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 */ getDelta() : Vec2; /** !#en Returns the current touch location in screen coordinates. !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 */ getLocationInView() : Vec2; /** !#en Returns the previous touch location in screen coordinates. !#zh 获取触点在上一次事件时在游戏窗口中的位置对象,对象包含 x 和 y 属性。 */ getPreviousLocationInView() : Vec2; /** !#en Returns the start touch location in screen coordinates. !#zh 获取触点落下时在游戏窗口中的位置对象,对象包含 x 和 y 属性。 */ getStartLocationInView() : Vec2; /** !#en Returns the id of cc.Touch. !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 */ getID() : number; /** !#en Sets information to touch. !#zh 设置触摸相关的信息。用于监控触摸事件。 */ setTouchInfo(id : number, x : number, y : number) : void; } /** Loader for resource loading process. It's a singleton object. */ export class loader extends Pipeline { /** The downloader in cc.loader's pipeline, it's by default the first pipe. It's used to download files with several handlers: pure text, image, script, audio, font, uuid. You can add your own download function with addDownloadHandlers */ downloader : any; /** The downloader in cc.loader's pipeline, it's by default the second pipe. It's used to parse downloaded content with several handlers: JSON, image, plist, fnt, uuid. You can add your own download function with addLoadHandlers */ loader : any; /** Add custom supported types handler or modify existing type handler for download process. @param extMap Custom supported types with corresponded handler @example ```js cc.loader.addDownloadHandlers({ // This will match all url with `.scene` extension or all url with `scene` type 'scene' : function (url, callback) {} }); ``` */ addDownloadHandlers(extMap : any) : void; /** Add custom supported types handler or modify existing type handler for load process. @param extMap Custom supported types with corresponded handler @example ```js cc.loader.addLoadHandlers({ // This will match all url with `.scene` extension or all url with `scene` type 'scene' : function (url, callback) {} }); ``` */ addLoadHandlers(extMap : any) : void; /** Load resources with a progression callback and a complete callback. The progression callback is the same as Pipeline's {{#crossLink "Pipeline/onProgress:method"}}onProgress{{/crossLink}} The complete callback is almost the same as Pipeline's {{#crossLink "Pipeline/onComplete:method"}}onComplete{{/crossLink}} The only difference is when user pass a single url as resources, the complete callback will set its result directly as the second parameter. @param resources Url list in an array @param progressCallback Callback invoked when progression change @param completeCallback Callback invoked when all resources loaded @example ```js cc.loader.load('a.png', function (err, tex) { cc.log('Result should be a texture: ' + (tex instanceof cc.Texture2D)); }); cc.loader.load('http://example.com/a.png', function (err, tex) { cc.log('Should load a texture from external url: ' + (tex instanceof cc.Texture2D)); }); cc.loader.load({id: 'http://example.com/getImageREST?file=a.png', type: 'png'}, function (err, tex) { cc.log('Should load a texture from RESTful API by specify the type: ' + (tex instanceof cc.Texture2D)); }); cc.loader.load(['a.png', 'b.json'], function (errors, results) { if (errors) { for (var i = 0; i < errors.length; i++) { cc.log('Error url [' + errors[i] + ']: ' + results.getError(errors[i])); } } var aTex = results.getContent('a.png'); var bJsonObj = results.getContent('b.json'); }); ``` */ load(resources : string|any[], progressCallback? : Function, completeCallback : Function) : void; /** Load resources from the "resources" folder inside the "assets" folder of your project.

Note: All asset urls in Creator use forward slashes, urls using backslashes will not work. @param url Url of the target resource. The url is relative to the "resources" folder, extensions must be omitted. @param type Only asset of type will be loaded if this argument is supplied. @param completeCallback Callback invoked when the resource loaded. @example ```js // load the prefab (project/assets/resources/misc/character/cocos) from resources folder cc.loader.loadRes('misc/character/cocos', function (err, prefab) { if (err) { cc.error(err.message || err); return; } cc.log('Result should be a prefab: ' + (prefab instanceof cc.Prefab)); }); // load the sprite frame (project/assets/resources/imgs/cocos.png/cocos) from resources folder cc.loader.loadRes('imgs/cocos', cc.SpriteFrame, function (err, spriteFrame) { if (err) { cc.error(err.message || err); return; } cc.log('Result should be a sprite frame: ' + (spriteFrame instanceof cc.SpriteFrame)); }); ``` */ loadRes(url : string, type? : Function, completeCallback: (error: Error, resource: any) => void) : void; /** Load all assets in a folder inside the "assets/resources" folder of your project.

Note: All asset urls in Creator use forward slashes, urls using backslashes will not work. @param url Url of the target folder. The url is relative to the "resources" folder, extensions must be omitted. @param type Only asset of type will be loaded if this argument is supplied. @param completeCallback A callback which is called when all assets have been loaded, or an error occurs. @example ```js // load the texture (resources/imgs/cocos.png) and sprite frame (resources/imgs/cocos.png/cocos) cc.loader.loadResAll('imgs/cocos', function (err, assets) { if (err) { cc.error(err); return; } var texture = assets[0]; var spriteFrame = assets[1]; }); // load all textures in "resources/imgs/" cc.loader.loadResAll('imgs', cc.Texture2D, function (err, textures) { if (err) { cc.error(err); return; } var texture1 = textures[0]; var texture2 = textures[1]; }); ``` */ loadResAll(url : string, type? : Function, completeCallback: (error: Error, assets: any[]) => void) : void; /** Get resource data by id.
When you load resources with {{#crossLink "loader/load:method"}}{{/crossLink}} or {{#crossLink "loader/loadRes:method"}}{{/crossLink}}, the url will be the unique identity of the resource. After loaded, you can acquire them by passing the url to this API. */ getRes(url : string) : any; /** Returns an item in pipeline. */ getItem() : LoadingItem; /** Release the cache of resource by url. */ release(url : string) : void; /** Release the loaded cache of asset. */ releaseAsset(asset : Asset) : void; /** Release the cache of resource which loaded by {{#crossLink "loader/loadRes:method"}}{{/crossLink}}. */ releaseRes(url : string) : void; /** Resource cache of all resources. */ releaseAll() : void; } /** !#en LoadingItems is the manager of items in pipeline.
It hold a map of items, each entry in the map is a url to object key value pair.
Each item always contains the following property:
- id: The identification of the item, usually it's identical to url
- url: The url
- type: The type, it's the extension name of the url by default, could be specified manually too.
- error: The error happened in pipeline will be stored in this property.
- content: The content processed by the pipeline, the final result will also be stored in this property.
- complete: The flag indicate whether the item is completed by the pipeline.
- states: An object stores the states of each pipe the item go through, the state can be: Pipeline.ItemState.WORKING | Pipeline.ItemState.ERROR | Pipeline.ItemState.COMPLETE

Item can hold other custom properties. !#zh LoadingItems 负责管理 pipeline 中的对象
它有一个 map 属性用来存放加载项,在 map 对象中已 url 为 key 值。
每个对象都会包含下列属性:
- id:该对象的标识,通常与 url 相同。
- url:路径
- type: 类型,它这是默认的 URL 的扩展名,可以手动指定赋值。
- error:pipeline 中发生的错误将被保存在这个属性中。
- content: pipeline 中处理的内容时,最终的结果也将被存储在这个属性中。
- complete:该标志表明该对象是否通过 pipeline 完成。
- states:该对象存储每个管道中对象经历的状态,状态可以是 Pipeline.ItemState.WORKING | Pipeline.ItemState.ERROR | Pipeline.ItemState.COMPLETE

对象可容纳其他自定义属性。 */ export class LoadingItems extends CallbacksInvoker { /** !#en The map of all items. !#zh 存储所有加载项的对象。 */ map : any; /** !#en The map of completed items. !#zh 存储已经完成的加载项。 */ completed : any; /** !#en Total count of all items. !#zh 所有加载项的总数。 */ totalCount : number; /** !#en Total count of completed items. !#zh 所有完成加载项的总数。 */ completedCount : number; /** !#en Check whether all items are completed. !#zh 检查是否所有加载项都已经完成。 */ isCompleted() : boolean; /** !#en Check whether an item is completed. !#zh 通过 id 检查指定加载项是否已经加载完成。 @param id The item's id. */ isItemCompleted(id : string) : boolean; /** !#en Check whether an item exists. !#zh 通过 id 检查加载项是否存在。 @param id The item's id. */ exists(id : string) : boolean; /** !#en Returns the content of an internal item. !#zh 通过 id 获取指定对象的内容。 @param id The item's id. */ getContent(id : string) : any; /** !#en Returns the error of an internal item. !#zh 通过 id 获取指定对象的错误信息。 @param id The item's id. */ getError(id : string) : any; /** !#en Add a listener for an item, the callback will be invoked when the item is completed. !#zh 监听加载项(通过 key 指定)的完成事件。 @param callback can be null @param target can be null */ addListener(key : string, callback : Function, target : any) : boolean; /** !#en Check if the specified key has any registered callback.
If a callback is also specified, it will only return true if the callback is registered. !#zh 检查指定的加载项是否有完成事件监听器。
如果同时还指定了一个回调方法,并且回调有注册,它只会返回 true。 */ hasListener(key : string, callback? : Function, target? : any) : boolean; /** !#en Removes a listener.
It will only remove when key, callback, target all match correctly. !#zh 移除指定加载项已经注册的完成事件监听器。
只会删除 key, callback, target 均匹配的监听器。 */ remove(key : string, callback : Function, target : any) : boolean; /** !#en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target. !#zh 删除指定目标的所有完成事件监听器。 @param key The event key to be removed or the target to be removed */ removeAllListeners(key : string|any) : void; } /** !#en A pipeline describes a sequence of manipulations, each manipulation is called a pipe.
It's designed for loading process. so items should be urls, and the url will be the identity of each item during the process.
A list of items can flow in the pipeline and it will output the results of all pipes.
They flow in the pipeline like water in tubes, they go through pipe by pipe separately.
Finally all items will flow out the pipeline and the process is finished. !#zh pipeline 描述了一系列的操作,每个操作都被称为 pipe。
它被设计来做加载过程的流程管理。所以 item 应该是 url,并且该 url 将是在处理中的每个 item 的身份标识。
一个 item 列表可以在 pipeline 中流动,它将输出加载项经过所有 pipe 之后的结果。
它们穿过 pipeline 就像水在管子里流动,将会按顺序流过每个 pipe。
最后当所有加载项都流出 pipeline 时,整个加载流程就结束了。 */ export class Pipeline { /** !#en Constructor, pass an array of pipes to construct a new Pipeline, the pipes will be chained in the given order.
A pipe is an object which must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.
It can also include `async` property to identify whether it's an asynchronous process. !#zh 构造函数,通过一系列的 pipe 来构造一个新的 pipeline,pipes 将会在给定的顺序中被锁定。
一个 pipe 就是一个对象,它包含了字符串类型的 ‘id’ 和 ‘handle’ 函数,在 pipeline 中 id 必须是唯一的。
它还可以包括 ‘async’ 属性以确定它是否是一个异步过程。 @example ```js var pipeline = new Pipeline([ { id: 'Downloader', handle: function (item, callback) {}, async: true }, {id: 'Parser', handle: function (item) {}, async: false} ]); ``` */ Pipeline(pipes : any[]) : void; /** !#en Insert a new pipe at the given index of the pipeline.
A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. !#zh 在给定的索引位置插入一个新的 pipe。
一个 pipe 必须包含一个字符串类型的 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。 @param pipe The pipe to be inserted @param index The index to insert */ insertPipe(pipe : any, index : number) : void; /** !#en Add a new pipe at the end of the pipeline.
A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. !#zh 添加一个新的 pipe 到 pipeline 尾部。
该 pipe 必须包含一个字符串类型 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。 @param pipe The pipe to be appended */ appendPipe(pipe : any) : void; /** !#en Let new items flow into the pipeline.
Each item can be a simple url string or an object, if it's an object, it must contain `id` property.
You can specify its type by `type` property, by default, the type is the extension name in url.
By adding a `skips` property including pipe ids, you can skip these pipe.
The object can contain any supplementary property as you want.
!#zh 让新的 item 流入 pipeline 中。
这里的每个 item 可以是一个简单字符串类型的 url 或者是一个对象, 如果它是一个对象的话,他必须要包含 ‘id’ 属性。
你也可以指定它的 ‘type’ 属性类型,默认情况下,该类型是 ‘url’ 的后缀名。
也通过添加一个 包含 ‘skips’ 属性的 item 对象,你就可以跳过 skips 中包含的 pipe。
该对象可以包含任何附加属性。 @example ```js pipeline.flowIn([ 'res/Background.png', { id: 'res/scene.json', type: 'scene', name: 'scene', skips: ['Downloader'] } ]); ``` */ flowIn(urlList : any[]) : any[]; /** !#en Let new items flow into the pipeline and give a callback when the list of items are all completed.
This is for loading dependencies for an existing item in flow, usually used in a pipe logic.
For example, we have a loader for scene configuration file in JSON, the scene will only be fully loaded
after all its dependencies are loaded, then you will need to use function to flow in all dependencies
found in the configuration file, and finish the loader pipe only after all dependencies are loaded (in the callback). !#zh 让新 items 流入 pipeline 并且当 item 列表完成时进行回调函数。
这个 API 的使用通常是为了加载依赖项。
例如:
我们需要加载一个场景配置的 JSON 文件,该场景会将所有的依赖项全部都加载完毕以后,进行回调表示加载完毕。 */ flowInDeps(urlList : any[], callback : Function) : any[]; /** !#en Copy the item states from one source item to all destination items.
It's quite useful when a pipe generate new items from one source item,
then you should flowIn these generated items into pipeline,
but you probably want them to skip all pipes the source item already go through,
you can achieve it with this API.

For example, an unzip pipe will generate more items, but you won't want them to pass unzip or download pipe again. !#zh 从一个源 item 向所有目标 item 复制它的 pipe 状态,用于避免重复通过部分 pipe。
当一个源 item 生成了一系列新的 items 时很有用,
你希望让这些新的依赖项进入 pipeline,但是又不希望它们通过源 item 已经经过的 pipe,
但是你可能希望他们源 item 已经通过并跳过所有 pipes,
这个时候就可以使用这个 API。 @param srcItem The source item @param dstItems A single destination item or an array of destination items */ copyItemStates(srcItem : any, dstItems : any[]|any) : void; /** !#en Returns whether the pipeline is flowing (contains item) currently. !#zh 获取 pipeline 当前是否正在处理中。 */ isFlowing() : boolean; /** !#en Returns all items in pipeline. !#zh 获取 pipeline 中的所有 items。 */ getItems() : LoadingItems; /** !#en Returns an item in pipeline. !#zh 获取指定 item。 */ getItem() : LoadingItems; /** !#en Removes an item in pipeline, no matter it's in progress or completed. !#zh 移除指定 item,无论是进行时还是已完成。 */ removeItem() : boolean; /** !#en Clear the current pipeline, this function will clean up the items. !#zh 清空当前 pipeline,该函数将清理 items。 */ clear() : void; /** !#en This is a callback which will be invoked while an item flow out the pipeline, you should overwrite this function. !#zh 这个回调函数将在 item 流出 pipeline 时被调用,你应该重写该函数。 @param completedCount The number of the items that are already completed. @param totalCount The total number of the items. @param item The latest item which flow out the pipeline. @example ```js pipeline.onProgress = function (completedCount, totalCount, item) { var progress = (100 * completedCount / totalCount).toFixed(2); cc.log(progress + '%'); } ``` */ onProgress(completedCount : number, totalCount : number, item : any) : void; /** !#en This is a callback which will be invoked while all items flow out the pipeline, you should overwirte this function. !#zh 该函数将在所有 item 流出 pipeline 时被调用,你应该重写该函数。 @param error All errored urls will be stored in this array, if no error happened, then it will be null @param items All items. @example ```js pipeline.onComplete = function (error, items) { if (error) cc.log('Completed with ' + error.length + ' errors'); else cc.log('Completed ' + items.totalCount + ' items'); } ``` */ onComplete(error : any[], items : LoadingItems) : void; } /** undefined */ export class _ComponentAttributes { constructor(); /** Automatically add required component as a dependency. */ requireComponent : Component; /** If specified to a type, prevents Component of the same type (or subtype) to be added more than once to a Node. */ disallowMultiple : Component; /** The menu path to register a component to the editors "Component" menu. Eg. "Rendering/Camera". */ menu : string; /** Makes a component execute in edit mode. By default, all components are only executed in play mode, which means they will not have their callback functions executed while the Editor is in edit mode. */ executeInEditMode : boolean; /** This property is only available if executeInEditMode is true. If specified, the editor's scene view will keep updating this node in 60 fps when it is selected, otherwise, it will update only if necessary. */ playOnFocus : boolean; /** Specifying the url of the custom html to draw the component in inspector. */ inspector : string; /** Specifying the url of the icon to display in inspector. */ icon : string; /** The custom documentation URL */ help : string; } /**

This class manages all events of input. include: touch, mouse, accelerometer, keyboard

*/ export class inputManager { /** */ handleTouchesBegin(touches : any[]) : void; /** */ handleTouchesMove(touches : any[]) : void; /** */ handleTouchesEnd(touches : any[]) : void; /** */ handleTouchesCancel(touches : any[]) : void; /** */ getSetOfTouchesEndOrCancel(touches : any[]) : any[]; /** */ getHTMLElementPosition(element : HTMLElement) : any; /** */ getPreTouch(touch : Touch) : Touch; /** */ setPreTouch(touch : Touch) : void; /** */ getTouchByXY(tx : number, ty : number, pos : Vec2) : Touch; /** */ getTouchByXY(location : Vec2, pos : Vec2, eventType : number) : Event.EventMouse; /** */ getPointByEvent(event : Touch, pos : Vec2) : Vec2; /** */ getTouchesByEvent(event : Touch, pos : Vec2) : any[]; /** */ registerSystemEvent(element : HTMLElement) : void; /** */ update(dt : number) : void; } /** Key map for keyboard event */ export enum KEY { none = 0, back = 0, menu = 0, backspace = 0, tab = 0, enter = 0, shift = 0, ctrl = 0, alt = 0, pause = 0, capslock = 0, escape = 0, space = 0, pageup = 0, pagedown = 0, end = 0, home = 0, left = 0, up = 0, right = 0, down = 0, select = 0, insert = 0, Delete = 0, a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, i = 0, j = 0, k = 0, l = 0, m = 0, n = 0, o = 0, p = 0, q = 0, r = 0, s = 0, t = 0, u = 0, v = 0, w = 0, x = 0, y = 0, z = 0, num0 = 0, num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, num6 = 0, num7 = 0, num8 = 0, num9 = 0, '*' = 0, '+' = 0, '-' = 0, numdel = 0, '/' = 0, f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0, f6 = 0, f7 = 0, f8 = 0, f9 = 0, f10 = 0, f11 = 0, f12 = 0, numlock = 0, scrolllock = 0, ';' = 0, semicolon = 0, equal = 0, '=' = 0, ',' = 0, comma = 0, dash = 0, '.' = 0, period = 0, forwardslash = 0, grave = 0, '[' = 0, openbracket = 0, backslash = 0, ']' = 0, closebracket = 0, quote = 0, dpadLeft = 0, dpadRight = 0, dpadUp = 0, dpadDown = 0, dpadCenter = 0, } /** Image formats */ export enum ImageFormat { JPG = 0, PNG = 0, TIFF = 0, WEBP = 0, PVR = 0, ETC = 0, S3TC = 0, ATITC = 0, TGA = 0, RAWDATA = 0, UNKNOWN = 0, getImageFormatByData = 0, } /** Predefined constants */ export enum Macro { INVALID_INDEX = 0, NODE_TAG_INVALID = 0, PI = 0, PI2 = 0, FLT_MAX = 0, FLT_MIN = 0, RAD = 0, DEG = 0, UINT_MAX = 0, REPEAT_FOREVER = 0, FLT_EPSILON = 0, ONE = 0, ZERO = 0, SRC_ALPHA = 0, SRC_ALPHA_SATURATE = 0, SRC_COLOR = 0, DST_ALPHA = 0, DST_COLOR = 0, ONE_MINUS_SRC_ALPHA = 0, ONE_MINUS_SRC_COLOR = 0, ONE_MINUS_DST_ALPHA = 0, ONE_MINUS_DST_COLOR = 0, ONE_MINUS_CONSTANT_ALPHA = 0, ONE_MINUS_CONSTANT_COLOR = 0, LINEAR = 0, BLEND_DST = 0, WEB_ORIENTATION_PORTRAIT = 0, WEB_ORIENTATION_LANDSCAPE_LEFT = 0, WEB_ORIENTATION_PORTRAIT_UPSIDE_DOWN = 0, WEB_ORIENTATION_LANDSCAPE_RIGHT = 0, ORIENTATION_PORTRAIT = 0, ORIENTATION_LANDSCAPE = 0, ORIENTATION_AUTO = 0, VERTEX_ATTRIB_FLAG_NONE = 0, VERTEX_ATTRIB_FLAG_POSITION = 0, VERTEX_ATTRIB_FLAG_COLOR = 0, VERTEX_ATTRIB_FLAG_TEX_COORDS = 0, VERTEX_ATTRIB_FLAG_POS_COLOR_TEX = 0, GL_ALL = 0, VERTEX_ATTRIB_POSITION = 0, VERTEX_ATTRIB_COLOR = 0, VERTEX_ATTRIB_TEX_COORDS = 0, VERTEX_ATTRIB_MAX = 0, UNIFORM_PMATRIX = 0, UNIFORM_MVMATRIX = 0, UNIFORM_MVPMATRIX = 0, UNIFORM_TIME = 0, UNIFORM_SINTIME = 0, UNIFORM_COSTIME = 0, UNIFORM_RANDOM01 = 0, UNIFORM_SAMPLER = 0, UNIFORM_MAX = 0, SHADER_POSITION_TEXTURECOLOR = 0, SHADER_POSITION_TEXTURECOLORALPHATEST = 0, SHADER_POSITION_COLOR = 0, SHADER_POSITION_TEXTURE = 0, SHADER_POSITION_TEXTURE_UCOLOR = 0, SHADER_POSITION_TEXTUREA8COLOR = 0, SHADER_POSITION_UCOLOR = 0, SHADER_POSITION_LENGTHTEXTURECOLOR = 0, UNIFORM_PMATRIX_S = 0, UNIFORM_MVMATRIX_S = 0, UNIFORM_MVPMATRIX_S = 0, UNIFORM_TIME_S = 0, UNIFORM_SINTIME_S = 0, UNIFORM_COSTIME_S = 0, UNIFORM_RANDOM01_S = 0, UNIFORM_SAMPLER_S = 0, UNIFORM_ALPHA_TEST_VALUE_S = 0, ATTRIBUTE_NAME_COLOR = 0, ATTRIBUTE_NAME_POSITION = 0, ATTRIBUTE_NAME_TEX_COORD = 0, ITEM_SIZE = 0, CURRENT_ITEM = 0, ZOOM_ACTION_TAG = 0, NORMAL_TAG = 0, SELECTED_TAG = 0, DISABLE_TAG = 0, FIX_ARTIFACTS_BY_STRECHING_TEXEL = 0, DIRECTOR_STATS_POSITION = 0, DIRECTOR_FPS_INTERVAL = 0, COCOSNODE_RENDER_SUBPIXEL = 0, SPRITEBATCHNODE_RENDER_SUBPIXEL = 0, AUTO_PREMULTIPLIED_ALPHA_FOR_PNG = 0, OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA = 0, TEXTURE_ATLAS_USE_TRIANGLE_STRIP = 0, TEXTURE_ATLAS_USE_VAO = 0, USE_LA88_LABELS = 0, SPRITE_DEBUG_DRAW = 0, LABELBMFONT_DEBUG_DRAW = 0, LABELATLAS_DEBUG_DRAW = 0, ENABLE_STACKABLE_ACTIONS = 0, ENABLE_GL_STATE_CACHE = 0, BLEND_SRC = 0, lerp = 0, rand = 0, randomMinus1To1 = 0, random0To1 = 0, degreesToRadians = 0, radiansToDegrees = 0, nodeDrawSetup = 0, incrementGLDraws = 0, checkGLErrorDebug = 0, } /** The base class of most of all the objects in Fireball. */ export class Object { constructor(); /** !#en The name of the object. !#zh 该对象的名称。 */ name : string; /** !#en Indicates whether the object is not yet destroyed. !#zh 表示该对象是否可用(被销毁后将不可用)。 */ isValid : boolean; /** !#en Destroy this Object, and release all its own references to other objects.

After destroy, this CCObject is not usable any more.
You can use cc.isValid(obj) (or obj.isValid if obj is non-nil) to check whether the object is destroyed before accessing it. !#zh 销毁该对象,并释放所有它对其它对象的引用。
销毁后,CCObject 不再可用。
您可以在访问对象之前使用 cc.isValid(obj)(或 obj.isValid 如果 obj 不为 null)来检查对象是否已被销毁。 @example ```js obj.destroy(); ``` */ destroy() : boolean; } /** Bit mask that controls object states. */ export class Flags { /** !#en The object will not be saved. !#zh 该对象将不会被保存。 */ DontSave : number; /** !#en The object will not be saved when building a player. !#zh 构建项目时,该对象将不会被保存。 */ EditorOnly : number; } /** The fullscreen API provides an easy way for web content to be presented using the user's entire screen. It's invalid on safari, QQbrowser and android browser */ export class screen { /** initialize */ init() : void; /** return true if it's full now. */ fullScreen() : boolean; /** change the screen to full mode. */ requestFullScreen(element : Element, onFullScreenChange : Function) : void; /** exit the full mode. */ exitFullScreen() : boolean; /** Automatically request full screen with a touch/click event */ autoFullScreen(element : Element, onFullScreenChange : Function) : void; } /** System variables */ export class sys { /** English language code */ LANGUAGE_ENGLISH : string; /** Chinese language code */ LANGUAGE_CHINESE : string; /** French language code */ LANGUAGE_FRENCH : string; /** Italian language code */ LANGUAGE_ITALIAN : string; /** German language code */ LANGUAGE_GERMAN : string; /** Spanish language code */ LANGUAGE_SPANISH : string; /** Spanish language code */ LANGUAGE_DUTCH : string; /** Russian language code */ LANGUAGE_RUSSIAN : string; /** Korean language code */ LANGUAGE_KOREAN : string; /** Japanese language code */ LANGUAGE_JAPANESE : string; /** Hungarian language code */ LANGUAGE_HUNGARIAN : string; /** Portuguese language code */ LANGUAGE_PORTUGUESE : string; /** Arabic language code */ LANGUAGE_ARABIC : string; /** Norwegian language code */ LANGUAGE_NORWEGIAN : string; /** Polish language code */ LANGUAGE_POLISH : string; /** Unknown language code */ LANGUAGE_UNKNOWN : string; OS_IOS : string; OS_ANDROID : string; OS_WINDOWS : string; OS_MARMALADE : string; OS_LINUX : string; OS_BADA : string; OS_BLACKBERRY : string; OS_OSX : string; OS_WP8 : string; OS_WINRT : string; OS_UNKNOWN : string; UNKNOWN : number; WIN32 : number; LINUX : number; MACOS : number; ANDROID : number; IOS : number; IPAD : number; BLACKBERRY : number; NACL : number; EMSCRIPTEN : number; TIZEN : number; WINRT : number; WP8 : number; MOBILE_BROWSER : number; DESKTOP_BROWSER : number; /** Indicates whether executes in editor's window process (Electron's renderer context) */ EDITOR_PAGE : number; /** Indicates whether executes in editor's main process (Electron's browser context) */ EDITOR_CORE : number; /** BROWSER_TYPE_WECHAT */ BROWSER_TYPE_WECHAT : string; BROWSER_TYPE_ANDROID : string; BROWSER_TYPE_IE : string; BROWSER_TYPE_QQ : string; BROWSER_TYPE_MOBILE_QQ : string; BROWSER_TYPE_UC : string; BROWSER_TYPE_360 : string; BROWSER_TYPE_BAIDU_APP : string; BROWSER_TYPE_BAIDU : string; BROWSER_TYPE_MAXTHON : string; BROWSER_TYPE_OPERA : string; BROWSER_TYPE_OUPENG : string; BROWSER_TYPE_MIUI : string; BROWSER_TYPE_FIREFOX : string; BROWSER_TYPE_SAFARI : string; BROWSER_TYPE_CHROME : string; BROWSER_TYPE_LIEBAO : string; BROWSER_TYPE_QZONE : string; BROWSER_TYPE_SOUGOU : string; BROWSER_TYPE_UNKNOWN : string; /** Is native ? This is set to be true in jsb auto. */ isNative : boolean; /** Is web browser ? */ isBrowser : boolean; /** Indicate whether system is mobile system */ isMobile : boolean; /** Indicate the running platform */ platform : number; /** Indicate the current language of the running system */ language : string; /** Indicate the running os name */ os : string; /** Indicate the running browser type */ browserType : string; /** Indicate the running browser version */ browserVersion : number; /** Indicate the real pixel resolution of the whole game window */ windowPixelResolution : number; /** cc.sys.localStorage is a local storage component. */ localStorage : any; /** The capabilities of the current platform */ capabilities : any; /** Forces the garbage collection, only available in JSB */ garbageCollect() : void; /** Dumps rooted objects, only available in JSB */ dumpRoot() : void; /** Restart the JS VM, only available in JSB */ restartVM() : void; /** Clean a script in the JS VM, only available in JSB */ cleanScript(jsfile : string) : void; /** Check whether an object is valid, In web engine, it will return true if the object exist In native engine, it will return true if the JS object and the correspond native object are both valid */ isObjectValid(obj : any) : boolean; /** Dump system informations */ dump() : void; /** Open a url in browser */ openURL(url : string) : void; } /** cc.view is the singleton object which represents the game window.
It's main task include:
- Apply the design resolution policy
- Provide interaction with the window, like resize event on web, retina display support, etc...
- Manage the game view port which can be different with the window
- Manage the content scale and translation

Since the cc.view is a singleton, you don't need to call any constructor or create functions,
the standard way to use it is by calling:
- cc.view.methodName();
*/ export class View { /**

Sets view's target-densitydpi for android mobile browser. it can be set to:
1. cc.macro.DENSITYDPI_DEVICE, value is "device-dpi"
2. cc.macro.DENSITYDPI_HIGH, value is "high-dpi" (default value)
3. cc.macro.DENSITYDPI_MEDIUM, value is "medium-dpi" (browser's default value)
4. cc.macro.DENSITYDPI_LOW, value is "low-dpi"
5. Custom value, e.g: "480"

*/ setTargetDensityDPI(densityDPI : string) : void; /** Returns the current target-densitydpi value of cc.view. */ getTargetDensityDPI() : string; /** Sets whether resize canvas automatically when browser's size changed.
Useful only on web. @param enabled Whether enable automatic resize with browser's resize event */ resizeWithBrowserSize(enabled : boolean) : void; /** Sets the callback function for cc.view's resize action,
this callback will be invoked before applying resolution policy,
so you can do any additional modifications within the callback.
Useful only on web. @param callback The callback function */ setResizeCallback(callback : Function|void) : void; /** Sets the orientation of the game, it can be landscape, portrait or auto. When set it to landscape or portrait, and screen w/h ratio doesn't fit, cc.view will automatically rotate the game canvas using CSS. Note that this function doesn't have any effect in native, in native, you need to set the application orientation in native project settings @param orientation Possible values: cc.macro.ORIENTATION_LANDSCAPE | cc.macro.ORIENTATION_PORTRAIT | cc.macro.ORIENTATION_AUTO */ setOrientation(orientation : number) : void; /** Sets whether the engine modify the "viewport" meta in your web page.
It's enabled by default, we strongly suggest you not to disable it.
And even when it's enabled, you can still set your own "viewport" meta, it won't be overridden
Only useful on web @param enabled Enable automatic modification to "viewport" meta */ adjustViewPort(enabled : boolean) : void; /** Retina support is enabled by default for Apple device but disabled for other devices,
it takes effect only when you called setDesignResolutionPolicy
Only useful on web @param enabled Enable or disable retina display */ enableRetina(enabled : boolean) : void; /** Check whether retina display is enabled.
Only useful on web */ isRetinaEnabled() : boolean; /** If enabled, the application will try automatically to enter full screen mode on mobile devices
You can pass true as parameter to enable it and disable it by passing false.
Only useful on web @param enabled Enable or disable auto full screen on mobile devices */ enableAutoFullScreen(enabled : boolean) : void; /** Check whether auto full screen is enabled.
Only useful on web */ isAutoFullScreenEnabled() : boolean; /** Get whether render system is ready(no matter opengl or canvas),
this name is for the compatibility with cocos2d-x, subclass must implement this method. */ isViewReady() : boolean; /** Sets the resolution translate on View. */ setContentTranslateLeftTop(offsetLeft : number, offsetTop : number) : void; /** Returns the resolution translate on View */ getContentTranslateLeftTop() : Size; /** Returns the frame size of the view.
On native platforms, it returns the screen size since the view is a fullscreen view.
On web, it returns the size of the canvas's outer DOM element. */ getFrameSize() : Size; /** On native, it sets the frame size of view.
On web, it sets the size of the canvas's outer DOM element. */ setFrameSize(width : number, height : number) : void; /** Returns the visible area size of the view port. */ getVisibleSize() : Size; /** Returns the visible area size of the view port. */ getVisibleSizeInPixel() : Size; /** Returns the visible origin of the view port. */ getVisibleOrigin() : Vec2; /** Returns the visible origin of the view port. */ getVisibleOriginInPixel() : Vec2; /** Returns whether developer can set content's scale factor. */ canSetContentScaleFactor() : boolean; /** Returns the current resolution policy */ getResolutionPolicy() : ResolutionPolicy; /** Sets the current resolution policy */ setResolutionPolicy(resolutionPolicy : ResolutionPolicy|number) : void; /** Sets the resolution policy with designed view size in points.
The resolution policy include:
[1] ResolutionExactFit Fill screen by stretch-to-fit: if the design resolution ratio of width to height is different from the screen resolution ratio, your game view will be stretched.
[2] ResolutionNoBorder Full screen without black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two areas of your game view will be cut.
[3] ResolutionShowAll Full screen with black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two black borders will be shown.
[4] ResolutionFixedHeight Scale the content's height to screen's height and proportionally scale its width
[5] ResolutionFixedWidth Scale the content's width to screen's width and proportionally scale its height
[cc.ResolutionPolicy] [Web only feature] Custom resolution policy, constructed by cc.ResolutionPolicy
@param width Design resolution width. @param height Design resolution height. @param resolutionPolicy The resolution policy desired */ setDesignResolutionSize(width : number, height : number, resolutionPolicy : ResolutionPolicy|number) : void; /** Returns the designed size for the view. Default resolution size is the same as 'getFrameSize'. */ getDesignResolutionSize() : Size; /** Sets the container to desired pixel resolution and fit the game content to it. This function is very useful for adaptation in mobile browsers. In some HD android devices, the resolution is very high, but its browser performance may not be very good. In this case, enabling retina display is very costy and not suggested, and if retina is disabled, the image may be blurry. But this API can be helpful to set a desired pixel resolution which is in between. This API will do the following: 1. Set viewport's width to the desired width in pixel 2. Set body width to the exact pixel resolution 3. The resolution policy will be reset with designed view size in points. @param width Design resolution width. @param height Design resolution height. @param resolutionPolicy The resolution policy desired */ setRealPixelResolution(width : number, height : number, resolutionPolicy : ResolutionPolicy|number) : void; /** Sets view port rectangle with points. @param w width @param h height */ setViewPortInPoints(x : number, y : number, w : number, h : number) : void; /** Sets Scissor rectangle with points. */ setScissorInPoints(x : number, y : number, w : number, h : number) : void; /** Returns whether GL_SCISSOR_TEST is enable */ isScissorEnabled() : boolean; /** Returns the current scissor rectangle */ getScissorRect() : Rect; /** Sets the name of the view */ setViewName(viewName : string) : void; /** Returns the name of the view */ getViewName() : string; /** Returns the view port rectangle. */ getViewPortRect() : Rect; /** Returns scale factor of the horizontal direction (X axis). */ getScaleX() : number; /** Returns scale factor of the vertical direction (Y axis). */ getScaleY() : number; /** Returns device pixel ratio for retina display. */ getDevicePixelRatio() : number; /** Returns the real location in view for a translation based on a related position @param tx The X axis translation @param ty The Y axis translation @param relatedPos The related position object including "left", "top", "width", "height" informations */ convertToLocationInView(tx : number, ty : number, relatedPos : any) : Vec2; } /**

cc.ContainerStrategy class is the root strategy class of container's scale strategy, it controls the behavior of how to scale the cc.container and cc.game.canvas object

*/ export class ContainerStrategy { /** Manipulation before appling the strategy @param view The target view */ preApply(view : View) : void; /** Function to apply this strategy */ apply(view : View, designedResolution : Size) : void; /** Manipulation after applying the strategy @param view The target view */ postApply(view : View) : void; } /**

cc.ContentStrategy class is the root strategy class of content's scale strategy, it controls the behavior of how to scale the scene and setup the viewport for the game

*/ export class ContentStrategy { /** Manipulation before applying the strategy @param view The target view */ preApply(view : View) : void; /** Function to apply this strategy The return value is {scale: [scaleX, scaleY], viewport: {cc.Rect}}, The target view can then apply these value to itself, it's preferred not to modify directly its private variables */ apply(view : View, designedResolution : Size) : any; /** Manipulation after applying the strategy @param view The target view */ postApply(view : View) : void; } /** undefined */ export class EqualToFrame extends ContainerStrategy { } /** undefined */ export class ProportionalToFrame extends ContainerStrategy { } /** undefined */ export class EqualToWindow extends EqualToFrame { } /** undefined */ export class ProportionalToWindow extends ProportionalToFrame { } /** undefined */ export class OriginalContainer extends ContainerStrategy { } /**

cc.ResolutionPolicy class is the root strategy class of scale strategy, its main task is to maintain the compatibility with Cocos2d-x

*/ export class ResolutionPolicy { /** @param containerStg The container strategy @param contentStg The content strategy */ ResolutionPolicy(containerStg : ContainerStrategy, contentStg : ContentStrategy) : void; /** Manipulation before applying the resolution policy @param view The target view */ preApply(view : View) : void; /** Function to apply this resolution policy The return value is {scale: [scaleX, scaleY], viewport: {cc.Rect}}, The target view can then apply these value to itself, it's preferred not to modify directly its private variables @param view The target view @param designedResolution The user defined design resolution */ apply(view : View, designedResolution : Size) : any; /** Manipulation after appyling the strategy @param view The target view */ postApply(view : View) : void; /** Setup the container's scale strategy */ setContainerStrategy(containerStg : ContainerStrategy) : void; /** Setup the content's scale strategy */ setContentStrategy(contentStg : ContentStrategy) : void; /** The entire application is visible in the specified area without trying to preserve the original aspect ratio.
Distortion can occur, and the application may appear stretched or compressed. */ EXACT_FIT : number; /** The entire application fills the specified area, without distortion but possibly with some cropping,
while maintaining the original aspect ratio of the application. */ NO_BORDER : number; /** The entire application is visible in the specified area without distortion while maintaining the original
aspect ratio of the application. Borders can appear on two sides of the application. */ SHOW_ALL : number; /** The application takes the height of the design resolution size and modifies the width of the internal
canvas so that it fits the aspect ratio of the device
no distortion will occur however you must make sure your application works on different
aspect ratios */ FIXED_HEIGHT : number; /** The application takes the width of the design resolution size and modifies the height of the internal
canvas so that it fits the aspect ratio of the device
no distortion will occur however you must make sure your application works on different
aspect ratios */ FIXED_WIDTH : number; /** Unknow policy */ UNKNOWN : number; } /** cc.visibleRect is a singleton object which defines the actual visible rect of the current view, it should represent the same rect as cc.view.getViewportRect() */ export class visibleRect { /** initialize */ init(visibleRect : Rect) : void; /** Top left coordinate of the screen related to the game scene. */ topLeft : Vec2; /** Top right coordinate of the screen related to the game scene. */ topRight : Vec2; /** Top center coordinate of the screen related to the game scene. */ top : Vec2; /** Bottom left coordinate of the screen related to the game scene. */ bottomLeft : Vec2; /** Bottom right coordinate of the screen related to the game scene. */ bottomRight : Vec2; /** Bottom center coordinate of the screen related to the game scene. */ bottom : Vec2; /** Center coordinate of the screen related to the game scene. */ center : Vec2; /** Left center coordinate of the screen related to the game scene. */ left : Vec2; /** Right center coordinate of the screen related to the game scene. */ right : Vec2; /** Width of the screen. */ width : number; /** Height of the screen. */ height : number; } /** The CallbacksHandler is an abstract class that can register and unregister callbacks by key. Subclasses should implement their own methods about how to invoke the callbacks. */ export class _CallbacksHandler { constructor(); /** @param target can be null */ add(key : string, callback : Function, target? : any) : boolean; /** Check if the specified key has any registered callback. If a callback is also specified, it will only return true if the callback is registered. */ has(key : string, callback? : Function, target? : any) : boolean; /** Removes all callbacks registered in a certain event type or all callbacks registered with a certain target @param key The event key to be removed or the target to be removed */ removeAll(key : string|any) : void; /** */ remove(key : string, callback : Function, target : any) : boolean; } /** !#en The callbacks invoker to handle and invoke callbacks by key. !#zh CallbacksInvoker 用来根据 Key 管理并调用回调方法。 */ export class CallbacksInvoker extends _CallbacksHandler { constructor(); /** */ invoke(key : string, p1? : any, p2? : any, p3? : any, p4? : any, p5? : any) : void; /** */ invokeAndRemove(key : string, p1? : any, p2? : any, p3? : any, p4? : any, p5? : any) : void; /** @param remove remove callbacks after invoked */ bindKey(key : string, remove? : boolean) : Function; } /** !#en Contains information collected during deserialization !#zh 包含反序列化时的一些信息 */ export class Details { constructor(); /** list of the depends assets' uuid */ uuidList : String[]; /** the obj list whose field needs to load asset by uuid */ uuidObjList : any[]; /** the corresponding field name which referenced to the asset */ uuidPropList : String[]; /** the corresponding field name which referenced to the raw object */ rawProp : string; reset() : void; /** */ getUuidOf(obj : any, propName : string) : string; /** */ assignAssetsBy(getter : Function) : boolean; /** */ push(obj : any, propName : string, uuid : string) : void; } /** undefined */ export class url { /** Returns the url of raw assets, you will only need this if the raw asset is inside the "resources" folder. @example ```js --- var url = cc.url.raw("textures/myTexture.png"); console.log(url); // "resources/raw/textures/myTexture.png" ``` */ raw(url : string) : string; /** Returns the url of builtin raw assets. This method can only used in editor. @example ```js --- var url = cc.url.builtinRaw("textures/myTexture.png"); console.log(url); // "resources/default-raw/textures/myTexture.png" ``` */ builtinRaw(url : string) : string; } /** A cc.SpriteFrame has:
- texture: A cc.Texture2D that will be used by the _ccsg.Sprite
- rectangle: A rectangle of the texture

You can modify the frame of a _ccsg.Sprite by doing:
*/ export class SpriteFrame extends Asset { constructor(); /** Constructor of SpriteFrame class @param rotated Whether the frame is rotated in the texture @param offset The offset of the frame in the texture @param originalSize The size of the frame in the texture @example ```js // ---------------------------------------------------- // 1. Create a cc.SpriteFrame with image path var url = cc.url.raw('resources/textures/grossini_dance.png'); var frame1 = new cc.SpriteFrame(url, cc.Rect(0, 0, 90, 128)); // ---------------------------------------------------- // 2. Create a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels. var url = cc.url.raw('resources/textures/grossini_dance.png'); var texture = cc.textureCache.addImage(url); var frame1 = new cc.SpriteFrame(texture, cc.Rect(0, 0, 90, 128)); var frame2 = new cc.SpriteFrame(texture, cc.Rect(0, 0, 90, 128), false, 0, cc.Size(90, 128)); // ---------------------------------------------------- // 3. load a cc.SpriteFrame with image path (Recommend) var url = 'resources://test assets/PurpleMonster.png/PurpleMonster'; var self = this; cc.loader.load(url, function (err, spriteFrame) { var node = new cc.Node("New Sprite"); var sprite = node.addComponent(cc.Sprite); sprite.spriteFrame = spriteFrame; node.parent = self.node } ); ``` */ SpriteFrame(filename? : string|Texture2D, rect? : Rect, rotated? : boolean, offset? : Vec2, originalSize? : Size) : void; /** Top border of the sprite */ insetTop : number; /** Bottom border of the sprite */ insetBottom : number; /** Left border of the sprite */ insetLeft : number; /** Right border of the sprite */ insetRight : number; /** Returns whether the texture have been loaded */ textureLoaded() : boolean; /** Add a event listener for texture loaded event. */ addLoadedEventListener(callback : Function, target : any) : void; /** Returns whether the sprite frame is rotated in the texture. */ isRotated() : boolean; /** Set whether the sprite frame is rotated in the texture. */ setRotated(bRotated : boolean) : void; /** Returns the rect of the sprite frame in the texture. */ getRect() : Rect; /** Sets the rect of the sprite frame in the texture. */ setRect(rect : Rect) : void; /** Returns the original size of the trimmed image. */ getOriginalSize() : Size; /** Sets the original size of the trimmed image. */ setOriginalSize(size : Size) : void; /** Returns the texture of the frame. */ getTexture() : Texture2D; /** Sets the texture of the frame, the texture is retained automatically. */ _refreshTexture(texture : Texture2D) : void; /** Returns the offset of the frame in the texture. */ getOffset() : Vec2; /** Sets the offset of the frame in the texture. */ setOffset(offsets : Vec2) : void; /** Clone the sprite frame. */ clone() : SpriteFrame; /** Initializes SpriteFrame with Texture, rect, rotated, offset and originalSize in pixels.
Please pass parameters to the constructor to initialize the sprite, do not call this function yourself. */ initWithTexture(texture : string|Texture2D, rect? : Rect, rotated? : boolean, offset? : Vec2, originalSize? : Size) : boolean; /** Copy the sprite frame */ copyWithZone() : SpriteFrame; /** Copy the sprite frame */ copy() : SpriteFrame; } /**

This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data.
The created cc.Texture2D object will always have power-of-two dimensions.
Depending on how you create the cc.Texture2D object, the actual image area of the texture might be smaller than the texture dimensions
i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
Be aware that the content of the generated textures will be upside-down!

*/ export class Texture2D extends RawAsset { /** Get width in pixels. */ getPixelWidth() : number; /** Get height of in pixels. */ getPixelHeight() : number; /** Get content size. */ getContentSize() : Size; /** Get content size in pixels. */ getContentSizeInPixels() : Size; /** Init with HTML element. @example ```js var img = new Image(); img.src = dataURL; texture.initWithElement(img); texture.handleLoadedTexture(); ``` */ initWithElement(element : HTMLImageElement|HTMLCanvasElement) : void; /** Intializes with a texture2d with data. */ initWithData(data : any[], pixelFormat : number, pixelsWide : number, pixelsHigh : number, contentSize : Size) : boolean; /** Initializes a texture from a UIImage object. Extensions to make it easy to create a CCTexture2D object from an image file. Note that RGBA type textures will have their alpha premultiplied - use the blending mode (gl.ONE, gl.ONE_MINUS_SRC_ALPHA). */ initWithImage(uiImage : HTMLImageElement) : boolean; /** HTMLElement Object getter. */ getHtmlElementObj() : HTMLImageElement; /** Check whether texture is loaded. */ isLoaded() : boolean; /** Handler of texture loaded event. */ handleLoadedTexture(premultiplied? : boolean) : void; /** Description of cc.Texture2D. */ description() : string; /** Release texture. */ releaseTexture() : void; /** Pixel format of the texture. */ getPixelFormat() : number; /** Whether or not the texture has their Alpha premultiplied, support only in WebGl rendering mode. */ hasPremultipliedAlpha() : boolean; /** Whether or not use mipmap, support only in WebGl rendering mode. */ hasMipmaps() : boolean; /** Sets the min filter, mag filter, wrap s and wrap t texture parameters.
If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}. @param texParams texParams object or minFilter */ setTexParameters(texParams : any|number, magFilter? : number, wrapS? : Texture2D.WrapMode, wrapT? : Texture2D.WrapMode) : void; /** WebGLTexture Object. */ name : WebGLTexture; /** Pixel format of the texture. */ pixelFormat : number; /** Width in pixels. */ pixelWidth : number; /** Height in pixels. */ pixelHeight : number; /** Content width in points. */ width : number; /** Content height in points. */ height : number; } /**

A class that implements a Texture Atlas.
Supported features:
The atlas file can be a PNG, JPG.
Quads can be updated in runtime
Quads can be added in runtime
Quads can be removed in runtime
Quads can be re-ordered in runtime
The TextureAtlas capacity can be increased or decreased in runtime.

*/ export class TextureAtlas { constructor(); /**

Creates a TextureAtlas with an filename and with an initial capacity for Quads.
The TextureAtlas capacity can be increased in runtime.

Constructor of cc.TextureAtlas @example ```js -------------------------- 1. //creates a TextureAtlas with filename var textureAtlas = new cc.TextureAtlas("res/hello.png", 3); 2. //creates a TextureAtlas with texture var texture = cc.textureCache.addImage("hello.png"); var textureAtlas = new cc.TextureAtlas(texture, 3); ``` */ TextureAtlas(fileName : string|Texture2D, capacity : number) : void; /** Quantity of quads that are going to be drawn. */ getTotalQuads() : number; /** Quantity of quads that can be stored with the current texture atlas size. */ getCapacity() : number; /** Texture of the texture atlas. */ getTexture() : Image; /** Set texture for texture atlas. */ setTexture(texture : Image) : void; /** specify if the array buffer of the VBO needs to be updated. */ setDirty(dirty : boolean) : void; /** whether or not the array buffer of the VBO needs to be updated. */ isDirty() : boolean; /** Quads that are going to be rendered. */ getQuads() : any[]; /** */ setQuads(quads : any[]) : void; /**

Initializes a TextureAtlas with a filename and with a certain capacity for Quads.
The TextureAtlas capacity can be increased in runtime.
WARNING: Do not reinitialize the TextureAtlas because it will leak memory.

@example ```js -------------------------------------------------- var textureAtlas = new cc.TextureAtlas(); textureAtlas.initWithTexture("hello.png", 3); ``` */ initWithFile(file : string, capacity : number) : boolean; /**

Initializes a TextureAtlas with a previously initialized Texture2D object, and
with an initial capacity for Quads.
The TextureAtlas capacity can be increased in runtime.
WARNING: Do not reinitialize the TextureAtlas because it will leak memory

@example ```js --------------------------- var texture = cc.textureCache.addImage("hello.png"); var textureAtlas = new cc.TextureAtlas(); textureAtlas.initWithTexture(texture, 3); ``` */ initWithTexture(texture : Image, capacity : number) : boolean; /**

Updates a Quad (texture, vertex and color) at a certain index
index must be between 0 and the atlas capacity - 1

*/ updateQuad(quad : V3F_C4B_T2F_Quad, index : number) : void; /**

Inserts a Quad (texture, vertex and color) at a certain index
index must be between 0 and the atlas capacity - 1

*/ insertQuad(quad : V3F_C4B_T2F_Quad, index : number) : void; /**

Inserts a c array of quads at a given index
index must be between 0 and the atlas capacity - 1
this method doesn't enlarge the array when amount + index > totalQuads

*/ insertQuads(quads : any[], index : number, amount : number) : void; /**

Removes the quad that is located at a certain index and inserts it at a new index
This operation is faster than removing and inserting in a quad in 2 different steps

*/ insertQuadFromIndex(fromIndex : number, newIndex : number) : void; /**

Removes a quad at a given index number.
The capacity remains the same, but the total number of quads to be drawn is reduced in 1

*/ removeQuadAtIndex(index : number) : void; /** Removes a given number of quads at a given index. */ removeQuadsAtIndex(index : number, amount : number) : void; /**

Removes all Quads.
The TextureAtlas capacity remains untouched. No memory is freed.
The total number of quads to be drawn will be 0

*/ removeAllQuads() : void; /**

Resize the capacity of the CCTextureAtlas.
The new capacity can be lower or higher than the current one
It returns YES if the resize was successful.
If it fails to resize the capacity it will return NO with a new capacity of 0.
no used for js

*/ resizeCapacity(newCapacity : number) : boolean; /** Used internally by CCParticleBatchNode
don't use this unless you know what you're doing. */ increaseTotalQuadsWith(amount : number) : void; /** Moves an amount of quads from oldIndex at newIndex. */ moveQuadsFromIndex(oldIndex : number, amount : number, newIndex : number) : void; /** Ensures that after a realloc quads are still empty
Used internally by CCParticleBatchNode. */ fillWithEmptyQuadsFromIndex(index : number, amount : number) : void; /**

Draws n quads from an index (offset).
n + start can't be greater than the capacity of the atlas

*/ drawNumberOfQuads(n : number, start : number) : void; /** Indicates whether or not the array buffer of the VBO needs to be updated. */ dirty : boolean; /** Image texture for cc.TextureAtlas. */ texture : Image; /** Quantity of quads that can be stored with the current texture atlas size. */ capacity : number; /** Quantity of quads that are going to be drawn. */ totalQuads : number; /** Quads that are going to be rendered. */ quads : any[]; } /** cc.textureCache is a singleton object, it's the global cache for cc.Texture2D */ export class textureCache { /** Description */ description() : string; /** Returns an already created texture. Returns null if the texture doesn't exist. @example ```js ------------------ var key = cc.textureCache.textureForKey("hello.png"); ``` */ textureForKey(textureKeyName : string) : Texture2D; /** Returns an already created texture. Returns null if the texture doesn't exist. @example ```js ------------------ var key = cc.textureCache.getTextureForKey("hello.png"); ``` */ getTextureForKey(textureKeyName : string) : Texture2D; /** @example ```js --------- var key = cc.textureCache.getKeyByTexture(texture); ``` */ getKeyByTexture(texture : Image) : string; /** @example ```js --------------- var cacheTextureForColor = cc.textureCache.getTextureColors(texture); ``` */ getTextureColors(texture : Image) : any[]; /**

Purges the dictionary of loaded textures.
Call this method if you receive the "Memory Warning"
In the short term: it will free some resources preventing your app from being killed
In the medium term: it will allocate more resources
In the long term: it will be the same

@example ```js -------- cc.textureCache.removeAllTextures(); ``` */ removeAllTextures() : void; /** Deletes a texture from the cache given a texture. @example ```js ----- cc.textureCache.removeTexture(texture); ``` */ removeTexture(texture : Image) : void; /** Deletes a texture from the cache given a its key name. @example ```js ------ cc.textureCache.removeTexture("hello.png"); ``` */ removeTextureForKey(textureKeyName : string) : void; /**

Returns a Texture2D object given an file image
If the file image was not previously loaded, it will create a new Texture2D
object and it will return it. It will use the filename as a key.
Otherwise it will return a reference of a previously loaded image.
Supported image extensions: .png, .jpg, .gif

@example ```js ---- cc.textureCache.addImage("hello.png"); ``` */ addImage(url : string, cb : Function, target : any) : Texture2D; /** Cache the image data. */ cacheImage(path : string, texture : Image|HTMLImageElement|HTMLCanvasElement) : void; /**

Returns a Texture2D object given an UIImage image
If the image was not previously loaded, it will create a new Texture2D object and it will return it.
Otherwise it will return a reference of a previously loaded image
The "key" parameter will be used as the "key" for the cache.
If "key" is null, then a new texture will be created each time.

*/ addUIImage(image : HTMLImageElement|HTMLCanvasElement, key : string) : Texture2D; } /** A base node for CCNode and CCEScene, it will: - provide the same api with origin cocos2d rendering node (SGNode) - maintains properties of the internal SGNode - retain and release the SGNode - serialize datas for SGNode (but SGNode itself will not being serialized) - notifications if some properties changed - define some interfaces shares between CCNode and CCEScene */ export class _BaseNode extends Object { /** !#en Name of node. !#zh 该节点名称。 */ name : string; /** !#en The parent of the node. !#zh 该节点的父节点。 */ parent : Node; /** !#en The uuid for editor, will be stripped before building project. !#zh 用于编辑器使用的 uuid,在构建项目之前将会被剔除。 */ uuid : string; /** !#en Skew x !#zh 该节点 Y 轴倾斜角度。 */ skewX : number; /** !#en Skew y !#zh 该节点 X 轴倾斜角度。 */ skewY : number; /** !#en Z order in depth which stands for the drawing order. !#zh 该节点渲染排序的 Z 轴深度。 */ zIndex : number; /** !#en Rotation of node. !#zh 该节点旋转角度。 */ rotation : number; /** !#en Rotation on x axis. !#zh 该节点 X 轴旋转角度。 */ rotationX : number; /** !#en Rotation on y axis. !#zh 该节点 Y 轴旋转角度。 */ rotationY : number; /** !#en Scale on x axis. !#zh 节点 X 轴缩放。 */ scaleX : number; /** !#en Scale on y axis. !#zh 节点 Y 轴缩放。 */ scaleY : number; /** !#en x axis position of node. !#zh 节点 X 轴坐标。 */ x : number; /** !#en y axis position of node. !#zh 节点 Y 轴坐标。 */ y : number; /** !#en All children nodes. !#zh 节点的所有子节点。 */ children : Node[]; /** !#en All children nodes. !#zh 节点的子节点数量。 */ childrenCount : number; /** !#en Anchor point's position on x axis. !#zh 节点 X 轴锚点位置。 */ anchorX : number; /** !#en Anchor point's position on y axis. !#zh 节点 Y 轴锚点位置。 */ anchorY : number; /** !#en Width of node. !#zh 节点宽度。 */ width : number; /** !#en Height of node. !#zh 节点高度。 */ height : number; /** !#en Tag of node. !#zh 节点标签。 */ tag : number; /** !#en Opacity of node, default value is 255. !#zh 节点透明度,默认值为 255。 */ opacity : number; /** !#en Indicate whether node's opacity value affect its child nodes, default value is false. !#zh 节点的不透明度值是否影响其子节点,默认值为 false。 */ cascadeOpacity : boolean; /** !#en Color of node, default value is white: (255, 255, 255). !#zh 节点颜色。默认为白色,数值为:(255,255,255)。 */ color : Color; /** !#en Properties configuration function
All properties in attrs will be set to the node,
when the setter of the node is available,
the property will be set via setter function.
!#zh 属性配置函数。在 attrs 的所有属性将被设置为节点属性。 @param attrs Properties to be set to node @example ```js var attrs = { key: 0, num: 100 }; node.attr(attrs); ``` */ attr(attrs : any) : void; /** !#en Defines the oder in which the nodes are renderer. Nodes that have a Global Z Order lower, are renderer first.
In case two or more nodes have the same Global Z Order, the oder is not guaranteed. The only exception if the Nodes have a Global Z Order == 0. In that case, the Scene Graph order is used.
By default, all nodes have a Global Z Order = 0. That means that by default, the Scene Graph order is used to render the nodes.
Global Z Order is useful when you need to render nodes in an order different than the Scene Graph order.
Limitations: Global Z Order can't be used used by Nodes that have SpriteBatchNode as one of their ancestors. And if ClippingNode is one of the ancestors, then "global Z order" will be relative to the ClippingNode. !#zh 定义节点的渲染顺序。 节点具有全局 Z 顺序,顺序越小的节点,最先渲染。
假设两个或者更多的节点拥有相同的全局 Z 顺序,那么渲染顺序无法保证。 唯一的例外是如果节点的全局 Z 顺序为零,那么场景中的顺序是可以使用默认的。
所有的节点全局 Z 顺序都是零。这就是说,默认使用场景中的顺序来渲染节点。
全局 Z 顺序是非常有用的当你需要渲染节点按照不同的顺序而不是场景顺序。
局限性: 全局 Z 顺序不能够被拥有继承 “SpriteBatchNode” 的节点使用。 并且如果 “ClippingNode” 是其中之一的上代,那么 “global Z order” 将会和 “ClippingNode” 有关。 @example ```js node.setGlobalZOrder(0); ``` */ setGlobalZOrder(globalZOrder : number) : void; /** !#en Return the Node's Global Z Order. !#zh 获取节点的全局 Z 顺序。 @example ```js cc.log("Global Z Order: " + node.getGlobalZOrder()); ``` */ getGlobalZOrder() : number; /** !#en Returns the scale factor of the node. Assertion will fail when _scaleX != _scaleY. !#zh 获取节点的缩放。当 X 轴和 Y 轴有相同的缩放数值时。 @example ```js cc.log("Node Scale: " + node.getScale()); ``` */ getScale() : number; /** !#en Sets the scale factor of the node. 1.0 is the default scale factor. This function can modify the X and Y scale at the same time. !#zh 设置节点的缩放比例,默认值为 1.0。这个函数可以在同一时间修改 X 和 Y 缩放。 @param scale scaleX or scale @example ```js node.setScale(cc.v2(1, 1)); node.setScale(1, 1); ``` */ setScale(scale : number|Vec2, scaleY? : number) : void; /** !#en Returns a copy of the position (x,y) of the node in cocos2d coordinates. (0,0) is the left-bottom corner. !#zh 获取在父节点坐标系中节点的位置( x , y )。 @example ```js cc.log("Node Position: " + node.getPosition()); ``` */ getPosition() : Vec2; /** !#en Changes the position (x,y) of the node in cocos2d coordinates.
The original point (0,0) is at the left-bottom corner of screen.
Usually we use cc.v2(x,y) to compose CCVec2 object.
and Passing two numbers (x,y) is more efficient than passing CCPoint object. !#zh 设置节点在父坐标系中的位置。
可以通过 2 种方式设置坐标点:
1.传入 cc.v2(x, y) 类型为 cc.Vec2 的对象。
2.传入 2 个数值 x 和 y。 @param newPosOrxValue The position (x,y) of the node in coordinates or the X coordinate for position @param yValue Y coordinate for position @example ```js node.setPosition(cc.v2(0, 0)); node.setPosition(0, 0); ``` */ setPosition(newPosOrxValue : Vec2|number, yValue? : number) : void; /** !#en Returns a copy of the anchor point.
Anchor point is the point around which all transformations and positioning manipulations take place.
It's like a pin in the node where it is "attached" to its parent.
The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
But you can use values higher than (1,1) and lower than (0,0) too.
The default anchor point is (0.5,0.5), so it starts at the center of the node. !#zh 获取节点锚点,用百分比表示。
锚点应用于所有变换和坐标点的操作,它就像在节点上连接其父节点的大头针。
锚点是标准化的,就像百分比一样。(0,0) 表示左下角,(1,1) 表示右上角。
但是你可以使用比(1,1)更高的值或者比(0,0)更低的值。
默认的锚点是(0.5,0.5),因此它开始于节点的中心位置。
注意:Creator 中的锚点仅用于定位所在的节点,子节点的定位不受影响。 @example ```js cc.log("Node AnchorPoint: " + node.getAnchorPoint()); ``` */ getAnchorPoint() : Vec2; /** !#en Sets the anchor point in percent.
anchor point is the point around which all transformations and positioning manipulations take place.
It's like a pin in the node where it is "attached" to its parent.
The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
But you can use values higher than (1,1) and lower than (0,0) too.
The default anchor point is (0.5,0.5), so it starts at the center of the node. !#zh 设置锚点的百分比。
锚点应用于所有变换和坐标点的操作,它就像在节点上连接其父节点的大头针。
锚点是标准化的,就像百分比一样。(0,0) 表示左下角,(1,1) 表示右上角。
但是你可以使用比(1,1)更高的值或者比(0,0)更低的值。
默认的锚点是(0.5,0.5),因此它开始于节点的中心位置。
注意:Creator 中的锚点仅用于定位所在的节点,子节点的定位不受影响。 @param point The anchor point of node or The x axis anchor of node. @param y The y axis anchor of node. @example ```js node.setAnchorPoint(cc.v2(1, 1)); node.setAnchorPoint(1, 1); ``` */ setAnchorPoint(point : Vec2|number, y? : number) : void; /** !#en Returns a copy of the anchor point in absolute pixels.
you can only read it. If you wish to modify it, use setAnchorPoint. !#zh 返回锚点的绝对像素位置。
你只能读它。如果您要修改它,使用 setAnchorPoint。 @example ```js cc.log("AnchorPointInPoints: " + node.getAnchorPointInPoints()); ``` */ getAnchorPointInPoints() : Vec2; /** !#en Returns a copy the untransformed size of the node.
The contentSize remains the same no matter the node is scaled or rotated.
All nodes has a size. Layer and Scene has the same size of the screen by default.
!#zh 获取节点自身大小,不受该节点是否被缩放或者旋转的影响。 @param ignoreSizeProvider true if you need to get the original size of the node @example ```js cc.log("Content Size: " + node.getContentSize()); ``` */ getContentSize(ignoreSizeProvider? : boolean) : Size; /** !#en Sets the untransformed size of the node.
The contentSize remains the same no matter the node is scaled or rotated.
All nodes has a size. Layer and Scene has the same size of the screen. !#zh 设置节点原始大小,不受该节点是否被缩放或者旋转的影响。 @param size The untransformed size of the node or The untransformed size's width of the node. @param height The untransformed size's height of the node. @example ```js node.setContentSize(cc.size(100, 100)); node.setContentSize(100, 100); ``` */ setContentSize(size : Size|number, height? : number) : void; /** !#en Returns a "local" axis aligned bounding box of the node.
The returned box is relative only to its parent. !#zh 返回父节坐标系下的轴向对齐的包围盒。 @example ```js var boundingBox = node.getBoundingBox(); ``` */ getBoundingBox() : Rect; /** !#en Stops all running actions and schedulers. !#zh 停止所有正在播放的动作和计时器。 @example ```js node.cleanup(); ``` */ cleanup() : void; /** !#en Returns a child from the container given its tag. !#zh 通过标签获取节点的子节点。 @param aTag An identifier to find the child node. @example ```js var child = node.getChildByTag(1001); ``` */ getChildByTag(aTag : number) : Node; /** !#en Returns a child from the container given its uuid. !#zh 通过 uuid 获取节点的子节点。 @param uuid The uuid to find the child node. @example ```js var child = node.getChildByUuid(uuid); ``` */ getChildByUuid(uuid : string) : Node; /** !#en Returns a child from the container given its name. !#zh 通过名称获取节点的子节点。 @param name A name to find the child node. @example ```js var child = node.getChildByName("Test Node"); ``` */ getChildByName(name : string) : Node; /** !#en "add" logic MUST only be in this method
!#zh 添加子节点,并且可以修改该节点的 局部 Z 顺序和标签。 @param child A child node @param localZOrder Z order for drawing priority. Please refer to setZOrder(int) @param tag An integer or a name to identify the node easily. Please refer to setTag(int) and setName(string) @example ```js node.addChild(newNode, 1, 1001); ``` */ addChild(child : Node, localZOrder? : number, tag? : number|string) : void; /** !#en Remove itself from its parent node. If cleanup is true, then also remove all actions and callbacks.
If the cleanup parameter is not passed, it will force a cleanup.
If the node orphan, then nothing happens. !#zh 从父节点中删除一个节点。cleanup 参数为 true,那么在这个节点上所有的动作和回调都会被删除,反之则不会。
如果不传入 cleanup 参数,默认是 true 的。
如果这个节点是一个孤节点,那么什么都不会发生。 @param cleanup true if all actions and callbacks on this node should be removed, false otherwise. @example ```js node.removeFromParent(); node.removeFromParent(false); ``` */ removeFromParent(cleanup? : boolean) : void; /** !#en Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter.

If the cleanup parameter is not passed, it will force a cleanup.
"remove" logic MUST only be on this method
If a class wants to extend the 'removeChild' behavior it only needs
to override this method. !#zh 移除节点中指定的子节点,是否需要清理所有正在运行的行为取决于 cleanup 参数。
如果 cleanup 参数不传入,默认为 true 表示清理。
@param child The child node which will be removed. @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. @example ```js node.removeChild(newNode); node.removeChild(newNode, false); ``` */ removeChild(child : Node, cleanup? : boolean) : void; /** !#en Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter. If the cleanup parameter is not passed, it will force a cleanup.
!#zh 通过标签移除节点中指定的子节点,是否需要清理所有正在运行的行为取决于 cleanup 参数。
如果 cleanup 参数不传入,默认为 true 表示清理。 @param tag An integer number that identifies a child node @param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise. @example ```js node.removeChildByTag(1001); node.removeChildByTag(1001, false); ``` */ removeChildByTag(tag : number, cleanup? : boolean) : void; /** !#en Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter.
If the cleanup parameter is not passed, it will force a cleanup. !#zh 移除节点所有的子节点,是否需要清理所有正在运行的行为取决于 cleanup 参数。
如果 cleanup 参数不传入,默认为 true 表示清理。 @param cleanup true if all running actions on all children nodes should be cleanup, false otherwise. @example ```js node.removeAllChildren(); node.removeAllChildren(false); ``` */ removeAllChildren(cleanup? : boolean) : void; /** !#en Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates.
The matrix is in Pixels. The returned transform is readonly and cannot be changed. !#zh 返回将父节点的坐标系转换成节点(局部)的空间坐标系的矩阵。
该矩阵以像素为单位。返回的矩阵是只读的,不能更改。 @example ```js var affineTransform = node.getParentToNodeTransform(); ``` */ getParentToNodeTransform() : AffineTransform; /** !#en Returns the world affine transform matrix. The matrix is in Pixels. !#zh 返回节点到世界坐标系的仿射变换矩阵。矩阵单位是像素。 @example ```js var affineTransform = node.getNodeToWorldTransform(); ``` */ getNodeToWorldTransform() : AffineTransform; /** !#en Returns the world affine transform matrix. The matrix is in Pixels.
This method is AR (Anchor Relative). !#zh 返回节点到世界坐标仿射变换矩阵。矩阵单位是像素。
该方法基于节点坐标。 @example ```js var mat = node.getNodeToWorldTransformAR(); ``` */ getNodeToWorldTransformAR() : AffineTransform; /** !#en Returns the inverse world affine transform matrix. The matrix is in Pixels. !#en 返回世界坐标系到节点坐标系的逆矩阵。 @example ```js var affineTransform = node.getWorldToNodeTransform(); ``` */ getWorldToNodeTransform() : AffineTransform; /** !#en Converts a Point to node (local) space coordinates. The result is in Vec2. !#zh 将一个点转换到节点 (局部) 坐标系。结果以 Vec2 为单位。 @example ```js var newVec2 = node.convertToNodeSpace(cc.v2(100, 100)); ``` */ convertToNodeSpace(worldPoint : Vec2) : Vec2; /** !#en Converts a Point to world space coordinates. The result is in Points. !#zh 将一个点转换到世界空间坐标系。结果以 Vec2 为单位。 @example ```js var newVec2 = node.convertToWorldSpace(cc.v2(100, 100)); ``` */ convertToWorldSpace(nodePoint : Vec2) : Vec2; /** !#en Converts a Point to node (local) space coordinates. The result is in Points.
treating the returned/received node point as anchor relative. !#zh 将一个点转换到节点 (局部) 空间坐标系。结果以 Vec2 为单位。
返回值将基于节点坐标。 @example ```js var newVec2 = node.convertToNodeSpaceAR(cc.v2(100, 100)); ``` */ convertToNodeSpaceAR(worldPoint : Vec2) : Vec2; /** !#en Converts a local Point to world space coordinates.The result is in Points.
treating the returned/received node point as anchor relative. !#zh 将一个点转换到世界空间坐标系。结果以 Vec2 为单位。
返回值将基于节点坐标。 @example ```js var newVec2 = node.convertToWorldSpaceAR(cc.v2(100, 100)); ``` */ convertToWorldSpaceAR(nodePoint : Vec2) : Vec2; /** !#en convenience methods which take a cc.Touch instead of cc.Vec2. !#zh 将触摸点转换成本地坐标系中位置。 @param touch The touch object @example ```js var newVec2 = node.convertTouchToNodeSpace(touch); ``` */ convertTouchToNodeSpace(touch : Touch) : Vec2; /** !#en converts a cc.Touch (world coordinates) into a local coordinate. This method is AR (Anchor Relative). !#zh 转换一个 cc.Touch(世界坐标)到一个局部坐标,该方法基于节点坐标。 @param touch The touch object @example ```js var newVec2 = node.convertTouchToNodeSpaceAR(touch); ``` */ convertTouchToNodeSpaceAR(touch : Touch) : Vec2; /** !#en Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates.
The matrix is in Pixels. !#zh 返回这个将节点(局部)的空间坐标系转换成父节点的空间坐标系的矩阵。这个矩阵以像素为单位。 @example ```js var affineTransform = node.getNodeToParentTransform(); ``` */ getNodeToParentTransform() : AffineTransform; /** !#en Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates.
The matrix is in Pixels.
This method is AR (Anchor Relative). !#zh 返回这个将节点(局部)的空间坐标系转换成父节点的空间坐标系的矩阵。
这个矩阵以像素为单位。
该方法基于节点坐标。 @example ```js var affineTransform = node.getNodeToParentTransformAR(); ``` */ getNodeToParentTransformAR() : AffineTransform; /** !#en Returns a "world" axis aligned bounding box of the node.
The bounding box contains self and active children's world bounding box. !#zh 返回节点在世界坐标系下的对齐轴向的包围盒(AABB)。
该边框包含自身和已激活的子节点的世界边框。 @example ```js var newRect = node.getBoundingBoxToWorld(); ``` */ getBoundingBoxToWorld() : Rect; /** !#en Returns the displayed opacity of Node, the difference between displayed opacity and opacity is that displayed opacity is calculated based on opacity and parent node's opacity when cascade opacity enabled. !#zh 获取节点显示透明度, 显示透明度和透明度之间的不同之处在于当启用级连透明度时, 显示透明度是基于自身透明度和父节点透明度计算的。 @example ```js var displayOpacity = node.getDisplayedOpacity(); ``` */ getDisplayedOpacity() : number; /** !#en Returns the displayed color of Node, the difference between displayed color and color is that displayed color is calculated based on color and parent node's color when cascade color enabled. !#zh 获取节点的显示透明度, 显示透明度和透明度之间的不同之处在于显示透明度是基于透明度和父节点透明度启用级连透明度时计算的。 @example ```js var displayColor = node.getDisplayedColor(); ``` */ getDisplayedColor() : Color; /** !#en Set whether color should be changed with the opacity value, useless in ccsg.Node, but this function is override in some class to have such behavior. !#zh 设置更改透明度时是否修改RGB值, @example ```js node.setOpacityModifyRGB(true); ``` */ setOpacityModifyRGB(opacityValue : boolean) : void; /** !#en Get whether color should be changed with the opacity value. !#zh 更改透明度时是否修改RGB值。 @example ```js var hasChange = node.isOpacityModifyRGB(); ``` */ isOpacityModifyRGB() : boolean; /** !#en Get the sibling index. !#zh 获取同级索引。 @example ```js var index = node.getSiblingIndex(); ``` */ getSiblingIndex() : number; /** !#en Set the sibling index of this node. !#zh 设置节点同级索引。 @example ```js node.setSiblingIndex(1); ``` */ setSiblingIndex(index : number) : void; /** !#en Is this node a child of the given node? !#zh 是否是指定节点的子节点? @example ```js node.isChildOf(newNode); ``` */ isChildOf(parent : Node) : boolean; /** !#en Sorts the children array depends on children's zIndex and arrivalOrder, normally you won't need to invoke this function. !#zh 根据子节点的 zIndex 和 arrivalOrder 进行排序,正常情况下开发者不需要手动调用这个函数。 */ sortAllChildren() : void; /** !#en position of node. !#zh 节点相对父节点的坐标。 */ position : Vec2; /** !#en Scale of node. !#zh 节点缩放 */ scale : number; /** !#en Returns the x axis position of the node in cocos2d coordinates. !#zh 获取节点 X 轴坐标。 @example ```js var posX = node.getPositionX(); ``` */ getPositionX() : number; /** !#en Sets the x axis position of the node in cocos2d coordinates. !#zh 设置节点 X 轴坐标。 @example ```js node.setPositionX(1); ``` */ setPositionX(x : number) : void; /** !#en Returns the y axis position of the node in cocos2d coordinates. !#zh 获取节点 Y 轴坐标。 @example ```js var posY = node.getPositionY(); ``` */ getPositionY() : number; /** !#en Sets the y axis position of the node in cocos2d coordinates. !#zh 设置节点 Y 轴坐标。 @param y The new position in y axis @example ```js node.setPositionY(100); ``` */ setPositionY(y : number) : void; /** !#en Returns the local Z order of this node. !#zh 获取节点局部 Z 轴顺序。 @example ```js var localZorder = node.getLocalZOrder(); ``` */ getLocalZOrder() : number; /** !#en LocalZOrder is the 'key' used to sort the node relative to its siblings.

The Node's parent will sort all its children based ont the LocalZOrder value.
If two nodes have the same LocalZOrder, then the node that was added first to the children's array
will be in front of the other node in the array.
Also, the Scene Graph is traversed using the "In-Order" tree traversal algorithm ( http://en.wikipedia.org/wiki/Tree_traversal#In-order )
And Nodes that have LocalZOder values smaller than 0 are the "left" subtree
While Nodes with LocalZOder greater than 0 are the "right" subtree. !#zh LocalZOrder 是 “key” (关键)来分辨节点和它兄弟节点的相关性。 父节点将会通过 LocalZOrder 的值来分辨所有的子节点。 如果两个节点有同样的 LocalZOrder,那么先加入子节点数组的节点将会显示在后加入的节点的前面。 同样的,场景图使用 “In-Order(按顺序)” 遍历数算法来遍历 ( http://en.wikipedia.org/wiki/Tree_traversal#In-order ) 并且拥有小于 0 的 LocalZOrder 的值的节点是 “ left ” 子树(左子树) 所以拥有大于 0 的 LocalZOrder 的值得节点是 “ right ”子树(右子树)。 @example ```js node.setLocalZOrder(1); ``` */ setLocalZOrder(localZOrder : number) : void; /** !#en Returns whether node's opacity value affect its child nodes. !#zh 返回节点的不透明度值是否影响其子节点。 @example ```js cc.log(node.isCascadeOpacityEnabled()); ``` */ isCascadeOpacityEnabled() : boolean; /** !#en Enable or disable cascade opacity, if cascade enabled, child nodes' opacity will be the multiplication of parent opacity and its own opacity. !#zh 启用或禁用级连不透明度,如果级连启用,子节点的不透明度将是父不透明度乘上它自己的不透明度。 @example ```js node.setCascadeOpacityEnabled(true); ``` */ setCascadeOpacityEnabled(cascadeOpacityEnabled : boolean) : void; /** !#en Enable or disable cascade color, if cascade enabled, child nodes' opacity will be the cascade value of parent color and its own color. !#zh 启用或禁用级连颜色,如果级连启用,子节点的颜色将是父颜色和它自己的颜色的级连值。 @example ```js node.setCascadeColorEnabled(true); ``` */ setCascadeColorEnabled(cascadeColorEnabled : boolean) : void; } /** !#en cc.AffineTransform class represent an affine transform matrix. It's composed basically by translation, rotation, scale transformations.
Please do not use its constructor directly, use cc.affineTransformMake alias function instead. !#zh cc.AffineTransform 类代表一个仿射变换矩阵。它基本上是由平移旋转,缩放转变所组成。
请不要直接使用它的构造,请使用 cc.affineTransformMake 函数代替。 */ export class AffineTransform { /** !#en Create a cc.AffineTransform object with all contents in the matrix. !#zh 用在矩阵中的所有内容创建一个 cc.AffineTransform 对象。 */ affineTransformMake(a : number, b : number, c : number, d : number, tx : number, ty : number) : AffineTransform; /** !#en Clone a cc.AffineTransform object from the specified transform. !#zh 克隆指定的 cc.AffineTransform 对象。 */ affineTransformClone(t : AffineTransform) : AffineTransform; /** !#en Apply the affine transformation on a point. !#zh 对一个点应用矩阵变换。 @param point or x. @param transOrY transform matrix or y. @param t transform matrix or y. */ pointApplyAffineTransform(point : Vec2|number, transOrY : AffineTransform|number, t : AffineTransform) : Vec2; /** !#en Apply the affine transformation on a size. !#zh 应用 Size 到仿射变换矩阵上。 */ sizeApplyAffineTransform(size : Size, t : AffineTransform) : Size; /** !#en Create a identity transformation matrix:
[ 1, 0, 0,
0, 1, 0 ] !#zh 单位矩阵:
[ 1, 0, 0,
0, 1, 0 ] */ affineTransformMakeIdentity() : AffineTransform; /** !#en Apply the affine transformation on a rect. !#zh 应用 Rect 到仿射变换矩阵上。 */ rectApplyAffineTransform(rect : Rect, anAffineTransform : AffineTransform) : Rect; /** !#en Apply the affine transformation on a rect, and truns to an Oriented Bounding Box. !#zh 应用 Rect 到仿射变换矩阵上, 并转换为有向包围盒 */ obbApplyAffineTransform(rect : Rect, anAffineTransform : AffineTransform, out_bl : Vec2, out_tl : Vec2, out_tr : Vec2, out_br : Vec2) : void; /** !#en Create a new affine transformation with a base transformation matrix and a translation based on it. !#zh 基于一个基础矩阵加上一个平移操作来创建一个新的矩阵。 @param t The base affine transform object. @param tx The translation on x axis. @param ty The translation on y axis. */ affineTransformTranslate(t : AffineTransform, tx : number, ty : number) : AffineTransform; /** !#en Create a new affine transformation with a base transformation matrix and a scale based on it. !#zh 创建一个基础变换矩阵,并在此基础上进行了 Scale 仿射变换。 @param t The base affine transform object. @param sx The scale on x axis. @param sy The scale on y axis. */ affineTransformScale(t : AffineTransform, sx : number, sy : number) : AffineTransform; /** !#en Create a new affine transformation with a base transformation matrix and a rotation based on it. !#zh 创建一个基础变换矩阵,并在此基础上进行了 Rotation 仿射变换。 @param aTransform The base affine transform object. @param anAngle The angle to rotate. */ affineTransformRotate(aTransform : AffineTransform, anAngle : number) : AffineTransform; /** !#en Concatenate a transform matrix to another and return the result:
t' = t1 * t2 !#zh 拼接两个矩阵,并返回结果:
t' = t1 * t2 @param t1 The first transform object. @param t2 The transform object to concatenate. */ affineTransformConcat(t1 : AffineTransform, t2 : AffineTransform) : AffineTransform; /** !#en Concatenate a transform matrix to another
The results are reflected in the first matrix.
t' = t1 * t2 !#zh 拼接两个矩阵,将结果保存到第一个矩阵。
t' = t1 * t2 @param t1 The first transform object. @param t2 The transform object to concatenate. */ affineTransformConcatIn(t1 : AffineTransform, t2 : AffineTransform) : AffineTransform; /** !#en Return true if an affine transform equals to another, false otherwise. !#zh 判断两个矩阵是否相等。 */ affineTransformEqualToTransform(t1 : AffineTransform, t2 : AffineTransform) : boolean; /** !#en Get the invert transform of an AffineTransform object. !#zh 求逆矩阵。 */ affineTransformInvert(t : AffineTransform) : AffineTransform; } /** !#en Representation of RGBA colors. Each color component is a floating point value with a range from 0 to 255. You can also use the convenience method {{#crossLink "cc/color:method"}}cc.color{{/crossLink}} to create a new Color. !#zh cc.Color 用于表示颜色。 它包含 RGBA 四个以浮点数保存的颜色分量,每个的值都在 0 到 255 之间。 您也可以通过使用 {{#crossLink "cc/color:method"}}cc.color{{/crossLink}} 的便捷方法来创建一个新的 Color。 */ export class Color extends ValueType { /** @param r red component of the color, default value is 0. @param g green component of the color, defualt value is 0. @param b blue component of the color, default value is 0. @param a alpha component of the color, default value is 255. */ Color(r? : number, g? : number, b? : number, a? : number) : Color; /** !#en Solid white, RGBA is [255, 255, 255, 255]. !#zh 纯白色,RGBA 是 [255, 255, 255, 255]。 */ WHITE : Color; /** !#en Solid black, RGBA is [0, 0, 0, 255]. !#zh 纯黑色,RGBA 是 [0, 0, 0, 255]。 */ BLACK : Color; /** !#en Transparent, RGBA is [0, 0, 0, 0]. !#zh 透明,RGBA 是 [0, 0, 0, 0]。 */ TRANSPARENT : Color; /** !#en Grey, RGBA is [127.5, 127.5, 127.5]. !#zh 灰色,RGBA 是 [127.5, 127.5, 127.5]。 */ GRAY : Color; /** !#en Solid red, RGBA is [255, 0, 0]. !#zh 纯红色,RGBA 是 [255, 0, 0]。 */ RED : Color; /** !#en Solid green, RGBA is [0, 255, 0]. !#zh 纯绿色,RGBA 是 [0, 255, 0]。 */ GREEN : Color; /** !#en Solid blue, RGBA is [0, 0, 255]. !#zh 纯蓝色,RGBA 是 [0, 0, 255]。 */ BLUE : Color; /** !#en Yellow, RGBA is [255, 235, 4]. !#zh 黄色,RGBA 是 [255, 235, 4]。 */ YELLOW : Color; /** !#en Orange, RGBA is [255, 127, 0]. !#zh 橙色,RGBA 是 [255, 127, 0]。 */ ORANGE : Color; /** !#en Cyan, RGBA is [0, 255, 255]. !#zh 青色,RGBA 是 [0, 255, 255]。 */ CYAN : Color; /** !#en Magenta, RGBA is [255, 0, 255]. !#zh 洋红色(品红色),RGBA 是 [255, 0, 255]。 */ MAGENTA : Color; /** !#en Clone a new color from the current color. !#zh 克隆当前颜色。 @example ```js var color = new cc.Color(); var newColor = color.clone();// Color {r: 0, g: 0, b: 0, a: 255} ``` */ clone() : Color; /** !#en TODO !#zh 判断两个颜色是否相等。 @example ```js var color1 = cc.Color.WHITE; var color2 = new cc.Color(255, 255, 255); cc.log(color1.equals(color2)); // true; color2 = cc.Color.RED; cc.log(color2.equals(color1)); // false; ``` */ equals(other: (r: number, g: number, b: number, a: number) => void) : boolean; /** !#en TODO !#zh 线性插值 @param ratio the interpolation coefficient. @param out optional, the receiving vector. @example ```js // Converts a white color to a black one trough time. update: function (dt) { var color = this.node.color; if (color.equals(cc.Color.BLACK)) { return; } this.ratio += dt * 0.1; this.node.color = cc.Color.WHITE.lerp(cc.Color.BLACK, ratio); } ``` */ lerp(to: (r: number, g: number, b: number, a: number) => void, ratio : number, out: (r: number, g: number, b: number, a: number) => void) : Color; /** !#en TODO !#zh 转换为方便阅读的字符串。 @example ```js var color = cc.Color.WHITE; color.toString(); // "rgba(255, 255, 255, 255)" ``` */ toString() : string; /** !#en TODO !#zh 设置当前的红色值,并返回当前对象。 @param red the new Red component. @example ```js var color = new cc.Color(); color.setR(255); // Color {r: 255, g: 0, b: 0, a: 255} ``` */ setR(red : number) : Color; /** !#en TODO !#zh 设置当前的绿色值,并返回当前对象。 @param green the new Green component. @example ```js var color = new cc.Color(); color.setG(255); // Color {r: 0, g: 255, b: 0, a: 255} ``` */ setG(green : number) : Color; /** !#en TODO !#zh 设置当前的蓝色值,并返回当前对象。 @param blue the new Blue component. @example ```js var color = new cc.Color(); color.setB(255); // Color {r: 0, g: 0, b: 255, a: 255} ``` */ setB(blue : number) : Color; /** !#en TODO !#zh 设置当前的透明度,并返回当前对象。 @param alpha the new Alpha component. @example ```js var color = new cc.Color(); color.setA(0); // Color {r: 0, g: 0, b: 0, a: 0} ``` */ setA(alpha : number) : Color; /** !#en TODO !#zh 转换为 CSS 格式。 @param opt "rgba", "rgb", "#rgb" or "#rrggbb". @example ```js var color = cc.Color.BLACK; color.toCSS(); // "#000"; color.toCSS("rgba"); // "rgba(0,0,0,1.00)"; color.toCSS("rgb"); // "rgba(0,0,0)"; color.toCSS("#rgb"); // "#000"; color.toCSS("#rrggbb"); // "#000000"; ``` */ toCSS(opt : string) : string; /** !#en Clamp this color to make all components between 0 to 255。 !#zh 限制颜色数值,在 0 到 255 之间。 @example ```js var color = new cc.Color(1000, 0, 0, 255); color.clamp(); cc.log(color); // (255, 0, 0, 255) ``` */ clamp() : void; /** !#en TODO !#zh 读取 16 进制。 @example ```js var color = cc.Color.BLACK; color.fromHEX("#FFFF33"); // Color {r: 255, g: 255, b: 51, a: 255}; ``` */ fromHEX(hexString : string) : Color; /** !#en TODO !#zh 转换为 16 进制。 @param fmt "#rgb" or "#rrggbb". @example ```js var color = cc.Color.BLACK; color.toHEX("#rgb"); // "000"; color.toHEX("#rrggbb"); // "000000"; ``` */ toHEX(fmt : string) : string; /** !#en Convert to 24bit rgb value. !#zh 转换为 24bit 的 RGB 值。 @example ```js var color = cc.Color.YELLOW; color.toRGBValue(); // 16771844; ``` */ toRGBValue() : number; /** !#en TODO !#zh 读取 HSV(色彩模型)格式。 @example ```js var color = cc.Color.YELLOW; color.fromHSV(0, 0, 1); // Color {r: 255, g: 255, b: 255, a: 255}; ``` */ fromHSV(h : number, s : number, v : number) : Color; /** !#en TODO !#zh 转换为 HSV(色彩模型)格式。 @example ```js var color = cc.Color.YELLOW; color.toHSV(); // Object {h: 0.1533864541832669, s: 0.9843137254901961, v: 1}; ``` */ toHSV() : any; /** !#en TODO !#zh RGB 转换为 HSV。 @param r red, must be [0, 255]. @param g red, must be [0, 255]. @param b red, must be [0, 255]. @example ```js cc.Color.rgb2hsv(255, 255, 255); // Object {h: 0, s: 0, v: 1}; ``` */ rgb2hsv(r : number, g : number, b : number) : any; /** !#en TODO !#zh HSV 转换为 RGB。 @example ```js cc.Color.hsv2rgb(0, 0, 1); // Object {r: 255, g: 255, b: 255}; ``` */ hsv2rgb(h : number, s : number, v : number) : any; } /** !#en A 2D rectangle defined by x, y position and width, height. !#zh 通过位置和宽高定义的 2D 矩形。 */ export class Rect extends ValueType { /** !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 */ Rect(x? : number, y? : number, w? : number, h? : number) : Rect; /** !#en Creates a rectangle from two coordinate values. !#zh 根据指定 2 个坐标创建出一个矩形区域。 @example ```js cc.Rect.fromMinMax(cc.v2(10, 10), cc.v2(20, 20)); // Rect {x: 10, y: 10, width: 10, height: 10}; ``` */ fromMinMax(v1 : Vec2, v2 : Vec2) : Rect; /** !#en Checks if rect contains. !#zh 判断 2 个矩形是否有包含。
返回 1 为 a 包含 b,如果 -1 为 b 包含 a, 0 这则都不包含。 @param a Rect a @param b Rect b @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.rect(5, 5, 5, 5); var c = new cc.rect(20, 20, 10, 10); cc.Rect.contain(a, b); // 1; cc.Rect.contain(b, a); // -1; cc.Rect.contain(a, c); // 0; ``` */ contain(a: (x: number, y: number, w: number, h: number) => void, b: (x: number, y: number, w: number, h: number) => void) : number; /** !#en TODO !#zh 克隆一个新的 Rect。 @example ```js var a = new cc.rect(0, 0, 10, 10); a.clone();// Rect {x: 0, y: 0, width: 10, height: 10} ``` */ clone() : Rect; /** !#en TODO !#zh 是否等于指定的矩形。 @param other !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.rect(0, 0, 10, 10); a.equals(b);// true; ``` */ equals(other: (x: number, y: number, w: number, h: number) => void) : boolean; /** !#en TODO !#zh 线性插值 @param to !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param ratio the interpolation coefficient. @param out optional, the receiving vector. @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.rect(50, 50, 100, 100); update (dt) { // method 1; var c = a.lerp(b, dt * 0.1); // method 2; a.lerp(b, dt * 0.1, c); } ``` */ lerp(to: (x: number, y: number, w: number, h: number) => void, ratio : number, out: (x: number, y: number, w: number, h: number) => void) : Rect; /** !#en TODO !#zh 转换为方便阅读的字符串 @example ```js var a = new cc.rect(0, 0, 10, 10); a.toString();// "(0.00, 0.00, 10.00, 10.00)"; ``` */ toString() : string; /** !#en TODO !#zh 矩形 x 轴上的最小值。 */ xMin : number; /** !#en TODO !#zh 矩形 y 轴上的最小值。 */ yMin : number; /** !#en TODO !#zh 矩形 x 轴上的最大值。 */ xMax : number; /** !#en TODO !#zh 矩形 y 轴上的最大值。 */ yMax : number; /** !#en TODO !#zh 矩形的中心点。 */ center : number; /** !#en TODO !#zh 矩形的大小。 */ size : Size; /** !#en TODO !#zh 当前矩形与指定矩形是否相交。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.rect(0, 0, 20, 20); a.intersects(b);// true ``` */ intersects(rect: (x: number, y: number, w: number, h: number) => void) : void; /** !#en TODO !#zh 当前矩形是否包含指定坐标点。 Returns true if the point inside this rectangle. @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.v2(0, 5); a.contains(b);// true ``` */ contains(point : Vec2) : void; /** !#en Returns true if the other rect totally inside this rectangle. !#zh 当前矩形是否包含指定矩形。 @param rect !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @example ```js var a = new cc.rect(0, 0, 10, 10); var b = new cc.rect(0, 0, 20, 20); a.containsRect(b);// true ``` */ containsRect(rect: (x: number, y: number, w: number, h: number) => void) : void; } /** !#en cc.Size is the class for size object,
please do not use its constructor to create sizes,
use {{#crossLink "cc/size:method"}}{{/crossLink}} alias function instead.
It will be deprecated soon, please use cc.Vec2 instead. !#zh cc.Size 是 size 对象的类。
请不要使用它的构造函数创建的 size,
使用 {{#crossLink "cc/size:method"}}{{/crossLink}} 别名函数。
它不久将被取消,请使用cc.Vec2代替。 */ export class Size { /** */ Size(width : number, height : number) : Size; /** !#en return a Size object with width = 0 and height = 0. !#zh 返回一个宽度为 0 和高度为 0 的 Size 对象。 */ ZERO : Size; /** !#en TODO !#zh 克隆 size 对象。 @example ```js var a = new cc.size(10, 10); a.clone();// return Size {width: 0, height: 0}; ``` */ clone() : Size; /** !#en TODO !#zh 当前 Size 对象是否等于指定 Size 对象。 @example ```js var a = new cc.size(10, 10); a.equals(new cc.size(10, 10));// return true; ``` */ equals(other: (width: number, height: number) => void) : boolean; /** !#en TODO !#zh 线性插值。 @param to !#en Constructor of cc.Rect class. see {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} for convenience method. !#zh cc.Rect类的构造函数。可以通过 {{#crossLink "cc/rect:method"}} cc.rect {{/crossLink}} 简便方法进行创建。 @param ratio the interpolation coefficient. @param out optional, the receiving vector. @example ```js var a = new cc.size(10, 10); var b = new cc.rect(50, 50, 100, 100); update (dt) { // method 1; var c = a.lerp(b, dt * 0.1); // method 2; a.lerp(b, dt * 0.1, c); } ``` */ lerp(to: (x: number, y: number, w: number, h: number) => void, ratio : number, out: (width: number, height: number) => void) : Size; /** !#en TODO !#zh 转换为方便阅读的字符串。 @example ```js var a = new cc.size(10, 10); a.toString();// return "(10.00, 10.00)"; ``` */ toString() : string; /** !#en Helper function that creates a cc.Size.
Please use cc.p or cc.v2 instead, it will soon replace cc.Size. !#zh 创建一个 cc.Size 对象的帮助函数。
注意:可以使用 cc.p 或者是 cc.v2 代替,它们将很快取代 cc.Size。 @param w width or a size object @param h height @example ```js var size1 = cc.size(); var size2 = cc.size(100,100); var size3 = cc.size(size2); var size4 = cc.size({width: 100, height: 100}); ``` */ size(w : number|Size, h : number) : Size; /** !#en Check whether a point's value equals to another. !#zh 检查 Size 对象是否等于另一个。 @example ```js var a = new cc.size(10, 10); var b = new cc.size(10, 10); cc.sizeEqualToSize(a, b);// return true; var b = new cc.size(5, 10); cc.sizeEqualToSize(a, b);// return false; ``` */ sizeEqualToSize(size1: (width: number, height: number) => void, size2: (width: number, height: number) => void) : boolean; } /** !#en the device accelerometer reports values for each axis in units of g-force. !#zh 设备重力传感器传递的各个轴的数据。 */ export class Acceleration { constructor(); /** */ Acceleration(x : number, y : number, z : number, timestamp : number) : Acceleration; } /** !#en Blend Function used for textures. !#zh 图像的混合方式。 */ export class BlendFunc { constructor(); /** @param src1 source blend function @param dst1 destination blend function */ BlendFunc(src1 : number, dst1 : number) : BlendFunc; } /** !#en Enum for blend factor Refer to: http://www.andersriggelsen.dk/glblendfunc.php !#zh 混合因子 可参考: http://www.andersriggelsen.dk/glblendfunc.php */ export enum BlendFactor { ONE = 0, ZERO = 0, SRC_ALPHA = 0, SRC_COLOR = 0, DST_ALPHA = 0, DST_COLOR = 0, ONE_MINUS_SRC_ALPHA = 0, ONE_MINUS_SRC_COLOR = 0, ONE_MINUS_DST_ALPHA = 0, ONE_MINUS_DST_COLOR = 0, blendFuncDisable = 0, } /** undefined */ export class WebGLColor { constructor(); /** */ WebGLColor(r : number, g : number, b : number, a : number, arrayBuffer : any[], offset : number) : WebGLColor; BYTES_PER_ELEMENT : number; } /** undefined */ export class Vertex2F { /** */ Vertex2F(x : number, y : number, arrayBuffer : any[], offset : number) : Vertex2F; BYTES_PER_ELEMENT : number; } /** undefined */ export class Vertex3F { constructor(); /** */ Vertex3F(x : number, y : number, z : number, arrayBuffer : any[], offset : number) : Vertex3F; BYTES_PER_ELEMENT : number; } /** undefined */ export class Tex2F { constructor(); /** */ Tex2F(u : number, v : number, arrayBuffer : any[], offset : number) : Tex2F; BYTES_PER_ELEMENT : number; } /** undefined */ export class Quad2 { constructor(); /** */ Quad2(tl: (x: number, y: number, arrayBuffer: any[], offset: number) => void, tr: (x: number, y: number, arrayBuffer: any[], offset: number) => void, bl: (x: number, y: number, arrayBuffer: any[], offset: number) => void, br: (x: number, y: number, arrayBuffer: any[], offset: number) => void, arrayBuffer : any[], offset : number) : Quad2; BYTES_PER_ELEMENT : number; } /** A 3D Quad. 4 * 3 floats */ export class Quad3 { /** */ Quad3(bl1: (x: number, y: number, z: number, arrayBuffer: any[], offset: number) => void, br1: (x: number, y: number, z: number, arrayBuffer: any[], offset: number) => void, tl1: (x: number, y: number, z: number, arrayBuffer: any[], offset: number) => void, tr1: (x: number, y: number, z: number, arrayBuffer: any[], offset: number) => void) : Quad3; } /** undefined */ export class V3F_C4B_T2F { constructor(); /** */ V3F_C4B_T2F(vertices: (x: number, y: number, z: number, arrayBuffer: any[], offset: number) => void, colors: (r: number, g: number, b: number, a: number) => void, texCoords: (u: number, v: number, arrayBuffer: any[], offset: number) => void, arrayBuffer : any[], offset : number) : V3F_C4B_T2F; BYTES_PER_ELEMENT() : void; } /** undefined */ export class V3F_C4B_T2F_Quad { constructor(); /** */ V3F_C4B_T2F_Quad(tl: (vertices: Vertex3F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, bl: (vertices: Vertex3F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, tr: (vertices: Vertex3F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, br: (vertices: Vertex3F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, arrayBuffer : any[], offset : number) : V3F_C4B_T2F_Quad; BYTES_PER_ELEMENT : number; } /** undefined */ export class V2F_C4B_T2F { constructor(); /** */ V2F_C4B_T2F(vertices: (x: number, y: number, arrayBuffer: any[], offset: number) => void, colors: (r: number, g: number, b: number, a: number) => void, texCoords: (u: number, v: number, arrayBuffer: any[], offset: number) => void, arrayBuffer : any[], offset : number) : V2F_C4B_T2F; BYTES_PER_ELEMENT : number; } /** undefined */ export class V2F_C4B_T2F_Triangle { constructor(); /** */ V2F_C4B_T2F_Triangle(a: (vertices: Vertex2F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, b: (vertices: Vertex2F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, c: (vertices: Vertex2F, colors: Color, texCoords: Tex2F, arrayBuffer: any[], offset: number) => void, arrayBuffer : any[], offset : number) : V2F_C4B_T2F_Triangle; } /** !#en The base class of all value types. !#zh 所有值类型的基类。 */ export class ValueType { constructor(); /** !#en This method returns an exact copy of current value. !#zh 克隆当前值,该方法返回一个新对象,新对象的值和原对象相等。 */ clone() : ValueType; /** !#en Compares this object with the other one. !#zh 当前对象是否等于指定对象。 */ equals(other : ValueType) : boolean; /** !#en TODO !#zh 转换为方便阅读的字符串。 */ toString() : string; /** !#en Linearly interpolates between this value to to value by ratio which is in the range [0, 1]. When ratio = 0 returns this. When ratio = 1 return to. When ratio = 0.5 returns the average of this and to. !#zh 线性插值。
当 ratio = 0 时返回自身,ratio = 1 时返回目标,ratio = 0.5 返回自身和目标的平均值。。 @param to the to value @param ratio the interpolation coefficient */ lerp(to : ValueType, ratio : number) : ValueType; } /** !#en Representation of 2D vectors and points. !#zh 表示 2D 向量和坐标 */ export class Vec2 extends ValueType { constructor(); /** !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} */ Vec2(x? : number, y? : number) : Vec2; /** !#en clone a Vec2 value !#zh 克隆一个 Vec2 值 */ clone() : Vec2; /** !#en TODO !#zh 设置向量值。 @param newValue !#en new value to set. !#zh 要设置的新值 */ set(newValue: (x: number, y: number) => void) : Vec2; /** !#en TODO !#zh 当前的向量是否与指定的向量相等。 @param other !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} */ equals(other: (x: number, y: number) => void) : boolean; /** !#en TODO !#zh 转换为方便阅读的字符串。 */ toString() : string; /** !#en TODO !#zh 线性插值。 @param to !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @param ratio the interpolation coefficient @param out optional, the receiving vector */ lerp(to: (x: number, y: number) => void, ratio : number, out: (x: number, y: number) => void) : Vec2; /** !#en Adds this vector. If you want to save result to another vector, use add() instead. !#zh 向量加法。如果你想保存结果到另一个向量,使用 add() 代替。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @example ```js var v = cc.v2(10, 10); v.addSelf(cc.v2(5, 5));// return Vec2 {x: 15, y: 15}; ``` */ addSelf(vector: (x: number, y: number) => void) : Vec2; /** !#en Adds two vectors, and returns the new result. !#zh 向量加法,并返回新结果。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @param out optional, the receiving vector @example ```js var v = cc.v2(10, 10); v.add(cc.v2(5, 5)); // return Vec2 {x: 15, y: 15}; var v1; v.add(cc.v2(5, 5), v1); // return Vec2 {x: 15, y: 15}; ``` */ add(vector: (x: number, y: number) => void, out: (x: number, y: number) => void) : Vec2; /** !#en Subtracts one vector from this. If you want to save result to another vector, use sub() instead. !#zh 向量减法。如果你想保存结果到另一个向量,可使用 sub() 代替。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @example ```js var v = cc.v2(10, 10); v.subSelf(cc.v2(5, 5));// return Vec2 {x: 5, y: 5}; ``` */ subSelf(vector: (x: number, y: number) => void) : Vec2; /** !#en Subtracts one vector from this, and returns the new result. !#zh 向量减法,并返回新结果。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @param out optional, the receiving vector @example ```js var v = cc.v2(10, 10); v.sub(cc.v2(5, 5)); // return Vec2 {x: 5, y: 5}; var v1; v.sub(cc.v2(5, 5), v1); // return Vec2 {x: 5, y: 5}; ``` */ sub(vector: (x: number, y: number) => void, out: (x: number, y: number) => void) : Vec2; /** !#en Multiplies this by a number. If you want to save result to another vector, use mul() instead. !#zh 缩放当前向量。如果你想结果保存到另一个向量,可使用 mul() 代替。 @example ```js var v = cc.v2(10, 10); v.mulSelf(5);// return Vec2 {x: 50, y: 50}; ``` */ mulSelf(num : number) : Vec2; /** !#en Multiplies by a number, and returns the new result. !#zh 缩放当前向量,并返回新结果。 @param out optional, the receiving vector @example ```js var v = cc.v2(10, 10); v.mul(5); // return Vec2 {x: 50, y: 50}; var v1; v.mul(5, v1); // return Vec2 {x: 50, y: 50}; ``` */ mul(num : number, out: (x: number, y: number) => void) : Vec2; /** !#en Multiplies two vectors. !#zh 分量相乘。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @example ```js var v = cc.v2(10, 10); v.scaleSelf(cc.v2(5, 5));// return Vec2 {x: 50, y: 50}; ``` */ scaleSelf(vector: (x: number, y: number) => void) : Vec2; /** !#en Multiplies two vectors, and returns the new result. !#zh 分量相乘,并返回新的结果。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @param out optional, the receiving vector @example ```js var v = cc.v2(10, 10); v.scale(cc.v2(5, 5)); // return Vec2 {x: 50, y: 50}; var v1; v.scale(cc.v2(5, 5), v1); // return Vec2 {x: 50, y: 50}; ``` */ scale(vector: (x: number, y: number) => void, out: (x: number, y: number) => void) : Vec2; /** !#en Divides by a number. If you want to save result to another vector, use div() instead. !#zh 向量除法。如果你想结果保存到另一个向量,可使用 div() 代替。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @example ```js var v = cc.v2(10, 10); v.divSelf(5); // return Vec2 {x: 2, y: 2}; ``` */ divSelf(vector: (x: number, y: number) => void) : Vec2; /** !#en Divides by a number, and returns the new result. !#zh 向量除法,并返回新的结果。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @param out optional, the receiving vector @example ```js var v = cc.v2(10, 10); v.div(5); // return Vec2 {x: 2, y: 2}; var v1; v.div(5, v1); // return Vec2 {x: 2, y: 2}; ``` */ div(vector: (x: number, y: number) => void, out: (x: number, y: number) => void) : Vec2; /** !#en Negates the components. If you want to save result to another vector, use neg() instead. !#zh 向量取反。如果你想结果保存到另一个向量,可使用 neg() 代替。 @example ```js var v = cc.v2(10, 10); v.negSelf(); // return Vec2 {x: -10, y: -10}; ``` */ negSelf() : Vec2; /** !#en Negates the components, and returns the new result. !#zh 返回取反后的新向量。 @param out optional, the receiving vector @example ```js var v = cc.v2(10, 10); var v1; v.neg(v1); // return Vec2 {x: -10, y: -10}; ``` */ neg(out: (x: number, y: number) => void) : Vec2; /** !#en Dot product !#zh 当前向量与指定向量进行点乘。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @example ```js var v = cc.v2(10, 10); v.dot(cc.v2(5, 5)); // return 100; ``` */ dot(vector: (x: number, y: number) => void) : number; /** !#en Cross product !#zh 当前向量与指定向量进行叉乘。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} @example ```js var v = cc.v2(10, 10); v.cross(cc.v2(5, 5)); // return 0; ``` */ cross(vector: (x: number, y: number) => void) : number; /** !#en Returns the length of this vector. !#zh 返回该向量的长度。 @example ```js var v = cc.v2(10, 10); v.mag(); // return 14.142135623730951; ``` */ mag() : number; /** !#en Returns the squared length of this vector. !#zh 返回该向量的长度平方。 @example ```js var v = cc.v2(10, 10); v.magSqr(); // return 200; ``` */ magSqr() : number; /** !#en Make the length of this vector to 1. !#zh 向量归一化,让这个向量的长度为 1。 @example ```js var v = cc.v2(10, 10); v.normalizeSelf(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475}; ``` */ normalizeSelf() : Vec2; /** !#en Returns this vector with a magnitude of 1.

Note that the current vector is unchanged and a new normalized vector is returned. If you want to normalize the current vector, use normalizeSelf function. !#zh 返回归一化后的向量。

注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 normalizeSelf 函数。 @param out optional, the receiving vector */ normalize(out: (x: number, y: number) => void) : Vec2; /** !#en Get angle in radian between this and vector. !#zh 夹角的弧度。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} */ angle(vector: (x: number, y: number) => void) : number; /** !#en Get angle in radian between this and vector with direction. !#zh 带方向的夹角的弧度。 @param vector !#en Constructor see {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} or {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} !#zh 构造函数,可查看 {{#crossLink "cc/vec2:method"}}cc.v2{{/crossLink}} 或者 {{#crossLink "cc/p:method"}}cc.p{{/crossLink}} */ signAngle(vector: (x: number, y: number) => void) : number; /** !#en rotate !#zh 返回旋转给定弧度后的新向量。 @param out optional, the receiving vector */ rotate(radians : number, out: (x: number, y: number) => void) : Vec2; /** !#en rotate self !#zh 按指定弧度旋转向量。 */ rotateSelf(radians : number) : Vec2; /** !#en return a Vec2 object with x = 1 and y = 1. !#zh 新 Vec2 对象。 */ ONE : Vec2; /** !#en return a Vec2 object with x = 0 and y = 0. !#zh 返回 x = 0 和 y = 0 的 Vec2 对象。 */ ZERO : Vec2; /** !#en return a Vec2 object with x = 0 and y = 1. !#zh 返回 x = 0 和 y = 1 的 Vec2 对象。 */ up : Vec2; /** !#en return a Vec2 object with x = 1 and y = 0. !#zh 返回 x = 1 和 y = 0 的 Vec2 对象。 */ RIGHT : Vec2; } /**************************************************** * Node *****************************************************/ export module Node { /** !#en The event type supported by Node !#zh Node 支持的事件类型 */ export enum EventType { TOUCH_START = 0, TOUCH_MOVE = 0, TOUCH_END = 0, TOUCH_CANCEL = 0, MOUSE_DOWN = 0, MOUSE_MOVE = 0, MOUSE_ENTER = 0, MOUSE_LEAVE = 0, MOUSE_UP = 0, MOUSE_WHEEL = 0, } } /**************************************************** * ParticleSystem *****************************************************/ export module ParticleSystem { /** !#en Enum for emitter modes !#zh 发射模式 */ export enum EmitterMode { GRAVITY = 0, RADIUS = 0, } } /**************************************************** * ParticleSystem *****************************************************/ export module ParticleSystem { /** !#en Enum for particles movement type. !#zh 粒子位置类型 */ export enum PositionType { FREE = 0, RELATIVE = 0, GROUPED = 0, } } /**************************************************** * TiledMap *****************************************************/ export module TiledMap { /** !#en The orientation of tiled map. !#zh Tiled Map 地图方向。 */ export enum Orientation { ORTHO = 0, HEX = 0, ISO = 0, NONE = 0, MAP = 0, LAYER = 0, OBJECTGROUP = 0, OBJECT = 0, TILE = 0, HORIZONTAL = 0, VERTICAL = 0, DIAGONAL = 0, FLIPPED_ALL = 0, FLIPPED_MASK = 0, } } /**************************************************** * Button *****************************************************/ export module Button { /** !#en Enum for transition type. !#zh 过渡类型 */ export enum Transition { NONE = 0, COLOR = 0, SPRITE = 0, } } /**************************************************** * Component *****************************************************/ export module Component { /** !#en Component will register a event to target component's handler. And it will trigger the handler when a certain event occurs. !@zh “EventHandler” 类用来设置场景中的事件回调, 该类允许用户设置回调目标节点,目标组件名,组件方法名, 并可通过 emit 方法调用目标函数。 */ export class EventHandler { /** !#en Event target !#zh 目标节点 */ target : Node; /** !#en Component name !#zh 目标组件名 */ component : string; /** !#en Event handler !#zh 响应事件函数名 */ handler : string; /** */ emitEvents(events : Component.EventHandler[]) : void; /** !#en Emit event with params !#zh 触发目标组件上的指定 handler 函数,该参数是回调函数的参数值(可不填)。 @example ```js // Call Function var eventHandler = new cc.Component.EventHandler(); eventHandler.target = newTarget; eventHandler.component = "MainMenu"; eventHandler.handler = "OnClick" eventHandler.emit("This is the argument to the callback function!"); ``` */ emit(params : any) : void; } } /**************************************************** * EditBox *****************************************************/ export module EditBox { /** !#en Enum for keyboard return types !#zh 键盘的返回键类型 */ export enum KeyboardReturnType { DEFAULT = 0, DONE = 0, SEND = 0, SEARCH = 0, GO = 0, } } /**************************************************** * EditBox *****************************************************/ export module EditBox { /** !#en The EditBox's InputMode defines the type of text that the user is allowed to enter. !#zh 输入模式 */ export enum InputMode { ANY = 0, EMAIL_ADDR = 0, NUMERIC = 0, PHONE_NUMBER = 0, URL = 0, DECIMAL = 0, SINGLE_LINE = 0, } } /**************************************************** * EditBox *****************************************************/ export module EditBox { /** !#en Enum for the EditBox's input flags !#zh 定义了一些用于设置文本显示和文本格式化的标志位。 */ export enum InputFlag { PASSWORD = 0, SENSITIVE = 0, INITIAL_CAPS_WORD = 0, INITIAL_CAPS_SENTENCE = 0, INITIAL_CAPS_ALL_CHARACTERS = 0, } } /**************************************************** * Label *****************************************************/ export module Label { /** !#en Enum for Overflow. !#zh Overflow 类型 */ export enum Overflow { NONE = 0, CLAMP = 0, SHRINK = 0, RESIZE_HEIGHT = 0, } } /**************************************************** * Label *****************************************************/ export module Label { /** !#en Enum for font type. !#zh Type 类型 */ export enum Type { TTF = 0, BMFont = 0, SystemFont = 0, } } /**************************************************** * Layout *****************************************************/ export module Layout { /** !#en Enum for Layout type !#zh 布局类型 */ export enum Type { NONE = 0, HORIZONTAL = 0, VERTICAL = 0, GRID = 0, } } /**************************************************** * Layout *****************************************************/ export module Layout { /** !#en Enum for Layout Resize Mode !#zh 缩放模式 */ export enum ResizeMode { NONE = 0, CONTAINER = 0, CHILDREN = 0, } } /**************************************************** * Layout *****************************************************/ export module Layout { /** !#en Enum for Grid Layout start axis direction. !#zh 布局轴向,只用于 GRID 布局。 */ export enum AxisDirection { HORIZONTAL = 0, VERTICAL = 0, } } /**************************************************** * Layout *****************************************************/ export module Layout { /** !#en Enum for vertical layout direction. !#zh 垂直方向布局方式 */ export enum VerticalDirection { BOTTOM_TO_TOP = 0, TOP_TO_BOTTOM = 0, } } /**************************************************** * Layout *****************************************************/ export module Layout { /** !#en Enum for horizontal layout direction. !#zh 水平方向布局方式 */ export enum HorizontalDirection { LEFT_TO_RIGHT = 0, RIGHT_TO_LEFT = 0, } } /**************************************************** * Mask *****************************************************/ export module Mask { /** !#en the type for mask. !#zh 遮罩组件的类型 */ export enum Type { RECT = 0, ELLIPSE = 0, type = 0, segements = 0, } } /**************************************************** * ProgressBar *****************************************************/ export module ProgressBar { /** !#en Enum for ProgressBar mode !#zh 进度条模式 */ export enum Mode { HORIZONTAL = 0, VERTICAL = 0, FILLED = 0, } } /**************************************************** * Scrollbar *****************************************************/ export module Scrollbar { /** Enum for Scrollbar direction */ export enum Direction { HORIZONTAL = 0, VERTICAL = 0, } } /**************************************************** * ScrollView *****************************************************/ export module ScrollView { /** !#en Enum for ScrollView event type. !#zh 滚动视图事件类型 */ export enum EventType { SCROLL_TO_TOP = 0, SCROLL_TO_BOTTOM = 0, SCROLL_TO_LEFT = 0, SCROLL_TO_RIGHT = 0, SCROLLING = 0, BOUNCE_TOP = 0, BOUNCE_BOTTOM = 0, BOUNCE_LEFT = 0, BOUNCE_RIGHT = 0, AUTOSCROLL_ENDED = 0, } } /**************************************************** * Sprite *****************************************************/ export module Sprite { /** !#en Enum for sprite type. !#zh Sprite 类型 */ export enum SpriteType { SIMPLE = 0, SLICED = 0, TILED = 0, FILLED = 0, } } /**************************************************** * Sprite *****************************************************/ export module Sprite { /** !#en Enum for fill type. !#zh 填充类型 */ export enum FillType { HORIZONTAL = 0, VERTICAL = 0, RADIAL = 0, } } /**************************************************** * Sprite *****************************************************/ export module Sprite { /** !#en Sprite Size can track trimmed size, raw size or none. !#zh 精灵尺寸调整模式 */ export enum SizeMode { CUSTOM = 0, TRIMMED = 0, RAW = 0, } } /**************************************************** * VideoPlayer *****************************************************/ export module VideoPlayer { /** !#en Enum for video resouce type type. !#zh 视频来源 */ export enum ResourceType { REMOTE = 0, LOCAL = 0, } } /**************************************************** * Event *****************************************************/ export module Event { /** !#en The Custom event !#zh 自定义事件 */ export class EventCustom extends Event { constructor(); /** @param type The name of the event (case-sensitive), e.g. "click", "fire", or "submit" @param bubbles A boolean indicating whether the event bubbles up through the tree or not */ EventCustom(type : string, bubbles : boolean) : EventCustom; /** !#en A reference to the detailed data of the event !#zh 事件的详细数据 */ detail : any; /** !#en Sets user data !#zh 设置用户数据 */ setUserData(data : any) : void; /** !#en Gets user data !#zh 获取用户数据 */ getUserData() : any; /** !#en Gets event name !#zh 获取事件名称 */ getEventName() : string; } } /**************************************************** * Event *****************************************************/ export module Event { /** !#en The mouse event !#zh 鼠标事件类型 */ export class EventMouse extends Event { /** @param eventType The mouse event type, UP, DOWN, MOVE, CANCELED @param bubbles A boolean indicating whether the event bubbles up through the tree or not */ constructor(eventType : number, bubbles? : boolean); /** !#en Sets scroll data. !#zh 设置鼠标的滚动数据。 */ setScrollData(scrollX : number, scrollY : number) : void; /** !#en Returns the x axis scroll value. !#zh 获取鼠标滚动的X轴距离,只有滚动时才有效。 */ getScrollX() : number; /** !#en Returns the y axis scroll value. !#zh 获取滚轮滚动的 Y 轴距离,只有滚动时才有效。 */ getScrollY() : number; /** !#en Sets cursor location. !#zh 设置当前鼠标位置。 */ setLocation(x : number, y : number) : void; /** !#en Returns cursor location. !#zh 获取鼠标位置对象,对象包含 x 和 y 属性。 */ getLocation() : Vec2; /** !#en Returns the current cursor location in screen coordinates. !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 */ getLocationInView() : Vec2; /** !#en Returns the previous touch location. !#zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。 */ getPreviousLocation() : Vec2; /** !#en Returns the delta distance from the previous location to current location. !#zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 */ getDelta() : Vec2; /** !#en Returns the X axis delta distance from the previous location to current location. !#zh 获取鼠标距离上一次事件移动的 X 轴距离。 */ getDeltaX() : number; /** !#en Returns the Y axis delta distance from the previous location to current location. !#zh 获取鼠标距离上一次事件移动的 Y 轴距离。 */ getDeltaY() : number; /** !#en Sets mouse button. !#zh 设置鼠标按键。 */ setButton(button : number) : void; /** !#en Returns mouse button. !#zh 获取鼠标按键。 */ getButton() : number; /** !#en Returns location X axis data. !#zh 获取鼠标当前位置 X 轴。 */ getLocationX() : number; /** !#en Returns location Y axis data. !#zh 获取鼠标当前位置 Y 轴。 */ getLocationY() : number; } } /**************************************************** * Event *****************************************************/ export module Event { /** !#en The touch event !#zh 触摸事件 */ export class EventTouch extends Event { /** @param touchArr The array of the touches @param bubbles A boolean indicating whether the event bubbles up through the tree or not */ constructor(touchArr : any[], bubbles : boolean); /** !#en Returns event code. !#zh 获取事件类型。 */ getEventCode() : number; /** !#en Returns touches of event. !#zh 获取触摸点的列表。 */ getTouches() : any[]; /** !#en Sets touch location. !#zh 设置当前触点位置 */ setLocation(x : number, y : number) : void; /** !#en Returns touch location. !#zh 获取触点位置。 */ getLocation() : Vec2; /** !#en Returns the current touch location in screen coordinates. !#zh 获取当前触点在游戏窗口中的位置。 */ getLocationInView() : Vec2; /** !#en Returns the previous touch location. !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 */ getPreviousLocation() : Vec2; /** !#en Returns the start touch location. !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 */ getStartLocation() : Vec2; /** !#en Returns the id of cc.Touch. !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 */ getID() : number; /** !#en Returns the delta distance from the previous location to current location. !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 */ getDelta() : Vec2; /** !#en Returns the X axis delta distance from the previous location to current location. !#zh 获取触点距离上一次事件移动的 x 轴距离。 */ getDeltaX() : number; /** !#en Returns the Y axis delta distance from the previous location to current location. !#zh 获取触点距离上一次事件移动的 y 轴距离。 */ getDeltaY() : number; /** !#en Returns location X axis data. !#zh 获取当前触点 X 轴位置。 */ getLocationX() : number; /** !#en Returns location Y axis data. !#zh 获取当前触点 Y 轴位置。 */ getLocationY() : number; } } /**************************************************** * Event *****************************************************/ export module Event { /** !#en The acceleration event !#zh 加速度事件 */ export class EventAcceleration extends Event { /** @param acc The acceleration @param bubbles A boolean indicating whether the event bubbles up through the tree or not */ constructor(acc : any, bubbles : boolean); } } /**************************************************** * Event *****************************************************/ export module Event { /** !#en The keyboard event !#zh 键盘事件 */ export class EventKeyboard extends Event { /** @param keyCode The key code of which triggered this event @param isPressed A boolean indicating whether the key have been pressed @param bubbles A boolean indicating whether the event bubbles up through the tree or not */ constructor(keyCode : number, isPressed : boolean, bubbles : boolean); } } /**************************************************** * Pipeline *****************************************************/ export module Pipeline { /** The downloader pipe, it can download several types of files: 1. Text 2. Image 3. Script 4. Audio All unknown type will be downloaded as plain text. You can pass custom supported types in the constructor. */ export class Downloader { /** Constructor of Downloader, you can pass custom supported types. @param extMap Custom supported types with corresponded handler @example ```js var downloader = new Downloader({ // This will match all url with `.scene` extension or all url with `scene` type 'scene' : function (url, callback) {} }); ``` */ Downloader(extMap : any) : void; /** Add custom supported types handler or modify existing type handler. @param extMap Custom supported types with corresponded handler */ addHandlers(extMap : any) : void; } } /**************************************************** * Pipeline *****************************************************/ export module Pipeline { /** The loader pipe, it can load several types of files: 1. Images 2. JSON 3. Plist 4. Audio 5. Font 6. Cocos Creator scene It will not interfere with items of unknown type. You can pass custom supported types in the constructor. */ export class Loader { /** Constructor of Loader, you can pass custom supported types. @param extMap Custom supported types with corresponded handler @example ```js var loader = new Loader({ // This will match all url with `.scene` extension or all url with `scene` type 'scene' : function (url, callback) {} }); ``` */ Loader(extMap : any) : void; /** Add custom supported types handler or modify existing type handler. @param extMap Custom supported types with corresponded handler */ addHandlers(extMap : any) : void; } } /**************************************************** * Texture2D *****************************************************/ export module Texture2D { /** The texture wrap mode */ export enum WrapMode { REPEAT = 0, CLAMP_TO_EDGE = 0, MIRRORED_REPEAT = 0, } } /**************************************************** * Label *****************************************************/ export module Label { /** !#en Enum for text alignment. !#zh 文本对齐类型 */ export enum TextAlignment { LEFT = 0, CENTER = 0, RIGHT = 0, } } /**************************************************** * Label *****************************************************/ export module Label { /** !#en Enum for vertical text alignment. !#zh 文本垂直对齐类型 */ export enum VerticalTextAlignment { TOP = 0, CENTER = 0, BOTTOM = 0, } } } /** !#en The global main namespace of Spine, all classes, functions, properties and constants of Spine are defined in this namespace !#zh Spine 的全局的命名空间, 与 Spine 相关的所有的类,函数,属性,常量都在这个命名空间中定义。 */ declare module sp { /** !#en The official spine runtime.
See http://en.esotericsoftware.com/spine-using-runtimes !#zh 官方 Spine Runtime。
可查看 Spine 官方文档 http://en.esotericsoftware.com/spine-using-runtimes */ export var spine : any; /** !#en The skeleton of Spine

(Skeleton has a reference to a SkeletonData and stores the state for skeleton instance, which consists of the current pose's bone SRT, slot colors, and which slot attachments are visible.
Multiple skeletons can use the same SkeletonData which includes all animations, skins, and attachments.)
!#zh Spine 骨骼动画

(Skeleton 具有对骨骼数据的引用并且存储了骨骼实例的状态, 它由当前的骨骼动作,slot 颜色,和可见的 slot attachments 组成。
多个 Skeleton 可以使用相同的骨骼数据,其中包括所有的动画,皮肤和 attachments。 */ export class Skeleton extends cc._RendererUnderSG { constructor(); /** !#en The skeletal animation is paused? !#zh 该骨骼动画是否暂停。 */ paused : boolean; /** !#en The skeleton data contains the skeleton information (bind pose bones, slots, draw order, attachments, skins, etc) and animations but does not hold any state.
Multiple skeletons can share the same skeleton data. !#zh 骨骼数据包含了骨骼信息(绑定骨骼动作,slots,渲染顺序, attachments,皮肤等等)和动画但不持有任何状态。
多个 Skeleton 可以共用相同的骨骼数据。 */ skeletonData : SkeletonData; /** !#en The name of default skin. !#zh 默认的皮肤名称。 */ defaultSkin : string; /** !#en The name of default animation. !#zh 默认的动画名称。 */ defaultAnimation : string; /** !#en The name of current playing animation. !#zh 当前播放的动画名称。 */ animation : string; _defaultSkinIndex : number; /** !#en TODO !#zh 是否循环播放当前骨骼动画。 */ loop : boolean; /** !#en The time scale of this skeleton. !#zh 当前骨骼中所有动画的时间缩放率。 */ timeScale : number; /** !#en Indicates whether open debug slots. !#zh 是否显示 slot 的 debug 信息。 */ debugSlots : boolean; /** !#en Indicates whether open debug bones. !#zh 是否显示 bone 的 debug 信息。 */ debugBones : boolean; /** !#en Computes the world SRT from the local SRT for each bone. !#zh 重新更新所有骨骼的世界 Transform, 当获取 bone 的数值未更新时,即可使用该函数进行更新数值。 @example ```js var bone = spine.findBone('head'); cc.log(bone.worldX); // return 0; spine.updateWorldTransform(); bone = spine.findBone('head'); cc.log(bone.worldX); // return -23.12; ``` */ updateWorldTransform() : void; /** !#en Sets the bones and slots to the setup pose. !#zh 还原到起始动作 */ setToSetupPose() : void; /** !#en Sets the bones to the setup pose, using the values from the `BoneData` list in the `SkeletonData`. !#zh 设置 bone 到起始动作 使用 SkeletonData 中的 BoneData 列表中的值。 */ setBonesToSetupPose() : void; /** !#en Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`. !#zh 设置 slot 到起始动作。 使用 SkeletonData 中的 SlotData 列表中的值。 */ setSlotsToSetupPose() : void; /** !#en Finds a bone by name. This does a string comparison for every bone. !#zh 通过名称查找 bone。 这里对每个 bone 的名称进行了对比。 */ findBone(boneName : string) : spine.Bone; /** !#en Finds a slot by name. This does a string comparison for every slot. !#zh 通过名称查找 slot。 这里对每个 slot 的名称进行了比较。 */ findSlot(slotName : string) : spine.Slot; /** !#en Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible. !#zh 按名称查找皮肤,激活该皮肤。 这里对每个皮肤的名称进行了比较。 注意:设置皮肤不会改变 attachment 的可见性。。 */ setSkin(skinName : string) : spine.Skin; /** !#en Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. !#zh 通过 slot 和 attachment 的名称获取 attachment。 Skeleton 优先查找它的皮肤,然后才是 Skeleton Data 中默认的皮肤。 */ getAttachment(slotName : string, attachmentName : string) : spine.RegionAttachment; /** !#en Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. !#zh 通过 slot 和 attachment 的名字来设置 attachment。 Skeleton 优先查找它的皮肤,然后才是 Skeleton Data 中默认的皮肤。 */ setAttachment(slotName : string, attachmentName : string) : void; /** !#en Sets skeleton data to sp.Skeleton. !#zh 设置 Skeleton 中的 Skeleton Data。 */ setSkeletonData(skeletonData : spine.SkeletonData, ownsSkeletonData : spine.SkeletonData) : void; /** !#en Sets animation state data. !#zh 设置动画状态数据。 */ setAnimationStateData(stateData : spine.AnimationStateData) : void; /** !#en Mix applies all keyframe values, interpolated for the specified time and mixed with the current values. !#zh 为所有关键帧设定混合及混合时间(从当前值开始差值)。 */ setMix(fromAnimation : string, toAnimation : string, duration : number) : void; /** !#en Sets event listener. !#zh 设置动画事件监听器。 */ setAnimationListener(target : any, callback : Function) : void; /** !#en Set the current animation. Any queued animations are cleared. !#zh 设置当前动画。队列中的任何的动画将被清除。 */ setAnimation(trackIndex : number, name : string, loop : boolean) : spine.TrackEntry; /** !#en Adds an animation to be played delay seconds after the current or last queued animation. !#zh 添加一个动画到动画队列尾部,还可以延迟指定的秒数。 */ addAnimation(trackIndex : number, name : string, loop : boolean, delay? : number) : spine.TrackEntry; /** !#en Returns track entry by trackIndex. !#zh 通过 track 索引获取 TrackEntry。 */ getCurrent(trackIndex : void) : spine.TrackEntry; /** !#en Clears all tracks of animation state. !#zh 清除所有 track 的动画状态。 */ clearTracks() : void; /** !#en Clears track of animation state by trackIndex. !#zh 清除出指定 track 的动画状态。 */ clearTrack(trackIndex : number) : void; /** !#en Set the start event listener. !#zh 用来设置开始播放动画的事件监听。 */ setStartListener(listener : Function) : void; /** !#en Set the end event listener. !#zh 用来设置动画播放完后的事件监听。 */ setEndListener(listener : Function) : void; } /** !#en The skeleton data of spine. !#zh Spine 的 骨骼数据。 */ export class SkeletonData extends cc.Asset { /** !#en See http://en.esotericsoftware.com/spine-json-format !#zh 可查看 Spine 官方文档 http://zh.esotericsoftware.com/spine-json-format */ skeletonJson : any; atlasText : string; textures : Texture2D; /** !#en A scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. This can be useful when using different sized images than were used when designing the skeleton in Spine. For example, if using images that are half the size than were used in Spine, a scale of 0.5 can be used. This is commonly used for games that can run with either low or high resolution texture atlases. see http://en.esotericsoftware.com/spine-using-runtimes#Scaling !#zh 可查看 Spine 官方文档: http://zh.esotericsoftware.com/spine-using-runtimes#Scaling */ scale : number; /** !#en Get the included SkeletonData used in spine runtime. !#zh 获取 Spine Runtime 使用的 SkeletonData。 */ getRuntimeData(quiet? : boolean) : spine.SkeletonData; } /** !#en The event type of spine skeleton animation. !#zh 骨骼动画事件类型。 */ export enum AnimationEventType { START = 0, END = 0, COMPLETE = 0, EVENT = 0, } } /** This module provides some JavaScript utilities. All members can be accessed with cc.js */ declare module js { /** Check the obj whether is number or not If a number is created by using 'new Number(10086)', the typeof it will be "object"... Then you can use this function if you care about this case. */ export function isNumber(obj : any) : boolean; /** Check the obj whether is string or not. If a string is created by using 'new String("blabla")', the typeof it will be "object"... Then you can use this function if you care about this case. */ export function isString(obj : any) : boolean; /** copy all properties not defined in obj from arguments[1...n] @param obj object to extend its properties @param sourceObj source object to copy properties from */ export function addon(obj : any, sourceObj : any) : any; /** copy all properties from arguments[1...n] to obj */ export function mixin(obj : any, sourceObj : any) : any; /** Derive the class from the supplied base class. Both classes are just native javascript constructors, not created by cc.Class, so usually you will want to inherit using {{#crossLink "cc/Class:method"}}cc.Class {{/crossLink}} instead. @param base the baseclass to inherit */ export function extend(cls : Function, base : Function) : Function; /** Removes all enumerable properties from object */ export function clear(obj : any) : void; /** Get property descriptor in object and all its ancestors */ export function getPropertyDescriptor(obj : any, name : string) : any; /** Get class name of the object, if object is just a {} (and which class named 'Object'), it will return null. (modified from the code from this stackoverflow post) @param obj instance or constructor */ export function getClassName(obj : any|Function) : string; /** Register the class by specified name manually */ export function setClassName(className : string, constructor : Function) : void; /** Unregister a class from fireball. If you dont need a registered class anymore, you should unregister the class so that Fireball will not keep its reference anymore. Please note that its still your responsibility to free other references to the class. @param constructor the class you will want to unregister, any number of classes can be added */ export function unregisterClass(constructor : Function) : void; /** Get the registered class by name */ export function getClassByName(classname : string) : Function; /** Define get set accessor, just help to call Object.defineProperty(...) */ export function getset(obj : any, prop : string, getter : Function, setter : Function, enumerable? : boolean) : void; /** Define get accessor, just help to call Object.defineProperty(...) */ export function get(obj : any, prop : string, getter : Function, enumerable? : boolean) : void; /** Define set accessor, just help to call Object.defineProperty(...) */ export function set(obj : any, prop : string, setter : Function, enumerable? : boolean) : void; /** Defines a polyfill field for obsoleted codes. @param obj YourObject or YourClass.prototype @param obsoleted "OldParam" or "YourClass.OldParam" @param newPropName "NewParam" */ export function obsolete(obj : any, obsoleted : string, newPropName : string, writable? : boolean) : void; /** Defines all polyfill fields for obsoleted codes corresponding to the enumerable properties of props. @param obj YourObject or YourClass.prototype @param objName "YourObject" or "YourClass" */ export function obsoletes(obj : any, objName : any, props : any, writable? : boolean) : void; /** A string tool to construct a string with format string. for example: cc.js.formatStr("a: %s, b: %s", a, b); cc.js.formatStr(a, b, c); */ export function formatStr() : string; /** undefined */ export class array { /** Removes the first occurrence of a specific object from the array. */ remove(array : any[], value : any) : boolean; /** Removes the array item at the specified index. */ removeAt(array : any[], index : number) : void; /** Determines whether the array contains a specific value. */ contains(array : any[], value : any) : boolean; /** Verify array's Type */ verifyType(array : any[], type : Function) : boolean; /** Removes from array all values in minusArr. For each Value in minusArr, the first matching instance in array will be removed. @param array Source Array @param minusArr minus Array */ removeArray(array : any[], minusArr : any[]) : void; /** Inserts some objects at index */ appendObjectsAt(array : any[], addObjs : any[], index : number) : any[]; /** Copy an array's item to a new array (its performance is better than Array.slice) */ copy(array : any[]) : any[]; /** Exact same function as Array.prototype.indexOf. HACK: ugliy hack for Baidu mobile browser compatibility, stupid Baidu guys modify Array.prototype.indexOf for all pages loaded, their version changes strict comparison to non-strict comparison, it also ignores the second parameter of the original API, and this will cause event handler enter infinite loop. Baidu developers, if you ever see this documentation, here is the standard: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf Seriously ! @param searchElement Element to locate in the array. @param fromIndex The index to start the search at */ indexOf(searchElement : any, fromIndex? : number) : number; } } ================================================ FILE: bin/client/jsconfig.json ================================================ { "compilerOptions": { "target": "es6", "module": "commonjs" }, "exclude": [ "node_modules", "library", "local", "settings", "temp" ] } ================================================ FILE: bin/client/project.json ================================================ { "engine": "cocos-creator-js", "packages": "packages" } ================================================ FILE: bin/client.html ================================================ game test

登录 :

================================================ FILE: src/github.com/davecgh/go-spew/LICENSE ================================================ Copyright (c) 2012-2013 Dave Collins Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ================================================ FILE: src/github.com/davecgh/go-spew/spew/bypass.go ================================================ // Copyright (c) 2015 Dave Collins // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // NOTE: Due to the following build constraints, this file will only be compiled // when the code is not running on Google App Engine and "-tags disableunsafe" // is not added to the go build command line. // +build !appengine,!disableunsafe package spew import ( "reflect" "unsafe" ) const ( // UnsafeDisabled is a build-time constant which specifies whether or // not access to the unsafe package is available. UnsafeDisabled = false // ptrSize is the size of a pointer on the current arch. ptrSize = unsafe.Sizeof((*byte)(nil)) ) var ( // offsetPtr, offsetScalar, and offsetFlag are the offsets for the // internal reflect.Value fields. These values are valid before golang // commit ecccf07e7f9d which changed the format. The are also valid // after commit 82f48826c6c7 which changed the format again to mirror // the original format. Code in the init function updates these offsets // as necessary. offsetPtr = uintptr(ptrSize) offsetScalar = uintptr(0) offsetFlag = uintptr(ptrSize * 2) // flagKindWidth and flagKindShift indicate various bits that the // reflect package uses internally to track kind information. // // flagRO indicates whether or not the value field of a reflect.Value is // read-only. // // flagIndir indicates whether the value field of a reflect.Value is // the actual data or a pointer to the data. // // These values are valid before golang commit 90a7c3c86944 which // changed their positions. Code in the init function updates these // flags as necessary. flagKindWidth = uintptr(5) flagKindShift = uintptr(flagKindWidth - 1) flagRO = uintptr(1 << 0) flagIndir = uintptr(1 << 1) ) func init() { // Older versions of reflect.Value stored small integers directly in the // ptr field (which is named val in the older versions). Versions // between commits ecccf07e7f9d and 82f48826c6c7 added a new field named // scalar for this purpose which unfortunately came before the flag // field, so the offset of the flag field is different for those // versions. // // This code constructs a new reflect.Value from a known small integer // and checks if the size of the reflect.Value struct indicates it has // the scalar field. When it does, the offsets are updated accordingly. vv := reflect.ValueOf(0xf00) if unsafe.Sizeof(vv) == (ptrSize * 4) { offsetScalar = ptrSize * 2 offsetFlag = ptrSize * 3 } // Commit 90a7c3c86944 changed the flag positions such that the low // order bits are the kind. This code extracts the kind from the flags // field and ensures it's the correct type. When it's not, the flag // order has been changed to the newer format, so the flags are updated // accordingly. upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag) upfv := *(*uintptr)(upf) flagKindMask := uintptr((1<>flagKindShift != uintptr(reflect.Int) { flagKindShift = 0 flagRO = 1 << 5 flagIndir = 1 << 6 // Commit adf9b30e5594 modified the flags to separate the // flagRO flag into two bits which specifies whether or not the // field is embedded. This causes flagIndir to move over a bit // and means that flagRO is the combination of either of the // original flagRO bit and the new bit. // // This code detects the change by extracting what used to be // the indirect bit to ensure it's set. When it's not, the flag // order has been changed to the newer format, so the flags are // updated accordingly. if upfv&flagIndir == 0 { flagRO = 3 << 5 flagIndir = 1 << 7 } } } // unsafeReflectValue converts the passed reflect.Value into a one that bypasses // the typical safety restrictions preventing access to unaddressable and // unexported data. It works by digging the raw pointer to the underlying // value out of the protected value and generating a new unprotected (unsafe) // reflect.Value to it. // // This allows us to check for implementations of the Stringer and error // interfaces to be used for pretty printing ordinarily unaddressable and // inaccessible values such as unexported struct fields. func unsafeReflectValue(v reflect.Value) (rv reflect.Value) { indirects := 1 vt := v.Type() upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr) rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag)) if rvf&flagIndir != 0 { vt = reflect.PtrTo(v.Type()) indirects++ } else if offsetScalar != 0 { // The value is in the scalar field when it's not one of the // reference types. switch vt.Kind() { case reflect.Uintptr: case reflect.Chan: case reflect.Func: case reflect.Map: case reflect.Ptr: case reflect.UnsafePointer: default: upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetScalar) } } pv := reflect.NewAt(vt, upv) rv = pv for i := 0; i < indirects; i++ { rv = rv.Elem() } return rv } ================================================ FILE: src/github.com/davecgh/go-spew/spew/bypasssafe.go ================================================ // Copyright (c) 2015 Dave Collins // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // NOTE: Due to the following build constraints, this file will only be compiled // when either the code is running on Google App Engine or "-tags disableunsafe" // is added to the go build command line. // +build appengine disableunsafe package spew import "reflect" const ( // UnsafeDisabled is a build-time constant which specifies whether or // not access to the unsafe package is available. UnsafeDisabled = true ) // unsafeReflectValue typically converts the passed reflect.Value into a one // that bypasses the typical safety restrictions preventing access to // unaddressable and unexported data. However, doing this relies on access to // the unsafe package. This is a stub version which simply returns the passed // reflect.Value when the unsafe package is not available. func unsafeReflectValue(v reflect.Value) reflect.Value { return v } ================================================ FILE: src/github.com/davecgh/go-spew/spew/common.go ================================================ /* * Copyright (c) 2013 Dave Collins * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "io" "reflect" "sort" "strconv" ) // Some constants in the form of bytes to avoid string overhead. This mirrors // the technique used in the fmt package. var ( panicBytes = []byte("(PANIC=") plusBytes = []byte("+") iBytes = []byte("i") trueBytes = []byte("true") falseBytes = []byte("false") interfaceBytes = []byte("(interface {})") commaNewlineBytes = []byte(",\n") newlineBytes = []byte("\n") openBraceBytes = []byte("{") openBraceNewlineBytes = []byte("{\n") closeBraceBytes = []byte("}") asteriskBytes = []byte("*") colonBytes = []byte(":") colonSpaceBytes = []byte(": ") openParenBytes = []byte("(") closeParenBytes = []byte(")") spaceBytes = []byte(" ") pointerChainBytes = []byte("->") nilAngleBytes = []byte("") maxNewlineBytes = []byte("\n") maxShortBytes = []byte("") circularBytes = []byte("") circularShortBytes = []byte("") invalidAngleBytes = []byte("") openBracketBytes = []byte("[") closeBracketBytes = []byte("]") percentBytes = []byte("%") precisionBytes = []byte(".") openAngleBytes = []byte("<") closeAngleBytes = []byte(">") openMapBytes = []byte("map[") closeMapBytes = []byte("]") lenEqualsBytes = []byte("len=") capEqualsBytes = []byte("cap=") ) // hexDigits is used to map a decimal value to a hex digit. var hexDigits = "0123456789abcdef" // catchPanic handles any panics that might occur during the handleMethods // calls. func catchPanic(w io.Writer, v reflect.Value) { if err := recover(); err != nil { w.Write(panicBytes) fmt.Fprintf(w, "%v", err) w.Write(closeParenBytes) } } // handleMethods attempts to call the Error and String methods on the underlying // type the passed reflect.Value represents and outputes the result to Writer w. // // It handles panics in any called methods by catching and displaying the error // as the formatted value. func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { // We need an interface to check if the type implements the error or // Stringer interface. However, the reflect package won't give us an // interface on certain things like unexported struct fields in order // to enforce visibility rules. We use unsafe, when it's available, // to bypass these restrictions since this package does not mutate the // values. if !v.CanInterface() { if UnsafeDisabled { return false } v = unsafeReflectValue(v) } // Choose whether or not to do error and Stringer interface lookups against // the base type or a pointer to the base type depending on settings. // Technically calling one of these methods with a pointer receiver can // mutate the value, however, types which choose to satisify an error or // Stringer interface with a pointer receiver should not be mutating their // state inside these interface methods. if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { v = unsafeReflectValue(v) } if v.CanAddr() { v = v.Addr() } // Is it an error or Stringer? switch iface := v.Interface().(type) { case error: defer catchPanic(w, v) if cs.ContinueOnMethod { w.Write(openParenBytes) w.Write([]byte(iface.Error())) w.Write(closeParenBytes) w.Write(spaceBytes) return false } w.Write([]byte(iface.Error())) return true case fmt.Stringer: defer catchPanic(w, v) if cs.ContinueOnMethod { w.Write(openParenBytes) w.Write([]byte(iface.String())) w.Write(closeParenBytes) w.Write(spaceBytes) return false } w.Write([]byte(iface.String())) return true } return false } // printBool outputs a boolean value as true or false to Writer w. func printBool(w io.Writer, val bool) { if val { w.Write(trueBytes) } else { w.Write(falseBytes) } } // printInt outputs a signed integer value to Writer w. func printInt(w io.Writer, val int64, base int) { w.Write([]byte(strconv.FormatInt(val, base))) } // printUint outputs an unsigned integer value to Writer w. func printUint(w io.Writer, val uint64, base int) { w.Write([]byte(strconv.FormatUint(val, base))) } // printFloat outputs a floating point value using the specified precision, // which is expected to be 32 or 64bit, to Writer w. func printFloat(w io.Writer, val float64, precision int) { w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) } // printComplex outputs a complex value using the specified float precision // for the real and imaginary parts to Writer w. func printComplex(w io.Writer, c complex128, floatPrecision int) { r := real(c) w.Write(openParenBytes) w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) i := imag(c) if i >= 0 { w.Write(plusBytes) } w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) w.Write(iBytes) w.Write(closeParenBytes) } // printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x' // prefix to Writer w. func printHexPtr(w io.Writer, p uintptr) { // Null pointer. num := uint64(p) if num == 0 { w.Write(nilAngleBytes) return } // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix buf := make([]byte, 18) // It's simpler to construct the hex string right to left. base := uint64(16) i := len(buf) - 1 for num >= base { buf[i] = hexDigits[num%base] num /= base i-- } buf[i] = hexDigits[num] // Add '0x' prefix. i-- buf[i] = 'x' i-- buf[i] = '0' // Strip unused leading bytes. buf = buf[i:] w.Write(buf) } // valuesSorter implements sort.Interface to allow a slice of reflect.Value // elements to be sorted. type valuesSorter struct { values []reflect.Value strings []string // either nil or same len and values cs *ConfigState } // newValuesSorter initializes a valuesSorter instance, which holds a set of // surrogate keys on which the data should be sorted. It uses flags in // ConfigState to decide if and how to populate those surrogate keys. func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { vs := &valuesSorter{values: values, cs: cs} if canSortSimply(vs.values[0].Kind()) { return vs } if !cs.DisableMethods { vs.strings = make([]string, len(values)) for i := range vs.values { b := bytes.Buffer{} if !handleMethods(cs, &b, vs.values[i]) { vs.strings = nil break } vs.strings[i] = b.String() } } if vs.strings == nil && cs.SpewKeys { vs.strings = make([]string, len(values)) for i := range vs.values { vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) } } return vs } // canSortSimply tests whether a reflect.Kind is a primitive that can be sorted // directly, or whether it should be considered for sorting by surrogate keys // (if the ConfigState allows it). func canSortSimply(kind reflect.Kind) bool { // This switch parallels valueSortLess, except for the default case. switch kind { case reflect.Bool: return true case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return true case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: return true case reflect.Float32, reflect.Float64: return true case reflect.String: return true case reflect.Uintptr: return true case reflect.Array: return true } return false } // Len returns the number of values in the slice. It is part of the // sort.Interface implementation. func (s *valuesSorter) Len() int { return len(s.values) } // Swap swaps the values at the passed indices. It is part of the // sort.Interface implementation. func (s *valuesSorter) Swap(i, j int) { s.values[i], s.values[j] = s.values[j], s.values[i] if s.strings != nil { s.strings[i], s.strings[j] = s.strings[j], s.strings[i] } } // valueSortLess returns whether the first value should sort before the second // value. It is used by valueSorter.Less as part of the sort.Interface // implementation. func valueSortLess(a, b reflect.Value) bool { switch a.Kind() { case reflect.Bool: return !a.Bool() && b.Bool() case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return a.Int() < b.Int() case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: return a.Uint() < b.Uint() case reflect.Float32, reflect.Float64: return a.Float() < b.Float() case reflect.String: return a.String() < b.String() case reflect.Uintptr: return a.Uint() < b.Uint() case reflect.Array: // Compare the contents of both arrays. l := a.Len() for i := 0; i < l; i++ { av := a.Index(i) bv := b.Index(i) if av.Interface() == bv.Interface() { continue } return valueSortLess(av, bv) } } return a.String() < b.String() } // Less returns whether the value at index i should sort before the // value at index j. It is part of the sort.Interface implementation. func (s *valuesSorter) Less(i, j int) bool { if s.strings == nil { return valueSortLess(s.values[i], s.values[j]) } return s.strings[i] < s.strings[j] } // sortValues is a sort function that handles both native types and any type that // can be converted to error or Stringer. Other inputs are sorted according to // their Value.String() value to ensure display stability. func sortValues(values []reflect.Value, cs *ConfigState) { if len(values) == 0 { return } sort.Sort(newValuesSorter(values, cs)) } ================================================ FILE: src/github.com/davecgh/go-spew/spew/config.go ================================================ /* * Copyright (c) 2013 Dave Collins * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "io" "os" ) // ConfigState houses the configuration options used by spew to format and // display values. There is a global instance, Config, that is used to control // all top-level Formatter and Dump functionality. Each ConfigState instance // provides methods equivalent to the top-level functions. // // The zero value for ConfigState provides no indentation. You would typically // want to set it to a space or a tab. // // Alternatively, you can use NewDefaultConfig to get a ConfigState instance // with default settings. See the documentation of NewDefaultConfig for default // values. type ConfigState struct { // Indent specifies the string to use for each indentation level. The // global config instance that all top-level functions use set this to a // single space by default. If you would like more indentation, you might // set this to a tab with "\t" or perhaps two spaces with " ". Indent string // MaxDepth controls the maximum number of levels to descend into nested // data structures. The default, 0, means there is no limit. // // NOTE: Circular data structures are properly detected, so it is not // necessary to set this value unless you specifically want to limit deeply // nested data structures. MaxDepth int // DisableMethods specifies whether or not error and Stringer interfaces are // invoked for types that implement them. DisableMethods bool // DisablePointerMethods specifies whether or not to check for and invoke // error and Stringer interfaces on types which only accept a pointer // receiver when the current type is not a pointer. // // NOTE: This might be an unsafe action since calling one of these methods // with a pointer receiver could technically mutate the value, however, // in practice, types which choose to satisify an error or Stringer // interface with a pointer receiver should not be mutating their state // inside these interface methods. As a result, this option relies on // access to the unsafe package, so it will not have any effect when // running in environments without access to the unsafe package such as // Google App Engine or with the "disableunsafe" build tag specified. DisablePointerMethods bool // ContinueOnMethod specifies whether or not recursion should continue once // a custom error or Stringer interface is invoked. The default, false, // means it will print the results of invoking the custom error or Stringer // interface and return immediately instead of continuing to recurse into // the internals of the data type. // // NOTE: This flag does not have any effect if method invocation is disabled // via the DisableMethods or DisablePointerMethods options. ContinueOnMethod bool // SortKeys specifies map keys should be sorted before being printed. Use // this to have a more deterministic, diffable output. Note that only // native types (bool, int, uint, floats, uintptr and string) and types // that support the error or Stringer interfaces (if methods are // enabled) are supported, with other types sorted according to the // reflect.Value.String() output which guarantees display stability. SortKeys bool // SpewKeys specifies that, as a last resort attempt, map keys should // be spewed to strings and sorted by those strings. This is only // considered if SortKeys is true. SpewKeys bool } // Config is the active configuration of the top-level functions. // The configuration can be changed by modifying the contents of spew.Config. var Config = ConfigState{Indent: " "} // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the formatted string as a value that satisfies error. See NewFormatter // for formatting details. // // This function is shorthand for the following syntax: // // fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { return fmt.Errorf(format, c.convertArgs(a)...) } // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprint(w, c.convertArgs(a)...) } // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { return fmt.Fprintf(w, format, c.convertArgs(a)...) } // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it // passed with a Formatter interface returned by c.NewFormatter. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprintln(w, c.convertArgs(a)...) } // Print is a wrapper for fmt.Print that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Print(a ...interface{}) (n int, err error) { return fmt.Print(c.convertArgs(a)...) } // Printf is a wrapper for fmt.Printf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format, c.convertArgs(a)...) } // Println is a wrapper for fmt.Println that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Println(a ...interface{}) (n int, err error) { return fmt.Println(c.convertArgs(a)...) } // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Sprint(a ...interface{}) string { return fmt.Sprint(c.convertArgs(a)...) } // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Sprintf(format string, a ...interface{}) string { return fmt.Sprintf(format, c.convertArgs(a)...) } // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it // were passed with a Formatter interface returned by c.NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Sprintln(a ...interface{}) string { return fmt.Sprintln(c.convertArgs(a)...) } /* NewFormatter returns a custom formatter that satisfies the fmt.Formatter interface. As a result, it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Typically this function shouldn't be called directly. It is much easier to make use of the custom formatter by calling one of the convenience functions such as c.Printf, c.Println, or c.Printf. */ func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { return newFormatter(c, v) } // Fdump formats and displays the passed arguments to io.Writer w. It formats // exactly the same as Dump. func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { fdump(c, w, a...) } /* Dump displays the passed parameters to standard out with newlines, customizable indentation, and additional debug information such as complete types and all pointer addresses used to indirect to the final value. It provides the following features over the built-in printing facilities provided by the fmt package: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output The configuration options are controlled by modifying the public members of c. See ConfigState for options documentation. See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to get the formatted result as a string. */ func (c *ConfigState) Dump(a ...interface{}) { fdump(c, os.Stdout, a...) } // Sdump returns a string with the passed arguments formatted exactly the same // as Dump. func (c *ConfigState) Sdump(a ...interface{}) string { var buf bytes.Buffer fdump(c, &buf, a...) return buf.String() } // convertArgs accepts a slice of arguments and returns a slice of the same // length with each argument converted to a spew Formatter interface using // the ConfigState associated with s. func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { formatters = make([]interface{}, len(args)) for index, arg := range args { formatters[index] = newFormatter(c, arg) } return formatters } // NewDefaultConfig returns a ConfigState with the following default settings. // // Indent: " " // MaxDepth: 0 // DisableMethods: false // DisablePointerMethods: false // ContinueOnMethod: false // SortKeys: false func NewDefaultConfig() *ConfigState { return &ConfigState{Indent: " "} } ================================================ FILE: src/github.com/davecgh/go-spew/spew/doc.go ================================================ /* * Copyright (c) 2013 Dave Collins * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* Package spew implements a deep pretty printer for Go data structures to aid in debugging. A quick overview of the additional features spew provides over the built-in printing facilities for Go data types are as follows: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output (only when using Dump style) There are two different approaches spew allows for dumping Go data structures: * Dump style which prints with newlines, customizable indentation, and additional debug information such as types and all pointer addresses used to indirect to the final value * A custom Formatter interface that integrates cleanly with the standard fmt package and replaces %v, %+v, %#v, and %#+v to provide inline printing similar to the default %v while providing the additional functionality outlined above and passing unsupported format verbs such as %x and %q along to fmt Quick Start This section demonstrates how to quickly get started with spew. See the sections below for further details on formatting and configuration options. To dump a variable with full newlines, indentation, type, and pointer information use Dump, Fdump, or Sdump: spew.Dump(myVar1, myVar2, ...) spew.Fdump(someWriter, myVar1, myVar2, ...) str := spew.Sdump(myVar1, myVar2, ...) Alternatively, if you would prefer to use format strings with a compacted inline printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses): spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) Configuration Options Configuration of spew is handled by fields in the ConfigState type. For convenience, all of the top-level functions use a global state available via the spew.Config global. It is also possible to create a ConfigState instance that provides methods equivalent to the top-level functions. This allows concurrent configuration options. See the ConfigState documentation for more details. The following configuration options are available: * Indent String to use for each indentation level for Dump functions. It is a single space by default. A popular alternative is "\t". * MaxDepth Maximum number of levels to descend into nested data structures. There is no limit by default. * DisableMethods Disables invocation of error and Stringer interface methods. Method invocation is enabled by default. * DisablePointerMethods Disables invocation of error and Stringer interface methods on types which only accept pointer receivers from non-pointer variables. Pointer method invocation is enabled by default. * ContinueOnMethod Enables recursion into types after invoking error and Stringer interface methods. Recursion after method invocation is disabled by default. * SortKeys Specifies map keys should be sorted before being printed. Use this to have a more deterministic, diffable output. Note that only native types (bool, int, uint, floats, uintptr and string) and types which implement error or Stringer interfaces are supported with other types sorted according to the reflect.Value.String() output which guarantees display stability. Natural map order is used by default. * SpewKeys Specifies that, as a last resort attempt, map keys should be spewed to strings and sorted by those strings. This is only considered if SortKeys is true. Dump Usage Simply call spew.Dump with a list of variables you want to dump: spew.Dump(myVar1, myVar2, ...) You may also call spew.Fdump if you would prefer to output to an arbitrary io.Writer. For example, to dump to standard error: spew.Fdump(os.Stderr, myVar1, myVar2, ...) A third option is to call spew.Sdump to get the formatted output as a string: str := spew.Sdump(myVar1, myVar2, ...) Sample Dump Output See the Dump example for details on the setup of the types and variables being shown here. (main.Foo) { unexportedField: (*main.Bar)(0xf84002e210)({ flag: (main.Flag) flagTwo, data: (uintptr) }), ExportedField: (map[interface {}]interface {}) (len=1) { (string) (len=3) "one": (bool) true } } Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C command as shown. ([]uint8) (len=32 cap=32) { 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| 00000020 31 32 |12| } Custom Formatter Spew provides a custom formatter that implements the fmt.Formatter interface so that it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Custom Formatter Usage The simplest way to make use of the spew custom formatter is to call one of the convenience functions such as spew.Printf, spew.Println, or spew.Printf. The functions have syntax you are most likely already familiar with: spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) spew.Println(myVar, myVar2) spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) See the Index for the full list convenience functions. Sample Formatter Output Double pointer to a uint8: %v: <**>5 %+v: <**>(0xf8400420d0->0xf8400420c8)5 %#v: (**uint8)5 %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 Pointer to circular struct with a uint8 field and a pointer to itself: %v: <*>{1 <*>} %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} See the Printf example for details on the setup of variables being shown here. Errors Since it is possible for custom Stringer/error interfaces to panic, spew detects them and handles them internally by printing the panic information inline with the output. Since spew is intended to provide deep pretty printing capabilities on structures, it intentionally does not return any errors. */ package spew ================================================ FILE: src/github.com/davecgh/go-spew/spew/dump.go ================================================ /* * Copyright (c) 2013 Dave Collins * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "encoding/hex" "fmt" "io" "os" "reflect" "regexp" "strconv" "strings" ) var ( // uint8Type is a reflect.Type representing a uint8. It is used to // convert cgo types to uint8 slices for hexdumping. uint8Type = reflect.TypeOf(uint8(0)) // cCharRE is a regular expression that matches a cgo char. // It is used to detect character arrays to hexdump them. cCharRE = regexp.MustCompile("^.*\\._Ctype_char$") // cUnsignedCharRE is a regular expression that matches a cgo unsigned // char. It is used to detect unsigned character arrays to hexdump // them. cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$") // cUint8tCharRE is a regular expression that matches a cgo uint8_t. // It is used to detect uint8_t arrays to hexdump them. cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$") ) // dumpState contains information about the state of a dump operation. type dumpState struct { w io.Writer depth int pointers map[uintptr]int ignoreNextType bool ignoreNextIndent bool cs *ConfigState } // indent performs indentation according to the depth level and cs.Indent // option. func (d *dumpState) indent() { if d.ignoreNextIndent { d.ignoreNextIndent = false return } d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) } // unpackValue returns values inside of non-nil interfaces when possible. // This is useful for data types like structs, arrays, slices, and maps which // can contain varying types packed inside an interface. func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface && !v.IsNil() { v = v.Elem() } return v } // dumpPtr handles formatting of pointers by indirecting them as necessary. func (d *dumpState) dumpPtr(v reflect.Value) { // Remove pointers at or below the current depth from map used to detect // circular refs. for k, depth := range d.pointers { if depth >= d.depth { delete(d.pointers, k) } } // Keep list of all dereferenced pointers to show later. pointerChain := make([]uintptr, 0) // Figure out how many levels of indirection there are by dereferencing // pointers and unpacking interfaces down the chain while detecting circular // references. nilFound := false cycleFound := false indirects := 0 ve := v for ve.Kind() == reflect.Ptr { if ve.IsNil() { nilFound = true break } indirects++ addr := ve.Pointer() pointerChain = append(pointerChain, addr) if pd, ok := d.pointers[addr]; ok && pd < d.depth { cycleFound = true indirects-- break } d.pointers[addr] = d.depth ve = ve.Elem() if ve.Kind() == reflect.Interface { if ve.IsNil() { nilFound = true break } ve = ve.Elem() } } // Display type information. d.w.Write(openParenBytes) d.w.Write(bytes.Repeat(asteriskBytes, indirects)) d.w.Write([]byte(ve.Type().String())) d.w.Write(closeParenBytes) // Display pointer information. if len(pointerChain) > 0 { d.w.Write(openParenBytes) for i, addr := range pointerChain { if i > 0 { d.w.Write(pointerChainBytes) } printHexPtr(d.w, addr) } d.w.Write(closeParenBytes) } // Display dereferenced value. d.w.Write(openParenBytes) switch { case nilFound == true: d.w.Write(nilAngleBytes) case cycleFound == true: d.w.Write(circularBytes) default: d.ignoreNextType = true d.dump(ve) } d.w.Write(closeParenBytes) } // dumpSlice handles formatting of arrays and slices. Byte (uint8 under // reflection) arrays and slices are dumped in hexdump -C fashion. func (d *dumpState) dumpSlice(v reflect.Value) { // Determine whether this type should be hex dumped or not. Also, // for types which should be hexdumped, try to use the underlying data // first, then fall back to trying to convert them to a uint8 slice. var buf []uint8 doConvert := false doHexDump := false numEntries := v.Len() if numEntries > 0 { vt := v.Index(0).Type() vts := vt.String() switch { // C types that need to be converted. case cCharRE.MatchString(vts): fallthrough case cUnsignedCharRE.MatchString(vts): fallthrough case cUint8tCharRE.MatchString(vts): doConvert = true // Try to use existing uint8 slices and fall back to converting // and copying if that fails. case vt.Kind() == reflect.Uint8: // We need an addressable interface to convert the type // to a byte slice. However, the reflect package won't // give us an interface on certain things like // unexported struct fields in order to enforce // visibility rules. We use unsafe, when available, to // bypass these restrictions since this package does not // mutate the values. vs := v if !vs.CanInterface() || !vs.CanAddr() { vs = unsafeReflectValue(vs) } if !UnsafeDisabled { vs = vs.Slice(0, numEntries) // Use the existing uint8 slice if it can be // type asserted. iface := vs.Interface() if slice, ok := iface.([]uint8); ok { buf = slice doHexDump = true break } } // The underlying data needs to be converted if it can't // be type asserted to a uint8 slice. doConvert = true } // Copy and convert the underlying type if needed. if doConvert && vt.ConvertibleTo(uint8Type) { // Convert and copy each element into a uint8 byte // slice. buf = make([]uint8, numEntries) for i := 0; i < numEntries; i++ { vv := v.Index(i) buf[i] = uint8(vv.Convert(uint8Type).Uint()) } doHexDump = true } } // Hexdump the entire slice as needed. if doHexDump { indent := strings.Repeat(d.cs.Indent, d.depth) str := indent + hex.Dump(buf) str = strings.Replace(str, "\n", "\n"+indent, -1) str = strings.TrimRight(str, d.cs.Indent) d.w.Write([]byte(str)) return } // Recursively call dump for each item. for i := 0; i < numEntries; i++ { d.dump(d.unpackValue(v.Index(i))) if i < (numEntries - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } // dump is the main workhorse for dumping a value. It uses the passed reflect // value to figure out what kind of object we are dealing with and formats it // appropriately. It is a recursive function, however circular data structures // are detected and handled properly. func (d *dumpState) dump(v reflect.Value) { // Handle invalid reflect values immediately. kind := v.Kind() if kind == reflect.Invalid { d.w.Write(invalidAngleBytes) return } // Handle pointers specially. if kind == reflect.Ptr { d.indent() d.dumpPtr(v) return } // Print type information unless already handled elsewhere. if !d.ignoreNextType { d.indent() d.w.Write(openParenBytes) d.w.Write([]byte(v.Type().String())) d.w.Write(closeParenBytes) d.w.Write(spaceBytes) } d.ignoreNextType = false // Display length and capacity if the built-in len and cap functions // work with the value's kind and the len/cap itself is non-zero. valueLen, valueCap := 0, 0 switch v.Kind() { case reflect.Array, reflect.Slice, reflect.Chan: valueLen, valueCap = v.Len(), v.Cap() case reflect.Map, reflect.String: valueLen = v.Len() } if valueLen != 0 || valueCap != 0 { d.w.Write(openParenBytes) if valueLen != 0 { d.w.Write(lenEqualsBytes) printInt(d.w, int64(valueLen), 10) } if valueCap != 0 { if valueLen != 0 { d.w.Write(spaceBytes) } d.w.Write(capEqualsBytes) printInt(d.w, int64(valueCap), 10) } d.w.Write(closeParenBytes) d.w.Write(spaceBytes) } // Call Stringer/error interfaces if they exist and the handle methods flag // is enabled if !d.cs.DisableMethods { if (kind != reflect.Invalid) && (kind != reflect.Interface) { if handled := handleMethods(d.cs, d.w, v); handled { return } } } switch kind { case reflect.Invalid: // Do nothing. We should never get here since invalid has already // been handled above. case reflect.Bool: printBool(d.w, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: printInt(d.w, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: printUint(d.w, v.Uint(), 10) case reflect.Float32: printFloat(d.w, v.Float(), 32) case reflect.Float64: printFloat(d.w, v.Float(), 64) case reflect.Complex64: printComplex(d.w, v.Complex(), 32) case reflect.Complex128: printComplex(d.w, v.Complex(), 64) case reflect.Slice: if v.IsNil() { d.w.Write(nilAngleBytes) break } fallthrough case reflect.Array: d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { d.dumpSlice(v) } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.String: d.w.Write([]byte(strconv.Quote(v.String()))) case reflect.Interface: // The only time we should get here is for nil interfaces due to // unpackValue calls. if v.IsNil() { d.w.Write(nilAngleBytes) } case reflect.Ptr: // Do nothing. We should never get here since pointers have already // been handled above. case reflect.Map: // nil maps should be indicated as different than empty maps if v.IsNil() { d.w.Write(nilAngleBytes) break } d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { numEntries := v.Len() keys := v.MapKeys() if d.cs.SortKeys { sortValues(keys, d.cs) } for i, key := range keys { d.dump(d.unpackValue(key)) d.w.Write(colonSpaceBytes) d.ignoreNextIndent = true d.dump(d.unpackValue(v.MapIndex(key))) if i < (numEntries - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.Struct: d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { vt := v.Type() numFields := v.NumField() for i := 0; i < numFields; i++ { d.indent() vtf := vt.Field(i) d.w.Write([]byte(vtf.Name)) d.w.Write(colonSpaceBytes) d.ignoreNextIndent = true d.dump(d.unpackValue(v.Field(i))) if i < (numFields - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.Uintptr: printHexPtr(d.w, uintptr(v.Uint())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: printHexPtr(d.w, v.Pointer()) // There were not any other types at the time this code was written, but // fall back to letting the default fmt package handle it in case any new // types are added. default: if v.CanInterface() { fmt.Fprintf(d.w, "%v", v.Interface()) } else { fmt.Fprintf(d.w, "%v", v.String()) } } } // fdump is a helper function to consolidate the logic from the various public // methods which take varying writers and config states. func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { for _, arg := range a { if arg == nil { w.Write(interfaceBytes) w.Write(spaceBytes) w.Write(nilAngleBytes) w.Write(newlineBytes) continue } d := dumpState{w: w, cs: cs} d.pointers = make(map[uintptr]int) d.dump(reflect.ValueOf(arg)) d.w.Write(newlineBytes) } } // Fdump formats and displays the passed arguments to io.Writer w. It formats // exactly the same as Dump. func Fdump(w io.Writer, a ...interface{}) { fdump(&Config, w, a...) } // Sdump returns a string with the passed arguments formatted exactly the same // as Dump. func Sdump(a ...interface{}) string { var buf bytes.Buffer fdump(&Config, &buf, a...) return buf.String() } /* Dump displays the passed parameters to standard out with newlines, customizable indentation, and additional debug information such as complete types and all pointer addresses used to indirect to the final value. It provides the following features over the built-in printing facilities provided by the fmt package: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output The configuration options are controlled by an exported package global, spew.Config. See ConfigState for options documentation. See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to get the formatted result as a string. */ func Dump(a ...interface{}) { fdump(&Config, os.Stdout, a...) } ================================================ FILE: src/github.com/davecgh/go-spew/spew/format.go ================================================ /* * Copyright (c) 2013 Dave Collins * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "reflect" "strconv" "strings" ) // supportedFlags is a list of all the character flags supported by fmt package. const supportedFlags = "0-+# " // formatState implements the fmt.Formatter interface and contains information // about the state of a formatting operation. The NewFormatter function can // be used to get a new Formatter which can be used directly as arguments // in standard fmt package printing calls. type formatState struct { value interface{} fs fmt.State depth int pointers map[uintptr]int ignoreNextType bool cs *ConfigState } // buildDefaultFormat recreates the original format string without precision // and width information to pass in to fmt.Sprintf in the case of an // unrecognized type. Unless new types are added to the language, this // function won't ever be called. func (f *formatState) buildDefaultFormat() (format string) { buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { if f.fs.Flag(int(flag)) { buf.WriteRune(flag) } } buf.WriteRune('v') format = buf.String() return format } // constructOrigFormat recreates the original format string including precision // and width information to pass along to the standard fmt package. This allows // automatic deferral of all format strings this package doesn't support. func (f *formatState) constructOrigFormat(verb rune) (format string) { buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { if f.fs.Flag(int(flag)) { buf.WriteRune(flag) } } if width, ok := f.fs.Width(); ok { buf.WriteString(strconv.Itoa(width)) } if precision, ok := f.fs.Precision(); ok { buf.Write(precisionBytes) buf.WriteString(strconv.Itoa(precision)) } buf.WriteRune(verb) format = buf.String() return format } // unpackValue returns values inside of non-nil interfaces when possible and // ensures that types for values which have been unpacked from an interface // are displayed when the show types flag is also set. // This is useful for data types like structs, arrays, slices, and maps which // can contain varying types packed inside an interface. func (f *formatState) unpackValue(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface { f.ignoreNextType = false if !v.IsNil() { v = v.Elem() } } return v } // formatPtr handles formatting of pointers by indirecting them as necessary. func (f *formatState) formatPtr(v reflect.Value) { // Display nil if top level pointer is nil. showTypes := f.fs.Flag('#') if v.IsNil() && (!showTypes || f.ignoreNextType) { f.fs.Write(nilAngleBytes) return } // Remove pointers at or below the current depth from map used to detect // circular refs. for k, depth := range f.pointers { if depth >= f.depth { delete(f.pointers, k) } } // Keep list of all dereferenced pointers to possibly show later. pointerChain := make([]uintptr, 0) // Figure out how many levels of indirection there are by derferencing // pointers and unpacking interfaces down the chain while detecting circular // references. nilFound := false cycleFound := false indirects := 0 ve := v for ve.Kind() == reflect.Ptr { if ve.IsNil() { nilFound = true break } indirects++ addr := ve.Pointer() pointerChain = append(pointerChain, addr) if pd, ok := f.pointers[addr]; ok && pd < f.depth { cycleFound = true indirects-- break } f.pointers[addr] = f.depth ve = ve.Elem() if ve.Kind() == reflect.Interface { if ve.IsNil() { nilFound = true break } ve = ve.Elem() } } // Display type or indirection level depending on flags. if showTypes && !f.ignoreNextType { f.fs.Write(openParenBytes) f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) f.fs.Write([]byte(ve.Type().String())) f.fs.Write(closeParenBytes) } else { if nilFound || cycleFound { indirects += strings.Count(ve.Type().String(), "*") } f.fs.Write(openAngleBytes) f.fs.Write([]byte(strings.Repeat("*", indirects))) f.fs.Write(closeAngleBytes) } // Display pointer information depending on flags. if f.fs.Flag('+') && (len(pointerChain) > 0) { f.fs.Write(openParenBytes) for i, addr := range pointerChain { if i > 0 { f.fs.Write(pointerChainBytes) } printHexPtr(f.fs, addr) } f.fs.Write(closeParenBytes) } // Display dereferenced value. switch { case nilFound == true: f.fs.Write(nilAngleBytes) case cycleFound == true: f.fs.Write(circularShortBytes) default: f.ignoreNextType = true f.format(ve) } } // format is the main workhorse for providing the Formatter interface. It // uses the passed reflect value to figure out what kind of object we are // dealing with and formats it appropriately. It is a recursive function, // however circular data structures are detected and handled properly. func (f *formatState) format(v reflect.Value) { // Handle invalid reflect values immediately. kind := v.Kind() if kind == reflect.Invalid { f.fs.Write(invalidAngleBytes) return } // Handle pointers specially. if kind == reflect.Ptr { f.formatPtr(v) return } // Print type information unless already handled elsewhere. if !f.ignoreNextType && f.fs.Flag('#') { f.fs.Write(openParenBytes) f.fs.Write([]byte(v.Type().String())) f.fs.Write(closeParenBytes) } f.ignoreNextType = false // Call Stringer/error interfaces if they exist and the handle methods // flag is enabled. if !f.cs.DisableMethods { if (kind != reflect.Invalid) && (kind != reflect.Interface) { if handled := handleMethods(f.cs, f.fs, v); handled { return } } } switch kind { case reflect.Invalid: // Do nothing. We should never get here since invalid has already // been handled above. case reflect.Bool: printBool(f.fs, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: printInt(f.fs, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: printUint(f.fs, v.Uint(), 10) case reflect.Float32: printFloat(f.fs, v.Float(), 32) case reflect.Float64: printFloat(f.fs, v.Float(), 64) case reflect.Complex64: printComplex(f.fs, v.Complex(), 32) case reflect.Complex128: printComplex(f.fs, v.Complex(), 64) case reflect.Slice: if v.IsNil() { f.fs.Write(nilAngleBytes) break } fallthrough case reflect.Array: f.fs.Write(openBracketBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { numEntries := v.Len() for i := 0; i < numEntries; i++ { if i > 0 { f.fs.Write(spaceBytes) } f.ignoreNextType = true f.format(f.unpackValue(v.Index(i))) } } f.depth-- f.fs.Write(closeBracketBytes) case reflect.String: f.fs.Write([]byte(v.String())) case reflect.Interface: // The only time we should get here is for nil interfaces due to // unpackValue calls. if v.IsNil() { f.fs.Write(nilAngleBytes) } case reflect.Ptr: // Do nothing. We should never get here since pointers have already // been handled above. case reflect.Map: // nil maps should be indicated as different than empty maps if v.IsNil() { f.fs.Write(nilAngleBytes) break } f.fs.Write(openMapBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { keys := v.MapKeys() if f.cs.SortKeys { sortValues(keys, f.cs) } for i, key := range keys { if i > 0 { f.fs.Write(spaceBytes) } f.ignoreNextType = true f.format(f.unpackValue(key)) f.fs.Write(colonBytes) f.ignoreNextType = true f.format(f.unpackValue(v.MapIndex(key))) } } f.depth-- f.fs.Write(closeMapBytes) case reflect.Struct: numFields := v.NumField() f.fs.Write(openBraceBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { vt := v.Type() for i := 0; i < numFields; i++ { if i > 0 { f.fs.Write(spaceBytes) } vtf := vt.Field(i) if f.fs.Flag('+') || f.fs.Flag('#') { f.fs.Write([]byte(vtf.Name)) f.fs.Write(colonBytes) } f.format(f.unpackValue(v.Field(i))) } } f.depth-- f.fs.Write(closeBraceBytes) case reflect.Uintptr: printHexPtr(f.fs, uintptr(v.Uint())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: printHexPtr(f.fs, v.Pointer()) // There were not any other types at the time this code was written, but // fall back to letting the default fmt package handle it if any get added. default: format := f.buildDefaultFormat() if v.CanInterface() { fmt.Fprintf(f.fs, format, v.Interface()) } else { fmt.Fprintf(f.fs, format, v.String()) } } } // Format satisfies the fmt.Formatter interface. See NewFormatter for usage // details. func (f *formatState) Format(fs fmt.State, verb rune) { f.fs = fs // Use standard formatting for verbs that are not v. if verb != 'v' { format := f.constructOrigFormat(verb) fmt.Fprintf(fs, format, f.value) return } if f.value == nil { if fs.Flag('#') { fs.Write(interfaceBytes) } fs.Write(nilAngleBytes) return } f.format(reflect.ValueOf(f.value)) } // newFormatter is a helper function to consolidate the logic from the various // public methods which take varying config states. func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { fs := &formatState{value: v, cs: cs} fs.pointers = make(map[uintptr]int) return fs } /* NewFormatter returns a custom formatter that satisfies the fmt.Formatter interface. As a result, it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Typically this function shouldn't be called directly. It is much easier to make use of the custom formatter by calling one of the convenience functions such as Printf, Println, or Fprintf. */ func NewFormatter(v interface{}) fmt.Formatter { return newFormatter(&Config, v) } ================================================ FILE: src/github.com/davecgh/go-spew/spew/spew.go ================================================ /* * Copyright (c) 2013 Dave Collins * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "fmt" "io" ) // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the formatted string as a value that satisfies error. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) func Errorf(format string, a ...interface{}) (err error) { return fmt.Errorf(format, convertArgs(a)...) } // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) func Fprint(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprint(w, convertArgs(a)...) } // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { return fmt.Fprintf(w, format, convertArgs(a)...) } // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it // passed with a default Formatter interface returned by NewFormatter. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprintln(w, convertArgs(a)...) } // Print is a wrapper for fmt.Print that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) func Print(a ...interface{}) (n int, err error) { return fmt.Print(convertArgs(a)...) } // Printf is a wrapper for fmt.Printf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) func Printf(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format, convertArgs(a)...) } // Println is a wrapper for fmt.Println that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) func Println(a ...interface{}) (n int, err error) { return fmt.Println(convertArgs(a)...) } // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) func Sprint(a ...interface{}) string { return fmt.Sprint(convertArgs(a)...) } // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) func Sprintf(format string, a ...interface{}) string { return fmt.Sprintf(format, convertArgs(a)...) } // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it // were passed with a default Formatter interface returned by NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) func Sprintln(a ...interface{}) string { return fmt.Sprintln(convertArgs(a)...) } // convertArgs accepts a slice of arguments and returns a slice of the same // length with each argument converted to a default spew Formatter interface. func convertArgs(args []interface{}) (formatters []interface{}) { formatters = make([]interface{}, len(args)) for index, arg := range args { formatters[index] = NewFormatter(arg) } return formatters } ================================================ FILE: src/github.com/dolotech/leaf/LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright 2014-2017 Name5566. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: src/github.com/dolotech/leaf/README.md ================================================ Leaf ==== A pragmatic game server framework in Go (golang). Features --------- * Extremely easy to use * Reliable * Multicore support * Modularity Community --------- * QQ 群:376389675 Documentation --------- * [中文文档](https://github.com/name5566/leaf/blob/master/TUTORIAL_ZH.md) * [English](https://github.com/name5566/leaf/blob/master/TUTORIAL_EN.md) Licensing --------- Leaf is licensed under the Apache License, Version 2.0. See [LICENSE](https://github.com/name5566/leaf/blob/master/LICENSE) for the full license text. ================================================ FILE: src/github.com/dolotech/leaf/TUTORIAL_EN.md ================================================ Brief introduction to Leaf ========================== Leaf, written in Go, is a open source game server framework aiming to boost the efficiency both in development and runtime. Leaf champions below philosophies: * Simple APIs. Leaf tends to provide simple and plain interfaces which are always best for use. * Self-healing. Leaf always tries to salvage the process from runtime errors instead of leaving it to crash. * Multi-core support. Leaf utilize its modules and [leaf/go](https://github.com/name5566/leaf/tree/master/go) to make use of CPU resouces at maximum while avoiding varieties of side effects may be caused. * Module-based. Leaf's Modules -------------- A game server implemented with Leaf may include many modules (e.g. [LeafServer](https://github.com/name5566/leafserver)) which all share below traits: * Each module runs inside a separate goroutine * Modules communicate with one another via a light weight RPC channel([leaf/chanrpc](https://github.com/name5566/leaf/tree/master/chanrpc)) Leaf suggests not to take in too many modules in your game server implementation. Modules are registered at the beginning of program as below ```go leaf.Run( game.Module, gate.Module, login.Module, ) ``` The modules of `game`, `gate` and `gate` are registered consecutively. They are required to implement a `Module` interface. ```go type Module interface { OnInit() OnDestroy() Run(closeSig chan bool) } ``` Leaf follows below steps to manage modules: 1. Takes turns (FIFO) to register the given modules by calling `OnInit()`' in a parent goroutine 2. Starts a new goroutine for each module to run `Run()` 3. When the parent goroutine is being closed (like by a SIGINT), the modules will be unregistered by calling `OnDestroy()` in the reverse order when they get registered. Leaf source code directories ---------------------------- * leaf/chanrpc : RPC channel for inter-modules communication * leaf/db : Database Utilities with [MongoDB](https://www.mongodb.org/) support * leaf/gate : Gate module that connects to client * leaf/go : Factory of goroutine that manageable for Leaf * leaf/log : Logging * leaf/network : Networking through TCP or WebSocket with a customized message encoding. There are two built-in encodings, [protobuf](https://developers.google.com/protocol-buffers) and JSON. * leaf/recordfile : To manage game related data. * leaf/timer : Timer * leaf/util : Utilities How to use Leaf --------------- [LeafServer](https://github.com/name5566/leafserver) is a game server developped with Leaf. Let's start with it. Download the source code of LeafServer: ``` git clone https://github.com/name5566/leafserver ``` Download and install leafserver to GOPATH: ``` go get github.com/name5566/leaf ``` Compile LeafServer: ``` go install server ``` Run `server` you will get below screen output if everything is successful. ``` 2015/08/26 22:11:27 [release] Leaf 1.1.2 starting up ``` Press Ctrl + C to terminate the process, you'll see ``` 2015/08/26 22:12:30 [release] Leaf closing down (signal: interrupt) ``` ### Hello Leaf Now with the acknowledge of LeafServer, we come to see how server receives and handles messages. Firstly we define a JSON-encoded message(likely the protobuf). Open LeafServer msg/msg.go then you will see below: ```go package msg import ( "github.com/name5566/leaf/network" ) var Processor network.Processor func init() { } ``` Processor is the message handler. Here we use the handler of JSON, the default message encoding, and create a Hello message. ```go package msg import ( "github.com/name5566/leaf/network/json" ) // Create a JSON Processor(or protobuf if you like) var Processor = json.NewProcessor() func init() { // Register message Hello Processor.Register(&Hello{}) } // One struct for one message // Contains a string member type Hello struct { Name string } ``` Every message sent from client to server will be flown to `gate` module for routing. Just in brief, `gate` determines which message will be handled by which modules. We want to feed `game` module with `Hello` here, so open LeafServer gate/router.go and write below: ```go package gate import ( "server/game" "server/msg" ) func init() { // Route Hello to game // All communication are through ChanRPC including the management messages msg.Processor.SetRouter(&msg.Hello{}, game.ChanRPC) } ``` It is ready to handle `Hello` message in `game` module. Open LeafServer game/internal/handler.go and write: ```go package internal import ( "github.com/name5566/leaf/log" "github.com/name5566/leaf/gate" "reflect" "server/msg" ) func init() { // Register the handler of `Hello` message to `game` module handleHello handler(&msg.Hello{}, handleHello) } func handler(m interface{}, h interface{}) { skeleton.RegisterChanRPC(reflect.TypeOf(m), h) } func handleHello(args []interface{}) { // Send "Hello" m := args[0].(*msg.Hello) // The receiver a := args[1].(gate.Agent) // The content of the message log.Debug("hello %v", m.Name) // Reply with a `Hello` a.WriteMsg(&msg.Hello{ Name: "client", }) } ``` By here we've finished a simplest example for server. Now we will write a client from scratch for testing to understand the message structure better. When we choose TCP over the others, the message in transition will be all formated like below: ``` -------------- | len | data | -------------- ``` To be more specific: 1. len means the size of data by bytes. len itself takes space(2 bytes by default, configurable). The minimum size of len equals the the minimum size of a single message. 2. data part is encoded with JSON or protobuf (or a customized one) Write the client: ```go package main import ( "encoding/binary" "net" ) func main() { conn, err := net.Dial("tcp", "127.0.0.1:3563") if err != nil { panic(err) } // Hello message (JSON-encoded) // The structure of the message data := []byte(`{ "Hello": { "Name": "leaf" } }`) // len + data m := make([]byte, 2+len(data)) // BigEndian encoded binary.BigEndian.PutUint16(m, uint16(len(data))) copy(m[2:], data) // Send message conn.Write(m) } ``` Run the client to send the message, then server will display it as received ``` 2015/09/25 07:41:03 [debug ] hello leaf 2015/09/25 07:41:03 [debug ] read message: read tcp 127.0.0.1:3563->127.0.0.1:54599: wsarecv: An existing connection was forcibly closed by the remote host. ``` Client will exit after send out the message, and then disconnect with server. Thus server displays the event message of disconnection(the second, the event message might be dependant on the version of Go environment). Beside TCP, WebSocket is another choice of protocol and ideal for HTML5 web game. Leaf uses TCP or WebSocket separately or jointly. In other words, server can handle TCP messages and WebSocket messages at the same time. They are "transparent" for developers. From now on we will demonstrate how to use a client based on WebSocket: ```html ``` Save above to a HTML file and open it in a browser (with WebSocket support). Before that, we still have to update the configuration for LeafServer in bin/conf/server.json by adding WebSocket listenning address: ```json { "LogLevel": "debug", "LogPath": "", "TCPAddr": "127.0.0.1:3563", "WSAddr": "127.0.0.1:3653", "MaxConnNum": 20000 } ``` Restart server then we get the first WebSocket message: ``` 2015/09/25 07:50:03 [debug ] hello leaf ``` Please to be noted: Within WebSocket, Leaf always send binary messages rather text messages. ### Leaf in details LeafServer includes three modules, they are: * gate module: for management of connection * login module: for the user authentication * game module: for the main business The structure of a Leaf module is suggested (but not forced) to: 1. Be located in a separate directory 2. Have its internal implementation located under `./internal` 3. Have a file external.go to expose its interfaces. For instance of external.go: ```go package game import ( "server/game/internal" ) var ( // Instantiate game module Module = new(internal.Module) // Expose ChanRPC ChanRPC = internal.ChanRPC ) ``` Instantiation of game module must be done before its registration to Leaf framework(detailed in LeafServer main.go). Besides ChanRPC needs to be exposed for inter-module communication. Enter into game module's internal(LeafServer game/internal/module.go): ```go package internal import ( "github.com/name5566/leaf/module" "server/base" ) var ( skeleton = base.NewSkeleton() ChanRPC = skeleton.ChanRPCServer ) type Module struct { *module.Skeleton } func (m *Module) OnInit() { m.Skeleton = skeleton } func (m *Module) OnDestroy() { } ``` skeleton is the key which implements `Run()` and provides: * ChanRPC * goroutine * Timer ### Leaf ChanRPC Since in Leaf, every module runs in a separate goroutine, a RPC channel is needed to support the communication between modules. The representing object ChanRPC needs to be registered when the game server is being started and actually it is not safe. For example, in LeafServer, game module registers two ChanRPC objects: NewAgent and CloseAgent. ```go package internal import ( "github.com/name5566/leaf/gate" ) func init() { skeleton.RegisterChanRPC("NewAgent", rpcNewAgent) skeleton.RegisterChanRPC("CloseAgent", rpcCloseAgent) } func rpcNewAgent(args []interface{}) { } func rpcCloseAgent(args []interface{}) { } ``` skeleton is used to register ChanRPC. RegisterChanRPC's first parameter is the string name of ChanRPC and the second is the function that implements ChanRPC. NewAgent and CloseAgent will be called by gate module respectively when connection is set up or broken. The calling of ChanRPC includes 3 modes: 1. Synchronous mode : called waiting for ChanRPC is yielded 2. Asynchronous mode : called with a callback function where you can handle the returned ChanRPC 3. "Go mode" : return immediately ignoring any return values or errors This is how gate module call game module's NewAgent ChanRPC (This snippet is simplified for demonstration): ```go game.ChanRPC.Go("NewAgent", a) ``` Here NewAgent will be called with a parameter a which can be retrieved from args[0], the rest can be done in the same manner. More references are at [leaf/chanrpc](https://github.com/name5566/leaf/blob/master/chanrpc). Please be noted, no matter how delicate the encapsulation is, calling function across goroutines cannot be that straight. Try not to create too many modules and interactions. Modules designed in Leaf are supposed to decouple the businesses from others rather make most use of CPU cores. The correct way to make most use of CPU cores is to use goroutine properly. ### Leaf Go Use goroutine properly can make better use of CPU cores. Leaf implements its own Go() for below reasons: * Errors within goroutine can be handled * Game server needs to wait for all goroutines' execution * The results of goroutine can be obtained more easily * goroutine will follow the order to be exercised. It is very important in some occasion Here is an example which can be tested in OnInit() in LeafServer's module. ```go log.Debug("1") // Define res to make the result watchable var res string skeleton.Go(func() { // Simulate a slow operation time.Sleep(1 * time.Second) // res is modified res = "3" }, func() { log.Debug(res) }) log.Debug("2") ``` The result are: ```go 2015/08/27 20:37:17 [debug ] 1 2015/08/27 20:37:17 [debug ] 2 2015/08/27 20:37:18 [debug ] 3 ``` skeleton.Go() accepts two function parameters, first one will be exercised in a separate goroutine and afterwards the second be exercised within the same goroutine. And res can only be used by one goroutine at one moment so nothing more need to be done for synchronization. This implementation makes CPU can be fully used while no need to block goroutines. It is quite convenient when shared resources are used. More references are at [leaf/go](https://github.com/name5566/leaf/blob/master/go)。 ### Leaf timer Go has a built-in implementation in its standard library: ```go func AfterFunc(d Duration, f func()) *Timer ``` AfterFunc() will wait for a duration of d then exercises f() in a separate goroutine. Leaf also implement AfterFunc(), and in this version f() will be exercised but within the same goroutine. It will prevent synchronization from happening. ```go skeleton.AfterFunc(5 * time.Second, func() { // ... }) ``` Besides, Leaf timer support [cron expressions](https://en.wikipedia.org/wiki/Cron) to support scheduled jobs like start at 9am daily or Sunday 6pm weekly. More references are at [leaf/timer](https://github.com/name5566/leaf/blob/master/timer)。 ### Leaf log Leaf support below log level: 1. Debug level: Not critical 2. Release level: Critical 3. Error level: Errors 4. Fatal level: Fatal errors Debug < Release < Error < Fatal (In priority level) For LeafServer, bin/conf/server.json is used to configure log level which will filter out the lower level log information. Fatal level log is sort of different and comes only when the game server exit. Usually it records the information when the game server is failed to start up. Set LogFlag (LeafServer conf/conf.go) to output the file name and the line number: ``` LogFlag = log.Lshortfile ``` LogFlag:[https://golang.org/pkg/log/#pkg-constants](https://golang.org/pkg/log/#pkg-constants) More references are at [leaf/log](https://github.com/name5566/leaf/blob/master/log). ### Leaf recordfile Leaf recordfile is formatted in CSV([Example](https://github.com/name5566/leaf/blob/master/recordfile/test.txt)). recordfile is to manage the configuration for game. The usage of recordfile in LeafServer is quite simple: 1. Create a CSV file under bin/gamedata 2. Call readRf() to read it in gamedata module Samples: ```go // Make sure Test.txt is located in bin/gamedata // The file name must match the name of the struct, and all characters are case sensitive. // Every instance of defined struct maps to one specific row in recordfile type Test struct { // The type of first column is int // "index" means this column will be indexed(exclusively) Id int "index" // The type of second column is an array of int with a length of 4 Arr [4]int // The type of third column is string Str string } // Load recordfile Test.txt into memory // RfTest is the object that represents Test.txt in memory var RfTest = readRf(Test{}) func init() { // Search in index // Fetch the row with id equals 1 in Test.txt r := RfTest.Index(1) if r != nil { row := r.(*Test) // Log this row log.Debug("%v %v %v", row.Id, row.Arr, row.Str) } } ``` Refer to [leaf/recordfile](https://github.com/name5566/leaf/blob/master/recordfile) for more details. Learn more ---------- More references are at Wiki [https://github.com/name5566/leaf/wiki](https://github.com/name5566/leaf/wiki) ================================================ FILE: src/github.com/dolotech/leaf/TUTORIAL_ZH.md ================================================ Leaf 游戏服务器框架简介 ================== Leaf 是一个由 Go 语言(golang)编写的开发效率和执行效率并重的开源游戏服务器框架。Leaf 适用于各类游戏服务器的开发,包括 H5(HTML5)游戏服务器。 Leaf 的关注点: * 良好的使用体验。Leaf 总是尽可能的提供简洁和易用的接口,尽可能的提升开发的效率 * 稳定性。Leaf 总是尽可能的恢复运行过程中的错误,避免崩溃 * 多核支持。Leaf 通过模块机制和 [leaf/go](https://github.com/name5566/leaf/tree/master/go) 尽可能的利用多核资源,同时又尽量避免各种副作用 * 模块机制。 Leaf 的模块机制 --------------- 一个 Leaf 开发的游戏服务器由多个模块组成(例如 [LeafServer](https://github.com/name5566/leafserver)),模块有以下特点: * 每个模块运行在一个单独的 goroutine 中 * 模块间通过一套轻量的 RPC 机制通讯([leaf/chanrpc](https://github.com/name5566/leaf/tree/master/chanrpc)) Leaf 不建议在游戏服务器中设计过多的模块。 游戏服务器在启动时进行模块的注册,例如: ```go leaf.Run( game.Module, gate.Module, login.Module, ) ``` 这里按顺序注册了 game、gate、login 三个模块。每个模块都需要实现接口: ```go type Module interface { OnInit() OnDestroy() Run(closeSig chan bool) } ``` Leaf 首先会在同一个 goroutine 中按模块注册顺序执行模块的 OnInit 方法,等到所有模块 OnInit 方法执行完成后则为每一个模块启动一个 goroutine 并执行模块的 Run 方法。最后,游戏服务器关闭时(Ctrl + C 关闭游戏服务器)将按模块注册相反顺序在同一个 goroutine 中执行模块的 OnDestroy 方法。 Leaf 源码概览 --------------- * leaf/chanrpc 提供了一套基于 channel 的 RPC 机制,用于游戏服务器模块间通讯 * leaf/db 数据库相关,目前支持 [MongoDB](https://www.mongodb.org/) * leaf/gate 网关模块,负责游戏客户端的接入 * leaf/go 用于创建能够被 Leaf 管理的 goroutine * leaf/log 日志相关 * leaf/network 网络相关,使用 TCP 和 WebSocket 协议,可自定义消息格式,默认 Leaf 提供了基于 [protobuf](https://developers.google.com/protocol-buffers) 和 JSON 的消息格式 * leaf/recordfile 用于管理游戏数据 * leaf/timer 定时器相关 * leaf/util 辅助库 使用 Leaf 开发游戏服务器 --------------- [LeafServer](https://github.com/name5566/leafserver) 是一个基于 Leaf 开发的游戏服务器,我们以 LeafServer 作为起点。 获取 LeafServer: ``` git clone https://github.com/name5566/leafserver ``` 设置 leafserver 目录到 GOPATH 环境变量后获取 Leaf: ``` go get github.com/name5566/leaf ``` 编译 LeafServer: ``` go install server ``` 如果一切顺利,运行 server 你可以获得以下输出: ``` 2015/08/26 22:11:27 [release] Leaf 1.1.2 starting up ``` 敲击 Ctrl + C 关闭游戏服务器,服务器正常关闭输出: ``` 2015/08/26 22:12:30 [release] Leaf closing down (signal: interrupt) ``` ### Hello Leaf 现在,在 LeafServer 的基础上,我们来看看游戏服务器如何接收和处理网络消息。 首先定义一个 JSON 格式的消息(protobuf 类似)。打开 LeafServer msg/msg.go 文件可以看到如下代码: ```go package msg import ( "github.com/name5566/leaf/network" ) var Processor network.Processor func init() { } ``` Processor 为消息的处理器(可由用户自定义),这里我们使用 Leaf 默认提供的 JSON 消息处理器并尝试添加一个名字为 Hello 的消息: ```go package msg import ( "github.com/name5566/leaf/network/json" ) // 使用默认的 JSON 消息处理器(默认还提供了 protobuf 消息处理器) var Processor = json.NewProcessor() func init() { // 这里我们注册了一个 JSON 消息 Hello Processor.Register(&Hello{}) } // 一个结构体定义了一个 JSON 消息的格式 // 消息名为 Hello type Hello struct { Name string } ``` 客户端发送到游戏服务器的消息需要通过 gate 模块路由,简而言之,gate 模块决定了某个消息具体交给内部的哪个模块来处理。这里,我们将 Hello 消息路由到 game 模块中。打开 LeafServer gate/router.go,敲入如下代码: ```go package gate import ( "server/game" "server/msg" ) func init() { // 这里指定消息 Hello 路由到 game 模块 // 模块间使用 ChanRPC 通讯,消息路由也不例外 msg.Processor.SetRouter(&msg.Hello{}, game.ChanRPC) } ``` 一切就绪,我们现在可以在 game 模块中处理 Hello 消息了。打开 LeafServer game/internal/handler.go,敲入如下代码: ```go package internal import ( "github.com/name5566/leaf/log" "github.com/name5566/leaf/gate" "reflect" "server/msg" ) func init() { // 向当前模块(game 模块)注册 Hello 消息的消息处理函数 handleHello handler(&msg.Hello{}, handleHello) } func handler(m interface{}, h interface{}) { skeleton.RegisterChanRPC(reflect.TypeOf(m), h) } func handleHello(args []interface{}) { // 收到的 Hello 消息 m := args[0].(*msg.Hello) // 消息的发送者 a := args[1].(gate.Agent) // 输出收到的消息的内容 log.Debug("hello %v", m.Name) // 给发送者回应一个 Hello 消息 a.WriteMsg(&msg.Hello{ Name: "client", }) } ``` 到这里,一个简单的范例就完成了。为了更加清楚的了解消息的格式,我们从 0 编写一个最简单的测试客户端。 Leaf 中,当选择使用 TCP 协议时,在网络中传输的消息都会使用以下格式: ``` -------------- | len | data | -------------- ``` 其中: 1. len 表示了 data 部分的长度(字节数)。len 本身也有长度,默认为 2 字节(可配置),len 本身的长度决定了单个消息的最大大小 2. data 部分使用 JSON 或者 protobuf 编码(也可自定义其他编码方式) 测试客户端同样使用 Go 语言编写: ```go package main import ( "encoding/binary" "net" ) func main() { conn, err := net.Dial("tcp", "127.0.0.1:3563") if err != nil { panic(err) } // Hello 消息(JSON 格式) // 对应游戏服务器 Hello 消息结构体 data := []byte(`{ "Hello": { "Name": "leaf" } }`) // len + data m := make([]byte, 2+len(data)) // 默认使用大端序 binary.BigEndian.PutUint16(m, uint16(len(data))) copy(m[2:], data) // 发送消息 conn.Write(m) } ``` 执行此测试客户端,游戏服务器输出: ``` 2015/09/25 07:41:03 [debug ] hello leaf 2015/09/25 07:41:03 [debug ] read message: read tcp 127.0.0.1:3563->127.0.0.1:54599: wsarecv: An existing connection was forcibly closed by the remote host. ``` 测试客户端发送完消息以后就退出了,此时和游戏服务器的连接断开,相应的,游戏服务器输出连接断开的提示日志(第二条日志,日志的具体内容和 Go 语言版本有关)。 除了使用 TCP 协议外,还可以选择使用 WebSocket 协议(例如开发 H5 游戏)。Leaf 可以单独使用 TCP 协议或 WebSocket 协议,也可以同时使用两者,换而言之,服务器可以同时接受 TCP 连接和 WebSocket 连接,对开发者而言消息来自 TCP 还是 WebSocket 是完全透明的。现在,我们来编写一个对应上例的使用 WebSocket 协议的客户端: ```html ``` 保存上述代码到某 HTML 文件中并使用(任意支持 WebSocket 协议的)浏览器打开。在打开此 HTML 文件前,首先需要配置一下 LeafServer 的 bin/conf/server.json 文件,增加 WebSocket 监听地址(WSAddr): ```json { "LogLevel": "debug", "LogPath": "", "TCPAddr": "127.0.0.1:3563", "WSAddr": "127.0.0.1:3653", "MaxConnNum": 20000 } ``` 重启游戏服务器后,方可接受 WebSocket 消息: ``` 2015/09/25 07:50:03 [debug ] hello leaf ``` 在 Leaf 中使用 WebSocket 需要注意的一点是:Leaf 总是发送二进制消息而非文本消息。 ### Leaf 模块详解 LeafServer 中包含了 3 个模块,它们分别是: * gate 模块,负责游戏客户端的接入 * login 模块,负责登录流程 * game 模块,负责游戏主逻辑 一般来说(而非强制规定),从代码结构上,一个 Leaf 模块: 1. 放置于一个目录中(例如 game 模块放置于 game 目录中) 2. 模块的具体实现放置于 internal 包中(例如 game 模块的具体实现放置于 game/internal 包中) 每个模块下一般有一个 external.go 的文件,顾名思义表示模块对外暴露的接口,这里以 game 模块的 external.go 文件为例: ```go package game import ( "server/game/internal" ) var ( // 实例化 game 模块 Module = new(internal.Module) // 暴露 ChanRPC ChanRPC = internal.ChanRPC ) ``` 首先,模块会被实例化,这样才能注册到 Leaf 框架中(详见 LeafServer main.go),另外,模块暴露的 ChanRPC 被用于模块间通讯。 进入 game 模块的内部(LeafServer game/internal/module.go): ```go package internal import ( "github.com/name5566/leaf/module" "server/base" ) var ( skeleton = base.NewSkeleton() ChanRPC = skeleton.ChanRPCServer ) type Module struct { *module.Skeleton } func (m *Module) OnInit() { m.Skeleton = skeleton } func (m *Module) OnDestroy() { } ``` 模块中最关键的就是 skeleton(骨架),skeleton 实现了 Module 接口的 Run 方法并提供了: * ChanRPC * goroutine * 定时器 ### Leaf ChanRPC 由于 Leaf 中,每个模块跑在独立的 goroutine 上,为了模块间方便的相互调用就有了基于 channel 的 RPC 机制。一个 ChanRPC 需要在游戏服务器初始化的时候进行注册(注册过程不是 goroutine 安全的),例如 LeafServer 中 game 模块注册了 NewAgent 和 CloseAgent 两个 ChanRPC: ```go package internal import ( "github.com/name5566/leaf/gate" ) func init() { skeleton.RegisterChanRPC("NewAgent", rpcNewAgent) skeleton.RegisterChanRPC("CloseAgent", rpcCloseAgent) } func rpcNewAgent(args []interface{}) { } func rpcCloseAgent(args []interface{}) { } ``` 使用 skeleton 来注册 ChanRPC。RegisterChanRPC 的第一个参数是 ChanRPC 的名字,第二个参数是 ChanRPC 的实现。这里的 NewAgent 和 CloseAgent 会被 LeafServer 的 gate 模块在连接建立和连接中断时调用。ChanRPC 的调用方有 3 种调用模式: 1. 同步模式,调用并等待 ChanRPC 返回 2. 异步模式,调用并提供回调函数,回调函数会在 ChanRPC 返回后被调用 3. Go 模式,调用并立即返回,忽略任何返回值和错误 gate 模块这样调用 game 模块的 NewAgent ChanRPC(这仅仅是一个示例,实际的代码细节复杂的多): ```go game.ChanRPC.Go("NewAgent", a) ``` 这里调用 NewAgent 并传递参数 a,我们在 rpcNewAgent 的参数 args[0] 中可以取到 a(args[1] 表示第二个参数,以此类推)。 更加详细的用法可以参考 [leaf/chanrpc](https://github.com/name5566/leaf/blob/master/chanrpc)。需要注意的是,无论封装多么精巧,跨 goroutine 的调用总不能像直接的函数调用那样简单直接,因此除非必要我们不要构建太多的模块,模块间不要太频繁的交互。模块在 Leaf 中被设计出来最主要是用于划分功能而非利用多核,Leaf 认为在模块内按需使用 goroutine 才是多核利用率问题的解决之道。 ### Leaf Go 善用 goroutine 能够充分利用多核资源,Leaf 提供的 Go 机制解决了原生 goroutine 存在的一些问题: * 能够恢复 goroutine 运行过程中的错误 * 游戏服务器会等待所有 goroutine 执行结束后才关闭 * 非常方便的获取 goroutine 执行的结果数据 * 在一些特殊场合保证 goroutine 按创建顺序执行 我们来看一个例子(可以在 LeafServer 的模块的 OnInit 方法中测试): ```go log.Debug("1") // 定义变量 res 接收结果 var res string skeleton.Go(func() { // 这里使用 Sleep 来模拟一个很慢的操作 time.Sleep(1 * time.Second) // 假定得到结果 res = "3" }, func() { log.Debug(res) }) log.Debug("2") ``` 上面代码执行结果如下: ```go 2015/08/27 20:37:17 [debug ] 1 2015/08/27 20:37:17 [debug ] 2 2015/08/27 20:37:18 [debug ] 3 ``` 这里的 Go 方法接收 2 个函数作为参数,第一个函数会被放置在一个新创建的 goroutine 中执行,在其执行完成之后,第二个函数会在当前 goroutine 中被执行。由此,我们可以看到变量 res 同一时刻总是只被一个 goroutine 访问,这就避免了同步机制的使用。Go 的设计使得 CPU 得到充分利用,避免操作阻塞当前 goroutine,同时又无需为共享资源同步而忧心。 更加详细的用法可以参考 [leaf/go](https://github.com/name5566/leaf/blob/master/go)。 ### Leaf timer Go 语言标准库提供了定时器的支持: ```go func AfterFunc(d Duration, f func()) *Timer ``` AfterFunc 会等待 d 时长后调用 f 函数,这里的 f 函数将在另外一个 goroutine 中执行。Leaf 提供了一个相同的 AfterFunc 函数,相比之下,f 函数在 AfterFunc 的调用 goroutine 中执行,这样就避免了同步机制的使用: ```go skeleton.AfterFunc(5 * time.Second, func() { // ... }) ``` 另外,Leaf timer 还支持 [cron 表达式](https://en.wikipedia.org/wiki/Cron),用于实现诸如“每天 9 点执行”、“每周末 6 点执行”的逻辑。 更加详细的用法可以参考 [leaf/timer](https://github.com/name5566/leaf/blob/master/timer)。 ### Leaf log Leaf 的 log 系统支持多种日志级别: 1. Debug 日志,非关键日志 2. Release 日志,关键日志 3. Error 日志,错误日志 4. Fatal 日志,致命错误日志 Debug < Release < Error < Fatal(日志级别高低) 在 LeafServer 中,bin/conf/server.json 可以配置日志级别,低于配置的日志级别的日志将不会输出。Fatal 日志比较特殊,每次输出 Fatal 日志之后游戏服务器进程就会结束,通常来说,只在游戏服务器初始化失败时使用 Fatal 日志。 我们还可以通过配置 LeafServer conf/conf.go 的 LogFlag 来在日志中输出文件名和行号: ``` LogFlag = log.Lshortfile ``` 可用的 LogFlag 见:[https://golang.org/pkg/log/#pkg-constants](https://golang.org/pkg/log/#pkg-constants) 更加详细的用法可以参考 [leaf/log](https://github.com/name5566/leaf/blob/master/log)。 ### Leaf recordfile Leaf 的 recordfile 是基于 CSV 格式(范例见[这里](https://github.com/name5566/leaf/blob/master/recordfile/test.txt))。recordfile 用于管理游戏配置数据。在 LeafServer 中使用 recordfile 非常简单: 1. 将 CSV 文件放置于 bin/gamedata 目录中 2. 在 gamedata 模块中调用函数 readRf 读取 CSV 文件 范例: ```go // 确保 bin/gamedata 目录中存在 Test.txt 文件 // 文件名必须和此结构体名称相同(大小写敏感) // 结构体的一个实例映射 recordfile 中的一行 type Test struct { // 将第一列按 int 类型解析 // "index" 表明在此列上建立唯一索引 Id int "index" // 将第二列解析为长度为 4 的整型数组 Arr [4]int // 将第三列解析为字符串 Str string } // 读取 recordfile Test.txt 到内存中 // RfTest 即为 Test.txt 的内存镜像 var RfTest = readRf(Test{}) func init() { // 按索引查找 // 获取 Test.txt 中 Id 为 1 的那一行 r := RfTest.Index(1) if r != nil { row := r.(*Test) // 输出此行的所有列的数据 log.Debug("%v %v %v", row.Id, row.Arr, row.Str) } } ``` 更加详细的用法可以参考 [leaf/recordfile](https://github.com/name5566/leaf/blob/master/recordfile)。 了解更多 --------------- 阅读 Wiki 获取更多的帮助:[https://github.com/name5566/leaf/wiki](https://github.com/name5566/leaf/wiki) ================================================ FILE: src/github.com/dolotech/leaf/chanrpc/chanrpc.go ================================================ package chanrpc import ( "errors" "fmt" "github.com/golang/glog" "reflect" "github.com/dolotech/lib/utils" ) type Server struct { functions map[interface{}]*reflect.Value ChanCall chan *CallInfo } type CallInfo struct { f *reflect.Value args []interface{} chanRet chan *RetInfo cb interface{} } type RetInfo struct { ret interface{} err error cb interface{} } type Client struct { s *Server chanSyncRet chan *RetInfo ChanAsynRet chan *RetInfo pendingAsynCall int } func NewServer(l int) *Server { s := new(Server) s.functions = make(map[interface{}]*reflect.Value) s.ChanCall = make(chan *CallInfo, l) return s } func assert(i interface{}) []interface{} { if i == nil { return nil } else { return i.([]interface{}) } } // you must call the function before calling Open and Go func (s *Server) Register(id interface{}, f interface{}) { if reflect.TypeOf(f).Kind() != reflect.Func { glog.Warning("消息处理不是函数", id) return } if _, ok := s.functions[id]; ok { return //panic(fmt.Sprintf("function id %v: already registered", id)) } v := reflect.ValueOf(f) s.functions[id] = &v } func (s *Server) ret(ci *CallInfo, ri *RetInfo) (err error) { if ci.chanRet == nil { return } defer utils.PrintPanicStack() ri.cb = ci.cb ci.chanRet <- ri return } func (s *Server) Exec(ci *CallInfo) { defer func() { if r := utils.PrintPanicStack(); r != nil { s.ret(ci, &RetInfo{err: fmt.Errorf("%v", r)}) } }() agrs := make([]reflect.Value, 0, len(ci.args)) for i := 0; i < len(ci.args); i++ { agrs = append(agrs, reflect.ValueOf(ci.args[i])) } ci.f.Call(agrs) } // goroutine safe func (s *Server) Go(id interface{}, args ...interface{}) { f, _ := s.functions[id] if f == nil { return } defer utils.PrintPanicStack() s.ChanCall <- &CallInfo{ f: f, args: args, } } // goroutine safe func (s *Server) Call0(id interface{}, args ...interface{}) error { return s.Open(0).Call0(id, args...) } // goroutine safe func (s *Server) Call1(id interface{}, args ...interface{}) (interface{}, error) { return s.Open(0).Call1(id, args...) } // goroutine safe func (s *Server) CallN(id interface{}, args ...interface{}) ([]interface{}, error) { return s.Open(0).CallN(id, args...) } func (s *Server) Close() { close(s.ChanCall) for ci := range s.ChanCall { s.ret(ci, &RetInfo{ err: errors.New("chanrpc server closed"), }) } } // goroutine safe func (s *Server) Open(l int) *Client { c := NewClient(l) c.Attach(s) return c } func NewClient(l int) *Client { c := new(Client) c.chanSyncRet = make(chan *RetInfo, 1) c.ChanAsynRet = make(chan *RetInfo, l) return c } func (c *Client) Attach(s *Server) { c.s = s } func (c *Client) call(ci *CallInfo, block bool) (err error) { defer func() { if r := utils.PrintPanicStack(); r != nil { err = r.(error) } }() if block { c.s.ChanCall <- ci } else { select { case c.s.ChanCall <- ci: default: err = errors.New("chanrpc channel full") } } return } func (c *Client) f(id interface{}, n int) (*reflect.Value, error) { if c.s == nil { return nil, errors.New("server not attached") } f := c.s.functions[id] if f == nil { return nil, fmt.Errorf("function id %v: function not registered", id) } return f, nil } func (c *Client) Call0(id interface{}, args ...interface{}) error { f, err := c.f(id, 0) if err != nil { return err } err = c.call(&CallInfo{ f: f, args: args, chanRet: c.chanSyncRet, }, true) if err != nil { return err } ri := <-c.chanSyncRet return ri.err } func (c *Client) Call1(id interface{}, args ...interface{}) (interface{}, error) { f, err := c.f(id, 1) if err != nil { return nil, err } err = c.call(&CallInfo{ f: f, args: args, chanRet: c.chanSyncRet, }, true) if err != nil { return nil, err } ri := <-c.chanSyncRet return ri.ret, ri.err } func (c *Client) CallN(id interface{}, args ...interface{}) ([]interface{}, error) { f, err := c.f(id, 2) if err != nil { return nil, err } err = c.call(&CallInfo{ f: f, args: args, chanRet: c.chanSyncRet, }, true) if err != nil { return nil, err } ri := <-c.chanSyncRet return assert(ri.ret), ri.err } func (c *Client) asynCall(id interface{}, args []interface{}, cb interface{}, n int) { f, err := c.f(id, n) if err != nil { c.ChanAsynRet <- &RetInfo{err: err, cb: cb} return } err = c.call(&CallInfo{ f: f, args: args, chanRet: c.ChanAsynRet, cb: cb, }, false) if err != nil { c.ChanAsynRet <- &RetInfo{err: err, cb: cb} return } } func (c *Client) AsynCall(id interface{}, _args ...interface{}) { if len(_args) < 1 { panic("callback function not found") } args := _args[:len(_args)-1] cb := _args[len(_args)-1] var n int switch cb.(type) { case func(error): n = 0 case func(interface{}, error): n = 1 case func([]interface{}, error): n = 2 default: panic("definition of callback function is invalid") } // too many calls if c.pendingAsynCall >= cap(c.ChanAsynRet) { execCb(&RetInfo{err: errors.New("too many calls"), cb: cb}) return } c.asynCall(id, args, cb, n) c.pendingAsynCall++ } func execCb(ri *RetInfo) { defer utils.PrintPanicStack() // execute switch ri.cb.(type) { case func(error): ri.cb.(func(error))(ri.err) case func(interface{}, error): ri.cb.(func(interface{}, error))(ri.ret, ri.err) case func([]interface{}, error): ri.cb.(func([]interface{}, error))(assert(ri.ret), ri.err) default: panic("bug") } return } func (c *Client) Cb(ri *RetInfo) { c.pendingAsynCall-- execCb(ri) } func (c *Client) Close() { for c.pendingAsynCall > 0 { c.Cb(<-c.ChanAsynRet) } } func (c *Client) Idle() bool { return c.pendingAsynCall == 0 } ================================================ FILE: src/github.com/dolotech/leaf/chanrpc/example_test.go ================================================ package chanrpc import ( "sync" "testing" ) func TestClient_AsynCall(t *testing.T) { s := NewServer(10) var wg sync.WaitGroup wg.Add(1) // goroutine 1 go func() { s.Register("f0", func(args []interface{}) { }) s.Register("f1", func(args []interface{}) interface{} { return 1 }) s.Register("fn", func(args []interface{}) []interface{} { return []interface{}{1, 2, 3} }) s.Register("add", func(args []interface{}) interface{} { n1 := args[0].(int) n2 := args[1].(int) return n1 + n2 }) wg.Done() for { s.Exec(<-s.ChanCall) } }() wg.Wait() wg.Add(1) // goroutine 2 go func() { c := s.Open(10) // sync err := c.Call0("f0") if err != nil { t.Log(err) } r1, err := c.Call1("f1") if err != nil { t.Log(err) } else { t.Log(r1) } rn, err := c.CallN("fn") if err != nil { t.Log(err) } else { t.Log(rn[0], rn[1], rn[2]) } ra, err := c.Call1("add", 1, 2) if err != nil { t.Log(err) } else { t.Log(ra) } // asyn c.AsynCall("f0", func(err error) { if err != nil { t.Log(err) } }) c.AsynCall("f1", func(ret interface{}, err error) { if err != nil { t.Log(err) } else { t.Log(ret) } }) c.AsynCall("fn", func(ret []interface{}, err error) { if err != nil { t.Log(err) } else { t.Log(ret[0], ret[1], ret[2]) } }) c.AsynCall("add", 1, 2, func(ret interface{}, err error) { if err != nil { t.Log(err) } else { t.Log(ret) } }) c.Cb(<-c.ChanAsynRet) c.Cb(<-c.ChanAsynRet) c.Cb(<-c.ChanAsynRet) c.Cb(<-c.ChanAsynRet) // go s.Go("f0") wg.Done() }() wg.Wait() // Output: // 1 // 1 2 3 // 3 // 1 // 1 2 3 // 3 } ================================================ FILE: src/github.com/dolotech/leaf/conf/conf.go ================================================ package conf var ( LenStackBuf = 4096 // console ConsolePort int ConsolePrompt string = "Leaf# " ProfilePath string // cluster ListenAddr string ConnAddrs []string PendingWriteNum int ) ================================================ FILE: src/github.com/dolotech/leaf/gate/agent.go ================================================ package gate import ( "net" ) type Agent interface { WriteMsg(msg interface{}) LocalAddr() net.Addr RemoteAddr() net.Addr Close() Destroy() UserData() interface{} SetUserData(data interface{}) } ================================================ FILE: src/github.com/dolotech/leaf/gate/gate.go ================================================ package gate import ( "github.com/dolotech/leaf/chanrpc" "github.com/golang/glog" "github.com/dolotech/leaf/network" "net" "reflect" "time" ) type Gate struct { MaxConnNum int PendingWriteNum int MaxMsgLen uint32 Processor network.Processor AgentChanRPC *chanrpc.Server // websocket WSAddr string HTTPTimeout time.Duration CertFile string KeyFile string // tcp TCPAddr string LenMsgLen int LittleEndian bool } func (gate *Gate) Run(closeSig chan bool) { var wsServer *network.WSServer if gate.WSAddr != "" { wsServer = new(network.WSServer) wsServer.Addr = gate.WSAddr wsServer.MaxConnNum = gate.MaxConnNum wsServer.PendingWriteNum = gate.PendingWriteNum wsServer.MaxMsgLen = gate.MaxMsgLen wsServer.HTTPTimeout = gate.HTTPTimeout wsServer.CertFile = gate.CertFile wsServer.KeyFile = gate.KeyFile wsServer.NewAgent = func(conn *network.WSConn) network.Agent { a := &agent{conn: conn, gate: gate} if gate.AgentChanRPC != nil { gate.AgentChanRPC.Go("NewAgent", a) } return a } } var tcpServer *network.TCPServer if gate.TCPAddr != "" { tcpServer = new(network.TCPServer) tcpServer.Addr = gate.TCPAddr tcpServer.MaxConnNum = gate.MaxConnNum tcpServer.PendingWriteNum = gate.PendingWriteNum tcpServer.LenMsgLen = gate.LenMsgLen tcpServer.MaxMsgLen = gate.MaxMsgLen tcpServer.LittleEndian = gate.LittleEndian tcpServer.NewAgent = func(conn *network.TCPConn) network.Agent { a := &agent{conn: conn, gate: gate} if gate.AgentChanRPC != nil { gate.AgentChanRPC.Go("NewAgent", a) } return a } } if wsServer != nil { wsServer.Start() } if tcpServer != nil { tcpServer.Start() } <-closeSig if wsServer != nil { wsServer.Close() } if tcpServer != nil { tcpServer.Close() } } func (gate *Gate) OnDestroy() {} type agent struct { conn network.Conn gate *Gate userData interface{} } func (a *agent) Run() { for { data, err := a.conn.ReadMsg() if err != nil { glog.Errorf("read message: %v", err) break } if a.gate.Processor != nil { msg, err := a.gate.Processor.Unmarshal(data) if err != nil { glog.Errorf("unmarshal message error: %v", err) break } err = a.gate.Processor.Route(msg, a) if err != nil { glog.Errorf("route message error: %v", err) break } } } } func (a *agent) OnClose() { if a.gate.AgentChanRPC != nil { err := a.gate.AgentChanRPC.Call0("CloseAgent", a) if err != nil { glog.Errorf("chanrpc error: %v", err) } } } func (a *agent) WriteMsg(msg interface{}) { if a.gate.Processor != nil { data, err := a.gate.Processor.Marshal(msg) if err != nil { glog.Errorf("marshal message %v error: %v", reflect.TypeOf(msg), err) return } err = a.conn.WriteMsg(data...) if err != nil { glog.Errorf("write message %v error: %v", reflect.TypeOf(msg), err) } } } func (a *agent) LocalAddr() net.Addr { return a.conn.LocalAddr() } func (a *agent) RemoteAddr() net.Addr { return a.conn.RemoteAddr() } func (a *agent) Close() { a.conn.Close() } func (a *agent) Destroy() { a.conn.Destroy() } func (a *agent) UserData() interface{} { return a.userData } func (a *agent) SetUserData(data interface{}) { a.userData = data } ================================================ FILE: src/github.com/dolotech/leaf/leaf.go ================================================ package leaf import ( "github.com/golang/glog" "github.com/dolotech/leaf/module" "os" "os/signal" ) func Run(mods ...module.Module) { glog.Errorf("Leaf %v starting up", version) // module for i := 0; i < len(mods); i++ { module.Register(mods[i]) } module.Init() // close c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, os.Kill) sig := <-c glog.Errorf("Leaf closing down (signal: %v)", sig) module.Destroy() } ================================================ FILE: src/github.com/dolotech/leaf/module/go_test.go ================================================ package module import ( "testing" "time" ) func TestSkeleton_Go(t *testing.T) { s := Skeleton{} s.Init() f := func() { <-time.After(time.Second) t.Log("ffff") } ch:= make(chan int) c := func() { <-time.After(time.Second) t.Log("ccc") ch <- 0 } s.Go(f, c) t.Log("end",<-ch) } ================================================ FILE: src/github.com/dolotech/leaf/module/module.go ================================================ package module import ( "sync" "github.com/dolotech/lib/utils" ) type Module interface { OnInit() OnDestroy() Run(closeSig chan bool) } type module struct { mi Module closeSig chan bool wg sync.WaitGroup } var mods []*module func Register(mi Module) { m := new(module) m.mi = mi m.closeSig = make(chan bool, 1) mods = append(mods, m) } func Init() { for i := 0; i < len(mods); i++ { mods[i].mi.OnInit() } for i := 0; i < len(mods); i++ { m := mods[i] m.wg.Add(1) go run(m) } } func Destroy() { for i := len(mods) - 1; i >= 0; i-- { m := mods[i] m.closeSig <- true m.wg.Wait() destroy(m) } } func run(m *module) { defer utils.PrintPanicStack() m.mi.Run(m.closeSig) m.wg.Done() } func destroy(m *module) { defer utils.PrintPanicStack() m.mi.OnDestroy() } ================================================ FILE: src/github.com/dolotech/leaf/module/skeleton.go ================================================ package module import ( "github.com/dolotech/leaf/chanrpc" "github.com/dolotech/leaf/timer" "time" "github.com/dolotech/lib/grpool" "runtime" ) type Skeleton struct { GoLen int TimerDispatcherLen int AsynCallLen int ChanRPCServer *chanrpc.Server dispatcher *timer.Dispatcher client *chanrpc.Client server *chanrpc.Server commandServer *chanrpc.Server pool *grpool.Pool } func (s *Skeleton) Init() { if s.GoLen < runtime.NumCPU()*2 { s.GoLen = runtime.NumCPU() * 4 } s.pool = grpool.NewPool(runtime.NumCPU()*2, s.GoLen) if s.TimerDispatcherLen <= 0 { s.TimerDispatcherLen = 0 } if s.AsynCallLen <= 0 { s.AsynCallLen = 0 } s.dispatcher = timer.NewDispatcher(s.TimerDispatcherLen) s.client = chanrpc.NewClient(s.AsynCallLen) s.server = s.ChanRPCServer if s.server == nil { s.server = chanrpc.NewServer(0) } s.commandServer = chanrpc.NewServer(0) } func (s *Skeleton) Run(closeSig chan bool) { for { select { case <-closeSig: s.commandServer.Close() s.server.Close() //for !s.g.Idle() || !s.client.Idle() { for !s.client.Idle() { //s.g.Close() s.client.Close() } s.pool.Release() return case ri := <-s.client.ChanAsynRet: s.client.Cb(ri) case ci := <-s.server.ChanCall: s.server.Exec(ci) case ci := <-s.commandServer.ChanCall: s.commandServer.Exec(ci) /*case cb := <-s.g.ChanCb: s.g.Cb(cb)*/ case t := <-s.dispatcher.ChanTimer: t.Cb() } } } func (s *Skeleton) AfterFunc(d time.Duration, cb func()) *timer.Timer { if s.TimerDispatcherLen == 0 { panic("invalid TimerDispatcherLen") } return s.dispatcher.AfterFunc(d, cb) } func (s *Skeleton) CronFunc(cronExpr *timer.CronExpr, cb func()) *timer.Cron { if s.TimerDispatcherLen == 0 { panic("invalid TimerDispatcherLen") } return s.dispatcher.CronFunc(cronExpr, cb) } /*func (s *Skeleton) Go(f func(), cb func()) { s.pool.JobQueue <- func() { defer func() { if nil != cb { s.pool.JobQueue <- cb } if r := recover(); r != nil { if conf.LenStackBuf > 0 { buf := make([]byte, conf.LenStackBuf) l := runtime.Stack(buf, false) glog.Errorf("%v: %s", r, buf[:l]) } else { glog.Errorf("%v", r) } } }() f() } }*/ func (s *Skeleton) AsynCall(server *chanrpc.Server, id interface{}, args ...interface{}) { if s.AsynCallLen == 0 { panic("invalid AsynCallLen") } s.client.Attach(server) s.client.AsynCall(id, args...) } func (s *Skeleton) RegisterChanRPC(id interface{}, f interface{}) { if s.ChanRPCServer == nil { panic("invalid ChanRPCServer") } s.server.Register(id, f) } ================================================ FILE: src/github.com/dolotech/leaf/network/agent.go ================================================ package network type Agent interface { Run() OnClose() } ================================================ FILE: src/github.com/dolotech/leaf/network/conn.go ================================================ package network import ( "net" ) type Conn interface { ReadMsg() ([]byte, error) WriteMsg(args ...[]byte) error LocalAddr() net.Addr RemoteAddr() net.Addr Close() Destroy() } ================================================ FILE: src/github.com/dolotech/leaf/network/json/json.go ================================================ package json import ( "encoding/json" "errors" "fmt" "github.com/dolotech/leaf/chanrpc" "github.com/golang/glog" "reflect" ) type Processor struct { msgInfo map[string]*MsgInfo } type MsgInfo struct { msgType reflect.Type msgRouter *chanrpc.Server msgHandler *reflect.Value msgRawHandler MsgHandler } type MsgHandler func([]interface{}) type MsgRaw struct { msgID string msgRawData json.RawMessage } func NewProcessor() *Processor { p := new(Processor) p.msgInfo = make(map[string]*MsgInfo) return p } // It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) Register(msg interface{}) string { msgType := reflect.TypeOf(msg) if msgType == nil || msgType.Kind() != reflect.Ptr { glog.Fatal("json message pointer required") } msgID := msgType.Elem().Name() if msgID == "" { glog.Fatal("unnamed json message") } if _, ok := p.msgInfo[msgID]; ok { glog.Fatal("message %v is already registered", msgID) } i := new(MsgInfo) i.msgType = msgType p.msgInfo[msgID] = i return msgID } // It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) SetRouter(msg interface{}, msgRouter *chanrpc.Server) { msgType := reflect.TypeOf(msg) if msgType == nil || msgType.Kind() != reflect.Ptr { glog.Fatal("json message pointer required") } msgID := msgType.Elem().Name() i, ok := p.msgInfo[msgID] if !ok { glog.Fatal("message %v not registered", msgID) } i.msgRouter = msgRouter } // It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) SetHandler(msg interface{}, msgHandler interface{}) { msgType := reflect.TypeOf(msg) if msgType == nil || msgType.Kind() != reflect.Ptr { glog.Fatal("json message pointer required") } msgID := msgType.Elem().Name() i, ok := p.msgInfo[msgID] if !ok { glog.Fatal("message %v not registered", msgID) } v:=reflect.ValueOf(msgHandler) i.msgHandler = &v } // It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) SetRawHandler(msgID string, msgRawHandler MsgHandler) { i, ok := p.msgInfo[msgID] if !ok { glog.Fatal("message %v not registered", msgID) } i.msgRawHandler = msgRawHandler } // goroutine safe func (p *Processor) Route(msg, userData interface{}) error { // raw if msgRaw, ok := msg.(MsgRaw); ok { i, ok := p.msgInfo[msgRaw.msgID] if !ok { return fmt.Errorf("message %v not registered", msgRaw.msgID) } if i.msgRawHandler != nil { i.msgRawHandler([]interface{}{msgRaw.msgID, msgRaw.msgRawData, userData}) } glog.Infoln(msg) return nil } // json msgType := reflect.TypeOf(msg) if msgType == nil || msgType.Kind() != reflect.Ptr { return errors.New("json message pointer required") } msgID := msgType.Elem().Name() i, ok := p.msgInfo[msgID] if !ok { return fmt.Errorf("message %v not registered", msgID) } if i.msgHandler != nil { i.msgHandler.Call([]reflect.Value{reflect.ValueOf(msg), reflect.ValueOf(userData)}) } if i.msgRouter != nil { i.msgRouter.Go(msgType, msg, userData) } return nil } // goroutine safe func (p *Processor) Unmarshal(data []byte) (interface{}, error) { if len(data) == 0 { return nil, errors.New("json data len == 0") } var m map[string]json.RawMessage err := json.Unmarshal(data, &m) if err != nil { return nil, err } if len(m) != 1 { return nil, errors.New("invalid json data") } for msgID, data := range m { i, ok := p.msgInfo[msgID] if !ok { return nil, fmt.Errorf("message %v not registered", msgID) } // msg if i.msgRawHandler != nil { return MsgRaw{msgID, data}, nil } else { msg := reflect.New(i.msgType.Elem()).Interface() return msg, json.Unmarshal(data, msg) } } return nil, errors.New("invalid json data") } // goroutine safe func (p *Processor) Marshal(msg interface{}) ([][]byte, error) { msgType := reflect.TypeOf(msg) if msgType == nil || msgType.Kind() != reflect.Ptr { return nil, errors.New("json message pointer required") } msgID := msgType.Elem().Name() if _, ok := p.msgInfo[msgID]; !ok { return nil, fmt.Errorf("message %v not registered", msgID) } // data m := map[string]interface{}{msgID: msg} data, err := json.Marshal(m) return [][]byte{data}, err } ================================================ FILE: src/github.com/dolotech/leaf/network/processor.go ================================================ package network type Processor interface { // must goroutine safe Route(msg , userData interface{}) error // must goroutine safe Unmarshal(data []byte) (interface{}, error) // must goroutine safe Marshal(msg interface{}) ([][]byte, error) } ================================================ FILE: src/github.com/dolotech/leaf/network/protobuf/protobuf.go ================================================ package protobuf import ( "encoding/binary" "errors" "fmt" "github.com/golang/protobuf/proto" "github.com/dolotech/leaf/chanrpc" "github.com/golang/glog" "math" "reflect" ) // ------------------------- // | id | protobuf message | // ------------------------- type Processor struct { littleEndian bool msgInfo []*MsgInfo msgID map[reflect.Type]uint16 } type MsgInfo struct { msgType reflect.Type msgRouter *chanrpc.Server msgHandler *reflect.Value msgRawHandler MsgHandler } type MsgHandler func([]interface{}) type MsgRaw struct { msgID uint16 msgRawData []byte } func NewProcessor() *Processor { p := new(Processor) p.littleEndian = false p.msgID = make(map[reflect.Type]uint16) return p } // It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) SetByteOrder(littleEndian bool) { p.littleEndian = littleEndian } // It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) Register(msg interface{}) uint16 { msgType := reflect.TypeOf(msg) if msgType == nil || msgType.Kind() != reflect.Ptr { glog.Fatal("protobuf message pointer required") } if _, ok := p.msgID[msgType]; ok { glog.Fatal("message %s is already registered", msgType) } if len(p.msgInfo) >= math.MaxUint16 { glog.Fatal("too many protobuf messages (max = %v)", math.MaxUint16) } i := new(MsgInfo) i.msgType = msgType p.msgInfo = append(p.msgInfo, i) id := uint16(len(p.msgInfo) - 1) p.msgID[msgType] = id return id } // It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) SetRouter(msg interface{}, msgRouter *chanrpc.Server) { msgType := reflect.TypeOf(msg) id, ok := p.msgID[msgType] if !ok { glog.Fatal("message %s not registered", msgType) } p.msgInfo[id].msgRouter = msgRouter } // It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) SetHandler(msg , msgHandler interface{}) { msgType := reflect.TypeOf(msg) id, ok := p.msgID[msgType] if !ok { glog.Fatal("message %s not registered", msgType) } v:=reflect.ValueOf(msgHandler) p.msgInfo[id].msgHandler = &v } // It's dangerous to call the method on routing or marshaling (unmarshaling) func (p *Processor) SetRawHandler(id uint16, msgRawHandler MsgHandler) { if id >= uint16(len(p.msgInfo)) { glog.Fatal("message id %v not registered", id) } p.msgInfo[id].msgRawHandler = msgRawHandler } // goroutine safe func (p *Processor) Route(msg , userData interface{}) error { // raw if msgRaw, ok := msg.(MsgRaw); ok { if msgRaw.msgID >= uint16(len(p.msgInfo)) { return fmt.Errorf("message id %v not registered", msgRaw.msgID) } i := p.msgInfo[msgRaw.msgID] if i.msgRawHandler != nil { i.msgRawHandler([]interface{}{msgRaw.msgID, msgRaw.msgRawData, userData}) } return nil } // protobuf msgType := reflect.TypeOf(msg) id, ok := p.msgID[msgType] if !ok { return fmt.Errorf("message %s not registered", msgType) } i := p.msgInfo[id] if i.msgHandler != nil { //i.msgHandler([]interface{}{msg, userData}) i.msgHandler.Call([]reflect.Value{reflect.ValueOf(msg), reflect.ValueOf(userData)}) } if i.msgRouter != nil { i.msgRouter.Go(msgType, msg, userData) } return nil } // goroutine safe func (p *Processor) Unmarshal(data []byte) (interface{}, error) { if len(data) < 2 { return nil, errors.New("protobuf data too short") } // id var id uint16 if p.littleEndian { id = binary.LittleEndian.Uint16(data) } else { id = binary.BigEndian.Uint16(data) } if id >= uint16(len(p.msgInfo)) { return nil, fmt.Errorf("message id %v not registered", id) } // msg i := p.msgInfo[id] if i.msgRawHandler != nil { return MsgRaw{id, data[2:]}, nil } else { msg := reflect.New(i.msgType.Elem()).Interface() return msg, proto.UnmarshalMerge(data[2:], msg.(proto.Message)) } } // goroutine safe func (p *Processor) Marshal(msg interface{}) ([][]byte, error) { msgType := reflect.TypeOf(msg) // id _id, ok := p.msgID[msgType] if !ok { err := fmt.Errorf("message %s not registered", msgType) return nil, err } id := make([]byte, 2) if p.littleEndian { binary.LittleEndian.PutUint16(id, _id) } else { binary.BigEndian.PutUint16(id, _id) } // data data, err := proto.Marshal(msg.(proto.Message)) return [][]byte{id, data}, err } // goroutine safe func (p *Processor) Range(f func(id uint16, t reflect.Type)) { for id, i := range p.msgInfo { f(uint16(id), i.msgType) } } ================================================ FILE: src/github.com/dolotech/leaf/network/tcp_client.go ================================================ package network import ( "github.com/golang/glog" "net" "sync" "time" ) type TCPClient struct { sync.Mutex Addr string ConnNum int ConnectInterval time.Duration PendingWriteNum int AutoReconnect bool NewAgent func(*TCPConn) Agent conns ConnSet wg sync.WaitGroup closeFlag bool // msg parser LenMsgLen int MinMsgLen uint32 MaxMsgLen uint32 LittleEndian bool msgParser *MsgParser } func (client *TCPClient) Start() { client.init() for i := 0; i < client.ConnNum; i++ { client.wg.Add(1) go client.connect() } } func (client *TCPClient) init() { client.Lock() defer client.Unlock() if client.ConnNum <= 0 { client.ConnNum = 1 glog.Errorf("invalid ConnNum, reset to %v", client.ConnNum) } if client.ConnectInterval <= 0 { client.ConnectInterval = 3 * time.Second glog.Errorf("invalid ConnectInterval, reset to %v", client.ConnectInterval) } if client.PendingWriteNum <= 0 { client.PendingWriteNum = 100 glog.Errorf("invalid PendingWriteNum, reset to %v", client.PendingWriteNum) } if client.NewAgent == nil { glog.Fatal("NewAgent must not be nil") } if client.conns != nil { glog.Fatal("client is running") } client.conns = make(ConnSet) client.closeFlag = false // msg parser msgParser := NewMsgParser() msgParser.SetMsgLen(client.LenMsgLen, client.MinMsgLen, client.MaxMsgLen) msgParser.SetByteOrder(client.LittleEndian) client.msgParser = msgParser } func (client *TCPClient) dial() net.Conn { for { conn, err := net.Dial("tcp", client.Addr) if err == nil || client.closeFlag { return conn } glog.Errorf("connect to %v error: %v", client.Addr, err) time.Sleep(client.ConnectInterval) continue } } func (client *TCPClient) connect() { defer client.wg.Done() reconnect: conn := client.dial() if conn == nil { return } client.Lock() if client.closeFlag { client.Unlock() conn.Close() return } client.conns[conn] = struct{}{} client.Unlock() tcpConn := newTCPConn(conn, client.PendingWriteNum, client.msgParser) agent := client.NewAgent(tcpConn) agent.Run() // cleanup tcpConn.Close() client.Lock() delete(client.conns, conn) client.Unlock() agent.OnClose() if client.AutoReconnect { time.Sleep(client.ConnectInterval) goto reconnect } } func (client *TCPClient) Close() { client.Lock() client.closeFlag = true for conn := range client.conns { conn.Close() } client.conns = nil client.Unlock() client.wg.Wait() } ================================================ FILE: src/github.com/dolotech/leaf/network/tcp_conn.go ================================================ package network import ( "github.com/golang/glog" "net" "sync" ) type ConnSet map[net.Conn]struct{} type TCPConn struct { sync.Mutex conn net.Conn writeChan chan []byte closeFlag bool msgParser *MsgParser } func newTCPConn(conn net.Conn, pendingWriteNum int, msgParser *MsgParser) *TCPConn { tcpConn := new(TCPConn) tcpConn.conn = conn tcpConn.writeChan = make(chan []byte, pendingWriteNum) tcpConn.msgParser = msgParser go func() { for b := range tcpConn.writeChan { if b == nil { break } _, err := conn.Write(b) if err != nil { break } } conn.Close() tcpConn.Lock() tcpConn.closeFlag = true tcpConn.Unlock() }() return tcpConn } func (tcpConn *TCPConn) doDestroy() { tcpConn.conn.(*net.TCPConn).SetLinger(0) tcpConn.conn.Close() if !tcpConn.closeFlag { close(tcpConn.writeChan) tcpConn.closeFlag = true } } func (tcpConn *TCPConn) Destroy() { tcpConn.Lock() defer tcpConn.Unlock() tcpConn.doDestroy() } func (tcpConn *TCPConn) Close() { tcpConn.Lock() defer tcpConn.Unlock() if tcpConn.closeFlag { return } tcpConn.doWrite(nil) tcpConn.closeFlag = true } func (tcpConn *TCPConn) doWrite(b []byte) { if len(tcpConn.writeChan) == cap(tcpConn.writeChan) { glog.Error("close conn: channel full") tcpConn.doDestroy() return } tcpConn.writeChan <- b } // b must not be modified by the others goroutines func (tcpConn *TCPConn) Write(b []byte) { tcpConn.Lock() defer tcpConn.Unlock() if tcpConn.closeFlag || b == nil { return } tcpConn.doWrite(b) } func (tcpConn *TCPConn) Read(b []byte) (int, error) { return tcpConn.conn.Read(b) } func (tcpConn *TCPConn) LocalAddr() net.Addr { return tcpConn.conn.LocalAddr() } func (tcpConn *TCPConn) RemoteAddr() net.Addr { return tcpConn.conn.RemoteAddr() } func (tcpConn *TCPConn) ReadMsg() ([]byte, error) { return tcpConn.msgParser.Read(tcpConn) } func (tcpConn *TCPConn) WriteMsg(args ...[]byte) error { return tcpConn.msgParser.Write(tcpConn, args...) } ================================================ FILE: src/github.com/dolotech/leaf/network/tcp_msg.go ================================================ package network import ( "encoding/binary" "errors" "io" "math" ) // -------------- // | len | data | // -------------- type MsgParser struct { lenMsgLen int minMsgLen uint32 maxMsgLen uint32 littleEndian bool } func NewMsgParser() *MsgParser { p := new(MsgParser) p.lenMsgLen = 2 p.minMsgLen = 1 p.maxMsgLen = 4096 p.littleEndian = false return p } // It's dangerous to call the method on reading or writing func (p *MsgParser) SetMsgLen(lenMsgLen int, minMsgLen uint32, maxMsgLen uint32) { if lenMsgLen == 1 || lenMsgLen == 2 || lenMsgLen == 4 { p.lenMsgLen = lenMsgLen } if minMsgLen != 0 { p.minMsgLen = minMsgLen } if maxMsgLen != 0 { p.maxMsgLen = maxMsgLen } var max uint32 switch p.lenMsgLen { case 1: max = math.MaxUint8 case 2: max = math.MaxUint16 case 4: max = math.MaxUint32 } if p.minMsgLen > max { p.minMsgLen = max } if p.maxMsgLen > max { p.maxMsgLen = max } } // It's dangerous to call the method on reading or writing func (p *MsgParser) SetByteOrder(littleEndian bool) { p.littleEndian = littleEndian } // goroutine safe func (p *MsgParser) Read(conn *TCPConn) ([]byte, error) { var b [4]byte bufMsgLen := b[:p.lenMsgLen] // read len if _, err := io.ReadFull(conn, bufMsgLen); err != nil { return nil, err } // parse len var msgLen uint32 switch p.lenMsgLen { case 1: msgLen = uint32(bufMsgLen[0]) case 2: if p.littleEndian { msgLen = uint32(binary.LittleEndian.Uint16(bufMsgLen)) } else { msgLen = uint32(binary.BigEndian.Uint16(bufMsgLen)) } case 4: if p.littleEndian { msgLen = binary.LittleEndian.Uint32(bufMsgLen) } else { msgLen = binary.BigEndian.Uint32(bufMsgLen) } } // check len if msgLen > p.maxMsgLen { return nil, errors.New("message too long") } else if msgLen < p.minMsgLen { return nil, errors.New("message too short") } // data msgData := make([]byte, msgLen) if _, err := io.ReadFull(conn, msgData); err != nil { return nil, err } return msgData, nil } // goroutine safe func (p *MsgParser) Write(conn *TCPConn, args ...[]byte) error { // get len var msgLen uint32 for i := 0; i < len(args); i++ { msgLen += uint32(len(args[i])) } // check len if msgLen > p.maxMsgLen { return errors.New("message too long") } else if msgLen < p.minMsgLen { return errors.New("message too short") } msg := make([]byte, uint32(p.lenMsgLen)+msgLen) // write len switch p.lenMsgLen { case 1: msg[0] = byte(msgLen) case 2: if p.littleEndian { binary.LittleEndian.PutUint16(msg, uint16(msgLen)) } else { binary.BigEndian.PutUint16(msg, uint16(msgLen)) } case 4: if p.littleEndian { binary.LittleEndian.PutUint32(msg, msgLen) } else { binary.BigEndian.PutUint32(msg, msgLen) } } // write data l := p.lenMsgLen for i := 0; i < len(args); i++ { copy(msg[l:], args[i]) l += len(args[i]) } conn.Write(msg) return nil } ================================================ FILE: src/github.com/dolotech/leaf/network/tcp_server.go ================================================ package network import ( "github.com/golang/glog" "net" "sync" "time" ) type TCPServer struct { Addr string MaxConnNum int PendingWriteNum int NewAgent func(*TCPConn) Agent ln net.Listener conns ConnSet mutexConns sync.Mutex wgLn sync.WaitGroup wgConns sync.WaitGroup // msg parser LenMsgLen int MinMsgLen uint32 MaxMsgLen uint32 LittleEndian bool msgParser *MsgParser } func (server *TCPServer) Start() { server.init() go server.run() } func (server *TCPServer) init() { ln, err := net.Listen("tcp", server.Addr) if err != nil { glog.Fatal("%v", err) } if server.MaxConnNum <= 0 { server.MaxConnNum = 100 glog.Errorf("invalid MaxConnNum, reset to %v", server.MaxConnNum) } if server.PendingWriteNum <= 0 { server.PendingWriteNum = 100 glog.Errorf("invalid PendingWriteNum, reset to %v", server.PendingWriteNum) } if server.NewAgent == nil { glog.Fatal("NewAgent must not be nil") } server.ln = ln server.conns = make(ConnSet) // msg parser msgParser := NewMsgParser() msgParser.SetMsgLen(server.LenMsgLen, server.MinMsgLen, server.MaxMsgLen) msgParser.SetByteOrder(server.LittleEndian) server.msgParser = msgParser } func (server *TCPServer) run() { server.wgLn.Add(1) defer server.wgLn.Done() var tempDelay time.Duration for { conn, err := server.ln.Accept() if err != nil { if ne, ok := err.(net.Error); ok && ne.Temporary() { if tempDelay == 0 { tempDelay = 5 * time.Millisecond } else { tempDelay *= 2 } if max := 1 * time.Second; tempDelay > max { tempDelay = max } glog.Errorf("accept error: %v; retrying in %v", err, tempDelay) time.Sleep(tempDelay) continue } return } tempDelay = 0 server.mutexConns.Lock() if len(server.conns) >= server.MaxConnNum { server.mutexConns.Unlock() conn.Close() glog.Errorf("too many connections") continue } server.conns[conn] = struct{}{} server.mutexConns.Unlock() server.wgConns.Add(1) tcpConn := newTCPConn(conn, server.PendingWriteNum, server.msgParser) agent := server.NewAgent(tcpConn) go func() { agent.Run() // cleanup tcpConn.Close() server.mutexConns.Lock() delete(server.conns, conn) server.mutexConns.Unlock() agent.OnClose() server.wgConns.Done() }() } } func (server *TCPServer) Close() { server.ln.Close() server.wgLn.Wait() server.mutexConns.Lock() for conn := range server.conns { conn.Close() } server.conns = nil server.mutexConns.Unlock() server.wgConns.Wait() } ================================================ FILE: src/github.com/dolotech/leaf/network/ws_client.go ================================================ package network import ( "github.com/gorilla/websocket" "github.com/golang/glog" "sync" "time" ) type WSClient struct { sync.Mutex Addr string ConnNum int ConnectInterval time.Duration PendingWriteNum int MaxMsgLen uint32 HandshakeTimeout time.Duration AutoReconnect bool NewAgent func(*WSConn) Agent dialer websocket.Dialer conns WebsocketConnSet wg sync.WaitGroup closeFlag bool } func (client *WSClient) Start() { client.init() for i := 0; i < client.ConnNum; i++ { client.wg.Add(1) go client.connect() } } func (client *WSClient) init() { client.Lock() defer client.Unlock() if client.ConnNum <= 0 { client.ConnNum = 1 glog.Errorf("invalid ConnNum, reset to %v", client.ConnNum) } if client.ConnectInterval <= 0 { client.ConnectInterval = 3 * time.Second glog.Errorf("invalid ConnectInterval, reset to %v", client.ConnectInterval) } if client.PendingWriteNum <= 0 { client.PendingWriteNum = 100 glog.Errorf("invalid PendingWriteNum, reset to %v", client.PendingWriteNum) } if client.MaxMsgLen <= 0 { client.MaxMsgLen = 4096 glog.Errorf("invalid MaxMsgLen, reset to %v", client.MaxMsgLen) } if client.HandshakeTimeout <= 0 { client.HandshakeTimeout = 10 * time.Second glog.Errorf("invalid HandshakeTimeout, reset to %v", client.HandshakeTimeout) } if client.NewAgent == nil { glog.Fatal("NewAgent must not be nil") } if client.conns != nil { glog.Fatal("client is running") } client.conns = make(WebsocketConnSet) client.closeFlag = false client.dialer = websocket.Dialer{ HandshakeTimeout: client.HandshakeTimeout, } } func (client *WSClient) dial() *websocket.Conn { for { conn, _, err := client.dialer.Dial(client.Addr, nil) if err == nil || client.closeFlag { return conn } glog.Errorf("connect to %v error: %v", client.Addr, err) time.Sleep(client.ConnectInterval) continue } } func (client *WSClient) connect() { defer client.wg.Done() reconnect: conn := client.dial() if conn == nil { return } conn.SetReadLimit(int64(client.MaxMsgLen)) client.Lock() if client.closeFlag { client.Unlock() conn.Close() return } client.conns[conn] = struct{}{} client.Unlock() wsConn := newWSConn(conn, client.PendingWriteNum, client.MaxMsgLen) agent := client.NewAgent(wsConn) agent.Run() // cleanup wsConn.Close() client.Lock() delete(client.conns, conn) client.Unlock() agent.OnClose() if client.AutoReconnect { time.Sleep(client.ConnectInterval) goto reconnect } } func (client *WSClient) Close() { client.Lock() client.closeFlag = true for conn := range client.conns { conn.Close() } client.conns = nil client.Unlock() client.wg.Wait() } ================================================ FILE: src/github.com/dolotech/leaf/network/ws_conn.go ================================================ package network import ( "errors" "github.com/gorilla/websocket" "github.com/golang/glog" "net" "sync" ) type WebsocketConnSet map[*websocket.Conn]struct{} type WSConn struct { sync.Mutex conn *websocket.Conn writeChan chan []byte maxMsgLen uint32 closeFlag bool } func newWSConn(conn *websocket.Conn, pendingWriteNum int, maxMsgLen uint32) *WSConn { wsConn := new(WSConn) wsConn.conn = conn wsConn.writeChan = make(chan []byte, pendingWriteNum) wsConn.maxMsgLen = maxMsgLen go func() { for b := range wsConn.writeChan { if b == nil { break } err := conn.WriteMessage(websocket.BinaryMessage, b) if err != nil { break } } conn.Close() wsConn.Lock() wsConn.closeFlag = true wsConn.Unlock() }() return wsConn } func (wsConn *WSConn) doDestroy() { wsConn.conn.UnderlyingConn().(*net.TCPConn).SetLinger(0) wsConn.conn.Close() if !wsConn.closeFlag { close(wsConn.writeChan) wsConn.closeFlag = true } } func (wsConn *WSConn) Destroy() { wsConn.Lock() defer wsConn.Unlock() wsConn.doDestroy() } func (wsConn *WSConn) Close() { wsConn.Lock() defer wsConn.Unlock() if wsConn.closeFlag { return } wsConn.doWrite(nil) wsConn.closeFlag = true } func (wsConn *WSConn) doWrite(b []byte) { if len(wsConn.writeChan) == cap(wsConn.writeChan) { glog.Error("close conn: channel full") wsConn.doDestroy() return } wsConn.writeChan <- b } func (wsConn *WSConn) LocalAddr() net.Addr { return wsConn.conn.LocalAddr() } func (wsConn *WSConn) RemoteAddr() net.Addr { return wsConn.conn.RemoteAddr() } // goroutine not safe func (wsConn *WSConn) ReadMsg() ([]byte, error) { _, b, err := wsConn.conn.ReadMessage() return b, err } // args must not be modified by the others goroutines func (wsConn *WSConn) WriteMsg(args ...[]byte) error { wsConn.Lock() defer wsConn.Unlock() if wsConn.closeFlag { return nil } // get len var msgLen uint32 for i := 0; i < len(args); i++ { msgLen += uint32(len(args[i])) } // check len if msgLen > wsConn.maxMsgLen { return errors.New("message too long") } else if msgLen < 1 { return errors.New("message too short") } // don't copy if len(args) == 1 { wsConn.doWrite(args[0]) return nil } // merge the args msg := make([]byte, msgLen) l := 0 for i := 0; i < len(args); i++ { copy(msg[l:], args[i]) l += len(args[i]) } wsConn.doWrite(msg) return nil } ================================================ FILE: src/github.com/dolotech/leaf/network/ws_server.go ================================================ package network import ( "crypto/tls" "github.com/gorilla/websocket" "github.com/golang/glog" "net" "net/http" "sync" "time" ) type WSServer struct { Addr string MaxConnNum int PendingWriteNum int MaxMsgLen uint32 HTTPTimeout time.Duration CertFile string KeyFile string NewAgent func(*WSConn) Agent ln net.Listener handler *WSHandler } type WSHandler struct { maxConnNum int pendingWriteNum int maxMsgLen uint32 newAgent func(*WSConn) Agent upgrader websocket.Upgrader conns WebsocketConnSet mutexConns sync.Mutex wg sync.WaitGroup } func (handler *WSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, "Method not allowed", 405) return } conn, err := handler.upgrader.Upgrade(w, r, nil) if err != nil { glog.Errorf("upgrade error: %v", err) return } conn.SetReadLimit(int64(handler.maxMsgLen)) handler.wg.Add(1) defer handler.wg.Done() handler.mutexConns.Lock() if handler.conns == nil { handler.mutexConns.Unlock() conn.Close() return } if len(handler.conns) >= handler.maxConnNum { handler.mutexConns.Unlock() conn.Close() glog.Error("too many connections") return } handler.conns[conn] = struct{}{} handler.mutexConns.Unlock() wsConn := newWSConn(conn, handler.pendingWriteNum, handler.maxMsgLen) agent := handler.newAgent(wsConn) agent.Run() // cleanup wsConn.Close() handler.mutexConns.Lock() delete(handler.conns, conn) handler.mutexConns.Unlock() agent.OnClose() } func (server *WSServer) Start() { ln, err := net.Listen("tcp", server.Addr) if err != nil { glog.Fatalf("%v", err) } if server.MaxConnNum <= 0 { server.MaxConnNum = 100 glog.Errorf("invalid MaxConnNum, reset to %v", server.MaxConnNum) } if server.PendingWriteNum <= 0 { server.PendingWriteNum = 100 glog.Errorf("invalid PendingWriteNum, reset to %v", server.PendingWriteNum) } if server.MaxMsgLen <= 0 { server.MaxMsgLen = 4096 glog.Errorf("invalid MaxMsgLen, reset to %v", server.MaxMsgLen) } if server.HTTPTimeout <= 0 { server.HTTPTimeout = 10 * time.Second glog.Errorf("invalid HTTPTimeout, reset to %v", server.HTTPTimeout) } if server.NewAgent == nil { glog.Fatal("NewAgent must not be nil") } if server.CertFile != "" || server.KeyFile != "" { config := &tls.Config{} config.NextProtos = []string{"http/1.1"} var err error config.Certificates = make([]tls.Certificate, 1) config.Certificates[0], err = tls.LoadX509KeyPair(server.CertFile, server.KeyFile) if err != nil { glog.Fatalf("%v", err) } ln = tls.NewListener(ln, config) } server.ln = ln server.handler = &WSHandler{ maxConnNum: server.MaxConnNum, pendingWriteNum: server.PendingWriteNum, maxMsgLen: server.MaxMsgLen, newAgent: server.NewAgent, conns: make(WebsocketConnSet), upgrader: websocket.Upgrader{ HandshakeTimeout: server.HTTPTimeout, CheckOrigin: func(_ *http.Request) bool { return true }, }, } httpServer := &http.Server{ Addr: server.Addr, Handler: server.handler, ReadTimeout: server.HTTPTimeout, WriteTimeout: server.HTTPTimeout, MaxHeaderBytes: 1024, } go httpServer.Serve(ln) } func (server *WSServer) Close() { server.ln.Close() server.handler.mutexConns.Lock() for conn := range server.handler.conns { conn.Close() } server.handler.conns = nil server.handler.mutexConns.Unlock() server.handler.wg.Wait() } ================================================ FILE: src/github.com/dolotech/leaf/room/interface.go ================================================ package room type IOccupant interface { GetRoom() IRoom WriteMsg(msg interface{}) } type ICreator interface { Create(interface{}) IRoom } type IRoom interface { Cap() uint8 Len() uint8 GetNumber() string SetNumber(string) Data() interface{} SetData(interface{}) Close(room IRoom) Closed() chan struct{} Send(IOccupant, interface{}) error WriteMsg(interface{}, ...uint32) Regist(interface{}, interface{}) Info(args ...interface{}) Infof(format string, args ...interface{}) Error(args ...interface{}) Errorf(format string, args ...interface{}) } ================================================ FILE: src/github.com/dolotech/leaf/room/msg_loop.go ================================================ package room import ( "github.com/dolotech/lib/utils" "server/protocol" "errors" "github.com/dolotech/lib/route" "github.com/golang/glog" "github.com/davecgh/go-spew/spew" ) type MsgLoop struct { closedBroadcastChan chan struct{} closeChan chan IRoom msgChan chan *msgObj route.Route } func NewMsgLoop() *MsgLoop { m := &MsgLoop{ closeChan: make(chan IRoom, 1), closedBroadcastChan: make(chan struct{}), msgChan: make(chan *msgObj, 128), } go m.msgLoop() return m } func (r *MsgLoop) Closed() chan struct{} { return r.closedBroadcastChan } func (r *MsgLoop) msgLoop() { defer func() { if err := utils.PrintPanicStack(); err != nil { go r.msgLoop() } }() for { select { case m := <-r.closeChan: close(r.closedBroadcastChan) DelRoom(m.(IRoom)) return case m := <-r.msgChan: r.Emit(m.msg, m.o) } } } func (r *MsgLoop) Close(m IRoom) { select { case r.closeChan <- m: default: } } type msgObj struct { msg interface{} o IOccupant } func (r *MsgLoop) Send(o IOccupant, m interface{}) error { select { case r.msgChan <- &msgObj{m, o}: default: o.WriteMsg(protocol.MSG_ROOM_CLOSED) } return errors.New("room closed") } type Log struct { room IRoom } func NewLog(room IRoom) *Log { return &Log{room: room} } func (r *Log) Info(args ...interface{}) { glog.InfoDepth(1, r.parseLog(args)...) } func (r *Log) Infof(format string, args ...interface{}) { glog.InfofDepth(1, format, r.parseLog(args)...) } func (r *Log) Error(args ...interface{}) { glog.ErrorDepth(1, r.parseLog(args)...) } func (r *Log) Debug(args ...interface{}) { for k, v := range args { args[k] = spew.Sdump(v) } glog.InfoDepth(1, r.parseLog(args)...) } func (r *Log) Debugf(format string, args ...interface{}) { for k, v := range args { args[k] = spew.Sdump(v) } glog.InfofDepth(1, format, r.parseLog(args)...) } func (r *Log) Errorf(format string, args ...interface{}) { glog.ErrorfDepth(1, format, r.parseLog(args)...) } func (r *Log) parseLog(args ...interface{}) []interface{} { param := make([]interface{}, len(args)+4) param[0] = r.room.GetNumber() param[1] = r.room.Cap() param[2] = r.room.Len() param[3] = r.room.Data() copy(param[4:], args) return param } ================================================ FILE: src/github.com/dolotech/leaf/room/room_list.go ================================================ package room import ( "sync" "time" "strconv" "math/rand" "server/protocol" "github.com/dolotech/leaf/gate" ) func OnMessage(m interface{}, a gate.Agent) { o := a.UserData().(IOccupant) if o.GetRoom() != nil { o.GetRoom().Send(o, m) } else { if r := hand.Create(m); r == nil { a.WriteMsg(protocol.MSG_NOT_IN_ROOM) } else { SetRoom(r) r.Send(o, m) } } } var rooms *roomlist var hand ICreator func init() { rooms = &roomlist{ M: make(map[string]IRoom, 1000), } } func Init(h ICreator) { hand = h } type roomlist struct { M map[string]IRoom sync.RWMutex } func FindRoom() IRoom { rooms.Lock() for _, v := range rooms.M { if v.Len() < v.Cap() { return v } } rooms.Unlock() return nil } func GetRoom(rid string) IRoom { rooms.RLock() r := rooms.M[rid] rooms.RUnlock() return r } func SetRoom(room IRoom) string { rooms.Lock() id := rooms.createNumber() room.SetNumber(id) rooms.M[id] = room rooms.Unlock() return id } func DelRoom(room IRoom) { rooms.Lock() delete(rooms.M, room.GetNumber()) rooms.Unlock() } func (this *roomlist) createNumber() string { r := rand.New(rand.NewSource(time.Now().UnixNano())) var n string for i := 0; i < 100; i++ { n = strconv.Itoa(int(r.Int31n(999999-100000) + 100000)) if _, ok := rooms.M[n]; !ok { return n } } return n } func Each(f func(o IRoom) bool) { rooms.RLock() for _, v := range rooms.M { if !f(v) { break } } rooms.RUnlock() } func GetRooms() []IRoom { r := make([]IRoom, len(rooms.M)) rooms.RLock() var n = 0 for _, v := range rooms.M { r[n] = v n ++ } rooms.RUnlock() return r } ================================================ FILE: src/github.com/dolotech/leaf/timer/cronexpr.go ================================================ package timer // reference: https://github.com/robfig/cron import ( "fmt" "math" "strconv" "strings" "time" ) // Field name | Mandatory? | Allowed values | Allowed special characters // ---------- | ---------- | -------------- | -------------------------- // Seconds | No | 0-59 | * / , - // Minutes | Yes | 0-59 | * / , - // Hours | Yes | 0-23 | * / , - // Day of month | Yes | 1-31 | * / , - // Month | Yes | 1-12 | * / , - // Day of week | Yes | 0-6 | * / , - type CronExpr struct { sec uint64 min uint64 hour uint64 dom uint64 month uint64 dow uint64 } // goroutine safe func NewCronExpr(expr string) (cronExpr *CronExpr, err error) { fields := strings.Fields(expr) if len(fields) != 5 && len(fields) != 6 { err = fmt.Errorf("invalid expr %v: expected 5 or 6 fields, got %v", expr, len(fields)) return } if len(fields) == 5 { fields = append([]string{"0"}, fields...) } cronExpr = new(CronExpr) // Seconds cronExpr.sec, err = parseCronField(fields[0], 0, 59) if err != nil { goto onError } // Minutes cronExpr.min, err = parseCronField(fields[1], 0, 59) if err != nil { goto onError } // Hours cronExpr.hour, err = parseCronField(fields[2], 0, 23) if err != nil { goto onError } // Day of month cronExpr.dom, err = parseCronField(fields[3], 1, 31) if err != nil { goto onError } // Month cronExpr.month, err = parseCronField(fields[4], 1, 12) if err != nil { goto onError } // Day of week cronExpr.dow, err = parseCronField(fields[5], 0, 6) if err != nil { goto onError } return onError: err = fmt.Errorf("invalid expr %v: %v", expr, err) return } // 1. * // 2. num // 3. num-num // 4. */num // 5. num/num (means num-max/num) // 6. num-num/num func parseCronField(field string, min int, max int) (cronField uint64, err error) { fields := strings.Split(field, ",") for _, field := range fields { rangeAndIncr := strings.Split(field, "/") if len(rangeAndIncr) > 2 { err = fmt.Errorf("too many slashes: %v", field) return } // range startAndEnd := strings.Split(rangeAndIncr[0], "-") if len(startAndEnd) > 2 { err = fmt.Errorf("too many hyphens: %v", rangeAndIncr[0]) return } var start, end int if startAndEnd[0] == "*" { if len(startAndEnd) != 1 { err = fmt.Errorf("invalid range: %v", rangeAndIncr[0]) return } start = min end = max } else { // start start, err = strconv.Atoi(startAndEnd[0]) if err != nil { err = fmt.Errorf("invalid range: %v", rangeAndIncr[0]) return } // end if len(startAndEnd) == 1 { if len(rangeAndIncr) == 2 { end = max } else { end = start } } else { end, err = strconv.Atoi(startAndEnd[1]) if err != nil { err = fmt.Errorf("invalid range: %v", rangeAndIncr[0]) return } } } if start > end { err = fmt.Errorf("invalid range: %v", rangeAndIncr[0]) return } if start < min { err = fmt.Errorf("out of range [%v, %v]: %v", min, max, rangeAndIncr[0]) return } if end > max { err = fmt.Errorf("out of range [%v, %v]: %v", min, max, rangeAndIncr[0]) return } // increment var incr int if len(rangeAndIncr) == 1 { incr = 1 } else { incr, err = strconv.Atoi(rangeAndIncr[1]) if err != nil { err = fmt.Errorf("invalid increment: %v", rangeAndIncr[1]) return } if incr <= 0 { err = fmt.Errorf("invalid increment: %v", rangeAndIncr[1]) return } } // cronField if incr == 1 { cronField |= ^(math.MaxUint64 << uint(end+1)) & (math.MaxUint64 << uint(start)) } else { for i := start; i <= end; i += incr { cronField |= 1 << uint(i) } } } return } func (e *CronExpr) matchDay(t time.Time) bool { // day-of-month blank if e.dom == 0xfffffffe { return 1< year+1 { return time.Time{} } // Month for 1< 0 { buf := make([]byte, conf.LenStackBuf) l := runtime.Stack(buf, false) glog.Error("%v: %s", r, buf[:l]) } else { glog.Error("%v", r) } } }() if t.cb != nil { t.cb() } } func (disp *Dispatcher) AfterFunc(d time.Duration, cb func()) *Timer { t := new(Timer) t.cb = cb t.t = time.AfterFunc(d, func() { disp.ChanTimer <- t }) return t } // Cron type Cron struct { t *Timer } func (c *Cron) Stop() { if c.t != nil { c.t.Stop() } } func (disp *Dispatcher) CronFunc(cronExpr *CronExpr, _cb func()) *Cron { c := new(Cron) now := time.Now() nextTime := cronExpr.Next(now) if nextTime.IsZero() { return c } // callback var cb func() cb = func() { defer _cb() now := time.Now() nextTime := cronExpr.Next(now) if nextTime.IsZero() { return } c.t = disp.AfterFunc(nextTime.Sub(now), cb) } c.t = disp.AfterFunc(nextTime.Sub(now), cb) return c } ================================================ FILE: src/github.com/dolotech/leaf/version.go ================================================ package leaf const version = "1.1.2" ================================================ FILE: src/github.com/dolotech/lib/README.md ================================================ ================================================ FILE: src/github.com/dolotech/lib/csv/bench_test.go ================================================ /********************************************************** * Author : Michael * Email : dolotech@163.com * Last modified : 2016-07-07 23:40 * Filename : bench_test.go * Description : * *******************************************************/ package csv import ( "bytes" "compress/gzip" "io/ioutil" "os" "testing" ) // Benchmark with large CSV data set func loadData() []byte { f, err := os.Open("testdata/ercot-dam.csv.gz") if err != nil { panic(err) } defer f.Close() gz, err := gzip.NewReader(f) if err != nil { panic(err) } data, err := ioutil.ReadAll(gz) if err != nil { panic(err) } return data } type Price struct { DeliveryDate string HourEnding string BusName string LMP float32 DSTFlag bool `true:"Y" false:"N"` } func BenchmarkUnmarshal(b *testing.B) { b.StopTimer() data := loadData() b.StartTimer() pp := []Price{} err := Unmarshal(data, &pp) if err != nil { panic(err) } out, err := Marshal(pp) if err != nil { panic(err) } if bytes.Equal(data, out) != true { panic("wrong results") } b.Logf("Unmarshal %d rows", len(pp)) b.Logf("Marshaled %d bytes", len(out)) } ================================================ FILE: src/github.com/dolotech/lib/csv/cfield.go ================================================ /********************************************************** * Author : Michael * Email : dolotech@163.com * Last modified : 2016-07-07 23:41 * Filename : cfield.go * Description : * *******************************************************/ package csv import ( "fmt" "reflect" "strconv" ) type decoderFn func(*reflect.Value, *Row) error // maps a CSV column Name and index to a StructField type cfield struct { colIndex int structField *reflect.StructField decoder decoderFn } func newCfield(index int, sf *reflect.StructField) cfield { cf := cfield{ colIndex: index, structField: sf, } cf.decoder = cf.unassignedDecoder return cf } func (cf *cfield) assignUnmarshaller(code int) { if code == impsPtr { cf.decoder = cf.unmarshalPointer } else { cf.decoder = cf.unmarshalValue } } func (cf *cfield) unmarshalPointer(cell *reflect.Value, row *Row) error { val := row.At(cf.colIndex) m := cell.Addr().Interface().(Unmarshaler) m.UnmarshalCSV(val, row) return nil } func (cf *cfield) unmarshalValue(cell *reflect.Value, row *Row) error { val := row.At(cf.colIndex) m := cell.Interface().(Unmarshaler) m.UnmarshalCSV(val, row) return nil } func (cf *cfield) assignDecoder() { switch cf.structField.Type.Kind() { case reflect.String: cf.decoder = cf.decodeString case reflect.Uint32: cf.decoder = cf.decodeUint32 case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8: cf.decoder = cf.decodeInt case reflect.Float32: cf.decoder = cf.decodeFloat(32) case reflect.Float64: cf.decoder = cf.decodeFloat(64) case reflect.Bool: cf.decoder = cf.decodeBool default: cf.decoder = cf.ignoreValue } } func (cf *cfield) decodeBool(cell *reflect.Value, row *Row) error { val := row.At(cf.colIndex) var bv bool bt := cf.structField.Tag.Get("true") bf := cf.structField.Tag.Get("false") switch val { case bt: bv = true case bf: bv = false default: bv = true } cell.SetBool(bv) return nil } func (cf *cfield) decodeUint32(cell *reflect.Value, row *Row) error { val := row.At(cf.colIndex) i, e := strconv.ParseUint(val, 10, 32) if e != nil { return e } cell.SetUint(i) return nil } func (cf *cfield) decodeInt(cell *reflect.Value, row *Row) error { val := row.At(cf.colIndex) i, e := strconv.Atoi(val) if e != nil { return e } cell.SetInt(int64(i)) return nil } func (cf *cfield) decodeString(cell *reflect.Value, row *Row) error { val := row.At(cf.colIndex) cell.SetString(val) return nil } func (cf *cfield) decodeFloat(bit int) decoderFn { return func(cell *reflect.Value, row *Row) error { val := row.At(cf.colIndex) n, err := strconv.ParseFloat(val, bit) if err != nil { return err } cell.SetFloat(n) return nil } } // ignoreValue does nothing. This is for unsupported types. func (cf *cfield) ignoreValue(cell *reflect.Value, row *Row) error { return nil } // unassignedDecoder is the default decoder. It returns an error since it should // have been assigned. func (cf *cfield) unassignedDecoder(cell *reflect.Value, row *Row) error { return fmt.Errorf("no decoder for %v\n", cf.structField.Name) } ================================================ FILE: src/github.com/dolotech/lib/csv/csv.go ================================================ /********************************************************** * Author : Michael * Email : dolotech@163.com * Last modified : 2016-07-07 23:41 * Filename : csv.go * Description : * *******************************************************/ // Package csv provides `Marshal` and `UnMarshal` encoding functions for CSV(Comma Seperated Value) data. // This package is built on the the standard library's encoding/csv. package csv import ( "reflect" ) // fieldHeaderName returns the header name to use for the given StructField // This can be a user defined name (via the Tag) or a default name. func fieldHeaderName(f reflect.StructField) (string, bool) { h := f.Tag.Get("csv") if h == "-" { return "", false } // If there is no tag set, use a default name if h == "" { return f.Name, true } return h, true } ================================================ FILE: src/github.com/dolotech/lib/csv/csv_test.go ================================================ /********************************************************** * Author : Michael * Email : dolotech@163.com * Last modified : 2016-07-07 23:41 * Filename : csv_test.go * Description : * *******************************************************/ package csv import ( "fmt" "reflect" "testing" ) type simple struct { Name string `csv:"FullName"` Gender string private int `csv:"-"` Ignore string `csv:"-"` Age int } func TestHeader(t *testing.T) { x := reflect.TypeOf(simple{}) // Get the header when defined via a tag f, _ := x.FieldByName("Name") h, _ := fieldHeaderName(f) if h != "FullName" { t.Error("header does not match") } // Use the field FullName when there is no tag f, _ = x.FieldByName("Gender") h, _ = fieldHeaderName(f) if h != "Gender" { t.Error("Default header FullName not created") } // Get the header when defined via a tag f, _ = x.FieldByName("Ignore") _, ok := fieldHeaderName(f) if ok == true { t.Error("Omitted field returned ok") } } func TestHeaders(t *testing.T) { x := reflect.TypeOf(simple{}) hh := colNames(x) if "[FullName Gender Age]" != fmt.Sprintf("%v", hh) { t.Errorf("Incorrected headers: %v", hh) } } ================================================ FILE: src/github.com/dolotech/lib/csv/decode.go ================================================ /********************************************************** * Author : Michael * Email : dolotech@163.com * Last modified : 2016-07-07 23:41 * Filename : decode.go * Description : * *******************************************************/ package csv import ( "bytes" "encoding/csv" "errors" "fmt" "reflect" ) // Row is one row of CSV data, indexed by column name or position. type Row struct { Columns *[]string // The name of the columns, in order Data []string // the data for the row } // At returns the rows data for the column positon i func (r *Row) At(i int) string { return r.Data[i] } // Named returns the row's data for the first columne named 'n' func (r *Row) Named(n string) (string, error) { for i, cn := range *r.Columns { if cn == n { return r.At(i), nil } } return "", fmt.Errorf("no column found for %s", n) } type decoder struct { csv *csv.Reader // the csv document for input reflect.Type // the underlying struct to decode out reflect.Value // the slice output cfields []cfield // cols []string // colum names } // Unmarshaler is the interface implemented by objects which can unmarshall the CSV row itself. type Unmarshaler interface { // UnmarshalCSV receives a string with the column value matching this field // and a reference to the the current row. // This allows composing a value from mutliple columns. UnmarshalCSV(string, *Row) error } // Unmarshal parses the CSV document and stores the result in the value pointed to by v. Only a slice of a struct is allowed for v. // // The first line of the CSV is document is used for column names. These are // paired to matching exported fields in v's type. See Marshal on how to use tags // to map to different names and additional options. // // Supported Types // // string, int, float and bool are supported. Any type which implements Unmarshal is also supported. func Unmarshal(doc []byte, v interface{}) error { rv, err := checkForSlice(v) if err != nil { return err } dec, err := newDecoder(doc, rv) if err != nil { return err } dec.unmarshal() return nil } func (dec *decoder) unmarshal() error { for { raw, err := dec.csv.Read() if err != nil { break } else { row := dec.newRow(raw) o := reflect.New(dec.Type).Elem() err := dec.set(row, &o) if err != nil { return err } dec.out.Set(reflect.Append(dec.out, o)) } } return nil } func (dec *decoder) newRow(raw []string) *Row { return &Row{ Columns: &dec.cols, Data: raw, } } // checkForSlice validates that the interface is a slice type func checkForSlice(v interface{}) (reflect.Value, error) { pv := reflect.ValueOf(v) if pv.Kind() != reflect.Ptr || pv.IsNil() { return pv, errors.New("type is nil or not a pointer") } rv := reflect.ValueOf(v).Elem() if rv.Kind() != reflect.Slice { return rv, fmt.Errorf("only slices are allowed: %s", rv.Kind()) } return rv, nil } const ( // interface is implemented on a value impsVal int = 1 // interface is implemented on a pointer impsPtr int = 2 ) // impsUnmarshaller checks if an object implements the Unmarshaler interface func impsUnmarshaller(et reflect.Type, i interface{}) (int, error) { el := reflect.New(et).Elem() it := reflect.TypeOf(i).Elem() if el.Type().Implements(it) { return impsVal, nil } if el.Addr().Type().Implements(it) { return impsPtr, nil } return 0, fmt.Errorf("%v el does not implement %s", el, it.Name()) } // mapFields creates a set of fieldMap instances. // // A cfield is created when a column name matches an exported field name in the // decoder's Type. func (dec *decoder) mapFieldsToCols(cols []string) { pFields := exportedFields(dec.Type) cMap := map[string]int{} for i, col := range cols { cMap[col] = i } for _, f := range pFields { name, ok := fieldHeaderName(*f) if ok == false { continue } index, ok := cMap[name] if ok == true { cf := newCfield(index, f) if code, err := impsUnmarshaller(f.Type, new(Unmarshaler)); err == nil { cf.assignUnmarshaller(code) } else { cf.assignDecoder() } dec.cfields = append(dec.cfields, cf) } } } // exportedFields returns a slice of exported fields func exportedFields(t reflect.Type) []*reflect.StructField { var out []*reflect.StructField // if t.Kind() == reflect.Ptr { // t = t.Elem() // } v := reflect.New(t).Elem() flen := v.NumField() for i := 0; i < flen; i++ { // Get the StructField from the Type sf := t.Field(i) // Check if the field is CanSet from the value (v) if v.Field(i).CanSet() == true { out = append(out, &sf) } } return out } func newDecoder(doc []byte, rv reflect.Value) (*decoder, error) { b := bytes.NewReader(doc) r := csv.NewReader(b) cols, err := r.Read() if err != nil { return nil, err } el := rv.Type().Elem() dec := decoder{ Type: el, csv: r, out: rv, cols: cols, } dec.mapFieldsToCols(cols) return &dec, nil } // Sets each field value for the el struct for the given row func (dec *decoder) set(row *Row, el *reflect.Value) error { for _, cf := range dec.cfields { field := cf.structField f := el.FieldByName(field.Name) err := cf.decoder(&f, row) if err != nil { return err } } return nil } ================================================ FILE: src/github.com/dolotech/lib/csv/decode_test.go ================================================ /********************************************************** * Author : Michael * Email : dolotech@163.com * Last modified : 2016-07-07 23:41 * Filename : decode_test.go * Description : * *******************************************************/ package csv import ( "reflect" "testing" ) type Q struct { String string Int int unxported int Bool bool `true:"Yes" false:"No"` Float32 float32 Float64 float64 Complex64 complex64 `csv:"C64"` } func TestUnmarshal(t *testing.T) { doc := []byte(`String,Int,unexported,Bool,Float32,Float64,C64 John,23,1,Yes,32.2,64.1,1 Jane,27,2,No,33.1,65.1,2 Bill,28,3,Yes,34.7,65.1,3`) pp := []Q{} Unmarshal(doc, &pp) if len(pp) != 3 { t.Errorf("Incorrect record length: %d", len(pp)) } assert := func(e, a interface{}) { if e != a { t.Errorf("expected (%s) got (%s)", e, a) } } strs := []string{"John", "Jane", "Bill"} ints := []int{23, 27, 28} bools := []bool{true, false, true} f32s := []float32{32.2, 33.1, 34.7} f64s := []float64{64.1, 65.1, 65.1} for i, p := range pp { assert(strs[i], p.String) assert(ints[i], p.Int) assert(bools[i], p.Bool) assert(f32s[i], p.Float32) assert(f64s[i], p.Float64) } } func TestMarshalErrors(t *testing.T) { doc := []byte(`Name,Age`) err := Unmarshal(doc, []Q{}) if err == nil { t.Error("No error generated for non-pointer") } err = Unmarshal(doc, &Q{}) if err == nil { t.Error("No error generated for non-slice") } pp := []Q{} err = Unmarshal(doc, &pp) if err != nil { t.Error("Error returned when not expected:", err) } } func TestExportedFields(t *testing.T) { type s struct { Name string Age int `csv:"Age"` priv int `csv:"-"` } fs := exportedFields(reflect.TypeOf(s{})) if len(fs) != 2 { t.Error("Incorrect number of exported fields 2 expected got %d", len(fs)) } if fs[0].Name != "Name" || fs[1].Name != "Age" { t.Error("Incorrect returned fields") } } type T struct { Name string age string // unexported, should not be included Addr string `csv:"Address"` NoMatch int // public, but no match in the CSV headers } func TestMapFields(t *testing.T) { dec := &decoder{Type: reflect.TypeOf(T{})} cols := []string{ "Name", "age", // should not match since the 'age' field is not exported "Address", } dec.mapFieldsToCols(cols) fm := dec.cfields if len(fm) != 2 { t.Errorf("Expected length of 2, got %d", len(fm)) } for i, n := range []int{0, 2} { if fm[i].colIndex != n { t.Errorf("expected colIndex of %d got %d", fm[i].colIndex, n) } } } type Um struct { V string } type U struct { Name Um } func (u *Um) UnmarshalCSV(val string, row *Row) error { v, _ := row.Named("Age") u.V = row.At(0) + " " + v return nil } func TestCustomUnMarshaller(t *testing.T) { doc := `Name,Age Jay,23` oo := []U{} Unmarshal([]byte(doc), &oo) if oo[0].Name.V != "Jay 23" { t.Errorf("custom unmarshal did not work (%s)", oo[0].Name.V) } } ================================================ FILE: src/github.com/dolotech/lib/csv/encode.go ================================================ /********************************************************** * Author : Michael * Email : dolotech@163.com * Last modified : 2016-07-07 23:41 * Filename : encode.go * Description : * *******************************************************/ package csv import ( "bytes" "encoding/csv" "errors" "fmt" "reflect" "strconv" ) // Marshaler is an interface for objects which can Marshal themselves into CSV. type Marshaler interface { MarshalCSV() ([]byte, error) } type encoder struct { *csv.Writer buffer *bytes.Buffer } // Marshal returns the CSV encoding of i, which must be a slice of struct types. // // Marshal traverses the slice and encodes the primative values. // // The first row of the CSV output is a header row. The column names are based // on the field name. If a different name is required a struct tag can be used // to define a new name. // // Field string `csv:"Column Name"` // // To skip encoding a field use the "-" as the tag value. // // Field string `csv:"-"` // // Boolean fields can use string values to define true or false. // Bool bool `true:"Yes" false:"No"` func Marshal(i interface{}) ([]byte, error) { // validate the interface // create a new encoder // assing the cfields // get the headers // encoder each row data := reflect.ValueOf(i) if data.Kind() != reflect.Slice { return []byte{}, errors.New("only slices can be marshalled") } el := data.Index(0) enc, err := newEncoder(el) if err != nil { return []byte{}, err } err = enc.encodeAll(data) if err != nil { return []byte{}, err } enc.Flush() return enc.buffer.Bytes(), nil } func newEncoder(el reflect.Value) (*encoder, error) { b := bytes.NewBuffer([]byte{}) enc := &encoder{ buffer: b, Writer: csv.NewWriter(b), } err := enc.Write(colNames(el.Type())) return enc, err } // colNames takes a struct and returns the computed columns names for each // field. func colNames(t reflect.Type) (out []string) { l := t.NumField() for x := 0; x < l; x++ { f := t.Field(x) h, ok := fieldHeaderName(f) if ok { out = append(out, h) } } return } // encodeAll iterates over each item in data, encoder it then writes it func (enc *encoder) encodeAll(data reflect.Value) error { n := data.Len() for c := 0; c < n; c++ { row, err := enc.encodeRow(data.Index(c)) if err != nil { return err } err = enc.Write(row) if err != nil { return err } } return nil } // encodes a struct into a CSV row func (enc *encoder) encodeRow(v reflect.Value) ([]string, error) { var row []string // TODO env.columns should map to a cfield // iterate over each cfield and encode with it l := v.Type().NumField() for x := 0; x < l; x++ { fv := v.Field(x) st := v.Type().Field(x).Tag if st.Get("csv") == "-" { continue } o := enc.encodeCol(fv, st) row = append(row, o) } return row, nil } // Returns the string representation of the field value func (enc *encoder) encodeCol(fv reflect.Value, st reflect.StructTag) string { switch fv.Kind() { case reflect.String: return fv.String() case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int8: return fmt.Sprintf("%v", fv.Int()) case reflect.Float32: return encodeFloat(32, fv) case reflect.Float64: return encodeFloat(64, fv) case reflect.Bool: return encodeBool(fv.Bool(), st) case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint8: return fmt.Sprintf("%v", fv.Uint()) case reflect.Complex64, reflect.Complex128: return fmt.Sprintf("%+.3g", fv.Complex()) case reflect.Interface: return encodeInterface(fv, st) case reflect.Struct: return encodeInterface(fv, st) default: panic(fmt.Sprintf("Unsupported type %s", fv.Kind())) } return "" } func encodeFloat(bits int, f reflect.Value) string { return strconv.FormatFloat(f.Float(), 'g', -1, bits) } func encodeBool(b bool, st reflect.StructTag) string { v := strconv.FormatBool(b) tv := st.Get(v) if tv != "" { return tv } return v } func encodeInterface(fv reflect.Value, st reflect.StructTag) string { marshalerType := reflect.TypeOf(new(Marshaler)).Elem() if fv.Type().Implements(marshalerType) { m := fv.Interface().(Marshaler) b, err := m.MarshalCSV() if err != nil { return "" } return string(b) } return "" } ================================================ FILE: src/github.com/dolotech/lib/csv/encode_test.go ================================================ /********************************************************** * Author : Michael * Email : dolotech@163.com * Last modified : 2016-07-07 23:42 * Filename : encode_test.go * Description : * *******************************************************/ package csv import ( "reflect" "testing" ) type X struct { First string } type P struct { First string Last string } func (p P) MarshalCSV() ([]byte, error) { return []byte(p.First + " " + p.Last), nil } func TestMarshal_without_a_slice(t *testing.T) { _, err := Marshal(simple{}) if err == nil { t.Error("Non slice produced no error") } } func TestEncodeFieldValue(t *testing.T) { var encTests = []struct { val interface{} expected string tag string }{ // Strings {"ABC", "ABC", ""}, {byte(123), "123", ""}, // Numerics {int(1), "1", ""}, {float32(3.2), "3.2", ""}, {uint32(123), "123", ""}, {complex64(1 + 2i), "(+1+2i)", ""}, // Boolean {true, "Yes", `true:"Yes" false:"No"`}, {false, "No", `true:"Yes" false:"No"`}, // TODO Array // Interface with Marshaler {P{"Jay", "Zee"}, "Jay Zee", ""}, // Struct without Marshaler will produce nothing {X{"Jay"}, "", ""}, } enc := &encoder{} for _, test := range encTests { fv := reflect.ValueOf(test.val) st := reflect.StructTag(test.tag) res := enc.encodeCol(fv, st) if res != test.expected { t.Errorf("%s does not match %s", res, test.expected) } } } ================================================ FILE: src/github.com/dolotech/lib/csv/example_marshal_test.go ================================================ /********************************************************** * Author : Michael * Email : dolotech@163.com * Last modified : 2016-07-07 23:42 * Filename : example_marshal_test.go * Description : * *******************************************************/ package csv import ( "fmt" "github.com/golang/glog" ) func ExampleMarshal() { type Person struct { Name string `csv:"FullName"` Gender string Age int Wallet float32 `csv:"Bank Account"` Happy bool `true:"Yes!" false:"Sad"` private int `csv:"-"` } people := []Person{ Person{ Name: "Smith, Joe", Gender: "M", Age: 23, Wallet: 19.07, Happy: false, }, } out, _ := Marshal(people) glog.Infof("%s", out) // Output: // FullName,Gender,Age,Bank Account,Happy // "Smith, Joe",M,23,19.07,Sad } ================================================ FILE: src/github.com/dolotech/lib/csv/example_test.go ================================================ /********************************************************** * Author : Michael * Email : dolotech@163.com * Last modified : 2016-07-07 23:42 * Filename : example_test.go * Description : * *******************************************************/ package csv import ( "fmt" "github.com/golang/glog" ) type Person struct { Name string `csv:"Full Name"` income string // unexported fields are not Unmarshalled Age int `csv:"-"` // skip this field Address Address `csv:"Street"` // skip this field } type Address struct { City string Street string } func (a *Address) UnmarshalCSV(val string, row *Row) error { c, _ := row.Named("City") s, _ := row.Named("Street") a.Street = s a.City = c return nil } func ExampleUnmarshal() { people := []Person{} sample := []byte( `Full Name,income,Age,City,Street John Doe,"32,000",45,Brooklyn,"7th Street" `) err := Unmarshal(sample, &people) if err != nil { glog.Infoln("Error: ", err) } glog.Infof("%+v", people) // Output: // [{Name:John Doe income: Age:0 Address:{City:Brooklyn Street:7th Street}}] } ================================================ FILE: src/github.com/dolotech/lib/db/client.go ================================================ // 数据库客户端常用操作 (基于 xorm) package db import ( "errors" "fmt" "strconv" "time" "github.com/go-xorm/xorm" _ "github.com/lib/pq" ) // Client 数据库客户端 type Client struct { engine *xorm.Engine } var db *Client //var database_addr string //const configFilePath string = "config.ini" func Init(url string) error{ var err error if db == nil { db, err = NewClient("postgres", url) //db.ShowSQL(config.GetCfgDatabase().ShowSql) db.ShowSQL(true) } return err } func C() *Client { return db } // NewClient 创建一个客户端链接 func NewClient(driver, connstr string) (*Client, error) { engine, err := xorm.NewEngine(driver, connstr) engine.SetMaxIdleConns(200) //最大连接数设置为200 if err == nil { ping := func() <-chan string { errmsg := make(chan string) go func() { err := engine.Ping() if err != nil { errmsg <- err.Error() } else { errmsg <- "" } }() return errmsg } go func() { select { case msg := <-ping(): if len(msg) > 0 { //logs.Error(msg) } else { //logs.Info("connect %s succeed.", driver) } case <-time.After(time.Second * 5): //logs.Info("connect timeout 5 second.") } }() } return &Client{engine: engine}, err } func (cl *Client) Engine() *xorm.Engine { return cl.engine } // Close 关闭连接 func (cl *Client) Close() error { if cl.engine != nil { err := cl.engine.Close() cl.engine = nil return err } return nil } // SerialInteractor 序列接口 type SerialInteractor interface { TableName() string } // ShowSQL 显示 SQL func (cl *Client) ShowSQL(show bool) { cl.engine.ShowSQL(show) } // NewSession 创建一个事务 func (cl *Client) NewSession() *xorm.Session { return cl.engine.NewSession() } // GetNextSerial 获取下个以序列 func (cl *Client) GetNextSerial(serialbean SerialInteractor) (int, error) { sqlStr := fmt.Sprintf("select nextval('%s_id_seq'::regclass)", serialbean.TableName()) data, err := cl.engine.Query(sqlStr) if err != nil || data == nil || len(data) == 0 { return 0, err } nextval := string(data[0]["nextval"]) return strconv.Atoi(nextval) } // SimpleValue 简单结果 func (cl *Client) SimpleValue(sql string) (string, error) { data, err := cl.engine.Query(sql) if err != nil || data == nil || len(data) == 0 { return "", err } for _, v := range data[0] { ret := string(v) return ret, nil } return "", errors.New("not found return value") } // SimpleIntValue 简单的 int 值 func (cl *Client) SimpleIntValue(sql string) (int, error) { data, err := cl.engine.Query(sql) if err != nil || data == nil || len(data) == 0 { return 0, err } for _, v := range data[0] { ret := string(v) return strconv.Atoi(ret) } return 0, errors.New("not found return value") } // Insert 保存一个数据 func (cl *Client) Insert(bean interface{}, omitColumns ...string) (int64, error) { return cl.engine.Omit(omitColumns...).Insert(bean) } // Get 查找一条数据 func (cl *Client) Get(bean interface{}) (bool, error) { has, err := cl.engine.Get(bean) return has, err } // WhereGet 条件查询 func (cl *Client) WhereGet(bean interface{}, querystring string, args ...interface{}) (bool, error) { return cl.engine.Where(querystring, args...).Get(bean) } // WhereFind 条件查询 func (cl *Client) WhereFind(bean interface{}, querystring string, args ...interface{}) error { return cl.engine.Where(querystring, args...).Find(bean) } // Update 修改一条数据 func (cl *Client) Update(id int, bean interface{}, omitClumns ...string) error { session := cl.engine.NewSession() defer session.Close() rows, err := session.Omit(omitClumns...).Id(id).Update(bean) if rows > 1 { _ = session.Rollback() return fmt.Errorf("修改失败,影响行数: %d ", rows) } _ = session.Commit() return err } // Delete 删除数据 func (cl *Client) Delete(bean interface{}) error { session := cl.engine.NewSession() rows, err := session.Delete(bean) if rows > 1 { _ = session.Rollback() return fmt.Errorf("修改失败,影响行数: %d ", rows) } _ = session.Commit() return err } // // Query 多数据查询 // func (cl *Client) Query(beans interface{}, querystring string, args ...interface{}) error { // return cl.engine.Where(querystring, args...).Find(beans) // } // Where 条件查询 func (cl *Client) Where(beans interface{}, querystring string, args ...interface{}) error { return cl.engine.Where(querystring, args...).Find(beans) } // In 条件查询 IN list func (cl *Client) In(beans interface{}, querystring string, args ...interface{}) error { return cl.engine.In(querystring, args...).Find(beans) } // SQL 查询 func (cl *Client) SQL(beans interface{}, querystring string, args ...interface{}) error { return cl.engine.Sql(querystring, args...).Find(beans) } // QueryValue 查询 func (cl *Client) QueryValue(sqlstr string) ([]map[string][]byte, error) { data, err := cl.engine.Query(sqlstr) return data, err } // Create 新建一个表 func (cl *Client) CreateTables(beans ...interface{}) error { return cl.engine.CreateTables(beans...) } // Sync 同步新表 func (cl *Client) Sync(beans ...interface{}) error { return cl.engine.Sync(beans...) } ================================================ FILE: src/github.com/dolotech/lib/db/client_test.go ================================================ package db import ( //"game/player" //"github.com/bmizerany/assert" _ "github.com/lib/pq" //l4g "lib/log4go" "testing" ) const UCDBURL = "postgres://postgres:postgres@192.168.1.240:3021/postgres?sslmode=disable" func Test_NewClient(t *testing.T) { //l4g.Info("test client ...") //client, err := NewClient("postgres", UCDBURL) //client.engine.ShowSQL(true) //assert.Equal(t, err, nil) //defer client.Close() //l4g.Info("Start New Client", client) } func Test_Insert(t *testing.T) { //client, err := NewClient("postgres", UCDBURL) //assert.Equal(t, err, nil) //defer client.Close() // //l4g.Info("XXXXX", client) //client.Insert(&player.User{},) } ================================================ FILE: src/github.com/dolotech/lib/filter/filter.go ================================================ package filter import ( "bytes" _ "fmt" "io/ioutil" "os" "os/signal" "sort" "syscall" "time" "github.com/golang/glog" ) var dicFileTrie map[string]*Trie = make(map[string]*Trie) //map for dictionary file to trie var dicFileTime map[string]int64 = make(map[string]int64) //map for dictionary file to it's built time func LoadDicFiles(dicFiles []string) { //load serveral dictionary file to build tries for _, dicFile := range dicFiles { dicFileTrie[dicFile] = nil dicFileTime[dicFile] = 0 } go buildDicFileTrie() //asyn build dictionary file trie,when completed the old trie will be replaced } func buildDicFileTrie() { //when server start-up the trie will be built automatically for { c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGHUP) for dicFile, _ := range dicFileTrie { stat, e := os.Stat(dicFile) if e != nil || stat.ModTime().Unix() > dicFileTime[dicFile] { //maybe deleted file or updated file data, e := ioutil.ReadFile(dicFile) if e != nil || len(data) <= 0 { //file not exist or empty dicFileTrie[dicFile] = nil //delete the old trie,maybe concurrency problem } dictionary := bytes.Split(data, []byte("\n")) var tree Trie tree.InitRootNode() tree.BuildTrie(dictionary) dicFileTrie[dicFile] = &tree //replace the old trie,maybe concurrency problem dicFileTime[dicFile] = time.Now().Unix() //save the replace time } } <-c //after we refresh the all dictionary trie we will block to the next SIGHUP signal and refresh the all dictionary trie again } } //separator charactors,if we want to match "abcde" in "abc112312de" ,separator charactors can be set to "123" type Seps []rune func (s Seps) Len() int { return len(s) } func (s Seps) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s Seps) Less(i, j int) bool { return s[i] < s[j] } func FindSepC(seps Seps, charactor rune) bool { i := sort.Search(len(seps), func(i int) bool { return seps[i] >= charactor }) return i < len(seps) && seps[i] == charactor } // we use a dictionary file to filter text,all separator in text will be bypassed,and matched words will be replace by rep func FilterText(dicFile string, text []rune, seps Seps, rep rune) { T := dicFileTrie[dicFile] //save trie to temporary variable to eliminate concurrency problem if T == nil { //no matched trie for dictionary file return } sort.Sort(seps) //sort seps to speed up search process walkNode := T.RootNode //walk through the trie from root var nextNode *Node //point to walkNode's next node for i, charactor := range text { //travel the text,i is used as an index to present charactor for { if FindSepC(seps, charactor) { //omit charactor in seps break } nextNode = walkNode.BinGetChildNodeByVal(charactor) if nextNode == nil { //not found next node whose val is charactor if nil != walkNode.SuffixNode { //point to suffix node, redo the find operation,maybe its suffix node is root walkNode = walkNode.SuffixNode continue } else { //only root node's suffix node is null walkNode = T.RootNode //restart from root break //break to handle next charactor } } else { // find node if nextNode.EOW { //if a word end up with next node depth := nextNode.Depth //get the word length j := i //search back from i for depth > 0 { //until to root for j >= 0 && FindSepC(seps, text[j]) { //omit j-- } if j >= 0 { text[j] = rep //replace with rep j-- } depth-- } walkNode = T.RootNode //restart from root } else { //not EOW walkNode = nextNode //step to next node } break //break to handle next charactor } } } } // we use a dictionary file to filter text,all separator in text will be bypassed,and matched words will be replace by rep func IsInValid(dicFile string, text []rune, seps Seps, rep rune)(valid bool) { T := dicFileTrie[dicFile] //save trie to temporary variable to eliminate concurrency problem if T == nil { //no matched trie for dictionary file glog.Errorf("empty is %+v",T) return } sort.Sort(seps) //sort seps to speed up search process walkNode := T.RootNode //walk through the trie from root var nextNode *Node //point to walkNode's next node for i, charactor := range text { //travel the text,i is used as an index to present charactor for { if FindSepC(seps, charactor) { //omit charactor in seps break } nextNode = walkNode.BinGetChildNodeByVal(charactor) if nextNode == nil { //not found next node whose val is charactor if nil != walkNode.SuffixNode { //point to suffix node, redo the find operation,maybe its suffix node is root walkNode = walkNode.SuffixNode continue } else { //only root node's suffix node is null walkNode = T.RootNode //restart from root break //break to handle next charactor } } else { // find node if nextNode.EOW { //if a word end up with next node depth := nextNode.Depth //get the word length j := i //search back from i for depth > 0 { //until to root for j >= 0 && FindSepC(seps, text[j]) { //omit j-- } if j >= 0 { valid=true //text[j] = rep //replace with rep //j-- } depth-- } walkNode = T.RootNode //restart from root } else { //not EOW walkNode = nextNode //step to next node } break //break to handle next charactor } } } return } ================================================ FILE: src/github.com/dolotech/lib/filter/readme.txt ================================================ Aho-Corasick is a multiple string matching algorithm I implement the algorithm in trie.go In filter.go, I use the built trie to search sensitive words,and filter them out In test1.go, I test the filter function In test2.go, I implement a simple http server, and the dictionary can be asynchronously hot-updated and hot-reloading using command: 'kill -1 pid' go run test1.go go run test2.go I tested for a dictionary file which contains 140W lines of diffrent sensitive phrases and 2100W charactors and totally 35M in size. It takes 50s to build the according trie, and it takes 1.5s to filter the all phrases out from a given text file which is the same to the dictionary file ( the worst case ) in a routine. And the total memory usage of the process is 2.4G ================================================ FILE: src/github.com/dolotech/lib/filter/trie.go ================================================ // trie.go: use dictionary words to build FSM // with the help of Aho-Corasick algorithm // which is proficient in searching multiple string pattern in text // with small usage of memory and high speed. package filter import ( "container/list" "fmt" "sort" "unicode/utf8" "github.com/golang/glog" ) // In a trie, each node has many child nodes type ChildNodeType []*Node // Implement the interface which is needed by STL sort function func (c ChildNodeType) Len() int { return len(c) } // Implement the interface which is needed by STL sort function func (c ChildNodeType) Swap(i, j int) { c[i], c[j] = c[j], c[i] } // Implement the interface which is needed by STL sort function func (c ChildNodeType) Less(i, j int) bool { return c[i].Val < c[j].Val } // Node used to build trie structure type Node struct { Val rune // val from the parent to the node,or edge, utf-8 encode Depth int // depth of the node from root,root's depth is 0 ParentNode *Node // parent node used to trace back to the root ChildNodes ChildNodeType // child node slice SuffixNode *Node // suffix node of the node's longest postfix, represented by root->node1->node2....->suffix EOW bool // end-of-word tag } // get child node by given val func (N *Node) GetChildNodeByVal(val rune) *Node { childNodeNum := len(N.ChildNodes) for left := 0; left <= childNodeNum-1; left++ { if N.ChildNodes[left].Val == val { return N.ChildNodes[left] } } return nil } // binary search childnodes with given val func (N *Node) BinGetChildNodeByVal(val rune) *Node { right := len(N.ChildNodes) - 1 left := 0 mid := 0 var midnode *Node for left <= right { mid = (left + right) / 2 midnode = N.ChildNodes[mid] if midnode.Val == val { return midnode } else if midnode.Val < val { left = mid + 1 } else if midnode.Val > val { right = mid - 1 } } return nil } // simplly insert a child node func (N *Node) InsertChildNodeByVal(val rune) *Node { node := new(Node) node.Val = val node.Depth = N.Depth + 1 node.ParentNode = N node.ChildNodes = nil node.SuffixNode = nil node.EOW = false N.ChildNodes = append(N.ChildNodes, node) //fmt.Printf("build %c---->%c\n", N.Val, node.Val) return node } // Trie type Trie struct { RootNode *Node // root } func (T *Trie) InitRootNode() { node := new(Node) node.Val = 0 node.Depth = 0 node.ParentNode = nil node.ChildNodes = nil node.SuffixNode = nil node.EOW = false T.RootNode = node } // dump the whole trie which is rooted in node func (T *Trie) DumpTrie(node *Node) { lst := new(list.List) lst.PushBack(node) for lst.Len() > 0 { node := lst.Remove(lst.Front()).(*Node) pnode := node.ParentNode snode := node.SuffixNode var adr *Node = nil var padr *Node = nil var sadr *Node = nil var cadr *Node = nil var val rune = 0 var pval rune = 0 var sval rune = 0 var cval rune = 0 val = node.Val adr = node if pnode != nil { pval = pnode.Val padr = pnode } if snode != nil { sval = snode.Val sadr = snode } glog.Infof("adr:%p val:%c depth:%d padr:%p pval:%c sadr:%p sval:%c eow:%v\n", adr, val, node.Depth, padr, pval, sadr, sval, node.EOW) for _, child := range node.ChildNodes { cadr = child cval = child.Val glog.Infof("-------------->cadr:%p cval:%c\n", cadr, cval) lst.PushBack(child) } } } // trace from a node to root, root and the node are both contained in return func (T *Trie) TraceBackToRoot(node *Node) []*Node { depth := node.Depth nodes := make([]*Node, depth+1) nodes[0] = T.RootNode for tmpnode := node; tmpnode != nil; tmpnode = tmpnode.ParentNode { nodes[depth] = tmpnode depth-- } return nodes } // find a node the path to which can be represented by value of nodes arr func (T *Trie) FindNodeByPath(nodes []*Node) *Node { //nodes not contain root node tmpnode := T.RootNode for i, node := range nodes { tmpnode = tmpnode.GetChildNodeByVal(node.Val) if tmpnode == nil || tmpnode.Val != node.Val { return nil } else if i == len(nodes)-1 { return tmpnode } } return nil } // build trie by given dictionary,each line in dictionary is a word func (T *Trie) BuildTrie(dictionary [][]byte) { for _, line := range dictionary { if len(line) <= 0 { continue } parent := T.RootNode //when we handle a word, we start from rootnode for len(line) > 0 { charactor, length := utf8.DecodeRune(line) //each time get a rune and its size in bytes if length <= 0 { break //maybe not handle whole line } child := parent.GetChildNodeByVal(charactor) if child == nil { child = parent.InsertChildNodeByVal(charactor) } parent = child line = line[length:] } if parent != T.RootNode { parent.EOW = true // if len(line)>0 and rightly handle at least one charactor, we tag the node as EOW } } // now a trie is built lst := new(list.List) lst.PushBack(T.RootNode) // start from root node , we find suffix node of each node for lst.Len() > 0 { node := lst.Remove(lst.Front()).(*Node) sort.Sort(node.ChildNodes) //sort the child nodes to use binary search for _, child := range node.ChildNodes { //each time we get a child lst.PushBack(child) startDepth := 2 //only nodes whose depth>=2 have suffix node searchDepth := child.Depth //search from child's depth var suffixNode *Node if searchDepth >= startDepth { // only nodes whose depth is bigger or equal to 2 are considered pathToRoot := T.TraceBackToRoot(child) //pathToRoot is root->level1node->level2node->level3node...... for startDepth <= searchDepth { suffixNode = T.FindNodeByPath(pathToRoot[startDepth : searchDepth+1]) //just start from level2node if suffixNode != nil { //if find,we break,because we just care the longest postfix break } startDepth++ //each time we add startDepth the postfix is shortened } } if suffixNode != nil { child.SuffixNode = suffixNode // found } else { child.SuffixNode = T.RootNode // if not found or level1 nodes ,root is set, so we can ensure that every node has a suffix node } } } //T.DumpTrie(T.RootNode) } ================================================ FILE: src/github.com/dolotech/lib/goevent/go_event.go ================================================ package goevent import ( "fmt" "reflect" "sync" ) type Event struct { listeners []reflect.Value lmu sync.RWMutex argTypes []reflect.Type tmu sync.RWMutex } func (p *Event) Trigger(args ...interface{}) error { arguments := make([]reflect.Value, 0, len(args)) argTypes := make([]reflect.Type, 0, len(args)) for _, v := range args { arguments = append(arguments, reflect.ValueOf(v)) argTypes = append(argTypes, reflect.TypeOf(v)) } err := p.validateArgs(argTypes) if err != nil { return err } p.lmu.RLock() defer p.lmu.RUnlock() wg := sync.WaitGroup{} wg.Add(len(p.listeners)) for _, fn := range p.listeners { go func(f reflect.Value) { defer wg.Done() f.Call(arguments) }(fn) } wg.Wait() return nil } // Start to listen an Event. func (p *Event) On(f interface{}) error { fn, err := p.checkFuncSignature(f) if err != nil { return err } p.lmu.Lock() defer p.lmu.Unlock() p.listeners = append(p.listeners, *fn) return nil } // Stop listening an Event. func (p *Event) Off(f interface{}) error { fn := reflect.ValueOf(f) p.lmu.Lock() defer p.lmu.Unlock() l := len(p.listeners) m := l // for error check for i := 0; i < l; i++ { if fn == p.listeners[i] { // XXX: GC Ref: http://jxck.hatenablog.com/entry/golang-slice-internals p.listeners = append(p.listeners[:i], p.listeners[i+1:]...) l-- i-- } } if l == m { return fmt.Errorf("Listener does't exists") } return nil } // retrun function as reflect.Value // retrun error if f isn't function, argument is invalid func (p *Event) checkFuncSignature(f interface{}) (*reflect.Value, error) { fn := reflect.ValueOf(f) if fn.Kind() != reflect.Func { return nil, fmt.Errorf("Argument should be a function") } types := fnArgTypes(fn) p.lmu.RLock() defer p.lmu.RUnlock() if len(p.listeners) == 0 { p.tmu.Lock() defer p.tmu.Unlock() p.argTypes = types return &fn, nil } err := p.validateArgs(types) if err != nil { return nil, err } return &fn, nil } // if argument size or type are different return error. func (p *Event) validateArgs(types []reflect.Type) error { p.tmu.RLock() defer p.tmu.RUnlock() if len(types) != len(p.argTypes) { return fmt.Errorf("Argument length expected %d, but got %d", len(p.argTypes), len(types)) } for i, t := range types { if t != p.argTypes[i] { return fmt.Errorf("Argument Error. Args[%d] expected %s, but got %s", i, p.argTypes[i], t) } } return nil } // return argument types. func fnArgTypes(fn reflect.Value) []reflect.Type { fnType := fn.Type() fnNum := fnType.NumIn() types := make([]reflect.Type, 0, fnNum) for i := 0; i < fnNum; i++ { types = append(types, fnType.In(i)) } return types } ================================================ FILE: src/github.com/dolotech/lib/grpool/grpool.go ================================================ package grpool import ( "sync" ) // Gorouting instance which can accept client jobs type worker struct { workerPool chan *worker jobChannel chan Job stop chan struct{} } func (w *worker) start() { go func() { var job Job for { // worker free, add it to pool w.workerPool <- w select { case job = <-w.jobChannel: job() case <-w.stop: w.stop <- struct{}{} return } } }() } func newWorker(pool chan *worker) *worker { return &worker{ workerPool: pool, jobChannel: make(chan Job), stop: make(chan struct{}), } } // Accepts jobs from clients, and waits for first free worker to deliver job type dispatcher struct { workerPool chan *worker jobQueue chan Job stop chan struct{} } func (d *dispatcher) dispatch() { for { select { case job := <-d.jobQueue: worker := <-d.workerPool worker.jobChannel <- job case <-d.stop: for i := 0; i < cap(d.workerPool); i++ { worker := <-d.workerPool worker.stop <- struct{}{} <-worker.stop } d.stop <- struct{}{} return } } } func newDispatcher(workerPool chan *worker, jobQueue chan Job) *dispatcher { d := &dispatcher{ workerPool: workerPool, jobQueue: jobQueue, stop: make(chan struct{}), } for i := 0; i < cap(d.workerPool); i++ { worker := newWorker(d.workerPool) worker.start() } go d.dispatch() return d } // Represents user request, function which should be executed in some worker. type Job func() type Pool struct { JobQueue chan Job dispatcher *dispatcher wg sync.WaitGroup } // Will make pool of gorouting workers. // numWorkers - how many workers will be created for this pool // queueLen - how many jobs can we accept until we block // // Returned object contains JobQueue reference, which you can use to send job to pool. func NewPool(numWorkers int, jobQueueLen int) *Pool { jobQueue := make(chan Job, jobQueueLen) workerPool := make(chan *worker, numWorkers) pool := &Pool{ JobQueue: jobQueue, dispatcher: newDispatcher(workerPool, jobQueue), } return pool } // In case you are using WaitAll fn, you should call this method // every time your job is done. // // If you are not using WaitAll then we assume you have your own way of synchronizing. func (p *Pool) JobDone() { p.wg.Done() } // How many jobs we should wait when calling WaitAll. // It is using WaitGroup Add/Done/Wait func (p *Pool) WaitCount(count int) { p.wg.Add(count) } // Will wait for all jobs to finish. func (p *Pool) WaitAll() { p.wg.Wait() } // Will release resources used by pool func (p *Pool) Release() { p.dispatcher.stop <- struct{}{} <-p.dispatcher.stop } ================================================ FILE: src/github.com/dolotech/lib/grpool/grpool_test.go ================================================ package grpool import ( "io/ioutil" "log" "runtime" "sync/atomic" "testing" "github.com/stretchr/testify/assert" ) func init() { println("using MAXPROC") numCPUs := runtime.NumCPU() runtime.GOMAXPROCS(numCPUs) } func TestNewWorker(t *testing.T) { pool := make(chan *worker) worker := newWorker(pool) worker.start() assert.NotNil(t, worker) worker = <-pool assert.NotNil(t, worker, "Worker should register itself to the pool") called := false done := make(chan bool) job := func() { called = true done <- true } worker.jobChannel <- job <-done assert.Equal(t, true, called) } func TestNewPool(t *testing.T) { pool := NewPool(1000, 10000) defer pool.Release() iterations := 1000000 pool.WaitCount(iterations) var counter uint64 = 0 for i := 0; i < iterations; i++ { arg := uint64(1) job := func() { defer pool.JobDone() atomic.AddUint64(&counter, arg) assert.Equal(t, uint64(1), arg) } pool.JobQueue <- job } pool.WaitAll() counterFinal := atomic.LoadUint64(&counter) assert.Equal(t, uint64(iterations), counterFinal) } func TestRelease(t *testing.T) { grNum := runtime.NumGoroutine() pool := NewPool(5, 10) //t.Log(runtime.NumCPU()) defer func() { pool.Release() // give some time for all goroutines to quit assert.Equal(t, grNum, runtime.NumGoroutine(), "All goroutines should be released after Release() call") }() pool.WaitCount(1000) for i := 0; i < 1000; i++ { job := func() { defer pool.JobDone() } pool.JobQueue <- job } t.Log(runtime.NumCPU()) pool.WaitAll() } func BenchmarkPool(b *testing.B) { // Testing with just 1 goroutine // to benchmark the non-parallel part of the code pool := NewPool(1, 10) defer pool.Release() log.SetOutput(ioutil.Discard) for n := 0; n < b.N; n++ { pool.JobQueue <- func() { log.Printf("I am worker! Number %d\n", n) } } } ================================================ FILE: src/github.com/dolotech/lib/pse/pse_darwin.go ================================================ // Copyright 2015-2016 Apcera Inc. All rights reserved. package pse import ( "fmt" "os" "os/exec" ) // ProcUsage returns CPU usage func ProcUsage(pcpu *float64, rss, vss *int64) error { pidStr := fmt.Sprintf("%d", os.Getpid()) out, err := exec.Command("ps", "o", "pcpu=,rss=,vsz=", "-p", pidStr).Output() if err != nil { *rss, *vss = -1, -1 return fmt.Errorf("ps call failed:%v", err) } fmt.Sscanf(string(out), "%f %d %d", pcpu, rss, vss) *rss *= 1024 // 1k blocks, want bytes. *vss *= 1024 // 1k blocks, want bytes. return nil } ================================================ FILE: src/github.com/dolotech/lib/pse/pse_freebsd.go ================================================ // Copyright 2015-2016 Apcera Inc. All rights reserved. package pse /* #include #include #include #include #include long pagetok(long size) { int pageshift, pagesize; pagesize = getpagesize(); pageshift = 0; while (pagesize > 1) { pageshift++; pagesize >>= 1; } return (size << pageshift); } int getusage(double *pcpu, unsigned int *rss, unsigned int *vss) { int mib[4], ret; size_t len; struct kinfo_proc kp; len = 4; sysctlnametomib("kern.proc.pid", mib, &len); mib[3] = getpid(); len = sizeof(kp); ret = sysctl(mib, 4, &kp, &len, NULL, 0); if (ret != 0) { return (errno); } *rss = pagetok(kp.ki_rssize); *vss = kp.ki_size; *pcpu = kp.ki_pctcpu; return 0; } */ import "C" import ( "syscall" ) // This is a placeholder for now. func ProcUsage(pcpu *float64, rss, vss *int64) error { var r, v C.uint var c C.double if ret := C.getusage(&c, &r, &v); ret != 0 { return syscall.Errno(ret) } *pcpu = float64(c) *rss = int64(r) *vss = int64(v) return nil } ================================================ FILE: src/github.com/dolotech/lib/pse/pse_linux.go ================================================ // Copyright 2015 Apcera Inc. All rights reserved. package pse import ( "bytes" "fmt" "io/ioutil" "os" "sync/atomic" "syscall" "time" ) var ( procStatFile string ticks int64 lastTotal int64 lastSeconds int64 ipcpu int64 ) const ( utimePos = 13 stimePos = 14 startPos = 21 vssPos = 22 rssPos = 23 ) func init() { // Avoiding to generate docker image without CGO ticks = 100 // int64(C.sysconf(C._SC_CLK_TCK)) procStatFile = fmt.Sprintf("/proc/%d/stat", os.Getpid()) periodic() } // Sampling function to keep pcpu relevant. func periodic() { contents, err := ioutil.ReadFile(procStatFile) if err != nil { return } fields := bytes.Fields(contents) // PCPU pstart := parseInt64(fields[startPos]) utime := parseInt64(fields[utimePos]) stime := parseInt64(fields[stimePos]) total := utime + stime var sysinfo syscall.Sysinfo_t if err := syscall.Sysinfo(&sysinfo); err != nil { return } seconds := int64(sysinfo.Uptime) - (pstart / ticks) // Save off temps lt := lastTotal ls := lastSeconds // Update last sample lastTotal = total lastSeconds = seconds // Adjust to current time window total -= lt seconds -= ls if seconds > 0 { atomic.StoreInt64(&ipcpu, (total*1000/ticks)/seconds) } time.AfterFunc(1*time.Second, periodic) } func ProcUsage(pcpu *float64, rss, vss *int64) error { contents, err := ioutil.ReadFile(procStatFile) if err != nil { return err } fields := bytes.Fields(contents) // Memory *rss = (parseInt64(fields[rssPos])) << 12 *vss = parseInt64(fields[vssPos]) // PCPU // We track this with periodic sampling, so just load and go. *pcpu = float64(atomic.LoadInt64(&ipcpu)) / 10.0 return nil } // Ascii numbers 0-9 const ( asciiZero = 48 asciiNine = 57 ) // parseInt64 expects decimal positive numbers. We // return -1 to signal error func parseInt64(d []byte) (n int64) { if len(d) == 0 { return -1 } for _, dec := range d { if dec < asciiZero || dec > asciiNine { return -1 } n = n*10 + (int64(dec) - asciiZero) } return n } ================================================ FILE: src/github.com/dolotech/lib/pse/pse_rumprun.go ================================================ // Copyright 2015-2016 Apcera Inc. All rights reserved. // +build rumprun package pse // This is a placeholder for now. func ProcUsage(pcpu *float64, rss, vss *int64) error { *pcpu = 0.0 *rss = 0 *vss = 0 return nil } ================================================ FILE: src/github.com/dolotech/lib/pse/pse_solaris.go ================================================ // Copyright 2015-2016 Apcera Inc. All rights reserved. package pse // This is a placeholder for now. func ProcUsage(pcpu *float64, rss, vss *int64) error { *pcpu = 0.0 *rss = 0 *vss = 0 return nil } ================================================ FILE: src/github.com/dolotech/lib/pse/pse_test.go ================================================ // Copyright 2015-2016 Apcera Inc. All rights reserved. package pse import ( "fmt" "os" "os/exec" "runtime" "testing" ) func TestPSEmulation(t *testing.T) { if runtime.GOOS == "windows" { t.Skipf("Skipping this test on Windows") } var rss, vss, psRss, psVss int64 var pcpu, psPcpu float64 runtime.GC() // PS version first pidStr := fmt.Sprintf("%d", os.Getpid()) out, err := exec.Command("ps", "o", "pcpu=,rss=,vsz=", "-p", pidStr).Output() if err != nil { t.Fatalf("Failed to execute ps command: %v\n", err) } fmt.Sscanf(string(out), "%f %d %d", &psPcpu, &psRss, &psVss) psRss *= 1024 // 1k blocks, want bytes. psVss *= 1024 // 1k blocks, want bytes. runtime.GC() // Our internal version ProcUsage(&pcpu, &rss, &vss) if pcpu != psPcpu { delta := int64(pcpu - psPcpu) if delta < 0 { delta = -delta } if delta > 30 { // 30%? t.Fatalf("CPUs did not match close enough: %f vs %f", pcpu, psPcpu) } } if rss != psRss { delta := rss - psRss if delta < 0 { delta = -delta } if delta > 1024*1024 { // 1MB t.Fatalf("RSSs did not match close enough: %d vs %d", rss, psRss) } } } ================================================ FILE: src/github.com/dolotech/lib/pse/pse_windows.go ================================================ // Copyright 2015-2016 Apcera Inc. All rights reserved. // +build windows package pse import ( "fmt" "os" "path/filepath" "strings" "sync" "syscall" "time" "unsafe" ) var ( pdh = syscall.NewLazyDLL("pdh.dll") winPdhOpenQuery = pdh.NewProc("PdhOpenQuery") winPdhAddCounter = pdh.NewProc("PdhAddCounterW") winPdhCollectQueryData = pdh.NewProc("PdhCollectQueryData") winPdhGetFormattedCounterValue = pdh.NewProc("PdhGetFormattedCounterValue") winPdhGetFormattedCounterArray = pdh.NewProc("PdhGetFormattedCounterArrayW") ) // global performance counter query handle and counters var ( pcHandle PDH_HQUERY pidCounter, cpuCounter, rssCounter, vssCounter PDH_HCOUNTER prevCPU float64 prevRss int64 prevVss int64 lastSampleTime time.Time processPid int pcQueryLock sync.Mutex initialSample = true ) // maxQuerySize is the number of values to return from a query. // It represents the maximum # of servers that can be queried // simultaneously running on a machine. const maxQuerySize = 512 // Keep static memory around to reuse; this works best for passing // into the pdh API. var counterResults [maxQuerySize]PDH_FMT_COUNTERVALUE_ITEM_DOUBLE // PDH Types type ( PDH_HQUERY syscall.Handle PDH_HCOUNTER syscall.Handle ) // PDH constants used here const ( PDH_FMT_DOUBLE = 0x00000200 PDH_INVALID_DATA = 0xC0000BC6 PDH_MORE_DATA = 0x800007D2 ) // PDH_FMT_COUNTERVALUE_DOUBLE - double value type PDH_FMT_COUNTERVALUE_DOUBLE struct { CStatus uint32 DoubleValue float64 } // PDH_FMT_COUNTERVALUE_ITEM_DOUBLE is an array // element of a double value type PDH_FMT_COUNTERVALUE_ITEM_DOUBLE struct { SzName *uint16 // pointer to a string FmtValue PDH_FMT_COUNTERVALUE_DOUBLE } func pdhAddCounter(hQuery PDH_HQUERY, szFullCounterPath string, dwUserData uintptr, phCounter *PDH_HCOUNTER) error { ptxt, _ := syscall.UTF16PtrFromString(szFullCounterPath) r0, _, _ := winPdhAddCounter.Call( uintptr(hQuery), uintptr(unsafe.Pointer(ptxt)), dwUserData, uintptr(unsafe.Pointer(phCounter))) if r0 != 0 { return fmt.Errorf("pdhAddCounter failed. %d", r0) } return nil } func pdhOpenQuery(datasrc *uint16, userdata uint32, query *PDH_HQUERY) error { r0, _, _ := syscall.Syscall(winPdhOpenQuery.Addr(), 3, 0, uintptr(userdata), uintptr(unsafe.Pointer(query))) if r0 != 0 { return fmt.Errorf("pdhOpenQuery failed - %d", r0) } return nil } func pdhCollectQueryData(hQuery PDH_HQUERY) error { r0, _, _ := winPdhCollectQueryData.Call(uintptr(hQuery)) if r0 != 0 { return fmt.Errorf("pdhCollectQueryData failed - %d", r0) } return nil } // pdhGetFormattedCounterArrayDouble returns the value of return code // rather than error, to easily check return codes func pdhGetFormattedCounterArrayDouble(hCounter PDH_HCOUNTER, lpdwBufferSize *uint32, lpdwBufferCount *uint32, itemBuffer *PDH_FMT_COUNTERVALUE_ITEM_DOUBLE) uint32 { ret, _, _ := winPdhGetFormattedCounterArray.Call( uintptr(hCounter), uintptr(PDH_FMT_DOUBLE), uintptr(unsafe.Pointer(lpdwBufferSize)), uintptr(unsafe.Pointer(lpdwBufferCount)), uintptr(unsafe.Pointer(itemBuffer))) return uint32(ret) } func getCounterArrayData(counter PDH_HCOUNTER) ([]float64, error) { var bufSize uint32 var bufCount uint32 // Retrieving array data requires two calls, the first which // requires an addressable empty buffer, and sets size fields. // The second call returns the data. initialBuf := make([]PDH_FMT_COUNTERVALUE_ITEM_DOUBLE, 1) ret := pdhGetFormattedCounterArrayDouble(counter, &bufSize, &bufCount, &initialBuf[0]) if ret == PDH_MORE_DATA { // we'll likely never get here, but be safe. if bufCount > maxQuerySize { bufCount = maxQuerySize } ret = pdhGetFormattedCounterArrayDouble(counter, &bufSize, &bufCount, &counterResults[0]) if ret == 0 { rv := make([]float64, bufCount) for i := 0; i < int(bufCount); i++ { rv[i] = counterResults[i].FmtValue.DoubleValue } return rv, nil } } if ret != 0 { return nil, fmt.Errorf("getCounterArrayData failed - %d", ret) } return nil, nil } // getProcessImageName returns the name of the process image, as expected by // the performance counter API. func getProcessImageName() (name string) { name = filepath.Base(os.Args[0]) name = strings.TrimRight(name, ".exe") return } // initialize our counters func initCounters() (err error) { processPid = os.Getpid() // require an addressible nil pointer var source uint16 if err := pdhOpenQuery(&source, 0, &pcHandle); err != nil { return err } // setup the performance counters, search for all server instances name := fmt.Sprintf("%s*", getProcessImageName()) pidQuery := fmt.Sprintf("\\Process(%s)\\ID Process", name) cpuQuery := fmt.Sprintf("\\Process(%s)\\%% Processor Time", name) rssQuery := fmt.Sprintf("\\Process(%s)\\Working Set - Private", name) vssQuery := fmt.Sprintf("\\Process(%s)\\Virtual Bytes", name) if err = pdhAddCounter(pcHandle, pidQuery, 0, &pidCounter); err != nil { return err } if err = pdhAddCounter(pcHandle, cpuQuery, 0, &cpuCounter); err != nil { return err } if err = pdhAddCounter(pcHandle, rssQuery, 0, &rssCounter); err != nil { return err } if err = pdhAddCounter(pcHandle, vssQuery, 0, &vssCounter); err != nil { return err } // prime the counters by collecting once, and sleep to get somewhat // useful information the first request. Counters for the CPU require // at least two collect calls. if err = pdhCollectQueryData(pcHandle); err != nil { return err } time.Sleep(50) return nil } // ProcUsage returns process CPU and memory statistics func ProcUsage(pcpu *float64, rss, vss *int64) error { var err error // For simplicity, protect the entire call. // Most simultaneous requests will immediately return // with cached values. pcQueryLock.Lock() defer pcQueryLock.Unlock() // First time through, initialize counters. if initialSample { if err = initCounters(); err != nil { return err } initialSample = false } else if time.Since(lastSampleTime) < (2 * time.Second) { // only refresh every two seconds as to minimize impact // on the server. *pcpu = prevCPU *rss = prevRss *vss = prevVss return nil } // always save the sample time, even on errors. defer func() { lastSampleTime = time.Now() }() // refresh the performance counter data if err = pdhCollectQueryData(pcHandle); err != nil { return err } // retrieve the data var pidAry, cpuAry, rssAry, vssAry []float64 if pidAry, err = getCounterArrayData(pidCounter); err != nil { return err } if cpuAry, err = getCounterArrayData(cpuCounter); err != nil { return err } if rssAry, err = getCounterArrayData(rssCounter); err != nil { return err } if vssAry, err = getCounterArrayData(vssCounter); err != nil { return err } // find the index of the entry for this process idx := int(-1) for i := range pidAry { if int(pidAry[i]) == processPid { idx = i break } } // no pid found... if idx < 0 { return fmt.Errorf("could not find pid in performance counter results") } // assign values from the performance counters *pcpu = cpuAry[idx] *rss = int64(rssAry[idx]) *vss = int64(vssAry[idx]) // save off cache values prevCPU = *pcpu prevRss = *rss prevVss = *vss return nil } ================================================ FILE: src/github.com/dolotech/lib/pse/pse_windows_test.go ================================================ // Copyright 2016 Apcera Inc. All rights reserved. // +build windows package pse import ( "fmt" "os/exec" "runtime" "strconv" "strings" "testing" ) func checkValues(t *testing.T, pcpu, tPcpu float64, rss, tRss int64) { if pcpu != tPcpu { delta := int64(pcpu - tPcpu) if delta < 0 { delta = -delta } if delta > 30 { // 30%? t.Fatalf("CPUs did not match close enough: %f vs %f", pcpu, tPcpu) } } if rss != tRss { delta := rss - tRss if delta < 0 { delta = -delta } if delta > 1024*1024 { // 1MB t.Fatalf("RSSs did not match close enough: %d vs %d", rss, tRss) } } } func TestPSEmulationWin(t *testing.T) { var pcpu, tPcpu float64 var rss, vss, tRss int64 runtime.GC() if err := ProcUsage(&pcpu, &rss, &vss); err != nil { t.Fatalf("Error: %v", err) } runtime.GC() imageName := getProcessImageName() // query the counters using typeperf out, err := exec.Command("typeperf.exe", fmt.Sprintf("\\Process(%s)\\%% Processor Time", imageName), fmt.Sprintf("\\Process(%s)\\Working Set - Private", imageName), fmt.Sprintf("\\Process(%s)\\Virtual Bytes", imageName), "-sc", "1").Output() if err != nil { t.Fatal("unable to run command", err) } // parse out results - refer to comments in procUsage for detail results := strings.Split(string(out), "\r\n") values := strings.Split(results[2], ",") // parse pcpu tPcpu, err = strconv.ParseFloat(strings.Trim(values[1], "\""), 64) if err != nil { t.Fatalf("Unable to parse percent cpu: %s", values[1]) } // parse private bytes (rss) fval, err := strconv.ParseFloat(strings.Trim(values[2], "\""), 64) if err != nil { t.Fatalf("Unable to parse private bytes: %s", values[2]) } tRss = int64(fval) checkValues(t, pcpu, tPcpu, rss, tRss) runtime.GC() // Again to test caching if err = ProcUsage(&pcpu, &rss, &vss); err != nil { t.Fatalf("Error: %v", err) } checkValues(t, pcpu, tPcpu, rss, tRss) } ================================================ FILE: src/github.com/dolotech/lib/route/route_msg.go ================================================ package route import ( "reflect" "github.com/golang/glog" ) type Route map[string]*reflect.Value func (this *Route) Emit(msg interface{}, arg ...interface{}) { if *this != nil { msgID := reflect.TypeOf(msg).Elem().Name() if f, ok := (*this)[msgID]; ok { array := make([]reflect.Value, len(arg)+1) array[0] = reflect.ValueOf(msg) for i := 0; i < len(arg); i++ { array[i+1] = reflect.ValueOf(arg[i]) } f.Call(array) } } } func (this *Route) Regist(msg, f interface{}) { if *this == nil { *this = make(map[string]*reflect.Value, 18) } msgType := reflect.TypeOf(msg) if msgType == nil || msgType.Kind() != reflect.Ptr { glog.Error("message pointer required") } msgID := msgType.Elem().Name() if msgID == "" { glog.Error("unnamed message") } if _, ok := (*this)[msgID]; ok { glog.Errorf("message %v is already registered", msgID) } v := reflect.ValueOf(f) (*this)[msgID] = &v } ================================================ FILE: src/github.com/dolotech/lib/route/router_test.go ================================================ package route import "testing" func TestNewRoute(t *testing.T) { var r Route type msg struct { N int } r.Regist(&msg{}, func(m *msg) {t.Log("callback",m)}) r.Emit(&msg{123}) r.Emit(&msg{123}) } ================================================ FILE: src/github.com/dolotech/lib/utils/aes.go ================================================ package utils import ( "crypto/aes" "crypto/cipher" "errors" ) //type AesEncrypt struct { // Key []byte //} func SetKey(key []byte) ([]byte,error){ keyLen := len(key) if keyLen < 16 { //panic("res key 长度不能小于16") return nil,errors.New("res key 长度不能小于16") } if keyLen >= 32 { //取前32个字节 return key[:32],nil } if keyLen >= 24 { //取前24个字节 return key[:24],nil } //取前16个字节 return key[:16],nil } //加密字符串 func AesEncrypt(key []byte,strMesg []byte) ([]byte, error) { key,err:= SetKey(key) encrypted := make([]byte, len(strMesg)) if err!= nil{ return encrypted,err } var iv = key[:aes.BlockSize] aesBlockEncrypter, err := aes.NewCipher(key) if err != nil { return nil, err } aesEncrypter := cipher.NewCFBEncrypter(aesBlockEncrypter, iv) aesEncrypter.XORKeyStream(encrypted, strMesg) return encrypted, nil } //解密字符串 func AesDecrypt(key []byte,src []byte) (strDesc []byte, err error) { key,err= SetKey(key) if err!= nil{ return } var iv = key[:aes.BlockSize] decrypted := make([]byte, len(src)) var aesBlockDecrypter cipher.Block aesBlockDecrypter, err = aes.NewCipher(key) if err != nil { return } aesDecrypter := cipher.NewCFBDecrypter(aesBlockDecrypter, iv) aesDecrypter.XORKeyStream(decrypted, src) return decrypted,err } ================================================ FILE: src/github.com/dolotech/lib/utils/debug.go ================================================ /********************************************************** * Author : Michael * Email : dolotech@163.com * Last modified : 2016-04-30 09:40 * Filename : debug.go * Description : * *******************************************************/ package utils import ( "fmt" "reflect" "strconv" "github.com/golang/glog" ) type variable struct { // Output dump string Out string // Indent counter indent int64 } func (v *variable) dump(val reflect.Value, name string) { v.indent++ if val.IsValid() && val.CanInterface() { typ := val.Type() switch typ.Kind() { case reflect.Array, reflect.Slice: v.printType(name, val.Interface()) l := val.Len() for i := 0; i < l; i++ { v.dump(val.Index(i), strconv.Itoa(i)) } case reflect.Map: v.printType(name, val.Interface()) //l := val.Len() keys := val.MapKeys() for _, k := range keys { v.dump(val.MapIndex(k), k.Interface().(string)) } case reflect.Ptr: v.printType(name, val.Interface()) v.dump(val.Elem(), name) case reflect.Struct: v.printType(name, val.Interface()) for i := 0; i < typ.NumField(); i++ { field := typ.Field(i) v.dump(val.FieldByIndex([]int{i}), field.Name) } default: v.printValue(name, val.Interface()) } } else { v.printValue(name, "") } v.indent-- } func (v *variable) printType(name string, vv interface{}) { v.printIndent() v.Out = fmt.Sprintf("%s%s(%T)\n", v.Out, name, vv) } func (v *variable) printValue(name string, vv interface{}) { v.printIndent() v.Out = fmt.Sprintf("%s%s(%T) %#v\n", v.Out, name, vv, vv) } func (v *variable) printIndent() { var i int64 for i = 0; i < v.indent; i++ { v.Out = fmt.Sprintf("%s ", v.Out) } } // Print to standard out the value that is passed as the argument with indentation. // Pointers are dereferenced. func Dump(v interface{}) { val := reflect.ValueOf(v) dump := &variable{indent: -1} dump.dump(val, "") glog.Infof("%s", dump.Out) } // Return the value that is passed as the argument with indentation. // Pointers are dereferenced. func Sdump(v interface{}) string { val := reflect.ValueOf(v) dump := &variable{indent: -1} dump.dump(val, "") return dump.Out } ================================================ FILE: src/github.com/dolotech/lib/utils/helper.go ================================================ package utils import ( "runtime" "runtime/debug" "time" "fmt" "strconv" ) var startTime = time.Now() func avg(items []time.Duration) time.Duration { var sum time.Duration for _, item := range items { sum += item } return time.Duration(int64(sum) / int64(len(items))) } func toH(bytes uint64) string { switch { case bytes < 1024: return fmt.Sprintf("%dB", bytes) case bytes < 1024*1024: return fmt.Sprintf("%.2fK", float64(bytes)/1024) case bytes < 1024*1024*1024: return fmt.Sprintf("%.2fM", float64(bytes)/1024/1024) default: return fmt.Sprintf("%.2fG", float64(bytes)/1024/1024/1024) } } func toS(d time.Duration) string { u := uint64(d) if u < uint64(time.Second) { switch { case u == 0: return "0" case u < uint64(time.Microsecond): return fmt.Sprintf("%.2fns", float64(u)) case u < uint64(time.Millisecond): return fmt.Sprintf("%.2fus", float64(u)/1000) default: return fmt.Sprintf("%.2fms", float64(u)/1000/1000) } } else { switch { case u < uint64(time.Minute): return fmt.Sprintf("%.2fs", float64(u)/1000/1000/1000) case u < uint64(time.Hour): return fmt.Sprintf("%.2fm", float64(u)/1000/1000/1000/60) default: return fmt.Sprintf("%.2fh", float64(u)/1000/1000/1000/60/60) } } } func printGC(memStats *runtime.MemStats, gcstats *debug.GCStats) string { if gcstats.NumGC > 0 { lastPause := gcstats.Pause[0] elapsed := time.Now().Sub(startTime) overhead := float64(gcstats.PauseTotal) / float64(elapsed) * 100 allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds() return fmt.Sprintf("NumGC:%d Pause:%s Pause(Avg):%s Overhead:%3.2f%% Alloc:%s Sys:%s Alloc(Rate):%s/s Histogram:%s %s %s \n", gcstats.NumGC, toS(lastPause), toS(avg(gcstats.Pause)), overhead, toH(memStats.Alloc), toH(memStats.Sys), toH(uint64(allocatedRate)), toS(gcstats.PauseQuantiles[94]), toS(gcstats.PauseQuantiles[98]), toS(gcstats.PauseQuantiles[99])) } else { elapsed := time.Now().Sub(startTime) allocatedRate := float64(memStats.TotalAlloc) / elapsed.Seconds() return fmt.Sprintf("Alloc:%s Sys:%s Alloc(Rate):%s/s\n", toH(memStats.Alloc), toH(memStats.Sys), toH(uint64(allocatedRate))) } } func GCSummary() string { memStats := &runtime.MemStats{} runtime.ReadMemStats(memStats) gcstats := &debug.GCStats{PauseQuantiles: make([]time.Duration, 100)} debug.ReadGCStats(gcstats) return printGC(memStats, gcstats) +"NumGoroutine: "+ strconv.Itoa(runtime.NumGoroutine()) } ================================================ FILE: src/github.com/dolotech/lib/utils/list.go ================================================ // 线程安全的数组封装,注意:写锁接口不能嵌套调用,比如:Range接口不能调用删除接口Del package utils import ( "sync" ) func NewList() *List { return &List{elems: make([]interface{}, 0)} } type List struct { sync.RWMutex elems []interface{} } func (this *List) Get(f func(interface{}) bool) interface{} { this.RLock() defer this.RUnlock() for _, v := range this.elems { if f(v) { return v } } return nil } func (this *List) Add(value interface{}) { this.Lock() defer this.Unlock() this.elems = append(this.elems, value) } func (this *List) Pure() { this.Lock() defer this.Unlock() this.elems = this.elems[:0] } func (this *List) Del(value interface{}) { this.Lock() defer this.Unlock() for k, v := range this.elems { if value == v { this.elems = append(this.elems[:k], this.elems[k+1:]...) break } } } func (this *List) Delete(f func(interface{}) bool) { this.Lock() defer this.Unlock() for k, v := range this.elems { if f(v) { this.elems = append(this.elems[:k], this.elems[k+1:]...) break } } } func (this *List) Len() int { this.RLock() defer this.RUnlock() return len(this.elems) } func (this *List) Replace(value interface{}, f func(interface{}) bool) { this.RLock() defer this.RUnlock() for k, v := range this.elems { if f(v) { this.elems = append(this.elems[:k], this.elems[k+1:]...) this.elems = append(this.elems, value) break } } } func (this *List) Range(f func(interface{}) bool) { this.RLock() defer this.RUnlock() for _, v := range this.elems { if f(v) { break } } } func (this *List) LRange(f func(interface{}) bool) { this.Lock() defer this.Unlock() for _, v := range this.elems { if f(v) { break } } } ================================================ FILE: src/github.com/dolotech/lib/utils/map.go ================================================ package utils import ( "sync" ) func NewMap() *Map { return &Map{elems: map[interface{}]interface{}{}} } type Map struct { sync.RWMutex elems map[interface{}]interface{} } func (this *Map) Get(key interface{}) interface{} { this.RLock() defer this.RUnlock() if value, ok := this.elems[key]; ok { return value } else { return nil } } func (this *Map) Set(key interface{}, value interface{}) { this.Lock() defer this.Unlock() this.elems[key] = value } func (this *Map) Del(key interface{}) { this.Lock() defer this.Unlock() delete(this.elems, key) } func (this *Map) Len() int { this.RLock() defer this.RUnlock() return len(this.elems) } func (this *Map) Range(f func(interface{}, interface{}) bool) { this.RLock() defer this.RUnlock() for k, v := range this.elems { if f(k, v) { break } } } func (this *Map) LRange(f func(interface{}, interface{}) bool) { this.Lock() defer this.Unlock() for k, v := range this.elems { if f(k, v) { break } } } ================================================ FILE: src/github.com/dolotech/lib/utils/map_list_test.go ================================================ /** * Created by Michael on 2015/8/4. */ package utils import "testing" func Test_ran(t *testing.T) { list := &List{} t.Log(list) //m := NewMap() } ================================================ FILE: src/github.com/dolotech/lib/utils/queue.go ================================================ package utils type Queue struct { elems []interface{} nelems, popi, pushi int } func (q *Queue) Len() int { return q.nelems } func (q *Queue) Push(elem interface{}) { if q.nelems == len(q.elems) { q.expand() } q.elems[q.pushi] = elem q.nelems++ q.pushi = (q.pushi + 1) % len(q.elems) } func (q *Queue) Pop() (elem interface{}) { if q.nelems == 0 { return nil } elem = q.elems[q.popi] q.elems[q.popi] = nil // Help GC. q.nelems-- q.popi = (q.popi + 1) % len(q.elems) return elem } func (q *Queue) expand() { curcap := len(q.elems) var newcap int if curcap == 0 { newcap = 8 } else if curcap < 1024 { newcap = curcap * 2 } else { newcap = curcap + (curcap / 4) } elems := make([]interface{}, newcap) if q.popi == 0 { copy(elems, q.elems) q.pushi = curcap } else { newpopi := newcap - (curcap - q.popi) copy(elems, q.elems[:q.popi]) copy(elems[newpopi:], q.elems[q.popi:]) q.popi = newpopi } for i := range q.elems { q.elems[i] = nil // Help GC. } q.elems = elems } ================================================ FILE: src/github.com/dolotech/lib/utils/random.go ================================================ package utils import ( "math/rand" "time" "sync" //crand "crypto/rand" ) var o *rand.Rand = rand.New(rand.NewSource(TimestampNano())) var random_mux_ sync.Mutex func RandInt64() (r int64) { random_mux_.Lock() defer random_mux_.Unlock() return (o.Int63()) } func RandInt32() (r int32) { random_mux_.Lock() defer random_mux_.Unlock() return (o.Int31()) } func RandUint32() (r uint32) { random_mux_.Lock() defer random_mux_.Unlock() return (o.Uint32()) } func RandInt64N(n int64) (r int64) { random_mux_.Lock() defer random_mux_.Unlock() return (o.Int63n(n)) } func RandInt32N(n int32) (r int32) { random_mux_.Lock() defer random_mux_.Unlock() return (o.Int31n(n)) } var randomChan chan uint32 func randUint32() { randomChan = make(chan uint32, 1024) go func() { var numstr uint32 for { numstr = RandUint32() select { case randomChan <- numstr: } <-time.After(time.Millisecond * 100) } }() } func GetRandUint32() uint32 { return <-randomChan } func init() { rand.Seed(time.Now().UTC().UnixNano()) } var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") func RandomString(length int) string { //rand.Seed(time.Now().UTC().UnixNano()) b := make([]rune, length) for i := range b { b[i] = letters[rand.Intn(len(letters))] } return string(b) } var letters_ = []rune("ABCDEFGHIJKLMNPQRSTUVWXYZ123456789") func RandomString_(length int) string { //rand.Seed(time.Now().UTC().UnixNano()) b := make([]rune, length) for i := range b { b[i] = letters_[rand.Intn(len(letters_))] } return string(b) } ================================================ FILE: src/github.com/dolotech/lib/utils/sign.go ================================================ package utils import ( "crypto/md5" "encoding/hex" "fmt" "sort" "strings" ) //生成签名 func LoginSign(gameid string, device string) (string, error) { parra := fmt.Sprintf("gameid=%s&deviceId=%s", gameid, device) parameters := strings.Split(parra, "&") sort_parameters := sort.StringSlice(parameters) sort.Sort(sort_parameters) parameter := "" for i := 0; i < len(sort_parameters); i++ { parameter += "&" + sort_parameters[i] } parameter = string([]byte(parameter)[1:]) h := md5.New() _, err := h.Write([]byte(parameter + "&key=" + "19a87399fde1bccbf04a5eaa018ea0df")) if err != nil { return "", err } return strings.ToUpper(hex.EncodeToString(h.Sum(nil))), nil } ================================================ FILE: src/github.com/dolotech/lib/utils/stack.go ================================================ package utils import ( "runtime" "github.com/davecgh/go-spew/spew" "github.com/golang/glog" ) // 产生panic时的调用栈打印 func PrintPanicStack(extras ...interface{}) interface{}{ if x := recover(); x != nil { glog.Errorln(x) i := 0 funcName, file, line, ok := runtime.Caller(i) for ok { glog.Errorf("frame %v:[func:%v,file:%v,line:%v]\n", i, runtime.FuncForPC(funcName).Name(), file, line) i++ funcName, file, line, ok = runtime.Caller(i) } for k := range extras { glog.Errorf("EXRAS#%v DATA:%v\n", k, spew.Sdump(extras[k])) } return x } return nil } ================================================ FILE: src/github.com/dolotech/lib/utils/string_2_bytes.go ================================================ package utils import ( "unsafe" "reflect" ) func String2Bytes(s string) (b []byte) { pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) pbytes.Data = pstring.Data pbytes.Len = pstring.Len pbytes.Cap = pstring.Len return } func Bytes2String(b []byte) (s string) { pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b)) pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) pstring.Data = pbytes.Data pstring.Len = pbytes.Len return } ================================================ FILE: src/github.com/dolotech/lib/utils/string_2_bytes_test.go ================================================ package utils import ( "testing" ) /*func BenchmarkBytes2String(t *testing.B) { for i := 1; i < N; i++ { b := []byte("34asdfasdfasdfasdfasdfasdfasdfasdf12") t.Log(Bytes2String(b)) } }*/ func BenchmarkTestString2Bytes(t *testing.B) { for i := 1; i < N; i++ { b := "34asdfasdfasdfasdfasdfasdfasdfasdf12" t.Log(Bytes2String(String2Bytes(b))) } } const N = 30000 /*func BenchmarkBytes2String1(t *testing.B) { for i := 1; i < N; i++ { b := []byte("34asdfasdfasdfasdfasdfasdfasdfasdf12") t.Log(Bytes2String(b)) } }*/ func BenchmarkTestString2Bytes1(t *testing.B) { for i := 1; i < N; i++ { b := "34asdfasdfasdfasdfasdfasdfasdfasdf12" t.Log(string([]byte(b))) } } ================================================ FILE: src/github.com/dolotech/lib/utils/structandmap.go ================================================ package utils import ( "errors" "reflect" ) func ToM(value interface{}) map[string]interface{} { if value == nil{ return nil } v := reflect.ValueOf(value) if v.Kind() == reflect.Ptr { v = v.Elem() value = v.Interface() v = reflect.ValueOf(value) } t := reflect.TypeOf(value) var data = make(map[string]interface{}) for i := 0; i < t.NumField(); i++ { data[t.Field(i).Name] = v.Field(i).Interface() } return data } // func ToMs(values []interface{}) []interface{} { list:= make([]interface{},len(values)) l:= len(values) for i:=0;i 0 { tmp := this.tq[0] if tmp.end <= now { timer := heap.Pop(&this.tq).(*Timer) queue.Push(timer.TimeOuter) if timer.interval > 0 { timer.end += timer.interval heap.Push(&this.tq, timer) } } else { break } if limit > 0 && queue.Len() >= limit { break } } for queue.Len() > 0 { queue.Pop().(TimeOuter).TimeOut(now) } } func (this *TimerManager) dump() { queue := &Queue{} for len(this.tq) > 0 { timer := heap.Pop(&this.tq).(*Timer) queue.Push(timer) println("Timer:", timer.id, timer.index, timer.end, timer.interval) } for queue.Len() > 0 { heap.Push(&this.tq, queue.Pop().(*Timer)) } } ================================================ FILE: src/github.com/dolotech/lib/utils/utils.go ================================================ /********************************************************** * Author : Michael * Email : dolotech@163.com * Last modified : 2016-04-30 09:40 * Filename : utils.go * Description : 常用的工具方法 * *******************************************************/ package utils import ( "bytes" "crypto/md5" "encoding/binary" "encoding/gob" "encoding/hex" "fmt" "github.com/golang/glog" "math" "math/rand" "net" "regexp" "strconv" "strings" "time" "unicode/utf8" ) // Auth func GetAuth() []rune { r := rand.New(rand.NewSource(time.Now().UnixNano())) var list []rune for i := 0; i < 6; i++ { ran := r.Intn(122-97+1) + 97 list = append(list, rune(ran)) } return list } // 验证是否邮箱 func EmailRegexp(mail string) bool { b := false if mail != "" { reg := regexp.MustCompile(`^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)$`) b = reg.FindString(mail) != "" } return b } // 验证是否手机 func PhoneRegexp(phone string) bool { b := false if phone != "" { reg := regexp.MustCompile(`^(86)*0*1\d{10}$`) b = reg.FindString(phone) != "" } return b } // 验证账号是否合法 func AccountRegexp(account string) bool { b := false if account != "" { reg := regexp.MustCompile(`^[a-zA-Z0-9]{6,8}$`) b = reg.FindString(account) != "" } return b } // 数值类型转成点分结构的IP地址 // eg: t.Log((InetTontoa(3232235966).String())) func InetTontoa(ipnr uint32) string { var bytes [4]byte bytes[0] = byte(ipnr & 0xFF) bytes[1] = byte((ipnr >> 8) & 0xFF) bytes[2] = byte((ipnr >> 16) & 0xFF) bytes[3] = byte((ipnr >> 24) & 0xFF) return net.IPv4(bytes[3], bytes[2], bytes[1], bytes[0]).String() } // 点分结构的IP地址转成数值类型 // eg: t.Log((InetToaton("192.168.1.190"))) func InetToaton(ipnr string) uint32 { bits := strings.Split(ipnr, ".") b0, _ := strconv.Atoi(bits[0]) b1, _ := strconv.Atoi(bits[1]) b2, _ := strconv.Atoi(bits[2]) b3, _ := strconv.Atoi(bits[3]) var sum uint32 sum += uint32(b0) << 24 sum += uint32(b1) << 16 sum += uint32(b2) << 8 sum += uint32(b3) return sum } // 验证只能由数字字母下划线组成的5-17位密码字符串 func AalidataPwd(name string) (b bool) { if name != "" { //reg := regexp.MustCompile(`^[a-zA-Z0-9_]*$`) reg := regexp.MustCompile(`^[a-zA-Z_]\w{5,17}$`) b = reg.FindString(name) != "" } return } // 不可见字符,用于用户提交的字符过滤分别对应为:,\0 \t _ space " ` ctrl+z \n \r ` % \ , var IllegalNameRune = [13]rune{0x00, 0x09, 0x5f, 0x20, 0x22, 0x60, 0x1a, 0x0a, 0x0d, 0x27, 0x25, 0x5c, 0x2c} var hasIllegalNameRune = func(c rune) bool { for _, v := range IllegalNameRune { if v == c { return true } } return false } // 限制最大字符数,检测不可见字符 // maxcount 限制的最大字符数,1个中文=2个英文 func LegalName(name string, maxcount int) bool { if !utf8.ValidString(name) { return false } num := len([]rune(name)) + len([]byte(name)) result := float64(num) / 4.0 sum := int(result + 0.99) if sum > maxcount*2 { return false } return strings.IndexFunc(name, hasIllegalNameRune) == -1 } /** * 截取字符串 * @param string str * @param begin int * @param length int * @return int 长度 */ func SubStr(str string, begin, length int) (substr string) { // 将字符串的转换成[]rune rs := []rune(str) lth := len(rs) // 简单的越界判断 if begin < 0 { begin = 0 } if begin >= lth { begin = lth } end := begin + length if end > lth { end = lth } // 返回子串 return string(rs[begin:end]) } //整形转换成字节 func IntToBytes(n int) []byte { x := int32(n) bytesBuffer := bytes.NewBuffer([]byte{}) binary.Write(bytesBuffer, binary.BigEndian, x) return bytesBuffer.Bytes() } //字节转换成整形 func BytesToInt(b []byte) int { bytesBuffer := bytes.NewBuffer(b) var x int32 binary.Read(bytesBuffer, binary.BigEndian, &x) return int(x) } //整形转换成字节 func Int64ToBytes(n int64) []byte { x := int64(n) bytesBuffer := bytes.NewBuffer([]byte{}) binary.Write(bytesBuffer, binary.BigEndian, x) return bytesBuffer.Bytes() } //字节转换成整形 func BytesToInt64(b []byte) int64 { bytesBuffer := bytes.NewBuffer(b) var x int64 binary.Read(bytesBuffer, binary.BigEndian, &x) return int64(x) } //切片中字符串第一个位置 func SliceIndexOf(arr []string, str string) int { var index int = -1 arrlen := len(arr) for i := 0; i < arrlen; i++ { if arr[i] == str { index = i break } } return index } //字节转换成整形 func SliceLastIndexOf(arr []string, str string) int { var index int = -1 for arrlen := len(arr) - 1; arrlen > -1; arrlen-- { if arr[arrlen] == str { index = arrlen break } } return index } //字节转换成整形 func SliceRemoveFormSlice(oriArr []string, removeArr []string) []string { endArr := oriArr[:] for _, value := range removeArr { index := SliceIndexOf(endArr, value) if index != -1 { endArr = append(endArr[:index], endArr[index+1:]...) } } return endArr } // 把时间戳转换成头像存储目录 func TimeToHeadphpoto(t int64, userid int, headname int64) (string, string) { var str, name string ti := time.Unix(t, 0) str = ti.Format("2006/01/02/15") str = "./headpic/" + str + "/" + strconv.Itoa(userid) if headname == 0 { name = "/130_" + strconv.Itoa(userid) + ".jpg" } else { name = "/" + strconv.Itoa(int(headname)) + ".jpg" } return str, name } // 把时间戳转换成头像存储目录 func TimeToPhpotoPath(t int64, userid int) string { var str string ti := time.Unix(t, 0) str = ti.Format("2006/01/02/15") return "./photo/" + str + "/" + strconv.Itoa(userid) } func UseridCovToInvate(userid string) uint32 { useridbyte := []byte(userid) useridbyte = useridbyte[len(useridbyte)-4:] timestr := []byte(strconv.Itoa(int(time.Now().Unix()))) timestr = timestr[len(timestr)-5:] useridbyte = append(useridbyte, timestr...) code, _ := strconv.Atoi(string(useridbyte)) return uint32(code) } var base = []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"} var flipbase = flip(base) var baselen = len(base) func Base62encode(num uint64) string { baseStr := "" for { if num <= 0 { break } i := num % uint64(baselen) baseStr += base[i] num = (num - i) / uint64(baselen) } return baseStr } func Base62decode(base62 string) uint64 { var rs uint64 = 0 len := uint64(len(base62)) var i uint64 for i = 0; i < len; i++ { rs += flipbase[string(base62[i])] * uint64(math.Pow(float64(baselen), float64(i))) } return rs } func flip(s []string) map[string]uint64 { f := make(map[string]uint64) for index, value := range s { f[value] = uint64(index) } return f } // 用gob进行数据编码 func Encode(data interface{}) ([]byte, error) { buf := bytes.NewBuffer(nil) enc := gob.NewEncoder(buf) err := enc.Encode(data) if err != nil { return nil, err } return buf.Bytes(), nil } // 用gob进行数据解码 // func Decode(data []byte, to interface{}) error { buf := bytes.NewBuffer(data) dec := gob.NewDecoder(buf) return dec.Decode(to) } // 对象深度拷贝 func Clone(dst, src interface{}) error { var buf bytes.Buffer if err := gob.NewEncoder(&buf).Encode(src); err != nil { return err } return gob.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(dst) } //----------------------一下几个函数只对数字字符串有效---------------------------- func IsNumString(str string) bool { runeArr := []rune(str) for i := 0; i < len(runeArr); i++ { if runeArr[i] > 56 { return false } else if runeArr[i] < 48 { return false } } return true } func Between(startid, endid string) []string { if startid == endid { return []string{startid} } ids := []string{} if len(startid) > len(endid) { return ids } start := []rune(startid) end := []rune(endid) for i := 0; i < len(start); i++ { if int(end[i]) < int(start[i]) { return ids } else if int(end[i]) > int(start[i]) { break } } for { ids = append(ids, startid) startid = StringAdd(startid) if startid == endid { ids = append(ids, startid) break } } return ids } func StringAddNum(numStr string, num int) string { for i := 0; i < num; i++ { numStr = StringAdd(numStr) } return numStr } // 字符串加法 func StringAdd(numStr string) string { runeArr := []rune(numStr) length := len(runeArr) add := true for i := length - 1; i >= 0; i-- { if runeArr[i] < 57 { runeArr[i]++ add = false break } else { runeArr[i] = 48 } } if add { runeArr = append([]rune{49}, runeArr...) } return string(runeArr) } //----------------------------------------------------------------- const FORMAT string = "2006-01-02 15:04:05" const FORMATDATA string = "2006-01-02 " // 获取当前时间截 func TimestampNano() int64 { return time.Now().UnixNano() } // 获取当前时间截 func Timestamp() int64 { return time.Now().Unix() } // 获取本周六零点时间截 func TimestampSaturday() int64 { now := time.Now() unix := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).Unix() return unix + int64(time.Saturday-now.Weekday())*86400 } // 获取本地当天零点时间截 func TimestampToday() int64 { return time.Date(Year(), Month(), Day(), 0, 0, 0, 0, time.Local).Unix() } func TimestampTodayStr() string { t := time.Date(Year(), Month(), Day(), 0, 0, 0, 0, time.Local).Unix() return strconv.FormatInt(t, 10) } // 获取本地昨天零点时间截 func TimestampYesterday() int64 { return TimestampToday() - 86400 } // 获取本地明天零点时间截 func TimestampTomorrow() int64 { return TimestampToday() + 86400 } // 获取当前年 func Year() int { return time.Now().Year() } // 获取当前月 func Month() time.Month { return time.Now().Month() } // 获取当前天 func Day() int { return time.Now().Day() } // 获取当前周 func Weekday() time.Weekday { return time.Now().Weekday() } // 获取指定时间截的年 func Unix2Year(t int64) int { return time.Unix(t, 0).Year() } // 获取指定时间截的月 func Unix2Month(t int64) time.Month { return time.Unix(t, 0).Month() } // 获取指定时间截的天 func Unix2Day(t int64) int { return time.Unix(t, 0).Day() } // 时间戳转str格式化时间 func Unix2Str(t int64) string { return time.Unix(t, 0).Format(FORMAT) } // str格式当前日期 func DateStr() string { return time.Now().Format(FORMATDATA) } // str格式化时间转时间戳 func Str2Unix(t string) (int64, error) { the_time, err := time.Parse(FORMAT, t) if err == nil { return the_time.Unix(), err } return 0, err } // 获取指定年月的天数 func MonthDays(year int, month int) (days int) { if month != 2 { if month == 4 || month == 6 || month == 9 || month == 11 { days = 30 } else { days = 31 } } else { if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 { days = 29 } else { days = 28 } } return } // md5 加密 // func Md5(text string) string { // hashMd5 := md5.New() // io.WriteString(hashMd5, text) // return fmt.Sprintf("%x", hashMd5.Sum(nil)) // } func Md5(text string) string { h := md5.New() h.Write([]byte(text)) // return hex.EncodeToString(h.Sum(nil)) // 输出加密结果 } // 延迟second func Sleep(second int) { <-time.After(time.Duration(second) * time.Second) } // 延迟1~second func SleepRand(second int) { <-time.After(time.Duration(rand.Intn(second)+1) * time.Second) } // 延迟second func Sleep64(second int64) { <-time.After(time.Duration(second) * time.Second) } // 延迟1~second func SleepRand64(second int64) { <-time.After(time.Duration(rand.Int63n(second)+1) * time.Second) } // 用于调式显示掩码 func BitOr(v int64) { glog.Info("bit set is:") var s string for i := 1; i <= 64; i++ { if v&(1< 0 { s = fmt.Sprintf("%s %d", s, i) } } glog.Infoln(s) } func Byte2uint32(in []byte) []uint32 { out := make([]uint32, 0, len(in)) for _, v := range in { out = append(out, uint32(v)) } return out } func Byte2int32(in []byte) []int32 { out := make([]int32, 0, len(in)) for _, v := range in { out = append(out, int32(v)) } return out } func Int642uint32(in []int64) []uint32 { out := make([]uint32, 0, len(in)) for _, v := range in { out = append(out, uint32(v)) } return out } func String2uint32(in []string) []uint32 { out := make([]uint32, 0, len(in)) for _, v := range in { t, _ := strconv.Atoi(v) out = append(out, uint32(t)) } return out } func String2int(in []string) []int { out := make([]int, 0, len(in)) for _, v := range in { t, _ := strconv.Atoi(v) out = append(out, t) } return out } func Uint322string(in []uint32) []string { out := make([]string, 0, len(in)) for _, v := range in { out = append(out, strconv.Itoa(int(v))) } return out } func int2string(in []int) []string { out := make([]string, 0, len(in)) for _, v := range in { out = append(out, strconv.Itoa(v)) } return out } // 是否在slice里面 func InSlice(ms uint32, arr []uint32) bool { for _, v := range arr { if ms == v { return true } } return false } func Truncate6Words(origin string) string { newString := origin nameRune := []rune(origin) glog.Errorf("len is %v", len(nameRune)) if len(nameRune) > 6 { newString = string(nameRune[:6]) } return newString } // "1.1.1"格式版本号对比,origin = target :1;origin < target :-1; origin = target:0 func VersionContrast(origin, target string) (int, error) { originArr := strings.Split(origin, ".") targetArr := strings.Split(target, ".") for i := 0; i < len(originArr); i++ { originItem := originArr[i] originInt, err := strconv.Atoi(originItem) if err != nil { return 0, err } if len(targetArr) <= i { return 1, nil } targetItem := targetArr[i] targetInt, err := strconv.Atoi(targetItem) if err != nil { return 0, err } if originInt > targetInt { return 1, nil } else if originInt < targetInt { return -1, nil } } return 0, nil } func LogPrefix(uid uint32, str string) string { return fmt.Sprintf("玩家:%v 操作:[%v]", uid, str) } /*serverid helper serverid采用6位数字,例如:123001 第1,2位是appid,对应客户端应用id 第3,4位是game类型,约局10,金币30 第5,6位是可执行文件编号,比如123001,123002分别是牛牛金币服两个game */ func ToServerType(sid int) int { return ((sid / 1000) % 100) % 10 } ================================================ FILE: src/github.com/dolotech/lib/utils/utils_test.go ================================================ /** * Created by Michael on 2015/8/4. */ package utils import ( "encoding/json" "fmt" "testing" ) func Test_StringAdd(t *testing.T) { t.Log(StringAdd("123")) t.Log(StringAdd("789786654567")) t.Log(StringAdd("sadfasdf")) t.Log(StringAdd("123944")) t.Log(StringAdd("1111111111")) t.Log(StringAdd("999999999")) t.Log(StringAdd("0")) t.Log(StringAdd("099")) } /* func Test_ran(t *testing.T) { //for i := 0; i < 100; i++ { // a := RandInt64() // t.Log(Conver10to62(a), len(Conver10to62(a))) //} //str := "12345678901" str := Conver10to62(RandInt64()) t.Log(str, len(str)) if len(str) < 12 { var buf = make([]byte, 12-len(str)) for i := 0; i < 12-len(str); i++ { buf[i] = 48 } str = string(buf) + str } t.Log(len(str), str) }*/ func Test_copy(t *testing.T) { a := AA{A: 999} b := AA{} //err :=Clone(b, a) t.Log(a, b) } func Test_AES(t *testing.T) { aesEnc := AesEncrypt{} aesEnc.SetKey([]byte("aalk;lkasjd;lkfj;alk")) doc := []byte("abcde号。") arrEncrypt, err := aesEnc.Encrypt(doc) glog.Infoln(string(arrEncrypt)) if err != nil { glog.Infoln(string(arrEncrypt)) return } strMsg, err := aesEnc.Decrypt(arrEncrypt) if err != nil { glog.Infoln(string(arrEncrypt)) return } glog.Infoln(string(strMsg)) } func Test_XXTEA(t *testing.T) { /*str := "Hello World! 你好,中国!" key := "1234567890" encrypt_data := Encrypt([]byte(str), []byte(key)) //glog.Infoln(base64.StdEncoding.EncodeToString(encrypt_data)) decrypt_data := Decrypt(encrypt_data, []byte(key))*/ } func TestPWD(t *testing.T) { t.Log(AalidataPwd("dolo0425")) } func TestPhone(t *testing.T) { t.Log(PhoneRegexp("8601593533372")) } type AA struct { CC A int `json:"a"` } type BB interface { Decode(b *[]byte) error Encode() (*[]byte, error) } type CC struct{} func (this *CC) Decode(b *[]byte) error { return json.Unmarshal(*b, this) } func (this *CC) Encode() (*[]byte, error) { data, err := json.Marshal(this) return &data, err } ================================================ FILE: src/github.com/dolotech/lib/utils/waitgroup.go ================================================ package utils import ( "sync" ) type WaitGroupWrapper struct { sync.WaitGroup } func (w *WaitGroupWrapper) Wrap(cb func()) { w.Add(1) go func() { cb() w.Done() }() } ================================================ FILE: src/github.com/dolotech/lib/utils/xxtea.go ================================================ package utils const delta = 0x9E3779B9 func toBytes(v []uint32, includeLength bool) []byte { length := uint32(len(v)) n := length << 2 if includeLength { m := v[length-1] n -= 4 if (m < n-3) || (m > n) { return nil } n = m } bytes := make([]byte, n) for i := uint32(0); i < n; i++ { bytes[i] = byte(v[i>>2] >> ((i & 3) << 3)) } return bytes } func toUint32s(bytes []byte, includeLength bool) (v []uint32) { length := uint32(len(bytes)) n := length >> 2 if length&3 != 0 { n++ } if includeLength { v = make([]uint32, n+1) v[n] = length } else { v = make([]uint32, n) } for i := uint32(0); i < length; i++ { v[i>>2] |= uint32(bytes[i]) << ((i & 3) << 3) } return v } func mx(sum uint32, y uint32, z uint32, p uint32, e uint32, k []uint32) uint32 { return ((z>>5 ^ y<<2) + (y>>3 ^ z<<4)) ^ ((sum ^ y) + (k[p&3^e] ^ z)) } func fixk(k []uint32) []uint32 { if len(k) < 4 { key := make([]uint32, 4) copy(key, k) return key } return k } func encrypt(v []uint32, k []uint32) []uint32 { length := uint32(len(v)) n := length - 1 k = fixk(k) var y, z, sum, e, p, q uint32 z = v[n] y = v[0] sum = 0 for q = 6 + 52/length; q > 0; q-- { sum += delta e = sum >> 2 & 3 for p = 0; p < n; p++ { y = v[p+1] v[p] += mx(sum, y, z, p, e, k) z = v[p] } y = v[0] v[n] += mx(sum, y, z, p, e, k) z = v[n] } return v } func decrypt(v []uint32, k []uint32) []uint32 { length := uint32(len(v)) n := length - 1 k = fixk(k) var y, z, sum, e, p, q uint32 z = v[n] y = v[0] q = 6 + 52/length for sum = q * delta; sum != 0; sum -= delta { e = sum >> 2 & 3 for p = n; p > 0; p-- { z = v[p-1] v[p] -= mx(sum, y, z, p, e, k) y = v[p] } z = v[n] v[0] -= mx(sum, y, z, p, e, k) y = v[0] } return v } // Encrypt the data with key. // data is the bytes to be encrypted. // key is the encrypt key. It is the same as the decrypt key. func Encrypt(data []byte, key []byte) []byte { if data == nil || len(data) == 0 { return data } return toBytes(encrypt(toUint32s(data, true), toUint32s(key, false)), false) } // Decrypt the data with key. // data is the bytes to be decrypted. // key is the decrypted key. It is the same as the encrypt key. func Decrypt(data []byte, key []byte) []byte { if data == nil || len(data) == 0 { return data } return toBytes(decrypt(toUint32s(data, false), toUint32s(key, false)), true) } ================================================ FILE: src/github.com/go-xorm/core/LICENSE ================================================ Copyright (c) 2013 - 2015 Lunny Xiao All rights reserved. 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 the {organization} 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 HOLDER 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. ================================================ FILE: src/github.com/go-xorm/core/README.md ================================================ Core is a lightweight wrapper of sql.DB. # Open ```Go db, _ := core.Open(db, connstr) ``` # SetMapper ```Go db.SetMapper(SameMapper()) ``` ## Scan usage ### Scan ```Go rows, _ := db.Query() for rows.Next() { rows.Scan() } ``` ### ScanMap ```Go rows, _ := db.Query() for rows.Next() { rows.ScanMap() ``` ### ScanSlice You can use `[]string`, `[][]byte`, `[]interface{}`, `[]*string`, `[]sql.NullString` to ScanSclice. Notice, slice's length should be equal or less than select columns. ```Go rows, _ := db.Query() cols, _ := rows.Columns() for rows.Next() { var s = make([]string, len(cols)) rows.ScanSlice(&s) } ``` ```Go rows, _ := db.Query() cols, _ := rows.Columns() for rows.Next() { var s = make([]*string, len(cols)) rows.ScanSlice(&s) } ``` ### ScanStruct ```Go rows, _ := db.Query() for rows.Next() { rows.ScanStructByName() rows.ScanStructByIndex() } ``` ## Query usage ```Go rows, err := db.Query("select * from table where name = ?", name) user = User{ Name:"lunny", } rows, err := db.QueryStruct("select * from table where name = ?Name", &user) var user = map[string]interface{}{ "name": "lunny", } rows, err = db.QueryMap("select * from table where name = ?name", &user) ``` ## QueryRow usage ```Go row := db.QueryRow("select * from table where name = ?", name) user = User{ Name:"lunny", } row := db.QueryRowStruct("select * from table where name = ?Name", &user) var user = map[string]interface{}{ "name": "lunny", } row = db.QueryRowMap("select * from table where name = ?name", &user) ``` ## Exec usage ```Go db.Exec("insert into user (`name`, title, age, alias, nick_name,created) values (?,?,?,?,?,?)", name, title, age, alias...) user = User{ Name:"lunny", Title:"test", Age: 18, } result, err = db.ExecStruct("insert into user (`name`, title, age, alias, nick_name,created) values (?Name,?Title,?Age,?Alias,?NickName,?Created)", &user) var user = map[string]interface{}{ "Name": "lunny", "Title": "test", "Age": 18, } result, err = db.ExecMap("insert into user (`name`, title, age, alias, nick_name,created) values (?Name,?Title,?Age,?Alias,?NickName,?Created)", &user) ``` ================================================ FILE: src/github.com/go-xorm/core/benchmark.sh ================================================ go test -v -bench=. -run=XXX ================================================ FILE: src/github.com/go-xorm/core/cache.go ================================================ package core import ( "errors" "fmt" "time" "bytes" "encoding/gob" ) const ( // default cache expired time CacheExpired = 60 * time.Minute // not use now CacheMaxMemory = 256 // evey ten minutes to clear all expired nodes CacheGcInterval = 10 * time.Minute // each time when gc to removed max nodes CacheGcMaxRemoved = 20 ) var ( ErrCacheMiss = errors.New("xorm/cache: key not found.") ErrNotStored = errors.New("xorm/cache: not stored.") ) // CacheStore is a interface to store cache type CacheStore interface { // key is primary key or composite primary key // value is struct's pointer // key format : -p--... Put(key string, value interface{}) error Get(key string) (interface{}, error) Del(key string) error } // Cacher is an interface to provide cache // id format : u--... type Cacher interface { GetIds(tableName, sql string) interface{} GetBean(tableName string, id string) interface{} PutIds(tableName, sql string, ids interface{}) PutBean(tableName string, id string, obj interface{}) DelIds(tableName, sql string) DelBean(tableName string, id string) ClearIds(tableName string) ClearBeans(tableName string) } func encodeIds(ids []PK) (string, error) { buf := new(bytes.Buffer) enc := gob.NewEncoder(buf) err := enc.Encode(ids) return buf.String(), err } func decodeIds(s string) ([]PK, error) { pks := make([]PK, 0) dec := gob.NewDecoder(bytes.NewBufferString(s)) err := dec.Decode(&pks) return pks, err } func GetCacheSql(m Cacher, tableName, sql string, args interface{}) ([]PK, error) { bytes := m.GetIds(tableName, GenSqlKey(sql, args)) if bytes == nil { return nil, errors.New("Not Exist") } return decodeIds(bytes.(string)) } func PutCacheSql(m Cacher, ids []PK, tableName, sql string, args interface{}) error { bytes, err := encodeIds(ids) if err != nil { return err } m.PutIds(tableName, GenSqlKey(sql, args), bytes) return nil } func GenSqlKey(sql string, args interface{}) string { return fmt.Sprintf("%v-%v", sql, args) } ================================================ FILE: src/github.com/go-xorm/core/column.go ================================================ package core import ( "fmt" "reflect" "strings" "time" ) const ( TWOSIDES = iota + 1 ONLYTODB ONLYFROMDB ) // database column type Column struct { Name string TableName string FieldName string SQLType SQLType Length int Length2 int Nullable bool Default string Indexes map[string]int IsPrimaryKey bool IsAutoIncrement bool MapType int IsCreated bool IsUpdated bool IsDeleted bool IsCascade bool IsVersion bool fieldPath []string DefaultIsEmpty bool EnumOptions map[string]int SetOptions map[string]int DisableTimeZone bool TimeZone *time.Location // column specified time zone } func NewColumn(name, fieldName string, sqlType SQLType, len1, len2 int, nullable bool) *Column { return &Column{ Name: name, TableName: "", FieldName: fieldName, SQLType: sqlType, Length: len1, Length2: len2, Nullable: nullable, Default: "", Indexes: make(map[string]int), IsPrimaryKey: false, IsAutoIncrement: false, MapType: TWOSIDES, IsCreated: false, IsUpdated: false, IsDeleted: false, IsCascade: false, IsVersion: false, fieldPath: nil, DefaultIsEmpty: false, EnumOptions: make(map[string]int), } } // generate column description string according dialect func (col *Column) String(d Dialect) string { sql := d.QuoteStr() + col.Name + d.QuoteStr() + " " sql += d.SqlType(col) + " " if col.IsPrimaryKey { sql += "PRIMARY KEY " if col.IsAutoIncrement { sql += d.AutoIncrStr() + " " } } if d.ShowCreateNull() { if col.Nullable { sql += "NULL " } else { sql += "NOT NULL " } } if col.Default != "" { sql += "DEFAULT " + col.Default + " " } return sql } func (col *Column) StringNoPk(d Dialect) string { sql := d.QuoteStr() + col.Name + d.QuoteStr() + " " sql += d.SqlType(col) + " " if d.ShowCreateNull() { if col.Nullable { sql += "NULL " } else { sql += "NOT NULL " } } if col.Default != "" { sql += "DEFAULT " + col.Default + " " } return sql } // return col's filed of struct's value func (col *Column) ValueOf(bean interface{}) (*reflect.Value, error) { dataStruct := reflect.Indirect(reflect.ValueOf(bean)) return col.ValueOfV(&dataStruct) } func (col *Column) ValueOfV(dataStruct *reflect.Value) (*reflect.Value, error) { var fieldValue reflect.Value if col.fieldPath == nil { col.fieldPath = strings.Split(col.FieldName, ".") } if dataStruct.Type().Kind() == reflect.Map { keyValue := reflect.ValueOf(col.fieldPath[len(col.fieldPath)-1]) fieldValue = dataStruct.MapIndex(keyValue) return &fieldValue, nil } else if dataStruct.Type().Kind() == reflect.Interface { structValue := reflect.ValueOf(dataStruct.Interface()) dataStruct = &structValue } level := len(col.fieldPath) fieldValue = dataStruct.FieldByName(col.fieldPath[0]) for i := 0; i < level-1; i++ { if !fieldValue.IsValid() { break } if fieldValue.Kind() == reflect.Struct { fieldValue = fieldValue.FieldByName(col.fieldPath[i+1]) } else if fieldValue.Kind() == reflect.Ptr { if fieldValue.IsNil() { fieldValue.Set(reflect.New(fieldValue.Type().Elem())) } fieldValue = fieldValue.Elem().FieldByName(col.fieldPath[i+1]) } else { return nil, fmt.Errorf("field %v is not valid", col.FieldName) } } if !fieldValue.IsValid() { return nil, fmt.Errorf("field %v is not valid", col.FieldName) } return &fieldValue, nil } ================================================ FILE: src/github.com/go-xorm/core/converstion.go ================================================ package core // Conversion is an interface. A type implements Conversion will according // the custom method to fill into database and retrieve from database. type Conversion interface { FromDB([]byte) error ToDB() ([]byte, error) } ================================================ FILE: src/github.com/go-xorm/core/db.go ================================================ package core import ( "database/sql" "database/sql/driver" "errors" "fmt" "reflect" "regexp" "sync" ) func MapToSlice(query string, mp interface{}) (string, []interface{}, error) { vv := reflect.ValueOf(mp) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map { return "", []interface{}{}, ErrNoMapPointer } args := make([]interface{}, 0, len(vv.Elem().MapKeys())) var err error query = re.ReplaceAllStringFunc(query, func(src string) string { v := vv.Elem().MapIndex(reflect.ValueOf(src[1:])) if !v.IsValid() { err = fmt.Errorf("map key %s is missing", src[1:]) } else { args = append(args, v.Interface()) } return "?" }) return query, args, err } func StructToSlice(query string, st interface{}) (string, []interface{}, error) { vv := reflect.ValueOf(st) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Struct { return "", []interface{}{}, ErrNoStructPointer } args := make([]interface{}, 0) var err error query = re.ReplaceAllStringFunc(query, func(src string) string { fv := vv.Elem().FieldByName(src[1:]).Interface() if v, ok := fv.(driver.Valuer); ok { var value driver.Value value, err = v.Value() if err != nil { return "?" } args = append(args, value) } else { args = append(args, fv) } return "?" }) if err != nil { return "", []interface{}{}, err } return query, args, nil } type DB struct { *sql.DB Mapper IMapper } func Open(driverName, dataSourceName string) (*DB, error) { db, err := sql.Open(driverName, dataSourceName) if err != nil { return nil, err } return &DB{db, NewCacheMapper(&SnakeMapper{})}, nil } func FromDB(db *sql.DB) *DB { return &DB{db, NewCacheMapper(&SnakeMapper{})} } func (db *DB) Query(query string, args ...interface{}) (*Rows, error) { rows, err := db.DB.Query(query, args...) if err != nil { if rows != nil { rows.Close() } return nil, err } return &Rows{rows, db.Mapper}, nil } func (db *DB) QueryMap(query string, mp interface{}) (*Rows, error) { query, args, err := MapToSlice(query, mp) if err != nil { return nil, err } return db.Query(query, args...) } func (db *DB) QueryStruct(query string, st interface{}) (*Rows, error) { query, args, err := StructToSlice(query, st) if err != nil { return nil, err } return db.Query(query, args...) } type Row struct { rows *Rows // One of these two will be non-nil: err error // deferred error for easy chaining } func (row *Row) Columns() ([]string, error) { if row.err != nil { return nil, row.err } return row.rows.Columns() } func (row *Row) Scan(dest ...interface{}) error { if row.err != nil { return row.err } defer row.rows.Close() for _, dp := range dest { if _, ok := dp.(*sql.RawBytes); ok { return errors.New("sql: RawBytes isn't allowed on Row.Scan") } } if !row.rows.Next() { if err := row.rows.Err(); err != nil { return err } return sql.ErrNoRows } err := row.rows.Scan(dest...) if err != nil { return err } // Make sure the query can be processed to completion with no errors. return row.rows.Close() } func (row *Row) ScanStructByName(dest interface{}) error { if row.err != nil { return row.err } if !row.rows.Next() { if err := row.rows.Err(); err != nil { return err } return sql.ErrNoRows } err := row.rows.ScanStructByName(dest) if err != nil { return err } // Make sure the query can be processed to completion with no errors. return row.rows.Close() } func (row *Row) ScanStructByIndex(dest interface{}) error { if row.err != nil { return row.err } if !row.rows.Next() { if err := row.rows.Err(); err != nil { return err } return sql.ErrNoRows } err := row.rows.ScanStructByIndex(dest) if err != nil { return err } // Make sure the query can be processed to completion with no errors. return row.rows.Close() } // scan data to a slice's pointer, slice's length should equal to columns' number func (row *Row) ScanSlice(dest interface{}) error { if row.err != nil { return row.err } if !row.rows.Next() { if err := row.rows.Err(); err != nil { return err } return sql.ErrNoRows } err := row.rows.ScanSlice(dest) if err != nil { return err } // Make sure the query can be processed to completion with no errors. return row.rows.Close() } // scan data to a map's pointer func (row *Row) ScanMap(dest interface{}) error { if row.err != nil { return row.err } if !row.rows.Next() { if err := row.rows.Err(); err != nil { return err } return sql.ErrNoRows } err := row.rows.ScanMap(dest) if err != nil { return err } // Make sure the query can be processed to completion with no errors. return row.rows.Close() } func (db *DB) QueryRow(query string, args ...interface{}) *Row { rows, err := db.Query(query, args...) if err != nil { return &Row{nil, err} } return &Row{rows, nil} } func (db *DB) QueryRowMap(query string, mp interface{}) *Row { query, args, err := MapToSlice(query, mp) if err != nil { return &Row{nil, err} } return db.QueryRow(query, args...) } func (db *DB) QueryRowStruct(query string, st interface{}) *Row { query, args, err := StructToSlice(query, st) if err != nil { return &Row{nil, err} } return db.QueryRow(query, args...) } type Stmt struct { *sql.Stmt Mapper IMapper names map[string]int } func (db *DB) Prepare(query string) (*Stmt, error) { names := make(map[string]int) var i int query = re.ReplaceAllStringFunc(query, func(src string) string { names[src[1:]] = i i += 1 return "?" }) stmt, err := db.DB.Prepare(query) if err != nil { return nil, err } return &Stmt{stmt, db.Mapper, names}, nil } func (s *Stmt) ExecMap(mp interface{}) (sql.Result, error) { vv := reflect.ValueOf(mp) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map { return nil, errors.New("mp should be a map's pointer") } args := make([]interface{}, len(s.names)) for k, i := range s.names { args[i] = vv.Elem().MapIndex(reflect.ValueOf(k)).Interface() } return s.Stmt.Exec(args...) } func (s *Stmt) ExecStruct(st interface{}) (sql.Result, error) { vv := reflect.ValueOf(st) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Struct { return nil, errors.New("mp should be a map's pointer") } args := make([]interface{}, len(s.names)) for k, i := range s.names { args[i] = vv.Elem().FieldByName(k).Interface() } return s.Stmt.Exec(args...) } func (s *Stmt) Query(args ...interface{}) (*Rows, error) { rows, err := s.Stmt.Query(args...) if err != nil { return nil, err } return &Rows{rows, s.Mapper}, nil } func (s *Stmt) QueryMap(mp interface{}) (*Rows, error) { vv := reflect.ValueOf(mp) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map { return nil, errors.New("mp should be a map's pointer") } args := make([]interface{}, len(s.names)) for k, i := range s.names { args[i] = vv.Elem().MapIndex(reflect.ValueOf(k)).Interface() } return s.Query(args...) } func (s *Stmt) QueryStruct(st interface{}) (*Rows, error) { vv := reflect.ValueOf(st) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Struct { return nil, errors.New("mp should be a map's pointer") } args := make([]interface{}, len(s.names)) for k, i := range s.names { args[i] = vv.Elem().FieldByName(k).Interface() } return s.Query(args...) } func (s *Stmt) QueryRow(args ...interface{}) *Row { rows, err := s.Query(args...) return &Row{rows, err} } func (s *Stmt) QueryRowMap(mp interface{}) *Row { vv := reflect.ValueOf(mp) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map { return &Row{nil, errors.New("mp should be a map's pointer")} } args := make([]interface{}, len(s.names)) for k, i := range s.names { args[i] = vv.Elem().MapIndex(reflect.ValueOf(k)).Interface() } return s.QueryRow(args...) } func (s *Stmt) QueryRowStruct(st interface{}) *Row { vv := reflect.ValueOf(st) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Struct { return &Row{nil, errors.New("st should be a struct's pointer")} } args := make([]interface{}, len(s.names)) for k, i := range s.names { args[i] = vv.Elem().FieldByName(k).Interface() } return s.QueryRow(args...) } var ( re = regexp.MustCompile(`[?](\w+)`) ) // insert into (name) values (?) // insert into (name) values (?name) func (db *DB) ExecMap(query string, mp interface{}) (sql.Result, error) { query, args, err := MapToSlice(query, mp) if err != nil { return nil, err } return db.DB.Exec(query, args...) } func (db *DB) ExecStruct(query string, st interface{}) (sql.Result, error) { query, args, err := StructToSlice(query, st) if err != nil { return nil, err } return db.DB.Exec(query, args...) } type Rows struct { *sql.Rows Mapper IMapper } // scan data to a struct's pointer according field index func (rs *Rows) ScanStructByIndex(dest ...interface{}) error { if len(dest) == 0 { return errors.New("at least one struct") } vvvs := make([]reflect.Value, len(dest)) for i, s := range dest { vv := reflect.ValueOf(s) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Struct { return errors.New("dest should be a struct's pointer") } vvvs[i] = vv.Elem() } cols, err := rs.Columns() if err != nil { return err } newDest := make([]interface{}, len(cols)) var i = 0 for _, vvv := range vvvs { for j := 0; j < vvv.NumField(); j++ { newDest[i] = vvv.Field(j).Addr().Interface() i = i + 1 } } return rs.Rows.Scan(newDest...) } type EmptyScanner struct { } func (EmptyScanner) Scan(src interface{}) error { return nil } var ( fieldCache = make(map[reflect.Type]map[string]int) fieldCacheMutex sync.RWMutex ) func fieldByName(v reflect.Value, name string) reflect.Value { t := v.Type() fieldCacheMutex.RLock() cache, ok := fieldCache[t] fieldCacheMutex.RUnlock() if !ok { cache = make(map[string]int) for i := 0; i < v.NumField(); i++ { cache[t.Field(i).Name] = i } fieldCacheMutex.Lock() fieldCache[t] = cache fieldCacheMutex.Unlock() } if i, ok := cache[name]; ok { return v.Field(i) } return reflect.Zero(t) } // scan data to a struct's pointer according field name func (rs *Rows) ScanStructByName(dest interface{}) error { vv := reflect.ValueOf(dest) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Struct { return errors.New("dest should be a struct's pointer") } cols, err := rs.Columns() if err != nil { return err } newDest := make([]interface{}, len(cols)) var v EmptyScanner for j, name := range cols { f := fieldByName(vv.Elem(), rs.Mapper.Table2Obj(name)) if f.IsValid() { newDest[j] = f.Addr().Interface() } else { newDest[j] = &v } } return rs.Rows.Scan(newDest...) } type cacheStruct struct { value reflect.Value idx int } var ( reflectCache = make(map[reflect.Type]*cacheStruct) reflectCacheMutex sync.RWMutex ) func ReflectNew(typ reflect.Type) reflect.Value { reflectCacheMutex.RLock() cs, ok := reflectCache[typ] reflectCacheMutex.RUnlock() const newSize = 200 if !ok || cs.idx+1 > newSize-1 { cs = &cacheStruct{reflect.MakeSlice(reflect.SliceOf(typ), newSize, newSize), 0} reflectCacheMutex.Lock() reflectCache[typ] = cs reflectCacheMutex.Unlock() } else { reflectCacheMutex.Lock() cs.idx = cs.idx + 1 reflectCacheMutex.Unlock() } return cs.value.Index(cs.idx).Addr() } // scan data to a slice's pointer, slice's length should equal to columns' number func (rs *Rows) ScanSlice(dest interface{}) error { vv := reflect.ValueOf(dest) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Slice { return errors.New("dest should be a slice's pointer") } vvv := vv.Elem() cols, err := rs.Columns() if err != nil { return err } newDest := make([]interface{}, len(cols)) for j := 0; j < len(cols); j++ { if j >= vvv.Len() { newDest[j] = reflect.New(vvv.Type().Elem()).Interface() } else { newDest[j] = vvv.Index(j).Addr().Interface() } } err = rs.Rows.Scan(newDest...) if err != nil { return err } srcLen := vvv.Len() for i := srcLen; i < len(cols); i++ { vvv = reflect.Append(vvv, reflect.ValueOf(newDest[i]).Elem()) } return nil } // scan data to a map's pointer func (rs *Rows) ScanMap(dest interface{}) error { vv := reflect.ValueOf(dest) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map { return errors.New("dest should be a map's pointer") } cols, err := rs.Columns() if err != nil { return err } newDest := make([]interface{}, len(cols)) vvv := vv.Elem() for i, _ := range cols { newDest[i] = ReflectNew(vvv.Type().Elem()).Interface() //v := reflect.New(vvv.Type().Elem()) //newDest[i] = v.Interface() } err = rs.Rows.Scan(newDest...) if err != nil { return err } for i, name := range cols { vname := reflect.ValueOf(name) vvv.SetMapIndex(vname, reflect.ValueOf(newDest[i]).Elem()) } return nil } /*func (rs *Rows) ScanMap(dest interface{}) error { vv := reflect.ValueOf(dest) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map { return errors.New("dest should be a map's pointer") } cols, err := rs.Columns() if err != nil { return err } newDest := make([]interface{}, len(cols)) err = rs.ScanSlice(newDest) if err != nil { return err } vvv := vv.Elem() for i, name := range cols { vname := reflect.ValueOf(name) vvv.SetMapIndex(vname, reflect.ValueOf(newDest[i]).Elem()) } return nil }*/ type Tx struct { *sql.Tx Mapper IMapper } func (db *DB) Begin() (*Tx, error) { tx, err := db.DB.Begin() if err != nil { return nil, err } return &Tx{tx, db.Mapper}, nil } func (tx *Tx) Prepare(query string) (*Stmt, error) { names := make(map[string]int) var i int query = re.ReplaceAllStringFunc(query, func(src string) string { names[src[1:]] = i i += 1 return "?" }) stmt, err := tx.Tx.Prepare(query) if err != nil { return nil, err } return &Stmt{stmt, tx.Mapper, names}, nil } func (tx *Tx) Stmt(stmt *Stmt) *Stmt { // TODO: return stmt } func (tx *Tx) ExecMap(query string, mp interface{}) (sql.Result, error) { query, args, err := MapToSlice(query, mp) if err != nil { return nil, err } return tx.Tx.Exec(query, args...) } func (tx *Tx) ExecStruct(query string, st interface{}) (sql.Result, error) { query, args, err := StructToSlice(query, st) if err != nil { return nil, err } return tx.Tx.Exec(query, args...) } func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) { rows, err := tx.Tx.Query(query, args...) if err != nil { return nil, err } return &Rows{rows, tx.Mapper}, nil } func (tx *Tx) QueryMap(query string, mp interface{}) (*Rows, error) { query, args, err := MapToSlice(query, mp) if err != nil { return nil, err } return tx.Query(query, args...) } func (tx *Tx) QueryStruct(query string, st interface{}) (*Rows, error) { query, args, err := StructToSlice(query, st) if err != nil { return nil, err } return tx.Query(query, args...) } func (tx *Tx) QueryRow(query string, args ...interface{}) *Row { rows, err := tx.Query(query, args...) return &Row{rows, err} } func (tx *Tx) QueryRowMap(query string, mp interface{}) *Row { query, args, err := MapToSlice(query, mp) if err != nil { return &Row{nil, err} } return tx.QueryRow(query, args...) } func (tx *Tx) QueryRowStruct(query string, st interface{}) *Row { query, args, err := StructToSlice(query, st) if err != nil { return &Row{nil, err} } return tx.QueryRow(query, args...) } ================================================ FILE: src/github.com/go-xorm/core/dialect.go ================================================ package core import ( "fmt" "strings" "time" ) type DbType string type Uri struct { DbType DbType Proto string Host string Port string DbName string User string Passwd string Charset string Laddr string Raddr string Timeout time.Duration Schema string } // a dialect is a driver's wrapper type Dialect interface { SetLogger(logger ILogger) Init(*DB, *Uri, string, string) error URI() *Uri DB() *DB DBType() DbType SqlType(*Column) string FormatBytes(b []byte) string DriverName() string DataSourceName() string QuoteStr() string IsReserved(string) bool Quote(string) string AndStr() string OrStr() string EqStr() string RollBackStr() string AutoIncrStr() string SupportInsertMany() bool SupportEngine() bool SupportCharset() bool SupportDropIfExists() bool IndexOnTable() bool ShowCreateNull() bool IndexCheckSql(tableName, idxName string) (string, []interface{}) TableCheckSql(tableName string) (string, []interface{}) IsColumnExist(tableName string, colName string) (bool, error) CreateTableSql(table *Table, tableName, storeEngine, charset string) string DropTableSql(tableName string) string CreateIndexSql(tableName string, index *Index) string DropIndexSql(tableName string, index *Index) string ModifyColumnSql(tableName string, col *Column) string ForUpdateSql(query string) string //CreateTableIfNotExists(table *Table, tableName, storeEngine, charset string) error //MustDropTable(tableName string) error GetColumns(tableName string) ([]string, map[string]*Column, error) GetTables() ([]*Table, error) GetIndexes(tableName string) (map[string]*Index, error) Filters() []Filter } func OpenDialect(dialect Dialect) (*DB, error) { return Open(dialect.DriverName(), dialect.DataSourceName()) } type Base struct { db *DB dialect Dialect driverName string dataSourceName string logger ILogger *Uri } func (b *Base) DB() *DB { return b.db } func (b *Base) SetLogger(logger ILogger) { b.logger = logger } func (b *Base) Init(db *DB, dialect Dialect, uri *Uri, drivername, dataSourceName string) error { b.db, b.dialect, b.Uri = db, dialect, uri b.driverName, b.dataSourceName = drivername, dataSourceName return nil } func (b *Base) URI() *Uri { return b.Uri } func (b *Base) DBType() DbType { return b.Uri.DbType } func (b *Base) FormatBytes(bs []byte) string { return fmt.Sprintf("0x%x", bs) } func (b *Base) DriverName() string { return b.driverName } func (b *Base) ShowCreateNull() bool { return true } func (b *Base) DataSourceName() string { return b.dataSourceName } func (b *Base) AndStr() string { return "AND" } func (b *Base) OrStr() string { return "OR" } func (b *Base) EqStr() string { return "=" } func (db *Base) RollBackStr() string { return "ROLL BACK" } func (db *Base) SupportDropIfExists() bool { return true } func (db *Base) DropTableSql(tableName string) string { return fmt.Sprintf("DROP TABLE IF EXISTS `%s`", tableName) } func (db *Base) HasRecords(query string, args ...interface{}) (bool, error) { db.LogSQL(query, args) rows, err := db.DB().Query(query, args...) if err != nil { return false, err } defer rows.Close() if rows.Next() { return true, nil } return false, nil } func (db *Base) IsColumnExist(tableName, colName string) (bool, error) { query := "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ?" query = strings.Replace(query, "`", db.dialect.QuoteStr(), -1) return db.HasRecords(query, db.DbName, tableName, colName) } /* func (db *Base) CreateTableIfNotExists(table *Table, tableName, storeEngine, charset string) error { sql, args := db.dialect.TableCheckSql(tableName) rows, err := db.DB().Query(sql, args...) if db.Logger != nil { db.Logger.Info("[sql]", sql, args) } if err != nil { return err } defer rows.Close() if rows.Next() { return nil } sql = db.dialect.CreateTableSql(table, tableName, storeEngine, charset) _, err = db.DB().Exec(sql) if db.Logger != nil { db.Logger.Info("[sql]", sql) } return err }*/ func (db *Base) CreateIndexSql(tableName string, index *Index) string { quote := db.dialect.Quote var unique string var idxName string if index.Type == UniqueType { unique = " UNIQUE" } idxName = index.XName(tableName) return fmt.Sprintf("CREATE%s INDEX %v ON %v (%v)", unique, quote(idxName), quote(tableName), quote(strings.Join(index.Cols, quote(",")))) } func (db *Base) DropIndexSql(tableName string, index *Index) string { quote := db.dialect.Quote var name string if index.IsRegular { name = index.XName(tableName) } else { name = index.Name } return fmt.Sprintf("DROP INDEX %v ON %s", quote(name), quote(tableName)) } func (db *Base) ModifyColumnSql(tableName string, col *Column) string { return fmt.Sprintf("alter table %s MODIFY COLUMN %s", tableName, col.StringNoPk(db.dialect)) } func (b *Base) CreateTableSql(table *Table, tableName, storeEngine, charset string) string { var sql string sql = "CREATE TABLE IF NOT EXISTS " if tableName == "" { tableName = table.Name } sql += b.dialect.Quote(tableName) sql += " (" if len(table.ColumnsSeq()) > 0 { pkList := table.PrimaryKeys for _, colName := range table.ColumnsSeq() { col := table.GetColumn(colName) if col.IsPrimaryKey && len(pkList) == 1 { sql += col.String(b.dialect) } else { sql += col.StringNoPk(b.dialect) } sql = strings.TrimSpace(sql) sql += ", " } if len(pkList) > 1 { sql += "PRIMARY KEY ( " sql += b.dialect.Quote(strings.Join(pkList, b.dialect.Quote(","))) sql += " ), " } sql = sql[:len(sql)-2] } sql += ")" if b.dialect.SupportEngine() && storeEngine != "" { sql += " ENGINE=" + storeEngine } if b.dialect.SupportCharset() { if len(charset) == 0 { charset = b.dialect.URI().Charset } if len(charset) > 0 { sql += " DEFAULT CHARSET " + charset } } return sql } func (b *Base) ForUpdateSql(query string) string { return query + " FOR UPDATE" } func (b *Base) LogSQL(sql string, args []interface{}) { if b.logger != nil && b.logger.IsShowSQL() { if len(args) > 0 { b.logger.Info("[sql]", sql, args) } else { b.logger.Info("[sql]", sql) } } } var ( dialects = map[DbType]func() Dialect{} ) func RegisterDialect(dbName DbType, dialectFunc func() Dialect) { if dialectFunc == nil { panic("core: Register dialect is nil") } dialects[dbName] = dialectFunc // !nashtsai! allow override dialect } func QueryDialect(dbName DbType) Dialect { return dialects[dbName]() } ================================================ FILE: src/github.com/go-xorm/core/driver.go ================================================ package core type Driver interface { Parse(string, string) (*Uri, error) } var ( drivers = map[string]Driver{} ) func RegisterDriver(driverName string, driver Driver) { if driver == nil { panic("core: Register driver is nil") } if _, dup := drivers[driverName]; dup { panic("core: Register called twice for driver " + driverName) } drivers[driverName] = driver } func QueryDriver(driverName string) Driver { return drivers[driverName] } func RegisteredDriverSize() int { return len(drivers) } ================================================ FILE: src/github.com/go-xorm/core/error.go ================================================ package core import "errors" var ( ErrNoMapPointer = errors.New("mp should be a map's pointer") ErrNoStructPointer = errors.New("mp should be a struct's pointer") ) ================================================ FILE: src/github.com/go-xorm/core/filter.go ================================================ package core import ( "fmt" "strings" ) // Filter is an interface to filter SQL type Filter interface { Do(sql string, dialect Dialect, table *Table) string } // QuoteFilter filter SQL replace ` to database's own quote character type QuoteFilter struct { } func (s *QuoteFilter) Do(sql string, dialect Dialect, table *Table) string { return strings.Replace(sql, "`", dialect.QuoteStr(), -1) } // IdFilter filter SQL replace (id) to primary key column name type IdFilter struct { } type Quoter struct { dialect Dialect } func NewQuoter(dialect Dialect) *Quoter { return &Quoter{dialect} } func (q *Quoter) Quote(content string) string { return q.dialect.QuoteStr() + content + q.dialect.QuoteStr() } func (i *IdFilter) Do(sql string, dialect Dialect, table *Table) string { quoter := NewQuoter(dialect) if table != nil && len(table.PrimaryKeys) == 1 { sql = strings.Replace(sql, "`(id)`", quoter.Quote(table.PrimaryKeys[0]), -1) sql = strings.Replace(sql, quoter.Quote("(id)"), quoter.Quote(table.PrimaryKeys[0]), -1) return strings.Replace(sql, "(id)", quoter.Quote(table.PrimaryKeys[0]), -1) } return sql } // SeqFilter filter SQL replace ?, ? ... to $1, $2 ... type SeqFilter struct { Prefix string Start int } func (s *SeqFilter) Do(sql string, dialect Dialect, table *Table) string { segs := strings.Split(sql, "?") size := len(segs) res := "" for i, c := range segs { if i < size-1 { res += c + fmt.Sprintf("%s%v", s.Prefix, i+s.Start) } } res += segs[size-1] return res } ================================================ FILE: src/github.com/go-xorm/core/ilogger.go ================================================ package core type LogLevel int const ( // !nashtsai! following level also match syslog.Priority value LOG_DEBUG LogLevel = iota LOG_INFO LOG_WARNING LOG_ERR LOG_OFF LOG_UNKNOWN ) // logger interface type ILogger interface { Debug(v ...interface{}) Debugf(format string, v ...interface{}) Error(v ...interface{}) Errorf(format string, v ...interface{}) Info(v ...interface{}) Infof(format string, v ...interface{}) Warn(v ...interface{}) Warnf(format string, v ...interface{}) Level() LogLevel SetLevel(l LogLevel) ShowSQL(show ...bool) IsShowSQL() bool } ================================================ FILE: src/github.com/go-xorm/core/index.go ================================================ package core import ( "fmt" "sort" "strings" ) const ( IndexType = iota + 1 UniqueType ) // database index type Index struct { IsRegular bool Name string Type int Cols []string } func (index *Index) XName(tableName string) string { if !strings.HasPrefix(index.Name, "UQE_") && !strings.HasPrefix(index.Name, "IDX_") { if index.Type == UniqueType { return fmt.Sprintf("UQE_%v_%v", tableName, index.Name) } return fmt.Sprintf("IDX_%v_%v", tableName, index.Name) } return index.Name } // add columns which will be composite index func (index *Index) AddColumn(cols ...string) { for _, col := range cols { index.Cols = append(index.Cols, col) } } func (index *Index) Equal(dst *Index) bool { if index.Type != dst.Type { return false } if len(index.Cols) != len(dst.Cols) { return false } sort.StringSlice(index.Cols).Sort() sort.StringSlice(dst.Cols).Sort() for i := 0; i < len(index.Cols); i++ { if index.Cols[i] != dst.Cols[i] { return false } } return true } // new an index func NewIndex(name string, indexType int) *Index { return &Index{true, name, indexType, make([]string, 0)} } ================================================ FILE: src/github.com/go-xorm/core/mapper.go ================================================ package core import ( "strings" "sync" ) // name translation between struct, fields names and table, column names type IMapper interface { Obj2Table(string) string Table2Obj(string) string } type CacheMapper struct { oriMapper IMapper obj2tableCache map[string]string obj2tableMutex sync.RWMutex table2objCache map[string]string table2objMutex sync.RWMutex } func NewCacheMapper(mapper IMapper) *CacheMapper { return &CacheMapper{oriMapper: mapper, obj2tableCache: make(map[string]string), table2objCache: make(map[string]string), } } func (m *CacheMapper) Obj2Table(o string) string { m.obj2tableMutex.RLock() t, ok := m.obj2tableCache[o] m.obj2tableMutex.RUnlock() if ok { return t } t = m.oriMapper.Obj2Table(o) m.obj2tableMutex.Lock() m.obj2tableCache[o] = t m.obj2tableMutex.Unlock() return t } func (m *CacheMapper) Table2Obj(t string) string { m.table2objMutex.RLock() o, ok := m.table2objCache[t] m.table2objMutex.RUnlock() if ok { return o } o = m.oriMapper.Table2Obj(t) m.table2objMutex.Lock() m.table2objCache[t] = o m.table2objMutex.Unlock() return o } // SameMapper implements IMapper and provides same name between struct and // database table type SameMapper struct { } func (m SameMapper) Obj2Table(o string) string { return o } func (m SameMapper) Table2Obj(t string) string { return t } // SnakeMapper implements IMapper and provides name transaltion between // struct and database table type SnakeMapper struct { } func snakeCasedName(name string) string { newstr := make([]rune, 0) for idx, chr := range name { if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { if idx > 0 { newstr = append(newstr, '_') } chr -= ('A' - 'a') } newstr = append(newstr, chr) } return string(newstr) } func (mapper SnakeMapper) Obj2Table(name string) string { return snakeCasedName(name) } func titleCasedName(name string) string { newstr := make([]rune, 0) upNextChar := true name = strings.ToLower(name) for _, chr := range name { switch { case upNextChar: upNextChar = false if 'a' <= chr && chr <= 'z' { chr -= ('a' - 'A') } case chr == '_': upNextChar = true continue } newstr = append(newstr, chr) } return string(newstr) } func (mapper SnakeMapper) Table2Obj(name string) string { return titleCasedName(name) } // GonicMapper implements IMapper. It will consider initialisms when mapping names. // E.g. id -> ID, user -> User and to table names: UserID -> user_id, MyUID -> my_uid type GonicMapper map[string]bool func isASCIIUpper(r rune) bool { return 'A' <= r && r <= 'Z' } func toASCIIUpper(r rune) rune { if 'a' <= r && r <= 'z' { r -= ('a' - 'A') } return r } func gonicCasedName(name string) string { newstr := make([]rune, 0, len(name)+3) for idx, chr := range name { if isASCIIUpper(chr) && idx > 0 { if !isASCIIUpper(newstr[len(newstr)-1]) { newstr = append(newstr, '_') } } if !isASCIIUpper(chr) && idx > 1 { l := len(newstr) if isASCIIUpper(newstr[l-1]) && isASCIIUpper(newstr[l-2]) { newstr = append(newstr, newstr[l-1]) newstr[l-1] = '_' } } newstr = append(newstr, chr) } return strings.ToLower(string(newstr)) } func (mapper GonicMapper) Obj2Table(name string) string { return gonicCasedName(name) } func (mapper GonicMapper) Table2Obj(name string) string { newstr := make([]rune, 0) name = strings.ToLower(name) parts := strings.Split(name, "_") for _, p := range parts { _, isInitialism := mapper[strings.ToUpper(p)] for i, r := range p { if i == 0 || isInitialism { r = toASCIIUpper(r) } newstr = append(newstr, r) } } return string(newstr) } // A GonicMapper that contains a list of common initialisms taken from golang/lint var LintGonicMapper = GonicMapper{ "API": true, "ASCII": true, "CPU": true, "CSS": true, "DNS": true, "EOF": true, "GUID": true, "HTML": true, "HTTP": true, "HTTPS": true, "ID": true, "IP": true, "JSON": true, "LHS": true, "QPS": true, "RAM": true, "RHS": true, "RPC": true, "SLA": true, "SMTP": true, "SSH": true, "TLS": true, "TTL": true, "UI": true, "UID": true, "UUID": true, "URI": true, "URL": true, "UTF8": true, "VM": true, "XML": true, "XSRF": true, "XSS": true, } // provide prefix table name support type PrefixMapper struct { Mapper IMapper Prefix string } func (mapper PrefixMapper) Obj2Table(name string) string { return mapper.Prefix + mapper.Mapper.Obj2Table(name) } func (mapper PrefixMapper) Table2Obj(name string) string { return mapper.Mapper.Table2Obj(name[len(mapper.Prefix):]) } func NewPrefixMapper(mapper IMapper, prefix string) PrefixMapper { return PrefixMapper{mapper, prefix} } // provide suffix table name support type SuffixMapper struct { Mapper IMapper Suffix string } func (mapper SuffixMapper) Obj2Table(name string) string { return mapper.Mapper.Obj2Table(name) + mapper.Suffix } func (mapper SuffixMapper) Table2Obj(name string) string { return mapper.Mapper.Table2Obj(name[:len(name)-len(mapper.Suffix)]) } func NewSuffixMapper(mapper IMapper, suffix string) SuffixMapper { return SuffixMapper{mapper, suffix} } ================================================ FILE: src/github.com/go-xorm/core/pk.go ================================================ package core import ( "bytes" "encoding/gob" ) type PK []interface{} func NewPK(pks ...interface{}) *PK { p := PK(pks) return &p } func (p *PK) ToString() (string, error) { buf := new(bytes.Buffer) enc := gob.NewEncoder(buf) err := enc.Encode(*p) return buf.String(), err } func (p *PK) FromString(content string) error { dec := gob.NewDecoder(bytes.NewBufferString(content)) err := dec.Decode(p) return err } ================================================ FILE: src/github.com/go-xorm/core/scan.go ================================================ package core import ( "database/sql/driver" "fmt" "time" ) type NullTime time.Time var ( _ driver.Valuer = NullTime{} ) func (ns *NullTime) Scan(value interface{}) error { if value == nil { return nil } return convertTime(ns, value) } // Value implements the driver Valuer interface. func (ns NullTime) Value() (driver.Value, error) { if (time.Time)(ns).IsZero() { return nil, nil } return (time.Time)(ns).Format("2006-01-02 15:04:05"), nil } func convertTime(dest *NullTime, src interface{}) error { // Common cases, without reflect. switch s := src.(type) { case string: t, err := time.Parse("2006-01-02 15:04:05", s) if err != nil { return err } *dest = NullTime(t) return nil case []uint8: t, err := time.Parse("2006-01-02 15:04:05", string(s)) if err != nil { return err } *dest = NullTime(t) return nil case nil: default: return fmt.Errorf("unsupported driver -> Scan pair: %T -> %T", src, dest) } return nil } ================================================ FILE: src/github.com/go-xorm/core/table.go ================================================ package core import ( "reflect" "strings" ) // database table type Table struct { Name string Type reflect.Type columnsSeq []string columnsMap map[string][]*Column columns []*Column Indexes map[string]*Index PrimaryKeys []string AutoIncrement string Created map[string]bool Updated string Deleted string Version string Cacher Cacher StoreEngine string Charset string } func (table *Table) Columns() []*Column { return table.columns } func (table *Table) ColumnsSeq() []string { return table.columnsSeq } func NewEmptyTable() *Table { return NewTable("", nil) } func NewTable(name string, t reflect.Type) *Table { return &Table{Name: name, Type: t, columnsSeq: make([]string, 0), columns: make([]*Column, 0), columnsMap: make(map[string][]*Column), Indexes: make(map[string]*Index), Created: make(map[string]bool), PrimaryKeys: make([]string, 0), } } func (table *Table) GetColumn(name string) *Column { if c, ok := table.columnsMap[strings.ToLower(name)]; ok { return c[0] } return nil } func (table *Table) GetColumnIdx(name string, idx int) *Column { if c, ok := table.columnsMap[strings.ToLower(name)]; ok { if idx < len(c) { return c[idx] } } return nil } // if has primary key, return column func (table *Table) PKColumns() []*Column { columns := make([]*Column, len(table.PrimaryKeys)) for i, name := range table.PrimaryKeys { columns[i] = table.GetColumn(name) } return columns } func (table *Table) ColumnType(name string) reflect.Type { t, _ := table.Type.FieldByName(name) return t.Type } func (table *Table) AutoIncrColumn() *Column { return table.GetColumn(table.AutoIncrement) } func (table *Table) VersionColumn() *Column { return table.GetColumn(table.Version) } func (table *Table) UpdatedColumn() *Column { return table.GetColumn(table.Updated) } func (table *Table) DeletedColumn() *Column { return table.GetColumn(table.Deleted) } // add a column to table func (table *Table) AddColumn(col *Column) { table.columnsSeq = append(table.columnsSeq, col.Name) table.columns = append(table.columns, col) colName := strings.ToLower(col.Name) if c, ok := table.columnsMap[colName]; ok { table.columnsMap[colName] = append(c, col) } else { table.columnsMap[colName] = []*Column{col} } if col.IsPrimaryKey { table.PrimaryKeys = append(table.PrimaryKeys, col.Name) } if col.IsAutoIncrement { table.AutoIncrement = col.Name } if col.IsCreated { table.Created[col.Name] = true } if col.IsUpdated { table.Updated = col.Name } if col.IsDeleted { table.Deleted = col.Name } if col.IsVersion { table.Version = col.Name } } // add an index or an unique to table func (table *Table) AddIndex(index *Index) { table.Indexes[index.Name] = index } ================================================ FILE: src/github.com/go-xorm/core/type.go ================================================ package core import ( "reflect" "sort" "strings" "time" ) const ( POSTGRES = "postgres" SQLITE = "sqlite3" MYSQL = "mysql" MSSQL = "mssql" ORACLE = "oracle" ) // xorm SQL types type SQLType struct { Name string DefaultLength int DefaultLength2 int } const ( UNKNOW_TYPE = iota TEXT_TYPE BLOB_TYPE TIME_TYPE NUMERIC_TYPE ) func (s *SQLType) IsType(st int) bool { if t, ok := SqlTypes[s.Name]; ok && t == st { return true } return false } func (s *SQLType) IsText() bool { return s.IsType(TEXT_TYPE) } func (s *SQLType) IsBlob() bool { return s.IsType(BLOB_TYPE) } func (s *SQLType) IsTime() bool { return s.IsType(TIME_TYPE) } func (s *SQLType) IsNumeric() bool { return s.IsType(NUMERIC_TYPE) } func (s *SQLType) IsJson() bool { return s.Name == Json } var ( Bit = "BIT" TinyInt = "TINYINT" SmallInt = "SMALLINT" MediumInt = "MEDIUMINT" Int = "INT" Integer = "INTEGER" BigInt = "BIGINT" Enum = "ENUM" Set = "SET" Char = "CHAR" Varchar = "VARCHAR" NVarchar = "NVARCHAR" TinyText = "TINYTEXT" Text = "TEXT" Clob = "CLOB" MediumText = "MEDIUMTEXT" LongText = "LONGTEXT" Uuid = "UUID" Date = "DATE" DateTime = "DATETIME" Time = "TIME" TimeStamp = "TIMESTAMP" TimeStampz = "TIMESTAMPZ" Decimal = "DECIMAL" Numeric = "NUMERIC" Real = "REAL" Float = "FLOAT" Double = "DOUBLE" Binary = "BINARY" VarBinary = "VARBINARY" TinyBlob = "TINYBLOB" Blob = "BLOB" MediumBlob = "MEDIUMBLOB" LongBlob = "LONGBLOB" Bytea = "BYTEA" Bool = "BOOL" Serial = "SERIAL" BigSerial = "BIGSERIAL" Json = "JSON" Jsonb = "JSONB" SqlTypes = map[string]int{ Bit: NUMERIC_TYPE, TinyInt: NUMERIC_TYPE, SmallInt: NUMERIC_TYPE, MediumInt: NUMERIC_TYPE, Int: NUMERIC_TYPE, Integer: NUMERIC_TYPE, BigInt: NUMERIC_TYPE, Enum: TEXT_TYPE, Set: TEXT_TYPE, Json: TEXT_TYPE, Jsonb: TEXT_TYPE, Char: TEXT_TYPE, Varchar: TEXT_TYPE, NVarchar: TEXT_TYPE, TinyText: TEXT_TYPE, Text: TEXT_TYPE, MediumText: TEXT_TYPE, LongText: TEXT_TYPE, Uuid: TEXT_TYPE, Clob: TEXT_TYPE, Date: TIME_TYPE, DateTime: TIME_TYPE, Time: TIME_TYPE, TimeStamp: TIME_TYPE, TimeStampz: TIME_TYPE, Decimal: NUMERIC_TYPE, Numeric: NUMERIC_TYPE, Real: NUMERIC_TYPE, Float: NUMERIC_TYPE, Double: NUMERIC_TYPE, Binary: BLOB_TYPE, VarBinary: BLOB_TYPE, TinyBlob: BLOB_TYPE, Blob: BLOB_TYPE, MediumBlob: BLOB_TYPE, LongBlob: BLOB_TYPE, Bytea: BLOB_TYPE, Bool: NUMERIC_TYPE, Serial: NUMERIC_TYPE, BigSerial: NUMERIC_TYPE, } intTypes = sort.StringSlice{"*int", "*int16", "*int32", "*int8"} uintTypes = sort.StringSlice{"*uint", "*uint16", "*uint32", "*uint8"} ) // !nashtsai! treat following var as interal const values, these are used for reflect.TypeOf comparision var ( c_EMPTY_STRING string c_BOOL_DEFAULT bool c_BYTE_DEFAULT byte c_COMPLEX64_DEFAULT complex64 c_COMPLEX128_DEFAULT complex128 c_FLOAT32_DEFAULT float32 c_FLOAT64_DEFAULT float64 c_INT64_DEFAULT int64 c_UINT64_DEFAULT uint64 c_INT32_DEFAULT int32 c_UINT32_DEFAULT uint32 c_INT16_DEFAULT int16 c_UINT16_DEFAULT uint16 c_INT8_DEFAULT int8 c_UINT8_DEFAULT uint8 c_INT_DEFAULT int c_UINT_DEFAULT uint c_TIME_DEFAULT time.Time ) var ( IntType = reflect.TypeOf(c_INT_DEFAULT) Int8Type = reflect.TypeOf(c_INT8_DEFAULT) Int16Type = reflect.TypeOf(c_INT16_DEFAULT) Int32Type = reflect.TypeOf(c_INT32_DEFAULT) Int64Type = reflect.TypeOf(c_INT64_DEFAULT) UintType = reflect.TypeOf(c_UINT_DEFAULT) Uint8Type = reflect.TypeOf(c_UINT8_DEFAULT) Uint16Type = reflect.TypeOf(c_UINT16_DEFAULT) Uint32Type = reflect.TypeOf(c_UINT32_DEFAULT) Uint64Type = reflect.TypeOf(c_UINT64_DEFAULT) Float32Type = reflect.TypeOf(c_FLOAT32_DEFAULT) Float64Type = reflect.TypeOf(c_FLOAT64_DEFAULT) Complex64Type = reflect.TypeOf(c_COMPLEX64_DEFAULT) Complex128Type = reflect.TypeOf(c_COMPLEX128_DEFAULT) StringType = reflect.TypeOf(c_EMPTY_STRING) BoolType = reflect.TypeOf(c_BOOL_DEFAULT) ByteType = reflect.TypeOf(c_BYTE_DEFAULT) BytesType = reflect.SliceOf(ByteType) TimeType = reflect.TypeOf(c_TIME_DEFAULT) ) var ( PtrIntType = reflect.PtrTo(IntType) PtrInt8Type = reflect.PtrTo(Int8Type) PtrInt16Type = reflect.PtrTo(Int16Type) PtrInt32Type = reflect.PtrTo(Int32Type) PtrInt64Type = reflect.PtrTo(Int64Type) PtrUintType = reflect.PtrTo(UintType) PtrUint8Type = reflect.PtrTo(Uint8Type) PtrUint16Type = reflect.PtrTo(Uint16Type) PtrUint32Type = reflect.PtrTo(Uint32Type) PtrUint64Type = reflect.PtrTo(Uint64Type) PtrFloat32Type = reflect.PtrTo(Float32Type) PtrFloat64Type = reflect.PtrTo(Float64Type) PtrComplex64Type = reflect.PtrTo(Complex64Type) PtrComplex128Type = reflect.PtrTo(Complex128Type) PtrStringType = reflect.PtrTo(StringType) PtrBoolType = reflect.PtrTo(BoolType) PtrByteType = reflect.PtrTo(ByteType) PtrTimeType = reflect.PtrTo(TimeType) ) // Type2SQLType generate SQLType acorrding Go's type func Type2SQLType(t reflect.Type) (st SQLType) { switch k := t.Kind(); k { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32: st = SQLType{Int, 0, 0} case reflect.Int64, reflect.Uint64: st = SQLType{BigInt, 0, 0} case reflect.Float32: st = SQLType{Float, 0, 0} case reflect.Float64: st = SQLType{Double, 0, 0} case reflect.Complex64, reflect.Complex128: st = SQLType{Varchar, 64, 0} case reflect.Array, reflect.Slice, reflect.Map: if t.Elem() == reflect.TypeOf(c_BYTE_DEFAULT) { st = SQLType{Blob, 0, 0} } else { st = SQLType{Text, 0, 0} } case reflect.Bool: st = SQLType{Bool, 0, 0} case reflect.String: st = SQLType{Varchar, 255, 0} case reflect.Struct: if t.ConvertibleTo(TimeType) { st = SQLType{DateTime, 0, 0} } else { // TODO need to handle association struct st = SQLType{Text, 0, 0} } case reflect.Ptr: st = Type2SQLType(t.Elem()) default: st = SQLType{Text, 0, 0} } return } // default sql type change to go types func SQLType2Type(st SQLType) reflect.Type { name := strings.ToUpper(st.Name) switch name { case Bit, TinyInt, SmallInt, MediumInt, Int, Integer, Serial: return reflect.TypeOf(1) case BigInt, BigSerial: return reflect.TypeOf(int64(1)) case Float, Real: return reflect.TypeOf(float32(1)) case Double: return reflect.TypeOf(float64(1)) case Char, Varchar, NVarchar, TinyText, Text, MediumText, LongText, Enum, Set, Uuid, Clob: return reflect.TypeOf("") case TinyBlob, Blob, LongBlob, Bytea, Binary, MediumBlob, VarBinary: return reflect.TypeOf([]byte{}) case Bool: return reflect.TypeOf(true) case DateTime, Date, Time, TimeStamp, TimeStampz: return reflect.TypeOf(c_TIME_DEFAULT) case Decimal, Numeric: return reflect.TypeOf("") default: return reflect.TypeOf("") } } ================================================ FILE: src/github.com/go-xorm/xorm/CONTRIBUTING.md ================================================ ## Contributing to xorm `xorm` has a backlog of [pull requests](https://help.github.com/articles/using-pull-requests), but contributions are still very much welcome. You can help with patch review, submitting bug reports, or adding new functionality. There is no formal style guide, but please conform to the style of existing code and general Go formatting conventions when submitting patches. * [fork a repo](https://help.github.com/articles/fork-a-repo) * [creating a pull request ](https://help.github.com/articles/creating-a-pull-request) ### Language Since `xorm` is a world-wide open source project, please describe your issues or code changes in English as soon as possible. ### Sign your codes with comments ``` // !! your comments e.g., // !lunny! this is comments made by lunny ``` ### Patch review Help review existing open [pull requests](https://help.github.com/articles/using-pull-requests) by commenting on the code or proposed functionality. ### Bug reports We appreciate any bug reports, but especially ones with self-contained (doesn't depend on code outside of xorm), minimal (can't be simplified further) test cases. It's especially helpful if you can submit a pull request with just the failing test case (you'll probably want to pattern it after the tests in [base.go](https://github.com/go-xorm/tests/blob/master/base.go) AND [benchmark.go](https://github.com/go-xorm/tests/blob/master/benchmark.go). If you implements a new database interface, you maybe need to add a _test.go file. For example, [mysql_test.go](https://github.com/go-xorm/tests/blob/master/mysql/mysql_test.go) ### New functionality There are a number of pending patches for new functionality, so additional feature patches will take a while to merge. Still, patches are generally reviewed based on usefulness and complexity in addition to time-in-queue, so if you have a knockout idea, take a shot. Feel free to open an issue discussion your proposed patch beforehand. ================================================ FILE: src/github.com/go-xorm/xorm/LICENSE ================================================ Copyright (c) 2013 - 2015 The Xorm Authors All rights reserved. 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 the {organization} 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 HOLDER 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. ================================================ FILE: src/github.com/go-xorm/xorm/README.md ================================================ [中文](https://github.com/go-xorm/xorm/blob/master/README_CN.md) Xorm is a simple and powerful ORM for Go. [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-xorm/xorm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![Build Status](https://drone.io/github.com/go-xorm/tests/status.png)](https://drone.io/github.com/go-xorm/tests/latest) # Notice The last master version is not backwards compatible. You should use `engine.ShowSQL()` and `engine.Logger().SetLevel()` instead of `engine.ShowSQL = `, `engine.ShowInfo = ` and so on. # Features * Struct <-> Table Mapping Support * Chainable APIs * Transaction Support * Both ORM and raw SQL operation Support * Sync database schema Support * Query Cache speed up * Database Reverse support, See [Xorm Tool README](https://github.com/go-xorm/cmd/blob/master/README.md) * Simple cascade loading support * Optimistic Locking support # Drivers Support Drivers for Go's sql package which currently support database/sql includes: * Mysql: [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql) * MyMysql: [github.com/ziutek/mymysql/godrv](https://github.com/ziutek/mymysql/godrv) * Postgres: [github.com/lib/pq](https://github.com/lib/pq) * Tidb: [github.com/pingcap/tidb](https://github.com/pingcap/tidb) * SQLite: [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3) * MsSql: [github.com/denisenkom/go-mssqldb](https://github.com/denisenkom/go-mssqldb) * MsSql: [github.com/lunny/godbc](https://github.com/lunny/godbc) * Oracle: [github.com/mattn/go-oci8](https://github.com/mattn/go-oci8) (experiment) * ql: [github.com/cznic/ql](https://github.com/cznic/ql) (experiment) # Changelog * **v0.5.0** * logging interface changed * some bugs fixed * **v0.4.5** * many bugs fixed * extends support unlimited deepth * Delete Limit support * **v0.4.4** * ql database expriment support * tidb database expriment support * sql.NullString and etc. field support * select ForUpdate support * many bugs fixed [More changes ...](https://github.com/go-xorm/manual-en-US/tree/master/chapter-16) # Installation If you have [gopm](https://github.com/gpmgo/gopm) installed, gopm get github.com/go-xorm/xorm Or go get github.com/go-xorm/xorm # Documents * [Manual](http://xorm.io/docs) * [GoDoc](http://godoc.org/github.com/go-xorm/xorm) * [GoWalker](http://gowalker.org/github.com/go-xorm/xorm) # Quick Start * Create Engine ```Go engine, err := xorm.NewEngine(driverName, dataSourceName) ``` * Define a struct and Sync2 table struct to database ```Go type User struct { Id int64 Name string Salt string Age int Passwd string `xorm:"varchar(200)"` Created time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` } err := engine.Sync2(new(User)) ``` * Query a SQL string, the returned results is []map[string][]byte ```Go results, err := engine.Query("select * from user") ``` * Execute a SQL string, the returned results ```Go affected, err := engine.Exec("update user set age = ? where name = ?", age, name) ``` * Insert one or multiple records to database ```Go affected, err := engine.Insert(&user) // INSERT INTO struct () values () affected, err := engine.Insert(&user1, &user2) // INSERT INTO struct1 () values () // INSERT INTO struct2 () values () affected, err := engine.Insert(&users) // INSERT INTO struct () values (),(),() affected, err := engine.Insert(&user1, &users) // INSERT INTO struct1 () values () // INSERT INTO struct2 () values (),(),() ``` * Query one record from database ```Go has, err := engine.Get(&user) // SELECT * FROM user LIMIT 1 has, err := engine.Where("name = ?", name).Desc("id").Get(&user) // SELECT * FROM user WHERE name = ? ORDER BY id DESC LIMIT 1 ``` * Query multiple records from database, also you can use join and extends ```Go var users []User err := engine.Where("name = ?", name).And("age > 10").Limit(10, 0).Find(&users) // SELECT * FROM user WHERE name = ? AND age > 10 limit 0 offset 10 type Detail struct { Id int64 UserId int64 `xorm:"index"` } type UserDetail struct { User `xorm:"extends"` Detail `xorm:"extends"` } var users []UserDetail err := engine.Table("user").Select("user.*, detail.*") Join("INNER", "detail", "detail.user_id = user.id"). Where("user.name = ?", name).Limit(10, 0). Find(&users) // SELECT user.*, detail.* FROM user INNER JOIN detail WHERE user.name = ? limit 0 offset 10 ``` * Query multiple records and record by record handle, there are two methods Iterate and Rows ```Go err := engine.Iterate(&User{Name:name}, func(idx int, bean interface{}) error { user := bean.(*User) return nil }) // SELECT * FROM user rows, err := engine.Rows(&User{Name:name}) // SELECT * FROM user defer rows.Close() bean := new(Struct) for rows.Next() { err = rows.Scan(bean) } ``` * Update one or more records, default will update non-empty and non-zero fields except when you use Cols, AllCols and so on. ```Go affected, err := engine.Id(1).Update(&user) // UPDATE user SET ... Where id = ? affected, err := engine.Update(&user, &User{Name:name}) // UPDATE user SET ... Where name = ? var ids = []int64{1, 2, 3} affected, err := engine.In("id", ids).Update(&user) // UPDATE user SET ... Where id IN (?, ?, ?) // force update indicated columns by Cols affected, err := engine.Id(1).Cols("age").Update(&User{Name:name, Age: 12}) // UPDATE user SET age = ?, updated=? Where id = ? // force NOT update indicated columns by Omit affected, err := engine.Id(1).Omit("name").Update(&User{Name:name, Age: 12}) // UPDATE user SET age = ?, updated=? Where id = ? affected, err := engine.Id(1).AllCols().Update(&user) // UPDATE user SET name=?,age=?,salt=?,passwd=?,updated=? Where id = ? ``` * Delete one or more records, Delete MUST have condition ```Go affected, err := engine.Where(...).Delete(&user) // DELETE FROM user Where ... affected, err := engine.Id(2).Delete(&user) ``` * Count records ```Go counts, err := engine.Count(&user) // SELECT count(*) AS total FROM user ``` # Cases * [github.com/m3ng9i/qreader](https://github.com/m3ng9i/qreader) * [Wego](http://github.com/go-tango/wego) * [Docker.cn](https://docker.cn/) * [Gogs](http://try.gogits.org) - [github.com/gogits/gogs](http://github.com/gogits/gogs) * [Gorevel](http://gorevel.cn/) - [github.com/goofcc/gorevel](http://github.com/goofcc/gorevel) * [Gowalker](http://gowalker.org) - [github.com/Unknwon/gowalker](http://github.com/Unknwon/gowalker) * [Gobuild.io](http://gobuild.io) - [github.com/shxsun/gobuild](http://github.com/shxsun/gobuild) * [Sudo China](http://sudochina.com) - [github.com/insionng/toropress](http://github.com/insionng/toropress) * [Godaily](http://godaily.org) - [github.com/govc/godaily](http://github.com/govc/godaily) * [YouGam](http://www.yougam.com/) * [GoCMS - github.com/zzboy/GoCMS](https://github.com/zzdboy/GoCMS) * [GoBBS - gobbs.domolo.com](http://gobbs.domolo.com/) * [go-blog](http://wangcheng.me) - [github.com/easykoo/go-blog](https://github.com/easykoo/go-blog) # Discuss Please visit [Xorm on Google Groups](https://groups.google.com/forum/#!forum/xorm) # Contributing If you want to pull request, please see [CONTRIBUTING](https://github.com/go-xorm/xorm/blob/master/CONTRIBUTING.md) # LICENSE BSD License [http://creativecommons.org/licenses/BSD/](http://creativecommons.org/licenses/BSD/) ================================================ FILE: src/github.com/go-xorm/xorm/README_CN.md ================================================ # xorm [English](https://github.com/go-xorm/xorm/blob/master/README.md) xorm是一个简单而强大的Go语言ORM库. 通过它可以使数据库操作非常简便。 [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-xorm/xorm?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![Build Status](https://drone.io/github.com/go-xorm/tests/status.png)](https://drone.io/github.com/go-xorm/tests/latest) [![Go Walker](http://gowalker.org/api/v1/badge)](http://gowalker.org/github.com/go-xorm/xorm) # 注意 最新的版本有不兼容的更新,您必须使用 `engine.ShowSQL()` 和 `engine.Logger().SetLevel()` 来替代 `engine.ShowSQL = `, `engine.ShowInfo = ` 等等。 ## 特性 * 支持Struct和数据库表之间的灵活映射,并支持自动同步 * 事务支持 * 同时支持原始SQL语句和ORM操作的混合执行 * 使用连写来简化调用 * 支持使用Id, In, Where, Limit, Join, Having, Table, Sql, Cols等函数和结构体等方式作为条件 * 支持级联加载Struct * 支持缓存 * 支持根据数据库自动生成xorm的结构体 * 支持记录版本(即乐观锁) ## 驱动支持 目前支持的Go数据库驱动和对应的数据库如下: * Mysql: [github.com/go-sql-driver/mysql](https://github.com/go-sql-driver/mysql) * MyMysql: [github.com/ziutek/mymysql/godrv](https://github.com/ziutek/mymysql/godrv) * Postgres: [github.com/lib/pq](https://github.com/lib/pq) * Tidb: [github.com/pingcap/tidb](https://github.com/pingcap/tidb) * SQLite: [github.com/mattn/go-sqlite3](https://github.com/mattn/go-sqlite3) * MsSql: [github.com/denisenkom/go-mssqldb](https://github.com/denisenkom/go-mssqldb) * MsSql: [github.com/lunny/godbc](https://github.com/lunny/godbc) * Oracle: [github.com/mattn/go-oci8](https://github.com/mattn/go-oci8) (试验性支持) * ql: [github.com/cznic/ql](https://github.com/cznic/ql) (试验性支持) ## 更新日志 * **v0.5.0** * logging接口进行不兼容改变 * Bug修正 * **v0.4.5** * bug修正 * extends 支持无限级 * Delete Limit 支持 * **v0.4.4** * Tidb 数据库支持 * QL 试验性支持 * sql.NullString支持 * ForUpdate 支持 * bug修正 [更多更新日志...](https://github.com/go-xorm/manual-zh-CN/tree/master/chapter-16) ## 安装 推荐使用 [gopm](https://github.com/gpmgo/gopm) 进行安装: gopm get github.com/go-xorm/xorm 或者您也可以使用go工具进行安装: go get github.com/go-xorm/xorm ## 文档 * [操作指南](http://xorm.io/docs) * [GoWalker代码文档](http://gowalker.org/github.com/go-xorm/xorm) * [Godoc代码文档](http://godoc.org/github.com/go-xorm/xorm) # 快速开始 * 第一步创建引擎,driverName, dataSourceName和database/sql接口相同 ```Go engine, err := xorm.NewEngine(driverName, dataSourceName) ``` * 定义一个和表同步的结构体,并且自动同步结构体到数据库 ```Go type User struct { Id int64 Name string Salt string Age int Passwd string `xorm:"varchar(200)"` Created time.Time `xorm:"created"` Updated time.Time `xorm:"updated"` } err := engine.Sync2(new(User)) ``` * 最原始的也支持SQL语句查询,返回的结果类型为 []map[string][]byte ```Go results, err := engine.Query("select * from user") ``` * 执行一个SQL语句 ```Go affected, err := engine.Exec("update user set age = ? where name = ?", age, name) ``` * 插入一条或者多条记录 ```Go affected, err := engine.Insert(&user) // INSERT INTO struct () values () affected, err := engine.Insert(&user1, &user2) // INSERT INTO struct1 () values () // INSERT INTO struct2 () values () affected, err := engine.Insert(&users) // INSERT INTO struct () values (),(),() affected, err := engine.Insert(&user1, &users) // INSERT INTO struct1 () values () // INSERT INTO struct2 () values (),(),() ``` * 查询单条记录 ```Go has, err := engine.Get(&user) // SELECT * FROM user LIMIT 1 has, err := engine.Where("name = ?", name).Desc("id").Get(&user) // SELECT * FROM user WHERE name = ? ORDER BY id DESC LIMIT 1 ``` * 查询多条记录,当然可以使用Join和extends来组合使用 ```Go var users []User err := engine.Where("name = ?", name).And("age > 10").Limit(10, 0).Find(&users) // SELECT * FROM user WHERE name = ? AND age > 10 limit 0 offset 10 type Detail struct { Id int64 UserId int64 `xorm:"index"` } type UserDetail struct { User `xorm:"extends"` Detail `xorm:"extends"` } var users []UserDetail err := engine.Table("user").Select("user.*, detail.*") Join("INNER", "detail", "detail.user_id = user.id"). Where("user.name = ?", name).Limit(10, 0). Find(&users) // SELECT user.*, detail.* FROM user INNER JOIN detail WHERE user.name = ? limit 0 offset 10 ``` * 根据条件遍历数据库,可以有两种方式: Iterate and Rows ```Go err := engine.Iterate(&User{Name:name}, func(idx int, bean interface{}) error { user := bean.(*User) return nil }) // SELECT * FROM user rows, err := engine.Rows(&User{Name:name}) // SELECT * FROM user defer rows.Close() bean := new(Struct) for rows.Next() { err = rows.Scan(bean) } ``` * 更新数据,除非使用Cols,AllCols函数指明,默认只更新非空和非0的字段 ```Go affected, err := engine.Id(1).Update(&user) // UPDATE user SET ... Where id = ? affected, err := engine.Update(&user, &User{Name:name}) // UPDATE user SET ... Where name = ? var ids = []int64{1, 2, 3} affected, err := engine.In(ids).Update(&user) // UPDATE user SET ... Where id IN (?, ?, ?) // force update indicated columns by Cols affected, err := engine.Id(1).Cols("age").Update(&User{Name:name, Age: 12}) // UPDATE user SET age = ?, updated=? Where id = ? // force NOT update indicated columns by Omit affected, err := engine.Id(1).Omit("name").Update(&User{Name:name, Age: 12}) // UPDATE user SET age = ?, updated=? Where id = ? affected, err := engine.Id(1).AllCols().Update(&user) // UPDATE user SET name=?,age=?,salt=?,passwd=?,updated=? Where id = ? ``` * 删除记录,需要注意,删除必须至少有一个条件,否则会报错。要清空数据库可以用EmptyTable ```Go affected, err := engine.Where(...).Delete(&user) // DELETE FROM user Where ... ``` * 获取记录条数 ```Go counts, err := engine.Count(&user) // SELECT count(*) AS total FROM user ``` # 案例 * [github.com/m3ng9i/qreader](https://github.com/m3ng9i/qreader) * [Wego](http://github.com/go-tango/wego) * [Docker.cn](https://docker.cn/) * [Gogs](http://try.gogits.org) - [github.com/gogits/gogs](http://github.com/gogits/gogs) * [Gowalker](http://gowalker.org) - [github.com/Unknwon/gowalker](http://github.com/Unknwon/gowalker) * [Gobuild.io](http://gobuild.io) - [github.com/shxsun/gobuild](http://github.com/shxsun/gobuild) * [Sudo China](http://sudochina.com) - [github.com/insionng/toropress](http://github.com/insionng/toropress) * [Godaily](http://godaily.org) - [github.com/govc/godaily](http://github.com/govc/godaily) * [YouGam](http://www.yougam.com/) * [GoCMS - github.com/zzboy/GoCMS](https://github.com/zzdboy/GoCMS) * [GoBBS - gobbs.domolo.com](http://gobbs.domolo.com/) * [go-blog](http://wangcheng.me) - [github.com/easykoo/go-blog](https://github.com/easykoo/go-blog) ## 讨论 请加入QQ群:280360085 进行讨论。 ## 贡献 如果您也想为Xorm贡献您的力量,请查看 [CONTRIBUTING](https://github.com/go-xorm/xorm/blob/master/CONTRIBUTING.md) ## LICENSE BSD License [http://creativecommons.org/licenses/BSD/](http://creativecommons.org/licenses/BSD/) ================================================ FILE: src/github.com/go-xorm/xorm/VERSION ================================================ xorm v0.5.5.0711 ================================================ FILE: src/github.com/go-xorm/xorm/doc.go ================================================ // Copyright 2013 - 2016 The XORM Authors. All rights reserved. // Use of this source code is governed by a BSD // license that can be found in the LICENSE file. /* Package xorm is a simple and powerful ORM for Go. Installation Make sure you have installed Go 1.1+ and then: go get github.com/go-xorm/xorm Create Engine Firstly, we should new an engine for a database engine, err := xorm.NewEngine(driverName, dataSourceName) Method NewEngine's parameters is the same as sql.Open. It depends drivers' implementation. Generally, one engine for an application is enough. You can set it as package variable. Raw Methods Xorm also support raw sql execution: 1. query a SQL string, the returned results is []map[string][]byte results, err := engine.Query("select * from user") 2. execute a SQL string, the returned results affected, err := engine.Exec("update user set .... where ...") ORM Methods There are 7 major ORM methods and many helpful methods to use to operate database. 1. Insert one or multipe records to database affected, err := engine.Insert(&struct) // INSERT INTO struct () values () affected, err := engine.Insert(&struct1, &struct2) // INSERT INTO struct1 () values () // INSERT INTO struct2 () values () affected, err := engine.Insert(&sliceOfStruct) // INSERT INTO struct () values (),(),() affected, err := engine.Insert(&struct1, &sliceOfStruct2) // INSERT INTO struct1 () values () // INSERT INTO struct2 () values (),(),() 2. Query one record from database has, err := engine.Get(&user) // SELECT * FROM user LIMIT 1 3. Query multiple records from database sliceOfStructs := new(Struct) err := engine.Find(sliceOfStructs) // SELECT * FROM user 4. Query multiple records and record by record handle, there two methods, one is Iterate, another is Rows err := engine.Iterate(...) // SELECT * FROM user rows, err := engine.Rows(...) // SELECT * FROM user defer rows.Close() bean := new(Struct) for rows.Next() { err = rows.Scan(bean) } 5. Update one or more records affected, err := engine.Id(...).Update(&user) // UPDATE user SET ... 6. Delete one or more records, Delete MUST has conditon affected, err := engine.Where(...).Delete(&user) // DELETE FROM user Where ... 7. Count records counts, err := engine.Count(&user) // SELECT count(*) AS total FROM user Conditions The above 7 methods could use with condition methods chainable. Attention: the above 7 methods should be the last chainable method. 1. Id, In engine.Id(1).Get(&user) // for single primary key // SELECT * FROM user WHERE id = 1 engine.Id(core.PK{1, 2}).Get(&user) // for composite primary keys // SELECT * FROM user WHERE id1 = 1 AND id2 = 2 engine.In("id", 1, 2, 3).Find(&users) // SELECT * FROM user WHERE id IN (1, 2, 3) engine.In("id", []int{1, 2, 3}) // SELECT * FROM user WHERE id IN (1, 2, 3) 2. Where, And, Or engine.Where().And().Or().Find() // SELECT * FROM user WHERE (.. AND ..) OR ... 3. OrderBy, Asc, Desc engine.Asc().Desc().Find() // SELECT * FROM user ORDER BY .. ASC, .. DESC engine.OrderBy().Find() // SELECT * FROM user ORDER BY .. 4. Limit, Top engine.Limit().Find() // SELECT * FROM user LIMIT .. OFFSET .. engine.Top(5).Find() // SELECT TOP 5 * FROM user // for mssql // SELECT * FROM user LIMIT .. OFFSET 0 //for other databases 5. Sql, let you custom SQL var users []User engine.Sql("select * from user").Find(&users) 6. Cols, Omit, Distinct var users []*User engine.Cols("col1, col2").Find(&users) // SELECT col1, col2 FROM user engine.Cols("col1", "col2").Where().Update(user) // UPDATE user set col1 = ?, col2 = ? Where ... engine.Omit("col1").Find(&users) // SELECT col2, col3 FROM user engine.Omit("col1").Insert(&user) // INSERT INTO table (non-col1) VALUES () engine.Distinct("col1").Find(&users) // SELECT DISTINCT col1 FROM user 7. Join, GroupBy, Having engine.GroupBy("name").Having("name='xlw'").Find(&users) //SELECT * FROM user GROUP BY name HAVING name='xlw' engine.Join("LEFT", "userdetail", "user.id=userdetail.id").Find(&users) //SELECT * FROM user LEFT JOIN userdetail ON user.id=userdetail.id More usage, please visit http://xorm.io/docs */ package xorm ================================================ FILE: src/github.com/go-xorm/xorm/engine.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "bufio" "bytes" "database/sql" "encoding/gob" "errors" "fmt" "io" "os" "reflect" "strconv" "strings" "sync" "time" "github.com/go-xorm/core" ) // Engine is the major struct of xorm, it means a database manager. // Commonly, an application only need one engine type Engine struct { db *core.DB dialect core.Dialect ColumnMapper core.IMapper TableMapper core.IMapper TagIdentifier string Tables map[reflect.Type]*core.Table mutex *sync.RWMutex Cacher core.Cacher showSQL bool showExecTime bool logger core.ILogger TZLocation *time.Location DatabaseTZ *time.Location // The timezone of the database disableGlobalCache bool } // ShowSQL show SQL statment or not on logger if log level is great than INFO func (engine *Engine) ShowSQL(show ...bool) { engine.logger.ShowSQL(show...) if len(show) == 0 { engine.showSQL = true } else { engine.showSQL = show[0] } } // ShowExecTime show SQL statment and execute time or not on logger if log level is great than INFO func (engine *Engine) ShowExecTime(show ...bool) { if len(show) == 0 { engine.showExecTime = true } else { engine.showExecTime = show[0] } } // Logger return the logger interface func (engine *Engine) Logger() core.ILogger { return engine.logger } // SetLogger set the new logger func (engine *Engine) SetLogger(logger core.ILogger) { engine.logger = logger engine.dialect.SetLogger(logger) } // SetDisableGlobalCache disable global cache or not func (engine *Engine) SetDisableGlobalCache(disable bool) { if engine.disableGlobalCache != disable { engine.disableGlobalCache = disable } } // DriverName return the current sql driver's name func (engine *Engine) DriverName() string { return engine.dialect.DriverName() } // DataSourceName return the current connection string func (engine *Engine) DataSourceName() string { return engine.dialect.DataSourceName() } // SetMapper set the name mapping rules func (engine *Engine) SetMapper(mapper core.IMapper) { engine.SetTableMapper(mapper) engine.SetColumnMapper(mapper) } // SetTableMapper set the table name mapping rule func (engine *Engine) SetTableMapper(mapper core.IMapper) { engine.TableMapper = mapper } // SetColumnMapper set the column name mapping rule func (engine *Engine) SetColumnMapper(mapper core.IMapper) { engine.ColumnMapper = mapper } // SupportInsertMany If engine's database support batch insert records like // "insert into user values (name, age), (name, age)". // When the return is ture, then engine.Insert(&users) will // generate batch sql and exeute. func (engine *Engine) SupportInsertMany() bool { return engine.dialect.SupportInsertMany() } // QuoteStr Engine's database use which charactor as quote. // mysql, sqlite use ` and postgres use " func (engine *Engine) QuoteStr() string { return engine.dialect.QuoteStr() } // Quote Use QuoteStr quote the string sql func (engine *Engine) Quote(sql string) string { return engine.quoteTable(sql) } func (engine *Engine) quote(sql string) string { return engine.dialect.QuoteStr() + sql + engine.dialect.QuoteStr() } func (engine *Engine) quoteColumn(keyName string) string { if len(keyName) == 0 { return keyName } keyName = strings.TrimSpace(keyName) keyName = strings.Replace(keyName, "`", "", -1) keyName = strings.Replace(keyName, engine.QuoteStr(), "", -1) keyName = strings.Replace(keyName, ",", engine.dialect.QuoteStr()+","+engine.dialect.QuoteStr(), -1) keyName = strings.Replace(keyName, ".", engine.dialect.QuoteStr()+"."+engine.dialect.QuoteStr(), -1) return engine.dialect.QuoteStr() + keyName + engine.dialect.QuoteStr() } func (engine *Engine) quoteTable(keyName string) string { keyName = strings.TrimSpace(keyName) if len(keyName) == 0 { return keyName } if string(keyName[0]) == engine.dialect.QuoteStr() || keyName[0] == '`' { return keyName } keyName = strings.Replace(keyName, ".", engine.dialect.QuoteStr()+"."+engine.dialect.QuoteStr(), -1) return engine.dialect.QuoteStr() + keyName + engine.dialect.QuoteStr() } // SqlType will be depracated, please use SQLType instead func (engine *Engine) SqlType(c *core.Column) string { return engine.dialect.SqlType(c) } // SQLType A simple wrapper to dialect's core.SqlType method func (engine *Engine) SQLType(c *core.Column) string { return engine.dialect.SqlType(c) } // AutoIncrStr Database's autoincrement statement func (engine *Engine) AutoIncrStr() string { return engine.dialect.AutoIncrStr() } // SetMaxOpenConns is only available for go 1.2+ func (engine *Engine) SetMaxOpenConns(conns int) { engine.db.SetMaxOpenConns(conns) } // SetMaxIdleConns set the max idle connections on pool, default is 2 func (engine *Engine) SetMaxIdleConns(conns int) { engine.db.SetMaxIdleConns(conns) } // SetDefaultCacher set the default cacher. Xorm's default not enable cacher. func (engine *Engine) SetDefaultCacher(cacher core.Cacher) { engine.Cacher = cacher } // NoCache If you has set default cacher, and you want temporilly stop use cache, // you can use NoCache() func (engine *Engine) NoCache() *Session { session := engine.NewSession() session.IsAutoClose = true return session.NoCache() } // NoCascade If you do not want to auto cascade load object func (engine *Engine) NoCascade() *Session { session := engine.NewSession() session.IsAutoClose = true return session.NoCascade() } // MapCacher Set a table use a special cacher func (engine *Engine) MapCacher(bean interface{}, cacher core.Cacher) { v := rValue(bean) tb := engine.autoMapType(v) tb.Cacher = cacher } // NewDB provides an interface to operate database directly func (engine *Engine) NewDB() (*core.DB, error) { return core.OpenDialect(engine.dialect) } // DB return the wrapper of sql.DB func (engine *Engine) DB() *core.DB { return engine.db } // Dialect return database dialect func (engine *Engine) Dialect() core.Dialect { return engine.dialect } // NewSession New a session func (engine *Engine) NewSession() *Session { session := &Session{Engine: engine} session.Init() return session } // Close the engine func (engine *Engine) Close() error { return engine.db.Close() } // Ping tests if database is alive func (engine *Engine) Ping() error { session := engine.NewSession() defer session.Close() engine.logger.Infof("PING DATABASE %v", engine.DriverName()) return session.Ping() } // logging sql func (engine *Engine) logSQL(sqlStr string, sqlArgs ...interface{}) { if engine.showSQL && !engine.showExecTime { if len(sqlArgs) > 0 { engine.logger.Infof("[sql] %v [args] %v", sqlStr, sqlArgs) } else { engine.logger.Infof("[sql] %v", sqlStr) } } } func (engine *Engine) logSQLQueryTime(sqlStr string, args []interface{}, executionBlock func() (*core.Stmt, *core.Rows, error)) (*core.Stmt, *core.Rows, error) { if engine.showSQL && engine.showExecTime { b4ExecTime := time.Now() stmt, res, err := executionBlock() execDuration := time.Since(b4ExecTime) if len(args) > 0 { engine.logger.Infof("[sql] %s [args] %v - took: %v", sqlStr, args, execDuration) } else { engine.logger.Infof("[sql] %s - took: %v", sqlStr, execDuration) } return stmt, res, err } return executionBlock() } func (engine *Engine) logSQLExecutionTime(sqlStr string, args []interface{}, executionBlock func() (sql.Result, error)) (sql.Result, error) { if engine.showSQL && engine.showExecTime { b4ExecTime := time.Now() res, err := executionBlock() execDuration := time.Since(b4ExecTime) if len(args) > 0 { engine.logger.Infof("[sql] %s [args] %v - took: %v", sqlStr, args, execDuration) } else { engine.logger.Infof("[sql] %s - took: %v", sqlStr, execDuration) } return res, err } return executionBlock() } // Sql will be depracated, please use SQL instead func (engine *Engine) Sql(querystring string, args ...interface{}) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Sql(querystring, args...) } // SQL method let's you manualy write raw SQL and operate // For example: // // engine.SQL("select * from user").Find(&users) // // This code will execute "select * from user" and set the records to users func (engine *Engine) SQL(querystring string, args ...interface{}) *Session { session := engine.NewSession() session.IsAutoClose = true return session.SQL(querystring, args...) } // NoAutoTime Default if your struct has "created" or "updated" filed tag, the fields // will automatically be filled with current time when Insert or Update // invoked. Call NoAutoTime if you dont' want to fill automatically. func (engine *Engine) NoAutoTime() *Session { session := engine.NewSession() session.IsAutoClose = true return session.NoAutoTime() } // NoAutoCondition disable auto generate Where condition from bean or not func (engine *Engine) NoAutoCondition(no ...bool) *Session { session := engine.NewSession() session.IsAutoClose = true return session.NoAutoCondition(no...) } // DBMetas Retrieve all tables, columns, indexes' informations from database. func (engine *Engine) DBMetas() ([]*core.Table, error) { tables, err := engine.dialect.GetTables() if err != nil { return nil, err } for _, table := range tables { colSeq, cols, err := engine.dialect.GetColumns(table.Name) if err != nil { return nil, err } for _, name := range colSeq { table.AddColumn(cols[name]) } //table.Columns = cols //table.ColumnsSeq = colSeq indexes, err := engine.dialect.GetIndexes(table.Name) if err != nil { return nil, err } table.Indexes = indexes for _, index := range indexes { for _, name := range index.Cols { if col := table.GetColumn(name); col != nil { col.Indexes[index.Name] = index.Type } else { return nil, fmt.Errorf("Unknown col "+name+" in indexes %v of table", index, table.ColumnsSeq()) } } } } return tables, nil } // DumpAllToFile dump database all table structs and data to a file func (engine *Engine) DumpAllToFile(fp string) error { f, err := os.Create(fp) if err != nil { return err } defer f.Close() return engine.DumpAll(f) } // DumpAll dump database all table structs and data to w func (engine *Engine) DumpAll(w io.Writer) error { return engine.dumpAll(w, engine.dialect.DBType()) } // DumpTablesToFile dump specified tables to SQL file. func (engine *Engine) DumpTablesToFile(tables []*core.Table, fp string, tp ...core.DbType) error { f, err := os.Create(fp) if err != nil { return err } defer f.Close() return engine.DumpTables(tables, f, tp...) } // DumpTables dump specify tables to io.Writer func (engine *Engine) DumpTables(tables []*core.Table, w io.Writer, tp ...core.DbType) error { return engine.dumpTables(tables, w, tp...) } func (engine *Engine) tableName(beanOrTableName interface{}) (string, error) { v := rValue(beanOrTableName) if v.Type().Kind() == reflect.String { return beanOrTableName.(string), nil } else if v.Type().Kind() == reflect.Struct { return engine.tbName(v), nil } return "", errors.New("bean should be a struct or struct's point") } func (engine *Engine) tbName(v reflect.Value) string { if tb, ok := v.Interface().(TableName); ok { return tb.TableName() } if v.CanAddr() { if tb, ok := v.Addr().Interface().(TableName); ok { return tb.TableName() } } return engine.TableMapper.Obj2Table(v.Type().Name()) } // DumpAll dump database all table structs and data to w with specify db type func (engine *Engine) dumpAll(w io.Writer, tp ...core.DbType) error { tables, err := engine.DBMetas() if err != nil { return err } var dialect core.Dialect if len(tp) == 0 { dialect = engine.dialect } else { dialect = core.QueryDialect(tp[0]) if dialect == nil { return errors.New("Unsupported database type.") } dialect.Init(nil, engine.dialect.URI(), "", "") } _, err = io.WriteString(w, fmt.Sprintf("/*Generated by xorm v%s %s*/\n\n", Version, time.Now().In(engine.TZLocation).Format("2006-01-02 15:04:05"))) if err != nil { return err } for i, table := range tables { if i > 0 { _, err = io.WriteString(w, "\n") if err != nil { return err } } _, err = io.WriteString(w, dialect.CreateTableSql(table, "", table.StoreEngine, "")+";\n") if err != nil { return err } for _, index := range table.Indexes { _, err = io.WriteString(w, dialect.CreateIndexSql(table.Name, index)+";\n") if err != nil { return err } } rows, err := engine.DB().Query("SELECT * FROM " + engine.Quote(table.Name)) if err != nil { return err } defer rows.Close() cols, err := rows.Columns() if err != nil { return err } if len(cols) == 0 { continue } for rows.Next() { dest := make([]interface{}, len(cols)) err = rows.ScanSlice(&dest) if err != nil { return err } _, err = io.WriteString(w, "INSERT INTO "+dialect.Quote(table.Name)+" ("+dialect.Quote(strings.Join(cols, dialect.Quote(", ")))+") VALUES (") if err != nil { return err } var temp string for i, d := range dest { col := table.GetColumn(cols[i]) if d == nil { temp += ", NULL" } else if col.SQLType.IsText() || col.SQLType.IsTime() { var v = fmt.Sprintf("%s", d) temp += ", '" + strings.Replace(v, "'", "''", -1) + "'" } else if col.SQLType.IsBlob() { if reflect.TypeOf(d).Kind() == reflect.Slice { temp += fmt.Sprintf(", %s", dialect.FormatBytes(d.([]byte))) } else if reflect.TypeOf(d).Kind() == reflect.String { temp += fmt.Sprintf(", '%s'", d.(string)) } } else if col.SQLType.IsNumeric() { switch reflect.TypeOf(d).Kind() { case reflect.Slice: temp += fmt.Sprintf(", %s", string(d.([]byte))) default: temp += fmt.Sprintf(", %v", d) } } else { s := fmt.Sprintf("%v", d) if strings.Contains(s, ":") || strings.Contains(s, "-") { temp += fmt.Sprintf(", '%s'", s) } else { temp += fmt.Sprintf(", %s", s) } } } _, err = io.WriteString(w, temp[2:]+");\n") if err != nil { return err } } } return nil } // DumpAll dump database all table structs and data to w with specify db type func (engine *Engine) dumpTables(tables []*core.Table, w io.Writer, tp ...core.DbType) error { var dialect core.Dialect if len(tp) == 0 { dialect = engine.dialect } else { dialect = core.QueryDialect(tp[0]) if dialect == nil { return errors.New("Unsupported database type.") } dialect.Init(nil, engine.dialect.URI(), "", "") } _, err := io.WriteString(w, fmt.Sprintf("/*Generated by xorm v%s %s, from %s to %s*/\n\n", Version, time.Now().In(engine.TZLocation).Format("2006-01-02 15:04:05"), engine.dialect.DBType(), dialect.DBType())) if err != nil { return err } for i, table := range tables { if i > 0 { _, err = io.WriteString(w, "\n") if err != nil { return err } } _, err = io.WriteString(w, dialect.CreateTableSql(table, "", table.StoreEngine, "")+";\n") if err != nil { return err } for _, index := range table.Indexes { _, err = io.WriteString(w, dialect.CreateIndexSql(table.Name, index)+";\n") if err != nil { return err } } rows, err := engine.DB().Query("SELECT * FROM " + engine.Quote(table.Name)) if err != nil { return err } defer rows.Close() cols, err := rows.Columns() if err != nil { return err } if len(cols) == 0 { continue } for rows.Next() { dest := make([]interface{}, len(cols)) err = rows.ScanSlice(&dest) if err != nil { return err } _, err = io.WriteString(w, "INSERT INTO "+dialect.Quote(table.Name)+" ("+dialect.Quote(strings.Join(cols, dialect.Quote(", ")))+") VALUES (") if err != nil { return err } var temp string for i, d := range dest { col := table.GetColumn(cols[i]) if d == nil { temp += ", NULL" } else if col.SQLType.IsText() || col.SQLType.IsTime() { var v = fmt.Sprintf("%s", d) if strings.HasSuffix(v, " +0000 UTC") { temp += fmt.Sprintf(", '%s'", v[0:len(v)-len(" +0000 UTC")]) } else { temp += ", '" + strings.Replace(v, "'", "''", -1) + "'" } } else if col.SQLType.IsBlob() { if reflect.TypeOf(d).Kind() == reflect.Slice { temp += fmt.Sprintf(", %s", dialect.FormatBytes(d.([]byte))) } else if reflect.TypeOf(d).Kind() == reflect.String { temp += fmt.Sprintf(", '%s'", d.(string)) } } else if col.SQLType.IsNumeric() { switch reflect.TypeOf(d).Kind() { case reflect.Slice: temp += fmt.Sprintf(", %s", string(d.([]byte))) default: temp += fmt.Sprintf(", %v", d) } } else { s := fmt.Sprintf("%v", d) if strings.Contains(s, ":") || strings.Contains(s, "-") { if strings.HasSuffix(s, " +0000 UTC") { temp += fmt.Sprintf(", '%s'", s[0:len(s)-len(" +0000 UTC")]) } else { temp += fmt.Sprintf(", '%s'", s) } } else { temp += fmt.Sprintf(", %s", s) } } } _, err = io.WriteString(w, temp[2:]+");\n") if err != nil { return err } } } return nil } // Cascade use cascade or not func (engine *Engine) Cascade(trueOrFalse ...bool) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Cascade(trueOrFalse...) } // Where method provide a condition query func (engine *Engine) Where(querystring string, args ...interface{}) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Where(querystring, args...) } // Id will be depracated, please use ID instead func (engine *Engine) Id(id interface{}) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Id(id) } // ID mehtod provoide a condition as (id) = ? func (engine *Engine) ID(id interface{}) *Session { session := engine.NewSession() session.IsAutoClose = true return session.ID(id) } // Before apply before Processor, affected bean is passed to closure arg func (engine *Engine) Before(closures func(interface{})) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Before(closures) } // After apply after insert Processor, affected bean is passed to closure arg func (engine *Engine) After(closures func(interface{})) *Session { session := engine.NewSession() session.IsAutoClose = true return session.After(closures) } // Charset set charset when create table, only support mysql now func (engine *Engine) Charset(charset string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Charset(charset) } // StoreEngine set store engine when create table, only support mysql now func (engine *Engine) StoreEngine(storeEngine string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.StoreEngine(storeEngine) } // Distinct use for distinct columns. Caution: when you are using cache, // distinct will not be cached because cache system need id, // but distinct will not provide id func (engine *Engine) Distinct(columns ...string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Distinct(columns...) } // Select customerize your select columns or contents func (engine *Engine) Select(str string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Select(str) } // Cols only use the paramters as select or update columns func (engine *Engine) Cols(columns ...string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Cols(columns...) } // AllCols indicates that all columns should be use func (engine *Engine) AllCols() *Session { session := engine.NewSession() session.IsAutoClose = true return session.AllCols() } // MustCols specify some columns must use even if they are empty func (engine *Engine) MustCols(columns ...string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.MustCols(columns...) } // UseBool xorm automatically retrieve condition according struct, but // if struct has bool field, it will ignore them. So use UseBool // to tell system to do not ignore them. // If no paramters, it will use all the bool field of struct, or // it will use paramters's columns func (engine *Engine) UseBool(columns ...string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.UseBool(columns...) } // Omit only not use the paramters as select or update columns func (engine *Engine) Omit(columns ...string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Omit(columns...) } // Nullable set null when column is zero-value and nullable for update func (engine *Engine) Nullable(columns ...string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Nullable(columns...) } // In will generate "column IN (?, ?)" func (engine *Engine) In(column string, args ...interface{}) *Session { session := engine.NewSession() session.IsAutoClose = true return session.In(column, args...) } // Incr provides a update string like "column = column + ?" func (engine *Engine) Incr(column string, arg ...interface{}) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Incr(column, arg...) } // Decr provides a update string like "column = column - ?" func (engine *Engine) Decr(column string, arg ...interface{}) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Decr(column, arg...) } // SetExpr provides a update string like "column = {expression}" func (engine *Engine) SetExpr(column string, expression string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.SetExpr(column, expression) } // Table temporarily change the Get, Find, Update's table func (engine *Engine) Table(tableNameOrBean interface{}) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Table(tableNameOrBean) } // Alias set the table alias func (engine *Engine) Alias(alias string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Alias(alias) } // Limit will generate "LIMIT start, limit" func (engine *Engine) Limit(limit int, start ...int) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Limit(limit, start...) } // Desc will generate "ORDER BY column1 DESC, column2 DESC" func (engine *Engine) Desc(colNames ...string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Desc(colNames...) } // Asc will generate "ORDER BY column1,column2 Asc" // This method can chainable use. // // engine.Desc("name").Asc("age").Find(&users) // // SELECT * FROM user ORDER BY name DESC, age ASC // func (engine *Engine) Asc(colNames ...string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Asc(colNames...) } // OrderBy will generate "ORDER BY order" func (engine *Engine) OrderBy(order string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.OrderBy(order) } // Join the join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN func (engine *Engine) Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Join(joinOperator, tablename, condition, args...) } // GroupBy generate group by statement func (engine *Engine) GroupBy(keys string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.GroupBy(keys) } // Having generate having statement func (engine *Engine) Having(conditions string) *Session { session := engine.NewSession() session.IsAutoClose = true return session.Having(conditions) } func (engine *Engine) autoMapType(v reflect.Value) *core.Table { t := v.Type() engine.mutex.Lock() table, ok := engine.Tables[t] if !ok { table = engine.mapType(v) engine.Tables[t] = table if engine.Cacher != nil { if v.CanAddr() { engine.GobRegister(v.Addr().Interface()) } else { engine.GobRegister(v.Interface()) } } } engine.mutex.Unlock() return table } // GobRegister register one struct to gob for cache use func (engine *Engine) GobRegister(v interface{}) *Engine { //fmt.Printf("Type: %[1]T => Data: %[1]#v\n", v) gob.Register(v) return engine } // Table table struct type Table struct { *core.Table Name string } // TableInfo get table info according to bean's content func (engine *Engine) TableInfo(bean interface{}) *Table { v := rValue(bean) return &Table{engine.autoMapType(v), engine.tbName(v)} } func addIndex(indexName string, table *core.Table, col *core.Column, indexType int) { if index, ok := table.Indexes[indexName]; ok { index.AddColumn(col.Name) col.Indexes[index.Name] = indexType } else { index := core.NewIndex(indexName, indexType) index.AddColumn(col.Name) table.AddIndex(index) col.Indexes[index.Name] = indexType } } func (engine *Engine) newTable() *core.Table { table := core.NewEmptyTable() if !engine.disableGlobalCache { table.Cacher = engine.Cacher } return table } // TableName table name interface to define customerize table name type TableName interface { TableName() string } func (engine *Engine) mapType(v reflect.Value) *core.Table { t := v.Type() table := engine.newTable() if tb, ok := v.Interface().(TableName); ok { table.Name = tb.TableName() } else { if v.CanAddr() { if tb, ok = v.Addr().Interface().(TableName); ok { table.Name = tb.TableName() } } if table.Name == "" { table.Name = engine.TableMapper.Obj2Table(t.Name()) } } table.Type = t var idFieldColName string var err error var hasCacheTag, hasNoCacheTag bool for i := 0; i < t.NumField(); i++ { tag := t.Field(i).Tag ormTagStr := tag.Get(engine.TagIdentifier) var col *core.Column fieldValue := v.Field(i) fieldType := fieldValue.Type() if ormTagStr != "" { col = &core.Column{FieldName: t.Field(i).Name, Nullable: true, IsPrimaryKey: false, IsAutoIncrement: false, MapType: core.TWOSIDES, Indexes: make(map[string]int)} tags := splitTag(ormTagStr) if len(tags) > 0 { if tags[0] == "-" { continue } if strings.ToUpper(tags[0]) == "EXTENDS" { switch fieldValue.Kind() { case reflect.Ptr: f := fieldValue.Type().Elem() if f.Kind() == reflect.Struct { fieldPtr := fieldValue fieldValue = fieldValue.Elem() if !fieldValue.IsValid() || fieldPtr.IsNil() { fieldValue = reflect.New(f).Elem() } } fallthrough case reflect.Struct: parentTable := engine.mapType(fieldValue) for _, col := range parentTable.Columns() { col.FieldName = fmt.Sprintf("%v.%v", t.Field(i).Name, col.FieldName) table.AddColumn(col) for indexName, indexType := range col.Indexes { addIndex(indexName, table, col, indexType) } } continue default: //TODO: warning } } indexNames := make(map[string]int) var isIndex, isUnique bool var preKey string for j, key := range tags { k := strings.ToUpper(key) switch { case k == "<-": col.MapType = core.ONLYFROMDB case k == "->": col.MapType = core.ONLYTODB case k == "PK": col.IsPrimaryKey = true col.Nullable = false case k == "NULL": if j == 0 { col.Nullable = true } else { col.Nullable = (strings.ToUpper(tags[j-1]) != "NOT") } // TODO: for postgres how add autoincr? /*case strings.HasPrefix(k, "AUTOINCR(") && strings.HasSuffix(k, ")"): col.IsAutoIncrement = true autoStart := k[len("AUTOINCR")+1 : len(k)-1] autoStartInt, err := strconv.Atoi(autoStart) if err != nil { engine.LogError(err) } col.AutoIncrStart = autoStartInt*/ case k == "AUTOINCR": col.IsAutoIncrement = true //col.AutoIncrStart = 1 case k == "DEFAULT": col.Default = tags[j+1] case k == "CREATED": col.IsCreated = true case k == "VERSION": col.IsVersion = true col.Default = "1" case k == "UTC": col.TimeZone = time.UTC case k == "LOCAL": col.TimeZone = time.Local case strings.HasPrefix(k, "LOCALE(") && strings.HasSuffix(k, ")"): location := k[len("INDEX")+1 : len(k)-1] col.TimeZone, err = time.LoadLocation(location) if err != nil { engine.logger.Error(err) } case k == "UPDATED": col.IsUpdated = true case k == "DELETED": col.IsDeleted = true case strings.HasPrefix(k, "INDEX(") && strings.HasSuffix(k, ")"): indexName := k[len("INDEX")+1 : len(k)-1] indexNames[indexName] = core.IndexType case k == "INDEX": isIndex = true case strings.HasPrefix(k, "UNIQUE(") && strings.HasSuffix(k, ")"): indexName := k[len("UNIQUE")+1 : len(k)-1] indexNames[indexName] = core.UniqueType case k == "UNIQUE": isUnique = true case k == "NOTNULL": col.Nullable = false case k == "CACHE": if !hasCacheTag { hasCacheTag = true } case k == "NOCACHE": if !hasNoCacheTag { hasNoCacheTag = true } case k == "NOT": default: if strings.HasPrefix(k, "'") && strings.HasSuffix(k, "'") { if preKey != "DEFAULT" { col.Name = key[1 : len(key)-1] } } else if strings.Contains(k, "(") && strings.HasSuffix(k, ")") { fs := strings.Split(k, "(") if _, ok := core.SqlTypes[fs[0]]; !ok { preKey = k continue } col.SQLType = core.SQLType{Name: fs[0]} if fs[0] == core.Enum && fs[1][0] == '\'' { //enum options := strings.Split(fs[1][0:len(fs[1])-1], ",") col.EnumOptions = make(map[string]int) for k, v := range options { v = strings.TrimSpace(v) v = strings.Trim(v, "'") col.EnumOptions[v] = k } } else if fs[0] == core.Set && fs[1][0] == '\'' { //set options := strings.Split(fs[1][0:len(fs[1])-1], ",") col.SetOptions = make(map[string]int) for k, v := range options { v = strings.TrimSpace(v) v = strings.Trim(v, "'") col.SetOptions[v] = k } } else { fs2 := strings.Split(fs[1][0:len(fs[1])-1], ",") if len(fs2) == 2 { col.Length, err = strconv.Atoi(fs2[0]) if err != nil { engine.logger.Error(err) } col.Length2, err = strconv.Atoi(fs2[1]) if err != nil { engine.logger.Error(err) } } else if len(fs2) == 1 { col.Length, err = strconv.Atoi(fs2[0]) if err != nil { engine.logger.Error(err) } } } } else { if _, ok := core.SqlTypes[k]; ok { col.SQLType = core.SQLType{Name: k} } else if key != col.Default { col.Name = key } } engine.dialect.SqlType(col) } preKey = k } if col.SQLType.Name == "" { col.SQLType = core.Type2SQLType(fieldType) } if col.Length == 0 { col.Length = col.SQLType.DefaultLength } if col.Length2 == 0 { col.Length2 = col.SQLType.DefaultLength2 } if col.Name == "" { col.Name = engine.ColumnMapper.Obj2Table(t.Field(i).Name) } if isUnique { indexNames[col.Name] = core.UniqueType } else if isIndex { indexNames[col.Name] = core.IndexType } for indexName, indexType := range indexNames { addIndex(indexName, table, col, indexType) } } } else { var sqlType core.SQLType if fieldValue.CanAddr() { if _, ok := fieldValue.Addr().Interface().(core.Conversion); ok { sqlType = core.SQLType{Name: core.Text} } } if _, ok := fieldValue.Interface().(core.Conversion); ok { sqlType = core.SQLType{Name: core.Text} } else { sqlType = core.Type2SQLType(fieldType) } col = core.NewColumn(engine.ColumnMapper.Obj2Table(t.Field(i).Name), t.Field(i).Name, sqlType, sqlType.DefaultLength, sqlType.DefaultLength2, true) } if col.IsAutoIncrement { col.Nullable = false } table.AddColumn(col) if fieldType.Kind() == reflect.Int64 && (strings.ToUpper(col.FieldName) == "ID" || strings.HasSuffix(strings.ToUpper(col.FieldName), ".ID")) { idFieldColName = col.Name } } // end for if idFieldColName != "" && len(table.PrimaryKeys) == 0 { col := table.GetColumn(idFieldColName) col.IsPrimaryKey = true col.IsAutoIncrement = true col.Nullable = false table.PrimaryKeys = append(table.PrimaryKeys, col.Name) table.AutoIncrement = col.Name } if hasCacheTag { if engine.Cacher != nil { // !nash! use engine's cacher if provided engine.logger.Info("enable cache on table:", table.Name) table.Cacher = engine.Cacher } else { engine.logger.Info("enable LRU cache on table:", table.Name) table.Cacher = NewLRUCacher2(NewMemoryStore(), time.Hour, 10000) // !nashtsai! HACK use LRU cacher for now } } if hasNoCacheTag { engine.logger.Info("no cache on table:", table.Name) table.Cacher = nil } return table } // Map a struct to a table func (engine *Engine) mapping(beans ...interface{}) (e error) { engine.mutex.Lock() defer engine.mutex.Unlock() for _, bean := range beans { v := rValue(bean) engine.Tables[v.Type()] = engine.mapType(v) } return } // IsTableEmpty if a table has any reocrd func (engine *Engine) IsTableEmpty(bean interface{}) (bool, error) { session := engine.NewSession() defer session.Close() return session.IsTableEmpty(bean) } // IsTableExist if a table is exist func (engine *Engine) IsTableExist(beanOrTableName interface{}) (bool, error) { session := engine.NewSession() defer session.Close() return session.IsTableExist(beanOrTableName) } // IdOf get id from one struct func (engine *Engine) IdOf(bean interface{}) core.PK { return engine.IdOfV(reflect.ValueOf(bean)) } // IdOfV get id from one value of struct func (engine *Engine) IdOfV(rv reflect.Value) core.PK { v := reflect.Indirect(rv) table := engine.autoMapType(v) pk := make([]interface{}, len(table.PrimaryKeys)) for i, col := range table.PKColumns() { pkField := v.FieldByName(col.FieldName) switch pkField.Kind() { case reflect.String: pk[i] = pkField.String() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: pk[i] = pkField.Int() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: pk[i] = pkField.Uint() } } return core.PK(pk) } // CreateIndexes create indexes func (engine *Engine) CreateIndexes(bean interface{}) error { session := engine.NewSession() defer session.Close() return session.CreateIndexes(bean) } // CreateUniques create uniques func (engine *Engine) CreateUniques(bean interface{}) error { session := engine.NewSession() defer session.Close() return session.CreateUniques(bean) } func (engine *Engine) getCacher2(table *core.Table) core.Cacher { return table.Cacher } func (engine *Engine) getCacher(v reflect.Value) core.Cacher { if table := engine.autoMapType(v); table != nil { return table.Cacher } return engine.Cacher } // ClearCacheBean if enabled cache, clear the cache bean func (engine *Engine) ClearCacheBean(bean interface{}, id string) error { v := rValue(bean) t := v.Type() if t.Kind() != reflect.Struct { return errors.New("error params") } tableName := engine.tbName(v) table := engine.autoMapType(v) cacher := table.Cacher if cacher == nil { cacher = engine.Cacher } if cacher != nil { cacher.ClearIds(tableName) cacher.DelBean(tableName, id) } return nil } // ClearCache if enabled cache, clear some tables' cache func (engine *Engine) ClearCache(beans ...interface{}) error { for _, bean := range beans { v := rValue(bean) t := v.Type() if t.Kind() != reflect.Struct { return errors.New("error params") } tableName := engine.tbName(v) table := engine.autoMapType(v) cacher := table.Cacher if cacher == nil { cacher = engine.Cacher } if cacher != nil { cacher.ClearIds(tableName) cacher.ClearBeans(tableName) } } return nil } // Sync the new struct changes to database, this method will automatically add // table, column, index, unique. but will not delete or change anything. // If you change some field, you should change the database manually. func (engine *Engine) Sync(beans ...interface{}) error { for _, bean := range beans { v := rValue(bean) tableName := engine.tbName(v) table := engine.autoMapType(v) s := engine.NewSession() defer s.Close() isExist, err := s.Table(bean).isTableExist(tableName) if err != nil { return err } if !isExist { err = engine.CreateTables(bean) if err != nil { return err } } /*isEmpty, err := engine.IsEmptyTable(bean) if err != nil { return err }*/ var isEmpty bool if isEmpty { err = engine.DropTables(bean) if err != nil { return err } err = engine.CreateTables(bean) if err != nil { return err } } else { for _, col := range table.Columns() { session := engine.NewSession() session.Statement.RefTable = table defer session.Close() isExist, err := session.Engine.dialect.IsColumnExist(tableName, col.Name) if err != nil { return err } if !isExist { session := engine.NewSession() session.Statement.RefTable = table defer session.Close() err = session.addColumn(col.Name) if err != nil { return err } } } for name, index := range table.Indexes { session := engine.NewSession() session.Statement.RefTable = table defer session.Close() if index.Type == core.UniqueType { //isExist, err := session.isIndexExist(table.Name, name, true) isExist, err := session.isIndexExist2(tableName, index.Cols, true) if err != nil { return err } if !isExist { session := engine.NewSession() session.Statement.RefTable = table defer session.Close() err = session.addUnique(tableName, name) if err != nil { return err } } } else if index.Type == core.IndexType { isExist, err := session.isIndexExist2(tableName, index.Cols, false) if err != nil { return err } if !isExist { session := engine.NewSession() session.Statement.RefTable = table defer session.Close() err = session.addIndex(tableName, name) if err != nil { return err } } } else { return errors.New("unknow index type") } } } } return nil } // Sync2 synchronize structs to database tables func (engine *Engine) Sync2(beans ...interface{}) error { s := engine.NewSession() defer s.Close() return s.Sync2(beans...) } func (engine *Engine) unMap(beans ...interface{}) (e error) { engine.mutex.Lock() defer engine.mutex.Unlock() for _, bean := range beans { t := rType(bean) if _, ok := engine.Tables[t]; ok { delete(engine.Tables, t) } } return } // Drop all mapped table func (engine *Engine) dropAll() error { session := engine.NewSession() defer session.Close() err := session.Begin() if err != nil { return err } err = session.dropAll() if err != nil { session.Rollback() return err } return session.Commit() } // CreateTables create tabls according bean func (engine *Engine) CreateTables(beans ...interface{}) error { session := engine.NewSession() defer session.Close() err := session.Begin() if err != nil { return err } for _, bean := range beans { err = session.CreateTable(bean) if err != nil { session.Rollback() return err } } return session.Commit() } // DropTables drop specify tables func (engine *Engine) DropTables(beans ...interface{}) error { session := engine.NewSession() defer session.Close() err := session.Begin() if err != nil { return err } for _, bean := range beans { err = session.DropTable(bean) if err != nil { session.Rollback() return err } } return session.Commit() } func (engine *Engine) createAll() error { session := engine.NewSession() defer session.Close() return session.createAll() } // Exec raw sql func (engine *Engine) Exec(sql string, args ...interface{}) (sql.Result, error) { session := engine.NewSession() defer session.Close() return session.Exec(sql, args...) } // Query a raw sql and return records as []map[string][]byte func (engine *Engine) Query(sql string, paramStr ...interface{}) (resultsSlice []map[string][]byte, err error) { session := engine.NewSession() defer session.Close() return session.Query(sql, paramStr...) } // Insert one or more records func (engine *Engine) Insert(beans ...interface{}) (int64, error) { session := engine.NewSession() defer session.Close() return session.Insert(beans...) } // InsertOne insert only one record func (engine *Engine) InsertOne(bean interface{}) (int64, error) { session := engine.NewSession() defer session.Close() return session.InsertOne(bean) } // Update records, bean's non-empty fields are updated contents, // condiBean' non-empty filds are conditions // CAUTION: // 1.bool will defaultly be updated content nor conditions // You should call UseBool if you have bool to use. // 2.float32 & float64 may be not inexact as conditions func (engine *Engine) Update(bean interface{}, condiBeans ...interface{}) (int64, error) { session := engine.NewSession() defer session.Close() return session.Update(bean, condiBeans...) } // Delete records, bean's non-empty fields are conditions func (engine *Engine) Delete(bean interface{}) (int64, error) { session := engine.NewSession() defer session.Close() return session.Delete(bean) } // Get retrieve one record from table, bean's non-empty fields // are conditions func (engine *Engine) Get(bean interface{}) (bool, error) { session := engine.NewSession() defer session.Close() return session.Get(bean) } // Find retrieve records from table, condiBeans's non-empty fields // are conditions. beans could be []Struct, []*Struct, map[int64]Struct // map[int64]*Struct func (engine *Engine) Find(beans interface{}, condiBeans ...interface{}) error { session := engine.NewSession() defer session.Close() return session.Find(beans, condiBeans...) } // Iterate record by record handle records from table, bean's non-empty fields // are conditions. func (engine *Engine) Iterate(bean interface{}, fun IterFunc) error { session := engine.NewSession() defer session.Close() return session.Iterate(bean, fun) } // Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields // are conditions. func (engine *Engine) Rows(bean interface{}) (*Rows, error) { session := engine.NewSession() return session.Rows(bean) } // Count counts the records. bean's non-empty fields are conditions. func (engine *Engine) Count(bean interface{}) (int64, error) { session := engine.NewSession() defer session.Close() return session.Count(bean) } // Sum sum the records by some column. bean's non-empty fields are conditions. func (engine *Engine) Sum(bean interface{}, colName string) (float64, error) { session := engine.NewSession() defer session.Close() return session.Sum(bean, colName) } // Sums sum the records by some columns. bean's non-empty fields are conditions. func (engine *Engine) Sums(bean interface{}, colNames ...string) ([]float64, error) { session := engine.NewSession() defer session.Close() return session.Sums(bean, colNames...) } // SumsInt like Sums but return slice of int64 instead of float64. func (engine *Engine) SumsInt(bean interface{}, colNames ...string) ([]int64, error) { session := engine.NewSession() defer session.Close() return session.SumsInt(bean, colNames...) } // ImportFile SQL DDL file func (engine *Engine) ImportFile(ddlPath string) ([]sql.Result, error) { file, err := os.Open(ddlPath) if err != nil { return nil, err } defer file.Close() return engine.Import(file) } // Import SQL DDL from io.Reader func (engine *Engine) Import(r io.Reader) ([]sql.Result, error) { var results []sql.Result var lastError error scanner := bufio.NewScanner(r) semiColSpliter := func(data []byte, atEOF bool) (advance int, token []byte, err error) { if atEOF && len(data) == 0 { return 0, nil, nil } if i := bytes.IndexByte(data, ';'); i >= 0 { return i + 1, data[0:i], nil } // If we're at EOF, we have a final, non-terminated line. Return it. if atEOF { return len(data), data, nil } // Request more data. return 0, nil, nil } scanner.Split(semiColSpliter) for scanner.Scan() { query := strings.Trim(scanner.Text(), " \t\n\r") if len(query) > 0 { engine.logSQL(query) result, err := engine.DB().Exec(query) results = append(results, result) if err != nil { return nil, err //lastError = err } } } return results, lastError } // TZTime change one time to xorm time location func (engine *Engine) TZTime(t time.Time) time.Time { if !t.IsZero() { // if time is not initialized it's not suitable for Time.In() return t.In(engine.TZLocation) } return t } // NowTime return current time func (engine *Engine) NowTime(sqlTypeName string) interface{} { t := time.Now() return engine.FormatTime(sqlTypeName, t) } // NowTime2 return current time func (engine *Engine) NowTime2(sqlTypeName string) (interface{}, time.Time) { t := time.Now() return engine.FormatTime(sqlTypeName, t), t } // FormatTime format time func (engine *Engine) FormatTime(sqlTypeName string, t time.Time) (v interface{}) { return engine.formatTime(engine.TZLocation, sqlTypeName, t) } func (engine *Engine) formatColTime(col *core.Column, t time.Time) (v interface{}) { if col.DisableTimeZone { return engine.formatTime(nil, col.SQLType.Name, t) } else if col.TimeZone != nil { return engine.formatTime(col.TimeZone, col.SQLType.Name, t) } return engine.formatTime(engine.TZLocation, col.SQLType.Name, t) } func (engine *Engine) formatTime(tz *time.Location, sqlTypeName string, t time.Time) (v interface{}) { if engine.dialect.DBType() == core.ORACLE { return t } if tz != nil { t = engine.TZTime(t) } switch sqlTypeName { case core.Time: s := t.Format("2006-01-02 15:04:05") //time.RFC3339 v = s[11:19] case core.Date: v = t.Format("2006-01-02") case core.DateTime, core.TimeStamp: if engine.dialect.DBType() == "ql" { v = t } else if engine.dialect.DBType() == "sqlite3" { v = t.UTC().Format("2006-01-02 15:04:05") } else { v = t.Format("2006-01-02 15:04:05") } case core.TimeStampz: if engine.dialect.DBType() == core.MSSQL { v = t.Format("2006-01-02T15:04:05.9999999Z07:00") } else if engine.DriverName() == "mssql" { v = t } else { v = t.Format(time.RFC3339Nano) } case core.BigInt, core.Int: v = t.Unix() default: v = t } return } // Unscoped always disable struct tag "deleted" func (engine *Engine) Unscoped() *Session { session := engine.NewSession() session.IsAutoClose = true return session.Unscoped() } ================================================ FILE: src/github.com/go-xorm/xorm/error.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "errors" ) var ( ErrParamsType error = errors.New("Params type error") ErrTableNotFound error = errors.New("Not found table") ErrUnSupportedType error = errors.New("Unsupported type error") ErrNotExist error = errors.New("Not exist error") ErrCacheFailed error = errors.New("Cache failed") ErrNeedDeletedCond error = errors.New("Delete need at least one condition") ErrNotImplemented error = errors.New("Not implemented.") ) ================================================ FILE: src/github.com/go-xorm/xorm/gen_reserved.sh ================================================ #!/bin/bash if [ -f $1 ];then cat $1| awk '{printf("\""$1"\":true,\n")}' else echo "argument $1 if not a file!" fi ================================================ FILE: src/github.com/go-xorm/xorm/goracle_driver.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "errors" "regexp" "github.com/go-xorm/core" ) // func init() { // core.RegisterDriver("goracle", &goracleDriver{}) // } type goracleDriver struct { } func (cfg *goracleDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) { db := &core.Uri{DbType: core.ORACLE} dsnPattern := regexp.MustCompile( `^(?:(?P.*?)(?::(?P.*))?@)?` + // [user[:password]@] `(?:(?P[^\(]*)(?:\((?P[^\)]*)\))?)?` + // [net[(addr)]] `\/(?P.*?)` + // /dbname `(?:\?(?P[^\?]*))?$`) // [?param1=value1¶mN=valueN] matches := dsnPattern.FindStringSubmatch(dataSourceName) //tlsConfigRegister := make(map[string]*tls.Config) names := dsnPattern.SubexpNames() for i, match := range matches { switch names[i] { case "dbname": db.DbName = match } } if db.DbName == "" { return nil, errors.New("dbname is empty") } return db, nil } ================================================ FILE: src/github.com/go-xorm/xorm/helpers.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "errors" "fmt" "reflect" "sort" "strconv" "strings" "time" "github.com/go-xorm/core" ) // str2PK convert string value to primary key value according to tp func str2PK(s string, tp reflect.Type) (interface{}, error) { var err error var result interface{} switch tp.Kind() { case reflect.Int: result, err = strconv.Atoi(s) if err != nil { return nil, errors.New("convert " + s + " as int: " + err.Error()) } case reflect.Int8: x, err := strconv.Atoi(s) if err != nil { return nil, errors.New("convert " + s + " as int16: " + err.Error()) } result = int8(x) case reflect.Int16: x, err := strconv.Atoi(s) if err != nil { return nil, errors.New("convert " + s + " as int16: " + err.Error()) } result = int16(x) case reflect.Int32: x, err := strconv.Atoi(s) if err != nil { return nil, errors.New("convert " + s + " as int32: " + err.Error()) } result = int32(x) case reflect.Int64: result, err = strconv.ParseInt(s, 10, 64) if err != nil { return nil, errors.New("convert " + s + " as int64: " + err.Error()) } case reflect.Uint: x, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, errors.New("convert " + s + " as uint: " + err.Error()) } result = uint(x) case reflect.Uint8: x, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, errors.New("convert " + s + " as uint8: " + err.Error()) } result = uint8(x) case reflect.Uint16: x, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, errors.New("convert " + s + " as uint16: " + err.Error()) } result = uint16(x) case reflect.Uint32: x, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, errors.New("convert " + s + " as uint32: " + err.Error()) } result = uint32(x) case reflect.Uint64: result, err = strconv.ParseUint(s, 10, 64) if err != nil { return nil, errors.New("convert " + s + " as uint64: " + err.Error()) } case reflect.String: result = s default: panic("unsupported convert type") } result = reflect.ValueOf(result).Convert(tp).Interface() return result, nil } func splitTag(tag string) (tags []string) { tag = strings.TrimSpace(tag) var hasQuote = false var lastIdx = 0 for i, t := range tag { if t == '\'' { hasQuote = !hasQuote } else if t == ' ' { if lastIdx < i && !hasQuote { tags = append(tags, strings.TrimSpace(tag[lastIdx:i])) lastIdx = i + 1 } } } if lastIdx < len(tag) { tags = append(tags, strings.TrimSpace(tag[lastIdx:len(tag)])) } return } type zeroable interface { IsZero() bool } func isZero(k interface{}) bool { switch k.(type) { case int: return k.(int) == 0 case int8: return k.(int8) == 0 case int16: return k.(int16) == 0 case int32: return k.(int32) == 0 case int64: return k.(int64) == 0 case uint: return k.(uint) == 0 case uint8: return k.(uint8) == 0 case uint16: return k.(uint16) == 0 case uint32: return k.(uint32) == 0 case uint64: return k.(uint64) == 0 case float32: return k.(float32) == 0 case float64: return k.(float64) == 0 case bool: return k.(bool) == false case string: return k.(string) == "" case zeroable: return k.(zeroable).IsZero() } return false } func isStructZero(v reflect.Value) bool { if !v.IsValid() { return true } for i := 0; i < v.NumField(); i++ { field := v.Field(i) switch field.Kind() { case reflect.Ptr: field = field.Elem() fallthrough case reflect.Struct: if !isStructZero(field) { return false } default: if field.CanInterface() && !isZero(field.Interface()) { return false } } } return true } func int64ToIntValue(id int64, tp reflect.Type) reflect.Value { var v interface{} switch tp.Kind() { case reflect.Int16: v = int16(id) case reflect.Int32: v = int32(id) case reflect.Int: v = int(id) case reflect.Int64: v = id case reflect.Uint16: v = uint16(id) case reflect.Uint32: v = uint32(id) case reflect.Uint64: v = uint64(id) case reflect.Uint: v = uint(id) } return reflect.ValueOf(v).Convert(tp) } func int64ToInt(id int64, tp reflect.Type) interface{} { return int64ToIntValue(id, tp).Interface() } func isPKZero(pk core.PK) bool { for _, k := range pk { if isZero(k) { return true } } return false } func equalNoCase(s1, s2 string) bool { return strings.ToLower(s1) == strings.ToLower(s2) } func indexNoCase(s, sep string) int { return strings.Index(strings.ToLower(s), strings.ToLower(sep)) } func splitNoCase(s, sep string) []string { idx := indexNoCase(s, sep) if idx < 0 { return []string{s} } return strings.Split(s, s[idx:idx+len(sep)]) } func splitNNoCase(s, sep string, n int) []string { idx := indexNoCase(s, sep) if idx < 0 { return []string{s} } return strings.SplitN(s, s[idx:idx+len(sep)], n) } func makeArray(elem string, count int) []string { res := make([]string, count) for i := 0; i < count; i++ { res[i] = elem } return res } func rValue(bean interface{}) reflect.Value { return reflect.Indirect(reflect.ValueOf(bean)) } func rType(bean interface{}) reflect.Type { sliceValue := reflect.Indirect(reflect.ValueOf(bean)) //return reflect.TypeOf(sliceValue.Interface()) return sliceValue.Type() } func structName(v reflect.Type) string { for v.Kind() == reflect.Ptr { v = v.Elem() } return v.Name() } func col2NewCols(columns ...string) []string { newColumns := make([]string, 0, len(columns)) for _, col := range columns { col = strings.Replace(col, "`", "", -1) col = strings.Replace(col, `"`, "", -1) ccols := strings.Split(col, ",") for _, c := range ccols { newColumns = append(newColumns, strings.TrimSpace(c)) } } return newColumns } func sliceEq(left, right []string) bool { if len(left) != len(right) { return false } sort.Sort(sort.StringSlice(left)) sort.Sort(sort.StringSlice(right)) for i := 0; i < len(left); i++ { if left[i] != right[i] { return false } } return true } func reflect2value(rawValue *reflect.Value) (str string, err error) { aa := reflect.TypeOf((*rawValue).Interface()) vv := reflect.ValueOf((*rawValue).Interface()) switch aa.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: str = strconv.FormatInt(vv.Int(), 10) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: str = strconv.FormatUint(vv.Uint(), 10) case reflect.Float32, reflect.Float64: str = strconv.FormatFloat(vv.Float(), 'f', -1, 64) case reflect.String: str = vv.String() case reflect.Array, reflect.Slice: switch aa.Elem().Kind() { case reflect.Uint8: data := rawValue.Interface().([]byte) str = string(data) default: err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name()) } // time type case reflect.Struct: if aa.ConvertibleTo(core.TimeType) { str = vv.Convert(core.TimeType).Interface().(time.Time).Format(time.RFC3339Nano) } else { err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name()) } case reflect.Bool: str = strconv.FormatBool(vv.Bool()) case reflect.Complex128, reflect.Complex64: str = fmt.Sprintf("%v", vv.Complex()) /* TODO: unsupported types below case reflect.Map: case reflect.Ptr: case reflect.Uintptr: case reflect.UnsafePointer: case reflect.Chan, reflect.Func, reflect.Interface: */ default: err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name()) } return } func value2Bytes(rawValue *reflect.Value) (data []byte, err error) { var str string str, err = reflect2value(rawValue) if err != nil { return } data = []byte(str) return } func value2String(rawValue *reflect.Value) (data string, err error) { data, err = reflect2value(rawValue) if err != nil { return } return } func rows2Strings(rows *core.Rows) (resultsSlice []map[string]string, err error) { fields, err := rows.Columns() if err != nil { return nil, err } for rows.Next() { result, err := row2mapStr(rows, fields) if err != nil { return nil, err } resultsSlice = append(resultsSlice, result) } return resultsSlice, nil } func rows2maps(rows *core.Rows) (resultsSlice []map[string][]byte, err error) { fields, err := rows.Columns() if err != nil { return nil, err } for rows.Next() { result, err := row2map(rows, fields) if err != nil { return nil, err } resultsSlice = append(resultsSlice, result) } return resultsSlice, nil } func row2map(rows *core.Rows, fields []string) (resultsMap map[string][]byte, err error) { result := make(map[string][]byte) scanResultContainers := make([]interface{}, len(fields)) for i := 0; i < len(fields); i++ { var scanResultContainer interface{} scanResultContainers[i] = &scanResultContainer } if err := rows.Scan(scanResultContainers...); err != nil { return nil, err } for ii, key := range fields { rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii])) //if row is null then ignore if rawValue.Interface() == nil { //fmt.Println("ignore ...", key, rawValue) continue } if data, err := value2Bytes(&rawValue); err == nil { result[key] = data } else { return nil, err // !nashtsai! REVIEW, should return err or just error log? } } return result, nil } func row2mapStr(rows *core.Rows, fields []string) (resultsMap map[string]string, err error) { result := make(map[string]string) scanResultContainers := make([]interface{}, len(fields)) for i := 0; i < len(fields); i++ { var scanResultContainer interface{} scanResultContainers[i] = &scanResultContainer } if err := rows.Scan(scanResultContainers...); err != nil { return nil, err } for ii, key := range fields { rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii])) //if row is null then ignore if rawValue.Interface() == nil { //fmt.Println("ignore ...", key, rawValue) continue } if data, err := value2String(&rawValue); err == nil { result[key] = data } else { return nil, err // !nashtsai! REVIEW, should return err or just error log? } } return result, nil } func txQuery2(tx *core.Tx, sqlStr string, params ...interface{}) (resultsSlice []map[string]string, err error) { rows, err := tx.Query(sqlStr, params...) if err != nil { return nil, err } defer rows.Close() return rows2Strings(rows) } func query2(db *core.DB, sqlStr string, params ...interface{}) (resultsSlice []map[string]string, err error) { s, err := db.Prepare(sqlStr) if err != nil { return nil, err } defer s.Close() rows, err := s.Query(params...) if err != nil { return nil, err } defer rows.Close() return rows2Strings(rows) } func setColumnInt(bean interface{}, col *core.Column, t int64) { v, err := col.ValueOf(bean) if err != nil { return } if v.CanSet() { switch v.Type().Kind() { case reflect.Int, reflect.Int64, reflect.Int32: v.SetInt(t) case reflect.Uint, reflect.Uint64, reflect.Uint32: v.SetUint(uint64(t)) } } } func setColumnTime(bean interface{}, col *core.Column, t time.Time) { v, err := col.ValueOf(bean) if err != nil { return } if v.CanSet() { switch v.Type().Kind() { case reflect.Struct: v.Set(reflect.ValueOf(t).Convert(v.Type())) case reflect.Int, reflect.Int64, reflect.Int32: v.SetInt(t.Unix()) case reflect.Uint, reflect.Uint64, reflect.Uint32: v.SetUint(uint64(t.Unix())) } } } func genCols(table *core.Table, session *Session, bean interface{}, useCol bool, includeQuote bool) ([]string, []interface{}, error) { colNames := make([]string, 0, len(table.ColumnsSeq())) args := make([]interface{}, 0, len(table.ColumnsSeq())) for _, col := range table.Columns() { lColName := strings.ToLower(col.Name) if useCol && !col.IsVersion && !col.IsCreated && !col.IsUpdated { if _, ok := session.Statement.columnMap[lColName]; !ok { continue } } if col.MapType == core.ONLYFROMDB { continue } fieldValuePtr, err := col.ValueOf(bean) if err != nil { return nil, nil, err } fieldValue := *fieldValuePtr if col.IsAutoIncrement { switch fieldValue.Type().Kind() { case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int, reflect.Int64: if fieldValue.Int() == 0 { continue } case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64: if fieldValue.Uint() == 0 { continue } case reflect.String: if len(fieldValue.String()) == 0 { continue } } } if col.IsDeleted { continue } if session.Statement.ColumnStr != "" { if _, ok := session.Statement.columnMap[lColName]; !ok { continue } } if session.Statement.OmitStr != "" { if _, ok := session.Statement.columnMap[lColName]; ok { continue } } // !evalphobia! set fieldValue as nil when column is nullable and zero-value if _, ok := session.Statement.nullableMap[lColName]; ok { if col.Nullable && isZero(fieldValue.Interface()) { var nilValue *int fieldValue = reflect.ValueOf(nilValue) } } if (col.IsCreated || col.IsUpdated) && session.Statement.UseAutoTime { val, t := session.Engine.NowTime2(col.SQLType.Name) args = append(args, val) var colName = col.Name session.afterClosures = append(session.afterClosures, func(bean interface{}) { col := table.GetColumn(colName) setColumnTime(bean, col, t) }) } else if col.IsVersion && session.Statement.checkVersion { args = append(args, 1) } else { arg, err := session.value2Interface(col, fieldValue) if err != nil { return colNames, args, err } args = append(args, arg) } if includeQuote { colNames = append(colNames, session.Engine.Quote(col.Name)+" = ?") } else { colNames = append(colNames, col.Name) } } return colNames, args, nil } func indexName(tableName, idxName string) string { return fmt.Sprintf("IDX_%v_%v", tableName, idxName) } ================================================ FILE: src/github.com/go-xorm/xorm/logger.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "fmt" "io" "log" "github.com/go-xorm/core" ) const ( DEFAULT_LOG_PREFIX = "[xorm]" DEFAULT_LOG_FLAG = log.Ldate | log.Lmicroseconds DEFAULT_LOG_LEVEL = core.LOG_DEBUG ) var _ core.ILogger = DiscardLogger{} type DiscardLogger struct{} func (DiscardLogger) Debug(v ...interface{}) {} func (DiscardLogger) Debugf(format string, v ...interface{}) {} func (DiscardLogger) Error(v ...interface{}) {} func (DiscardLogger) Errorf(format string, v ...interface{}) {} func (DiscardLogger) Info(v ...interface{}) {} func (DiscardLogger) Infof(format string, v ...interface{}) {} func (DiscardLogger) Warn(v ...interface{}) {} func (DiscardLogger) Warnf(format string, v ...interface{}) {} func (DiscardLogger) Level() core.LogLevel { return core.LOG_UNKNOWN } func (DiscardLogger) SetLevel(l core.LogLevel) {} func (DiscardLogger) ShowSQL(show ...bool) {} func (DiscardLogger) IsShowSQL() bool { return false } // SimpleLogger is the default implment of core.ILogger type SimpleLogger struct { DEBUG *log.Logger ERR *log.Logger INFO *log.Logger WARN *log.Logger level core.LogLevel showSQL bool } var _ core.ILogger = &SimpleLogger{} // NewSimpleLogger use a special io.Writer as logger output func NewSimpleLogger(out io.Writer) *SimpleLogger { return NewSimpleLogger2(out, DEFAULT_LOG_PREFIX, DEFAULT_LOG_FLAG) } // NewSimpleLogger2 let you customrize your logger prefix and flag func NewSimpleLogger2(out io.Writer, prefix string, flag int) *SimpleLogger { return NewSimpleLogger3(out, prefix, flag, DEFAULT_LOG_LEVEL) } // NewSimpleLogger3 let you customrize your logger prefix and flag and logLevel func NewSimpleLogger3(out io.Writer, prefix string, flag int, l core.LogLevel) *SimpleLogger { return &SimpleLogger{ DEBUG: log.New(out, fmt.Sprintf("%s [debug] ", prefix), flag), ERR: log.New(out, fmt.Sprintf("%s [error] ", prefix), flag), INFO: log.New(out, fmt.Sprintf("%s [info] ", prefix), flag), WARN: log.New(out, fmt.Sprintf("%s [warn] ", prefix), flag), level: l, } } // Error implement core.ILogger func (s *SimpleLogger) Error(v ...interface{}) { if s.level <= core.LOG_ERR { s.ERR.Output(2, fmt.Sprint(v...)) } return } // Errorf implement core.ILogger func (s *SimpleLogger) Errorf(format string, v ...interface{}) { if s.level <= core.LOG_ERR { s.ERR.Output(2, fmt.Sprintf(format, v...)) } return } // Debug implement core.ILogger func (s *SimpleLogger) Debug(v ...interface{}) { if s.level <= core.LOG_DEBUG { s.DEBUG.Output(2, fmt.Sprint(v...)) } return } // Debugf implement core.ILogger func (s *SimpleLogger) Debugf(format string, v ...interface{}) { if s.level <= core.LOG_DEBUG { s.DEBUG.Output(2, fmt.Sprintf(format, v...)) } return } // Info implement core.ILogger func (s *SimpleLogger) Info(v ...interface{}) { if s.level <= core.LOG_INFO { s.INFO.Output(2, fmt.Sprint(v...)) } return } // Infof implement core.ILogger func (s *SimpleLogger) Infof(format string, v ...interface{}) { if s.level <= core.LOG_INFO { s.INFO.Output(2, fmt.Sprintf(format, v...)) } return } // Warn implement core.ILogger func (s *SimpleLogger) Warn(v ...interface{}) { if s.level <= core.LOG_WARNING { s.WARN.Output(2, fmt.Sprint(v...)) } return } // Warnf implement core.ILogger func (s *SimpleLogger) Warnf(format string, v ...interface{}) { if s.level <= core.LOG_WARNING { s.WARN.Output(2, fmt.Sprintf(format, v...)) } return } // Level implement core.ILogger func (s *SimpleLogger) Level() core.LogLevel { return s.level } // SetLevel implement core.ILogger func (s *SimpleLogger) SetLevel(l core.LogLevel) { s.level = l return } // ShowSQL implement core.ILogger func (s *SimpleLogger) ShowSQL(show ...bool) { if len(show) == 0 { s.showSQL = true return } s.showSQL = show[0] } // IsShowSQL implement core.ILogger func (s *SimpleLogger) IsShowSQL() bool { return s.showSQL } ================================================ FILE: src/github.com/go-xorm/xorm/lru_cacher.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "container/list" "fmt" "sync" "time" "github.com/go-xorm/core" ) type LRUCacher struct { idList *list.List sqlList *list.List idIndex map[string]map[string]*list.Element sqlIndex map[string]map[string]*list.Element store core.CacheStore mutex sync.Mutex // maxSize int MaxElementSize int Expired time.Duration GcInterval time.Duration } func NewLRUCacher(store core.CacheStore, maxElementSize int) *LRUCacher { return NewLRUCacher2(store, 3600*time.Second, maxElementSize) } func NewLRUCacher2(store core.CacheStore, expired time.Duration, maxElementSize int) *LRUCacher { cacher := &LRUCacher{store: store, idList: list.New(), sqlList: list.New(), Expired: expired, GcInterval: core.CacheGcInterval, MaxElementSize: maxElementSize, sqlIndex: make(map[string]map[string]*list.Element), idIndex: make(map[string]map[string]*list.Element), } cacher.RunGC() return cacher } //func NewLRUCacher3(store CacheStore, expired time.Duration, maxSize int) *LRUCacher { // return newLRUCacher(store, expired, maxSize, 0) //} // RunGC run once every m.GcInterval func (m *LRUCacher) RunGC() { time.AfterFunc(m.GcInterval, func() { m.RunGC() m.GC() }) } // GC check ids lit and sql list to remove all element expired func (m *LRUCacher) GC() { //fmt.Println("begin gc ...") //defer fmt.Println("end gc ...") m.mutex.Lock() defer m.mutex.Unlock() var removedNum int for e := m.idList.Front(); e != nil; { if removedNum <= core.CacheGcMaxRemoved && time.Now().Sub(e.Value.(*idNode).lastVisit) > m.Expired { removedNum++ next := e.Next() //fmt.Println("removing ...", e.Value) node := e.Value.(*idNode) m.delBean(node.tbName, node.id) e = next } else { //fmt.Printf("removing %d cache nodes ..., left %d\n", removedNum, m.idList.Len()) break } } removedNum = 0 for e := m.sqlList.Front(); e != nil; { if removedNum <= core.CacheGcMaxRemoved && time.Now().Sub(e.Value.(*sqlNode).lastVisit) > m.Expired { removedNum++ next := e.Next() //fmt.Println("removing ...", e.Value) node := e.Value.(*sqlNode) m.delIds(node.tbName, node.sql) e = next } else { //fmt.Printf("removing %d cache nodes ..., left %d\n", removedNum, m.sqlList.Len()) break } } } // Get all bean's ids according to sql and parameter from cache func (m *LRUCacher) GetIds(tableName, sql string) interface{} { m.mutex.Lock() defer m.mutex.Unlock() if _, ok := m.sqlIndex[tableName]; !ok { m.sqlIndex[tableName] = make(map[string]*list.Element) } if v, err := m.store.Get(sql); err == nil { if el, ok := m.sqlIndex[tableName][sql]; !ok { el = m.sqlList.PushBack(newSqlNode(tableName, sql)) m.sqlIndex[tableName][sql] = el } else { lastTime := el.Value.(*sqlNode).lastVisit // if expired, remove the node and return nil if time.Now().Sub(lastTime) > m.Expired { m.delIds(tableName, sql) return nil } m.sqlList.MoveToBack(el) el.Value.(*sqlNode).lastVisit = time.Now() } return v } else { m.delIds(tableName, sql) } return nil } // Get bean according tableName and id from cache func (m *LRUCacher) GetBean(tableName string, id string) interface{} { m.mutex.Lock() defer m.mutex.Unlock() if _, ok := m.idIndex[tableName]; !ok { m.idIndex[tableName] = make(map[string]*list.Element) } tid := genId(tableName, id) if v, err := m.store.Get(tid); err == nil { if el, ok := m.idIndex[tableName][id]; ok { lastTime := el.Value.(*idNode).lastVisit // if expired, remove the node and return nil if time.Now().Sub(lastTime) > m.Expired { m.delBean(tableName, id) //m.clearIds(tableName) return nil } m.idList.MoveToBack(el) el.Value.(*idNode).lastVisit = time.Now() } else { el = m.idList.PushBack(newIdNode(tableName, id)) m.idIndex[tableName][id] = el } return v } else { // store bean is not exist, then remove memory's index m.delBean(tableName, id) //m.clearIds(tableName) return nil } } // Clear all sql-ids mapping on table tableName from cache func (m *LRUCacher) clearIds(tableName string) { if tis, ok := m.sqlIndex[tableName]; ok { for sql, v := range tis { m.sqlList.Remove(v) m.store.Del(sql) } } m.sqlIndex[tableName] = make(map[string]*list.Element) } func (m *LRUCacher) ClearIds(tableName string) { m.mutex.Lock() defer m.mutex.Unlock() m.clearIds(tableName) } func (m *LRUCacher) clearBeans(tableName string) { if tis, ok := m.idIndex[tableName]; ok { for id, v := range tis { m.idList.Remove(v) tid := genId(tableName, id) m.store.Del(tid) } } m.idIndex[tableName] = make(map[string]*list.Element) } func (m *LRUCacher) ClearBeans(tableName string) { m.mutex.Lock() defer m.mutex.Unlock() m.clearBeans(tableName) } func (m *LRUCacher) PutIds(tableName, sql string, ids interface{}) { m.mutex.Lock() defer m.mutex.Unlock() if _, ok := m.sqlIndex[tableName]; !ok { m.sqlIndex[tableName] = make(map[string]*list.Element) } if el, ok := m.sqlIndex[tableName][sql]; !ok { el = m.sqlList.PushBack(newSqlNode(tableName, sql)) m.sqlIndex[tableName][sql] = el } else { el.Value.(*sqlNode).lastVisit = time.Now() } m.store.Put(sql, ids) if m.sqlList.Len() > m.MaxElementSize { e := m.sqlList.Front() node := e.Value.(*sqlNode) m.delIds(node.tbName, node.sql) } } func (m *LRUCacher) PutBean(tableName string, id string, obj interface{}) { m.mutex.Lock() defer m.mutex.Unlock() var el *list.Element var ok bool if el, ok = m.idIndex[tableName][id]; !ok { el = m.idList.PushBack(newIdNode(tableName, id)) m.idIndex[tableName][id] = el } else { el.Value.(*idNode).lastVisit = time.Now() } m.store.Put(genId(tableName, id), obj) if m.idList.Len() > m.MaxElementSize { e := m.idList.Front() node := e.Value.(*idNode) m.delBean(node.tbName, node.id) } } func (m *LRUCacher) delIds(tableName, sql string) { if _, ok := m.sqlIndex[tableName]; ok { if el, ok := m.sqlIndex[tableName][sql]; ok { delete(m.sqlIndex[tableName], sql) m.sqlList.Remove(el) } } m.store.Del(sql) } func (m *LRUCacher) DelIds(tableName, sql string) { m.mutex.Lock() defer m.mutex.Unlock() m.delIds(tableName, sql) } func (m *LRUCacher) delBean(tableName string, id string) { tid := genId(tableName, id) if el, ok := m.idIndex[tableName][id]; ok { delete(m.idIndex[tableName], id) m.idList.Remove(el) m.clearIds(tableName) } m.store.Del(tid) } func (m *LRUCacher) DelBean(tableName string, id string) { m.mutex.Lock() defer m.mutex.Unlock() m.delBean(tableName, id) } type idNode struct { tbName string id string lastVisit time.Time } type sqlNode struct { tbName string sql string lastVisit time.Time } func genSqlKey(sql string, args interface{}) string { return fmt.Sprintf("%v-%v", sql, args) } func genId(prefix string, id string) string { return fmt.Sprintf("%v-%v", prefix, id) } func newIdNode(tbName string, id string) *idNode { return &idNode{tbName, id, time.Now()} } func newSqlNode(tbName, sql string) *sqlNode { return &sqlNode{tbName, sql, time.Now()} } ================================================ FILE: src/github.com/go-xorm/xorm/memory_store.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "sync" "github.com/go-xorm/core" ) var _ core.CacheStore = NewMemoryStore() // memory store type MemoryStore struct { store map[interface{}]interface{} mutex sync.RWMutex } func NewMemoryStore() *MemoryStore { return &MemoryStore{store: make(map[interface{}]interface{})} } func (s *MemoryStore) Put(key string, value interface{}) error { s.mutex.Lock() defer s.mutex.Unlock() s.store[key] = value return nil } func (s *MemoryStore) Get(key string) (interface{}, error) { s.mutex.RLock() defer s.mutex.RUnlock() if v, ok := s.store[key]; ok { return v, nil } return nil, ErrNotExist } func (s *MemoryStore) Del(key string) error { s.mutex.Lock() defer s.mutex.Unlock() delete(s.store, key) return nil } ================================================ FILE: src/github.com/go-xorm/xorm/mssql_dialect.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "errors" "fmt" "strconv" "strings" "github.com/go-xorm/core" ) var ( mssqlReservedWords = map[string]bool{ "ADD": true, "EXTERNAL": true, "PROCEDURE": true, "ALL": true, "FETCH": true, "PUBLIC": true, "ALTER": true, "FILE": true, "RAISERROR": true, "AND": true, "FILLFACTOR": true, "READ": true, "ANY": true, "FOR": true, "READTEXT": true, "AS": true, "FOREIGN": true, "RECONFIGURE": true, "ASC": true, "FREETEXT": true, "REFERENCES": true, "AUTHORIZATION": true, "FREETEXTTABLE": true, "REPLICATION": true, "BACKUP": true, "FROM": true, "RESTORE": true, "BEGIN": true, "FULL": true, "RESTRICT": true, "BETWEEN": true, "FUNCTION": true, "RETURN": true, "BREAK": true, "GOTO": true, "REVERT": true, "BROWSE": true, "GRANT": true, "REVOKE": true, "BULK": true, "GROUP": true, "RIGHT": true, "BY": true, "HAVING": true, "ROLLBACK": true, "CASCADE": true, "HOLDLOCK": true, "ROWCOUNT": true, "CASE": true, "IDENTITY": true, "ROWGUIDCOL": true, "CHECK": true, "IDENTITY_INSERT": true, "RULE": true, "CHECKPOINT": true, "IDENTITYCOL": true, "SAVE": true, "CLOSE": true, "IF": true, "SCHEMA": true, "CLUSTERED": true, "IN": true, "SECURITYAUDIT": true, "COALESCE": true, "INDEX": true, "SELECT": true, "COLLATE": true, "INNER": true, "SEMANTICKEYPHRASETABLE": true, "COLUMN": true, "INSERT": true, "SEMANTICSIMILARITYDETAILSTABLE": true, "COMMIT": true, "INTERSECT": true, "SEMANTICSIMILARITYTABLE": true, "COMPUTE": true, "INTO": true, "SESSION_USER": true, "CONSTRAINT": true, "IS": true, "SET": true, "CONTAINS": true, "JOIN": true, "SETUSER": true, "CONTAINSTABLE": true, "KEY": true, "SHUTDOWN": true, "CONTINUE": true, "KILL": true, "SOME": true, "CONVERT": true, "LEFT": true, "STATISTICS": true, "CREATE": true, "LIKE": true, "SYSTEM_USER": true, "CROSS": true, "LINENO": true, "TABLE": true, "CURRENT": true, "LOAD": true, "TABLESAMPLE": true, "CURRENT_DATE": true, "MERGE": true, "TEXTSIZE": true, "CURRENT_TIME": true, "NATIONAL": true, "THEN": true, "CURRENT_TIMESTAMP": true, "NOCHECK": true, "TO": true, "CURRENT_USER": true, "NONCLUSTERED": true, "TOP": true, "CURSOR": true, "NOT": true, "TRAN": true, "DATABASE": true, "NULL": true, "TRANSACTION": true, "DBCC": true, "NULLIF": true, "TRIGGER": true, "DEALLOCATE": true, "OF": true, "TRUNCATE": true, "DECLARE": true, "OFF": true, "TRY_CONVERT": true, "DEFAULT": true, "OFFSETS": true, "TSEQUAL": true, "DELETE": true, "ON": true, "UNION": true, "DENY": true, "OPEN": true, "UNIQUE": true, "DESC": true, "OPENDATASOURCE": true, "UNPIVOT": true, "DISK": true, "OPENQUERY": true, "UPDATE": true, "DISTINCT": true, "OPENROWSET": true, "UPDATETEXT": true, "DISTRIBUTED": true, "OPENXML": true, "USE": true, "DOUBLE": true, "OPTION": true, "USER": true, "DROP": true, "OR": true, "VALUES": true, "DUMP": true, "ORDER": true, "VARYING": true, "ELSE": true, "OUTER": true, "VIEW": true, "END": true, "OVER": true, "WAITFOR": true, "ERRLVL": true, "PERCENT": true, "WHEN": true, "ESCAPE": true, "PIVOT": true, "WHERE": true, "EXCEPT": true, "PLAN": true, "WHILE": true, "EXEC": true, "PRECISION": true, "WITH": true, "EXECUTE": true, "PRIMARY": true, "WITHIN": true, "EXISTS": true, "PRINT": true, "WRITETEXT": true, "EXIT": true, "PROC": true, } ) type mssql struct { core.Base } func (db *mssql) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error { return db.Base.Init(d, db, uri, drivername, dataSourceName) } func (db *mssql) SqlType(c *core.Column) string { var res string switch t := c.SQLType.Name; t { case core.Bool: res = core.TinyInt if c.Default == "true" { c.Default = "1" } else if c.Default == "false" { c.Default = "0" } case core.Serial: c.IsAutoIncrement = true c.IsPrimaryKey = true c.Nullable = false res = core.Int case core.BigSerial: c.IsAutoIncrement = true c.IsPrimaryKey = true c.Nullable = false res = core.BigInt case core.Bytea, core.Blob, core.Binary, core.TinyBlob, core.MediumBlob, core.LongBlob: res = core.VarBinary if c.Length == 0 { c.Length = 50 } case core.TimeStamp: res = core.DateTime case core.TimeStampz: res = "DATETIMEOFFSET" c.Length = 7 case core.MediumInt: res = core.Int case core.MediumText, core.TinyText, core.LongText, core.Json: res = core.Text case core.Double: res = core.Real default: res = t } if res == core.Int { return core.Int } var hasLen1 bool = (c.Length > 0) var hasLen2 bool = (c.Length2 > 0) if hasLen2 { res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")" } else if hasLen1 { res += "(" + strconv.Itoa(c.Length) + ")" } return res } func (db *mssql) SupportInsertMany() bool { return true } func (db *mssql) IsReserved(name string) bool { _, ok := mssqlReservedWords[name] return ok } func (db *mssql) Quote(name string) string { return "\"" + name + "\"" } func (db *mssql) QuoteStr() string { return "\"" } func (db *mssql) SupportEngine() bool { return false } func (db *mssql) AutoIncrStr() string { return "IDENTITY" } func (db *mssql) DropTableSql(tableName string) string { return fmt.Sprintf("IF EXISTS (SELECT * FROM sysobjects WHERE id = "+ "object_id(N'%s') and OBJECTPROPERTY(id, N'IsUserTable') = 1) "+ "DROP TABLE \"%s\"", tableName, tableName) } func (db *mssql) SupportCharset() bool { return false } func (db *mssql) IndexOnTable() bool { return true } func (db *mssql) IndexCheckSql(tableName, idxName string) (string, []interface{}) { args := []interface{}{idxName} sql := "select name from sysindexes where id=object_id('" + tableName + "') and name=?" return sql, args } /*func (db *mssql) ColumnCheckSql(tableName, colName string) (string, []interface{}) { args := []interface{}{tableName, colName} sql := `SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "COLUMN_NAME" = ?` return sql, args }*/ func (db *mssql) IsColumnExist(tableName, colName string) (bool, error) { query := `SELECT "COLUMN_NAME" FROM "INFORMATION_SCHEMA"."COLUMNS" WHERE "TABLE_NAME" = ? AND "COLUMN_NAME" = ?` return db.HasRecords(query, tableName, colName) } func (db *mssql) TableCheckSql(tableName string) (string, []interface{}) { args := []interface{}{} sql := "select * from sysobjects where id = object_id(N'" + tableName + "') and OBJECTPROPERTY(id, N'IsUserTable') = 1" return sql, args } func (db *mssql) GetColumns(tableName string) ([]string, map[string]*core.Column, error) { args := []interface{}{} s := `select a.name as name, b.name as ctype,a.max_length,a.precision,a.scale from sys.columns a left join sys.types b on a.user_type_id=b.user_type_id where a.object_id=object_id('` + tableName + `')` db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, nil, err } defer rows.Close() cols := make(map[string]*core.Column) colSeq := make([]string, 0) for rows.Next() { var name, ctype, precision, scale string var maxLen int err = rows.Scan(&name, &ctype, &maxLen, &precision, &scale) if err != nil { return nil, nil, err } col := new(core.Column) col.Indexes = make(map[string]int) col.Length = maxLen col.Name = strings.Trim(name, "` ") ct := strings.ToUpper(ctype) switch ct { case "DATETIMEOFFSET": col.SQLType = core.SQLType{core.TimeStampz, 0, 0} case "NVARCHAR": col.SQLType = core.SQLType{core.NVarchar, 0, 0} case "IMAGE": col.SQLType = core.SQLType{core.VarBinary, 0, 0} default: if _, ok := core.SqlTypes[ct]; ok { col.SQLType = core.SQLType{ct, 0, 0} } else { return nil, nil, errors.New(fmt.Sprintf("unknow colType %v for %v - %v", ct, tableName, col.Name)) } } if col.SQLType.IsText() || col.SQLType.IsTime() { if col.Default != "" { col.Default = "'" + col.Default + "'" } else { if col.DefaultIsEmpty { col.Default = "''" } } } cols[col.Name] = col colSeq = append(colSeq, col.Name) } return colSeq, cols, nil } func (db *mssql) GetTables() ([]*core.Table, error) { args := []interface{}{} s := `select name from sysobjects where xtype ='U'` db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, err } defer rows.Close() tables := make([]*core.Table, 0) for rows.Next() { table := core.NewEmptyTable() var name string err = rows.Scan(&name) if err != nil { return nil, err } table.Name = strings.Trim(name, "` ") tables = append(tables, table) } return tables, nil } func (db *mssql) GetIndexes(tableName string) (map[string]*core.Index, error) { args := []interface{}{tableName} s := `SELECT IXS.NAME AS [INDEX_NAME], C.NAME AS [COLUMN_NAME], IXS.is_unique AS [IS_UNIQUE] FROM SYS.INDEXES IXS INNER JOIN SYS.INDEX_COLUMNS IXCS ON IXS.OBJECT_ID=IXCS.OBJECT_ID AND IXS.INDEX_ID = IXCS.INDEX_ID INNER JOIN SYS.COLUMNS C ON IXS.OBJECT_ID=C.OBJECT_ID AND IXCS.COLUMN_ID=C.COLUMN_ID WHERE IXS.TYPE_DESC='NONCLUSTERED' and OBJECT_NAME(IXS.OBJECT_ID) =? ` db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, err } defer rows.Close() indexes := make(map[string]*core.Index, 0) for rows.Next() { var indexType int var indexName, colName, isUnique string err = rows.Scan(&indexName, &colName, &isUnique) if err != nil { return nil, err } i, err := strconv.ParseBool(isUnique) if err != nil { return nil, err } if i { indexType = core.UniqueType } else { indexType = core.IndexType } colName = strings.Trim(colName, "` ") if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) { indexName = indexName[5+len(tableName) : len(indexName)] } var index *core.Index var ok bool if index, ok = indexes[indexName]; !ok { index = new(core.Index) index.Type = indexType index.Name = indexName indexes[indexName] = index } index.AddColumn(colName) } return indexes, nil } func (db *mssql) CreateTableSql(table *core.Table, tableName, storeEngine, charset string) string { var sql string if tableName == "" { tableName = table.Name } sql = "IF NOT EXISTS (SELECT [name] FROM sys.tables WHERE [name] = '" + tableName + "' ) CREATE TABLE " sql += db.QuoteStr() + tableName + db.QuoteStr() + " (" pkList := table.PrimaryKeys for _, colName := range table.ColumnsSeq() { col := table.GetColumn(colName) if col.IsPrimaryKey && len(pkList) == 1 { sql += col.String(db) } else { sql += col.StringNoPk(db) } sql = strings.TrimSpace(sql) sql += ", " } if len(pkList) > 1 { sql += "PRIMARY KEY ( " sql += strings.Join(pkList, ",") sql += " ), " } sql = sql[:len(sql)-2] + ")" sql += ";" return sql } func (db *mssql) ForUpdateSql(query string) string { return query } func (db *mssql) Filters() []core.Filter { return []core.Filter{&core.IdFilter{}, &core.QuoteFilter{}} } ================================================ FILE: src/github.com/go-xorm/xorm/mymysql_driver.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "errors" "strings" "time" "github.com/go-xorm/core" ) type mymysqlDriver struct { } func (p *mymysqlDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) { db := &core.Uri{DbType: core.MYSQL} pd := strings.SplitN(dataSourceName, "*", 2) if len(pd) == 2 { // Parse protocol part of URI p := strings.SplitN(pd[0], ":", 2) if len(p) != 2 { return nil, errors.New("Wrong protocol part of URI") } db.Proto = p[0] options := strings.Split(p[1], ",") db.Raddr = options[0] for _, o := range options[1:] { kv := strings.SplitN(o, "=", 2) var k, v string if len(kv) == 2 { k, v = kv[0], kv[1] } else { k, v = o, "true" } switch k { case "laddr": db.Laddr = v case "timeout": to, err := time.ParseDuration(v) if err != nil { return nil, err } db.Timeout = to default: return nil, errors.New("Unknown option: " + k) } } // Remove protocol part pd = pd[1:] } // Parse database part of URI dup := strings.SplitN(pd[0], "/", 3) if len(dup) != 3 { return nil, errors.New("Wrong database part of URI") } db.DbName = dup[0] db.User = dup[1] db.Passwd = dup[2] return db, nil } ================================================ FILE: src/github.com/go-xorm/xorm/mysql_dialect.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "crypto/tls" "errors" "fmt" "strconv" "strings" "time" "github.com/go-xorm/core" ) var ( mysqlReservedWords = map[string]bool{ "ADD": true, "ALL": true, "ALTER": true, "ANALYZE": true, "AND": true, "AS": true, "ASC": true, "ASENSITIVE": true, "BEFORE": true, "BETWEEN": true, "BIGINT": true, "BINARY": true, "BLOB": true, "BOTH": true, "BY": true, "CALL": true, "CASCADE": true, "CASE": true, "CHANGE": true, "CHAR": true, "CHARACTER": true, "CHECK": true, "COLLATE": true, "COLUMN": true, "CONDITION": true, "CONNECTION": true, "CONSTRAINT": true, "CONTINUE": true, "CONVERT": true, "CREATE": true, "CROSS": true, "CURRENT_DATE": true, "CURRENT_TIME": true, "CURRENT_TIMESTAMP": true, "CURRENT_USER": true, "CURSOR": true, "DATABASE": true, "DATABASES": true, "DAY_HOUR": true, "DAY_MICROSECOND": true, "DAY_MINUTE": true, "DAY_SECOND": true, "DEC": true, "DECIMAL": true, "DECLARE": true, "DEFAULT": true, "DELAYED": true, "DELETE": true, "DESC": true, "DESCRIBE": true, "DETERMINISTIC": true, "DISTINCT": true, "DISTINCTROW": true, "DIV": true, "DOUBLE": true, "DROP": true, "DUAL": true, "EACH": true, "ELSE": true, "ELSEIF": true, "ENCLOSED": true, "ESCAPED": true, "EXISTS": true, "EXIT": true, "EXPLAIN": true, "FALSE": true, "FETCH": true, "FLOAT": true, "FLOAT4": true, "FLOAT8": true, "FOR": true, "FORCE": true, "FOREIGN": true, "FROM": true, "FULLTEXT": true, "GOTO": true, "GRANT": true, "GROUP": true, "HAVING": true, "HIGH_PRIORITY": true, "HOUR_MICROSECOND": true, "HOUR_MINUTE": true, "HOUR_SECOND": true, "IF": true, "IGNORE": true, "IN": true, "INDEX": true, "INFILE": true, "INNER": true, "INOUT": true, "INSENSITIVE": true, "INSERT": true, "INT": true, "INT1": true, "INT2": true, "INT3": true, "INT4": true, "INT8": true, "INTEGER": true, "INTERVAL": true, "INTO": true, "IS": true, "ITERATE": true, "JOIN": true, "KEY": true, "KEYS": true, "KILL": true, "LABEL": true, "LEADING": true, "LEAVE": true, "LEFT": true, "LIKE": true, "LIMIT": true, "LINEAR": true, "LINES": true, "LOAD": true, "LOCALTIME": true, "LOCALTIMESTAMP": true, "LOCK": true, "LONG": true, "LONGBLOB": true, "LONGTEXT": true, "LOOP": true, "LOW_PRIORITY": true, "MATCH": true, "MEDIUMBLOB": true, "MEDIUMINT": true, "MEDIUMTEXT": true, "MIDDLEINT": true, "MINUTE_MICROSECOND": true, "MINUTE_SECOND": true, "MOD": true, "MODIFIES": true, "NATURAL": true, "NOT": true, "NO_WRITE_TO_BINLOG": true, "NULL": true, "NUMERIC": true, "ON OPTIMIZE": true, "OPTION": true, "OPTIONALLY": true, "OR": true, "ORDER": true, "OUT": true, "OUTER": true, "OUTFILE": true, "PRECISION": true, "PRIMARY": true, "PROCEDURE": true, "PURGE": true, "RAID0": true, "RANGE": true, "READ": true, "READS": true, "REAL": true, "REFERENCES": true, "REGEXP": true, "RELEASE": true, "RENAME": true, "REPEAT": true, "REPLACE": true, "REQUIRE": true, "RESTRICT": true, "RETURN": true, "REVOKE": true, "RIGHT": true, "RLIKE": true, "SCHEMA": true, "SCHEMAS": true, "SECOND_MICROSECOND": true, "SELECT": true, "SENSITIVE": true, "SEPARATOR": true, "SET": true, "SHOW": true, "SMALLINT": true, "SPATIAL": true, "SPECIFIC": true, "SQL": true, "SQLEXCEPTION": true, "SQLSTATE": true, "SQLWARNING": true, "SQL_BIG_RESULT": true, "SQL_CALC_FOUND_ROWS": true, "SQL_SMALL_RESULT": true, "SSL": true, "STARTING": true, "STRAIGHT_JOIN": true, "TABLE": true, "TERMINATED": true, "THEN": true, "TINYBLOB": true, "TINYINT": true, "TINYTEXT": true, "TO": true, "TRAILING": true, "TRIGGER": true, "TRUE": true, "UNDO": true, "UNION": true, "UNIQUE": true, "UNLOCK": true, "UNSIGNED": true, "UPDATE": true, "USAGE": true, "USE": true, "USING": true, "UTC_DATE": true, "UTC_TIME": true, "UTC_TIMESTAMP": true, "VALUES": true, "VARBINARY": true, "VARCHAR": true, "VARCHARACTER": true, "VARYING": true, "WHEN": true, "WHERE": true, "WHILE": true, "WITH": true, "WRITE": true, "X509": true, "XOR": true, "YEAR_MONTH": true, "ZEROFILL": true, } ) type mysql struct { core.Base net string addr string params map[string]string loc *time.Location timeout time.Duration tls *tls.Config allowAllFiles bool allowOldPasswords bool clientFoundRows bool } func (db *mysql) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error { return db.Base.Init(d, db, uri, drivername, dataSourceName) } func (db *mysql) SqlType(c *core.Column) string { var res string switch t := c.SQLType.Name; t { case core.Bool: res = core.TinyInt c.Length = 1 case core.Serial: c.IsAutoIncrement = true c.IsPrimaryKey = true c.Nullable = false res = core.Int case core.BigSerial: c.IsAutoIncrement = true c.IsPrimaryKey = true c.Nullable = false res = core.BigInt case core.Bytea: res = core.Blob case core.TimeStampz: res = core.Char c.Length = 64 case core.Enum: //mysql enum res = core.Enum res += "(" opts := "" for v, _ := range c.EnumOptions { opts += fmt.Sprintf(",'%v'", v) } res += strings.TrimLeft(opts, ",") res += ")" case core.Set: //mysql set res = core.Set res += "(" opts := "" for v, _ := range c.SetOptions { opts += fmt.Sprintf(",'%v'", v) } res += strings.TrimLeft(opts, ",") res += ")" case core.NVarchar: res = core.Varchar case core.Uuid: res = core.Varchar c.Length = 40 case core.Json: res = core.Text default: res = t } var hasLen1 bool = (c.Length > 0) var hasLen2 bool = (c.Length2 > 0) if res == core.BigInt && !hasLen1 && !hasLen2 { c.Length = 20 hasLen1 = true } if hasLen2 { res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")" } else if hasLen1 { res += "(" + strconv.Itoa(c.Length) + ")" } return res } func (db *mysql) SupportInsertMany() bool { return true } func (db *mysql) IsReserved(name string) bool { _, ok := mysqlReservedWords[name] return ok } func (db *mysql) Quote(name string) string { return "`" + name + "`" } func (db *mysql) QuoteStr() string { return "`" } func (db *mysql) SupportEngine() bool { return true } func (db *mysql) AutoIncrStr() string { return "AUTO_INCREMENT" } func (db *mysql) SupportCharset() bool { return true } func (db *mysql) IndexOnTable() bool { return true } func (db *mysql) IndexCheckSql(tableName, idxName string) (string, []interface{}) { args := []interface{}{db.DbName, tableName, idxName} sql := "SELECT `INDEX_NAME` FROM `INFORMATION_SCHEMA`.`STATISTICS`" sql += " WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `INDEX_NAME`=?" return sql, args } /*func (db *mysql) ColumnCheckSql(tableName, colName string) (string, []interface{}) { args := []interface{}{db.DbName, tableName, colName} sql := "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ?" return sql, args }*/ func (db *mysql) TableCheckSql(tableName string) (string, []interface{}) { args := []interface{}{db.DbName, tableName} sql := "SELECT `TABLE_NAME` from `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? and `TABLE_NAME`=?" return sql, args } func (db *mysql) GetColumns(tableName string) ([]string, map[string]*core.Column, error) { args := []interface{}{db.DbName, tableName} s := "SELECT `COLUMN_NAME`, `IS_NULLABLE`, `COLUMN_DEFAULT`, `COLUMN_TYPE`," + " `COLUMN_KEY`, `EXTRA` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?" db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, nil, err } defer rows.Close() cols := make(map[string]*core.Column) colSeq := make([]string, 0) for rows.Next() { col := new(core.Column) col.Indexes = make(map[string]int) var columnName, isNullable, colType, colKey, extra string var colDefault *string err = rows.Scan(&columnName, &isNullable, &colDefault, &colType, &colKey, &extra) if err != nil { return nil, nil, err } col.Name = strings.Trim(columnName, "` ") if "YES" == isNullable { col.Nullable = true } if colDefault != nil { col.Default = *colDefault if col.Default == "" { col.DefaultIsEmpty = true } } cts := strings.Split(colType, "(") colName := cts[0] colType = strings.ToUpper(colName) var len1, len2 int if len(cts) == 2 { idx := strings.Index(cts[1], ")") if colType == core.Enum && cts[1][0] == '\'' { //enum options := strings.Split(cts[1][0:idx], ",") col.EnumOptions = make(map[string]int) for k, v := range options { v = strings.TrimSpace(v) v = strings.Trim(v, "'") col.EnumOptions[v] = k } } else if colType == core.Set && cts[1][0] == '\'' { options := strings.Split(cts[1][0:idx], ",") col.SetOptions = make(map[string]int) for k, v := range options { v = strings.TrimSpace(v) v = strings.Trim(v, "'") col.SetOptions[v] = k } } else { lens := strings.Split(cts[1][0:idx], ",") len1, err = strconv.Atoi(strings.TrimSpace(lens[0])) if err != nil { return nil, nil, err } if len(lens) == 2 { len2, err = strconv.Atoi(lens[1]) if err != nil { return nil, nil, err } } } } if colType == "FLOAT UNSIGNED" { colType = "FLOAT" } col.Length = len1 col.Length2 = len2 if _, ok := core.SqlTypes[colType]; ok { col.SQLType = core.SQLType{colType, len1, len2} } else { return nil, nil, errors.New(fmt.Sprintf("unkonw colType %v", colType)) } if colKey == "PRI" { col.IsPrimaryKey = true } if colKey == "UNI" { //col.is } if extra == "auto_increment" { col.IsAutoIncrement = true } if col.SQLType.IsText() || col.SQLType.IsTime() { if col.Default != "" { col.Default = "'" + col.Default + "'" } else { if col.DefaultIsEmpty { col.Default = "''" } } } cols[col.Name] = col colSeq = append(colSeq, col.Name) } return colSeq, cols, nil } func (db *mysql) GetTables() ([]*core.Table, error) { args := []interface{}{db.DbName} s := "SELECT `TABLE_NAME`, `ENGINE`, `TABLE_ROWS`, `AUTO_INCREMENT` from " + "`INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`=? AND (`ENGINE`='MyISAM' OR `ENGINE` = 'InnoDB' OR `ENGINE` = 'TokuDB')" db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, err } defer rows.Close() tables := make([]*core.Table, 0) for rows.Next() { table := core.NewEmptyTable() var name, engine, tableRows string var autoIncr *string err = rows.Scan(&name, &engine, &tableRows, &autoIncr) if err != nil { return nil, err } table.Name = name table.StoreEngine = engine tables = append(tables, table) } return tables, nil } func (db *mysql) GetIndexes(tableName string) (map[string]*core.Index, error) { args := []interface{}{db.DbName, tableName} s := "SELECT `INDEX_NAME`, `NON_UNIQUE`, `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`STATISTICS` WHERE `TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?" db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, err } defer rows.Close() indexes := make(map[string]*core.Index, 0) for rows.Next() { var indexType int var indexName, colName, nonUnique string err = rows.Scan(&indexName, &nonUnique, &colName) if err != nil { return nil, err } if indexName == "PRIMARY" { continue } if "YES" == nonUnique || nonUnique == "1" { indexType = core.IndexType } else { indexType = core.UniqueType } colName = strings.Trim(colName, "` ") var isRegular bool if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) { indexName = indexName[5+len(tableName) : len(indexName)] isRegular = true } var index *core.Index var ok bool if index, ok = indexes[indexName]; !ok { index = new(core.Index) index.IsRegular = isRegular index.Type = indexType index.Name = indexName indexes[indexName] = index } index.AddColumn(colName) } return indexes, nil } func (db *mysql) Filters() []core.Filter { return []core.Filter{&core.IdFilter{}} } ================================================ FILE: src/github.com/go-xorm/xorm/mysql_driver.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "regexp" "strings" "github.com/go-xorm/core" ) type mysqlDriver struct { } func (p *mysqlDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) { dsnPattern := regexp.MustCompile( `^(?:(?P.*?)(?::(?P.*))?@)?` + // [user[:password]@] `(?:(?P[^\(]*)(?:\((?P[^\)]*)\))?)?` + // [net[(addr)]] `\/(?P.*?)` + // /dbname `(?:\?(?P[^\?]*))?$`) // [?param1=value1¶mN=valueN] matches := dsnPattern.FindStringSubmatch(dataSourceName) //tlsConfigRegister := make(map[string]*tls.Config) names := dsnPattern.SubexpNames() uri := &core.Uri{DbType: core.MYSQL} for i, match := range matches { switch names[i] { case "dbname": uri.DbName = match case "params": if len(match) > 0 { kvs := strings.Split(match, "&") for _, kv := range kvs { splits := strings.Split(kv, "=") if len(splits) == 2 { switch splits[0] { case "charset": uri.Charset = splits[1] } } } } } } return uri, nil } ================================================ FILE: src/github.com/go-xorm/xorm/oci8_driver.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "errors" "regexp" "github.com/go-xorm/core" ) type oci8Driver struct { } //dataSourceName=user/password@ipv4:port/dbname //dataSourceName=user/password@[ipv6]:port/dbname func (p *oci8Driver) Parse(driverName, dataSourceName string) (*core.Uri, error) { db := &core.Uri{DbType: core.ORACLE} dsnPattern := regexp.MustCompile( `^(?P.*)\/(?P.*)@` + // user:password@ `(?P.*)` + // ip:port `\/(?P.*)`) // dbname matches := dsnPattern.FindStringSubmatch(dataSourceName) names := dsnPattern.SubexpNames() for i, match := range matches { switch names[i] { case "dbname": db.DbName = match } } if db.DbName == "" { return nil, errors.New("dbname is empty") } return db, nil } ================================================ FILE: src/github.com/go-xorm/xorm/odbc_driver.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "errors" "strings" "github.com/go-xorm/core" ) type odbcDriver struct { } func (p *odbcDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) { kv := strings.Split(dataSourceName, ";") var dbName string for _, c := range kv { vv := strings.Split(strings.TrimSpace(c), "=") if len(vv) == 2 { switch strings.ToLower(vv[0]) { case "database": dbName = vv[1] } } } if dbName == "" { return nil, errors.New("no db name provided") } return &core.Uri{DbName: dbName, DbType: core.MSSQL}, nil } ================================================ FILE: src/github.com/go-xorm/xorm/oracle_dialect.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "errors" "fmt" "strconv" "strings" "github.com/go-xorm/core" ) var ( oracleReservedWords = map[string]bool{ "ACCESS": true, "ACCOUNT": true, "ACTIVATE": true, "ADD": true, "ADMIN": true, "ADVISE": true, "AFTER": true, "ALL": true, "ALL_ROWS": true, "ALLOCATE": true, "ALTER": true, "ANALYZE": true, "AND": true, "ANY": true, "ARCHIVE": true, "ARCHIVELOG": true, "ARRAY": true, "AS": true, "ASC": true, "AT": true, "AUDIT": true, "AUTHENTICATED": true, "AUTHORIZATION": true, "AUTOEXTEND": true, "AUTOMATIC": true, "BACKUP": true, "BECOME": true, "BEFORE": true, "BEGIN": true, "BETWEEN": true, "BFILE": true, "BITMAP": true, "BLOB": true, "BLOCK": true, "BODY": true, "BY": true, "CACHE": true, "CACHE_INSTANCES": true, "CANCEL": true, "CASCADE": true, "CAST": true, "CFILE": true, "CHAINED": true, "CHANGE": true, "CHAR": true, "CHAR_CS": true, "CHARACTER": true, "CHECK": true, "CHECKPOINT": true, "CHOOSE": true, "CHUNK": true, "CLEAR": true, "CLOB": true, "CLONE": true, "CLOSE": true, "CLOSE_CACHED_OPEN_CURSORS": true, "CLUSTER": true, "COALESCE": true, "COLUMN": true, "COLUMNS": true, "COMMENT": true, "COMMIT": true, "COMMITTED": true, "COMPATIBILITY": true, "COMPILE": true, "COMPLETE": true, "COMPOSITE_LIMIT": true, "COMPRESS": true, "COMPUTE": true, "CONNECT": true, "CONNECT_TIME": true, "CONSTRAINT": true, "CONSTRAINTS": true, "CONTENTS": true, "CONTINUE": true, "CONTROLFILE": true, "CONVERT": true, "COST": true, "CPU_PER_CALL": true, "CPU_PER_SESSION": true, "CREATE": true, "CURRENT": true, "CURRENT_SCHEMA": true, "CURREN_USER": true, "CURSOR": true, "CYCLE": true, "DANGLING": true, "DATABASE": true, "DATAFILE": true, "DATAFILES": true, "DATAOBJNO": true, "DATE": true, "DBA": true, "DBHIGH": true, "DBLOW": true, "DBMAC": true, "DEALLOCATE": true, "DEBUG": true, "DEC": true, "DECIMAL": true, "DECLARE": true, "DEFAULT": true, "DEFERRABLE": true, "DEFERRED": true, "DEGREE": true, "DELETE": true, "DEREF": true, "DESC": true, "DIRECTORY": true, "DISABLE": true, "DISCONNECT": true, "DISMOUNT": true, "DISTINCT": true, "DISTRIBUTED": true, "DML": true, "DOUBLE": true, "DROP": true, "DUMP": true, "EACH": true, "ELSE": true, "ENABLE": true, "END": true, "ENFORCE": true, "ENTRY": true, "ESCAPE": true, "EXCEPT": true, "EXCEPTIONS": true, "EXCHANGE": true, "EXCLUDING": true, "EXCLUSIVE": true, "EXECUTE": true, "EXISTS": true, "EXPIRE": true, "EXPLAIN": true, "EXTENT": true, "EXTENTS": true, "EXTERNALLY": true, "FAILED_LOGIN_ATTEMPTS": true, "FALSE": true, "FAST": true, "FILE": true, "FIRST_ROWS": true, "FLAGGER": true, "FLOAT": true, "FLOB": true, "FLUSH": true, "FOR": true, "FORCE": true, "FOREIGN": true, "FREELIST": true, "FREELISTS": true, "FROM": true, "FULL": true, "FUNCTION": true, "GLOBAL": true, "GLOBALLY": true, "GLOBAL_NAME": true, "GRANT": true, "GROUP": true, "GROUPS": true, "HASH": true, "HASHKEYS": true, "HAVING": true, "HEADER": true, "HEAP": true, "IDENTIFIED": true, "IDGENERATORS": true, "IDLE_TIME": true, "IF": true, "IMMEDIATE": true, "IN": true, "INCLUDING": true, "INCREMENT": true, "INDEX": true, "INDEXED": true, "INDEXES": true, "INDICATOR": true, "IND_PARTITION": true, "INITIAL": true, "INITIALLY": true, "INITRANS": true, "INSERT": true, "INSTANCE": true, "INSTANCES": true, "INSTEAD": true, "INT": true, "INTEGER": true, "INTERMEDIATE": true, "INTERSECT": true, "INTO": true, "IS": true, "ISOLATION": true, "ISOLATION_LEVEL": true, "KEEP": true, "KEY": true, "KILL": true, "LABEL": true, "LAYER": true, "LESS": true, "LEVEL": true, "LIBRARY": true, "LIKE": true, "LIMIT": true, "LINK": true, "LIST": true, "LOB": true, "LOCAL": true, "LOCK": true, "LOCKED": true, "LOG": true, "LOGFILE": true, "LOGGING": true, "LOGICAL_READS_PER_CALL": true, "LOGICAL_READS_PER_SESSION": true, "LONG": true, "MANAGE": true, "MASTER": true, "MAX": true, "MAXARCHLOGS": true, "MAXDATAFILES": true, "MAXEXTENTS": true, "MAXINSTANCES": true, "MAXLOGFILES": true, "MAXLOGHISTORY": true, "MAXLOGMEMBERS": true, "MAXSIZE": true, "MAXTRANS": true, "MAXVALUE": true, "MIN": true, "MEMBER": true, "MINIMUM": true, "MINEXTENTS": true, "MINUS": true, "MINVALUE": true, "MLSLABEL": true, "MLS_LABEL_FORMAT": true, "MODE": true, "MODIFY": true, "MOUNT": true, "MOVE": true, "MTS_DISPATCHERS": true, "MULTISET": true, "NATIONAL": true, "NCHAR": true, "NCHAR_CS": true, "NCLOB": true, "NEEDED": true, "NESTED": true, "NETWORK": true, "NEW": true, "NEXT": true, "NOARCHIVELOG": true, "NOAUDIT": true, "NOCACHE": true, "NOCOMPRESS": true, "NOCYCLE": true, "NOFORCE": true, "NOLOGGING": true, "NOMAXVALUE": true, "NOMINVALUE": true, "NONE": true, "NOORDER": true, "NOOVERRIDE": true, "NOPARALLEL": true, "NOREVERSE": true, "NORMAL": true, "NOSORT": true, "NOT": true, "NOTHING": true, "NOWAIT": true, "NULL": true, "NUMBER": true, "NUMERIC": true, "NVARCHAR2": true, "OBJECT": true, "OBJNO": true, "OBJNO_REUSE": true, "OF": true, "OFF": true, "OFFLINE": true, "OID": true, "OIDINDEX": true, "OLD": true, "ON": true, "ONLINE": true, "ONLY": true, "OPCODE": true, "OPEN": true, "OPTIMAL": true, "OPTIMIZER_GOAL": true, "OPTION": true, "OR": true, "ORDER": true, "ORGANIZATION": true, "OSLABEL": true, "OVERFLOW": true, "OWN": true, "PACKAGE": true, "PARALLEL": true, "PARTITION": true, "PASSWORD": true, "PASSWORD_GRACE_TIME": true, "PASSWORD_LIFE_TIME": true, "PASSWORD_LOCK_TIME": true, "PASSWORD_REUSE_MAX": true, "PASSWORD_REUSE_TIME": true, "PASSWORD_VERIFY_FUNCTION": true, "PCTFREE": true, "PCTINCREASE": true, "PCTTHRESHOLD": true, "PCTUSED": true, "PCTVERSION": true, "PERCENT": true, "PERMANENT": true, "PLAN": true, "PLSQL_DEBUG": true, "POST_TRANSACTION": true, "PRECISION": true, "PRESERVE": true, "PRIMARY": true, "PRIOR": true, "PRIVATE": true, "PRIVATE_SGA": true, "PRIVILEGE": true, "PRIVILEGES": true, "PROCEDURE": true, "PROFILE": true, "PUBLIC": true, "PURGE": true, "QUEUE": true, "QUOTA": true, "RANGE": true, "RAW": true, "RBA": true, "READ": true, "READUP": true, "REAL": true, "REBUILD": true, "RECOVER": true, "RECOVERABLE": true, "RECOVERY": true, "REF": true, "REFERENCES": true, "REFERENCING": true, "REFRESH": true, "RENAME": true, "REPLACE": true, "RESET": true, "RESETLOGS": true, "RESIZE": true, "RESOURCE": true, "RESTRICTED": true, "RETURN": true, "RETURNING": true, "REUSE": true, "REVERSE": true, "REVOKE": true, "ROLE": true, "ROLES": true, "ROLLBACK": true, "ROW": true, "ROWID": true, "ROWNUM": true, "ROWS": true, "RULE": true, "SAMPLE": true, "SAVEPOINT": true, "SB4": true, "SCAN_INSTANCES": true, "SCHEMA": true, "SCN": true, "SCOPE": true, "SD_ALL": true, "SD_INHIBIT": true, "SD_SHOW": true, "SEGMENT": true, "SEG_BLOCK": true, "SEG_FILE": true, "SELECT": true, "SEQUENCE": true, "SERIALIZABLE": true, "SESSION": true, "SESSION_CACHED_CURSORS": true, "SESSIONS_PER_USER": true, "SET": true, "SHARE": true, "SHARED": true, "SHARED_POOL": true, "SHRINK": true, "SIZE": true, "SKIP": true, "SKIP_UNUSABLE_INDEXES": true, "SMALLINT": true, "SNAPSHOT": true, "SOME": true, "SORT": true, "SPECIFICATION": true, "SPLIT": true, "SQL_TRACE": true, "STANDBY": true, "START": true, "STATEMENT_ID": true, "STATISTICS": true, "STOP": true, "STORAGE": true, "STORE": true, "STRUCTURE": true, "SUCCESSFUL": true, "SWITCH": true, "SYS_OP_ENFORCE_NOT_NULL$": true, "SYS_OP_NTCIMG$": true, "SYNONYM": true, "SYSDATE": true, "SYSDBA": true, "SYSOPER": true, "SYSTEM": true, "TABLE": true, "TABLES": true, "TABLESPACE": true, "TABLESPACE_NO": true, "TABNO": true, "TEMPORARY": true, "THAN": true, "THE": true, "THEN": true, "THREAD": true, "TIMESTAMP": true, "TIME": true, "TO": true, "TOPLEVEL": true, "TRACE": true, "TRACING": true, "TRANSACTION": true, "TRANSITIONAL": true, "TRIGGER": true, "TRIGGERS": true, "TRUE": true, "TRUNCATE": true, "TX": true, "TYPE": true, "UB2": true, "UBA": true, "UID": true, "UNARCHIVED": true, "UNDO": true, "UNION": true, "UNIQUE": true, "UNLIMITED": true, "UNLOCK": true, "UNRECOVERABLE": true, "UNTIL": true, "UNUSABLE": true, "UNUSED": true, "UPDATABLE": true, "UPDATE": true, "USAGE": true, "USE": true, "USER": true, "USING": true, "VALIDATE": true, "VALIDATION": true, "VALUE": true, "VALUES": true, "VARCHAR": true, "VARCHAR2": true, "VARYING": true, "VIEW": true, "WHEN": true, "WHENEVER": true, "WHERE": true, "WITH": true, "WITHOUT": true, "WORK": true, "WRITE": true, "WRITEDOWN": true, "WRITEUP": true, "XID": true, "YEAR": true, "ZONE": true, } ) type oracle struct { core.Base } func (db *oracle) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error { return db.Base.Init(d, db, uri, drivername, dataSourceName) } func (db *oracle) SqlType(c *core.Column) string { var res string switch t := c.SQLType.Name; t { case core.Bit, core.TinyInt, core.SmallInt, core.MediumInt, core.Int, core.Integer, core.BigInt, core.Bool, core.Serial, core.BigSerial: res = "NUMBER" case core.Binary, core.VarBinary, core.Blob, core.TinyBlob, core.MediumBlob, core.LongBlob, core.Bytea: return core.Blob case core.Time, core.DateTime, core.TimeStamp: res = core.TimeStamp case core.TimeStampz: res = "TIMESTAMP WITH TIME ZONE" case core.Float, core.Double, core.Numeric, core.Decimal: res = "NUMBER" case core.Text, core.MediumText, core.LongText, core.Json: res = "CLOB" case core.Char, core.Varchar, core.TinyText: res = "VARCHAR2" default: res = t } var hasLen1 bool = (c.Length > 0) var hasLen2 bool = (c.Length2 > 0) if hasLen2 { res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")" } else if hasLen1 { res += "(" + strconv.Itoa(c.Length) + ")" } return res } func (db *oracle) AutoIncrStr() string { return "AUTO_INCREMENT" } func (db *oracle) SupportInsertMany() bool { return true } func (db *oracle) IsReserved(name string) bool { _, ok := oracleReservedWords[name] return ok } func (db *oracle) Quote(name string) string { return "\"" + name + "\"" } func (db *oracle) QuoteStr() string { return "\"" } func (db *oracle) SupportEngine() bool { return false } func (db *oracle) SupportCharset() bool { return false } func (db *oracle) SupportDropIfExists() bool { return false } func (db *oracle) IndexOnTable() bool { return false } func (db *oracle) DropTableSql(tableName string) string { return fmt.Sprintf("DROP TABLE `%s`", tableName) } func (b *oracle) CreateTableSql(table *core.Table, tableName, storeEngine, charset string) string { var sql string sql = "CREATE TABLE " if tableName == "" { tableName = table.Name } sql += b.Quote(tableName) + " (" pkList := table.PrimaryKeys for _, colName := range table.ColumnsSeq() { col := table.GetColumn(colName) /*if col.IsPrimaryKey && len(pkList) == 1 { sql += col.String(b.dialect) } else {*/ sql += col.StringNoPk(b) //} sql = strings.TrimSpace(sql) sql += ", " } if len(pkList) > 0 { sql += "PRIMARY KEY ( " sql += b.Quote(strings.Join(pkList, b.Quote(","))) sql += " ), " } sql = sql[:len(sql)-2] + ")" if b.SupportEngine() && storeEngine != "" { sql += " ENGINE=" + storeEngine } if b.SupportCharset() { if len(charset) == 0 { charset = b.URI().Charset } if len(charset) > 0 { sql += " DEFAULT CHARSET " + charset } } return sql } func (db *oracle) IndexCheckSql(tableName, idxName string) (string, []interface{}) { args := []interface{}{tableName, idxName} return `SELECT INDEX_NAME FROM USER_INDEXES ` + `WHERE TABLE_NAME = :1 AND INDEX_NAME = :2`, args } func (db *oracle) TableCheckSql(tableName string) (string, []interface{}) { args := []interface{}{tableName} return `SELECT table_name FROM user_tables WHERE table_name = :1`, args } func (db *oracle) MustDropTable(tableName string) error { sql, args := db.TableCheckSql(tableName) db.LogSQL(sql, args) rows, err := db.DB().Query(sql, args...) if err != nil { return err } defer rows.Close() if !rows.Next() { return nil } sql = "Drop Table \"" + tableName + "\"" db.LogSQL(sql, args) _, err = db.DB().Exec(sql) return err } /*func (db *oracle) ColumnCheckSql(tableName, colName string) (string, []interface{}) { args := []interface{}{strings.ToUpper(tableName), strings.ToUpper(colName)} return "SELECT column_name FROM USER_TAB_COLUMNS WHERE table_name = ?" + " AND column_name = ?", args }*/ func (db *oracle) IsColumnExist(tableName, colName string) (bool, error) { args := []interface{}{tableName, colName} query := "SELECT column_name FROM USER_TAB_COLUMNS WHERE table_name = :1" + " AND column_name = :2" db.LogSQL(query, args) rows, err := db.DB().Query(query, args...) if err != nil { return false, err } defer rows.Close() if rows.Next() { return true, nil } return false, nil } func (db *oracle) GetColumns(tableName string) ([]string, map[string]*core.Column, error) { args := []interface{}{tableName} s := "SELECT column_name,data_default,data_type,data_length,data_precision,data_scale," + "nullable FROM USER_TAB_COLUMNS WHERE table_name = :1" db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, nil, err } defer rows.Close() cols := make(map[string]*core.Column) colSeq := make([]string, 0) for rows.Next() { col := new(core.Column) col.Indexes = make(map[string]int) var colName, colDefault, nullable, dataType, dataPrecision, dataScale *string var dataLen int err = rows.Scan(&colName, &colDefault, &dataType, &dataLen, &dataPrecision, &dataScale, &nullable) if err != nil { return nil, nil, err } col.Name = strings.Trim(*colName, `" `) if colDefault != nil { col.Default = *colDefault col.DefaultIsEmpty = false } if *nullable == "Y" { col.Nullable = true } else { col.Nullable = false } var ignore bool var dt string var len1, len2 int dts := strings.Split(*dataType, "(") dt = dts[0] if len(dts) > 1 { lens := strings.Split(dts[1][:len(dts[1])-1], ",") if len(lens) > 1 { len1, _ = strconv.Atoi(lens[0]) len2, _ = strconv.Atoi(lens[1]) } else { len1, _ = strconv.Atoi(lens[0]) } } switch dt { case "VARCHAR2": col.SQLType = core.SQLType{core.Varchar, len1, len2} case "NVARCHAR2": col.SQLType = core.SQLType{core.NVarchar, len1, len2} case "TIMESTAMP WITH TIME ZONE": col.SQLType = core.SQLType{core.TimeStampz, 0, 0} case "NUMBER": col.SQLType = core.SQLType{core.Double, len1, len2} case "LONG", "LONG RAW": col.SQLType = core.SQLType{core.Text, 0, 0} case "RAW": col.SQLType = core.SQLType{core.Binary, 0, 0} case "ROWID": col.SQLType = core.SQLType{core.Varchar, 18, 0} case "AQ$_SUBSCRIBERS": ignore = true default: col.SQLType = core.SQLType{strings.ToUpper(dt), len1, len2} } if ignore { continue } if _, ok := core.SqlTypes[col.SQLType.Name]; !ok { return nil, nil, errors.New(fmt.Sprintf("unkonw colType %v %v", *dataType, col.SQLType)) } col.Length = dataLen if col.SQLType.IsText() || col.SQLType.IsTime() { if !col.DefaultIsEmpty { col.Default = "'" + col.Default + "'" } } cols[col.Name] = col colSeq = append(colSeq, col.Name) } return colSeq, cols, nil } func (db *oracle) GetTables() ([]*core.Table, error) { args := []interface{}{} s := "SELECT table_name FROM user_tables" db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, err } defer rows.Close() tables := make([]*core.Table, 0) for rows.Next() { table := core.NewEmptyTable() err = rows.Scan(&table.Name) if err != nil { return nil, err } tables = append(tables, table) } return tables, nil } func (db *oracle) GetIndexes(tableName string) (map[string]*core.Index, error) { args := []interface{}{tableName} s := "SELECT t.column_name,i.uniqueness,i.index_name FROM user_ind_columns t,user_indexes i " + "WHERE t.index_name = i.index_name and t.table_name = i.table_name and t.table_name =:1" db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, err } defer rows.Close() indexes := make(map[string]*core.Index, 0) for rows.Next() { var indexType int var indexName, colName, uniqueness string err = rows.Scan(&colName, &uniqueness, &indexName) if err != nil { return nil, err } indexName = strings.Trim(indexName, `" `) if uniqueness == "UNIQUE" { indexType = core.UniqueType } else { indexType = core.IndexType } var index *core.Index var ok bool if index, ok = indexes[indexName]; !ok { index = new(core.Index) index.Type = indexType index.Name = indexName indexes[indexName] = index } index.AddColumn(colName) } return indexes, nil } func (db *oracle) Filters() []core.Filter { return []core.Filter{&core.QuoteFilter{}, &core.SeqFilter{":", 1}, &core.IdFilter{}} } ================================================ FILE: src/github.com/go-xorm/xorm/pg_reserved.txt ================================================ A non-reserved non-reserved ABORT non-reserved ABS reserved reserved ABSENT non-reserved non-reserved ABSOLUTE non-reserved non-reserved non-reserved reserved ACCESS non-reserved ACCORDING non-reserved non-reserved ACTION non-reserved non-reserved non-reserved reserved ADA non-reserved non-reserved non-reserved ADD non-reserved non-reserved non-reserved reserved ADMIN non-reserved non-reserved non-reserved AFTER non-reserved non-reserved non-reserved AGGREGATE non-reserved ALL reserved reserved reserved reserved ALLOCATE reserved reserved reserved ALSO non-reserved ALTER non-reserved reserved reserved reserved ALWAYS non-reserved non-reserved non-reserved ANALYSE reserved ANALYZE reserved AND reserved reserved reserved reserved ANY reserved reserved reserved reserved ARE reserved reserved reserved ARRAY reserved reserved reserved ARRAY_AGG reserved reserved ARRAY_MAX_CARDINALITY reserved AS reserved reserved reserved reserved ASC reserved non-reserved non-reserved reserved ASENSITIVE reserved reserved ASSERTION non-reserved non-reserved non-reserved reserved ASSIGNMENT non-reserved non-reserved non-reserved ASYMMETRIC reserved reserved reserved AT non-reserved reserved reserved reserved ATOMIC reserved reserved ATTRIBUTE non-reserved non-reserved non-reserved ATTRIBUTES non-reserved non-reserved AUTHORIZATION reserved (can be function or type) reserved reserved reserved AVG reserved reserved reserved BACKWARD non-reserved BASE64 non-reserved non-reserved BEFORE non-reserved non-reserved non-reserved BEGIN non-reserved reserved reserved reserved BEGIN_FRAME reserved BEGIN_PARTITION reserved BERNOULLI non-reserved non-reserved BETWEEN non-reserved (cannot be function or type) reserved reserved reserved BIGINT non-reserved (cannot be function or type) reserved reserved BINARY reserved (can be function or type) reserved reserved BIT non-reserved (cannot be function or type) reserved BIT_LENGTH reserved BLOB reserved reserved BLOCKED non-reserved non-reserved BOM non-reserved non-reserved BOOLEAN non-reserved (cannot be function or type) reserved reserved BOTH reserved reserved reserved reserved BREADTH non-reserved non-reserved BY non-reserved reserved reserved reserved C non-reserved non-reserved non-reserved CACHE non-reserved CALL reserved reserved CALLED non-reserved reserved reserved CARDINALITY reserved reserved CASCADE non-reserved non-reserved non-reserved reserved CASCADED non-reserved reserved reserved reserved CASE reserved reserved reserved reserved CAST reserved reserved reserved reserved CATALOG non-reserved non-reserved non-reserved reserved CATALOG_NAME non-reserved non-reserved non-reserved CEIL reserved reserved CEILING reserved reserved CHAIN non-reserved non-reserved non-reserved CHAR non-reserved (cannot be function or type) reserved reserved reserved CHARACTER non-reserved (cannot be function or type) reserved reserved reserved CHARACTERISTICS non-reserved non-reserved non-reserved CHARACTERS non-reserved non-reserved CHARACTER_LENGTH reserved reserved reserved CHARACTER_SET_CATALOG non-reserved non-reserved non-reserved CHARACTER_SET_NAME non-reserved non-reserved non-reserved CHARACTER_SET_SCHEMA non-reserved non-reserved non-reserved CHAR_LENGTH reserved reserved reserved CHECK reserved reserved reserved reserved CHECKPOINT non-reserved CLASS non-reserved CLASS_ORIGIN non-reserved non-reserved non-reserved CLOB reserved reserved CLOSE non-reserved reserved reserved reserved CLUSTER non-reserved COALESCE non-reserved (cannot be function or type) reserved reserved reserved COBOL non-reserved non-reserved non-reserved COLLATE reserved reserved reserved reserved COLLATION reserved (can be function or type) non-reserved non-reserved reserved COLLATION_CATALOG non-reserved non-reserved non-reserved COLLATION_NAME non-reserved non-reserved non-reserved COLLATION_SCHEMA non-reserved non-reserved non-reserved COLLECT reserved reserved COLUMN reserved reserved reserved reserved COLUMNS non-reserved non-reserved COLUMN_NAME non-reserved non-reserved non-reserved COMMAND_FUNCTION non-reserved non-reserved non-reserved COMMAND_FUNCTION_CODE non-reserved non-reserved COMMENT non-reserved COMMENTS non-reserved COMMIT non-reserved reserved reserved reserved COMMITTED non-reserved non-reserved non-reserved non-reserved CONCURRENTLY reserved (can be function or type) CONDITION reserved reserved CONDITION_NUMBER non-reserved non-reserved non-reserved CONFIGURATION non-reserved CONNECT reserved reserved reserved CONNECTION non-reserved non-reserved non-reserved reserved CONNECTION_NAME non-reserved non-reserved non-reserved CONSTRAINT reserved reserved reserved reserved CONSTRAINTS non-reserved non-reserved non-reserved reserved CONSTRAINT_CATALOG non-reserved non-reserved non-reserved CONSTRAINT_NAME non-reserved non-reserved non-reserved CONSTRAINT_SCHEMA non-reserved non-reserved non-reserved CONSTRUCTOR non-reserved non-reserved CONTAINS reserved non-reserved CONTENT non-reserved non-reserved non-reserved CONTINUE non-reserved non-reserved non-reserved reserved CONTROL non-reserved non-reserved CONVERSION non-reserved CONVERT reserved reserved reserved COPY non-reserved CORR reserved reserved CORRESPONDING reserved reserved reserved COST non-reserved COUNT reserved reserved reserved COVAR_POP reserved reserved COVAR_SAMP reserved reserved CREATE reserved reserved reserved reserved CROSS reserved (can be function or type) reserved reserved reserved CSV non-reserved CUBE reserved reserved CUME_DIST reserved reserved CURRENT non-reserved reserved reserved reserved CURRENT_CATALOG reserved reserved reserved CURRENT_DATE reserved reserved reserved reserved CURRENT_DEFAULT_TRANSFORM_GROUP reserved reserved CURRENT_PATH reserved reserved CURRENT_ROLE reserved reserved reserved CURRENT_ROW reserved CURRENT_SCHEMA reserved (can be function or type) reserved reserved CURRENT_TIME reserved reserved reserved reserved CURRENT_TIMESTAMP reserved reserved reserved reserved CURRENT_TRANSFORM_GROUP_FOR_TYPE reserved reserved CURRENT_USER reserved reserved reserved reserved CURSOR non-reserved reserved reserved reserved CURSOR_NAME non-reserved non-reserved non-reserved CYCLE non-reserved reserved reserved DATA non-reserved non-reserved non-reserved non-reserved DATABASE non-reserved DATALINK reserved reserved DATE reserved reserved reserved DATETIME_INTERVAL_CODE non-reserved non-reserved non-reserved DATETIME_INTERVAL_PRECISION non-reserved non-reserved non-reserved DAY non-reserved reserved reserved reserved DB non-reserved non-reserved DEALLOCATE non-reserved reserved reserved reserved DEC non-reserved (cannot be function or type) reserved reserved reserved DECIMAL non-reserved (cannot be function or type) reserved reserved reserved DECLARE non-reserved reserved reserved reserved DEFAULT reserved reserved reserved reserved DEFAULTS non-reserved non-reserved non-reserved DEFERRABLE reserved non-reserved non-reserved reserved DEFERRED non-reserved non-reserved non-reserved reserved DEFINED non-reserved non-reserved DEFINER non-reserved non-reserved non-reserved DEGREE non-reserved non-reserved DELETE non-reserved reserved reserved reserved DELIMITER non-reserved DELIMITERS non-reserved DENSE_RANK reserved reserved DEPTH non-reserved non-reserved DEREF reserved reserved DERIVED non-reserved non-reserved DESC reserved non-reserved non-reserved reserved DESCRIBE reserved reserved reserved DESCRIPTOR non-reserved non-reserved reserved DETERMINISTIC reserved reserved DIAGNOSTICS non-reserved non-reserved reserved DICTIONARY non-reserved DISABLE non-reserved DISCARD non-reserved DISCONNECT reserved reserved reserved DISPATCH non-reserved non-reserved DISTINCT reserved reserved reserved reserved DLNEWCOPY reserved reserved DLPREVIOUSCOPY reserved reserved DLURLCOMPLETE reserved reserved DLURLCOMPLETEONLY reserved reserved DLURLCOMPLETEWRITE reserved reserved DLURLPATH reserved reserved DLURLPATHONLY reserved reserved DLURLPATHWRITE reserved reserved DLURLSCHEME reserved reserved DLURLSERVER reserved reserved DLVALUE reserved reserved DO reserved DOCUMENT non-reserved non-reserved non-reserved DOMAIN non-reserved non-reserved non-reserved reserved DOUBLE non-reserved reserved reserved reserved DROP non-reserved reserved reserved reserved DYNAMIC reserved reserved DYNAMIC_FUNCTION non-reserved non-reserved non-reserved DYNAMIC_FUNCTION_CODE non-reserved non-reserved EACH non-reserved reserved reserved ELEMENT reserved reserved ELSE reserved reserved reserved reserved EMPTY non-reserved non-reserved ENABLE non-reserved ENCODING non-reserved non-reserved non-reserved ENCRYPTED non-reserved END reserved reserved reserved reserved END-EXEC reserved reserved reserved END_FRAME reserved END_PARTITION reserved ENFORCED non-reserved ENUM non-reserved EQUALS reserved non-reserved ESCAPE non-reserved reserved reserved reserved EVENT non-reserved EVERY reserved reserved EXCEPT reserved reserved reserved reserved EXCEPTION reserved EXCLUDE non-reserved non-reserved non-reserved EXCLUDING non-reserved non-reserved non-reserved EXCLUSIVE non-reserved EXEC reserved reserved reserved EXECUTE non-reserved reserved reserved reserved EXISTS non-reserved (cannot be function or type) reserved reserved reserved EXP reserved reserved EXPLAIN non-reserved EXPRESSION non-reserved EXTENSION non-reserved EXTERNAL non-reserved reserved reserved reserved EXTRACT non-reserved (cannot be function or type) reserved reserved reserved FALSE reserved reserved reserved reserved FAMILY non-reserved FETCH reserved reserved reserved reserved FILE non-reserved non-reserved FILTER reserved reserved FINAL non-reserved non-reserved FIRST non-reserved non-reserved non-reserved reserved FIRST_VALUE reserved reserved FLAG non-reserved non-reserved FLOAT non-reserved (cannot be function or type) reserved reserved reserved FLOOR reserved reserved FOLLOWING non-reserved non-reserved non-reserved FOR reserved reserved reserved reserved FORCE non-reserved FOREIGN reserved reserved reserved reserved FORTRAN non-reserved non-reserved non-reserved FORWARD non-reserved FOUND non-reserved non-reserved reserved FRAME_ROW reserved FREE reserved reserved FREEZE reserved (can be function or type) FROM reserved reserved reserved reserved FS non-reserved non-reserved FULL reserved (can be function or type) reserved reserved reserved FUNCTION non-reserved reserved reserved FUNCTIONS non-reserved FUSION reserved reserved G non-reserved non-reserved GENERAL non-reserved non-reserved GENERATED non-reserved non-reserved GET reserved reserved reserved GLOBAL non-reserved reserved reserved reserved GO non-reserved non-reserved reserved GOTO non-reserved non-reserved reserved GRANT reserved reserved reserved reserved GRANTED non-reserved non-reserved non-reserved GREATEST non-reserved (cannot be function or type) GROUP reserved reserved reserved reserved GROUPING reserved reserved GROUPS reserved HANDLER non-reserved HAVING reserved reserved reserved reserved HEADER non-reserved HEX non-reserved non-reserved HIERARCHY non-reserved non-reserved HOLD non-reserved reserved reserved HOUR non-reserved reserved reserved reserved ID non-reserved non-reserved IDENTITY non-reserved reserved reserved reserved IF non-reserved IGNORE non-reserved non-reserved ILIKE reserved (can be function or type) IMMEDIATE non-reserved non-reserved non-reserved reserved IMMEDIATELY non-reserved IMMUTABLE non-reserved IMPLEMENTATION non-reserved non-reserved IMPLICIT non-reserved IMPORT reserved reserved IN reserved reserved reserved reserved INCLUDING non-reserved non-reserved non-reserved INCREMENT non-reserved non-reserved non-reserved INDENT non-reserved non-reserved INDEX non-reserved INDEXES non-reserved INDICATOR reserved reserved reserved INHERIT non-reserved INHERITS non-reserved INITIALLY reserved non-reserved non-reserved reserved INLINE non-reserved INNER reserved (can be function or type) reserved reserved reserved INOUT non-reserved (cannot be function or type) reserved reserved INPUT non-reserved non-reserved non-reserved reserved INSENSITIVE non-reserved reserved reserved reserved INSERT non-reserved reserved reserved reserved INSTANCE non-reserved non-reserved INSTANTIABLE non-reserved non-reserved INSTEAD non-reserved non-reserved non-reserved INT non-reserved (cannot be function or type) reserved reserved reserved INTEGER non-reserved (cannot be function or type) reserved reserved reserved INTEGRITY non-reserved non-reserved INTERSECT reserved reserved reserved reserved INTERSECTION reserved reserved INTERVAL non-reserved (cannot be function or type) reserved reserved reserved INTO reserved reserved reserved reserved INVOKER non-reserved non-reserved non-reserved IS reserved (can be function or type) reserved reserved reserved ISNULL reserved (can be function or type) ISOLATION non-reserved non-reserved non-reserved reserved JOIN reserved (can be function or type) reserved reserved reserved K non-reserved non-reserved KEY non-reserved non-reserved non-reserved reserved KEY_MEMBER non-reserved non-reserved KEY_TYPE non-reserved non-reserved LABEL non-reserved LAG reserved reserved LANGUAGE non-reserved reserved reserved reserved LARGE non-reserved reserved reserved LAST non-reserved non-reserved non-reserved reserved LAST_VALUE reserved reserved LATERAL reserved reserved reserved LC_COLLATE non-reserved LC_CTYPE non-reserved LEAD reserved reserved LEADING reserved reserved reserved reserved LEAKPROOF non-reserved LEAST non-reserved (cannot be function or type) LEFT reserved (can be function or type) reserved reserved reserved LENGTH non-reserved non-reserved non-reserved LEVEL non-reserved non-reserved non-reserved reserved LIBRARY non-reserved non-reserved LIKE reserved (can be function or type) reserved reserved reserved LIKE_REGEX reserved reserved LIMIT reserved non-reserved non-reserved LINK non-reserved non-reserved LISTEN non-reserved LN reserved reserved LOAD non-reserved LOCAL non-reserved reserved reserved reserved LOCALTIME reserved reserved reserved LOCALTIMESTAMP reserved reserved reserved LOCATION non-reserved non-reserved non-reserved LOCATOR non-reserved non-reserved LOCK non-reserved LOWER reserved reserved reserved M non-reserved non-reserved MAP non-reserved non-reserved MAPPING non-reserved non-reserved non-reserved MATCH non-reserved reserved reserved reserved MATCHED non-reserved non-reserved MATERIALIZED non-reserved MAX reserved reserved reserved MAXVALUE non-reserved non-reserved non-reserved MAX_CARDINALITY reserved MEMBER reserved reserved MERGE reserved reserved MESSAGE_LENGTH non-reserved non-reserved non-reserved MESSAGE_OCTET_LENGTH non-reserved non-reserved non-reserved MESSAGE_TEXT non-reserved non-reserved non-reserved METHOD reserved reserved MIN reserved reserved reserved MINUTE non-reserved reserved reserved reserved MINVALUE non-reserved non-reserved non-reserved MOD reserved reserved MODE non-reserved MODIFIES reserved reserved MODULE reserved reserved reserved MONTH non-reserved reserved reserved reserved MORE non-reserved non-reserved non-reserved MOVE non-reserved MULTISET reserved reserved MUMPS non-reserved non-reserved non-reserved NAME non-reserved non-reserved non-reserved non-reserved NAMES non-reserved non-reserved non-reserved reserved NAMESPACE non-reserved non-reserved NATIONAL non-reserved (cannot be function or type) reserved reserved reserved NATURAL reserved (can be function or type) reserved reserved reserved NCHAR non-reserved (cannot be function or type) reserved reserved reserved NCLOB reserved reserved NESTING non-reserved non-reserved NEW reserved reserved NEXT non-reserved non-reserved non-reserved reserved NFC non-reserved non-reserved NFD non-reserved non-reserved NFKC non-reserved non-reserved NFKD non-reserved non-reserved NIL non-reserved non-reserved NO non-reserved reserved reserved reserved NONE non-reserved (cannot be function or type) reserved reserved NORMALIZE reserved reserved NORMALIZED non-reserved non-reserved NOT reserved reserved reserved reserved NOTHING non-reserved NOTIFY non-reserved NOTNULL reserved (can be function or type) NOWAIT non-reserved NTH_VALUE reserved reserved NTILE reserved reserved NULL reserved reserved reserved reserved NULLABLE non-reserved non-reserved non-reserved NULLIF non-reserved (cannot be function or type) reserved reserved reserved NULLS non-reserved non-reserved non-reserved NUMBER non-reserved non-reserved non-reserved NUMERIC non-reserved (cannot be function or type) reserved reserved reserved OBJECT non-reserved non-reserved non-reserved OCCURRENCES_REGEX reserved reserved OCTETS non-reserved non-reserved OCTET_LENGTH reserved reserved reserved OF non-reserved reserved reserved reserved OFF non-reserved non-reserved non-reserved OFFSET reserved reserved reserved OIDS non-reserved OLD reserved reserved ON reserved reserved reserved reserved ONLY reserved reserved reserved reserved OPEN reserved reserved reserved OPERATOR non-reserved OPTION non-reserved non-reserved non-reserved reserved OPTIONS non-reserved non-reserved non-reserved OR reserved reserved reserved reserved ORDER reserved reserved reserved reserved ORDERING non-reserved non-reserved ORDINALITY non-reserved non-reserved OTHERS non-reserved non-reserved OUT non-reserved (cannot be function or type) reserved reserved OUTER reserved (can be function or type) reserved reserved reserved OUTPUT non-reserved non-reserved reserved OVER reserved (can be function or type) reserved reserved OVERLAPS reserved (can be function or type) reserved reserved reserved OVERLAY non-reserved (cannot be function or type) reserved reserved OVERRIDING non-reserved non-reserved OWNED non-reserved OWNER non-reserved P non-reserved non-reserved PAD non-reserved non-reserved reserved PARAMETER reserved reserved PARAMETER_MODE non-reserved non-reserved PARAMETER_NAME non-reserved non-reserved PARAMETER_ORDINAL_POSITION non-reserved non-reserved PARAMETER_SPECIFIC_CATALOG non-reserved non-reserved PARAMETER_SPECIFIC_NAME non-reserved non-reserved PARAMETER_SPECIFIC_SCHEMA non-reserved non-reserved PARSER non-reserved PARTIAL non-reserved non-reserved non-reserved reserved PARTITION non-reserved reserved reserved PASCAL non-reserved non-reserved non-reserved PASSING non-reserved non-reserved non-reserved PASSTHROUGH non-reserved non-reserved PASSWORD non-reserved PATH non-reserved non-reserved PERCENT reserved PERCENTILE_CONT reserved reserved PERCENTILE_DISC reserved reserved PERCENT_RANK reserved reserved PERIOD reserved PERMISSION non-reserved non-reserved PLACING reserved non-reserved non-reserved PLANS non-reserved PLI non-reserved non-reserved non-reserved PORTION reserved POSITION non-reserved (cannot be function or type) reserved reserved reserved POSITION_REGEX reserved reserved POWER reserved reserved PRECEDES reserved PRECEDING non-reserved non-reserved non-reserved PRECISION non-reserved (cannot be function or type) reserved reserved reserved PREPARE non-reserved reserved reserved reserved PREPARED non-reserved PRESERVE non-reserved non-reserved non-reserved reserved PRIMARY reserved reserved reserved reserved PRIOR non-reserved non-reserved non-reserved reserved PRIVILEGES non-reserved non-reserved non-reserved reserved PROCEDURAL non-reserved PROCEDURE non-reserved reserved reserved reserved PROGRAM non-reserved PUBLIC non-reserved non-reserved reserved QUOTE non-reserved RANGE non-reserved reserved reserved RANK reserved reserved READ non-reserved non-reserved non-reserved reserved READS reserved reserved REAL non-reserved (cannot be function or type) reserved reserved reserved REASSIGN non-reserved RECHECK non-reserved RECOVERY non-reserved non-reserved RECURSIVE non-reserved reserved reserved REF non-reserved reserved reserved REFERENCES reserved reserved reserved reserved REFERENCING reserved reserved REFRESH non-reserved REGR_AVGX reserved reserved REGR_AVGY reserved reserved REGR_COUNT reserved reserved REGR_INTERCEPT reserved reserved REGR_R2 reserved reserved REGR_SLOPE reserved reserved REGR_SXX reserved reserved REGR_SXY reserved reserved REGR_SYY reserved reserved REINDEX non-reserved RELATIVE non-reserved non-reserved non-reserved reserved RELEASE non-reserved reserved reserved RENAME non-reserved REPEATABLE non-reserved non-reserved non-reserved non-reserved REPLACE non-reserved REPLICA non-reserved REQUIRING non-reserved non-reserved RESET non-reserved RESPECT non-reserved non-reserved RESTART non-reserved non-reserved non-reserved RESTORE non-reserved non-reserved RESTRICT non-reserved non-reserved non-reserved reserved RESULT reserved reserved RETURN reserved reserved RETURNED_CARDINALITY non-reserved non-reserved RETURNED_LENGTH non-reserved non-reserved non-reserved RETURNED_OCTET_LENGTH non-reserved non-reserved non-reserved RETURNED_SQLSTATE non-reserved non-reserved non-reserved RETURNING reserved non-reserved non-reserved RETURNS non-reserved reserved reserved REVOKE non-reserved reserved reserved reserved RIGHT reserved (can be function or type) reserved reserved reserved ROLE non-reserved non-reserved non-reserved ROLLBACK non-reserved reserved reserved reserved ROLLUP reserved reserved ROUTINE non-reserved non-reserved ROUTINE_CATALOG non-reserved non-reserved ROUTINE_NAME non-reserved non-reserved ROUTINE_SCHEMA non-reserved non-reserved ROW non-reserved (cannot be function or type) reserved reserved ROWS non-reserved reserved reserved reserved ROW_COUNT non-reserved non-reserved non-reserved ROW_NUMBER reserved reserved RULE non-reserved SAVEPOINT non-reserved reserved reserved SCALE non-reserved non-reserved non-reserved SCHEMA non-reserved non-reserved non-reserved reserved SCHEMA_NAME non-reserved non-reserved non-reserved SCOPE reserved reserved SCOPE_CATALOG non-reserved non-reserved SCOPE_NAME non-reserved non-reserved SCOPE_SCHEMA non-reserved non-reserved SCROLL non-reserved reserved reserved reserved SEARCH non-reserved reserved reserved SECOND non-reserved reserved reserved reserved SECTION non-reserved non-reserved reserved SECURITY non-reserved non-reserved non-reserved SELECT reserved reserved reserved reserved SELECTIVE non-reserved non-reserved SELF non-reserved non-reserved SENSITIVE reserved reserved SEQUENCE non-reserved non-reserved non-reserved SEQUENCES non-reserved SERIALIZABLE non-reserved non-reserved non-reserved non-reserved SERVER non-reserved non-reserved non-reserved SERVER_NAME non-reserved non-reserved non-reserved SESSION non-reserved non-reserved non-reserved reserved SESSION_USER reserved reserved reserved reserved SET non-reserved reserved reserved reserved SETOF non-reserved (cannot be function or type) SETS non-reserved non-reserved SHARE non-reserved SHOW non-reserved SIMILAR reserved (can be function or type) reserved reserved SIMPLE non-reserved non-reserved non-reserved SIZE non-reserved non-reserved reserved SMALLINT non-reserved (cannot be function or type) reserved reserved reserved SNAPSHOT non-reserved SOME reserved reserved reserved reserved SOURCE non-reserved non-reserved SPACE non-reserved non-reserved reserved SPECIFIC reserved reserved SPECIFICTYPE reserved reserved SPECIFIC_NAME non-reserved non-reserved SQL reserved reserved reserved SQLCODE reserved SQLERROR reserved SQLEXCEPTION reserved reserved SQLSTATE reserved reserved reserved SQLWARNING reserved reserved SQRT reserved reserved STABLE non-reserved STANDALONE non-reserved non-reserved non-reserved START non-reserved reserved reserved STATE non-reserved non-reserved STATEMENT non-reserved non-reserved non-reserved STATIC reserved reserved STATISTICS non-reserved STDDEV_POP reserved reserved STDDEV_SAMP reserved reserved STDIN non-reserved STDOUT non-reserved STORAGE non-reserved STRICT non-reserved STRIP non-reserved non-reserved non-reserved STRUCTURE non-reserved non-reserved STYLE non-reserved non-reserved SUBCLASS_ORIGIN non-reserved non-reserved non-reserved SUBMULTISET reserved reserved SUBSTRING non-reserved (cannot be function or type) reserved reserved reserved SUBSTRING_REGEX reserved reserved SUCCEEDS reserved SUM reserved reserved reserved SYMMETRIC reserved reserved reserved SYSID non-reserved SYSTEM non-reserved reserved reserved SYSTEM_TIME reserved SYSTEM_USER reserved reserved reserved T non-reserved non-reserved TABLE reserved reserved reserved reserved TABLES non-reserved TABLESAMPLE reserved reserved TABLESPACE non-reserved TABLE_NAME non-reserved non-reserved non-reserved TEMP non-reserved TEMPLATE non-reserved TEMPORARY non-reserved non-reserved non-reserved reserved TEXT non-reserved THEN reserved reserved reserved reserved TIES non-reserved non-reserved TIME non-reserved (cannot be function or type) reserved reserved reserved TIMESTAMP non-reserved (cannot be function or type) reserved reserved reserved TIMEZONE_HOUR reserved reserved reserved TIMEZONE_MINUTE reserved reserved reserved TO reserved reserved reserved reserved TOKEN non-reserved non-reserved TOP_LEVEL_COUNT non-reserved non-reserved TRAILING reserved reserved reserved reserved TRANSACTION non-reserved non-reserved non-reserved reserved TRANSACTIONS_COMMITTED non-reserved non-reserved TRANSACTIONS_ROLLED_BACK non-reserved non-reserved TRANSACTION_ACTIVE non-reserved non-reserved TRANSFORM non-reserved non-reserved TRANSFORMS non-reserved non-reserved TRANSLATE reserved reserved reserved TRANSLATE_REGEX reserved reserved TRANSLATION reserved reserved reserved TREAT non-reserved (cannot be function or type) reserved reserved TRIGGER non-reserved reserved reserved TRIGGER_CATALOG non-reserved non-reserved TRIGGER_NAME non-reserved non-reserved TRIGGER_SCHEMA non-reserved non-reserved TRIM non-reserved (cannot be function or type) reserved reserved reserved TRIM_ARRAY reserved reserved TRUE reserved reserved reserved reserved TRUNCATE non-reserved reserved reserved TRUSTED non-reserved TYPE non-reserved non-reserved non-reserved non-reserved TYPES non-reserved UESCAPE reserved reserved UNBOUNDED non-reserved non-reserved non-reserved UNCOMMITTED non-reserved non-reserved non-reserved non-reserved UNDER non-reserved non-reserved UNENCRYPTED non-reserved UNION reserved reserved reserved reserved UNIQUE reserved reserved reserved reserved UNKNOWN non-reserved reserved reserved reserved UNLINK non-reserved non-reserved UNLISTEN non-reserved UNLOGGED non-reserved UNNAMED non-reserved non-reserved non-reserved UNNEST reserved reserved UNTIL non-reserved UNTYPED non-reserved non-reserved UPDATE non-reserved reserved reserved reserved UPPER reserved reserved reserved URI non-reserved non-reserved USAGE non-reserved non-reserved reserved USER reserved reserved reserved reserved USER_DEFINED_TYPE_CATALOG non-reserved non-reserved USER_DEFINED_TYPE_CODE non-reserved non-reserved USER_DEFINED_TYPE_NAME non-reserved non-reserved USER_DEFINED_TYPE_SCHEMA non-reserved non-reserved USING reserved reserved reserved reserved VACUUM non-reserved VALID non-reserved non-reserved non-reserved VALIDATE non-reserved VALIDATOR non-reserved VALUE non-reserved reserved reserved reserved VALUES non-reserved (cannot be function or type) reserved reserved reserved VALUE_OF reserved VARBINARY reserved reserved VARCHAR non-reserved (cannot be function or type) reserved reserved reserved VARIADIC reserved VARYING non-reserved reserved reserved reserved VAR_POP reserved reserved VAR_SAMP reserved reserved VERBOSE reserved (can be function or type) VERSION non-reserved non-reserved non-reserved VERSIONING reserved VIEW non-reserved non-reserved non-reserved reserved VOLATILE non-reserved WHEN reserved reserved reserved reserved WHENEVER reserved reserved reserved WHERE reserved reserved reserved reserved WHITESPACE non-reserved non-reserved non-reserved WIDTH_BUCKET reserved reserved WINDOW reserved reserved reserved WITH reserved reserved reserved reserved WITHIN reserved reserved WITHOUT non-reserved reserved reserved WORK non-reserved non-reserved non-reserved reserved WRAPPER non-reserved non-reserved non-reserved WRITE non-reserved non-reserved non-reserved reserved XML non-reserved reserved reserved XMLAGG reserved reserved XMLATTRIBUTES non-reserved (cannot be function or type) reserved reserved XMLBINARY reserved reserved XMLCAST reserved reserved XMLCOMMENT reserved reserved XMLCONCAT non-reserved (cannot be function or type) reserved reserved XMLDECLARATION non-reserved non-reserved XMLDOCUMENT reserved reserved XMLELEMENT non-reserved (cannot be function or type) reserved reserved XMLEXISTS non-reserved (cannot be function or type) reserved reserved XMLFOREST non-reserved (cannot be function or type) reserved reserved XMLITERATE reserved reserved XMLNAMESPACES reserved reserved XMLPARSE non-reserved (cannot be function or type) reserved reserved XMLPI non-reserved (cannot be function or type) reserved reserved XMLQUERY reserved reserved XMLROOT non-reserved (cannot be function or type) XMLSCHEMA non-reserved non-reserved XMLSERIALIZE non-reserved (cannot be function or type) reserved reserved XMLTABLE reserved reserved XMLTEXT reserved reserved XMLVALIDATE reserved reserved YEAR non-reserved reserved reserved reserved YES non-reserved non-reserved non-reserved ZONE non-reserved non-reserved non-reserved reserved ================================================ FILE: src/github.com/go-xorm/xorm/postgres_dialect.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "errors" "fmt" "strconv" "strings" "github.com/go-xorm/core" ) // from http://www.postgresql.org/docs/current/static/sql-keywords-appendix.html var ( postgresReservedWords = map[string]bool{ "A": true, "ABORT": true, "ABS": true, "ABSENT": true, "ABSOLUTE": true, "ACCESS": true, "ACCORDING": true, "ACTION": true, "ADA": true, "ADD": true, "ADMIN": true, "AFTER": true, "AGGREGATE": true, "ALL": true, "ALLOCATE": true, "ALSO": true, "ALTER": true, "ALWAYS": true, "ANALYSE": true, "ANALYZE": true, "AND": true, "ANY": true, "ARE": true, "ARRAY": true, "ARRAY_AGG": true, "ARRAY_MAX_CARDINALITY": true, "AS": true, "ASC": true, "ASENSITIVE": true, "ASSERTION": true, "ASSIGNMENT": true, "ASYMMETRIC": true, "AT": true, "ATOMIC": true, "ATTRIBUTE": true, "ATTRIBUTES": true, "AUTHORIZATION": true, "AVG": true, "BACKWARD": true, "BASE64": true, "BEFORE": true, "BEGIN": true, "BEGIN_FRAME": true, "BEGIN_PARTITION": true, "BERNOULLI": true, "BETWEEN": true, "BIGINT": true, "BINARY": true, "BIT": true, "BIT_LENGTH": true, "BLOB": true, "BLOCKED": true, "BOM": true, "BOOLEAN": true, "BOTH": true, "BREADTH": true, "BY": true, "C": true, "CACHE": true, "CALL": true, "CALLED": true, "CARDINALITY": true, "CASCADE": true, "CASCADED": true, "CASE": true, "CAST": true, "CATALOG": true, "CATALOG_NAME": true, "CEIL": true, "CEILING": true, "CHAIN": true, "CHAR": true, "CHARACTER": true, "CHARACTERISTICS": true, "CHARACTERS": true, "CHARACTER_LENGTH": true, "CHARACTER_SET_CATALOG": true, "CHARACTER_SET_NAME": true, "CHARACTER_SET_SCHEMA": true, "CHAR_LENGTH": true, "CHECK": true, "CHECKPOINT": true, "CLASS": true, "CLASS_ORIGIN": true, "CLOB": true, "CLOSE": true, "CLUSTER": true, "COALESCE": true, "COBOL": true, "COLLATE": true, "COLLATION": true, "COLLATION_CATALOG": true, "COLLATION_NAME": true, "COLLATION_SCHEMA": true, "COLLECT": true, "COLUMN": true, "COLUMNS": true, "COLUMN_NAME": true, "COMMAND_FUNCTION": true, "COMMAND_FUNCTION_CODE": true, "COMMENT": true, "COMMENTS": true, "COMMIT": true, "COMMITTED": true, "CONCURRENTLY": true, "CONDITION": true, "CONDITION_NUMBER": true, "CONFIGURATION": true, "CONNECT": true, "CONNECTION": true, "CONNECTION_NAME": true, "CONSTRAINT": true, "CONSTRAINTS": true, "CONSTRAINT_CATALOG": true, "CONSTRAINT_NAME": true, "CONSTRAINT_SCHEMA": true, "CONSTRUCTOR": true, "CONTAINS": true, "CONTENT": true, "CONTINUE": true, "CONTROL": true, "CONVERSION": true, "CONVERT": true, "COPY": true, "CORR": true, "CORRESPONDING": true, "COST": true, "COUNT": true, "COVAR_POP": true, "COVAR_SAMP": true, "CREATE": true, "CROSS": true, "CSV": true, "CUBE": true, "CUME_DIST": true, "CURRENT": true, "CURRENT_CATALOG": true, "CURRENT_DATE": true, "CURRENT_DEFAULT_TRANSFORM_GROUP": true, "CURRENT_PATH": true, "CURRENT_ROLE": true, "CURRENT_ROW": true, "CURRENT_SCHEMA": true, "CURRENT_TIME": true, "CURRENT_TIMESTAMP": true, "CURRENT_TRANSFORM_GROUP_FOR_TYPE": true, "CURRENT_USER": true, "CURSOR": true, "CURSOR_NAME": true, "CYCLE": true, "DATA": true, "DATABASE": true, "DATALINK": true, "DATE": true, "DATETIME_INTERVAL_CODE": true, "DATETIME_INTERVAL_PRECISION": true, "DAY": true, "DB": true, "DEALLOCATE": true, "DEC": true, "DECIMAL": true, "DECLARE": true, "DEFAULT": true, "DEFAULTS": true, "DEFERRABLE": true, "DEFERRED": true, "DEFINED": true, "DEFINER": true, "DEGREE": true, "DELETE": true, "DELIMITER": true, "DELIMITERS": true, "DENSE_RANK": true, "DEPTH": true, "DEREF": true, "DERIVED": true, "DESC": true, "DESCRIBE": true, "DESCRIPTOR": true, "DETERMINISTIC": true, "DIAGNOSTICS": true, "DICTIONARY": true, "DISABLE": true, "DISCARD": true, "DISCONNECT": true, "DISPATCH": true, "DISTINCT": true, "DLNEWCOPY": true, "DLPREVIOUSCOPY": true, "DLURLCOMPLETE": true, "DLURLCOMPLETEONLY": true, "DLURLCOMPLETEWRITE": true, "DLURLPATH": true, "DLURLPATHONLY": true, "DLURLPATHWRITE": true, "DLURLSCHEME": true, "DLURLSERVER": true, "DLVALUE": true, "DO": true, "DOCUMENT": true, "DOMAIN": true, "DOUBLE": true, "DROP": true, "DYNAMIC": true, "DYNAMIC_FUNCTION": true, "DYNAMIC_FUNCTION_CODE": true, "EACH": true, "ELEMENT": true, "ELSE": true, "EMPTY": true, "ENABLE": true, "ENCODING": true, "ENCRYPTED": true, "END": true, "END-EXEC": true, "END_FRAME": true, "END_PARTITION": true, "ENFORCED": true, "ENUM": true, "EQUALS": true, "ESCAPE": true, "EVENT": true, "EVERY": true, "EXCEPT": true, "EXCEPTION": true, "EXCLUDE": true, "EXCLUDING": true, "EXCLUSIVE": true, "EXEC": true, "EXECUTE": true, "EXISTS": true, "EXP": true, "EXPLAIN": true, "EXPRESSION": true, "EXTENSION": true, "EXTERNAL": true, "EXTRACT": true, "FALSE": true, "FAMILY": true, "FETCH": true, "FILE": true, "FILTER": true, "FINAL": true, "FIRST": true, "FIRST_VALUE": true, "FLAG": true, "FLOAT": true, "FLOOR": true, "FOLLOWING": true, "FOR": true, "FORCE": true, "FOREIGN": true, "FORTRAN": true, "FORWARD": true, "FOUND": true, "FRAME_ROW": true, "FREE": true, "FREEZE": true, "FROM": true, "FS": true, "FULL": true, "FUNCTION": true, "FUNCTIONS": true, "FUSION": true, "G": true, "GENERAL": true, "GENERATED": true, "GET": true, "GLOBAL": true, "GO": true, "GOTO": true, "GRANT": true, "GRANTED": true, "GREATEST": true, "GROUP": true, "GROUPING": true, "GROUPS": true, "HANDLER": true, "HAVING": true, "HEADER": true, "HEX": true, "HIERARCHY": true, "HOLD": true, "HOUR": true, "ID": true, "IDENTITY": true, "IF": true, "IGNORE": true, "ILIKE": true, "IMMEDIATE": true, "IMMEDIATELY": true, "IMMUTABLE": true, "IMPLEMENTATION": true, "IMPLICIT": true, "IMPORT": true, "IN": true, "INCLUDING": true, "INCREMENT": true, "INDENT": true, "INDEX": true, "INDEXES": true, "INDICATOR": true, "INHERIT": true, "INHERITS": true, "INITIALLY": true, "INLINE": true, "INNER": true, "INOUT": true, "INPUT": true, "INSENSITIVE": true, "INSERT": true, "INSTANCE": true, "INSTANTIABLE": true, "INSTEAD": true, "INT": true, "INTEGER": true, "INTEGRITY": true, "INTERSECT": true, "INTERSECTION": true, "INTERVAL": true, "INTO": true, "INVOKER": true, "IS": true, "ISNULL": true, "ISOLATION": true, "JOIN": true, "K": true, "KEY": true, "KEY_MEMBER": true, "KEY_TYPE": true, "LABEL": true, "LAG": true, "LANGUAGE": true, "LARGE": true, "LAST": true, "LAST_VALUE": true, "LATERAL": true, "LC_COLLATE": true, "LC_CTYPE": true, "LEAD": true, "LEADING": true, "LEAKPROOF": true, "LEAST": true, "LEFT": true, "LENGTH": true, "LEVEL": true, "LIBRARY": true, "LIKE": true, "LIKE_REGEX": true, "LIMIT": true, "LINK": true, "LISTEN": true, "LN": true, "LOAD": true, "LOCAL": true, "LOCALTIME": true, "LOCALTIMESTAMP": true, "LOCATION": true, "LOCATOR": true, "LOCK": true, "LOWER": true, "M": true, "MAP": true, "MAPPING": true, "MATCH": true, "MATCHED": true, "MATERIALIZED": true, "MAX": true, "MAXVALUE": true, "MAX_CARDINALITY": true, "MEMBER": true, "MERGE": true, "MESSAGE_LENGTH": true, "MESSAGE_OCTET_LENGTH": true, "MESSAGE_TEXT": true, "METHOD": true, "MIN": true, "MINUTE": true, "MINVALUE": true, "MOD": true, "MODE": true, "MODIFIES": true, "MODULE": true, "MONTH": true, "MORE": true, "MOVE": true, "MULTISET": true, "MUMPS": true, "NAME": true, "NAMES": true, "NAMESPACE": true, "NATIONAL": true, "NATURAL": true, "NCHAR": true, "NCLOB": true, "NESTING": true, "NEW": true, "NEXT": true, "NFC": true, "NFD": true, "NFKC": true, "NFKD": true, "NIL": true, "NO": true, "NONE": true, "NORMALIZE": true, "NORMALIZED": true, "NOT": true, "NOTHING": true, "NOTIFY": true, "NOTNULL": true, "NOWAIT": true, "NTH_VALUE": true, "NTILE": true, "NULL": true, "NULLABLE": true, "NULLIF": true, "NULLS": true, "NUMBER": true, "NUMERIC": true, "OBJECT": true, "OCCURRENCES_REGEX": true, "OCTETS": true, "OCTET_LENGTH": true, "OF": true, "OFF": true, "OFFSET": true, "OIDS": true, "OLD": true, "ON": true, "ONLY": true, "OPEN": true, "OPERATOR": true, "OPTION": true, "OPTIONS": true, "OR": true, "ORDER": true, "ORDERING": true, "ORDINALITY": true, "OTHERS": true, "OUT": true, "OUTER": true, "OUTPUT": true, "OVER": true, "OVERLAPS": true, "OVERLAY": true, "OVERRIDING": true, "OWNED": true, "OWNER": true, "P": true, "PAD": true, "PARAMETER": true, "PARAMETER_MODE": true, "PARAMETER_NAME": true, "PARAMETER_ORDINAL_POSITION": true, "PARAMETER_SPECIFIC_CATALOG": true, "PARAMETER_SPECIFIC_NAME": true, "PARAMETER_SPECIFIC_SCHEMA": true, "PARSER": true, "PARTIAL": true, "PARTITION": true, "PASCAL": true, "PASSING": true, "PASSTHROUGH": true, "PASSWORD": true, "PATH": true, "PERCENT": true, "PERCENTILE_CONT": true, "PERCENTILE_DISC": true, "PERCENT_RANK": true, "PERIOD": true, "PERMISSION": true, "PLACING": true, "PLANS": true, "PLI": true, "PORTION": true, "POSITION": true, "POSITION_REGEX": true, "POWER": true, "PRECEDES": true, "PRECEDING": true, "PRECISION": true, "PREPARE": true, "PREPARED": true, "PRESERVE": true, "PRIMARY": true, "PRIOR": true, "PRIVILEGES": true, "PROCEDURAL": true, "PROCEDURE": true, "PROGRAM": true, "PUBLIC": true, "QUOTE": true, "RANGE": true, "RANK": true, "READ": true, "READS": true, "REAL": true, "REASSIGN": true, "RECHECK": true, "RECOVERY": true, "RECURSIVE": true, "REF": true, "REFERENCES": true, "REFERENCING": true, "REFRESH": true, "REGR_AVGX": true, "REGR_AVGY": true, "REGR_COUNT": true, "REGR_INTERCEPT": true, "REGR_R2": true, "REGR_SLOPE": true, "REGR_SXX": true, "REGR_SXY": true, "REGR_SYY": true, "REINDEX": true, "RELATIVE": true, "RELEASE": true, "RENAME": true, "REPEATABLE": true, "REPLACE": true, "REPLICA": true, "REQUIRING": true, "RESET": true, "RESPECT": true, "RESTART": true, "RESTORE": true, "RESTRICT": true, "RESULT": true, "RETURN": true, "RETURNED_CARDINALITY": true, "RETURNED_LENGTH": true, "RETURNED_OCTET_LENGTH": true, "RETURNED_SQLSTATE": true, "RETURNING": true, "RETURNS": true, "REVOKE": true, "RIGHT": true, "ROLE": true, "ROLLBACK": true, "ROLLUP": true, "ROUTINE": true, "ROUTINE_CATALOG": true, "ROUTINE_NAME": true, "ROUTINE_SCHEMA": true, "ROW": true, "ROWS": true, "ROW_COUNT": true, "ROW_NUMBER": true, "RULE": true, "SAVEPOINT": true, "SCALE": true, "SCHEMA": true, "SCHEMA_NAME": true, "SCOPE": true, "SCOPE_CATALOG": true, "SCOPE_NAME": true, "SCOPE_SCHEMA": true, "SCROLL": true, "SEARCH": true, "SECOND": true, "SECTION": true, "SECURITY": true, "SELECT": true, "SELECTIVE": true, "SELF": true, "SENSITIVE": true, "SEQUENCE": true, "SEQUENCES": true, "SERIALIZABLE": true, "SERVER": true, "SERVER_NAME": true, "SESSION": true, "SESSION_USER": true, "SET": true, "SETOF": true, "SETS": true, "SHARE": true, "SHOW": true, "SIMILAR": true, "SIMPLE": true, "SIZE": true, "SMALLINT": true, "SNAPSHOT": true, "SOME": true, "SOURCE": true, "SPACE": true, "SPECIFIC": true, "SPECIFICTYPE": true, "SPECIFIC_NAME": true, "SQL": true, "SQLCODE": true, "SQLERROR": true, "SQLEXCEPTION": true, "SQLSTATE": true, "SQLWARNING": true, "SQRT": true, "STABLE": true, "STANDALONE": true, "START": true, "STATE": true, "STATEMENT": true, "STATIC": true, "STATISTICS": true, "STDDEV_POP": true, "STDDEV_SAMP": true, "STDIN": true, "STDOUT": true, "STORAGE": true, "STRICT": true, "STRIP": true, "STRUCTURE": true, "STYLE": true, "SUBCLASS_ORIGIN": true, "SUBMULTISET": true, "SUBSTRING": true, "SUBSTRING_REGEX": true, "SUCCEEDS": true, "SUM": true, "SYMMETRIC": true, "SYSID": true, "SYSTEM": true, "SYSTEM_TIME": true, "SYSTEM_USER": true, "T": true, "TABLE": true, "TABLES": true, "TABLESAMPLE": true, "TABLESPACE": true, "TABLE_NAME": true, "TEMP": true, "TEMPLATE": true, "TEMPORARY": true, "TEXT": true, "THEN": true, "TIES": true, "TIME": true, "TIMESTAMP": true, "TIMEZONE_HOUR": true, "TIMEZONE_MINUTE": true, "TO": true, "TOKEN": true, "TOP_LEVEL_COUNT": true, "TRAILING": true, "TRANSACTION": true, "TRANSACTIONS_COMMITTED": true, "TRANSACTIONS_ROLLED_BACK": true, "TRANSACTION_ACTIVE": true, "TRANSFORM": true, "TRANSFORMS": true, "TRANSLATE": true, "TRANSLATE_REGEX": true, "TRANSLATION": true, "TREAT": true, "TRIGGER": true, "TRIGGER_CATALOG": true, "TRIGGER_NAME": true, "TRIGGER_SCHEMA": true, "TRIM": true, "TRIM_ARRAY": true, "TRUE": true, "TRUNCATE": true, "TRUSTED": true, "TYPE": true, "TYPES": true, "UESCAPE": true, "UNBOUNDED": true, "UNCOMMITTED": true, "UNDER": true, "UNENCRYPTED": true, "UNION": true, "UNIQUE": true, "UNKNOWN": true, "UNLINK": true, "UNLISTEN": true, "UNLOGGED": true, "UNNAMED": true, "UNNEST": true, "UNTIL": true, "UNTYPED": true, "UPDATE": true, "UPPER": true, "URI": true, "USAGE": true, "USER": true, "USER_DEFINED_TYPE_CATALOG": true, "USER_DEFINED_TYPE_CODE": true, "USER_DEFINED_TYPE_NAME": true, "USER_DEFINED_TYPE_SCHEMA": true, "USING": true, "VACUUM": true, "VALID": true, "VALIDATE": true, "VALIDATOR": true, "VALUE": true, "VALUES": true, "VALUE_OF": true, "VARBINARY": true, "VARCHAR": true, "VARIADIC": true, "VARYING": true, "VAR_POP": true, "VAR_SAMP": true, "VERBOSE": true, "VERSION": true, "VERSIONING": true, "VIEW": true, "VOLATILE": true, "WHEN": true, "WHENEVER": true, "WHERE": true, "WHITESPACE": true, "WIDTH_BUCKET": true, "WINDOW": true, "WITH": true, "WITHIN": true, "WITHOUT": true, "WORK": true, "WRAPPER": true, "WRITE": true, "XML": true, "XMLAGG": true, "XMLATTRIBUTES": true, "XMLBINARY": true, "XMLCAST": true, "XMLCOMMENT": true, "XMLCONCAT": true, "XMLDECLARATION": true, "XMLDOCUMENT": true, "XMLELEMENT": true, "XMLEXISTS": true, "XMLFOREST": true, "XMLITERATE": true, "XMLNAMESPACES": true, "XMLPARSE": true, "XMLPI": true, "XMLQUERY": true, "XMLROOT": true, "XMLSCHEMA": true, "XMLSERIALIZE": true, "XMLTABLE": true, "XMLTEXT": true, "XMLVALIDATE": true, "YEAR": true, "YES": true, "ZONE": true, } ) type postgres struct { core.Base } func (db *postgres) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error { return db.Base.Init(d, db, uri, drivername, dataSourceName) } func (db *postgres) SqlType(c *core.Column) string { var res string switch t := c.SQLType.Name; t { case core.TinyInt: res = core.SmallInt return res case core.MediumInt, core.Int, core.Integer: if c.IsAutoIncrement { return core.Serial } return core.Integer case core.Serial, core.BigSerial: c.IsAutoIncrement = true c.Nullable = false res = t case core.Binary, core.VarBinary: return core.Bytea case core.DateTime: res = core.TimeStamp case core.TimeStampz: return "timestamp with time zone" case core.Float: res = core.Real case core.TinyText, core.MediumText, core.LongText: res = core.Text case core.NVarchar: res = core.Varchar case core.Uuid: res = core.Uuid case core.Blob, core.TinyBlob, core.MediumBlob, core.LongBlob: return core.Bytea case core.Double: return "DOUBLE PRECISION" default: if c.IsAutoIncrement { return core.Serial } res = t } var hasLen1 bool = (c.Length > 0) var hasLen2 bool = (c.Length2 > 0) if hasLen2 { res += "(" + strconv.Itoa(c.Length) + "," + strconv.Itoa(c.Length2) + ")" } else if hasLen1 { res += "(" + strconv.Itoa(c.Length) + ")" } return res } func (db *postgres) SupportInsertMany() bool { return true } func (db *postgres) IsReserved(name string) bool { _, ok := postgresReservedWords[name] return ok } func (db *postgres) Quote(name string) string { name = strings.Replace(name, ".", `"."`, -1) return "\"" + name + "\"" } func (db *postgres) QuoteStr() string { return "\"" } func (db *postgres) AutoIncrStr() string { return "" } func (db *postgres) SupportEngine() bool { return false } func (db *postgres) SupportCharset() bool { return false } func (db *postgres) IndexOnTable() bool { return false } func (db *postgres) IndexCheckSql(tableName, idxName string) (string, []interface{}) { args := []interface{}{tableName, idxName} return `SELECT indexname FROM pg_indexes ` + `WHERE tablename = ? AND indexname = ?`, args } func (db *postgres) TableCheckSql(tableName string) (string, []interface{}) { args := []interface{}{tableName} return `SELECT tablename FROM pg_tables WHERE tablename = ?`, args } /*func (db *postgres) ColumnCheckSql(tableName, colName string) (string, []interface{}) { args := []interface{}{tableName, colName} return "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ?" + " AND column_name = ?", args }*/ func (db *postgres) ModifyColumnSql(tableName string, col *core.Column) string { return fmt.Sprintf("alter table %s ALTER COLUMN %s TYPE %s", tableName, col.Name, db.SqlType(col)) } func (db *postgres) DropIndexSql(tableName string, index *core.Index) string { quote := db.Quote //var unique string var idxName string = index.Name if !strings.HasPrefix(idxName, "UQE_") && !strings.HasPrefix(idxName, "IDX_") { if index.Type == core.UniqueType { idxName = fmt.Sprintf("UQE_%v_%v", tableName, index.Name) } else { idxName = fmt.Sprintf("IDX_%v_%v", tableName, index.Name) } } return fmt.Sprintf("DROP INDEX %v", quote(idxName)) } func (db *postgres) IsColumnExist(tableName, colName string) (bool, error) { args := []interface{}{tableName, colName} query := "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = $1" + " AND column_name = $2" db.LogSQL(query, args) rows, err := db.DB().Query(query, args...) if err != nil { return false, err } defer rows.Close() return rows.Next(), nil } func (db *postgres) GetColumns(tableName string) ([]string, map[string]*core.Column, error) { // FIXME: the schema should be replaced by user custom's args := []interface{}{tableName, "public"} s := `SELECT column_name, column_default, is_nullable, data_type, character_maximum_length, numeric_precision, numeric_precision_radix , CASE WHEN p.contype = 'p' THEN true ELSE false END AS primarykey, CASE WHEN p.contype = 'u' THEN true ELSE false END AS uniquekey FROM pg_attribute f JOIN pg_class c ON c.oid = f.attrelid JOIN pg_type t ON t.oid = f.atttypid LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum LEFT JOIN pg_namespace n ON n.oid = c.relnamespace LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey) LEFT JOIN pg_class AS g ON p.confrelid = g.oid LEFT JOIN INFORMATION_SCHEMA.COLUMNS s ON s.column_name=f.attname AND c.relname=s.table_name WHERE c.relkind = 'r'::char AND c.relname = $1 AND s.table_schema = $2 AND f.attnum > 0 ORDER BY f.attnum;` db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, nil, err } defer rows.Close() cols := make(map[string]*core.Column) colSeq := make([]string, 0) for rows.Next() { col := new(core.Column) col.Indexes = make(map[string]int) var colName, isNullable, dataType string var maxLenStr, colDefault, numPrecision, numRadix *string var isPK, isUnique bool err = rows.Scan(&colName, &colDefault, &isNullable, &dataType, &maxLenStr, &numPrecision, &numRadix, &isPK, &isUnique) if err != nil { return nil, nil, err } //fmt.Println(args, colName, isNullable, dataType, maxLenStr, colDefault, numPrecision, numRadix, isPK, isUnique) var maxLen int if maxLenStr != nil { maxLen, err = strconv.Atoi(*maxLenStr) if err != nil { return nil, nil, err } } col.Name = strings.Trim(colName, `" `) if colDefault != nil || isPK { if isPK { col.IsPrimaryKey = true } else { col.Default = *colDefault } } if colDefault != nil && strings.HasPrefix(*colDefault, "nextval(") { col.IsAutoIncrement = true } col.Nullable = (isNullable == "YES") switch dataType { case "character varying", "character": col.SQLType = core.SQLType{core.Varchar, 0, 0} case "timestamp without time zone": col.SQLType = core.SQLType{core.DateTime, 0, 0} case "timestamp with time zone": col.SQLType = core.SQLType{core.TimeStampz, 0, 0} case "double precision": col.SQLType = core.SQLType{core.Double, 0, 0} case "boolean": col.SQLType = core.SQLType{core.Bool, 0, 0} case "time without time zone": col.SQLType = core.SQLType{core.Time, 0, 0} case "oid": col.SQLType = core.SQLType{core.BigInt, 0, 0} default: col.SQLType = core.SQLType{strings.ToUpper(dataType), 0, 0} } if _, ok := core.SqlTypes[col.SQLType.Name]; !ok { return nil, nil, errors.New(fmt.Sprintf("unknow colType: %v", dataType)) } col.Length = maxLen if col.SQLType.IsText() || col.SQLType.IsTime() { if col.Default != "" { col.Default = "'" + col.Default + "'" } else { if col.DefaultIsEmpty { col.Default = "''" } } } cols[col.Name] = col colSeq = append(colSeq, col.Name) } return colSeq, cols, nil } func (db *postgres) GetTables() ([]*core.Table, error) { // FIXME: replace public to user customrize schema args := []interface{}{"public"} s := fmt.Sprintf("SELECT tablename FROM pg_tables WHERE schemaname = $1") db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, err } defer rows.Close() tables := make([]*core.Table, 0) for rows.Next() { table := core.NewEmptyTable() var name string err = rows.Scan(&name) if err != nil { return nil, err } table.Name = name tables = append(tables, table) } return tables, nil } func (db *postgres) GetIndexes(tableName string) (map[string]*core.Index, error) { // FIXME: replace the public schema to user specify schema args := []interface{}{"public", tableName} s := fmt.Sprintf("SELECT indexname, indexdef FROM pg_indexes WHERE schemaname=$1 AND tablename=$2") db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, err } defer rows.Close() indexes := make(map[string]*core.Index, 0) for rows.Next() { var indexType int var indexName, indexdef string var colNames []string err = rows.Scan(&indexName, &indexdef) if err != nil { return nil, err } indexName = strings.Trim(indexName, `" `) if strings.HasSuffix(indexName, "_pkey") { continue } if strings.HasPrefix(indexdef, "CREATE UNIQUE INDEX") { indexType = core.UniqueType } else { indexType = core.IndexType } cs := strings.Split(indexdef, "(") colNames = strings.Split(cs[1][0:len(cs[1])-1], ",") if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) { newIdxName := indexName[5+len(tableName) : len(indexName)] if newIdxName != "" { indexName = newIdxName } } index := &core.Index{Name: indexName, Type: indexType, Cols: make([]string, 0)} for _, colName := range colNames { index.Cols = append(index.Cols, strings.Trim(colName, `" `)) } indexes[index.Name] = index } return indexes, nil } func (db *postgres) Filters() []core.Filter { return []core.Filter{&core.IdFilter{}, &core.QuoteFilter{}, &core.SeqFilter{"$", 1}} } ================================================ FILE: src/github.com/go-xorm/xorm/pq_driver.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "errors" "fmt" "net/url" "sort" "strings" "github.com/go-xorm/core" ) type pqDriver struct { } type values map[string]string func (vs values) Set(k, v string) { vs[k] = v } func (vs values) Get(k string) (v string) { return vs[k] } func errorf(s string, args ...interface{}) { panic(fmt.Errorf("pq: %s", fmt.Sprintf(s, args...))) } func parseURL(connstr string) (string, error) { u, err := url.Parse(connstr) if err != nil { return "", err } if u.Scheme != "postgresql" && u.Scheme != "postgres" { return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme) } var kvs []string escaper := strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`) accrue := func(k, v string) { if v != "" { kvs = append(kvs, k+"="+escaper.Replace(v)) } } if u.User != nil { v := u.User.Username() accrue("user", v) v, _ = u.User.Password() accrue("password", v) } i := strings.Index(u.Host, ":") if i < 0 { accrue("host", u.Host) } else { accrue("host", u.Host[:i]) accrue("port", u.Host[i+1:]) } if u.Path != "" { accrue("dbname", u.Path[1:]) } q := u.Query() for k := range q { accrue(k, q.Get(k)) } sort.Strings(kvs) // Makes testing easier (not a performance concern) return strings.Join(kvs, " "), nil } func parseOpts(name string, o values) { if len(name) == 0 { return } name = strings.TrimSpace(name) ps := strings.Split(name, " ") for _, p := range ps { kv := strings.Split(p, "=") if len(kv) < 2 { errorf("invalid option: %q", p) } o.Set(kv[0], kv[1]) } } func (p *pqDriver) Parse(driverName, dataSourceName string) (*core.Uri, error) { db := &core.Uri{DbType: core.POSTGRES} o := make(values) var err error if strings.HasPrefix(dataSourceName, "postgresql://") || strings.HasPrefix(dataSourceName, "postgres://") { dataSourceName, err = parseURL(dataSourceName) if err != nil { return nil, err } } parseOpts(dataSourceName, o) db.DbName = o.Get("dbname") if db.DbName == "" { return nil, errors.New("dbname is empty") } /*db.Schema = o.Get("schema") if len(db.Schema) == 0 { db.Schema = "public" }*/ return db, nil } ================================================ FILE: src/github.com/go-xorm/xorm/processors.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm // Executed before an object is initially persisted to the database type BeforeInsertProcessor interface { BeforeInsert() } // Executed before an object is updated type BeforeUpdateProcessor interface { BeforeUpdate() } // Executed before an object is deleted type BeforeDeleteProcessor interface { BeforeDelete() } type BeforeSetProcessor interface { BeforeSet(string, Cell) } type AfterSetProcessor interface { AfterSet(string, Cell) } // !nashtsai! TODO enable BeforeValidateProcessor when xorm start to support validations //// Executed before an object is validated //type BeforeValidateProcessor interface { // BeforeValidate() //} // -- // Executed after an object is persisted to the database type AfterInsertProcessor interface { AfterInsert() } // Executed after an object has been updated type AfterUpdateProcessor interface { AfterUpdate() } // Executed after an object has been deleted type AfterDeleteProcessor interface { AfterDelete() } ================================================ FILE: src/github.com/go-xorm/xorm/rows.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "database/sql" "fmt" "reflect" "github.com/go-xorm/core" ) // Rows rows wrapper a rows to type Rows struct { NoTypeCheck bool session *Session stmt *core.Stmt rows *core.Rows fields []string fieldsCount int beanType reflect.Type lastError error } func newRows(session *Session, bean interface{}) (*Rows, error) { rows := new(Rows) rows.session = session rows.beanType = reflect.Indirect(reflect.ValueOf(bean)).Type() defer rows.session.resetStatement() var sqlStr string var args []interface{} rows.session.Statement.setRefValue(rValue(bean)) if len(session.Statement.TableName()) <= 0 { return nil, ErrTableNotFound } if rows.session.Statement.RawSQL == "" { sqlStr, args = rows.session.Statement.genGetSql(bean) } else { sqlStr = rows.session.Statement.RawSQL args = rows.session.Statement.RawParams } for _, filter := range rows.session.Engine.dialect.Filters() { sqlStr = filter.Do(sqlStr, session.Engine.dialect, rows.session.Statement.RefTable) } rows.session.saveLastSQL(sqlStr, args) var err error if rows.session.prepareStmt { rows.stmt, err = rows.session.DB().Prepare(sqlStr) if err != nil { rows.lastError = err rows.Close() return nil, err } rows.rows, err = rows.stmt.Query(args...) if err != nil { rows.lastError = err rows.Close() return nil, err } } else { rows.rows, err = rows.session.DB().Query(sqlStr, args...) if err != nil { rows.lastError = err rows.Close() return nil, err } } rows.fields, err = rows.rows.Columns() if err != nil { rows.lastError = err rows.Close() return nil, err } rows.fieldsCount = len(rows.fields) return rows, nil } // Next move cursor to next record, return false if end has reached func (rows *Rows) Next() bool { if rows.lastError == nil && rows.rows != nil { hasNext := rows.rows.Next() if !hasNext { rows.lastError = sql.ErrNoRows } return hasNext } return false } // Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Close. func (rows *Rows) Err() error { return rows.lastError } // Scan row record to bean properties func (rows *Rows) Scan(bean interface{}) error { if rows.lastError != nil { return rows.lastError } if !rows.NoTypeCheck && reflect.Indirect(reflect.ValueOf(bean)).Type() != rows.beanType { return fmt.Errorf("scan arg is incompatible type to [%v]", rows.beanType) } return rows.session.row2Bean(rows.rows, rows.fields, rows.fieldsCount, bean) } // Close session if session.IsAutoClose is true, and claimed any opened resources func (rows *Rows) Close() error { if rows.session.IsAutoClose { defer rows.session.Close() } if rows.lastError == nil { if rows.rows != nil { rows.lastError = rows.rows.Close() if rows.lastError != nil { defer rows.stmt.Close() return rows.lastError } } if rows.stmt != nil { rows.lastError = rows.stmt.Close() } } else { if rows.stmt != nil { defer rows.stmt.Close() } if rows.rows != nil { defer rows.rows.Close() } } return rows.lastError } ================================================ FILE: src/github.com/go-xorm/xorm/session.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "database/sql" "database/sql/driver" "encoding/json" "errors" "fmt" "hash/crc32" "reflect" "strconv" "strings" "time" "github.com/go-xorm/core" ) // Session keep a pointer to sql.DB and provides all execution of all // kind of database operations. type Session struct { db *core.DB Engine *Engine Tx *core.Tx Statement Statement IsAutoCommit bool IsCommitedOrRollbacked bool TransType string IsAutoClose bool // Automatically reset the statement after operations that execute a SQL // query such as Count(), Find(), Get(), ... AutoResetStatement bool // !nashtsai! storing these beans due to yet committed tx afterInsertBeans map[interface{}]*[]func(interface{}) afterUpdateBeans map[interface{}]*[]func(interface{}) afterDeleteBeans map[interface{}]*[]func(interface{}) // -- beforeClosures []func(interface{}) afterClosures []func(interface{}) prepareStmt bool stmtCache map[uint32]*core.Stmt //key: hash.Hash32 of (queryStr, len(queryStr)) cascadeDeep int // !evalphobia! stored the last executed query on this session //beforeSQLExec func(string, ...interface{}) lastSQL string lastSQLArgs []interface{} } // Clone copy all the session's content and return a new session func (session *Session) Clone() *Session { var sess = *session return &sess } // Init reset the session as the init status. func (session *Session) Init() { session.Statement.Init() session.Statement.Engine = session.Engine session.IsAutoCommit = true session.IsCommitedOrRollbacked = false session.IsAutoClose = false session.AutoResetStatement = true session.prepareStmt = false // !nashtsai! is lazy init better? session.afterInsertBeans = make(map[interface{}]*[]func(interface{}), 0) session.afterUpdateBeans = make(map[interface{}]*[]func(interface{}), 0) session.afterDeleteBeans = make(map[interface{}]*[]func(interface{}), 0) session.beforeClosures = make([]func(interface{}), 0) session.afterClosures = make([]func(interface{}), 0) session.lastSQL = "" session.lastSQLArgs = []interface{}{} } // Close release the connection from pool func (session *Session) Close() { for _, v := range session.stmtCache { v.Close() } if session.db != nil { // When Close be called, if session is a transaction and do not call // Commit or Rollback, then call Rollback. if session.Tx != nil && !session.IsCommitedOrRollbacked { session.Rollback() } session.Tx = nil session.stmtCache = nil session.Init() session.db = nil } } func (session *Session) resetStatement() { if session.AutoResetStatement { session.Statement.Init() } } // Prepare set a flag to session that should be prepare statment before execute query func (session *Session) Prepare() *Session { session.prepareStmt = true return session } // Sql will be deprecated, please use SQL instead. func (session *Session) Sql(querystring string, args ...interface{}) *Session { session.Statement.Sql(querystring, args...) return session } // SQL provides raw sql input parameter. When you have a complex SQL statement // and cannot use Where, Id, In and etc. Methods to describe, you can use SQL. func (session *Session) SQL(querystring string, args ...interface{}) *Session { session.Statement.Sql(querystring, args...) return session } // Where provides custom query condition. func (session *Session) Where(querystring string, args ...interface{}) *Session { session.Statement.Where(querystring, args...) return session } // And provides custom query condition. func (session *Session) And(querystring string, args ...interface{}) *Session { session.Statement.And(querystring, args...) return session } // Or provides custom query condition. func (session *Session) Or(querystring string, args ...interface{}) *Session { session.Statement.Or(querystring, args...) return session } // Id will be deprecated, please use ID instead func (session *Session) Id(id interface{}) *Session { session.Statement.Id(id) return session } // ID provides converting id as a query condition func (session *Session) ID(id interface{}) *Session { session.Statement.Id(id) return session } // Before Apply before Processor, affected bean is passed to closure arg func (session *Session) Before(closures func(interface{})) *Session { if closures != nil { session.beforeClosures = append(session.beforeClosures, closures) } return session } // After Apply after Processor, affected bean is passed to closure arg func (session *Session) After(closures func(interface{})) *Session { if closures != nil { session.afterClosures = append(session.afterClosures, closures) } return session } // Table can input a string or pointer to struct for special a table to operate. func (session *Session) Table(tableNameOrBean interface{}) *Session { session.Statement.Table(tableNameOrBean) return session } // Alias set the table alias func (session *Session) Alias(alias string) *Session { session.Statement.Alias(alias) return session } // In provides a query string like "id in (1, 2, 3)" func (session *Session) In(column string, args ...interface{}) *Session { session.Statement.In(column, args...) return session } // Incr provides a query string like "count = count + 1" func (session *Session) Incr(column string, arg ...interface{}) *Session { session.Statement.Incr(column, arg...) return session } // Decr provides a query string like "count = count - 1" func (session *Session) Decr(column string, arg ...interface{}) *Session { session.Statement.Decr(column, arg...) return session } // SetExpr provides a query string like "column = {expression}" func (session *Session) SetExpr(column string, expression string) *Session { session.Statement.SetExpr(column, expression) return session } // Select provides some columns to special func (session *Session) Select(str string) *Session { session.Statement.Select(str) return session } // Cols provides some columns to special func (session *Session) Cols(columns ...string) *Session { session.Statement.Cols(columns...) return session } // AllCols ask all columns func (session *Session) AllCols() *Session { session.Statement.AllCols() return session } // MustCols specify some columns must use even if they are empty func (session *Session) MustCols(columns ...string) *Session { session.Statement.MustCols(columns...) return session } // NoCascade indicate that no cascade load child object func (session *Session) NoCascade() *Session { session.Statement.UseCascade = false return session } // UseBool automatically retrieve condition according struct, but // if struct has bool field, it will ignore them. So use UseBool // to tell system to do not ignore them. // If no paramters, it will use all the bool field of struct, or // it will use paramters's columns func (session *Session) UseBool(columns ...string) *Session { session.Statement.UseBool(columns...) return session } // Distinct use for distinct columns. Caution: when you are using cache, // distinct will not be cached because cache system need id, // but distinct will not provide id func (session *Session) Distinct(columns ...string) *Session { session.Statement.Distinct(columns...) return session } // ForUpdate Set Read/Write locking for UPDATE func (session *Session) ForUpdate() *Session { session.Statement.IsForUpdate = true return session } // Omit Only not use the paramters as select or update columns func (session *Session) Omit(columns ...string) *Session { session.Statement.Omit(columns...) return session } // Nullable Set null when column is zero-value and nullable for update func (session *Session) Nullable(columns ...string) *Session { session.Statement.Nullable(columns...) return session } // NoAutoTime means do not automatically give created field and updated field // the current time on the current session temporarily func (session *Session) NoAutoTime() *Session { session.Statement.UseAutoTime = false return session } // NoAutoCondition disable generate SQL condition from beans func (session *Session) NoAutoCondition(no ...bool) *Session { session.Statement.NoAutoCondition(no...) return session } // Limit provide limit and offset query condition func (session *Session) Limit(limit int, start ...int) *Session { session.Statement.Limit(limit, start...) return session } // OrderBy provide order by query condition, the input parameter is the content // after order by on a sql statement. func (session *Session) OrderBy(order string) *Session { session.Statement.OrderBy(order) return session } // Desc provide desc order by query condition, the input parameters are columns. func (session *Session) Desc(colNames ...string) *Session { session.Statement.Desc(colNames...) return session } // Asc provide asc order by query condition, the input parameters are columns. func (session *Session) Asc(colNames ...string) *Session { session.Statement.Asc(colNames...) return session } // StoreEngine is only avialble mysql dialect currently func (session *Session) StoreEngine(storeEngine string) *Session { session.Statement.StoreEngine = storeEngine return session } // Charset is only avialble mysql dialect currently func (session *Session) Charset(charset string) *Session { session.Statement.Charset = charset return session } // Cascade indicates if loading sub Struct func (session *Session) Cascade(trueOrFalse ...bool) *Session { if len(trueOrFalse) >= 1 { session.Statement.UseCascade = trueOrFalse[0] } return session } // NoCache ask this session do not retrieve data from cache system and // get data from database directly. func (session *Session) NoCache() *Session { session.Statement.UseCache = false return session } // Join join_operator should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN func (session *Session) Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *Session { session.Statement.Join(joinOperator, tablename, condition, args...) return session } // GroupBy Generate Group By statement func (session *Session) GroupBy(keys string) *Session { session.Statement.GroupBy(keys) return session } // Having Generate Having statement func (session *Session) Having(conditions string) *Session { session.Statement.Having(conditions) return session } // DB db return the wrapper of sql.DB func (session *Session) DB() *core.DB { if session.db == nil { session.db = session.Engine.db session.stmtCache = make(map[uint32]*core.Stmt, 0) } return session.db } // Begin a transaction func (session *Session) Begin() error { if session.IsAutoCommit { tx, err := session.DB().Begin() if err != nil { return err } session.IsAutoCommit = false session.IsCommitedOrRollbacked = false session.Tx = tx session.saveLastSQL("BEGIN TRANSACTION") } return nil } // Rollback When using transaction, you can rollback if any error func (session *Session) Rollback() error { if !session.IsAutoCommit && !session.IsCommitedOrRollbacked { session.saveLastSQL(session.Engine.dialect.RollBackStr()) session.IsCommitedOrRollbacked = true return session.Tx.Rollback() } return nil } // Commit When using transaction, Commit will commit all operations. func (session *Session) Commit() error { if !session.IsAutoCommit && !session.IsCommitedOrRollbacked { session.saveLastSQL("COMMIT") session.IsCommitedOrRollbacked = true var err error if err = session.Tx.Commit(); err == nil { // handle processors after tx committed closureCallFunc := func(closuresPtr *[]func(interface{}), bean interface{}) { if closuresPtr != nil { for _, closure := range *closuresPtr { closure(bean) } } } for bean, closuresPtr := range session.afterInsertBeans { closureCallFunc(closuresPtr, bean) if processor, ok := interface{}(bean).(AfterInsertProcessor); ok { processor.AfterInsert() } } for bean, closuresPtr := range session.afterUpdateBeans { closureCallFunc(closuresPtr, bean) if processor, ok := interface{}(bean).(AfterUpdateProcessor); ok { processor.AfterUpdate() } } for bean, closuresPtr := range session.afterDeleteBeans { closureCallFunc(closuresPtr, bean) if processor, ok := interface{}(bean).(AfterDeleteProcessor); ok { processor.AfterDelete() } } cleanUpFunc := func(slices *map[interface{}]*[]func(interface{})) { if len(*slices) > 0 { *slices = make(map[interface{}]*[]func(interface{}), 0) } } cleanUpFunc(&session.afterInsertBeans) cleanUpFunc(&session.afterUpdateBeans) cleanUpFunc(&session.afterDeleteBeans) } return err } return nil } func cleanupProcessorsClosures(slices *[]func(interface{})) { if len(*slices) > 0 { *slices = make([]func(interface{}), 0) } } func (session *Session) scanMapIntoStruct(obj interface{}, objMap map[string][]byte) error { dataStruct := rValue(obj) if dataStruct.Kind() != reflect.Struct { return errors.New("Expected a pointer to a struct") } var col *core.Column session.Statement.setRefValue(dataStruct) table := session.Statement.RefTable tableName := session.Statement.tableName for key, data := range objMap { if col = table.GetColumn(key); col == nil { session.Engine.logger.Warnf("struct %v's has not field %v. %v", table.Type.Name(), key, table.ColumnsSeq()) continue } fieldName := col.FieldName fieldPath := strings.Split(fieldName, ".") var fieldValue reflect.Value if len(fieldPath) > 2 { session.Engine.logger.Error("Unsupported mutliderive", fieldName) continue } else if len(fieldPath) == 2 { parentField := dataStruct.FieldByName(fieldPath[0]) if parentField.IsValid() { fieldValue = parentField.FieldByName(fieldPath[1]) } } else { fieldValue = dataStruct.FieldByName(fieldName) } if !fieldValue.IsValid() || !fieldValue.CanSet() { session.Engine.logger.Warnf("table %v's column %v is not valid or cannot set", tableName, key) continue } err := session.bytes2Value(col, &fieldValue, data) if err != nil { return err } } return nil } // Execute sql func (session *Session) innerExec(sqlStr string, args ...interface{}) (sql.Result, error) { if session.prepareStmt { stmt, err := session.doPrepare(sqlStr) if err != nil { return nil, err } res, err := stmt.Exec(args...) if err != nil { return nil, err } return res, nil } return session.DB().Exec(sqlStr, args...) } func (session *Session) exec(sqlStr string, args ...interface{}) (sql.Result, error) { for _, filter := range session.Engine.dialect.Filters() { // TODO: for table name, it's no need to RefTable sqlStr = filter.Do(sqlStr, session.Engine.dialect, session.Statement.RefTable) } session.saveLastSQL(sqlStr, args...) return session.Engine.logSQLExecutionTime(sqlStr, args, func() (sql.Result, error) { if session.IsAutoCommit { // FIXME: oci8 can not auto commit (github.com/mattn/go-oci8) if session.Engine.dialect.DBType() == core.ORACLE { session.Begin() r, err := session.Tx.Exec(sqlStr, args...) session.Commit() return r, err } return session.innerExec(sqlStr, args...) } return session.Tx.Exec(sqlStr, args...) }) } // Exec raw sql func (session *Session) Exec(sqlStr string, args ...interface{}) (sql.Result, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } return session.exec(sqlStr, args...) } // CreateTable create a table according a bean func (session *Session) CreateTable(bean interface{}) error { v := rValue(bean) session.Statement.setRefValue(v) defer session.resetStatement() if session.IsAutoClose { defer session.Close() } return session.createOneTable() } // CreateIndexes create indexes func (session *Session) CreateIndexes(bean interface{}) error { v := rValue(bean) session.Statement.setRefValue(v) defer session.resetStatement() if session.IsAutoClose { defer session.Close() } sqls := session.Statement.genIndexSQL() for _, sqlStr := range sqls { _, err := session.exec(sqlStr) if err != nil { return err } } return nil } // CreateUniques create uniques func (session *Session) CreateUniques(bean interface{}) error { v := rValue(bean) session.Statement.setRefValue(v) defer session.resetStatement() if session.IsAutoClose { defer session.Close() } sqls := session.Statement.genUniqueSQL() for _, sqlStr := range sqls { _, err := session.exec(sqlStr) if err != nil { return err } } return nil } func (session *Session) createOneTable() error { sqlStr := session.Statement.genCreateTableSQL() _, err := session.exec(sqlStr) return err } // to be deleted func (session *Session) createAll() error { if session.IsAutoClose { defer session.Close() } for _, table := range session.Engine.Tables { session.Statement.RefTable = table session.Statement.tableName = table.Name err := session.createOneTable() session.resetStatement() if err != nil { return err } } return nil } // DropIndexes drop indexes func (session *Session) DropIndexes(bean interface{}) error { v := rValue(bean) session.Statement.setRefValue(v) defer session.resetStatement() if session.IsAutoClose { defer session.Close() } sqls := session.Statement.genDelIndexSQL() for _, sqlStr := range sqls { _, err := session.exec(sqlStr) if err != nil { return err } } return nil } // DropTable drop table will drop table if exist, if drop failed, it will return error func (session *Session) DropTable(beanOrTableName interface{}) error { tableName, err := session.Engine.tableName(beanOrTableName) if err != nil { return err } var needDrop = true if !session.Engine.dialect.SupportDropIfExists() { sqlStr, args := session.Engine.dialect.TableCheckSql(tableName) results, err := session.query(sqlStr, args...) if err != nil { return err } needDrop = len(results) > 0 } if needDrop { sqlStr := session.Engine.Dialect().DropTableSql(tableName) _, err = session.exec(sqlStr) return err } return nil } func (session *Session) canCache() bool { if session.Statement.RefTable == nil || session.Statement.JoinStr != "" || session.Statement.RawSQL != "" || session.Tx != nil || len(session.Statement.selectStr) > 0 { return false } return true } func (session *Session) cacheGet(bean interface{}, sqlStr string, args ...interface{}) (has bool, err error) { // if has no reftable, then don't use cache currently if !session.canCache() { return false, ErrCacheFailed } for _, filter := range session.Engine.dialect.Filters() { sqlStr = filter.Do(sqlStr, session.Engine.dialect, session.Statement.RefTable) } newsql := session.Statement.convertIdSql(sqlStr) if newsql == "" { return false, ErrCacheFailed } cacher := session.Engine.getCacher2(session.Statement.RefTable) tableName := session.Statement.TableName() session.Engine.logger.Debug("[cacheGet] find sql:", newsql, args) ids, err := core.GetCacheSql(cacher, tableName, newsql, args) table := session.Statement.RefTable if err != nil { var res = make([]string, len(table.PrimaryKeys)) rows, err := session.DB().Query(newsql, args...) if err != nil { return false, err } defer rows.Close() if rows.Next() { err = rows.ScanSlice(&res) if err != nil { return false, err } } else { return false, ErrCacheFailed } var pk core.PK = make([]interface{}, len(table.PrimaryKeys)) for i, col := range table.PKColumns() { if col.SQLType.IsText() { pk[i] = res[i] } else if col.SQLType.IsNumeric() { n, err := strconv.ParseInt(res[i], 10, 64) if err != nil { return false, err } pk[i] = n } else { return false, errors.New("unsupported") } } ids = []core.PK{pk} session.Engine.logger.Debug("[cacheGet] cache ids:", newsql, ids) err = core.PutCacheSql(cacher, ids, tableName, newsql, args) if err != nil { return false, err } } else { session.Engine.logger.Debug("[cacheGet] cache hit sql:", newsql) } if len(ids) > 0 { structValue := reflect.Indirect(reflect.ValueOf(bean)) id := ids[0] session.Engine.logger.Debug("[cacheGet] get bean:", tableName, id) sid, err := id.ToString() if err != nil { return false, err } cacheBean := cacher.GetBean(tableName, sid) if cacheBean == nil { newSession := session.Engine.NewSession() defer newSession.Close() cacheBean = reflect.New(structValue.Type()).Interface() newSession.Id(id).NoCache() if session.Statement.AltTableName != "" { newSession.Table(session.Statement.AltTableName) } if !session.Statement.UseCascade { newSession.NoCascade() } has, err = newSession.Get(cacheBean) if err != nil || !has { return has, err } session.Engine.logger.Debug("[cacheGet] cache bean:", tableName, id, cacheBean) cacher.PutBean(tableName, sid, cacheBean) } else { session.Engine.logger.Debug("[cacheGet] cache hit bean:", tableName, id, cacheBean) has = true } structValue.Set(reflect.Indirect(reflect.ValueOf(cacheBean))) return has, nil } return false, nil } func (session *Session) cacheFind(t reflect.Type, sqlStr string, rowsSlicePtr interface{}, args ...interface{}) (err error) { if !session.canCache() || indexNoCase(sqlStr, "having") != -1 || indexNoCase(sqlStr, "group by") != -1 { return ErrCacheFailed } for _, filter := range session.Engine.dialect.Filters() { sqlStr = filter.Do(sqlStr, session.Engine.dialect, session.Statement.RefTable) } newsql := session.Statement.convertIdSql(sqlStr) if newsql == "" { return ErrCacheFailed } tableName := session.Statement.TableName() table := session.Statement.RefTable cacher := session.Engine.getCacher2(table) ids, err := core.GetCacheSql(cacher, tableName, newsql, args) if err != nil { rows, err := session.DB().Query(newsql, args...) if err != nil { return err } defer rows.Close() var i int ids = make([]core.PK, 0) for rows.Next() { i++ if i > 500 { session.Engine.logger.Debug("[cacheFind] ids length > 500, no cache") return ErrCacheFailed } var res = make([]string, len(table.PrimaryKeys)) err = rows.ScanSlice(&res) if err != nil { return err } var pk core.PK = make([]interface{}, len(table.PrimaryKeys)) for i, col := range table.PKColumns() { if col.SQLType.IsNumeric() { n, err := strconv.ParseInt(res[i], 10, 64) if err != nil { return err } pk[i] = n } else if col.SQLType.IsText() { pk[i] = res[i] } else { return errors.New("not supported") } } ids = append(ids, pk) } session.Engine.logger.Debug("[cacheFind] cache sql:", ids, tableName, newsql, args) err = core.PutCacheSql(cacher, ids, tableName, newsql, args) if err != nil { return err } } else { session.Engine.logger.Debug("[cacheFind] cache hit sql:", newsql, args) } sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr)) ididxes := make(map[string]int) var ides []core.PK var temps = make([]interface{}, len(ids)) for idx, id := range ids { sid, err := id.ToString() if err != nil { return err } bean := cacher.GetBean(tableName, sid) if bean == nil { ides = append(ides, id) ididxes[sid] = idx } else { session.Engine.logger.Debug("[cacheFind] cache hit bean:", tableName, id, bean) pk := session.Engine.IdOf(bean) xid, err := pk.ToString() if err != nil { return err } if sid != xid { session.Engine.logger.Error("[cacheFind] error cache", xid, sid, bean) return ErrCacheFailed } temps[idx] = bean } } if len(ides) > 0 { newSession := session.Engine.NewSession() defer newSession.Close() slices := reflect.New(reflect.SliceOf(t)) beans := slices.Interface() if len(table.PrimaryKeys) == 1 { ff := make([]interface{}, 0, len(ides)) for _, ie := range ides { ff = append(ff, ie[0]) } newSession.In(table.PrimaryKeys[0], ff...) } else { var kn = make([]string, 0) for _, name := range table.PrimaryKeys { kn = append(kn, name+" = ?") } condi := "(" + strings.Join(kn, " AND ") + ")" for _, ie := range ides { newSession.Or(condi, ie...) } } err = newSession.NoCache().Find(beans) if err != nil { return err } vs := reflect.Indirect(reflect.ValueOf(beans)) for i := 0; i < vs.Len(); i++ { rv := vs.Index(i) if rv.Kind() != reflect.Ptr { rv = rv.Addr() } bean := rv.Interface() id := session.Engine.IdOf(bean) sid, err := id.ToString() if err != nil { return err } temps[ididxes[sid]] = bean session.Engine.logger.Debug("[cacheFind] cache bean:", tableName, id, bean, temps) cacher.PutBean(tableName, sid, bean) } } for j := 0; j < len(temps); j++ { bean := temps[j] if bean == nil { session.Engine.logger.Warn("[cacheFind] cache no hit:", tableName, ids[j], temps) // return errors.New("cache error") // !nashtsai! no need to return error, but continue instead continue } if sliceValue.Kind() == reflect.Slice { if t.Kind() == reflect.Ptr { sliceValue.Set(reflect.Append(sliceValue, reflect.ValueOf(bean))) } else { sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(bean)))) } } else if sliceValue.Kind() == reflect.Map { var key = ids[j] keyType := sliceValue.Type().Key() var ikey interface{} if len(key) == 1 { ikey, err = str2PK(fmt.Sprintf("%v", key[0]), keyType) if err != nil { return err } } else { if keyType.Kind() != reflect.Slice { return errors.New("table have multiple primary keys, key is not core.PK or slice") } ikey = key } if t.Kind() == reflect.Ptr { sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.ValueOf(bean)) } else { sliceValue.SetMapIndex(reflect.ValueOf(ikey), reflect.Indirect(reflect.ValueOf(bean))) } } } return nil } // IterFunc only use by Iterate type IterFunc func(idx int, bean interface{}) error // Rows return sql.Rows compatible Rows obj, as a forward Iterator object for iterating record by record, bean's non-empty fields // are conditions. func (session *Session) Rows(bean interface{}) (*Rows, error) { return newRows(session, bean) } // Iterate record by record handle records from table, condiBeans's non-empty fields // are conditions. beans could be []Struct, []*Struct, map[int64]Struct // map[int64]*Struct func (session *Session) Iterate(bean interface{}, fun IterFunc) error { rows, err := session.Rows(bean) if err != nil { return err } defer rows.Close() //b := reflect.New(iterator.beanType).Interface() i := 0 for rows.Next() { b := reflect.New(rows.beanType).Interface() err = rows.Scan(b) if err != nil { return err } err = fun(i, b) if err != nil { return err } i++ } return err } func (session *Session) doPrepare(sqlStr string) (stmt *core.Stmt, err error) { crc := crc32.ChecksumIEEE([]byte(sqlStr)) // TODO try hash(sqlStr+len(sqlStr)) var has bool stmt, has = session.stmtCache[crc] if !has { stmt, err = session.DB().Prepare(sqlStr) if err != nil { return nil, err } session.stmtCache[crc] = stmt } return } // Get retrieve one record from database, bean's non-empty fields // will be as conditions func (session *Session) Get(bean interface{}) (bool, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } session.Statement.setRefValue(rValue(bean)) var sqlStr string var args []interface{} if session.Statement.RawSQL == "" { if len(session.Statement.TableName()) <= 0 { return false, ErrTableNotFound } session.Statement.Limit(1) sqlStr, args = session.Statement.genGetSql(bean) } else { sqlStr = session.Statement.RawSQL args = session.Statement.RawParams } if session.Statement.JoinStr == "" { if cacher := session.Engine.getCacher2(session.Statement.RefTable); cacher != nil && session.Statement.UseCache && !session.Statement.unscoped { has, err := session.cacheGet(bean, sqlStr, args...) if err != ErrCacheFailed { return has, err } } } var rawRows *core.Rows var err error session.queryPreprocess(&sqlStr, args...) if session.IsAutoCommit { _, rawRows, err = session.innerQuery(sqlStr, args...) } else { rawRows, err = session.Tx.Query(sqlStr, args...) } if err != nil { return false, err } defer rawRows.Close() if rawRows.Next() { if fields, err := rawRows.Columns(); err == nil { err = session.row2Bean(rawRows, fields, len(fields), bean) } return true, err } return false, nil } // Count counts the records. bean's non-empty fields // are conditions. func (session *Session) Count(bean interface{}) (int64, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } var sqlStr string var args []interface{} if session.Statement.RawSQL == "" { sqlStr, args = session.Statement.genCountSql(bean) } else { sqlStr = session.Statement.RawSQL args = session.Statement.RawParams } session.queryPreprocess(&sqlStr, args...) var err error var total int64 if session.IsAutoCommit { err = session.DB().QueryRow(sqlStr, args...).Scan(&total) } else { err = session.Tx.QueryRow(sqlStr, args...).Scan(&total) } if err != nil { return 0, err } return total, nil } // Sum call sum some column. bean's non-empty fields are conditions. func (session *Session) Sum(bean interface{}, columnName string) (float64, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } var sqlStr string var args []interface{} if len(session.Statement.RawSQL) == 0 { sqlStr, args = session.Statement.genSumSql(bean, columnName) } else { sqlStr = session.Statement.RawSQL args = session.Statement.RawParams } session.queryPreprocess(&sqlStr, args...) var err error var res float64 if session.IsAutoCommit { err = session.DB().QueryRow(sqlStr, args...).Scan(&res) } else { err = session.Tx.QueryRow(sqlStr, args...).Scan(&res) } if err != nil { return 0, err } return res, nil } // Sums call sum some columns. bean's non-empty fields are conditions. func (session *Session) Sums(bean interface{}, columnNames ...string) ([]float64, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } var sqlStr string var args []interface{} if len(session.Statement.RawSQL) == 0 { sqlStr, args = session.Statement.genSumSql(bean, columnNames...) } else { sqlStr = session.Statement.RawSQL args = session.Statement.RawParams } session.queryPreprocess(&sqlStr, args...) var err error var res = make([]float64, len(columnNames), len(columnNames)) if session.IsAutoCommit { err = session.DB().QueryRow(sqlStr, args...).ScanSlice(&res) } else { err = session.Tx.QueryRow(sqlStr, args...).ScanSlice(&res) } if err != nil { return nil, err } return res, nil } // SumsInt sum specify columns and return as []int64 instead of []float64 func (session *Session) SumsInt(bean interface{}, columnNames ...string) ([]int64, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } var sqlStr string var args []interface{} if len(session.Statement.RawSQL) == 0 { sqlStr, args = session.Statement.genSumSql(bean, columnNames...) } else { sqlStr = session.Statement.RawSQL args = session.Statement.RawParams } session.queryPreprocess(&sqlStr, args...) var err error var res = make([]int64, 0, len(columnNames)) if session.IsAutoCommit { err = session.DB().QueryRow(sqlStr, args...).ScanSlice(&res) } else { err = session.Tx.QueryRow(sqlStr, args...).ScanSlice(&res) } if err != nil { return nil, err } return res, nil } // Find retrieve records from table, condiBeans's non-empty fields // are conditions. beans could be []Struct, []*Struct, map[int64]Struct // map[int64]*Struct func (session *Session) Find(rowsSlicePtr interface{}, condiBean ...interface{}) error { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr)) if sliceValue.Kind() != reflect.Slice && sliceValue.Kind() != reflect.Map { return errors.New("needs a pointer to a slice or a map") } sliceElementType := sliceValue.Type().Elem() if session.Statement.RefTable == nil { if sliceElementType.Kind() == reflect.Ptr { if sliceElementType.Elem().Kind() == reflect.Struct { pv := reflect.New(sliceElementType.Elem()) session.Statement.setRefValue(pv.Elem()) } else { return errors.New("slice type") } } else if sliceElementType.Kind() == reflect.Struct { pv := reflect.New(sliceElementType) session.Statement.setRefValue(pv.Elem()) } else { return errors.New("slice type") } } var table = session.Statement.RefTable var addedTableName = (len(session.Statement.JoinStr) > 0) if !session.Statement.noAutoCondition && len(condiBean) > 0 { colNames, args := session.Statement.buildConditions(table, condiBean[0], true, true, false, true, addedTableName) session.Statement.ConditionStr = strings.Join(colNames, " AND ") session.Statement.BeanArgs = args } else { // !oinume! Add " IS NULL" to WHERE whatever condiBean is given. // See https://github.com/go-xorm/xorm/issues/179 if col := table.DeletedColumn(); col != nil && !session.Statement.unscoped { // tag "deleted" is enabled var colName = session.Engine.Quote(col.Name) if addedTableName { var nm = session.Statement.TableName() if len(session.Statement.TableAlias) > 0 { nm = session.Statement.TableAlias } colName = session.Engine.Quote(nm) + "." + colName } session.Statement.ConditionStr = fmt.Sprintf("(%v IS NULL OR %v = '0001-01-01 00:00:00')", colName, colName) } } var sqlStr string var args []interface{} if session.Statement.RawSQL == "" { if len(session.Statement.TableName()) <= 0 { return ErrTableNotFound } var columnStr = session.Statement.ColumnStr if len(session.Statement.selectStr) > 0 { columnStr = session.Statement.selectStr } else { if session.Statement.JoinStr == "" { if columnStr == "" { if session.Statement.GroupByStr != "" { columnStr = session.Statement.Engine.Quote(strings.Replace(session.Statement.GroupByStr, ",", session.Engine.Quote(","), -1)) } else { columnStr = session.Statement.genColumnStr() } } } else { if columnStr == "" { if session.Statement.GroupByStr != "" { columnStr = session.Statement.Engine.Quote(strings.Replace(session.Statement.GroupByStr, ",", session.Engine.Quote(","), -1)) } else { columnStr = "*" } } } } session.Statement.Params = append(session.Statement.joinArgs, append(session.Statement.Params, session.Statement.BeanArgs...)...) session.Statement.attachInSql() sqlStr = session.Statement.genSelectSQL(columnStr) args = session.Statement.Params // for mssql and use limit qs := strings.Count(sqlStr, "?") if len(args)*2 == qs { args = append(args, args...) } } else { sqlStr = session.Statement.RawSQL args = session.Statement.RawParams } var err error if session.Statement.JoinStr == "" { if cacher := session.Engine.getCacher2(table); cacher != nil && session.Statement.UseCache && !session.Statement.IsDistinct && !session.Statement.unscoped { err = session.cacheFind(sliceElementType, sqlStr, rowsSlicePtr, args...) if err != ErrCacheFailed { return err } err = nil // !nashtsai! reset err to nil for ErrCacheFailed session.Engine.logger.Warn("Cache Find Failed") } } if sliceValue.Kind() != reflect.Map { var rawRows *core.Rows session.queryPreprocess(&sqlStr, args...) if session.IsAutoCommit { _, rawRows, err = session.innerQuery(sqlStr, args...) } else { rawRows, err = session.Tx.Query(sqlStr, args...) } if err != nil { return err } defer rawRows.Close() fields, err := rawRows.Columns() if err != nil { return err } var newElemFunc func() reflect.Value if sliceElementType.Kind() == reflect.Ptr { newElemFunc = func() reflect.Value { return reflect.New(sliceElementType.Elem()) } } else { newElemFunc = func() reflect.Value { return reflect.New(sliceElementType) } } var sliceValueSetFunc func(*reflect.Value) if sliceValue.Kind() == reflect.Slice { if sliceElementType.Kind() == reflect.Ptr { sliceValueSetFunc = func(newValue *reflect.Value) { sliceValue.Set(reflect.Append(sliceValue, reflect.ValueOf(newValue.Interface()))) } } else { sliceValueSetFunc = func(newValue *reflect.Value) { sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(newValue.Interface())))) } } } var newValue = newElemFunc() dataStruct := rValue(newValue.Interface()) if dataStruct.Kind() != reflect.Struct { return errors.New("Expected a pointer to a struct") } return session.rows2Beans(rawRows, fields, len(fields), session.Engine.autoMapType(dataStruct), newElemFunc, sliceValueSetFunc) } resultsSlice, err := session.query(sqlStr, args...) if err != nil { return err } keyType := sliceValue.Type().Key() for _, results := range resultsSlice { var newValue reflect.Value if sliceElementType.Kind() == reflect.Ptr { newValue = reflect.New(sliceElementType.Elem()) } else { newValue = reflect.New(sliceElementType) } err := session.scanMapIntoStruct(newValue.Interface(), results) if err != nil { return err } var key interface{} // if there is only one pk, we can put the id as map key. if len(table.PrimaryKeys) == 1 { key, err = str2PK(string(results[table.PrimaryKeys[0]]), keyType) if err != nil { return err } } else { if keyType.Kind() != reflect.Slice { panic("don't support multiple primary key's map has non-slice key type") } else { var keys core.PK = make([]interface{}, 0, len(table.PrimaryKeys)) for _, pk := range table.PrimaryKeys { skey, err := str2PK(string(results[pk]), keyType) if err != nil { return err } keys = append(keys, skey) } key = keys } } if sliceElementType.Kind() == reflect.Ptr { sliceValue.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(newValue.Interface())) } else { sliceValue.SetMapIndex(reflect.ValueOf(key), reflect.Indirect(reflect.ValueOf(newValue.Interface()))) } } return nil } // Ping test if database is ok func (session *Session) Ping() error { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } return session.DB().Ping() } // IsTableExist if a table is exist func (session *Session) IsTableExist(beanOrTableName interface{}) (bool, error) { tableName, err := session.Engine.tableName(beanOrTableName) if err != nil { return false, err } return session.isTableExist(tableName) } func (session *Session) isTableExist(tableName string) (bool, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } sqlStr, args := session.Engine.dialect.TableCheckSql(tableName) results, err := session.query(sqlStr, args...) return len(results) > 0, err } // IsTableEmpty if table have any records func (session *Session) IsTableEmpty(bean interface{}) (bool, error) { v := rValue(bean) t := v.Type() if t.Kind() == reflect.String { return session.isTableEmpty(bean.(string)) } else if t.Kind() == reflect.Struct { rows, err := session.Count(bean) return rows == 0, err } return false, errors.New("bean should be a struct or struct's point") } func (session *Session) isTableEmpty(tableName string) (bool, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } var total int64 sql := fmt.Sprintf("select count(*) from %s", session.Engine.Quote(tableName)) err := session.DB().QueryRow(sql).Scan(&total) session.saveLastSQL(sql) if err != nil { return true, err } return total == 0, nil } func (session *Session) isIndexExist(tableName, idxName string, unique bool) (bool, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } var idx string if unique { idx = uniqueName(tableName, idxName) } else { idx = indexName(tableName, idxName) } sqlStr, args := session.Engine.dialect.IndexCheckSql(tableName, idx) results, err := session.query(sqlStr, args...) return len(results) > 0, err } // find if index is exist according cols func (session *Session) isIndexExist2(tableName string, cols []string, unique bool) (bool, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } indexes, err := session.Engine.dialect.GetIndexes(tableName) if err != nil { return false, err } for _, index := range indexes { if sliceEq(index.Cols, cols) { if unique { return index.Type == core.UniqueType, nil } return index.Type == core.IndexType, nil } } return false, nil } func (session *Session) addColumn(colName string) error { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } col := session.Statement.RefTable.GetColumn(colName) sql, args := session.Statement.genAddColumnStr(col) _, err := session.exec(sql, args...) return err } func (session *Session) addIndex(tableName, idxName string) error { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } index := session.Statement.RefTable.Indexes[idxName] sqlStr := session.Engine.dialect.CreateIndexSql(tableName, index) _, err := session.exec(sqlStr) return err } func (session *Session) addUnique(tableName, uqeName string) error { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } index := session.Statement.RefTable.Indexes[uqeName] sqlStr := session.Engine.dialect.CreateIndexSql(tableName, index) _, err := session.exec(sqlStr) return err } // To be deleted func (session *Session) dropAll() error { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } for _, table := range session.Engine.Tables { session.Statement.Init() session.Statement.RefTable = table sqlStr := session.Engine.Dialect().DropTableSql(session.Statement.TableName()) _, err := session.exec(sqlStr) if err != nil { return err } } return nil } func (session *Session) getField(dataStruct *reflect.Value, key string, table *core.Table, idx int) *reflect.Value { var col *core.Column if col = table.GetColumnIdx(key, idx); col == nil { session.Engine.logger.Warnf("table %v has no column %v. %v", table.Name, key, table.ColumnsSeq()) return nil } fieldValue, err := col.ValueOfV(dataStruct) if err != nil { session.Engine.logger.Error(err) return nil } if !fieldValue.IsValid() || !fieldValue.CanSet() { session.Engine.logger.Warnf("table %v's column %v is not valid or cannot set", table.Name, key) return nil } return fieldValue } // Cell cell is a result of one column field type Cell *interface{} func (session *Session) rows2Beans(rows *core.Rows, fields []string, fieldsCount int, table *core.Table, newElemFunc func() reflect.Value, sliceValueSetFunc func(*reflect.Value)) error { for rows.Next() { var newValue = newElemFunc() bean := newValue.Interface() dataStruct := rValue(bean) err := session._row2Bean(rows, fields, fieldsCount, bean, &dataStruct, table) if err != nil { return err } sliceValueSetFunc(&newValue) } return nil } func (session *Session) row2Bean(rows *core.Rows, fields []string, fieldsCount int, bean interface{}) error { dataStruct := rValue(bean) if dataStruct.Kind() != reflect.Struct { return errors.New("Expected a pointer to a struct") } session.Statement.setRefValue(dataStruct) return session._row2Bean(rows, fields, fieldsCount, bean, &dataStruct, session.Statement.RefTable) } func (session *Session) _row2Bean(rows *core.Rows, fields []string, fieldsCount int, bean interface{}, dataStruct *reflect.Value, table *core.Table) error { scanResults := make([]interface{}, fieldsCount) for i := 0; i < len(fields); i++ { var cell interface{} scanResults[i] = &cell } if err := rows.Scan(scanResults...); err != nil { return err } if b, hasBeforeSet := bean.(BeforeSetProcessor); hasBeforeSet { for ii, key := range fields { b.BeforeSet(key, Cell(scanResults[ii].(*interface{}))) } } defer func() { if b, hasAfterSet := bean.(AfterSetProcessor); hasAfterSet { for ii, key := range fields { b.AfterSet(key, Cell(scanResults[ii].(*interface{}))) } } }() var tempMap = make(map[string]int) for ii, key := range fields { var idx int var ok bool var lKey = strings.ToLower(key) if idx, ok = tempMap[lKey]; !ok { idx = 0 } else { idx = idx + 1 } tempMap[lKey] = idx if fieldValue := session.getField(dataStruct, key, table, idx); fieldValue != nil { rawValue := reflect.Indirect(reflect.ValueOf(scanResults[ii])) // if row is null then ignore if rawValue.Interface() == nil { continue } if fieldValue.CanAddr() { if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok { if data, err := value2Bytes(&rawValue); err == nil { structConvert.FromDB(data) } else { session.Engine.logger.Error(err) } continue } } if _, ok := fieldValue.Interface().(core.Conversion); ok { if data, err := value2Bytes(&rawValue); err == nil { if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() { fieldValue.Set(reflect.New(fieldValue.Type().Elem())) } fieldValue.Interface().(core.Conversion).FromDB(data) } else { session.Engine.logger.Error(err) } continue } rawValueType := reflect.TypeOf(rawValue.Interface()) vv := reflect.ValueOf(rawValue.Interface()) fieldType := fieldValue.Type() hasAssigned := false col := table.GetColumnIdx(key, idx) if col.SQLType.IsJson() { var bs []byte if rawValueType.Kind() == reflect.String { bs = []byte(vv.String()) } else if rawValueType.ConvertibleTo(core.BytesType) { bs = vv.Bytes() } else { return fmt.Errorf("unsupported database data type: %s %v", key, rawValueType.Kind()) } hasAssigned = true if len(bs) > 0 { if fieldValue.CanAddr() { err := json.Unmarshal(bs, fieldValue.Addr().Interface()) if err != nil { session.Engine.logger.Error(key, err) return err } } else { x := reflect.New(fieldType) err := json.Unmarshal(bs, x.Interface()) if err != nil { session.Engine.logger.Error(key, err) return err } fieldValue.Set(x.Elem()) } } continue } switch fieldType.Kind() { case reflect.Complex64, reflect.Complex128: // TODO: reimplement this var bs []byte if rawValueType.Kind() == reflect.String { bs = []byte(vv.String()) } else if rawValueType.ConvertibleTo(core.BytesType) { bs = vv.Bytes() } hasAssigned = true if len(bs) > 0 { if fieldValue.CanAddr() { err := json.Unmarshal(bs, fieldValue.Addr().Interface()) if err != nil { session.Engine.logger.Error(err) return err } } else { x := reflect.New(fieldType) err := json.Unmarshal(bs, x.Interface()) if err != nil { session.Engine.logger.Error(err) return err } fieldValue.Set(x.Elem()) } } case reflect.Slice, reflect.Array: switch rawValueType.Kind() { case reflect.Slice, reflect.Array: switch rawValueType.Elem().Kind() { case reflect.Uint8: if fieldType.Elem().Kind() == reflect.Uint8 { hasAssigned = true fieldValue.Set(vv) } } } case reflect.String: if rawValueType.Kind() == reflect.String { hasAssigned = true fieldValue.SetString(vv.String()) } case reflect.Bool: if rawValueType.Kind() == reflect.Bool { hasAssigned = true fieldValue.SetBool(vv.Bool()) } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: switch rawValueType.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: hasAssigned = true fieldValue.SetInt(vv.Int()) } case reflect.Float32, reflect.Float64: switch rawValueType.Kind() { case reflect.Float32, reflect.Float64: hasAssigned = true fieldValue.SetFloat(vv.Float()) } case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: switch rawValueType.Kind() { case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: hasAssigned = true fieldValue.SetUint(vv.Uint()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: hasAssigned = true fieldValue.SetUint(uint64(vv.Int())) } case reflect.Struct: if fieldType.ConvertibleTo(core.TimeType) { if rawValueType == core.TimeType { hasAssigned = true t := vv.Convert(core.TimeType).Interface().(time.Time) z, _ := t.Zone() if len(z) == 0 || t.Year() == 0 { // !nashtsai! HACK tmp work around for lib/pq doesn't properly time with location dbTZ := session.Engine.DatabaseTZ if dbTZ == nil { dbTZ = time.Local } session.Engine.logger.Debugf("empty zone key[%v] : %v | zone: %v | location: %+v\n", key, t, z, *t.Location()) t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), dbTZ) } // !nashtsai! convert to engine location if col.TimeZone == nil { t = t.In(session.Engine.TZLocation) } else { t = t.In(col.TimeZone) } fieldValue.Set(reflect.ValueOf(t).Convert(fieldType)) // t = fieldValue.Interface().(time.Time) // z, _ = t.Zone() // session.Engine.LogDebug("fieldValue key[%v]: %v | zone: %v | location: %+v\n", key, t, z, *t.Location()) } else if rawValueType == core.IntType || rawValueType == core.Int64Type || rawValueType == core.Int32Type { hasAssigned = true var tz *time.Location if col.TimeZone == nil { tz = session.Engine.TZLocation } else { tz = col.TimeZone } t := time.Unix(vv.Int(), 0).In(tz) //vv = reflect.ValueOf(t) fieldValue.Set(reflect.ValueOf(t).Convert(fieldType)) } else { if d, ok := vv.Interface().([]uint8); ok { hasAssigned = true t, err := session.byte2Time(col, d) if err != nil { session.Engine.logger.Error("byte2Time error:", err.Error()) hasAssigned = false } else { fieldValue.Set(reflect.ValueOf(t).Convert(fieldType)) } } else if d, ok := vv.Interface().(string); ok { hasAssigned = true t, err := session.str2Time(col, d) if err != nil { session.Engine.logger.Error("byte2Time error:", err.Error()) hasAssigned = false } else { fieldValue.Set(reflect.ValueOf(t).Convert(fieldType)) } } else { panic(fmt.Sprintf("rawValueType is %v, value is %v", rawValueType, vv.Interface())) } } } else if nulVal, ok := fieldValue.Addr().Interface().(sql.Scanner); ok { // !! 增加支持sql.Scanner接口的结构,如sql.NullString hasAssigned = true if err := nulVal.Scan(vv.Interface()); err != nil { //fmt.Println("sql.Sanner error:", err.Error()) session.Engine.logger.Error("sql.Sanner error:", err.Error()) hasAssigned = false } } else if col.SQLType.IsJson() { if rawValueType.Kind() == reflect.String { hasAssigned = true x := reflect.New(fieldType) if len([]byte(vv.String())) > 0 { err := json.Unmarshal([]byte(vv.String()), x.Interface()) if err != nil { session.Engine.logger.Error(err) return err } fieldValue.Set(x.Elem()) } } else if rawValueType.Kind() == reflect.Slice { hasAssigned = true x := reflect.New(fieldType) if len(vv.Bytes()) > 0 { err := json.Unmarshal(vv.Bytes(), x.Interface()) if err != nil { session.Engine.logger.Error(err) return err } fieldValue.Set(x.Elem()) } } } else if session.Statement.UseCascade { table := session.Engine.autoMapType(*fieldValue) if table != nil { hasAssigned = true if len(table.PrimaryKeys) != 1 { panic("unsupported non or composited primary key cascade") } var pk = make(core.PK, len(table.PrimaryKeys)) switch rawValueType.Kind() { case reflect.Int64: pk[0] = vv.Int() case reflect.Int: pk[0] = int(vv.Int()) case reflect.Int32: pk[0] = int32(vv.Int()) case reflect.Int16: pk[0] = int16(vv.Int()) case reflect.Int8: pk[0] = int8(vv.Int()) case reflect.Uint64: pk[0] = vv.Uint() case reflect.Uint: pk[0] = uint(vv.Uint()) case reflect.Uint32: pk[0] = uint32(vv.Uint()) case reflect.Uint16: pk[0] = uint16(vv.Uint()) case reflect.Uint8: pk[0] = uint8(vv.Uint()) case reflect.String: pk[0] = vv.String() case reflect.Slice: pk[0], _ = strconv.ParseInt(string(rawValue.Interface().([]byte)), 10, 64) default: panic(fmt.Sprintf("unsupported primary key type: %v, %v", rawValueType, fieldValue)) } if !isPKZero(pk) { // !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch // however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne // property to be fetched lazily structInter := reflect.New(fieldValue.Type()) newsession := session.Engine.NewSession() defer newsession.Close() has, err := newsession.Id(pk).NoCascade().Get(structInter.Interface()) if err != nil { return err } if has { //v := structInter.Elem().Interface() //fieldValue.Set(reflect.ValueOf(v)) fieldValue.Set(structInter.Elem()) } else { return errors.New("cascade obj is not exist") } } } else { session.Engine.logger.Error("unsupported struct type in Scan: ", fieldValue.Type().String()) } } case reflect.Ptr: // !nashtsai! TODO merge duplicated codes above //typeStr := fieldType.String() switch fieldType { // following types case matching ptr's native type, therefore assign ptr directly case core.PtrStringType: if rawValueType.Kind() == reflect.String { x := vv.String() hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.PtrBoolType: if rawValueType.Kind() == reflect.Bool { x := vv.Bool() hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.PtrTimeType: if rawValueType == core.PtrTimeType { hasAssigned = true var x = rawValue.Interface().(time.Time) fieldValue.Set(reflect.ValueOf(&x)) } case core.PtrFloat64Type: if rawValueType.Kind() == reflect.Float64 { x := vv.Float() hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.PtrUint64Type: if rawValueType.Kind() == reflect.Int64 { var x = uint64(vv.Int()) hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.PtrInt64Type: if rawValueType.Kind() == reflect.Int64 { x := vv.Int() hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.PtrFloat32Type: if rawValueType.Kind() == reflect.Float64 { var x = float32(vv.Float()) hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.PtrIntType: if rawValueType.Kind() == reflect.Int64 { var x = int(vv.Int()) hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.PtrInt32Type: if rawValueType.Kind() == reflect.Int64 { var x = int32(vv.Int()) hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.PtrInt8Type: if rawValueType.Kind() == reflect.Int64 { var x = int8(vv.Int()) hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.PtrInt16Type: if rawValueType.Kind() == reflect.Int64 { var x = int16(vv.Int()) hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.PtrUintType: if rawValueType.Kind() == reflect.Int64 { var x = uint(vv.Int()) hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.PtrUint32Type: if rawValueType.Kind() == reflect.Int64 { var x = uint32(vv.Int()) hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.Uint8Type: if rawValueType.Kind() == reflect.Int64 { var x = uint8(vv.Int()) hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.Uint16Type: if rawValueType.Kind() == reflect.Int64 { var x = uint16(vv.Int()) hasAssigned = true fieldValue.Set(reflect.ValueOf(&x)) } case core.Complex64Type: var x complex64 if len([]byte(vv.String())) > 0 { err := json.Unmarshal([]byte(vv.String()), &x) if err != nil { session.Engine.logger.Error(err) } else { fieldValue.Set(reflect.ValueOf(&x)) } } hasAssigned = true case core.Complex128Type: var x complex128 if len([]byte(vv.String())) > 0 { err := json.Unmarshal([]byte(vv.String()), &x) if err != nil { session.Engine.logger.Error(err) } else { fieldValue.Set(reflect.ValueOf(&x)) } } hasAssigned = true } // switch fieldType // default: // session.Engine.LogError("unsupported type in Scan: ", reflect.TypeOf(v).String()) } // switch fieldType.Kind() // !nashtsai! for value can't be assigned directly fallback to convert to []byte then back to value if !hasAssigned { data, err := value2Bytes(&rawValue) if err == nil { session.bytes2Value(col, fieldValue, data) } else { session.Engine.logger.Error(err.Error()) } } } } return nil } func (session *Session) queryPreprocess(sqlStr *string, paramStr ...interface{}) { for _, filter := range session.Engine.dialect.Filters() { *sqlStr = filter.Do(*sqlStr, session.Engine.dialect, session.Statement.RefTable) } session.saveLastSQL(*sqlStr, paramStr...) } func (session *Session) query(sqlStr string, paramStr ...interface{}) (resultsSlice []map[string][]byte, err error) { session.queryPreprocess(&sqlStr, paramStr...) if session.IsAutoCommit { return session.innerQuery2(sqlStr, paramStr...) } return session.txQuery(session.Tx, sqlStr, paramStr...) } func (session *Session) txQuery(tx *core.Tx, sqlStr string, params ...interface{}) (resultsSlice []map[string][]byte, err error) { rows, err := tx.Query(sqlStr, params...) if err != nil { return nil, err } defer rows.Close() return rows2maps(rows) } func (session *Session) innerQuery(sqlStr string, params ...interface{}) (*core.Stmt, *core.Rows, error) { var callback func() (*core.Stmt, *core.Rows, error) if session.prepareStmt { callback = func() (*core.Stmt, *core.Rows, error) { stmt, err := session.doPrepare(sqlStr) if err != nil { return nil, nil, err } rows, err := stmt.Query(params...) if err != nil { return nil, nil, err } return stmt, rows, nil } } else { callback = func() (*core.Stmt, *core.Rows, error) { rows, err := session.DB().Query(sqlStr, params...) if err != nil { return nil, nil, err } return nil, rows, err } } stmt, rows, err := session.Engine.logSQLQueryTime(sqlStr, params, callback) if err != nil { return nil, nil, err } return stmt, rows, nil } func (session *Session) innerQuery2(sqlStr string, params ...interface{}) ([]map[string][]byte, error) { _, rows, err := session.innerQuery(sqlStr, params...) if rows != nil { defer rows.Close() } if err != nil { return nil, err } return rows2maps(rows) } // Query a raw sql and return records as []map[string][]byte func (session *Session) Query(sqlStr string, paramStr ...interface{}) (resultsSlice []map[string][]byte, err error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } return session.query(sqlStr, paramStr...) } // ============================= // for string // ============================= func (session *Session) query2(sqlStr string, paramStr ...interface{}) (resultsSlice []map[string]string, err error) { session.queryPreprocess(&sqlStr, paramStr...) if session.IsAutoCommit { return query2(session.DB(), sqlStr, paramStr...) } return txQuery2(session.Tx, sqlStr, paramStr...) } // Insert insert one or more beans func (session *Session) Insert(beans ...interface{}) (int64, error) { var affected int64 var err error if session.IsAutoClose { defer session.Close() } for _, bean := range beans { sliceValue := reflect.Indirect(reflect.ValueOf(bean)) if sliceValue.Kind() == reflect.Slice { size := sliceValue.Len() if size > 0 { if session.Engine.SupportInsertMany() { cnt, err := session.innerInsertMulti(bean) session.resetStatement() if err != nil { return affected, err } affected += cnt } else { for i := 0; i < size; i++ { cnt, err := session.innerInsert(sliceValue.Index(i).Interface()) session.resetStatement() if err != nil { return affected, err } affected += cnt } } } } else { cnt, err := session.innerInsert(bean) session.resetStatement() if err != nil { return affected, err } affected += cnt } } return affected, err } func (session *Session) innerInsertMulti(rowsSlicePtr interface{}) (int64, error) { sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr)) if sliceValue.Kind() != reflect.Slice { return 0, errors.New("needs a pointer to a slice") } bean := sliceValue.Index(0).Interface() elementValue := rValue(bean) session.Statement.setRefValue(elementValue) if len(session.Statement.TableName()) <= 0 { return 0, ErrTableNotFound } table := session.Statement.RefTable size := sliceValue.Len() var colNames []string var colMultiPlaces []string var args []interface{} var cols []*core.Column for i := 0; i < size; i++ { v := sliceValue.Index(i) vv := reflect.Indirect(v) elemValue := v.Interface() var colPlaces []string // handle BeforeInsertProcessor // !nashtsai! does user expect it's same slice to passed closure when using Before()/After() when insert multi?? for _, closure := range session.beforeClosures { closure(elemValue) } if processor, ok := interface{}(elemValue).(BeforeInsertProcessor); ok { processor.BeforeInsert() } // -- if i == 0 { for _, col := range table.Columns() { ptrFieldValue, err := col.ValueOfV(&vv) if err != nil { return 0, err } fieldValue := *ptrFieldValue if col.IsAutoIncrement && isZero(fieldValue.Interface()) { continue } if col.MapType == core.ONLYFROMDB { continue } if col.IsDeleted { continue } if session.Statement.ColumnStr != "" { if _, ok := session.Statement.columnMap[strings.ToLower(col.Name)]; !ok { continue } } if session.Statement.OmitStr != "" { if _, ok := session.Statement.columnMap[strings.ToLower(col.Name)]; ok { continue } } if (col.IsCreated || col.IsUpdated) && session.Statement.UseAutoTime { val, t := session.Engine.NowTime2(col.SQLType.Name) args = append(args, val) var colName = col.Name session.afterClosures = append(session.afterClosures, func(bean interface{}) { col := table.GetColumn(colName) setColumnTime(bean, col, t) }) } else if col.IsVersion && session.Statement.checkVersion { args = append(args, 1) var colName = col.Name session.afterClosures = append(session.afterClosures, func(bean interface{}) { col := table.GetColumn(colName) setColumnInt(bean, col, 1) }) } else { arg, err := session.value2Interface(col, fieldValue) if err != nil { return 0, err } args = append(args, arg) } colNames = append(colNames, col.Name) cols = append(cols, col) colPlaces = append(colPlaces, "?") } } else { for _, col := range cols { ptrFieldValue, err := col.ValueOfV(&vv) if err != nil { return 0, err } fieldValue := *ptrFieldValue if col.IsAutoIncrement && isZero(fieldValue.Interface()) { continue } if col.MapType == core.ONLYFROMDB { continue } if col.IsDeleted { continue } if session.Statement.ColumnStr != "" { if _, ok := session.Statement.columnMap[strings.ToLower(col.Name)]; !ok { continue } } if session.Statement.OmitStr != "" { if _, ok := session.Statement.columnMap[strings.ToLower(col.Name)]; ok { continue } } if (col.IsCreated || col.IsUpdated) && session.Statement.UseAutoTime { val, t := session.Engine.NowTime2(col.SQLType.Name) args = append(args, val) var colName = col.Name session.afterClosures = append(session.afterClosures, func(bean interface{}) { col := table.GetColumn(colName) setColumnTime(bean, col, t) }) } else if col.IsVersion && session.Statement.checkVersion { args = append(args, 1) var colName = col.Name session.afterClosures = append(session.afterClosures, func(bean interface{}) { col := table.GetColumn(colName) setColumnInt(bean, col, 1) }) } else { arg, err := session.value2Interface(col, fieldValue) if err != nil { return 0, err } args = append(args, arg) } colPlaces = append(colPlaces, "?") } } colMultiPlaces = append(colMultiPlaces, strings.Join(colPlaces, ", ")) } cleanupProcessorsClosures(&session.beforeClosures) statement := fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)", session.Engine.Quote(session.Statement.TableName()), session.Engine.QuoteStr(), strings.Join(colNames, session.Engine.QuoteStr()+", "+session.Engine.QuoteStr()), session.Engine.QuoteStr(), strings.Join(colMultiPlaces, "),(")) res, err := session.exec(statement, args...) if err != nil { return 0, err } if cacher := session.Engine.getCacher2(table); cacher != nil && session.Statement.UseCache { session.cacheInsert(session.Statement.TableName()) } lenAfterClosures := len(session.afterClosures) for i := 0; i < size; i++ { elemValue := reflect.Indirect(sliceValue.Index(i)).Addr().Interface() // handle AfterInsertProcessor if session.IsAutoCommit { // !nashtsai! does user expect it's same slice to passed closure when using Before()/After() when insert multi?? for _, closure := range session.afterClosures { closure(elemValue) } if processor, ok := interface{}(elemValue).(AfterInsertProcessor); ok { processor.AfterInsert() } } else { if lenAfterClosures > 0 { if value, has := session.afterInsertBeans[elemValue]; has && value != nil { *value = append(*value, session.afterClosures...) } else { afterClosures := make([]func(interface{}), lenAfterClosures) copy(afterClosures, session.afterClosures) session.afterInsertBeans[elemValue] = &afterClosures } } else { if _, ok := interface{}(elemValue).(AfterInsertProcessor); ok { session.afterInsertBeans[elemValue] = nil } } } } cleanupProcessorsClosures(&session.afterClosures) return res.RowsAffected() } // InsertMulti insert multiple records func (session *Session) InsertMulti(rowsSlicePtr interface{}) (int64, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr)) if sliceValue.Kind() != reflect.Slice { return 0, ErrParamsType } if sliceValue.Len() <= 0 { return 0, nil } return session.innerInsertMulti(rowsSlicePtr) } func (session *Session) str2Time(col *core.Column, data string) (outTime time.Time, outErr error) { sdata := strings.TrimSpace(data) var x time.Time var err error if sdata == "0000-00-00 00:00:00" || sdata == "0001-01-01 00:00:00" { } else if !strings.ContainsAny(sdata, "- :") { // !nashtsai! has only found that mymysql driver is using this for time type column // time stamp sd, err := strconv.ParseInt(sdata, 10, 64) if err == nil { x = time.Unix(sd, 0) // !nashtsai! HACK mymysql driver is casuing Local location being change to CHAT and cause wrong time conversion //fmt.Println(x.In(session.Engine.TZLocation), "===") if col.TimeZone == nil { x = x.In(session.Engine.TZLocation) } else { x = x.In(col.TimeZone) } //fmt.Println(x, "=====") session.Engine.logger.Debugf("time(0) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata) } else { session.Engine.logger.Debugf("time(0) err key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata) } } else if len(sdata) > 19 && strings.Contains(sdata, "-") { x, err = time.ParseInLocation(time.RFC3339Nano, sdata, session.Engine.TZLocation) session.Engine.logger.Debugf("time(1) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata) if err != nil { x, err = time.ParseInLocation("2006-01-02 15:04:05.999999999", sdata, session.Engine.TZLocation) session.Engine.logger.Debugf("time(2) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata) } if err != nil { x, err = time.ParseInLocation("2006-01-02 15:04:05.9999999 Z07:00", sdata, session.Engine.TZLocation) session.Engine.logger.Debugf("time(3) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata) } } else if len(sdata) == 19 && strings.Contains(sdata, "-") { x, err = time.ParseInLocation("2006-01-02 15:04:05", sdata, session.Engine.TZLocation) session.Engine.logger.Debugf("time(4) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata) } else if len(sdata) == 10 && sdata[4] == '-' && sdata[7] == '-' { x, err = time.ParseInLocation("2006-01-02", sdata, session.Engine.TZLocation) session.Engine.logger.Debugf("time(5) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata) } else if col.SQLType.Name == core.Time { if strings.Contains(sdata, " ") { ssd := strings.Split(sdata, " ") sdata = ssd[1] } sdata = strings.TrimSpace(sdata) if session.Engine.dialect.DBType() == core.MYSQL && len(sdata) > 8 { sdata = sdata[len(sdata)-8:] } st := fmt.Sprintf("2006-01-02 %v", sdata) x, err = time.ParseInLocation("2006-01-02 15:04:05", st, session.Engine.TZLocation) session.Engine.logger.Debugf("time(6) key[%v]: %+v | sdata: [%v]\n", col.FieldName, x, sdata) } else { outErr = fmt.Errorf("unsupported time format %v", sdata) return } if err != nil { outErr = fmt.Errorf("unsupported time format %v: %v", sdata, err) return } outTime = x return } func (session *Session) byte2Time(col *core.Column, data []byte) (outTime time.Time, outErr error) { return session.str2Time(col, string(data)) } // convert a db data([]byte) to a field value func (session *Session) bytes2Value(col *core.Column, fieldValue *reflect.Value, data []byte) error { if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok { return structConvert.FromDB(data) } if structConvert, ok := fieldValue.Interface().(core.Conversion); ok { return structConvert.FromDB(data) } var v interface{} key := col.Name fieldType := fieldValue.Type() switch fieldType.Kind() { case reflect.Complex64, reflect.Complex128: x := reflect.New(fieldType) if len(data) > 0 { err := json.Unmarshal(data, x.Interface()) if err != nil { session.Engine.logger.Error(err) return err } fieldValue.Set(x.Elem()) } case reflect.Slice, reflect.Array, reflect.Map: v = data t := fieldType.Elem() k := t.Kind() if col.SQLType.IsText() { x := reflect.New(fieldType) if len(data) > 0 { err := json.Unmarshal(data, x.Interface()) if err != nil { session.Engine.logger.Error(err) return err } fieldValue.Set(x.Elem()) } } else if col.SQLType.IsBlob() { if k == reflect.Uint8 { fieldValue.Set(reflect.ValueOf(v)) } else { x := reflect.New(fieldType) if len(data) > 0 { err := json.Unmarshal(data, x.Interface()) if err != nil { session.Engine.logger.Error(err) return err } fieldValue.Set(x.Elem()) } } } else { return ErrUnSupportedType } case reflect.String: fieldValue.SetString(string(data)) case reflect.Bool: d := string(data) v, err := strconv.ParseBool(d) if err != nil { return fmt.Errorf("arg %v as bool: %s", key, err.Error()) } fieldValue.Set(reflect.ValueOf(v)) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: sdata := string(data) var x int64 var err error // for mysql, when use bit, it returned \x01 if col.SQLType.Name == core.Bit && session.Engine.dialect.DBType() == core.MYSQL { // !nashtsai! TODO dialect needs to provide conversion interface API if len(data) == 1 { x = int64(data[0]) } else { x = 0 } } else if strings.HasPrefix(sdata, "0x") { x, err = strconv.ParseInt(sdata, 16, 64) } else if strings.HasPrefix(sdata, "0") { x, err = strconv.ParseInt(sdata, 8, 64) } else if strings.ToLower(sdata) == "true" { x = 1 } else if strings.ToLower(sdata) == "false" { x = 0 } else { x, err = strconv.ParseInt(sdata, 10, 64) } if err != nil { return fmt.Errorf("arg %v as int: %s", key, err.Error()) } fieldValue.SetInt(x) case reflect.Float32, reflect.Float64: x, err := strconv.ParseFloat(string(data), 64) if err != nil { return fmt.Errorf("arg %v as float64: %s", key, err.Error()) } fieldValue.SetFloat(x) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: x, err := strconv.ParseUint(string(data), 10, 64) if err != nil { return fmt.Errorf("arg %v as int: %s", key, err.Error()) } fieldValue.SetUint(x) //Currently only support Time type case reflect.Struct: // !! 增加支持sql.Scanner接口的结构,如sql.NullString if nulVal, ok := fieldValue.Addr().Interface().(sql.Scanner); ok { if err := nulVal.Scan(data); err != nil { return fmt.Errorf("sql.Scan(%v) failed: %s ", data, err.Error()) } } else { if fieldType.ConvertibleTo(core.TimeType) { x, err := session.byte2Time(col, data) if err != nil { return err } v = x fieldValue.Set(reflect.ValueOf(v).Convert(fieldType)) } else if session.Statement.UseCascade { table := session.Engine.autoMapType(*fieldValue) if table != nil { // TODO: current only support 1 primary key if len(table.PrimaryKeys) > 1 { panic("unsupported composited primary key cascade") } var pk = make(core.PK, len(table.PrimaryKeys)) rawValueType := table.ColumnType(table.PKColumns()[0].FieldName) var err error pk[0], err = str2PK(string(data), rawValueType) if err != nil { return err } if !isPKZero(pk) { // !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch // however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne // property to be fetched lazily structInter := reflect.New(fieldValue.Type()) newsession := session.Engine.NewSession() defer newsession.Close() has, err := newsession.Id(pk).NoCascade().Get(structInter.Interface()) if err != nil { return err } if has { v = structInter.Elem().Interface() fieldValue.Set(reflect.ValueOf(v)) } else { return errors.New("cascade obj is not exist") } } } else { return fmt.Errorf("unsupported struct type in Scan: %s", fieldValue.Type().String()) } } } case reflect.Ptr: // !nashtsai! TODO merge duplicated codes above //typeStr := fieldType.String() switch fieldType.Elem().Kind() { // case "*string": case core.StringType.Kind(): x := string(data) fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*bool": case core.BoolType.Kind(): d := string(data) v, err := strconv.ParseBool(d) if err != nil { return fmt.Errorf("arg %v as bool: %s", key, err.Error()) } fieldValue.Set(reflect.ValueOf(&v).Convert(fieldType)) // case "*complex64": case core.Complex64Type.Kind(): var x complex64 if len(data) > 0 { err := json.Unmarshal(data, &x) if err != nil { session.Engine.logger.Error(err) return err } fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) } // case "*complex128": case core.Complex128Type.Kind(): var x complex128 if len(data) > 0 { err := json.Unmarshal(data, &x) if err != nil { session.Engine.logger.Error(err) return err } fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) } // case "*float64": case core.Float64Type.Kind(): x, err := strconv.ParseFloat(string(data), 64) if err != nil { return fmt.Errorf("arg %v as float64: %s", key, err.Error()) } fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*float32": case core.Float32Type.Kind(): var x float32 x1, err := strconv.ParseFloat(string(data), 32) if err != nil { return fmt.Errorf("arg %v as float32: %s", key, err.Error()) } x = float32(x1) fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*uint64": case core.Uint64Type.Kind(): var x uint64 x, err := strconv.ParseUint(string(data), 10, 64) if err != nil { return fmt.Errorf("arg %v as int: %s", key, err.Error()) } fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*uint": case core.UintType.Kind(): var x uint x1, err := strconv.ParseUint(string(data), 10, 64) if err != nil { return fmt.Errorf("arg %v as int: %s", key, err.Error()) } x = uint(x1) fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*uint32": case core.Uint32Type.Kind(): var x uint32 x1, err := strconv.ParseUint(string(data), 10, 64) if err != nil { return fmt.Errorf("arg %v as int: %s", key, err.Error()) } x = uint32(x1) fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*uint8": case core.Uint8Type.Kind(): var x uint8 x1, err := strconv.ParseUint(string(data), 10, 64) if err != nil { return fmt.Errorf("arg %v as int: %s", key, err.Error()) } x = uint8(x1) fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*uint16": case core.Uint16Type.Kind(): var x uint16 x1, err := strconv.ParseUint(string(data), 10, 64) if err != nil { return fmt.Errorf("arg %v as int: %s", key, err.Error()) } x = uint16(x1) fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*int64": case core.Int64Type.Kind(): sdata := string(data) var x int64 var err error // for mysql, when use bit, it returned \x01 if col.SQLType.Name == core.Bit && strings.Contains(session.Engine.DriverName(), "mysql") { if len(data) == 1 { x = int64(data[0]) } else { x = 0 } } else if strings.HasPrefix(sdata, "0x") { x, err = strconv.ParseInt(sdata, 16, 64) } else if strings.HasPrefix(sdata, "0") { x, err = strconv.ParseInt(sdata, 8, 64) } else { x, err = strconv.ParseInt(sdata, 10, 64) } if err != nil { return fmt.Errorf("arg %v as int: %s", key, err.Error()) } fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*int": case core.IntType.Kind(): sdata := string(data) var x int var x1 int64 var err error // for mysql, when use bit, it returned \x01 if col.SQLType.Name == core.Bit && strings.Contains(session.Engine.DriverName(), "mysql") { if len(data) == 1 { x = int(data[0]) } else { x = 0 } } else if strings.HasPrefix(sdata, "0x") { x1, err = strconv.ParseInt(sdata, 16, 64) x = int(x1) } else if strings.HasPrefix(sdata, "0") { x1, err = strconv.ParseInt(sdata, 8, 64) x = int(x1) } else { x1, err = strconv.ParseInt(sdata, 10, 64) x = int(x1) } if err != nil { return fmt.Errorf("arg %v as int: %s", key, err.Error()) } fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*int32": case core.Int32Type.Kind(): sdata := string(data) var x int32 var x1 int64 var err error // for mysql, when use bit, it returned \x01 if col.SQLType.Name == core.Bit && session.Engine.dialect.DBType() == core.MYSQL { if len(data) == 1 { x = int32(data[0]) } else { x = 0 } } else if strings.HasPrefix(sdata, "0x") { x1, err = strconv.ParseInt(sdata, 16, 64) x = int32(x1) } else if strings.HasPrefix(sdata, "0") { x1, err = strconv.ParseInt(sdata, 8, 64) x = int32(x1) } else { x1, err = strconv.ParseInt(sdata, 10, 64) x = int32(x1) } if err != nil { return fmt.Errorf("arg %v as int: %s", key, err.Error()) } fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*int8": case core.Int8Type.Kind(): sdata := string(data) var x int8 var x1 int64 var err error // for mysql, when use bit, it returned \x01 if col.SQLType.Name == core.Bit && strings.Contains(session.Engine.DriverName(), "mysql") { if len(data) == 1 { x = int8(data[0]) } else { x = 0 } } else if strings.HasPrefix(sdata, "0x") { x1, err = strconv.ParseInt(sdata, 16, 64) x = int8(x1) } else if strings.HasPrefix(sdata, "0") { x1, err = strconv.ParseInt(sdata, 8, 64) x = int8(x1) } else { x1, err = strconv.ParseInt(sdata, 10, 64) x = int8(x1) } if err != nil { return fmt.Errorf("arg %v as int: %s", key, err.Error()) } fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*int16": case core.Int16Type.Kind(): sdata := string(data) var x int16 var x1 int64 var err error // for mysql, when use bit, it returned \x01 if col.SQLType.Name == core.Bit && strings.Contains(session.Engine.DriverName(), "mysql") { if len(data) == 1 { x = int16(data[0]) } else { x = 0 } } else if strings.HasPrefix(sdata, "0x") { x1, err = strconv.ParseInt(sdata, 16, 64) x = int16(x1) } else if strings.HasPrefix(sdata, "0") { x1, err = strconv.ParseInt(sdata, 8, 64) x = int16(x1) } else { x1, err = strconv.ParseInt(sdata, 10, 64) x = int16(x1) } if err != nil { return fmt.Errorf("arg %v as int: %s", key, err.Error()) } fieldValue.Set(reflect.ValueOf(&x).Convert(fieldType)) // case "*SomeStruct": case reflect.Struct: switch fieldType { // case "*.time.Time": case core.PtrTimeType: x, err := session.byte2Time(col, data) if err != nil { return err } v = x fieldValue.Set(reflect.ValueOf(&x)) default: if session.Statement.UseCascade { structInter := reflect.New(fieldType.Elem()) table := session.Engine.autoMapType(structInter.Elem()) if table != nil { if len(table.PrimaryKeys) > 1 { panic("unsupported composited primary key cascade") } var pk = make(core.PK, len(table.PrimaryKeys)) var err error rawValueType := table.ColumnType(table.PKColumns()[0].FieldName) pk[0], err = str2PK(string(data), rawValueType) if err != nil { return err } if !isPKZero(pk) { // !nashtsai! TODO for hasOne relationship, it's preferred to use join query for eager fetch // however, also need to consider adding a 'lazy' attribute to xorm tag which allow hasOne // property to be fetched lazily newsession := session.Engine.NewSession() defer newsession.Close() has, err := newsession.Id(pk).NoCascade().Get(structInter.Interface()) if err != nil { return err } if has { v = structInter.Interface() fieldValue.Set(reflect.ValueOf(v)) } else { return errors.New("cascade obj is not exist") } } } } else { return fmt.Errorf("unsupported struct type in Scan: %s", fieldValue.Type().String()) } } default: return fmt.Errorf("unsupported type in Scan: %s", fieldValue.Type().String()) } default: return fmt.Errorf("unsupported type in Scan: %s", fieldValue.Type().String()) } return nil } // convert a field value of a struct to interface for put into db func (session *Session) value2Interface(col *core.Column, fieldValue reflect.Value) (interface{}, error) { if fieldValue.CanAddr() { if fieldConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok { data, err := fieldConvert.ToDB() if err != nil { return 0, err } return string(data), nil } } if fieldConvert, ok := fieldValue.Interface().(core.Conversion); ok { data, err := fieldConvert.ToDB() if err != nil { return 0, err } return string(data), nil } fieldType := fieldValue.Type() k := fieldType.Kind() if k == reflect.Ptr { if fieldValue.IsNil() { return nil, nil } else if !fieldValue.IsValid() { session.Engine.logger.Warn("the field[", col.FieldName, "] is invalid") return nil, nil } else { // !nashtsai! deference pointer type to instance type fieldValue = fieldValue.Elem() fieldType = fieldValue.Type() k = fieldType.Kind() } } switch k { case reflect.Bool: return fieldValue.Bool(), nil case reflect.String: return fieldValue.String(), nil case reflect.Struct: if fieldType.ConvertibleTo(core.TimeType) { t := fieldValue.Convert(core.TimeType).Interface().(time.Time) if session.Engine.dialect.DBType() == core.MSSQL { if t.IsZero() { return nil, nil } } tf := session.Engine.FormatTime(col.SQLType.Name, t) return tf, nil } if !col.SQLType.IsJson() { // !! 增加支持driver.Valuer接口的结构,如sql.NullString if v, ok := fieldValue.Interface().(driver.Valuer); ok { return v.Value() } fieldTable := session.Engine.autoMapType(fieldValue) if len(fieldTable.PrimaryKeys) == 1 { pkField := reflect.Indirect(fieldValue).FieldByName(fieldTable.PKColumns()[0].FieldName) return pkField.Interface(), nil } return 0, fmt.Errorf("no primary key for col %v", col.Name) } if col.SQLType.IsText() { bytes, err := json.Marshal(fieldValue.Interface()) if err != nil { session.Engine.logger.Error(err) return 0, err } return string(bytes), nil } else if col.SQLType.IsBlob() { bytes, err := json.Marshal(fieldValue.Interface()) if err != nil { session.Engine.logger.Error(err) return 0, err } return bytes, nil } return nil, fmt.Errorf("Unsupported type %v", fieldValue.Type()) case reflect.Complex64, reflect.Complex128: bytes, err := json.Marshal(fieldValue.Interface()) if err != nil { session.Engine.logger.Error(err) return 0, err } return string(bytes), nil case reflect.Array, reflect.Slice, reflect.Map: if !fieldValue.IsValid() { return fieldValue.Interface(), nil } if col.SQLType.IsText() { bytes, err := json.Marshal(fieldValue.Interface()) if err != nil { session.Engine.logger.Error(err) return 0, err } return string(bytes), nil } else if col.SQLType.IsBlob() { var bytes []byte var err error if (k == reflect.Array || k == reflect.Slice) && (fieldValue.Type().Elem().Kind() == reflect.Uint8) { bytes = fieldValue.Bytes() } else { bytes, err = json.Marshal(fieldValue.Interface()) if err != nil { session.Engine.logger.Error(err) return 0, err } } return bytes, nil } return nil, ErrUnSupportedType case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: return int64(fieldValue.Uint()), nil default: return fieldValue.Interface(), nil } } func (session *Session) innerInsert(bean interface{}) (int64, error) { session.Statement.setRefValue(rValue(bean)) if len(session.Statement.TableName()) <= 0 { return 0, ErrTableNotFound } table := session.Statement.RefTable // handle BeforeInsertProcessor for _, closure := range session.beforeClosures { closure(bean) } cleanupProcessorsClosures(&session.beforeClosures) // cleanup after used if processor, ok := interface{}(bean).(BeforeInsertProcessor); ok { processor.BeforeInsert() } // -- colNames, args, err := genCols(session.Statement.RefTable, session, bean, false, false) if err != nil { return 0, err } // insert expr columns, override if exists exprColumns := session.Statement.getExpr() exprColVals := make([]string, 0, len(exprColumns)) for _, v := range exprColumns { // remove the expr columns for i, colName := range colNames { if colName == v.colName { colNames = append(colNames[:i], colNames[i+1:]...) args = append(args[:i], args[i+1:]...) } } // append expr column to the end colNames = append(colNames, v.colName) exprColVals = append(exprColVals, v.expr) } colPlaces := strings.Repeat("?, ", len(colNames)-len(exprColumns)) if len(exprColVals) > 0 { colPlaces = colPlaces + strings.Join(exprColVals, ", ") } else { colPlaces = colPlaces[0 : len(colPlaces)-2] } sqlStr := fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)", session.Engine.Quote(session.Statement.TableName()), session.Engine.QuoteStr(), strings.Join(colNames, session.Engine.Quote(", ")), session.Engine.QuoteStr(), colPlaces) handleAfterInsertProcessorFunc := func(bean interface{}) { if session.IsAutoCommit { for _, closure := range session.afterClosures { closure(bean) } if processor, ok := interface{}(bean).(AfterInsertProcessor); ok { processor.AfterInsert() } } else { lenAfterClosures := len(session.afterClosures) if lenAfterClosures > 0 { if value, has := session.afterInsertBeans[bean]; has && value != nil { *value = append(*value, session.afterClosures...) } else { afterClosures := make([]func(interface{}), lenAfterClosures) copy(afterClosures, session.afterClosures) session.afterInsertBeans[bean] = &afterClosures } } else { if _, ok := interface{}(bean).(AfterInsertProcessor); ok { session.afterInsertBeans[bean] = nil } } } cleanupProcessorsClosures(&session.afterClosures) // cleanup after used } // for postgres, many of them didn't implement lastInsertId, so we should // implemented it ourself. if session.Engine.dialect.DBType() == core.ORACLE && len(table.AutoIncrement) > 0 { //assert table.AutoIncrement != "" res, err := session.query("select seq_atable.currval from dual", args...) if err != nil { return 0, err } handleAfterInsertProcessorFunc(bean) if cacher := session.Engine.getCacher2(table); cacher != nil && session.Statement.UseCache { session.cacheInsert(session.Statement.TableName()) } if table.Version != "" && session.Statement.checkVersion { verValue, err := table.VersionColumn().ValueOf(bean) if err != nil { session.Engine.logger.Error(err) } else if verValue.IsValid() && verValue.CanSet() { verValue.SetInt(1) } } if len(res) < 1 { return 0, errors.New("insert no error but not returned id") } idByte := res[0][table.AutoIncrement] id, err := strconv.ParseInt(string(idByte), 10, 64) if err != nil || id <= 0 { return 1, err } aiValue, err := table.AutoIncrColumn().ValueOf(bean) if err != nil { session.Engine.logger.Error(err) } if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() { return 1, nil } aiValue.Set(int64ToIntValue(id, aiValue.Type())) return 1, nil } else if session.Engine.dialect.DBType() == core.POSTGRES && len(table.AutoIncrement) > 0 { //assert table.AutoIncrement != "" sqlStr = sqlStr + " RETURNING " + session.Engine.Quote(table.AutoIncrement) res, err := session.query(sqlStr, args...) if err != nil { return 0, err } handleAfterInsertProcessorFunc(bean) if cacher := session.Engine.getCacher2(table); cacher != nil && session.Statement.UseCache { session.cacheInsert(session.Statement.TableName()) } if table.Version != "" && session.Statement.checkVersion { verValue, err := table.VersionColumn().ValueOf(bean) if err != nil { session.Engine.logger.Error(err) } else if verValue.IsValid() && verValue.CanSet() { verValue.SetInt(1) } } if len(res) < 1 { return 0, errors.New("insert no error but not returned id") } idByte := res[0][table.AutoIncrement] id, err := strconv.ParseInt(string(idByte), 10, 64) if err != nil || id <= 0 { return 1, err } aiValue, err := table.AutoIncrColumn().ValueOf(bean) if err != nil { session.Engine.logger.Error(err) } if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() { return 1, nil } aiValue.Set(int64ToIntValue(id, aiValue.Type())) return 1, nil } else { res, err := session.exec(sqlStr, args...) if err != nil { return 0, err } handleAfterInsertProcessorFunc(bean) if cacher := session.Engine.getCacher2(table); cacher != nil && session.Statement.UseCache { session.cacheInsert(session.Statement.TableName()) } if table.Version != "" && session.Statement.checkVersion { verValue, err := table.VersionColumn().ValueOf(bean) if err != nil { session.Engine.logger.Error(err) } else if verValue.IsValid() && verValue.CanSet() { verValue.SetInt(1) } } if table.AutoIncrement == "" { return res.RowsAffected() } var id int64 id, err = res.LastInsertId() if err != nil || id <= 0 { return res.RowsAffected() } aiValue, err := table.AutoIncrColumn().ValueOf(bean) if err != nil { session.Engine.logger.Error(err) } if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() { return res.RowsAffected() } aiValue.Set(int64ToIntValue(id, aiValue.Type())) return res.RowsAffected() } } // InsertOne insert only one struct into database as a record. // The in parameter bean must a struct or a point to struct. The return // parameter is inserted and error func (session *Session) InsertOne(bean interface{}) (int64, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } return session.innerInsert(bean) } func (session *Session) cacheInsert(tables ...string) error { if session.Statement.RefTable == nil { return ErrCacheFailed } table := session.Statement.RefTable cacher := session.Engine.getCacher2(table) for _, t := range tables { session.Engine.logger.Debug("[cache] clear sql:", t) cacher.ClearIds(t) } return nil } func (session *Session) cacheUpdate(sqlStr string, args ...interface{}) error { if session.Statement.RefTable == nil || session.Tx != nil { return ErrCacheFailed } oldhead, newsql := session.Statement.convertUpdateSQL(sqlStr) if newsql == "" { return ErrCacheFailed } for _, filter := range session.Engine.dialect.Filters() { newsql = filter.Do(newsql, session.Engine.dialect, session.Statement.RefTable) } session.Engine.logger.Debug("[cacheUpdate] new sql", oldhead, newsql) var nStart int if len(args) > 0 { if strings.Index(sqlStr, "?") > -1 { nStart = strings.Count(oldhead, "?") } else { // only for pq, TODO: if any other databse? nStart = strings.Count(oldhead, "$") } } table := session.Statement.RefTable cacher := session.Engine.getCacher2(table) tableName := session.Statement.TableName() session.Engine.logger.Debug("[cacheUpdate] get cache sql", newsql, args[nStart:]) ids, err := core.GetCacheSql(cacher, tableName, newsql, args[nStart:]) if err != nil { rows, err := session.DB().Query(newsql, args[nStart:]...) if err != nil { return err } defer rows.Close() ids = make([]core.PK, 0) for rows.Next() { var res = make([]string, len(table.PrimaryKeys)) err = rows.ScanSlice(&res) if err != nil { return err } var pk core.PK = make([]interface{}, len(table.PrimaryKeys)) for i, col := range table.PKColumns() { if col.SQLType.IsNumeric() { n, err := strconv.ParseInt(res[i], 10, 64) if err != nil { return err } pk[i] = n } else if col.SQLType.IsText() { pk[i] = res[i] } else { return errors.New("not supported") } } ids = append(ids, pk) } session.Engine.logger.Debug("[cacheUpdate] find updated id", ids) } /*else { session.Engine.LogDebug("[xorm:cacheUpdate] del cached sql:", tableName, newsql, args) cacher.DelIds(tableName, genSqlKey(newsql, args)) }*/ for _, id := range ids { sid, err := id.ToString() if err != nil { return err } if bean := cacher.GetBean(tableName, sid); bean != nil { sqls := splitNNoCase(sqlStr, "where", 2) if len(sqls) == 0 || len(sqls) > 2 { return ErrCacheFailed } sqls = splitNNoCase(sqls[0], "set", 2) if len(sqls) != 2 { return ErrCacheFailed } kvs := strings.Split(strings.TrimSpace(sqls[1]), ",") for idx, kv := range kvs { sps := strings.SplitN(kv, "=", 2) sps2 := strings.Split(sps[0], ".") colName := sps2[len(sps2)-1] if strings.Contains(colName, "`") { colName = strings.TrimSpace(strings.Replace(colName, "`", "", -1)) } else if strings.Contains(colName, session.Engine.QuoteStr()) { colName = strings.TrimSpace(strings.Replace(colName, session.Engine.QuoteStr(), "", -1)) } else { session.Engine.logger.Debug("[cacheUpdate] cannot find column", tableName, colName) return ErrCacheFailed } if col := table.GetColumn(colName); col != nil { fieldValue, err := col.ValueOf(bean) if err != nil { session.Engine.logger.Error(err) } else { session.Engine.logger.Debug("[cacheUpdate] set bean field", bean, colName, fieldValue.Interface()) if col.IsVersion && session.Statement.checkVersion { fieldValue.SetInt(fieldValue.Int() + 1) } else { fieldValue.Set(reflect.ValueOf(args[idx])) } } } else { session.Engine.logger.Errorf("[cacheUpdate] ERROR: column %v is not table %v's", colName, table.Name) } } session.Engine.logger.Debug("[cacheUpdate] update cache", tableName, id, bean) cacher.PutBean(tableName, sid, bean) } } session.Engine.logger.Debug("[cacheUpdate] clear cached table sql:", tableName) cacher.ClearIds(tableName) return nil } // Update records, bean's non-empty fields are updated contents, // condiBean' non-empty filds are conditions // CAUTION: // 1.bool will defaultly be updated content nor conditions // You should call UseBool if you have bool to use. // 2.float32 & float64 may be not inexact as conditions func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int64, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } v := rValue(bean) t := v.Type() var colNames []string var args []interface{} // handle before update processors for _, closure := range session.beforeClosures { closure(bean) } cleanupProcessorsClosures(&session.beforeClosures) // cleanup after used if processor, ok := interface{}(bean).(BeforeUpdateProcessor); ok { processor.BeforeUpdate() } // -- var err error var isMap = t.Kind() == reflect.Map var isStruct = t.Kind() == reflect.Struct if isStruct { session.Statement.setRefValue(v) if len(session.Statement.TableName()) <= 0 { return 0, ErrTableNotFound } if session.Statement.ColumnStr == "" { colNames, args = buildUpdates(session.Engine, session.Statement.RefTable, bean, false, false, false, false, session.Statement.allUseBool, session.Statement.useAllCols, session.Statement.mustColumnMap, session.Statement.nullableMap, session.Statement.columnMap, true, session.Statement.unscoped) } else { colNames, args, err = genCols(session.Statement.RefTable, session, bean, true, true) if err != nil { return 0, err } } } else if isMap { colNames = make([]string, 0) args = make([]interface{}, 0) bValue := reflect.Indirect(reflect.ValueOf(bean)) for _, v := range bValue.MapKeys() { colNames = append(colNames, session.Engine.Quote(v.String())+" = ?") args = append(args, bValue.MapIndex(v).Interface()) } } else { return 0, ErrParamsType } table := session.Statement.RefTable if session.Statement.UseAutoTime && table != nil && table.Updated != "" { colNames = append(colNames, session.Engine.Quote(table.Updated)+" = ?") col := table.UpdatedColumn() val, t := session.Engine.NowTime2(col.SQLType.Name) args = append(args, val) var colName = col.Name if isStruct { session.afterClosures = append(session.afterClosures, func(bean interface{}) { col := table.GetColumn(colName) setColumnTime(bean, col, t) }) } } //for update action to like "column = column + ?" incColumns := session.Statement.getInc() for _, v := range incColumns { colNames = append(colNames, session.Engine.Quote(v.colName)+" = "+session.Engine.Quote(v.colName)+" + ?") args = append(args, v.arg) } //for update action to like "column = column - ?" decColumns := session.Statement.getDec() for _, v := range decColumns { colNames = append(colNames, session.Engine.Quote(v.colName)+" = "+session.Engine.Quote(v.colName)+" - ?") args = append(args, v.arg) } //for update action to like "column = expression" exprColumns := session.Statement.getExpr() for _, v := range exprColumns { colNames = append(colNames, session.Engine.Quote(v.colName)+" = "+v.expr) } var condiColNames []string var condiArgs []interface{} if !session.Statement.noAutoCondition && len(condiBean) > 0 { condiColNames, condiArgs = session.Statement.buildConditions(session.Statement.RefTable, condiBean[0], true, true, false, true, false) } var condition = "" session.Statement.processIdParam() st := session.Statement defer session.resetStatement() if st.WhereStr != "" { condition = fmt.Sprintf("%v", st.WhereStr) } if condition == "" { if len(condiColNames) > 0 { condition = fmt.Sprintf("%v", strings.Join(condiColNames, " "+session.Engine.Dialect().AndStr()+" ")) } } else { if len(condiColNames) > 0 { condition = fmt.Sprintf("(%v) %v (%v)", condition, session.Engine.Dialect().AndStr(), strings.Join(condiColNames, " "+session.Engine.Dialect().AndStr()+" ")) } } var sqlStr, inSQL string var inArgs []interface{} doIncVer := false var verValue *reflect.Value if table != nil && table.Version != "" && session.Statement.checkVersion { if condition != "" { condition = fmt.Sprintf("WHERE (%v) %v %v = ?", condition, session.Engine.Dialect().AndStr(), session.Engine.Quote(table.Version)) } else { condition = fmt.Sprintf("WHERE %v = ?", session.Engine.Quote(table.Version)) } inSQL, inArgs = session.Statement.genInSql() if len(inSQL) > 0 { if condition != "" { condition += " " + session.Engine.Dialect().AndStr() + " " + inSQL } else { condition = "WHERE " + inSQL } } if st.LimitN > 0 { condition = condition + fmt.Sprintf(" LIMIT %d", st.LimitN) } sqlStr = fmt.Sprintf("UPDATE %v SET %v, %v %v", session.Engine.Quote(session.Statement.TableName()), strings.Join(colNames, ", "), session.Engine.Quote(table.Version)+" = "+session.Engine.Quote(table.Version)+" + 1", condition) verValue, err = table.VersionColumn().ValueOf(bean) if err != nil { return 0, err } condiArgs = append(condiArgs, verValue.Interface()) doIncVer = true } else { if condition != "" { condition = "WHERE " + condition } inSQL, inArgs = session.Statement.genInSql() if len(inSQL) > 0 { if condition != "" { condition += " " + session.Engine.Dialect().AndStr() + " " + inSQL } else { condition = "WHERE " + inSQL } } if st.LimitN > 0 { condition = condition + fmt.Sprintf(" LIMIT %d", st.LimitN) } sqlStr = fmt.Sprintf("UPDATE %v SET %v %v", session.Engine.Quote(session.Statement.TableName()), strings.Join(colNames, ", "), condition) } args = append(args, st.Params...) args = append(args, inArgs...) args = append(args, condiArgs...) res, err := session.exec(sqlStr, args...) if err != nil { return 0, err } else if doIncVer { if verValue != nil && verValue.IsValid() && verValue.CanSet() { verValue.SetInt(verValue.Int() + 1) } } if table != nil { if cacher := session.Engine.getCacher2(table); cacher != nil && session.Statement.UseCache { cacher.ClearIds(session.Statement.TableName()) cacher.ClearBeans(session.Statement.TableName()) } } // handle after update processors if session.IsAutoCommit { for _, closure := range session.afterClosures { closure(bean) } if processor, ok := interface{}(bean).(AfterUpdateProcessor); ok { session.Engine.logger.Debug("[event]", session.Statement.TableName(), " has after update processor") processor.AfterUpdate() } } else { lenAfterClosures := len(session.afterClosures) if lenAfterClosures > 0 { if value, has := session.afterUpdateBeans[bean]; has && value != nil { *value = append(*value, session.afterClosures...) } else { afterClosures := make([]func(interface{}), lenAfterClosures) copy(afterClosures, session.afterClosures) // FIXME: if bean is a map type, it will panic because map cannot be as map key session.afterUpdateBeans[bean] = &afterClosures } } else { if _, ok := interface{}(bean).(AfterInsertProcessor); ok { session.afterUpdateBeans[bean] = nil } } } cleanupProcessorsClosures(&session.afterClosures) // cleanup after used // -- return res.RowsAffected() } func (session *Session) cacheDelete(sqlStr string, args ...interface{}) error { if session.Statement.RefTable == nil || session.Tx != nil { return ErrCacheFailed } for _, filter := range session.Engine.dialect.Filters() { sqlStr = filter.Do(sqlStr, session.Engine.dialect, session.Statement.RefTable) } newsql := session.Statement.convertIdSql(sqlStr) if newsql == "" { return ErrCacheFailed } cacher := session.Engine.getCacher2(session.Statement.RefTable) tableName := session.Statement.TableName() ids, err := core.GetCacheSql(cacher, tableName, newsql, args) if err != nil { resultsSlice, err := session.query(newsql, args...) if err != nil { return err } ids = make([]core.PK, 0) if len(resultsSlice) > 0 { for _, data := range resultsSlice { var id int64 var pk core.PK = make([]interface{}, 0) for _, col := range session.Statement.RefTable.PKColumns() { if v, ok := data[col.Name]; !ok { return errors.New("no id") } else if col.SQLType.IsText() { pk = append(pk, string(v)) } else if col.SQLType.IsNumeric() { id, err = strconv.ParseInt(string(v), 10, 64) if err != nil { return err } pk = append(pk, id) } else { return errors.New("not supported primary key type") } } ids = append(ids, pk) } } } /*else { session.Engine.LogDebug("delete cache sql %v", newsql) cacher.DelIds(tableName, genSqlKey(newsql, args)) }*/ for _, id := range ids { session.Engine.logger.Debug("[cacheDelete] delete cache obj", tableName, id) sid, err := id.ToString() if err != nil { return err } cacher.DelBean(tableName, sid) } session.Engine.logger.Debug("[cacheDelete] clear cache sql", tableName) cacher.ClearIds(tableName) return nil } // Delete records, bean's non-empty fields are conditions func (session *Session) Delete(bean interface{}) (int64, error) { defer session.resetStatement() if session.IsAutoClose { defer session.Close() } session.Statement.setRefValue(rValue(bean)) var table = session.Statement.RefTable // handle before delete processors for _, closure := range session.beforeClosures { closure(bean) } cleanupProcessorsClosures(&session.beforeClosures) if processor, ok := interface{}(bean).(BeforeDeleteProcessor); ok { processor.BeforeDelete() } // -- var colNames []string var args []interface{} if !session.Statement.noAutoCondition { colNames, args = session.Statement.buildConditions(table, bean, true, true, false, true, false) } var condition = "" var andStr = session.Engine.dialect.AndStr() session.Statement.processIdParam() if session.Statement.WhereStr != "" { condition = session.Statement.WhereStr if len(colNames) > 0 { condition += " " + andStr + " " + strings.Join(colNames, " "+andStr+" ") } } else { condition = strings.Join(colNames, " "+andStr+" ") } inSQL, inArgs := session.Statement.genInSql() if len(inSQL) > 0 { if len(condition) > 0 { condition += " " + andStr + " " } condition += inSQL args = append(args, inArgs...) } if len(condition) == 0 && session.Statement.LimitN == 0 { return 0, ErrNeedDeletedCond } var deleteSQL, realSQL string var tableName = session.Engine.Quote(session.Statement.TableName()) if len(condition) > 0 { deleteSQL = fmt.Sprintf("DELETE FROM %v WHERE %v", tableName, condition) } else { deleteSQL = fmt.Sprintf("DELETE FROM %v", tableName) } var orderSQL string if len(session.Statement.OrderStr) > 0 { orderSQL += fmt.Sprintf(" ORDER BY %s", session.Statement.OrderStr) } if session.Statement.LimitN > 0 { orderSQL += fmt.Sprintf(" LIMIT %d", session.Statement.LimitN) } if len(orderSQL) > 0 { switch session.Engine.dialect.DBType() { case core.POSTGRES: inSQL := fmt.Sprintf("ctid IN (SELECT ctid FROM %s%s)", tableName, orderSQL) if len(condition) > 0 { deleteSQL += " AND " + inSQL } else { deleteSQL += " WHERE " + inSQL } case core.SQLITE: inSQL := fmt.Sprintf("rowid IN (SELECT rowid FROM %s%s)", tableName, orderSQL) if len(condition) > 0 { deleteSQL += " AND " + inSQL } else { deleteSQL += " WHERE " + inSQL } // TODO: how to handle delete limit on mssql? case core.MSSQL: return 0, ErrNotImplemented default: deleteSQL += orderSQL } } argsForCache := make([]interface{}, 0, len(args)*2) if session.Statement.unscoped || table.DeletedColumn() == nil { // tag "deleted" is disabled realSQL = deleteSQL copy(argsForCache, args) argsForCache = append(session.Statement.Params, argsForCache...) } else { // !oinume! sqlStrForCache and argsForCache is needed to behave as executing "DELETE FROM ..." for cache. copy(argsForCache, args) argsForCache = append(session.Statement.Params, argsForCache...) deletedColumn := table.DeletedColumn() realSQL = fmt.Sprintf("UPDATE %v SET %v = ? WHERE %v", session.Engine.Quote(session.Statement.TableName()), session.Engine.Quote(deletedColumn.Name), condition) if len(orderSQL) > 0 { switch session.Engine.dialect.DBType() { case core.POSTGRES: inSQL := fmt.Sprintf("ctid IN (SELECT ctid FROM %s%s)", tableName, orderSQL) if len(condition) > 0 { realSQL += " AND " + inSQL } else { realSQL += " WHERE " + inSQL } case core.SQLITE: inSQL := fmt.Sprintf("rowid IN (SELECT rowid FROM %s%s)", tableName, orderSQL) if len(condition) > 0 { realSQL += " AND " + inSQL } else { realSQL += " WHERE " + inSQL } // TODO: how to handle delete limit on mssql? case core.MSSQL: return 0, ErrNotImplemented default: realSQL += orderSQL } } // !oinume! Insert NowTime to the head of session.Statement.Params session.Statement.Params = append(session.Statement.Params, "") paramsLen := len(session.Statement.Params) copy(session.Statement.Params[1:paramsLen], session.Statement.Params[0:paramsLen-1]) val, t := session.Engine.NowTime2(deletedColumn.SQLType.Name) session.Statement.Params[0] = val var colName = deletedColumn.Name session.afterClosures = append(session.afterClosures, func(bean interface{}) { col := table.GetColumn(colName) setColumnTime(bean, col, t) }) } args = append(session.Statement.Params, args...) if cacher := session.Engine.getCacher2(session.Statement.RefTable); cacher != nil && session.Statement.UseCache { session.cacheDelete(deleteSQL, argsForCache...) } res, err := session.exec(realSQL, args...) if err != nil { return 0, err } // handle after delete processors if session.IsAutoCommit { for _, closure := range session.afterClosures { closure(bean) } if processor, ok := interface{}(bean).(AfterDeleteProcessor); ok { processor.AfterDelete() } } else { lenAfterClosures := len(session.afterClosures) if lenAfterClosures > 0 { if value, has := session.afterDeleteBeans[bean]; has && value != nil { *value = append(*value, session.afterClosures...) } else { afterClosures := make([]func(interface{}), lenAfterClosures) copy(afterClosures, session.afterClosures) session.afterDeleteBeans[bean] = &afterClosures } } else { if _, ok := interface{}(bean).(AfterInsertProcessor); ok { session.afterDeleteBeans[bean] = nil } } } cleanupProcessorsClosures(&session.afterClosures) // -- return res.RowsAffected() } // saveLastSQL stores executed query information func (session *Session) saveLastSQL(sql string, args ...interface{}) { session.lastSQL = sql session.lastSQLArgs = args session.Engine.logSQL(sql, args...) } // LastSQL returns last query information func (session *Session) LastSQL() (string, []interface{}) { return session.lastSQL, session.lastSQLArgs } // tbName get some table's table name func (session *Session) tbNameNoSchema(table *core.Table) string { if len(session.Statement.AltTableName) > 0 { return session.Statement.AltTableName } return table.Name } // Sync2 synchronize structs to database tables func (session *Session) Sync2(beans ...interface{}) error { engine := session.Engine tables, err := engine.DBMetas() if err != nil { return err } var structTables []*core.Table for _, bean := range beans { v := rValue(bean) table := engine.mapType(v) structTables = append(structTables, table) var tbName = session.tbNameNoSchema(table) var oriTable *core.Table for _, tb := range tables { if equalNoCase(tb.Name, tbName) { oriTable = tb break } } if oriTable == nil { err = session.StoreEngine(session.Statement.StoreEngine).CreateTable(bean) if err != nil { return err } err = session.CreateUniques(bean) if err != nil { return err } err = session.CreateIndexes(bean) if err != nil { return err } } else { for _, col := range table.Columns() { var oriCol *core.Column for _, col2 := range oriTable.Columns() { if equalNoCase(col.Name, col2.Name) { oriCol = col2 break } } if oriCol != nil { expectedType := engine.dialect.SqlType(col) curType := engine.dialect.SqlType(oriCol) if expectedType != curType { if expectedType == core.Text && strings.HasPrefix(curType, core.Varchar) { // currently only support mysql & postgres if engine.dialect.DBType() == core.MYSQL || engine.dialect.DBType() == core.POSTGRES { engine.logger.Infof("Table %s column %s change type from %s to %s\n", tbName, col.Name, curType, expectedType) _, err = engine.Exec(engine.dialect.ModifyColumnSql(table.Name, col)) } else { engine.logger.Warnf("Table %s column %s db type is %s, struct type is %s\n", tbName, col.Name, curType, expectedType) } } else if strings.HasPrefix(curType, core.Varchar) && strings.HasPrefix(expectedType, core.Varchar) { if engine.dialect.DBType() == core.MYSQL { if oriCol.Length < col.Length { engine.logger.Infof("Table %s column %s change type from varchar(%d) to varchar(%d)\n", tbName, col.Name, oriCol.Length, col.Length) _, err = engine.Exec(engine.dialect.ModifyColumnSql(table.Name, col)) } } } else { if !(strings.HasPrefix(curType, expectedType) && curType[len(expectedType)] == '(') { engine.logger.Warnf("Table %s column %s db type is %s, struct type is %s", tbName, col.Name, curType, expectedType) } } } else if expectedType == core.Varchar { if engine.dialect.DBType() == core.MYSQL { if oriCol.Length < col.Length { engine.logger.Infof("Table %s column %s change type from varchar(%d) to varchar(%d)\n", tbName, col.Name, oriCol.Length, col.Length) _, err = engine.Exec(engine.dialect.ModifyColumnSql(table.Name, col)) } } } if col.Default != oriCol.Default { engine.logger.Warnf("Table %s Column %s db default is %s, struct default is %s", tbName, col.Name, oriCol.Default, col.Default) } if col.Nullable != oriCol.Nullable { engine.logger.Warnf("Table %s Column %s db nullable is %v, struct nullable is %v", tbName, col.Name, oriCol.Nullable, col.Nullable) } } else { session := engine.NewSession() session.Statement.RefTable = table session.Statement.tableName = tbName defer session.Close() err = session.addColumn(col.Name) } if err != nil { return err } } var foundIndexNames = make(map[string]bool) var addedNames = make(map[string]*core.Index) for name, index := range table.Indexes { var oriIndex *core.Index for name2, index2 := range oriTable.Indexes { if index.Equal(index2) { oriIndex = index2 foundIndexNames[name2] = true break } } if oriIndex != nil { if oriIndex.Type != index.Type { sql := engine.dialect.DropIndexSql(tbName, oriIndex) _, err = engine.Exec(sql) if err != nil { return err } oriIndex = nil } } if oriIndex == nil { addedNames[name] = index } } for name2, index2 := range oriTable.Indexes { if _, ok := foundIndexNames[name2]; !ok { sql := engine.dialect.DropIndexSql(tbName, index2) _, err = engine.Exec(sql) if err != nil { return err } } } for name, index := range addedNames { if index.Type == core.UniqueType { session := engine.NewSession() session.Statement.RefTable = table session.Statement.tableName = tbName defer session.Close() err = session.addUnique(tbName, name) } else if index.Type == core.IndexType { session := engine.NewSession() session.Statement.RefTable = table session.Statement.tableName = tbName defer session.Close() err = session.addIndex(tbName, name) } if err != nil { return err } } } } for _, table := range tables { var oriTable *core.Table for _, structTable := range structTables { if equalNoCase(table.Name, session.tbNameNoSchema(structTable)) { oriTable = structTable break } } if oriTable == nil { //engine.LogWarnf("Table %s has no struct to mapping it", table.Name) continue } for _, colName := range table.ColumnsSeq() { if oriTable.GetColumn(colName) == nil { engine.logger.Warnf("Table %s has column %s but struct has not related field", table.Name, colName) } } } return nil } // Unscoped always disable struct tag "deleted" func (session *Session) Unscoped() *Session { session.Statement.Unscoped() return session } ================================================ FILE: src/github.com/go-xorm/xorm/sqlite3_dialect.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "database/sql" "errors" "fmt" "regexp" "strings" "github.com/go-xorm/core" ) // func init() { // RegisterDialect("sqlite3", &sqlite3{}) // } var ( sqlite3ReservedWords = map[string]bool{ "ABORT": true, "ACTION": true, "ADD": true, "AFTER": true, "ALL": true, "ALTER": true, "ANALYZE": true, "AND": true, "AS": true, "ASC": true, "ATTACH": true, "AUTOINCREMENT": true, "BEFORE": true, "BEGIN": true, "BETWEEN": true, "BY": true, "CASCADE": true, "CASE": true, "CAST": true, "CHECK": true, "COLLATE": true, "COLUMN": true, "COMMIT": true, "CONFLICT": true, "CONSTRAINT": true, "CREATE": true, "CROSS": true, "CURRENT_DATE": true, "CURRENT_TIME": true, "CURRENT_TIMESTAMP": true, "DATABASE": true, "DEFAULT": true, "DEFERRABLE": true, "DEFERRED": true, "DELETE": true, "DESC": true, "DETACH": true, "DISTINCT": true, "DROP": true, "EACH": true, "ELSE": true, "END": true, "ESCAPE": true, "EXCEPT": true, "EXCLUSIVE": true, "EXISTS": true, "EXPLAIN": true, "FAIL": true, "FOR": true, "FOREIGN": true, "FROM": true, "FULL": true, "GLOB": true, "GROUP": true, "HAVING": true, "IF": true, "IGNORE": true, "IMMEDIATE": true, "IN": true, "INDEX": true, "INDEXED": true, "INITIALLY": true, "INNER": true, "INSERT": true, "INSTEAD": true, "INTERSECT": true, "INTO": true, "IS": true, "ISNULL": true, "JOIN": true, "KEY": true, "LEFT": true, "LIKE": true, "LIMIT": true, "MATCH": true, "NATURAL": true, "NO": true, "NOT": true, "NOTNULL": true, "NULL": true, "OF": true, "OFFSET": true, "ON": true, "OR": true, "ORDER": true, "OUTER": true, "PLAN": true, "PRAGMA": true, "PRIMARY": true, "QUERY": true, "RAISE": true, "RECURSIVE": true, "REFERENCES": true, "REGEXP": true, "REINDEX": true, "RELEASE": true, "RENAME": true, "REPLACE": true, "RESTRICT": true, "RIGHT": true, "ROLLBACK": true, "ROW": true, "SAVEPOINT": true, "SELECT": true, "SET": true, "TABLE": true, "TEMP": true, "TEMPORARY": true, "THEN": true, "TO": true, "TRANSACTI": true, "TRIGGER": true, "UNION": true, "UNIQUE": true, "UPDATE": true, "USING": true, "VACUUM": true, "VALUES": true, "VIEW": true, "VIRTUAL": true, "WHEN": true, "WHERE": true, "WITH": true, "WITHOUT": true, } ) type sqlite3 struct { core.Base } func (db *sqlite3) Init(d *core.DB, uri *core.Uri, drivername, dataSourceName string) error { return db.Base.Init(d, db, uri, drivername, dataSourceName) } func (db *sqlite3) SqlType(c *core.Column) string { switch t := c.SQLType.Name; t { case core.Bool: if c.Default == "true" { c.Default = "1" } else if c.Default == "false" { c.Default = "0" } return core.Integer case core.Date, core.DateTime, core.TimeStamp, core.Time: return core.DateTime case core.TimeStampz: return core.Text case core.Char, core.Varchar, core.NVarchar, core.TinyText, core.Text, core.MediumText, core.LongText, core.Json: return core.Text case core.Bit, core.TinyInt, core.SmallInt, core.MediumInt, core.Int, core.Integer, core.BigInt: return core.Integer case core.Float, core.Double, core.Real: return core.Real case core.Decimal, core.Numeric: return core.Numeric case core.TinyBlob, core.Blob, core.MediumBlob, core.LongBlob, core.Bytea, core.Binary, core.VarBinary: return core.Blob case core.Serial, core.BigSerial: c.IsPrimaryKey = true c.IsAutoIncrement = true c.Nullable = false return core.Integer default: return t } } func (db *sqlite3) FormatBytes(bs []byte) string { return fmt.Sprintf("X'%x'", bs) } func (db *sqlite3) SupportInsertMany() bool { return true } func (db *sqlite3) IsReserved(name string) bool { _, ok := sqlite3ReservedWords[name] return ok } func (db *sqlite3) Quote(name string) string { return "`" + name + "`" } func (db *sqlite3) QuoteStr() string { return "`" } func (db *sqlite3) AutoIncrStr() string { return "AUTOINCREMENT" } func (db *sqlite3) SupportEngine() bool { return false } func (db *sqlite3) SupportCharset() bool { return false } func (db *sqlite3) IndexOnTable() bool { return false } func (db *sqlite3) IndexCheckSql(tableName, idxName string) (string, []interface{}) { args := []interface{}{idxName} return "SELECT name FROM sqlite_master WHERE type='index' and name = ?", args } func (db *sqlite3) TableCheckSql(tableName string) (string, []interface{}) { args := []interface{}{tableName} return "SELECT name FROM sqlite_master WHERE type='table' and name = ?", args } func (db *sqlite3) DropIndexSql(tableName string, index *core.Index) string { quote := db.Quote //var unique string var idxName string = index.Name if !strings.HasPrefix(idxName, "UQE_") && !strings.HasPrefix(idxName, "IDX_") { if index.Type == core.UniqueType { idxName = fmt.Sprintf("UQE_%v_%v", tableName, index.Name) } else { idxName = fmt.Sprintf("IDX_%v_%v", tableName, index.Name) } } return fmt.Sprintf("DROP INDEX %v", quote(idxName)) } func (db *sqlite3) ForUpdateSql(query string) string { return query } /*func (db *sqlite3) ColumnCheckSql(tableName, colName string) (string, []interface{}) { args := []interface{}{tableName} sql := "SELECT name FROM sqlite_master WHERE type='table' and name = ? and ((sql like '%`" + colName + "`%') or (sql like '%[" + colName + "]%'))" return sql, args }*/ func (db *sqlite3) IsColumnExist(tableName, colName string) (bool, error) { args := []interface{}{tableName} query := "SELECT name FROM sqlite_master WHERE type='table' and name = ? and ((sql like '%`" + colName + "`%') or (sql like '%[" + colName + "]%'))" db.LogSQL(query, args) rows, err := db.DB().Query(query, args...) if err != nil { return false, err } defer rows.Close() if rows.Next() { return true, nil } return false, nil } func (db *sqlite3) GetColumns(tableName string) ([]string, map[string]*core.Column, error) { args := []interface{}{tableName} s := "SELECT sql FROM sqlite_master WHERE type='table' and name = ?" db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, nil, err } defer rows.Close() var name string for rows.Next() { err = rows.Scan(&name) if err != nil { return nil, nil, err } break } if name == "" { return nil, nil, errors.New("no table named " + tableName) } nStart := strings.Index(name, "(") nEnd := strings.LastIndex(name, ")") reg := regexp.MustCompile(`[^\(,\)]*(\([^\(]*\))?`) colCreates := reg.FindAllString(name[nStart+1:nEnd], -1) cols := make(map[string]*core.Column) colSeq := make([]string, 0) for _, colStr := range colCreates { reg = regexp.MustCompile(`,\s`) colStr = reg.ReplaceAllString(colStr, ",") fields := strings.Fields(strings.TrimSpace(colStr)) col := new(core.Column) col.Indexes = make(map[string]int) col.Nullable = true col.DefaultIsEmpty = true for idx, field := range fields { if idx == 0 { col.Name = strings.Trim(field, "`[] ") continue } else if idx == 1 { col.SQLType = core.SQLType{field, 0, 0} } switch field { case "PRIMARY": col.IsPrimaryKey = true case "AUTOINCREMENT": col.IsAutoIncrement = true case "NULL": if fields[idx-1] == "NOT" { col.Nullable = false } else { col.Nullable = true } case "DEFAULT": col.Default = fields[idx+1] col.DefaultIsEmpty = false } } if !col.SQLType.IsNumeric() && !col.DefaultIsEmpty { col.Default = "'" + col.Default + "'" } cols[col.Name] = col colSeq = append(colSeq, col.Name) } return colSeq, cols, nil } func (db *sqlite3) GetTables() ([]*core.Table, error) { args := []interface{}{} s := "SELECT name FROM sqlite_master WHERE type='table'" db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, err } defer rows.Close() tables := make([]*core.Table, 0) for rows.Next() { table := core.NewEmptyTable() err = rows.Scan(&table.Name) if err != nil { return nil, err } if table.Name == "sqlite_sequence" { continue } tables = append(tables, table) } return tables, nil } func (db *sqlite3) GetIndexes(tableName string) (map[string]*core.Index, error) { args := []interface{}{tableName} s := "SELECT sql FROM sqlite_master WHERE type='index' and tbl_name = ?" db.LogSQL(s, args) rows, err := db.DB().Query(s, args...) if err != nil { return nil, err } defer rows.Close() indexes := make(map[string]*core.Index, 0) for rows.Next() { var tmpSql sql.NullString err = rows.Scan(&tmpSql) if err != nil { return nil, err } if !tmpSql.Valid { continue } sql := tmpSql.String index := new(core.Index) nNStart := strings.Index(sql, "INDEX") nNEnd := strings.Index(sql, "ON") if nNStart == -1 || nNEnd == -1 { continue } indexName := strings.Trim(sql[nNStart+6:nNEnd], "` []") if strings.HasPrefix(indexName, "IDX_"+tableName) || strings.HasPrefix(indexName, "UQE_"+tableName) { index.Name = indexName[5+len(tableName) : len(indexName)] } else { index.Name = indexName } if strings.HasPrefix(sql, "CREATE UNIQUE INDEX") { index.Type = core.UniqueType } else { index.Type = core.IndexType } nStart := strings.Index(sql, "(") nEnd := strings.Index(sql, ")") colIndexes := strings.Split(sql[nStart+1:nEnd], ",") index.Cols = make([]string, 0) for _, col := range colIndexes { index.Cols = append(index.Cols, strings.Trim(col, "` []")) } indexes[index.Name] = index } return indexes, nil } func (db *sqlite3) Filters() []core.Filter { return []core.Filter{&core.IdFilter{}} } ================================================ FILE: src/github.com/go-xorm/xorm/sqlite3_driver.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "github.com/go-xorm/core" ) // func init() { // core.RegisterDriver("sqlite3", &sqlite3Driver{}) // } type sqlite3Driver struct { } func (p *sqlite3Driver) Parse(driverName, dataSourceName string) (*core.Uri, error) { return &core.Uri{DbType: core.SQLITE, DbName: dataSourceName}, nil } ================================================ FILE: src/github.com/go-xorm/xorm/statement.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "bytes" "database/sql/driver" "encoding/json" "errors" "fmt" "reflect" "strings" "time" "github.com/go-xorm/core" ) type inParam struct { colName string args []interface{} } type incrParam struct { colName string arg interface{} } type decrParam struct { colName string arg interface{} } type exprParam struct { colName string expr string } // Statement save all the sql info for executing SQL type Statement struct { RefTable *core.Table Engine *Engine Start int LimitN int WhereStr string IdParam *core.PK Params []interface{} OrderStr string JoinStr string joinArgs []interface{} GroupByStr string HavingStr string ColumnStr string selectStr string columnMap map[string]bool useAllCols bool OmitStr string ConditionStr string AltTableName string tableName string RawSQL string RawParams []interface{} UseCascade bool UseAutoJoin bool StoreEngine string Charset string BeanArgs []interface{} UseCache bool UseAutoTime bool noAutoCondition bool IsDistinct bool IsForUpdate bool TableAlias string allUseBool bool checkVersion bool unscoped bool mustColumnMap map[string]bool nullableMap map[string]bool inColumns map[string]*inParam incrColumns map[string]incrParam decrColumns map[string]decrParam exprColumns map[string]exprParam } // Init reset all the statment's fields func (statement *Statement) Init() { statement.RefTable = nil statement.Start = 0 statement.LimitN = 0 statement.WhereStr = "" statement.Params = make([]interface{}, 0) statement.OrderStr = "" statement.UseCascade = true statement.JoinStr = "" statement.joinArgs = make([]interface{}, 0) statement.GroupByStr = "" statement.HavingStr = "" statement.ColumnStr = "" statement.OmitStr = "" statement.columnMap = make(map[string]bool) statement.ConditionStr = "" statement.AltTableName = "" statement.tableName = "" statement.IdParam = nil statement.RawSQL = "" statement.RawParams = make([]interface{}, 0) statement.BeanArgs = make([]interface{}, 0) statement.UseCache = true statement.UseAutoTime = true statement.noAutoCondition = false statement.IsDistinct = false statement.IsForUpdate = false statement.TableAlias = "" statement.selectStr = "" statement.allUseBool = false statement.useAllCols = false statement.mustColumnMap = make(map[string]bool) statement.nullableMap = make(map[string]bool) statement.checkVersion = true statement.unscoped = false statement.inColumns = make(map[string]*inParam) statement.incrColumns = make(map[string]incrParam) statement.decrColumns = make(map[string]decrParam) statement.exprColumns = make(map[string]exprParam) } // NoAutoCondition if you do not want convert bean's field as query condition, then use this function func (statement *Statement) NoAutoCondition(no ...bool) *Statement { statement.noAutoCondition = true if len(no) > 0 { statement.noAutoCondition = no[0] } return statement } // Sql add the raw sql statement func (statement *Statement) Sql(querystring string, args ...interface{}) *Statement { statement.RawSQL = querystring statement.RawParams = args return statement } // Alias set the table alias func (statement *Statement) Alias(alias string) *Statement { statement.TableAlias = alias return statement } // Where add Where statment func (statement *Statement) Where(querystring string, args ...interface{}) *Statement { // The second where will be triggered as And if len(statement.WhereStr) > 0 { return statement.And(querystring, args...) } if !strings.Contains(querystring, statement.Engine.dialect.EqStr()) { querystring = strings.Replace(querystring, "=", statement.Engine.dialect.EqStr(), -1) } statement.WhereStr = querystring statement.Params = args return statement } // And add Where & and statment func (statement *Statement) And(querystring string, args ...interface{}) *Statement { if len(statement.WhereStr) > 0 { var buf bytes.Buffer fmt.Fprintf(&buf, "(%v) %s (%v)", statement.WhereStr, statement.Engine.dialect.AndStr(), querystring) statement.WhereStr = buf.String() } else { statement.WhereStr = querystring } statement.Params = append(statement.Params, args...) return statement } // Or add Where & Or statment func (statement *Statement) Or(querystring string, args ...interface{}) *Statement { if len(statement.WhereStr) > 0 { var buf bytes.Buffer fmt.Fprintf(&buf, "(%v) %s (%v)", statement.WhereStr, statement.Engine.dialect.OrStr(), querystring) statement.WhereStr = buf.String() } else { statement.WhereStr = querystring } statement.Params = append(statement.Params, args...) return statement } func (statement *Statement) setRefValue(v reflect.Value) { statement.RefTable = statement.Engine.autoMapType(v) statement.tableName = statement.Engine.tbName(v) } // Table tempororily set table name, the parameter could be a string or a pointer of struct func (statement *Statement) Table(tableNameOrBean interface{}) *Statement { v := rValue(tableNameOrBean) t := v.Type() if t.Kind() == reflect.String { statement.AltTableName = tableNameOrBean.(string) } else if t.Kind() == reflect.Struct { statement.RefTable = statement.Engine.autoMapType(v) statement.AltTableName = statement.Engine.tbName(v) } return statement } // Auto generating update columnes and values according a struct func buildUpdates(engine *Engine, table *core.Table, bean interface{}, includeVersion bool, includeUpdated bool, includeNil bool, includeAutoIncr bool, allUseBool bool, useAllCols bool, mustColumnMap map[string]bool, nullableMap map[string]bool, columnMap map[string]bool, update, unscoped bool) ([]string, []interface{}) { var colNames = make([]string, 0) var args = make([]interface{}, 0) for _, col := range table.Columns() { if !includeVersion && col.IsVersion { continue } if col.IsCreated { continue } if !includeUpdated && col.IsUpdated { continue } if !includeAutoIncr && col.IsAutoIncrement { continue } if col.IsDeleted && !unscoped { continue } if use, ok := columnMap[col.Name]; ok && !use { continue } fieldValuePtr, err := col.ValueOf(bean) if err != nil { engine.logger.Error(err) continue } fieldValue := *fieldValuePtr fieldType := reflect.TypeOf(fieldValue.Interface()) requiredField := useAllCols includeNil := useAllCols lColName := strings.ToLower(col.Name) if b, ok := mustColumnMap[lColName]; ok { if b { requiredField = true } else { continue } } // !evalphobia! set fieldValue as nil when column is nullable and zero-value if b, ok := nullableMap[lColName]; ok { if b && col.Nullable && isZero(fieldValue.Interface()) { var nilValue *int fieldValue = reflect.ValueOf(nilValue) fieldType = reflect.TypeOf(fieldValue.Interface()) includeNil = true } } var val interface{} if fieldValue.CanAddr() { if structConvert, ok := fieldValue.Addr().Interface().(core.Conversion); ok { data, err := structConvert.ToDB() if err != nil { engine.logger.Error(err) } else { val = data } goto APPEND } } if structConvert, ok := fieldValue.Interface().(core.Conversion); ok { data, err := structConvert.ToDB() if err != nil { engine.logger.Error(err) } else { val = data } goto APPEND } if fieldType.Kind() == reflect.Ptr { if fieldValue.IsNil() { if includeNil { args = append(args, nil) colNames = append(colNames, fmt.Sprintf("%v=?", engine.Quote(col.Name))) } continue } else if !fieldValue.IsValid() { continue } else { // dereference ptr type to instance type fieldValue = fieldValue.Elem() fieldType = reflect.TypeOf(fieldValue.Interface()) requiredField = true } } switch fieldType.Kind() { case reflect.Bool: if allUseBool || requiredField { val = fieldValue.Interface() } else { // if a bool in a struct, it will not be as a condition because it default is false, // please use Where() instead continue } case reflect.String: if !requiredField && fieldValue.String() == "" { continue } // for MyString, should convert to string or panic if fieldType.String() != reflect.String.String() { val = fieldValue.String() } else { val = fieldValue.Interface() } case reflect.Int8, reflect.Int16, reflect.Int, reflect.Int32, reflect.Int64: if !requiredField && fieldValue.Int() == 0 { continue } val = fieldValue.Interface() case reflect.Float32, reflect.Float64: if !requiredField && fieldValue.Float() == 0.0 { continue } val = fieldValue.Interface() case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64: if !requiredField && fieldValue.Uint() == 0 { continue } t := int64(fieldValue.Uint()) val = reflect.ValueOf(&t).Interface() case reflect.Struct: if fieldType.ConvertibleTo(core.TimeType) { t := fieldValue.Convert(core.TimeType).Interface().(time.Time) if !requiredField && (t.IsZero() || !fieldValue.IsValid()) { continue } val = engine.FormatTime(col.SQLType.Name, t) } else if nulType, ok := fieldValue.Interface().(driver.Valuer); ok { val, _ = nulType.Value() } else { if !col.SQLType.IsJson() { engine.autoMapType(fieldValue) if table, ok := engine.Tables[fieldValue.Type()]; ok { if len(table.PrimaryKeys) == 1 { pkField := reflect.Indirect(fieldValue).FieldByName(table.PKColumns()[0].FieldName) // fix non-int pk issues if pkField.IsValid() && (!requiredField && !isZero(pkField.Interface())) { val = pkField.Interface() } else { continue } } else { //TODO: how to handler? panic("not supported") } } else { val = fieldValue.Interface() } } else { // Blank struct could not be as update data if requiredField || !isStructZero(fieldValue) { bytes, err := json.Marshal(fieldValue.Interface()) if err != nil { panic(fmt.Sprintf("mashal %v failed", fieldValue.Interface())) } if col.SQLType.IsText() { val = string(bytes) } else if col.SQLType.IsBlob() { val = bytes } } else { continue } } } case reflect.Array, reflect.Slice, reflect.Map: if !requiredField { if fieldValue == reflect.Zero(fieldType) { continue } if fieldValue.IsNil() || !fieldValue.IsValid() || fieldValue.Len() == 0 { continue } } if col.SQLType.IsText() { bytes, err := json.Marshal(fieldValue.Interface()) if err != nil { engine.logger.Error(err) continue } val = string(bytes) } else if col.SQLType.IsBlob() { var bytes []byte var err error if (fieldType.Kind() == reflect.Array || fieldType.Kind() == reflect.Slice) && fieldType.Elem().Kind() == reflect.Uint8 { if fieldValue.Len() > 0 { val = fieldValue.Bytes() } else { continue } } else { bytes, err = json.Marshal(fieldValue.Interface()) if err != nil { engine.logger.Error(err) continue } val = bytes } } else { continue } default: val = fieldValue.Interface() } APPEND: //fmt.Println("==", col.Name, "==", fmt.Sprintf("%v", val)) args = append(args, val) if col.IsPrimaryKey && engine.dialect.DBType() == "ql" { continue } colNames = append(colNames, fmt.Sprintf("%v = ?", engine.Quote(col.Name))) } return colNames, args } func (statement *Statement) needTableName() bool { return len(statement.JoinStr) > 0 } func (statement *Statement) colName(col *core.Column, tableName string) string { if statement.needTableName() { var nm = tableName if len(statement.TableAlias) > 0 { nm = statement.TableAlias } return statement.Engine.Quote(nm) + "." + statement.Engine.Quote(col.Name) } return statement.Engine.Quote(col.Name) } // Auto generating conditions according a struct func buildConditions(engine *Engine, table *core.Table, bean interface{}, includeVersion bool, includeUpdated bool, includeNil bool, includeAutoIncr bool, allUseBool bool, useAllCols bool, unscoped bool, mustColumnMap map[string]bool, tableName, aliasName string, addedTableName bool) ([]string, []interface{}) { var colNames []string var args = make([]interface{}, 0) for _, col := range table.Columns() { if !includeVersion && col.IsVersion { continue } if !includeUpdated && col.IsUpdated { continue } if !includeAutoIncr && col.IsAutoIncrement { continue } if engine.dialect.DBType() == core.MSSQL && col.SQLType.Name == core.Text { continue } if col.SQLType.IsJson() { continue } var colName string if addedTableName { var nm = tableName if len(aliasName) > 0 { nm = aliasName } colName = engine.Quote(nm) + "." + engine.Quote(col.Name) } else { colName = engine.Quote(col.Name) } fieldValuePtr, err := col.ValueOf(bean) if err != nil { engine.logger.Error(err) continue } if col.IsDeleted && !unscoped { // tag "deleted" is enabled colNames = append(colNames, fmt.Sprintf("(%v IS NULL OR %v = '0001-01-01 00:00:00')", colName, colName)) } fieldValue := *fieldValuePtr if fieldValue.Interface() == nil { continue } fieldType := reflect.TypeOf(fieldValue.Interface()) requiredField := useAllCols if b, ok := mustColumnMap[strings.ToLower(col.Name)]; ok { if b { requiredField = true } else { continue } } if fieldType.Kind() == reflect.Ptr { if fieldValue.IsNil() { if includeNil { args = append(args, nil) colNames = append(colNames, fmt.Sprintf("%v %s ?", colName, engine.dialect.EqStr())) } continue } else if !fieldValue.IsValid() { continue } else { // dereference ptr type to instance type fieldValue = fieldValue.Elem() fieldType = reflect.TypeOf(fieldValue.Interface()) requiredField = true } } var val interface{} switch fieldType.Kind() { case reflect.Bool: if allUseBool || requiredField { val = fieldValue.Interface() } else { // if a bool in a struct, it will not be as a condition because it default is false, // please use Where() instead continue } case reflect.String: if !requiredField && fieldValue.String() == "" { continue } // for MyString, should convert to string or panic if fieldType.String() != reflect.String.String() { val = fieldValue.String() } else { val = fieldValue.Interface() } case reflect.Int8, reflect.Int16, reflect.Int, reflect.Int32, reflect.Int64: if !requiredField && fieldValue.Int() == 0 { continue } val = fieldValue.Interface() case reflect.Float32, reflect.Float64: if !requiredField && fieldValue.Float() == 0.0 { continue } val = fieldValue.Interface() case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64: if !requiredField && fieldValue.Uint() == 0 { continue } t := int64(fieldValue.Uint()) val = reflect.ValueOf(&t).Interface() case reflect.Struct: if fieldType.ConvertibleTo(core.TimeType) { t := fieldValue.Convert(core.TimeType).Interface().(time.Time) if !requiredField && (t.IsZero() || !fieldValue.IsValid()) { continue } val = engine.FormatTime(col.SQLType.Name, t) } else if _, ok := reflect.New(fieldType).Interface().(core.Conversion); ok { continue } else if valNul, ok := fieldValue.Interface().(driver.Valuer); ok { val, _ = valNul.Value() if val == nil { continue } } else { if col.SQLType.IsJson() { if col.SQLType.IsText() { bytes, err := json.Marshal(fieldValue.Interface()) if err != nil { engine.logger.Error(err) continue } val = string(bytes) } else if col.SQLType.IsBlob() { var bytes []byte var err error bytes, err = json.Marshal(fieldValue.Interface()) if err != nil { engine.logger.Error(err) continue } val = bytes } } else { engine.autoMapType(fieldValue) if table, ok := engine.Tables[fieldValue.Type()]; ok { if len(table.PrimaryKeys) == 1 { pkField := reflect.Indirect(fieldValue).FieldByName(table.PKColumns()[0].FieldName) // fix non-int pk issues //if pkField.Int() != 0 { if pkField.IsValid() && !isZero(pkField.Interface()) { val = pkField.Interface() } else { continue } } else { //TODO: how to handler? panic(fmt.Sprintln("not supported", fieldValue.Interface(), "as", table.PrimaryKeys)) } } else { val = fieldValue.Interface() } } } case reflect.Array, reflect.Slice, reflect.Map: if fieldValue == reflect.Zero(fieldType) { continue } if fieldValue.IsNil() || !fieldValue.IsValid() || fieldValue.Len() == 0 { continue } if col.SQLType.IsText() { bytes, err := json.Marshal(fieldValue.Interface()) if err != nil { engine.logger.Error(err) continue } val = string(bytes) } else if col.SQLType.IsBlob() { var bytes []byte var err error if (fieldType.Kind() == reflect.Array || fieldType.Kind() == reflect.Slice) && fieldType.Elem().Kind() == reflect.Uint8 { if fieldValue.Len() > 0 { val = fieldValue.Bytes() } else { continue } } else { bytes, err = json.Marshal(fieldValue.Interface()) if err != nil { engine.logger.Error(err) continue } val = bytes } } else { continue } default: val = fieldValue.Interface() } args = append(args, val) var condi string if col.IsPrimaryKey && engine.dialect.DBType() == "ql" { condi = "id() == ?" } else { condi = fmt.Sprintf("%v %s ?", colName, engine.dialect.EqStr()) } colNames = append(colNames, condi) } return colNames, args } // TableName return current tableName func (statement *Statement) TableName() string { if statement.AltTableName != "" { return statement.AltTableName } return statement.tableName } // Id generate "where id = ? " statment or for composite key "where key1 = ? and key2 = ?" func (statement *Statement) Id(id interface{}) *Statement { idValue := reflect.ValueOf(id) idType := reflect.TypeOf(idValue.Interface()) switch idType { case ptrPkType: if pkPtr, ok := (id).(*core.PK); ok { statement.IdParam = pkPtr return statement } case pkType: if pk, ok := (id).(core.PK); ok { statement.IdParam = &pk return statement } } switch idType.Kind() { case reflect.String: statement.IdParam = &core.PK{idValue.Convert(reflect.TypeOf("")).Interface()} return statement } statement.IdParam = &core.PK{id} return statement } // Incr Generate "Update ... Set column = column + arg" statment func (statement *Statement) Incr(column string, arg ...interface{}) *Statement { k := strings.ToLower(column) if len(arg) > 0 { statement.incrColumns[k] = incrParam{column, arg[0]} } else { statement.incrColumns[k] = incrParam{column, 1} } return statement } // Decr Generate "Update ... Set column = column - arg" statment func (statement *Statement) Decr(column string, arg ...interface{}) *Statement { k := strings.ToLower(column) if len(arg) > 0 { statement.decrColumns[k] = decrParam{column, arg[0]} } else { statement.decrColumns[k] = decrParam{column, 1} } return statement } // SetExpr Generate "Update ... Set column = {expression}" statment func (statement *Statement) SetExpr(column string, expression string) *Statement { k := strings.ToLower(column) statement.exprColumns[k] = exprParam{column, expression} return statement } // Generate "Update ... Set column = column + arg" statment func (statement *Statement) getInc() map[string]incrParam { return statement.incrColumns } // Generate "Update ... Set column = column - arg" statment func (statement *Statement) getDec() map[string]decrParam { return statement.decrColumns } // Generate "Update ... Set column = {expression}" statment func (statement *Statement) getExpr() map[string]exprParam { return statement.exprColumns } // In generate "Where column IN (?) " statment func (statement *Statement) In(column string, args ...interface{}) *Statement { length := len(args) if length == 0 { return statement } k := strings.ToLower(column) var newargs []interface{} if length == 1 && reflect.TypeOf(args[0]).Kind() == reflect.Slice { newargs = make([]interface{}, 0) v := reflect.ValueOf(args[0]) for i := 0; i < v.Len(); i++ { newargs = append(newargs, v.Index(i).Interface()) } } else { newargs = args } if _, ok := statement.inColumns[k]; ok { statement.inColumns[k].args = append(statement.inColumns[k].args, newargs...) } else { statement.inColumns[k] = &inParam{column, newargs} } return statement } func (statement *Statement) genInSql() (string, []interface{}) { if len(statement.inColumns) == 0 { return "", []interface{}{} } inStrs := make([]string, len(statement.inColumns), len(statement.inColumns)) args := make([]interface{}, 0, len(statement.inColumns)) var buf bytes.Buffer var i int for _, params := range statement.inColumns { buf.Reset() fmt.Fprintf(&buf, "(%v IN (%v))", statement.Engine.quoteColumn(params.colName), strings.Join(makeArray("?", len(params.args)), ",")) inStrs[i] = buf.String() i++ args = append(args, params.args...) } if len(statement.inColumns) == 1 { return inStrs[0], args } return fmt.Sprintf("(%v)", strings.Join(inStrs, " "+statement.Engine.dialect.AndStr()+" ")), args } func (statement *Statement) attachInSql() { inSql, inArgs := statement.genInSql() if len(inSql) > 0 { if len(statement.ConditionStr) > 0 { statement.ConditionStr += " " + statement.Engine.dialect.AndStr() + " " } statement.ConditionStr += inSql statement.Params = append(statement.Params, inArgs...) } } func (statement *Statement) col2NewColsWithQuote(columns ...string) []string { newColumns := make([]string, 0) for _, col := range columns { col = strings.Replace(col, "`", "", -1) col = strings.Replace(col, statement.Engine.QuoteStr(), "", -1) ccols := strings.Split(col, ",") for _, c := range ccols { fields := strings.Split(strings.TrimSpace(c), ".") if len(fields) == 1 { newColumns = append(newColumns, statement.Engine.quote(fields[0])) } else if len(fields) == 2 { newColumns = append(newColumns, statement.Engine.quote(fields[0])+"."+ statement.Engine.quote(fields[1])) } else { panic(errors.New("unwanted colnames")) } } } return newColumns } // Generate "Distince col1, col2 " statment func (statement *Statement) Distinct(columns ...string) *Statement { statement.IsDistinct = true statement.Cols(columns...) return statement } // Generate "SELECT ... FOR UPDATE" statment func (statement *Statement) ForUpdate() *Statement { statement.IsForUpdate = true return statement } // Select replace select func (s *Statement) Select(str string) *Statement { s.selectStr = str return s } // Cols generate "col1, col2" statement func (statement *Statement) Cols(columns ...string) *Statement { cols := col2NewCols(columns...) for _, nc := range cols { statement.columnMap[strings.ToLower(nc)] = true } newColumns := statement.col2NewColsWithQuote(columns...) //fmt.Println("=====", columns, newColumns, cols) statement.ColumnStr = strings.Join(newColumns, ", ") statement.ColumnStr = strings.Replace(statement.ColumnStr, statement.Engine.quote("*"), "*", -1) return statement } // AllCols update use only: update all columns func (statement *Statement) AllCols() *Statement { statement.useAllCols = true return statement } // MustCols update use only: must update columns func (statement *Statement) MustCols(columns ...string) *Statement { newColumns := col2NewCols(columns...) for _, nc := range newColumns { statement.mustColumnMap[strings.ToLower(nc)] = true } return statement } // UseBool indicates that use bool fields as update contents and query contiditions func (statement *Statement) UseBool(columns ...string) *Statement { if len(columns) > 0 { statement.MustCols(columns...) } else { statement.allUseBool = true } return statement } // Omit do not use the columns func (statement *Statement) Omit(columns ...string) { newColumns := col2NewCols(columns...) for _, nc := range newColumns { statement.columnMap[strings.ToLower(nc)] = false } statement.OmitStr = statement.Engine.Quote(strings.Join(newColumns, statement.Engine.Quote(", "))) } // Nullable Update use only: update columns to null when value is nullable and zero-value func (statement *Statement) Nullable(columns ...string) { newColumns := col2NewCols(columns...) for _, nc := range newColumns { statement.nullableMap[strings.ToLower(nc)] = true } } // Top generate LIMIT limit statement func (statement *Statement) Top(limit int) *Statement { statement.Limit(limit) return statement } // Limit generate LIMIT start, limit statement func (statement *Statement) Limit(limit int, start ...int) *Statement { statement.LimitN = limit if len(start) > 0 { statement.Start = start[0] } return statement } // OrderBy generate "Order By order" statement func (statement *Statement) OrderBy(order string) *Statement { if len(statement.OrderStr) > 0 { statement.OrderStr += ", " } statement.OrderStr += order return statement } // Desc generate `ORDER BY xx DESC` func (statement *Statement) Desc(colNames ...string) *Statement { var buf bytes.Buffer fmt.Fprintf(&buf, statement.OrderStr) if len(statement.OrderStr) > 0 { fmt.Fprint(&buf, ", ") } newColNames := statement.col2NewColsWithQuote(colNames...) fmt.Fprintf(&buf, "%v DESC", strings.Join(newColNames, " DESC, ")) statement.OrderStr = buf.String() return statement } // Asc provide asc order by query condition, the input parameters are columns. func (statement *Statement) Asc(colNames ...string) *Statement { var buf bytes.Buffer fmt.Fprintf(&buf, statement.OrderStr) if len(statement.OrderStr) > 0 { fmt.Fprint(&buf, ", ") } newColNames := statement.col2NewColsWithQuote(colNames...) fmt.Fprintf(&buf, "%v ASC", strings.Join(newColNames, " ASC, ")) statement.OrderStr = buf.String() return statement } // Join The joinOP should be one of INNER, LEFT OUTER, CROSS etc - this will be prepended to JOIN func (statement *Statement) Join(joinOP string, tablename interface{}, condition string, args ...interface{}) *Statement { var buf bytes.Buffer if len(statement.JoinStr) > 0 { fmt.Fprintf(&buf, "%v %v JOIN ", statement.JoinStr, joinOP) } else { fmt.Fprintf(&buf, "%v JOIN ", joinOP) } switch tablename.(type) { case []string: t := tablename.([]string) if len(t) > 1 { fmt.Fprintf(&buf, "%v AS %v", statement.Engine.Quote(t[0]), statement.Engine.Quote(t[1])) } else if len(t) == 1 { fmt.Fprintf(&buf, statement.Engine.Quote(t[0])) } case []interface{}: t := tablename.([]interface{}) l := len(t) var table string if l > 0 { f := t[0] v := rValue(f) t := v.Type() if t.Kind() == reflect.String { table = f.(string) } else if t.Kind() == reflect.Struct { table = statement.Engine.tbName(v) } } if l > 1 { fmt.Fprintf(&buf, "%v AS %v", statement.Engine.Quote(table), statement.Engine.Quote(fmt.Sprintf("%v", t[1]))) } else if l == 1 { fmt.Fprintf(&buf, statement.Engine.Quote(table)) } default: fmt.Fprintf(&buf, statement.Engine.Quote(fmt.Sprintf("%v", tablename))) } fmt.Fprintf(&buf, " ON %v", condition) statement.JoinStr = buf.String() statement.joinArgs = append(statement.joinArgs, args...) return statement } // GroupBy generate "Group By keys" statement func (statement *Statement) GroupBy(keys string) *Statement { statement.GroupByStr = keys return statement } // Having generate "Having conditions" statement func (statement *Statement) Having(conditions string) *Statement { statement.HavingStr = fmt.Sprintf("HAVING %v", conditions) return statement } // Unscoped always disable struct tag "deleted" func (statement *Statement) Unscoped() *Statement { statement.unscoped = true return statement } func (statement *Statement) genColumnStr() string { table := statement.RefTable var colNames []string for _, col := range table.Columns() { if statement.OmitStr != "" { if _, ok := statement.columnMap[strings.ToLower(col.Name)]; ok { continue } } if col.MapType == core.ONLYTODB { continue } if statement.JoinStr != "" { var name string if statement.TableAlias != "" { name = statement.Engine.Quote(statement.TableAlias) } else { name = statement.Engine.Quote(statement.TableName()) } name += "." + statement.Engine.Quote(col.Name) if col.IsPrimaryKey && statement.Engine.Dialect().DBType() == "ql" { colNames = append(colNames, "id() AS "+name) } else { colNames = append(colNames, name) } } else { name := statement.Engine.Quote(col.Name) if col.IsPrimaryKey && statement.Engine.Dialect().DBType() == "ql" { colNames = append(colNames, "id() AS "+name) } else { colNames = append(colNames, name) } } } return strings.Join(colNames, ", ") } func (statement *Statement) genCreateTableSQL() string { return statement.Engine.dialect.CreateTableSql(statement.RefTable, statement.TableName(), statement.StoreEngine, statement.Charset) } func (s *Statement) genIndexSQL() []string { var sqls []string tbName := s.TableName() quote := s.Engine.Quote for idxName, index := range s.RefTable.Indexes { if index.Type == core.IndexType { sql := fmt.Sprintf("CREATE INDEX %v ON %v (%v);", quote(indexName(tbName, idxName)), quote(tbName), quote(strings.Join(index.Cols, quote(",")))) sqls = append(sqls, sql) } } return sqls } func uniqueName(tableName, uqeName string) string { return fmt.Sprintf("UQE_%v_%v", tableName, uqeName) } func (s *Statement) genUniqueSQL() []string { var sqls []string tbName := s.TableName() for _, index := range s.RefTable.Indexes { if index.Type == core.UniqueType { sql := s.Engine.dialect.CreateIndexSql(tbName, index) sqls = append(sqls, sql) } } return sqls } func (s *Statement) genDelIndexSQL() []string { var sqls []string tbName := s.TableName() for idxName, index := range s.RefTable.Indexes { var rIdxName string if index.Type == core.UniqueType { rIdxName = uniqueName(tbName, idxName) } else if index.Type == core.IndexType { rIdxName = indexName(tbName, idxName) } sql := fmt.Sprintf("DROP INDEX %v", s.Engine.Quote(rIdxName)) if s.Engine.dialect.IndexOnTable() { sql += fmt.Sprintf(" ON %v", s.Engine.Quote(s.TableName())) } sqls = append(sqls, sql) } return sqls } func (statement *Statement) genGetSql(bean interface{}) (string, []interface{}) { statement.setRefValue(rValue(bean)) var table = statement.RefTable var addedTableName = (len(statement.JoinStr) > 0) if !statement.noAutoCondition { colNames, args := statement.buildConditions(table, bean, true, true, false, true, addedTableName) statement.ConditionStr = strings.Join(colNames, " "+statement.Engine.dialect.AndStr()+" ") statement.BeanArgs = args } var columnStr = statement.ColumnStr if len(statement.selectStr) > 0 { columnStr = statement.selectStr } else { // TODO: always generate column names, not use * even if join if len(statement.JoinStr) == 0 { if len(columnStr) == 0 { if len(statement.GroupByStr) > 0 { columnStr = statement.Engine.Quote(strings.Replace(statement.GroupByStr, ",", statement.Engine.Quote(","), -1)) } else { columnStr = statement.genColumnStr() } } } else { if len(columnStr) == 0 { if len(statement.GroupByStr) > 0 { columnStr = statement.Engine.Quote(strings.Replace(statement.GroupByStr, ",", statement.Engine.Quote(","), -1)) } else { columnStr = "*" } } } } statement.attachInSql() // !admpub! fix bug:Iterate func missing "... IN (...)" return statement.genSelectSQL(columnStr), append(append(statement.joinArgs, statement.Params...), statement.BeanArgs...) } func (s *Statement) genAddColumnStr(col *core.Column) (string, []interface{}) { quote := s.Engine.Quote sql := fmt.Sprintf("ALTER TABLE %v ADD %v;", quote(s.TableName()), col.String(s.Engine.dialect)) return sql, []interface{}{} } /*func (s *Statement) genAddIndexStr(idxName string, cols []string) (string, []interface{}) { quote := s.Engine.Quote colstr := quote(strings.Join(cols, quote(", "))) sql := fmt.Sprintf("CREATE INDEX %v ON %v (%v);", quote(idxName), quote(s.TableName()), colstr) return sql, []interface{}{} } func (s *Statement) genAddUniqueStr(uqeName string, cols []string) (string, []interface{}) { quote := s.Engine.Quote colstr := quote(strings.Join(cols, quote(", "))) sql := fmt.Sprintf("CREATE UNIQUE INDEX %v ON %v (%v);", quote(uqeName), quote(s.TableName()), colstr) return sql, []interface{}{} }*/ func (statement *Statement) buildConditions(table *core.Table, bean interface{}, includeVersion bool, includeUpdated bool, includeNil bool, includeAutoIncr bool, addedTableName bool) ([]string, []interface{}) { return buildConditions(statement.Engine, table, bean, includeVersion, includeUpdated, includeNil, includeAutoIncr, statement.allUseBool, statement.useAllCols, statement.unscoped, statement.mustColumnMap, statement.TableName(), statement.TableAlias, addedTableName) } func (statement *Statement) genCountSql(bean interface{}) (string, []interface{}) { statement.setRefValue(rValue(bean)) var addedTableName = (len(statement.JoinStr) > 0) if !statement.noAutoCondition { colNames, args := statement.buildConditions(statement.RefTable, bean, true, true, false, true, addedTableName) statement.ConditionStr = strings.Join(colNames, " "+statement.Engine.Dialect().AndStr()+" ") statement.BeanArgs = args } // count(index fieldname) > count(0) > count(*) var id = "*" if statement.Engine.Dialect().DBType() == "ql" { id = "" } statement.attachInSql() return statement.genSelectSQL(fmt.Sprintf("count(%v)", id)), append(append(statement.joinArgs, statement.Params...), statement.BeanArgs...) } func (statement *Statement) genSumSql(bean interface{}, columns ...string) (string, []interface{}) { statement.setRefValue(rValue(bean)) var addedTableName = (len(statement.JoinStr) > 0) if !statement.noAutoCondition { colNames, args := statement.buildConditions(statement.RefTable, bean, true, true, false, true, addedTableName) statement.ConditionStr = strings.Join(colNames, " "+statement.Engine.Dialect().AndStr()+" ") statement.BeanArgs = args } statement.attachInSql() var sumStrs = make([]string, 0, len(columns)) for _, colName := range columns { sumStrs = append(sumStrs, fmt.Sprintf("sum(%s)", colName)) } return statement.genSelectSQL(strings.Join(sumStrs, ", ")), append(append(statement.joinArgs, statement.Params...), statement.BeanArgs...) } func (statement *Statement) genSelectSQL(columnStr string) (a string) { var distinct string if statement.IsDistinct { distinct = "DISTINCT " } var dialect = statement.Engine.Dialect() var quote = statement.Engine.Quote var top string var mssqlCondi string statement.processIdParam() var buf bytes.Buffer if len(statement.WhereStr) > 0 { if len(statement.ConditionStr) > 0 { fmt.Fprintf(&buf, " WHERE (%v)", statement.WhereStr) } else { fmt.Fprintf(&buf, " WHERE %v", statement.WhereStr) } if statement.ConditionStr != "" { fmt.Fprintf(&buf, " %s (%v)", dialect.AndStr(), statement.ConditionStr) } } else if len(statement.ConditionStr) > 0 { fmt.Fprintf(&buf, " WHERE %v", statement.ConditionStr) } var whereStr = buf.String() var fromStr = " FROM " + quote(statement.TableName()) if statement.TableAlias != "" { if dialect.DBType() == core.ORACLE { fromStr += " " + quote(statement.TableAlias) } else { fromStr += " AS " + quote(statement.TableAlias) } } if statement.JoinStr != "" { fromStr = fmt.Sprintf("%v %v", fromStr, statement.JoinStr) } if dialect.DBType() == core.MSSQL { if statement.LimitN > 0 { top = fmt.Sprintf(" TOP %d ", statement.LimitN) } if statement.Start > 0 { var column = "(id)" if len(statement.RefTable.PKColumns()) == 0 { for _, index := range statement.RefTable.Indexes { if len(index.Cols) == 1 { column = index.Cols[0] break } } if len(column) == 0 { column = statement.RefTable.ColumnsSeq()[0] } } var orderStr string if len(statement.OrderStr) > 0 { orderStr = " ORDER BY " + statement.OrderStr } var groupStr string if len(statement.GroupByStr) > 0 { groupStr = " GROUP BY " + statement.GroupByStr } mssqlCondi = fmt.Sprintf("(%s NOT IN (SELECT TOP %d %s%s%s%s%s))", column, statement.Start, column, fromStr, whereStr, orderStr, groupStr) } } // !nashtsai! REVIEW Sprintf is considered slowest mean of string concatnation, better to work with builder pattern a = fmt.Sprintf("SELECT %v%v%v%v%v", top, distinct, columnStr, fromStr, whereStr) if len(mssqlCondi) > 0 { if len(whereStr) > 0 { a += " AND " + mssqlCondi } else { a += " WHERE " + mssqlCondi } } if statement.GroupByStr != "" { a = fmt.Sprintf("%v GROUP BY %v", a, statement.GroupByStr) } if statement.HavingStr != "" { a = fmt.Sprintf("%v %v", a, statement.HavingStr) } if statement.OrderStr != "" { a = fmt.Sprintf("%v ORDER BY %v", a, statement.OrderStr) } if dialect.DBType() != core.MSSQL && dialect.DBType() != core.ORACLE { if statement.Start > 0 { a = fmt.Sprintf("%v LIMIT %v OFFSET %v", a, statement.LimitN, statement.Start) } else if statement.LimitN > 0 { a = fmt.Sprintf("%v LIMIT %v", a, statement.LimitN) } } else if dialect.DBType() == core.ORACLE { if statement.Start != 0 || statement.LimitN != 0 { a = fmt.Sprintf("SELECT %v FROM (SELECT %v,ROWNUM RN FROM (%v) at WHERE ROWNUM <= %d) aat WHERE RN > %d", columnStr, columnStr, a, statement.Start+statement.LimitN, statement.Start) } } if statement.IsForUpdate { a = dialect.ForUpdateSql(a) } return } func (statement *Statement) processIdParam() { if statement.IdParam != nil { if statement.Engine.dialect.DBType() != "ql" { for i, col := range statement.RefTable.PKColumns() { var colName = statement.colName(col, statement.TableName()) if i < len(*(statement.IdParam)) { statement.And(fmt.Sprintf("%v %s ?", colName, statement.Engine.dialect.EqStr()), (*(statement.IdParam))[i]) } else { statement.And(fmt.Sprintf("%v %s ?", colName, statement.Engine.dialect.EqStr()), "") } } } else { if len(*(statement.IdParam)) <= 1 { statement.And("id() == ?", (*(statement.IdParam))[0]) } } } } func (statement *Statement) JoinColumns(cols []*core.Column, includeTableName bool) string { var colnames = make([]string, len(cols)) for i, col := range cols { if includeTableName { colnames[i] = statement.Engine.Quote(statement.TableName()) + "." + statement.Engine.Quote(col.Name) } else { colnames[i] = statement.Engine.Quote(col.Name) } } return strings.Join(colnames, ", ") } func (statement *Statement) convertIdSql(sqlStr string) string { if statement.RefTable != nil { cols := statement.RefTable.PKColumns() if len(cols) == 0 { return "" } colstrs := statement.JoinColumns(cols, false) sqls := splitNNoCase(sqlStr, " from ", 2) if len(sqls) != 2 { return "" } if statement.Engine.dialect.DBType() == "ql" { return fmt.Sprintf("SELECT id() FROM %v", sqls[1]) } return fmt.Sprintf("SELECT %s FROM %v", colstrs, sqls[1]) } return "" } func (statement *Statement) convertUpdateSQL(sqlStr string) (string, string) { if statement.RefTable == nil || len(statement.RefTable.PrimaryKeys) != 1 { return "", "" } colstrs := statement.JoinColumns(statement.RefTable.PKColumns(), true) sqls := splitNNoCase(sqlStr, "where", 2) if len(sqls) != 2 { if len(sqls) == 1 { return sqls[0], fmt.Sprintf("SELECT %v FROM %v", colstrs, statement.Engine.Quote(statement.TableName())) } return "", "" } var whereStr = sqls[1] //TODO: for postgres only, if any other database? var paraStr string if statement.Engine.dialect.DBType() == core.POSTGRES { paraStr = "$" } else if statement.Engine.dialect.DBType() == core.MSSQL { paraStr = ":" } if paraStr != "" { if strings.Contains(sqls[1], paraStr) { dollers := strings.Split(sqls[1], paraStr) whereStr = dollers[0] for i, c := range dollers[1:] { ccs := strings.SplitN(c, " ", 2) whereStr += fmt.Sprintf(paraStr+"%v %v", i+1, ccs[1]) } } } return sqls[0], fmt.Sprintf("SELECT %v FROM %v WHERE %v", colstrs, statement.Engine.Quote(statement.TableName()), whereStr) } ================================================ FILE: src/github.com/go-xorm/xorm/syslogger.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !windows,!nacl,!plan9 package xorm import ( "fmt" "log/syslog" "github.com/go-xorm/core" ) var _ core.ILogger = &SyslogLogger{} // SyslogLogger will be depricated type SyslogLogger struct { w *syslog.Writer showSQL bool } func NewSyslogLogger(w *syslog.Writer) *SyslogLogger { return &SyslogLogger{w: w} } func (s *SyslogLogger) Debug(v ...interface{}) { s.w.Debug(fmt.Sprint(v...)) } func (s *SyslogLogger) Debugf(format string, v ...interface{}) { s.w.Debug(fmt.Sprintf(format, v...)) } func (s *SyslogLogger) Error(v ...interface{}) { s.w.Err(fmt.Sprint(v...)) } func (s *SyslogLogger) Errorf(format string, v ...interface{}) { s.w.Err(fmt.Sprintf(format, v...)) } func (s *SyslogLogger) Info(v ...interface{}) { s.w.Info(fmt.Sprint(v...)) } func (s *SyslogLogger) Infof(format string, v ...interface{}) { s.w.Info(fmt.Sprintf(format, v...)) } func (s *SyslogLogger) Warn(v ...interface{}) { s.w.Warning(fmt.Sprint(v...)) } func (s *SyslogLogger) Warnf(format string, v ...interface{}) { s.w.Warning(fmt.Sprintf(format, v...)) } func (s *SyslogLogger) Level() core.LogLevel { return core.LOG_UNKNOWN } // SetLevel always return error, as current log/syslog package doesn't allow to set priority level after syslog.Writer created func (s *SyslogLogger) SetLevel(l core.LogLevel) {} func (s *SyslogLogger) ShowSQL(show ...bool) { if len(show) == 0 { s.showSQL = true return } s.showSQL = show[0] } func (s *SyslogLogger) IsShowSQL() bool { return s.showSQL } ================================================ FILE: src/github.com/go-xorm/xorm/types.go ================================================ package xorm import ( "reflect" "github.com/go-xorm/core" ) var ( ptrPkType = reflect.TypeOf(&core.PK{}) pkType = reflect.TypeOf(core.PK{}) ) ================================================ FILE: src/github.com/go-xorm/xorm/xorm.go ================================================ // Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "fmt" "os" "reflect" "runtime" "sync" "time" "github.com/go-xorm/core" ) const ( // Version show the xorm's version Version string = "0.5.5.0711" ) func regDrvsNDialects() bool { providedDrvsNDialects := map[string]struct { dbType core.DbType getDriver func() core.Driver getDialect func() core.Dialect }{ "mssql": {"mssql", func() core.Driver { return &odbcDriver{} }, func() core.Dialect { return &mssql{} }}, "odbc": {"mssql", func() core.Driver { return &odbcDriver{} }, func() core.Dialect { return &mssql{} }}, // !nashtsai! TODO change this when supporting MS Access "mysql": {"mysql", func() core.Driver { return &mysqlDriver{} }, func() core.Dialect { return &mysql{} }}, "mymysql": {"mysql", func() core.Driver { return &mymysqlDriver{} }, func() core.Dialect { return &mysql{} }}, "postgres": {"postgres", func() core.Driver { return &pqDriver{} }, func() core.Dialect { return &postgres{} }}, "sqlite3": {"sqlite3", func() core.Driver { return &sqlite3Driver{} }, func() core.Dialect { return &sqlite3{} }}, "oci8": {"oracle", func() core.Driver { return &oci8Driver{} }, func() core.Dialect { return &oracle{} }}, "goracle": {"oracle", func() core.Driver { return &goracleDriver{} }, func() core.Dialect { return &oracle{} }}, } for driverName, v := range providedDrvsNDialects { if driver := core.QueryDriver(driverName); driver == nil { core.RegisterDriver(driverName, v.getDriver()) core.RegisterDialect(v.dbType, v.getDialect) } } return true } func close(engine *Engine) { engine.Close() } // NewEngine new a db manager according to the parameter. Currently support four // drivers func NewEngine(driverName string, dataSourceName string) (*Engine, error) { regDrvsNDialects() driver := core.QueryDriver(driverName) if driver == nil { return nil, fmt.Errorf("Unsupported driver name: %v", driverName) } uri, err := driver.Parse(driverName, dataSourceName) if err != nil { return nil, err } dialect := core.QueryDialect(uri.DbType) if dialect == nil { return nil, fmt.Errorf("Unsupported dialect type: %v", uri.DbType) } db, err := core.Open(driverName, dataSourceName) if err != nil { return nil, err } err = dialect.Init(db, uri, driverName, dataSourceName) if err != nil { return nil, err } engine := &Engine{ db: db, dialect: dialect, Tables: make(map[reflect.Type]*core.Table), mutex: &sync.RWMutex{}, TagIdentifier: "xorm", TZLocation: time.Local, } logger := NewSimpleLogger(os.Stdout) logger.SetLevel(core.LOG_INFO) engine.SetLogger(logger) engine.SetMapper(core.NewCacheMapper(new(core.SnakeMapper))) runtime.SetFinalizer(engine, close) return engine, nil } // Clone clone an engine func (engine *Engine) Clone() (*Engine, error) { return NewEngine(engine.DriverName(), engine.DataSourceName()) } ================================================ FILE: src/github.com/golang/glog/glog.go ================================================ // Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ // // Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package glog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. // It provides functions Info, Warning, Error, Fatal, plus formatting variants such as // Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags. // // Basic examples: // // glog.Info("Prepare to repel boarders") // // glog.Fatalf("Initialization failed: %s", err) // // See the documentation for the V function for an explanation of these examples: // // if glog.V(2) { // glog.Info("Starting transaction...") // } // // glog.V(2).Infoln("Processed", nItems, "elements") // // Log output is buffered and written periodically using Flush. Programs // should call Flush before exiting to guarantee all glog output is written. // // By default, all glog statements write to files in a temporary directory. // This package provides several flags that modify this behavior. // As a result, flag.Parse must be called before any logging is done. // // -logtostderr=false // Logs are written to standard error instead of to files. // -alsologtostderr=false // Logs are written to standard error as well as to files. // -stderrthreshold=ERROR // Log events at or above this severity are logged to standard // error as well as to files. // -log_dir="" // Log files will be written to this directory instead of the // default temporary directory. // // Other flags provide aids to debugging. // // -log_backtrace_at="" // When set to a file and line number holding a logging statement, // such as // -log_backtrace_at=gopherflakes.go:234 // a stack trace will be written to the Info glog whenever execution // hits that statement. (Unlike with -vmodule, the ".go" must be // present.) // -v=0 // Enable V-leveled logging at the specified level. // -vmodule="" // The syntax of the argument is a comma-separated list of pattern=N, // where pattern is a literal file name (minus the ".go" suffix) or // "glob" pattern and N is a V level. For instance, // -vmodule=gopher*=3 // sets the V level to 3 in all Go files whose names begin "gopher". // package glog import ( "bufio" "bytes" "errors" "flag" "fmt" "io" stdLog "log" "os" "path/filepath" "runtime" "strconv" "strings" "sync" "sync/atomic" "time" ) // severity identifies the sort of glog: info, warning etc. It also implements // the flag.Value interface. The -stderrthreshold flag is of type severity and // should be modified only through the flag.Value interface. The values match // the corresponding constants in C++. type severity int32 // sync/atomic int32 // These constants identify the glog levels in order of increasing severity. // A message written to a high-severity glog file is also written to each // lower-severity glog file. const ( infoLog severity = iota warningLog errorLog fatalLog numSeverity = 4 ) const severityChar = "IWEF" var severityName = []string{ infoLog: "INFO", warningLog: "WARNING", errorLog: "ERROR", fatalLog: "FATAL", } // get returns the value of the severity. func (s *severity) get() severity { return severity(atomic.LoadInt32((*int32)(s))) } // set sets the value of the severity. func (s *severity) set(val severity) { atomic.StoreInt32((*int32)(s), int32(val)) } // String is part of the flag.Value interface. func (s *severity) String() string { return strconv.FormatInt(int64(*s), 10) } // Get is part of the flag.Value interface. func (s *severity) Get() interface{} { return *s } // Set is part of the flag.Value interface. func (s *severity) Set(value string) error { var threshold severity // Is it a known name? if v, ok := severityByName(value); ok { threshold = v } else { v, err := strconv.Atoi(value) if err != nil { return err } threshold = severity(v) } logging.stderrThreshold.set(threshold) return nil } func severityByName(s string) (severity, bool) { s = strings.ToUpper(s) for i, name := range severityName { if name == s { return severity(i), true } } return 0, false } // OutputStats tracks the number of output lines and bytes written. type OutputStats struct { lines int64 bytes int64 } // Lines returns the number of lines written. func (s *OutputStats) Lines() int64 { return atomic.LoadInt64(&s.lines) } // Bytes returns the number of bytes written. func (s *OutputStats) Bytes() int64 { return atomic.LoadInt64(&s.bytes) } // Stats tracks the number of lines of output and number of bytes // per severity level. Values must be read with atomic.LoadInt64. var Stats struct { Info, Warning, Error OutputStats } var severityStats = [numSeverity]*OutputStats{ infoLog: &Stats.Info, warningLog: &Stats.Warning, errorLog: &Stats.Error, } // Level is exported because it appears in the arguments to V and is // the type of the v flag, which can be set programmatically. // It's a distinct type because we want to discriminate it from logType. // Variables of type level are only changed under logging.mu. // The -v flag is read only with atomic ops, so the state of the logging // module is consistent. // Level is treated as a sync/atomic int32. // Level specifies a level of verbosity for V logs. *Level implements // flag.Value; the -v flag is of type Level and should be modified // only through the flag.Value interface. type Level int32 // get returns the value of the Level. func (l *Level) get() Level { return Level(atomic.LoadInt32((*int32)(l))) } // set sets the value of the Level. func (l *Level) set(val Level) { atomic.StoreInt32((*int32)(l), int32(val)) } // String is part of the flag.Value interface. func (l *Level) String() string { return strconv.FormatInt(int64(*l), 10) } // Get is part of the flag.Value interface. func (l *Level) Get() interface{} { return *l } // Set is part of the flag.Value interface. func (l *Level) Set(value string) error { v, err := strconv.Atoi(value) if err != nil { return err } logging.mu.Lock() defer logging.mu.Unlock() logging.setVState(Level(v), logging.vmodule.filter, false) return nil } // moduleSpec represents the setting of the -vmodule flag. type moduleSpec struct { filter []modulePat } // modulePat contains a filter for the -vmodule flag. // It holds a verbosity level and a file pattern to match. type modulePat struct { pattern string literal bool // The pattern is a literal string level Level } // match reports whether the file matches the pattern. It uses a string // comparison if the pattern contains no metacharacters. func (m *modulePat) match(file string) bool { if m.literal { return file == m.pattern } match, _ := filepath.Match(m.pattern, file) return match } func (m *moduleSpec) String() string { // Lock because the type is not atomic. TODO: clean this up. logging.mu.Lock() defer logging.mu.Unlock() var b bytes.Buffer for i, f := range m.filter { if i > 0 { b.WriteRune(',') } fmt.Fprintf(&b, "%s=%d", f.pattern, f.level) } return b.String() } // Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the // struct is not exported. func (m *moduleSpec) Get() interface{} { return nil } var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N") // Syntax: -vmodule=recordio=2,file=1,gfs*=3 func (m *moduleSpec) Set(value string) error { var filter []modulePat for _, pat := range strings.Split(value, ",") { if len(pat) == 0 { // Empty strings such as from a trailing comma can be ignored. continue } patLev := strings.Split(pat, "=") if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 { return errVmoduleSyntax } pattern := patLev[0] v, err := strconv.Atoi(patLev[1]) if err != nil { return errors.New("syntax error: expect comma-separated list of filename=N") } if v < 0 { return errors.New("negative value for vmodule level") } if v == 0 { continue // Ignore. It's harmless but no point in paying the overhead. } // TODO: check syntax of filter? filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)}) } logging.mu.Lock() defer logging.mu.Unlock() logging.setVState(logging.verbosity, filter, true) return nil } // isLiteral reports whether the pattern is a literal string, that is, has no metacharacters // that require filepath.Match to be called to match the pattern. func isLiteral(pattern string) bool { return !strings.ContainsAny(pattern, `\*?[]`) } // traceLocation represents the setting of the -log_backtrace_at flag. type traceLocation struct { file string line int } // isSet reports whether the trace location has been specified. // logging.mu is held. func (t *traceLocation) isSet() bool { return t.line > 0 } // match reports whether the specified file and line matches the trace location. // The argument file name is the full path, not the basename specified in the flag. // logging.mu is held. func (t *traceLocation) match(file string, line int) bool { if t.line != line { return false } if i := strings.LastIndex(file, "/"); i >= 0 { file = file[i+1:] } return t.file == file } func (t *traceLocation) String() string { // Lock because the type is not atomic. TODO: clean this up. logging.mu.Lock() defer logging.mu.Unlock() return fmt.Sprintf("%s:%d", t.file, t.line) } // Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the // struct is not exported func (t *traceLocation) Get() interface{} { return nil } var errTraceSyntax = errors.New("syntax error: expect file.go:234") // Syntax: -log_backtrace_at=gopherflakes.go:234 // Note that unlike vmodule the file extension is included here. func (t *traceLocation) Set(value string) error { if value == "" { // Unset. t.line = 0 t.file = "" } fields := strings.Split(value, ":") if len(fields) != 2 { return errTraceSyntax } file, line := fields[0], fields[1] if !strings.Contains(file, ".") { return errTraceSyntax } v, err := strconv.Atoi(line) if err != nil { return errTraceSyntax } if v <= 0 { return errors.New("negative or zero value for level") } logging.mu.Lock() defer logging.mu.Unlock() t.line = v t.file = file return nil } // flushSyncWriter is the interface satisfied by logging destinations. type flushSyncWriter interface { Flush() error Sync() error io.Writer } func init() { flag.BoolVar(&logging.toStderr, "logtostderr", false, "glog to standard error instead of files") flag.BoolVar(&logging.alsoToStderr, "alsologtostderr", false, "glog to standard error as well as files") flag.Var(&logging.verbosity, "v", "glog level for V logs") flag.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr") flag.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging") flag.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace") // Default stderrThreshold is ERROR. logging.stderrThreshold = errorLog logging.setVState(0, nil, false) go logging.flushDaemon() } // Flush flushes all pending glog I/O. func Flush() { logging.lockAndFlushAll() } // loggingT collects all the global state of the logging setup. type loggingT struct { // Boolean flags. Not handled atomically because the flag.Value interface // does not let us avoid the =true, and that shorthand is necessary for // compatibility. TODO: does this matter enough to fix? Seems unlikely. toStderr bool // The -logtostderr flag. alsoToStderr bool // The -alsologtostderr flag. // Level flag. Handled atomically. stderrThreshold severity // The -stderrthreshold flag. // freeList is a list of byte buffers, maintained under freeListMu. freeList *buffer // freeListMu maintains the free list. It is separate from the main mutex // so buffers can be grabbed and printed to without holding the main lock, // for better parallelization. freeListMu sync.Mutex // mu protects the remaining elements of this structure and is // used to synchronize logging. mu sync.Mutex // file holds writer for each of the glog types. file [numSeverity]flushSyncWriter // pcs is used in V to avoid an allocation when computing the caller's PC. pcs [1]uintptr // vmap is a cache of the V Level for each V() call site, identified by PC. // It is wiped whenever the vmodule flag changes state. vmap map[uintptr]Level // filterLength stores the length of the vmodule filter chain. If greater // than zero, it means vmodule is enabled. It may be read safely // using sync.LoadInt32, but is only modified under mu. filterLength int32 // traceLocation is the state of the -log_backtrace_at flag. traceLocation traceLocation // These flags are modified only under lock, although verbosity may be fetched // safely using atomic.LoadInt32. vmodule moduleSpec // The state of the -vmodule flag. verbosity Level // V logging level, the value of the -v flag/ } // buffer holds a byte Buffer for reuse. The zero value is ready for use. type buffer struct { bytes.Buffer tmp [64]byte // temporary byte array for creating headers. next *buffer } var logging loggingT // setVState sets a consistent state for V logging. // l.mu is held. func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) { // Turn verbosity off so V will not fire while we are in transition. logging.verbosity.set(0) // Ditto for filter length. atomic.StoreInt32(&logging.filterLength, 0) // Set the new filters and wipe the pc->Level map if the filter has changed. if setFilter { logging.vmodule.filter = filter logging.vmap = make(map[uintptr]Level) } // Things are consistent now, so enable filtering and verbosity. // They are enabled in order opposite to that in V. atomic.StoreInt32(&logging.filterLength, int32(len(filter))) logging.verbosity.set(verbosity) } // getBuffer returns a new, ready-to-use buffer. func (l *loggingT) getBuffer() *buffer { l.freeListMu.Lock() b := l.freeList if b != nil { l.freeList = b.next } l.freeListMu.Unlock() if b == nil { b = new(buffer) } else { b.next = nil b.Reset() } return b } // putBuffer returns a buffer to the free list. func (l *loggingT) putBuffer(b *buffer) { if b.Len() >= 256 { // Let big buffers die a natural death. return } l.freeListMu.Lock() b.next = l.freeList l.freeList = b l.freeListMu.Unlock() } var timeNow = time.Now // Stubbed out for testing. /* header formats a glog header as defined by the C++ implementation. It returns a buffer containing the formatted header and the user's file and line number. The depth specifies how many stack frames above lives the source line to be identified in the glog message. Log lines have this form: Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg... where the fields are defined as follows: L A single character, representing the glog level (eg 'I' for INFO) mm The month (zero padded; ie May is '05') dd The day (zero padded) hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds threadid The space-padded thread ID as returned by GetTID() file The file name line The line number msg The user-supplied message */ func (l *loggingT) header(s severity, depth int) (*buffer, string, int) { _, file, line, ok := runtime.Caller(3 + depth) if !ok { file = "???" line = 1 } else { slash := strings.LastIndex(file, "/") if slash >= 0 { file = file[slash+1:] } } return l.formatHeader(s, file, line), file, line } // formatHeader formats a glog header using the provided file name and line number. func (l *loggingT) formatHeader(s severity, file string, line int) *buffer { now := timeNow() if line < 0 { line = 0 // not a real line number, but acceptable to someDigits } if s > fatalLog { s = infoLog // for safety. } buf := l.getBuffer() // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand. // It's worth about 3X. Fprintf is hard. _, month, day := now.Date() hour, minute, second := now.Clock() // Lmmdd hh:mm:ss.uuuuuu threadid file:line] buf.tmp[0] = severityChar[s] buf.twoDigits(1, int(month)) buf.twoDigits(3, day) buf.tmp[5] = ' ' buf.twoDigits(6, hour) buf.tmp[8] = ':' buf.twoDigits(9, minute) buf.tmp[11] = ':' buf.twoDigits(12, second) buf.tmp[14] = '.' buf.nDigits(6, 15, now.Nanosecond()/1000, '0') buf.tmp[21] = ' ' buf.nDigits(7, 22, pid, ' ') // TODO: should be TID buf.tmp[29] = ' ' buf.Write(buf.tmp[:30]) buf.WriteString(file) buf.tmp[0] = ':' n := buf.someDigits(1, line) buf.tmp[n+1] = ']' buf.tmp[n+2] = ' ' buf.Write(buf.tmp[:n+3]) return buf } // Some custom tiny helper functions to print the glog header efficiently. const digits = "0123456789" // twoDigits formats a zero-prefixed two-digit integer at buf.tmp[i]. func (buf *buffer) twoDigits(i, d int) { buf.tmp[i+1] = digits[d%10] d /= 10 buf.tmp[i] = digits[d%10] } // nDigits formats an n-digit integer at buf.tmp[i], // padding with pad on the left. // It assumes d >= 0. func (buf *buffer) nDigits(n, i, d int, pad byte) { j := n - 1 for ; j >= 0 && d > 0; j-- { buf.tmp[i+j] = digits[d%10] d /= 10 } for ; j >= 0; j-- { buf.tmp[i+j] = pad } } // someDigits formats a zero-prefixed variable-width integer at buf.tmp[i]. func (buf *buffer) someDigits(i, d int) int { // Print into the top, then copy down. We know there's space for at least // a 10-digit number. j := len(buf.tmp) for { j-- buf.tmp[j] = digits[d%10] d /= 10 if d == 0 { break } } return copy(buf.tmp[i:], buf.tmp[j:]) } func (l *loggingT) println(depth int, s severity, args ...interface{}) { buf, file, line := l.header(s, depth) fmt.Fprintln(buf, args...) l.output(s, buf, file, line, false) } func (l *loggingT) print(s severity, args ...interface{}) { l.printDepth(s, 1, args...) } func (l *loggingT) printDepth(s severity, depth int, args ...interface{}) { buf, file, line := l.header(s, depth) fmt.Fprint(buf, args...) if buf.Bytes()[buf.Len()-1] != '\n' { buf.WriteByte('\n') } l.output(s, buf, file, line, false) } func (l *loggingT) printf(depth int, s severity, format string, args ...interface{}) { buf, file, line := l.header(s, depth) fmt.Fprintf(buf, format, args...) if buf.Bytes()[buf.Len()-1] != '\n' { buf.WriteByte('\n') } l.output(s, buf, file, line, false) } // printWithFileLine behaves like print but uses the provided file and line number. If // alsoLogToStderr is true, the glog message always appears on standard error; it // will also appear in the glog file unless --logtostderr is set. func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToStderr bool, args ...interface{}) { buf := l.formatHeader(s, file, line) fmt.Fprint(buf, args...) if buf.Bytes()[buf.Len()-1] != '\n' { buf.WriteByte('\n') } l.output(s, buf, file, line, alsoToStderr) } // output writes the data to the glog files and releases the buffer. func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) { l.mu.Lock() if l.traceLocation.isSet() { if l.traceLocation.match(file, line) { buf.Write(stacks(false)) } } data := buf.Bytes() if !flag.Parsed() { os.Stderr.Write([]byte("ERROR: logging before flag.Parse: ")) os.Stderr.Write(data) } else if l.toStderr { os.Stderr.Write(data) } else { if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() { os.Stderr.Write(data) } if l.file[s] == nil { if err := l.createFiles(s); err != nil { os.Stderr.Write(data) // Make sure the message appears somewhere. l.exit(err) } } switch s { case fatalLog: l.file[fatalLog].Write(data) fallthrough case errorLog: l.file[errorLog].Write(data) fallthrough case warningLog: l.file[warningLog].Write(data) fallthrough case infoLog: l.file[infoLog].Write(data) } } if s == fatalLog { // If we got here via Exit rather than Fatal, print no stacks. if atomic.LoadUint32(&fatalNoStacks) > 0 { l.mu.Unlock() timeoutFlush(10 * time.Second) os.Exit(1) } // Dump all goroutine stacks before exiting. // First, make sure we see the trace for the current goroutine on standard error. // If -logtostderr has been specified, the loop below will do that anyway // as the first stack in the full dump. if !l.toStderr { os.Stderr.Write(stacks(false)) } // Write the stack trace for all goroutines to the files. trace := stacks(true) logExitFunc = func(error) {} // If we get a write error, we'll still exit below. for log := fatalLog; log >= infoLog; log-- { if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set. f.Write(trace) } } l.mu.Unlock() timeoutFlush(10 * time.Second) os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway. } l.putBuffer(buf) l.mu.Unlock() if stats := severityStats[s]; stats != nil { atomic.AddInt64(&stats.lines, 1) atomic.AddInt64(&stats.bytes, int64(len(data))) } } // timeoutFlush calls Flush and returns when it completes or after timeout // elapses, whichever happens first. This is needed because the hooks invoked // by Flush may deadlock when glog.Fatal is called from a hook that holds // a lock. func timeoutFlush(timeout time.Duration) { done := make(chan bool, 1) go func() { Flush() // calls logging.lockAndFlushAll() done <- true }() select { case <-done: case <-time.After(timeout): fmt.Fprintln(os.Stderr, "glog: Flush took longer than", timeout) } } // stacks is a wrapper for runtime.Stack that attempts to recover the data for all goroutines. func stacks(all bool) []byte { // We don't know how big the traces are, so grow a few times if they don't fit. Start large, though. n := 10000 if all { n = 100000 } var trace []byte for i := 0; i < 5; i++ { trace = make([]byte, n) nbytes := runtime.Stack(trace, all) if nbytes < len(trace) { return trace[:nbytes] } n *= 2 } return trace } // logExitFunc provides a simple mechanism to override the default behavior // of exiting on error. Used in testing and to guarantee we reach a required exit // for fatal logs. Instead, exit could be a function rather than a method but that // would make its use clumsier. var logExitFunc func(error) // exit is called if there is trouble creating or writing glog files. // It flushes the logs and exits the program; there's no point in hanging around. // l.mu is held. func (l *loggingT) exit(err error) { fmt.Fprintf(os.Stderr, "glog: exiting because of error: %s\n", err) // If logExitFunc is set, we do that instead of exiting. if logExitFunc != nil { logExitFunc(err) return } l.flushAll() os.Exit(2) } // syncBuffer joins a bufio.Writer to its underlying file, providing access to the // file's Sync method and providing a wrapper for the Write method that provides glog // file rotation. There are conflicting methods, so the file cannot be embedded. // l.mu is held for all its methods. type syncBuffer struct { logger *loggingT *bufio.Writer file *os.File sev severity nbytes uint64 // The number of bytes written to this file } func (sb *syncBuffer) Sync() error { return sb.file.Sync() } func (sb *syncBuffer) Write(p []byte) (n int, err error) { if sb.nbytes+uint64(len(p)) >= MaxSize { if err := sb.rotateFile(time.Now()); err != nil { sb.logger.exit(err) } } n, err = sb.Writer.Write(p) sb.nbytes += uint64(n) if err != nil { sb.logger.exit(err) } return } // rotateFile closes the syncBuffer's file and starts a new one. func (sb *syncBuffer) rotateFile(now time.Time) error { if sb.file != nil { sb.Flush() sb.file.Close() } var err error sb.file, _, err = create(severityName[sb.sev], now) sb.nbytes = 0 if err != nil { return err } sb.Writer = bufio.NewWriterSize(sb.file, bufferSize) // Write header. var buf bytes.Buffer fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05")) fmt.Fprintf(&buf, "Running on machine: %s\n", host) fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH) fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n") n, err := sb.file.Write(buf.Bytes()) sb.nbytes += uint64(n) return err } // bufferSize sizes the buffer associated with each glog file. It's large // so that glog records can accumulate without the logging thread blocking // on disk I/O. The flushDaemon will block instead. const bufferSize = 256 * 1024 // createFiles creates all the glog files for severity from sev down to infoLog. // l.mu is held. func (l *loggingT) createFiles(sev severity) error { now := time.Now() // Files are created in decreasing severity order, so as soon as we find one // has already been created, we can stop. for s := sev; s >= infoLog && l.file[s] == nil; s-- { sb := &syncBuffer{ logger: l, sev: s, } if err := sb.rotateFile(now); err != nil { return err } l.file[s] = sb } return nil } const flushInterval = 30 * time.Second // flushDaemon periodically flushes the glog file buffers. func (l *loggingT) flushDaemon() { for _ = range time.NewTicker(flushInterval).C { l.lockAndFlushAll() } } // lockAndFlushAll is like flushAll but locks l.mu first. func (l *loggingT) lockAndFlushAll() { l.mu.Lock() l.flushAll() l.mu.Unlock() } // flushAll flushes all the logs and attempts to "sync" their data to disk. // l.mu is held. func (l *loggingT) flushAll() { // Flush from fatal down, in case there's trouble flushing. for s := fatalLog; s >= infoLog; s-- { file := l.file[s] if file != nil { file.Flush() // ignore error file.Sync() // ignore error } } } // CopyStandardLogTo arranges for messages written to the Go "glog" package's // default logs to also appear in the Google logs for the named and lower // severities. Subsequent changes to the standard glog's default output location // or format may break this behavior. // // Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not // recognized, CopyStandardLogTo panics. func CopyStandardLogTo(name string) { sev, ok := severityByName(name) if !ok { panic(fmt.Sprintf("glog.CopyStandardLogTo(%q): unrecognized severity name", name)) } // Set a glog format that captures the user's file and line: // d.go:23: message stdLog.SetFlags(stdLog.Lshortfile) stdLog.SetOutput(logBridge(sev)) } // logBridge provides the Write method that enables CopyStandardLogTo to connect // Go's standard logs to the logs provided by this package. type logBridge severity // Write parses the standard logging line and passes its components to the // logger for severity(lb). func (lb logBridge) Write(b []byte) (n int, err error) { var ( file = "???" line = 1 text string ) // Split "d.go:23: message" into "d.go", "23", and "message". if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 { text = fmt.Sprintf("bad glog format: %s", b) } else { file = string(parts[0]) text = string(parts[2][1:]) // skip leading space line, err = strconv.Atoi(string(parts[1])) if err != nil { text = fmt.Sprintf("bad line number: %s", b) line = 1 } } // printWithFileLine with alsoToStderr=true, so standard glog messages // always appear on standard error. logging.printWithFileLine(severity(lb), file, line, true, text) return len(b), nil } // setV computes and remembers the V level for a given PC // when vmodule is enabled. // File pattern matching takes the basename of the file, stripped // of its .go suffix, and uses filepath.Match, which is a little more // general than the *? matching used in C++. // l.mu is held. func (l *loggingT) setV(pc uintptr) Level { fn := runtime.FuncForPC(pc) file, _ := fn.FileLine(pc) // The file is something like /a/b/c/d.go. We want just the d. if strings.HasSuffix(file, ".go") { file = file[:len(file)-3] } if slash := strings.LastIndex(file, "/"); slash >= 0 { file = file[slash+1:] } for _, filter := range l.vmodule.filter { if filter.match(file) { l.vmap[pc] = filter.level return filter.level } } l.vmap[pc] = 0 return 0 } // Verbose is a boolean type that implements Infof (like Printf) etc. // See the documentation of V for more information. type Verbose bool // V reports whether verbosity at the call site is at least the requested level. // The returned value is a boolean of type Verbose, which implements Info, Infoln // and Infof. These methods will write to the Info glog if called. // Thus, one may write either // if glog.V(2) { glog.Info("glog this") } // or // glog.V(2).Info("glog this") // The second form is shorter but the first is cheaper if logging is off because it does // not evaluate its arguments. // // Whether an individual call to V generates a glog record depends on the setting of // the -v and --vmodule flags; both are off by default. If the level in the call to // V is at least the value of -v, or of -vmodule for the source file containing the // call, the V call will glog. func V(level Level) Verbose { // This function tries hard to be cheap unless there's work to do. // The fast path is two atomic loads and compares. // Here is a cheap but safe test to see if V logging is enabled globally. if logging.verbosity.get() >= level { return Verbose(true) } // It's off globally but it vmodule may still be set. // Here is another cheap but safe test to see if vmodule is enabled. if atomic.LoadInt32(&logging.filterLength) > 0 { // Now we need a proper lock to use the logging structure. The pcs field // is shared so we must lock before accessing it. This is fairly expensive, // but if V logging is enabled we're slow anyway. logging.mu.Lock() defer logging.mu.Unlock() if runtime.Callers(2, logging.pcs[:]) == 0 { return Verbose(false) } v, ok := logging.vmap[logging.pcs[0]] if !ok { v = logging.setV(logging.pcs[0]) } return Verbose(v >= level) } return Verbose(false) } // Info is equivalent to the global Info function, guarded by the value of v. // See the documentation of V for usage. func (v Verbose) Info(args ...interface{}) { if v { logging.print(infoLog, args...) } } // Infoln is equivalent to the global Infoln function, guarded by the value of v. // See the documentation of V for usage. func (v Verbose) Infoln(args ...interface{}) { if v { logging.println(0, infoLog, args...) } } // Infof is equivalent to the global Infof function, guarded by the value of v. // See the documentation of V for usage. func (v Verbose) Infof(format string, args ...interface{}) { if v { logging.printf(0, infoLog, format, args...) } } // Info logs to the INFO glog. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Info(args ...interface{}) { logging.print(infoLog, args...) } // InfoDepth acts as Info but uses depth to determine which call frame to glog. // InfoDepth(0, "msg") is the same as Info("msg"). func InfoDepth(depth int, args ...interface{}) { logging.printDepth(infoLog, depth, args...) } func InfofDepth(depth int, format string, args ...interface{}) { logging.printf(depth, infoLog, format, args...) } // Infoln logs to the INFO glog. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. func Infoln(args ...interface{}) { logging.println(0, infoLog, args...) } // Infof logs to the INFO glog. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Infof(format string, args ...interface{}) { logging.printf(0, infoLog, format, args...) } // Warning logs to the WARNING and INFO logs. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Warning(args ...interface{}) { logging.print(warningLog, args...) } // WarningDepth acts as Warning but uses depth to determine which call frame to glog. // WarningDepth(0, "msg") is the same as Warning("msg"). func WarningDepth(depth int, args ...interface{}) { logging.printDepth(warningLog, depth, args...) } // Warningln logs to the WARNING and INFO logs. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. func Warningln(args ...interface{}) { logging.println(0, warningLog, args...) } // Warningf logs to the WARNING and INFO logs. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Warningf(format string, args ...interface{}) { logging.printf(0, warningLog, format, args...) } // Error logs to the ERROR, WARNING, and INFO logs. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Error(args ...interface{}) { logging.print(errorLog, args...) } // ErrorDepth acts as Error but uses depth to determine which call frame to glog. // ErrorDepth(0, "msg") is the same as Error("msg"). func ErrorDepth(depth int, args ...interface{}) { logging.printDepth(errorLog, depth, args...) } func ErrorfDepth(depth int, format string, args ...interface{}) { logging.printf(depth, errorLog, format, args...) } // Errorln logs to the ERROR, WARNING, and INFO logs. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. func Errorln(args ...interface{}) { logging.println(0, errorLog, args...) } // Errorf logs to the ERROR, WARNING, and INFO logs. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Errorf(format string, args ...interface{}) { logging.printf(0, errorLog, format, args...) } // Fatal logs to the FATAL, ERROR, WARNING, and INFO logs, // including a stack trace of all running goroutines, then calls os.Exit(255). // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Fatal(args ...interface{}) { logging.print(fatalLog, args...) } // FatalDepth acts as Fatal but uses depth to determine which call frame to glog. // FatalDepth(0, "msg") is the same as Fatal("msg"). func FatalDepth(depth int, args ...interface{}) { logging.printDepth(fatalLog, depth, args...) } // Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs, // including a stack trace of all running goroutines, then calls os.Exit(255). // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. func Fatalln(args ...interface{}) { logging.println(0, fatalLog, args...) } // Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs, // including a stack trace of all running goroutines, then calls os.Exit(255). // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Fatalf(format string, args ...interface{}) { logging.printf(0, fatalLog, format, args...) } // fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks. // It allows Exit and relatives to use the Fatal logs. var fatalNoStacks uint32 // Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Exit(args ...interface{}) { atomic.StoreUint32(&fatalNoStacks, 1) logging.print(fatalLog, args...) } // ExitDepth acts as Exit but uses depth to determine which call frame to glog. // ExitDepth(0, "msg") is the same as Exit("msg"). func ExitDepth(depth int, args ...interface{}) { atomic.StoreUint32(&fatalNoStacks, 1) logging.printDepth(fatalLog, depth, args...) } // Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). func Exitln(args ...interface{}) { atomic.StoreUint32(&fatalNoStacks, 1) logging.println(0, fatalLog, args...) } // Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Exitf(format string, args ...interface{}) { atomic.StoreUint32(&fatalNoStacks, 1) logging.printf(0, fatalLog, format, args...) } ================================================ FILE: src/github.com/golang/glog/glog_file.go ================================================ // Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ // // Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // File I/O for logs. package glog import ( "errors" "flag" "fmt" "os" "os/user" "path/filepath" "strings" "sync" "time" ) // MaxSize is the maximum size of a glog file in bytes. var MaxSize uint64 = 1024 * 1024 * 1800 // logDirs lists the candidate directories for new glog files. var logDirs []string // If non-empty, overrides the choice of directory in which to write logs. // See createLogDirs for the full list of possible destinations. var logDir = flag.String("log_dir", "", "If non-empty, write glog files in this directory") func createLogDirs() { if *logDir != "" { logDirs = append(logDirs, *logDir) } logDirs = append(logDirs, os.TempDir()) } var ( pid = os.Getpid() program = filepath.Base(os.Args[0]) host = "unknownhost" userName = "unknownuser" ) func init() { h, err := os.Hostname() if err == nil { host = shortHostname(h) } current, err := user.Current() if err == nil { userName = current.Username } // Sanitize userName since it may contain filepath separators on Windows. userName = strings.Replace(userName, `\`, "_", -1) } // shortHostname returns its argument, truncating at the first period. // For instance, given "www.google.com" it returns "www". func shortHostname(hostname string) string { if i := strings.Index(hostname, "."); i >= 0 { return hostname[:i] } return hostname } // logName returns a new glog file name containing tag, with start time t, and // the name for the symlink for tag. func logName(tag string, t time.Time) (name, link string) { name = fmt.Sprintf("%s.%s.%s.glog.%s.%04d%02d%02d-%02d%02d%02d.%d", program, host, userName, tag, t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), pid) return name, program + "." + tag } var onceLogDirs sync.Once // create creates a new glog file and returns the file and its filename, which // contains tag ("INFO", "FATAL", etc.) and t. If the file is created // successfully, create also attempts to update the symlink for that tag, ignoring // errors. func create(tag string, t time.Time) (f *os.File, filename string, err error) { onceLogDirs.Do(createLogDirs) if len(logDirs) == 0 { return nil, "", errors.New("glog: no glog dirs") } name, link := logName(tag, t) var lastErr error for _, dir := range logDirs { fname := filepath.Join(dir, name) f, err := os.Create(fname) if err == nil { symlink := filepath.Join(dir, link) os.Remove(symlink) // ignore err os.Symlink(name, symlink) // ignore err return f, fname, nil } lastErr = err } return nil, "", fmt.Errorf("glog: cannot create glog: %v", lastErr) } ================================================ FILE: src/github.com/golang/glog/glog_test.go ================================================ // Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ // // Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package glog import ( "bytes" "fmt" stdLog "log" "path/filepath" "runtime" "strconv" "strings" "testing" "time" ) // Test that shortHostname works as advertised. func TestShortHostname(t *testing.T) { for hostname, expect := range map[string]string{ "": "", "host": "host", "host.google.com": "host", } { if got := shortHostname(hostname); expect != got { t.Errorf("shortHostname(%q): expected %q, got %q", hostname, expect, got) } } } // flushBuffer wraps a bytes.Buffer to satisfy flushSyncWriter. type flushBuffer struct { bytes.Buffer } func (f *flushBuffer) Flush() error { return nil } func (f *flushBuffer) Sync() error { return nil } // swap sets the glog writers and returns the old array. func (l *loggingT) swap(writers [numSeverity]flushSyncWriter) (old [numSeverity]flushSyncWriter) { l.mu.Lock() defer l.mu.Unlock() old = l.file for i, w := range writers { logging.file[i] = w } return } // newBuffers sets the glog writers to all new byte buffers and returns the old array. func (l *loggingT) newBuffers() [numSeverity]flushSyncWriter { return l.swap([numSeverity]flushSyncWriter{new(flushBuffer), new(flushBuffer), new(flushBuffer), new(flushBuffer)}) } // contents returns the specified glog value as a string. func contents(s severity) string { return logging.file[s].(*flushBuffer).String() } // contains reports whether the string is contained in the glog. func contains(s severity, str string, t *testing.T) bool { return strings.Contains(contents(s), str) } // setFlags configures the logging flags how the test expects them. func setFlags() { logging.toStderr = false } // Test that Info works as advertised. func TestInfo(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) Info("test") if !contains(infoLog, "I", t) { t.Errorf("Info has wrong character: %q", contents(infoLog)) } if !contains(infoLog, "test", t) { t.Error("Info failed") } } func TestInfoDepth(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) f := func() { InfoDepth(1, "depth-test1") } // The next three lines must stay together _, _, wantLine, _ := runtime.Caller(0) InfoDepth(0, "depth-test0") f() msgs := strings.Split(strings.TrimSuffix(contents(infoLog), "\n"), "\n") if len(msgs) != 2 { t.Fatalf("Got %d lines, expected 2", len(msgs)) } for i, m := range msgs { if !strings.HasPrefix(m, "I") { t.Errorf("InfoDepth[%d] has wrong character: %q", i, m) } w := fmt.Sprintf("depth-test%d", i) if !strings.Contains(m, w) { t.Errorf("InfoDepth[%d] missing %q: %q", i, w, m) } // pull out the line number (between : and ]) msg := m[strings.LastIndex(m, ":")+1:] x := strings.Index(msg, "]") if x < 0 { t.Errorf("InfoDepth[%d]: missing ']': %q", i, m) continue } line, err := strconv.Atoi(msg[:x]) if err != nil { t.Errorf("InfoDepth[%d]: bad line number: %q", i, m) continue } wantLine++ if wantLine != line { t.Errorf("InfoDepth[%d]: got line %d, want %d", i, line, wantLine) } } } func init() { CopyStandardLogTo("INFO") } // Test that CopyStandardLogTo panics on bad input. func TestCopyStandardLogToPanic(t *testing.T) { defer func() { if s, ok := recover().(string); !ok || !strings.Contains(s, "LOG") { t.Errorf(`CopyStandardLogTo("LOG") should have panicked: %v`, s) } }() CopyStandardLogTo("LOG") } // Test that using the standard glog package logs to INFO. func TestStandardLog(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) stdLog.Print("test") if !contains(infoLog, "I", t) { t.Errorf("Info has wrong character: %q", contents(infoLog)) } if !contains(infoLog, "test", t) { t.Error("Info failed") } } // Test that the header has the correct format. func TestHeader(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) defer func(previous func() time.Time) { timeNow = previous }(timeNow) timeNow = func() time.Time { return time.Date(2006, 1, 2, 15, 4, 5, .067890e9, time.Local) } pid = 1234 Info("test") var line int format := "I0102 15:04:05.067890 1234 glog_test.go:%d] test\n" n, err := fmt.Sscanf(contents(infoLog), format, &line) if n != 1 || err != nil { t.Errorf("glog format error: %d elements, error %s:\n%s", n, err, contents(infoLog)) } // Scanf treats multiple spaces as equivalent to a single space, // so check for correct space-padding also. want := fmt.Sprintf(format, line) if contents(infoLog) != want { t.Errorf("glog format error: got:\n\t%q\nwant:\t%q", contents(infoLog), want) } } // Test that an Error glog goes to Warning and Info. // Even in the Info glog, the source character will be E, so the data should // all be identical. func TestError(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) Error("test") if !contains(errorLog, "E", t) { t.Errorf("Error has wrong character: %q", contents(errorLog)) } if !contains(errorLog, "test", t) { t.Error("Error failed") } str := contents(errorLog) if !contains(warningLog, str, t) { t.Error("Warning failed") } if !contains(infoLog, str, t) { t.Error("Info failed") } } // Test that a Warning glog goes to Info. // Even in the Info glog, the source character will be W, so the data should // all be identical. func TestWarning(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) Warning("test") if !contains(warningLog, "W", t) { t.Errorf("Warning has wrong character: %q", contents(warningLog)) } if !contains(warningLog, "test", t) { t.Error("Warning failed") } str := contents(warningLog) if !contains(infoLog, str, t) { t.Error("Info failed") } } // Test that a V glog goes to Info. func TestV(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) logging.verbosity.Set("2") defer logging.verbosity.Set("0") V(2).Info("test") if !contains(infoLog, "I", t) { t.Errorf("Info has wrong character: %q", contents(infoLog)) } if !contains(infoLog, "test", t) { t.Error("Info failed") } } // Test that a vmodule enables a glog in this file. func TestVmoduleOn(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) logging.vmodule.Set("glog_test=2") defer logging.vmodule.Set("") if !V(1) { t.Error("V not enabled for 1") } if !V(2) { t.Error("V not enabled for 2") } if V(3) { t.Error("V enabled for 3") } V(2).Info("test") if !contains(infoLog, "I", t) { t.Errorf("Info has wrong character: %q", contents(infoLog)) } if !contains(infoLog, "test", t) { t.Error("Info failed") } } // Test that a vmodule of another file does not enable a glog in this file. func TestVmoduleOff(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) logging.vmodule.Set("notthisfile=2") defer logging.vmodule.Set("") for i := 1; i <= 3; i++ { if V(Level(i)) { t.Errorf("V enabled for %d", i) } } V(2).Info("test") if contents(infoLog) != "" { t.Error("V logged incorrectly") } } // vGlobs are patterns that match/don't match this file at V=2. var vGlobs = map[string]bool{ // Easy to test the numeric match here. "glog_test=1": false, // If -vmodule sets V to 1, V(2) will fail. "glog_test=2": true, "glog_test=3": true, // If -vmodule sets V to 1, V(3) will succeed. // These all use 2 and check the patterns. All are true. "*=2": true, "?l*=2": true, "????_*=2": true, "??[mno]?_*t=2": true, // These all use 2 and check the patterns. All are false. "*x=2": false, "m*=2": false, "??_*=2": false, "?[abc]?_*t=2": false, } // Test that vmodule globbing works as advertised. func testVmoduleGlob(pat string, match bool, t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) defer logging.vmodule.Set("") logging.vmodule.Set(pat) if V(2) != Verbose(match) { t.Errorf("incorrect match for %q: got %t expected %t", pat, V(2), match) } } // Test that a vmodule globbing works as advertised. func TestVmoduleGlob(t *testing.T) { for glob, match := range vGlobs { testVmoduleGlob(glob, match, t) } } func TestRollover(t *testing.T) { setFlags() var err error defer func(previous func(error)) { logExitFunc = previous }(logExitFunc) logExitFunc = func(e error) { err = e } defer func(previous uint64) { MaxSize = previous }(MaxSize) MaxSize = 512 Info("x") // Be sure we have a file. info, ok := logging.file[infoLog].(*syncBuffer) if !ok { t.Fatal("info wasn't created") } if err != nil { t.Fatalf("info has initial error: %v", err) } fname0 := info.file.Name() Info(strings.Repeat("x", int(MaxSize))) // force a rollover if err != nil { t.Fatalf("info has error after big write: %v", err) } // Make sure the next glog file gets a file name with a different // time stamp. // // TODO: determine whether we need to support subsecond glog // rotation. C++ does not appear to handle this case (nor does it // handle Daylight Savings Time properly). time.Sleep(1 * time.Second) Info("x") // create a new file if err != nil { t.Fatalf("error after rotation: %v", err) } fname1 := info.file.Name() if fname0 == fname1 { t.Errorf("info.f.Name did not change: %v", fname0) } if info.nbytes >= MaxSize { t.Errorf("file size was not reset: %d", info.nbytes) } } func TestLogBacktraceAt(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) // The peculiar style of this code simplifies line counting and maintenance of the // tracing block below. var infoLine string setTraceLocation := func(file string, line int, ok bool, delta int) { if !ok { t.Fatal("could not get file:line") } _, file = filepath.Split(file) infoLine = fmt.Sprintf("%s:%d", file, line+delta) err := logging.traceLocation.Set(infoLine) if err != nil { t.Fatal("error setting log_backtrace_at: ", err) } } { // Start of tracing block. These lines know about each other's relative position. _, file, line, ok := runtime.Caller(0) setTraceLocation(file, line, ok, +2) // Two lines between Caller and Info calls. Info("we want a stack trace here") } numAppearances := strings.Count(contents(infoLog), infoLine) if numAppearances < 2 { // Need 2 appearances, one in the glog header and one in the trace: // log_test.go:281: I0511 16:36:06.952398 02238 log_test.go:280] we want a stack trace here // ... // github.com/glog/glog_test.go:280 (0x41ba91) // ... // We could be more precise but that would require knowing the details // of the traceback format, which may not be dependable. t.Fatal("got no trace back; glog is ", contents(infoLog)) } } func BenchmarkHeader(b *testing.B) { for i := 0; i < b.N; i++ { buf, _, _ := logging.header(infoLog, 0) logging.putBuffer(buf) } } ================================================ FILE: src/github.com/golang/protobuf/.gitignore ================================================ .DS_Store *.[568ao] *.ao *.so *.pyc ._* .nfs.* [568a].out *~ *.orig core _obj _test _testmain.go protoc-gen-go/testdata/multi/*.pb.go _conformance/_conformance ================================================ FILE: src/github.com/golang/protobuf/.travis.yml ================================================ sudo: false language: go go: - 1.6.x - 1.7.x - 1.8.x - 1.9.x install: - go get -v -d -t github.com/golang/protobuf/... - curl -L https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip -o /tmp/protoc.zip - unzip /tmp/protoc.zip -d $HOME/protoc env: - PATH=$HOME/protoc/bin:$PATH script: - make all test ================================================ FILE: src/github.com/golang/protobuf/AUTHORS ================================================ # This source code refers to The Go Authors for copyright purposes. # The master list of authors is in the main Go distribution, # visible at http://tip.golang.org/AUTHORS. ================================================ FILE: src/github.com/golang/protobuf/CONTRIBUTORS ================================================ # This source code was written by the Go contributors. # The master list of contributors is in the main Go distribution, # visible at http://tip.golang.org/CONTRIBUTORS. ================================================ FILE: src/github.com/golang/protobuf/LICENSE ================================================ Go support for Protocol Buffers - Google's data interchange format Copyright 2010 The Go Authors. All rights reserved. https://github.com/golang/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. ================================================ FILE: src/github.com/golang/protobuf/Make.protobuf ================================================ # Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/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. # Includable Makefile to add a rule for generating .pb.go files from .proto files # (Google protocol buffer descriptions). # Typical use if myproto.proto is a file in package mypackage in this directory: # # include $(GOROOT)/src/pkg/github.com/golang/protobuf/Make.protobuf %.pb.go: %.proto protoc --go_out=. $< ================================================ FILE: src/github.com/golang/protobuf/Makefile ================================================ # Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/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. all: install install: go install ./proto ./jsonpb ./ptypes go install ./protoc-gen-go test: go test ./proto ./jsonpb ./ptypes make -C protoc-gen-go/testdata test clean: go clean ./... nuke: go clean -i ./... regenerate: make -C protoc-gen-go/descriptor regenerate make -C protoc-gen-go/plugin regenerate make -C protoc-gen-go/testdata regenerate make -C proto/testdata regenerate make -C jsonpb/jsonpb_test_proto regenerate make -C _conformance regenerate ================================================ FILE: src/github.com/golang/protobuf/README.md ================================================ # Go support for Protocol Buffers [![Build Status](https://travis-ci.org/golang/protobuf.svg?branch=master)](https://travis-ci.org/golang/protobuf) [![GoDoc](https://godoc.org/github.com/golang/protobuf?status.svg)](https://godoc.org/github.com/golang/protobuf) Google's data interchange format. Copyright 2010 The Go Authors. https://github.com/golang/protobuf This package and the code it generates requires at least Go 1.4. This software implements Go bindings for protocol buffers. For information about protocol buffers themselves, see https://developers.google.com/protocol-buffers/ ## Installation ## To use this software, you must: - Install the standard C++ implementation of protocol buffers from https://developers.google.com/protocol-buffers/ - Of course, install the Go compiler and tools from https://golang.org/ See https://golang.org/doc/install for details or, if you are using gccgo, follow the instructions at https://golang.org/doc/install/gccgo - Grab the code from the repository and install the proto package. The simplest way is to run `go get -u github.com/golang/protobuf/protoc-gen-go`. The compiler plugin, protoc-gen-go, will be installed in $GOBIN, defaulting to $GOPATH/bin. It must be in your $PATH for the protocol compiler, protoc, to find it. This software has two parts: a 'protocol compiler plugin' that generates Go source files that, once compiled, can access and manage protocol buffers; and a library that implements run-time support for encoding (marshaling), decoding (unmarshaling), and accessing protocol buffers. There is support for gRPC in Go using protocol buffers. See the note at the bottom of this file for details. There are no insertion points in the plugin. ## Using protocol buffers with Go ## Once the software is installed, there are two steps to using it. First you must compile the protocol buffer definitions and then import them, with the support library, into your program. To compile the protocol buffer definition, run protoc with the --go_out parameter set to the directory you want to output the Go code to. protoc --go_out=. *.proto The generated files will be suffixed .pb.go. See the Test code below for an example using such a file. The package comment for the proto library contains text describing the interface provided in Go for protocol buffers. Here is an edited version. ========== The proto package converts data structures to and from the wire format of protocol buffers. It works in concert with the Go source code generated for .proto files by the protocol compiler. A summary of the properties of the protocol buffer interface for a protocol buffer variable v: - Names are turned from camel_case to CamelCase for export. - There are no methods on v to set fields; just treat them as structure fields. - There are getters that return a field's value if set, and return the field's default value if unset. The getters work even if the receiver is a nil message. - The zero value for a struct is its correct initialization state. All desired fields must be set before marshaling. - A Reset() method will restore a protobuf struct to its zero state. - Non-repeated fields are pointers to the values; nil means unset. That is, optional or required field int32 f becomes F *int32. - Repeated fields are slices. - Helper functions are available to aid the setting of fields. Helpers for getting values are superseded by the GetFoo methods and their use is deprecated. msg.Foo = proto.String("hello") // set field - Constants are defined to hold the default values of all fields that have them. They have the form Default_StructName_FieldName. Because the getter methods handle defaulted values, direct use of these constants should be rare. - Enums are given type names and maps from names to values. Enum values are prefixed with the enum's type name. Enum types have a String method, and a Enum method to assist in message construction. - Nested groups and enums have type names prefixed with the name of the surrounding message type. - Extensions are given descriptor names that start with E_, followed by an underscore-delimited list of the nested messages that contain it (if any) followed by the CamelCased name of the extension field itself. HasExtension, ClearExtension, GetExtension and SetExtension are functions for manipulating extensions. - Oneof field sets are given a single field in their message, with distinguished wrapper types for each possible field value. - Marshal and Unmarshal are functions to encode and decode the wire format. When the .proto file specifies `syntax="proto3"`, there are some differences: - Non-repeated fields of non-message type are values instead of pointers. - Enum types do not get an Enum method. Consider file test.proto, containing ```proto syntax = "proto2"; package example; enum FOO { X = 17; }; message Test { required string label = 1; optional int32 type = 2 [default=77]; repeated int64 reps = 3; optional group OptionalGroup = 4 { required string RequiredField = 5; } } ``` To create and play with a Test object from the example package, ```go package main import ( "log" "github.com/golang/protobuf/proto" "path/to/example" ) func main() { test := &example.Test { Label: proto.String("hello"), Type: proto.Int32(17), Reps: []int64{1, 2, 3}, Optionalgroup: &example.Test_OptionalGroup { RequiredField: proto.String("good bye"), }, } data, err := proto.Marshal(test) if err != nil { log.Fatal("marshaling error: ", err) } newTest := &example.Test{} err = proto.Unmarshal(data, newTest) if err != nil { log.Fatal("unmarshaling error: ", err) } // Now test and newTest contain the same data. if test.GetLabel() != newTest.GetLabel() { log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) } // etc. } ``` ## Parameters ## To pass extra parameters to the plugin, use a comma-separated parameter list separated from the output directory by a colon: protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto - `import_prefix=xxx` - a prefix that is added onto the beginning of all imports. Useful for things like generating protos in a subdirectory, or regenerating vendored protobufs in-place. - `import_path=foo/bar` - used as the package if no input files declare `go_package`. If it contains slashes, everything up to the rightmost slash is ignored. - `plugins=plugin1+plugin2` - specifies the list of sub-plugins to load. The only plugin in this repo is `grpc`. - `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is associated with Go package quux/shme. This is subject to the import_prefix parameter. ## gRPC Support ## If a proto file specifies RPC services, protoc-gen-go can be instructed to generate code compatible with gRPC (http://www.grpc.io/). To do this, pass the `plugins` parameter to protoc-gen-go; the usual way is to insert it into the --go_out argument to protoc: protoc --go_out=plugins=grpc:. *.proto ## Compatibility ## The library and the generated code are expected to be stable over time. However, we reserve the right to make breaking changes without notice for the following reasons: - Security. A security issue in the specification or implementation may come to light whose resolution requires breaking compatibility. We reserve the right to address such security issues. - Unspecified behavior. There are some aspects of the Protocol Buffers specification that are undefined. Programs that depend on such unspecified behavior may break in future releases. - Specification errors or changes. If it becomes necessary to address an inconsistency, incompleteness, or change in the Protocol Buffers specification, resolving the issue could affect the meaning or legality of existing programs. We reserve the right to address such issues, including updating the implementations. - Bugs. If the library has a bug that violates the specification, a program that depends on the buggy behavior may break if the bug is fixed. We reserve the right to fix such bugs. - Adding methods or fields to generated structs. These may conflict with field names that already exist in a schema, causing applications to break. When the code generator encounters a field in the schema that would collide with a generated field or method name, the code generator will append an underscore to the generated field or method name. - Adding, removing, or changing methods or fields in generated structs that start with `XXX`. These parts of the generated code are exported out of necessity, but should not be considered part of the public API. - Adding, removing, or changing unexported symbols in generated code. Any breaking changes outside of these will be announced 6 months in advance to protobuf@googlegroups.com. You should, whenever possible, use generated code created by the `protoc-gen-go` tool built at the same commit as the `proto` package. The `proto` package declares package-level constants in the form `ProtoPackageIsVersionX`. Application code and generated code may depend on one of these constants to ensure that compilation will fail if the available version of the proto library is too old. Whenever we make a change to the generated code that requires newer library support, in the same commit we will increment the version number of the generated code and declare a new package-level constant whose name incorporates the latest version number. Removing a compatibility constant is considered a breaking change and would be subject to the announcement policy stated above. The `protoc-gen-go/generator` package exposes a plugin interface, which is used by the gRPC code generation. This interface is not supported and is subject to incompatible changes without notice. ================================================ FILE: src/github.com/golang/protobuf/_conformance/Makefile ================================================ # Go support for Protocol Buffers - Google's data interchange format # # Copyright 2016 The Go Authors. All rights reserved. # https://github.com/golang/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. regenerate: protoc --go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any,Mgoogle/protobuf/duration.proto=github.com/golang/protobuf/ptypes/duration,Mgoogle/protobuf/struct.proto=github.com/golang/protobuf/ptypes/struct,Mgoogle/protobuf/timestamp.proto=github.com/golang/protobuf/ptypes/timestamp,Mgoogle/protobuf/wrappers.proto=github.com/golang/protobuf/ptypes/wrappers,Mgoogle/protobuf/field_mask.proto=google.golang.org/genproto/protobuf:. conformance_proto/conformance.proto ================================================ FILE: src/github.com/golang/protobuf/_conformance/conformance.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/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. // conformance implements the conformance test subprocess protocol as // documented in conformance.proto. package main import ( "encoding/binary" "fmt" "io" "os" pb "github.com/golang/protobuf/_conformance/conformance_proto" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/proto" ) func main() { var sizeBuf [4]byte inbuf := make([]byte, 0, 4096) outbuf := proto.NewBuffer(nil) for { if _, err := io.ReadFull(os.Stdin, sizeBuf[:]); err == io.EOF { break } else if err != nil { fmt.Fprintln(os.Stderr, "go conformance: read request:", err) os.Exit(1) } size := binary.LittleEndian.Uint32(sizeBuf[:]) if int(size) > cap(inbuf) { inbuf = make([]byte, size) } inbuf = inbuf[:size] if _, err := io.ReadFull(os.Stdin, inbuf); err != nil { fmt.Fprintln(os.Stderr, "go conformance: read request:", err) os.Exit(1) } req := new(pb.ConformanceRequest) if err := proto.Unmarshal(inbuf, req); err != nil { fmt.Fprintln(os.Stderr, "go conformance: parse request:", err) os.Exit(1) } res := handle(req) if err := outbuf.Marshal(res); err != nil { fmt.Fprintln(os.Stderr, "go conformance: marshal response:", err) os.Exit(1) } binary.LittleEndian.PutUint32(sizeBuf[:], uint32(len(outbuf.Bytes()))) if _, err := os.Stdout.Write(sizeBuf[:]); err != nil { fmt.Fprintln(os.Stderr, "go conformance: write response:", err) os.Exit(1) } if _, err := os.Stdout.Write(outbuf.Bytes()); err != nil { fmt.Fprintln(os.Stderr, "go conformance: write response:", err) os.Exit(1) } outbuf.Reset() } } var jsonMarshaler = jsonpb.Marshaler{ OrigName: true, } func handle(req *pb.ConformanceRequest) *pb.ConformanceResponse { var err error var msg pb.TestAllTypes switch p := req.Payload.(type) { case *pb.ConformanceRequest_ProtobufPayload: err = proto.Unmarshal(p.ProtobufPayload, &msg) case *pb.ConformanceRequest_JsonPayload: err = jsonpb.UnmarshalString(p.JsonPayload, &msg) if err != nil && err.Error() == "unmarshaling Any not supported yet" { return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_Skipped{ Skipped: err.Error(), }, } } default: return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_RuntimeError{ RuntimeError: "unknown request payload type", }, } } if err != nil { return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_ParseError{ ParseError: err.Error(), }, } } switch req.RequestedOutputFormat { case pb.WireFormat_PROTOBUF: p, err := proto.Marshal(&msg) if err != nil { return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_SerializeError{ SerializeError: err.Error(), }, } } return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_ProtobufPayload{ ProtobufPayload: p, }, } case pb.WireFormat_JSON: p, err := jsonMarshaler.MarshalToString(&msg) if err != nil { return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_SerializeError{ SerializeError: err.Error(), }, } } return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_JsonPayload{ JsonPayload: p, }, } default: return &pb.ConformanceResponse{ Result: &pb.ConformanceResponse_RuntimeError{ RuntimeError: "unknown output format", }, } } } ================================================ FILE: src/github.com/golang/protobuf/_conformance/conformance_proto/conformance.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: conformance_proto/conformance.proto /* Package conformance is a generated protocol buffer package. It is generated from these files: conformance_proto/conformance.proto It has these top-level messages: ConformanceRequest ConformanceResponse TestAllTypes ForeignMessage */ package conformance import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import google_protobuf "github.com/golang/protobuf/ptypes/any" import google_protobuf1 "github.com/golang/protobuf/ptypes/duration" import google_protobuf2 "google.golang.org/genproto/protobuf" import google_protobuf3 "github.com/golang/protobuf/ptypes/struct" import google_protobuf4 "github.com/golang/protobuf/ptypes/timestamp" import google_protobuf5 "github.com/golang/protobuf/ptypes/wrappers" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type WireFormat int32 const ( WireFormat_UNSPECIFIED WireFormat = 0 WireFormat_PROTOBUF WireFormat = 1 WireFormat_JSON WireFormat = 2 ) var WireFormat_name = map[int32]string{ 0: "UNSPECIFIED", 1: "PROTOBUF", 2: "JSON", } var WireFormat_value = map[string]int32{ "UNSPECIFIED": 0, "PROTOBUF": 1, "JSON": 2, } func (x WireFormat) String() string { return proto.EnumName(WireFormat_name, int32(x)) } func (WireFormat) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } type ForeignEnum int32 const ( ForeignEnum_FOREIGN_FOO ForeignEnum = 0 ForeignEnum_FOREIGN_BAR ForeignEnum = 1 ForeignEnum_FOREIGN_BAZ ForeignEnum = 2 ) var ForeignEnum_name = map[int32]string{ 0: "FOREIGN_FOO", 1: "FOREIGN_BAR", 2: "FOREIGN_BAZ", } var ForeignEnum_value = map[string]int32{ "FOREIGN_FOO": 0, "FOREIGN_BAR": 1, "FOREIGN_BAZ": 2, } func (x ForeignEnum) String() string { return proto.EnumName(ForeignEnum_name, int32(x)) } func (ForeignEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } type TestAllTypes_NestedEnum int32 const ( TestAllTypes_FOO TestAllTypes_NestedEnum = 0 TestAllTypes_BAR TestAllTypes_NestedEnum = 1 TestAllTypes_BAZ TestAllTypes_NestedEnum = 2 TestAllTypes_NEG TestAllTypes_NestedEnum = -1 ) var TestAllTypes_NestedEnum_name = map[int32]string{ 0: "FOO", 1: "BAR", 2: "BAZ", -1: "NEG", } var TestAllTypes_NestedEnum_value = map[string]int32{ "FOO": 0, "BAR": 1, "BAZ": 2, "NEG": -1, } func (x TestAllTypes_NestedEnum) String() string { return proto.EnumName(TestAllTypes_NestedEnum_name, int32(x)) } func (TestAllTypes_NestedEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } // Represents a single test case's input. The testee should: // // 1. parse this proto (which should always succeed) // 2. parse the protobuf or JSON payload in "payload" (which may fail) // 3. if the parse succeeded, serialize the message in the requested format. type ConformanceRequest struct { // The payload (whether protobuf of JSON) is always for a TestAllTypes proto // (see below). // // Types that are valid to be assigned to Payload: // *ConformanceRequest_ProtobufPayload // *ConformanceRequest_JsonPayload Payload isConformanceRequest_Payload `protobuf_oneof:"payload"` // Which format should the testee serialize its message to? RequestedOutputFormat WireFormat `protobuf:"varint,3,opt,name=requested_output_format,json=requestedOutputFormat,enum=conformance.WireFormat" json:"requested_output_format,omitempty"` } func (m *ConformanceRequest) Reset() { *m = ConformanceRequest{} } func (m *ConformanceRequest) String() string { return proto.CompactTextString(m) } func (*ConformanceRequest) ProtoMessage() {} func (*ConformanceRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } type isConformanceRequest_Payload interface { isConformanceRequest_Payload() } type ConformanceRequest_ProtobufPayload struct { ProtobufPayload []byte `protobuf:"bytes,1,opt,name=protobuf_payload,json=protobufPayload,proto3,oneof"` } type ConformanceRequest_JsonPayload struct { JsonPayload string `protobuf:"bytes,2,opt,name=json_payload,json=jsonPayload,oneof"` } func (*ConformanceRequest_ProtobufPayload) isConformanceRequest_Payload() {} func (*ConformanceRequest_JsonPayload) isConformanceRequest_Payload() {} func (m *ConformanceRequest) GetPayload() isConformanceRequest_Payload { if m != nil { return m.Payload } return nil } func (m *ConformanceRequest) GetProtobufPayload() []byte { if x, ok := m.GetPayload().(*ConformanceRequest_ProtobufPayload); ok { return x.ProtobufPayload } return nil } func (m *ConformanceRequest) GetJsonPayload() string { if x, ok := m.GetPayload().(*ConformanceRequest_JsonPayload); ok { return x.JsonPayload } return "" } func (m *ConformanceRequest) GetRequestedOutputFormat() WireFormat { if m != nil { return m.RequestedOutputFormat } return WireFormat_UNSPECIFIED } // XXX_OneofFuncs is for the internal use of the proto package. func (*ConformanceRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _ConformanceRequest_OneofMarshaler, _ConformanceRequest_OneofUnmarshaler, _ConformanceRequest_OneofSizer, []interface{}{ (*ConformanceRequest_ProtobufPayload)(nil), (*ConformanceRequest_JsonPayload)(nil), } } func _ConformanceRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*ConformanceRequest) // payload switch x := m.Payload.(type) { case *ConformanceRequest_ProtobufPayload: b.EncodeVarint(1<<3 | proto.WireBytes) b.EncodeRawBytes(x.ProtobufPayload) case *ConformanceRequest_JsonPayload: b.EncodeVarint(2<<3 | proto.WireBytes) b.EncodeStringBytes(x.JsonPayload) case nil: default: return fmt.Errorf("ConformanceRequest.Payload has unexpected type %T", x) } return nil } func _ConformanceRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*ConformanceRequest) switch tag { case 1: // payload.protobuf_payload if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Payload = &ConformanceRequest_ProtobufPayload{x} return true, err case 2: // payload.json_payload if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Payload = &ConformanceRequest_JsonPayload{x} return true, err default: return false, nil } } func _ConformanceRequest_OneofSizer(msg proto.Message) (n int) { m := msg.(*ConformanceRequest) // payload switch x := m.Payload.(type) { case *ConformanceRequest_ProtobufPayload: n += proto.SizeVarint(1<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.ProtobufPayload))) n += len(x.ProtobufPayload) case *ConformanceRequest_JsonPayload: n += proto.SizeVarint(2<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.JsonPayload))) n += len(x.JsonPayload) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // Represents a single test case's output. type ConformanceResponse struct { // Types that are valid to be assigned to Result: // *ConformanceResponse_ParseError // *ConformanceResponse_SerializeError // *ConformanceResponse_RuntimeError // *ConformanceResponse_ProtobufPayload // *ConformanceResponse_JsonPayload // *ConformanceResponse_Skipped Result isConformanceResponse_Result `protobuf_oneof:"result"` } func (m *ConformanceResponse) Reset() { *m = ConformanceResponse{} } func (m *ConformanceResponse) String() string { return proto.CompactTextString(m) } func (*ConformanceResponse) ProtoMessage() {} func (*ConformanceResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } type isConformanceResponse_Result interface { isConformanceResponse_Result() } type ConformanceResponse_ParseError struct { ParseError string `protobuf:"bytes,1,opt,name=parse_error,json=parseError,oneof"` } type ConformanceResponse_SerializeError struct { SerializeError string `protobuf:"bytes,6,opt,name=serialize_error,json=serializeError,oneof"` } type ConformanceResponse_RuntimeError struct { RuntimeError string `protobuf:"bytes,2,opt,name=runtime_error,json=runtimeError,oneof"` } type ConformanceResponse_ProtobufPayload struct { ProtobufPayload []byte `protobuf:"bytes,3,opt,name=protobuf_payload,json=protobufPayload,proto3,oneof"` } type ConformanceResponse_JsonPayload struct { JsonPayload string `protobuf:"bytes,4,opt,name=json_payload,json=jsonPayload,oneof"` } type ConformanceResponse_Skipped struct { Skipped string `protobuf:"bytes,5,opt,name=skipped,oneof"` } func (*ConformanceResponse_ParseError) isConformanceResponse_Result() {} func (*ConformanceResponse_SerializeError) isConformanceResponse_Result() {} func (*ConformanceResponse_RuntimeError) isConformanceResponse_Result() {} func (*ConformanceResponse_ProtobufPayload) isConformanceResponse_Result() {} func (*ConformanceResponse_JsonPayload) isConformanceResponse_Result() {} func (*ConformanceResponse_Skipped) isConformanceResponse_Result() {} func (m *ConformanceResponse) GetResult() isConformanceResponse_Result { if m != nil { return m.Result } return nil } func (m *ConformanceResponse) GetParseError() string { if x, ok := m.GetResult().(*ConformanceResponse_ParseError); ok { return x.ParseError } return "" } func (m *ConformanceResponse) GetSerializeError() string { if x, ok := m.GetResult().(*ConformanceResponse_SerializeError); ok { return x.SerializeError } return "" } func (m *ConformanceResponse) GetRuntimeError() string { if x, ok := m.GetResult().(*ConformanceResponse_RuntimeError); ok { return x.RuntimeError } return "" } func (m *ConformanceResponse) GetProtobufPayload() []byte { if x, ok := m.GetResult().(*ConformanceResponse_ProtobufPayload); ok { return x.ProtobufPayload } return nil } func (m *ConformanceResponse) GetJsonPayload() string { if x, ok := m.GetResult().(*ConformanceResponse_JsonPayload); ok { return x.JsonPayload } return "" } func (m *ConformanceResponse) GetSkipped() string { if x, ok := m.GetResult().(*ConformanceResponse_Skipped); ok { return x.Skipped } return "" } // XXX_OneofFuncs is for the internal use of the proto package. func (*ConformanceResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _ConformanceResponse_OneofMarshaler, _ConformanceResponse_OneofUnmarshaler, _ConformanceResponse_OneofSizer, []interface{}{ (*ConformanceResponse_ParseError)(nil), (*ConformanceResponse_SerializeError)(nil), (*ConformanceResponse_RuntimeError)(nil), (*ConformanceResponse_ProtobufPayload)(nil), (*ConformanceResponse_JsonPayload)(nil), (*ConformanceResponse_Skipped)(nil), } } func _ConformanceResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*ConformanceResponse) // result switch x := m.Result.(type) { case *ConformanceResponse_ParseError: b.EncodeVarint(1<<3 | proto.WireBytes) b.EncodeStringBytes(x.ParseError) case *ConformanceResponse_SerializeError: b.EncodeVarint(6<<3 | proto.WireBytes) b.EncodeStringBytes(x.SerializeError) case *ConformanceResponse_RuntimeError: b.EncodeVarint(2<<3 | proto.WireBytes) b.EncodeStringBytes(x.RuntimeError) case *ConformanceResponse_ProtobufPayload: b.EncodeVarint(3<<3 | proto.WireBytes) b.EncodeRawBytes(x.ProtobufPayload) case *ConformanceResponse_JsonPayload: b.EncodeVarint(4<<3 | proto.WireBytes) b.EncodeStringBytes(x.JsonPayload) case *ConformanceResponse_Skipped: b.EncodeVarint(5<<3 | proto.WireBytes) b.EncodeStringBytes(x.Skipped) case nil: default: return fmt.Errorf("ConformanceResponse.Result has unexpected type %T", x) } return nil } func _ConformanceResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*ConformanceResponse) switch tag { case 1: // result.parse_error if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Result = &ConformanceResponse_ParseError{x} return true, err case 6: // result.serialize_error if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Result = &ConformanceResponse_SerializeError{x} return true, err case 2: // result.runtime_error if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Result = &ConformanceResponse_RuntimeError{x} return true, err case 3: // result.protobuf_payload if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Result = &ConformanceResponse_ProtobufPayload{x} return true, err case 4: // result.json_payload if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Result = &ConformanceResponse_JsonPayload{x} return true, err case 5: // result.skipped if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Result = &ConformanceResponse_Skipped{x} return true, err default: return false, nil } } func _ConformanceResponse_OneofSizer(msg proto.Message) (n int) { m := msg.(*ConformanceResponse) // result switch x := m.Result.(type) { case *ConformanceResponse_ParseError: n += proto.SizeVarint(1<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.ParseError))) n += len(x.ParseError) case *ConformanceResponse_SerializeError: n += proto.SizeVarint(6<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.SerializeError))) n += len(x.SerializeError) case *ConformanceResponse_RuntimeError: n += proto.SizeVarint(2<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.RuntimeError))) n += len(x.RuntimeError) case *ConformanceResponse_ProtobufPayload: n += proto.SizeVarint(3<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.ProtobufPayload))) n += len(x.ProtobufPayload) case *ConformanceResponse_JsonPayload: n += proto.SizeVarint(4<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.JsonPayload))) n += len(x.JsonPayload) case *ConformanceResponse_Skipped: n += proto.SizeVarint(5<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Skipped))) n += len(x.Skipped) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // This proto includes every type of field in both singular and repeated // forms. type TestAllTypes struct { // Singular OptionalInt32 int32 `protobuf:"varint,1,opt,name=optional_int32,json=optionalInt32" json:"optional_int32,omitempty"` OptionalInt64 int64 `protobuf:"varint,2,opt,name=optional_int64,json=optionalInt64" json:"optional_int64,omitempty"` OptionalUint32 uint32 `protobuf:"varint,3,opt,name=optional_uint32,json=optionalUint32" json:"optional_uint32,omitempty"` OptionalUint64 uint64 `protobuf:"varint,4,opt,name=optional_uint64,json=optionalUint64" json:"optional_uint64,omitempty"` OptionalSint32 int32 `protobuf:"zigzag32,5,opt,name=optional_sint32,json=optionalSint32" json:"optional_sint32,omitempty"` OptionalSint64 int64 `protobuf:"zigzag64,6,opt,name=optional_sint64,json=optionalSint64" json:"optional_sint64,omitempty"` OptionalFixed32 uint32 `protobuf:"fixed32,7,opt,name=optional_fixed32,json=optionalFixed32" json:"optional_fixed32,omitempty"` OptionalFixed64 uint64 `protobuf:"fixed64,8,opt,name=optional_fixed64,json=optionalFixed64" json:"optional_fixed64,omitempty"` OptionalSfixed32 int32 `protobuf:"fixed32,9,opt,name=optional_sfixed32,json=optionalSfixed32" json:"optional_sfixed32,omitempty"` OptionalSfixed64 int64 `protobuf:"fixed64,10,opt,name=optional_sfixed64,json=optionalSfixed64" json:"optional_sfixed64,omitempty"` OptionalFloat float32 `protobuf:"fixed32,11,opt,name=optional_float,json=optionalFloat" json:"optional_float,omitempty"` OptionalDouble float64 `protobuf:"fixed64,12,opt,name=optional_double,json=optionalDouble" json:"optional_double,omitempty"` OptionalBool bool `protobuf:"varint,13,opt,name=optional_bool,json=optionalBool" json:"optional_bool,omitempty"` OptionalString string `protobuf:"bytes,14,opt,name=optional_string,json=optionalString" json:"optional_string,omitempty"` OptionalBytes []byte `protobuf:"bytes,15,opt,name=optional_bytes,json=optionalBytes,proto3" json:"optional_bytes,omitempty"` OptionalNestedMessage *TestAllTypes_NestedMessage `protobuf:"bytes,18,opt,name=optional_nested_message,json=optionalNestedMessage" json:"optional_nested_message,omitempty"` OptionalForeignMessage *ForeignMessage `protobuf:"bytes,19,opt,name=optional_foreign_message,json=optionalForeignMessage" json:"optional_foreign_message,omitempty"` OptionalNestedEnum TestAllTypes_NestedEnum `protobuf:"varint,21,opt,name=optional_nested_enum,json=optionalNestedEnum,enum=conformance.TestAllTypes_NestedEnum" json:"optional_nested_enum,omitempty"` OptionalForeignEnum ForeignEnum `protobuf:"varint,22,opt,name=optional_foreign_enum,json=optionalForeignEnum,enum=conformance.ForeignEnum" json:"optional_foreign_enum,omitempty"` OptionalStringPiece string `protobuf:"bytes,24,opt,name=optional_string_piece,json=optionalStringPiece" json:"optional_string_piece,omitempty"` OptionalCord string `protobuf:"bytes,25,opt,name=optional_cord,json=optionalCord" json:"optional_cord,omitempty"` RecursiveMessage *TestAllTypes `protobuf:"bytes,27,opt,name=recursive_message,json=recursiveMessage" json:"recursive_message,omitempty"` // Repeated RepeatedInt32 []int32 `protobuf:"varint,31,rep,packed,name=repeated_int32,json=repeatedInt32" json:"repeated_int32,omitempty"` RepeatedInt64 []int64 `protobuf:"varint,32,rep,packed,name=repeated_int64,json=repeatedInt64" json:"repeated_int64,omitempty"` RepeatedUint32 []uint32 `protobuf:"varint,33,rep,packed,name=repeated_uint32,json=repeatedUint32" json:"repeated_uint32,omitempty"` RepeatedUint64 []uint64 `protobuf:"varint,34,rep,packed,name=repeated_uint64,json=repeatedUint64" json:"repeated_uint64,omitempty"` RepeatedSint32 []int32 `protobuf:"zigzag32,35,rep,packed,name=repeated_sint32,json=repeatedSint32" json:"repeated_sint32,omitempty"` RepeatedSint64 []int64 `protobuf:"zigzag64,36,rep,packed,name=repeated_sint64,json=repeatedSint64" json:"repeated_sint64,omitempty"` RepeatedFixed32 []uint32 `protobuf:"fixed32,37,rep,packed,name=repeated_fixed32,json=repeatedFixed32" json:"repeated_fixed32,omitempty"` RepeatedFixed64 []uint64 `protobuf:"fixed64,38,rep,packed,name=repeated_fixed64,json=repeatedFixed64" json:"repeated_fixed64,omitempty"` RepeatedSfixed32 []int32 `protobuf:"fixed32,39,rep,packed,name=repeated_sfixed32,json=repeatedSfixed32" json:"repeated_sfixed32,omitempty"` RepeatedSfixed64 []int64 `protobuf:"fixed64,40,rep,packed,name=repeated_sfixed64,json=repeatedSfixed64" json:"repeated_sfixed64,omitempty"` RepeatedFloat []float32 `protobuf:"fixed32,41,rep,packed,name=repeated_float,json=repeatedFloat" json:"repeated_float,omitempty"` RepeatedDouble []float64 `protobuf:"fixed64,42,rep,packed,name=repeated_double,json=repeatedDouble" json:"repeated_double,omitempty"` RepeatedBool []bool `protobuf:"varint,43,rep,packed,name=repeated_bool,json=repeatedBool" json:"repeated_bool,omitempty"` RepeatedString []string `protobuf:"bytes,44,rep,name=repeated_string,json=repeatedString" json:"repeated_string,omitempty"` RepeatedBytes [][]byte `protobuf:"bytes,45,rep,name=repeated_bytes,json=repeatedBytes,proto3" json:"repeated_bytes,omitempty"` RepeatedNestedMessage []*TestAllTypes_NestedMessage `protobuf:"bytes,48,rep,name=repeated_nested_message,json=repeatedNestedMessage" json:"repeated_nested_message,omitempty"` RepeatedForeignMessage []*ForeignMessage `protobuf:"bytes,49,rep,name=repeated_foreign_message,json=repeatedForeignMessage" json:"repeated_foreign_message,omitempty"` RepeatedNestedEnum []TestAllTypes_NestedEnum `protobuf:"varint,51,rep,packed,name=repeated_nested_enum,json=repeatedNestedEnum,enum=conformance.TestAllTypes_NestedEnum" json:"repeated_nested_enum,omitempty"` RepeatedForeignEnum []ForeignEnum `protobuf:"varint,52,rep,packed,name=repeated_foreign_enum,json=repeatedForeignEnum,enum=conformance.ForeignEnum" json:"repeated_foreign_enum,omitempty"` RepeatedStringPiece []string `protobuf:"bytes,54,rep,name=repeated_string_piece,json=repeatedStringPiece" json:"repeated_string_piece,omitempty"` RepeatedCord []string `protobuf:"bytes,55,rep,name=repeated_cord,json=repeatedCord" json:"repeated_cord,omitempty"` // Map MapInt32Int32 map[int32]int32 `protobuf:"bytes,56,rep,name=map_int32_int32,json=mapInt32Int32" json:"map_int32_int32,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` MapInt64Int64 map[int64]int64 `protobuf:"bytes,57,rep,name=map_int64_int64,json=mapInt64Int64" json:"map_int64_int64,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` MapUint32Uint32 map[uint32]uint32 `protobuf:"bytes,58,rep,name=map_uint32_uint32,json=mapUint32Uint32" json:"map_uint32_uint32,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` MapUint64Uint64 map[uint64]uint64 `protobuf:"bytes,59,rep,name=map_uint64_uint64,json=mapUint64Uint64" json:"map_uint64_uint64,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` MapSint32Sint32 map[int32]int32 `protobuf:"bytes,60,rep,name=map_sint32_sint32,json=mapSint32Sint32" json:"map_sint32_sint32,omitempty" protobuf_key:"zigzag32,1,opt,name=key" protobuf_val:"zigzag32,2,opt,name=value"` MapSint64Sint64 map[int64]int64 `protobuf:"bytes,61,rep,name=map_sint64_sint64,json=mapSint64Sint64" json:"map_sint64_sint64,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"zigzag64,2,opt,name=value"` MapFixed32Fixed32 map[uint32]uint32 `protobuf:"bytes,62,rep,name=map_fixed32_fixed32,json=mapFixed32Fixed32" json:"map_fixed32_fixed32,omitempty" protobuf_key:"fixed32,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"` MapFixed64Fixed64 map[uint64]uint64 `protobuf:"bytes,63,rep,name=map_fixed64_fixed64,json=mapFixed64Fixed64" json:"map_fixed64_fixed64,omitempty" protobuf_key:"fixed64,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"` MapSfixed32Sfixed32 map[int32]int32 `protobuf:"bytes,64,rep,name=map_sfixed32_sfixed32,json=mapSfixed32Sfixed32" json:"map_sfixed32_sfixed32,omitempty" protobuf_key:"fixed32,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"` MapSfixed64Sfixed64 map[int64]int64 `protobuf:"bytes,65,rep,name=map_sfixed64_sfixed64,json=mapSfixed64Sfixed64" json:"map_sfixed64_sfixed64,omitempty" protobuf_key:"fixed64,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"` MapInt32Float map[int32]float32 `protobuf:"bytes,66,rep,name=map_int32_float,json=mapInt32Float" json:"map_int32_float,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"` MapInt32Double map[int32]float64 `protobuf:"bytes,67,rep,name=map_int32_double,json=mapInt32Double" json:"map_int32_double,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"` MapBoolBool map[bool]bool `protobuf:"bytes,68,rep,name=map_bool_bool,json=mapBoolBool" json:"map_bool_bool,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` MapStringString map[string]string `protobuf:"bytes,69,rep,name=map_string_string,json=mapStringString" json:"map_string_string,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` MapStringBytes map[string][]byte `protobuf:"bytes,70,rep,name=map_string_bytes,json=mapStringBytes" json:"map_string_bytes,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"` MapStringNestedMessage map[string]*TestAllTypes_NestedMessage `protobuf:"bytes,71,rep,name=map_string_nested_message,json=mapStringNestedMessage" json:"map_string_nested_message,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` MapStringForeignMessage map[string]*ForeignMessage `protobuf:"bytes,72,rep,name=map_string_foreign_message,json=mapStringForeignMessage" json:"map_string_foreign_message,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` MapStringNestedEnum map[string]TestAllTypes_NestedEnum `protobuf:"bytes,73,rep,name=map_string_nested_enum,json=mapStringNestedEnum" json:"map_string_nested_enum,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=conformance.TestAllTypes_NestedEnum"` MapStringForeignEnum map[string]ForeignEnum `protobuf:"bytes,74,rep,name=map_string_foreign_enum,json=mapStringForeignEnum" json:"map_string_foreign_enum,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=conformance.ForeignEnum"` // Types that are valid to be assigned to OneofField: // *TestAllTypes_OneofUint32 // *TestAllTypes_OneofNestedMessage // *TestAllTypes_OneofString // *TestAllTypes_OneofBytes // *TestAllTypes_OneofBool // *TestAllTypes_OneofUint64 // *TestAllTypes_OneofFloat // *TestAllTypes_OneofDouble // *TestAllTypes_OneofEnum OneofField isTestAllTypes_OneofField `protobuf_oneof:"oneof_field"` // Well-known types OptionalBoolWrapper *google_protobuf5.BoolValue `protobuf:"bytes,201,opt,name=optional_bool_wrapper,json=optionalBoolWrapper" json:"optional_bool_wrapper,omitempty"` OptionalInt32Wrapper *google_protobuf5.Int32Value `protobuf:"bytes,202,opt,name=optional_int32_wrapper,json=optionalInt32Wrapper" json:"optional_int32_wrapper,omitempty"` OptionalInt64Wrapper *google_protobuf5.Int64Value `protobuf:"bytes,203,opt,name=optional_int64_wrapper,json=optionalInt64Wrapper" json:"optional_int64_wrapper,omitempty"` OptionalUint32Wrapper *google_protobuf5.UInt32Value `protobuf:"bytes,204,opt,name=optional_uint32_wrapper,json=optionalUint32Wrapper" json:"optional_uint32_wrapper,omitempty"` OptionalUint64Wrapper *google_protobuf5.UInt64Value `protobuf:"bytes,205,opt,name=optional_uint64_wrapper,json=optionalUint64Wrapper" json:"optional_uint64_wrapper,omitempty"` OptionalFloatWrapper *google_protobuf5.FloatValue `protobuf:"bytes,206,opt,name=optional_float_wrapper,json=optionalFloatWrapper" json:"optional_float_wrapper,omitempty"` OptionalDoubleWrapper *google_protobuf5.DoubleValue `protobuf:"bytes,207,opt,name=optional_double_wrapper,json=optionalDoubleWrapper" json:"optional_double_wrapper,omitempty"` OptionalStringWrapper *google_protobuf5.StringValue `protobuf:"bytes,208,opt,name=optional_string_wrapper,json=optionalStringWrapper" json:"optional_string_wrapper,omitempty"` OptionalBytesWrapper *google_protobuf5.BytesValue `protobuf:"bytes,209,opt,name=optional_bytes_wrapper,json=optionalBytesWrapper" json:"optional_bytes_wrapper,omitempty"` RepeatedBoolWrapper []*google_protobuf5.BoolValue `protobuf:"bytes,211,rep,name=repeated_bool_wrapper,json=repeatedBoolWrapper" json:"repeated_bool_wrapper,omitempty"` RepeatedInt32Wrapper []*google_protobuf5.Int32Value `protobuf:"bytes,212,rep,name=repeated_int32_wrapper,json=repeatedInt32Wrapper" json:"repeated_int32_wrapper,omitempty"` RepeatedInt64Wrapper []*google_protobuf5.Int64Value `protobuf:"bytes,213,rep,name=repeated_int64_wrapper,json=repeatedInt64Wrapper" json:"repeated_int64_wrapper,omitempty"` RepeatedUint32Wrapper []*google_protobuf5.UInt32Value `protobuf:"bytes,214,rep,name=repeated_uint32_wrapper,json=repeatedUint32Wrapper" json:"repeated_uint32_wrapper,omitempty"` RepeatedUint64Wrapper []*google_protobuf5.UInt64Value `protobuf:"bytes,215,rep,name=repeated_uint64_wrapper,json=repeatedUint64Wrapper" json:"repeated_uint64_wrapper,omitempty"` RepeatedFloatWrapper []*google_protobuf5.FloatValue `protobuf:"bytes,216,rep,name=repeated_float_wrapper,json=repeatedFloatWrapper" json:"repeated_float_wrapper,omitempty"` RepeatedDoubleWrapper []*google_protobuf5.DoubleValue `protobuf:"bytes,217,rep,name=repeated_double_wrapper,json=repeatedDoubleWrapper" json:"repeated_double_wrapper,omitempty"` RepeatedStringWrapper []*google_protobuf5.StringValue `protobuf:"bytes,218,rep,name=repeated_string_wrapper,json=repeatedStringWrapper" json:"repeated_string_wrapper,omitempty"` RepeatedBytesWrapper []*google_protobuf5.BytesValue `protobuf:"bytes,219,rep,name=repeated_bytes_wrapper,json=repeatedBytesWrapper" json:"repeated_bytes_wrapper,omitempty"` OptionalDuration *google_protobuf1.Duration `protobuf:"bytes,301,opt,name=optional_duration,json=optionalDuration" json:"optional_duration,omitempty"` OptionalTimestamp *google_protobuf4.Timestamp `protobuf:"bytes,302,opt,name=optional_timestamp,json=optionalTimestamp" json:"optional_timestamp,omitempty"` OptionalFieldMask *google_protobuf2.FieldMask `protobuf:"bytes,303,opt,name=optional_field_mask,json=optionalFieldMask" json:"optional_field_mask,omitempty"` OptionalStruct *google_protobuf3.Struct `protobuf:"bytes,304,opt,name=optional_struct,json=optionalStruct" json:"optional_struct,omitempty"` OptionalAny *google_protobuf.Any `protobuf:"bytes,305,opt,name=optional_any,json=optionalAny" json:"optional_any,omitempty"` OptionalValue *google_protobuf3.Value `protobuf:"bytes,306,opt,name=optional_value,json=optionalValue" json:"optional_value,omitempty"` RepeatedDuration []*google_protobuf1.Duration `protobuf:"bytes,311,rep,name=repeated_duration,json=repeatedDuration" json:"repeated_duration,omitempty"` RepeatedTimestamp []*google_protobuf4.Timestamp `protobuf:"bytes,312,rep,name=repeated_timestamp,json=repeatedTimestamp" json:"repeated_timestamp,omitempty"` RepeatedFieldmask []*google_protobuf2.FieldMask `protobuf:"bytes,313,rep,name=repeated_fieldmask,json=repeatedFieldmask" json:"repeated_fieldmask,omitempty"` RepeatedStruct []*google_protobuf3.Struct `protobuf:"bytes,324,rep,name=repeated_struct,json=repeatedStruct" json:"repeated_struct,omitempty"` RepeatedAny []*google_protobuf.Any `protobuf:"bytes,315,rep,name=repeated_any,json=repeatedAny" json:"repeated_any,omitempty"` RepeatedValue []*google_protobuf3.Value `protobuf:"bytes,316,rep,name=repeated_value,json=repeatedValue" json:"repeated_value,omitempty"` // Test field-name-to-JSON-name convention. // (protobuf says names can be any valid C/C++ identifier.) Fieldname1 int32 `protobuf:"varint,401,opt,name=fieldname1" json:"fieldname1,omitempty"` FieldName2 int32 `protobuf:"varint,402,opt,name=field_name2,json=fieldName2" json:"field_name2,omitempty"` XFieldName3 int32 `protobuf:"varint,403,opt,name=_field_name3,json=FieldName3" json:"_field_name3,omitempty"` Field_Name4_ int32 `protobuf:"varint,404,opt,name=field__name4_,json=fieldName4" json:"field__name4_,omitempty"` Field0Name5 int32 `protobuf:"varint,405,opt,name=field0name5" json:"field0name5,omitempty"` Field_0Name6 int32 `protobuf:"varint,406,opt,name=field_0_name6,json=field0Name6" json:"field_0_name6,omitempty"` FieldName7 int32 `protobuf:"varint,407,opt,name=fieldName7" json:"fieldName7,omitempty"` FieldName8 int32 `protobuf:"varint,408,opt,name=FieldName8" json:"FieldName8,omitempty"` Field_Name9 int32 `protobuf:"varint,409,opt,name=field_Name9,json=fieldName9" json:"field_Name9,omitempty"` Field_Name10 int32 `protobuf:"varint,410,opt,name=Field_Name10,json=FieldName10" json:"Field_Name10,omitempty"` FIELD_NAME11 int32 `protobuf:"varint,411,opt,name=FIELD_NAME11,json=FIELDNAME11" json:"FIELD_NAME11,omitempty"` FIELDName12 int32 `protobuf:"varint,412,opt,name=FIELD_name12,json=FIELDName12" json:"FIELD_name12,omitempty"` XFieldName13 int32 `protobuf:"varint,413,opt,name=__field_name13,json=FieldName13" json:"__field_name13,omitempty"` X_FieldName14 int32 `protobuf:"varint,414,opt,name=__Field_name14,json=FieldName14" json:"__Field_name14,omitempty"` Field_Name15 int32 `protobuf:"varint,415,opt,name=field__name15,json=fieldName15" json:"field__name15,omitempty"` Field__Name16 int32 `protobuf:"varint,416,opt,name=field__Name16,json=fieldName16" json:"field__Name16,omitempty"` FieldName17__ int32 `protobuf:"varint,417,opt,name=field_name17__,json=fieldName17" json:"field_name17__,omitempty"` FieldName18__ int32 `protobuf:"varint,418,opt,name=Field_name18__,json=FieldName18" json:"Field_name18__,omitempty"` } func (m *TestAllTypes) Reset() { *m = TestAllTypes{} } func (m *TestAllTypes) String() string { return proto.CompactTextString(m) } func (*TestAllTypes) ProtoMessage() {} func (*TestAllTypes) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } type isTestAllTypes_OneofField interface { isTestAllTypes_OneofField() } type TestAllTypes_OneofUint32 struct { OneofUint32 uint32 `protobuf:"varint,111,opt,name=oneof_uint32,json=oneofUint32,oneof"` } type TestAllTypes_OneofNestedMessage struct { OneofNestedMessage *TestAllTypes_NestedMessage `protobuf:"bytes,112,opt,name=oneof_nested_message,json=oneofNestedMessage,oneof"` } type TestAllTypes_OneofString struct { OneofString string `protobuf:"bytes,113,opt,name=oneof_string,json=oneofString,oneof"` } type TestAllTypes_OneofBytes struct { OneofBytes []byte `protobuf:"bytes,114,opt,name=oneof_bytes,json=oneofBytes,proto3,oneof"` } type TestAllTypes_OneofBool struct { OneofBool bool `protobuf:"varint,115,opt,name=oneof_bool,json=oneofBool,oneof"` } type TestAllTypes_OneofUint64 struct { OneofUint64 uint64 `protobuf:"varint,116,opt,name=oneof_uint64,json=oneofUint64,oneof"` } type TestAllTypes_OneofFloat struct { OneofFloat float32 `protobuf:"fixed32,117,opt,name=oneof_float,json=oneofFloat,oneof"` } type TestAllTypes_OneofDouble struct { OneofDouble float64 `protobuf:"fixed64,118,opt,name=oneof_double,json=oneofDouble,oneof"` } type TestAllTypes_OneofEnum struct { OneofEnum TestAllTypes_NestedEnum `protobuf:"varint,119,opt,name=oneof_enum,json=oneofEnum,enum=conformance.TestAllTypes_NestedEnum,oneof"` } func (*TestAllTypes_OneofUint32) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofNestedMessage) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofString) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofBytes) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofBool) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofUint64) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofFloat) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofDouble) isTestAllTypes_OneofField() {} func (*TestAllTypes_OneofEnum) isTestAllTypes_OneofField() {} func (m *TestAllTypes) GetOneofField() isTestAllTypes_OneofField { if m != nil { return m.OneofField } return nil } func (m *TestAllTypes) GetOptionalInt32() int32 { if m != nil { return m.OptionalInt32 } return 0 } func (m *TestAllTypes) GetOptionalInt64() int64 { if m != nil { return m.OptionalInt64 } return 0 } func (m *TestAllTypes) GetOptionalUint32() uint32 { if m != nil { return m.OptionalUint32 } return 0 } func (m *TestAllTypes) GetOptionalUint64() uint64 { if m != nil { return m.OptionalUint64 } return 0 } func (m *TestAllTypes) GetOptionalSint32() int32 { if m != nil { return m.OptionalSint32 } return 0 } func (m *TestAllTypes) GetOptionalSint64() int64 { if m != nil { return m.OptionalSint64 } return 0 } func (m *TestAllTypes) GetOptionalFixed32() uint32 { if m != nil { return m.OptionalFixed32 } return 0 } func (m *TestAllTypes) GetOptionalFixed64() uint64 { if m != nil { return m.OptionalFixed64 } return 0 } func (m *TestAllTypes) GetOptionalSfixed32() int32 { if m != nil { return m.OptionalSfixed32 } return 0 } func (m *TestAllTypes) GetOptionalSfixed64() int64 { if m != nil { return m.OptionalSfixed64 } return 0 } func (m *TestAllTypes) GetOptionalFloat() float32 { if m != nil { return m.OptionalFloat } return 0 } func (m *TestAllTypes) GetOptionalDouble() float64 { if m != nil { return m.OptionalDouble } return 0 } func (m *TestAllTypes) GetOptionalBool() bool { if m != nil { return m.OptionalBool } return false } func (m *TestAllTypes) GetOptionalString() string { if m != nil { return m.OptionalString } return "" } func (m *TestAllTypes) GetOptionalBytes() []byte { if m != nil { return m.OptionalBytes } return nil } func (m *TestAllTypes) GetOptionalNestedMessage() *TestAllTypes_NestedMessage { if m != nil { return m.OptionalNestedMessage } return nil } func (m *TestAllTypes) GetOptionalForeignMessage() *ForeignMessage { if m != nil { return m.OptionalForeignMessage } return nil } func (m *TestAllTypes) GetOptionalNestedEnum() TestAllTypes_NestedEnum { if m != nil { return m.OptionalNestedEnum } return TestAllTypes_FOO } func (m *TestAllTypes) GetOptionalForeignEnum() ForeignEnum { if m != nil { return m.OptionalForeignEnum } return ForeignEnum_FOREIGN_FOO } func (m *TestAllTypes) GetOptionalStringPiece() string { if m != nil { return m.OptionalStringPiece } return "" } func (m *TestAllTypes) GetOptionalCord() string { if m != nil { return m.OptionalCord } return "" } func (m *TestAllTypes) GetRecursiveMessage() *TestAllTypes { if m != nil { return m.RecursiveMessage } return nil } func (m *TestAllTypes) GetRepeatedInt32() []int32 { if m != nil { return m.RepeatedInt32 } return nil } func (m *TestAllTypes) GetRepeatedInt64() []int64 { if m != nil { return m.RepeatedInt64 } return nil } func (m *TestAllTypes) GetRepeatedUint32() []uint32 { if m != nil { return m.RepeatedUint32 } return nil } func (m *TestAllTypes) GetRepeatedUint64() []uint64 { if m != nil { return m.RepeatedUint64 } return nil } func (m *TestAllTypes) GetRepeatedSint32() []int32 { if m != nil { return m.RepeatedSint32 } return nil } func (m *TestAllTypes) GetRepeatedSint64() []int64 { if m != nil { return m.RepeatedSint64 } return nil } func (m *TestAllTypes) GetRepeatedFixed32() []uint32 { if m != nil { return m.RepeatedFixed32 } return nil } func (m *TestAllTypes) GetRepeatedFixed64() []uint64 { if m != nil { return m.RepeatedFixed64 } return nil } func (m *TestAllTypes) GetRepeatedSfixed32() []int32 { if m != nil { return m.RepeatedSfixed32 } return nil } func (m *TestAllTypes) GetRepeatedSfixed64() []int64 { if m != nil { return m.RepeatedSfixed64 } return nil } func (m *TestAllTypes) GetRepeatedFloat() []float32 { if m != nil { return m.RepeatedFloat } return nil } func (m *TestAllTypes) GetRepeatedDouble() []float64 { if m != nil { return m.RepeatedDouble } return nil } func (m *TestAllTypes) GetRepeatedBool() []bool { if m != nil { return m.RepeatedBool } return nil } func (m *TestAllTypes) GetRepeatedString() []string { if m != nil { return m.RepeatedString } return nil } func (m *TestAllTypes) GetRepeatedBytes() [][]byte { if m != nil { return m.RepeatedBytes } return nil } func (m *TestAllTypes) GetRepeatedNestedMessage() []*TestAllTypes_NestedMessage { if m != nil { return m.RepeatedNestedMessage } return nil } func (m *TestAllTypes) GetRepeatedForeignMessage() []*ForeignMessage { if m != nil { return m.RepeatedForeignMessage } return nil } func (m *TestAllTypes) GetRepeatedNestedEnum() []TestAllTypes_NestedEnum { if m != nil { return m.RepeatedNestedEnum } return nil } func (m *TestAllTypes) GetRepeatedForeignEnum() []ForeignEnum { if m != nil { return m.RepeatedForeignEnum } return nil } func (m *TestAllTypes) GetRepeatedStringPiece() []string { if m != nil { return m.RepeatedStringPiece } return nil } func (m *TestAllTypes) GetRepeatedCord() []string { if m != nil { return m.RepeatedCord } return nil } func (m *TestAllTypes) GetMapInt32Int32() map[int32]int32 { if m != nil { return m.MapInt32Int32 } return nil } func (m *TestAllTypes) GetMapInt64Int64() map[int64]int64 { if m != nil { return m.MapInt64Int64 } return nil } func (m *TestAllTypes) GetMapUint32Uint32() map[uint32]uint32 { if m != nil { return m.MapUint32Uint32 } return nil } func (m *TestAllTypes) GetMapUint64Uint64() map[uint64]uint64 { if m != nil { return m.MapUint64Uint64 } return nil } func (m *TestAllTypes) GetMapSint32Sint32() map[int32]int32 { if m != nil { return m.MapSint32Sint32 } return nil } func (m *TestAllTypes) GetMapSint64Sint64() map[int64]int64 { if m != nil { return m.MapSint64Sint64 } return nil } func (m *TestAllTypes) GetMapFixed32Fixed32() map[uint32]uint32 { if m != nil { return m.MapFixed32Fixed32 } return nil } func (m *TestAllTypes) GetMapFixed64Fixed64() map[uint64]uint64 { if m != nil { return m.MapFixed64Fixed64 } return nil } func (m *TestAllTypes) GetMapSfixed32Sfixed32() map[int32]int32 { if m != nil { return m.MapSfixed32Sfixed32 } return nil } func (m *TestAllTypes) GetMapSfixed64Sfixed64() map[int64]int64 { if m != nil { return m.MapSfixed64Sfixed64 } return nil } func (m *TestAllTypes) GetMapInt32Float() map[int32]float32 { if m != nil { return m.MapInt32Float } return nil } func (m *TestAllTypes) GetMapInt32Double() map[int32]float64 { if m != nil { return m.MapInt32Double } return nil } func (m *TestAllTypes) GetMapBoolBool() map[bool]bool { if m != nil { return m.MapBoolBool } return nil } func (m *TestAllTypes) GetMapStringString() map[string]string { if m != nil { return m.MapStringString } return nil } func (m *TestAllTypes) GetMapStringBytes() map[string][]byte { if m != nil { return m.MapStringBytes } return nil } func (m *TestAllTypes) GetMapStringNestedMessage() map[string]*TestAllTypes_NestedMessage { if m != nil { return m.MapStringNestedMessage } return nil } func (m *TestAllTypes) GetMapStringForeignMessage() map[string]*ForeignMessage { if m != nil { return m.MapStringForeignMessage } return nil } func (m *TestAllTypes) GetMapStringNestedEnum() map[string]TestAllTypes_NestedEnum { if m != nil { return m.MapStringNestedEnum } return nil } func (m *TestAllTypes) GetMapStringForeignEnum() map[string]ForeignEnum { if m != nil { return m.MapStringForeignEnum } return nil } func (m *TestAllTypes) GetOneofUint32() uint32 { if x, ok := m.GetOneofField().(*TestAllTypes_OneofUint32); ok { return x.OneofUint32 } return 0 } func (m *TestAllTypes) GetOneofNestedMessage() *TestAllTypes_NestedMessage { if x, ok := m.GetOneofField().(*TestAllTypes_OneofNestedMessage); ok { return x.OneofNestedMessage } return nil } func (m *TestAllTypes) GetOneofString() string { if x, ok := m.GetOneofField().(*TestAllTypes_OneofString); ok { return x.OneofString } return "" } func (m *TestAllTypes) GetOneofBytes() []byte { if x, ok := m.GetOneofField().(*TestAllTypes_OneofBytes); ok { return x.OneofBytes } return nil } func (m *TestAllTypes) GetOneofBool() bool { if x, ok := m.GetOneofField().(*TestAllTypes_OneofBool); ok { return x.OneofBool } return false } func (m *TestAllTypes) GetOneofUint64() uint64 { if x, ok := m.GetOneofField().(*TestAllTypes_OneofUint64); ok { return x.OneofUint64 } return 0 } func (m *TestAllTypes) GetOneofFloat() float32 { if x, ok := m.GetOneofField().(*TestAllTypes_OneofFloat); ok { return x.OneofFloat } return 0 } func (m *TestAllTypes) GetOneofDouble() float64 { if x, ok := m.GetOneofField().(*TestAllTypes_OneofDouble); ok { return x.OneofDouble } return 0 } func (m *TestAllTypes) GetOneofEnum() TestAllTypes_NestedEnum { if x, ok := m.GetOneofField().(*TestAllTypes_OneofEnum); ok { return x.OneofEnum } return TestAllTypes_FOO } func (m *TestAllTypes) GetOptionalBoolWrapper() *google_protobuf5.BoolValue { if m != nil { return m.OptionalBoolWrapper } return nil } func (m *TestAllTypes) GetOptionalInt32Wrapper() *google_protobuf5.Int32Value { if m != nil { return m.OptionalInt32Wrapper } return nil } func (m *TestAllTypes) GetOptionalInt64Wrapper() *google_protobuf5.Int64Value { if m != nil { return m.OptionalInt64Wrapper } return nil } func (m *TestAllTypes) GetOptionalUint32Wrapper() *google_protobuf5.UInt32Value { if m != nil { return m.OptionalUint32Wrapper } return nil } func (m *TestAllTypes) GetOptionalUint64Wrapper() *google_protobuf5.UInt64Value { if m != nil { return m.OptionalUint64Wrapper } return nil } func (m *TestAllTypes) GetOptionalFloatWrapper() *google_protobuf5.FloatValue { if m != nil { return m.OptionalFloatWrapper } return nil } func (m *TestAllTypes) GetOptionalDoubleWrapper() *google_protobuf5.DoubleValue { if m != nil { return m.OptionalDoubleWrapper } return nil } func (m *TestAllTypes) GetOptionalStringWrapper() *google_protobuf5.StringValue { if m != nil { return m.OptionalStringWrapper } return nil } func (m *TestAllTypes) GetOptionalBytesWrapper() *google_protobuf5.BytesValue { if m != nil { return m.OptionalBytesWrapper } return nil } func (m *TestAllTypes) GetRepeatedBoolWrapper() []*google_protobuf5.BoolValue { if m != nil { return m.RepeatedBoolWrapper } return nil } func (m *TestAllTypes) GetRepeatedInt32Wrapper() []*google_protobuf5.Int32Value { if m != nil { return m.RepeatedInt32Wrapper } return nil } func (m *TestAllTypes) GetRepeatedInt64Wrapper() []*google_protobuf5.Int64Value { if m != nil { return m.RepeatedInt64Wrapper } return nil } func (m *TestAllTypes) GetRepeatedUint32Wrapper() []*google_protobuf5.UInt32Value { if m != nil { return m.RepeatedUint32Wrapper } return nil } func (m *TestAllTypes) GetRepeatedUint64Wrapper() []*google_protobuf5.UInt64Value { if m != nil { return m.RepeatedUint64Wrapper } return nil } func (m *TestAllTypes) GetRepeatedFloatWrapper() []*google_protobuf5.FloatValue { if m != nil { return m.RepeatedFloatWrapper } return nil } func (m *TestAllTypes) GetRepeatedDoubleWrapper() []*google_protobuf5.DoubleValue { if m != nil { return m.RepeatedDoubleWrapper } return nil } func (m *TestAllTypes) GetRepeatedStringWrapper() []*google_protobuf5.StringValue { if m != nil { return m.RepeatedStringWrapper } return nil } func (m *TestAllTypes) GetRepeatedBytesWrapper() []*google_protobuf5.BytesValue { if m != nil { return m.RepeatedBytesWrapper } return nil } func (m *TestAllTypes) GetOptionalDuration() *google_protobuf1.Duration { if m != nil { return m.OptionalDuration } return nil } func (m *TestAllTypes) GetOptionalTimestamp() *google_protobuf4.Timestamp { if m != nil { return m.OptionalTimestamp } return nil } func (m *TestAllTypes) GetOptionalFieldMask() *google_protobuf2.FieldMask { if m != nil { return m.OptionalFieldMask } return nil } func (m *TestAllTypes) GetOptionalStruct() *google_protobuf3.Struct { if m != nil { return m.OptionalStruct } return nil } func (m *TestAllTypes) GetOptionalAny() *google_protobuf.Any { if m != nil { return m.OptionalAny } return nil } func (m *TestAllTypes) GetOptionalValue() *google_protobuf3.Value { if m != nil { return m.OptionalValue } return nil } func (m *TestAllTypes) GetRepeatedDuration() []*google_protobuf1.Duration { if m != nil { return m.RepeatedDuration } return nil } func (m *TestAllTypes) GetRepeatedTimestamp() []*google_protobuf4.Timestamp { if m != nil { return m.RepeatedTimestamp } return nil } func (m *TestAllTypes) GetRepeatedFieldmask() []*google_protobuf2.FieldMask { if m != nil { return m.RepeatedFieldmask } return nil } func (m *TestAllTypes) GetRepeatedStruct() []*google_protobuf3.Struct { if m != nil { return m.RepeatedStruct } return nil } func (m *TestAllTypes) GetRepeatedAny() []*google_protobuf.Any { if m != nil { return m.RepeatedAny } return nil } func (m *TestAllTypes) GetRepeatedValue() []*google_protobuf3.Value { if m != nil { return m.RepeatedValue } return nil } func (m *TestAllTypes) GetFieldname1() int32 { if m != nil { return m.Fieldname1 } return 0 } func (m *TestAllTypes) GetFieldName2() int32 { if m != nil { return m.FieldName2 } return 0 } func (m *TestAllTypes) GetXFieldName3() int32 { if m != nil { return m.XFieldName3 } return 0 } func (m *TestAllTypes) GetField_Name4_() int32 { if m != nil { return m.Field_Name4_ } return 0 } func (m *TestAllTypes) GetField0Name5() int32 { if m != nil { return m.Field0Name5 } return 0 } func (m *TestAllTypes) GetField_0Name6() int32 { if m != nil { return m.Field_0Name6 } return 0 } func (m *TestAllTypes) GetFieldName7() int32 { if m != nil { return m.FieldName7 } return 0 } func (m *TestAllTypes) GetFieldName8() int32 { if m != nil { return m.FieldName8 } return 0 } func (m *TestAllTypes) GetField_Name9() int32 { if m != nil { return m.Field_Name9 } return 0 } func (m *TestAllTypes) GetField_Name10() int32 { if m != nil { return m.Field_Name10 } return 0 } func (m *TestAllTypes) GetFIELD_NAME11() int32 { if m != nil { return m.FIELD_NAME11 } return 0 } func (m *TestAllTypes) GetFIELDName12() int32 { if m != nil { return m.FIELDName12 } return 0 } func (m *TestAllTypes) GetXFieldName13() int32 { if m != nil { return m.XFieldName13 } return 0 } func (m *TestAllTypes) GetX_FieldName14() int32 { if m != nil { return m.X_FieldName14 } return 0 } func (m *TestAllTypes) GetField_Name15() int32 { if m != nil { return m.Field_Name15 } return 0 } func (m *TestAllTypes) GetField__Name16() int32 { if m != nil { return m.Field__Name16 } return 0 } func (m *TestAllTypes) GetFieldName17__() int32 { if m != nil { return m.FieldName17__ } return 0 } func (m *TestAllTypes) GetFieldName18__() int32 { if m != nil { return m.FieldName18__ } return 0 } // XXX_OneofFuncs is for the internal use of the proto package. func (*TestAllTypes) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _TestAllTypes_OneofMarshaler, _TestAllTypes_OneofUnmarshaler, _TestAllTypes_OneofSizer, []interface{}{ (*TestAllTypes_OneofUint32)(nil), (*TestAllTypes_OneofNestedMessage)(nil), (*TestAllTypes_OneofString)(nil), (*TestAllTypes_OneofBytes)(nil), (*TestAllTypes_OneofBool)(nil), (*TestAllTypes_OneofUint64)(nil), (*TestAllTypes_OneofFloat)(nil), (*TestAllTypes_OneofDouble)(nil), (*TestAllTypes_OneofEnum)(nil), } } func _TestAllTypes_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*TestAllTypes) // oneof_field switch x := m.OneofField.(type) { case *TestAllTypes_OneofUint32: b.EncodeVarint(111<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.OneofUint32)) case *TestAllTypes_OneofNestedMessage: b.EncodeVarint(112<<3 | proto.WireBytes) if err := b.EncodeMessage(x.OneofNestedMessage); err != nil { return err } case *TestAllTypes_OneofString: b.EncodeVarint(113<<3 | proto.WireBytes) b.EncodeStringBytes(x.OneofString) case *TestAllTypes_OneofBytes: b.EncodeVarint(114<<3 | proto.WireBytes) b.EncodeRawBytes(x.OneofBytes) case *TestAllTypes_OneofBool: t := uint64(0) if x.OneofBool { t = 1 } b.EncodeVarint(115<<3 | proto.WireVarint) b.EncodeVarint(t) case *TestAllTypes_OneofUint64: b.EncodeVarint(116<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.OneofUint64)) case *TestAllTypes_OneofFloat: b.EncodeVarint(117<<3 | proto.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.OneofFloat))) case *TestAllTypes_OneofDouble: b.EncodeVarint(118<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.OneofDouble)) case *TestAllTypes_OneofEnum: b.EncodeVarint(119<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.OneofEnum)) case nil: default: return fmt.Errorf("TestAllTypes.OneofField has unexpected type %T", x) } return nil } func _TestAllTypes_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*TestAllTypes) switch tag { case 111: // oneof_field.oneof_uint32 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.OneofField = &TestAllTypes_OneofUint32{uint32(x)} return true, err case 112: // oneof_field.oneof_nested_message if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(TestAllTypes_NestedMessage) err := b.DecodeMessage(msg) m.OneofField = &TestAllTypes_OneofNestedMessage{msg} return true, err case 113: // oneof_field.oneof_string if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.OneofField = &TestAllTypes_OneofString{x} return true, err case 114: // oneof_field.oneof_bytes if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.OneofField = &TestAllTypes_OneofBytes{x} return true, err case 115: // oneof_field.oneof_bool if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.OneofField = &TestAllTypes_OneofBool{x != 0} return true, err case 116: // oneof_field.oneof_uint64 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.OneofField = &TestAllTypes_OneofUint64{x} return true, err case 117: // oneof_field.oneof_float if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.OneofField = &TestAllTypes_OneofFloat{math.Float32frombits(uint32(x))} return true, err case 118: // oneof_field.oneof_double if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.OneofField = &TestAllTypes_OneofDouble{math.Float64frombits(x)} return true, err case 119: // oneof_field.oneof_enum if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.OneofField = &TestAllTypes_OneofEnum{TestAllTypes_NestedEnum(x)} return true, err default: return false, nil } } func _TestAllTypes_OneofSizer(msg proto.Message) (n int) { m := msg.(*TestAllTypes) // oneof_field switch x := m.OneofField.(type) { case *TestAllTypes_OneofUint32: n += proto.SizeVarint(111<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.OneofUint32)) case *TestAllTypes_OneofNestedMessage: s := proto.Size(x.OneofNestedMessage) n += proto.SizeVarint(112<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *TestAllTypes_OneofString: n += proto.SizeVarint(113<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.OneofString))) n += len(x.OneofString) case *TestAllTypes_OneofBytes: n += proto.SizeVarint(114<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.OneofBytes))) n += len(x.OneofBytes) case *TestAllTypes_OneofBool: n += proto.SizeVarint(115<<3 | proto.WireVarint) n += 1 case *TestAllTypes_OneofUint64: n += proto.SizeVarint(116<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.OneofUint64)) case *TestAllTypes_OneofFloat: n += proto.SizeVarint(117<<3 | proto.WireFixed32) n += 4 case *TestAllTypes_OneofDouble: n += proto.SizeVarint(118<<3 | proto.WireFixed64) n += 8 case *TestAllTypes_OneofEnum: n += proto.SizeVarint(119<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.OneofEnum)) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type TestAllTypes_NestedMessage struct { A int32 `protobuf:"varint,1,opt,name=a" json:"a,omitempty"` Corecursive *TestAllTypes `protobuf:"bytes,2,opt,name=corecursive" json:"corecursive,omitempty"` } func (m *TestAllTypes_NestedMessage) Reset() { *m = TestAllTypes_NestedMessage{} } func (m *TestAllTypes_NestedMessage) String() string { return proto.CompactTextString(m) } func (*TestAllTypes_NestedMessage) ProtoMessage() {} func (*TestAllTypes_NestedMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } func (m *TestAllTypes_NestedMessage) GetA() int32 { if m != nil { return m.A } return 0 } func (m *TestAllTypes_NestedMessage) GetCorecursive() *TestAllTypes { if m != nil { return m.Corecursive } return nil } type ForeignMessage struct { C int32 `protobuf:"varint,1,opt,name=c" json:"c,omitempty"` } func (m *ForeignMessage) Reset() { *m = ForeignMessage{} } func (m *ForeignMessage) String() string { return proto.CompactTextString(m) } func (*ForeignMessage) ProtoMessage() {} func (*ForeignMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *ForeignMessage) GetC() int32 { if m != nil { return m.C } return 0 } func init() { proto.RegisterType((*ConformanceRequest)(nil), "conformance.ConformanceRequest") proto.RegisterType((*ConformanceResponse)(nil), "conformance.ConformanceResponse") proto.RegisterType((*TestAllTypes)(nil), "conformance.TestAllTypes") proto.RegisterType((*TestAllTypes_NestedMessage)(nil), "conformance.TestAllTypes.NestedMessage") proto.RegisterType((*ForeignMessage)(nil), "conformance.ForeignMessage") proto.RegisterEnum("conformance.WireFormat", WireFormat_name, WireFormat_value) proto.RegisterEnum("conformance.ForeignEnum", ForeignEnum_name, ForeignEnum_value) proto.RegisterEnum("conformance.TestAllTypes_NestedEnum", TestAllTypes_NestedEnum_name, TestAllTypes_NestedEnum_value) } func init() { proto.RegisterFile("conformance_proto/conformance.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 2737 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x5a, 0xd9, 0x72, 0xdb, 0xc8, 0xd5, 0x16, 0x08, 0x59, 0x4b, 0x93, 0x92, 0xa8, 0xd6, 0xd6, 0x96, 0x5d, 0x63, 0x58, 0xb2, 0x7f, 0xd3, 0xf6, 0x8c, 0xac, 0x05, 0x86, 0x65, 0xcf, 0x3f, 0x8e, 0x45, 0x9b, 0xb4, 0xe4, 0x8c, 0x25, 0x17, 0x64, 0x8d, 0xab, 0x9c, 0x0b, 0x06, 0xa6, 0x20, 0x15, 0xc7, 0x24, 0xc1, 0x01, 0x48, 0x4f, 0x94, 0xcb, 0xbc, 0x41, 0xf6, 0x7d, 0xbd, 0xcf, 0x7a, 0x93, 0xa4, 0x92, 0xab, 0x54, 0x6e, 0xb2, 0x27, 0x95, 0x3d, 0x79, 0x85, 0xbc, 0x43, 0x52, 0xbd, 0xa2, 0xbb, 0x01, 0x50, 0xf4, 0x54, 0x0d, 0x25, 0x1e, 0x7c, 0xfd, 0x9d, 0xd3, 0xe7, 0x1c, 0x7c, 0x2d, 0x1c, 0x18, 0x2c, 0xd7, 0x83, 0xf6, 0x51, 0x10, 0xb6, 0xbc, 0x76, 0xdd, 0xaf, 0x75, 0xc2, 0xa0, 0x1b, 0xdc, 0x90, 0x2c, 0x2b, 0xc4, 0x02, 0xf3, 0x92, 0x69, 0xf1, 0xec, 0x71, 0x10, 0x1c, 0x37, 0xfd, 0x1b, 0xe4, 0xd2, 0x8b, 0xde, 0xd1, 0x0d, 0xaf, 0x7d, 0x42, 0x71, 0x8b, 0x6f, 0xe8, 0x97, 0x0e, 0x7b, 0xa1, 0xd7, 0x6d, 0x04, 0x6d, 0x76, 0xdd, 0xd2, 0xaf, 0x1f, 0x35, 0xfc, 0xe6, 0x61, 0xad, 0xe5, 0x45, 0x2f, 0x19, 0xe2, 0xbc, 0x8e, 0x88, 0xba, 0x61, 0xaf, 0xde, 0x65, 0x57, 0x2f, 0xe8, 0x57, 0xbb, 0x8d, 0x96, 0x1f, 0x75, 0xbd, 0x56, 0x27, 0x2b, 0x80, 0x0f, 0x43, 0xaf, 0xd3, 0xf1, 0xc3, 0x88, 0x5e, 0x5f, 0xfa, 0x85, 0x01, 0xe0, 0xfd, 0x78, 0x2f, 0xae, 0xff, 0x41, 0xcf, 0x8f, 0xba, 0xf0, 0x3a, 0x28, 0xf2, 0x15, 0xb5, 0x8e, 0x77, 0xd2, 0x0c, 0xbc, 0x43, 0x64, 0x58, 0x46, 0xa9, 0xb0, 0x3d, 0xe4, 0x4e, 0xf1, 0x2b, 0x4f, 0xe8, 0x05, 0xb8, 0x0c, 0x0a, 0xef, 0x47, 0x41, 0x5b, 0x00, 0x73, 0x96, 0x51, 0x1a, 0xdf, 0x1e, 0x72, 0xf3, 0xd8, 0xca, 0x41, 0x7b, 0x60, 0x21, 0xa4, 0xe4, 0xfe, 0x61, 0x2d, 0xe8, 0x75, 0x3b, 0xbd, 0x6e, 0x8d, 0x78, 0xed, 0x22, 0xd3, 0x32, 0x4a, 0x93, 0xeb, 0x0b, 0x2b, 0x72, 0x9a, 0x9f, 0x35, 0x42, 0xbf, 0x4a, 0x2e, 0xbb, 0x73, 0x62, 0xdd, 0x1e, 0x59, 0x46, 0xcd, 0xe5, 0x71, 0x30, 0xca, 0x1c, 0x2e, 0x7d, 0x2a, 0x07, 0x66, 0x94, 0x4d, 0x44, 0x9d, 0xa0, 0x1d, 0xf9, 0xf0, 0x22, 0xc8, 0x77, 0xbc, 0x30, 0xf2, 0x6b, 0x7e, 0x18, 0x06, 0x21, 0xd9, 0x00, 0x8e, 0x0b, 0x10, 0x63, 0x05, 0xdb, 0xe0, 0x55, 0x30, 0x15, 0xf9, 0x61, 0xc3, 0x6b, 0x36, 0x3e, 0xc9, 0x61, 0x23, 0x0c, 0x36, 0x29, 0x2e, 0x50, 0xe8, 0x65, 0x30, 0x11, 0xf6, 0xda, 0x38, 0xc1, 0x0c, 0xc8, 0xf7, 0x59, 0x60, 0x66, 0x0a, 0x4b, 0x4b, 0x9d, 0x39, 0x68, 0xea, 0x86, 0xd3, 0x52, 0xb7, 0x08, 0x46, 0xa3, 0x97, 0x8d, 0x4e, 0xc7, 0x3f, 0x44, 0x67, 0xd8, 0x75, 0x6e, 0x28, 0x8f, 0x81, 0x91, 0xd0, 0x8f, 0x7a, 0xcd, 0xee, 0xd2, 0x7f, 0xaa, 0xa0, 0xf0, 0xd4, 0x8f, 0xba, 0x5b, 0xcd, 0xe6, 0xd3, 0x93, 0x8e, 0x1f, 0xc1, 0xcb, 0x60, 0x32, 0xe8, 0xe0, 0x5e, 0xf3, 0x9a, 0xb5, 0x46, 0xbb, 0xbb, 0xb1, 0x4e, 0x12, 0x70, 0xc6, 0x9d, 0xe0, 0xd6, 0x1d, 0x6c, 0xd4, 0x61, 0x8e, 0x4d, 0xf6, 0x65, 0x2a, 0x30, 0xc7, 0x86, 0x57, 0xc0, 0x94, 0x80, 0xf5, 0x28, 0x1d, 0xde, 0xd5, 0x84, 0x2b, 0x56, 0x1f, 0x10, 0x6b, 0x02, 0xe8, 0xd8, 0x64, 0x57, 0xc3, 0x2a, 0x50, 0x63, 0x8c, 0x28, 0x23, 0xde, 0xde, 0x74, 0x0c, 0xdc, 0x4f, 0x32, 0x46, 0x94, 0x11, 0xd7, 0x08, 0xaa, 0x40, 0xc7, 0x86, 0x57, 0x41, 0x51, 0x00, 0x8f, 0x1a, 0x9f, 0xf0, 0x0f, 0x37, 0xd6, 0xd1, 0xa8, 0x65, 0x94, 0x46, 0x5d, 0x41, 0x50, 0xa5, 0xe6, 0x24, 0xd4, 0xb1, 0xd1, 0x98, 0x65, 0x94, 0x46, 0x34, 0xa8, 0x63, 0xc3, 0xeb, 0x60, 0x3a, 0x76, 0xcf, 0x69, 0xc7, 0x2d, 0xa3, 0x34, 0xe5, 0x0a, 0x8e, 0x7d, 0x66, 0x4f, 0x01, 0x3b, 0x36, 0x02, 0x96, 0x51, 0x2a, 0xea, 0x60, 0xc7, 0x56, 0x52, 0x7f, 0xd4, 0x0c, 0xbc, 0x2e, 0xca, 0x5b, 0x46, 0x29, 0x17, 0xa7, 0xbe, 0x8a, 0x8d, 0xca, 0xfe, 0x0f, 0x83, 0xde, 0x8b, 0xa6, 0x8f, 0x0a, 0x96, 0x51, 0x32, 0xe2, 0xfd, 0x3f, 0x20, 0x56, 0xb8, 0x0c, 0xc4, 0xca, 0xda, 0x8b, 0x20, 0x68, 0xa2, 0x09, 0xcb, 0x28, 0x8d, 0xb9, 0x05, 0x6e, 0x2c, 0x07, 0x41, 0x53, 0xcd, 0x66, 0x37, 0x6c, 0xb4, 0x8f, 0xd1, 0x24, 0xee, 0x2a, 0x29, 0x9b, 0xc4, 0xaa, 0x44, 0xf7, 0xe2, 0xa4, 0xeb, 0x47, 0x68, 0x0a, 0xb7, 0x71, 0x1c, 0x5d, 0x19, 0x1b, 0x61, 0x0d, 0x2c, 0x08, 0x58, 0x9b, 0xde, 0xde, 0x2d, 0x3f, 0x8a, 0xbc, 0x63, 0x1f, 0x41, 0xcb, 0x28, 0xe5, 0xd7, 0xaf, 0x28, 0x37, 0xb6, 0xdc, 0xa2, 0x2b, 0xbb, 0x04, 0xff, 0x98, 0xc2, 0xdd, 0x39, 0xce, 0xa3, 0x98, 0xe1, 0x01, 0x40, 0x71, 0x96, 0x82, 0xd0, 0x6f, 0x1c, 0xb7, 0x85, 0x87, 0x19, 0xe2, 0xe1, 0x9c, 0xe2, 0xa1, 0x4a, 0x31, 0x9c, 0x75, 0x5e, 0x24, 0x53, 0xb1, 0xc3, 0xf7, 0xc0, 0xac, 0x1e, 0xb7, 0xdf, 0xee, 0xb5, 0xd0, 0x1c, 0x51, 0xa3, 0x4b, 0xa7, 0x05, 0x5d, 0x69, 0xf7, 0x5a, 0x2e, 0x54, 0x23, 0xc6, 0x36, 0xf8, 0x2e, 0x98, 0x4b, 0x84, 0x4b, 0x88, 0xe7, 0x09, 0x31, 0x4a, 0x8b, 0x95, 0x90, 0xcd, 0x68, 0x81, 0x12, 0x36, 0x47, 0x62, 0xa3, 0xd5, 0xaa, 0x75, 0x1a, 0x7e, 0xdd, 0x47, 0x08, 0xd7, 0xac, 0x9c, 0x1b, 0xcb, 0xc5, 0xeb, 0x68, 0xdd, 0x9e, 0xe0, 0xcb, 0xf0, 0x8a, 0xd4, 0x0a, 0xf5, 0x20, 0x3c, 0x44, 0x67, 0x19, 0xde, 0x88, 0xdb, 0xe1, 0x7e, 0x10, 0x1e, 0xc2, 0x2a, 0x98, 0x0e, 0xfd, 0x7a, 0x2f, 0x8c, 0x1a, 0xaf, 0x7c, 0x91, 0xd6, 0x73, 0x24, 0xad, 0x67, 0x33, 0x73, 0xe0, 0x16, 0xc5, 0x1a, 0x9e, 0xce, 0xcb, 0x60, 0x32, 0xf4, 0x3b, 0xbe, 0x87, 0xf3, 0x48, 0x6f, 0xe6, 0x0b, 0x96, 0x89, 0xd5, 0x86, 0x5b, 0x85, 0xda, 0xc8, 0x30, 0xc7, 0x46, 0x96, 0x65, 0x62, 0xb5, 0x91, 0x60, 0x54, 0x1b, 0x04, 0x8c, 0xa9, 0xcd, 0x45, 0xcb, 0xc4, 0x6a, 0xc3, 0xcd, 0xb1, 0xda, 0x28, 0x40, 0xc7, 0x46, 0x4b, 0x96, 0x89, 0xd5, 0x46, 0x06, 0x6a, 0x8c, 0x4c, 0x6d, 0x96, 0x2d, 0x13, 0xab, 0x0d, 0x37, 0xef, 0x27, 0x19, 0x99, 0xda, 0x5c, 0xb2, 0x4c, 0xac, 0x36, 0x32, 0x90, 0xaa, 0x8d, 0x00, 0x72, 0x59, 0xb8, 0x6c, 0x99, 0x58, 0x6d, 0xb8, 0x5d, 0x52, 0x1b, 0x15, 0xea, 0xd8, 0xe8, 0xff, 0x2c, 0x13, 0xab, 0x8d, 0x02, 0xa5, 0x6a, 0x13, 0xbb, 0xe7, 0xb4, 0x57, 0x2c, 0x13, 0xab, 0x8d, 0x08, 0x40, 0x52, 0x1b, 0x0d, 0xec, 0xd8, 0xa8, 0x64, 0x99, 0x58, 0x6d, 0x54, 0x30, 0x55, 0x9b, 0x38, 0x08, 0xa2, 0x36, 0x57, 0x2d, 0x13, 0xab, 0x8d, 0x08, 0x81, 0xab, 0x8d, 0x80, 0x31, 0xb5, 0xb9, 0x66, 0x99, 0x58, 0x6d, 0xb8, 0x39, 0x56, 0x1b, 0x01, 0x24, 0x6a, 0x73, 0xdd, 0x32, 0xb1, 0xda, 0x70, 0x23, 0x57, 0x9b, 0x38, 0x42, 0xaa, 0x36, 0x6f, 0x5a, 0x26, 0x56, 0x1b, 0x11, 0x9f, 0x50, 0x9b, 0x98, 0x8d, 0xa8, 0xcd, 0x5b, 0x96, 0x89, 0xd5, 0x46, 0xd0, 0x71, 0xb5, 0x11, 0x30, 0x4d, 0x6d, 0x56, 0x2d, 0xf3, 0xb5, 0xd4, 0x86, 0xf3, 0x24, 0xd4, 0x26, 0xce, 0x92, 0xa6, 0x36, 0x6b, 0xc4, 0x43, 0x7f, 0xb5, 0x11, 0xc9, 0x4c, 0xa8, 0x8d, 0x1e, 0x37, 0x11, 0x85, 0x0d, 0xcb, 0x1c, 0x5c, 0x6d, 0xd4, 0x88, 0xb9, 0xda, 0x24, 0xc2, 0x25, 0xc4, 0x36, 0x21, 0xee, 0xa3, 0x36, 0x5a, 0xa0, 0x5c, 0x6d, 0xb4, 0x6a, 0x31, 0xb5, 0x71, 0x70, 0xcd, 0xa8, 0xda, 0xa8, 0x75, 0x13, 0x6a, 0x23, 0xd6, 0x11, 0xb5, 0xb9, 0xc5, 0xf0, 0x46, 0xdc, 0x0e, 0x44, 0x6d, 0x9e, 0x82, 0xa9, 0x96, 0xd7, 0xa1, 0x02, 0xc1, 0x64, 0x62, 0x93, 0x24, 0xf5, 0xcd, 0xec, 0x0c, 0x3c, 0xf6, 0x3a, 0x44, 0x3b, 0xc8, 0x47, 0xa5, 0xdd, 0x0d, 0x4f, 0xdc, 0x89, 0x96, 0x6c, 0x93, 0x58, 0x1d, 0x9b, 0xa9, 0xca, 0xed, 0xc1, 0x58, 0x1d, 0x9b, 0x7c, 0x28, 0xac, 0xcc, 0x06, 0x9f, 0x83, 0x69, 0xcc, 0x4a, 0xe5, 0x87, 0xab, 0xd0, 0x1d, 0xc2, 0xbb, 0xd2, 0x97, 0x97, 0x4a, 0x13, 0xfd, 0xa4, 0xcc, 0x38, 0x3c, 0xd9, 0x2a, 0x73, 0x3b, 0x36, 0x17, 0xae, 0xb7, 0x07, 0xe4, 0x76, 0x6c, 0xfa, 0xa9, 0x72, 0x73, 0x2b, 0xe7, 0xa6, 0x22, 0xc7, 0xb5, 0xee, 0xff, 0x07, 0xe0, 0xa6, 0x02, 0xb8, 0xaf, 0xc5, 0x2d, 0x5b, 0x65, 0x6e, 0xc7, 0xe6, 0xf2, 0xf8, 0xce, 0x80, 0xdc, 0x8e, 0xbd, 0xaf, 0xc5, 0x2d, 0x5b, 0xe1, 0xc7, 0xc1, 0x0c, 0xe6, 0x66, 0xda, 0x26, 0x24, 0xf5, 0x2e, 0x61, 0x5f, 0xed, 0xcb, 0xce, 0x74, 0x96, 0xfd, 0xa0, 0xfc, 0x38, 0x50, 0xd5, 0xae, 0x78, 0x70, 0x6c, 0xa1, 0xc4, 0x1f, 0x19, 0xd4, 0x83, 0x63, 0xb3, 0x1f, 0x9a, 0x07, 0x61, 0x87, 0x47, 0x60, 0x8e, 0xe4, 0x87, 0x6f, 0x42, 0x28, 0xf8, 0x3d, 0xe2, 0x63, 0xbd, 0x7f, 0x8e, 0x18, 0x98, 0xff, 0xa4, 0x5e, 0x70, 0xc8, 0xfa, 0x15, 0xd5, 0x0f, 0xae, 0x04, 0xdf, 0xcb, 0xd6, 0xc0, 0x7e, 0x1c, 0x9b, 0xff, 0xd4, 0xfd, 0xc4, 0x57, 0xd4, 0xfb, 0x95, 0x1e, 0x1a, 0xe5, 0x41, 0xef, 0x57, 0x72, 0x9c, 0x68, 0xf7, 0x2b, 0x3d, 0x62, 0x9e, 0x81, 0x62, 0xcc, 0xca, 0xce, 0x98, 0xfb, 0x84, 0xf6, 0xad, 0xd3, 0x69, 0xe9, 0xe9, 0x43, 0x79, 0x27, 0x5b, 0x8a, 0x11, 0xee, 0x02, 0xec, 0x89, 0x9c, 0x46, 0xf4, 0x48, 0x7a, 0x40, 0x58, 0xaf, 0xf5, 0x65, 0xc5, 0xe7, 0x14, 0xfe, 0x9f, 0x52, 0xe6, 0x5b, 0xb1, 0x45, 0xb4, 0x3b, 0x95, 0x42, 0x76, 0x7e, 0x55, 0x06, 0x69, 0x77, 0x02, 0xa5, 0x9f, 0x52, 0xbb, 0x4b, 0x56, 0x9e, 0x04, 0xc6, 0x4d, 0x8f, 0xbc, 0xea, 0x00, 0x49, 0xa0, 0xcb, 0xc9, 0x69, 0x18, 0x27, 0x41, 0x32, 0xc2, 0x0e, 0x38, 0x2b, 0x11, 0x6b, 0x87, 0xe4, 0x43, 0xe2, 0xe1, 0xe6, 0x00, 0x1e, 0x94, 0x63, 0x91, 0x7a, 0x9a, 0x6f, 0xa5, 0x5e, 0x84, 0x11, 0x58, 0x94, 0x3c, 0xea, 0xa7, 0xe6, 0x36, 0x71, 0xe9, 0x0c, 0xe0, 0x52, 0x3d, 0x33, 0xa9, 0xcf, 0x85, 0x56, 0xfa, 0x55, 0x78, 0x0c, 0xe6, 0x93, 0xdb, 0x24, 0x47, 0xdf, 0xce, 0x20, 0xf7, 0x80, 0xb4, 0x0d, 0x7c, 0xf4, 0x49, 0xf7, 0x80, 0x76, 0x05, 0xbe, 0x0f, 0x16, 0x52, 0x76, 0x47, 0x3c, 0x3d, 0x22, 0x9e, 0x36, 0x06, 0xdf, 0x5a, 0xec, 0x6a, 0xb6, 0x95, 0x72, 0x09, 0x2e, 0x83, 0x42, 0xd0, 0xf6, 0x83, 0x23, 0x7e, 0xdc, 0x04, 0xf8, 0x11, 0x7b, 0x7b, 0xc8, 0xcd, 0x13, 0x2b, 0x3b, 0x3c, 0x3e, 0x06, 0x66, 0x29, 0x48, 0xab, 0x6d, 0xe7, 0xb5, 0x1e, 0xb7, 0xb6, 0x87, 0x5c, 0x48, 0x68, 0xd4, 0x5a, 0x8a, 0x08, 0x58, 0xb7, 0x7f, 0xc0, 0x27, 0x12, 0xc4, 0xca, 0x7a, 0xf7, 0x22, 0xa0, 0x5f, 0x59, 0xdb, 0x86, 0x6c, 0xbc, 0x01, 0x88, 0x91, 0x76, 0xe1, 0x05, 0x00, 0x18, 0x04, 0xdf, 0x87, 0x11, 0x7e, 0x10, 0xdd, 0x1e, 0x72, 0xc7, 0x29, 0x02, 0xdf, 0x5b, 0xca, 0x56, 0x1d, 0x1b, 0x75, 0x2d, 0xa3, 0x34, 0xac, 0x6c, 0xd5, 0xb1, 0x63, 0x47, 0x54, 0x7b, 0x7a, 0xf8, 0xf1, 0x58, 0x38, 0xa2, 0x62, 0x22, 0x78, 0x98, 0x90, 0xbc, 0xc2, 0x8f, 0xc6, 0x82, 0x87, 0x09, 0x43, 0x85, 0x47, 0x43, 0xca, 0xf6, 0xe1, 0xe0, 0x8f, 0x78, 0x22, 0x66, 0x52, 0x9e, 0x3d, 0xe9, 0x69, 0x8c, 0x88, 0x0c, 0x9b, 0xa6, 0xa1, 0x5f, 0x19, 0x24, 0xf7, 0x8b, 0x2b, 0x74, 0xdc, 0xb6, 0xc2, 0xe7, 0x3c, 0x2b, 0x78, 0xab, 0xef, 0x79, 0xcd, 0x9e, 0x1f, 0x3f, 0xa6, 0x61, 0xd3, 0x33, 0xba, 0x0e, 0xba, 0x60, 0x5e, 0x9d, 0xd1, 0x08, 0xc6, 0x5f, 0x1b, 0xec, 0xd1, 0x56, 0x67, 0x24, 0x7a, 0x47, 0x29, 0x67, 0x95, 0x49, 0x4e, 0x06, 0xa7, 0x63, 0x0b, 0xce, 0xdf, 0xf4, 0xe1, 0x74, 0xec, 0x24, 0xa7, 0x63, 0x73, 0xce, 0x03, 0xe9, 0x21, 0xbf, 0xa7, 0x06, 0xfa, 0x5b, 0x4a, 0x7a, 0x3e, 0x41, 0x7a, 0x20, 0x45, 0x3a, 0xa7, 0x0e, 0x89, 0xb2, 0x68, 0xa5, 0x58, 0x7f, 0xd7, 0x8f, 0x96, 0x07, 0x3b, 0xa7, 0x8e, 0x94, 0xd2, 0x32, 0x40, 0x1a, 0x47, 0xb0, 0xfe, 0x3e, 0x2b, 0x03, 0xa4, 0x97, 0xb4, 0x0c, 0x10, 0x5b, 0x5a, 0xa8, 0xb4, 0xd3, 0x04, 0xe9, 0x1f, 0xb2, 0x42, 0xa5, 0xcd, 0xa7, 0x85, 0x4a, 0x8d, 0x69, 0xb4, 0x4c, 0x61, 0x38, 0xed, 0x1f, 0xb3, 0x68, 0xe9, 0x4d, 0xa8, 0xd1, 0x52, 0x63, 0x5a, 0x06, 0xc8, 0x3d, 0x2a, 0x58, 0xff, 0x94, 0x95, 0x01, 0x72, 0xdb, 0x6a, 0x19, 0x20, 0x36, 0xce, 0xb9, 0x27, 0x3d, 0x1c, 0x28, 0xcd, 0xff, 0x67, 0x83, 0xc8, 0x60, 0xdf, 0xe6, 0x97, 0x1f, 0x0a, 0xa5, 0x20, 0xd5, 0x91, 0x81, 0x60, 0xfc, 0x8b, 0xc1, 0x9e, 0xb4, 0xfa, 0x35, 0xbf, 0x32, 0x58, 0xc8, 0xe0, 0x94, 0x1a, 0xea, 0xaf, 0x7d, 0x38, 0x45, 0xf3, 0x2b, 0x53, 0x08, 0xa9, 0x46, 0xda, 0x30, 0x42, 0x90, 0xfe, 0x8d, 0x92, 0x9e, 0xd2, 0xfc, 0xea, 0xcc, 0x22, 0x8b, 0x56, 0x8a, 0xf5, 0xef, 0xfd, 0x68, 0x45, 0xf3, 0xab, 0x13, 0x8e, 0xb4, 0x0c, 0xa8, 0xcd, 0xff, 0x8f, 0xac, 0x0c, 0xc8, 0xcd, 0xaf, 0x0c, 0x03, 0xd2, 0x42, 0xd5, 0x9a, 0xff, 0x9f, 0x59, 0xa1, 0x2a, 0xcd, 0xaf, 0x8e, 0x0e, 0xd2, 0x68, 0xb5, 0xe6, 0xff, 0x57, 0x16, 0xad, 0xd2, 0xfc, 0xea, 0xb3, 0x68, 0x5a, 0x06, 0xd4, 0xe6, 0xff, 0x77, 0x56, 0x06, 0xe4, 0xe6, 0x57, 0x06, 0x0e, 0x9c, 0xf3, 0xa1, 0x34, 0xd7, 0xe5, 0xef, 0x70, 0xd0, 0x77, 0x73, 0x6c, 0x4e, 0x96, 0xd8, 0x3b, 0x43, 0xc4, 0x33, 0x5f, 0x6e, 0x81, 0x8f, 0x80, 0x18, 0x1a, 0xd6, 0xc4, 0xcb, 0x1a, 0xf4, 0xbd, 0x5c, 0xc6, 0xf9, 0xf1, 0x94, 0x43, 0x5c, 0xe1, 0x5f, 0x98, 0xe0, 0x47, 0xc1, 0x8c, 0x34, 0xc4, 0xe6, 0x2f, 0x8e, 0xd0, 0xf7, 0xb3, 0xc8, 0xaa, 0x18, 0xf3, 0xd8, 0x8b, 0x5e, 0xc6, 0x64, 0xc2, 0x04, 0xb7, 0xd4, 0xb9, 0x70, 0xaf, 0xde, 0x45, 0x3f, 0xa0, 0x44, 0x0b, 0x69, 0x45, 0xe8, 0xd5, 0xbb, 0xca, 0xc4, 0xb8, 0x57, 0xef, 0xc2, 0x4d, 0x20, 0x66, 0x8b, 0x35, 0xaf, 0x7d, 0x82, 0x7e, 0x48, 0xd7, 0xcf, 0x26, 0xd6, 0x6f, 0xb5, 0x4f, 0xdc, 0x3c, 0x87, 0x6e, 0xb5, 0x4f, 0xe0, 0x5d, 0x69, 0xd6, 0xfc, 0x0a, 0x97, 0x01, 0xfd, 0x88, 0xae, 0x9d, 0x4f, 0xac, 0xa5, 0x55, 0x12, 0xd3, 0x4d, 0xf2, 0x15, 0x97, 0x27, 0x6e, 0x50, 0x5e, 0x9e, 0x1f, 0xe7, 0x48, 0xb5, 0xfb, 0x95, 0x47, 0xf4, 0xa5, 0x54, 0x1e, 0x41, 0x14, 0x97, 0xe7, 0x27, 0xb9, 0x0c, 0x85, 0x93, 0xca, 0xc3, 0x97, 0xc5, 0xe5, 0x91, 0xb9, 0x48, 0x79, 0x48, 0x75, 0x7e, 0x9a, 0xc5, 0x25, 0x55, 0x27, 0x1e, 0x0a, 0xb2, 0x55, 0xb8, 0x3a, 0xf2, 0xad, 0x82, 0xab, 0xf3, 0x4b, 0x4a, 0x94, 0x5d, 0x1d, 0xe9, 0xee, 0x60, 0xd5, 0x11, 0x14, 0xb8, 0x3a, 0x3f, 0xa3, 0xeb, 0x33, 0xaa, 0xc3, 0xa1, 0xac, 0x3a, 0x62, 0x25, 0xad, 0xce, 0xcf, 0xe9, 0xda, 0xcc, 0xea, 0x70, 0x38, 0xad, 0xce, 0x05, 0x00, 0xc8, 0xfe, 0xdb, 0x5e, 0xcb, 0x5f, 0x43, 0x9f, 0x36, 0xc9, 0x6b, 0x28, 0xc9, 0x04, 0x2d, 0x90, 0xa7, 0xfd, 0x8b, 0xbf, 0xae, 0xa3, 0xcf, 0xc8, 0x88, 0x5d, 0x6c, 0x82, 0x17, 0x41, 0xa1, 0x16, 0x43, 0x36, 0xd0, 0x67, 0x19, 0xa4, 0xca, 0x21, 0x1b, 0x70, 0x09, 0x4c, 0x50, 0x04, 0x81, 0xd8, 0x35, 0xf4, 0x39, 0x9d, 0x86, 0xfc, 0x3d, 0x49, 0xbe, 0xad, 0x62, 0xc8, 0x4d, 0xf4, 0x79, 0x8a, 0x90, 0x6d, 0x70, 0x99, 0xd3, 0xac, 0x12, 0x1e, 0x07, 0x7d, 0x41, 0x01, 0x61, 0x1e, 0x47, 0xec, 0x08, 0x7f, 0xbb, 0x85, 0xbe, 0xa8, 0x3b, 0xba, 0x85, 0x01, 0x22, 0xb4, 0x4d, 0xf4, 0x25, 0x3d, 0xda, 0xcd, 0x78, 0xcb, 0xf8, 0xeb, 0x6d, 0xf4, 0x65, 0x9d, 0xe2, 0x36, 0x5c, 0x02, 0x85, 0xaa, 0x40, 0xac, 0xad, 0xa2, 0xaf, 0xb0, 0x38, 0x04, 0xc9, 0xda, 0x2a, 0xc1, 0xec, 0x54, 0xde, 0x7d, 0x50, 0xdb, 0xdd, 0x7a, 0x5c, 0x59, 0x5b, 0x43, 0x5f, 0xe5, 0x18, 0x6c, 0xa4, 0xb6, 0x18, 0x43, 0x72, 0xbd, 0x8e, 0xbe, 0xa6, 0x60, 0x88, 0x0d, 0x5e, 0x02, 0x93, 0x35, 0x29, 0xbf, 0x6b, 0x1b, 0xe8, 0xeb, 0x09, 0x6f, 0x1b, 0x14, 0x55, 0x8d, 0x51, 0x36, 0xfa, 0x46, 0x02, 0x65, 0xc7, 0x09, 0xa4, 0xa0, 0x9b, 0xe8, 0x9b, 0x72, 0x02, 0x09, 0x48, 0xca, 0x32, 0xdd, 0x9d, 0x83, 0xbe, 0x95, 0x00, 0x39, 0xd8, 0x9f, 0x14, 0xd3, 0xad, 0x5a, 0x0d, 0x7d, 0x3b, 0x81, 0xba, 0x85, 0x51, 0x52, 0x4c, 0x9b, 0xb5, 0x1a, 0xfa, 0x4e, 0x22, 0xaa, 0xcd, 0xc5, 0xe7, 0x60, 0x42, 0x7d, 0xd0, 0x29, 0x00, 0xc3, 0x63, 0x6f, 0x44, 0x0d, 0x0f, 0xbe, 0x0d, 0xf2, 0xf5, 0x40, 0xbc, 0xd4, 0x40, 0xb9, 0xd3, 0x5e, 0x80, 0xc8, 0xe8, 0xc5, 0x7b, 0x00, 0x26, 0x87, 0x94, 0xb0, 0x08, 0xcc, 0x97, 0xfe, 0x09, 0x73, 0x81, 0x7f, 0x85, 0xb3, 0xe0, 0x0c, 0xbd, 0x7d, 0x72, 0xc4, 0x46, 0xbf, 0xdc, 0xc9, 0x6d, 0x1a, 0x31, 0x83, 0x3c, 0x90, 0x94, 0x19, 0xcc, 0x14, 0x06, 0x53, 0x66, 0x28, 0x83, 0xd9, 0xb4, 0xd1, 0xa3, 0xcc, 0x31, 0x91, 0xc2, 0x31, 0x91, 0xce, 0xa1, 0x8c, 0x18, 0x65, 0x8e, 0xe1, 0x14, 0x8e, 0xe1, 0x24, 0x47, 0x62, 0x94, 0x28, 0x73, 0x4c, 0xa7, 0x70, 0x4c, 0xa7, 0x73, 0x28, 0x23, 0x43, 0x99, 0x03, 0xa6, 0x70, 0x40, 0x99, 0xe3, 0x01, 0x98, 0x4f, 0x1f, 0x0c, 0xca, 0x2c, 0xa3, 0x29, 0x2c, 0xa3, 0x19, 0x2c, 0xea, 0xf0, 0x4f, 0x66, 0x19, 0x49, 0x61, 0x19, 0x91, 0x59, 0xaa, 0x00, 0x65, 0x8d, 0xf7, 0x64, 0x9e, 0xa9, 0x14, 0x9e, 0xa9, 0x2c, 0x1e, 0x6d, 0x7c, 0x27, 0xf3, 0x14, 0x53, 0x78, 0x8a, 0xa9, 0xdd, 0x26, 0x0f, 0xe9, 0x4e, 0xeb, 0xd7, 0x9c, 0xcc, 0xb0, 0x05, 0x66, 0x52, 0xe6, 0x71, 0xa7, 0x51, 0x18, 0x32, 0xc5, 0x5d, 0x50, 0xd4, 0x87, 0x6f, 0xf2, 0xfa, 0xb1, 0x94, 0xf5, 0x63, 0x29, 0x4d, 0xa2, 0x0f, 0xda, 0x64, 0x8e, 0xf1, 0x14, 0x8e, 0xf1, 0xe4, 0x36, 0xf4, 0x89, 0xda, 0x69, 0x14, 0x05, 0x99, 0x22, 0x04, 0xe7, 0xfa, 0x8c, 0xcc, 0x52, 0xa8, 0xde, 0x91, 0xa9, 0x5e, 0xe3, 0x7d, 0x95, 0xe4, 0xf3, 0x18, 0x9c, 0xef, 0x37, 0x33, 0x4b, 0x71, 0xba, 0xa6, 0x3a, 0xed, 0xfb, 0x0a, 0x4b, 0x72, 0xd4, 0xa4, 0x0d, 0x97, 0x36, 0x2b, 0x4b, 0x71, 0x72, 0x47, 0x76, 0x32, 0xe8, 0x4b, 0x2d, 0xc9, 0x9b, 0x07, 0xce, 0x66, 0xce, 0xcb, 0x52, 0xdc, 0xad, 0xa8, 0xee, 0xb2, 0x5f, 0x75, 0xc5, 0x2e, 0x96, 0x6e, 0x03, 0x20, 0x4d, 0xf6, 0x46, 0x81, 0x59, 0xdd, 0xdb, 0x2b, 0x0e, 0xe1, 0x5f, 0xca, 0x5b, 0x6e, 0xd1, 0xa0, 0xbf, 0x3c, 0x2f, 0xe6, 0xb0, 0xbb, 0xdd, 0xca, 0xc3, 0xe2, 0x7f, 0xf9, 0x7f, 0x46, 0x79, 0x42, 0x8c, 0xa2, 0xf0, 0xa9, 0xb2, 0xf4, 0x06, 0x98, 0xd4, 0x06, 0x92, 0x05, 0x60, 0xd4, 0xf9, 0x81, 0x52, 0xbf, 0x76, 0x13, 0x80, 0xf8, 0xdf, 0x30, 0xc1, 0x29, 0x90, 0x3f, 0xd8, 0xdd, 0x7f, 0x52, 0xb9, 0xbf, 0x53, 0xdd, 0xa9, 0x3c, 0x28, 0x0e, 0xc1, 0x02, 0x18, 0x7b, 0xe2, 0xee, 0x3d, 0xdd, 0x2b, 0x1f, 0x54, 0x8b, 0x06, 0x1c, 0x03, 0xc3, 0x8f, 0xf6, 0xf7, 0x76, 0x8b, 0xb9, 0x6b, 0xf7, 0x40, 0x5e, 0x9e, 0x07, 0x4e, 0x81, 0x7c, 0x75, 0xcf, 0xad, 0xec, 0x3c, 0xdc, 0xad, 0xd1, 0x48, 0x25, 0x03, 0x8d, 0x58, 0x31, 0x3c, 0x2f, 0xe6, 0xca, 0x17, 0xc1, 0x85, 0x7a, 0xd0, 0x4a, 0xfc, 0x61, 0x26, 0x25, 0xe7, 0xc5, 0x08, 0xb1, 0x6e, 0xfc, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x33, 0xc2, 0x0c, 0xb6, 0xeb, 0x26, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/_conformance/conformance_proto/conformance.proto ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. syntax = "proto3"; package conformance; option java_package = "com.google.protobuf.conformance"; import "google/protobuf/any.proto"; import "google/protobuf/duration.proto"; import "google/protobuf/field_mask.proto"; import "google/protobuf/struct.proto"; import "google/protobuf/timestamp.proto"; import "google/protobuf/wrappers.proto"; // This defines the conformance testing protocol. This protocol exists between // the conformance test suite itself and the code being tested. For each test, // the suite will send a ConformanceRequest message and expect a // ConformanceResponse message. // // You can either run the tests in two different ways: // // 1. in-process (using the interface in conformance_test.h). // // 2. as a sub-process communicating over a pipe. Information about how to // do this is in conformance_test_runner.cc. // // Pros/cons of the two approaches: // // - running as a sub-process is much simpler for languages other than C/C++. // // - running as a sub-process may be more tricky in unusual environments like // iOS apps, where fork/stdin/stdout are not available. enum WireFormat { UNSPECIFIED = 0; PROTOBUF = 1; JSON = 2; } // Represents a single test case's input. The testee should: // // 1. parse this proto (which should always succeed) // 2. parse the protobuf or JSON payload in "payload" (which may fail) // 3. if the parse succeeded, serialize the message in the requested format. message ConformanceRequest { // The payload (whether protobuf of JSON) is always for a TestAllTypes proto // (see below). oneof payload { bytes protobuf_payload = 1; string json_payload = 2; } // Which format should the testee serialize its message to? WireFormat requested_output_format = 3; } // Represents a single test case's output. message ConformanceResponse { oneof result { // This string should be set to indicate parsing failed. The string can // provide more information about the parse error if it is available. // // Setting this string does not necessarily mean the testee failed the // test. Some of the test cases are intentionally invalid input. string parse_error = 1; // If the input was successfully parsed but errors occurred when // serializing it to the requested output format, set the error message in // this field. string serialize_error = 6; // This should be set if some other error occurred. This will always // indicate that the test failed. The string can provide more information // about the failure. string runtime_error = 2; // If the input was successfully parsed and the requested output was // protobuf, serialize it to protobuf and set it in this field. bytes protobuf_payload = 3; // If the input was successfully parsed and the requested output was JSON, // serialize to JSON and set it in this field. string json_payload = 4; // For when the testee skipped the test, likely because a certain feature // wasn't supported, like JSON input/output. string skipped = 5; } } // This proto includes every type of field in both singular and repeated // forms. message TestAllTypes { message NestedMessage { int32 a = 1; TestAllTypes corecursive = 2; } enum NestedEnum { FOO = 0; BAR = 1; BAZ = 2; NEG = -1; // Intentionally negative. } // Singular int32 optional_int32 = 1; int64 optional_int64 = 2; uint32 optional_uint32 = 3; uint64 optional_uint64 = 4; sint32 optional_sint32 = 5; sint64 optional_sint64 = 6; fixed32 optional_fixed32 = 7; fixed64 optional_fixed64 = 8; sfixed32 optional_sfixed32 = 9; sfixed64 optional_sfixed64 = 10; float optional_float = 11; double optional_double = 12; bool optional_bool = 13; string optional_string = 14; bytes optional_bytes = 15; NestedMessage optional_nested_message = 18; ForeignMessage optional_foreign_message = 19; NestedEnum optional_nested_enum = 21; ForeignEnum optional_foreign_enum = 22; string optional_string_piece = 24 [ctype=STRING_PIECE]; string optional_cord = 25 [ctype=CORD]; TestAllTypes recursive_message = 27; // Repeated repeated int32 repeated_int32 = 31; repeated int64 repeated_int64 = 32; repeated uint32 repeated_uint32 = 33; repeated uint64 repeated_uint64 = 34; repeated sint32 repeated_sint32 = 35; repeated sint64 repeated_sint64 = 36; repeated fixed32 repeated_fixed32 = 37; repeated fixed64 repeated_fixed64 = 38; repeated sfixed32 repeated_sfixed32 = 39; repeated sfixed64 repeated_sfixed64 = 40; repeated float repeated_float = 41; repeated double repeated_double = 42; repeated bool repeated_bool = 43; repeated string repeated_string = 44; repeated bytes repeated_bytes = 45; repeated NestedMessage repeated_nested_message = 48; repeated ForeignMessage repeated_foreign_message = 49; repeated NestedEnum repeated_nested_enum = 51; repeated ForeignEnum repeated_foreign_enum = 52; repeated string repeated_string_piece = 54 [ctype=STRING_PIECE]; repeated string repeated_cord = 55 [ctype=CORD]; // Map map < int32, int32> map_int32_int32 = 56; map < int64, int64> map_int64_int64 = 57; map < uint32, uint32> map_uint32_uint32 = 58; map < uint64, uint64> map_uint64_uint64 = 59; map < sint32, sint32> map_sint32_sint32 = 60; map < sint64, sint64> map_sint64_sint64 = 61; map < fixed32, fixed32> map_fixed32_fixed32 = 62; map < fixed64, fixed64> map_fixed64_fixed64 = 63; map map_sfixed32_sfixed32 = 64; map map_sfixed64_sfixed64 = 65; map < int32, float> map_int32_float = 66; map < int32, double> map_int32_double = 67; map < bool, bool> map_bool_bool = 68; map < string, string> map_string_string = 69; map < string, bytes> map_string_bytes = 70; map < string, NestedMessage> map_string_nested_message = 71; map < string, ForeignMessage> map_string_foreign_message = 72; map < string, NestedEnum> map_string_nested_enum = 73; map < string, ForeignEnum> map_string_foreign_enum = 74; oneof oneof_field { uint32 oneof_uint32 = 111; NestedMessage oneof_nested_message = 112; string oneof_string = 113; bytes oneof_bytes = 114; bool oneof_bool = 115; uint64 oneof_uint64 = 116; float oneof_float = 117; double oneof_double = 118; NestedEnum oneof_enum = 119; } // Well-known types google.protobuf.BoolValue optional_bool_wrapper = 201; google.protobuf.Int32Value optional_int32_wrapper = 202; google.protobuf.Int64Value optional_int64_wrapper = 203; google.protobuf.UInt32Value optional_uint32_wrapper = 204; google.protobuf.UInt64Value optional_uint64_wrapper = 205; google.protobuf.FloatValue optional_float_wrapper = 206; google.protobuf.DoubleValue optional_double_wrapper = 207; google.protobuf.StringValue optional_string_wrapper = 208; google.protobuf.BytesValue optional_bytes_wrapper = 209; repeated google.protobuf.BoolValue repeated_bool_wrapper = 211; repeated google.protobuf.Int32Value repeated_int32_wrapper = 212; repeated google.protobuf.Int64Value repeated_int64_wrapper = 213; repeated google.protobuf.UInt32Value repeated_uint32_wrapper = 214; repeated google.protobuf.UInt64Value repeated_uint64_wrapper = 215; repeated google.protobuf.FloatValue repeated_float_wrapper = 216; repeated google.protobuf.DoubleValue repeated_double_wrapper = 217; repeated google.protobuf.StringValue repeated_string_wrapper = 218; repeated google.protobuf.BytesValue repeated_bytes_wrapper = 219; google.protobuf.Duration optional_duration = 301; google.protobuf.Timestamp optional_timestamp = 302; google.protobuf.FieldMask optional_field_mask = 303; google.protobuf.Struct optional_struct = 304; google.protobuf.Any optional_any = 305; google.protobuf.Value optional_value = 306; repeated google.protobuf.Duration repeated_duration = 311; repeated google.protobuf.Timestamp repeated_timestamp = 312; repeated google.protobuf.FieldMask repeated_fieldmask = 313; repeated google.protobuf.Struct repeated_struct = 324; repeated google.protobuf.Any repeated_any = 315; repeated google.protobuf.Value repeated_value = 316; // Test field-name-to-JSON-name convention. // (protobuf says names can be any valid C/C++ identifier.) int32 fieldname1 = 401; int32 field_name2 = 402; int32 _field_name3 = 403; int32 field__name4_ = 404; int32 field0name5 = 405; int32 field_0_name6 = 406; int32 fieldName7 = 407; int32 FieldName8 = 408; int32 field_Name9 = 409; int32 Field_Name10 = 410; int32 FIELD_NAME11 = 411; int32 FIELD_name12 = 412; int32 __field_name13 = 413; int32 __Field_name14 = 414; int32 field__name15 = 415; int32 field__Name16 = 416; int32 field_name17__ = 417; int32 Field_name18__ = 418; } message ForeignMessage { int32 c = 1; } enum ForeignEnum { FOREIGN_FOO = 0; FOREIGN_BAR = 1; FOREIGN_BAZ = 2; } ================================================ FILE: src/github.com/golang/protobuf/descriptor/descriptor.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/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. // Package descriptor provides functions for obtaining protocol buffer // descriptors for generated Go types. // // These functions cannot go in package proto because they depend on the // generated protobuf descriptor messages, which themselves depend on proto. package descriptor import ( "bytes" "compress/gzip" "fmt" "io/ioutil" "github.com/golang/protobuf/proto" protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" ) // extractFile extracts a FileDescriptorProto from a gzip'd buffer. func extractFile(gz []byte) (*protobuf.FileDescriptorProto, error) { r, err := gzip.NewReader(bytes.NewReader(gz)) if err != nil { return nil, fmt.Errorf("failed to open gzip reader: %v", err) } defer r.Close() b, err := ioutil.ReadAll(r) if err != nil { return nil, fmt.Errorf("failed to uncompress descriptor: %v", err) } fd := new(protobuf.FileDescriptorProto) if err := proto.Unmarshal(b, fd); err != nil { return nil, fmt.Errorf("malformed FileDescriptorProto: %v", err) } return fd, nil } // Message is a proto.Message with a method to return its descriptor. // // Message types generated by the protocol compiler always satisfy // the Message interface. type Message interface { proto.Message Descriptor() ([]byte, []int) } // ForMessage returns a FileDescriptorProto and a DescriptorProto from within it // describing the given message. func ForMessage(msg Message) (fd *protobuf.FileDescriptorProto, md *protobuf.DescriptorProto) { gz, path := msg.Descriptor() fd, err := extractFile(gz) if err != nil { panic(fmt.Sprintf("invalid FileDescriptorProto for %T: %v", msg, err)) } md = fd.MessageType[path[0]] for _, i := range path[1:] { md = md.NestedType[i] } return fd, md } ================================================ FILE: src/github.com/golang/protobuf/descriptor/descriptor_test.go ================================================ package descriptor_test import ( "fmt" "testing" "github.com/golang/protobuf/descriptor" tpb "github.com/golang/protobuf/proto/testdata" protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" ) func TestMessage(t *testing.T) { var msg *protobuf.DescriptorProto fd, md := descriptor.ForMessage(msg) if pkg, want := fd.GetPackage(), "google.protobuf"; pkg != want { t.Errorf("descriptor.ForMessage(%T).GetPackage() = %q; want %q", msg, pkg, want) } if name, want := md.GetName(), "DescriptorProto"; name != want { t.Fatalf("descriptor.ForMessage(%T).GetName() = %q; want %q", msg, name, want) } } func Example_Options() { var msg *tpb.MyMessageSet _, md := descriptor.ForMessage(msg) if md.GetOptions().GetMessageSetWireFormat() { fmt.Printf("%v uses option message_set_wire_format.\n", md.GetName()) } // Output: // MyMessageSet uses option message_set_wire_format. } ================================================ FILE: src/github.com/golang/protobuf/jsonpb/jsonpb.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/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. /* Package jsonpb provides marshaling and unmarshaling between protocol buffers and JSON. It follows the specification at https://developers.google.com/protocol-buffers/docs/proto3#json. This package produces a different output than the standard "encoding/json" package, which does not operate correctly on protocol buffers. */ package jsonpb import ( "bytes" "encoding/json" "errors" "fmt" "io" "math" "reflect" "sort" "strconv" "strings" "time" "github.com/golang/protobuf/proto" stpb "github.com/golang/protobuf/ptypes/struct" ) // Marshaler is a configurable object for converting between // protocol buffer objects and a JSON representation for them. type Marshaler struct { // Whether to render enum values as integers, as opposed to string values. EnumsAsInts bool // Whether to render fields with zero values. EmitDefaults bool // A string to indent each level by. The presence of this field will // also cause a space to appear between the field separator and // value, and for newlines to be appear between fields and array // elements. Indent string // Whether to use the original (.proto) name for fields. OrigName bool // A custom URL resolver to use when marshaling Any messages to JSON. // If unset, the default resolution strategy is to extract the // fully-qualified type name from the type URL and pass that to // proto.MessageType(string). AnyResolver AnyResolver } // AnyResolver takes a type URL, present in an Any message, and resolves it into // an instance of the associated message. type AnyResolver interface { Resolve(typeUrl string) (proto.Message, error) } func defaultResolveAny(typeUrl string) (proto.Message, error) { // Only the part of typeUrl after the last slash is relevant. mname := typeUrl if slash := strings.LastIndex(mname, "/"); slash >= 0 { mname = mname[slash+1:] } mt := proto.MessageType(mname) if mt == nil { return nil, fmt.Errorf("unknown message type %q", mname) } return reflect.New(mt.Elem()).Interface().(proto.Message), nil } // JSONPBMarshaler is implemented by protobuf messages that customize the // way they are marshaled to JSON. Messages that implement this should // also implement JSONPBUnmarshaler so that the custom format can be // parsed. type JSONPBMarshaler interface { MarshalJSONPB(*Marshaler) ([]byte, error) } // JSONPBUnmarshaler is implemented by protobuf messages that customize // the way they are unmarshaled from JSON. Messages that implement this // should also implement JSONPBMarshaler so that the custom format can be // produced. type JSONPBUnmarshaler interface { UnmarshalJSONPB(*Unmarshaler, []byte) error } // Marshal marshals a protocol buffer into JSON. func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error { writer := &errWriter{writer: out} return m.marshalObject(writer, pb, "", "") } // MarshalToString converts a protocol buffer object to JSON string. func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) { var buf bytes.Buffer if err := m.Marshal(&buf, pb); err != nil { return "", err } return buf.String(), nil } type int32Slice []int32 var nonFinite = map[string]float64{ `"NaN"`: math.NaN(), `"Infinity"`: math.Inf(1), `"-Infinity"`: math.Inf(-1), } // For sorting extensions ids to ensure stable output. func (s int32Slice) Len() int { return len(s) } func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } type wkt interface { XXX_WellKnownType() string } // marshalObject writes a struct to the Writer. func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeURL string) error { if jsm, ok := v.(JSONPBMarshaler); ok { b, err := jsm.MarshalJSONPB(m) if err != nil { return err } if typeURL != "" { // we are marshaling this object to an Any type var js map[string]*json.RawMessage if err = json.Unmarshal(b, &js); err != nil { return fmt.Errorf("type %T produced invalid JSON: %v", v, err) } turl, err := json.Marshal(typeURL) if err != nil { return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err) } js["@type"] = (*json.RawMessage)(&turl) if b, err = json.Marshal(js); err != nil { return err } } out.write(string(b)) return out.err } s := reflect.ValueOf(v).Elem() // Handle well-known types. if wkt, ok := v.(wkt); ok { switch wkt.XXX_WellKnownType() { case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value", "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue": // "Wrappers use the same representation in JSON // as the wrapped primitive type, ..." sprop := proto.GetProperties(s.Type()) return m.marshalValue(out, sprop.Prop[0], s.Field(0), indent) case "Any": // Any is a bit more involved. return m.marshalAny(out, v, indent) case "Duration": // "Generated output always contains 3, 6, or 9 fractional digits, // depending on required precision." s, ns := s.Field(0).Int(), s.Field(1).Int() d := time.Duration(s)*time.Second + time.Duration(ns)*time.Nanosecond x := fmt.Sprintf("%.9f", d.Seconds()) x = strings.TrimSuffix(x, "000") x = strings.TrimSuffix(x, "000") out.write(`"`) out.write(x) out.write(`s"`) return out.err case "Struct", "ListValue": // Let marshalValue handle the `Struct.fields` map or the `ListValue.values` slice. // TODO: pass the correct Properties if needed. return m.marshalValue(out, &proto.Properties{}, s.Field(0), indent) case "Timestamp": // "RFC 3339, where generated output will always be Z-normalized // and uses 3, 6 or 9 fractional digits." s, ns := s.Field(0).Int(), s.Field(1).Int() t := time.Unix(s, ns).UTC() // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits). x := t.Format("2006-01-02T15:04:05.000000000") x = strings.TrimSuffix(x, "000") x = strings.TrimSuffix(x, "000") out.write(`"`) out.write(x) out.write(`Z"`) return out.err case "Value": // Value has a single oneof. kind := s.Field(0) if kind.IsNil() { // "absence of any variant indicates an error" return errors.New("nil Value") } // oneof -> *T -> T -> T.F x := kind.Elem().Elem().Field(0) // TODO: pass the correct Properties if needed. return m.marshalValue(out, &proto.Properties{}, x, indent) } } out.write("{") if m.Indent != "" { out.write("\n") } firstField := true if typeURL != "" { if err := m.marshalTypeURL(out, indent, typeURL); err != nil { return err } firstField = false } for i := 0; i < s.NumField(); i++ { value := s.Field(i) valueField := s.Type().Field(i) if strings.HasPrefix(valueField.Name, "XXX_") { continue } // IsNil will panic on most value kinds. switch value.Kind() { case reflect.Chan, reflect.Func, reflect.Interface: if value.IsNil() { continue } } if !m.EmitDefaults { switch value.Kind() { case reflect.Bool: if !value.Bool() { continue } case reflect.Int32, reflect.Int64: if value.Int() == 0 { continue } case reflect.Uint32, reflect.Uint64: if value.Uint() == 0 { continue } case reflect.Float32, reflect.Float64: if value.Float() == 0 { continue } case reflect.String: if value.Len() == 0 { continue } case reflect.Map, reflect.Ptr, reflect.Slice: if value.IsNil() { continue } } } // Oneof fields need special handling. if valueField.Tag.Get("protobuf_oneof") != "" { // value is an interface containing &T{real_value}. sv := value.Elem().Elem() // interface -> *T -> T value = sv.Field(0) valueField = sv.Type().Field(0) } prop := jsonProperties(valueField, m.OrigName) if !firstField { m.writeSep(out) } if err := m.marshalField(out, prop, value, indent); err != nil { return err } firstField = false } // Handle proto2 extensions. if ep, ok := v.(proto.Message); ok { extensions := proto.RegisteredExtensions(v) // Sort extensions for stable output. ids := make([]int32, 0, len(extensions)) for id, desc := range extensions { if !proto.HasExtension(ep, desc) { continue } ids = append(ids, id) } sort.Sort(int32Slice(ids)) for _, id := range ids { desc := extensions[id] if desc == nil { // unknown extension continue } ext, extErr := proto.GetExtension(ep, desc) if extErr != nil { return extErr } value := reflect.ValueOf(ext) var prop proto.Properties prop.Parse(desc.Tag) prop.JSONName = fmt.Sprintf("[%s]", desc.Name) if !firstField { m.writeSep(out) } if err := m.marshalField(out, &prop, value, indent); err != nil { return err } firstField = false } } if m.Indent != "" { out.write("\n") out.write(indent) } out.write("}") return out.err } func (m *Marshaler) writeSep(out *errWriter) { if m.Indent != "" { out.write(",\n") } else { out.write(",") } } func (m *Marshaler) marshalAny(out *errWriter, any proto.Message, indent string) error { // "If the Any contains a value that has a special JSON mapping, // it will be converted as follows: {"@type": xxx, "value": yyy}. // Otherwise, the value will be converted into a JSON object, // and the "@type" field will be inserted to indicate the actual data type." v := reflect.ValueOf(any).Elem() turl := v.Field(0).String() val := v.Field(1).Bytes() var msg proto.Message var err error if m.AnyResolver != nil { msg, err = m.AnyResolver.Resolve(turl) } else { msg, err = defaultResolveAny(turl) } if err != nil { return err } if err := proto.Unmarshal(val, msg); err != nil { return err } if _, ok := msg.(wkt); ok { out.write("{") if m.Indent != "" { out.write("\n") } if err := m.marshalTypeURL(out, indent, turl); err != nil { return err } m.writeSep(out) if m.Indent != "" { out.write(indent) out.write(m.Indent) out.write(`"value": `) } else { out.write(`"value":`) } if err := m.marshalObject(out, msg, indent+m.Indent, ""); err != nil { return err } if m.Indent != "" { out.write("\n") out.write(indent) } out.write("}") return out.err } return m.marshalObject(out, msg, indent, turl) } func (m *Marshaler) marshalTypeURL(out *errWriter, indent, typeURL string) error { if m.Indent != "" { out.write(indent) out.write(m.Indent) } out.write(`"@type":`) if m.Indent != "" { out.write(" ") } b, err := json.Marshal(typeURL) if err != nil { return err } out.write(string(b)) return out.err } // marshalField writes field description and value to the Writer. func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error { if m.Indent != "" { out.write(indent) out.write(m.Indent) } out.write(`"`) out.write(prop.JSONName) out.write(`":`) if m.Indent != "" { out.write(" ") } if err := m.marshalValue(out, prop, v, indent); err != nil { return err } return nil } // marshalValue writes the value to the Writer. func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error { var err error v = reflect.Indirect(v) // Handle nil pointer if v.Kind() == reflect.Invalid { out.write("null") return out.err } // Handle repeated elements. if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 { out.write("[") comma := "" for i := 0; i < v.Len(); i++ { sliceVal := v.Index(i) out.write(comma) if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) out.write(m.Indent) } if err := m.marshalValue(out, prop, sliceVal, indent+m.Indent); err != nil { return err } comma = "," } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) } out.write("]") return out.err } // Handle well-known types. // Most are handled up in marshalObject (because 99% are messages). if wkt, ok := v.Interface().(wkt); ok { switch wkt.XXX_WellKnownType() { case "NullValue": out.write("null") return out.err } } // Handle enumerations. if !m.EnumsAsInts && prop.Enum != "" { // Unknown enum values will are stringified by the proto library as their // value. Such values should _not_ be quoted or they will be interpreted // as an enum string instead of their value. enumStr := v.Interface().(fmt.Stringer).String() var valStr string if v.Kind() == reflect.Ptr { valStr = strconv.Itoa(int(v.Elem().Int())) } else { valStr = strconv.Itoa(int(v.Int())) } isKnownEnum := enumStr != valStr if isKnownEnum { out.write(`"`) } out.write(enumStr) if isKnownEnum { out.write(`"`) } return out.err } // Handle nested messages. if v.Kind() == reflect.Struct { return m.marshalObject(out, v.Addr().Interface().(proto.Message), indent+m.Indent, "") } // Handle maps. // Since Go randomizes map iteration, we sort keys for stable output. if v.Kind() == reflect.Map { out.write(`{`) keys := v.MapKeys() sort.Sort(mapKeys(keys)) for i, k := range keys { if i > 0 { out.write(`,`) } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) out.write(m.Indent) } b, err := json.Marshal(k.Interface()) if err != nil { return err } s := string(b) // If the JSON is not a string value, encode it again to make it one. if !strings.HasPrefix(s, `"`) { b, err := json.Marshal(s) if err != nil { return err } s = string(b) } out.write(s) out.write(`:`) if m.Indent != "" { out.write(` `) } if err := m.marshalValue(out, prop, v.MapIndex(k), indent+m.Indent); err != nil { return err } } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) } out.write(`}`) return out.err } // Handle non-finite floats, e.g. NaN, Infinity and -Infinity. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { f := v.Float() var sval string switch { case math.IsInf(f, 1): sval = `"Infinity"` case math.IsInf(f, -1): sval = `"-Infinity"` case math.IsNaN(f): sval = `"NaN"` } if sval != "" { out.write(sval) return out.err } } // Default handling defers to the encoding/json library. b, err := json.Marshal(v.Interface()) if err != nil { return err } needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64) if needToQuote { out.write(`"`) } out.write(string(b)) if needToQuote { out.write(`"`) } return out.err } // Unmarshaler is a configurable object for converting from a JSON // representation to a protocol buffer object. type Unmarshaler struct { // Whether to allow messages to contain unknown fields, as opposed to // failing to unmarshal. AllowUnknownFields bool // A custom URL resolver to use when unmarshaling Any messages from JSON. // If unset, the default resolution strategy is to extract the // fully-qualified type name from the type URL and pass that to // proto.MessageType(string). AnyResolver AnyResolver } // UnmarshalNext unmarshals the next protocol buffer from a JSON object stream. // This function is lenient and will decode any options permutations of the // related Marshaler. func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error { inputValue := json.RawMessage{} if err := dec.Decode(&inputValue); err != nil { return err } return u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil) } // Unmarshal unmarshals a JSON object stream into a protocol // buffer. This function is lenient and will decode any options // permutations of the related Marshaler. func (u *Unmarshaler) Unmarshal(r io.Reader, pb proto.Message) error { dec := json.NewDecoder(r) return u.UnmarshalNext(dec, pb) } // UnmarshalNext unmarshals the next protocol buffer from a JSON object stream. // This function is lenient and will decode any options permutations of the // related Marshaler. func UnmarshalNext(dec *json.Decoder, pb proto.Message) error { return new(Unmarshaler).UnmarshalNext(dec, pb) } // Unmarshal unmarshals a JSON object stream into a protocol // buffer. This function is lenient and will decode any options // permutations of the related Marshaler. func Unmarshal(r io.Reader, pb proto.Message) error { return new(Unmarshaler).Unmarshal(r, pb) } // UnmarshalString will populate the fields of a protocol buffer based // on a JSON string. This function is lenient and will decode any options // permutations of the related Marshaler. func UnmarshalString(str string, pb proto.Message) error { return new(Unmarshaler).Unmarshal(strings.NewReader(str), pb) } // unmarshalValue converts/copies a value into the target. // prop may be nil. func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMessage, prop *proto.Properties) error { targetType := target.Type() // Allocate memory for pointer fields. if targetType.Kind() == reflect.Ptr { // If input value is "null" and target is a pointer type, then the field should be treated as not set // UNLESS the target is structpb.Value, in which case it should be set to structpb.NullValue. _, isJSONPBUnmarshaler := target.Interface().(JSONPBUnmarshaler) if string(inputValue) == "null" && targetType != reflect.TypeOf(&stpb.Value{}) && !isJSONPBUnmarshaler { return nil } target.Set(reflect.New(targetType.Elem())) return u.unmarshalValue(target.Elem(), inputValue, prop) } if jsu, ok := target.Addr().Interface().(JSONPBUnmarshaler); ok { return jsu.UnmarshalJSONPB(u, []byte(inputValue)) } // Handle well-known types that are not pointers. if w, ok := target.Addr().Interface().(wkt); ok { switch w.XXX_WellKnownType() { case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value", "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue": return u.unmarshalValue(target.Field(0), inputValue, prop) case "Any": // Use json.RawMessage pointer type instead of value to support pre-1.8 version. // 1.8 changed RawMessage.MarshalJSON from pointer type to value type, see // https://github.com/golang/go/issues/14493 var jsonFields map[string]*json.RawMessage if err := json.Unmarshal(inputValue, &jsonFields); err != nil { return err } val, ok := jsonFields["@type"] if !ok || val == nil { return errors.New("Any JSON doesn't have '@type'") } var turl string if err := json.Unmarshal([]byte(*val), &turl); err != nil { return fmt.Errorf("can't unmarshal Any's '@type': %q", *val) } target.Field(0).SetString(turl) var m proto.Message var err error if u.AnyResolver != nil { m, err = u.AnyResolver.Resolve(turl) } else { m, err = defaultResolveAny(turl) } if err != nil { return err } if _, ok := m.(wkt); ok { val, ok := jsonFields["value"] if !ok { return errors.New("Any JSON doesn't have 'value'") } if err := u.unmarshalValue(reflect.ValueOf(m).Elem(), *val, nil); err != nil { return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err) } } else { delete(jsonFields, "@type") nestedProto, err := json.Marshal(jsonFields) if err != nil { return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err) } if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), nestedProto, nil); err != nil { return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err) } } b, err := proto.Marshal(m) if err != nil { return fmt.Errorf("can't marshal proto %T into Any.Value: %v", m, err) } target.Field(1).SetBytes(b) return nil case "Duration": unq, err := strconv.Unquote(string(inputValue)) if err != nil { return err } d, err := time.ParseDuration(unq) if err != nil { return fmt.Errorf("bad Duration: %v", err) } ns := d.Nanoseconds() s := ns / 1e9 ns %= 1e9 target.Field(0).SetInt(s) target.Field(1).SetInt(ns) return nil case "Timestamp": unq, err := strconv.Unquote(string(inputValue)) if err != nil { return err } t, err := time.Parse(time.RFC3339Nano, unq) if err != nil { return fmt.Errorf("bad Timestamp: %v", err) } target.Field(0).SetInt(t.Unix()) target.Field(1).SetInt(int64(t.Nanosecond())) return nil case "Struct": var m map[string]json.RawMessage if err := json.Unmarshal(inputValue, &m); err != nil { return fmt.Errorf("bad StructValue: %v", err) } target.Field(0).Set(reflect.ValueOf(map[string]*stpb.Value{})) for k, jv := range m { pv := &stpb.Value{} if err := u.unmarshalValue(reflect.ValueOf(pv).Elem(), jv, prop); err != nil { return fmt.Errorf("bad value in StructValue for key %q: %v", k, err) } target.Field(0).SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(pv)) } return nil case "ListValue": var s []json.RawMessage if err := json.Unmarshal(inputValue, &s); err != nil { return fmt.Errorf("bad ListValue: %v", err) } target.Field(0).Set(reflect.ValueOf(make([]*stpb.Value, len(s), len(s)))) for i, sv := range s { if err := u.unmarshalValue(target.Field(0).Index(i), sv, prop); err != nil { return err } } return nil case "Value": ivStr := string(inputValue) if ivStr == "null" { target.Field(0).Set(reflect.ValueOf(&stpb.Value_NullValue{})) } else if v, err := strconv.ParseFloat(ivStr, 0); err == nil { target.Field(0).Set(reflect.ValueOf(&stpb.Value_NumberValue{v})) } else if v, err := strconv.Unquote(ivStr); err == nil { target.Field(0).Set(reflect.ValueOf(&stpb.Value_StringValue{v})) } else if v, err := strconv.ParseBool(ivStr); err == nil { target.Field(0).Set(reflect.ValueOf(&stpb.Value_BoolValue{v})) } else if err := json.Unmarshal(inputValue, &[]json.RawMessage{}); err == nil { lv := &stpb.ListValue{} target.Field(0).Set(reflect.ValueOf(&stpb.Value_ListValue{lv})) return u.unmarshalValue(reflect.ValueOf(lv).Elem(), inputValue, prop) } else if err := json.Unmarshal(inputValue, &map[string]json.RawMessage{}); err == nil { sv := &stpb.Struct{} target.Field(0).Set(reflect.ValueOf(&stpb.Value_StructValue{sv})) return u.unmarshalValue(reflect.ValueOf(sv).Elem(), inputValue, prop) } else { return fmt.Errorf("unrecognized type for Value %q", ivStr) } return nil } } // Handle enums, which have an underlying type of int32, // and may appear as strings. // The case of an enum appearing as a number is handled // at the bottom of this function. if inputValue[0] == '"' && prop != nil && prop.Enum != "" { vmap := proto.EnumValueMap(prop.Enum) // Don't need to do unquoting; valid enum names // are from a limited character set. s := inputValue[1 : len(inputValue)-1] n, ok := vmap[string(s)] if !ok { return fmt.Errorf("unknown value %q for enum %s", s, prop.Enum) } if target.Kind() == reflect.Ptr { // proto2 target.Set(reflect.New(targetType.Elem())) target = target.Elem() } target.SetInt(int64(n)) return nil } // Handle nested messages. if targetType.Kind() == reflect.Struct { var jsonFields map[string]json.RawMessage if err := json.Unmarshal(inputValue, &jsonFields); err != nil { return err } consumeField := func(prop *proto.Properties) (json.RawMessage, bool) { // Be liberal in what names we accept; both orig_name and camelName are okay. fieldNames := acceptedJSONFieldNames(prop) vOrig, okOrig := jsonFields[fieldNames.orig] vCamel, okCamel := jsonFields[fieldNames.camel] if !okOrig && !okCamel { return nil, false } // If, for some reason, both are present in the data, favour the camelName. var raw json.RawMessage if okOrig { raw = vOrig delete(jsonFields, fieldNames.orig) } if okCamel { raw = vCamel delete(jsonFields, fieldNames.camel) } return raw, true } sprops := proto.GetProperties(targetType) for i := 0; i < target.NumField(); i++ { ft := target.Type().Field(i) if strings.HasPrefix(ft.Name, "XXX_") { continue } valueForField, ok := consumeField(sprops.Prop[i]) if !ok { continue } if err := u.unmarshalValue(target.Field(i), valueForField, sprops.Prop[i]); err != nil { return err } } // Check for any oneof fields. if len(jsonFields) > 0 { for _, oop := range sprops.OneofTypes { raw, ok := consumeField(oop.Prop) if !ok { continue } nv := reflect.New(oop.Type.Elem()) target.Field(oop.Field).Set(nv) if err := u.unmarshalValue(nv.Elem().Field(0), raw, oop.Prop); err != nil { return err } } } // Handle proto2 extensions. if len(jsonFields) > 0 { if ep, ok := target.Addr().Interface().(proto.Message); ok { for _, ext := range proto.RegisteredExtensions(ep) { name := fmt.Sprintf("[%s]", ext.Name) raw, ok := jsonFields[name] if !ok { continue } delete(jsonFields, name) nv := reflect.New(reflect.TypeOf(ext.ExtensionType).Elem()) if err := u.unmarshalValue(nv.Elem(), raw, nil); err != nil { return err } if err := proto.SetExtension(ep, ext, nv.Interface()); err != nil { return err } } } } if !u.AllowUnknownFields && len(jsonFields) > 0 { // Pick any field to be the scapegoat. var f string for fname := range jsonFields { f = fname break } return fmt.Errorf("unknown field %q in %v", f, targetType) } return nil } // Handle arrays (which aren't encoded bytes) if targetType.Kind() == reflect.Slice && targetType.Elem().Kind() != reflect.Uint8 { var slc []json.RawMessage if err := json.Unmarshal(inputValue, &slc); err != nil { return err } if slc != nil { l := len(slc) target.Set(reflect.MakeSlice(targetType, l, l)) for i := 0; i < l; i++ { if err := u.unmarshalValue(target.Index(i), slc[i], prop); err != nil { return err } } } return nil } // Handle maps (whose keys are always strings) if targetType.Kind() == reflect.Map { var mp map[string]json.RawMessage if err := json.Unmarshal(inputValue, &mp); err != nil { return err } if mp != nil { target.Set(reflect.MakeMap(targetType)) var keyprop, valprop *proto.Properties if prop != nil { // These could still be nil if the protobuf metadata is broken somehow. // TODO: This won't work because the fields are unexported. // We should probably just reparse them. //keyprop, valprop = prop.mkeyprop, prop.mvalprop } for ks, raw := range mp { // Unmarshal map key. The core json library already decoded the key into a // string, so we handle that specially. Other types were quoted post-serialization. var k reflect.Value if targetType.Key().Kind() == reflect.String { k = reflect.ValueOf(ks) } else { k = reflect.New(targetType.Key()).Elem() if err := u.unmarshalValue(k, json.RawMessage(ks), keyprop); err != nil { return err } } // Unmarshal map value. v := reflect.New(targetType.Elem()).Elem() if err := u.unmarshalValue(v, raw, valprop); err != nil { return err } target.SetMapIndex(k, v) } } return nil } // 64-bit integers can be encoded as strings. In this case we drop // the quotes and proceed as normal. isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64 if isNum && strings.HasPrefix(string(inputValue), `"`) { inputValue = inputValue[1 : len(inputValue)-1] } // Non-finite numbers can be encoded as strings. isFloat := targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64 if isFloat { if num, ok := nonFinite[string(inputValue)]; ok { target.SetFloat(num) return nil } } // Use the encoding/json for parsing other value types. return json.Unmarshal(inputValue, target.Addr().Interface()) } // jsonProperties returns parsed proto.Properties for the field and corrects JSONName attribute. func jsonProperties(f reflect.StructField, origName bool) *proto.Properties { var prop proto.Properties prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f) if origName || prop.JSONName == "" { prop.JSONName = prop.OrigName } return &prop } type fieldNames struct { orig, camel string } func acceptedJSONFieldNames(prop *proto.Properties) fieldNames { opts := fieldNames{orig: prop.OrigName, camel: prop.OrigName} if prop.JSONName != "" { opts.camel = prop.JSONName } return opts } // Writer wrapper inspired by https://blog.golang.org/errors-are-values type errWriter struct { writer io.Writer err error } func (w *errWriter) write(str string) { if w.err != nil { return } _, w.err = w.writer.Write([]byte(str)) } // Map fields may have key types of non-float scalars, strings and enums. // The easiest way to sort them in some deterministic order is to use fmt. // If this turns out to be inefficient we can always consider other options, // such as doing a Schwartzian transform. // // Numeric keys are sorted in numeric order per // https://developers.google.com/protocol-buffers/docs/proto#maps. type mapKeys []reflect.Value func (s mapKeys) Len() int { return len(s) } func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s mapKeys) Less(i, j int) bool { if k := s[i].Kind(); k == s[j].Kind() { switch k { case reflect.Int32, reflect.Int64: return s[i].Int() < s[j].Int() case reflect.Uint32, reflect.Uint64: return s[i].Uint() < s[j].Uint() } } return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface()) } ================================================ FILE: src/github.com/golang/protobuf/jsonpb/jsonpb_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/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. package jsonpb import ( "bytes" "encoding/json" "io" "math" "reflect" "strings" "testing" "github.com/golang/protobuf/proto" pb "github.com/golang/protobuf/jsonpb/jsonpb_test_proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" "github.com/golang/protobuf/ptypes" anypb "github.com/golang/protobuf/ptypes/any" durpb "github.com/golang/protobuf/ptypes/duration" stpb "github.com/golang/protobuf/ptypes/struct" tspb "github.com/golang/protobuf/ptypes/timestamp" wpb "github.com/golang/protobuf/ptypes/wrappers" ) var ( marshaler = Marshaler{} marshalerAllOptions = Marshaler{ Indent: " ", } simpleObject = &pb.Simple{ OInt32: proto.Int32(-32), OInt64: proto.Int64(-6400000000), OUint32: proto.Uint32(32), OUint64: proto.Uint64(6400000000), OSint32: proto.Int32(-13), OSint64: proto.Int64(-2600000000), OFloat: proto.Float32(3.14), ODouble: proto.Float64(6.02214179e23), OBool: proto.Bool(true), OString: proto.String("hello \"there\""), OBytes: []byte("beep boop"), } simpleObjectJSON = `{` + `"oBool":true,` + `"oInt32":-32,` + `"oInt64":"-6400000000",` + `"oUint32":32,` + `"oUint64":"6400000000",` + `"oSint32":-13,` + `"oSint64":"-2600000000",` + `"oFloat":3.14,` + `"oDouble":6.02214179e+23,` + `"oString":"hello \"there\"",` + `"oBytes":"YmVlcCBib29w"` + `}` simpleObjectPrettyJSON = `{ "oBool": true, "oInt32": -32, "oInt64": "-6400000000", "oUint32": 32, "oUint64": "6400000000", "oSint32": -13, "oSint64": "-2600000000", "oFloat": 3.14, "oDouble": 6.02214179e+23, "oString": "hello \"there\"", "oBytes": "YmVlcCBib29w" }` repeatsObject = &pb.Repeats{ RBool: []bool{true, false, true}, RInt32: []int32{-3, -4, -5}, RInt64: []int64{-123456789, -987654321}, RUint32: []uint32{1, 2, 3}, RUint64: []uint64{6789012345, 3456789012}, RSint32: []int32{-1, -2, -3}, RSint64: []int64{-6789012345, -3456789012}, RFloat: []float32{3.14, 6.28}, RDouble: []float64{299792458 * 1e20, 6.62606957e-34}, RString: []string{"happy", "days"}, RBytes: [][]byte{[]byte("skittles"), []byte("m&m's")}, } repeatsObjectJSON = `{` + `"rBool":[true,false,true],` + `"rInt32":[-3,-4,-5],` + `"rInt64":["-123456789","-987654321"],` + `"rUint32":[1,2,3],` + `"rUint64":["6789012345","3456789012"],` + `"rSint32":[-1,-2,-3],` + `"rSint64":["-6789012345","-3456789012"],` + `"rFloat":[3.14,6.28],` + `"rDouble":[2.99792458e+28,6.62606957e-34],` + `"rString":["happy","days"],` + `"rBytes":["c2tpdHRsZXM=","bSZtJ3M="]` + `}` repeatsObjectPrettyJSON = `{ "rBool": [ true, false, true ], "rInt32": [ -3, -4, -5 ], "rInt64": [ "-123456789", "-987654321" ], "rUint32": [ 1, 2, 3 ], "rUint64": [ "6789012345", "3456789012" ], "rSint32": [ -1, -2, -3 ], "rSint64": [ "-6789012345", "-3456789012" ], "rFloat": [ 3.14, 6.28 ], "rDouble": [ 2.99792458e+28, 6.62606957e-34 ], "rString": [ "happy", "days" ], "rBytes": [ "c2tpdHRsZXM=", "bSZtJ3M=" ] }` innerSimple = &pb.Simple{OInt32: proto.Int32(-32)} innerSimple2 = &pb.Simple{OInt64: proto.Int64(25)} innerRepeats = &pb.Repeats{RString: []string{"roses", "red"}} innerRepeats2 = &pb.Repeats{RString: []string{"violets", "blue"}} complexObject = &pb.Widget{ Color: pb.Widget_GREEN.Enum(), RColor: []pb.Widget_Color{pb.Widget_RED, pb.Widget_GREEN, pb.Widget_BLUE}, Simple: innerSimple, RSimple: []*pb.Simple{innerSimple, innerSimple2}, Repeats: innerRepeats, RRepeats: []*pb.Repeats{innerRepeats, innerRepeats2}, } complexObjectJSON = `{"color":"GREEN",` + `"rColor":["RED","GREEN","BLUE"],` + `"simple":{"oInt32":-32},` + `"rSimple":[{"oInt32":-32},{"oInt64":"25"}],` + `"repeats":{"rString":["roses","red"]},` + `"rRepeats":[{"rString":["roses","red"]},{"rString":["violets","blue"]}]` + `}` complexObjectPrettyJSON = `{ "color": "GREEN", "rColor": [ "RED", "GREEN", "BLUE" ], "simple": { "oInt32": -32 }, "rSimple": [ { "oInt32": -32 }, { "oInt64": "25" } ], "repeats": { "rString": [ "roses", "red" ] }, "rRepeats": [ { "rString": [ "roses", "red" ] }, { "rString": [ "violets", "blue" ] } ] }` colorPrettyJSON = `{ "color": 2 }` colorListPrettyJSON = `{ "color": 1000, "rColor": [ "RED" ] }` nummyPrettyJSON = `{ "nummy": { "1": 2, "3": 4 } }` objjyPrettyJSON = `{ "objjy": { "1": { "dub": 1 } } }` realNumber = &pb.Real{Value: proto.Float64(3.14159265359)} realNumberName = "Pi" complexNumber = &pb.Complex{Imaginary: proto.Float64(0.5772156649)} realNumberJSON = `{` + `"value":3.14159265359,` + `"[jsonpb.Complex.real_extension]":{"imaginary":0.5772156649},` + `"[jsonpb.name]":"Pi"` + `}` anySimple = &pb.KnownTypes{ An: &anypb.Any{ TypeUrl: "something.example.com/jsonpb.Simple", Value: []byte{ // &pb.Simple{OBool:true} 1 << 3, 1, }, }, } anySimpleJSON = `{"an":{"@type":"something.example.com/jsonpb.Simple","oBool":true}}` anySimplePrettyJSON = `{ "an": { "@type": "something.example.com/jsonpb.Simple", "oBool": true } }` anyWellKnown = &pb.KnownTypes{ An: &anypb.Any{ TypeUrl: "type.googleapis.com/google.protobuf.Duration", Value: []byte{ // &durpb.Duration{Seconds: 1, Nanos: 212000000 } 1 << 3, 1, // seconds 2 << 3, 0x80, 0xba, 0x8b, 0x65, // nanos }, }, } anyWellKnownJSON = `{"an":{"@type":"type.googleapis.com/google.protobuf.Duration","value":"1.212s"}}` anyWellKnownPrettyJSON = `{ "an": { "@type": "type.googleapis.com/google.protobuf.Duration", "value": "1.212s" } }` nonFinites = &pb.NonFinites{ FNan: proto.Float32(float32(math.NaN())), FPinf: proto.Float32(float32(math.Inf(1))), FNinf: proto.Float32(float32(math.Inf(-1))), DNan: proto.Float64(float64(math.NaN())), DPinf: proto.Float64(float64(math.Inf(1))), DNinf: proto.Float64(float64(math.Inf(-1))), } nonFinitesJSON = `{` + `"fNan":"NaN",` + `"fPinf":"Infinity",` + `"fNinf":"-Infinity",` + `"dNan":"NaN",` + `"dPinf":"Infinity",` + `"dNinf":"-Infinity"` + `}` ) func init() { if err := proto.SetExtension(realNumber, pb.E_Name, &realNumberName); err != nil { panic(err) } if err := proto.SetExtension(realNumber, pb.E_Complex_RealExtension, complexNumber); err != nil { panic(err) } } var marshalingTests = []struct { desc string marshaler Marshaler pb proto.Message json string }{ {"simple flat object", marshaler, simpleObject, simpleObjectJSON}, {"simple pretty object", marshalerAllOptions, simpleObject, simpleObjectPrettyJSON}, {"non-finite floats fields object", marshaler, nonFinites, nonFinitesJSON}, {"repeated fields flat object", marshaler, repeatsObject, repeatsObjectJSON}, {"repeated fields pretty object", marshalerAllOptions, repeatsObject, repeatsObjectPrettyJSON}, {"nested message/enum flat object", marshaler, complexObject, complexObjectJSON}, {"nested message/enum pretty object", marshalerAllOptions, complexObject, complexObjectPrettyJSON}, {"enum-string flat object", Marshaler{}, &pb.Widget{Color: pb.Widget_BLUE.Enum()}, `{"color":"BLUE"}`}, {"enum-value pretty object", Marshaler{EnumsAsInts: true, Indent: " "}, &pb.Widget{Color: pb.Widget_BLUE.Enum()}, colorPrettyJSON}, {"unknown enum value object", marshalerAllOptions, &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}, colorListPrettyJSON}, {"repeated proto3 enum", Marshaler{}, &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ proto3pb.Message_PUNS, proto3pb.Message_SLAPSTICK, }}, `{"rFunny":["PUNS","SLAPSTICK"]}`}, {"repeated proto3 enum as int", Marshaler{EnumsAsInts: true}, &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ proto3pb.Message_PUNS, proto3pb.Message_SLAPSTICK, }}, `{"rFunny":[1,2]}`}, {"empty value", marshaler, &pb.Simple3{}, `{}`}, {"empty value emitted", Marshaler{EmitDefaults: true}, &pb.Simple3{}, `{"dub":0}`}, {"empty repeated emitted", Marshaler{EmitDefaults: true}, &pb.SimpleSlice3{}, `{"slices":[]}`}, {"empty map emitted", Marshaler{EmitDefaults: true}, &pb.SimpleMap3{}, `{"stringy":{}}`}, {"nested struct null", Marshaler{EmitDefaults: true}, &pb.SimpleNull3{}, `{"simple":null}`}, {"map", marshaler, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, `{"nummy":{"1":2,"3":4}}`}, {"map", marshalerAllOptions, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, nummyPrettyJSON}, {"map", marshaler, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}, `{"strry":{"\"one\"":"two","three":"four"}}`}, {"map", marshaler, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, `{"objjy":{"1":{"dub":1}}}`}, {"map", marshalerAllOptions, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, objjyPrettyJSON}, {"map", marshaler, &pb.Mappy{Buggy: map[int64]string{1234: "yup"}}, `{"buggy":{"1234":"yup"}}`}, {"map", marshaler, &pb.Mappy{Booly: map[bool]bool{false: true}}, `{"booly":{"false":true}}`}, // TODO: This is broken. //{"map", marshaler, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":"ROMAN"}`}, {"map", Marshaler{EnumsAsInts: true}, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":2}}`}, {"map", marshaler, &pb.Mappy{S32Booly: map[int32]bool{1: true, 3: false, 10: true, 12: false}}, `{"s32booly":{"1":true,"3":false,"10":true,"12":false}}`}, {"map", marshaler, &pb.Mappy{S64Booly: map[int64]bool{1: true, 3: false, 10: true, 12: false}}, `{"s64booly":{"1":true,"3":false,"10":true,"12":false}}`}, {"map", marshaler, &pb.Mappy{U32Booly: map[uint32]bool{1: true, 3: false, 10: true, 12: false}}, `{"u32booly":{"1":true,"3":false,"10":true,"12":false}}`}, {"map", marshaler, &pb.Mappy{U64Booly: map[uint64]bool{1: true, 3: false, 10: true, 12: false}}, `{"u64booly":{"1":true,"3":false,"10":true,"12":false}}`}, {"proto2 map", marshaler, &pb.Maps{MInt64Str: map[int64]string{213: "cat"}}, `{"mInt64Str":{"213":"cat"}}`}, {"proto2 map", marshaler, &pb.Maps{MBoolSimple: map[bool]*pb.Simple{true: {OInt32: proto.Int32(1)}}}, `{"mBoolSimple":{"true":{"oInt32":1}}}`}, {"oneof, not set", marshaler, &pb.MsgWithOneof{}, `{}`}, {"oneof, set", marshaler, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Title{"Grand Poobah"}}, `{"title":"Grand Poobah"}`}, {"force orig_name", Marshaler{OrigName: true}, &pb.Simple{OInt32: proto.Int32(4)}, `{"o_int32":4}`}, {"proto2 extension", marshaler, realNumber, realNumberJSON}, {"Any with message", marshaler, anySimple, anySimpleJSON}, {"Any with message and indent", marshalerAllOptions, anySimple, anySimplePrettyJSON}, {"Any with WKT", marshaler, anyWellKnown, anyWellKnownJSON}, {"Any with WKT and indent", marshalerAllOptions, anyWellKnown, anyWellKnownPrettyJSON}, {"Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}, `{"dur":"3.000s"}`}, {"Struct", marshaler, &pb.KnownTypes{St: &stpb.Struct{ Fields: map[string]*stpb.Value{ "one": {Kind: &stpb.Value_StringValue{"loneliest number"}}, "two": {Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}, }, }}, `{"st":{"one":"loneliest number","two":null}}`}, {"empty ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{}}, `{"lv":[]}`}, {"basic ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{ {Kind: &stpb.Value_StringValue{"x"}}, {Kind: &stpb.Value_NullValue{}}, {Kind: &stpb.Value_NumberValue{3}}, {Kind: &stpb.Value_BoolValue{true}}, }}}, `{"lv":["x",null,3,true]}`}, {"Timestamp", marshaler, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}, `{"ts":"2014-05-13T16:53:20.021Z"}`}, {"number Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}, `{"val":1}`}, {"null Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}, `{"val":null}`}, {"string number value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}, `{"val":"9223372036854775807"}`}, {"list of lists Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{ Kind: &stpb.Value_ListValue{&stpb.ListValue{ Values: []*stpb.Value{ {Kind: &stpb.Value_StringValue{"x"}}, {Kind: &stpb.Value_ListValue{&stpb.ListValue{ Values: []*stpb.Value{ {Kind: &stpb.Value_ListValue{&stpb.ListValue{ Values: []*stpb.Value{{Kind: &stpb.Value_StringValue{"y"}}}, }}}, {Kind: &stpb.Value_StringValue{"z"}}, }, }}}, }, }}, }}, `{"val":["x",[["y"],"z"]]}`}, {"DoubleValue", marshaler, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}, `{"dbl":1.2}`}, {"FloatValue", marshaler, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}, `{"flt":1.2}`}, {"Int64Value", marshaler, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}, `{"i64":"-3"}`}, {"UInt64Value", marshaler, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}, `{"u64":"3"}`}, {"Int32Value", marshaler, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}, `{"i32":-4}`}, {"UInt32Value", marshaler, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}, `{"u32":4}`}, {"BoolValue", marshaler, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}, `{"bool":true}`}, {"StringValue", marshaler, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}, `{"str":"plush"}`}, {"BytesValue", marshaler, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}, `{"bytes":"d293"}`}, } func TestMarshaling(t *testing.T) { for _, tt := range marshalingTests { json, err := tt.marshaler.MarshalToString(tt.pb) if err != nil { t.Errorf("%s: marshaling error: %v", tt.desc, err) } else if tt.json != json { t.Errorf("%s: got [%v] want [%v]", tt.desc, json, tt.json) } } } func TestMarshalJSONPBMarshaler(t *testing.T) { rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }` msg := dynamicMessage{rawJson: rawJson} str, err := new(Marshaler).MarshalToString(&msg) if err != nil { t.Errorf("an unexpected error occurred when marshalling JSONPBMarshaler: %v", err) } if str != rawJson { t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, rawJson) } } func TestMarshalAnyJSONPBMarshaler(t *testing.T) { msg := dynamicMessage{rawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`} a, err := ptypes.MarshalAny(&msg) if err != nil { t.Errorf("an unexpected error occurred when marshalling to Any: %v", err) } str, err := new(Marshaler).MarshalToString(a) if err != nil { t.Errorf("an unexpected error occurred when marshalling Any to JSON: %v", err) } // after custom marshaling, it's round-tripped through JSON decoding/encoding already, // so the keys are sorted, whitespace is compacted, and "@type" key has been added expected := `{"@type":"type.googleapis.com/` + dynamicMessageName + `","baz":[0,1,2,3],"foo":"bar"}` if str != expected { t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected) } } var unmarshalingTests = []struct { desc string unmarshaler Unmarshaler json string pb proto.Message }{ {"simple flat object", Unmarshaler{}, simpleObjectJSON, simpleObject}, {"simple pretty object", Unmarshaler{}, simpleObjectPrettyJSON, simpleObject}, {"repeated fields flat object", Unmarshaler{}, repeatsObjectJSON, repeatsObject}, {"repeated fields pretty object", Unmarshaler{}, repeatsObjectPrettyJSON, repeatsObject}, {"nested message/enum flat object", Unmarshaler{}, complexObjectJSON, complexObject}, {"nested message/enum pretty object", Unmarshaler{}, complexObjectPrettyJSON, complexObject}, {"enum-string object", Unmarshaler{}, `{"color":"BLUE"}`, &pb.Widget{Color: pb.Widget_BLUE.Enum()}}, {"enum-value object", Unmarshaler{}, "{\n \"color\": 2\n}", &pb.Widget{Color: pb.Widget_BLUE.Enum()}}, {"unknown field with allowed option", Unmarshaler{AllowUnknownFields: true}, `{"unknown": "foo"}`, new(pb.Simple)}, {"proto3 enum string", Unmarshaler{}, `{"hilarity":"PUNS"}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, {"proto3 enum value", Unmarshaler{}, `{"hilarity":1}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, {"unknown enum value object", Unmarshaler{}, "{\n \"color\": 1000,\n \"r_color\": [\n \"RED\"\n ]\n}", &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}}, {"repeated proto3 enum", Unmarshaler{}, `{"rFunny":["PUNS","SLAPSTICK"]}`, &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ proto3pb.Message_PUNS, proto3pb.Message_SLAPSTICK, }}}, {"repeated proto3 enum as int", Unmarshaler{}, `{"rFunny":[1,2]}`, &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ proto3pb.Message_PUNS, proto3pb.Message_SLAPSTICK, }}}, {"repeated proto3 enum as mix of strings and ints", Unmarshaler{}, `{"rFunny":["PUNS",2]}`, &proto3pb.Message{RFunny: []proto3pb.Message_Humour{ proto3pb.Message_PUNS, proto3pb.Message_SLAPSTICK, }}}, {"unquoted int64 object", Unmarshaler{}, `{"oInt64":-314}`, &pb.Simple{OInt64: proto.Int64(-314)}}, {"unquoted uint64 object", Unmarshaler{}, `{"oUint64":123}`, &pb.Simple{OUint64: proto.Uint64(123)}}, {"NaN", Unmarshaler{}, `{"oDouble":"NaN"}`, &pb.Simple{ODouble: proto.Float64(math.NaN())}}, {"Inf", Unmarshaler{}, `{"oFloat":"Infinity"}`, &pb.Simple{OFloat: proto.Float32(float32(math.Inf(1)))}}, {"-Inf", Unmarshaler{}, `{"oDouble":"-Infinity"}`, &pb.Simple{ODouble: proto.Float64(math.Inf(-1))}}, {"map", Unmarshaler{}, `{"nummy":{"1":2,"3":4}}`, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}}, {"map", Unmarshaler{}, `{"strry":{"\"one\"":"two","three":"four"}}`, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}}, {"map", Unmarshaler{}, `{"objjy":{"1":{"dub":1}}}`, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}}, {"proto2 extension", Unmarshaler{}, realNumberJSON, realNumber}, {"Any with message", Unmarshaler{}, anySimpleJSON, anySimple}, {"Any with message and indent", Unmarshaler{}, anySimplePrettyJSON, anySimple}, {"Any with WKT", Unmarshaler{}, anyWellKnownJSON, anyWellKnown}, {"Any with WKT and indent", Unmarshaler{}, anyWellKnownPrettyJSON, anyWellKnown}, // TODO: This is broken. //{"map", Unmarshaler{}, `{"enumy":{"XIV":"ROMAN"}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}}, {"map", Unmarshaler{}, `{"enumy":{"XIV":2}}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}}, {"oneof", Unmarshaler{}, `{"salary":31000}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Salary{31000}}}, {"oneof spec name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}}, {"oneof orig_name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}}, {"oneof spec name2", Unmarshaler{}, `{"homeAddress":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}}, {"oneof orig_name2", Unmarshaler{}, `{"home_address":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}}, {"orig_name input", Unmarshaler{}, `{"o_bool":true}`, &pb.Simple{OBool: proto.Bool(true)}}, {"camelName input", Unmarshaler{}, `{"oBool":true}`, &pb.Simple{OBool: proto.Bool(true)}}, {"Duration", Unmarshaler{}, `{"dur":"3.000s"}`, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}}, {"null Duration", Unmarshaler{}, `{"dur":null}`, &pb.KnownTypes{Dur: nil}}, {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20.021Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}}, {"PreEpochTimestamp", Unmarshaler{}, `{"ts":"1969-12-31T23:59:58.999999995Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -2, Nanos: 999999995}}}, {"ZeroTimeTimestamp", Unmarshaler{}, `{"ts":"0001-01-01T00:00:00Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -62135596800, Nanos: 0}}}, {"null Timestamp", Unmarshaler{}, `{"ts":null}`, &pb.KnownTypes{Ts: nil}}, {"null Struct", Unmarshaler{}, `{"st": null}`, &pb.KnownTypes{St: nil}}, {"empty Struct", Unmarshaler{}, `{"st": {}}`, &pb.KnownTypes{St: &stpb.Struct{}}}, {"basic Struct", Unmarshaler{}, `{"st": {"a": "x", "b": null, "c": 3, "d": true}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{ "a": {Kind: &stpb.Value_StringValue{"x"}}, "b": {Kind: &stpb.Value_NullValue{}}, "c": {Kind: &stpb.Value_NumberValue{3}}, "d": {Kind: &stpb.Value_BoolValue{true}}, }}}}, {"nested Struct", Unmarshaler{}, `{"st": {"a": {"b": 1, "c": [{"d": true}, "f"]}}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{ "a": {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{ "b": {Kind: &stpb.Value_NumberValue{1}}, "c": {Kind: &stpb.Value_ListValue{&stpb.ListValue{Values: []*stpb.Value{ {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{"d": {Kind: &stpb.Value_BoolValue{true}}}}}}, {Kind: &stpb.Value_StringValue{"f"}}, }}}}, }}}}, }}}}, {"null ListValue", Unmarshaler{}, `{"lv": null}`, &pb.KnownTypes{Lv: nil}}, {"empty ListValue", Unmarshaler{}, `{"lv": []}`, &pb.KnownTypes{Lv: &stpb.ListValue{}}}, {"basic ListValue", Unmarshaler{}, `{"lv": ["x", null, 3, true]}`, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{ {Kind: &stpb.Value_StringValue{"x"}}, {Kind: &stpb.Value_NullValue{}}, {Kind: &stpb.Value_NumberValue{3}}, {Kind: &stpb.Value_BoolValue{true}}, }}}}, {"number Value", Unmarshaler{}, `{"val":1}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}}, {"null Value", Unmarshaler{}, `{"val":null}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}}, {"bool Value", Unmarshaler{}, `{"val":true}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_BoolValue{true}}}}, {"string Value", Unmarshaler{}, `{"val":"x"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"x"}}}}, {"string number value", Unmarshaler{}, `{"val":"9223372036854775807"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}}, {"list of lists Value", Unmarshaler{}, `{"val":["x", [["y"], "z"]]}`, &pb.KnownTypes{Val: &stpb.Value{ Kind: &stpb.Value_ListValue{&stpb.ListValue{ Values: []*stpb.Value{ {Kind: &stpb.Value_StringValue{"x"}}, {Kind: &stpb.Value_ListValue{&stpb.ListValue{ Values: []*stpb.Value{ {Kind: &stpb.Value_ListValue{&stpb.ListValue{ Values: []*stpb.Value{{Kind: &stpb.Value_StringValue{"y"}}}, }}}, {Kind: &stpb.Value_StringValue{"z"}}, }, }}}, }, }}}}}, {"DoubleValue", Unmarshaler{}, `{"dbl":1.2}`, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}}, {"FloatValue", Unmarshaler{}, `{"flt":1.2}`, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}}, {"Int64Value", Unmarshaler{}, `{"i64":"-3"}`, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}}, {"UInt64Value", Unmarshaler{}, `{"u64":"3"}`, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}}, {"Int32Value", Unmarshaler{}, `{"i32":-4}`, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}}, {"UInt32Value", Unmarshaler{}, `{"u32":4}`, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}}, {"BoolValue", Unmarshaler{}, `{"bool":true}`, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}}, {"StringValue", Unmarshaler{}, `{"str":"plush"}`, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}}, {"BytesValue", Unmarshaler{}, `{"bytes":"d293"}`, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}}, // Ensure that `null` as a value ends up with a nil pointer instead of a [type]Value struct. {"null DoubleValue", Unmarshaler{}, `{"dbl":null}`, &pb.KnownTypes{Dbl: nil}}, {"null FloatValue", Unmarshaler{}, `{"flt":null}`, &pb.KnownTypes{Flt: nil}}, {"null Int64Value", Unmarshaler{}, `{"i64":null}`, &pb.KnownTypes{I64: nil}}, {"null UInt64Value", Unmarshaler{}, `{"u64":null}`, &pb.KnownTypes{U64: nil}}, {"null Int32Value", Unmarshaler{}, `{"i32":null}`, &pb.KnownTypes{I32: nil}}, {"null UInt32Value", Unmarshaler{}, `{"u32":null}`, &pb.KnownTypes{U32: nil}}, {"null BoolValue", Unmarshaler{}, `{"bool":null}`, &pb.KnownTypes{Bool: nil}}, {"null StringValue", Unmarshaler{}, `{"str":null}`, &pb.KnownTypes{Str: nil}}, {"null BytesValue", Unmarshaler{}, `{"bytes":null}`, &pb.KnownTypes{Bytes: nil}}, } func TestUnmarshaling(t *testing.T) { for _, tt := range unmarshalingTests { // Make a new instance of the type of our expected object. p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message) err := tt.unmarshaler.Unmarshal(strings.NewReader(tt.json), p) if err != nil { t.Errorf("%s: %v", tt.desc, err) continue } // For easier diffs, compare text strings of the protos. exp := proto.MarshalTextString(tt.pb) act := proto.MarshalTextString(p) if string(exp) != string(act) { t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp) } } } func TestUnmarshalNullArray(t *testing.T) { var repeats pb.Repeats if err := UnmarshalString(`{"rBool":null}`, &repeats); err != nil { t.Fatal(err) } if !reflect.DeepEqual(repeats, pb.Repeats{}) { t.Errorf("got non-nil fields in [%#v]", repeats) } } func TestUnmarshalNullObject(t *testing.T) { var maps pb.Maps if err := UnmarshalString(`{"mInt64Str":null}`, &maps); err != nil { t.Fatal(err) } if !reflect.DeepEqual(maps, pb.Maps{}) { t.Errorf("got non-nil fields in [%#v]", maps) } } func TestUnmarshalNext(t *testing.T) { // We only need to check against a few, not all of them. tests := unmarshalingTests[:5] // Create a buffer with many concatenated JSON objects. var b bytes.Buffer for _, tt := range tests { b.WriteString(tt.json) } dec := json.NewDecoder(&b) for _, tt := range tests { // Make a new instance of the type of our expected object. p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message) err := tt.unmarshaler.UnmarshalNext(dec, p) if err != nil { t.Errorf("%s: %v", tt.desc, err) continue } // For easier diffs, compare text strings of the protos. exp := proto.MarshalTextString(tt.pb) act := proto.MarshalTextString(p) if string(exp) != string(act) { t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp) } } p := &pb.Simple{} err := new(Unmarshaler).UnmarshalNext(dec, p) if err != io.EOF { t.Errorf("eof: got %v, expected io.EOF", err) } } var unmarshalingShouldError = []struct { desc string in string pb proto.Message }{ {"a value", "666", new(pb.Simple)}, {"gibberish", "{adskja123;l23=-=", new(pb.Simple)}, {"unknown field", `{"unknown": "foo"}`, new(pb.Simple)}, {"unknown enum name", `{"hilarity":"DAVE"}`, new(proto3pb.Message)}, } func TestUnmarshalingBadInput(t *testing.T) { for _, tt := range unmarshalingShouldError { err := UnmarshalString(tt.in, tt.pb) if err == nil { t.Errorf("an error was expected when parsing %q instead of an object", tt.desc) } } } type funcResolver func(turl string) (proto.Message, error) func (fn funcResolver) Resolve(turl string) (proto.Message, error) { return fn(turl) } func TestAnyWithCustomResolver(t *testing.T) { var resolvedTypeUrls []string resolver := funcResolver(func(turl string) (proto.Message, error) { resolvedTypeUrls = append(resolvedTypeUrls, turl) return new(pb.Simple), nil }) msg := &pb.Simple{ OBytes: []byte{1, 2, 3, 4}, OBool: proto.Bool(true), OString: proto.String("foobar"), OInt64: proto.Int64(1020304), } msgBytes, err := proto.Marshal(msg) if err != nil { t.Errorf("an unexpected error occurred when marshaling message: %v", err) } // make an Any with a type URL that won't resolve w/out custom resolver any := &anypb.Any{ TypeUrl: "https://foobar.com/some.random.MessageKind", Value: msgBytes, } m := Marshaler{AnyResolver: resolver} js, err := m.MarshalToString(any) if err != nil { t.Errorf("an unexpected error occurred when marshaling any to JSON: %v", err) } if len(resolvedTypeUrls) != 1 { t.Errorf("custom resolver was not invoked during marshaling") } else if resolvedTypeUrls[0] != "https://foobar.com/some.random.MessageKind" { t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[0], "https://foobar.com/some.random.MessageKind") } wanted := `{"@type":"https://foobar.com/some.random.MessageKind","oBool":true,"oInt64":"1020304","oString":"foobar","oBytes":"AQIDBA=="}` if js != wanted { t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", js, wanted) } u := Unmarshaler{AnyResolver: resolver} roundTrip := &anypb.Any{} err = u.Unmarshal(bytes.NewReader([]byte(js)), roundTrip) if err != nil { t.Errorf("an unexpected error occurred when unmarshaling any from JSON: %v", err) } if len(resolvedTypeUrls) != 2 { t.Errorf("custom resolver was not invoked during marshaling") } else if resolvedTypeUrls[1] != "https://foobar.com/some.random.MessageKind" { t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[1], "https://foobar.com/some.random.MessageKind") } if !proto.Equal(any, roundTrip) { t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", roundTrip, any) } } func TestUnmarshalJSONPBUnmarshaler(t *testing.T) { rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }` var msg dynamicMessage if err := Unmarshal(strings.NewReader(rawJson), &msg); err != nil { t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err) } if msg.rawJson != rawJson { t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", msg.rawJson, rawJson) } } func TestUnmarshalNullWithJSONPBUnmarshaler(t *testing.T) { rawJson := `{"stringField":null}` var ptrFieldMsg ptrFieldMessage if err := Unmarshal(strings.NewReader(rawJson), &ptrFieldMsg); err != nil { t.Errorf("unmarshal error: %v", err) } want := ptrFieldMessage{StringField: &stringField{IsSet: true, StringValue: "null"}} if !proto.Equal(&ptrFieldMsg, &want) { t.Errorf("unmarshal result StringField: got %v, want %v", ptrFieldMsg, want) } } func TestUnmarshalAnyJSONPBUnmarshaler(t *testing.T) { rawJson := `{ "@type": "blah.com/` + dynamicMessageName + `", "foo": "bar", "baz": [0, 1, 2, 3] }` var got anypb.Any if err := Unmarshal(strings.NewReader(rawJson), &got); err != nil { t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err) } dm := &dynamicMessage{rawJson: `{"baz":[0,1,2,3],"foo":"bar"}`} var want anypb.Any if b, err := proto.Marshal(dm); err != nil { t.Errorf("an unexpected error occurred when marshaling message: %v", err) } else { want.TypeUrl = "blah.com/" + dynamicMessageName want.Value = b } if !proto.Equal(&got, &want) { t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", got, want) } } const ( dynamicMessageName = "google.protobuf.jsonpb.testing.dynamicMessage" ) func init() { // we register the custom type below so that we can use it in Any types proto.RegisterType((*dynamicMessage)(nil), dynamicMessageName) } type ptrFieldMessage struct { StringField *stringField `protobuf:"bytes,1,opt,name=stringField"` } func (m *ptrFieldMessage) Reset() { } func (m *ptrFieldMessage) String() string { return m.StringField.StringValue } func (m *ptrFieldMessage) ProtoMessage() { } type stringField struct { IsSet bool `protobuf:"varint,1,opt,name=isSet"` StringValue string `protobuf:"bytes,2,opt,name=stringValue"` } func (s *stringField) Reset() { } func (s *stringField) String() string { return s.StringValue } func (s *stringField) ProtoMessage() { } func (s *stringField) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error { s.IsSet = true s.StringValue = string(js) return nil } // dynamicMessage implements protobuf.Message but is not a normal generated message type. // It provides implementations of JSONPBMarshaler and JSONPBUnmarshaler for JSON support. type dynamicMessage struct { rawJson string `protobuf:"bytes,1,opt,name=rawJson"` } func (m *dynamicMessage) Reset() { m.rawJson = "{}" } func (m *dynamicMessage) String() string { return m.rawJson } func (m *dynamicMessage) ProtoMessage() { } func (m *dynamicMessage) MarshalJSONPB(jm *Marshaler) ([]byte, error) { return []byte(m.rawJson), nil } func (m *dynamicMessage) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error { m.rawJson = string(js) return nil } ================================================ FILE: src/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/Makefile ================================================ # Go support for Protocol Buffers - Google's data interchange format # # Copyright 2015 The Go Authors. All rights reserved. # https://github.com/golang/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. regenerate: protoc --go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any,Mgoogle/protobuf/duration.proto=github.com/golang/protobuf/ptypes/duration,Mgoogle/protobuf/struct.proto=github.com/golang/protobuf/ptypes/struct,Mgoogle/protobuf/timestamp.proto=github.com/golang/protobuf/ptypes/timestamp,Mgoogle/protobuf/wrappers.proto=github.com/golang/protobuf/ptypes/wrappers:. *.proto ================================================ FILE: src/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: more_test_objects.proto /* Package jsonpb is a generated protocol buffer package. It is generated from these files: more_test_objects.proto test_objects.proto It has these top-level messages: Simple3 SimpleSlice3 SimpleMap3 SimpleNull3 Mappy Simple NonFinites Repeats Widget Maps MsgWithOneof Real Complex KnownTypes */ package jsonpb import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type Numeral int32 const ( Numeral_UNKNOWN Numeral = 0 Numeral_ARABIC Numeral = 1 Numeral_ROMAN Numeral = 2 ) var Numeral_name = map[int32]string{ 0: "UNKNOWN", 1: "ARABIC", 2: "ROMAN", } var Numeral_value = map[string]int32{ "UNKNOWN": 0, "ARABIC": 1, "ROMAN": 2, } func (x Numeral) String() string { return proto.EnumName(Numeral_name, int32(x)) } func (Numeral) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } type Simple3 struct { Dub float64 `protobuf:"fixed64,1,opt,name=dub" json:"dub,omitempty"` } func (m *Simple3) Reset() { *m = Simple3{} } func (m *Simple3) String() string { return proto.CompactTextString(m) } func (*Simple3) ProtoMessage() {} func (*Simple3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *Simple3) GetDub() float64 { if m != nil { return m.Dub } return 0 } type SimpleSlice3 struct { Slices []string `protobuf:"bytes,1,rep,name=slices" json:"slices,omitempty"` } func (m *SimpleSlice3) Reset() { *m = SimpleSlice3{} } func (m *SimpleSlice3) String() string { return proto.CompactTextString(m) } func (*SimpleSlice3) ProtoMessage() {} func (*SimpleSlice3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *SimpleSlice3) GetSlices() []string { if m != nil { return m.Slices } return nil } type SimpleMap3 struct { Stringy map[string]string `protobuf:"bytes,1,rep,name=stringy" json:"stringy,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` } func (m *SimpleMap3) Reset() { *m = SimpleMap3{} } func (m *SimpleMap3) String() string { return proto.CompactTextString(m) } func (*SimpleMap3) ProtoMessage() {} func (*SimpleMap3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *SimpleMap3) GetStringy() map[string]string { if m != nil { return m.Stringy } return nil } type SimpleNull3 struct { Simple *Simple3 `protobuf:"bytes,1,opt,name=simple" json:"simple,omitempty"` } func (m *SimpleNull3) Reset() { *m = SimpleNull3{} } func (m *SimpleNull3) String() string { return proto.CompactTextString(m) } func (*SimpleNull3) ProtoMessage() {} func (*SimpleNull3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *SimpleNull3) GetSimple() *Simple3 { if m != nil { return m.Simple } return nil } type Mappy struct { Nummy map[int64]int32 `protobuf:"bytes,1,rep,name=nummy" json:"nummy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` Strry map[string]string `protobuf:"bytes,2,rep,name=strry" json:"strry,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Objjy map[int32]*Simple3 `protobuf:"bytes,3,rep,name=objjy" json:"objjy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Buggy map[int64]string `protobuf:"bytes,4,rep,name=buggy" json:"buggy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Booly map[bool]bool `protobuf:"bytes,5,rep,name=booly" json:"booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` Enumy map[string]Numeral `protobuf:"bytes,6,rep,name=enumy" json:"enumy,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=jsonpb.Numeral"` S32Booly map[int32]bool `protobuf:"bytes,7,rep,name=s32booly" json:"s32booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` S64Booly map[int64]bool `protobuf:"bytes,8,rep,name=s64booly" json:"s64booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` U32Booly map[uint32]bool `protobuf:"bytes,9,rep,name=u32booly" json:"u32booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` U64Booly map[uint64]bool `protobuf:"bytes,10,rep,name=u64booly" json:"u64booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` } func (m *Mappy) Reset() { *m = Mappy{} } func (m *Mappy) String() string { return proto.CompactTextString(m) } func (*Mappy) ProtoMessage() {} func (*Mappy) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (m *Mappy) GetNummy() map[int64]int32 { if m != nil { return m.Nummy } return nil } func (m *Mappy) GetStrry() map[string]string { if m != nil { return m.Strry } return nil } func (m *Mappy) GetObjjy() map[int32]*Simple3 { if m != nil { return m.Objjy } return nil } func (m *Mappy) GetBuggy() map[int64]string { if m != nil { return m.Buggy } return nil } func (m *Mappy) GetBooly() map[bool]bool { if m != nil { return m.Booly } return nil } func (m *Mappy) GetEnumy() map[string]Numeral { if m != nil { return m.Enumy } return nil } func (m *Mappy) GetS32Booly() map[int32]bool { if m != nil { return m.S32Booly } return nil } func (m *Mappy) GetS64Booly() map[int64]bool { if m != nil { return m.S64Booly } return nil } func (m *Mappy) GetU32Booly() map[uint32]bool { if m != nil { return m.U32Booly } return nil } func (m *Mappy) GetU64Booly() map[uint64]bool { if m != nil { return m.U64Booly } return nil } func init() { proto.RegisterType((*Simple3)(nil), "jsonpb.Simple3") proto.RegisterType((*SimpleSlice3)(nil), "jsonpb.SimpleSlice3") proto.RegisterType((*SimpleMap3)(nil), "jsonpb.SimpleMap3") proto.RegisterType((*SimpleNull3)(nil), "jsonpb.SimpleNull3") proto.RegisterType((*Mappy)(nil), "jsonpb.Mappy") proto.RegisterEnum("jsonpb.Numeral", Numeral_name, Numeral_value) } func init() { proto.RegisterFile("more_test_objects.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 526 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xdd, 0x6b, 0xdb, 0x3c, 0x14, 0x87, 0x5f, 0x27, 0xf5, 0xd7, 0x49, 0xfb, 0x2e, 0x88, 0xb1, 0x99, 0xf4, 0x62, 0xc5, 0xb0, 0xad, 0x0c, 0xe6, 0x8b, 0x78, 0x74, 0x5d, 0x77, 0x95, 0x8e, 0x5e, 0x94, 0x11, 0x07, 0x1c, 0xc2, 0x2e, 0x4b, 0xdc, 0x99, 0x90, 0xcc, 0x5f, 0xd8, 0xd6, 0xc0, 0xd7, 0xfb, 0xbb, 0x07, 0xe3, 0x48, 0x72, 0x2d, 0x07, 0x85, 0x6c, 0x77, 0x52, 0x7e, 0xcf, 0xe3, 0x73, 0x24, 0x1d, 0x02, 0x2f, 0xd3, 0xbc, 0x8c, 0x1f, 0xea, 0xb8, 0xaa, 0x1f, 0xf2, 0x68, 0x17, 0x3f, 0xd6, 0x95, 0x57, 0x94, 0x79, 0x9d, 0x13, 0x63, 0x57, 0xe5, 0x59, 0x11, 0xb9, 0xe7, 0x60, 0x2e, 0xb7, 0x69, 0x91, 0xc4, 0x3e, 0x19, 0xc3, 0xf0, 0x3b, 0x8d, 0x1c, 0xed, 0x42, 0xbb, 0xd4, 0x42, 0x5c, 0xba, 0x6f, 0xe0, 0x94, 0x87, 0xcb, 0x64, 0xfb, 0x18, 0xfb, 0xe4, 0x05, 0x18, 0x15, 0xae, 0x2a, 0x47, 0xbb, 0x18, 0x5e, 0xda, 0xa1, 0xd8, 0xb9, 0xbf, 0x34, 0x00, 0x0e, 0xce, 0xd7, 0x85, 0x4f, 0x3e, 0x81, 0x59, 0xd5, 0xe5, 0x36, 0xdb, 0x34, 0x8c, 0x1b, 0x4d, 0x5f, 0x79, 0xbc, 0x9a, 0xd7, 0x41, 0xde, 0x92, 0x13, 0x77, 0x59, 0x5d, 0x36, 0x61, 0xcb, 0x4f, 0x6e, 0xe0, 0x54, 0x0e, 0xb0, 0xa7, 0x1f, 0x71, 0xc3, 0x7a, 0xb2, 0x43, 0x5c, 0x92, 0xe7, 0xa0, 0xff, 0x5c, 0x27, 0x34, 0x76, 0x06, 0xec, 0x37, 0xbe, 0xb9, 0x19, 0x5c, 0x6b, 0xee, 0x15, 0x8c, 0xf8, 0xf7, 0x03, 0x9a, 0x24, 0x3e, 0x79, 0x0b, 0x46, 0xc5, 0xb6, 0xcc, 0x1e, 0x4d, 0x9f, 0xf5, 0x9b, 0xf0, 0x43, 0x11, 0xbb, 0xbf, 0x2d, 0xd0, 0xe7, 0xeb, 0xa2, 0x68, 0x88, 0x07, 0x7a, 0x46, 0xd3, 0xb4, 0x6d, 0xdb, 0x69, 0x0d, 0x96, 0x7a, 0x01, 0x46, 0xbc, 0x5f, 0x8e, 0x21, 0x5f, 0xd5, 0x65, 0xd9, 0x38, 0x03, 0x15, 0xbf, 0xc4, 0x48, 0xf0, 0x0c, 0x43, 0x3e, 0x8f, 0x76, 0xbb, 0xc6, 0x19, 0xaa, 0xf8, 0x05, 0x46, 0x82, 0x67, 0x18, 0xf2, 0x11, 0xdd, 0x6c, 0x1a, 0xe7, 0x44, 0xc5, 0xdf, 0x62, 0x24, 0x78, 0x86, 0x31, 0x3e, 0xcf, 0x93, 0xc6, 0xd1, 0x95, 0x3c, 0x46, 0x2d, 0x8f, 0x6b, 0xe4, 0xe3, 0x8c, 0xa6, 0x8d, 0x63, 0xa8, 0xf8, 0x3b, 0x8c, 0x04, 0xcf, 0x30, 0xf2, 0x11, 0xac, 0xca, 0x9f, 0xf2, 0x12, 0x26, 0x53, 0xce, 0xf7, 0x8e, 0x2c, 0x52, 0x6e, 0x3d, 0xc1, 0x4c, 0xbc, 0xfa, 0xc0, 0x45, 0x4b, 0x29, 0x8a, 0xb4, 0x15, 0xc5, 0x16, 0x45, 0xda, 0x56, 0xb4, 0x55, 0xe2, 0xaa, 0x5f, 0x91, 0x4a, 0x15, 0x69, 0x5b, 0x11, 0x94, 0x62, 0xbf, 0x62, 0x0b, 0x4f, 0xae, 0x01, 0xba, 0x87, 0x96, 0xe7, 0x6f, 0xa8, 0x98, 0x3f, 0x5d, 0x9a, 0x3f, 0x34, 0xbb, 0x27, 0xff, 0x97, 0xc9, 0x9d, 0xdc, 0x03, 0x74, 0x8f, 0x2f, 0x9b, 0x3a, 0x37, 0x5f, 0xcb, 0xa6, 0x62, 0x92, 0xfb, 0x4d, 0x74, 0x73, 0x71, 0xac, 0x7d, 0x7b, 0xdf, 0x7c, 0xba, 0x10, 0xd9, 0xb4, 0x14, 0xa6, 0xb5, 0xd7, 0x7e, 0x37, 0x2b, 0x8a, 0x83, 0xf7, 0xda, 0xff, 0xbf, 0x6b, 0x3f, 0xa0, 0x69, 0x5c, 0xae, 0x13, 0xf9, 0x53, 0x9f, 0xe1, 0xac, 0x37, 0x43, 0x8a, 0xcb, 0x38, 0xdc, 0x07, 0xca, 0xf2, 0xab, 0x1e, 0x3b, 0xfe, 0xbe, 0xbc, 0x3a, 0x54, 0xf9, 0xec, 0x6f, 0xe4, 0x43, 0x95, 0x4f, 0x8e, 0xc8, 0xef, 0xde, 0x83, 0x29, 0x6e, 0x82, 0x8c, 0xc0, 0x5c, 0x05, 0x5f, 0x83, 0xc5, 0xb7, 0x60, 0xfc, 0x1f, 0x01, 0x30, 0x66, 0xe1, 0xec, 0xf6, 0xfe, 0xcb, 0x58, 0x23, 0x36, 0xe8, 0xe1, 0x62, 0x3e, 0x0b, 0xc6, 0x83, 0xc8, 0x60, 0x7f, 0xe0, 0xfe, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x34, 0xaf, 0xdb, 0x05, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto3"; package jsonpb; message Simple3 { double dub = 1; } message SimpleSlice3 { repeated string slices = 1; } message SimpleMap3 { map stringy = 1; } message SimpleNull3 { Simple3 simple = 1; } enum Numeral { UNKNOWN = 0; ARABIC = 1; ROMAN = 2; } message Mappy { map nummy = 1; map strry = 2; map objjy = 3; map buggy = 4; map booly = 5; map enumy = 6; map s32booly = 7; map s64booly = 8; map u32booly = 9; map u64booly = 10; } ================================================ FILE: src/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: test_objects.proto package jsonpb import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import google_protobuf "github.com/golang/protobuf/ptypes/any" import google_protobuf1 "github.com/golang/protobuf/ptypes/duration" import google_protobuf2 "github.com/golang/protobuf/ptypes/struct" import google_protobuf3 "github.com/golang/protobuf/ptypes/timestamp" import google_protobuf4 "github.com/golang/protobuf/ptypes/wrappers" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf type Widget_Color int32 const ( Widget_RED Widget_Color = 0 Widget_GREEN Widget_Color = 1 Widget_BLUE Widget_Color = 2 ) var Widget_Color_name = map[int32]string{ 0: "RED", 1: "GREEN", 2: "BLUE", } var Widget_Color_value = map[string]int32{ "RED": 0, "GREEN": 1, "BLUE": 2, } func (x Widget_Color) Enum() *Widget_Color { p := new(Widget_Color) *p = x return p } func (x Widget_Color) String() string { return proto.EnumName(Widget_Color_name, int32(x)) } func (x *Widget_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Widget_Color_value, data, "Widget_Color") if err != nil { return err } *x = Widget_Color(value) return nil } func (Widget_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor1, []int{3, 0} } // Test message for holding primitive types. type Simple struct { OBool *bool `protobuf:"varint,1,opt,name=o_bool,json=oBool" json:"o_bool,omitempty"` OInt32 *int32 `protobuf:"varint,2,opt,name=o_int32,json=oInt32" json:"o_int32,omitempty"` OInt64 *int64 `protobuf:"varint,3,opt,name=o_int64,json=oInt64" json:"o_int64,omitempty"` OUint32 *uint32 `protobuf:"varint,4,opt,name=o_uint32,json=oUint32" json:"o_uint32,omitempty"` OUint64 *uint64 `protobuf:"varint,5,opt,name=o_uint64,json=oUint64" json:"o_uint64,omitempty"` OSint32 *int32 `protobuf:"zigzag32,6,opt,name=o_sint32,json=oSint32" json:"o_sint32,omitempty"` OSint64 *int64 `protobuf:"zigzag64,7,opt,name=o_sint64,json=oSint64" json:"o_sint64,omitempty"` OFloat *float32 `protobuf:"fixed32,8,opt,name=o_float,json=oFloat" json:"o_float,omitempty"` ODouble *float64 `protobuf:"fixed64,9,opt,name=o_double,json=oDouble" json:"o_double,omitempty"` OString *string `protobuf:"bytes,10,opt,name=o_string,json=oString" json:"o_string,omitempty"` OBytes []byte `protobuf:"bytes,11,opt,name=o_bytes,json=oBytes" json:"o_bytes,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Simple) Reset() { *m = Simple{} } func (m *Simple) String() string { return proto.CompactTextString(m) } func (*Simple) ProtoMessage() {} func (*Simple) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{0} } func (m *Simple) GetOBool() bool { if m != nil && m.OBool != nil { return *m.OBool } return false } func (m *Simple) GetOInt32() int32 { if m != nil && m.OInt32 != nil { return *m.OInt32 } return 0 } func (m *Simple) GetOInt64() int64 { if m != nil && m.OInt64 != nil { return *m.OInt64 } return 0 } func (m *Simple) GetOUint32() uint32 { if m != nil && m.OUint32 != nil { return *m.OUint32 } return 0 } func (m *Simple) GetOUint64() uint64 { if m != nil && m.OUint64 != nil { return *m.OUint64 } return 0 } func (m *Simple) GetOSint32() int32 { if m != nil && m.OSint32 != nil { return *m.OSint32 } return 0 } func (m *Simple) GetOSint64() int64 { if m != nil && m.OSint64 != nil { return *m.OSint64 } return 0 } func (m *Simple) GetOFloat() float32 { if m != nil && m.OFloat != nil { return *m.OFloat } return 0 } func (m *Simple) GetODouble() float64 { if m != nil && m.ODouble != nil { return *m.ODouble } return 0 } func (m *Simple) GetOString() string { if m != nil && m.OString != nil { return *m.OString } return "" } func (m *Simple) GetOBytes() []byte { if m != nil { return m.OBytes } return nil } // Test message for holding special non-finites primitives. type NonFinites struct { FNan *float32 `protobuf:"fixed32,1,opt,name=f_nan,json=fNan" json:"f_nan,omitempty"` FPinf *float32 `protobuf:"fixed32,2,opt,name=f_pinf,json=fPinf" json:"f_pinf,omitempty"` FNinf *float32 `protobuf:"fixed32,3,opt,name=f_ninf,json=fNinf" json:"f_ninf,omitempty"` DNan *float64 `protobuf:"fixed64,4,opt,name=d_nan,json=dNan" json:"d_nan,omitempty"` DPinf *float64 `protobuf:"fixed64,5,opt,name=d_pinf,json=dPinf" json:"d_pinf,omitempty"` DNinf *float64 `protobuf:"fixed64,6,opt,name=d_ninf,json=dNinf" json:"d_ninf,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *NonFinites) Reset() { *m = NonFinites{} } func (m *NonFinites) String() string { return proto.CompactTextString(m) } func (*NonFinites) ProtoMessage() {} func (*NonFinites) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{1} } func (m *NonFinites) GetFNan() float32 { if m != nil && m.FNan != nil { return *m.FNan } return 0 } func (m *NonFinites) GetFPinf() float32 { if m != nil && m.FPinf != nil { return *m.FPinf } return 0 } func (m *NonFinites) GetFNinf() float32 { if m != nil && m.FNinf != nil { return *m.FNinf } return 0 } func (m *NonFinites) GetDNan() float64 { if m != nil && m.DNan != nil { return *m.DNan } return 0 } func (m *NonFinites) GetDPinf() float64 { if m != nil && m.DPinf != nil { return *m.DPinf } return 0 } func (m *NonFinites) GetDNinf() float64 { if m != nil && m.DNinf != nil { return *m.DNinf } return 0 } // Test message for holding repeated primitives. type Repeats struct { RBool []bool `protobuf:"varint,1,rep,name=r_bool,json=rBool" json:"r_bool,omitempty"` RInt32 []int32 `protobuf:"varint,2,rep,name=r_int32,json=rInt32" json:"r_int32,omitempty"` RInt64 []int64 `protobuf:"varint,3,rep,name=r_int64,json=rInt64" json:"r_int64,omitempty"` RUint32 []uint32 `protobuf:"varint,4,rep,name=r_uint32,json=rUint32" json:"r_uint32,omitempty"` RUint64 []uint64 `protobuf:"varint,5,rep,name=r_uint64,json=rUint64" json:"r_uint64,omitempty"` RSint32 []int32 `protobuf:"zigzag32,6,rep,name=r_sint32,json=rSint32" json:"r_sint32,omitempty"` RSint64 []int64 `protobuf:"zigzag64,7,rep,name=r_sint64,json=rSint64" json:"r_sint64,omitempty"` RFloat []float32 `protobuf:"fixed32,8,rep,name=r_float,json=rFloat" json:"r_float,omitempty"` RDouble []float64 `protobuf:"fixed64,9,rep,name=r_double,json=rDouble" json:"r_double,omitempty"` RString []string `protobuf:"bytes,10,rep,name=r_string,json=rString" json:"r_string,omitempty"` RBytes [][]byte `protobuf:"bytes,11,rep,name=r_bytes,json=rBytes" json:"r_bytes,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Repeats) Reset() { *m = Repeats{} } func (m *Repeats) String() string { return proto.CompactTextString(m) } func (*Repeats) ProtoMessage() {} func (*Repeats) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{2} } func (m *Repeats) GetRBool() []bool { if m != nil { return m.RBool } return nil } func (m *Repeats) GetRInt32() []int32 { if m != nil { return m.RInt32 } return nil } func (m *Repeats) GetRInt64() []int64 { if m != nil { return m.RInt64 } return nil } func (m *Repeats) GetRUint32() []uint32 { if m != nil { return m.RUint32 } return nil } func (m *Repeats) GetRUint64() []uint64 { if m != nil { return m.RUint64 } return nil } func (m *Repeats) GetRSint32() []int32 { if m != nil { return m.RSint32 } return nil } func (m *Repeats) GetRSint64() []int64 { if m != nil { return m.RSint64 } return nil } func (m *Repeats) GetRFloat() []float32 { if m != nil { return m.RFloat } return nil } func (m *Repeats) GetRDouble() []float64 { if m != nil { return m.RDouble } return nil } func (m *Repeats) GetRString() []string { if m != nil { return m.RString } return nil } func (m *Repeats) GetRBytes() [][]byte { if m != nil { return m.RBytes } return nil } // Test message for holding enums and nested messages. type Widget struct { Color *Widget_Color `protobuf:"varint,1,opt,name=color,enum=jsonpb.Widget_Color" json:"color,omitempty"` RColor []Widget_Color `protobuf:"varint,2,rep,name=r_color,json=rColor,enum=jsonpb.Widget_Color" json:"r_color,omitempty"` Simple *Simple `protobuf:"bytes,10,opt,name=simple" json:"simple,omitempty"` RSimple []*Simple `protobuf:"bytes,11,rep,name=r_simple,json=rSimple" json:"r_simple,omitempty"` Repeats *Repeats `protobuf:"bytes,20,opt,name=repeats" json:"repeats,omitempty"` RRepeats []*Repeats `protobuf:"bytes,21,rep,name=r_repeats,json=rRepeats" json:"r_repeats,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Widget) Reset() { *m = Widget{} } func (m *Widget) String() string { return proto.CompactTextString(m) } func (*Widget) ProtoMessage() {} func (*Widget) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{3} } func (m *Widget) GetColor() Widget_Color { if m != nil && m.Color != nil { return *m.Color } return Widget_RED } func (m *Widget) GetRColor() []Widget_Color { if m != nil { return m.RColor } return nil } func (m *Widget) GetSimple() *Simple { if m != nil { return m.Simple } return nil } func (m *Widget) GetRSimple() []*Simple { if m != nil { return m.RSimple } return nil } func (m *Widget) GetRepeats() *Repeats { if m != nil { return m.Repeats } return nil } func (m *Widget) GetRRepeats() []*Repeats { if m != nil { return m.RRepeats } return nil } type Maps struct { MInt64Str map[int64]string `protobuf:"bytes,1,rep,name=m_int64_str,json=mInt64Str" json:"m_int64_str,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` MBoolSimple map[bool]*Simple `protobuf:"bytes,2,rep,name=m_bool_simple,json=mBoolSimple" json:"m_bool_simple,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` XXX_unrecognized []byte `json:"-"` } func (m *Maps) Reset() { *m = Maps{} } func (m *Maps) String() string { return proto.CompactTextString(m) } func (*Maps) ProtoMessage() {} func (*Maps) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{4} } func (m *Maps) GetMInt64Str() map[int64]string { if m != nil { return m.MInt64Str } return nil } func (m *Maps) GetMBoolSimple() map[bool]*Simple { if m != nil { return m.MBoolSimple } return nil } type MsgWithOneof struct { // Types that are valid to be assigned to Union: // *MsgWithOneof_Title // *MsgWithOneof_Salary // *MsgWithOneof_Country // *MsgWithOneof_HomeAddress Union isMsgWithOneof_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *MsgWithOneof) Reset() { *m = MsgWithOneof{} } func (m *MsgWithOneof) String() string { return proto.CompactTextString(m) } func (*MsgWithOneof) ProtoMessage() {} func (*MsgWithOneof) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{5} } type isMsgWithOneof_Union interface { isMsgWithOneof_Union() } type MsgWithOneof_Title struct { Title string `protobuf:"bytes,1,opt,name=title,oneof"` } type MsgWithOneof_Salary struct { Salary int64 `protobuf:"varint,2,opt,name=salary,oneof"` } type MsgWithOneof_Country struct { Country string `protobuf:"bytes,3,opt,name=Country,oneof"` } type MsgWithOneof_HomeAddress struct { HomeAddress string `protobuf:"bytes,4,opt,name=home_address,json=homeAddress,oneof"` } func (*MsgWithOneof_Title) isMsgWithOneof_Union() {} func (*MsgWithOneof_Salary) isMsgWithOneof_Union() {} func (*MsgWithOneof_Country) isMsgWithOneof_Union() {} func (*MsgWithOneof_HomeAddress) isMsgWithOneof_Union() {} func (m *MsgWithOneof) GetUnion() isMsgWithOneof_Union { if m != nil { return m.Union } return nil } func (m *MsgWithOneof) GetTitle() string { if x, ok := m.GetUnion().(*MsgWithOneof_Title); ok { return x.Title } return "" } func (m *MsgWithOneof) GetSalary() int64 { if x, ok := m.GetUnion().(*MsgWithOneof_Salary); ok { return x.Salary } return 0 } func (m *MsgWithOneof) GetCountry() string { if x, ok := m.GetUnion().(*MsgWithOneof_Country); ok { return x.Country } return "" } func (m *MsgWithOneof) GetHomeAddress() string { if x, ok := m.GetUnion().(*MsgWithOneof_HomeAddress); ok { return x.HomeAddress } return "" } // XXX_OneofFuncs is for the internal use of the proto package. func (*MsgWithOneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _MsgWithOneof_OneofMarshaler, _MsgWithOneof_OneofUnmarshaler, _MsgWithOneof_OneofSizer, []interface{}{ (*MsgWithOneof_Title)(nil), (*MsgWithOneof_Salary)(nil), (*MsgWithOneof_Country)(nil), (*MsgWithOneof_HomeAddress)(nil), } } func _MsgWithOneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*MsgWithOneof) // union switch x := m.Union.(type) { case *MsgWithOneof_Title: b.EncodeVarint(1<<3 | proto.WireBytes) b.EncodeStringBytes(x.Title) case *MsgWithOneof_Salary: b.EncodeVarint(2<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Salary)) case *MsgWithOneof_Country: b.EncodeVarint(3<<3 | proto.WireBytes) b.EncodeStringBytes(x.Country) case *MsgWithOneof_HomeAddress: b.EncodeVarint(4<<3 | proto.WireBytes) b.EncodeStringBytes(x.HomeAddress) case nil: default: return fmt.Errorf("MsgWithOneof.Union has unexpected type %T", x) } return nil } func _MsgWithOneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*MsgWithOneof) switch tag { case 1: // union.title if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &MsgWithOneof_Title{x} return true, err case 2: // union.salary if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &MsgWithOneof_Salary{int64(x)} return true, err case 3: // union.Country if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &MsgWithOneof_Country{x} return true, err case 4: // union.home_address if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &MsgWithOneof_HomeAddress{x} return true, err default: return false, nil } } func _MsgWithOneof_OneofSizer(msg proto.Message) (n int) { m := msg.(*MsgWithOneof) // union switch x := m.Union.(type) { case *MsgWithOneof_Title: n += proto.SizeVarint(1<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Title))) n += len(x.Title) case *MsgWithOneof_Salary: n += proto.SizeVarint(2<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Salary)) case *MsgWithOneof_Country: n += proto.SizeVarint(3<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Country))) n += len(x.Country) case *MsgWithOneof_HomeAddress: n += proto.SizeVarint(4<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.HomeAddress))) n += len(x.HomeAddress) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type Real struct { Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *Real) Reset() { *m = Real{} } func (m *Real) String() string { return proto.CompactTextString(m) } func (*Real) ProtoMessage() {} func (*Real) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{6} } var extRange_Real = []proto.ExtensionRange{ {100, 536870911}, } func (*Real) ExtensionRangeArray() []proto.ExtensionRange { return extRange_Real } func (m *Real) GetValue() float64 { if m != nil && m.Value != nil { return *m.Value } return 0 } type Complex struct { Imaginary *float64 `protobuf:"fixed64,1,opt,name=imaginary" json:"imaginary,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *Complex) Reset() { *m = Complex{} } func (m *Complex) String() string { return proto.CompactTextString(m) } func (*Complex) ProtoMessage() {} func (*Complex) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{7} } var extRange_Complex = []proto.ExtensionRange{ {100, 536870911}, } func (*Complex) ExtensionRangeArray() []proto.ExtensionRange { return extRange_Complex } func (m *Complex) GetImaginary() float64 { if m != nil && m.Imaginary != nil { return *m.Imaginary } return 0 } var E_Complex_RealExtension = &proto.ExtensionDesc{ ExtendedType: (*Real)(nil), ExtensionType: (*Complex)(nil), Field: 123, Name: "jsonpb.Complex.real_extension", Tag: "bytes,123,opt,name=real_extension,json=realExtension", Filename: "test_objects.proto", } type KnownTypes struct { An *google_protobuf.Any `protobuf:"bytes,14,opt,name=an" json:"an,omitempty"` Dur *google_protobuf1.Duration `protobuf:"bytes,1,opt,name=dur" json:"dur,omitempty"` St *google_protobuf2.Struct `protobuf:"bytes,12,opt,name=st" json:"st,omitempty"` Ts *google_protobuf3.Timestamp `protobuf:"bytes,2,opt,name=ts" json:"ts,omitempty"` Lv *google_protobuf2.ListValue `protobuf:"bytes,15,opt,name=lv" json:"lv,omitempty"` Val *google_protobuf2.Value `protobuf:"bytes,16,opt,name=val" json:"val,omitempty"` Dbl *google_protobuf4.DoubleValue `protobuf:"bytes,3,opt,name=dbl" json:"dbl,omitempty"` Flt *google_protobuf4.FloatValue `protobuf:"bytes,4,opt,name=flt" json:"flt,omitempty"` I64 *google_protobuf4.Int64Value `protobuf:"bytes,5,opt,name=i64" json:"i64,omitempty"` U64 *google_protobuf4.UInt64Value `protobuf:"bytes,6,opt,name=u64" json:"u64,omitempty"` I32 *google_protobuf4.Int32Value `protobuf:"bytes,7,opt,name=i32" json:"i32,omitempty"` U32 *google_protobuf4.UInt32Value `protobuf:"bytes,8,opt,name=u32" json:"u32,omitempty"` Bool *google_protobuf4.BoolValue `protobuf:"bytes,9,opt,name=bool" json:"bool,omitempty"` Str *google_protobuf4.StringValue `protobuf:"bytes,10,opt,name=str" json:"str,omitempty"` Bytes *google_protobuf4.BytesValue `protobuf:"bytes,11,opt,name=bytes" json:"bytes,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *KnownTypes) Reset() { *m = KnownTypes{} } func (m *KnownTypes) String() string { return proto.CompactTextString(m) } func (*KnownTypes) ProtoMessage() {} func (*KnownTypes) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{8} } func (m *KnownTypes) GetAn() *google_protobuf.Any { if m != nil { return m.An } return nil } func (m *KnownTypes) GetDur() *google_protobuf1.Duration { if m != nil { return m.Dur } return nil } func (m *KnownTypes) GetSt() *google_protobuf2.Struct { if m != nil { return m.St } return nil } func (m *KnownTypes) GetTs() *google_protobuf3.Timestamp { if m != nil { return m.Ts } return nil } func (m *KnownTypes) GetLv() *google_protobuf2.ListValue { if m != nil { return m.Lv } return nil } func (m *KnownTypes) GetVal() *google_protobuf2.Value { if m != nil { return m.Val } return nil } func (m *KnownTypes) GetDbl() *google_protobuf4.DoubleValue { if m != nil { return m.Dbl } return nil } func (m *KnownTypes) GetFlt() *google_protobuf4.FloatValue { if m != nil { return m.Flt } return nil } func (m *KnownTypes) GetI64() *google_protobuf4.Int64Value { if m != nil { return m.I64 } return nil } func (m *KnownTypes) GetU64() *google_protobuf4.UInt64Value { if m != nil { return m.U64 } return nil } func (m *KnownTypes) GetI32() *google_protobuf4.Int32Value { if m != nil { return m.I32 } return nil } func (m *KnownTypes) GetU32() *google_protobuf4.UInt32Value { if m != nil { return m.U32 } return nil } func (m *KnownTypes) GetBool() *google_protobuf4.BoolValue { if m != nil { return m.Bool } return nil } func (m *KnownTypes) GetStr() *google_protobuf4.StringValue { if m != nil { return m.Str } return nil } func (m *KnownTypes) GetBytes() *google_protobuf4.BytesValue { if m != nil { return m.Bytes } return nil } var E_Name = &proto.ExtensionDesc{ ExtendedType: (*Real)(nil), ExtensionType: (*string)(nil), Field: 124, Name: "jsonpb.name", Tag: "bytes,124,opt,name=name", Filename: "test_objects.proto", } func init() { proto.RegisterType((*Simple)(nil), "jsonpb.Simple") proto.RegisterType((*NonFinites)(nil), "jsonpb.NonFinites") proto.RegisterType((*Repeats)(nil), "jsonpb.Repeats") proto.RegisterType((*Widget)(nil), "jsonpb.Widget") proto.RegisterType((*Maps)(nil), "jsonpb.Maps") proto.RegisterType((*MsgWithOneof)(nil), "jsonpb.MsgWithOneof") proto.RegisterType((*Real)(nil), "jsonpb.Real") proto.RegisterType((*Complex)(nil), "jsonpb.Complex") proto.RegisterType((*KnownTypes)(nil), "jsonpb.KnownTypes") proto.RegisterEnum("jsonpb.Widget_Color", Widget_Color_name, Widget_Color_value) proto.RegisterExtension(E_Complex_RealExtension) proto.RegisterExtension(E_Name) } func init() { proto.RegisterFile("test_objects.proto", fileDescriptor1) } var fileDescriptor1 = []byte{ // 1160 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x95, 0x41, 0x73, 0xdb, 0x44, 0x14, 0xc7, 0x23, 0xc9, 0x92, 0xed, 0x75, 0x92, 0x9a, 0x6d, 0xda, 0x2a, 0x26, 0x80, 0xc6, 0x94, 0x22, 0x0a, 0x75, 0x07, 0xc7, 0xe3, 0x61, 0x0a, 0x97, 0xa4, 0x71, 0x29, 0x43, 0x13, 0x98, 0x4d, 0x43, 0x8f, 0x1e, 0x39, 0x5a, 0xbb, 0x2a, 0xf2, 0xae, 0x67, 0x77, 0x95, 0xd4, 0x03, 0x87, 0x9c, 0x39, 0x32, 0x7c, 0x05, 0xf8, 0x08, 0x1c, 0xf8, 0x74, 0xcc, 0xdb, 0x95, 0xac, 0xc4, 0x8e, 0x4f, 0xf1, 0x7b, 0xef, 0xff, 0xfe, 0x59, 0xed, 0x6f, 0x77, 0x1f, 0xc2, 0x8a, 0x4a, 0x35, 0xe4, 0xa3, 0x77, 0xf4, 0x5c, 0xc9, 0xce, 0x4c, 0x70, 0xc5, 0xb1, 0xf7, 0x4e, 0x72, 0x36, 0x1b, 0xb5, 0x76, 0x27, 0x9c, 0x4f, 0x52, 0xfa, 0x54, 0x67, 0x47, 0xd9, 0xf8, 0x69, 0xc4, 0xe6, 0x46, 0xd2, 0xfa, 0x78, 0xb9, 0x14, 0x67, 0x22, 0x52, 0x09, 0x67, 0x79, 0x7d, 0x6f, 0xb9, 0x2e, 0x95, 0xc8, 0xce, 0x55, 0x5e, 0xfd, 0x64, 0xb9, 0xaa, 0x92, 0x29, 0x95, 0x2a, 0x9a, 0xce, 0xd6, 0xd9, 0x5f, 0x8a, 0x68, 0x36, 0xa3, 0x22, 0x5f, 0x61, 0xfb, 0x6f, 0x1b, 0x79, 0xa7, 0xc9, 0x74, 0x96, 0x52, 0x7c, 0x0f, 0x79, 0x7c, 0x38, 0xe2, 0x3c, 0xf5, 0xad, 0xc0, 0x0a, 0x6b, 0xc4, 0xe5, 0x87, 0x9c, 0xa7, 0xf8, 0x01, 0xaa, 0xf2, 0x61, 0xc2, 0xd4, 0x7e, 0xd7, 0xb7, 0x03, 0x2b, 0x74, 0x89, 0xc7, 0x7f, 0x80, 0x68, 0x51, 0xe8, 0xf7, 0x7c, 0x27, 0xb0, 0x42, 0xc7, 0x14, 0xfa, 0x3d, 0xbc, 0x8b, 0x6a, 0x7c, 0x98, 0x99, 0x96, 0x4a, 0x60, 0x85, 0x5b, 0xa4, 0xca, 0xcf, 0x74, 0x58, 0x96, 0xfa, 0x3d, 0xdf, 0x0d, 0xac, 0xb0, 0x92, 0x97, 0x8a, 0x2e, 0x69, 0xba, 0xbc, 0xc0, 0x0a, 0x3f, 0x20, 0x55, 0x7e, 0x7a, 0xad, 0x4b, 0x9a, 0xae, 0x6a, 0x60, 0x85, 0x38, 0x2f, 0xf5, 0x7b, 0x66, 0x11, 0xe3, 0x94, 0x47, 0xca, 0xaf, 0x05, 0x56, 0x68, 0x13, 0x8f, 0xbf, 0x80, 0xc8, 0xf4, 0xc4, 0x3c, 0x1b, 0xa5, 0xd4, 0xaf, 0x07, 0x56, 0x68, 0x91, 0x2a, 0x3f, 0xd2, 0x61, 0x6e, 0xa7, 0x44, 0xc2, 0x26, 0x3e, 0x0a, 0xac, 0xb0, 0x0e, 0x76, 0x3a, 0x34, 0x76, 0xa3, 0xb9, 0xa2, 0xd2, 0x6f, 0x04, 0x56, 0xb8, 0x49, 0x3c, 0x7e, 0x08, 0x51, 0xfb, 0x4f, 0x0b, 0xa1, 0x13, 0xce, 0x5e, 0x24, 0x2c, 0x51, 0x54, 0xe2, 0xbb, 0xc8, 0x1d, 0x0f, 0x59, 0xc4, 0xf4, 0x56, 0xd9, 0xa4, 0x32, 0x3e, 0x89, 0x18, 0x6c, 0xe0, 0x78, 0x38, 0x4b, 0xd8, 0x58, 0x6f, 0x94, 0x4d, 0xdc, 0xf1, 0xcf, 0x09, 0x1b, 0x9b, 0x34, 0x83, 0xb4, 0x93, 0xa7, 0x4f, 0x20, 0x7d, 0x17, 0xb9, 0xb1, 0xb6, 0xa8, 0xe8, 0xd5, 0x55, 0xe2, 0xdc, 0x22, 0x36, 0x16, 0xae, 0xce, 0xba, 0x71, 0x61, 0x11, 0x1b, 0x0b, 0x2f, 0x4f, 0x83, 0x45, 0xfb, 0x1f, 0x1b, 0x55, 0x09, 0x9d, 0xd1, 0x48, 0x49, 0x90, 0x88, 0x82, 0x9e, 0x03, 0xf4, 0x44, 0x41, 0x4f, 0x2c, 0xe8, 0x39, 0x40, 0x4f, 0x2c, 0xe8, 0x89, 0x05, 0x3d, 0x07, 0xe8, 0x89, 0x05, 0x3d, 0x51, 0xd2, 0x73, 0x80, 0x9e, 0x28, 0xe9, 0x89, 0x92, 0x9e, 0x03, 0xf4, 0x44, 0x49, 0x4f, 0x94, 0xf4, 0x1c, 0xa0, 0x27, 0x4e, 0xaf, 0x75, 0x2d, 0xe8, 0x39, 0x40, 0x4f, 0x94, 0xf4, 0xc4, 0x82, 0x9e, 0x03, 0xf4, 0xc4, 0x82, 0x9e, 0x28, 0xe9, 0x39, 0x40, 0x4f, 0x94, 0xf4, 0x44, 0x49, 0xcf, 0x01, 0x7a, 0xa2, 0xa4, 0x27, 0x16, 0xf4, 0x1c, 0xa0, 0x27, 0x0c, 0xbd, 0x7f, 0x6d, 0xe4, 0xbd, 0x49, 0xe2, 0x09, 0x55, 0xf8, 0x31, 0x72, 0xcf, 0x79, 0xca, 0x85, 0x26, 0xb7, 0xdd, 0xdd, 0xe9, 0x98, 0x2b, 0xda, 0x31, 0xe5, 0xce, 0x73, 0xa8, 0x11, 0x23, 0xc1, 0x4f, 0xc0, 0xcf, 0xa8, 0x61, 0xf3, 0xd6, 0xa9, 0x3d, 0xa1, 0xff, 0xe2, 0x47, 0xc8, 0x93, 0xfa, 0x2a, 0xe9, 0x53, 0xd5, 0xe8, 0x6e, 0x17, 0x6a, 0x73, 0xc1, 0x48, 0x5e, 0xc5, 0x5f, 0x98, 0x0d, 0xd1, 0x4a, 0x58, 0xe7, 0xaa, 0x12, 0x36, 0x28, 0x97, 0x56, 0x85, 0x01, 0xec, 0xef, 0x68, 0xcf, 0x3b, 0x85, 0x32, 0xe7, 0x4e, 0x8a, 0x3a, 0xfe, 0x0a, 0xd5, 0xc5, 0xb0, 0x10, 0xdf, 0xd3, 0xb6, 0x2b, 0xe2, 0x9a, 0xc8, 0x7f, 0xb5, 0x3f, 0x43, 0xae, 0x59, 0x74, 0x15, 0x39, 0x64, 0x70, 0xd4, 0xdc, 0xc0, 0x75, 0xe4, 0x7e, 0x4f, 0x06, 0x83, 0x93, 0xa6, 0x85, 0x6b, 0xa8, 0x72, 0xf8, 0xea, 0x6c, 0xd0, 0xb4, 0xdb, 0x7f, 0xd9, 0xa8, 0x72, 0x1c, 0xcd, 0x24, 0xfe, 0x16, 0x35, 0xa6, 0xe6, 0xb8, 0xc0, 0xde, 0xeb, 0x33, 0xd6, 0xe8, 0x7e, 0x58, 0xf8, 0x83, 0xa4, 0x73, 0xac, 0xcf, 0xcf, 0xa9, 0x12, 0x03, 0xa6, 0xc4, 0x9c, 0xd4, 0xa7, 0x45, 0x8c, 0x0f, 0xd0, 0xd6, 0x54, 0x9f, 0xcd, 0xe2, 0xab, 0x6d, 0xdd, 0xfe, 0xd1, 0xcd, 0x76, 0x38, 0xaf, 0xe6, 0xb3, 0x8d, 0x41, 0x63, 0x5a, 0x66, 0x5a, 0xdf, 0xa1, 0xed, 0x9b, 0xfe, 0xb8, 0x89, 0x9c, 0x5f, 0xe9, 0x5c, 0x63, 0x74, 0x08, 0xfc, 0xc4, 0x3b, 0xc8, 0xbd, 0x88, 0xd2, 0x8c, 0xea, 0xeb, 0x57, 0x27, 0x26, 0x78, 0x66, 0x7f, 0x63, 0xb5, 0x4e, 0x50, 0x73, 0xd9, 0xfe, 0x7a, 0x7f, 0xcd, 0xf4, 0x3f, 0xbc, 0xde, 0xbf, 0x0a, 0xa5, 0xf4, 0x6b, 0xff, 0x61, 0xa1, 0xcd, 0x63, 0x39, 0x79, 0x93, 0xa8, 0xb7, 0x3f, 0x31, 0xca, 0xc7, 0xf8, 0x3e, 0x72, 0x55, 0xa2, 0x52, 0xaa, 0xed, 0xea, 0x2f, 0x37, 0x88, 0x09, 0xb1, 0x8f, 0x3c, 0x19, 0xa5, 0x91, 0x98, 0x6b, 0x4f, 0xe7, 0xe5, 0x06, 0xc9, 0x63, 0xdc, 0x42, 0xd5, 0xe7, 0x3c, 0x83, 0x95, 0xe8, 0x67, 0x01, 0x7a, 0x8a, 0x04, 0xfe, 0x14, 0x6d, 0xbe, 0xe5, 0x53, 0x3a, 0x8c, 0xe2, 0x58, 0x50, 0x29, 0xf5, 0x0b, 0x01, 0x82, 0x06, 0x64, 0x0f, 0x4c, 0xf2, 0xb0, 0x8a, 0xdc, 0x8c, 0x25, 0x9c, 0xb5, 0x1f, 0xa1, 0x0a, 0xa1, 0x51, 0x5a, 0x7e, 0xbe, 0x65, 0xde, 0x08, 0x1d, 0x3c, 0xae, 0xd5, 0xe2, 0xe6, 0xd5, 0xd5, 0xd5, 0x95, 0xdd, 0xbe, 0x84, 0xff, 0x08, 0x5f, 0xf2, 0x1e, 0xef, 0xa1, 0x7a, 0x32, 0x8d, 0x26, 0x09, 0x83, 0x95, 0x19, 0x79, 0x99, 0x28, 0x5b, 0xba, 0x47, 0x68, 0x5b, 0xd0, 0x28, 0x1d, 0xd2, 0xf7, 0x8a, 0x32, 0x99, 0x70, 0x86, 0x37, 0xcb, 0x23, 0x15, 0xa5, 0xfe, 0x6f, 0x37, 0xcf, 0x64, 0x6e, 0x4f, 0xb6, 0xa0, 0x69, 0x50, 0xf4, 0xb4, 0xff, 0x73, 0x11, 0xfa, 0x91, 0xf1, 0x4b, 0xf6, 0x7a, 0x3e, 0xa3, 0x12, 0x3f, 0x44, 0x76, 0xc4, 0xfc, 0x6d, 0xdd, 0xba, 0xd3, 0x31, 0xf3, 0xa9, 0x53, 0xcc, 0xa7, 0xce, 0x01, 0x9b, 0x13, 0x3b, 0x62, 0xf8, 0x4b, 0xe4, 0xc4, 0x99, 0xb9, 0xa5, 0x8d, 0xee, 0xee, 0x8a, 0xec, 0x28, 0x9f, 0x92, 0x04, 0x54, 0xf8, 0x73, 0x64, 0x4b, 0xe5, 0x6f, 0x6a, 0xed, 0x83, 0x15, 0xed, 0xa9, 0x9e, 0x98, 0xc4, 0x96, 0x70, 0xfb, 0x6d, 0x25, 0x73, 0xbe, 0xad, 0x15, 0xe1, 0xeb, 0x62, 0x78, 0x12, 0x5b, 0x49, 0xd0, 0xa6, 0x17, 0xfe, 0x9d, 0x35, 0xda, 0x57, 0x89, 0x54, 0xbf, 0xc0, 0x0e, 0x13, 0x3b, 0xbd, 0xc0, 0x21, 0x72, 0x2e, 0xa2, 0xd4, 0x6f, 0x6a, 0xf1, 0xfd, 0x15, 0xb1, 0x11, 0x82, 0x04, 0x77, 0x90, 0x13, 0x8f, 0x52, 0xcd, 0xbc, 0xd1, 0xdd, 0x5b, 0xfd, 0x2e, 0xfd, 0xc8, 0xe5, 0xfa, 0x78, 0x94, 0xe2, 0x27, 0xc8, 0x19, 0xa7, 0x4a, 0x1f, 0x01, 0xb8, 0x70, 0xcb, 0x7a, 0xfd, 0x5c, 0xe6, 0xf2, 0x71, 0xaa, 0x40, 0x9e, 0xe4, 0xb3, 0xf5, 0x36, 0xb9, 0xbe, 0x42, 0xb9, 0x3c, 0xe9, 0xf7, 0x60, 0x35, 0x59, 0xbf, 0xa7, 0xa7, 0xca, 0x6d, 0xab, 0x39, 0xbb, 0xae, 0xcf, 0xfa, 0x3d, 0x6d, 0xbf, 0xdf, 0xd5, 0x43, 0x78, 0x8d, 0xfd, 0x7e, 0xb7, 0xb0, 0xdf, 0xef, 0x6a, 0xfb, 0xfd, 0xae, 0x9e, 0xcc, 0xeb, 0xec, 0x17, 0xfa, 0x4c, 0xeb, 0x2b, 0x7a, 0x84, 0xd5, 0xd7, 0x6c, 0x3a, 0xdc, 0x61, 0x23, 0xd7, 0x3a, 0xf0, 0x87, 0xd7, 0x08, 0xad, 0xf1, 0x37, 0x63, 0x21, 0xf7, 0x97, 0x4a, 0xe0, 0xaf, 0x91, 0x5b, 0x0e, 0xf7, 0xdb, 0x3e, 0x40, 0x8f, 0x0b, 0xd3, 0x60, 0x94, 0xcf, 0x02, 0x54, 0x61, 0xd1, 0x94, 0x2e, 0x1d, 0xfc, 0xdf, 0xf5, 0x0b, 0xa3, 0x2b, 0xff, 0x07, 0x00, 0x00, 0xff, 0xff, 0xd5, 0x39, 0x32, 0x09, 0xf9, 0x09, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto2"; import "google/protobuf/any.proto"; import "google/protobuf/duration.proto"; import "google/protobuf/struct.proto"; import "google/protobuf/timestamp.proto"; import "google/protobuf/wrappers.proto"; package jsonpb; // Test message for holding primitive types. message Simple { optional bool o_bool = 1; optional int32 o_int32 = 2; optional int64 o_int64 = 3; optional uint32 o_uint32 = 4; optional uint64 o_uint64 = 5; optional sint32 o_sint32 = 6; optional sint64 o_sint64 = 7; optional float o_float = 8; optional double o_double = 9; optional string o_string = 10; optional bytes o_bytes = 11; } // Test message for holding special non-finites primitives. message NonFinites { optional float f_nan = 1; optional float f_pinf = 2; optional float f_ninf = 3; optional double d_nan = 4; optional double d_pinf = 5; optional double d_ninf = 6; } // Test message for holding repeated primitives. message Repeats { repeated bool r_bool = 1; repeated int32 r_int32 = 2; repeated int64 r_int64 = 3; repeated uint32 r_uint32 = 4; repeated uint64 r_uint64 = 5; repeated sint32 r_sint32 = 6; repeated sint64 r_sint64 = 7; repeated float r_float = 8; repeated double r_double = 9; repeated string r_string = 10; repeated bytes r_bytes = 11; } // Test message for holding enums and nested messages. message Widget { enum Color { RED = 0; GREEN = 1; BLUE = 2; }; optional Color color = 1; repeated Color r_color = 2; optional Simple simple = 10; repeated Simple r_simple = 11; optional Repeats repeats = 20; repeated Repeats r_repeats = 21; } message Maps { map m_int64_str = 1; map m_bool_simple = 2; } message MsgWithOneof { oneof union { string title = 1; int64 salary = 2; string Country = 3; string home_address = 4; } } message Real { optional double value = 1; extensions 100 to max; } extend Real { optional string name = 124; } message Complex { extend Real { optional Complex real_extension = 123; } optional double imaginary = 1; extensions 100 to max; } message KnownTypes { optional google.protobuf.Any an = 14; optional google.protobuf.Duration dur = 1; optional google.protobuf.Struct st = 12; optional google.protobuf.Timestamp ts = 2; optional google.protobuf.ListValue lv = 15; optional google.protobuf.Value val = 16; optional google.protobuf.DoubleValue dbl = 3; optional google.protobuf.FloatValue flt = 4; optional google.protobuf.Int64Value i64 = 5; optional google.protobuf.UInt64Value u64 = 6; optional google.protobuf.Int32Value i32 = 7; optional google.protobuf.UInt32Value u32 = 8; optional google.protobuf.BoolValue bool = 9; optional google.protobuf.StringValue str = 10; optional google.protobuf.BytesValue bytes = 11; } ================================================ FILE: src/github.com/golang/protobuf/proto/Makefile ================================================ # Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/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. install: go install test: install generate-test-pbs go test generate-test-pbs: make install make -C testdata protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata,Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. proto3_proto/proto3.proto make ================================================ FILE: src/github.com/golang/protobuf/proto/all_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto_test import ( "bytes" "encoding/json" "errors" "fmt" "math" "math/rand" "reflect" "runtime/debug" "strings" "testing" "time" . "github.com/golang/protobuf/proto" . "github.com/golang/protobuf/proto/testdata" ) var globalO *Buffer func old() *Buffer { if globalO == nil { globalO = NewBuffer(nil) } globalO.Reset() return globalO } func equalbytes(b1, b2 []byte, t *testing.T) { if len(b1) != len(b2) { t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) return } for i := 0; i < len(b1); i++ { if b1[i] != b2[i] { t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) } } } func initGoTestField() *GoTestField { f := new(GoTestField) f.Label = String("label") f.Type = String("type") return f } // These are all structurally equivalent but the tag numbers differ. // (It's remarkable that required, optional, and repeated all have // 8 letters.) func initGoTest_RequiredGroup() *GoTest_RequiredGroup { return &GoTest_RequiredGroup{ RequiredField: String("required"), } } func initGoTest_OptionalGroup() *GoTest_OptionalGroup { return &GoTest_OptionalGroup{ RequiredField: String("optional"), } } func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { return &GoTest_RepeatedGroup{ RequiredField: String("repeated"), } } func initGoTest(setdefaults bool) *GoTest { pb := new(GoTest) if setdefaults { pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) } pb.Kind = GoTest_TIME.Enum() pb.RequiredField = initGoTestField() pb.F_BoolRequired = Bool(true) pb.F_Int32Required = Int32(3) pb.F_Int64Required = Int64(6) pb.F_Fixed32Required = Uint32(32) pb.F_Fixed64Required = Uint64(64) pb.F_Uint32Required = Uint32(3232) pb.F_Uint64Required = Uint64(6464) pb.F_FloatRequired = Float32(3232) pb.F_DoubleRequired = Float64(6464) pb.F_StringRequired = String("string") pb.F_BytesRequired = []byte("bytes") pb.F_Sint32Required = Int32(-32) pb.F_Sint64Required = Int64(-64) pb.Requiredgroup = initGoTest_RequiredGroup() return pb } func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { data := b.Bytes() ld := len(data) ls := len(s) / 2 fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) // find the interesting spot - n n := ls if ld < ls { n = ld } j := 0 for i := 0; i < n; i++ { bs := hex(s[j])*16 + hex(s[j+1]) j += 2 if data[i] == bs { continue } n = i break } l := n - 10 if l < 0 { l = 0 } h := n + 10 // find the interesting spot - n fmt.Printf("is[%d]:", l) for i := l; i < h; i++ { if i >= ld { fmt.Printf(" --") continue } fmt.Printf(" %.2x", data[i]) } fmt.Printf("\n") fmt.Printf("sb[%d]:", l) for i := l; i < h; i++ { if i >= ls { fmt.Printf(" --") continue } bs := hex(s[j])*16 + hex(s[j+1]) j += 2 fmt.Printf(" %.2x", bs) } fmt.Printf("\n") t.Fail() // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) // Print the output in a partially-decoded format; can // be helpful when updating the test. It produces the output // that is pasted, with minor edits, into the argument to verify(). // data := b.Bytes() // nesting := 0 // for b.Len() > 0 { // start := len(data) - b.Len() // var u uint64 // u, err := DecodeVarint(b) // if err != nil { // fmt.Printf("decode error on varint:", err) // return // } // wire := u & 0x7 // tag := u >> 3 // switch wire { // case WireVarint: // v, err := DecodeVarint(b) // if err != nil { // fmt.Printf("decode error on varint:", err) // return // } // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", // data[start:len(data)-b.Len()], tag, wire, v) // case WireFixed32: // v, err := DecodeFixed32(b) // if err != nil { // fmt.Printf("decode error on fixed32:", err) // return // } // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", // data[start:len(data)-b.Len()], tag, wire, v) // case WireFixed64: // v, err := DecodeFixed64(b) // if err != nil { // fmt.Printf("decode error on fixed64:", err) // return // } // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", // data[start:len(data)-b.Len()], tag, wire, v) // case WireBytes: // nb, err := DecodeVarint(b) // if err != nil { // fmt.Printf("decode error on bytes:", err) // return // } // after_tag := len(data) - b.Len() // str := make([]byte, nb) // _, err = b.Read(str) // if err != nil { // fmt.Printf("decode error on bytes:", err) // return // } // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", // data[start:after_tag], str, tag, wire) // case WireStartGroup: // nesting++ // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", // data[start:len(data)-b.Len()], tag, nesting) // case WireEndGroup: // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", // data[start:len(data)-b.Len()], tag, nesting) // nesting-- // default: // fmt.Printf("unrecognized wire type %d\n", wire) // return // } // } } func hex(c uint8) uint8 { if '0' <= c && c <= '9' { return c - '0' } if 'a' <= c && c <= 'f' { return 10 + c - 'a' } if 'A' <= c && c <= 'F' { return 10 + c - 'A' } return 0 } func equal(b []byte, s string, t *testing.T) bool { if 2*len(b) != len(s) { // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) return false } for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { x := hex(s[j])*16 + hex(s[j+1]) if b[i] != x { // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) return false } } return true } func overify(t *testing.T, pb *GoTest, expected string) { o := old() err := o.Marshal(pb) if err != nil { fmt.Printf("overify marshal-1 err = %v", err) o.DebugPrint("", o.Bytes()) t.Fatalf("expected = %s", expected) } if !equal(o.Bytes(), expected, t) { o.DebugPrint("overify neq 1", o.Bytes()) t.Fatalf("expected = %s", expected) } // Now test Unmarshal by recreating the original buffer. pbd := new(GoTest) err = o.Unmarshal(pbd) if err != nil { t.Fatalf("overify unmarshal err = %v", err) o.DebugPrint("", o.Bytes()) t.Fatalf("string = %s", expected) } o.Reset() err = o.Marshal(pbd) if err != nil { t.Errorf("overify marshal-2 err = %v", err) o.DebugPrint("", o.Bytes()) t.Fatalf("string = %s", expected) } if !equal(o.Bytes(), expected, t) { o.DebugPrint("overify neq 2", o.Bytes()) t.Fatalf("string = %s", expected) } } // Simple tests for numeric encode/decode primitives (varint, etc.) func TestNumericPrimitives(t *testing.T) { for i := uint64(0); i < 1e6; i += 111 { o := old() if o.EncodeVarint(i) != nil { t.Error("EncodeVarint") break } x, e := o.DecodeVarint() if e != nil { t.Fatal("DecodeVarint") } if x != i { t.Fatal("varint decode fail:", i, x) } o = old() if o.EncodeFixed32(i) != nil { t.Fatal("encFixed32") } x, e = o.DecodeFixed32() if e != nil { t.Fatal("decFixed32") } if x != i { t.Fatal("fixed32 decode fail:", i, x) } o = old() if o.EncodeFixed64(i*1234567) != nil { t.Error("encFixed64") break } x, e = o.DecodeFixed64() if e != nil { t.Error("decFixed64") break } if x != i*1234567 { t.Error("fixed64 decode fail:", i*1234567, x) break } o = old() i32 := int32(i - 12345) if o.EncodeZigzag32(uint64(i32)) != nil { t.Fatal("EncodeZigzag32") } x, e = o.DecodeZigzag32() if e != nil { t.Fatal("DecodeZigzag32") } if x != uint64(uint32(i32)) { t.Fatal("zigzag32 decode fail:", i32, x) } o = old() i64 := int64(i - 12345) if o.EncodeZigzag64(uint64(i64)) != nil { t.Fatal("EncodeZigzag64") } x, e = o.DecodeZigzag64() if e != nil { t.Fatal("DecodeZigzag64") } if x != uint64(i64) { t.Fatal("zigzag64 decode fail:", i64, x) } } } // fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. type fakeMarshaler struct { b []byte err error } func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err } func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) } func (f *fakeMarshaler) ProtoMessage() {} func (f *fakeMarshaler) Reset() {} type msgWithFakeMarshaler struct { M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"` } func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) } func (m *msgWithFakeMarshaler) ProtoMessage() {} func (m *msgWithFakeMarshaler) Reset() {} // Simple tests for proto messages that implement the Marshaler interface. func TestMarshalerEncoding(t *testing.T) { tests := []struct { name string m Message want []byte errType reflect.Type }{ { name: "Marshaler that fails", m: &fakeMarshaler{ err: errors.New("some marshal err"), b: []byte{5, 6, 7}, }, // Since the Marshal method returned bytes, they should be written to the // buffer. (For efficiency, we assume that Marshal implementations are // always correct w.r.t. RequiredNotSetError and output.) want: []byte{5, 6, 7}, errType: reflect.TypeOf(errors.New("some marshal err")), }, { name: "Marshaler that fails with RequiredNotSetError", m: &msgWithFakeMarshaler{ M: &fakeMarshaler{ err: &RequiredNotSetError{}, b: []byte{5, 6, 7}, }, }, // Since there's an error that can be continued after, // the buffer should be written. want: []byte{ 10, 3, // for &msgWithFakeMarshaler 5, 6, 7, // for &fakeMarshaler }, errType: reflect.TypeOf(&RequiredNotSetError{}), }, { name: "Marshaler that succeeds", m: &fakeMarshaler{ b: []byte{0, 1, 2, 3, 4, 127, 255}, }, want: []byte{0, 1, 2, 3, 4, 127, 255}, }, } for _, test := range tests { b := NewBuffer(nil) err := b.Marshal(test.m) if reflect.TypeOf(err) != test.errType { t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType) } if !reflect.DeepEqual(test.want, b.Bytes()) { t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) } if size := Size(test.m); size != len(b.Bytes()) { t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes())) } m, mErr := Marshal(test.m) if !bytes.Equal(b.Bytes(), m) { t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes()) } if !reflect.DeepEqual(err, mErr) { t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q", test.name, fmt.Sprint(mErr), fmt.Sprint(err)) } } } // Simple tests for bytes func TestBytesPrimitives(t *testing.T) { o := old() bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} if o.EncodeRawBytes(bytes) != nil { t.Error("EncodeRawBytes") } decb, e := o.DecodeRawBytes(false) if e != nil { t.Error("DecodeRawBytes") } equalbytes(bytes, decb, t) } // Simple tests for strings func TestStringPrimitives(t *testing.T) { o := old() s := "now is the time" if o.EncodeStringBytes(s) != nil { t.Error("enc_string") } decs, e := o.DecodeStringBytes() if e != nil { t.Error("dec_string") } if s != decs { t.Error("string encode/decode fail:", s, decs) } } // Do we catch the "required bit not set" case? func TestRequiredBit(t *testing.T) { o := old() pb := new(GoTest) err := o.Marshal(pb) if err == nil { t.Error("did not catch missing required fields") } else if strings.Index(err.Error(), "Kind") < 0 { t.Error("wrong error type:", err) } } // Check that all fields are nil. // Clearly silly, and a residue from a more interesting test with an earlier, // different initialization property, but it once caught a compiler bug so // it lives. func checkInitialized(pb *GoTest, t *testing.T) { if pb.F_BoolDefaulted != nil { t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) } if pb.F_Int32Defaulted != nil { t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) } if pb.F_Int64Defaulted != nil { t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) } if pb.F_Fixed32Defaulted != nil { t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) } if pb.F_Fixed64Defaulted != nil { t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) } if pb.F_Uint32Defaulted != nil { t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) } if pb.F_Uint64Defaulted != nil { t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) } if pb.F_FloatDefaulted != nil { t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) } if pb.F_DoubleDefaulted != nil { t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) } if pb.F_StringDefaulted != nil { t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) } if pb.F_BytesDefaulted != nil { t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) } if pb.F_Sint32Defaulted != nil { t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) } if pb.F_Sint64Defaulted != nil { t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) } } // Does Reset() reset? func TestReset(t *testing.T) { pb := initGoTest(true) // muck with some values pb.F_BoolDefaulted = Bool(false) pb.F_Int32Defaulted = Int32(237) pb.F_Int64Defaulted = Int64(12346) pb.F_Fixed32Defaulted = Uint32(32000) pb.F_Fixed64Defaulted = Uint64(666) pb.F_Uint32Defaulted = Uint32(323232) pb.F_Uint64Defaulted = nil pb.F_FloatDefaulted = nil pb.F_DoubleDefaulted = Float64(0) pb.F_StringDefaulted = String("gotcha") pb.F_BytesDefaulted = []byte("asdfasdf") pb.F_Sint32Defaulted = Int32(123) pb.F_Sint64Defaulted = Int64(789) pb.Reset() checkInitialized(pb, t) } // All required fields set, no defaults provided. func TestEncodeDecode1(t *testing.T) { pb := initGoTest(false) overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 0x20 "714000000000000000"+ // field 14, encoding 1, value 0x40 "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" "b304"+ // field 70, encoding 3, start group "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // field 70, encoding 4, end group "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f") // field 103, encoding 0, 0x7f zigzag64 } // All required fields set, defaults provided. func TestEncodeDecode2(t *testing.T) { pb := initGoTest(true) overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "c00201"+ // field 40, encoding 0, value 1 "c80220"+ // field 41, encoding 0, value 32 "d00240"+ // field 42, encoding 0, value 64 "dd0240010000"+ // field 43, encoding 5, value 320 "e1028002000000000000"+ // field 44, encoding 1, value 640 "e8028019"+ // field 45, encoding 0, value 3200 "f0028032"+ // field 46, encoding 0, value 6400 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" "90193f"+ // field 402, encoding 0, value 63 "98197f") // field 403, encoding 0, value 127 } // All default fields set to their default value by hand func TestEncodeDecode3(t *testing.T) { pb := initGoTest(false) pb.F_BoolDefaulted = Bool(true) pb.F_Int32Defaulted = Int32(32) pb.F_Int64Defaulted = Int64(64) pb.F_Fixed32Defaulted = Uint32(320) pb.F_Fixed64Defaulted = Uint64(640) pb.F_Uint32Defaulted = Uint32(3200) pb.F_Uint64Defaulted = Uint64(6400) pb.F_FloatDefaulted = Float32(314159) pb.F_DoubleDefaulted = Float64(271828) pb.F_StringDefaulted = String("hello, \"world!\"\n") pb.F_BytesDefaulted = []byte("Bignose") pb.F_Sint32Defaulted = Int32(-32) pb.F_Sint64Defaulted = Int64(-64) overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "c00201"+ // field 40, encoding 0, value 1 "c80220"+ // field 41, encoding 0, value 32 "d00240"+ // field 42, encoding 0, value 64 "dd0240010000"+ // field 43, encoding 5, value 320 "e1028002000000000000"+ // field 44, encoding 1, value 640 "e8028019"+ // field 45, encoding 0, value 3200 "f0028032"+ // field 46, encoding 0, value 6400 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" "90193f"+ // field 402, encoding 0, value 63 "98197f") // field 403, encoding 0, value 127 } // All required fields set, defaults provided, all non-defaulted optional fields have values. func TestEncodeDecode4(t *testing.T) { pb := initGoTest(true) pb.Table = String("hello") pb.Param = Int32(7) pb.OptionalField = initGoTestField() pb.F_BoolOptional = Bool(true) pb.F_Int32Optional = Int32(32) pb.F_Int64Optional = Int64(64) pb.F_Fixed32Optional = Uint32(3232) pb.F_Fixed64Optional = Uint64(6464) pb.F_Uint32Optional = Uint32(323232) pb.F_Uint64Optional = Uint64(646464) pb.F_FloatOptional = Float32(32.) pb.F_DoubleOptional = Float64(64.) pb.F_StringOptional = String("hello") pb.F_BytesOptional = []byte("Bignose") pb.F_Sint32Optional = Int32(-32) pb.F_Sint64Optional = Int64(-64) pb.Optionalgroup = initGoTest_OptionalGroup() overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" "1807"+ // field 3, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "f00101"+ // field 30, encoding 0, value 1 "f80120"+ // field 31, encoding 0, value 32 "800240"+ // field 32, encoding 0, value 64 "8d02a00c0000"+ // field 33, encoding 5, value 3232 "91024019000000000000"+ // field 34, encoding 1, value 6464 "9802a0dd13"+ // field 35, encoding 0, value 323232 "a002c0ba27"+ // field 36, encoding 0, value 646464 "ad0200000042"+ // field 37, encoding 5, value 32.0 "b1020000000000005040"+ // field 38, encoding 1, value 64.0 "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" "c00201"+ // field 40, encoding 0, value 1 "c80220"+ // field 41, encoding 0, value 32 "d00240"+ // field 42, encoding 0, value 64 "dd0240010000"+ // field 43, encoding 5, value 320 "e1028002000000000000"+ // field 44, encoding 1, value 640 "e8028019"+ // field 45, encoding 0, value 3200 "f0028032"+ // field 46, encoding 0, value 6400 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "d305"+ // start group field 90 level 1 "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" "d405"+ // end group field 90 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" "f0123f"+ // field 302, encoding 0, value 63 "f8127f"+ // field 303, encoding 0, value 127 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" "90193f"+ // field 402, encoding 0, value 63 "98197f") // field 403, encoding 0, value 127 } // All required fields set, defaults provided, all repeated fields given two values. func TestEncodeDecode5(t *testing.T) { pb := initGoTest(true) pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} pb.F_BoolRepeated = []bool{false, true} pb.F_Int32Repeated = []int32{32, 33} pb.F_Int64Repeated = []int64{64, 65} pb.F_Fixed32Repeated = []uint32{3232, 3333} pb.F_Fixed64Repeated = []uint64{6464, 6565} pb.F_Uint32Repeated = []uint32{323232, 333333} pb.F_Uint64Repeated = []uint64{646464, 656565} pb.F_FloatRepeated = []float32{32., 33.} pb.F_DoubleRepeated = []float64{64., 65.} pb.F_StringRepeated = []string{"hello", "sailor"} pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} pb.F_Sint32Repeated = []int32{32, -32} pb.F_Sint64Repeated = []int64{64, -64} pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "a00100"+ // field 20, encoding 0, value 0 "a00101"+ // field 20, encoding 0, value 1 "a80120"+ // field 21, encoding 0, value 32 "a80121"+ // field 21, encoding 0, value 33 "b00140"+ // field 22, encoding 0, value 64 "b00141"+ // field 22, encoding 0, value 65 "bd01a00c0000"+ // field 23, encoding 5, value 3232 "bd01050d0000"+ // field 23, encoding 5, value 3333 "c1014019000000000000"+ // field 24, encoding 1, value 6464 "c101a519000000000000"+ // field 24, encoding 1, value 6565 "c801a0dd13"+ // field 25, encoding 0, value 323232 "c80195ac14"+ // field 25, encoding 0, value 333333 "d001c0ba27"+ // field 26, encoding 0, value 646464 "d001b58928"+ // field 26, encoding 0, value 656565 "dd0100000042"+ // field 27, encoding 5, value 32.0 "dd0100000442"+ // field 27, encoding 5, value 33.0 "e1010000000000005040"+ // field 28, encoding 1, value 64.0 "e1010000000000405040"+ // field 28, encoding 1, value 65.0 "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" "c00201"+ // field 40, encoding 0, value 1 "c80220"+ // field 41, encoding 0, value 32 "d00240"+ // field 42, encoding 0, value 64 "dd0240010000"+ // field 43, encoding 5, value 320 "e1028002000000000000"+ // field 44, encoding 1, value 640 "e8028019"+ // field 45, encoding 0, value 3200 "f0028032"+ // field 46, encoding 0, value 6400 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "8305"+ // start group field 80 level 1 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" "8405"+ // end group field 80 level 1 "8305"+ // start group field 80 level 1 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" "8405"+ // end group field 80 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "ca0c03"+"626967"+ // field 201, encoding 2, string "big" "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" "d00c40"+ // field 202, encoding 0, value 32 "d00c3f"+ // field 202, encoding 0, value -32 "d80c8001"+ // field 203, encoding 0, value 64 "d80c7f"+ // field 203, encoding 0, value -64 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" "90193f"+ // field 402, encoding 0, value 63 "98197f") // field 403, encoding 0, value 127 } // All required fields set, all packed repeated fields given two values. func TestEncodeDecode6(t *testing.T) { pb := initGoTest(false) pb.F_BoolRepeatedPacked = []bool{false, true} pb.F_Int32RepeatedPacked = []int32{32, 33} pb.F_Int64RepeatedPacked = []int64{64, 65} pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} pb.F_FloatRepeatedPacked = []float32{32., 33.} pb.F_DoubleRepeatedPacked = []float64{64., 65.} pb.F_Sint32RepeatedPacked = []int32{32, -32} pb.F_Sint64RepeatedPacked = []int64{64, -64} overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 "aa0308"+ // field 53, encoding 2, 8 bytes "a00c0000050d0000"+ // value 3232, value 3333 "b20310"+ // field 54, encoding 2, 16 bytes "4019000000000000a519000000000000"+ // value 6464, value 6565 "ba0306"+ // field 55, encoding 2, 6 bytes "a0dd1395ac14"+ // value 323232, value 333333 "c20306"+ // field 56, encoding 2, 6 bytes "c0ba27b58928"+ // value 646464, value 656565 "ca0308"+ // field 57, encoding 2, 8 bytes "0000004200000442"+ // value 32.0, value 33.0 "d20310"+ // field 58, encoding 2, 16 bytes "00000000000050400000000000405040"+ // value 64.0, value 65.0 "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "b21f02"+ // field 502, encoding 2, 2 bytes "403f"+ // value 32, value -32 "ba1f03"+ // field 503, encoding 2, 3 bytes "80017f") // value 64, value -64 } // Test that we can encode empty bytes fields. func TestEncodeDecodeBytes1(t *testing.T) { pb := initGoTest(false) // Create our bytes pb.F_BytesRequired = []byte{} pb.F_BytesRepeated = [][]byte{{}} pb.F_BytesOptional = []byte{} d, err := Marshal(pb) if err != nil { t.Error(err) } pbd := new(GoTest) if err := Unmarshal(d, pbd); err != nil { t.Error(err) } if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { t.Error("required empty bytes field is incorrect") } if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { t.Error("repeated empty bytes field is incorrect") } if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { t.Error("optional empty bytes field is incorrect") } } // Test that we encode nil-valued fields of a repeated bytes field correctly. // Since entries in a repeated field cannot be nil, nil must mean empty value. func TestEncodeDecodeBytes2(t *testing.T) { pb := initGoTest(false) // Create our bytes pb.F_BytesRepeated = [][]byte{nil} d, err := Marshal(pb) if err != nil { t.Error(err) } pbd := new(GoTest) if err := Unmarshal(d, pbd); err != nil { t.Error(err) } if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { t.Error("Unexpected value for repeated bytes field") } } // All required fields set, defaults provided, all repeated fields given two values. func TestSkippingUnrecognizedFields(t *testing.T) { o := old() pb := initGoTestField() // Marshal it normally. o.Marshal(pb) // Now new a GoSkipTest record. skip := &GoSkipTest{ SkipInt32: Int32(32), SkipFixed32: Uint32(3232), SkipFixed64: Uint64(6464), SkipString: String("skipper"), Skipgroup: &GoSkipTest_SkipGroup{ GroupInt32: Int32(75), GroupString: String("wxyz"), }, } // Marshal it into same buffer. o.Marshal(skip) pbd := new(GoTestField) o.Unmarshal(pbd) // The __unrecognized field should be a marshaling of GoSkipTest skipd := new(GoSkipTest) o.SetBuf(pbd.XXX_unrecognized) o.Unmarshal(skipd) if *skipd.SkipInt32 != *skip.SkipInt32 { t.Error("skip int32", skipd.SkipInt32) } if *skipd.SkipFixed32 != *skip.SkipFixed32 { t.Error("skip fixed32", skipd.SkipFixed32) } if *skipd.SkipFixed64 != *skip.SkipFixed64 { t.Error("skip fixed64", skipd.SkipFixed64) } if *skipd.SkipString != *skip.SkipString { t.Error("skip string", *skipd.SkipString) } if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { t.Error("skip group int32", skipd.Skipgroup.GroupInt32) } if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { t.Error("skip group string", *skipd.Skipgroup.GroupString) } } // Check that unrecognized fields of a submessage are preserved. func TestSubmessageUnrecognizedFields(t *testing.T) { nm := &NewMessage{ Nested: &NewMessage_Nested{ Name: String("Nigel"), FoodGroup: String("carbs"), }, } b, err := Marshal(nm) if err != nil { t.Fatalf("Marshal of NewMessage: %v", err) } // Unmarshal into an OldMessage. om := new(OldMessage) if err := Unmarshal(b, om); err != nil { t.Fatalf("Unmarshal to OldMessage: %v", err) } exp := &OldMessage{ Nested: &OldMessage_Nested{ Name: String("Nigel"), // normal protocol buffer users should not do this XXX_unrecognized: []byte("\x12\x05carbs"), }, } if !Equal(om, exp) { t.Errorf("om = %v, want %v", om, exp) } // Clone the OldMessage. om = Clone(om).(*OldMessage) if !Equal(om, exp) { t.Errorf("Clone(om) = %v, want %v", om, exp) } // Marshal the OldMessage, then unmarshal it into an empty NewMessage. if b, err = Marshal(om); err != nil { t.Fatalf("Marshal of OldMessage: %v", err) } t.Logf("Marshal(%v) -> %q", om, b) nm2 := new(NewMessage) if err := Unmarshal(b, nm2); err != nil { t.Fatalf("Unmarshal to NewMessage: %v", err) } if !Equal(nm, nm2) { t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) } } // Check that an int32 field can be upgraded to an int64 field. func TestNegativeInt32(t *testing.T) { om := &OldMessage{ Num: Int32(-1), } b, err := Marshal(om) if err != nil { t.Fatalf("Marshal of OldMessage: %v", err) } // Check the size. It should be 11 bytes; // 1 for the field/wire type, and 10 for the negative number. if len(b) != 11 { t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) } // Unmarshal into a NewMessage. nm := new(NewMessage) if err := Unmarshal(b, nm); err != nil { t.Fatalf("Unmarshal to NewMessage: %v", err) } want := &NewMessage{ Num: Int64(-1), } if !Equal(nm, want) { t.Errorf("nm = %v, want %v", nm, want) } } // Check that we can grow an array (repeated field) to have many elements. // This test doesn't depend only on our encoding; for variety, it makes sure // we create, encode, and decode the correct contents explicitly. It's therefore // a bit messier. // This test also uses (and hence tests) the Marshal/Unmarshal functions // instead of the methods. func TestBigRepeated(t *testing.T) { pb := initGoTest(true) // Create the arrays const N = 50 // Internally the library starts much smaller. pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) pb.F_Sint64Repeated = make([]int64, N) pb.F_Sint32Repeated = make([]int32, N) pb.F_BytesRepeated = make([][]byte, N) pb.F_StringRepeated = make([]string, N) pb.F_DoubleRepeated = make([]float64, N) pb.F_FloatRepeated = make([]float32, N) pb.F_Uint64Repeated = make([]uint64, N) pb.F_Uint32Repeated = make([]uint32, N) pb.F_Fixed64Repeated = make([]uint64, N) pb.F_Fixed32Repeated = make([]uint32, N) pb.F_Int64Repeated = make([]int64, N) pb.F_Int32Repeated = make([]int32, N) pb.F_BoolRepeated = make([]bool, N) pb.RepeatedField = make([]*GoTestField, N) // Fill in the arrays with checkable values. igtf := initGoTestField() igtrg := initGoTest_RepeatedGroup() for i := 0; i < N; i++ { pb.Repeatedgroup[i] = igtrg pb.F_Sint64Repeated[i] = int64(i) pb.F_Sint32Repeated[i] = int32(i) s := fmt.Sprint(i) pb.F_BytesRepeated[i] = []byte(s) pb.F_StringRepeated[i] = s pb.F_DoubleRepeated[i] = float64(i) pb.F_FloatRepeated[i] = float32(i) pb.F_Uint64Repeated[i] = uint64(i) pb.F_Uint32Repeated[i] = uint32(i) pb.F_Fixed64Repeated[i] = uint64(i) pb.F_Fixed32Repeated[i] = uint32(i) pb.F_Int64Repeated[i] = int64(i) pb.F_Int32Repeated[i] = int32(i) pb.F_BoolRepeated[i] = i%2 == 0 pb.RepeatedField[i] = igtf } // Marshal. buf, _ := Marshal(pb) // Now test Unmarshal by recreating the original buffer. pbd := new(GoTest) Unmarshal(buf, pbd) // Check the checkable values for i := uint64(0); i < N; i++ { if pbd.Repeatedgroup[i] == nil { // TODO: more checking? t.Error("pbd.Repeatedgroup bad") } var x uint64 x = uint64(pbd.F_Sint64Repeated[i]) if x != i { t.Error("pbd.F_Sint64Repeated bad", x, i) } x = uint64(pbd.F_Sint32Repeated[i]) if x != i { t.Error("pbd.F_Sint32Repeated bad", x, i) } s := fmt.Sprint(i) equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) if pbd.F_StringRepeated[i] != s { t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) } x = uint64(pbd.F_DoubleRepeated[i]) if x != i { t.Error("pbd.F_DoubleRepeated bad", x, i) } x = uint64(pbd.F_FloatRepeated[i]) if x != i { t.Error("pbd.F_FloatRepeated bad", x, i) } x = pbd.F_Uint64Repeated[i] if x != i { t.Error("pbd.F_Uint64Repeated bad", x, i) } x = uint64(pbd.F_Uint32Repeated[i]) if x != i { t.Error("pbd.F_Uint32Repeated bad", x, i) } x = pbd.F_Fixed64Repeated[i] if x != i { t.Error("pbd.F_Fixed64Repeated bad", x, i) } x = uint64(pbd.F_Fixed32Repeated[i]) if x != i { t.Error("pbd.F_Fixed32Repeated bad", x, i) } x = uint64(pbd.F_Int64Repeated[i]) if x != i { t.Error("pbd.F_Int64Repeated bad", x, i) } x = uint64(pbd.F_Int32Repeated[i]) if x != i { t.Error("pbd.F_Int32Repeated bad", x, i) } if pbd.F_BoolRepeated[i] != (i%2 == 0) { t.Error("pbd.F_BoolRepeated bad", x, i) } if pbd.RepeatedField[i] == nil { // TODO: more checking? t.Error("pbd.RepeatedField bad") } } } // Verify we give a useful message when decoding to the wrong structure type. func TestTypeMismatch(t *testing.T) { pb1 := initGoTest(true) // Marshal o := old() o.Marshal(pb1) // Now Unmarshal it to the wrong type. pb2 := initGoTestField() err := o.Unmarshal(pb2) if err == nil { t.Error("expected error, got no error") } else if !strings.Contains(err.Error(), "bad wiretype") { t.Error("expected bad wiretype error, got", err) } } func encodeDecode(t *testing.T, in, out Message, msg string) { buf, err := Marshal(in) if err != nil { t.Fatalf("failed marshaling %v: %v", msg, err) } if err := Unmarshal(buf, out); err != nil { t.Fatalf("failed unmarshaling %v: %v", msg, err) } } func TestPackedNonPackedDecoderSwitching(t *testing.T) { np, p := new(NonPackedTest), new(PackedTest) // non-packed -> packed np.A = []int32{0, 1, 1, 2, 3, 5} encodeDecode(t, np, p, "non-packed -> packed") if !reflect.DeepEqual(np.A, p.B) { t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) } // packed -> non-packed np.Reset() p.B = []int32{3, 1, 4, 1, 5, 9} encodeDecode(t, p, np, "packed -> non-packed") if !reflect.DeepEqual(p.B, np.A) { t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) } } func TestProto1RepeatedGroup(t *testing.T) { pb := &MessageList{ Message: []*MessageList_Message{ { Name: String("blah"), Count: Int32(7), }, // NOTE: pb.Message[1] is a nil nil, }, } o := old() err := o.Marshal(pb) if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { t.Fatalf("unexpected or no error when marshaling: %v", err) } } // Test that enums work. Checks for a bug introduced by making enums // named types instead of int32: newInt32FromUint64 would crash with // a type mismatch in reflect.PointTo. func TestEnum(t *testing.T) { pb := new(GoEnum) pb.Foo = FOO_FOO1.Enum() o := old() if err := o.Marshal(pb); err != nil { t.Fatal("error encoding enum:", err) } pb1 := new(GoEnum) if err := o.Unmarshal(pb1); err != nil { t.Fatal("error decoding enum:", err) } if *pb1.Foo != FOO_FOO1 { t.Error("expected 7 but got ", *pb1.Foo) } } // Enum types have String methods. Check that enum fields can be printed. // We don't care what the value actually is, just as long as it doesn't crash. func TestPrintingNilEnumFields(t *testing.T) { pb := new(GoEnum) _ = fmt.Sprintf("%+v", pb) } // Verify that absent required fields cause Marshal/Unmarshal to return errors. func TestRequiredFieldEnforcement(t *testing.T) { pb := new(GoTestField) _, err := Marshal(pb) if err == nil { t.Error("marshal: expected error, got nil") } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") { t.Errorf("marshal: bad error type: %v", err) } // A slightly sneaky, yet valid, proto. It encodes the same required field twice, // so simply counting the required fields is insufficient. // field 1, encoding 2, value "hi" buf := []byte("\x0A\x02hi\x0A\x02hi") err = Unmarshal(buf, pb) if err == nil { t.Error("unmarshal: expected error, got nil") } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "{Unknown}") { t.Errorf("unmarshal: bad error type: %v", err) } } // Verify that absent required fields in groups cause Marshal/Unmarshal to return errors. func TestRequiredFieldEnforcementGroups(t *testing.T) { pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}} if _, err := Marshal(pb); err == nil { t.Error("marshal: expected error, got nil") } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") { t.Errorf("marshal: bad error type: %v", err) } buf := []byte{11, 12} if err := Unmarshal(buf, pb); err == nil { t.Error("unmarshal: expected error, got nil") } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.{Unknown}") { t.Errorf("unmarshal: bad error type: %v", err) } } func TestTypedNilMarshal(t *testing.T) { // A typed nil should return ErrNil and not crash. { var m *GoEnum if _, err := Marshal(m); err != ErrNil { t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err) } } { m := &Communique{Union: &Communique_Msg{nil}} if _, err := Marshal(m); err == nil || err == ErrNil { t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err) } } } // A type that implements the Marshaler interface, but is not nillable. type nonNillableInt uint64 func (nni nonNillableInt) Marshal() ([]byte, error) { return EncodeVarint(uint64(nni)), nil } type NNIMessage struct { nni nonNillableInt } func (*NNIMessage) Reset() {} func (*NNIMessage) String() string { return "" } func (*NNIMessage) ProtoMessage() {} // A type that implements the Marshaler interface and is nillable. type nillableMessage struct { x uint64 } func (nm *nillableMessage) Marshal() ([]byte, error) { return EncodeVarint(nm.x), nil } type NMMessage struct { nm *nillableMessage } func (*NMMessage) Reset() {} func (*NMMessage) String() string { return "" } func (*NMMessage) ProtoMessage() {} // Verify a type that uses the Marshaler interface, but has a nil pointer. func TestNilMarshaler(t *testing.T) { // Try a struct with a Marshaler field that is nil. // It should be directly marshable. nmm := new(NMMessage) if _, err := Marshal(nmm); err != nil { t.Error("unexpected error marshaling nmm: ", err) } // Try a struct with a Marshaler field that is not nillable. nnim := new(NNIMessage) nnim.nni = 7 var _ Marshaler = nnim.nni // verify it is truly a Marshaler if _, err := Marshal(nnim); err != nil { t.Error("unexpected error marshaling nnim: ", err) } } func TestAllSetDefaults(t *testing.T) { // Exercise SetDefaults with all scalar field types. m := &Defaults{ // NaN != NaN, so override that here. F_Nan: Float32(1.7), } expected := &Defaults{ F_Bool: Bool(true), F_Int32: Int32(32), F_Int64: Int64(64), F_Fixed32: Uint32(320), F_Fixed64: Uint64(640), F_Uint32: Uint32(3200), F_Uint64: Uint64(6400), F_Float: Float32(314159), F_Double: Float64(271828), F_String: String(`hello, "world!"` + "\n"), F_Bytes: []byte("Bignose"), F_Sint32: Int32(-32), F_Sint64: Int64(-64), F_Enum: Defaults_GREEN.Enum(), F_Pinf: Float32(float32(math.Inf(1))), F_Ninf: Float32(float32(math.Inf(-1))), F_Nan: Float32(1.7), StrZero: String(""), } SetDefaults(m) if !Equal(m, expected) { t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) } } func TestSetDefaultsWithSetField(t *testing.T) { // Check that a set value is not overridden. m := &Defaults{ F_Int32: Int32(12), } SetDefaults(m) if v := m.GetF_Int32(); v != 12 { t.Errorf("m.FInt32 = %v, want 12", v) } } func TestSetDefaultsWithSubMessage(t *testing.T) { m := &OtherMessage{ Key: Int64(123), Inner: &InnerMessage{ Host: String("gopher"), }, } expected := &OtherMessage{ Key: Int64(123), Inner: &InnerMessage{ Host: String("gopher"), Port: Int32(4000), }, } SetDefaults(m) if !Equal(m, expected) { t.Errorf("\n got %v\nwant %v", m, expected) } } func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { m := &MyMessage{ RepInner: []*InnerMessage{{}}, } expected := &MyMessage{ RepInner: []*InnerMessage{{ Port: Int32(4000), }}, } SetDefaults(m) if !Equal(m, expected) { t.Errorf("\n got %v\nwant %v", m, expected) } } func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { m := &MyMessage{ Pet: []string{"turtle", "wombat"}, } expected := Clone(m) SetDefaults(m) if !Equal(m, expected) { t.Errorf("\n got %v\nwant %v", m, expected) } } func TestMaximumTagNumber(t *testing.T) { m := &MaxTag{ LastField: String("natural goat essence"), } buf, err := Marshal(m) if err != nil { t.Fatalf("proto.Marshal failed: %v", err) } m2 := new(MaxTag) if err := Unmarshal(buf, m2); err != nil { t.Fatalf("proto.Unmarshal failed: %v", err) } if got, want := m2.GetLastField(), *m.LastField; got != want { t.Errorf("got %q, want %q", got, want) } } func TestJSON(t *testing.T) { m := &MyMessage{ Count: Int32(4), Pet: []string{"bunny", "kitty"}, Inner: &InnerMessage{ Host: String("cauchy"), }, Bikeshed: MyMessage_GREEN.Enum(), } const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` b, err := json.Marshal(m) if err != nil { t.Fatalf("json.Marshal failed: %v", err) } s := string(b) if s != expected { t.Errorf("got %s\nwant %s", s, expected) } received := new(MyMessage) if err := json.Unmarshal(b, received); err != nil { t.Fatalf("json.Unmarshal failed: %v", err) } if !Equal(received, m) { t.Fatalf("got %s, want %s", received, m) } // Test unmarshalling of JSON with symbolic enum name. const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` received.Reset() if err := json.Unmarshal([]byte(old), received); err != nil { t.Fatalf("json.Unmarshal failed: %v", err) } if !Equal(received, m) { t.Fatalf("got %s, want %s", received, m) } } func TestBadWireType(t *testing.T) { b := []byte{7<<3 | 6} // field 7, wire type 6 pb := new(OtherMessage) if err := Unmarshal(b, pb); err == nil { t.Errorf("Unmarshal did not fail") } else if !strings.Contains(err.Error(), "unknown wire type") { t.Errorf("wrong error: %v", err) } } func TestBytesWithInvalidLength(t *testing.T) { // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} Unmarshal(b, new(MyMessage)) } func TestLengthOverflow(t *testing.T) { // Overflowing a length should not panic. b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} Unmarshal(b, new(MyMessage)) } func TestVarintOverflow(t *testing.T) { // Overflowing a 64-bit length should not be allowed. b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} if err := Unmarshal(b, new(MyMessage)); err == nil { t.Fatalf("Overflowed uint64 length without error") } } func TestUnmarshalFuzz(t *testing.T) { const N = 1000 seed := time.Now().UnixNano() t.Logf("RNG seed is %d", seed) rng := rand.New(rand.NewSource(seed)) buf := make([]byte, 20) for i := 0; i < N; i++ { for j := range buf { buf[j] = byte(rng.Intn(256)) } fuzzUnmarshal(t, buf) } } func TestMergeMessages(t *testing.T) { pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} data, err := Marshal(pb) if err != nil { t.Fatalf("Marshal: %v", err) } pb1 := new(MessageList) if err := Unmarshal(data, pb1); err != nil { t.Fatalf("first Unmarshal: %v", err) } if err := Unmarshal(data, pb1); err != nil { t.Fatalf("second Unmarshal: %v", err) } if len(pb1.Message) != 1 { t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) } pb2 := new(MessageList) if err := UnmarshalMerge(data, pb2); err != nil { t.Fatalf("first UnmarshalMerge: %v", err) } if err := UnmarshalMerge(data, pb2); err != nil { t.Fatalf("second UnmarshalMerge: %v", err) } if len(pb2.Message) != 2 { t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) } } func TestExtensionMarshalOrder(t *testing.T) { m := &MyMessage{Count: Int(123)} if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { t.Fatalf("SetExtension: %v", err) } if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { t.Fatalf("SetExtension: %v", err) } if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { t.Fatalf("SetExtension: %v", err) } // Serialize m several times, and check we get the same bytes each time. var orig []byte for i := 0; i < 100; i++ { b, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } if i == 0 { orig = b continue } if !bytes.Equal(b, orig) { t.Errorf("Bytes differ on attempt #%d", i) } } } // Many extensions, because small maps might not iterate differently on each iteration. var exts = []*ExtensionDesc{ E_X201, E_X202, E_X203, E_X204, E_X205, E_X206, E_X207, E_X208, E_X209, E_X210, E_X211, E_X212, E_X213, E_X214, E_X215, E_X216, E_X217, E_X218, E_X219, E_X220, E_X221, E_X222, E_X223, E_X224, E_X225, E_X226, E_X227, E_X228, E_X229, E_X230, E_X231, E_X232, E_X233, E_X234, E_X235, E_X236, E_X237, E_X238, E_X239, E_X240, E_X241, E_X242, E_X243, E_X244, E_X245, E_X246, E_X247, E_X248, E_X249, E_X250, } func TestMessageSetMarshalOrder(t *testing.T) { m := &MyMessageSet{} for _, x := range exts { if err := SetExtension(m, x, &Empty{}); err != nil { t.Fatalf("SetExtension: %v", err) } } buf, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } // Serialize m several times, and check we get the same bytes each time. for i := 0; i < 10; i++ { b1, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } if !bytes.Equal(b1, buf) { t.Errorf("Bytes differ on re-Marshal #%d", i) } m2 := &MyMessageSet{} if err := Unmarshal(buf, m2); err != nil { t.Errorf("Unmarshal: %v", err) } b2, err := Marshal(m2) if err != nil { t.Errorf("re-Marshal: %v", err) } if !bytes.Equal(b2, buf) { t.Errorf("Bytes differ on round-trip #%d", i) } } } func TestUnmarshalMergesMessages(t *testing.T) { // If a nested message occurs twice in the input, // the fields should be merged when decoding. a := &OtherMessage{ Key: Int64(123), Inner: &InnerMessage{ Host: String("polhode"), Port: Int32(1234), }, } aData, err := Marshal(a) if err != nil { t.Fatalf("Marshal(a): %v", err) } b := &OtherMessage{ Weight: Float32(1.2), Inner: &InnerMessage{ Host: String("herpolhode"), Connected: Bool(true), }, } bData, err := Marshal(b) if err != nil { t.Fatalf("Marshal(b): %v", err) } want := &OtherMessage{ Key: Int64(123), Weight: Float32(1.2), Inner: &InnerMessage{ Host: String("herpolhode"), Port: Int32(1234), Connected: Bool(true), }, } got := new(OtherMessage) if err := Unmarshal(append(aData, bData...), got); err != nil { t.Fatalf("Unmarshal: %v", err) } if !Equal(got, want) { t.Errorf("\n got %v\nwant %v", got, want) } } func TestEncodingSizes(t *testing.T) { tests := []struct { m Message n int }{ {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, } for _, test := range tests { b, err := Marshal(test.m) if err != nil { t.Errorf("Marshal(%v): %v", test.m, err) continue } if len(b) != test.n { t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) } } } func TestRequiredNotSetError(t *testing.T) { pb := initGoTest(false) pb.RequiredField.Label = nil pb.F_Int32Required = nil pb.F_Int64Required = nil expected := "0807" + // field 1, encoding 0, value 7 "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) "5001" + // field 10, encoding 0, value 1 "6d20000000" + // field 13, encoding 5, value 0x20 "714000000000000000" + // field 14, encoding 1, value 0x40 "78a019" + // field 15, encoding 0, value 0xca0 = 3232 "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 "8d0100004a45" + // field 17, encoding 5, value 3232.0 "9101000000000040b940" + // field 18, encoding 1, value 6464.0 "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" "b304" + // field 70, encoding 3, start group "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" "b404" + // field 70, encoding 4, end group "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" "b0063f" + // field 102, encoding 0, 0x3f zigzag32 "b8067f" // field 103, encoding 0, 0x7f zigzag64 o := old() bytes, err := Marshal(pb) if _, ok := err.(*RequiredNotSetError); !ok { fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) o.DebugPrint("", bytes) t.Fatalf("expected = %s", expected) } if strings.Index(err.Error(), "RequiredField.Label") < 0 { t.Errorf("marshal-1 wrong err msg: %v", err) } if !equal(bytes, expected, t) { o.DebugPrint("neq 1", bytes) t.Fatalf("expected = %s", expected) } // Now test Unmarshal by recreating the original buffer. pbd := new(GoTest) err = Unmarshal(bytes, pbd) if _, ok := err.(*RequiredNotSetError); !ok { t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) o.DebugPrint("", bytes) t.Fatalf("string = %s", expected) } if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { t.Errorf("unmarshal wrong err msg: %v", err) } bytes, err = Marshal(pbd) if _, ok := err.(*RequiredNotSetError); !ok { t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) o.DebugPrint("", bytes) t.Fatalf("string = %s", expected) } if strings.Index(err.Error(), "RequiredField.Label") < 0 { t.Errorf("marshal-2 wrong err msg: %v", err) } if !equal(bytes, expected, t) { o.DebugPrint("neq 2", bytes) t.Fatalf("string = %s", expected) } } func fuzzUnmarshal(t *testing.T, data []byte) { defer func() { if e := recover(); e != nil { t.Errorf("These bytes caused a panic: %+v", data) t.Logf("Stack:\n%s", debug.Stack()) t.FailNow() } }() pb := new(MyMessage) Unmarshal(data, pb) } func TestMapFieldMarshal(t *testing.T) { m := &MessageWithMap{ NameMapping: map[int32]string{ 1: "Rob", 4: "Ian", 8: "Dave", }, } b, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } // b should be the concatenation of these three byte sequences in some order. parts := []string{ "\n\a\b\x01\x12\x03Rob", "\n\a\b\x04\x12\x03Ian", "\n\b\b\x08\x12\x04Dave", } ok := false for i := range parts { for j := range parts { if j == i { continue } for k := range parts { if k == i || k == j { continue } try := parts[i] + parts[j] + parts[k] if bytes.Equal(b, []byte(try)) { ok = true break } } } } if !ok { t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) } t.Logf("FYI b: %q", b) (new(Buffer)).DebugPrint("Dump of b", b) } func TestMapFieldRoundTrips(t *testing.T) { m := &MessageWithMap{ NameMapping: map[int32]string{ 1: "Rob", 4: "Ian", 8: "Dave", }, MsgMapping: map[int64]*FloatingPoint{ 0x7001: &FloatingPoint{F: Float64(2.0)}, }, ByteMapping: map[bool][]byte{ false: []byte("that's not right!"), true: []byte("aye, 'tis true!"), }, } b, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } t.Logf("FYI b: %q", b) m2 := new(MessageWithMap) if err := Unmarshal(b, m2); err != nil { t.Fatalf("Unmarshal: %v", err) } for _, pair := range [][2]interface{}{ {m.NameMapping, m2.NameMapping}, {m.MsgMapping, m2.MsgMapping}, {m.ByteMapping, m2.ByteMapping}, } { if !reflect.DeepEqual(pair[0], pair[1]) { t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) } } } func TestMapFieldWithNil(t *testing.T) { m1 := &MessageWithMap{ MsgMapping: map[int64]*FloatingPoint{ 1: nil, }, } b, err := Marshal(m1) if err != nil { t.Fatalf("Marshal: %v", err) } m2 := new(MessageWithMap) if err := Unmarshal(b, m2); err != nil { t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) } if v, ok := m2.MsgMapping[1]; !ok { t.Error("msg_mapping[1] not present") } else if v != nil { t.Errorf("msg_mapping[1] not nil: %v", v) } } func TestMapFieldWithNilBytes(t *testing.T) { m1 := &MessageWithMap{ ByteMapping: map[bool][]byte{ false: []byte{}, true: nil, }, } n := Size(m1) b, err := Marshal(m1) if err != nil { t.Fatalf("Marshal: %v", err) } if n != len(b) { t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b)) } m2 := new(MessageWithMap) if err := Unmarshal(b, m2); err != nil { t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) } if v, ok := m2.ByteMapping[false]; !ok { t.Error("byte_mapping[false] not present") } else if len(v) != 0 { t.Errorf("byte_mapping[false] not empty: %#v", v) } if v, ok := m2.ByteMapping[true]; !ok { t.Error("byte_mapping[true] not present") } else if len(v) != 0 { t.Errorf("byte_mapping[true] not empty: %#v", v) } } func TestDecodeMapFieldMissingKey(t *testing.T) { b := []byte{ 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes // no key 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m" } got := &MessageWithMap{} err := Unmarshal(b, got) if err != nil { t.Fatalf("failed to marshal map with missing key: %v", err) } want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}} if !Equal(got, want) { t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want) } } func TestDecodeMapFieldMissingValue(t *testing.T) { b := []byte{ 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes 0x08, 0x01, // varint key, value 1 // no value } got := &MessageWithMap{} err := Unmarshal(b, got) if err != nil { t.Fatalf("failed to marshal map with missing value: %v", err) } want := &MessageWithMap{NameMapping: map[int32]string{1: ""}} if !Equal(got, want) { t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want) } } func TestOneof(t *testing.T) { m := &Communique{} b, err := Marshal(m) if err != nil { t.Fatalf("Marshal of empty message with oneof: %v", err) } if len(b) != 0 { t.Errorf("Marshal of empty message yielded too many bytes: %v", b) } m = &Communique{ Union: &Communique_Name{"Barry"}, } // Round-trip. b, err = Marshal(m) if err != nil { t.Fatalf("Marshal of message with oneof: %v", err) } if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5) t.Errorf("Incorrect marshal of message with oneof: %v", b) } m.Reset() if err := Unmarshal(b, m); err != nil { t.Fatalf("Unmarshal of message with oneof: %v", err) } if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" { t.Errorf("After round trip, Union = %+v", m.Union) } if name := m.GetName(); name != "Barry" { t.Errorf("After round trip, GetName = %q, want %q", name, "Barry") } // Let's try with a message in the oneof. m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}} b, err = Marshal(m) if err != nil { t.Fatalf("Marshal of message with oneof set to message: %v", err) } if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16) t.Errorf("Incorrect marshal of message with oneof set to message: %v", b) } m.Reset() if err := Unmarshal(b, m); err != nil { t.Fatalf("Unmarshal of message with oneof set to message: %v", err) } ss, ok := m.Union.(*Communique_Msg) if !ok || ss.Msg.GetStringField() != "deep deep string" { t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union) } } func TestInefficientPackedBool(t *testing.T) { // https://github.com/golang/protobuf/issues/76 inp := []byte{ 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes // Usually a bool should take a single byte, // but it is permitted to be any varint. 0xb9, 0x30, } if err := Unmarshal(inp, new(MoreRepeated)); err != nil { t.Error(err) } } // Benchmarks func testMsg() *GoTest { pb := initGoTest(true) const N = 1000 // Internally the library starts much smaller. pb.F_Int32Repeated = make([]int32, N) pb.F_DoubleRepeated = make([]float64, N) for i := 0; i < N; i++ { pb.F_Int32Repeated[i] = int32(i) pb.F_DoubleRepeated[i] = float64(i) } return pb } func bytesMsg() *GoTest { pb := initGoTest(true) buf := make([]byte, 4000) for i := range buf { buf[i] = byte(i) } pb.F_BytesDefaulted = buf return pb } func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { d, _ := marshal(pb) b.SetBytes(int64(len(d))) b.ResetTimer() for i := 0; i < b.N; i++ { marshal(pb) } } func benchmarkBufferMarshal(b *testing.B, pb Message) { p := NewBuffer(nil) benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { p.Reset() err := p.Marshal(pb0) return p.Bytes(), err }) } func benchmarkSize(b *testing.B, pb Message) { benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { Size(pb) return nil, nil }) } func newOf(pb Message) Message { in := reflect.ValueOf(pb) if in.IsNil() { return pb } return reflect.New(in.Type().Elem()).Interface().(Message) } func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { d, _ := Marshal(pb) b.SetBytes(int64(len(d))) pbd := newOf(pb) b.ResetTimer() for i := 0; i < b.N; i++ { unmarshal(d, pbd) } } func benchmarkBufferUnmarshal(b *testing.B, pb Message) { p := NewBuffer(nil) benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { p.SetBuf(d) return p.Unmarshal(pb0) }) } // Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} func BenchmarkMarshal(b *testing.B) { benchmarkMarshal(b, testMsg(), Marshal) } func BenchmarkBufferMarshal(b *testing.B) { benchmarkBufferMarshal(b, testMsg()) } func BenchmarkSize(b *testing.B) { benchmarkSize(b, testMsg()) } func BenchmarkUnmarshal(b *testing.B) { benchmarkUnmarshal(b, testMsg(), Unmarshal) } func BenchmarkBufferUnmarshal(b *testing.B) { benchmarkBufferUnmarshal(b, testMsg()) } func BenchmarkMarshalBytes(b *testing.B) { benchmarkMarshal(b, bytesMsg(), Marshal) } func BenchmarkBufferMarshalBytes(b *testing.B) { benchmarkBufferMarshal(b, bytesMsg()) } func BenchmarkSizeBytes(b *testing.B) { benchmarkSize(b, bytesMsg()) } func BenchmarkUnmarshalBytes(b *testing.B) { benchmarkUnmarshal(b, bytesMsg(), Unmarshal) } func BenchmarkBufferUnmarshalBytes(b *testing.B) { benchmarkBufferUnmarshal(b, bytesMsg()) } func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { b.StopTimer() pb := initGoTestField() skip := &GoSkipTest{ SkipInt32: Int32(32), SkipFixed32: Uint32(3232), SkipFixed64: Uint64(6464), SkipString: String("skipper"), Skipgroup: &GoSkipTest_SkipGroup{ GroupInt32: Int32(75), GroupString: String("wxyz"), }, } pbd := new(GoTestField) p := NewBuffer(nil) p.Marshal(pb) p.Marshal(skip) p2 := NewBuffer(nil) b.StartTimer() for i := 0; i < b.N; i++ { p2.SetBuf(p.Bytes()) p2.Unmarshal(pbd) } } ================================================ FILE: src/github.com/golang/protobuf/proto/any_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto_test import ( "strings" "testing" "github.com/golang/protobuf/proto" pb "github.com/golang/protobuf/proto/proto3_proto" testpb "github.com/golang/protobuf/proto/testdata" anypb "github.com/golang/protobuf/ptypes/any" ) var ( expandedMarshaler = proto.TextMarshaler{ExpandAny: true} expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true} ) // anyEqual reports whether two messages which may be google.protobuf.Any or may // contain google.protobuf.Any fields are equal. We can't use proto.Equal for // comparison, because semantically equivalent messages may be marshaled to // binary in different tag order. Instead, trust that TextMarshaler with // ExpandAny option works and compare the text marshaling results. func anyEqual(got, want proto.Message) bool { // if messages are proto.Equal, no need to marshal. if proto.Equal(got, want) { return true } g := expandedMarshaler.Text(got) w := expandedMarshaler.Text(want) return g == w } type golden struct { m proto.Message t, c string } var goldenMessages = makeGolden() func makeGolden() []golden { nested := &pb.Nested{Bunny: "Monty"} nb, err := proto.Marshal(nested) if err != nil { panic(err) } m1 := &pb.Message{ Name: "David", ResultCount: 47, Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}, } m2 := &pb.Message{ Name: "David", ResultCount: 47, Anything: &anypb.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb}, } m3 := &pb.Message{ Name: "David", ResultCount: 47, Anything: &anypb.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb}, } m4 := &pb.Message{ Name: "David", ResultCount: 47, Anything: &anypb.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb}, } m5 := &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb} any1 := &testpb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")} proto.SetExtension(any1, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("foo")}) proto.SetExtension(any1, testpb.E_Ext_Text, proto.String("bar")) any1b, err := proto.Marshal(any1) if err != nil { panic(err) } any2 := &testpb.MyMessage{Count: proto.Int32(42), Bikeshed: testpb.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}} proto.SetExtension(any2, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("baz")}) any2b, err := proto.Marshal(any2) if err != nil { panic(err) } m6 := &pb.Message{ Name: "David", ResultCount: 47, Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, ManyThings: []*anypb.Any{ &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b}, &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, }, } const ( m1Golden = ` name: "David" result_count: 47 anything: < [type.googleapis.com/proto3_proto.Nested]: < bunny: "Monty" > > ` m2Golden = ` name: "David" result_count: 47 anything: < ["http://[::1]/type.googleapis.com/proto3_proto.Nested"]: < bunny: "Monty" > > ` m3Golden = ` name: "David" result_count: 47 anything: < ["type.googleapis.com/\"/proto3_proto.Nested"]: < bunny: "Monty" > > ` m4Golden = ` name: "David" result_count: 47 anything: < [type.googleapis.com/a/path/proto3_proto.Nested]: < bunny: "Monty" > > ` m5Golden = ` [type.googleapis.com/proto3_proto.Nested]: < bunny: "Monty" > ` m6Golden = ` name: "David" result_count: 47 anything: < [type.googleapis.com/testdata.MyMessage]: < count: 47 name: "David" [testdata.Ext.more]: < data: "foo" > [testdata.Ext.text]: "bar" > > many_things: < [type.googleapis.com/testdata.MyMessage]: < count: 42 bikeshed: GREEN rep_bytes: "roboto" [testdata.Ext.more]: < data: "baz" > > > many_things: < [type.googleapis.com/testdata.MyMessage]: < count: 47 name: "David" [testdata.Ext.more]: < data: "foo" > [testdata.Ext.text]: "bar" > > ` ) return []golden{ {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "}, {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "}, {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "}, {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "}, {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "}, {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "}, } } func TestMarshalGolden(t *testing.T) { for _, tt := range goldenMessages { if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want { t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want) } if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want { t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want) } } } func TestUnmarshalGolden(t *testing.T) { for _, tt := range goldenMessages { want := tt.m got := proto.Clone(tt.m) got.Reset() if err := proto.UnmarshalText(tt.t, got); err != nil { t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err) } if !anyEqual(got, want) { t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want) } got.Reset() if err := proto.UnmarshalText(tt.c, got); err != nil { t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err) } if !anyEqual(got, want) { t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want) } } } func TestMarshalUnknownAny(t *testing.T) { m := &pb.Message{ Anything: &anypb.Any{ TypeUrl: "foo", Value: []byte("bar"), }, } want := `anything: < type_url: "foo" value: "bar" > ` got := expandedMarshaler.Text(m) if got != want { t.Errorf("got\n`%s`\nwant\n`%s`", got, want) } } func TestAmbiguousAny(t *testing.T) { pb := &anypb.Any{} err := proto.UnmarshalText(` type_url: "ttt/proto3_proto.Nested" value: "\n\x05Monty" `, pb) t.Logf("result: %v (error: %v)", expandedMarshaler.Text(pb), err) if err != nil { t.Errorf("failed to parse ambiguous Any message: %v", err) } } func TestUnmarshalOverwriteAny(t *testing.T) { pb := &anypb.Any{} err := proto.UnmarshalText(` [type.googleapis.com/a/path/proto3_proto.Nested]: < bunny: "Monty" > [type.googleapis.com/a/path/proto3_proto.Nested]: < bunny: "Rabbit of Caerbannog" > `, pb) want := `line 7: Any message unpacked multiple times, or "type_url" already set` if err.Error() != want { t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) } } func TestUnmarshalAnyMixAndMatch(t *testing.T) { pb := &anypb.Any{} err := proto.UnmarshalText(` value: "\n\x05Monty" [type.googleapis.com/a/path/proto3_proto.Nested]: < bunny: "Rabbit of Caerbannog" > `, pb) want := `line 5: Any message unpacked multiple times, or "value" already set` if err.Error() != want { t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) } } ================================================ FILE: src/github.com/golang/protobuf/proto/clone.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/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. // Protocol buffer deep copy and merge. // TODO: RawMessage. package proto import ( "log" "reflect" "strings" ) // Clone returns a deep copy of a protocol buffer. func Clone(pb Message) Message { in := reflect.ValueOf(pb) if in.IsNil() { return pb } out := reflect.New(in.Type().Elem()) // out is empty so a merge is a deep copy. mergeStruct(out.Elem(), in.Elem()) return out.Interface().(Message) } // Merge merges src into dst. // Required and optional fields that are set in src will be set to that value in dst. // Elements of repeated fields will be appended. // Merge panics if src and dst are not the same type, or if dst is nil. func Merge(dst, src Message) { in := reflect.ValueOf(src) out := reflect.ValueOf(dst) if out.IsNil() { panic("proto: nil destination") } if in.Type() != out.Type() { // Explicit test prior to mergeStruct so that mistyped nils will fail panic("proto: type mismatch") } if in.IsNil() { // Merging nil into non-nil is a quiet no-op return } mergeStruct(out.Elem(), in.Elem()) } func mergeStruct(out, in reflect.Value) { sprop := GetProperties(in.Type()) for i := 0; i < in.NumField(); i++ { f := in.Type().Field(i) if strings.HasPrefix(f.Name, "XXX_") { continue } mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) } if emIn, ok := extendable(in.Addr().Interface()); ok { emOut, _ := extendable(out.Addr().Interface()) mIn, muIn := emIn.extensionsRead() if mIn != nil { mOut := emOut.extensionsWrite() muIn.Lock() mergeExtension(mOut, mIn) muIn.Unlock() } } uf := in.FieldByName("XXX_unrecognized") if !uf.IsValid() { return } uin := uf.Bytes() if len(uin) > 0 { out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) } } // mergeAny performs a merge between two values of the same type. // viaPtr indicates whether the values were indirected through a pointer (implying proto2). // prop is set if this is a struct field (it may be nil). func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { if in.Type() == protoMessageType { if !in.IsNil() { if out.IsNil() { out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) } else { Merge(out.Interface().(Message), in.Interface().(Message)) } } return } switch in.Kind() { case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64: if !viaPtr && isProto3Zero(in) { return } out.Set(in) case reflect.Interface: // Probably a oneof field; copy non-nil values. if in.IsNil() { return } // Allocate destination if it is not set, or set to a different type. // Otherwise we will merge as normal. if out.IsNil() || out.Elem().Type() != in.Elem().Type() { out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) } mergeAny(out.Elem(), in.Elem(), false, nil) case reflect.Map: if in.Len() == 0 { return } if out.IsNil() { out.Set(reflect.MakeMap(in.Type())) } // For maps with value types of *T or []byte we need to deep copy each value. elemKind := in.Type().Elem().Kind() for _, key := range in.MapKeys() { var val reflect.Value switch elemKind { case reflect.Ptr: val = reflect.New(in.Type().Elem().Elem()) mergeAny(val, in.MapIndex(key), false, nil) case reflect.Slice: val = in.MapIndex(key) val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) default: val = in.MapIndex(key) } out.SetMapIndex(key, val) } case reflect.Ptr: if in.IsNil() { return } if out.IsNil() { out.Set(reflect.New(in.Elem().Type())) } mergeAny(out.Elem(), in.Elem(), true, nil) case reflect.Slice: if in.IsNil() { return } if in.Type().Elem().Kind() == reflect.Uint8 { // []byte is a scalar bytes field, not a repeated field. // Edge case: if this is in a proto3 message, a zero length // bytes field is considered the zero value, and should not // be merged. if prop != nil && prop.proto3 && in.Len() == 0 { return } // Make a deep copy. // Append to []byte{} instead of []byte(nil) so that we never end up // with a nil result. out.SetBytes(append([]byte{}, in.Bytes()...)) return } n := in.Len() if out.IsNil() { out.Set(reflect.MakeSlice(in.Type(), 0, n)) } switch in.Type().Elem().Kind() { case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64: out.Set(reflect.AppendSlice(out, in)) default: for i := 0; i < n; i++ { x := reflect.Indirect(reflect.New(in.Type().Elem())) mergeAny(x, in.Index(i), false, nil) out.Set(reflect.Append(out, x)) } } case reflect.Struct: mergeStruct(out, in) default: // unknown type, so not a protocol buffer log.Printf("proto: don't know how to copy %v", in) } } func mergeExtension(out, in map[int32]Extension) { for extNum, eIn := range in { eOut := Extension{desc: eIn.desc} if eIn.value != nil { v := reflect.New(reflect.TypeOf(eIn.value)).Elem() mergeAny(v, reflect.ValueOf(eIn.value), false, nil) eOut.value = v.Interface() } if eIn.enc != nil { eOut.enc = make([]byte, len(eIn.enc)) copy(eOut.enc, eIn.enc) } out[extNum] = eOut } } ================================================ FILE: src/github.com/golang/protobuf/proto/clone_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto_test import ( "testing" "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" pb "github.com/golang/protobuf/proto/testdata" ) var cloneTestMessage = &pb.MyMessage{ Count: proto.Int32(42), Name: proto.String("Dave"), Pet: []string{"bunny", "kitty", "horsey"}, Inner: &pb.InnerMessage{ Host: proto.String("niles"), Port: proto.Int32(9099), Connected: proto.Bool(true), }, Others: []*pb.OtherMessage{ { Value: []byte("some bytes"), }, }, Somegroup: &pb.MyMessage_SomeGroup{ GroupField: proto.Int32(6), }, RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, } func init() { ext := &pb.Ext{ Data: proto.String("extension"), } if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { panic("SetExtension: " + err.Error()) } } func TestClone(t *testing.T) { m := proto.Clone(cloneTestMessage).(*pb.MyMessage) if !proto.Equal(m, cloneTestMessage) { t.Errorf("Clone(%v) = %v", cloneTestMessage, m) } // Verify it was a deep copy. *m.Inner.Port++ if proto.Equal(m, cloneTestMessage) { t.Error("Mutating clone changed the original") } // Byte fields and repeated fields should be copied. if &m.Pet[0] == &cloneTestMessage.Pet[0] { t.Error("Pet: repeated field not copied") } if &m.Others[0] == &cloneTestMessage.Others[0] { t.Error("Others: repeated field not copied") } if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { t.Error("Others[0].Value: bytes field not copied") } if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { t.Error("RepBytes: repeated field not copied") } if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { t.Error("RepBytes[0]: bytes field not copied") } } func TestCloneNil(t *testing.T) { var m *pb.MyMessage if c := proto.Clone(m); !proto.Equal(m, c) { t.Errorf("Clone(%v) = %v", m, c) } } var mergeTests = []struct { src, dst, want proto.Message }{ { src: &pb.MyMessage{ Count: proto.Int32(42), }, dst: &pb.MyMessage{ Name: proto.String("Dave"), }, want: &pb.MyMessage{ Count: proto.Int32(42), Name: proto.String("Dave"), }, }, { src: &pb.MyMessage{ Inner: &pb.InnerMessage{ Host: proto.String("hey"), Connected: proto.Bool(true), }, Pet: []string{"horsey"}, Others: []*pb.OtherMessage{ { Value: []byte("some bytes"), }, }, }, dst: &pb.MyMessage{ Inner: &pb.InnerMessage{ Host: proto.String("niles"), Port: proto.Int32(9099), }, Pet: []string{"bunny", "kitty"}, Others: []*pb.OtherMessage{ { Key: proto.Int64(31415926535), }, { // Explicitly test a src=nil field Inner: nil, }, }, }, want: &pb.MyMessage{ Inner: &pb.InnerMessage{ Host: proto.String("hey"), Connected: proto.Bool(true), Port: proto.Int32(9099), }, Pet: []string{"bunny", "kitty", "horsey"}, Others: []*pb.OtherMessage{ { Key: proto.Int64(31415926535), }, {}, { Value: []byte("some bytes"), }, }, }, }, { src: &pb.MyMessage{ RepBytes: [][]byte{[]byte("wow")}, }, dst: &pb.MyMessage{ Somegroup: &pb.MyMessage_SomeGroup{ GroupField: proto.Int32(6), }, RepBytes: [][]byte{[]byte("sham")}, }, want: &pb.MyMessage{ Somegroup: &pb.MyMessage_SomeGroup{ GroupField: proto.Int32(6), }, RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, }, }, // Check that a scalar bytes field replaces rather than appends. { src: &pb.OtherMessage{Value: []byte("foo")}, dst: &pb.OtherMessage{Value: []byte("bar")}, want: &pb.OtherMessage{Value: []byte("foo")}, }, { src: &pb.MessageWithMap{ NameMapping: map[int32]string{6: "Nigel"}, MsgMapping: map[int64]*pb.FloatingPoint{ 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, 0x4002: &pb.FloatingPoint{ F: proto.Float64(2.0), }, }, ByteMapping: map[bool][]byte{true: []byte("wowsa")}, }, dst: &pb.MessageWithMap{ NameMapping: map[int32]string{ 6: "Bruce", // should be overwritten 7: "Andrew", }, MsgMapping: map[int64]*pb.FloatingPoint{ 0x4002: &pb.FloatingPoint{ F: proto.Float64(3.0), Exact: proto.Bool(true), }, // the entire message should be overwritten }, }, want: &pb.MessageWithMap{ NameMapping: map[int32]string{ 6: "Nigel", 7: "Andrew", }, MsgMapping: map[int64]*pb.FloatingPoint{ 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, 0x4002: &pb.FloatingPoint{ F: proto.Float64(2.0), }, }, ByteMapping: map[bool][]byte{true: []byte("wowsa")}, }, }, // proto3 shouldn't merge zero values, // in the same way that proto2 shouldn't merge nils. { src: &proto3pb.Message{ Name: "Aaron", Data: []byte(""), // zero value, but not nil }, dst: &proto3pb.Message{ HeightInCm: 176, Data: []byte("texas!"), }, want: &proto3pb.Message{ Name: "Aaron", HeightInCm: 176, Data: []byte("texas!"), }, }, // Oneof fields should merge by assignment. { src: &pb.Communique{ Union: &pb.Communique_Number{41}, }, dst: &pb.Communique{ Union: &pb.Communique_Name{"Bobby Tables"}, }, want: &pb.Communique{ Union: &pb.Communique_Number{41}, }, }, // Oneof nil is the same as not set. { src: &pb.Communique{}, dst: &pb.Communique{ Union: &pb.Communique_Name{"Bobby Tables"}, }, want: &pb.Communique{ Union: &pb.Communique_Name{"Bobby Tables"}, }, }, { src: &proto3pb.Message{ Terrain: map[string]*proto3pb.Nested{ "kay_a": &proto3pb.Nested{Cute: true}, // replace "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, // insert }, }, dst: &proto3pb.Message{ Terrain: map[string]*proto3pb.Nested{ "kay_a": &proto3pb.Nested{Bunny: "lost"}, // replaced "kay_c": &proto3pb.Nested{Bunny: "bunny"}, // keep }, }, want: &proto3pb.Message{ Terrain: map[string]*proto3pb.Nested{ "kay_a": &proto3pb.Nested{Cute: true}, "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, "kay_c": &proto3pb.Nested{Bunny: "bunny"}, }, }, }, } func TestMerge(t *testing.T) { for _, m := range mergeTests { got := proto.Clone(m.dst) proto.Merge(got, m.src) if !proto.Equal(got, m.want) { t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) } } } ================================================ FILE: src/github.com/golang/protobuf/proto/decode.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto /* * Routines for decoding protocol buffer data to construct in-memory representations. */ import ( "errors" "fmt" "io" "os" "reflect" ) // errOverflow is returned when an integer is too large to be represented. var errOverflow = errors.New("proto: integer overflow") // ErrInternalBadWireType is returned by generated code when an incorrect // wire type is encountered. It does not get returned to user code. var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") // The fundamental decoders that interpret bytes on the wire. // Those that take integer types all return uint64 and are // therefore of type valueDecoder. // DecodeVarint reads a varint-encoded integer from the slice. // It returns the integer and the number of bytes consumed, or // zero if there is not enough. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. func DecodeVarint(buf []byte) (x uint64, n int) { for shift := uint(0); shift < 64; shift += 7 { if n >= len(buf) { return 0, 0 } b := uint64(buf[n]) n++ x |= (b & 0x7F) << shift if (b & 0x80) == 0 { return x, n } } // The number is too large to represent in a 64-bit value. return 0, 0 } func (p *Buffer) decodeVarintSlow() (x uint64, err error) { i := p.index l := len(p.buf) for shift := uint(0); shift < 64; shift += 7 { if i >= l { err = io.ErrUnexpectedEOF return } b := p.buf[i] i++ x |= (uint64(b) & 0x7F) << shift if b < 0x80 { p.index = i return } } // The number is too large to represent in a 64-bit value. err = errOverflow return } // DecodeVarint reads a varint-encoded integer from the Buffer. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. func (p *Buffer) DecodeVarint() (x uint64, err error) { i := p.index buf := p.buf if i >= len(buf) { return 0, io.ErrUnexpectedEOF } else if buf[i] < 0x80 { p.index++ return uint64(buf[i]), nil } else if len(buf)-i < 10 { return p.decodeVarintSlow() } var b uint64 // we already checked the first byte x = uint64(buf[i]) - 0x80 i++ b = uint64(buf[i]) i++ x += b << 7 if b&0x80 == 0 { goto done } x -= 0x80 << 7 b = uint64(buf[i]) i++ x += b << 14 if b&0x80 == 0 { goto done } x -= 0x80 << 14 b = uint64(buf[i]) i++ x += b << 21 if b&0x80 == 0 { goto done } x -= 0x80 << 21 b = uint64(buf[i]) i++ x += b << 28 if b&0x80 == 0 { goto done } x -= 0x80 << 28 b = uint64(buf[i]) i++ x += b << 35 if b&0x80 == 0 { goto done } x -= 0x80 << 35 b = uint64(buf[i]) i++ x += b << 42 if b&0x80 == 0 { goto done } x -= 0x80 << 42 b = uint64(buf[i]) i++ x += b << 49 if b&0x80 == 0 { goto done } x -= 0x80 << 49 b = uint64(buf[i]) i++ x += b << 56 if b&0x80 == 0 { goto done } x -= 0x80 << 56 b = uint64(buf[i]) i++ x += b << 63 if b&0x80 == 0 { goto done } // x -= 0x80 << 63 // Always zero. return 0, errOverflow done: p.index = i return x, nil } // DecodeFixed64 reads a 64-bit integer from the Buffer. // This is the format for the // fixed64, sfixed64, and double protocol buffer types. func (p *Buffer) DecodeFixed64() (x uint64, err error) { // x, err already 0 i := p.index + 8 if i < 0 || i > len(p.buf) { err = io.ErrUnexpectedEOF return } p.index = i x = uint64(p.buf[i-8]) x |= uint64(p.buf[i-7]) << 8 x |= uint64(p.buf[i-6]) << 16 x |= uint64(p.buf[i-5]) << 24 x |= uint64(p.buf[i-4]) << 32 x |= uint64(p.buf[i-3]) << 40 x |= uint64(p.buf[i-2]) << 48 x |= uint64(p.buf[i-1]) << 56 return } // DecodeFixed32 reads a 32-bit integer from the Buffer. // This is the format for the // fixed32, sfixed32, and float protocol buffer types. func (p *Buffer) DecodeFixed32() (x uint64, err error) { // x, err already 0 i := p.index + 4 if i < 0 || i > len(p.buf) { err = io.ErrUnexpectedEOF return } p.index = i x = uint64(p.buf[i-4]) x |= uint64(p.buf[i-3]) << 8 x |= uint64(p.buf[i-2]) << 16 x |= uint64(p.buf[i-1]) << 24 return } // DecodeZigzag64 reads a zigzag-encoded 64-bit integer // from the Buffer. // This is the format used for the sint64 protocol buffer type. func (p *Buffer) DecodeZigzag64() (x uint64, err error) { x, err = p.DecodeVarint() if err != nil { return } x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) return } // DecodeZigzag32 reads a zigzag-encoded 32-bit integer // from the Buffer. // This is the format used for the sint32 protocol buffer type. func (p *Buffer) DecodeZigzag32() (x uint64, err error) { x, err = p.DecodeVarint() if err != nil { return } x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) return } // These are not ValueDecoders: they produce an array of bytes or a string. // bytes, embedded messages // DecodeRawBytes reads a count-delimited byte buffer from the Buffer. // This is the format used for the bytes protocol buffer // type and for embedded messages. func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { n, err := p.DecodeVarint() if err != nil { return nil, err } nb := int(n) if nb < 0 { return nil, fmt.Errorf("proto: bad byte length %d", nb) } end := p.index + nb if end < p.index || end > len(p.buf) { return nil, io.ErrUnexpectedEOF } if !alloc { // todo: check if can get more uses of alloc=false buf = p.buf[p.index:end] p.index += nb return } buf = make([]byte, nb) copy(buf, p.buf[p.index:]) p.index += nb return } // DecodeStringBytes reads an encoded string from the Buffer. // This is the format used for the proto2 string type. func (p *Buffer) DecodeStringBytes() (s string, err error) { buf, err := p.DecodeRawBytes(false) if err != nil { return } return string(buf), nil } // Skip the next item in the buffer. Its wire type is decoded and presented as an argument. // If the protocol buffer has extensions, and the field matches, add it as an extension. // Otherwise, if the XXX_unrecognized field exists, append the skipped data there. func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error { oi := o.index err := o.skip(t, tag, wire) if err != nil { return err } if !unrecField.IsValid() { return nil } ptr := structPointer_Bytes(base, unrecField) // Add the skipped field to struct field obuf := o.buf o.buf = *ptr o.EncodeVarint(uint64(tag<<3 | wire)) *ptr = append(o.buf, obuf[oi:o.index]...) o.buf = obuf return nil } // Skip the next item in the buffer. Its wire type is decoded and presented as an argument. func (o *Buffer) skip(t reflect.Type, tag, wire int) error { var u uint64 var err error switch wire { case WireVarint: _, err = o.DecodeVarint() case WireFixed64: _, err = o.DecodeFixed64() case WireBytes: _, err = o.DecodeRawBytes(false) case WireFixed32: _, err = o.DecodeFixed32() case WireStartGroup: for { u, err = o.DecodeVarint() if err != nil { break } fwire := int(u & 0x7) if fwire == WireEndGroup { break } ftag := int(u >> 3) err = o.skip(t, ftag, fwire) if err != nil { break } } default: err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t) } return err } // Unmarshaler is the interface representing objects that can // unmarshal themselves. The method should reset the receiver before // decoding starts. The argument points to data that may be // overwritten, so implementations should not keep references to the // buffer. type Unmarshaler interface { Unmarshal([]byte) error } // Unmarshal parses the protocol buffer representation in buf and places the // decoded result in pb. If the struct underlying pb does not match // the data in buf, the results can be unpredictable. // // Unmarshal resets pb before starting to unmarshal, so any // existing data in pb is always removed. Use UnmarshalMerge // to preserve and append to existing data. func Unmarshal(buf []byte, pb Message) error { pb.Reset() return UnmarshalMerge(buf, pb) } // UnmarshalMerge parses the protocol buffer representation in buf and // writes the decoded result to pb. If the struct underlying pb does not match // the data in buf, the results can be unpredictable. // // UnmarshalMerge merges into existing data in pb. // Most code should use Unmarshal instead. func UnmarshalMerge(buf []byte, pb Message) error { // If the object can unmarshal itself, let it. if u, ok := pb.(Unmarshaler); ok { return u.Unmarshal(buf) } return NewBuffer(buf).Unmarshal(pb) } // DecodeMessage reads a count-delimited message from the Buffer. func (p *Buffer) DecodeMessage(pb Message) error { enc, err := p.DecodeRawBytes(false) if err != nil { return err } return NewBuffer(enc).Unmarshal(pb) } // DecodeGroup reads a tag-delimited group from the Buffer. func (p *Buffer) DecodeGroup(pb Message) error { typ, base, err := getbase(pb) if err != nil { return err } return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), true, base) } // Unmarshal parses the protocol buffer representation in the // Buffer and places the decoded result in pb. If the struct // underlying pb does not match the data in the buffer, the results can be // unpredictable. // // Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. func (p *Buffer) Unmarshal(pb Message) error { // If the object can unmarshal itself, let it. if u, ok := pb.(Unmarshaler); ok { err := u.Unmarshal(p.buf[p.index:]) p.index = len(p.buf) return err } typ, base, err := getbase(pb) if err != nil { return err } err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base) if collectStats { stats.Decode++ } return err } // unmarshalType does the work of unmarshaling a structure. func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error { var state errorState required, reqFields := prop.reqCount, uint64(0) var err error for err == nil && o.index < len(o.buf) { oi := o.index var u uint64 u, err = o.DecodeVarint() if err != nil { break } wire := int(u & 0x7) if wire == WireEndGroup { if is_group { if required > 0 { // Not enough information to determine the exact field. // (See below.) return &RequiredNotSetError{"{Unknown}"} } return nil // input is satisfied } return fmt.Errorf("proto: %s: wiretype end group for non-group", st) } tag := int(u >> 3) if tag <= 0 { return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire) } fieldnum, ok := prop.decoderTags.get(tag) if !ok { // Maybe it's an extension? if prop.extendable { if e, _ := extendable(structPointer_Interface(base, st)); isExtensionField(e, int32(tag)) { if err = o.skip(st, tag, wire); err == nil { extmap := e.extensionsWrite() ext := extmap[int32(tag)] // may be missing ext.enc = append(ext.enc, o.buf[oi:o.index]...) extmap[int32(tag)] = ext } continue } } // Maybe it's a oneof? if prop.oneofUnmarshaler != nil { m := structPointer_Interface(base, st).(Message) // First return value indicates whether tag is a oneof field. ok, err = prop.oneofUnmarshaler(m, tag, wire, o) if err == ErrInternalBadWireType { // Map the error to something more descriptive. // Do the formatting here to save generated code space. err = fmt.Errorf("bad wiretype for oneof field in %T", m) } if ok { continue } } err = o.skipAndSave(st, tag, wire, base, prop.unrecField) continue } p := prop.Prop[fieldnum] if p.dec == nil { fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name) continue } dec := p.dec if wire != WireStartGroup && wire != p.WireType { if wire == WireBytes && p.packedDec != nil { // a packable field dec = p.packedDec } else { err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType) continue } } decErr := dec(o, p, base) if decErr != nil && !state.shouldContinue(decErr, p) { err = decErr } if err == nil && p.Required { // Successfully decoded a required field. if tag <= 64 { // use bitmap for fields 1-64 to catch field reuse. var mask uint64 = 1 << uint64(tag-1) if reqFields&mask == 0 { // new required field reqFields |= mask required-- } } else { // This is imprecise. It can be fooled by a required field // with a tag > 64 that is encoded twice; that's very rare. // A fully correct implementation would require allocating // a data structure, which we would like to avoid. required-- } } } if err == nil { if is_group { return io.ErrUnexpectedEOF } if state.err != nil { return state.err } if required > 0 { // Not enough information to determine the exact field. If we use extra // CPU, we could determine the field only if the missing required field // has a tag <= 64 and we check reqFields. return &RequiredNotSetError{"{Unknown}"} } } return err } // Individual type decoders // For each, // u is the decoded value, // v is a pointer to the field (pointer) in the struct // Sizes of the pools to allocate inside the Buffer. // The goal is modest amortization and allocation // on at least 16-byte boundaries. const ( boolPoolSize = 16 uint32PoolSize = 8 uint64PoolSize = 4 ) // Decode a bool. func (o *Buffer) dec_bool(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } if len(o.bools) == 0 { o.bools = make([]bool, boolPoolSize) } o.bools[0] = u != 0 *structPointer_Bool(base, p.field) = &o.bools[0] o.bools = o.bools[1:] return nil } func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } *structPointer_BoolVal(base, p.field) = u != 0 return nil } // Decode an int32. func (o *Buffer) dec_int32(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } word32_Set(structPointer_Word32(base, p.field), o, uint32(u)) return nil } func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u)) return nil } // Decode an int64. func (o *Buffer) dec_int64(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } word64_Set(structPointer_Word64(base, p.field), o, u) return nil } func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } word64Val_Set(structPointer_Word64Val(base, p.field), o, u) return nil } // Decode a string. func (o *Buffer) dec_string(p *Properties, base structPointer) error { s, err := o.DecodeStringBytes() if err != nil { return err } *structPointer_String(base, p.field) = &s return nil } func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error { s, err := o.DecodeStringBytes() if err != nil { return err } *structPointer_StringVal(base, p.field) = s return nil } // Decode a slice of bytes ([]byte). func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error { b, err := o.DecodeRawBytes(true) if err != nil { return err } *structPointer_Bytes(base, p.field) = b return nil } // Decode a slice of bools ([]bool). func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } v := structPointer_BoolSlice(base, p.field) *v = append(*v, u != 0) return nil } // Decode a slice of bools ([]bool) in packed format. func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error { v := structPointer_BoolSlice(base, p.field) nn, err := o.DecodeVarint() if err != nil { return err } nb := int(nn) // number of bytes of encoded bools fin := o.index + nb if fin < o.index { return errOverflow } y := *v for o.index < fin { u, err := p.valDec(o) if err != nil { return err } y = append(y, u != 0) } *v = y return nil } // Decode a slice of int32s ([]int32). func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } structPointer_Word32Slice(base, p.field).Append(uint32(u)) return nil } // Decode a slice of int32s ([]int32) in packed format. func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error { v := structPointer_Word32Slice(base, p.field) nn, err := o.DecodeVarint() if err != nil { return err } nb := int(nn) // number of bytes of encoded int32s fin := o.index + nb if fin < o.index { return errOverflow } for o.index < fin { u, err := p.valDec(o) if err != nil { return err } v.Append(uint32(u)) } return nil } // Decode a slice of int64s ([]int64). func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error { u, err := p.valDec(o) if err != nil { return err } structPointer_Word64Slice(base, p.field).Append(u) return nil } // Decode a slice of int64s ([]int64) in packed format. func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error { v := structPointer_Word64Slice(base, p.field) nn, err := o.DecodeVarint() if err != nil { return err } nb := int(nn) // number of bytes of encoded int64s fin := o.index + nb if fin < o.index { return errOverflow } for o.index < fin { u, err := p.valDec(o) if err != nil { return err } v.Append(u) } return nil } // Decode a slice of strings ([]string). func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error { s, err := o.DecodeStringBytes() if err != nil { return err } v := structPointer_StringSlice(base, p.field) *v = append(*v, s) return nil } // Decode a slice of slice of bytes ([][]byte). func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error { b, err := o.DecodeRawBytes(true) if err != nil { return err } v := structPointer_BytesSlice(base, p.field) *v = append(*v, b) return nil } // Decode a map field. func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { raw, err := o.DecodeRawBytes(false) if err != nil { return err } oi := o.index // index at the end of this map entry o.index -= len(raw) // move buffer back to start of map entry mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V if mptr.Elem().IsNil() { mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem())) } v := mptr.Elem() // map[K]V // Prepare addressable doubly-indirect placeholders for the key and value types. // See enc_new_map for why. keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K keybase := toStructPointer(keyptr.Addr()) // **K var valbase structPointer var valptr reflect.Value switch p.mtype.Elem().Kind() { case reflect.Slice: // []byte var dummy []byte valptr = reflect.ValueOf(&dummy) // *[]byte valbase = toStructPointer(valptr) // *[]byte case reflect.Ptr: // message; valptr is **Msg; need to allocate the intermediate pointer valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V valptr.Set(reflect.New(valptr.Type().Elem())) valbase = toStructPointer(valptr) default: // everything else valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V valbase = toStructPointer(valptr.Addr()) // **V } // Decode. // This parses a restricted wire format, namely the encoding of a message // with two fields. See enc_new_map for the format. for o.index < oi { // tagcode for key and value properties are always a single byte // because they have tags 1 and 2. tagcode := o.buf[o.index] o.index++ switch tagcode { case p.mkeyprop.tagcode[0]: if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil { return err } case p.mvalprop.tagcode[0]: if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil { return err } default: // TODO: Should we silently skip this instead? return fmt.Errorf("proto: bad map data tag %d", raw[0]) } } keyelem, valelem := keyptr.Elem(), valptr.Elem() if !keyelem.IsValid() { keyelem = reflect.Zero(p.mtype.Key()) } if !valelem.IsValid() { valelem = reflect.Zero(p.mtype.Elem()) } v.SetMapIndex(keyelem, valelem) return nil } // Decode a group. func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error { bas := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(bas) { // allocate new nested message bas = toStructPointer(reflect.New(p.stype)) structPointer_SetStructPointer(base, p.field, bas) } return o.unmarshalType(p.stype, p.sprop, true, bas) } // Decode an embedded message. func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) { raw, e := o.DecodeRawBytes(false) if e != nil { return e } bas := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(bas) { // allocate new nested message bas = toStructPointer(reflect.New(p.stype)) structPointer_SetStructPointer(base, p.field, bas) } // If the object can unmarshal itself, let it. if p.isUnmarshaler { iv := structPointer_Interface(bas, p.stype) return iv.(Unmarshaler).Unmarshal(raw) } obuf := o.buf oi := o.index o.buf = raw o.index = 0 err = o.unmarshalType(p.stype, p.sprop, false, bas) o.buf = obuf o.index = oi return err } // Decode a slice of embedded messages. func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error { return o.dec_slice_struct(p, false, base) } // Decode a slice of embedded groups. func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error { return o.dec_slice_struct(p, true, base) } // Decode a slice of structs ([]*struct). func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error { v := reflect.New(p.stype) bas := toStructPointer(v) structPointer_StructPointerSlice(base, p.field).Append(bas) if is_group { err := o.unmarshalType(p.stype, p.sprop, is_group, bas) return err } raw, err := o.DecodeRawBytes(false) if err != nil { return err } // If the object can unmarshal itself, let it. if p.isUnmarshaler { iv := v.Interface() return iv.(Unmarshaler).Unmarshal(raw) } obuf := o.buf oi := o.index o.buf = raw o.index = 0 err = o.unmarshalType(p.stype, p.sprop, is_group, bas) o.buf = obuf o.index = oi return err } ================================================ FILE: src/github.com/golang/protobuf/proto/decode_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. // +build go1.7 package proto_test import ( "fmt" "testing" "github.com/golang/protobuf/proto" tpb "github.com/golang/protobuf/proto/proto3_proto" ) var ( bytesBlackhole []byte msgBlackhole = new(tpb.Message) ) // BenchmarkVarint32ArraySmall shows the performance on an array of small int32 fields (1 and // 2 bytes long). func BenchmarkVarint32ArraySmall(b *testing.B) { for i := uint(1); i <= 10; i++ { dist := genInt32Dist([7]int{0, 3, 1}, 1<2GB. ErrTooLarge = errors.New("proto: message encodes to over 2 GB") ) // The fundamental encoders that put bytes on the wire. // Those that take integer types all accept uint64 and are // therefore of type valueEncoder. const maxVarintBytes = 10 // maximum length of a varint // maxMarshalSize is the largest allowed size of an encoded protobuf, // since C++ and Java use signed int32s for the size. const maxMarshalSize = 1<<31 - 1 // EncodeVarint returns the varint encoding of x. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. // Not used by the package itself, but helpful to clients // wishing to use the same encoding. func EncodeVarint(x uint64) []byte { var buf [maxVarintBytes]byte var n int for n = 0; x > 127; n++ { buf[n] = 0x80 | uint8(x&0x7F) x >>= 7 } buf[n] = uint8(x) n++ return buf[0:n] } // EncodeVarint writes a varint-encoded integer to the Buffer. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. func (p *Buffer) EncodeVarint(x uint64) error { for x >= 1<<7 { p.buf = append(p.buf, uint8(x&0x7f|0x80)) x >>= 7 } p.buf = append(p.buf, uint8(x)) return nil } // SizeVarint returns the varint encoding size of an integer. func SizeVarint(x uint64) int { return sizeVarint(x) } func sizeVarint(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } // EncodeFixed64 writes a 64-bit integer to the Buffer. // This is the format for the // fixed64, sfixed64, and double protocol buffer types. func (p *Buffer) EncodeFixed64(x uint64) error { p.buf = append(p.buf, uint8(x), uint8(x>>8), uint8(x>>16), uint8(x>>24), uint8(x>>32), uint8(x>>40), uint8(x>>48), uint8(x>>56)) return nil } func sizeFixed64(x uint64) int { return 8 } // EncodeFixed32 writes a 32-bit integer to the Buffer. // This is the format for the // fixed32, sfixed32, and float protocol buffer types. func (p *Buffer) EncodeFixed32(x uint64) error { p.buf = append(p.buf, uint8(x), uint8(x>>8), uint8(x>>16), uint8(x>>24)) return nil } func sizeFixed32(x uint64) int { return 4 } // EncodeZigzag64 writes a zigzag-encoded 64-bit integer // to the Buffer. // This is the format used for the sint64 protocol buffer type. func (p *Buffer) EncodeZigzag64(x uint64) error { // use signed number to get arithmetic right shift. return p.EncodeVarint((x << 1) ^ uint64((int64(x) >> 63))) } func sizeZigzag64(x uint64) int { return sizeVarint((x << 1) ^ uint64((int64(x) >> 63))) } // EncodeZigzag32 writes a zigzag-encoded 32-bit integer // to the Buffer. // This is the format used for the sint32 protocol buffer type. func (p *Buffer) EncodeZigzag32(x uint64) error { // use signed number to get arithmetic right shift. return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) } func sizeZigzag32(x uint64) int { return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) } // EncodeRawBytes writes a count-delimited byte buffer to the Buffer. // This is the format used for the bytes protocol buffer // type and for embedded messages. func (p *Buffer) EncodeRawBytes(b []byte) error { p.EncodeVarint(uint64(len(b))) p.buf = append(p.buf, b...) return nil } func sizeRawBytes(b []byte) int { return sizeVarint(uint64(len(b))) + len(b) } // EncodeStringBytes writes an encoded string to the Buffer. // This is the format used for the proto2 string type. func (p *Buffer) EncodeStringBytes(s string) error { p.EncodeVarint(uint64(len(s))) p.buf = append(p.buf, s...) return nil } func sizeStringBytes(s string) int { return sizeVarint(uint64(len(s))) + len(s) } // Marshaler is the interface representing objects that can marshal themselves. type Marshaler interface { Marshal() ([]byte, error) } // Marshal takes the protocol buffer // and encodes it into the wire format, returning the data. func Marshal(pb Message) ([]byte, error) { // Can the object marshal itself? if m, ok := pb.(Marshaler); ok { return m.Marshal() } p := NewBuffer(nil) err := p.Marshal(pb) if p.buf == nil && err == nil { // Return a non-nil slice on success. return []byte{}, nil } return p.buf, err } // EncodeMessage writes the protocol buffer to the Buffer, // prefixed by a varint-encoded length. func (p *Buffer) EncodeMessage(pb Message) error { t, base, err := getbase(pb) if structPointer_IsNil(base) { return ErrNil } if err == nil { var state errorState err = p.enc_len_struct(GetProperties(t.Elem()), base, &state) } return err } // Marshal takes the protocol buffer // and encodes it into the wire format, writing the result to the // Buffer. func (p *Buffer) Marshal(pb Message) error { // Can the object marshal itself? if m, ok := pb.(Marshaler); ok { data, err := m.Marshal() p.buf = append(p.buf, data...) return err } t, base, err := getbase(pb) if structPointer_IsNil(base) { return ErrNil } if err == nil { err = p.enc_struct(GetProperties(t.Elem()), base) } if collectStats { (stats).Encode++ // Parens are to work around a goimports bug. } if len(p.buf) > maxMarshalSize { return ErrTooLarge } return err } // Size returns the encoded size of a protocol buffer. func Size(pb Message) (n int) { // Can the object marshal itself? If so, Size is slow. // TODO: add Size to Marshaler, or add a Sizer interface. if m, ok := pb.(Marshaler); ok { b, _ := m.Marshal() return len(b) } t, base, err := getbase(pb) if structPointer_IsNil(base) { return 0 } if err == nil { n = size_struct(GetProperties(t.Elem()), base) } if collectStats { (stats).Size++ // Parens are to work around a goimports bug. } return } // Individual type encoders. // Encode a bool. func (o *Buffer) enc_bool(p *Properties, base structPointer) error { v := *structPointer_Bool(base, p.field) if v == nil { return ErrNil } x := 0 if *v { x = 1 } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error { v := *structPointer_BoolVal(base, p.field) if !v { return ErrNil } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, 1) return nil } func size_bool(p *Properties, base structPointer) int { v := *structPointer_Bool(base, p.field) if v == nil { return 0 } return len(p.tagcode) + 1 // each bool takes exactly one byte } func size_proto3_bool(p *Properties, base structPointer) int { v := *structPointer_BoolVal(base, p.field) if !v && !p.oneof { return 0 } return len(p.tagcode) + 1 // each bool takes exactly one byte } // Encode an int32. func (o *Buffer) enc_int32(p *Properties, base structPointer) error { v := structPointer_Word32(base, p.field) if word32_IsNil(v) { return ErrNil } x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error { v := structPointer_Word32Val(base, p.field) x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range if x == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func size_int32(p *Properties, base structPointer) (n int) { v := structPointer_Word32(base, p.field) if word32_IsNil(v) { return 0 } x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range n += len(p.tagcode) n += p.valSize(uint64(x)) return } func size_proto3_int32(p *Properties, base structPointer) (n int) { v := structPointer_Word32Val(base, p.field) x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range if x == 0 && !p.oneof { return 0 } n += len(p.tagcode) n += p.valSize(uint64(x)) return } // Encode a uint32. // Exactly the same as int32, except for no sign extension. func (o *Buffer) enc_uint32(p *Properties, base structPointer) error { v := structPointer_Word32(base, p.field) if word32_IsNil(v) { return ErrNil } x := word32_Get(v) o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error { v := structPointer_Word32Val(base, p.field) x := word32Val_Get(v) if x == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func size_uint32(p *Properties, base structPointer) (n int) { v := structPointer_Word32(base, p.field) if word32_IsNil(v) { return 0 } x := word32_Get(v) n += len(p.tagcode) n += p.valSize(uint64(x)) return } func size_proto3_uint32(p *Properties, base structPointer) (n int) { v := structPointer_Word32Val(base, p.field) x := word32Val_Get(v) if x == 0 && !p.oneof { return 0 } n += len(p.tagcode) n += p.valSize(uint64(x)) return } // Encode an int64. func (o *Buffer) enc_int64(p *Properties, base structPointer) error { v := structPointer_Word64(base, p.field) if word64_IsNil(v) { return ErrNil } x := word64_Get(v) o.buf = append(o.buf, p.tagcode...) p.valEnc(o, x) return nil } func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error { v := structPointer_Word64Val(base, p.field) x := word64Val_Get(v) if x == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, x) return nil } func size_int64(p *Properties, base structPointer) (n int) { v := structPointer_Word64(base, p.field) if word64_IsNil(v) { return 0 } x := word64_Get(v) n += len(p.tagcode) n += p.valSize(x) return } func size_proto3_int64(p *Properties, base structPointer) (n int) { v := structPointer_Word64Val(base, p.field) x := word64Val_Get(v) if x == 0 && !p.oneof { return 0 } n += len(p.tagcode) n += p.valSize(x) return } // Encode a string. func (o *Buffer) enc_string(p *Properties, base structPointer) error { v := *structPointer_String(base, p.field) if v == nil { return ErrNil } x := *v o.buf = append(o.buf, p.tagcode...) o.EncodeStringBytes(x) return nil } func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error { v := *structPointer_StringVal(base, p.field) if v == "" { return ErrNil } o.buf = append(o.buf, p.tagcode...) o.EncodeStringBytes(v) return nil } func size_string(p *Properties, base structPointer) (n int) { v := *structPointer_String(base, p.field) if v == nil { return 0 } x := *v n += len(p.tagcode) n += sizeStringBytes(x) return } func size_proto3_string(p *Properties, base structPointer) (n int) { v := *structPointer_StringVal(base, p.field) if v == "" && !p.oneof { return 0 } n += len(p.tagcode) n += sizeStringBytes(v) return } // All protocol buffer fields are nillable, but be careful. func isNil(v reflect.Value) bool { switch v.Kind() { case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return v.IsNil() } return false } // Encode a message struct. func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error { var state errorState structp := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(structp) { return ErrNil } // Can the object marshal itself? if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, err := m.Marshal() if err != nil && !state.shouldContinue(err, nil) { return err } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(data) return state.err } o.buf = append(o.buf, p.tagcode...) return o.enc_len_struct(p.sprop, structp, &state) } func size_struct_message(p *Properties, base structPointer) int { structp := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(structp) { return 0 } // Can the object marshal itself? if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, _ := m.Marshal() n0 := len(p.tagcode) n1 := sizeRawBytes(data) return n0 + n1 } n0 := len(p.tagcode) n1 := size_struct(p.sprop, structp) n2 := sizeVarint(uint64(n1)) // size of encoded length return n0 + n1 + n2 } // Encode a group struct. func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error { var state errorState b := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(b) { return ErrNil } o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) err := o.enc_struct(p.sprop, b) if err != nil && !state.shouldContinue(err, nil) { return err } o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) return state.err } func size_struct_group(p *Properties, base structPointer) (n int) { b := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(b) { return 0 } n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup)) n += size_struct(p.sprop, b) n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup)) return } // Encode a slice of bools ([]bool). func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error { s := *structPointer_BoolSlice(base, p.field) l := len(s) if l == 0 { return ErrNil } for _, x := range s { o.buf = append(o.buf, p.tagcode...) v := uint64(0) if x { v = 1 } p.valEnc(o, v) } return nil } func size_slice_bool(p *Properties, base structPointer) int { s := *structPointer_BoolSlice(base, p.field) l := len(s) if l == 0 { return 0 } return l * (len(p.tagcode) + 1) // each bool takes exactly one byte } // Encode a slice of bools ([]bool) in packed format. func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error { s := *structPointer_BoolSlice(base, p.field) l := len(s) if l == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) o.EncodeVarint(uint64(l)) // each bool takes exactly one byte for _, x := range s { v := uint64(0) if x { v = 1 } p.valEnc(o, v) } return nil } func size_slice_packed_bool(p *Properties, base structPointer) (n int) { s := *structPointer_BoolSlice(base, p.field) l := len(s) if l == 0 { return 0 } n += len(p.tagcode) n += sizeVarint(uint64(l)) n += l // each bool takes exactly one byte return } // Encode a slice of bytes ([]byte). func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error { s := *structPointer_Bytes(base, p.field) if s == nil { return ErrNil } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(s) return nil } func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error { s := *structPointer_Bytes(base, p.field) if len(s) == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(s) return nil } func size_slice_byte(p *Properties, base structPointer) (n int) { s := *structPointer_Bytes(base, p.field) if s == nil && !p.oneof { return 0 } n += len(p.tagcode) n += sizeRawBytes(s) return } func size_proto3_slice_byte(p *Properties, base structPointer) (n int) { s := *structPointer_Bytes(base, p.field) if len(s) == 0 && !p.oneof { return 0 } n += len(p.tagcode) n += sizeRawBytes(s) return } // Encode a slice of int32s ([]int32). func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) x := int32(s.Index(i)) // permit sign extension to use full 64-bit range p.valEnc(o, uint64(x)) } return nil } func size_slice_int32(p *Properties, base structPointer) (n int) { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return 0 } for i := 0; i < l; i++ { n += len(p.tagcode) x := int32(s.Index(i)) // permit sign extension to use full 64-bit range n += p.valSize(uint64(x)) } return } // Encode a slice of int32s ([]int32) in packed format. func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } // TODO: Reuse a Buffer. buf := NewBuffer(nil) for i := 0; i < l; i++ { x := int32(s.Index(i)) // permit sign extension to use full 64-bit range p.valEnc(buf, uint64(x)) } o.buf = append(o.buf, p.tagcode...) o.EncodeVarint(uint64(len(buf.buf))) o.buf = append(o.buf, buf.buf...) return nil } func size_slice_packed_int32(p *Properties, base structPointer) (n int) { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return 0 } var bufSize int for i := 0; i < l; i++ { x := int32(s.Index(i)) // permit sign extension to use full 64-bit range bufSize += p.valSize(uint64(x)) } n += len(p.tagcode) n += sizeVarint(uint64(bufSize)) n += bufSize return } // Encode a slice of uint32s ([]uint32). // Exactly the same as int32, except for no sign extension. func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) x := s.Index(i) p.valEnc(o, uint64(x)) } return nil } func size_slice_uint32(p *Properties, base structPointer) (n int) { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return 0 } for i := 0; i < l; i++ { n += len(p.tagcode) x := s.Index(i) n += p.valSize(uint64(x)) } return } // Encode a slice of uint32s ([]uint32) in packed format. // Exactly the same as int32, except for no sign extension. func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } // TODO: Reuse a Buffer. buf := NewBuffer(nil) for i := 0; i < l; i++ { p.valEnc(buf, uint64(s.Index(i))) } o.buf = append(o.buf, p.tagcode...) o.EncodeVarint(uint64(len(buf.buf))) o.buf = append(o.buf, buf.buf...) return nil } func size_slice_packed_uint32(p *Properties, base structPointer) (n int) { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return 0 } var bufSize int for i := 0; i < l; i++ { bufSize += p.valSize(uint64(s.Index(i))) } n += len(p.tagcode) n += sizeVarint(uint64(bufSize)) n += bufSize return } // Encode a slice of int64s ([]int64). func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error { s := structPointer_Word64Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) p.valEnc(o, s.Index(i)) } return nil } func size_slice_int64(p *Properties, base structPointer) (n int) { s := structPointer_Word64Slice(base, p.field) l := s.Len() if l == 0 { return 0 } for i := 0; i < l; i++ { n += len(p.tagcode) n += p.valSize(s.Index(i)) } return } // Encode a slice of int64s ([]int64) in packed format. func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error { s := structPointer_Word64Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } // TODO: Reuse a Buffer. buf := NewBuffer(nil) for i := 0; i < l; i++ { p.valEnc(buf, s.Index(i)) } o.buf = append(o.buf, p.tagcode...) o.EncodeVarint(uint64(len(buf.buf))) o.buf = append(o.buf, buf.buf...) return nil } func size_slice_packed_int64(p *Properties, base structPointer) (n int) { s := structPointer_Word64Slice(base, p.field) l := s.Len() if l == 0 { return 0 } var bufSize int for i := 0; i < l; i++ { bufSize += p.valSize(s.Index(i)) } n += len(p.tagcode) n += sizeVarint(uint64(bufSize)) n += bufSize return } // Encode a slice of slice of bytes ([][]byte). func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error { ss := *structPointer_BytesSlice(base, p.field) l := len(ss) if l == 0 { return ErrNil } for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(ss[i]) } return nil } func size_slice_slice_byte(p *Properties, base structPointer) (n int) { ss := *structPointer_BytesSlice(base, p.field) l := len(ss) if l == 0 { return 0 } n += l * len(p.tagcode) for i := 0; i < l; i++ { n += sizeRawBytes(ss[i]) } return } // Encode a slice of strings ([]string). func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error { ss := *structPointer_StringSlice(base, p.field) l := len(ss) for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) o.EncodeStringBytes(ss[i]) } return nil } func size_slice_string(p *Properties, base structPointer) (n int) { ss := *structPointer_StringSlice(base, p.field) l := len(ss) n += l * len(p.tagcode) for i := 0; i < l; i++ { n += sizeStringBytes(ss[i]) } return } // Encode a slice of message structs ([]*struct). func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error { var state errorState s := structPointer_StructPointerSlice(base, p.field) l := s.Len() for i := 0; i < l; i++ { structp := s.Index(i) if structPointer_IsNil(structp) { return errRepeatedHasNil } // Can the object marshal itself? if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, err := m.Marshal() if err != nil && !state.shouldContinue(err, nil) { return err } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(data) continue } o.buf = append(o.buf, p.tagcode...) err := o.enc_len_struct(p.sprop, structp, &state) if err != nil && !state.shouldContinue(err, nil) { if err == ErrNil { return errRepeatedHasNil } return err } } return state.err } func size_slice_struct_message(p *Properties, base structPointer) (n int) { s := structPointer_StructPointerSlice(base, p.field) l := s.Len() n += l * len(p.tagcode) for i := 0; i < l; i++ { structp := s.Index(i) if structPointer_IsNil(structp) { return // return the size up to this point } // Can the object marshal itself? if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, _ := m.Marshal() n += sizeRawBytes(data) continue } n0 := size_struct(p.sprop, structp) n1 := sizeVarint(uint64(n0)) // size of encoded length n += n0 + n1 } return } // Encode a slice of group structs ([]*struct). func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error { var state errorState s := structPointer_StructPointerSlice(base, p.field) l := s.Len() for i := 0; i < l; i++ { b := s.Index(i) if structPointer_IsNil(b) { return errRepeatedHasNil } o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) err := o.enc_struct(p.sprop, b) if err != nil && !state.shouldContinue(err, nil) { if err == ErrNil { return errRepeatedHasNil } return err } o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) } return state.err } func size_slice_struct_group(p *Properties, base structPointer) (n int) { s := structPointer_StructPointerSlice(base, p.field) l := s.Len() n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup)) n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup)) for i := 0; i < l; i++ { b := s.Index(i) if structPointer_IsNil(b) { return // return size up to this point } n += size_struct(p.sprop, b) } return } // Encode an extension map. func (o *Buffer) enc_map(p *Properties, base structPointer) error { exts := structPointer_ExtMap(base, p.field) if err := encodeExtensionsMap(*exts); err != nil { return err } return o.enc_map_body(*exts) } func (o *Buffer) enc_exts(p *Properties, base structPointer) error { exts := structPointer_Extensions(base, p.field) v, mu := exts.extensionsRead() if v == nil { return nil } mu.Lock() defer mu.Unlock() if err := encodeExtensionsMap(v); err != nil { return err } return o.enc_map_body(v) } func (o *Buffer) enc_map_body(v map[int32]Extension) error { // Fast-path for common cases: zero or one extensions. if len(v) <= 1 { for _, e := range v { o.buf = append(o.buf, e.enc...) } return nil } // Sort keys to provide a deterministic encoding. keys := make([]int, 0, len(v)) for k := range v { keys = append(keys, int(k)) } sort.Ints(keys) for _, k := range keys { o.buf = append(o.buf, v[int32(k)].enc...) } return nil } func size_map(p *Properties, base structPointer) int { v := structPointer_ExtMap(base, p.field) return extensionsMapSize(*v) } func size_exts(p *Properties, base structPointer) int { v := structPointer_Extensions(base, p.field) return extensionsSize(v) } // Encode a map field. func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { var state errorState // XXX: or do we need to plumb this through? /* A map defined as map map_field = N; is encoded in the same way as message MapFieldEntry { key_type key = 1; value_type value = 2; } repeated MapFieldEntry map_field = N; */ v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V if v.Len() == 0 { return nil } keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) enc := func() error { if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil { return err } if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil { return err } return nil } // Don't sort map keys. It is not required by the spec, and C++ doesn't do it. for _, key := range v.MapKeys() { val := v.MapIndex(key) keycopy.Set(key) valcopy.Set(val) o.buf = append(o.buf, p.tagcode...) if err := o.enc_len_thing(enc, &state); err != nil { return err } } return nil } func size_new_map(p *Properties, base structPointer) int { v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) n := 0 for _, key := range v.MapKeys() { val := v.MapIndex(key) keycopy.Set(key) valcopy.Set(val) // Tag codes for key and val are the responsibility of the sub-sizer. keysize := p.mkeyprop.size(p.mkeyprop, keybase) valsize := p.mvalprop.size(p.mvalprop, valbase) entry := keysize + valsize // Add on tag code and length of map entry itself. n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry } return n } // mapEncodeScratch returns a new reflect.Value matching the map's value type, // and a structPointer suitable for passing to an encoder or sizer. func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) { // Prepare addressable doubly-indirect placeholders for the key and value types. // This is needed because the element-type encoders expect **T, but the map iteration produces T. keycopy = reflect.New(mapType.Key()).Elem() // addressable K keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K keyptr.Set(keycopy.Addr()) // keybase = toStructPointer(keyptr.Addr()) // **K // Value types are more varied and require special handling. switch mapType.Elem().Kind() { case reflect.Slice: // []byte var dummy []byte valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte valbase = toStructPointer(valcopy.Addr()) case reflect.Ptr: // message; the generated field type is map[K]*Msg (so V is *Msg), // so we only need one level of indirection. valcopy = reflect.New(mapType.Elem()).Elem() // addressable V valbase = toStructPointer(valcopy.Addr()) default: // everything else valcopy = reflect.New(mapType.Elem()).Elem() // addressable V valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V valptr.Set(valcopy.Addr()) // valbase = toStructPointer(valptr.Addr()) // **V } return } // Encode a struct. func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { var state errorState // Encode fields in tag order so that decoders may use optimizations // that depend on the ordering. // https://developers.google.com/protocol-buffers/docs/encoding#order for _, i := range prop.order { p := prop.Prop[i] if p.enc != nil { err := p.enc(o, p, base) if err != nil { if err == ErrNil { if p.Required && state.err == nil { state.err = &RequiredNotSetError{p.Name} } } else if err == errRepeatedHasNil { // Give more context to nil values in repeated fields. return errors.New("repeated field " + p.OrigName + " has nil element") } else if !state.shouldContinue(err, p) { return err } } if len(o.buf) > maxMarshalSize { return ErrTooLarge } } } // Do oneof fields. if prop.oneofMarshaler != nil { m := structPointer_Interface(base, prop.stype).(Message) if err := prop.oneofMarshaler(m, o); err == ErrNil { return errOneofHasNil } else if err != nil { return err } } // Add unrecognized fields at the end. if prop.unrecField.IsValid() { v := *structPointer_Bytes(base, prop.unrecField) if len(o.buf)+len(v) > maxMarshalSize { return ErrTooLarge } if len(v) > 0 { o.buf = append(o.buf, v...) } } return state.err } func size_struct(prop *StructProperties, base structPointer) (n int) { for _, i := range prop.order { p := prop.Prop[i] if p.size != nil { n += p.size(p, base) } } // Add unrecognized fields at the end. if prop.unrecField.IsValid() { v := *structPointer_Bytes(base, prop.unrecField) n += len(v) } // Factor in any oneof fields. if prop.oneofSizer != nil { m := structPointer_Interface(base, prop.stype).(Message) n += prop.oneofSizer(m) } return } var zeroes [20]byte // longer than any conceivable sizeVarint // Encode a struct, preceded by its encoded length (as a varint). func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error { return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state) } // Encode something, preceded by its encoded length (as a varint). func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error { iLen := len(o.buf) o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length iMsg := len(o.buf) err := enc() if err != nil && !state.shouldContinue(err, nil) { return err } lMsg := len(o.buf) - iMsg lLen := sizeVarint(uint64(lMsg)) switch x := lLen - (iMsg - iLen); { case x > 0: // actual length is x bytes larger than the space we reserved // Move msg x bytes right. o.buf = append(o.buf, zeroes[:x]...) copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) case x < 0: // actual length is x bytes smaller than the space we reserved // Move msg x bytes left. copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) o.buf = o.buf[:len(o.buf)+x] // x is negative } // Encode the length in the reserved space. o.buf = o.buf[:iLen] o.EncodeVarint(uint64(lMsg)) o.buf = o.buf[:len(o.buf)+lMsg] return state.err } // errorState maintains the first error that occurs and updates that error // with additional context. type errorState struct { err error } // shouldContinue reports whether encoding should continue upon encountering the // given error. If the error is RequiredNotSetError, shouldContinue returns true // and, if this is the first appearance of that error, remembers it for future // reporting. // // If prop is not nil, it may update any error with additional context about the // field with the error. func (s *errorState) shouldContinue(err error, prop *Properties) bool { // Ignore unset required fields. reqNotSet, ok := err.(*RequiredNotSetError) if !ok { return false } if s.err == nil { if prop != nil { err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field} } s.err = err } return true } ================================================ FILE: src/github.com/golang/protobuf/proto/encode_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. // +build go1.7 package proto_test import ( "strconv" "testing" "github.com/golang/protobuf/proto" tpb "github.com/golang/protobuf/proto/proto3_proto" "github.com/golang/protobuf/ptypes" ) var ( blackhole []byte ) // BenchmarkAny creates increasingly large arbitrary Any messages. The type is always the // same. func BenchmarkAny(b *testing.B) { data := make([]byte, 1<<20) quantum := 1 << 10 for i := uint(0); i <= 10; i++ { b.Run(strconv.Itoa(quantum<= len(o.buf) { break } } return value.Interface(), nil } // GetExtensions returns a slice of the extensions present in pb that are also listed in es. // The returned slice has the same length as es; missing extensions will appear as nil elements. func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { epb, ok := extendable(pb) if !ok { return nil, errors.New("proto: not an extendable proto") } extensions = make([]interface{}, len(es)) for i, e := range es { extensions[i], err = GetExtension(epb, e) if err == ErrMissingExtension { err = nil } if err != nil { return } } return } // ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. // For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing // just the Field field, which defines the extension's field number. func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { epb, ok := extendable(pb) if !ok { return nil, fmt.Errorf("proto: %T is not an extendable proto.Message", pb) } registeredExtensions := RegisteredExtensions(pb) emap, mu := epb.extensionsRead() if emap == nil { return nil, nil } mu.Lock() defer mu.Unlock() extensions := make([]*ExtensionDesc, 0, len(emap)) for extid, e := range emap { desc := e.desc if desc == nil { desc = registeredExtensions[extid] if desc == nil { desc = &ExtensionDesc{Field: extid} } } extensions = append(extensions, desc) } return extensions, nil } // SetExtension sets the specified extension of pb to the specified value. func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { epb, ok := extendable(pb) if !ok { return errors.New("proto: not an extendable proto") } if err := checkExtensionTypes(epb, extension); err != nil { return err } typ := reflect.TypeOf(extension.ExtensionType) if typ != reflect.TypeOf(value) { return errors.New("proto: bad extension value type") } // nil extension values need to be caught early, because the // encoder can't distinguish an ErrNil due to a nil extension // from an ErrNil due to a missing field. Extensions are // always optional, so the encoder would just swallow the error // and drop all the extensions from the encoded message. if reflect.ValueOf(value).IsNil() { return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) } extmap := epb.extensionsWrite() extmap[extension.Field] = Extension{desc: extension, value: value} return nil } // ClearAllExtensions clears all extensions from pb. func ClearAllExtensions(pb Message) { epb, ok := extendable(pb) if !ok { return } m := epb.extensionsWrite() for k := range m { delete(m, k) } } // A global registry of extensions. // The generated code will register the generated descriptors by calling RegisterExtension. var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) // RegisterExtension is called from the generated code. func RegisterExtension(desc *ExtensionDesc) { st := reflect.TypeOf(desc.ExtendedType).Elem() m := extensionMaps[st] if m == nil { m = make(map[int32]*ExtensionDesc) extensionMaps[st] = m } if _, ok := m[desc.Field]; ok { panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) } m[desc.Field] = desc } // RegisteredExtensions returns a map of the registered extensions of a // protocol buffer struct, indexed by the extension number. // The argument pb should be a nil pointer to the struct type. func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { return extensionMaps[reflect.TypeOf(pb).Elem()] } ================================================ FILE: src/github.com/golang/protobuf/proto/extensions_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto_test import ( "bytes" "fmt" "reflect" "sort" "testing" "github.com/golang/protobuf/proto" pb "github.com/golang/protobuf/proto/testdata" "golang.org/x/sync/errgroup" ) func TestGetExtensionsWithMissingExtensions(t *testing.T) { msg := &pb.MyMessage{} ext1 := &pb.Ext{} if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { t.Fatalf("Could not set ext1: %s", err) } exts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{ pb.E_Ext_More, pb.E_Ext_Text, }) if err != nil { t.Fatalf("GetExtensions() failed: %s", err) } if exts[0] != ext1 { t.Errorf("ext1 not in returned extensions: %T %v", exts[0], exts[0]) } if exts[1] != nil { t.Errorf("ext2 in returned extensions: %T %v", exts[1], exts[1]) } } func TestExtensionDescsWithMissingExtensions(t *testing.T) { msg := &pb.MyMessage{Count: proto.Int32(0)} extdesc1 := pb.E_Ext_More if descs, err := proto.ExtensionDescs(msg); len(descs) != 0 || err != nil { t.Errorf("proto.ExtensionDescs: got %d descs, error %v; want 0, nil", len(descs), err) } ext1 := &pb.Ext{} if err := proto.SetExtension(msg, extdesc1, ext1); err != nil { t.Fatalf("Could not set ext1: %s", err) } extdesc2 := &proto.ExtensionDesc{ ExtendedType: (*pb.MyMessage)(nil), ExtensionType: (*bool)(nil), Field: 123456789, Name: "a.b", Tag: "varint,123456789,opt", } ext2 := proto.Bool(false) if err := proto.SetExtension(msg, extdesc2, ext2); err != nil { t.Fatalf("Could not set ext2: %s", err) } b, err := proto.Marshal(msg) if err != nil { t.Fatalf("Could not marshal msg: %v", err) } if err := proto.Unmarshal(b, msg); err != nil { t.Fatalf("Could not unmarshal into msg: %v", err) } descs, err := proto.ExtensionDescs(msg) if err != nil { t.Fatalf("proto.ExtensionDescs: got error %v", err) } sortExtDescs(descs) wantDescs := []*proto.ExtensionDesc{extdesc1, &proto.ExtensionDesc{Field: extdesc2.Field}} if !reflect.DeepEqual(descs, wantDescs) { t.Errorf("proto.ExtensionDescs(msg) sorted extension ids: got %+v, want %+v", descs, wantDescs) } } type ExtensionDescSlice []*proto.ExtensionDesc func (s ExtensionDescSlice) Len() int { return len(s) } func (s ExtensionDescSlice) Less(i, j int) bool { return s[i].Field < s[j].Field } func (s ExtensionDescSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func sortExtDescs(s []*proto.ExtensionDesc) { sort.Sort(ExtensionDescSlice(s)) } func TestGetExtensionStability(t *testing.T) { check := func(m *pb.MyMessage) bool { ext1, err := proto.GetExtension(m, pb.E_Ext_More) if err != nil { t.Fatalf("GetExtension() failed: %s", err) } ext2, err := proto.GetExtension(m, pb.E_Ext_More) if err != nil { t.Fatalf("GetExtension() failed: %s", err) } return ext1 == ext2 } msg := &pb.MyMessage{Count: proto.Int32(4)} ext0 := &pb.Ext{} if err := proto.SetExtension(msg, pb.E_Ext_More, ext0); err != nil { t.Fatalf("Could not set ext1: %s", ext0) } if !check(msg) { t.Errorf("GetExtension() not stable before marshaling") } bb, err := proto.Marshal(msg) if err != nil { t.Fatalf("Marshal() failed: %s", err) } msg1 := &pb.MyMessage{} err = proto.Unmarshal(bb, msg1) if err != nil { t.Fatalf("Unmarshal() failed: %s", err) } if !check(msg1) { t.Errorf("GetExtension() not stable after unmarshaling") } } func TestGetExtensionDefaults(t *testing.T) { var setFloat64 float64 = 1 var setFloat32 float32 = 2 var setInt32 int32 = 3 var setInt64 int64 = 4 var setUint32 uint32 = 5 var setUint64 uint64 = 6 var setBool = true var setBool2 = false var setString = "Goodnight string" var setBytes = []byte("Goodnight bytes") var setEnum = pb.DefaultsMessage_TWO type testcase struct { ext *proto.ExtensionDesc // Extension we are testing. want interface{} // Expected value of extension, or nil (meaning that GetExtension will fail). def interface{} // Expected value of extension after ClearExtension(). } tests := []testcase{ {pb.E_NoDefaultDouble, setFloat64, nil}, {pb.E_NoDefaultFloat, setFloat32, nil}, {pb.E_NoDefaultInt32, setInt32, nil}, {pb.E_NoDefaultInt64, setInt64, nil}, {pb.E_NoDefaultUint32, setUint32, nil}, {pb.E_NoDefaultUint64, setUint64, nil}, {pb.E_NoDefaultSint32, setInt32, nil}, {pb.E_NoDefaultSint64, setInt64, nil}, {pb.E_NoDefaultFixed32, setUint32, nil}, {pb.E_NoDefaultFixed64, setUint64, nil}, {pb.E_NoDefaultSfixed32, setInt32, nil}, {pb.E_NoDefaultSfixed64, setInt64, nil}, {pb.E_NoDefaultBool, setBool, nil}, {pb.E_NoDefaultBool, setBool2, nil}, {pb.E_NoDefaultString, setString, nil}, {pb.E_NoDefaultBytes, setBytes, nil}, {pb.E_NoDefaultEnum, setEnum, nil}, {pb.E_DefaultDouble, setFloat64, float64(3.1415)}, {pb.E_DefaultFloat, setFloat32, float32(3.14)}, {pb.E_DefaultInt32, setInt32, int32(42)}, {pb.E_DefaultInt64, setInt64, int64(43)}, {pb.E_DefaultUint32, setUint32, uint32(44)}, {pb.E_DefaultUint64, setUint64, uint64(45)}, {pb.E_DefaultSint32, setInt32, int32(46)}, {pb.E_DefaultSint64, setInt64, int64(47)}, {pb.E_DefaultFixed32, setUint32, uint32(48)}, {pb.E_DefaultFixed64, setUint64, uint64(49)}, {pb.E_DefaultSfixed32, setInt32, int32(50)}, {pb.E_DefaultSfixed64, setInt64, int64(51)}, {pb.E_DefaultBool, setBool, true}, {pb.E_DefaultBool, setBool2, true}, {pb.E_DefaultString, setString, "Hello, string"}, {pb.E_DefaultBytes, setBytes, []byte("Hello, bytes")}, {pb.E_DefaultEnum, setEnum, pb.DefaultsMessage_ONE}, } checkVal := func(test testcase, msg *pb.DefaultsMessage, valWant interface{}) error { val, err := proto.GetExtension(msg, test.ext) if err != nil { if valWant != nil { return fmt.Errorf("GetExtension(): %s", err) } if want := proto.ErrMissingExtension; err != want { return fmt.Errorf("Unexpected error: got %v, want %v", err, want) } return nil } // All proto2 extension values are either a pointer to a value or a slice of values. ty := reflect.TypeOf(val) tyWant := reflect.TypeOf(test.ext.ExtensionType) if got, want := ty, tyWant; got != want { return fmt.Errorf("unexpected reflect.TypeOf(): got %v want %v", got, want) } tye := ty.Elem() tyeWant := tyWant.Elem() if got, want := tye, tyeWant; got != want { return fmt.Errorf("unexpected reflect.TypeOf().Elem(): got %v want %v", got, want) } // Check the name of the type of the value. // If it is an enum it will be type int32 with the name of the enum. if got, want := tye.Name(), tye.Name(); got != want { return fmt.Errorf("unexpected reflect.TypeOf().Elem().Name(): got %v want %v", got, want) } // Check that value is what we expect. // If we have a pointer in val, get the value it points to. valExp := val if ty.Kind() == reflect.Ptr { valExp = reflect.ValueOf(val).Elem().Interface() } if got, want := valExp, valWant; !reflect.DeepEqual(got, want) { return fmt.Errorf("unexpected reflect.DeepEqual(): got %v want %v", got, want) } return nil } setTo := func(test testcase) interface{} { setTo := reflect.ValueOf(test.want) if typ := reflect.TypeOf(test.ext.ExtensionType); typ.Kind() == reflect.Ptr { setTo = reflect.New(typ).Elem() setTo.Set(reflect.New(setTo.Type().Elem())) setTo.Elem().Set(reflect.ValueOf(test.want)) } return setTo.Interface() } for _, test := range tests { msg := &pb.DefaultsMessage{} name := test.ext.Name // Check the initial value. if err := checkVal(test, msg, test.def); err != nil { t.Errorf("%s: %v", name, err) } // Set the per-type value and check value. name = fmt.Sprintf("%s (set to %T %v)", name, test.want, test.want) if err := proto.SetExtension(msg, test.ext, setTo(test)); err != nil { t.Errorf("%s: SetExtension(): %v", name, err) continue } if err := checkVal(test, msg, test.want); err != nil { t.Errorf("%s: %v", name, err) continue } // Set and check the value. name += " (cleared)" proto.ClearExtension(msg, test.ext) if err := checkVal(test, msg, test.def); err != nil { t.Errorf("%s: %v", name, err) } } } func TestExtensionsRoundTrip(t *testing.T) { msg := &pb.MyMessage{} ext1 := &pb.Ext{ Data: proto.String("hi"), } ext2 := &pb.Ext{ Data: proto.String("there"), } exists := proto.HasExtension(msg, pb.E_Ext_More) if exists { t.Error("Extension More present unexpectedly") } if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { t.Error(err) } if err := proto.SetExtension(msg, pb.E_Ext_More, ext2); err != nil { t.Error(err) } e, err := proto.GetExtension(msg, pb.E_Ext_More) if err != nil { t.Error(err) } x, ok := e.(*pb.Ext) if !ok { t.Errorf("e has type %T, expected testdata.Ext", e) } else if *x.Data != "there" { t.Errorf("SetExtension failed to overwrite, got %+v, not 'there'", x) } proto.ClearExtension(msg, pb.E_Ext_More) if _, err = proto.GetExtension(msg, pb.E_Ext_More); err != proto.ErrMissingExtension { t.Errorf("got %v, expected ErrMissingExtension", e) } if _, err := proto.GetExtension(msg, pb.E_X215); err == nil { t.Error("expected bad extension error, got nil") } if err := proto.SetExtension(msg, pb.E_X215, 12); err == nil { t.Error("expected extension err") } if err := proto.SetExtension(msg, pb.E_Ext_More, 12); err == nil { t.Error("expected some sort of type mismatch error, got nil") } } func TestNilExtension(t *testing.T) { msg := &pb.MyMessage{ Count: proto.Int32(1), } if err := proto.SetExtension(msg, pb.E_Ext_Text, proto.String("hello")); err != nil { t.Fatal(err) } if err := proto.SetExtension(msg, pb.E_Ext_More, (*pb.Ext)(nil)); err == nil { t.Error("expected SetExtension to fail due to a nil extension") } else if want := "proto: SetExtension called with nil value of type *testdata.Ext"; err.Error() != want { t.Errorf("expected error %v, got %v", want, err) } // Note: if the behavior of Marshal is ever changed to ignore nil extensions, update // this test to verify that E_Ext_Text is properly propagated through marshal->unmarshal. } func TestMarshalUnmarshalRepeatedExtension(t *testing.T) { // Add a repeated extension to the result. tests := []struct { name string ext []*pb.ComplexExtension }{ { "two fields", []*pb.ComplexExtension{ {First: proto.Int32(7)}, {Second: proto.Int32(11)}, }, }, { "repeated field", []*pb.ComplexExtension{ {Third: []int32{1000}}, {Third: []int32{2000}}, }, }, { "two fields and repeated field", []*pb.ComplexExtension{ {Third: []int32{1000}}, {First: proto.Int32(9)}, {Second: proto.Int32(21)}, {Third: []int32{2000}}, }, }, } for _, test := range tests { // Marshal message with a repeated extension. msg1 := new(pb.OtherMessage) err := proto.SetExtension(msg1, pb.E_RComplex, test.ext) if err != nil { t.Fatalf("[%s] Error setting extension: %v", test.name, err) } b, err := proto.Marshal(msg1) if err != nil { t.Fatalf("[%s] Error marshaling message: %v", test.name, err) } // Unmarshal and read the merged proto. msg2 := new(pb.OtherMessage) err = proto.Unmarshal(b, msg2) if err != nil { t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) } e, err := proto.GetExtension(msg2, pb.E_RComplex) if err != nil { t.Fatalf("[%s] Error getting extension: %v", test.name, err) } ext := e.([]*pb.ComplexExtension) if ext == nil { t.Fatalf("[%s] Invalid extension", test.name) } if !reflect.DeepEqual(ext, test.ext) { t.Errorf("[%s] Wrong value for ComplexExtension: got: %v want: %v\n", test.name, ext, test.ext) } } } func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) { // We may see multiple instances of the same extension in the wire // format. For example, the proto compiler may encode custom options in // this way. Here, we verify that we merge the extensions together. tests := []struct { name string ext []*pb.ComplexExtension }{ { "two fields", []*pb.ComplexExtension{ {First: proto.Int32(7)}, {Second: proto.Int32(11)}, }, }, { "repeated field", []*pb.ComplexExtension{ {Third: []int32{1000}}, {Third: []int32{2000}}, }, }, { "two fields and repeated field", []*pb.ComplexExtension{ {Third: []int32{1000}}, {First: proto.Int32(9)}, {Second: proto.Int32(21)}, {Third: []int32{2000}}, }, }, } for _, test := range tests { var buf bytes.Buffer var want pb.ComplexExtension // Generate a serialized representation of a repeated extension // by catenating bytes together. for i, e := range test.ext { // Merge to create the wanted proto. proto.Merge(&want, e) // serialize the message msg := new(pb.OtherMessage) err := proto.SetExtension(msg, pb.E_Complex, e) if err != nil { t.Fatalf("[%s] Error setting extension %d: %v", test.name, i, err) } b, err := proto.Marshal(msg) if err != nil { t.Fatalf("[%s] Error marshaling message %d: %v", test.name, i, err) } buf.Write(b) } // Unmarshal and read the merged proto. msg2 := new(pb.OtherMessage) err := proto.Unmarshal(buf.Bytes(), msg2) if err != nil { t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) } e, err := proto.GetExtension(msg2, pb.E_Complex) if err != nil { t.Fatalf("[%s] Error getting extension: %v", test.name, err) } ext := e.(*pb.ComplexExtension) if ext == nil { t.Fatalf("[%s] Invalid extension", test.name) } if !reflect.DeepEqual(*ext, want) { t.Errorf("[%s] Wrong value for ComplexExtension: got: %s want: %s\n", test.name, ext, &want) } } } func TestClearAllExtensions(t *testing.T) { // unregistered extension desc := &proto.ExtensionDesc{ ExtendedType: (*pb.MyMessage)(nil), ExtensionType: (*bool)(nil), Field: 101010100, Name: "emptyextension", Tag: "varint,0,opt", } m := &pb.MyMessage{} if proto.HasExtension(m, desc) { t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) } if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) } if !proto.HasExtension(m, desc) { t.Errorf("proto.HasExtension(%s): got false, want true", proto.MarshalTextString(m)) } proto.ClearAllExtensions(m) if proto.HasExtension(m, desc) { t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) } } func TestMarshalRace(t *testing.T) { // unregistered extension desc := &proto.ExtensionDesc{ ExtendedType: (*pb.MyMessage)(nil), ExtensionType: (*bool)(nil), Field: 101010100, Name: "emptyextension", Tag: "varint,0,opt", } m := &pb.MyMessage{Count: proto.Int32(4)} if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) } var g errgroup.Group for n := 3; n > 0; n-- { g.Go(func() error { _, err := proto.Marshal(m) return err }) } if err := g.Wait(); err != nil { t.Fatal(err) } } ================================================ FILE: src/github.com/golang/protobuf/proto/lib.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. /* Package proto converts data structures to and from the wire format of protocol buffers. It works in concert with the Go source code generated for .proto files by the protocol compiler. A summary of the properties of the protocol buffer interface for a protocol buffer variable v: - Names are turned from camel_case to CamelCase for export. - There are no methods on v to set fields; just treat them as structure fields. - There are getters that return a field's value if set, and return the field's default value if unset. The getters work even if the receiver is a nil message. - The zero value for a struct is its correct initialization state. All desired fields must be set before marshaling. - A Reset() method will restore a protobuf struct to its zero state. - Non-repeated fields are pointers to the values; nil means unset. That is, optional or required field int32 f becomes F *int32. - Repeated fields are slices. - Helper functions are available to aid the setting of fields. msg.Foo = proto.String("hello") // set field - Constants are defined to hold the default values of all fields that have them. They have the form Default_StructName_FieldName. Because the getter methods handle defaulted values, direct use of these constants should be rare. - Enums are given type names and maps from names to values. Enum values are prefixed by the enclosing message's name, or by the enum's type name if it is a top-level enum. Enum types have a String method, and a Enum method to assist in message construction. - Nested messages, groups and enums have type names prefixed with the name of the surrounding message type. - Extensions are given descriptor names that start with E_, followed by an underscore-delimited list of the nested messages that contain it (if any) followed by the CamelCased name of the extension field itself. HasExtension, ClearExtension, GetExtension and SetExtension are functions for manipulating extensions. - Oneof field sets are given a single field in their message, with distinguished wrapper types for each possible field value. - Marshal and Unmarshal are functions to encode and decode the wire format. When the .proto file specifies `syntax="proto3"`, there are some differences: - Non-repeated fields of non-message type are values instead of pointers. - Enum types do not get an Enum method. The simplest way to describe this is to see an example. Given file test.proto, containing package example; enum FOO { X = 17; } message Test { required string label = 1; optional int32 type = 2 [default=77]; repeated int64 reps = 3; optional group OptionalGroup = 4 { required string RequiredField = 5; } oneof union { int32 number = 6; string name = 7; } } The resulting file, test.pb.go, is: package example import proto "github.com/golang/protobuf/proto" import math "math" type FOO int32 const ( FOO_X FOO = 17 ) var FOO_name = map[int32]string{ 17: "X", } var FOO_value = map[string]int32{ "X": 17, } func (x FOO) Enum() *FOO { p := new(FOO) *p = x return p } func (x FOO) String() string { return proto.EnumName(FOO_name, int32(x)) } func (x *FOO) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FOO_value, data) if err != nil { return err } *x = FOO(value) return nil } type Test struct { Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` // Types that are valid to be assigned to Union: // *Test_Number // *Test_Name Union isTest_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *Test) Reset() { *m = Test{} } func (m *Test) String() string { return proto.CompactTextString(m) } func (*Test) ProtoMessage() {} type isTest_Union interface { isTest_Union() } type Test_Number struct { Number int32 `protobuf:"varint,6,opt,name=number"` } type Test_Name struct { Name string `protobuf:"bytes,7,opt,name=name"` } func (*Test_Number) isTest_Union() {} func (*Test_Name) isTest_Union() {} func (m *Test) GetUnion() isTest_Union { if m != nil { return m.Union } return nil } const Default_Test_Type int32 = 77 func (m *Test) GetLabel() string { if m != nil && m.Label != nil { return *m.Label } return "" } func (m *Test) GetType() int32 { if m != nil && m.Type != nil { return *m.Type } return Default_Test_Type } func (m *Test) GetOptionalgroup() *Test_OptionalGroup { if m != nil { return m.Optionalgroup } return nil } type Test_OptionalGroup struct { RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` } func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } func (m *Test_OptionalGroup) GetRequiredField() string { if m != nil && m.RequiredField != nil { return *m.RequiredField } return "" } func (m *Test) GetNumber() int32 { if x, ok := m.GetUnion().(*Test_Number); ok { return x.Number } return 0 } func (m *Test) GetName() string { if x, ok := m.GetUnion().(*Test_Name); ok { return x.Name } return "" } func init() { proto.RegisterEnum("example.FOO", FOO_name, FOO_value) } To create and play with a Test object: package main import ( "log" "github.com/golang/protobuf/proto" pb "./example.pb" ) func main() { test := &pb.Test{ Label: proto.String("hello"), Type: proto.Int32(17), Reps: []int64{1, 2, 3}, Optionalgroup: &pb.Test_OptionalGroup{ RequiredField: proto.String("good bye"), }, Union: &pb.Test_Name{"fred"}, } data, err := proto.Marshal(test) if err != nil { log.Fatal("marshaling error: ", err) } newTest := &pb.Test{} err = proto.Unmarshal(data, newTest) if err != nil { log.Fatal("unmarshaling error: ", err) } // Now test and newTest contain the same data. if test.GetLabel() != newTest.GetLabel() { log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) } // Use a type switch to determine which oneof was set. switch u := test.Union.(type) { case *pb.Test_Number: // u.Number contains the number. case *pb.Test_Name: // u.Name contains the string. } // etc. } */ package proto import ( "encoding/json" "fmt" "log" "reflect" "sort" "strconv" "sync" ) // Message is implemented by generated protocol buffer messages. type Message interface { Reset() String() string ProtoMessage() } // Stats records allocation details about the protocol buffer encoders // and decoders. Useful for tuning the library itself. type Stats struct { Emalloc uint64 // mallocs in encode Dmalloc uint64 // mallocs in decode Encode uint64 // number of encodes Decode uint64 // number of decodes Chit uint64 // number of cache hits Cmiss uint64 // number of cache misses Size uint64 // number of sizes } // Set to true to enable stats collection. const collectStats = false var stats Stats // GetStats returns a copy of the global Stats structure. func GetStats() Stats { return stats } // A Buffer is a buffer manager for marshaling and unmarshaling // protocol buffers. It may be reused between invocations to // reduce memory usage. It is not necessary to use a Buffer; // the global functions Marshal and Unmarshal create a // temporary Buffer and are fine for most applications. type Buffer struct { buf []byte // encode/decode byte stream index int // read point // pools of basic types to amortize allocation. bools []bool uint32s []uint32 uint64s []uint64 // extra pools, only used with pointer_reflect.go int32s []int32 int64s []int64 float32s []float32 float64s []float64 } // NewBuffer allocates a new Buffer and initializes its internal data to // the contents of the argument slice. func NewBuffer(e []byte) *Buffer { return &Buffer{buf: e} } // Reset resets the Buffer, ready for marshaling a new protocol buffer. func (p *Buffer) Reset() { p.buf = p.buf[0:0] // for reading/writing p.index = 0 // for reading } // SetBuf replaces the internal buffer with the slice, // ready for unmarshaling the contents of the slice. func (p *Buffer) SetBuf(s []byte) { p.buf = s p.index = 0 } // Bytes returns the contents of the Buffer. func (p *Buffer) Bytes() []byte { return p.buf } /* * Helper routines for simplifying the creation of optional fields of basic type. */ // Bool is a helper routine that allocates a new bool value // to store v and returns a pointer to it. func Bool(v bool) *bool { return &v } // Int32 is a helper routine that allocates a new int32 value // to store v and returns a pointer to it. func Int32(v int32) *int32 { return &v } // Int is a helper routine that allocates a new int32 value // to store v and returns a pointer to it, but unlike Int32 // its argument value is an int. func Int(v int) *int32 { p := new(int32) *p = int32(v) return p } // Int64 is a helper routine that allocates a new int64 value // to store v and returns a pointer to it. func Int64(v int64) *int64 { return &v } // Float32 is a helper routine that allocates a new float32 value // to store v and returns a pointer to it. func Float32(v float32) *float32 { return &v } // Float64 is a helper routine that allocates a new float64 value // to store v and returns a pointer to it. func Float64(v float64) *float64 { return &v } // Uint32 is a helper routine that allocates a new uint32 value // to store v and returns a pointer to it. func Uint32(v uint32) *uint32 { return &v } // Uint64 is a helper routine that allocates a new uint64 value // to store v and returns a pointer to it. func Uint64(v uint64) *uint64 { return &v } // String is a helper routine that allocates a new string value // to store v and returns a pointer to it. func String(v string) *string { return &v } // EnumName is a helper function to simplify printing protocol buffer enums // by name. Given an enum map and a value, it returns a useful string. func EnumName(m map[int32]string, v int32) string { s, ok := m[v] if ok { return s } return strconv.Itoa(int(v)) } // UnmarshalJSONEnum is a helper function to simplify recovering enum int values // from their JSON-encoded representation. Given a map from the enum's symbolic // names to its int values, and a byte buffer containing the JSON-encoded // value, it returns an int32 that can be cast to the enum type by the caller. // // The function can deal with both JSON representations, numeric and symbolic. func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { if data[0] == '"' { // New style: enums are strings. var repr string if err := json.Unmarshal(data, &repr); err != nil { return -1, err } val, ok := m[repr] if !ok { return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) } return val, nil } // Old style: enums are ints. var val int32 if err := json.Unmarshal(data, &val); err != nil { return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) } return val, nil } // DebugPrint dumps the encoded data in b in a debugging format with a header // including the string s. Used in testing but made available for general debugging. func (p *Buffer) DebugPrint(s string, b []byte) { var u uint64 obuf := p.buf index := p.index p.buf = b p.index = 0 depth := 0 fmt.Printf("\n--- %s ---\n", s) out: for { for i := 0; i < depth; i++ { fmt.Print(" ") } index := p.index if index == len(p.buf) { break } op, err := p.DecodeVarint() if err != nil { fmt.Printf("%3d: fetching op err %v\n", index, err) break out } tag := op >> 3 wire := op & 7 switch wire { default: fmt.Printf("%3d: t=%3d unknown wire=%d\n", index, tag, wire) break out case WireBytes: var r []byte r, err = p.DecodeRawBytes(false) if err != nil { break out } fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) if len(r) <= 6 { for i := 0; i < len(r); i++ { fmt.Printf(" %.2x", r[i]) } } else { for i := 0; i < 3; i++ { fmt.Printf(" %.2x", r[i]) } fmt.Printf(" ..") for i := len(r) - 3; i < len(r); i++ { fmt.Printf(" %.2x", r[i]) } } fmt.Printf("\n") case WireFixed32: u, err = p.DecodeFixed32() if err != nil { fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) case WireFixed64: u, err = p.DecodeFixed64() if err != nil { fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) case WireVarint: u, err = p.DecodeVarint() if err != nil { fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) break out } fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) case WireStartGroup: fmt.Printf("%3d: t=%3d start\n", index, tag) depth++ case WireEndGroup: depth-- fmt.Printf("%3d: t=%3d end\n", index, tag) } } if depth != 0 { fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) } fmt.Printf("\n") p.buf = obuf p.index = index } // SetDefaults sets unset protocol buffer fields to their default values. // It only modifies fields that are both unset and have defined defaults. // It recursively sets default values in any non-nil sub-messages. func SetDefaults(pb Message) { setDefaults(reflect.ValueOf(pb), true, false) } // v is a pointer to a struct. func setDefaults(v reflect.Value, recur, zeros bool) { v = v.Elem() defaultMu.RLock() dm, ok := defaults[v.Type()] defaultMu.RUnlock() if !ok { dm = buildDefaultMessage(v.Type()) defaultMu.Lock() defaults[v.Type()] = dm defaultMu.Unlock() } for _, sf := range dm.scalars { f := v.Field(sf.index) if !f.IsNil() { // field already set continue } dv := sf.value if dv == nil && !zeros { // no explicit default, and don't want to set zeros continue } fptr := f.Addr().Interface() // **T // TODO: Consider batching the allocations we do here. switch sf.kind { case reflect.Bool: b := new(bool) if dv != nil { *b = dv.(bool) } *(fptr.(**bool)) = b case reflect.Float32: f := new(float32) if dv != nil { *f = dv.(float32) } *(fptr.(**float32)) = f case reflect.Float64: f := new(float64) if dv != nil { *f = dv.(float64) } *(fptr.(**float64)) = f case reflect.Int32: // might be an enum if ft := f.Type(); ft != int32PtrType { // enum f.Set(reflect.New(ft.Elem())) if dv != nil { f.Elem().SetInt(int64(dv.(int32))) } } else { // int32 field i := new(int32) if dv != nil { *i = dv.(int32) } *(fptr.(**int32)) = i } case reflect.Int64: i := new(int64) if dv != nil { *i = dv.(int64) } *(fptr.(**int64)) = i case reflect.String: s := new(string) if dv != nil { *s = dv.(string) } *(fptr.(**string)) = s case reflect.Uint8: // exceptional case: []byte var b []byte if dv != nil { db := dv.([]byte) b = make([]byte, len(db)) copy(b, db) } else { b = []byte{} } *(fptr.(*[]byte)) = b case reflect.Uint32: u := new(uint32) if dv != nil { *u = dv.(uint32) } *(fptr.(**uint32)) = u case reflect.Uint64: u := new(uint64) if dv != nil { *u = dv.(uint64) } *(fptr.(**uint64)) = u default: log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) } } for _, ni := range dm.nested { f := v.Field(ni) // f is *T or []*T or map[T]*T switch f.Kind() { case reflect.Ptr: if f.IsNil() { continue } setDefaults(f, recur, zeros) case reflect.Slice: for i := 0; i < f.Len(); i++ { e := f.Index(i) if e.IsNil() { continue } setDefaults(e, recur, zeros) } case reflect.Map: for _, k := range f.MapKeys() { e := f.MapIndex(k) if e.IsNil() { continue } setDefaults(e, recur, zeros) } } } } var ( // defaults maps a protocol buffer struct type to a slice of the fields, // with its scalar fields set to their proto-declared non-zero default values. defaultMu sync.RWMutex defaults = make(map[reflect.Type]defaultMessage) int32PtrType = reflect.TypeOf((*int32)(nil)) ) // defaultMessage represents information about the default values of a message. type defaultMessage struct { scalars []scalarField nested []int // struct field index of nested messages } type scalarField struct { index int // struct field index kind reflect.Kind // element type (the T in *T or []T) value interface{} // the proto-declared default value, or nil } // t is a struct type. func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { sprop := GetProperties(t) for _, prop := range sprop.Prop { fi, ok := sprop.decoderTags.get(prop.Tag) if !ok { // XXX_unrecognized continue } ft := t.Field(fi).Type sf, nested, err := fieldDefault(ft, prop) switch { case err != nil: log.Print(err) case nested: dm.nested = append(dm.nested, fi) case sf != nil: sf.index = fi dm.scalars = append(dm.scalars, *sf) } } return dm } // fieldDefault returns the scalarField for field type ft. // sf will be nil if the field can not have a default. // nestedMessage will be true if this is a nested message. // Note that sf.index is not set on return. func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { var canHaveDefault bool switch ft.Kind() { case reflect.Ptr: if ft.Elem().Kind() == reflect.Struct { nestedMessage = true } else { canHaveDefault = true // proto2 scalar field } case reflect.Slice: switch ft.Elem().Kind() { case reflect.Ptr: nestedMessage = true // repeated message case reflect.Uint8: canHaveDefault = true // bytes field } case reflect.Map: if ft.Elem().Kind() == reflect.Ptr { nestedMessage = true // map with message values } } if !canHaveDefault { if nestedMessage { return nil, true, nil } return nil, false, nil } // We now know that ft is a pointer or slice. sf = &scalarField{kind: ft.Elem().Kind()} // scalar fields without defaults if !prop.HasDefault { return sf, false, nil } // a scalar field: either *T or []byte switch ft.Elem().Kind() { case reflect.Bool: x, err := strconv.ParseBool(prop.Default) if err != nil { return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) } sf.value = x case reflect.Float32: x, err := strconv.ParseFloat(prop.Default, 32) if err != nil { return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) } sf.value = float32(x) case reflect.Float64: x, err := strconv.ParseFloat(prop.Default, 64) if err != nil { return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) } sf.value = x case reflect.Int32: x, err := strconv.ParseInt(prop.Default, 10, 32) if err != nil { return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) } sf.value = int32(x) case reflect.Int64: x, err := strconv.ParseInt(prop.Default, 10, 64) if err != nil { return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) } sf.value = x case reflect.String: sf.value = prop.Default case reflect.Uint8: // []byte (not *uint8) sf.value = []byte(prop.Default) case reflect.Uint32: x, err := strconv.ParseUint(prop.Default, 10, 32) if err != nil { return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) } sf.value = uint32(x) case reflect.Uint64: x, err := strconv.ParseUint(prop.Default, 10, 64) if err != nil { return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) } sf.value = x default: return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) } return sf, false, nil } // Map fields may have key types of non-float scalars, strings and enums. // The easiest way to sort them in some deterministic order is to use fmt. // If this turns out to be inefficient we can always consider other options, // such as doing a Schwartzian transform. func mapKeys(vs []reflect.Value) sort.Interface { s := mapKeySorter{ vs: vs, // default Less function: textual comparison less: func(a, b reflect.Value) bool { return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface()) }, } // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps; // numeric keys are sorted numerically. if len(vs) == 0 { return s } switch vs[0].Kind() { case reflect.Int32, reflect.Int64: s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } case reflect.Uint32, reflect.Uint64: s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } } return s } type mapKeySorter struct { vs []reflect.Value less func(a, b reflect.Value) bool } func (s mapKeySorter) Len() int { return len(s.vs) } func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } func (s mapKeySorter) Less(i, j int) bool { return s.less(s.vs[i], s.vs[j]) } // isProto3Zero reports whether v is a zero proto3 value. func isProto3Zero(v reflect.Value) bool { switch v.Kind() { case reflect.Bool: return !v.Bool() case reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint32, reflect.Uint64: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.String: return v.String() == "" } return false } // ProtoPackageIsVersion2 is referenced from generated protocol buffer files // to assert that that code is compatible with this version of the proto package. const ProtoPackageIsVersion2 = true // ProtoPackageIsVersion1 is referenced from generated protocol buffer files // to assert that that code is compatible with this version of the proto package. const ProtoPackageIsVersion1 = true ================================================ FILE: src/github.com/golang/protobuf/proto/map_test.go ================================================ package proto_test import ( "fmt" "testing" "github.com/golang/protobuf/proto" ppb "github.com/golang/protobuf/proto/proto3_proto" ) func marshalled() []byte { m := &ppb.IntMaps{} for i := 0; i < 1000; i++ { m.Maps = append(m.Maps, &ppb.IntMap{ Rtt: map[int32]int32{1: 2}, }) } b, err := proto.Marshal(m) if err != nil { panic(fmt.Sprintf("Can't marshal %+v: %v", m, err)) } return b } func BenchmarkConcurrentMapUnmarshal(b *testing.B) { in := marshalled() b.RunParallel(func(pb *testing.PB) { for pb.Next() { var out ppb.IntMaps if err := proto.Unmarshal(in, &out); err != nil { b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) } } }) } func BenchmarkSequentialMapUnmarshal(b *testing.B) { in := marshalled() b.ResetTimer() for i := 0; i < b.N; i++ { var out ppb.IntMaps if err := proto.Unmarshal(in, &out); err != nil { b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) } } } ================================================ FILE: src/github.com/golang/protobuf/proto/message_set.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto /* * Support for message sets. */ import ( "bytes" "encoding/json" "errors" "fmt" "reflect" "sort" ) // errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. // A message type ID is required for storing a protocol buffer in a message set. var errNoMessageTypeID = errors.New("proto does not have a message type ID") // The first two types (_MessageSet_Item and messageSet) // model what the protocol compiler produces for the following protocol message: // message MessageSet { // repeated group Item = 1 { // required int32 type_id = 2; // required string message = 3; // }; // } // That is the MessageSet wire format. We can't use a proto to generate these // because that would introduce a circular dependency between it and this package. type _MessageSet_Item struct { TypeId *int32 `protobuf:"varint,2,req,name=type_id"` Message []byte `protobuf:"bytes,3,req,name=message"` } type messageSet struct { Item []*_MessageSet_Item `protobuf:"group,1,rep"` XXX_unrecognized []byte // TODO: caching? } // Make sure messageSet is a Message. var _ Message = (*messageSet)(nil) // messageTypeIder is an interface satisfied by a protocol buffer type // that may be stored in a MessageSet. type messageTypeIder interface { MessageTypeId() int32 } func (ms *messageSet) find(pb Message) *_MessageSet_Item { mti, ok := pb.(messageTypeIder) if !ok { return nil } id := mti.MessageTypeId() for _, item := range ms.Item { if *item.TypeId == id { return item } } return nil } func (ms *messageSet) Has(pb Message) bool { if ms.find(pb) != nil { return true } return false } func (ms *messageSet) Unmarshal(pb Message) error { if item := ms.find(pb); item != nil { return Unmarshal(item.Message, pb) } if _, ok := pb.(messageTypeIder); !ok { return errNoMessageTypeID } return nil // TODO: return error instead? } func (ms *messageSet) Marshal(pb Message) error { msg, err := Marshal(pb) if err != nil { return err } if item := ms.find(pb); item != nil { // reuse existing item item.Message = msg return nil } mti, ok := pb.(messageTypeIder) if !ok { return errNoMessageTypeID } mtid := mti.MessageTypeId() ms.Item = append(ms.Item, &_MessageSet_Item{ TypeId: &mtid, Message: msg, }) return nil } func (ms *messageSet) Reset() { *ms = messageSet{} } func (ms *messageSet) String() string { return CompactTextString(ms) } func (*messageSet) ProtoMessage() {} // Support for the message_set_wire_format message option. func skipVarint(buf []byte) []byte { i := 0 for ; buf[i]&0x80 != 0; i++ { } return buf[i+1:] } // MarshalMessageSet encodes the extension map represented by m in the message set wire format. // It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. func MarshalMessageSet(exts interface{}) ([]byte, error) { var m map[int32]Extension switch exts := exts.(type) { case *XXX_InternalExtensions: if err := encodeExtensions(exts); err != nil { return nil, err } m, _ = exts.extensionsRead() case map[int32]Extension: if err := encodeExtensionsMap(exts); err != nil { return nil, err } m = exts default: return nil, errors.New("proto: not an extension map") } // Sort extension IDs to provide a deterministic encoding. // See also enc_map in encode.go. ids := make([]int, 0, len(m)) for id := range m { ids = append(ids, int(id)) } sort.Ints(ids) ms := &messageSet{Item: make([]*_MessageSet_Item, 0, len(m))} for _, id := range ids { e := m[int32(id)] // Remove the wire type and field number varint, as well as the length varint. msg := skipVarint(skipVarint(e.enc)) ms.Item = append(ms.Item, &_MessageSet_Item{ TypeId: Int32(int32(id)), Message: msg, }) } return Marshal(ms) } // UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. // It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option. func UnmarshalMessageSet(buf []byte, exts interface{}) error { var m map[int32]Extension switch exts := exts.(type) { case *XXX_InternalExtensions: m = exts.extensionsWrite() case map[int32]Extension: m = exts default: return errors.New("proto: not an extension map") } ms := new(messageSet) if err := Unmarshal(buf, ms); err != nil { return err } for _, item := range ms.Item { id := *item.TypeId msg := item.Message // Restore wire type and field number varint, plus length varint. // Be careful to preserve duplicate items. b := EncodeVarint(uint64(id)<<3 | WireBytes) if ext, ok := m[id]; ok { // Existing data; rip off the tag and length varint // so we join the new data correctly. // We can assume that ext.enc is set because we are unmarshaling. o := ext.enc[len(b):] // skip wire type and field number _, n := DecodeVarint(o) // calculate length of length varint o = o[n:] // skip length varint msg = append(o, msg...) // join old data and new data } b = append(b, EncodeVarint(uint64(len(msg)))...) b = append(b, msg...) m[id] = Extension{enc: b} } return nil } // MarshalMessageSetJSON encodes the extension map represented by m in JSON format. // It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { var m map[int32]Extension switch exts := exts.(type) { case *XXX_InternalExtensions: m, _ = exts.extensionsRead() case map[int32]Extension: m = exts default: return nil, errors.New("proto: not an extension map") } var b bytes.Buffer b.WriteByte('{') // Process the map in key order for deterministic output. ids := make([]int32, 0, len(m)) for id := range m { ids = append(ids, id) } sort.Sort(int32Slice(ids)) // int32Slice defined in text.go for i, id := range ids { ext := m[id] if i > 0 { b.WriteByte(',') } msd, ok := messageSetMap[id] if !ok { // Unknown type; we can't render it, so skip it. continue } fmt.Fprintf(&b, `"[%s]":`, msd.name) x := ext.value if x == nil { x = reflect.New(msd.t.Elem()).Interface() if err := Unmarshal(ext.enc, x.(Message)); err != nil { return nil, err } } d, err := json.Marshal(x) if err != nil { return nil, err } b.Write(d) } b.WriteByte('}') return b.Bytes(), nil } // UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. // It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error { // Common-case fast path. if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { return nil } // This is fairly tricky, and it's not clear that it is needed. return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented") } // A global registry of types that can be used in a MessageSet. var messageSetMap = make(map[int32]messageSetDesc) type messageSetDesc struct { t reflect.Type // pointer to struct name string } // RegisterMessageSetType is called from the generated code. func RegisterMessageSetType(m Message, fieldNum int32, name string) { messageSetMap[fieldNum] = messageSetDesc{ t: reflect.TypeOf(m), name: name, } } ================================================ FILE: src/github.com/golang/protobuf/proto/message_set_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto import ( "bytes" "testing" ) func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { // Check that a repeated message set entry will be concatenated. in := &messageSet{ Item: []*_MessageSet_Item{ {TypeId: Int32(12345), Message: []byte("hoo")}, {TypeId: Int32(12345), Message: []byte("hah")}, }, } b, err := Marshal(in) if err != nil { t.Fatalf("Marshal: %v", err) } t.Logf("Marshaled bytes: %q", b) var extensions XXX_InternalExtensions if err := UnmarshalMessageSet(b, &extensions); err != nil { t.Fatalf("UnmarshalMessageSet: %v", err) } ext, ok := extensions.p.extensionMap[12345] if !ok { t.Fatalf("Didn't retrieve extension 12345; map is %v", extensions.p.extensionMap) } // Skip wire type/field number and length varints. got := skipVarint(skipVarint(ext.enc)) if want := []byte("hoohah"); !bytes.Equal(got, want) { t.Errorf("Combined extension is %q, want %q", got, want) } } ================================================ FILE: src/github.com/golang/protobuf/proto/pointer_reflect.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/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. // +build appengine js // This file contains an implementation of proto field accesses using package reflect. // It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can // be used on App Engine. package proto import ( "math" "reflect" ) // A structPointer is a pointer to a struct. type structPointer struct { v reflect.Value } // toStructPointer returns a structPointer equivalent to the given reflect value. // The reflect value must itself be a pointer to a struct. func toStructPointer(v reflect.Value) structPointer { return structPointer{v} } // IsNil reports whether p is nil. func structPointer_IsNil(p structPointer) bool { return p.v.IsNil() } // Interface returns the struct pointer as an interface value. func structPointer_Interface(p structPointer, _ reflect.Type) interface{} { return p.v.Interface() } // A field identifies a field in a struct, accessible from a structPointer. // In this implementation, a field is identified by the sequence of field indices // passed to reflect's FieldByIndex. type field []int // toField returns a field equivalent to the given reflect field. func toField(f *reflect.StructField) field { return f.Index } // invalidField is an invalid field identifier. var invalidField = field(nil) // IsValid reports whether the field identifier is valid. func (f field) IsValid() bool { return f != nil } // field returns the given field in the struct as a reflect value. func structPointer_field(p structPointer, f field) reflect.Value { // Special case: an extension map entry with a value of type T // passes a *T to the struct-handling code with a zero field, // expecting that it will be treated as equivalent to *struct{ X T }, // which has the same memory layout. We have to handle that case // specially, because reflect will panic if we call FieldByIndex on a // non-struct. if f == nil { return p.v.Elem() } return p.v.Elem().FieldByIndex(f) } // ifield returns the given field in the struct as an interface value. func structPointer_ifield(p structPointer, f field) interface{} { return structPointer_field(p, f).Addr().Interface() } // Bytes returns the address of a []byte field in the struct. func structPointer_Bytes(p structPointer, f field) *[]byte { return structPointer_ifield(p, f).(*[]byte) } // BytesSlice returns the address of a [][]byte field in the struct. func structPointer_BytesSlice(p structPointer, f field) *[][]byte { return structPointer_ifield(p, f).(*[][]byte) } // Bool returns the address of a *bool field in the struct. func structPointer_Bool(p structPointer, f field) **bool { return structPointer_ifield(p, f).(**bool) } // BoolVal returns the address of a bool field in the struct. func structPointer_BoolVal(p structPointer, f field) *bool { return structPointer_ifield(p, f).(*bool) } // BoolSlice returns the address of a []bool field in the struct. func structPointer_BoolSlice(p structPointer, f field) *[]bool { return structPointer_ifield(p, f).(*[]bool) } // String returns the address of a *string field in the struct. func structPointer_String(p structPointer, f field) **string { return structPointer_ifield(p, f).(**string) } // StringVal returns the address of a string field in the struct. func structPointer_StringVal(p structPointer, f field) *string { return structPointer_ifield(p, f).(*string) } // StringSlice returns the address of a []string field in the struct. func structPointer_StringSlice(p structPointer, f field) *[]string { return structPointer_ifield(p, f).(*[]string) } // Extensions returns the address of an extension map field in the struct. func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { return structPointer_ifield(p, f).(*XXX_InternalExtensions) } // ExtMap returns the address of an extension map field in the struct. func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { return structPointer_ifield(p, f).(*map[int32]Extension) } // NewAt returns the reflect.Value for a pointer to a field in the struct. func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { return structPointer_field(p, f).Addr() } // SetStructPointer writes a *struct field in the struct. func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { structPointer_field(p, f).Set(q.v) } // GetStructPointer reads a *struct field in the struct. func structPointer_GetStructPointer(p structPointer, f field) structPointer { return structPointer{structPointer_field(p, f)} } // StructPointerSlice the address of a []*struct field in the struct. func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice { return structPointerSlice{structPointer_field(p, f)} } // A structPointerSlice represents the address of a slice of pointers to structs // (themselves messages or groups). That is, v.Type() is *[]*struct{...}. type structPointerSlice struct { v reflect.Value } func (p structPointerSlice) Len() int { return p.v.Len() } func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} } func (p structPointerSlice) Append(q structPointer) { p.v.Set(reflect.Append(p.v, q.v)) } var ( int32Type = reflect.TypeOf(int32(0)) uint32Type = reflect.TypeOf(uint32(0)) float32Type = reflect.TypeOf(float32(0)) int64Type = reflect.TypeOf(int64(0)) uint64Type = reflect.TypeOf(uint64(0)) float64Type = reflect.TypeOf(float64(0)) ) // A word32 represents a field of type *int32, *uint32, *float32, or *enum. // That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable. type word32 struct { v reflect.Value } // IsNil reports whether p is nil. func word32_IsNil(p word32) bool { return p.v.IsNil() } // Set sets p to point at a newly allocated word with bits set to x. func word32_Set(p word32, o *Buffer, x uint32) { t := p.v.Type().Elem() switch t { case int32Type: if len(o.int32s) == 0 { o.int32s = make([]int32, uint32PoolSize) } o.int32s[0] = int32(x) p.v.Set(reflect.ValueOf(&o.int32s[0])) o.int32s = o.int32s[1:] return case uint32Type: if len(o.uint32s) == 0 { o.uint32s = make([]uint32, uint32PoolSize) } o.uint32s[0] = x p.v.Set(reflect.ValueOf(&o.uint32s[0])) o.uint32s = o.uint32s[1:] return case float32Type: if len(o.float32s) == 0 { o.float32s = make([]float32, uint32PoolSize) } o.float32s[0] = math.Float32frombits(x) p.v.Set(reflect.ValueOf(&o.float32s[0])) o.float32s = o.float32s[1:] return } // must be enum p.v.Set(reflect.New(t)) p.v.Elem().SetInt(int64(int32(x))) } // Get gets the bits pointed at by p, as a uint32. func word32_Get(p word32) uint32 { elem := p.v.Elem() switch elem.Kind() { case reflect.Int32: return uint32(elem.Int()) case reflect.Uint32: return uint32(elem.Uint()) case reflect.Float32: return math.Float32bits(float32(elem.Float())) } panic("unreachable") } // Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct. func structPointer_Word32(p structPointer, f field) word32 { return word32{structPointer_field(p, f)} } // A word32Val represents a field of type int32, uint32, float32, or enum. // That is, v.Type() is int32, uint32, float32, or enum and v is assignable. type word32Val struct { v reflect.Value } // Set sets *p to x. func word32Val_Set(p word32Val, x uint32) { switch p.v.Type() { case int32Type: p.v.SetInt(int64(x)) return case uint32Type: p.v.SetUint(uint64(x)) return case float32Type: p.v.SetFloat(float64(math.Float32frombits(x))) return } // must be enum p.v.SetInt(int64(int32(x))) } // Get gets the bits pointed at by p, as a uint32. func word32Val_Get(p word32Val) uint32 { elem := p.v switch elem.Kind() { case reflect.Int32: return uint32(elem.Int()) case reflect.Uint32: return uint32(elem.Uint()) case reflect.Float32: return math.Float32bits(float32(elem.Float())) } panic("unreachable") } // Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct. func structPointer_Word32Val(p structPointer, f field) word32Val { return word32Val{structPointer_field(p, f)} } // A word32Slice is a slice of 32-bit values. // That is, v.Type() is []int32, []uint32, []float32, or []enum. type word32Slice struct { v reflect.Value } func (p word32Slice) Append(x uint32) { n, m := p.v.Len(), p.v.Cap() if n < m { p.v.SetLen(n + 1) } else { t := p.v.Type().Elem() p.v.Set(reflect.Append(p.v, reflect.Zero(t))) } elem := p.v.Index(n) switch elem.Kind() { case reflect.Int32: elem.SetInt(int64(int32(x))) case reflect.Uint32: elem.SetUint(uint64(x)) case reflect.Float32: elem.SetFloat(float64(math.Float32frombits(x))) } } func (p word32Slice) Len() int { return p.v.Len() } func (p word32Slice) Index(i int) uint32 { elem := p.v.Index(i) switch elem.Kind() { case reflect.Int32: return uint32(elem.Int()) case reflect.Uint32: return uint32(elem.Uint()) case reflect.Float32: return math.Float32bits(float32(elem.Float())) } panic("unreachable") } // Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct. func structPointer_Word32Slice(p structPointer, f field) word32Slice { return word32Slice{structPointer_field(p, f)} } // word64 is like word32 but for 64-bit values. type word64 struct { v reflect.Value } func word64_Set(p word64, o *Buffer, x uint64) { t := p.v.Type().Elem() switch t { case int64Type: if len(o.int64s) == 0 { o.int64s = make([]int64, uint64PoolSize) } o.int64s[0] = int64(x) p.v.Set(reflect.ValueOf(&o.int64s[0])) o.int64s = o.int64s[1:] return case uint64Type: if len(o.uint64s) == 0 { o.uint64s = make([]uint64, uint64PoolSize) } o.uint64s[0] = x p.v.Set(reflect.ValueOf(&o.uint64s[0])) o.uint64s = o.uint64s[1:] return case float64Type: if len(o.float64s) == 0 { o.float64s = make([]float64, uint64PoolSize) } o.float64s[0] = math.Float64frombits(x) p.v.Set(reflect.ValueOf(&o.float64s[0])) o.float64s = o.float64s[1:] return } panic("unreachable") } func word64_IsNil(p word64) bool { return p.v.IsNil() } func word64_Get(p word64) uint64 { elem := p.v.Elem() switch elem.Kind() { case reflect.Int64: return uint64(elem.Int()) case reflect.Uint64: return elem.Uint() case reflect.Float64: return math.Float64bits(elem.Float()) } panic("unreachable") } func structPointer_Word64(p structPointer, f field) word64 { return word64{structPointer_field(p, f)} } // word64Val is like word32Val but for 64-bit values. type word64Val struct { v reflect.Value } func word64Val_Set(p word64Val, o *Buffer, x uint64) { switch p.v.Type() { case int64Type: p.v.SetInt(int64(x)) return case uint64Type: p.v.SetUint(x) return case float64Type: p.v.SetFloat(math.Float64frombits(x)) return } panic("unreachable") } func word64Val_Get(p word64Val) uint64 { elem := p.v switch elem.Kind() { case reflect.Int64: return uint64(elem.Int()) case reflect.Uint64: return elem.Uint() case reflect.Float64: return math.Float64bits(elem.Float()) } panic("unreachable") } func structPointer_Word64Val(p structPointer, f field) word64Val { return word64Val{structPointer_field(p, f)} } type word64Slice struct { v reflect.Value } func (p word64Slice) Append(x uint64) { n, m := p.v.Len(), p.v.Cap() if n < m { p.v.SetLen(n + 1) } else { t := p.v.Type().Elem() p.v.Set(reflect.Append(p.v, reflect.Zero(t))) } elem := p.v.Index(n) switch elem.Kind() { case reflect.Int64: elem.SetInt(int64(int64(x))) case reflect.Uint64: elem.SetUint(uint64(x)) case reflect.Float64: elem.SetFloat(float64(math.Float64frombits(x))) } } func (p word64Slice) Len() int { return p.v.Len() } func (p word64Slice) Index(i int) uint64 { elem := p.v.Index(i) switch elem.Kind() { case reflect.Int64: return uint64(elem.Int()) case reflect.Uint64: return uint64(elem.Uint()) case reflect.Float64: return math.Float64bits(float64(elem.Float())) } panic("unreachable") } func structPointer_Word64Slice(p structPointer, f field) word64Slice { return word64Slice{structPointer_field(p, f)} } ================================================ FILE: src/github.com/golang/protobuf/proto/pointer_unsafe.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/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. // +build !appengine,!js // This file contains the implementation of the proto field accesses using package unsafe. package proto import ( "reflect" "unsafe" ) // NOTE: These type_Foo functions would more idiomatically be methods, // but Go does not allow methods on pointer types, and we must preserve // some pointer type for the garbage collector. We use these // funcs with clunky names as our poor approximation to methods. // // An alternative would be // type structPointer struct { p unsafe.Pointer } // but that does not registerize as well. // A structPointer is a pointer to a struct. type structPointer unsafe.Pointer // toStructPointer returns a structPointer equivalent to the given reflect value. func toStructPointer(v reflect.Value) structPointer { return structPointer(unsafe.Pointer(v.Pointer())) } // IsNil reports whether p is nil. func structPointer_IsNil(p structPointer) bool { return p == nil } // Interface returns the struct pointer, assumed to have element type t, // as an interface value. func structPointer_Interface(p structPointer, t reflect.Type) interface{} { return reflect.NewAt(t, unsafe.Pointer(p)).Interface() } // A field identifies a field in a struct, accessible from a structPointer. // In this implementation, a field is identified by its byte offset from the start of the struct. type field uintptr // toField returns a field equivalent to the given reflect field. func toField(f *reflect.StructField) field { return field(f.Offset) } // invalidField is an invalid field identifier. const invalidField = ^field(0) // IsValid reports whether the field identifier is valid. func (f field) IsValid() bool { return f != ^field(0) } // Bytes returns the address of a []byte field in the struct. func structPointer_Bytes(p structPointer, f field) *[]byte { return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // BytesSlice returns the address of a [][]byte field in the struct. func structPointer_BytesSlice(p structPointer, f field) *[][]byte { return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // Bool returns the address of a *bool field in the struct. func structPointer_Bool(p structPointer, f field) **bool { return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // BoolVal returns the address of a bool field in the struct. func structPointer_BoolVal(p structPointer, f field) *bool { return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // BoolSlice returns the address of a []bool field in the struct. func structPointer_BoolSlice(p structPointer, f field) *[]bool { return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // String returns the address of a *string field in the struct. func structPointer_String(p structPointer, f field) **string { return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // StringVal returns the address of a string field in the struct. func structPointer_StringVal(p structPointer, f field) *string { return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // StringSlice returns the address of a []string field in the struct. func structPointer_StringSlice(p structPointer, f field) *[]string { return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // ExtMap returns the address of an extension map field in the struct. func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { return (*XXX_InternalExtensions)(unsafe.Pointer(uintptr(p) + uintptr(f))) } func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // NewAt returns the reflect.Value for a pointer to a field in the struct. func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f))) } // SetStructPointer writes a *struct field in the struct. func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q } // GetStructPointer reads a *struct field in the struct. func structPointer_GetStructPointer(p structPointer, f field) structPointer { return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // StructPointerSlice the address of a []*struct field in the struct. func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice { return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups). type structPointerSlice []structPointer func (v *structPointerSlice) Len() int { return len(*v) } func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] } func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) } // A word32 is the address of a "pointer to 32-bit value" field. type word32 **uint32 // IsNil reports whether *v is nil. func word32_IsNil(p word32) bool { return *p == nil } // Set sets *v to point at a newly allocated word set to x. func word32_Set(p word32, o *Buffer, x uint32) { if len(o.uint32s) == 0 { o.uint32s = make([]uint32, uint32PoolSize) } o.uint32s[0] = x *p = &o.uint32s[0] o.uint32s = o.uint32s[1:] } // Get gets the value pointed at by *v. func word32_Get(p word32) uint32 { return **p } // Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct. func structPointer_Word32(p structPointer, f field) word32 { return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } // A word32Val is the address of a 32-bit value field. type word32Val *uint32 // Set sets *p to x. func word32Val_Set(p word32Val, x uint32) { *p = x } // Get gets the value pointed at by p. func word32Val_Get(p word32Val) uint32 { return *p } // Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct. func structPointer_Word32Val(p structPointer, f field) word32Val { return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } // A word32Slice is a slice of 32-bit values. type word32Slice []uint32 func (v *word32Slice) Append(x uint32) { *v = append(*v, x) } func (v *word32Slice) Len() int { return len(*v) } func (v *word32Slice) Index(i int) uint32 { return (*v)[i] } // Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct. func structPointer_Word32Slice(p structPointer, f field) *word32Slice { return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) } // word64 is like word32 but for 64-bit values. type word64 **uint64 func word64_Set(p word64, o *Buffer, x uint64) { if len(o.uint64s) == 0 { o.uint64s = make([]uint64, uint64PoolSize) } o.uint64s[0] = x *p = &o.uint64s[0] o.uint64s = o.uint64s[1:] } func word64_IsNil(p word64) bool { return *p == nil } func word64_Get(p word64) uint64 { return **p } func structPointer_Word64(p structPointer, f field) word64 { return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } // word64Val is like word32Val but for 64-bit values. type word64Val *uint64 func word64Val_Set(p word64Val, o *Buffer, x uint64) { *p = x } func word64Val_Get(p word64Val) uint64 { return *p } func structPointer_Word64Val(p structPointer, f field) word64Val { return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) } // word64Slice is like word32Slice but for 64-bit values. type word64Slice []uint64 func (v *word64Slice) Append(x uint64) { *v = append(*v, x) } func (v *word64Slice) Len() int { return len(*v) } func (v *word64Slice) Index(i int) uint64 { return (*v)[i] } func structPointer_Word64Slice(p structPointer, f field) *word64Slice { return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) } ================================================ FILE: src/github.com/golang/protobuf/proto/properties.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto /* * Routines for encoding data into the wire format for protocol buffers. */ import ( "fmt" "log" "os" "reflect" "sort" "strconv" "strings" "sync" ) const debug bool = false // Constants that identify the encoding of a value on the wire. const ( WireVarint = 0 WireFixed64 = 1 WireBytes = 2 WireStartGroup = 3 WireEndGroup = 4 WireFixed32 = 5 ) const startSize = 10 // initial slice/string sizes // Encoders are defined in encode.go // An encoder outputs the full representation of a field, including its // tag and encoder type. type encoder func(p *Buffer, prop *Properties, base structPointer) error // A valueEncoder encodes a single integer in a particular encoding. type valueEncoder func(o *Buffer, x uint64) error // Sizers are defined in encode.go // A sizer returns the encoded size of a field, including its tag and encoder // type. type sizer func(prop *Properties, base structPointer) int // A valueSizer returns the encoded size of a single integer in a particular // encoding. type valueSizer func(x uint64) int // Decoders are defined in decode.go // A decoder creates a value from its wire representation. // Unrecognized subelements are saved in unrec. type decoder func(p *Buffer, prop *Properties, base structPointer) error // A valueDecoder decodes a single integer in a particular encoding. type valueDecoder func(o *Buffer) (x uint64, err error) // A oneofMarshaler does the marshaling for all oneof fields in a message. type oneofMarshaler func(Message, *Buffer) error // A oneofUnmarshaler does the unmarshaling for a oneof field in a message. type oneofUnmarshaler func(Message, int, int, *Buffer) (bool, error) // A oneofSizer does the sizing for all oneof fields in a message. type oneofSizer func(Message) int // tagMap is an optimization over map[int]int for typical protocol buffer // use-cases. Encoded protocol buffers are often in tag order with small tag // numbers. type tagMap struct { fastTags []int slowTags map[int]int } // tagMapFastLimit is the upper bound on the tag number that will be stored in // the tagMap slice rather than its map. const tagMapFastLimit = 1024 func (p *tagMap) get(t int) (int, bool) { if t > 0 && t < tagMapFastLimit { if t >= len(p.fastTags) { return 0, false } fi := p.fastTags[t] return fi, fi >= 0 } fi, ok := p.slowTags[t] return fi, ok } func (p *tagMap) put(t int, fi int) { if t > 0 && t < tagMapFastLimit { for len(p.fastTags) < t+1 { p.fastTags = append(p.fastTags, -1) } p.fastTags[t] = fi return } if p.slowTags == nil { p.slowTags = make(map[int]int) } p.slowTags[t] = fi } // StructProperties represents properties for all the fields of a struct. // decoderTags and decoderOrigNames should only be used by the decoder. type StructProperties struct { Prop []*Properties // properties for each field reqCount int // required count decoderTags tagMap // map from proto tag to struct field number decoderOrigNames map[string]int // map from original name to struct field number order []int // list of struct field numbers in tag order unrecField field // field id of the XXX_unrecognized []byte field extendable bool // is this an extendable proto oneofMarshaler oneofMarshaler oneofUnmarshaler oneofUnmarshaler oneofSizer oneofSizer stype reflect.Type // OneofTypes contains information about the oneof fields in this message. // It is keyed by the original name of a field. OneofTypes map[string]*OneofProperties } // OneofProperties represents information about a specific field in a oneof. type OneofProperties struct { Type reflect.Type // pointer to generated struct type for this oneof field Field int // struct field number of the containing oneof in the message Prop *Properties } // Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. // See encode.go, (*Buffer).enc_struct. func (sp *StructProperties) Len() int { return len(sp.order) } func (sp *StructProperties) Less(i, j int) bool { return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag } func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } // Properties represents the protocol-specific behavior of a single struct field. type Properties struct { Name string // name of the field, for error messages OrigName string // original name before protocol compiler (always set) JSONName string // name to use for JSON; determined by protoc Wire string WireType int Tag int Required bool Optional bool Repeated bool Packed bool // relevant for repeated primitives only Enum string // set for enum types only proto3 bool // whether this is known to be a proto3 field; set for []byte only oneof bool // whether this is a oneof field Default string // default value HasDefault bool // whether an explicit default was provided def_uint64 uint64 enc encoder valEnc valueEncoder // set for bool and numeric types only field field tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType) tagbuf [8]byte stype reflect.Type // set for struct types only sprop *StructProperties // set for struct types only isMarshaler bool isUnmarshaler bool mtype reflect.Type // set for map types only mkeyprop *Properties // set for map types only mvalprop *Properties // set for map types only size sizer valSize valueSizer // set for bool and numeric types only dec decoder valDec valueDecoder // set for bool and numeric types only // If this is a packable field, this will be the decoder for the packed version of the field. packedDec decoder } // String formats the properties in the protobuf struct field tag style. func (p *Properties) String() string { s := p.Wire s = "," s += strconv.Itoa(p.Tag) if p.Required { s += ",req" } if p.Optional { s += ",opt" } if p.Repeated { s += ",rep" } if p.Packed { s += ",packed" } s += ",name=" + p.OrigName if p.JSONName != p.OrigName { s += ",json=" + p.JSONName } if p.proto3 { s += ",proto3" } if p.oneof { s += ",oneof" } if len(p.Enum) > 0 { s += ",enum=" + p.Enum } if p.HasDefault { s += ",def=" + p.Default } return s } // Parse populates p by parsing a string in the protobuf struct field tag style. func (p *Properties) Parse(s string) { // "bytes,49,opt,name=foo,def=hello!" fields := strings.Split(s, ",") // breaks def=, but handled below. if len(fields) < 2 { fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) return } p.Wire = fields[0] switch p.Wire { case "varint": p.WireType = WireVarint p.valEnc = (*Buffer).EncodeVarint p.valDec = (*Buffer).DecodeVarint p.valSize = sizeVarint case "fixed32": p.WireType = WireFixed32 p.valEnc = (*Buffer).EncodeFixed32 p.valDec = (*Buffer).DecodeFixed32 p.valSize = sizeFixed32 case "fixed64": p.WireType = WireFixed64 p.valEnc = (*Buffer).EncodeFixed64 p.valDec = (*Buffer).DecodeFixed64 p.valSize = sizeFixed64 case "zigzag32": p.WireType = WireVarint p.valEnc = (*Buffer).EncodeZigzag32 p.valDec = (*Buffer).DecodeZigzag32 p.valSize = sizeZigzag32 case "zigzag64": p.WireType = WireVarint p.valEnc = (*Buffer).EncodeZigzag64 p.valDec = (*Buffer).DecodeZigzag64 p.valSize = sizeZigzag64 case "bytes", "group": p.WireType = WireBytes // no numeric converter for non-numeric types default: fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s) return } var err error p.Tag, err = strconv.Atoi(fields[1]) if err != nil { return } for i := 2; i < len(fields); i++ { f := fields[i] switch { case f == "req": p.Required = true case f == "opt": p.Optional = true case f == "rep": p.Repeated = true case f == "packed": p.Packed = true case strings.HasPrefix(f, "name="): p.OrigName = f[5:] case strings.HasPrefix(f, "json="): p.JSONName = f[5:] case strings.HasPrefix(f, "enum="): p.Enum = f[5:] case f == "proto3": p.proto3 = true case f == "oneof": p.oneof = true case strings.HasPrefix(f, "def="): p.HasDefault = true p.Default = f[4:] // rest of string if i+1 < len(fields) { // Commas aren't escaped, and def is always last. p.Default += "," + strings.Join(fields[i+1:], ",") break } } } } func logNoSliceEnc(t1, t2 reflect.Type) { fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2) } var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() // Initialize the fields for encoding and decoding. func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { p.enc = nil p.dec = nil p.size = nil switch t1 := typ; t1.Kind() { default: fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1) // proto3 scalar types case reflect.Bool: p.enc = (*Buffer).enc_proto3_bool p.dec = (*Buffer).dec_proto3_bool p.size = size_proto3_bool case reflect.Int32: p.enc = (*Buffer).enc_proto3_int32 p.dec = (*Buffer).dec_proto3_int32 p.size = size_proto3_int32 case reflect.Uint32: p.enc = (*Buffer).enc_proto3_uint32 p.dec = (*Buffer).dec_proto3_int32 // can reuse p.size = size_proto3_uint32 case reflect.Int64, reflect.Uint64: p.enc = (*Buffer).enc_proto3_int64 p.dec = (*Buffer).dec_proto3_int64 p.size = size_proto3_int64 case reflect.Float32: p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits p.dec = (*Buffer).dec_proto3_int32 p.size = size_proto3_uint32 case reflect.Float64: p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits p.dec = (*Buffer).dec_proto3_int64 p.size = size_proto3_int64 case reflect.String: p.enc = (*Buffer).enc_proto3_string p.dec = (*Buffer).dec_proto3_string p.size = size_proto3_string case reflect.Ptr: switch t2 := t1.Elem(); t2.Kind() { default: fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2) break case reflect.Bool: p.enc = (*Buffer).enc_bool p.dec = (*Buffer).dec_bool p.size = size_bool case reflect.Int32: p.enc = (*Buffer).enc_int32 p.dec = (*Buffer).dec_int32 p.size = size_int32 case reflect.Uint32: p.enc = (*Buffer).enc_uint32 p.dec = (*Buffer).dec_int32 // can reuse p.size = size_uint32 case reflect.Int64, reflect.Uint64: p.enc = (*Buffer).enc_int64 p.dec = (*Buffer).dec_int64 p.size = size_int64 case reflect.Float32: p.enc = (*Buffer).enc_uint32 // can just treat them as bits p.dec = (*Buffer).dec_int32 p.size = size_uint32 case reflect.Float64: p.enc = (*Buffer).enc_int64 // can just treat them as bits p.dec = (*Buffer).dec_int64 p.size = size_int64 case reflect.String: p.enc = (*Buffer).enc_string p.dec = (*Buffer).dec_string p.size = size_string case reflect.Struct: p.stype = t1.Elem() p.isMarshaler = isMarshaler(t1) p.isUnmarshaler = isUnmarshaler(t1) if p.Wire == "bytes" { p.enc = (*Buffer).enc_struct_message p.dec = (*Buffer).dec_struct_message p.size = size_struct_message } else { p.enc = (*Buffer).enc_struct_group p.dec = (*Buffer).dec_struct_group p.size = size_struct_group } } case reflect.Slice: switch t2 := t1.Elem(); t2.Kind() { default: logNoSliceEnc(t1, t2) break case reflect.Bool: if p.Packed { p.enc = (*Buffer).enc_slice_packed_bool p.size = size_slice_packed_bool } else { p.enc = (*Buffer).enc_slice_bool p.size = size_slice_bool } p.dec = (*Buffer).dec_slice_bool p.packedDec = (*Buffer).dec_slice_packed_bool case reflect.Int32: if p.Packed { p.enc = (*Buffer).enc_slice_packed_int32 p.size = size_slice_packed_int32 } else { p.enc = (*Buffer).enc_slice_int32 p.size = size_slice_int32 } p.dec = (*Buffer).dec_slice_int32 p.packedDec = (*Buffer).dec_slice_packed_int32 case reflect.Uint32: if p.Packed { p.enc = (*Buffer).enc_slice_packed_uint32 p.size = size_slice_packed_uint32 } else { p.enc = (*Buffer).enc_slice_uint32 p.size = size_slice_uint32 } p.dec = (*Buffer).dec_slice_int32 p.packedDec = (*Buffer).dec_slice_packed_int32 case reflect.Int64, reflect.Uint64: if p.Packed { p.enc = (*Buffer).enc_slice_packed_int64 p.size = size_slice_packed_int64 } else { p.enc = (*Buffer).enc_slice_int64 p.size = size_slice_int64 } p.dec = (*Buffer).dec_slice_int64 p.packedDec = (*Buffer).dec_slice_packed_int64 case reflect.Uint8: p.dec = (*Buffer).dec_slice_byte if p.proto3 { p.enc = (*Buffer).enc_proto3_slice_byte p.size = size_proto3_slice_byte } else { p.enc = (*Buffer).enc_slice_byte p.size = size_slice_byte } case reflect.Float32, reflect.Float64: switch t2.Bits() { case 32: // can just treat them as bits if p.Packed { p.enc = (*Buffer).enc_slice_packed_uint32 p.size = size_slice_packed_uint32 } else { p.enc = (*Buffer).enc_slice_uint32 p.size = size_slice_uint32 } p.dec = (*Buffer).dec_slice_int32 p.packedDec = (*Buffer).dec_slice_packed_int32 case 64: // can just treat them as bits if p.Packed { p.enc = (*Buffer).enc_slice_packed_int64 p.size = size_slice_packed_int64 } else { p.enc = (*Buffer).enc_slice_int64 p.size = size_slice_int64 } p.dec = (*Buffer).dec_slice_int64 p.packedDec = (*Buffer).dec_slice_packed_int64 default: logNoSliceEnc(t1, t2) break } case reflect.String: p.enc = (*Buffer).enc_slice_string p.dec = (*Buffer).dec_slice_string p.size = size_slice_string case reflect.Ptr: switch t3 := t2.Elem(); t3.Kind() { default: fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3) break case reflect.Struct: p.stype = t2.Elem() p.isMarshaler = isMarshaler(t2) p.isUnmarshaler = isUnmarshaler(t2) if p.Wire == "bytes" { p.enc = (*Buffer).enc_slice_struct_message p.dec = (*Buffer).dec_slice_struct_message p.size = size_slice_struct_message } else { p.enc = (*Buffer).enc_slice_struct_group p.dec = (*Buffer).dec_slice_struct_group p.size = size_slice_struct_group } } case reflect.Slice: switch t2.Elem().Kind() { default: fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem()) break case reflect.Uint8: p.enc = (*Buffer).enc_slice_slice_byte p.dec = (*Buffer).dec_slice_slice_byte p.size = size_slice_slice_byte } } case reflect.Map: p.enc = (*Buffer).enc_new_map p.dec = (*Buffer).dec_new_map p.size = size_new_map p.mtype = t1 p.mkeyprop = &Properties{} p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) p.mvalprop = &Properties{} vtype := p.mtype.Elem() if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { // The value type is not a message (*T) or bytes ([]byte), // so we need encoders for the pointer to this type. vtype = reflect.PtrTo(vtype) } p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) } // precalculate tag code wire := p.WireType if p.Packed { wire = WireBytes } x := uint32(p.Tag)<<3 | uint32(wire) i := 0 for i = 0; x > 127; i++ { p.tagbuf[i] = 0x80 | uint8(x&0x7F) x >>= 7 } p.tagbuf[i] = uint8(x) p.tagcode = p.tagbuf[0 : i+1] if p.stype != nil { if lockGetProp { p.sprop = GetProperties(p.stype) } else { p.sprop = getPropertiesLocked(p.stype) } } } var ( marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() ) // isMarshaler reports whether type t implements Marshaler. func isMarshaler(t reflect.Type) bool { // We're checking for (likely) pointer-receiver methods // so if t is not a pointer, something is very wrong. // The calls above only invoke isMarshaler on pointer types. if t.Kind() != reflect.Ptr { panic("proto: misuse of isMarshaler") } return t.Implements(marshalerType) } // isUnmarshaler reports whether type t implements Unmarshaler. func isUnmarshaler(t reflect.Type) bool { // We're checking for (likely) pointer-receiver methods // so if t is not a pointer, something is very wrong. // The calls above only invoke isUnmarshaler on pointer types. if t.Kind() != reflect.Ptr { panic("proto: misuse of isUnmarshaler") } return t.Implements(unmarshalerType) } // Init populates the properties from a protocol buffer struct tag. func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { p.init(typ, name, tag, f, true) } func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { // "bytes,49,opt,def=hello!" p.Name = name p.OrigName = name if f != nil { p.field = toField(f) } if tag == "" { return } p.Parse(tag) p.setEncAndDec(typ, f, lockGetProp) } var ( propertiesMu sync.RWMutex propertiesMap = make(map[reflect.Type]*StructProperties) ) // GetProperties returns the list of properties for the type represented by t. // t must represent a generated struct type of a protocol message. func GetProperties(t reflect.Type) *StructProperties { if t.Kind() != reflect.Struct { panic("proto: type must have kind struct") } // Most calls to GetProperties in a long-running program will be // retrieving details for types we have seen before. propertiesMu.RLock() sprop, ok := propertiesMap[t] propertiesMu.RUnlock() if ok { if collectStats { stats.Chit++ } return sprop } propertiesMu.Lock() sprop = getPropertiesLocked(t) propertiesMu.Unlock() return sprop } // getPropertiesLocked requires that propertiesMu is held. func getPropertiesLocked(t reflect.Type) *StructProperties { if prop, ok := propertiesMap[t]; ok { if collectStats { stats.Chit++ } return prop } if collectStats { stats.Cmiss++ } prop := new(StructProperties) // in case of recursive protos, fill this in now. propertiesMap[t] = prop // build properties prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) || reflect.PtrTo(t).Implements(extendableProtoV1Type) prop.unrecField = invalidField prop.Prop = make([]*Properties, t.NumField()) prop.order = make([]int, t.NumField()) for i := 0; i < t.NumField(); i++ { f := t.Field(i) p := new(Properties) name := f.Name p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) if f.Name == "XXX_InternalExtensions" { // special case p.enc = (*Buffer).enc_exts p.dec = nil // not needed p.size = size_exts } else if f.Name == "XXX_extensions" { // special case p.enc = (*Buffer).enc_map p.dec = nil // not needed p.size = size_map } else if f.Name == "XXX_unrecognized" { // special case prop.unrecField = toField(&f) } oneof := f.Tag.Get("protobuf_oneof") // special case if oneof != "" { // Oneof fields don't use the traditional protobuf tag. p.OrigName = oneof } prop.Prop[i] = p prop.order[i] = i if debug { print(i, " ", f.Name, " ", t.String(), " ") if p.Tag > 0 { print(p.String()) } print("\n") } if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" { fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]") } } // Re-order prop.order. sort.Sort(prop) type oneofMessage interface { XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) } if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { var oots []interface{} prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs() prop.stype = t // Interpret oneof metadata. prop.OneofTypes = make(map[string]*OneofProperties) for _, oot := range oots { oop := &OneofProperties{ Type: reflect.ValueOf(oot).Type(), // *T Prop: new(Properties), } sft := oop.Type.Elem().Field(0) oop.Prop.Name = sft.Name oop.Prop.Parse(sft.Tag.Get("protobuf")) // There will be exactly one interface field that // this new value is assignable to. for i := 0; i < t.NumField(); i++ { f := t.Field(i) if f.Type.Kind() != reflect.Interface { continue } if !oop.Type.AssignableTo(f.Type) { continue } oop.Field = i break } prop.OneofTypes[oop.Prop.OrigName] = oop } } // build required counts // build tags reqCount := 0 prop.decoderOrigNames = make(map[string]int) for i, p := range prop.Prop { if strings.HasPrefix(p.Name, "XXX_") { // Internal fields should not appear in tags/origNames maps. // They are handled specially when encoding and decoding. continue } if p.Required { reqCount++ } prop.decoderTags.put(p.Tag, i) prop.decoderOrigNames[p.OrigName] = i } prop.reqCount = reqCount return prop } // Return the Properties object for the x[0]'th field of the structure. func propByIndex(t reflect.Type, x []int) *Properties { if len(x) != 1 { fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t) return nil } prop := GetProperties(t) return prop.Prop[x[0]] } // Get the address and type of a pointer to a struct from an interface. func getbase(pb Message) (t reflect.Type, b structPointer, err error) { if pb == nil { err = ErrNil return } // get the reflect type of the pointer to the struct. t = reflect.TypeOf(pb) // get the address of the struct. value := reflect.ValueOf(pb) b = toStructPointer(value) return } // A global registry of enum types. // The generated code will register the generated maps by calling RegisterEnum. var enumValueMaps = make(map[string]map[string]int32) // RegisterEnum is called from the generated code to install the enum descriptor // maps into the global table to aid parsing text format protocol buffers. func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { if _, ok := enumValueMaps[typeName]; ok { panic("proto: duplicate enum registered: " + typeName) } enumValueMaps[typeName] = valueMap } // EnumValueMap returns the mapping from names to integers of the // enum type enumType, or a nil if not found. func EnumValueMap(enumType string) map[string]int32 { return enumValueMaps[enumType] } // A registry of all linked message types. // The string is a fully-qualified proto name ("pkg.Message"). var ( protoTypes = make(map[string]reflect.Type) revProtoTypes = make(map[reflect.Type]string) ) // RegisterType is called from generated code and maps from the fully qualified // proto name to the type (pointer to struct) of the protocol buffer. func RegisterType(x Message, name string) { if _, ok := protoTypes[name]; ok { // TODO: Some day, make this a panic. log.Printf("proto: duplicate proto type registered: %s", name) return } t := reflect.TypeOf(x) protoTypes[name] = t revProtoTypes[t] = name } // MessageName returns the fully-qualified proto name for the given message type. func MessageName(x Message) string { type xname interface { XXX_MessageName() string } if m, ok := x.(xname); ok { return m.XXX_MessageName() } return revProtoTypes[reflect.TypeOf(x)] } // MessageType returns the message type (pointer to struct) for a named message. func MessageType(name string) reflect.Type { return protoTypes[name] } // A registry of all linked proto files. var ( protoFiles = make(map[string][]byte) // file name => fileDescriptor ) // RegisterFile is called from generated code and maps from the // full file name of a .proto file to its compressed FileDescriptorProto. func RegisterFile(filename string, fileDescriptor []byte) { protoFiles[filename] = fileDescriptor } // FileDescriptor returns the compressed FileDescriptorProto for a .proto file. func FileDescriptor(filename string) []byte { return protoFiles[filename] } ================================================ FILE: src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go ================================================ // Code generated by protoc-gen-go. // source: proto3_proto/proto3.proto // DO NOT EDIT! /* Package proto3_proto is a generated protocol buffer package. It is generated from these files: proto3_proto/proto3.proto It has these top-level messages: Message Nested MessageWithMap IntMap IntMaps */ package proto3_proto import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import google_protobuf "github.com/golang/protobuf/ptypes/any" import testdata "github.com/golang/protobuf/proto/testdata" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type Message_Humour int32 const ( Message_UNKNOWN Message_Humour = 0 Message_PUNS Message_Humour = 1 Message_SLAPSTICK Message_Humour = 2 Message_BILL_BAILEY Message_Humour = 3 ) var Message_Humour_name = map[int32]string{ 0: "UNKNOWN", 1: "PUNS", 2: "SLAPSTICK", 3: "BILL_BAILEY", } var Message_Humour_value = map[string]int32{ "UNKNOWN": 0, "PUNS": 1, "SLAPSTICK": 2, "BILL_BAILEY": 3, } func (x Message_Humour) String() string { return proto.EnumName(Message_Humour_name, int32(x)) } func (Message_Humour) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} } type Message struct { Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Hilarity Message_Humour `protobuf:"varint,2,opt,name=hilarity,enum=proto3_proto.Message_Humour" json:"hilarity,omitempty"` HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm,json=heightInCm" json:"height_in_cm,omitempty"` Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"` ResultCount int64 `protobuf:"varint,7,opt,name=result_count,json=resultCount" json:"result_count,omitempty"` TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman,json=trueScotsman" json:"true_scotsman,omitempty"` Score float32 `protobuf:"fixed32,9,opt,name=score" json:"score,omitempty"` Key []uint64 `protobuf:"varint,5,rep,packed,name=key" json:"key,omitempty"` ShortKey []int32 `protobuf:"varint,19,rep,packed,name=short_key,json=shortKey" json:"short_key,omitempty"` Nested *Nested `protobuf:"bytes,6,opt,name=nested" json:"nested,omitempty"` RFunny []Message_Humour `protobuf:"varint,16,rep,packed,name=r_funny,json=rFunny,enum=proto3_proto.Message_Humour" json:"r_funny,omitempty"` Terrain map[string]*Nested `protobuf:"bytes,10,rep,name=terrain" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Proto2Field *testdata.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field,json=proto2Field" json:"proto2_field,omitempty"` Proto2Value map[string]*testdata.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value,json=proto2Value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Anything *google_protobuf.Any `protobuf:"bytes,14,opt,name=anything" json:"anything,omitempty"` ManyThings []*google_protobuf.Any `protobuf:"bytes,15,rep,name=many_things,json=manyThings" json:"many_things,omitempty"` Submessage *Message `protobuf:"bytes,17,opt,name=submessage" json:"submessage,omitempty"` Children []*Message `protobuf:"bytes,18,rep,name=children" json:"children,omitempty"` } func (m *Message) Reset() { *m = Message{} } func (m *Message) String() string { return proto.CompactTextString(m) } func (*Message) ProtoMessage() {} func (*Message) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *Message) GetName() string { if m != nil { return m.Name } return "" } func (m *Message) GetHilarity() Message_Humour { if m != nil { return m.Hilarity } return Message_UNKNOWN } func (m *Message) GetHeightInCm() uint32 { if m != nil { return m.HeightInCm } return 0 } func (m *Message) GetData() []byte { if m != nil { return m.Data } return nil } func (m *Message) GetResultCount() int64 { if m != nil { return m.ResultCount } return 0 } func (m *Message) GetTrueScotsman() bool { if m != nil { return m.TrueScotsman } return false } func (m *Message) GetScore() float32 { if m != nil { return m.Score } return 0 } func (m *Message) GetKey() []uint64 { if m != nil { return m.Key } return nil } func (m *Message) GetShortKey() []int32 { if m != nil { return m.ShortKey } return nil } func (m *Message) GetNested() *Nested { if m != nil { return m.Nested } return nil } func (m *Message) GetRFunny() []Message_Humour { if m != nil { return m.RFunny } return nil } func (m *Message) GetTerrain() map[string]*Nested { if m != nil { return m.Terrain } return nil } func (m *Message) GetProto2Field() *testdata.SubDefaults { if m != nil { return m.Proto2Field } return nil } func (m *Message) GetProto2Value() map[string]*testdata.SubDefaults { if m != nil { return m.Proto2Value } return nil } func (m *Message) GetAnything() *google_protobuf.Any { if m != nil { return m.Anything } return nil } func (m *Message) GetManyThings() []*google_protobuf.Any { if m != nil { return m.ManyThings } return nil } func (m *Message) GetSubmessage() *Message { if m != nil { return m.Submessage } return nil } func (m *Message) GetChildren() []*Message { if m != nil { return m.Children } return nil } type Nested struct { Bunny string `protobuf:"bytes,1,opt,name=bunny" json:"bunny,omitempty"` Cute bool `protobuf:"varint,2,opt,name=cute" json:"cute,omitempty"` } func (m *Nested) Reset() { *m = Nested{} } func (m *Nested) String() string { return proto.CompactTextString(m) } func (*Nested) ProtoMessage() {} func (*Nested) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *Nested) GetBunny() string { if m != nil { return m.Bunny } return "" } func (m *Nested) GetCute() bool { if m != nil { return m.Cute } return false } type MessageWithMap struct { ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"` } func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } func (*MessageWithMap) ProtoMessage() {} func (*MessageWithMap) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *MessageWithMap) GetByteMapping() map[bool][]byte { if m != nil { return m.ByteMapping } return nil } type IntMap struct { Rtt map[int32]int32 `protobuf:"bytes,1,rep,name=rtt" json:"rtt,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"` } func (m *IntMap) Reset() { *m = IntMap{} } func (m *IntMap) String() string { return proto.CompactTextString(m) } func (*IntMap) ProtoMessage() {} func (*IntMap) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *IntMap) GetRtt() map[int32]int32 { if m != nil { return m.Rtt } return nil } type IntMaps struct { Maps []*IntMap `protobuf:"bytes,1,rep,name=maps" json:"maps,omitempty"` } func (m *IntMaps) Reset() { *m = IntMaps{} } func (m *IntMaps) String() string { return proto.CompactTextString(m) } func (*IntMaps) ProtoMessage() {} func (*IntMaps) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (m *IntMaps) GetMaps() []*IntMap { if m != nil { return m.Maps } return nil } func init() { proto.RegisterType((*Message)(nil), "proto3_proto.Message") proto.RegisterType((*Nested)(nil), "proto3_proto.Nested") proto.RegisterType((*MessageWithMap)(nil), "proto3_proto.MessageWithMap") proto.RegisterType((*IntMap)(nil), "proto3_proto.IntMap") proto.RegisterType((*IntMaps)(nil), "proto3_proto.IntMaps") proto.RegisterEnum("proto3_proto.Message_Humour", Message_Humour_name, Message_Humour_value) } func init() { proto.RegisterFile("proto3_proto/proto3.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 733 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x84, 0x53, 0x6d, 0x6f, 0xf3, 0x34, 0x14, 0x25, 0x4d, 0x5f, 0xd2, 0x9b, 0x74, 0x0b, 0x5e, 0x91, 0xbc, 0x02, 0x52, 0x28, 0x12, 0x8a, 0x78, 0x49, 0xa1, 0xd3, 0xd0, 0x84, 0x10, 0x68, 0x1b, 0x9b, 0xa8, 0xd6, 0x95, 0xca, 0xdd, 0x98, 0xf8, 0x14, 0xa5, 0xad, 0xdb, 0x46, 0x34, 0x4e, 0x49, 0x1c, 0xa4, 0xfc, 0x1d, 0xfe, 0x28, 0x8f, 0x6c, 0xa7, 0x5d, 0x36, 0x65, 0xcf, 0xf3, 0x29, 0xf6, 0xf1, 0xb9, 0xf7, 0x9c, 0x1c, 0x5f, 0xc3, 0xe9, 0x2e, 0x89, 0x79, 0x7c, 0xe6, 0xcb, 0xcf, 0x40, 0x6d, 0x3c, 0xf9, 0x41, 0x56, 0xf9, 0xa8, 0x77, 0xba, 0x8e, 0xe3, 0xf5, 0x96, 0x2a, 0xca, 0x3c, 0x5b, 0x0d, 0x02, 0x96, 0x2b, 0x62, 0xef, 0x84, 0xd3, 0x94, 0x2f, 0x03, 0x1e, 0x0c, 0xc4, 0x42, 0x81, 0xfd, 0xff, 0x5b, 0xd0, 0xba, 0xa7, 0x69, 0x1a, 0xac, 0x29, 0x42, 0x50, 0x67, 0x41, 0x44, 0xb1, 0xe6, 0x68, 0x6e, 0x9b, 0xc8, 0x35, 0xba, 0x00, 0x63, 0x13, 0x6e, 0x83, 0x24, 0xe4, 0x39, 0xae, 0x39, 0x9a, 0x7b, 0x34, 0xfc, 0xcc, 0x2b, 0x0b, 0x7a, 0x45, 0xb1, 0xf7, 0x7b, 0x16, 0xc5, 0x59, 0x42, 0x0e, 0x6c, 0xe4, 0x80, 0xb5, 0xa1, 0xe1, 0x7a, 0xc3, 0xfd, 0x90, 0xf9, 0x8b, 0x08, 0xeb, 0x8e, 0xe6, 0x76, 0x08, 0x28, 0x6c, 0xc4, 0xae, 0x23, 0xa1, 0x27, 0xec, 0xe0, 0xba, 0xa3, 0xb9, 0x16, 0x91, 0x6b, 0xf4, 0x05, 0x58, 0x09, 0x4d, 0xb3, 0x2d, 0xf7, 0x17, 0x71, 0xc6, 0x38, 0x6e, 0x39, 0x9a, 0xab, 0x13, 0x53, 0x61, 0xd7, 0x02, 0x42, 0x5f, 0x42, 0x87, 0x27, 0x19, 0xf5, 0xd3, 0x45, 0xcc, 0xd3, 0x28, 0x60, 0xd8, 0x70, 0x34, 0xd7, 0x20, 0x96, 0x00, 0x67, 0x05, 0x86, 0xba, 0xd0, 0x48, 0x17, 0x71, 0x42, 0x71, 0xdb, 0xd1, 0xdc, 0x1a, 0x51, 0x1b, 0x64, 0x83, 0xfe, 0x37, 0xcd, 0x71, 0xc3, 0xd1, 0xdd, 0x3a, 0x11, 0x4b, 0xf4, 0x29, 0xb4, 0xd3, 0x4d, 0x9c, 0x70, 0x5f, 0xe0, 0x27, 0x8e, 0xee, 0x36, 0x88, 0x21, 0x81, 0x3b, 0x9a, 0xa3, 0x6f, 0xa1, 0xc9, 0x68, 0xca, 0xe9, 0x12, 0x37, 0x1d, 0xcd, 0x35, 0x87, 0xdd, 0x97, 0xbf, 0x3e, 0x91, 0x67, 0xa4, 0xe0, 0xa0, 0x73, 0x68, 0x25, 0xfe, 0x2a, 0x63, 0x2c, 0xc7, 0xb6, 0xa3, 0x7f, 0x30, 0xa9, 0x66, 0x72, 0x2b, 0xb8, 0xe8, 0x67, 0x68, 0x71, 0x9a, 0x24, 0x41, 0xc8, 0x30, 0x38, 0xba, 0x6b, 0x0e, 0xfb, 0xd5, 0x65, 0x0f, 0x8a, 0x74, 0xc3, 0x78, 0x92, 0x93, 0x7d, 0x09, 0xba, 0x00, 0x75, 0xff, 0x43, 0x7f, 0x15, 0xd2, 0xed, 0x12, 0x9b, 0xd2, 0xe8, 0x27, 0xde, 0xfe, 0xae, 0xbd, 0x59, 0x36, 0xff, 0x8d, 0xae, 0x82, 0x6c, 0xcb, 0x53, 0x62, 0x2a, 0xea, 0xad, 0x60, 0xa2, 0xd1, 0xa1, 0xf2, 0xdf, 0x60, 0x9b, 0x51, 0xdc, 0x91, 0xe2, 0x5f, 0x55, 0x8b, 0x4f, 0x25, 0xf3, 0x4f, 0x41, 0x54, 0x06, 0x8a, 0x56, 0x12, 0x41, 0xdf, 0x83, 0x11, 0xb0, 0x9c, 0x6f, 0x42, 0xb6, 0xc6, 0x47, 0x45, 0x52, 0x6a, 0x0e, 0xbd, 0xfd, 0x1c, 0x7a, 0x97, 0x2c, 0x27, 0x07, 0x16, 0x3a, 0x07, 0x33, 0x0a, 0x58, 0xee, 0xcb, 0x5d, 0x8a, 0x8f, 0xa5, 0x76, 0x75, 0x11, 0x08, 0xe2, 0x83, 0xe4, 0xa1, 0x73, 0x80, 0x34, 0x9b, 0x47, 0xca, 0x14, 0xfe, 0xb8, 0xf8, 0xd7, 0x2a, 0xc7, 0xa4, 0x44, 0x44, 0x3f, 0x80, 0xb1, 0xd8, 0x84, 0xdb, 0x65, 0x42, 0x19, 0x46, 0x52, 0xea, 0x8d, 0xa2, 0x03, 0xad, 0x37, 0x05, 0xab, 0x1c, 0xf8, 0x7e, 0x72, 0xd4, 0xd3, 0x90, 0x93, 0xf3, 0x35, 0x34, 0x54, 0x70, 0xb5, 0xf7, 0xcc, 0x86, 0xa2, 0xfc, 0x54, 0xbb, 0xd0, 0x7a, 0x8f, 0x60, 0xbf, 0x4e, 0xb1, 0xa2, 0xeb, 0x37, 0x2f, 0xbb, 0xbe, 0x71, 0x91, 0xcf, 0x6d, 0xfb, 0xbf, 0x42, 0x53, 0x0d, 0x14, 0x32, 0xa1, 0xf5, 0x38, 0xb9, 0x9b, 0xfc, 0xf1, 0x34, 0xb1, 0x3f, 0x42, 0x06, 0xd4, 0xa7, 0x8f, 0x93, 0x99, 0xad, 0xa1, 0x0e, 0xb4, 0x67, 0xe3, 0xcb, 0xe9, 0xec, 0x61, 0x74, 0x7d, 0x67, 0xd7, 0xd0, 0x31, 0x98, 0x57, 0xa3, 0xf1, 0xd8, 0xbf, 0xba, 0x1c, 0x8d, 0x6f, 0xfe, 0xb2, 0xf5, 0xfe, 0x10, 0x9a, 0xca, 0xac, 0x78, 0x33, 0x73, 0x39, 0xbe, 0xca, 0x8f, 0xda, 0x88, 0x57, 0xba, 0xc8, 0xb8, 0x32, 0x64, 0x10, 0xb9, 0xee, 0xff, 0xa7, 0xc1, 0x51, 0x91, 0xd9, 0x53, 0xc8, 0x37, 0xf7, 0xc1, 0x0e, 0x4d, 0xc1, 0x9a, 0xe7, 0x9c, 0xfa, 0x51, 0xb0, 0xdb, 0x89, 0x39, 0xd0, 0x64, 0xce, 0xdf, 0x55, 0xe6, 0x5c, 0xd4, 0x78, 0x57, 0x39, 0xa7, 0xf7, 0x8a, 0x5f, 0x4c, 0xd5, 0xfc, 0x19, 0xe9, 0xfd, 0x02, 0xf6, 0x6b, 0x42, 0x39, 0x30, 0x43, 0x05, 0xd6, 0x2d, 0x07, 0x66, 0x95, 0x93, 0xf9, 0x07, 0x9a, 0x23, 0xc6, 0x85, 0xb7, 0x01, 0xe8, 0x09, 0xe7, 0x85, 0xa5, 0xcf, 0x5f, 0x5a, 0x52, 0x14, 0x8f, 0x70, 0xae, 0x2c, 0x08, 0x66, 0xef, 0x47, 0x30, 0xf6, 0x40, 0x59, 0xb2, 0x51, 0x21, 0xd9, 0x28, 0x4b, 0x9e, 0x41, 0x4b, 0xf5, 0x4b, 0x91, 0x0b, 0xf5, 0x28, 0xd8, 0xa5, 0x85, 0x68, 0xb7, 0x4a, 0x94, 0x48, 0xc6, 0xbc, 0xa9, 0x8e, 0xde, 0x05, 0x00, 0x00, 0xff, 0xff, 0x75, 0x38, 0xad, 0x84, 0xe4, 0x05, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto3"; import "google/protobuf/any.proto"; import "testdata/test.proto"; package proto3_proto; message Message { enum Humour { UNKNOWN = 0; PUNS = 1; SLAPSTICK = 2; BILL_BAILEY = 3; } string name = 1; Humour hilarity = 2; uint32 height_in_cm = 3; bytes data = 4; int64 result_count = 7; bool true_scotsman = 8; float score = 9; repeated uint64 key = 5; repeated int32 short_key = 19; Nested nested = 6; repeated Humour r_funny = 16; map terrain = 10; testdata.SubDefaults proto2_field = 11; map proto2_value = 13; google.protobuf.Any anything = 14; repeated google.protobuf.Any many_things = 15; Message submessage = 17; repeated Message children = 18; } message Nested { string bunny = 1; bool cute = 2; } message MessageWithMap { map byte_mapping = 1; } message IntMap { map rtt = 1; } message IntMaps { repeated IntMap maps = 1; } ================================================ FILE: src/github.com/golang/protobuf/proto/proto3_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto_test import ( "testing" "github.com/golang/protobuf/proto" pb "github.com/golang/protobuf/proto/proto3_proto" tpb "github.com/golang/protobuf/proto/testdata" ) func TestProto3ZeroValues(t *testing.T) { tests := []struct { desc string m proto.Message }{ {"zero message", &pb.Message{}}, {"empty bytes field", &pb.Message{Data: []byte{}}}, } for _, test := range tests { b, err := proto.Marshal(test.m) if err != nil { t.Errorf("%s: proto.Marshal: %v", test.desc, err) continue } if len(b) > 0 { t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) } } } func TestRoundTripProto3(t *testing.T) { m := &pb.Message{ Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" ResultCount: 47, // (0 | 7<<3): 0x38 0x2f TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 Score: 8.1, // (5 | 9<<3): 0x4d <8.1> Key: []uint64{1, 0xdeadbeef}, Nested: &pb.Nested{ Bunny: "Monty", }, } t.Logf(" m: %v", m) b, err := proto.Marshal(m) if err != nil { t.Fatalf("proto.Marshal: %v", err) } t.Logf(" b: %q", b) m2 := new(pb.Message) if err := proto.Unmarshal(b, m2); err != nil { t.Fatalf("proto.Unmarshal: %v", err) } t.Logf("m2: %v", m2) if !proto.Equal(m, m2) { t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) } } func TestGettersForBasicTypesExist(t *testing.T) { var m pb.Message if got := m.GetNested().GetBunny(); got != "" { t.Errorf("m.GetNested().GetBunny() = %q, want empty string", got) } if got := m.GetNested().GetCute(); got { t.Errorf("m.GetNested().GetCute() = %t, want false", got) } } func TestProto3SetDefaults(t *testing.T) { in := &pb.Message{ Terrain: map[string]*pb.Nested{ "meadow": new(pb.Nested), }, Proto2Field: new(tpb.SubDefaults), Proto2Value: map[string]*tpb.SubDefaults{ "badlands": new(tpb.SubDefaults), }, } got := proto.Clone(in).(*pb.Message) proto.SetDefaults(got) // There are no defaults in proto3. Everything should be the zero value, but // we need to remember to set defaults for nested proto2 messages. want := &pb.Message{ Terrain: map[string]*pb.Nested{ "meadow": new(pb.Nested), }, Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, Proto2Value: map[string]*tpb.SubDefaults{ "badlands": &tpb.SubDefaults{N: proto.Int64(7)}, }, } if !proto.Equal(got, want) { t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) } } ================================================ FILE: src/github.com/golang/protobuf/proto/size2_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto import ( "testing" ) // This is a separate file and package from size_test.go because that one uses // generated messages and thus may not be in package proto without having a circular // dependency, whereas this file tests unexported details of size.go. func TestVarintSize(t *testing.T) { // Check the edge cases carefully. testCases := []struct { n uint64 size int }{ {0, 1}, {1, 1}, {127, 1}, {128, 2}, {16383, 2}, {16384, 3}, {1<<63 - 1, 9}, {1 << 63, 10}, } for _, tc := range testCases { size := sizeVarint(tc.n) if size != tc.size { t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) } } } ================================================ FILE: src/github.com/golang/protobuf/proto/size_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto_test import ( "log" "strings" "testing" . "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" pb "github.com/golang/protobuf/proto/testdata" ) var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} // messageWithExtension2 is in equal_test.go. var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} func init() { if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { log.Panicf("SetExtension: %v", err) } if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { log.Panicf("SetExtension: %v", err) } // Force messageWithExtension3 to have the extension encoded. Marshal(messageWithExtension3) } var SizeTests = []struct { desc string pb Message }{ {"empty", &pb.OtherMessage{}}, // Basic types. {"bool", &pb.Defaults{F_Bool: Bool(true)}}, {"int32", &pb.Defaults{F_Int32: Int32(12)}}, {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, {"float", &pb.Defaults{F_Float: Float32(12.6)}}, {"double", &pb.Defaults{F_Double: Float64(13.9)}}, {"string", &pb.Defaults{F_String: String("niles")}}, {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, // Repeated. {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ // Need enough large numbers to verify that the header is counting the number of bytes // for the field, not the number of elements. 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, }}}, {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, // Nested. {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, // Other things. {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, {"extension (unencoded)", messageWithExtension1}, {"extension (encoded)", messageWithExtension3}, // proto3 message {"proto3 empty", &proto3pb.Message{}}, {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, {"proto3 float", &proto3pb.Message{Score: 12.6}}, {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}}, {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}}, {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}}, {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, {"oneof not set", &pb.Oneof{}}, {"oneof bool", &pb.Oneof{Union: &pb.Oneof_F_Bool{true}}}, {"oneof zero int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{0}}}, {"oneof big int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{1 << 20}}}, {"oneof int64", &pb.Oneof{Union: &pb.Oneof_F_Int64{42}}}, {"oneof fixed32", &pb.Oneof{Union: &pb.Oneof_F_Fixed32{43}}}, {"oneof fixed64", &pb.Oneof{Union: &pb.Oneof_F_Fixed64{44}}}, {"oneof uint32", &pb.Oneof{Union: &pb.Oneof_F_Uint32{45}}}, {"oneof uint64", &pb.Oneof{Union: &pb.Oneof_F_Uint64{46}}}, {"oneof float", &pb.Oneof{Union: &pb.Oneof_F_Float{47.1}}}, {"oneof double", &pb.Oneof{Union: &pb.Oneof_F_Double{48.9}}}, {"oneof string", &pb.Oneof{Union: &pb.Oneof_F_String{"Rhythmic Fman"}}}, {"oneof bytes", &pb.Oneof{Union: &pb.Oneof_F_Bytes{[]byte("let go")}}}, {"oneof sint32", &pb.Oneof{Union: &pb.Oneof_F_Sint32{50}}}, {"oneof sint64", &pb.Oneof{Union: &pb.Oneof_F_Sint64{51}}}, {"oneof enum", &pb.Oneof{Union: &pb.Oneof_F_Enum{pb.MyMessage_BLUE}}}, {"message for oneof", &pb.GoTestField{Label: String("k"), Type: String("v")}}, {"oneof message", &pb.Oneof{Union: &pb.Oneof_F_Message{&pb.GoTestField{Label: String("k"), Type: String("v")}}}}, {"oneof group", &pb.Oneof{Union: &pb.Oneof_FGroup{&pb.Oneof_F_Group{X: Int32(52)}}}}, {"oneof largest tag", &pb.Oneof{Union: &pb.Oneof_F_Largest_Tag{1}}}, {"multiple oneofs", &pb.Oneof{Union: &pb.Oneof_F_Int32{1}, Tormato: &pb.Oneof_Value{2}}}, } func TestSize(t *testing.T) { for _, tc := range SizeTests { size := Size(tc.pb) b, err := Marshal(tc.pb) if err != nil { t.Errorf("%v: Marshal failed: %v", tc.desc, err) continue } if size != len(b) { t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) t.Logf("%v: bytes: %#v", tc.desc, b) } } } ================================================ FILE: src/github.com/golang/protobuf/proto/testdata/Makefile ================================================ # Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/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. include ../../Make.protobuf all: regenerate regenerate: rm -f test.pb.go make test.pb.go # The following rules are just aids to development. Not needed for typical testing. diff: regenerate git diff test.pb.go restore: cp test.pb.go.golden test.pb.go preserve: cp test.pb.go test.pb.go.golden ================================================ FILE: src/github.com/golang/protobuf/proto/testdata/golden_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/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. // Verify that the compiler output for test.proto is unchanged. package testdata import ( "crypto/sha1" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "testing" ) // sum returns in string form (for easy comparison) the SHA-1 hash of the named file. func sum(t *testing.T, name string) string { data, err := ioutil.ReadFile(name) if err != nil { t.Fatal(err) } t.Logf("sum(%q): length is %d", name, len(data)) hash := sha1.New() _, err = hash.Write(data) if err != nil { t.Fatal(err) } return fmt.Sprintf("% x", hash.Sum(nil)) } func run(t *testing.T, name string, args ...string) { cmd := exec.Command(name, args...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { t.Fatal(err) } } func TestGolden(t *testing.T) { // Compute the original checksum. goldenSum := sum(t, "test.pb.go") // Run the proto compiler. run(t, "protoc", "--go_out="+os.TempDir(), "test.proto") newFile := filepath.Join(os.TempDir(), "test.pb.go") defer os.Remove(newFile) // Compute the new checksum. newSum := sum(t, newFile) // Verify if newSum != goldenSum { run(t, "diff", "-u", "test.pb.go", newFile) t.Fatal("Code generated by protoc-gen-go has changed; update test.pb.go") } } ================================================ FILE: src/github.com/golang/protobuf/proto/testdata/test.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: test.proto /* Package testdata is a generated protocol buffer package. It is generated from these files: test.proto It has these top-level messages: GoEnum GoTestField GoTest GoTestRequiredGroupField GoSkipTest NonPackedTest PackedTest MaxTag OldMessage NewMessage InnerMessage OtherMessage RequiredInnerMessage MyMessage Ext ComplexExtension DefaultsMessage MyMessageSet Empty MessageList Strings Defaults SubDefaults RepeatedEnum MoreRepeated GroupOld GroupNew FloatingPoint MessageWithMap Oneof Communique */ package testdata import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type FOO int32 const ( FOO_FOO1 FOO = 1 ) var FOO_name = map[int32]string{ 1: "FOO1", } var FOO_value = map[string]int32{ "FOO1": 1, } func (x FOO) Enum() *FOO { p := new(FOO) *p = x return p } func (x FOO) String() string { return proto.EnumName(FOO_name, int32(x)) } func (x *FOO) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO") if err != nil { return err } *x = FOO(value) return nil } func (FOO) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } // An enum, for completeness. type GoTest_KIND int32 const ( GoTest_VOID GoTest_KIND = 0 // Basic types GoTest_BOOL GoTest_KIND = 1 GoTest_BYTES GoTest_KIND = 2 GoTest_FINGERPRINT GoTest_KIND = 3 GoTest_FLOAT GoTest_KIND = 4 GoTest_INT GoTest_KIND = 5 GoTest_STRING GoTest_KIND = 6 GoTest_TIME GoTest_KIND = 7 // Groupings GoTest_TUPLE GoTest_KIND = 8 GoTest_ARRAY GoTest_KIND = 9 GoTest_MAP GoTest_KIND = 10 // Table types GoTest_TABLE GoTest_KIND = 11 // Functions GoTest_FUNCTION GoTest_KIND = 12 ) var GoTest_KIND_name = map[int32]string{ 0: "VOID", 1: "BOOL", 2: "BYTES", 3: "FINGERPRINT", 4: "FLOAT", 5: "INT", 6: "STRING", 7: "TIME", 8: "TUPLE", 9: "ARRAY", 10: "MAP", 11: "TABLE", 12: "FUNCTION", } var GoTest_KIND_value = map[string]int32{ "VOID": 0, "BOOL": 1, "BYTES": 2, "FINGERPRINT": 3, "FLOAT": 4, "INT": 5, "STRING": 6, "TIME": 7, "TUPLE": 8, "ARRAY": 9, "MAP": 10, "TABLE": 11, "FUNCTION": 12, } func (x GoTest_KIND) Enum() *GoTest_KIND { p := new(GoTest_KIND) *p = x return p } func (x GoTest_KIND) String() string { return proto.EnumName(GoTest_KIND_name, int32(x)) } func (x *GoTest_KIND) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND") if err != nil { return err } *x = GoTest_KIND(value) return nil } func (GoTest_KIND) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } type MyMessage_Color int32 const ( MyMessage_RED MyMessage_Color = 0 MyMessage_GREEN MyMessage_Color = 1 MyMessage_BLUE MyMessage_Color = 2 ) var MyMessage_Color_name = map[int32]string{ 0: "RED", 1: "GREEN", 2: "BLUE", } var MyMessage_Color_value = map[string]int32{ "RED": 0, "GREEN": 1, "BLUE": 2, } func (x MyMessage_Color) Enum() *MyMessage_Color { p := new(MyMessage_Color) *p = x return p } func (x MyMessage_Color) String() string { return proto.EnumName(MyMessage_Color_name, int32(x)) } func (x *MyMessage_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color") if err != nil { return err } *x = MyMessage_Color(value) return nil } func (MyMessage_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{13, 0} } type DefaultsMessage_DefaultsEnum int32 const ( DefaultsMessage_ZERO DefaultsMessage_DefaultsEnum = 0 DefaultsMessage_ONE DefaultsMessage_DefaultsEnum = 1 DefaultsMessage_TWO DefaultsMessage_DefaultsEnum = 2 ) var DefaultsMessage_DefaultsEnum_name = map[int32]string{ 0: "ZERO", 1: "ONE", 2: "TWO", } var DefaultsMessage_DefaultsEnum_value = map[string]int32{ "ZERO": 0, "ONE": 1, "TWO": 2, } func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum { p := new(DefaultsMessage_DefaultsEnum) *p = x return p } func (x DefaultsMessage_DefaultsEnum) String() string { return proto.EnumName(DefaultsMessage_DefaultsEnum_name, int32(x)) } func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(DefaultsMessage_DefaultsEnum_value, data, "DefaultsMessage_DefaultsEnum") if err != nil { return err } *x = DefaultsMessage_DefaultsEnum(value) return nil } func (DefaultsMessage_DefaultsEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{16, 0} } type Defaults_Color int32 const ( Defaults_RED Defaults_Color = 0 Defaults_GREEN Defaults_Color = 1 Defaults_BLUE Defaults_Color = 2 ) var Defaults_Color_name = map[int32]string{ 0: "RED", 1: "GREEN", 2: "BLUE", } var Defaults_Color_value = map[string]int32{ "RED": 0, "GREEN": 1, "BLUE": 2, } func (x Defaults_Color) Enum() *Defaults_Color { p := new(Defaults_Color) *p = x return p } func (x Defaults_Color) String() string { return proto.EnumName(Defaults_Color_name, int32(x)) } func (x *Defaults_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color") if err != nil { return err } *x = Defaults_Color(value) return nil } func (Defaults_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{21, 0} } type RepeatedEnum_Color int32 const ( RepeatedEnum_RED RepeatedEnum_Color = 1 ) var RepeatedEnum_Color_name = map[int32]string{ 1: "RED", } var RepeatedEnum_Color_value = map[string]int32{ "RED": 1, } func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color { p := new(RepeatedEnum_Color) *p = x return p } func (x RepeatedEnum_Color) String() string { return proto.EnumName(RepeatedEnum_Color_name, int32(x)) } func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color") if err != nil { return err } *x = RepeatedEnum_Color(value) return nil } func (RepeatedEnum_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{23, 0} } type GoEnum struct { Foo *FOO `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoEnum) Reset() { *m = GoEnum{} } func (m *GoEnum) String() string { return proto.CompactTextString(m) } func (*GoEnum) ProtoMessage() {} func (*GoEnum) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *GoEnum) GetFoo() FOO { if m != nil && m.Foo != nil { return *m.Foo } return FOO_FOO1 } type GoTestField struct { Label *string `protobuf:"bytes,1,req,name=Label" json:"Label,omitempty"` Type *string `protobuf:"bytes,2,req,name=Type" json:"Type,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTestField) Reset() { *m = GoTestField{} } func (m *GoTestField) String() string { return proto.CompactTextString(m) } func (*GoTestField) ProtoMessage() {} func (*GoTestField) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *GoTestField) GetLabel() string { if m != nil && m.Label != nil { return *m.Label } return "" } func (m *GoTestField) GetType() string { if m != nil && m.Type != nil { return *m.Type } return "" } type GoTest struct { // Some typical parameters Kind *GoTest_KIND `protobuf:"varint,1,req,name=Kind,enum=testdata.GoTest_KIND" json:"Kind,omitempty"` Table *string `protobuf:"bytes,2,opt,name=Table" json:"Table,omitempty"` Param *int32 `protobuf:"varint,3,opt,name=Param" json:"Param,omitempty"` // Required, repeated and optional foreign fields. RequiredField *GoTestField `protobuf:"bytes,4,req,name=RequiredField" json:"RequiredField,omitempty"` RepeatedField []*GoTestField `protobuf:"bytes,5,rep,name=RepeatedField" json:"RepeatedField,omitempty"` OptionalField *GoTestField `protobuf:"bytes,6,opt,name=OptionalField" json:"OptionalField,omitempty"` // Required fields of all basic types F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required,json=FBoolRequired" json:"F_Bool_required,omitempty"` F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required,json=FInt32Required" json:"F_Int32_required,omitempty"` F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required,json=FInt64Required" json:"F_Int64_required,omitempty"` F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required,json=FFixed32Required" json:"F_Fixed32_required,omitempty"` F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required,json=FFixed64Required" json:"F_Fixed64_required,omitempty"` F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required,json=FUint32Required" json:"F_Uint32_required,omitempty"` F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required,json=FUint64Required" json:"F_Uint64_required,omitempty"` F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required,json=FFloatRequired" json:"F_Float_required,omitempty"` F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required,json=FDoubleRequired" json:"F_Double_required,omitempty"` F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required,json=FStringRequired" json:"F_String_required,omitempty"` F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required,json=FBytesRequired" json:"F_Bytes_required,omitempty"` F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required,json=FSint32Required" json:"F_Sint32_required,omitempty"` F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required,json=FSint64Required" json:"F_Sint64_required,omitempty"` // Repeated fields of all basic types F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated,json=FBoolRepeated" json:"F_Bool_repeated,omitempty"` F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated,json=FInt32Repeated" json:"F_Int32_repeated,omitempty"` F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated,json=FInt64Repeated" json:"F_Int64_repeated,omitempty"` F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated,json=FFixed32Repeated" json:"F_Fixed32_repeated,omitempty"` F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated,json=FFixed64Repeated" json:"F_Fixed64_repeated,omitempty"` F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated,json=FUint32Repeated" json:"F_Uint32_repeated,omitempty"` F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated,json=FUint64Repeated" json:"F_Uint64_repeated,omitempty"` F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated,json=FFloatRepeated" json:"F_Float_repeated,omitempty"` F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated,json=FDoubleRepeated" json:"F_Double_repeated,omitempty"` F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated,json=FStringRepeated" json:"F_String_repeated,omitempty"` F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated,json=FBytesRepeated" json:"F_Bytes_repeated,omitempty"` F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated,json=FSint32Repeated" json:"F_Sint32_repeated,omitempty"` F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated,json=FSint64Repeated" json:"F_Sint64_repeated,omitempty"` // Optional fields of all basic types F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional,json=FBoolOptional" json:"F_Bool_optional,omitempty"` F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional,json=FInt32Optional" json:"F_Int32_optional,omitempty"` F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional,json=FInt64Optional" json:"F_Int64_optional,omitempty"` F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional,json=FFixed32Optional" json:"F_Fixed32_optional,omitempty"` F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional,json=FFixed64Optional" json:"F_Fixed64_optional,omitempty"` F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional,json=FUint32Optional" json:"F_Uint32_optional,omitempty"` F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional,json=FUint64Optional" json:"F_Uint64_optional,omitempty"` F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional,json=FFloatOptional" json:"F_Float_optional,omitempty"` F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional,json=FDoubleOptional" json:"F_Double_optional,omitempty"` F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional,json=FStringOptional" json:"F_String_optional,omitempty"` F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional,json=FBytesOptional" json:"F_Bytes_optional,omitempty"` F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional,json=FSint32Optional" json:"F_Sint32_optional,omitempty"` F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional,json=FSint64Optional" json:"F_Sint64_optional,omitempty"` // Default-valued fields of all basic types F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,json=FBoolDefaulted,def=1" json:"F_Bool_defaulted,omitempty"` F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,json=FInt32Defaulted,def=32" json:"F_Int32_defaulted,omitempty"` F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,json=FInt64Defaulted,def=64" json:"F_Int64_defaulted,omitempty"` F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,json=FFixed32Defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"` F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,json=FFixed64Defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"` F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,json=FUint32Defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"` F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,json=FUint64Defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"` F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,json=FFloatDefaulted,def=314159" json:"F_Float_defaulted,omitempty"` F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,json=FDoubleDefaulted,def=271828" json:"F_Double_defaulted,omitempty"` F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,json=FStringDefaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"` F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,json=FBytesDefaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"` F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,json=FSint32Defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"` F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,json=FSint64Defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"` // Packed repeated fields (no string or bytes). F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed,json=FBoolRepeatedPacked" json:"F_Bool_repeated_packed,omitempty"` F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed,json=FInt32RepeatedPacked" json:"F_Int32_repeated_packed,omitempty"` F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed,json=FInt64RepeatedPacked" json:"F_Int64_repeated_packed,omitempty"` F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed,json=FFixed32RepeatedPacked" json:"F_Fixed32_repeated_packed,omitempty"` F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed,json=FFixed64RepeatedPacked" json:"F_Fixed64_repeated_packed,omitempty"` F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed,json=FUint32RepeatedPacked" json:"F_Uint32_repeated_packed,omitempty"` F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed,json=FUint64RepeatedPacked" json:"F_Uint64_repeated_packed,omitempty"` F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed,json=FFloatRepeatedPacked" json:"F_Float_repeated_packed,omitempty"` F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed,json=FDoubleRepeatedPacked" json:"F_Double_repeated_packed,omitempty"` F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed,json=FSint32RepeatedPacked" json:"F_Sint32_repeated_packed,omitempty"` F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed,json=FSint64RepeatedPacked" json:"F_Sint64_repeated_packed,omitempty"` Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup,json=requiredgroup" json:"requiredgroup,omitempty"` Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup,json=repeatedgroup" json:"repeatedgroup,omitempty"` Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup,json=optionalgroup" json:"optionalgroup,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTest) Reset() { *m = GoTest{} } func (m *GoTest) String() string { return proto.CompactTextString(m) } func (*GoTest) ProtoMessage() {} func (*GoTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } const Default_GoTest_F_BoolDefaulted bool = true const Default_GoTest_F_Int32Defaulted int32 = 32 const Default_GoTest_F_Int64Defaulted int64 = 64 const Default_GoTest_F_Fixed32Defaulted uint32 = 320 const Default_GoTest_F_Fixed64Defaulted uint64 = 640 const Default_GoTest_F_Uint32Defaulted uint32 = 3200 const Default_GoTest_F_Uint64Defaulted uint64 = 6400 const Default_GoTest_F_FloatDefaulted float32 = 314159 const Default_GoTest_F_DoubleDefaulted float64 = 271828 const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n" var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose") const Default_GoTest_F_Sint32Defaulted int32 = -32 const Default_GoTest_F_Sint64Defaulted int64 = -64 func (m *GoTest) GetKind() GoTest_KIND { if m != nil && m.Kind != nil { return *m.Kind } return GoTest_VOID } func (m *GoTest) GetTable() string { if m != nil && m.Table != nil { return *m.Table } return "" } func (m *GoTest) GetParam() int32 { if m != nil && m.Param != nil { return *m.Param } return 0 } func (m *GoTest) GetRequiredField() *GoTestField { if m != nil { return m.RequiredField } return nil } func (m *GoTest) GetRepeatedField() []*GoTestField { if m != nil { return m.RepeatedField } return nil } func (m *GoTest) GetOptionalField() *GoTestField { if m != nil { return m.OptionalField } return nil } func (m *GoTest) GetF_BoolRequired() bool { if m != nil && m.F_BoolRequired != nil { return *m.F_BoolRequired } return false } func (m *GoTest) GetF_Int32Required() int32 { if m != nil && m.F_Int32Required != nil { return *m.F_Int32Required } return 0 } func (m *GoTest) GetF_Int64Required() int64 { if m != nil && m.F_Int64Required != nil { return *m.F_Int64Required } return 0 } func (m *GoTest) GetF_Fixed32Required() uint32 { if m != nil && m.F_Fixed32Required != nil { return *m.F_Fixed32Required } return 0 } func (m *GoTest) GetF_Fixed64Required() uint64 { if m != nil && m.F_Fixed64Required != nil { return *m.F_Fixed64Required } return 0 } func (m *GoTest) GetF_Uint32Required() uint32 { if m != nil && m.F_Uint32Required != nil { return *m.F_Uint32Required } return 0 } func (m *GoTest) GetF_Uint64Required() uint64 { if m != nil && m.F_Uint64Required != nil { return *m.F_Uint64Required } return 0 } func (m *GoTest) GetF_FloatRequired() float32 { if m != nil && m.F_FloatRequired != nil { return *m.F_FloatRequired } return 0 } func (m *GoTest) GetF_DoubleRequired() float64 { if m != nil && m.F_DoubleRequired != nil { return *m.F_DoubleRequired } return 0 } func (m *GoTest) GetF_StringRequired() string { if m != nil && m.F_StringRequired != nil { return *m.F_StringRequired } return "" } func (m *GoTest) GetF_BytesRequired() []byte { if m != nil { return m.F_BytesRequired } return nil } func (m *GoTest) GetF_Sint32Required() int32 { if m != nil && m.F_Sint32Required != nil { return *m.F_Sint32Required } return 0 } func (m *GoTest) GetF_Sint64Required() int64 { if m != nil && m.F_Sint64Required != nil { return *m.F_Sint64Required } return 0 } func (m *GoTest) GetF_BoolRepeated() []bool { if m != nil { return m.F_BoolRepeated } return nil } func (m *GoTest) GetF_Int32Repeated() []int32 { if m != nil { return m.F_Int32Repeated } return nil } func (m *GoTest) GetF_Int64Repeated() []int64 { if m != nil { return m.F_Int64Repeated } return nil } func (m *GoTest) GetF_Fixed32Repeated() []uint32 { if m != nil { return m.F_Fixed32Repeated } return nil } func (m *GoTest) GetF_Fixed64Repeated() []uint64 { if m != nil { return m.F_Fixed64Repeated } return nil } func (m *GoTest) GetF_Uint32Repeated() []uint32 { if m != nil { return m.F_Uint32Repeated } return nil } func (m *GoTest) GetF_Uint64Repeated() []uint64 { if m != nil { return m.F_Uint64Repeated } return nil } func (m *GoTest) GetF_FloatRepeated() []float32 { if m != nil { return m.F_FloatRepeated } return nil } func (m *GoTest) GetF_DoubleRepeated() []float64 { if m != nil { return m.F_DoubleRepeated } return nil } func (m *GoTest) GetF_StringRepeated() []string { if m != nil { return m.F_StringRepeated } return nil } func (m *GoTest) GetF_BytesRepeated() [][]byte { if m != nil { return m.F_BytesRepeated } return nil } func (m *GoTest) GetF_Sint32Repeated() []int32 { if m != nil { return m.F_Sint32Repeated } return nil } func (m *GoTest) GetF_Sint64Repeated() []int64 { if m != nil { return m.F_Sint64Repeated } return nil } func (m *GoTest) GetF_BoolOptional() bool { if m != nil && m.F_BoolOptional != nil { return *m.F_BoolOptional } return false } func (m *GoTest) GetF_Int32Optional() int32 { if m != nil && m.F_Int32Optional != nil { return *m.F_Int32Optional } return 0 } func (m *GoTest) GetF_Int64Optional() int64 { if m != nil && m.F_Int64Optional != nil { return *m.F_Int64Optional } return 0 } func (m *GoTest) GetF_Fixed32Optional() uint32 { if m != nil && m.F_Fixed32Optional != nil { return *m.F_Fixed32Optional } return 0 } func (m *GoTest) GetF_Fixed64Optional() uint64 { if m != nil && m.F_Fixed64Optional != nil { return *m.F_Fixed64Optional } return 0 } func (m *GoTest) GetF_Uint32Optional() uint32 { if m != nil && m.F_Uint32Optional != nil { return *m.F_Uint32Optional } return 0 } func (m *GoTest) GetF_Uint64Optional() uint64 { if m != nil && m.F_Uint64Optional != nil { return *m.F_Uint64Optional } return 0 } func (m *GoTest) GetF_FloatOptional() float32 { if m != nil && m.F_FloatOptional != nil { return *m.F_FloatOptional } return 0 } func (m *GoTest) GetF_DoubleOptional() float64 { if m != nil && m.F_DoubleOptional != nil { return *m.F_DoubleOptional } return 0 } func (m *GoTest) GetF_StringOptional() string { if m != nil && m.F_StringOptional != nil { return *m.F_StringOptional } return "" } func (m *GoTest) GetF_BytesOptional() []byte { if m != nil { return m.F_BytesOptional } return nil } func (m *GoTest) GetF_Sint32Optional() int32 { if m != nil && m.F_Sint32Optional != nil { return *m.F_Sint32Optional } return 0 } func (m *GoTest) GetF_Sint64Optional() int64 { if m != nil && m.F_Sint64Optional != nil { return *m.F_Sint64Optional } return 0 } func (m *GoTest) GetF_BoolDefaulted() bool { if m != nil && m.F_BoolDefaulted != nil { return *m.F_BoolDefaulted } return Default_GoTest_F_BoolDefaulted } func (m *GoTest) GetF_Int32Defaulted() int32 { if m != nil && m.F_Int32Defaulted != nil { return *m.F_Int32Defaulted } return Default_GoTest_F_Int32Defaulted } func (m *GoTest) GetF_Int64Defaulted() int64 { if m != nil && m.F_Int64Defaulted != nil { return *m.F_Int64Defaulted } return Default_GoTest_F_Int64Defaulted } func (m *GoTest) GetF_Fixed32Defaulted() uint32 { if m != nil && m.F_Fixed32Defaulted != nil { return *m.F_Fixed32Defaulted } return Default_GoTest_F_Fixed32Defaulted } func (m *GoTest) GetF_Fixed64Defaulted() uint64 { if m != nil && m.F_Fixed64Defaulted != nil { return *m.F_Fixed64Defaulted } return Default_GoTest_F_Fixed64Defaulted } func (m *GoTest) GetF_Uint32Defaulted() uint32 { if m != nil && m.F_Uint32Defaulted != nil { return *m.F_Uint32Defaulted } return Default_GoTest_F_Uint32Defaulted } func (m *GoTest) GetF_Uint64Defaulted() uint64 { if m != nil && m.F_Uint64Defaulted != nil { return *m.F_Uint64Defaulted } return Default_GoTest_F_Uint64Defaulted } func (m *GoTest) GetF_FloatDefaulted() float32 { if m != nil && m.F_FloatDefaulted != nil { return *m.F_FloatDefaulted } return Default_GoTest_F_FloatDefaulted } func (m *GoTest) GetF_DoubleDefaulted() float64 { if m != nil && m.F_DoubleDefaulted != nil { return *m.F_DoubleDefaulted } return Default_GoTest_F_DoubleDefaulted } func (m *GoTest) GetF_StringDefaulted() string { if m != nil && m.F_StringDefaulted != nil { return *m.F_StringDefaulted } return Default_GoTest_F_StringDefaulted } func (m *GoTest) GetF_BytesDefaulted() []byte { if m != nil && m.F_BytesDefaulted != nil { return m.F_BytesDefaulted } return append([]byte(nil), Default_GoTest_F_BytesDefaulted...) } func (m *GoTest) GetF_Sint32Defaulted() int32 { if m != nil && m.F_Sint32Defaulted != nil { return *m.F_Sint32Defaulted } return Default_GoTest_F_Sint32Defaulted } func (m *GoTest) GetF_Sint64Defaulted() int64 { if m != nil && m.F_Sint64Defaulted != nil { return *m.F_Sint64Defaulted } return Default_GoTest_F_Sint64Defaulted } func (m *GoTest) GetF_BoolRepeatedPacked() []bool { if m != nil { return m.F_BoolRepeatedPacked } return nil } func (m *GoTest) GetF_Int32RepeatedPacked() []int32 { if m != nil { return m.F_Int32RepeatedPacked } return nil } func (m *GoTest) GetF_Int64RepeatedPacked() []int64 { if m != nil { return m.F_Int64RepeatedPacked } return nil } func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32 { if m != nil { return m.F_Fixed32RepeatedPacked } return nil } func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64 { if m != nil { return m.F_Fixed64RepeatedPacked } return nil } func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32 { if m != nil { return m.F_Uint32RepeatedPacked } return nil } func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64 { if m != nil { return m.F_Uint64RepeatedPacked } return nil } func (m *GoTest) GetF_FloatRepeatedPacked() []float32 { if m != nil { return m.F_FloatRepeatedPacked } return nil } func (m *GoTest) GetF_DoubleRepeatedPacked() []float64 { if m != nil { return m.F_DoubleRepeatedPacked } return nil } func (m *GoTest) GetF_Sint32RepeatedPacked() []int32 { if m != nil { return m.F_Sint32RepeatedPacked } return nil } func (m *GoTest) GetF_Sint64RepeatedPacked() []int64 { if m != nil { return m.F_Sint64RepeatedPacked } return nil } func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup { if m != nil { return m.Requiredgroup } return nil } func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup { if m != nil { return m.Repeatedgroup } return nil } func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup { if m != nil { return m.Optionalgroup } return nil } // Required, repeated, and optional groups. type GoTest_RequiredGroup struct { RequiredField *string `protobuf:"bytes,71,req,name=RequiredField" json:"RequiredField,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} } func (m *GoTest_RequiredGroup) String() string { return proto.CompactTextString(m) } func (*GoTest_RequiredGroup) ProtoMessage() {} func (*GoTest_RequiredGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } func (m *GoTest_RequiredGroup) GetRequiredField() string { if m != nil && m.RequiredField != nil { return *m.RequiredField } return "" } type GoTest_RepeatedGroup struct { RequiredField *string `protobuf:"bytes,81,req,name=RequiredField" json:"RequiredField,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} } func (m *GoTest_RepeatedGroup) String() string { return proto.CompactTextString(m) } func (*GoTest_RepeatedGroup) ProtoMessage() {} func (*GoTest_RepeatedGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 1} } func (m *GoTest_RepeatedGroup) GetRequiredField() string { if m != nil && m.RequiredField != nil { return *m.RequiredField } return "" } type GoTest_OptionalGroup struct { RequiredField *string `protobuf:"bytes,91,req,name=RequiredField" json:"RequiredField,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} } func (m *GoTest_OptionalGroup) String() string { return proto.CompactTextString(m) } func (*GoTest_OptionalGroup) ProtoMessage() {} func (*GoTest_OptionalGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 2} } func (m *GoTest_OptionalGroup) GetRequiredField() string { if m != nil && m.RequiredField != nil { return *m.RequiredField } return "" } // For testing a group containing a required field. type GoTestRequiredGroupField struct { Group *GoTestRequiredGroupField_Group `protobuf:"group,1,req,name=Group,json=group" json:"group,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTestRequiredGroupField) Reset() { *m = GoTestRequiredGroupField{} } func (m *GoTestRequiredGroupField) String() string { return proto.CompactTextString(m) } func (*GoTestRequiredGroupField) ProtoMessage() {} func (*GoTestRequiredGroupField) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (m *GoTestRequiredGroupField) GetGroup() *GoTestRequiredGroupField_Group { if m != nil { return m.Group } return nil } type GoTestRequiredGroupField_Group struct { Field *int32 `protobuf:"varint,2,req,name=Field" json:"Field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoTestRequiredGroupField_Group) Reset() { *m = GoTestRequiredGroupField_Group{} } func (m *GoTestRequiredGroupField_Group) String() string { return proto.CompactTextString(m) } func (*GoTestRequiredGroupField_Group) ProtoMessage() {} func (*GoTestRequiredGroupField_Group) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3, 0} } func (m *GoTestRequiredGroupField_Group) GetField() int32 { if m != nil && m.Field != nil { return *m.Field } return 0 } // For testing skipping of unrecognized fields. // Numbers are all big, larger than tag numbers in GoTestField, // the message used in the corresponding test. type GoSkipTest struct { SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32,json=skipInt32" json:"skip_int32,omitempty"` SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32,json=skipFixed32" json:"skip_fixed32,omitempty"` SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64,json=skipFixed64" json:"skip_fixed64,omitempty"` SkipString *string `protobuf:"bytes,14,req,name=skip_string,json=skipString" json:"skip_string,omitempty"` Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup,json=skipgroup" json:"skipgroup,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoSkipTest) Reset() { *m = GoSkipTest{} } func (m *GoSkipTest) String() string { return proto.CompactTextString(m) } func (*GoSkipTest) ProtoMessage() {} func (*GoSkipTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (m *GoSkipTest) GetSkipInt32() int32 { if m != nil && m.SkipInt32 != nil { return *m.SkipInt32 } return 0 } func (m *GoSkipTest) GetSkipFixed32() uint32 { if m != nil && m.SkipFixed32 != nil { return *m.SkipFixed32 } return 0 } func (m *GoSkipTest) GetSkipFixed64() uint64 { if m != nil && m.SkipFixed64 != nil { return *m.SkipFixed64 } return 0 } func (m *GoSkipTest) GetSkipString() string { if m != nil && m.SkipString != nil { return *m.SkipString } return "" } func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup { if m != nil { return m.Skipgroup } return nil } type GoSkipTest_SkipGroup struct { GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32,json=groupInt32" json:"group_int32,omitempty"` GroupString *string `protobuf:"bytes,17,req,name=group_string,json=groupString" json:"group_string,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} } func (m *GoSkipTest_SkipGroup) String() string { return proto.CompactTextString(m) } func (*GoSkipTest_SkipGroup) ProtoMessage() {} func (*GoSkipTest_SkipGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4, 0} } func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32 { if m != nil && m.GroupInt32 != nil { return *m.GroupInt32 } return 0 } func (m *GoSkipTest_SkipGroup) GetGroupString() string { if m != nil && m.GroupString != nil { return *m.GroupString } return "" } // For testing packed/non-packed decoder switching. // A serialized instance of one should be deserializable as the other. type NonPackedTest struct { A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *NonPackedTest) Reset() { *m = NonPackedTest{} } func (m *NonPackedTest) String() string { return proto.CompactTextString(m) } func (*NonPackedTest) ProtoMessage() {} func (*NonPackedTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } func (m *NonPackedTest) GetA() []int32 { if m != nil { return m.A } return nil } type PackedTest struct { B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *PackedTest) Reset() { *m = PackedTest{} } func (m *PackedTest) String() string { return proto.CompactTextString(m) } func (*PackedTest) ProtoMessage() {} func (*PackedTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } func (m *PackedTest) GetB() []int32 { if m != nil { return m.B } return nil } type MaxTag struct { // Maximum possible tag number. LastField *string `protobuf:"bytes,536870911,opt,name=last_field,json=lastField" json:"last_field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MaxTag) Reset() { *m = MaxTag{} } func (m *MaxTag) String() string { return proto.CompactTextString(m) } func (*MaxTag) ProtoMessage() {} func (*MaxTag) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } func (m *MaxTag) GetLastField() string { if m != nil && m.LastField != nil { return *m.LastField } return "" } type OldMessage struct { Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` Num *int32 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *OldMessage) Reset() { *m = OldMessage{} } func (m *OldMessage) String() string { return proto.CompactTextString(m) } func (*OldMessage) ProtoMessage() {} func (*OldMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } func (m *OldMessage) GetNested() *OldMessage_Nested { if m != nil { return m.Nested } return nil } func (m *OldMessage) GetNum() int32 { if m != nil && m.Num != nil { return *m.Num } return 0 } type OldMessage_Nested struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} } func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) } func (*OldMessage_Nested) ProtoMessage() {} func (*OldMessage_Nested) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8, 0} } func (m *OldMessage_Nested) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } // NewMessage is wire compatible with OldMessage; // imagine it as a future version. type NewMessage struct { Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"` // This is an int32 in OldMessage. Num *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *NewMessage) Reset() { *m = NewMessage{} } func (m *NewMessage) String() string { return proto.CompactTextString(m) } func (*NewMessage) ProtoMessage() {} func (*NewMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} } func (m *NewMessage) GetNested() *NewMessage_Nested { if m != nil { return m.Nested } return nil } func (m *NewMessage) GetNum() int64 { if m != nil && m.Num != nil { return *m.Num } return 0 } type NewMessage_Nested struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` FoodGroup *string `protobuf:"bytes,2,opt,name=food_group,json=foodGroup" json:"food_group,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} } func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) } func (*NewMessage_Nested) ProtoMessage() {} func (*NewMessage_Nested) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9, 0} } func (m *NewMessage_Nested) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *NewMessage_Nested) GetFoodGroup() string { if m != nil && m.FoodGroup != nil { return *m.FoodGroup } return "" } type InnerMessage struct { Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"` Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"` Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *InnerMessage) Reset() { *m = InnerMessage{} } func (m *InnerMessage) String() string { return proto.CompactTextString(m) } func (*InnerMessage) ProtoMessage() {} func (*InnerMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} } const Default_InnerMessage_Port int32 = 4000 func (m *InnerMessage) GetHost() string { if m != nil && m.Host != nil { return *m.Host } return "" } func (m *InnerMessage) GetPort() int32 { if m != nil && m.Port != nil { return *m.Port } return Default_InnerMessage_Port } func (m *InnerMessage) GetConnected() bool { if m != nil && m.Connected != nil { return *m.Connected } return false } type OtherMessage struct { Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"` Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"` Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OtherMessage) Reset() { *m = OtherMessage{} } func (m *OtherMessage) String() string { return proto.CompactTextString(m) } func (*OtherMessage) ProtoMessage() {} func (*OtherMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} } var extRange_OtherMessage = []proto.ExtensionRange{ {100, 536870911}, } func (*OtherMessage) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OtherMessage } func (m *OtherMessage) GetKey() int64 { if m != nil && m.Key != nil { return *m.Key } return 0 } func (m *OtherMessage) GetValue() []byte { if m != nil { return m.Value } return nil } func (m *OtherMessage) GetWeight() float32 { if m != nil && m.Weight != nil { return *m.Weight } return 0 } func (m *OtherMessage) GetInner() *InnerMessage { if m != nil { return m.Inner } return nil } type RequiredInnerMessage struct { LeoFinallyWonAnOscar *InnerMessage `protobuf:"bytes,1,req,name=leo_finally_won_an_oscar,json=leoFinallyWonAnOscar" json:"leo_finally_won_an_oscar,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *RequiredInnerMessage) Reset() { *m = RequiredInnerMessage{} } func (m *RequiredInnerMessage) String() string { return proto.CompactTextString(m) } func (*RequiredInnerMessage) ProtoMessage() {} func (*RequiredInnerMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} } func (m *RequiredInnerMessage) GetLeoFinallyWonAnOscar() *InnerMessage { if m != nil { return m.LeoFinallyWonAnOscar } return nil } type MyMessage struct { Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"` Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"` Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"` Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"` Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"` Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"` WeMustGoDeeper *RequiredInnerMessage `protobuf:"bytes,13,opt,name=we_must_go_deeper,json=weMustGoDeeper" json:"we_must_go_deeper,omitempty"` RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner,json=repInner" json:"rep_inner,omitempty"` Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"` Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"` // This field becomes [][]byte in the generated code. RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes,json=repBytes" json:"rep_bytes,omitempty"` Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *MyMessage) Reset() { *m = MyMessage{} } func (m *MyMessage) String() string { return proto.CompactTextString(m) } func (*MyMessage) ProtoMessage() {} func (*MyMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} } var extRange_MyMessage = []proto.ExtensionRange{ {100, 536870911}, } func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange { return extRange_MyMessage } func (m *MyMessage) GetCount() int32 { if m != nil && m.Count != nil { return *m.Count } return 0 } func (m *MyMessage) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *MyMessage) GetQuote() string { if m != nil && m.Quote != nil { return *m.Quote } return "" } func (m *MyMessage) GetPet() []string { if m != nil { return m.Pet } return nil } func (m *MyMessage) GetInner() *InnerMessage { if m != nil { return m.Inner } return nil } func (m *MyMessage) GetOthers() []*OtherMessage { if m != nil { return m.Others } return nil } func (m *MyMessage) GetWeMustGoDeeper() *RequiredInnerMessage { if m != nil { return m.WeMustGoDeeper } return nil } func (m *MyMessage) GetRepInner() []*InnerMessage { if m != nil { return m.RepInner } return nil } func (m *MyMessage) GetBikeshed() MyMessage_Color { if m != nil && m.Bikeshed != nil { return *m.Bikeshed } return MyMessage_RED } func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup { if m != nil { return m.Somegroup } return nil } func (m *MyMessage) GetRepBytes() [][]byte { if m != nil { return m.RepBytes } return nil } func (m *MyMessage) GetBigfloat() float64 { if m != nil && m.Bigfloat != nil { return *m.Bigfloat } return 0 } type MyMessage_SomeGroup struct { GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} } func (m *MyMessage_SomeGroup) String() string { return proto.CompactTextString(m) } func (*MyMessage_SomeGroup) ProtoMessage() {} func (*MyMessage_SomeGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13, 0} } func (m *MyMessage_SomeGroup) GetGroupField() int32 { if m != nil && m.GroupField != nil { return *m.GroupField } return 0 } type Ext struct { Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Ext) Reset() { *m = Ext{} } func (m *Ext) String() string { return proto.CompactTextString(m) } func (*Ext) ProtoMessage() {} func (*Ext) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} } func (m *Ext) GetData() string { if m != nil && m.Data != nil { return *m.Data } return "" } var E_Ext_More = &proto.ExtensionDesc{ ExtendedType: (*MyMessage)(nil), ExtensionType: (*Ext)(nil), Field: 103, Name: "testdata.Ext.more", Tag: "bytes,103,opt,name=more", Filename: "test.proto", } var E_Ext_Text = &proto.ExtensionDesc{ ExtendedType: (*MyMessage)(nil), ExtensionType: (*string)(nil), Field: 104, Name: "testdata.Ext.text", Tag: "bytes,104,opt,name=text", Filename: "test.proto", } var E_Ext_Number = &proto.ExtensionDesc{ ExtendedType: (*MyMessage)(nil), ExtensionType: (*int32)(nil), Field: 105, Name: "testdata.Ext.number", Tag: "varint,105,opt,name=number", Filename: "test.proto", } type ComplexExtension struct { First *int32 `protobuf:"varint,1,opt,name=first" json:"first,omitempty"` Second *int32 `protobuf:"varint,2,opt,name=second" json:"second,omitempty"` Third []int32 `protobuf:"varint,3,rep,name=third" json:"third,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *ComplexExtension) Reset() { *m = ComplexExtension{} } func (m *ComplexExtension) String() string { return proto.CompactTextString(m) } func (*ComplexExtension) ProtoMessage() {} func (*ComplexExtension) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} } func (m *ComplexExtension) GetFirst() int32 { if m != nil && m.First != nil { return *m.First } return 0 } func (m *ComplexExtension) GetSecond() int32 { if m != nil && m.Second != nil { return *m.Second } return 0 } func (m *ComplexExtension) GetThird() []int32 { if m != nil { return m.Third } return nil } type DefaultsMessage struct { proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *DefaultsMessage) Reset() { *m = DefaultsMessage{} } func (m *DefaultsMessage) String() string { return proto.CompactTextString(m) } func (*DefaultsMessage) ProtoMessage() {} func (*DefaultsMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} } var extRange_DefaultsMessage = []proto.ExtensionRange{ {100, 536870911}, } func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange { return extRange_DefaultsMessage } type MyMessageSet struct { proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *MyMessageSet) Reset() { *m = MyMessageSet{} } func (m *MyMessageSet) String() string { return proto.CompactTextString(m) } func (*MyMessageSet) ProtoMessage() {} func (*MyMessageSet) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} } func (m *MyMessageSet) Marshal() ([]byte, error) { return proto.MarshalMessageSet(&m.XXX_InternalExtensions) } func (m *MyMessageSet) Unmarshal(buf []byte) error { return proto.UnmarshalMessageSet(buf, &m.XXX_InternalExtensions) } func (m *MyMessageSet) MarshalJSON() ([]byte, error) { return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions) } func (m *MyMessageSet) UnmarshalJSON(buf []byte) error { return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions) } // ensure MyMessageSet satisfies proto.Marshaler and proto.Unmarshaler var _ proto.Marshaler = (*MyMessageSet)(nil) var _ proto.Unmarshaler = (*MyMessageSet)(nil) var extRange_MyMessageSet = []proto.ExtensionRange{ {100, 2147483646}, } func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange { return extRange_MyMessageSet } type Empty struct { XXX_unrecognized []byte `json:"-"` } func (m *Empty) Reset() { *m = Empty{} } func (m *Empty) String() string { return proto.CompactTextString(m) } func (*Empty) ProtoMessage() {} func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} } type MessageList struct { Message []*MessageList_Message `protobuf:"group,1,rep,name=Message,json=message" json:"message,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MessageList) Reset() { *m = MessageList{} } func (m *MessageList) String() string { return proto.CompactTextString(m) } func (*MessageList) ProtoMessage() {} func (*MessageList) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} } func (m *MessageList) GetMessage() []*MessageList_Message { if m != nil { return m.Message } return nil } type MessageList_Message struct { Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"` Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MessageList_Message) Reset() { *m = MessageList_Message{} } func (m *MessageList_Message) String() string { return proto.CompactTextString(m) } func (*MessageList_Message) ProtoMessage() {} func (*MessageList_Message) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19, 0} } func (m *MessageList_Message) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *MessageList_Message) GetCount() int32 { if m != nil && m.Count != nil { return *m.Count } return 0 } type Strings struct { StringField *string `protobuf:"bytes,1,opt,name=string_field,json=stringField" json:"string_field,omitempty"` BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field,json=bytesField" json:"bytes_field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Strings) Reset() { *m = Strings{} } func (m *Strings) String() string { return proto.CompactTextString(m) } func (*Strings) ProtoMessage() {} func (*Strings) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20} } func (m *Strings) GetStringField() string { if m != nil && m.StringField != nil { return *m.StringField } return "" } func (m *Strings) GetBytesField() []byte { if m != nil { return m.BytesField } return nil } type Defaults struct { // Default-valued fields of all basic types. // Same as GoTest, but copied here to make testing easier. F_Bool *bool `protobuf:"varint,1,opt,name=F_Bool,json=FBool,def=1" json:"F_Bool,omitempty"` F_Int32 *int32 `protobuf:"varint,2,opt,name=F_Int32,json=FInt32,def=32" json:"F_Int32,omitempty"` F_Int64 *int64 `protobuf:"varint,3,opt,name=F_Int64,json=FInt64,def=64" json:"F_Int64,omitempty"` F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=FFixed32,def=320" json:"F_Fixed32,omitempty"` F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=FFixed64,def=640" json:"F_Fixed64,omitempty"` F_Uint32 *uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=FUint32,def=3200" json:"F_Uint32,omitempty"` F_Uint64 *uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=FUint64,def=6400" json:"F_Uint64,omitempty"` F_Float *float32 `protobuf:"fixed32,8,opt,name=F_Float,json=FFloat,def=314159" json:"F_Float,omitempty"` F_Double *float64 `protobuf:"fixed64,9,opt,name=F_Double,json=FDouble,def=271828" json:"F_Double,omitempty"` F_String *string `protobuf:"bytes,10,opt,name=F_String,json=FString,def=hello, \"world!\"\n" json:"F_String,omitempty"` F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=FBytes,def=Bignose" json:"F_Bytes,omitempty"` F_Sint32 *int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=FSint32,def=-32" json:"F_Sint32,omitempty"` F_Sint64 *int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=FSint64,def=-64" json:"F_Sint64,omitempty"` F_Enum *Defaults_Color `protobuf:"varint,14,opt,name=F_Enum,json=FEnum,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"` // More fields with crazy defaults. F_Pinf *float32 `protobuf:"fixed32,15,opt,name=F_Pinf,json=FPinf,def=inf" json:"F_Pinf,omitempty"` F_Ninf *float32 `protobuf:"fixed32,16,opt,name=F_Ninf,json=FNinf,def=-inf" json:"F_Ninf,omitempty"` F_Nan *float32 `protobuf:"fixed32,17,opt,name=F_Nan,json=FNan,def=nan" json:"F_Nan,omitempty"` // Sub-message. Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"` // Redundant but explicit defaults. StrZero *string `protobuf:"bytes,19,opt,name=str_zero,json=strZero,def=" json:"str_zero,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Defaults) Reset() { *m = Defaults{} } func (m *Defaults) String() string { return proto.CompactTextString(m) } func (*Defaults) ProtoMessage() {} func (*Defaults) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{21} } const Default_Defaults_F_Bool bool = true const Default_Defaults_F_Int32 int32 = 32 const Default_Defaults_F_Int64 int64 = 64 const Default_Defaults_F_Fixed32 uint32 = 320 const Default_Defaults_F_Fixed64 uint64 = 640 const Default_Defaults_F_Uint32 uint32 = 3200 const Default_Defaults_F_Uint64 uint64 = 6400 const Default_Defaults_F_Float float32 = 314159 const Default_Defaults_F_Double float64 = 271828 const Default_Defaults_F_String string = "hello, \"world!\"\n" var Default_Defaults_F_Bytes []byte = []byte("Bignose") const Default_Defaults_F_Sint32 int32 = -32 const Default_Defaults_F_Sint64 int64 = -64 const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN var Default_Defaults_F_Pinf float32 = float32(math.Inf(1)) var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1)) var Default_Defaults_F_Nan float32 = float32(math.NaN()) func (m *Defaults) GetF_Bool() bool { if m != nil && m.F_Bool != nil { return *m.F_Bool } return Default_Defaults_F_Bool } func (m *Defaults) GetF_Int32() int32 { if m != nil && m.F_Int32 != nil { return *m.F_Int32 } return Default_Defaults_F_Int32 } func (m *Defaults) GetF_Int64() int64 { if m != nil && m.F_Int64 != nil { return *m.F_Int64 } return Default_Defaults_F_Int64 } func (m *Defaults) GetF_Fixed32() uint32 { if m != nil && m.F_Fixed32 != nil { return *m.F_Fixed32 } return Default_Defaults_F_Fixed32 } func (m *Defaults) GetF_Fixed64() uint64 { if m != nil && m.F_Fixed64 != nil { return *m.F_Fixed64 } return Default_Defaults_F_Fixed64 } func (m *Defaults) GetF_Uint32() uint32 { if m != nil && m.F_Uint32 != nil { return *m.F_Uint32 } return Default_Defaults_F_Uint32 } func (m *Defaults) GetF_Uint64() uint64 { if m != nil && m.F_Uint64 != nil { return *m.F_Uint64 } return Default_Defaults_F_Uint64 } func (m *Defaults) GetF_Float() float32 { if m != nil && m.F_Float != nil { return *m.F_Float } return Default_Defaults_F_Float } func (m *Defaults) GetF_Double() float64 { if m != nil && m.F_Double != nil { return *m.F_Double } return Default_Defaults_F_Double } func (m *Defaults) GetF_String() string { if m != nil && m.F_String != nil { return *m.F_String } return Default_Defaults_F_String } func (m *Defaults) GetF_Bytes() []byte { if m != nil && m.F_Bytes != nil { return m.F_Bytes } return append([]byte(nil), Default_Defaults_F_Bytes...) } func (m *Defaults) GetF_Sint32() int32 { if m != nil && m.F_Sint32 != nil { return *m.F_Sint32 } return Default_Defaults_F_Sint32 } func (m *Defaults) GetF_Sint64() int64 { if m != nil && m.F_Sint64 != nil { return *m.F_Sint64 } return Default_Defaults_F_Sint64 } func (m *Defaults) GetF_Enum() Defaults_Color { if m != nil && m.F_Enum != nil { return *m.F_Enum } return Default_Defaults_F_Enum } func (m *Defaults) GetF_Pinf() float32 { if m != nil && m.F_Pinf != nil { return *m.F_Pinf } return Default_Defaults_F_Pinf } func (m *Defaults) GetF_Ninf() float32 { if m != nil && m.F_Ninf != nil { return *m.F_Ninf } return Default_Defaults_F_Ninf } func (m *Defaults) GetF_Nan() float32 { if m != nil && m.F_Nan != nil { return *m.F_Nan } return Default_Defaults_F_Nan } func (m *Defaults) GetSub() *SubDefaults { if m != nil { return m.Sub } return nil } func (m *Defaults) GetStrZero() string { if m != nil && m.StrZero != nil { return *m.StrZero } return "" } type SubDefaults struct { N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *SubDefaults) Reset() { *m = SubDefaults{} } func (m *SubDefaults) String() string { return proto.CompactTextString(m) } func (*SubDefaults) ProtoMessage() {} func (*SubDefaults) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{22} } const Default_SubDefaults_N int64 = 7 func (m *SubDefaults) GetN() int64 { if m != nil && m.N != nil { return *m.N } return Default_SubDefaults_N } type RepeatedEnum struct { Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} } func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) } func (*RepeatedEnum) ProtoMessage() {} func (*RepeatedEnum) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{23} } func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color { if m != nil { return m.Color } return nil } type MoreRepeated struct { Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"` BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed,json=boolsPacked" json:"bools_packed,omitempty"` Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"` IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed,json=intsPacked" json:"ints_packed,omitempty"` Int64SPacked []int64 `protobuf:"varint,7,rep,packed,name=int64s_packed,json=int64sPacked" json:"int64s_packed,omitempty"` Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"` Fixeds []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MoreRepeated) Reset() { *m = MoreRepeated{} } func (m *MoreRepeated) String() string { return proto.CompactTextString(m) } func (*MoreRepeated) ProtoMessage() {} func (*MoreRepeated) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{24} } func (m *MoreRepeated) GetBools() []bool { if m != nil { return m.Bools } return nil } func (m *MoreRepeated) GetBoolsPacked() []bool { if m != nil { return m.BoolsPacked } return nil } func (m *MoreRepeated) GetInts() []int32 { if m != nil { return m.Ints } return nil } func (m *MoreRepeated) GetIntsPacked() []int32 { if m != nil { return m.IntsPacked } return nil } func (m *MoreRepeated) GetInt64SPacked() []int64 { if m != nil { return m.Int64SPacked } return nil } func (m *MoreRepeated) GetStrings() []string { if m != nil { return m.Strings } return nil } func (m *MoreRepeated) GetFixeds() []uint32 { if m != nil { return m.Fixeds } return nil } type GroupOld struct { G *GroupOld_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GroupOld) Reset() { *m = GroupOld{} } func (m *GroupOld) String() string { return proto.CompactTextString(m) } func (*GroupOld) ProtoMessage() {} func (*GroupOld) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{25} } func (m *GroupOld) GetG() *GroupOld_G { if m != nil { return m.G } return nil } type GroupOld_G struct { X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GroupOld_G) Reset() { *m = GroupOld_G{} } func (m *GroupOld_G) String() string { return proto.CompactTextString(m) } func (*GroupOld_G) ProtoMessage() {} func (*GroupOld_G) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{25, 0} } func (m *GroupOld_G) GetX() int32 { if m != nil && m.X != nil { return *m.X } return 0 } type GroupNew struct { G *GroupNew_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GroupNew) Reset() { *m = GroupNew{} } func (m *GroupNew) String() string { return proto.CompactTextString(m) } func (*GroupNew) ProtoMessage() {} func (*GroupNew) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{26} } func (m *GroupNew) GetG() *GroupNew_G { if m != nil { return m.G } return nil } type GroupNew_G struct { X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"` Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GroupNew_G) Reset() { *m = GroupNew_G{} } func (m *GroupNew_G) String() string { return proto.CompactTextString(m) } func (*GroupNew_G) ProtoMessage() {} func (*GroupNew_G) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{26, 0} } func (m *GroupNew_G) GetX() int32 { if m != nil && m.X != nil { return *m.X } return 0 } func (m *GroupNew_G) GetY() int32 { if m != nil && m.Y != nil { return *m.Y } return 0 } type FloatingPoint struct { F *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"` Exact *bool `protobuf:"varint,2,opt,name=exact" json:"exact,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *FloatingPoint) Reset() { *m = FloatingPoint{} } func (m *FloatingPoint) String() string { return proto.CompactTextString(m) } func (*FloatingPoint) ProtoMessage() {} func (*FloatingPoint) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{27} } func (m *FloatingPoint) GetF() float64 { if m != nil && m.F != nil { return *m.F } return 0 } func (m *FloatingPoint) GetExact() bool { if m != nil && m.Exact != nil { return *m.Exact } return false } type MessageWithMap struct { NameMapping map[int32]string `protobuf:"bytes,1,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` MsgMapping map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` ByteMapping map[bool][]byte `protobuf:"bytes,3,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` StrToStr map[string]string `protobuf:"bytes,4,rep,name=str_to_str,json=strToStr" json:"str_to_str,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` XXX_unrecognized []byte `json:"-"` } func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } func (*MessageWithMap) ProtoMessage() {} func (*MessageWithMap) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{28} } func (m *MessageWithMap) GetNameMapping() map[int32]string { if m != nil { return m.NameMapping } return nil } func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint { if m != nil { return m.MsgMapping } return nil } func (m *MessageWithMap) GetByteMapping() map[bool][]byte { if m != nil { return m.ByteMapping } return nil } func (m *MessageWithMap) GetStrToStr() map[string]string { if m != nil { return m.StrToStr } return nil } type Oneof struct { // Types that are valid to be assigned to Union: // *Oneof_F_Bool // *Oneof_F_Int32 // *Oneof_F_Int64 // *Oneof_F_Fixed32 // *Oneof_F_Fixed64 // *Oneof_F_Uint32 // *Oneof_F_Uint64 // *Oneof_F_Float // *Oneof_F_Double // *Oneof_F_String // *Oneof_F_Bytes // *Oneof_F_Sint32 // *Oneof_F_Sint64 // *Oneof_F_Enum // *Oneof_F_Message // *Oneof_FGroup // *Oneof_F_Largest_Tag Union isOneof_Union `protobuf_oneof:"union"` // Types that are valid to be assigned to Tormato: // *Oneof_Value Tormato isOneof_Tormato `protobuf_oneof:"tormato"` XXX_unrecognized []byte `json:"-"` } func (m *Oneof) Reset() { *m = Oneof{} } func (m *Oneof) String() string { return proto.CompactTextString(m) } func (*Oneof) ProtoMessage() {} func (*Oneof) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{29} } type isOneof_Union interface { isOneof_Union() } type isOneof_Tormato interface { isOneof_Tormato() } type Oneof_F_Bool struct { F_Bool bool `protobuf:"varint,1,opt,name=F_Bool,json=FBool,oneof"` } type Oneof_F_Int32 struct { F_Int32 int32 `protobuf:"varint,2,opt,name=F_Int32,json=FInt32,oneof"` } type Oneof_F_Int64 struct { F_Int64 int64 `protobuf:"varint,3,opt,name=F_Int64,json=FInt64,oneof"` } type Oneof_F_Fixed32 struct { F_Fixed32 uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=FFixed32,oneof"` } type Oneof_F_Fixed64 struct { F_Fixed64 uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=FFixed64,oneof"` } type Oneof_F_Uint32 struct { F_Uint32 uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=FUint32,oneof"` } type Oneof_F_Uint64 struct { F_Uint64 uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=FUint64,oneof"` } type Oneof_F_Float struct { F_Float float32 `protobuf:"fixed32,8,opt,name=F_Float,json=FFloat,oneof"` } type Oneof_F_Double struct { F_Double float64 `protobuf:"fixed64,9,opt,name=F_Double,json=FDouble,oneof"` } type Oneof_F_String struct { F_String string `protobuf:"bytes,10,opt,name=F_String,json=FString,oneof"` } type Oneof_F_Bytes struct { F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=FBytes,oneof"` } type Oneof_F_Sint32 struct { F_Sint32 int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=FSint32,oneof"` } type Oneof_F_Sint64 struct { F_Sint64 int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=FSint64,oneof"` } type Oneof_F_Enum struct { F_Enum MyMessage_Color `protobuf:"varint,14,opt,name=F_Enum,json=FEnum,enum=testdata.MyMessage_Color,oneof"` } type Oneof_F_Message struct { F_Message *GoTestField `protobuf:"bytes,15,opt,name=F_Message,json=FMessage,oneof"` } type Oneof_FGroup struct { FGroup *Oneof_F_Group `protobuf:"group,16,opt,name=F_Group,json=fGroup,oneof"` } type Oneof_F_Largest_Tag struct { F_Largest_Tag int32 `protobuf:"varint,536870911,opt,name=F_Largest_Tag,json=FLargestTag,oneof"` } type Oneof_Value struct { Value int32 `protobuf:"varint,100,opt,name=value,oneof"` } func (*Oneof_F_Bool) isOneof_Union() {} func (*Oneof_F_Int32) isOneof_Union() {} func (*Oneof_F_Int64) isOneof_Union() {} func (*Oneof_F_Fixed32) isOneof_Union() {} func (*Oneof_F_Fixed64) isOneof_Union() {} func (*Oneof_F_Uint32) isOneof_Union() {} func (*Oneof_F_Uint64) isOneof_Union() {} func (*Oneof_F_Float) isOneof_Union() {} func (*Oneof_F_Double) isOneof_Union() {} func (*Oneof_F_String) isOneof_Union() {} func (*Oneof_F_Bytes) isOneof_Union() {} func (*Oneof_F_Sint32) isOneof_Union() {} func (*Oneof_F_Sint64) isOneof_Union() {} func (*Oneof_F_Enum) isOneof_Union() {} func (*Oneof_F_Message) isOneof_Union() {} func (*Oneof_FGroup) isOneof_Union() {} func (*Oneof_F_Largest_Tag) isOneof_Union() {} func (*Oneof_Value) isOneof_Tormato() {} func (m *Oneof) GetUnion() isOneof_Union { if m != nil { return m.Union } return nil } func (m *Oneof) GetTormato() isOneof_Tormato { if m != nil { return m.Tormato } return nil } func (m *Oneof) GetF_Bool() bool { if x, ok := m.GetUnion().(*Oneof_F_Bool); ok { return x.F_Bool } return false } func (m *Oneof) GetF_Int32() int32 { if x, ok := m.GetUnion().(*Oneof_F_Int32); ok { return x.F_Int32 } return 0 } func (m *Oneof) GetF_Int64() int64 { if x, ok := m.GetUnion().(*Oneof_F_Int64); ok { return x.F_Int64 } return 0 } func (m *Oneof) GetF_Fixed32() uint32 { if x, ok := m.GetUnion().(*Oneof_F_Fixed32); ok { return x.F_Fixed32 } return 0 } func (m *Oneof) GetF_Fixed64() uint64 { if x, ok := m.GetUnion().(*Oneof_F_Fixed64); ok { return x.F_Fixed64 } return 0 } func (m *Oneof) GetF_Uint32() uint32 { if x, ok := m.GetUnion().(*Oneof_F_Uint32); ok { return x.F_Uint32 } return 0 } func (m *Oneof) GetF_Uint64() uint64 { if x, ok := m.GetUnion().(*Oneof_F_Uint64); ok { return x.F_Uint64 } return 0 } func (m *Oneof) GetF_Float() float32 { if x, ok := m.GetUnion().(*Oneof_F_Float); ok { return x.F_Float } return 0 } func (m *Oneof) GetF_Double() float64 { if x, ok := m.GetUnion().(*Oneof_F_Double); ok { return x.F_Double } return 0 } func (m *Oneof) GetF_String() string { if x, ok := m.GetUnion().(*Oneof_F_String); ok { return x.F_String } return "" } func (m *Oneof) GetF_Bytes() []byte { if x, ok := m.GetUnion().(*Oneof_F_Bytes); ok { return x.F_Bytes } return nil } func (m *Oneof) GetF_Sint32() int32 { if x, ok := m.GetUnion().(*Oneof_F_Sint32); ok { return x.F_Sint32 } return 0 } func (m *Oneof) GetF_Sint64() int64 { if x, ok := m.GetUnion().(*Oneof_F_Sint64); ok { return x.F_Sint64 } return 0 } func (m *Oneof) GetF_Enum() MyMessage_Color { if x, ok := m.GetUnion().(*Oneof_F_Enum); ok { return x.F_Enum } return MyMessage_RED } func (m *Oneof) GetF_Message() *GoTestField { if x, ok := m.GetUnion().(*Oneof_F_Message); ok { return x.F_Message } return nil } func (m *Oneof) GetFGroup() *Oneof_F_Group { if x, ok := m.GetUnion().(*Oneof_FGroup); ok { return x.FGroup } return nil } func (m *Oneof) GetF_Largest_Tag() int32 { if x, ok := m.GetUnion().(*Oneof_F_Largest_Tag); ok { return x.F_Largest_Tag } return 0 } func (m *Oneof) GetValue() int32 { if x, ok := m.GetTormato().(*Oneof_Value); ok { return x.Value } return 0 } // XXX_OneofFuncs is for the internal use of the proto package. func (*Oneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Oneof_OneofMarshaler, _Oneof_OneofUnmarshaler, _Oneof_OneofSizer, []interface{}{ (*Oneof_F_Bool)(nil), (*Oneof_F_Int32)(nil), (*Oneof_F_Int64)(nil), (*Oneof_F_Fixed32)(nil), (*Oneof_F_Fixed64)(nil), (*Oneof_F_Uint32)(nil), (*Oneof_F_Uint64)(nil), (*Oneof_F_Float)(nil), (*Oneof_F_Double)(nil), (*Oneof_F_String)(nil), (*Oneof_F_Bytes)(nil), (*Oneof_F_Sint32)(nil), (*Oneof_F_Sint64)(nil), (*Oneof_F_Enum)(nil), (*Oneof_F_Message)(nil), (*Oneof_FGroup)(nil), (*Oneof_F_Largest_Tag)(nil), (*Oneof_Value)(nil), } } func _Oneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Oneof) // union switch x := m.Union.(type) { case *Oneof_F_Bool: t := uint64(0) if x.F_Bool { t = 1 } b.EncodeVarint(1<<3 | proto.WireVarint) b.EncodeVarint(t) case *Oneof_F_Int32: b.EncodeVarint(2<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.F_Int32)) case *Oneof_F_Int64: b.EncodeVarint(3<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.F_Int64)) case *Oneof_F_Fixed32: b.EncodeVarint(4<<3 | proto.WireFixed32) b.EncodeFixed32(uint64(x.F_Fixed32)) case *Oneof_F_Fixed64: b.EncodeVarint(5<<3 | proto.WireFixed64) b.EncodeFixed64(uint64(x.F_Fixed64)) case *Oneof_F_Uint32: b.EncodeVarint(6<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.F_Uint32)) case *Oneof_F_Uint64: b.EncodeVarint(7<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.F_Uint64)) case *Oneof_F_Float: b.EncodeVarint(8<<3 | proto.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.F_Float))) case *Oneof_F_Double: b.EncodeVarint(9<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.F_Double)) case *Oneof_F_String: b.EncodeVarint(10<<3 | proto.WireBytes) b.EncodeStringBytes(x.F_String) case *Oneof_F_Bytes: b.EncodeVarint(11<<3 | proto.WireBytes) b.EncodeRawBytes(x.F_Bytes) case *Oneof_F_Sint32: b.EncodeVarint(12<<3 | proto.WireVarint) b.EncodeZigzag32(uint64(x.F_Sint32)) case *Oneof_F_Sint64: b.EncodeVarint(13<<3 | proto.WireVarint) b.EncodeZigzag64(uint64(x.F_Sint64)) case *Oneof_F_Enum: b.EncodeVarint(14<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.F_Enum)) case *Oneof_F_Message: b.EncodeVarint(15<<3 | proto.WireBytes) if err := b.EncodeMessage(x.F_Message); err != nil { return err } case *Oneof_FGroup: b.EncodeVarint(16<<3 | proto.WireStartGroup) if err := b.Marshal(x.FGroup); err != nil { return err } b.EncodeVarint(16<<3 | proto.WireEndGroup) case *Oneof_F_Largest_Tag: b.EncodeVarint(536870911<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.F_Largest_Tag)) case nil: default: return fmt.Errorf("Oneof.Union has unexpected type %T", x) } // tormato switch x := m.Tormato.(type) { case *Oneof_Value: b.EncodeVarint(100<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Value)) case nil: default: return fmt.Errorf("Oneof.Tormato has unexpected type %T", x) } return nil } func _Oneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Oneof) switch tag { case 1: // union.F_Bool if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Bool{x != 0} return true, err case 2: // union.F_Int32 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Int32{int32(x)} return true, err case 3: // union.F_Int64 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Int64{int64(x)} return true, err case 4: // union.F_Fixed32 if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.Union = &Oneof_F_Fixed32{uint32(x)} return true, err case 5: // union.F_Fixed64 if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Union = &Oneof_F_Fixed64{x} return true, err case 6: // union.F_Uint32 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Uint32{uint32(x)} return true, err case 7: // union.F_Uint64 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Uint64{x} return true, err case 8: // union.F_Float if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.Union = &Oneof_F_Float{math.Float32frombits(uint32(x))} return true, err case 9: // union.F_Double if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Union = &Oneof_F_Double{math.Float64frombits(x)} return true, err case 10: // union.F_String if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &Oneof_F_String{x} return true, err case 11: // union.F_Bytes if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Union = &Oneof_F_Bytes{x} return true, err case 12: // union.F_Sint32 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag32() m.Union = &Oneof_F_Sint32{int32(x)} return true, err case 13: // union.F_Sint64 if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag64() m.Union = &Oneof_F_Sint64{int64(x)} return true, err case 14: // union.F_Enum if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Enum{MyMessage_Color(x)} return true, err case 15: // union.F_Message if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(GoTestField) err := b.DecodeMessage(msg) m.Union = &Oneof_F_Message{msg} return true, err case 16: // union.f_group if wire != proto.WireStartGroup { return true, proto.ErrInternalBadWireType } msg := new(Oneof_F_Group) err := b.DecodeGroup(msg) m.Union = &Oneof_FGroup{msg} return true, err case 536870911: // union.F_Largest_Tag if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Oneof_F_Largest_Tag{int32(x)} return true, err case 100: // tormato.value if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Tormato = &Oneof_Value{int32(x)} return true, err default: return false, nil } } func _Oneof_OneofSizer(msg proto.Message) (n int) { m := msg.(*Oneof) // union switch x := m.Union.(type) { case *Oneof_F_Bool: n += proto.SizeVarint(1<<3 | proto.WireVarint) n += 1 case *Oneof_F_Int32: n += proto.SizeVarint(2<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.F_Int32)) case *Oneof_F_Int64: n += proto.SizeVarint(3<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.F_Int64)) case *Oneof_F_Fixed32: n += proto.SizeVarint(4<<3 | proto.WireFixed32) n += 4 case *Oneof_F_Fixed64: n += proto.SizeVarint(5<<3 | proto.WireFixed64) n += 8 case *Oneof_F_Uint32: n += proto.SizeVarint(6<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.F_Uint32)) case *Oneof_F_Uint64: n += proto.SizeVarint(7<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.F_Uint64)) case *Oneof_F_Float: n += proto.SizeVarint(8<<3 | proto.WireFixed32) n += 4 case *Oneof_F_Double: n += proto.SizeVarint(9<<3 | proto.WireFixed64) n += 8 case *Oneof_F_String: n += proto.SizeVarint(10<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.F_String))) n += len(x.F_String) case *Oneof_F_Bytes: n += proto.SizeVarint(11<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.F_Bytes))) n += len(x.F_Bytes) case *Oneof_F_Sint32: n += proto.SizeVarint(12<<3 | proto.WireVarint) n += proto.SizeVarint(uint64((uint32(x.F_Sint32) << 1) ^ uint32((int32(x.F_Sint32) >> 31)))) case *Oneof_F_Sint64: n += proto.SizeVarint(13<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(uint64(x.F_Sint64<<1) ^ uint64((int64(x.F_Sint64) >> 63)))) case *Oneof_F_Enum: n += proto.SizeVarint(14<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.F_Enum)) case *Oneof_F_Message: s := proto.Size(x.F_Message) n += proto.SizeVarint(15<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Oneof_FGroup: n += proto.SizeVarint(16<<3 | proto.WireStartGroup) n += proto.Size(x.FGroup) n += proto.SizeVarint(16<<3 | proto.WireEndGroup) case *Oneof_F_Largest_Tag: n += proto.SizeVarint(536870911<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.F_Largest_Tag)) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } // tormato switch x := m.Tormato.(type) { case *Oneof_Value: n += proto.SizeVarint(100<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Value)) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type Oneof_F_Group struct { X *int32 `protobuf:"varint,17,opt,name=x" json:"x,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Oneof_F_Group) Reset() { *m = Oneof_F_Group{} } func (m *Oneof_F_Group) String() string { return proto.CompactTextString(m) } func (*Oneof_F_Group) ProtoMessage() {} func (*Oneof_F_Group) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{29, 0} } func (m *Oneof_F_Group) GetX() int32 { if m != nil && m.X != nil { return *m.X } return 0 } type Communique struct { MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"` // This is a oneof, called "union". // // Types that are valid to be assigned to Union: // *Communique_Number // *Communique_Name // *Communique_Data // *Communique_TempC // *Communique_Col // *Communique_Msg Union isCommunique_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *Communique) Reset() { *m = Communique{} } func (m *Communique) String() string { return proto.CompactTextString(m) } func (*Communique) ProtoMessage() {} func (*Communique) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{30} } type isCommunique_Union interface { isCommunique_Union() } type Communique_Number struct { Number int32 `protobuf:"varint,5,opt,name=number,oneof"` } type Communique_Name struct { Name string `protobuf:"bytes,6,opt,name=name,oneof"` } type Communique_Data struct { Data []byte `protobuf:"bytes,7,opt,name=data,oneof"` } type Communique_TempC struct { TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"` } type Communique_Col struct { Col MyMessage_Color `protobuf:"varint,9,opt,name=col,enum=testdata.MyMessage_Color,oneof"` } type Communique_Msg struct { Msg *Strings `protobuf:"bytes,10,opt,name=msg,oneof"` } func (*Communique_Number) isCommunique_Union() {} func (*Communique_Name) isCommunique_Union() {} func (*Communique_Data) isCommunique_Union() {} func (*Communique_TempC) isCommunique_Union() {} func (*Communique_Col) isCommunique_Union() {} func (*Communique_Msg) isCommunique_Union() {} func (m *Communique) GetUnion() isCommunique_Union { if m != nil { return m.Union } return nil } func (m *Communique) GetMakeMeCry() bool { if m != nil && m.MakeMeCry != nil { return *m.MakeMeCry } return false } func (m *Communique) GetNumber() int32 { if x, ok := m.GetUnion().(*Communique_Number); ok { return x.Number } return 0 } func (m *Communique) GetName() string { if x, ok := m.GetUnion().(*Communique_Name); ok { return x.Name } return "" } func (m *Communique) GetData() []byte { if x, ok := m.GetUnion().(*Communique_Data); ok { return x.Data } return nil } func (m *Communique) GetTempC() float64 { if x, ok := m.GetUnion().(*Communique_TempC); ok { return x.TempC } return 0 } func (m *Communique) GetCol() MyMessage_Color { if x, ok := m.GetUnion().(*Communique_Col); ok { return x.Col } return MyMessage_RED } func (m *Communique) GetMsg() *Strings { if x, ok := m.GetUnion().(*Communique_Msg); ok { return x.Msg } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{ (*Communique_Number)(nil), (*Communique_Name)(nil), (*Communique_Data)(nil), (*Communique_TempC)(nil), (*Communique_Col)(nil), (*Communique_Msg)(nil), } } func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: b.EncodeVarint(5<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Number)) case *Communique_Name: b.EncodeVarint(6<<3 | proto.WireBytes) b.EncodeStringBytes(x.Name) case *Communique_Data: b.EncodeVarint(7<<3 | proto.WireBytes) b.EncodeRawBytes(x.Data) case *Communique_TempC: b.EncodeVarint(8<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.TempC)) case *Communique_Col: b.EncodeVarint(9<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Col)) case *Communique_Msg: b.EncodeVarint(10<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Msg); err != nil { return err } case nil: default: return fmt.Errorf("Communique.Union has unexpected type %T", x) } return nil } func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Communique) switch tag { case 5: // union.number if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Number{int32(x)} return true, err case 6: // union.name if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &Communique_Name{x} return true, err case 7: // union.data if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Union = &Communique_Data{x} return true, err case 8: // union.temp_c if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Union = &Communique_TempC{math.Float64frombits(x)} return true, err case 9: // union.col if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Col{MyMessage_Color(x)} return true, err case 10: // union.msg if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Strings) err := b.DecodeMessage(msg) m.Union = &Communique_Msg{msg} return true, err default: return false, nil } } func _Communique_OneofSizer(msg proto.Message) (n int) { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: n += proto.SizeVarint(5<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Number)) case *Communique_Name: n += proto.SizeVarint(6<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Name))) n += len(x.Name) case *Communique_Data: n += proto.SizeVarint(7<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Data))) n += len(x.Data) case *Communique_TempC: n += proto.SizeVarint(8<<3 | proto.WireFixed64) n += 8 case *Communique_Col: n += proto.SizeVarint(9<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Col)) case *Communique_Msg: s := proto.Size(x.Msg) n += proto.SizeVarint(10<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } var E_Greeting = &proto.ExtensionDesc{ ExtendedType: (*MyMessage)(nil), ExtensionType: ([]string)(nil), Field: 106, Name: "testdata.greeting", Tag: "bytes,106,rep,name=greeting", Filename: "test.proto", } var E_Complex = &proto.ExtensionDesc{ ExtendedType: (*OtherMessage)(nil), ExtensionType: (*ComplexExtension)(nil), Field: 200, Name: "testdata.complex", Tag: "bytes,200,opt,name=complex", Filename: "test.proto", } var E_RComplex = &proto.ExtensionDesc{ ExtendedType: (*OtherMessage)(nil), ExtensionType: ([]*ComplexExtension)(nil), Field: 201, Name: "testdata.r_complex", Tag: "bytes,201,rep,name=r_complex,json=rComplex", Filename: "test.proto", } var E_NoDefaultDouble = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*float64)(nil), Field: 101, Name: "testdata.no_default_double", Tag: "fixed64,101,opt,name=no_default_double,json=noDefaultDouble", Filename: "test.proto", } var E_NoDefaultFloat = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*float32)(nil), Field: 102, Name: "testdata.no_default_float", Tag: "fixed32,102,opt,name=no_default_float,json=noDefaultFloat", Filename: "test.proto", } var E_NoDefaultInt32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int32)(nil), Field: 103, Name: "testdata.no_default_int32", Tag: "varint,103,opt,name=no_default_int32,json=noDefaultInt32", Filename: "test.proto", } var E_NoDefaultInt64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int64)(nil), Field: 104, Name: "testdata.no_default_int64", Tag: "varint,104,opt,name=no_default_int64,json=noDefaultInt64", Filename: "test.proto", } var E_NoDefaultUint32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint32)(nil), Field: 105, Name: "testdata.no_default_uint32", Tag: "varint,105,opt,name=no_default_uint32,json=noDefaultUint32", Filename: "test.proto", } var E_NoDefaultUint64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint64)(nil), Field: 106, Name: "testdata.no_default_uint64", Tag: "varint,106,opt,name=no_default_uint64,json=noDefaultUint64", Filename: "test.proto", } var E_NoDefaultSint32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int32)(nil), Field: 107, Name: "testdata.no_default_sint32", Tag: "zigzag32,107,opt,name=no_default_sint32,json=noDefaultSint32", Filename: "test.proto", } var E_NoDefaultSint64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int64)(nil), Field: 108, Name: "testdata.no_default_sint64", Tag: "zigzag64,108,opt,name=no_default_sint64,json=noDefaultSint64", Filename: "test.proto", } var E_NoDefaultFixed32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint32)(nil), Field: 109, Name: "testdata.no_default_fixed32", Tag: "fixed32,109,opt,name=no_default_fixed32,json=noDefaultFixed32", Filename: "test.proto", } var E_NoDefaultFixed64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint64)(nil), Field: 110, Name: "testdata.no_default_fixed64", Tag: "fixed64,110,opt,name=no_default_fixed64,json=noDefaultFixed64", Filename: "test.proto", } var E_NoDefaultSfixed32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int32)(nil), Field: 111, Name: "testdata.no_default_sfixed32", Tag: "fixed32,111,opt,name=no_default_sfixed32,json=noDefaultSfixed32", Filename: "test.proto", } var E_NoDefaultSfixed64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int64)(nil), Field: 112, Name: "testdata.no_default_sfixed64", Tag: "fixed64,112,opt,name=no_default_sfixed64,json=noDefaultSfixed64", Filename: "test.proto", } var E_NoDefaultBool = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*bool)(nil), Field: 113, Name: "testdata.no_default_bool", Tag: "varint,113,opt,name=no_default_bool,json=noDefaultBool", Filename: "test.proto", } var E_NoDefaultString = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*string)(nil), Field: 114, Name: "testdata.no_default_string", Tag: "bytes,114,opt,name=no_default_string,json=noDefaultString", Filename: "test.proto", } var E_NoDefaultBytes = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: ([]byte)(nil), Field: 115, Name: "testdata.no_default_bytes", Tag: "bytes,115,opt,name=no_default_bytes,json=noDefaultBytes", Filename: "test.proto", } var E_NoDefaultEnum = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), Field: 116, Name: "testdata.no_default_enum", Tag: "varint,116,opt,name=no_default_enum,json=noDefaultEnum,enum=testdata.DefaultsMessage_DefaultsEnum", Filename: "test.proto", } var E_DefaultDouble = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*float64)(nil), Field: 201, Name: "testdata.default_double", Tag: "fixed64,201,opt,name=default_double,json=defaultDouble,def=3.1415", Filename: "test.proto", } var E_DefaultFloat = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*float32)(nil), Field: 202, Name: "testdata.default_float", Tag: "fixed32,202,opt,name=default_float,json=defaultFloat,def=3.14", Filename: "test.proto", } var E_DefaultInt32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int32)(nil), Field: 203, Name: "testdata.default_int32", Tag: "varint,203,opt,name=default_int32,json=defaultInt32,def=42", Filename: "test.proto", } var E_DefaultInt64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int64)(nil), Field: 204, Name: "testdata.default_int64", Tag: "varint,204,opt,name=default_int64,json=defaultInt64,def=43", Filename: "test.proto", } var E_DefaultUint32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint32)(nil), Field: 205, Name: "testdata.default_uint32", Tag: "varint,205,opt,name=default_uint32,json=defaultUint32,def=44", Filename: "test.proto", } var E_DefaultUint64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint64)(nil), Field: 206, Name: "testdata.default_uint64", Tag: "varint,206,opt,name=default_uint64,json=defaultUint64,def=45", Filename: "test.proto", } var E_DefaultSint32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int32)(nil), Field: 207, Name: "testdata.default_sint32", Tag: "zigzag32,207,opt,name=default_sint32,json=defaultSint32,def=46", Filename: "test.proto", } var E_DefaultSint64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int64)(nil), Field: 208, Name: "testdata.default_sint64", Tag: "zigzag64,208,opt,name=default_sint64,json=defaultSint64,def=47", Filename: "test.proto", } var E_DefaultFixed32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint32)(nil), Field: 209, Name: "testdata.default_fixed32", Tag: "fixed32,209,opt,name=default_fixed32,json=defaultFixed32,def=48", Filename: "test.proto", } var E_DefaultFixed64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*uint64)(nil), Field: 210, Name: "testdata.default_fixed64", Tag: "fixed64,210,opt,name=default_fixed64,json=defaultFixed64,def=49", Filename: "test.proto", } var E_DefaultSfixed32 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int32)(nil), Field: 211, Name: "testdata.default_sfixed32", Tag: "fixed32,211,opt,name=default_sfixed32,json=defaultSfixed32,def=50", Filename: "test.proto", } var E_DefaultSfixed64 = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*int64)(nil), Field: 212, Name: "testdata.default_sfixed64", Tag: "fixed64,212,opt,name=default_sfixed64,json=defaultSfixed64,def=51", Filename: "test.proto", } var E_DefaultBool = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*bool)(nil), Field: 213, Name: "testdata.default_bool", Tag: "varint,213,opt,name=default_bool,json=defaultBool,def=1", Filename: "test.proto", } var E_DefaultString = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*string)(nil), Field: 214, Name: "testdata.default_string", Tag: "bytes,214,opt,name=default_string,json=defaultString,def=Hello, string", Filename: "test.proto", } var E_DefaultBytes = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: ([]byte)(nil), Field: 215, Name: "testdata.default_bytes", Tag: "bytes,215,opt,name=default_bytes,json=defaultBytes,def=Hello, bytes", Filename: "test.proto", } var E_DefaultEnum = &proto.ExtensionDesc{ ExtendedType: (*DefaultsMessage)(nil), ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil), Field: 216, Name: "testdata.default_enum", Tag: "varint,216,opt,name=default_enum,json=defaultEnum,enum=testdata.DefaultsMessage_DefaultsEnum,def=1", Filename: "test.proto", } var E_X201 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 201, Name: "testdata.x201", Tag: "bytes,201,opt,name=x201", Filename: "test.proto", } var E_X202 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 202, Name: "testdata.x202", Tag: "bytes,202,opt,name=x202", Filename: "test.proto", } var E_X203 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 203, Name: "testdata.x203", Tag: "bytes,203,opt,name=x203", Filename: "test.proto", } var E_X204 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 204, Name: "testdata.x204", Tag: "bytes,204,opt,name=x204", Filename: "test.proto", } var E_X205 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 205, Name: "testdata.x205", Tag: "bytes,205,opt,name=x205", Filename: "test.proto", } var E_X206 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 206, Name: "testdata.x206", Tag: "bytes,206,opt,name=x206", Filename: "test.proto", } var E_X207 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 207, Name: "testdata.x207", Tag: "bytes,207,opt,name=x207", Filename: "test.proto", } var E_X208 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 208, Name: "testdata.x208", Tag: "bytes,208,opt,name=x208", Filename: "test.proto", } var E_X209 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 209, Name: "testdata.x209", Tag: "bytes,209,opt,name=x209", Filename: "test.proto", } var E_X210 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 210, Name: "testdata.x210", Tag: "bytes,210,opt,name=x210", Filename: "test.proto", } var E_X211 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 211, Name: "testdata.x211", Tag: "bytes,211,opt,name=x211", Filename: "test.proto", } var E_X212 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 212, Name: "testdata.x212", Tag: "bytes,212,opt,name=x212", Filename: "test.proto", } var E_X213 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 213, Name: "testdata.x213", Tag: "bytes,213,opt,name=x213", Filename: "test.proto", } var E_X214 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 214, Name: "testdata.x214", Tag: "bytes,214,opt,name=x214", Filename: "test.proto", } var E_X215 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 215, Name: "testdata.x215", Tag: "bytes,215,opt,name=x215", Filename: "test.proto", } var E_X216 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 216, Name: "testdata.x216", Tag: "bytes,216,opt,name=x216", Filename: "test.proto", } var E_X217 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 217, Name: "testdata.x217", Tag: "bytes,217,opt,name=x217", Filename: "test.proto", } var E_X218 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 218, Name: "testdata.x218", Tag: "bytes,218,opt,name=x218", Filename: "test.proto", } var E_X219 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 219, Name: "testdata.x219", Tag: "bytes,219,opt,name=x219", Filename: "test.proto", } var E_X220 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 220, Name: "testdata.x220", Tag: "bytes,220,opt,name=x220", Filename: "test.proto", } var E_X221 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 221, Name: "testdata.x221", Tag: "bytes,221,opt,name=x221", Filename: "test.proto", } var E_X222 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 222, Name: "testdata.x222", Tag: "bytes,222,opt,name=x222", Filename: "test.proto", } var E_X223 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 223, Name: "testdata.x223", Tag: "bytes,223,opt,name=x223", Filename: "test.proto", } var E_X224 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 224, Name: "testdata.x224", Tag: "bytes,224,opt,name=x224", Filename: "test.proto", } var E_X225 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 225, Name: "testdata.x225", Tag: "bytes,225,opt,name=x225", Filename: "test.proto", } var E_X226 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 226, Name: "testdata.x226", Tag: "bytes,226,opt,name=x226", Filename: "test.proto", } var E_X227 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 227, Name: "testdata.x227", Tag: "bytes,227,opt,name=x227", Filename: "test.proto", } var E_X228 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 228, Name: "testdata.x228", Tag: "bytes,228,opt,name=x228", Filename: "test.proto", } var E_X229 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 229, Name: "testdata.x229", Tag: "bytes,229,opt,name=x229", Filename: "test.proto", } var E_X230 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 230, Name: "testdata.x230", Tag: "bytes,230,opt,name=x230", Filename: "test.proto", } var E_X231 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 231, Name: "testdata.x231", Tag: "bytes,231,opt,name=x231", Filename: "test.proto", } var E_X232 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 232, Name: "testdata.x232", Tag: "bytes,232,opt,name=x232", Filename: "test.proto", } var E_X233 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 233, Name: "testdata.x233", Tag: "bytes,233,opt,name=x233", Filename: "test.proto", } var E_X234 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 234, Name: "testdata.x234", Tag: "bytes,234,opt,name=x234", Filename: "test.proto", } var E_X235 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 235, Name: "testdata.x235", Tag: "bytes,235,opt,name=x235", Filename: "test.proto", } var E_X236 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 236, Name: "testdata.x236", Tag: "bytes,236,opt,name=x236", Filename: "test.proto", } var E_X237 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 237, Name: "testdata.x237", Tag: "bytes,237,opt,name=x237", Filename: "test.proto", } var E_X238 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 238, Name: "testdata.x238", Tag: "bytes,238,opt,name=x238", Filename: "test.proto", } var E_X239 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 239, Name: "testdata.x239", Tag: "bytes,239,opt,name=x239", Filename: "test.proto", } var E_X240 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 240, Name: "testdata.x240", Tag: "bytes,240,opt,name=x240", Filename: "test.proto", } var E_X241 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 241, Name: "testdata.x241", Tag: "bytes,241,opt,name=x241", Filename: "test.proto", } var E_X242 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 242, Name: "testdata.x242", Tag: "bytes,242,opt,name=x242", Filename: "test.proto", } var E_X243 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 243, Name: "testdata.x243", Tag: "bytes,243,opt,name=x243", Filename: "test.proto", } var E_X244 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 244, Name: "testdata.x244", Tag: "bytes,244,opt,name=x244", Filename: "test.proto", } var E_X245 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 245, Name: "testdata.x245", Tag: "bytes,245,opt,name=x245", Filename: "test.proto", } var E_X246 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 246, Name: "testdata.x246", Tag: "bytes,246,opt,name=x246", Filename: "test.proto", } var E_X247 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 247, Name: "testdata.x247", Tag: "bytes,247,opt,name=x247", Filename: "test.proto", } var E_X248 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 248, Name: "testdata.x248", Tag: "bytes,248,opt,name=x248", Filename: "test.proto", } var E_X249 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 249, Name: "testdata.x249", Tag: "bytes,249,opt,name=x249", Filename: "test.proto", } var E_X250 = &proto.ExtensionDesc{ ExtendedType: (*MyMessageSet)(nil), ExtensionType: (*Empty)(nil), Field: 250, Name: "testdata.x250", Tag: "bytes,250,opt,name=x250", Filename: "test.proto", } func init() { proto.RegisterType((*GoEnum)(nil), "testdata.GoEnum") proto.RegisterType((*GoTestField)(nil), "testdata.GoTestField") proto.RegisterType((*GoTest)(nil), "testdata.GoTest") proto.RegisterType((*GoTest_RequiredGroup)(nil), "testdata.GoTest.RequiredGroup") proto.RegisterType((*GoTest_RepeatedGroup)(nil), "testdata.GoTest.RepeatedGroup") proto.RegisterType((*GoTest_OptionalGroup)(nil), "testdata.GoTest.OptionalGroup") proto.RegisterType((*GoTestRequiredGroupField)(nil), "testdata.GoTestRequiredGroupField") proto.RegisterType((*GoTestRequiredGroupField_Group)(nil), "testdata.GoTestRequiredGroupField.Group") proto.RegisterType((*GoSkipTest)(nil), "testdata.GoSkipTest") proto.RegisterType((*GoSkipTest_SkipGroup)(nil), "testdata.GoSkipTest.SkipGroup") proto.RegisterType((*NonPackedTest)(nil), "testdata.NonPackedTest") proto.RegisterType((*PackedTest)(nil), "testdata.PackedTest") proto.RegisterType((*MaxTag)(nil), "testdata.MaxTag") proto.RegisterType((*OldMessage)(nil), "testdata.OldMessage") proto.RegisterType((*OldMessage_Nested)(nil), "testdata.OldMessage.Nested") proto.RegisterType((*NewMessage)(nil), "testdata.NewMessage") proto.RegisterType((*NewMessage_Nested)(nil), "testdata.NewMessage.Nested") proto.RegisterType((*InnerMessage)(nil), "testdata.InnerMessage") proto.RegisterType((*OtherMessage)(nil), "testdata.OtherMessage") proto.RegisterType((*RequiredInnerMessage)(nil), "testdata.RequiredInnerMessage") proto.RegisterType((*MyMessage)(nil), "testdata.MyMessage") proto.RegisterType((*MyMessage_SomeGroup)(nil), "testdata.MyMessage.SomeGroup") proto.RegisterType((*Ext)(nil), "testdata.Ext") proto.RegisterType((*ComplexExtension)(nil), "testdata.ComplexExtension") proto.RegisterType((*DefaultsMessage)(nil), "testdata.DefaultsMessage") proto.RegisterType((*MyMessageSet)(nil), "testdata.MyMessageSet") proto.RegisterType((*Empty)(nil), "testdata.Empty") proto.RegisterType((*MessageList)(nil), "testdata.MessageList") proto.RegisterType((*MessageList_Message)(nil), "testdata.MessageList.Message") proto.RegisterType((*Strings)(nil), "testdata.Strings") proto.RegisterType((*Defaults)(nil), "testdata.Defaults") proto.RegisterType((*SubDefaults)(nil), "testdata.SubDefaults") proto.RegisterType((*RepeatedEnum)(nil), "testdata.RepeatedEnum") proto.RegisterType((*MoreRepeated)(nil), "testdata.MoreRepeated") proto.RegisterType((*GroupOld)(nil), "testdata.GroupOld") proto.RegisterType((*GroupOld_G)(nil), "testdata.GroupOld.G") proto.RegisterType((*GroupNew)(nil), "testdata.GroupNew") proto.RegisterType((*GroupNew_G)(nil), "testdata.GroupNew.G") proto.RegisterType((*FloatingPoint)(nil), "testdata.FloatingPoint") proto.RegisterType((*MessageWithMap)(nil), "testdata.MessageWithMap") proto.RegisterType((*Oneof)(nil), "testdata.Oneof") proto.RegisterType((*Oneof_F_Group)(nil), "testdata.Oneof.F_Group") proto.RegisterType((*Communique)(nil), "testdata.Communique") proto.RegisterEnum("testdata.FOO", FOO_name, FOO_value) proto.RegisterEnum("testdata.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value) proto.RegisterEnum("testdata.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value) proto.RegisterEnum("testdata.DefaultsMessage_DefaultsEnum", DefaultsMessage_DefaultsEnum_name, DefaultsMessage_DefaultsEnum_value) proto.RegisterEnum("testdata.Defaults_Color", Defaults_Color_name, Defaults_Color_value) proto.RegisterEnum("testdata.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value) proto.RegisterExtension(E_Ext_More) proto.RegisterExtension(E_Ext_Text) proto.RegisterExtension(E_Ext_Number) proto.RegisterExtension(E_Greeting) proto.RegisterExtension(E_Complex) proto.RegisterExtension(E_RComplex) proto.RegisterExtension(E_NoDefaultDouble) proto.RegisterExtension(E_NoDefaultFloat) proto.RegisterExtension(E_NoDefaultInt32) proto.RegisterExtension(E_NoDefaultInt64) proto.RegisterExtension(E_NoDefaultUint32) proto.RegisterExtension(E_NoDefaultUint64) proto.RegisterExtension(E_NoDefaultSint32) proto.RegisterExtension(E_NoDefaultSint64) proto.RegisterExtension(E_NoDefaultFixed32) proto.RegisterExtension(E_NoDefaultFixed64) proto.RegisterExtension(E_NoDefaultSfixed32) proto.RegisterExtension(E_NoDefaultSfixed64) proto.RegisterExtension(E_NoDefaultBool) proto.RegisterExtension(E_NoDefaultString) proto.RegisterExtension(E_NoDefaultBytes) proto.RegisterExtension(E_NoDefaultEnum) proto.RegisterExtension(E_DefaultDouble) proto.RegisterExtension(E_DefaultFloat) proto.RegisterExtension(E_DefaultInt32) proto.RegisterExtension(E_DefaultInt64) proto.RegisterExtension(E_DefaultUint32) proto.RegisterExtension(E_DefaultUint64) proto.RegisterExtension(E_DefaultSint32) proto.RegisterExtension(E_DefaultSint64) proto.RegisterExtension(E_DefaultFixed32) proto.RegisterExtension(E_DefaultFixed64) proto.RegisterExtension(E_DefaultSfixed32) proto.RegisterExtension(E_DefaultSfixed64) proto.RegisterExtension(E_DefaultBool) proto.RegisterExtension(E_DefaultString) proto.RegisterExtension(E_DefaultBytes) proto.RegisterExtension(E_DefaultEnum) proto.RegisterExtension(E_X201) proto.RegisterExtension(E_X202) proto.RegisterExtension(E_X203) proto.RegisterExtension(E_X204) proto.RegisterExtension(E_X205) proto.RegisterExtension(E_X206) proto.RegisterExtension(E_X207) proto.RegisterExtension(E_X208) proto.RegisterExtension(E_X209) proto.RegisterExtension(E_X210) proto.RegisterExtension(E_X211) proto.RegisterExtension(E_X212) proto.RegisterExtension(E_X213) proto.RegisterExtension(E_X214) proto.RegisterExtension(E_X215) proto.RegisterExtension(E_X216) proto.RegisterExtension(E_X217) proto.RegisterExtension(E_X218) proto.RegisterExtension(E_X219) proto.RegisterExtension(E_X220) proto.RegisterExtension(E_X221) proto.RegisterExtension(E_X222) proto.RegisterExtension(E_X223) proto.RegisterExtension(E_X224) proto.RegisterExtension(E_X225) proto.RegisterExtension(E_X226) proto.RegisterExtension(E_X227) proto.RegisterExtension(E_X228) proto.RegisterExtension(E_X229) proto.RegisterExtension(E_X230) proto.RegisterExtension(E_X231) proto.RegisterExtension(E_X232) proto.RegisterExtension(E_X233) proto.RegisterExtension(E_X234) proto.RegisterExtension(E_X235) proto.RegisterExtension(E_X236) proto.RegisterExtension(E_X237) proto.RegisterExtension(E_X238) proto.RegisterExtension(E_X239) proto.RegisterExtension(E_X240) proto.RegisterExtension(E_X241) proto.RegisterExtension(E_X242) proto.RegisterExtension(E_X243) proto.RegisterExtension(E_X244) proto.RegisterExtension(E_X245) proto.RegisterExtension(E_X246) proto.RegisterExtension(E_X247) proto.RegisterExtension(E_X248) proto.RegisterExtension(E_X249) proto.RegisterExtension(E_X250) } func init() { proto.RegisterFile("test.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 4453 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x5a, 0xc9, 0x77, 0xdb, 0x48, 0x7a, 0x37, 0xc0, 0xfd, 0x23, 0x25, 0x42, 0x65, 0xb5, 0x9b, 0x96, 0xbc, 0xc0, 0x9c, 0xe9, 0x6e, 0x7a, 0xd3, 0x48, 0x20, 0x44, 0xdb, 0x74, 0xa7, 0xdf, 0xf3, 0x42, 0xca, 0x7a, 0x63, 0x89, 0x0a, 0xa4, 0xee, 0x7e, 0xd3, 0x39, 0xf0, 0x51, 0x22, 0x44, 0xb3, 0x4d, 0x02, 0x34, 0x09, 0xc5, 0x52, 0x72, 0xe9, 0x4b, 0x72, 0xcd, 0x76, 0xc9, 0x35, 0xa7, 0x9c, 0x92, 0xbc, 0x97, 0x7f, 0x22, 0xe9, 0xee, 0x59, 0x7b, 0xd6, 0xac, 0x93, 0x7d, 0x99, 0xec, 0xdb, 0x4c, 0x92, 0x4b, 0xcf, 0xab, 0xaf, 0x0a, 0x40, 0x01, 0x24, 0x20, 0xf9, 0x24, 0x56, 0xd5, 0xef, 0xf7, 0xd5, 0xf6, 0xab, 0xef, 0xab, 0xaf, 0x20, 0x00, 0xc7, 0x9c, 0x38, 0x2b, 0xa3, 0xb1, 0xed, 0xd8, 0x24, 0x4b, 0x7f, 0x77, 0x3b, 0x4e, 0xa7, 0x7c, 0x1d, 0xd2, 0x1b, 0x76, 0xc3, 0x3a, 0x1a, 0x92, 0xab, 0x90, 0x38, 0xb4, 0xed, 0x92, 0xa4, 0xca, 0x95, 0x79, 0x6d, 0x6e, 0xc5, 0x45, 0xac, 0x34, 0x5b, 0x2d, 0x83, 0xb6, 0x94, 0xef, 0x40, 0x7e, 0xc3, 0xde, 0x33, 0x27, 0x4e, 0xb3, 0x6f, 0x0e, 0xba, 0x64, 0x11, 0x52, 0x4f, 0x3b, 0xfb, 0xe6, 0x00, 0x19, 0x39, 0x83, 0x15, 0x08, 0x81, 0xe4, 0xde, 0xc9, 0xc8, 0x2c, 0xc9, 0x58, 0x89, 0xbf, 0xcb, 0xbf, 0x72, 0x85, 0x76, 0x42, 0x99, 0xe4, 0x3a, 0x24, 0xbf, 0xdc, 0xb7, 0xba, 0xbc, 0x97, 0xd7, 0xfc, 0x5e, 0x58, 0xfb, 0xca, 0x97, 0x37, 0xb7, 0x1f, 0x1b, 0x08, 0xa1, 0xf6, 0xf7, 0x3a, 0xfb, 0x03, 0x6a, 0x4a, 0xa2, 0xf6, 0xb1, 0x40, 0x6b, 0x77, 0x3a, 0xe3, 0xce, 0xb0, 0x94, 0x50, 0xa5, 0x4a, 0xca, 0x60, 0x05, 0x72, 0x1f, 0xe6, 0x0c, 0xf3, 0xc5, 0x51, 0x7f, 0x6c, 0x76, 0x71, 0x70, 0xa5, 0xa4, 0x2a, 0x57, 0xf2, 0xd3, 0xf6, 0xb1, 0xd1, 0x08, 0x62, 0x19, 0x79, 0x64, 0x76, 0x1c, 0x97, 0x9c, 0x52, 0x13, 0xb1, 0x64, 0x01, 0x4b, 0xc9, 0xad, 0x91, 0xd3, 0xb7, 0xad, 0xce, 0x80, 0x91, 0xd3, 0xaa, 0x14, 0x43, 0x0e, 0x60, 0xc9, 0x9b, 0x50, 0x6c, 0xb6, 0x1f, 0xda, 0xf6, 0xa0, 0x3d, 0xe6, 0x23, 0x2a, 0x81, 0x2a, 0x57, 0xb2, 0xc6, 0x5c, 0x93, 0xd6, 0xba, 0xc3, 0x24, 0x15, 0x50, 0x9a, 0xed, 0x4d, 0xcb, 0xa9, 0x6a, 0x3e, 0x30, 0xaf, 0xca, 0x95, 0x94, 0x31, 0xdf, 0xc4, 0xea, 0x29, 0x64, 0x4d, 0xf7, 0x91, 0x05, 0x55, 0xae, 0x24, 0x18, 0xb2, 0xa6, 0x7b, 0xc8, 0x5b, 0x40, 0x9a, 0xed, 0x66, 0xff, 0xd8, 0xec, 0x8a, 0x56, 0xe7, 0x54, 0xb9, 0x92, 0x31, 0x94, 0x26, 0x6f, 0x98, 0x81, 0x16, 0x2d, 0xcf, 0xab, 0x72, 0x25, 0xed, 0xa2, 0x05, 0xdb, 0x37, 0x60, 0xa1, 0xd9, 0x7e, 0xb7, 0x1f, 0x1c, 0x70, 0x51, 0x95, 0x2b, 0x73, 0x46, 0xb1, 0xc9, 0xea, 0xa7, 0xb1, 0xa2, 0x61, 0x45, 0x95, 0x2b, 0x49, 0x8e, 0x15, 0xec, 0xe2, 0xec, 0x9a, 0x03, 0xbb, 0xe3, 0xf8, 0xd0, 0x05, 0x55, 0xae, 0xc8, 0xc6, 0x7c, 0x13, 0xab, 0x83, 0x56, 0x1f, 0xdb, 0x47, 0xfb, 0x03, 0xd3, 0x87, 0x12, 0x55, 0xae, 0x48, 0x46, 0xb1, 0xc9, 0xea, 0x83, 0xd8, 0x5d, 0x67, 0xdc, 0xb7, 0x7a, 0x3e, 0xf6, 0x3c, 0xea, 0xb7, 0xd8, 0x64, 0xf5, 0xc1, 0x11, 0x3c, 0x3c, 0x71, 0xcc, 0x89, 0x0f, 0x35, 0x55, 0xb9, 0x52, 0x30, 0xe6, 0x9b, 0x58, 0x1d, 0xb2, 0x1a, 0x5a, 0x83, 0x43, 0x55, 0xae, 0x2c, 0x50, 0xab, 0x33, 0xd6, 0x60, 0x37, 0xb4, 0x06, 0x3d, 0x55, 0xae, 0x10, 0x8e, 0x15, 0xd6, 0x40, 0xd4, 0x0c, 0x13, 0x62, 0x69, 0x51, 0x4d, 0x08, 0x9a, 0x61, 0x95, 0x41, 0xcd, 0x70, 0xe0, 0x6b, 0x6a, 0x42, 0xd4, 0x4c, 0x08, 0x89, 0x9d, 0x73, 0xe4, 0x05, 0x35, 0x21, 0x6a, 0x86, 0x23, 0x43, 0x9a, 0xe1, 0xd8, 0xd7, 0xd5, 0x44, 0x50, 0x33, 0x53, 0x68, 0xd1, 0x72, 0x49, 0x4d, 0x04, 0x35, 0xc3, 0xd1, 0x41, 0xcd, 0x70, 0xf0, 0x45, 0x35, 0x11, 0xd0, 0x4c, 0x18, 0x2b, 0x1a, 0x5e, 0x52, 0x13, 0x01, 0xcd, 0x88, 0xb3, 0x73, 0x35, 0xc3, 0xa1, 0xcb, 0x6a, 0x42, 0xd4, 0x8c, 0x68, 0xd5, 0xd3, 0x0c, 0x87, 0x5e, 0x52, 0x13, 0x01, 0xcd, 0x88, 0x58, 0x4f, 0x33, 0x1c, 0x7b, 0x59, 0x4d, 0x04, 0x34, 0xc3, 0xb1, 0xd7, 0x45, 0xcd, 0x70, 0xe8, 0xc7, 0x92, 0x9a, 0x10, 0x45, 0xc3, 0xa1, 0x37, 0x03, 0xa2, 0xe1, 0xd8, 0x4f, 0x28, 0x56, 0x54, 0x4d, 0x18, 0x2c, 0xae, 0xc2, 0xa7, 0x14, 0x2c, 0xca, 0x86, 0x83, 0x7d, 0xd9, 0xd8, 0xdc, 0x05, 0x95, 0xae, 0xa8, 0x92, 0x27, 0x1b, 0xd7, 0x2f, 0x89, 0xb2, 0xf1, 0x80, 0x57, 0xd1, 0xd5, 0x72, 0xd9, 0x4c, 0x21, 0x6b, 0xba, 0x8f, 0x54, 0x55, 0xc9, 0x97, 0x8d, 0x87, 0x0c, 0xc8, 0xc6, 0xc3, 0x5e, 0x53, 0x25, 0x51, 0x36, 0x33, 0xd0, 0xa2, 0xe5, 0xb2, 0x2a, 0x89, 0xb2, 0xf1, 0xd0, 0xa2, 0x6c, 0x3c, 0xf0, 0x17, 0x54, 0x49, 0x90, 0xcd, 0x34, 0x56, 0x34, 0xfc, 0x45, 0x55, 0x12, 0x64, 0x13, 0x9c, 0x1d, 0x93, 0x8d, 0x07, 0x7d, 0x43, 0x95, 0x7c, 0xd9, 0x04, 0xad, 0x72, 0xd9, 0x78, 0xd0, 0x37, 0x55, 0x49, 0x90, 0x4d, 0x10, 0xcb, 0x65, 0xe3, 0x61, 0xdf, 0xc2, 0xf8, 0xe6, 0xca, 0xc6, 0xc3, 0x0a, 0xb2, 0xf1, 0xa0, 0xbf, 0x43, 0x63, 0xa1, 0x27, 0x1b, 0x0f, 0x2a, 0xca, 0xc6, 0xc3, 0xfe, 0x2e, 0xc5, 0xfa, 0xb2, 0x99, 0x06, 0x8b, 0xab, 0xf0, 0x7b, 0x14, 0xec, 0xcb, 0xc6, 0x03, 0xaf, 0xe0, 0x20, 0xa8, 0x6c, 0xba, 0xe6, 0x61, 0xe7, 0x68, 0x40, 0x25, 0x56, 0xa1, 0xba, 0xa9, 0x27, 0x9d, 0xf1, 0x91, 0x49, 0x47, 0x62, 0xdb, 0x83, 0xc7, 0x6e, 0x1b, 0x59, 0xa1, 0xc6, 0x99, 0x7c, 0x7c, 0xc2, 0x75, 0xaa, 0x9f, 0xba, 0x5c, 0xd5, 0x8c, 0x22, 0xd3, 0xd0, 0x34, 0xbe, 0xa6, 0x0b, 0xf8, 0x1b, 0x54, 0x45, 0x75, 0xb9, 0xa6, 0x33, 0x7c, 0x4d, 0xf7, 0xf1, 0x55, 0x38, 0xef, 0x4b, 0xc9, 0x67, 0xdc, 0xa4, 0x5a, 0xaa, 0x27, 0xaa, 0xda, 0xaa, 0xb1, 0xe0, 0x0a, 0x6a, 0x16, 0x29, 0xd0, 0xcd, 0x2d, 0x2a, 0xa9, 0x7a, 0xa2, 0xa6, 0x7b, 0x24, 0xb1, 0x27, 0x8d, 0xca, 0x90, 0x0b, 0xcb, 0xe7, 0xdc, 0xa6, 0xca, 0xaa, 0x27, 0xab, 0xda, 0xea, 0xaa, 0xa1, 0x70, 0x7d, 0xcd, 0xe0, 0x04, 0xfa, 0x59, 0xa1, 0x0a, 0xab, 0x27, 0x6b, 0xba, 0xc7, 0x09, 0xf6, 0xb3, 0xe0, 0x0a, 0xcd, 0xa7, 0x7c, 0x89, 0x2a, 0xad, 0x9e, 0xae, 0xae, 0xe9, 0x6b, 0xeb, 0xf7, 0x8c, 0x22, 0x53, 0x9c, 0xcf, 0xd1, 0x69, 0x3f, 0x5c, 0x72, 0x3e, 0x69, 0x95, 0x6a, 0xae, 0x9e, 0xd6, 0xee, 0xac, 0xdd, 0xd5, 0xee, 0x1a, 0x0a, 0xd7, 0x9e, 0xcf, 0x7a, 0x87, 0xb2, 0xb8, 0xf8, 0x7c, 0xd6, 0x1a, 0x55, 0x5f, 0x5d, 0x79, 0x66, 0x0e, 0x06, 0xf6, 0x2d, 0xb5, 0xfc, 0xd2, 0x1e, 0x0f, 0xba, 0xd7, 0xca, 0x60, 0x28, 0x5c, 0x8f, 0x62, 0xaf, 0x0b, 0xae, 0x20, 0x7d, 0xfa, 0xaf, 0xd1, 0x7b, 0x58, 0xa1, 0x9e, 0x79, 0xd8, 0xef, 0x59, 0xf6, 0xc4, 0x34, 0x8a, 0x4c, 0x9a, 0xa1, 0x35, 0xd9, 0x0d, 0xaf, 0xe3, 0xaf, 0x53, 0xda, 0x42, 0x3d, 0x71, 0xbb, 0xaa, 0xd1, 0x9e, 0x66, 0xad, 0xe3, 0x6e, 0x78, 0x1d, 0x7f, 0x83, 0x72, 0x48, 0x3d, 0x71, 0xbb, 0xa6, 0x73, 0x8e, 0xb8, 0x8e, 0x77, 0xe0, 0x42, 0x28, 0x2e, 0xb6, 0x47, 0x9d, 0x83, 0xe7, 0x66, 0xb7, 0xa4, 0xd1, 0xf0, 0xf8, 0x50, 0x56, 0x24, 0xe3, 0x7c, 0x20, 0x44, 0xee, 0x60, 0x33, 0xb9, 0x07, 0xaf, 0x87, 0x03, 0xa5, 0xcb, 0xac, 0xd2, 0x78, 0x89, 0xcc, 0xc5, 0x60, 0xcc, 0x0c, 0x51, 0x05, 0x07, 0xec, 0x52, 0x75, 0x1a, 0x40, 0x7d, 0xaa, 0xef, 0x89, 0x39, 0xf5, 0x67, 0xe0, 0xe2, 0x74, 0x28, 0x75, 0xc9, 0xeb, 0x34, 0xa2, 0x22, 0xf9, 0x42, 0x38, 0xaa, 0x4e, 0xd1, 0x67, 0xf4, 0x5d, 0xa3, 0x21, 0x56, 0xa4, 0x4f, 0xf5, 0x7e, 0x1f, 0x4a, 0x53, 0xc1, 0xd6, 0x65, 0xdf, 0xa1, 0x31, 0x17, 0xd9, 0xaf, 0x85, 0xe2, 0x6e, 0x98, 0x3c, 0xa3, 0xeb, 0xbb, 0x34, 0x08, 0x0b, 0xe4, 0xa9, 0x9e, 0x71, 0xc9, 0x82, 0xe1, 0xd8, 0xe5, 0xde, 0xa3, 0x51, 0x99, 0x2f, 0x59, 0x20, 0x32, 0x8b, 0xfd, 0x86, 0xe2, 0xb3, 0xcb, 0xad, 0xd3, 0x30, 0xcd, 0xfb, 0x0d, 0x86, 0x6a, 0x4e, 0x7e, 0x9b, 0x92, 0x77, 0x67, 0xcf, 0xf8, 0xc7, 0x09, 0x1a, 0x60, 0x39, 0x7b, 0x77, 0xd6, 0x94, 0x3d, 0xf6, 0x8c, 0x29, 0xff, 0x84, 0xb2, 0x89, 0xc0, 0x9e, 0x9a, 0xf3, 0x63, 0x98, 0x73, 0x6f, 0x75, 0xbd, 0xb1, 0x7d, 0x34, 0x2a, 0x35, 0x55, 0xb9, 0x02, 0xda, 0x95, 0xa9, 0xec, 0xc7, 0xbd, 0xe4, 0x6d, 0x50, 0x94, 0x11, 0x24, 0x31, 0x2b, 0xcc, 0x2e, 0xb3, 0xb2, 0xa3, 0x26, 0x22, 0xac, 0x30, 0x94, 0x67, 0x45, 0x20, 0x51, 0x2b, 0xae, 0xd3, 0x67, 0x56, 0x3e, 0x50, 0xa5, 0x99, 0x56, 0xdc, 0x10, 0xc0, 0xad, 0x04, 0x48, 0x4b, 0xeb, 0x7e, 0xbe, 0x85, 0xed, 0xe4, 0x8b, 0xe1, 0x04, 0x6c, 0x03, 0xef, 0xcf, 0xc1, 0x4a, 0x46, 0x13, 0x06, 0x37, 0x4d, 0xfb, 0xd9, 0x08, 0x5a, 0x60, 0x34, 0xd3, 0xb4, 0x9f, 0x9b, 0x41, 0x2b, 0xff, 0xa6, 0x04, 0x49, 0x9a, 0x4f, 0x92, 0x2c, 0x24, 0xdf, 0x6b, 0x6d, 0x3e, 0x56, 0xce, 0xd1, 0x5f, 0x0f, 0x5b, 0xad, 0xa7, 0x8a, 0x44, 0x72, 0x90, 0x7a, 0xf8, 0x95, 0xbd, 0xc6, 0xae, 0x22, 0x93, 0x22, 0xe4, 0x9b, 0x9b, 0xdb, 0x1b, 0x0d, 0x63, 0xc7, 0xd8, 0xdc, 0xde, 0x53, 0x12, 0xb4, 0xad, 0xf9, 0xb4, 0xf5, 0x60, 0x4f, 0x49, 0x92, 0x0c, 0x24, 0x68, 0x5d, 0x8a, 0x00, 0xa4, 0x77, 0xf7, 0x8c, 0xcd, 0xed, 0x0d, 0x25, 0x4d, 0xad, 0xec, 0x6d, 0x6e, 0x35, 0x94, 0x0c, 0x45, 0xee, 0xbd, 0xbb, 0xf3, 0xb4, 0xa1, 0x64, 0xe9, 0xcf, 0x07, 0x86, 0xf1, 0xe0, 0x2b, 0x4a, 0x8e, 0x92, 0xb6, 0x1e, 0xec, 0x28, 0x80, 0xcd, 0x0f, 0x1e, 0x3e, 0x6d, 0x28, 0x79, 0x52, 0x80, 0x6c, 0xf3, 0xdd, 0xed, 0x47, 0x7b, 0x9b, 0xad, 0x6d, 0xa5, 0x50, 0x3e, 0x81, 0x12, 0x5b, 0xe6, 0xc0, 0x2a, 0xb2, 0xa4, 0xf0, 0x1d, 0x48, 0xb1, 0x9d, 0x91, 0x50, 0x25, 0x95, 0xf0, 0xce, 0x4c, 0x53, 0x56, 0xd8, 0x1e, 0x31, 0xda, 0xd2, 0x65, 0x48, 0xb1, 0x55, 0x5a, 0x84, 0x14, 0x5b, 0x1d, 0x19, 0x53, 0x45, 0x56, 0x28, 0xff, 0x96, 0x0c, 0xb0, 0x61, 0xef, 0x3e, 0xef, 0x8f, 0x30, 0x21, 0xbf, 0x0c, 0x30, 0x79, 0xde, 0x1f, 0xb5, 0x51, 0xf5, 0x3c, 0xa9, 0xcc, 0xd1, 0x1a, 0xf4, 0x77, 0xe4, 0x1a, 0x14, 0xb0, 0xf9, 0x90, 0x79, 0x21, 0xcc, 0x25, 0x33, 0x46, 0x9e, 0xd6, 0x71, 0xc7, 0x14, 0x84, 0xd4, 0x74, 0x4c, 0x21, 0xd3, 0x02, 0xa4, 0xa6, 0x93, 0xab, 0x80, 0xc5, 0xf6, 0x04, 0x23, 0x0a, 0xa6, 0x8d, 0x39, 0x03, 0xfb, 0x65, 0x31, 0x86, 0xbc, 0x0d, 0xd8, 0x27, 0x9b, 0x77, 0x71, 0xfa, 0x74, 0xb8, 0xc3, 0x5d, 0xa1, 0x3f, 0xd8, 0x6c, 0x7d, 0xc2, 0x52, 0x0b, 0x72, 0x5e, 0x3d, 0xed, 0x0b, 0x6b, 0xf9, 0x8c, 0x14, 0x9c, 0x11, 0x60, 0x95, 0x37, 0x25, 0x06, 0xe0, 0xa3, 0x59, 0xc0, 0xd1, 0x30, 0x12, 0x1b, 0x4e, 0xf9, 0x32, 0xcc, 0x6d, 0xdb, 0x16, 0x3b, 0xbd, 0xb8, 0x4a, 0x05, 0x90, 0x3a, 0x25, 0x09, 0xb3, 0x27, 0xa9, 0x53, 0xbe, 0x02, 0x20, 0xb4, 0x29, 0x20, 0xed, 0xb3, 0x36, 0xf4, 0x01, 0xd2, 0x7e, 0xf9, 0x26, 0xa4, 0xb7, 0x3a, 0xc7, 0x7b, 0x9d, 0x1e, 0xb9, 0x06, 0x30, 0xe8, 0x4c, 0x9c, 0xf6, 0x21, 0xee, 0xc3, 0xe7, 0x9f, 0x7f, 0xfe, 0xb9, 0x84, 0x97, 0xbd, 0x1c, 0xad, 0x65, 0xfb, 0xf1, 0x02, 0xa0, 0x35, 0xe8, 0x6e, 0x99, 0x93, 0x49, 0xa7, 0x67, 0x92, 0x2a, 0xa4, 0x2d, 0x73, 0x42, 0xa3, 0x9d, 0x84, 0xef, 0x08, 0xcb, 0xfe, 0x2a, 0xf8, 0xa8, 0x95, 0x6d, 0x84, 0x18, 0x1c, 0x4a, 0x14, 0x48, 0x58, 0x47, 0x43, 0x7c, 0x27, 0x49, 0x19, 0xf4, 0xe7, 0xd2, 0x25, 0x48, 0x33, 0x0c, 0x21, 0x90, 0xb4, 0x3a, 0x43, 0xb3, 0xc4, 0xfa, 0xc5, 0xdf, 0xe5, 0x5f, 0x95, 0x00, 0xb6, 0xcd, 0x97, 0x67, 0xe8, 0xd3, 0x47, 0xc5, 0xf4, 0x99, 0x60, 0x7d, 0xde, 0x8f, 0xeb, 0x93, 0xea, 0xec, 0xd0, 0xb6, 0xbb, 0x6d, 0xb6, 0xc5, 0xec, 0x49, 0x27, 0x47, 0x6b, 0x70, 0xd7, 0xca, 0x1f, 0x40, 0x61, 0xd3, 0xb2, 0xcc, 0xb1, 0x3b, 0x26, 0x02, 0xc9, 0x67, 0xf6, 0xc4, 0xe1, 0x6f, 0x4b, 0xf8, 0x9b, 0x94, 0x20, 0x39, 0xb2, 0xc7, 0x0e, 0x9b, 0x67, 0x3d, 0xa9, 0xaf, 0xae, 0xae, 0x1a, 0x58, 0x43, 0x2e, 0x41, 0xee, 0xc0, 0xb6, 0x2c, 0xf3, 0x80, 0x4e, 0x22, 0x81, 0x69, 0x8d, 0x5f, 0x51, 0xfe, 0x65, 0x09, 0x0a, 0x2d, 0xe7, 0x99, 0x6f, 0x5c, 0x81, 0xc4, 0x73, 0xf3, 0x04, 0x87, 0x97, 0x30, 0xe8, 0x4f, 0x7a, 0x54, 0x7e, 0xbe, 0x33, 0x38, 0x62, 0x6f, 0x4d, 0x05, 0x83, 0x15, 0xc8, 0x05, 0x48, 0xbf, 0x34, 0xfb, 0xbd, 0x67, 0x0e, 0xda, 0x94, 0x0d, 0x5e, 0x22, 0xb7, 0x20, 0xd5, 0xa7, 0x83, 0x2d, 0x25, 0x71, 0xbd, 0x2e, 0xf8, 0xeb, 0x25, 0xce, 0xc1, 0x60, 0xa0, 0x1b, 0xd9, 0x6c, 0x57, 0xf9, 0xe8, 0xa3, 0x8f, 0x3e, 0x92, 0xcb, 0x87, 0xb0, 0xe8, 0x1e, 0xde, 0xc0, 0x64, 0xb7, 0xa1, 0x34, 0x30, 0xed, 0xf6, 0x61, 0xdf, 0xea, 0x0c, 0x06, 0x27, 0xed, 0x97, 0xb6, 0xd5, 0xee, 0x58, 0x6d, 0x7b, 0x72, 0xd0, 0x19, 0xe3, 0x02, 0x44, 0x77, 0xb1, 0x38, 0x30, 0xed, 0x26, 0xa3, 0xbd, 0x6f, 0x5b, 0x0f, 0xac, 0x16, 0xe5, 0x94, 0xff, 0x20, 0x09, 0xb9, 0xad, 0x13, 0xd7, 0xfa, 0x22, 0xa4, 0x0e, 0xec, 0x23, 0x8b, 0xad, 0x65, 0xca, 0x60, 0x05, 0x6f, 0x8f, 0x64, 0x61, 0x8f, 0x16, 0x21, 0xf5, 0xe2, 0xc8, 0x76, 0x4c, 0x9c, 0x6e, 0xce, 0x60, 0x05, 0xba, 0x5a, 0x23, 0xd3, 0x29, 0x25, 0x31, 0xb9, 0xa5, 0x3f, 0xfd, 0xf9, 0xa7, 0xce, 0x30, 0x7f, 0xb2, 0x02, 0x69, 0x9b, 0xae, 0xfe, 0xa4, 0x94, 0xc6, 0x77, 0x35, 0x01, 0x2e, 0xee, 0x8a, 0xc1, 0x51, 0x64, 0x13, 0x16, 0x5e, 0x9a, 0xed, 0xe1, 0xd1, 0xc4, 0x69, 0xf7, 0xec, 0x76, 0xd7, 0x34, 0x47, 0xe6, 0xb8, 0x34, 0x87, 0x3d, 0x09, 0x3e, 0x61, 0xd6, 0x42, 0x1a, 0xf3, 0x2f, 0xcd, 0xad, 0xa3, 0x89, 0xb3, 0x61, 0x3f, 0x46, 0x16, 0xa9, 0x42, 0x6e, 0x6c, 0x52, 0x4f, 0x40, 0x07, 0x5b, 0x08, 0xf7, 0x1e, 0xa0, 0x66, 0xc7, 0xe6, 0x08, 0x2b, 0xc8, 0x3a, 0x64, 0xf7, 0xfb, 0xcf, 0xcd, 0xc9, 0x33, 0xb3, 0x5b, 0xca, 0xa8, 0x52, 0x65, 0x5e, 0xbb, 0xe8, 0x73, 0xbc, 0x65, 0x5d, 0x79, 0x64, 0x0f, 0xec, 0xb1, 0xe1, 0x41, 0xc9, 0x7d, 0xc8, 0x4d, 0xec, 0xa1, 0xc9, 0xf4, 0x9d, 0xc5, 0xa0, 0x7a, 0x79, 0x16, 0x6f, 0xd7, 0x1e, 0x9a, 0xae, 0x07, 0x73, 0xf1, 0x64, 0x99, 0x0d, 0x74, 0x9f, 0x5e, 0x9d, 0x4b, 0x80, 0x4f, 0x03, 0x74, 0x40, 0x78, 0x95, 0x26, 0x4b, 0x74, 0x40, 0xbd, 0x43, 0x7a, 0x23, 0x2a, 0xe5, 0x31, 0xaf, 0xf4, 0xca, 0x4b, 0xb7, 0x20, 0xe7, 0x19, 0xf4, 0x5d, 0x1f, 0x73, 0x37, 0x39, 0xf4, 0x07, 0xcc, 0xf5, 0x31, 0x5f, 0xf3, 0x06, 0xa4, 0x70, 0xd8, 0x34, 0x42, 0x19, 0x0d, 0x1a, 0x10, 0x73, 0x90, 0xda, 0x30, 0x1a, 0x8d, 0x6d, 0x45, 0xc2, 0xd8, 0xf8, 0xf4, 0xdd, 0x86, 0x22, 0x0b, 0x8a, 0xfd, 0x6d, 0x09, 0x12, 0x8d, 0x63, 0x54, 0x0b, 0x9d, 0x86, 0x7b, 0xa2, 0xe9, 0x6f, 0xad, 0x06, 0xc9, 0xa1, 0x3d, 0x36, 0xc9, 0xf9, 0x19, 0xb3, 0x2c, 0xf5, 0x70, 0xbf, 0x84, 0x57, 0xe4, 0xc6, 0xb1, 0x63, 0x20, 0x5e, 0x7b, 0x0b, 0x92, 0x8e, 0x79, 0xec, 0xcc, 0xe6, 0x3d, 0x63, 0x1d, 0x50, 0x80, 0x76, 0x13, 0xd2, 0xd6, 0xd1, 0x70, 0xdf, 0x1c, 0xcf, 0x86, 0xf6, 0x71, 0x7a, 0x1c, 0x52, 0x7e, 0x0f, 0x94, 0x47, 0xf6, 0x70, 0x34, 0x30, 0x8f, 0x1b, 0xc7, 0x8e, 0x69, 0x4d, 0xfa, 0xb6, 0x45, 0xf5, 0x7c, 0xd8, 0x1f, 0xa3, 0x17, 0xc1, 0xb7, 0x62, 0x2c, 0xd0, 0x53, 0x3d, 0x31, 0x0f, 0x6c, 0xab, 0xcb, 0x1d, 0x26, 0x2f, 0x51, 0xb4, 0xf3, 0xac, 0x3f, 0xa6, 0x0e, 0x84, 0xfa, 0x79, 0x56, 0x28, 0x6f, 0x40, 0x91, 0xe7, 0x18, 0x13, 0xde, 0x71, 0xf9, 0x06, 0x14, 0xdc, 0x2a, 0x7c, 0x38, 0xcf, 0x42, 0xf2, 0x83, 0x86, 0xd1, 0x52, 0xce, 0xd1, 0x65, 0x6d, 0x6d, 0x37, 0x14, 0x89, 0xfe, 0xd8, 0x7b, 0xbf, 0x15, 0x58, 0xca, 0x4b, 0x50, 0xf0, 0xc6, 0xbe, 0x6b, 0x3a, 0xd8, 0x42, 0x03, 0x42, 0xa6, 0x2e, 0x67, 0xa5, 0x72, 0x06, 0x52, 0x8d, 0xe1, 0xc8, 0x39, 0x29, 0xff, 0x22, 0xe4, 0x39, 0xe8, 0x69, 0x7f, 0xe2, 0x90, 0x3b, 0x90, 0x19, 0xf2, 0xf9, 0x4a, 0x78, 0xdd, 0x13, 0x35, 0xe5, 0xe3, 0xdc, 0xdf, 0x86, 0x8b, 0x5e, 0xaa, 0x42, 0x46, 0xf0, 0xa5, 0xfc, 0xa8, 0xcb, 0xe2, 0x51, 0x67, 0x4e, 0x21, 0x21, 0x38, 0x85, 0xf2, 0x16, 0x64, 0x58, 0x04, 0x9c, 0x60, 0x54, 0x67, 0xa9, 0x22, 0x13, 0x13, 0xdb, 0xf9, 0x3c, 0xab, 0x63, 0x17, 0x95, 0xab, 0x90, 0x47, 0xc1, 0x72, 0x04, 0x73, 0x9d, 0x80, 0x55, 0x4c, 0x6e, 0xbf, 0x9f, 0x82, 0xac, 0xbb, 0x52, 0x64, 0x19, 0xd2, 0x2c, 0x3f, 0x43, 0x53, 0xee, 0xfb, 0x41, 0x0a, 0x33, 0x32, 0xb2, 0x0c, 0x19, 0x9e, 0x83, 0x71, 0xef, 0x2e, 0x57, 0x35, 0x23, 0xcd, 0x72, 0x2e, 0xaf, 0xb1, 0xa6, 0xa3, 0x63, 0x62, 0x2f, 0x03, 0x69, 0x96, 0x55, 0x11, 0x15, 0x72, 0x5e, 0x1e, 0x85, 0xfe, 0x98, 0x3f, 0x03, 0x64, 0xdd, 0xc4, 0x49, 0x40, 0xd4, 0x74, 0xf4, 0x58, 0x3c, 0xe7, 0xcf, 0x36, 0xfd, 0xeb, 0x49, 0xd6, 0xcd, 0x86, 0xf0, 0xf9, 0xde, 0x4d, 0xf0, 0x33, 0x3c, 0xff, 0xf1, 0x01, 0x35, 0x1d, 0x5d, 0x82, 0x9b, 0xcd, 0x67, 0x78, 0x8e, 0x43, 0xae, 0xd2, 0x21, 0x62, 0xce, 0x82, 0x47, 0xdf, 0x4f, 0xdd, 0xd3, 0x2c, 0x93, 0x21, 0xd7, 0xa8, 0x05, 0x96, 0x98, 0xe0, 0xb9, 0xf4, 0xf3, 0xf4, 0x0c, 0xcf, 0x57, 0xc8, 0x4d, 0x0a, 0x61, 0xcb, 0x5f, 0x82, 0x88, 0xa4, 0x3c, 0xc3, 0x93, 0x72, 0xa2, 0xd2, 0x0e, 0xd1, 0x3d, 0xa0, 0x4b, 0x10, 0x12, 0xf0, 0x34, 0x4b, 0xc0, 0xc9, 0x15, 0x34, 0xc7, 0x26, 0x55, 0xf0, 0x93, 0xed, 0x0c, 0x4f, 0x70, 0xfc, 0x76, 0xbc, 0xb2, 0x79, 0x89, 0x75, 0x86, 0xa7, 0x30, 0xa4, 0x46, 0xf7, 0x8b, 0xea, 0xbb, 0x34, 0x8f, 0x4e, 0xb0, 0xe4, 0x0b, 0xcf, 0xdd, 0x53, 0xe6, 0x03, 0xeb, 0xcc, 0x83, 0x18, 0xa9, 0x26, 0x9e, 0x86, 0x25, 0xca, 0xdb, 0xe9, 0x5b, 0x87, 0xa5, 0x22, 0xae, 0x44, 0xa2, 0x6f, 0x1d, 0x1a, 0xa9, 0x26, 0xad, 0x61, 0x1a, 0xd8, 0xa6, 0x6d, 0x0a, 0xb6, 0x25, 0x6f, 0xb3, 0x46, 0x5a, 0x45, 0x4a, 0x90, 0x6a, 0xb6, 0xb7, 0x3b, 0x56, 0x69, 0x81, 0xf1, 0xac, 0x8e, 0x65, 0x24, 0x9b, 0xdb, 0x1d, 0x8b, 0xbc, 0x05, 0x89, 0xc9, 0xd1, 0x7e, 0x89, 0x84, 0xbf, 0xac, 0xec, 0x1e, 0xed, 0xbb, 0x43, 0x31, 0x28, 0x82, 0x2c, 0x43, 0x76, 0xe2, 0x8c, 0xdb, 0xbf, 0x60, 0x8e, 0xed, 0xd2, 0x79, 0x5c, 0xc2, 0x73, 0x46, 0x66, 0xe2, 0x8c, 0x3f, 0x30, 0xc7, 0xf6, 0x19, 0x9d, 0x5f, 0xf9, 0x0a, 0xe4, 0x05, 0xbb, 0xa4, 0x08, 0x92, 0xc5, 0x6e, 0x0a, 0x75, 0xe9, 0x8e, 0x21, 0x59, 0xe5, 0x3d, 0x28, 0xb8, 0x39, 0x0c, 0xce, 0x57, 0xa3, 0x27, 0x69, 0x60, 0x8f, 0xf1, 0x7c, 0xce, 0x6b, 0x97, 0xc4, 0x10, 0xe5, 0xc3, 0x78, 0xb8, 0x60, 0xd0, 0xb2, 0x12, 0x1a, 0x8a, 0x54, 0xfe, 0xa1, 0x04, 0x85, 0x2d, 0x7b, 0xec, 0x3f, 0x30, 0x2f, 0x42, 0x6a, 0xdf, 0xb6, 0x07, 0x13, 0x34, 0x9b, 0x35, 0x58, 0x81, 0xbc, 0x01, 0x05, 0xfc, 0xe1, 0xe6, 0x9e, 0xb2, 0xf7, 0xb4, 0x91, 0xc7, 0x7a, 0x9e, 0x70, 0x12, 0x48, 0xf6, 0x2d, 0x67, 0xc2, 0x3d, 0x19, 0xfe, 0x26, 0x5f, 0x80, 0x3c, 0xfd, 0xeb, 0x32, 0x93, 0xde, 0x85, 0x15, 0x68, 0x35, 0x27, 0xbe, 0x05, 0x73, 0xb8, 0xfb, 0x1e, 0x2c, 0xe3, 0x3d, 0x63, 0x14, 0x58, 0x03, 0x07, 0x96, 0x20, 0xc3, 0x5c, 0xc1, 0x04, 0xbf, 0x96, 0xe5, 0x0c, 0xb7, 0x48, 0xdd, 0x2b, 0x66, 0x02, 0x2c, 0xdc, 0x67, 0x0c, 0x5e, 0x2a, 0x3f, 0x80, 0x2c, 0x46, 0xa9, 0xd6, 0xa0, 0x4b, 0xca, 0x20, 0xf5, 0x4a, 0x26, 0xc6, 0xc8, 0x45, 0xe1, 0x9a, 0xcf, 0x9b, 0x57, 0x36, 0x0c, 0xa9, 0xb7, 0xb4, 0x00, 0xd2, 0x06, 0xbd, 0x77, 0x1f, 0x73, 0x37, 0x2d, 0x1d, 0x97, 0x5b, 0xdc, 0xc4, 0xb6, 0xf9, 0x32, 0xce, 0xc4, 0xb6, 0xf9, 0x92, 0x99, 0xb8, 0x3a, 0x65, 0x82, 0x96, 0x4e, 0xf8, 0xa7, 0x43, 0xe9, 0xa4, 0x5c, 0x85, 0x39, 0x3c, 0x9e, 0x7d, 0xab, 0xb7, 0x63, 0xf7, 0x2d, 0xbc, 0xe7, 0x1f, 0xe2, 0x3d, 0x49, 0x32, 0xa4, 0x43, 0xba, 0x07, 0xe6, 0x71, 0xe7, 0x80, 0xdd, 0x38, 0xb3, 0x06, 0x2b, 0x94, 0x3f, 0x4b, 0xc2, 0x3c, 0x77, 0xad, 0xef, 0xf7, 0x9d, 0x67, 0x5b, 0x9d, 0x11, 0x79, 0x0a, 0x05, 0xea, 0x55, 0xdb, 0xc3, 0xce, 0x68, 0x44, 0x8f, 0xaf, 0x84, 0x57, 0x8d, 0xeb, 0x53, 0xae, 0x9a, 0xe3, 0x57, 0xb6, 0x3b, 0x43, 0x73, 0x8b, 0x61, 0x1b, 0x96, 0x33, 0x3e, 0x31, 0xf2, 0x96, 0x5f, 0x43, 0x36, 0x21, 0x3f, 0x9c, 0xf4, 0x3c, 0x63, 0x32, 0x1a, 0xab, 0x44, 0x1a, 0xdb, 0x9a, 0xf4, 0x02, 0xb6, 0x60, 0xe8, 0x55, 0xd0, 0x81, 0x51, 0x7f, 0xec, 0xd9, 0x4a, 0x9c, 0x32, 0x30, 0xea, 0x3a, 0x82, 0x03, 0xdb, 0xf7, 0x6b, 0xc8, 0x63, 0x00, 0x7a, 0xbc, 0x1c, 0x9b, 0xa6, 0x4e, 0xa8, 0xa0, 0xbc, 0xf6, 0x66, 0xa4, 0xad, 0x5d, 0x67, 0xbc, 0x67, 0xef, 0x3a, 0x63, 0x66, 0x88, 0x1e, 0x4c, 0x2c, 0x2e, 0xbd, 0x03, 0x4a, 0x78, 0xfe, 0xe2, 0x8d, 0x3c, 0x35, 0xe3, 0x46, 0x9e, 0xe3, 0x37, 0xf2, 0xba, 0x7c, 0x57, 0x5a, 0x7a, 0x0f, 0x8a, 0xa1, 0x29, 0x8b, 0x74, 0xc2, 0xe8, 0xb7, 0x45, 0x7a, 0x5e, 0x7b, 0x5d, 0xf8, 0x9c, 0x2d, 0x6e, 0xb8, 0x68, 0xf7, 0x1d, 0x50, 0xc2, 0xd3, 0x17, 0x0d, 0x67, 0x63, 0x32, 0x05, 0xe4, 0xdf, 0x87, 0xb9, 0xc0, 0x94, 0x45, 0x72, 0xee, 0x94, 0x49, 0x95, 0x7f, 0x29, 0x05, 0xa9, 0x96, 0x65, 0xda, 0x87, 0xe4, 0xf5, 0x60, 0x9c, 0x7c, 0x72, 0xce, 0x8d, 0x91, 0x17, 0x43, 0x31, 0xf2, 0xc9, 0x39, 0x2f, 0x42, 0x5e, 0x0c, 0x45, 0x48, 0xb7, 0xa9, 0xa6, 0x93, 0xcb, 0x53, 0xf1, 0xf1, 0xc9, 0x39, 0x21, 0x38, 0x5e, 0x9e, 0x0a, 0x8e, 0x7e, 0x73, 0x4d, 0xa7, 0x0e, 0x35, 0x18, 0x19, 0x9f, 0x9c, 0xf3, 0xa3, 0xe2, 0x72, 0x38, 0x2a, 0x7a, 0x8d, 0x35, 0x9d, 0x0d, 0x49, 0x88, 0x88, 0x38, 0x24, 0x16, 0x0b, 0x97, 0xc3, 0xb1, 0x10, 0x79, 0x3c, 0x0a, 0x2e, 0x87, 0xa3, 0x20, 0x36, 0xf2, 0xa8, 0x77, 0x31, 0x14, 0xf5, 0xd0, 0x28, 0x0b, 0x77, 0xcb, 0xe1, 0x70, 0xc7, 0x78, 0xc2, 0x48, 0xc5, 0x58, 0xe7, 0x35, 0xd6, 0x74, 0xa2, 0x85, 0x02, 0x5d, 0xf4, 0x6d, 0x1f, 0xf7, 0x02, 0x9d, 0xbe, 0x4e, 0x97, 0xcd, 0xbd, 0x88, 0x16, 0x63, 0xbe, 0xf8, 0xe3, 0x6a, 0xba, 0x17, 0x31, 0x0d, 0x32, 0x87, 0x3c, 0x01, 0x56, 0xd0, 0x73, 0x09, 0xb2, 0xc4, 0xcd, 0x5f, 0x69, 0xb6, 0xd1, 0x83, 0xd1, 0x79, 0x1d, 0xb2, 0x3b, 0x7d, 0x05, 0xe6, 0x9a, 0xed, 0xa7, 0x9d, 0x71, 0xcf, 0x9c, 0x38, 0xed, 0xbd, 0x4e, 0xcf, 0x7b, 0x44, 0xa0, 0xfb, 0x9f, 0x6f, 0xf2, 0x96, 0xbd, 0x4e, 0x8f, 0x5c, 0x70, 0xc5, 0xd5, 0xc5, 0x56, 0x89, 0xcb, 0x6b, 0xe9, 0x75, 0xba, 0x68, 0xcc, 0x18, 0xfa, 0xc2, 0x05, 0xee, 0x0b, 0x1f, 0x66, 0x20, 0x75, 0x64, 0xf5, 0x6d, 0xeb, 0x61, 0x0e, 0x32, 0x8e, 0x3d, 0x1e, 0x76, 0x1c, 0xbb, 0xfc, 0x23, 0x09, 0xe0, 0x91, 0x3d, 0x1c, 0x1e, 0x59, 0xfd, 0x17, 0x47, 0x26, 0xb9, 0x02, 0xf9, 0x61, 0xe7, 0xb9, 0xd9, 0x1e, 0x9a, 0xed, 0x83, 0xb1, 0x7b, 0x0e, 0x72, 0xb4, 0x6a, 0xcb, 0x7c, 0x34, 0x3e, 0x21, 0x25, 0xf7, 0x8a, 0x8e, 0xda, 0x41, 0x49, 0xf2, 0x2b, 0xfb, 0x22, 0xbf, 0x74, 0xa6, 0xf9, 0x1e, 0xba, 0xd7, 0x4e, 0x96, 0x47, 0x64, 0xf8, 0xee, 0x61, 0x89, 0x4a, 0xde, 0x31, 0x87, 0xa3, 0xf6, 0x01, 0x4a, 0x85, 0xca, 0x21, 0x45, 0xcb, 0x8f, 0xc8, 0x6d, 0x48, 0x1c, 0xd8, 0x03, 0x14, 0xc9, 0x29, 0xfb, 0x42, 0x71, 0xe4, 0x0d, 0x48, 0x0c, 0x27, 0x4c, 0x36, 0x79, 0x6d, 0x41, 0xb8, 0x27, 0xb0, 0xd0, 0x44, 0x61, 0xc3, 0x49, 0xcf, 0x9b, 0xf7, 0x8d, 0x22, 0x24, 0x9a, 0xad, 0x16, 0x8d, 0xfd, 0xcd, 0x56, 0x6b, 0x4d, 0x91, 0xea, 0x5f, 0x82, 0x6c, 0x6f, 0x6c, 0x9a, 0xd4, 0x3d, 0xcc, 0xce, 0x39, 0x3e, 0xc4, 0x58, 0xe7, 0x81, 0xea, 0x5b, 0x90, 0x39, 0x60, 0x59, 0x07, 0x89, 0x48, 0x6b, 0x4b, 0x7f, 0xc8, 0x1e, 0x55, 0x96, 0xfc, 0xe6, 0x70, 0x9e, 0x62, 0xb8, 0x36, 0xea, 0x3b, 0x90, 0x1b, 0xb7, 0x4f, 0x33, 0xf8, 0x31, 0x8b, 0x2e, 0x71, 0x06, 0xb3, 0x63, 0x5e, 0x55, 0x6f, 0xc0, 0x82, 0x65, 0xbb, 0xdf, 0x50, 0xda, 0x5d, 0x76, 0xc6, 0x2e, 0x4e, 0x5f, 0xe5, 0x5c, 0xe3, 0x26, 0xfb, 0x6e, 0x69, 0xd9, 0xbc, 0x81, 0x9d, 0xca, 0xfa, 0x23, 0x50, 0x04, 0x33, 0x98, 0x7a, 0xc6, 0x59, 0x39, 0x64, 0x1f, 0x4a, 0x3d, 0x2b, 0x78, 0xee, 0x43, 0x46, 0xd8, 0xc9, 0x8c, 0x31, 0xd2, 0x63, 0x5f, 0x9d, 0x3d, 0x23, 0xe8, 0xea, 0xa6, 0x8d, 0x50, 0x5f, 0x13, 0x6d, 0xe4, 0x19, 0xfb, 0x20, 0x2d, 0x1a, 0xa9, 0xe9, 0xa1, 0x55, 0x39, 0x3a, 0x75, 0x28, 0x7d, 0xf6, 0x3d, 0xd9, 0xb3, 0xc2, 0x1c, 0xe0, 0x0c, 0x33, 0xf1, 0x83, 0xf9, 0x90, 0x7d, 0x6a, 0x0e, 0x98, 0x99, 0x1a, 0xcd, 0xe4, 0xd4, 0xd1, 0x3c, 0x67, 0xdf, 0x75, 0x3d, 0x33, 0xbb, 0xb3, 0x46, 0x33, 0x39, 0x75, 0x34, 0x03, 0xf6, 0xc5, 0x37, 0x60, 0xa6, 0xa6, 0xd7, 0x37, 0x80, 0x88, 0x5b, 0xcd, 0xe3, 0x44, 0x8c, 0x9d, 0x21, 0xfb, 0x8e, 0xef, 0x6f, 0x36, 0xa3, 0xcc, 0x32, 0x14, 0x3f, 0x20, 0x8b, 0x7d, 0xe2, 0x0f, 0x1a, 0xaa, 0xe9, 0xf5, 0x4d, 0x38, 0x2f, 0x4e, 0xec, 0x0c, 0x43, 0xb2, 0x55, 0xa9, 0x52, 0x34, 0x16, 0xfc, 0xa9, 0x71, 0xce, 0x4c, 0x53, 0xf1, 0x83, 0x1a, 0xa9, 0x52, 0x45, 0x99, 0x32, 0x55, 0xd3, 0xeb, 0x0f, 0xa0, 0x28, 0x98, 0xda, 0xc7, 0x08, 0x1d, 0x6d, 0xe6, 0x05, 0xfb, 0x5f, 0x0b, 0xcf, 0x0c, 0x8d, 0xe8, 0xe1, 0x1d, 0xe3, 0x31, 0x2e, 0xda, 0xc8, 0x98, 0xfd, 0xa3, 0x80, 0x3f, 0x16, 0x64, 0x84, 0x8e, 0x04, 0xe6, 0xdf, 0x71, 0x56, 0x26, 0xec, 0x5f, 0x08, 0xfc, 0xa1, 0x50, 0x42, 0xbd, 0x1f, 0x98, 0x8e, 0x49, 0x83, 0x5c, 0x8c, 0x0d, 0x07, 0x3d, 0xf2, 0x9b, 0x91, 0x80, 0x15, 0xf1, 0x81, 0x44, 0x98, 0x36, 0x2d, 0xd6, 0x37, 0x61, 0xfe, 0xec, 0x0e, 0xe9, 0x63, 0x89, 0x65, 0xcb, 0xd5, 0x15, 0x9a, 0x50, 0x1b, 0x73, 0xdd, 0x80, 0x5f, 0x6a, 0xc0, 0xdc, 0x99, 0x9d, 0xd2, 0x27, 0x12, 0xcb, 0x39, 0xa9, 0x25, 0xa3, 0xd0, 0x0d, 0x7a, 0xa6, 0xb9, 0x33, 0xbb, 0xa5, 0x4f, 0x25, 0xf6, 0x40, 0xa1, 0x6b, 0x9e, 0x11, 0xd7, 0x33, 0xcd, 0x9d, 0xd9, 0x2d, 0x7d, 0x95, 0x65, 0x94, 0xb2, 0x5e, 0x15, 0x8d, 0xa0, 0x2f, 0x98, 0x3f, 0xbb, 0x5b, 0xfa, 0x9a, 0x84, 0x8f, 0x15, 0xb2, 0xae, 0x7b, 0xeb, 0xe2, 0x79, 0xa6, 0xf9, 0xb3, 0xbb, 0xa5, 0xaf, 0x4b, 0xf8, 0xa4, 0x21, 0xeb, 0xeb, 0x01, 0x33, 0xc1, 0xd1, 0x9c, 0xee, 0x96, 0xbe, 0x21, 0xe1, 0x2b, 0x83, 0xac, 0xd7, 0x3c, 0x33, 0xbb, 0x53, 0xa3, 0x39, 0xdd, 0x2d, 0x7d, 0x13, 0x6f, 0xf1, 0x75, 0x59, 0xbf, 0x13, 0x30, 0x83, 0x9e, 0xa9, 0xf8, 0x0a, 0x6e, 0xe9, 0x5b, 0x12, 0x3e, 0x06, 0xc9, 0xfa, 0x5d, 0xc3, 0xed, 0xdd, 0xf7, 0x4c, 0xc5, 0x57, 0x70, 0x4b, 0x9f, 0x49, 0xf8, 0x66, 0x24, 0xeb, 0xf7, 0x82, 0x86, 0xd0, 0x33, 0x29, 0xaf, 0xe2, 0x96, 0xbe, 0x4d, 0x2d, 0x15, 0xeb, 0xf2, 0xfa, 0xaa, 0xe1, 0x0e, 0x40, 0xf0, 0x4c, 0xca, 0xab, 0xb8, 0xa5, 0xef, 0x50, 0x53, 0x4a, 0x5d, 0x5e, 0x5f, 0x0b, 0x99, 0xaa, 0xe9, 0xf5, 0x47, 0x50, 0x38, 0xab, 0x5b, 0xfa, 0xae, 0xf8, 0x16, 0x97, 0xef, 0x0a, 0xbe, 0x69, 0x47, 0xd8, 0xb3, 0x53, 0x1d, 0xd3, 0xf7, 0x30, 0xc7, 0xa9, 0xcf, 0x3d, 0x61, 0xef, 0x55, 0x8c, 0xe0, 0x6f, 0x1f, 0x73, 0x53, 0x5b, 0xfe, 0xf9, 0x38, 0xd5, 0x47, 0x7d, 0x5f, 0xc2, 0x47, 0xad, 0x02, 0x37, 0x88, 0x78, 0xef, 0xa4, 0x30, 0x87, 0xf5, 0xa1, 0x3f, 0xcb, 0xd3, 0xbc, 0xd5, 0x0f, 0xa4, 0x57, 0x71, 0x57, 0xf5, 0x44, 0x6b, 0xbb, 0xe1, 0x2d, 0x06, 0xd6, 0xbc, 0x0d, 0xc9, 0x63, 0x6d, 0x75, 0x4d, 0xbc, 0x92, 0x89, 0x6f, 0xb9, 0xcc, 0x49, 0xe5, 0xb5, 0xa2, 0xf0, 0xdc, 0x3d, 0x1c, 0x39, 0x27, 0x06, 0xb2, 0x38, 0x5b, 0x8b, 0x64, 0x7f, 0x12, 0xc3, 0xd6, 0x38, 0xbb, 0x1a, 0xc9, 0xfe, 0x34, 0x86, 0x5d, 0xe5, 0x6c, 0x3d, 0x92, 0xfd, 0xd5, 0x18, 0xb6, 0xce, 0xd9, 0xeb, 0x91, 0xec, 0xaf, 0xc5, 0xb0, 0xd7, 0x39, 0xbb, 0x16, 0xc9, 0xfe, 0x7a, 0x0c, 0xbb, 0xc6, 0xd9, 0x77, 0x22, 0xd9, 0xdf, 0x88, 0x61, 0xdf, 0xe1, 0xec, 0xbb, 0x91, 0xec, 0x6f, 0xc6, 0xb0, 0xef, 0x72, 0xf6, 0xbd, 0x48, 0xf6, 0xb7, 0x62, 0xd8, 0xf7, 0x18, 0x7b, 0x6d, 0x35, 0x92, 0xfd, 0x59, 0x34, 0x7b, 0x6d, 0x95, 0xb3, 0xa3, 0xb5, 0xf6, 0xed, 0x18, 0x36, 0xd7, 0xda, 0x5a, 0xb4, 0xd6, 0xbe, 0x13, 0xc3, 0xe6, 0x5a, 0x5b, 0x8b, 0xd6, 0xda, 0x77, 0x63, 0xd8, 0x5c, 0x6b, 0x6b, 0xd1, 0x5a, 0xfb, 0x5e, 0x0c, 0x9b, 0x6b, 0x6d, 0x2d, 0x5a, 0x6b, 0xdf, 0x8f, 0x61, 0x73, 0xad, 0xad, 0x45, 0x6b, 0xed, 0x07, 0x31, 0x6c, 0xae, 0xb5, 0xb5, 0x68, 0xad, 0xfd, 0x51, 0x0c, 0x9b, 0x6b, 0x6d, 0x2d, 0x5a, 0x6b, 0x7f, 0x1c, 0xc3, 0xe6, 0x5a, 0x5b, 0x8b, 0xd6, 0xda, 0x9f, 0xc4, 0xb0, 0xb9, 0xd6, 0xb4, 0x68, 0xad, 0xfd, 0x69, 0x34, 0x5b, 0xe3, 0x5a, 0xd3, 0xa2, 0xb5, 0xf6, 0x67, 0x31, 0x6c, 0xae, 0x35, 0x2d, 0x5a, 0x6b, 0x7f, 0x1e, 0xc3, 0xe6, 0x5a, 0xd3, 0xa2, 0xb5, 0xf6, 0xc3, 0x18, 0x36, 0xd7, 0x9a, 0x16, 0xad, 0xb5, 0xbf, 0x88, 0x61, 0x73, 0xad, 0x69, 0xd1, 0x5a, 0xfb, 0xcb, 0x18, 0x36, 0xd7, 0x9a, 0x16, 0xad, 0xb5, 0xbf, 0x8a, 0x61, 0x73, 0xad, 0x69, 0xd1, 0x5a, 0xfb, 0xeb, 0x18, 0x36, 0xd7, 0x9a, 0x16, 0xad, 0xb5, 0xbf, 0x89, 0x61, 0x73, 0xad, 0x69, 0xd1, 0x5a, 0xfb, 0xdb, 0x18, 0x36, 0xd7, 0x5a, 0x35, 0x5a, 0x6b, 0x7f, 0x17, 0xcd, 0xae, 0x72, 0xad, 0x55, 0xa3, 0xb5, 0xf6, 0xf7, 0x31, 0x6c, 0xae, 0xb5, 0x6a, 0xb4, 0xd6, 0xfe, 0x21, 0x86, 0xcd, 0xb5, 0x56, 0x8d, 0xd6, 0xda, 0x3f, 0xc6, 0xb0, 0xb9, 0xd6, 0xaa, 0xd1, 0x5a, 0xfb, 0x51, 0x0c, 0x9b, 0x6b, 0xad, 0x1a, 0xad, 0xb5, 0x7f, 0x8a, 0x61, 0x73, 0xad, 0x55, 0xa3, 0xb5, 0xf6, 0xcf, 0x31, 0x6c, 0xae, 0xb5, 0x6a, 0xb4, 0xd6, 0xfe, 0x25, 0x86, 0xcd, 0xb5, 0x56, 0x8d, 0xd6, 0xda, 0xbf, 0xc6, 0xb0, 0xb9, 0xd6, 0xaa, 0xd1, 0x5a, 0xfb, 0xb7, 0x18, 0x36, 0xd7, 0x9a, 0x1e, 0xad, 0xb5, 0x7f, 0x8f, 0x66, 0xeb, 0x5c, 0x6b, 0x7a, 0xb4, 0xd6, 0xfe, 0x23, 0x86, 0xcd, 0xb5, 0xa6, 0x47, 0x6b, 0xed, 0x3f, 0x63, 0xd8, 0x5c, 0x6b, 0x7a, 0xb4, 0xd6, 0xfe, 0x2b, 0x86, 0xcd, 0xb5, 0xa6, 0x47, 0x6b, 0xed, 0xbf, 0x63, 0xd8, 0x5c, 0x6b, 0x7a, 0xb4, 0xd6, 0xfe, 0x27, 0x86, 0xcd, 0xb5, 0xa6, 0x47, 0x6b, 0xed, 0xc7, 0x31, 0x6c, 0xae, 0x35, 0x3d, 0x5a, 0x6b, 0x3f, 0x89, 0x61, 0x73, 0xad, 0xe9, 0xd1, 0x5a, 0xfb, 0xdf, 0x18, 0x36, 0xd7, 0x9a, 0x1e, 0xad, 0xb5, 0xff, 0x8b, 0x61, 0x73, 0xad, 0xad, 0x47, 0x6b, 0xed, 0xff, 0xa3, 0xd9, 0xeb, 0xab, 0x3f, 0x0d, 0x00, 0x00, 0xff, 0xff, 0xaa, 0x00, 0xcd, 0x32, 0x57, 0x39, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/proto/testdata/test.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. // A feature-rich test file for the protocol compiler and libraries. syntax = "proto2"; package testdata; enum FOO { FOO1 = 1; }; message GoEnum { required FOO foo = 1; } message GoTestField { required string Label = 1; required string Type = 2; } message GoTest { // An enum, for completeness. enum KIND { VOID = 0; // Basic types BOOL = 1; BYTES = 2; FINGERPRINT = 3; FLOAT = 4; INT = 5; STRING = 6; TIME = 7; // Groupings TUPLE = 8; ARRAY = 9; MAP = 10; // Table types TABLE = 11; // Functions FUNCTION = 12; // last tag }; // Some typical parameters required KIND Kind = 1; optional string Table = 2; optional int32 Param = 3; // Required, repeated and optional foreign fields. required GoTestField RequiredField = 4; repeated GoTestField RepeatedField = 5; optional GoTestField OptionalField = 6; // Required fields of all basic types required bool F_Bool_required = 10; required int32 F_Int32_required = 11; required int64 F_Int64_required = 12; required fixed32 F_Fixed32_required = 13; required fixed64 F_Fixed64_required = 14; required uint32 F_Uint32_required = 15; required uint64 F_Uint64_required = 16; required float F_Float_required = 17; required double F_Double_required = 18; required string F_String_required = 19; required bytes F_Bytes_required = 101; required sint32 F_Sint32_required = 102; required sint64 F_Sint64_required = 103; // Repeated fields of all basic types repeated bool F_Bool_repeated = 20; repeated int32 F_Int32_repeated = 21; repeated int64 F_Int64_repeated = 22; repeated fixed32 F_Fixed32_repeated = 23; repeated fixed64 F_Fixed64_repeated = 24; repeated uint32 F_Uint32_repeated = 25; repeated uint64 F_Uint64_repeated = 26; repeated float F_Float_repeated = 27; repeated double F_Double_repeated = 28; repeated string F_String_repeated = 29; repeated bytes F_Bytes_repeated = 201; repeated sint32 F_Sint32_repeated = 202; repeated sint64 F_Sint64_repeated = 203; // Optional fields of all basic types optional bool F_Bool_optional = 30; optional int32 F_Int32_optional = 31; optional int64 F_Int64_optional = 32; optional fixed32 F_Fixed32_optional = 33; optional fixed64 F_Fixed64_optional = 34; optional uint32 F_Uint32_optional = 35; optional uint64 F_Uint64_optional = 36; optional float F_Float_optional = 37; optional double F_Double_optional = 38; optional string F_String_optional = 39; optional bytes F_Bytes_optional = 301; optional sint32 F_Sint32_optional = 302; optional sint64 F_Sint64_optional = 303; // Default-valued fields of all basic types optional bool F_Bool_defaulted = 40 [default=true]; optional int32 F_Int32_defaulted = 41 [default=32]; optional int64 F_Int64_defaulted = 42 [default=64]; optional fixed32 F_Fixed32_defaulted = 43 [default=320]; optional fixed64 F_Fixed64_defaulted = 44 [default=640]; optional uint32 F_Uint32_defaulted = 45 [default=3200]; optional uint64 F_Uint64_defaulted = 46 [default=6400]; optional float F_Float_defaulted = 47 [default=314159.]; optional double F_Double_defaulted = 48 [default=271828.]; optional string F_String_defaulted = 49 [default="hello, \"world!\"\n"]; optional bytes F_Bytes_defaulted = 401 [default="Bignose"]; optional sint32 F_Sint32_defaulted = 402 [default = -32]; optional sint64 F_Sint64_defaulted = 403 [default = -64]; // Packed repeated fields (no string or bytes). repeated bool F_Bool_repeated_packed = 50 [packed=true]; repeated int32 F_Int32_repeated_packed = 51 [packed=true]; repeated int64 F_Int64_repeated_packed = 52 [packed=true]; repeated fixed32 F_Fixed32_repeated_packed = 53 [packed=true]; repeated fixed64 F_Fixed64_repeated_packed = 54 [packed=true]; repeated uint32 F_Uint32_repeated_packed = 55 [packed=true]; repeated uint64 F_Uint64_repeated_packed = 56 [packed=true]; repeated float F_Float_repeated_packed = 57 [packed=true]; repeated double F_Double_repeated_packed = 58 [packed=true]; repeated sint32 F_Sint32_repeated_packed = 502 [packed=true]; repeated sint64 F_Sint64_repeated_packed = 503 [packed=true]; // Required, repeated, and optional groups. required group RequiredGroup = 70 { required string RequiredField = 71; }; repeated group RepeatedGroup = 80 { required string RequiredField = 81; }; optional group OptionalGroup = 90 { required string RequiredField = 91; }; } // For testing a group containing a required field. message GoTestRequiredGroupField { required group Group = 1 { required int32 Field = 2; }; } // For testing skipping of unrecognized fields. // Numbers are all big, larger than tag numbers in GoTestField, // the message used in the corresponding test. message GoSkipTest { required int32 skip_int32 = 11; required fixed32 skip_fixed32 = 12; required fixed64 skip_fixed64 = 13; required string skip_string = 14; required group SkipGroup = 15 { required int32 group_int32 = 16; required string group_string = 17; } } // For testing packed/non-packed decoder switching. // A serialized instance of one should be deserializable as the other. message NonPackedTest { repeated int32 a = 1; } message PackedTest { repeated int32 b = 1 [packed=true]; } message MaxTag { // Maximum possible tag number. optional string last_field = 536870911; } message OldMessage { message Nested { optional string name = 1; } optional Nested nested = 1; optional int32 num = 2; } // NewMessage is wire compatible with OldMessage; // imagine it as a future version. message NewMessage { message Nested { optional string name = 1; optional string food_group = 2; } optional Nested nested = 1; // This is an int32 in OldMessage. optional int64 num = 2; } // Smaller tests for ASCII formatting. message InnerMessage { required string host = 1; optional int32 port = 2 [default=4000]; optional bool connected = 3; } message OtherMessage { optional int64 key = 1; optional bytes value = 2; optional float weight = 3; optional InnerMessage inner = 4; extensions 100 to max; } message RequiredInnerMessage { required InnerMessage leo_finally_won_an_oscar = 1; } message MyMessage { required int32 count = 1; optional string name = 2; optional string quote = 3; repeated string pet = 4; optional InnerMessage inner = 5; repeated OtherMessage others = 6; optional RequiredInnerMessage we_must_go_deeper = 13; repeated InnerMessage rep_inner = 12; enum Color { RED = 0; GREEN = 1; BLUE = 2; }; optional Color bikeshed = 7; optional group SomeGroup = 8 { optional int32 group_field = 9; } // This field becomes [][]byte in the generated code. repeated bytes rep_bytes = 10; optional double bigfloat = 11; extensions 100 to max; } message Ext { extend MyMessage { optional Ext more = 103; optional string text = 104; optional int32 number = 105; } optional string data = 1; } extend MyMessage { repeated string greeting = 106; } message ComplexExtension { optional int32 first = 1; optional int32 second = 2; repeated int32 third = 3; } extend OtherMessage { optional ComplexExtension complex = 200; repeated ComplexExtension r_complex = 201; } message DefaultsMessage { enum DefaultsEnum { ZERO = 0; ONE = 1; TWO = 2; }; extensions 100 to max; } extend DefaultsMessage { optional double no_default_double = 101; optional float no_default_float = 102; optional int32 no_default_int32 = 103; optional int64 no_default_int64 = 104; optional uint32 no_default_uint32 = 105; optional uint64 no_default_uint64 = 106; optional sint32 no_default_sint32 = 107; optional sint64 no_default_sint64 = 108; optional fixed32 no_default_fixed32 = 109; optional fixed64 no_default_fixed64 = 110; optional sfixed32 no_default_sfixed32 = 111; optional sfixed64 no_default_sfixed64 = 112; optional bool no_default_bool = 113; optional string no_default_string = 114; optional bytes no_default_bytes = 115; optional DefaultsMessage.DefaultsEnum no_default_enum = 116; optional double default_double = 201 [default = 3.1415]; optional float default_float = 202 [default = 3.14]; optional int32 default_int32 = 203 [default = 42]; optional int64 default_int64 = 204 [default = 43]; optional uint32 default_uint32 = 205 [default = 44]; optional uint64 default_uint64 = 206 [default = 45]; optional sint32 default_sint32 = 207 [default = 46]; optional sint64 default_sint64 = 208 [default = 47]; optional fixed32 default_fixed32 = 209 [default = 48]; optional fixed64 default_fixed64 = 210 [default = 49]; optional sfixed32 default_sfixed32 = 211 [default = 50]; optional sfixed64 default_sfixed64 = 212 [default = 51]; optional bool default_bool = 213 [default = true]; optional string default_string = 214 [default = "Hello, string"]; optional bytes default_bytes = 215 [default = "Hello, bytes"]; optional DefaultsMessage.DefaultsEnum default_enum = 216 [default = ONE]; } message MyMessageSet { option message_set_wire_format = true; extensions 100 to max; } message Empty { } extend MyMessageSet { optional Empty x201 = 201; optional Empty x202 = 202; optional Empty x203 = 203; optional Empty x204 = 204; optional Empty x205 = 205; optional Empty x206 = 206; optional Empty x207 = 207; optional Empty x208 = 208; optional Empty x209 = 209; optional Empty x210 = 210; optional Empty x211 = 211; optional Empty x212 = 212; optional Empty x213 = 213; optional Empty x214 = 214; optional Empty x215 = 215; optional Empty x216 = 216; optional Empty x217 = 217; optional Empty x218 = 218; optional Empty x219 = 219; optional Empty x220 = 220; optional Empty x221 = 221; optional Empty x222 = 222; optional Empty x223 = 223; optional Empty x224 = 224; optional Empty x225 = 225; optional Empty x226 = 226; optional Empty x227 = 227; optional Empty x228 = 228; optional Empty x229 = 229; optional Empty x230 = 230; optional Empty x231 = 231; optional Empty x232 = 232; optional Empty x233 = 233; optional Empty x234 = 234; optional Empty x235 = 235; optional Empty x236 = 236; optional Empty x237 = 237; optional Empty x238 = 238; optional Empty x239 = 239; optional Empty x240 = 240; optional Empty x241 = 241; optional Empty x242 = 242; optional Empty x243 = 243; optional Empty x244 = 244; optional Empty x245 = 245; optional Empty x246 = 246; optional Empty x247 = 247; optional Empty x248 = 248; optional Empty x249 = 249; optional Empty x250 = 250; } message MessageList { repeated group Message = 1 { required string name = 2; required int32 count = 3; } } message Strings { optional string string_field = 1; optional bytes bytes_field = 2; } message Defaults { enum Color { RED = 0; GREEN = 1; BLUE = 2; } // Default-valued fields of all basic types. // Same as GoTest, but copied here to make testing easier. optional bool F_Bool = 1 [default=true]; optional int32 F_Int32 = 2 [default=32]; optional int64 F_Int64 = 3 [default=64]; optional fixed32 F_Fixed32 = 4 [default=320]; optional fixed64 F_Fixed64 = 5 [default=640]; optional uint32 F_Uint32 = 6 [default=3200]; optional uint64 F_Uint64 = 7 [default=6400]; optional float F_Float = 8 [default=314159.]; optional double F_Double = 9 [default=271828.]; optional string F_String = 10 [default="hello, \"world!\"\n"]; optional bytes F_Bytes = 11 [default="Bignose"]; optional sint32 F_Sint32 = 12 [default=-32]; optional sint64 F_Sint64 = 13 [default=-64]; optional Color F_Enum = 14 [default=GREEN]; // More fields with crazy defaults. optional float F_Pinf = 15 [default=inf]; optional float F_Ninf = 16 [default=-inf]; optional float F_Nan = 17 [default=nan]; // Sub-message. optional SubDefaults sub = 18; // Redundant but explicit defaults. optional string str_zero = 19 [default=""]; } message SubDefaults { optional int64 n = 1 [default=7]; } message RepeatedEnum { enum Color { RED = 1; } repeated Color color = 1; } message MoreRepeated { repeated bool bools = 1; repeated bool bools_packed = 2 [packed=true]; repeated int32 ints = 3; repeated int32 ints_packed = 4 [packed=true]; repeated int64 int64s_packed = 7 [packed=true]; repeated string strings = 5; repeated fixed32 fixeds = 6; } // GroupOld and GroupNew have the same wire format. // GroupNew has a new field inside a group. message GroupOld { optional group G = 101 { optional int32 x = 2; } } message GroupNew { optional group G = 101 { optional int32 x = 2; optional int32 y = 3; } } message FloatingPoint { required double f = 1; optional bool exact = 2; } message MessageWithMap { map name_mapping = 1; map msg_mapping = 2; map byte_mapping = 3; map str_to_str = 4; } message Oneof { oneof union { bool F_Bool = 1; int32 F_Int32 = 2; int64 F_Int64 = 3; fixed32 F_Fixed32 = 4; fixed64 F_Fixed64 = 5; uint32 F_Uint32 = 6; uint64 F_Uint64 = 7; float F_Float = 8; double F_Double = 9; string F_String = 10; bytes F_Bytes = 11; sint32 F_Sint32 = 12; sint64 F_Sint64 = 13; MyMessage.Color F_Enum = 14; GoTestField F_Message = 15; group F_Group = 16 { optional int32 x = 17; } int32 F_Largest_Tag = 536870911; } oneof tormato { int32 value = 100; } } message Communique { optional bool make_me_cry = 1; // This is a oneof, called "union". oneof union { int32 number = 5; string name = 6; bytes data = 7; double temp_c = 8; MyMessage.Color col = 9; Strings msg = 10; } } ================================================ FILE: src/github.com/golang/protobuf/proto/text.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto // Functions for writing the text protocol buffer format. import ( "bufio" "bytes" "encoding" "errors" "fmt" "io" "log" "math" "reflect" "sort" "strings" ) var ( newline = []byte("\n") spaces = []byte(" ") gtNewline = []byte(">\n") endBraceNewline = []byte("}\n") backslashN = []byte{'\\', 'n'} backslashR = []byte{'\\', 'r'} backslashT = []byte{'\\', 't'} backslashDQ = []byte{'\\', '"'} backslashBS = []byte{'\\', '\\'} posInf = []byte("inf") negInf = []byte("-inf") nan = []byte("nan") ) type writer interface { io.Writer WriteByte(byte) error } // textWriter is an io.Writer that tracks its indentation level. type textWriter struct { ind int complete bool // if the current position is a complete line compact bool // whether to write out as a one-liner w writer } func (w *textWriter) WriteString(s string) (n int, err error) { if !strings.Contains(s, "\n") { if !w.compact && w.complete { w.writeIndent() } w.complete = false return io.WriteString(w.w, s) } // WriteString is typically called without newlines, so this // codepath and its copy are rare. We copy to avoid // duplicating all of Write's logic here. return w.Write([]byte(s)) } func (w *textWriter) Write(p []byte) (n int, err error) { newlines := bytes.Count(p, newline) if newlines == 0 { if !w.compact && w.complete { w.writeIndent() } n, err = w.w.Write(p) w.complete = false return n, err } frags := bytes.SplitN(p, newline, newlines+1) if w.compact { for i, frag := range frags { if i > 0 { if err := w.w.WriteByte(' '); err != nil { return n, err } n++ } nn, err := w.w.Write(frag) n += nn if err != nil { return n, err } } return n, nil } for i, frag := range frags { if w.complete { w.writeIndent() } nn, err := w.w.Write(frag) n += nn if err != nil { return n, err } if i+1 < len(frags) { if err := w.w.WriteByte('\n'); err != nil { return n, err } n++ } } w.complete = len(frags[len(frags)-1]) == 0 return n, nil } func (w *textWriter) WriteByte(c byte) error { if w.compact && c == '\n' { c = ' ' } if !w.compact && w.complete { w.writeIndent() } err := w.w.WriteByte(c) w.complete = c == '\n' return err } func (w *textWriter) indent() { w.ind++ } func (w *textWriter) unindent() { if w.ind == 0 { log.Print("proto: textWriter unindented too far") return } w.ind-- } func writeName(w *textWriter, props *Properties) error { if _, err := w.WriteString(props.OrigName); err != nil { return err } if props.Wire != "group" { return w.WriteByte(':') } return nil } // raw is the interface satisfied by RawMessage. type raw interface { Bytes() []byte } func requiresQuotes(u string) bool { // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. for _, ch := range u { switch { case ch == '.' || ch == '/' || ch == '_': continue case '0' <= ch && ch <= '9': continue case 'A' <= ch && ch <= 'Z': continue case 'a' <= ch && ch <= 'z': continue default: return true } } return false } // isAny reports whether sv is a google.protobuf.Any message func isAny(sv reflect.Value) bool { type wkt interface { XXX_WellKnownType() string } t, ok := sv.Addr().Interface().(wkt) return ok && t.XXX_WellKnownType() == "Any" } // writeProto3Any writes an expanded google.protobuf.Any message. // // It returns (false, nil) if sv value can't be unmarshaled (e.g. because // required messages are not linked in). // // It returns (true, error) when sv was written in expanded format or an error // was encountered. func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { turl := sv.FieldByName("TypeUrl") val := sv.FieldByName("Value") if !turl.IsValid() || !val.IsValid() { return true, errors.New("proto: invalid google.protobuf.Any message") } b, ok := val.Interface().([]byte) if !ok { return true, errors.New("proto: invalid google.protobuf.Any message") } parts := strings.Split(turl.String(), "/") mt := MessageType(parts[len(parts)-1]) if mt == nil { return false, nil } m := reflect.New(mt.Elem()) if err := Unmarshal(b, m.Interface().(Message)); err != nil { return false, nil } w.Write([]byte("[")) u := turl.String() if requiresQuotes(u) { writeString(w, u) } else { w.Write([]byte(u)) } if w.compact { w.Write([]byte("]:<")) } else { w.Write([]byte("]: <\n")) w.ind++ } if err := tm.writeStruct(w, m.Elem()); err != nil { return true, err } if w.compact { w.Write([]byte("> ")) } else { w.ind-- w.Write([]byte(">\n")) } return true, nil } func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { if tm.ExpandAny && isAny(sv) { if canExpand, err := tm.writeProto3Any(w, sv); canExpand { return err } } st := sv.Type() sprops := GetProperties(st) for i := 0; i < sv.NumField(); i++ { fv := sv.Field(i) props := sprops.Prop[i] name := st.Field(i).Name if strings.HasPrefix(name, "XXX_") { // There are two XXX_ fields: // XXX_unrecognized []byte // XXX_extensions map[int32]proto.Extension // The first is handled here; // the second is handled at the bottom of this function. if name == "XXX_unrecognized" && !fv.IsNil() { if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { return err } } continue } if fv.Kind() == reflect.Ptr && fv.IsNil() { // Field not filled in. This could be an optional field or // a required field that wasn't filled in. Either way, there // isn't anything we can show for it. continue } if fv.Kind() == reflect.Slice && fv.IsNil() { // Repeated field that is empty, or a bytes field that is unused. continue } if props.Repeated && fv.Kind() == reflect.Slice { // Repeated field. for j := 0; j < fv.Len(); j++ { if err := writeName(w, props); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } v := fv.Index(j) if v.Kind() == reflect.Ptr && v.IsNil() { // A nil message in a repeated field is not valid, // but we can handle that more gracefully than panicking. if _, err := w.Write([]byte("\n")); err != nil { return err } continue } if err := tm.writeAny(w, v, props); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } continue } if fv.Kind() == reflect.Map { // Map fields are rendered as a repeated struct with key/value fields. keys := fv.MapKeys() sort.Sort(mapKeys(keys)) for _, key := range keys { val := fv.MapIndex(key) if err := writeName(w, props); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } // open struct if err := w.WriteByte('<'); err != nil { return err } if !w.compact { if err := w.WriteByte('\n'); err != nil { return err } } w.indent() // key if _, err := w.WriteString("key:"); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if err := tm.writeAny(w, key, props.mkeyprop); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } // nil values aren't legal, but we can avoid panicking because of them. if val.Kind() != reflect.Ptr || !val.IsNil() { // value if _, err := w.WriteString("value:"); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if err := tm.writeAny(w, val, props.mvalprop); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } // close struct w.unindent() if err := w.WriteByte('>'); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } continue } if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { // empty bytes field continue } if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { // proto3 non-repeated scalar field; skip if zero value if isProto3Zero(fv) { continue } } if fv.Kind() == reflect.Interface { // Check if it is a oneof. if st.Field(i).Tag.Get("protobuf_oneof") != "" { // fv is nil, or holds a pointer to generated struct. // That generated struct has exactly one field, // which has a protobuf struct tag. if fv.IsNil() { continue } inner := fv.Elem().Elem() // interface -> *T -> T tag := inner.Type().Field(0).Tag.Get("protobuf") props = new(Properties) // Overwrite the outer props var, but not its pointee. props.Parse(tag) // Write the value in the oneof, not the oneof itself. fv = inner.Field(0) // Special case to cope with malformed messages gracefully: // If the value in the oneof is a nil pointer, don't panic // in writeAny. if fv.Kind() == reflect.Ptr && fv.IsNil() { // Use errors.New so writeAny won't render quotes. msg := errors.New("/* nil */") fv = reflect.ValueOf(&msg).Elem() } } } if err := writeName(w, props); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if b, ok := fv.Interface().(raw); ok { if err := writeRaw(w, b.Bytes()); err != nil { return err } continue } // Enums have a String method, so writeAny will work fine. if err := tm.writeAny(w, fv, props); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } // Extensions (the XXX_extensions field). pv := sv.Addr() if _, ok := extendable(pv.Interface()); ok { if err := tm.writeExtensions(w, pv); err != nil { return err } } return nil } // writeRaw writes an uninterpreted raw message. func writeRaw(w *textWriter, b []byte) error { if err := w.WriteByte('<'); err != nil { return err } if !w.compact { if err := w.WriteByte('\n'); err != nil { return err } } w.indent() if err := writeUnknownStruct(w, b); err != nil { return err } w.unindent() if err := w.WriteByte('>'); err != nil { return err } return nil } // writeAny writes an arbitrary field. func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { v = reflect.Indirect(v) // Floats have special cases. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { x := v.Float() var b []byte switch { case math.IsInf(x, 1): b = posInf case math.IsInf(x, -1): b = negInf case math.IsNaN(x): b = nan } if b != nil { _, err := w.Write(b) return err } // Other values are handled below. } // We don't attempt to serialise every possible value type; only those // that can occur in protocol buffers. switch v.Kind() { case reflect.Slice: // Should only be a []byte; repeated fields are handled in writeStruct. if err := writeString(w, string(v.Bytes())); err != nil { return err } case reflect.String: if err := writeString(w, v.String()); err != nil { return err } case reflect.Struct: // Required/optional group/message. var bra, ket byte = '<', '>' if props != nil && props.Wire == "group" { bra, ket = '{', '}' } if err := w.WriteByte(bra); err != nil { return err } if !w.compact { if err := w.WriteByte('\n'); err != nil { return err } } w.indent() if etm, ok := v.Interface().(encoding.TextMarshaler); ok { text, err := etm.MarshalText() if err != nil { return err } if _, err = w.Write(text); err != nil { return err } } else if err := tm.writeStruct(w, v); err != nil { return err } w.unindent() if err := w.WriteByte(ket); err != nil { return err } default: _, err := fmt.Fprint(w, v.Interface()) return err } return nil } // equivalent to C's isprint. func isprint(c byte) bool { return c >= 0x20 && c < 0x7f } // writeString writes a string in the protocol buffer text format. // It is similar to strconv.Quote except we don't use Go escape sequences, // we treat the string as a byte sequence, and we use octal escapes. // These differences are to maintain interoperability with the other // languages' implementations of the text format. func writeString(w *textWriter, s string) error { // use WriteByte here to get any needed indent if err := w.WriteByte('"'); err != nil { return err } // Loop over the bytes, not the runes. for i := 0; i < len(s); i++ { var err error // Divergence from C++: we don't escape apostrophes. // There's no need to escape them, and the C++ parser // copes with a naked apostrophe. switch c := s[i]; c { case '\n': _, err = w.w.Write(backslashN) case '\r': _, err = w.w.Write(backslashR) case '\t': _, err = w.w.Write(backslashT) case '"': _, err = w.w.Write(backslashDQ) case '\\': _, err = w.w.Write(backslashBS) default: if isprint(c) { err = w.w.WriteByte(c) } else { _, err = fmt.Fprintf(w.w, "\\%03o", c) } } if err != nil { return err } } return w.WriteByte('"') } func writeUnknownStruct(w *textWriter, data []byte) (err error) { if !w.compact { if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { return err } } b := NewBuffer(data) for b.index < len(b.buf) { x, err := b.DecodeVarint() if err != nil { _, err := fmt.Fprintf(w, "/* %v */\n", err) return err } wire, tag := x&7, x>>3 if wire == WireEndGroup { w.unindent() if _, err := w.Write(endBraceNewline); err != nil { return err } continue } if _, err := fmt.Fprint(w, tag); err != nil { return err } if wire != WireStartGroup { if err := w.WriteByte(':'); err != nil { return err } } if !w.compact || wire == WireStartGroup { if err := w.WriteByte(' '); err != nil { return err } } switch wire { case WireBytes: buf, e := b.DecodeRawBytes(false) if e == nil { _, err = fmt.Fprintf(w, "%q", buf) } else { _, err = fmt.Fprintf(w, "/* %v */", e) } case WireFixed32: x, err = b.DecodeFixed32() err = writeUnknownInt(w, x, err) case WireFixed64: x, err = b.DecodeFixed64() err = writeUnknownInt(w, x, err) case WireStartGroup: err = w.WriteByte('{') w.indent() case WireVarint: x, err = b.DecodeVarint() err = writeUnknownInt(w, x, err) default: _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) } if err != nil { return err } if err = w.WriteByte('\n'); err != nil { return err } } return nil } func writeUnknownInt(w *textWriter, x uint64, err error) error { if err == nil { _, err = fmt.Fprint(w, x) } else { _, err = fmt.Fprintf(w, "/* %v */", err) } return err } type int32Slice []int32 func (s int32Slice) Len() int { return len(s) } func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // writeExtensions writes all the extensions in pv. // pv is assumed to be a pointer to a protocol message struct that is extendable. func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { emap := extensionMaps[pv.Type().Elem()] ep, _ := extendable(pv.Interface()) // Order the extensions by ID. // This isn't strictly necessary, but it will give us // canonical output, which will also make testing easier. m, mu := ep.extensionsRead() if m == nil { return nil } mu.Lock() ids := make([]int32, 0, len(m)) for id := range m { ids = append(ids, id) } sort.Sort(int32Slice(ids)) mu.Unlock() for _, extNum := range ids { ext := m[extNum] var desc *ExtensionDesc if emap != nil { desc = emap[extNum] } if desc == nil { // Unknown extension. if err := writeUnknownStruct(w, ext.enc); err != nil { return err } continue } pb, err := GetExtension(ep, desc) if err != nil { return fmt.Errorf("failed getting extension: %v", err) } // Repeated extensions will appear as a slice. if !desc.repeated() { if err := tm.writeExtension(w, desc.Name, pb); err != nil { return err } } else { v := reflect.ValueOf(pb) for i := 0; i < v.Len(); i++ { if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { return err } } } } return nil } func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } return nil } func (w *textWriter) writeIndent() { if !w.complete { return } remain := w.ind * 2 for remain > 0 { n := remain if n > len(spaces) { n = len(spaces) } w.w.Write(spaces[:n]) remain -= n } w.complete = false } // TextMarshaler is a configurable text format marshaler. type TextMarshaler struct { Compact bool // use compact text format (one line). ExpandAny bool // expand google.protobuf.Any messages of known types } // Marshal writes a given protocol buffer in text format. // The only errors returned are from w. func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { val := reflect.ValueOf(pb) if pb == nil || val.IsNil() { w.Write([]byte("")) return nil } var bw *bufio.Writer ww, ok := w.(writer) if !ok { bw = bufio.NewWriter(w) ww = bw } aw := &textWriter{ w: ww, complete: true, compact: tm.Compact, } if etm, ok := pb.(encoding.TextMarshaler); ok { text, err := etm.MarshalText() if err != nil { return err } if _, err = aw.Write(text); err != nil { return err } if bw != nil { return bw.Flush() } return nil } // Dereference the received pointer so we don't have outer < and >. v := reflect.Indirect(val) if err := tm.writeStruct(aw, v); err != nil { return err } if bw != nil { return bw.Flush() } return nil } // Text is the same as Marshal, but returns the string directly. func (tm *TextMarshaler) Text(pb Message) string { var buf bytes.Buffer tm.Marshal(&buf, pb) return buf.String() } var ( defaultTextMarshaler = TextMarshaler{} compactTextMarshaler = TextMarshaler{Compact: true} ) // TODO: consider removing some of the Marshal functions below. // MarshalText writes a given protocol buffer in text format. // The only errors returned are from w. func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } // MarshalTextString is the same as MarshalText, but returns the string directly. func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } // CompactText writes a given protocol buffer in compact text format (one line). func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } // CompactTextString is the same as CompactText, but returns the string directly. func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) } ================================================ FILE: src/github.com/golang/protobuf/proto/text_parser.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto // Functions for parsing the Text protocol buffer format. // TODO: message sets. import ( "encoding" "errors" "fmt" "reflect" "strconv" "strings" "unicode/utf8" ) // Error string emitted when deserializing Any and fields are already set const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" type ParseError struct { Message string Line int // 1-based line number Offset int // 0-based byte offset from start of input } func (p *ParseError) Error() string { if p.Line == 1 { // show offset only for first line return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) } return fmt.Sprintf("line %d: %v", p.Line, p.Message) } type token struct { value string err *ParseError line int // line number offset int // byte number from start of input, not start of line unquoted string // the unquoted version of value, if it was a quoted string } func (t *token) String() string { if t.err == nil { return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) } return fmt.Sprintf("parse error: %v", t.err) } type textParser struct { s string // remaining input done bool // whether the parsing is finished (success or error) backed bool // whether back() was called offset, line int cur token } func newTextParser(s string) *textParser { p := new(textParser) p.s = s p.line = 1 p.cur.line = 1 return p } func (p *textParser) errorf(format string, a ...interface{}) *ParseError { pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} p.cur.err = pe p.done = true return pe } // Numbers and identifiers are matched by [-+._A-Za-z0-9] func isIdentOrNumberChar(c byte) bool { switch { case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': return true case '0' <= c && c <= '9': return true } switch c { case '-', '+', '.', '_': return true } return false } func isWhitespace(c byte) bool { switch c { case ' ', '\t', '\n', '\r': return true } return false } func isQuote(c byte) bool { switch c { case '"', '\'': return true } return false } func (p *textParser) skipWhitespace() { i := 0 for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { if p.s[i] == '#' { // comment; skip to end of line or input for i < len(p.s) && p.s[i] != '\n' { i++ } if i == len(p.s) { break } } if p.s[i] == '\n' { p.line++ } i++ } p.offset += i p.s = p.s[i:len(p.s)] if len(p.s) == 0 { p.done = true } } func (p *textParser) advance() { // Skip whitespace p.skipWhitespace() if p.done { return } // Start of non-whitespace p.cur.err = nil p.cur.offset, p.cur.line = p.offset, p.line p.cur.unquoted = "" switch p.s[0] { case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': // Single symbol p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] case '"', '\'': // Quoted string i := 1 for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { if p.s[i] == '\\' && i+1 < len(p.s) { // skip escaped char i++ } i++ } if i >= len(p.s) || p.s[i] != p.s[0] { p.errorf("unmatched quote") return } unq, err := unquoteC(p.s[1:i], rune(p.s[0])) if err != nil { p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) return } p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] p.cur.unquoted = unq default: i := 0 for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { i++ } if i == 0 { p.errorf("unexpected byte %#x", p.s[0]) return } p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] } p.offset += len(p.cur.value) } var ( errBadUTF8 = errors.New("proto: bad UTF-8") errBadHex = errors.New("proto: bad hexadecimal") ) func unquoteC(s string, quote rune) (string, error) { // This is based on C++'s tokenizer.cc. // Despite its name, this is *not* parsing C syntax. // For instance, "\0" is an invalid quoted string. // Avoid allocation in trivial cases. simple := true for _, r := range s { if r == '\\' || r == quote { simple = false break } } if simple { return s, nil } buf := make([]byte, 0, 3*len(s)/2) for len(s) > 0 { r, n := utf8.DecodeRuneInString(s) if r == utf8.RuneError && n == 1 { return "", errBadUTF8 } s = s[n:] if r != '\\' { if r < utf8.RuneSelf { buf = append(buf, byte(r)) } else { buf = append(buf, string(r)...) } continue } ch, tail, err := unescape(s) if err != nil { return "", err } buf = append(buf, ch...) s = tail } return string(buf), nil } func unescape(s string) (ch string, tail string, err error) { r, n := utf8.DecodeRuneInString(s) if r == utf8.RuneError && n == 1 { return "", "", errBadUTF8 } s = s[n:] switch r { case 'a': return "\a", s, nil case 'b': return "\b", s, nil case 'f': return "\f", s, nil case 'n': return "\n", s, nil case 'r': return "\r", s, nil case 't': return "\t", s, nil case 'v': return "\v", s, nil case '?': return "?", s, nil // trigraph workaround case '\'', '"', '\\': return string(r), s, nil case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X': if len(s) < 2 { return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) } base := 8 ss := s[:2] s = s[2:] if r == 'x' || r == 'X' { base = 16 } else { ss = string(r) + ss } i, err := strconv.ParseUint(ss, base, 8) if err != nil { return "", "", err } return string([]byte{byte(i)}), s, nil case 'u', 'U': n := 4 if r == 'U' { n = 8 } if len(s) < n { return "", "", fmt.Errorf(`\%c requires %d digits`, r, n) } bs := make([]byte, n/2) for i := 0; i < n; i += 2 { a, ok1 := unhex(s[i]) b, ok2 := unhex(s[i+1]) if !ok1 || !ok2 { return "", "", errBadHex } bs[i/2] = a<<4 | b } s = s[n:] return string(bs), s, nil } return "", "", fmt.Errorf(`unknown escape \%c`, r) } // Adapted from src/pkg/strconv/quote.go. func unhex(b byte) (v byte, ok bool) { switch { case '0' <= b && b <= '9': return b - '0', true case 'a' <= b && b <= 'f': return b - 'a' + 10, true case 'A' <= b && b <= 'F': return b - 'A' + 10, true } return 0, false } // Back off the parser by one token. Can only be done between calls to next(). // It makes the next advance() a no-op. func (p *textParser) back() { p.backed = true } // Advances the parser and returns the new current token. func (p *textParser) next() *token { if p.backed || p.done { p.backed = false return &p.cur } p.advance() if p.done { p.cur.value = "" } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { // Look for multiple quoted strings separated by whitespace, // and concatenate them. cat := p.cur for { p.skipWhitespace() if p.done || !isQuote(p.s[0]) { break } p.advance() if p.cur.err != nil { return &p.cur } cat.value += " " + p.cur.value cat.unquoted += p.cur.unquoted } p.done = false // parser may have seen EOF, but we want to return cat p.cur = cat } return &p.cur } func (p *textParser) consumeToken(s string) error { tok := p.next() if tok.err != nil { return tok.err } if tok.value != s { p.back() return p.errorf("expected %q, found %q", s, tok.value) } return nil } // Return a RequiredNotSetError indicating which required field was not set. func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { st := sv.Type() sprops := GetProperties(st) for i := 0; i < st.NumField(); i++ { if !isNil(sv.Field(i)) { continue } props := sprops.Prop[i] if props.Required { return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} } } return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen } // Returns the index in the struct for the named field, as well as the parsed tag properties. func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { i, ok := sprops.decoderOrigNames[name] if ok { return i, sprops.Prop[i], true } return -1, nil, false } // Consume a ':' from the input stream (if the next token is a colon), // returning an error if a colon is needed but not present. func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { tok := p.next() if tok.err != nil { return tok.err } if tok.value != ":" { // Colon is optional when the field is a group or message. needColon := true switch props.Wire { case "group": needColon = false case "bytes": // A "bytes" field is either a message, a string, or a repeated field; // those three become *T, *string and []T respectively, so we can check for // this field being a pointer to a non-string. if typ.Kind() == reflect.Ptr { // *T or *string if typ.Elem().Kind() == reflect.String { break } } else if typ.Kind() == reflect.Slice { // []T or []*T if typ.Elem().Kind() != reflect.Ptr { break } } else if typ.Kind() == reflect.String { // The proto3 exception is for a string field, // which requires a colon. break } needColon = false } if needColon { return p.errorf("expected ':', found %q", tok.value) } p.back() } return nil } func (p *textParser) readStruct(sv reflect.Value, terminator string) error { st := sv.Type() sprops := GetProperties(st) reqCount := sprops.reqCount var reqFieldErr error fieldSet := make(map[string]bool) // A struct is a sequence of "name: value", terminated by one of // '>' or '}', or the end of the input. A name may also be // "[extension]" or "[type/url]". // // The whole struct can also be an expanded Any message, like: // [type/url] < ... struct contents ... > for { tok := p.next() if tok.err != nil { return tok.err } if tok.value == terminator { break } if tok.value == "[" { // Looks like an extension or an Any. // // TODO: Check whether we need to handle // namespace rooted names (e.g. ".something.Foo"). extName, err := p.consumeExtName() if err != nil { return err } if s := strings.LastIndex(extName, "/"); s >= 0 { // If it contains a slash, it's an Any type URL. messageName := extName[s+1:] mt := MessageType(messageName) if mt == nil { return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) } tok = p.next() if tok.err != nil { return tok.err } // consume an optional colon if tok.value == ":" { tok = p.next() if tok.err != nil { return tok.err } } var terminator string switch tok.value { case "<": terminator = ">" case "{": terminator = "}" default: return p.errorf("expected '{' or '<', found %q", tok.value) } v := reflect.New(mt.Elem()) if pe := p.readStruct(v.Elem(), terminator); pe != nil { return pe } b, err := Marshal(v.Interface().(Message)) if err != nil { return p.errorf("failed to marshal message of type %q: %v", messageName, err) } if fieldSet["type_url"] { return p.errorf(anyRepeatedlyUnpacked, "type_url") } if fieldSet["value"] { return p.errorf(anyRepeatedlyUnpacked, "value") } sv.FieldByName("TypeUrl").SetString(extName) sv.FieldByName("Value").SetBytes(b) fieldSet["type_url"] = true fieldSet["value"] = true continue } var desc *ExtensionDesc // This could be faster, but it's functional. // TODO: Do something smarter than a linear scan. for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { if d.Name == extName { desc = d break } } if desc == nil { return p.errorf("unrecognized extension %q", extName) } props := &Properties{} props.Parse(desc.Tag) typ := reflect.TypeOf(desc.ExtensionType) if err := p.checkForColon(props, typ); err != nil { return err } rep := desc.repeated() // Read the extension structure, and set it in // the value we're constructing. var ext reflect.Value if !rep { ext = reflect.New(typ).Elem() } else { ext = reflect.New(typ.Elem()).Elem() } if err := p.readAny(ext, props); err != nil { if _, ok := err.(*RequiredNotSetError); !ok { return err } reqFieldErr = err } ep := sv.Addr().Interface().(Message) if !rep { SetExtension(ep, desc, ext.Interface()) } else { old, err := GetExtension(ep, desc) var sl reflect.Value if err == nil { sl = reflect.ValueOf(old) // existing slice } else { sl = reflect.MakeSlice(typ, 0, 1) } sl = reflect.Append(sl, ext) SetExtension(ep, desc, sl.Interface()) } if err := p.consumeOptionalSeparator(); err != nil { return err } continue } // This is a normal, non-extension field. name := tok.value var dst reflect.Value fi, props, ok := structFieldByName(sprops, name) if ok { dst = sv.Field(fi) } else if oop, ok := sprops.OneofTypes[name]; ok { // It is a oneof. props = oop.Prop nv := reflect.New(oop.Type.Elem()) dst = nv.Elem().Field(0) field := sv.Field(oop.Field) if !field.IsNil() { return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) } field.Set(nv) } if !dst.IsValid() { return p.errorf("unknown field name %q in %v", name, st) } if dst.Kind() == reflect.Map { // Consume any colon. if err := p.checkForColon(props, dst.Type()); err != nil { return err } // Construct the map if it doesn't already exist. if dst.IsNil() { dst.Set(reflect.MakeMap(dst.Type())) } key := reflect.New(dst.Type().Key()).Elem() val := reflect.New(dst.Type().Elem()).Elem() // The map entry should be this sequence of tokens: // < key : KEY value : VALUE > // However, implementations may omit key or value, and technically // we should support them in any order. See b/28924776 for a time // this went wrong. tok := p.next() var terminator string switch tok.value { case "<": terminator = ">" case "{": terminator = "}" default: return p.errorf("expected '{' or '<', found %q", tok.value) } for { tok := p.next() if tok.err != nil { return tok.err } if tok.value == terminator { break } switch tok.value { case "key": if err := p.consumeToken(":"); err != nil { return err } if err := p.readAny(key, props.mkeyprop); err != nil { return err } if err := p.consumeOptionalSeparator(); err != nil { return err } case "value": if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil { return err } if err := p.readAny(val, props.mvalprop); err != nil { return err } if err := p.consumeOptionalSeparator(); err != nil { return err } default: p.back() return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) } } dst.SetMapIndex(key, val) continue } // Check that it's not already set if it's not a repeated field. if !props.Repeated && fieldSet[name] { return p.errorf("non-repeated field %q was repeated", name) } if err := p.checkForColon(props, dst.Type()); err != nil { return err } // Parse into the field. fieldSet[name] = true if err := p.readAny(dst, props); err != nil { if _, ok := err.(*RequiredNotSetError); !ok { return err } reqFieldErr = err } if props.Required { reqCount-- } if err := p.consumeOptionalSeparator(); err != nil { return err } } if reqCount > 0 { return p.missingRequiredFieldError(sv) } return reqFieldErr } // consumeExtName consumes extension name or expanded Any type URL and the // following ']'. It returns the name or URL consumed. func (p *textParser) consumeExtName() (string, error) { tok := p.next() if tok.err != nil { return "", tok.err } // If extension name or type url is quoted, it's a single token. if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) if err != nil { return "", err } return name, p.consumeToken("]") } // Consume everything up to "]" var parts []string for tok.value != "]" { parts = append(parts, tok.value) tok = p.next() if tok.err != nil { return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) } } return strings.Join(parts, ""), nil } // consumeOptionalSeparator consumes an optional semicolon or comma. // It is used in readStruct to provide backward compatibility. func (p *textParser) consumeOptionalSeparator() error { tok := p.next() if tok.err != nil { return tok.err } if tok.value != ";" && tok.value != "," { p.back() } return nil } func (p *textParser) readAny(v reflect.Value, props *Properties) error { tok := p.next() if tok.err != nil { return tok.err } if tok.value == "" { return p.errorf("unexpected EOF") } switch fv := v; fv.Kind() { case reflect.Slice: at := v.Type() if at.Elem().Kind() == reflect.Uint8 { // Special case for []byte if tok.value[0] != '"' && tok.value[0] != '\'' { // Deliberately written out here, as the error after // this switch statement would write "invalid []byte: ...", // which is not as user-friendly. return p.errorf("invalid string: %v", tok.value) } bytes := []byte(tok.unquoted) fv.Set(reflect.ValueOf(bytes)) return nil } // Repeated field. if tok.value == "[" { // Repeated field with list notation, like [1,2,3]. for { fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) err := p.readAny(fv.Index(fv.Len()-1), props) if err != nil { return err } tok := p.next() if tok.err != nil { return tok.err } if tok.value == "]" { break } if tok.value != "," { return p.errorf("Expected ']' or ',' found %q", tok.value) } } return nil } // One value of the repeated field. p.back() fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) return p.readAny(fv.Index(fv.Len()-1), props) case reflect.Bool: // true/1/t/True or false/f/0/False. switch tok.value { case "true", "1", "t", "True": fv.SetBool(true) return nil case "false", "0", "f", "False": fv.SetBool(false) return nil } case reflect.Float32, reflect.Float64: v := tok.value // Ignore 'f' for compatibility with output generated by C++, but don't // remove 'f' when the value is "-inf" or "inf". if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { v = v[:len(v)-1] } if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { fv.SetFloat(f) return nil } case reflect.Int32: if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { fv.SetInt(x) return nil } if len(props.Enum) == 0 { break } m, ok := enumValueMaps[props.Enum] if !ok { break } x, ok := m[tok.value] if !ok { break } fv.SetInt(int64(x)) return nil case reflect.Int64: if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { fv.SetInt(x) return nil } case reflect.Ptr: // A basic field (indirected through pointer), or a repeated message/group p.back() fv.Set(reflect.New(fv.Type().Elem())) return p.readAny(fv.Elem(), props) case reflect.String: if tok.value[0] == '"' || tok.value[0] == '\'' { fv.SetString(tok.unquoted) return nil } case reflect.Struct: var terminator string switch tok.value { case "{": terminator = "}" case "<": terminator = ">" default: return p.errorf("expected '{' or '<', found %q", tok.value) } // TODO: Handle nested messages which implement encoding.TextUnmarshaler. return p.readStruct(fv, terminator) case reflect.Uint32: if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { fv.SetUint(x) return nil } case reflect.Uint64: if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { fv.SetUint(x) return nil } } return p.errorf("invalid %v: %v", v.Type(), tok.value) } // UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb // before starting to unmarshal, so any existing data in pb is always removed. // If a required field is not set and no other error occurs, // UnmarshalText returns *RequiredNotSetError. func UnmarshalText(s string, pb Message) error { if um, ok := pb.(encoding.TextUnmarshaler); ok { err := um.UnmarshalText([]byte(s)) return err } pb.Reset() v := reflect.ValueOf(pb) if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil { return pe } return nil } ================================================ FILE: src/github.com/golang/protobuf/proto/text_parser_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto_test import ( "math" "reflect" "testing" . "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" . "github.com/golang/protobuf/proto/testdata" ) type UnmarshalTextTest struct { in string err string // if "", no error expected out *MyMessage } func buildExtStructTest(text string) UnmarshalTextTest { msg := &MyMessage{ Count: Int32(42), } SetExtension(msg, E_Ext_More, &Ext{ Data: String("Hello, world!"), }) return UnmarshalTextTest{in: text, out: msg} } func buildExtDataTest(text string) UnmarshalTextTest { msg := &MyMessage{ Count: Int32(42), } SetExtension(msg, E_Ext_Text, String("Hello, world!")) SetExtension(msg, E_Ext_Number, Int32(1729)) return UnmarshalTextTest{in: text, out: msg} } func buildExtRepStringTest(text string) UnmarshalTextTest { msg := &MyMessage{ Count: Int32(42), } if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { panic(err) } return UnmarshalTextTest{in: text, out: msg} } var unMarshalTextTests = []UnmarshalTextTest{ // Basic { in: " count:42\n name:\"Dave\" ", out: &MyMessage{ Count: Int32(42), Name: String("Dave"), }, }, // Empty quoted string { in: `count:42 name:""`, out: &MyMessage{ Count: Int32(42), Name: String(""), }, }, // Quoted string concatenation with double quotes { in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, // Quoted string concatenation with single quotes { in: "count:42 name: 'My name is '\n'elsewhere'", out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, // Quoted string concatenations with mixed quotes { in: "count:42 name: 'My name is '\n\"elsewhere\"", out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, { in: "count:42 name: \"My name is \"\n'elsewhere'", out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, // Quoted string with escaped apostrophe { in: `count:42 name: "HOLIDAY - New Year\'s Day"`, out: &MyMessage{ Count: Int32(42), Name: String("HOLIDAY - New Year's Day"), }, }, // Quoted string with single quote { in: `count:42 name: 'Roger "The Ramster" Ramjet'`, out: &MyMessage{ Count: Int32(42), Name: String(`Roger "The Ramster" Ramjet`), }, }, // Quoted string with all the accepted special characters from the C++ test { in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", out: &MyMessage{ Count: Int32(42), Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), }, }, // Quoted string with quoted backslash { in: `count:42 name: "\\'xyz"`, out: &MyMessage{ Count: Int32(42), Name: String(`\'xyz`), }, }, // Quoted string with UTF-8 bytes. { in: "count:42 name: '\303\277\302\201\xAB'", out: &MyMessage{ Count: Int32(42), Name: String("\303\277\302\201\xAB"), }, }, // Bad quoted string { in: `inner: < host: "\0" >` + "\n", err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, }, // Number too large for int64 { in: "count: 1 others { key: 123456789012345678901 }", err: "line 1.23: invalid int64: 123456789012345678901", }, // Number too large for int32 { in: "count: 1234567890123", err: "line 1.7: invalid int32: 1234567890123", }, // Number in hexadecimal { in: "count: 0x2beef", out: &MyMessage{ Count: Int32(0x2beef), }, }, // Number in octal { in: "count: 024601", out: &MyMessage{ Count: Int32(024601), }, }, // Floating point number with "f" suffix { in: "count: 4 others:< weight: 17.0f >", out: &MyMessage{ Count: Int32(4), Others: []*OtherMessage{ { Weight: Float32(17), }, }, }, }, // Floating point positive infinity { in: "count: 4 bigfloat: inf", out: &MyMessage{ Count: Int32(4), Bigfloat: Float64(math.Inf(1)), }, }, // Floating point negative infinity { in: "count: 4 bigfloat: -inf", out: &MyMessage{ Count: Int32(4), Bigfloat: Float64(math.Inf(-1)), }, }, // Number too large for float32 { in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", }, // Number posing as a quoted string { in: `inner: < host: 12 >` + "\n", err: `line 1.15: invalid string: 12`, }, // Quoted string posing as int32 { in: `count: "12"`, err: `line 1.7: invalid int32: "12"`, }, // Quoted string posing a float32 { in: `others:< weight: "17.4" >`, err: `line 1.17: invalid float32: "17.4"`, }, // Enum { in: `count:42 bikeshed: BLUE`, out: &MyMessage{ Count: Int32(42), Bikeshed: MyMessage_BLUE.Enum(), }, }, // Repeated field { in: `count:42 pet: "horsey" pet:"bunny"`, out: &MyMessage{ Count: Int32(42), Pet: []string{"horsey", "bunny"}, }, }, // Repeated field with list notation { in: `count:42 pet: ["horsey", "bunny"]`, out: &MyMessage{ Count: Int32(42), Pet: []string{"horsey", "bunny"}, }, }, // Repeated message with/without colon and <>/{} { in: `count:42 others:{} others{} others:<> others:{}`, out: &MyMessage{ Count: Int32(42), Others: []*OtherMessage{ {}, {}, {}, {}, }, }, }, // Missing colon for inner message { in: `count:42 inner < host: "cauchy.syd" >`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("cauchy.syd"), }, }, }, // Missing colon for string field { in: `name "Dave"`, err: `line 1.5: expected ':', found "\"Dave\""`, }, // Missing colon for int32 field { in: `count 42`, err: `line 1.6: expected ':', found "42"`, }, // Missing required field { in: `name: "Pawel"`, err: `proto: required field "testdata.MyMessage.count" not set`, out: &MyMessage{ Name: String("Pawel"), }, }, // Missing required field in a required submessage { in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`, err: `proto: required field "testdata.InnerMessage.host" not set`, out: &MyMessage{ Count: Int32(42), WeMustGoDeeper: &RequiredInnerMessage{LeoFinallyWonAnOscar: &InnerMessage{}}, }, }, // Repeated non-repeated field { in: `name: "Rob" name: "Russ"`, err: `line 1.12: non-repeated field "name" was repeated`, }, // Group { in: `count: 17 SomeGroup { group_field: 12 }`, out: &MyMessage{ Count: Int32(17), Somegroup: &MyMessage_SomeGroup{ GroupField: Int32(12), }, }, }, // Semicolon between fields { in: `count:3;name:"Calvin"`, out: &MyMessage{ Count: Int32(3), Name: String("Calvin"), }, }, // Comma between fields { in: `count:4,name:"Ezekiel"`, out: &MyMessage{ Count: Int32(4), Name: String("Ezekiel"), }, }, // Boolean false { in: `count:42 inner { host: "example.com" connected: false }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(false), }, }, }, // Boolean true { in: `count:42 inner { host: "example.com" connected: true }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(true), }, }, }, // Boolean 0 { in: `count:42 inner { host: "example.com" connected: 0 }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(false), }, }, }, // Boolean 1 { in: `count:42 inner { host: "example.com" connected: 1 }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(true), }, }, }, // Boolean f { in: `count:42 inner { host: "example.com" connected: f }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(false), }, }, }, // Boolean t { in: `count:42 inner { host: "example.com" connected: t }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(true), }, }, }, // Boolean False { in: `count:42 inner { host: "example.com" connected: False }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(false), }, }, }, // Boolean True { in: `count:42 inner { host: "example.com" connected: True }`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("example.com"), Connected: Bool(true), }, }, }, // Extension buildExtStructTest(`count: 42 [testdata.Ext.more]:`), buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), // Big all-in-one { in: "count:42 # Meaning\n" + `name:"Dave" ` + `quote:"\"I didn't want to go.\"" ` + `pet:"bunny" ` + `pet:"kitty" ` + `pet:"horsey" ` + `inner:<` + ` host:"footrest.syd" ` + ` port:7001 ` + ` connected:true ` + `> ` + `others:<` + ` key:3735928559 ` + ` value:"\x01A\a\f" ` + `> ` + `others:<` + " weight:58.9 # Atomic weight of Co\n" + ` inner:<` + ` host:"lesha.mtv" ` + ` port:8002 ` + ` >` + `>`, out: &MyMessage{ Count: Int32(42), Name: String("Dave"), Quote: String(`"I didn't want to go."`), Pet: []string{"bunny", "kitty", "horsey"}, Inner: &InnerMessage{ Host: String("footrest.syd"), Port: Int32(7001), Connected: Bool(true), }, Others: []*OtherMessage{ { Key: Int64(3735928559), Value: []byte{0x1, 'A', '\a', '\f'}, }, { Weight: Float32(58.9), Inner: &InnerMessage{ Host: String("lesha.mtv"), Port: Int32(8002), }, }, }, }, }, } func TestUnmarshalText(t *testing.T) { for i, test := range unMarshalTextTests { pb := new(MyMessage) err := UnmarshalText(test.in, pb) if test.err == "" { // We don't expect failure. if err != nil { t.Errorf("Test %d: Unexpected error: %v", i, err) } else if !reflect.DeepEqual(pb, test.out) { t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", i, pb, test.out) } } else { // We do expect failure. if err == nil { t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) } else if err.Error() != test.err { t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", i, err.Error(), test.err) } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", i, pb, test.out) } } } } func TestUnmarshalTextCustomMessage(t *testing.T) { msg := &textMessage{} if err := UnmarshalText("custom", msg); err != nil { t.Errorf("Unexpected error from custom unmarshal: %v", err) } if UnmarshalText("not custom", msg) == nil { t.Errorf("Didn't get expected error from custom unmarshal") } } // Regression test; this caused a panic. func TestRepeatedEnum(t *testing.T) { pb := new(RepeatedEnum) if err := UnmarshalText("color: RED", pb); err != nil { t.Fatal(err) } exp := &RepeatedEnum{ Color: []RepeatedEnum_Color{RepeatedEnum_RED}, } if !Equal(pb, exp) { t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) } } func TestProto3TextParsing(t *testing.T) { m := new(proto3pb.Message) const in = `name: "Wallace" true_scotsman: true` want := &proto3pb.Message{ Name: "Wallace", TrueScotsman: true, } if err := UnmarshalText(in, m); err != nil { t.Fatal(err) } if !Equal(m, want) { t.Errorf("\n got %v\nwant %v", m, want) } } func TestMapParsing(t *testing.T) { m := new(MessageWithMap) const in = `name_mapping: name_mapping:` + `msg_mapping:,>` + // separating commas are okay `msg_mapping>` + // no colon after "value" `msg_mapping:>` + // omitted key `msg_mapping:` + // omitted value `byte_mapping:` + `byte_mapping:<>` // omitted key and value want := &MessageWithMap{ NameMapping: map[int32]string{ 1: "Beatles", 1234: "Feist", }, MsgMapping: map[int64]*FloatingPoint{ -4: {F: Float64(2.0)}, -2: {F: Float64(4.0)}, 0: {F: Float64(5.0)}, 1: nil, }, ByteMapping: map[bool][]byte{ false: nil, true: []byte("so be it"), }, } if err := UnmarshalText(in, m); err != nil { t.Fatal(err) } if !Equal(m, want) { t.Errorf("\n got %v\nwant %v", m, want) } } func TestOneofParsing(t *testing.T) { const in = `name:"Shrek"` m := new(Communique) want := &Communique{Union: &Communique_Name{"Shrek"}} if err := UnmarshalText(in, m); err != nil { t.Fatal(err) } if !Equal(m, want) { t.Errorf("\n got %v\nwant %v", m, want) } const inOverwrite = `name:"Shrek" number:42` m = new(Communique) testErr := "line 1.13: field 'number' would overwrite already parsed oneof 'Union'" if err := UnmarshalText(inOverwrite, m); err == nil { t.Errorf("TestOneofParsing: Didn't get expected error: %v", testErr) } else if err.Error() != testErr { t.Errorf("TestOneofParsing: Incorrect error.\nHave: %v\nWant: %v", err.Error(), testErr) } } var benchInput string func init() { benchInput = "count: 4\n" for i := 0; i < 1000; i++ { benchInput += "pet: \"fido\"\n" } // Check it is valid input. pb := new(MyMessage) err := UnmarshalText(benchInput, pb) if err != nil { panic("Bad benchmark input: " + err.Error()) } } func BenchmarkUnmarshalText(b *testing.B) { pb := new(MyMessage) for i := 0; i < b.N; i++ { UnmarshalText(benchInput, pb) } b.SetBytes(int64(len(benchInput))) } ================================================ FILE: src/github.com/golang/protobuf/proto/text_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. package proto_test import ( "bytes" "errors" "io/ioutil" "math" "strings" "testing" "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" pb "github.com/golang/protobuf/proto/testdata" ) // textMessage implements the methods that allow it to marshal and unmarshal // itself as text. type textMessage struct { } func (*textMessage) MarshalText() ([]byte, error) { return []byte("custom"), nil } func (*textMessage) UnmarshalText(bytes []byte) error { if string(bytes) != "custom" { return errors.New("expected 'custom'") } return nil } func (*textMessage) Reset() {} func (*textMessage) String() string { return "" } func (*textMessage) ProtoMessage() {} func newTestMessage() *pb.MyMessage { msg := &pb.MyMessage{ Count: proto.Int32(42), Name: proto.String("Dave"), Quote: proto.String(`"I didn't want to go."`), Pet: []string{"bunny", "kitty", "horsey"}, Inner: &pb.InnerMessage{ Host: proto.String("footrest.syd"), Port: proto.Int32(7001), Connected: proto.Bool(true), }, Others: []*pb.OtherMessage{ { Key: proto.Int64(0xdeadbeef), Value: []byte{1, 65, 7, 12}, }, { Weight: proto.Float32(6.022), Inner: &pb.InnerMessage{ Host: proto.String("lesha.mtv"), Port: proto.Int32(8002), }, }, }, Bikeshed: pb.MyMessage_BLUE.Enum(), Somegroup: &pb.MyMessage_SomeGroup{ GroupField: proto.Int32(8), }, // One normally wouldn't do this. // This is an undeclared tag 13, as a varint (wire type 0) with value 4. XXX_unrecognized: []byte{13<<3 | 0, 4}, } ext := &pb.Ext{ Data: proto.String("Big gobs for big rats"), } if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { panic(err) } greetings := []string{"adg", "easy", "cow"} if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { panic(err) } // Add an unknown extension. We marshal a pb.Ext, and fake the ID. b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) if err != nil { panic(err) } b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) proto.SetRawExtension(msg, 201, b) // Extensions can be plain fields, too, so let's test that. b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) proto.SetRawExtension(msg, 202, b) return msg } const text = `count: 42 name: "Dave" quote: "\"I didn't want to go.\"" pet: "bunny" pet: "kitty" pet: "horsey" inner: < host: "footrest.syd" port: 7001 connected: true > others: < key: 3735928559 value: "\001A\007\014" > others: < weight: 6.022 inner: < host: "lesha.mtv" port: 8002 > > bikeshed: BLUE SomeGroup { group_field: 8 } /* 2 unknown bytes */ 13: 4 [testdata.Ext.more]: < data: "Big gobs for big rats" > [testdata.greeting]: "adg" [testdata.greeting]: "easy" [testdata.greeting]: "cow" /* 13 unknown bytes */ 201: "\t3G skiing" /* 3 unknown bytes */ 202: 19 ` func TestMarshalText(t *testing.T) { buf := new(bytes.Buffer) if err := proto.MarshalText(buf, newTestMessage()); err != nil { t.Fatalf("proto.MarshalText: %v", err) } s := buf.String() if s != text { t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) } } func TestMarshalTextCustomMessage(t *testing.T) { buf := new(bytes.Buffer) if err := proto.MarshalText(buf, &textMessage{}); err != nil { t.Fatalf("proto.MarshalText: %v", err) } s := buf.String() if s != "custom" { t.Errorf("Got %q, expected %q", s, "custom") } } func TestMarshalTextNil(t *testing.T) { want := "" tests := []proto.Message{nil, (*pb.MyMessage)(nil)} for i, test := range tests { buf := new(bytes.Buffer) if err := proto.MarshalText(buf, test); err != nil { t.Fatal(err) } if got := buf.String(); got != want { t.Errorf("%d: got %q want %q", i, got, want) } } } func TestMarshalTextUnknownEnum(t *testing.T) { // The Color enum only specifies values 0-2. m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} got := m.String() const want = `bikeshed:3 ` if got != want { t.Errorf("\n got %q\nwant %q", got, want) } } func TestTextOneof(t *testing.T) { tests := []struct { m proto.Message want string }{ // zero message {&pb.Communique{}, ``}, // scalar field {&pb.Communique{Union: &pb.Communique_Number{4}}, `number:4`}, // message field {&pb.Communique{Union: &pb.Communique_Msg{ &pb.Strings{StringField: proto.String("why hello!")}, }}, `msg:`}, // bad oneof (should not panic) {&pb.Communique{Union: &pb.Communique_Msg{nil}}, `msg:/* nil */`}, } for _, test := range tests { got := strings.TrimSpace(test.m.String()) if got != test.want { t.Errorf("\n got %s\nwant %s", got, test.want) } } } func BenchmarkMarshalTextBuffered(b *testing.B) { buf := new(bytes.Buffer) m := newTestMessage() for i := 0; i < b.N; i++ { buf.Reset() proto.MarshalText(buf, m) } } func BenchmarkMarshalTextUnbuffered(b *testing.B) { w := ioutil.Discard m := newTestMessage() for i := 0; i < b.N; i++ { proto.MarshalText(w, m) } } func compact(src string) string { // s/[ \n]+/ /g; s/ $//; dst := make([]byte, len(src)) space, comment := false, false j := 0 for i := 0; i < len(src); i++ { if strings.HasPrefix(src[i:], "/*") { comment = true i++ continue } if comment && strings.HasPrefix(src[i:], "*/") { comment = false i++ continue } if comment { continue } c := src[i] if c == ' ' || c == '\n' { space = true continue } if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { space = false } if c == '{' { space = false } if space { dst[j] = ' ' j++ space = false } dst[j] = c j++ } if space { dst[j] = ' ' j++ } return string(dst[0:j]) } var compactText = compact(text) func TestCompactText(t *testing.T) { s := proto.CompactTextString(newTestMessage()) if s != compactText { t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) } } func TestStringEscaping(t *testing.T) { testCases := []struct { in *pb.Strings out string }{ { // Test data from C++ test (TextFormatTest.StringEscape). // Single divergence: we don't escape apostrophes. &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", }, { // Test data from the same C++ test. &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", }, { // Some UTF-8. &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, `string_field: "\000\001\377\201"` + "\n", }, } for i, tc := range testCases { var buf bytes.Buffer if err := proto.MarshalText(&buf, tc.in); err != nil { t.Errorf("proto.MarsalText: %v", err) continue } s := buf.String() if s != tc.out { t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) continue } // Check round-trip. pb := new(pb.Strings) if err := proto.UnmarshalText(s, pb); err != nil { t.Errorf("#%d: UnmarshalText: %v", i, err) continue } if !proto.Equal(pb, tc.in) { t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) } } } // A limitedWriter accepts some output before it fails. // This is a proxy for something like a nearly-full or imminently-failing disk, // or a network connection that is about to die. type limitedWriter struct { b bytes.Buffer limit int } var outOfSpace = errors.New("proto: insufficient space") func (w *limitedWriter) Write(p []byte) (n int, err error) { var avail = w.limit - w.b.Len() if avail <= 0 { return 0, outOfSpace } if len(p) <= avail { return w.b.Write(p) } n, _ = w.b.Write(p[:avail]) return n, outOfSpace } func TestMarshalTextFailing(t *testing.T) { // Try lots of different sizes to exercise more error code-paths. for lim := 0; lim < len(text); lim++ { buf := new(limitedWriter) buf.limit = lim err := proto.MarshalText(buf, newTestMessage()) // We expect a certain error, but also some partial results in the buffer. if err != outOfSpace { t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) } s := buf.b.String() x := text[:buf.limit] if s != x { t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) } } } func TestFloats(t *testing.T) { tests := []struct { f float64 want string }{ {0, "0"}, {4.7, "4.7"}, {math.Inf(1), "inf"}, {math.Inf(-1), "-inf"}, {math.NaN(), "nan"}, } for _, test := range tests { msg := &pb.FloatingPoint{F: &test.f} got := strings.TrimSpace(msg.String()) want := `f:` + test.want if got != want { t.Errorf("f=%f: got %q, want %q", test.f, got, want) } } } func TestRepeatedNilText(t *testing.T) { m := &pb.MessageList{ Message: []*pb.MessageList_Message{ nil, &pb.MessageList_Message{ Name: proto.String("Horse"), }, nil, }, } want := `Message Message { name: "Horse" } Message ` if s := proto.MarshalTextString(m); s != want { t.Errorf(" got: %s\nwant: %s", s, want) } } func TestProto3Text(t *testing.T) { tests := []struct { m proto.Message want string }{ // zero message {&proto3pb.Message{}, ``}, // zero message except for an empty byte slice {&proto3pb.Message{Data: []byte{}}, ``}, // trivial case {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, // empty map {&pb.MessageWithMap{}, ``}, // non-empty map; map format is the same as a repeated struct, // and they are sorted by key (numerically for numeric keys). { &pb.MessageWithMap{NameMapping: map[int32]string{ -1: "Negatory", 7: "Lucky", 1234: "Feist", 6345789: "Otis", }}, `name_mapping: ` + `name_mapping: ` + `name_mapping: ` + `name_mapping:`, }, // map with nil value; not well-defined, but we shouldn't crash { &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, `msg_mapping:`, }, } for _, test := range tests { got := strings.TrimSpace(test.m.String()) if got != test.want { t.Errorf("\n got %s\nwant %s", got, test.want) } } } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/Makefile ================================================ # Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/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: cd testdata && make test ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile ================================================ # Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/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. # Not stored here, but descriptor.proto is in https://github.com/google/protobuf/ # at src/google/protobuf/descriptor.proto regenerate: @echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION cp $(HOME)/src/protobuf/include/google/protobuf/descriptor.proto . protoc --go_out=../../../../.. -I$(HOME)/src/protobuf/include $(HOME)/src/protobuf/include/google/protobuf/descriptor.proto ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/descriptor.proto /* Package descriptor is a generated protocol buffer package. It is generated from these files: google/protobuf/descriptor.proto It has these top-level messages: FileDescriptorSet FileDescriptorProto DescriptorProto ExtensionRangeOptions FieldDescriptorProto OneofDescriptorProto EnumDescriptorProto EnumValueDescriptorProto ServiceDescriptorProto MethodDescriptorProto FileOptions MessageOptions FieldOptions OneofOptions EnumOptions EnumValueOptions ServiceOptions MethodOptions UninterpretedOption SourceCodeInfo GeneratedCodeInfo */ package descriptor import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type FieldDescriptorProto_Type int32 const ( // 0 is reserved for errors. // Order is weird for historical reasons. FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1 FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2 // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if // negative values are likely. FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3 FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4 // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if // negative values are likely. FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5 FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6 FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7 FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8 FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9 // Tag-delimited aggregate. // Group type is deprecated and not supported in proto3. However, Proto3 // implementations should still be able to parse the group wire format and // treat group fields as unknown fields. FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10 FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11 // New in version 2. FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12 FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13 FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14 FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15 FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16 FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17 FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18 ) var FieldDescriptorProto_Type_name = map[int32]string{ 1: "TYPE_DOUBLE", 2: "TYPE_FLOAT", 3: "TYPE_INT64", 4: "TYPE_UINT64", 5: "TYPE_INT32", 6: "TYPE_FIXED64", 7: "TYPE_FIXED32", 8: "TYPE_BOOL", 9: "TYPE_STRING", 10: "TYPE_GROUP", 11: "TYPE_MESSAGE", 12: "TYPE_BYTES", 13: "TYPE_UINT32", 14: "TYPE_ENUM", 15: "TYPE_SFIXED32", 16: "TYPE_SFIXED64", 17: "TYPE_SINT32", 18: "TYPE_SINT64", } var FieldDescriptorProto_Type_value = map[string]int32{ "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, } func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type { p := new(FieldDescriptorProto_Type) *p = x return p } func (x FieldDescriptorProto_Type) String() string { return proto.EnumName(FieldDescriptorProto_Type_name, int32(x)) } func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type") if err != nil { return err } *x = FieldDescriptorProto_Type(value) return nil } func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{4, 0} } type FieldDescriptorProto_Label int32 const ( // 0 is reserved for errors FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1 FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2 FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3 ) var FieldDescriptorProto_Label_name = map[int32]string{ 1: "LABEL_OPTIONAL", 2: "LABEL_REQUIRED", 3: "LABEL_REPEATED", } var FieldDescriptorProto_Label_value = map[string]int32{ "LABEL_OPTIONAL": 1, "LABEL_REQUIRED": 2, "LABEL_REPEATED": 3, } func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label { p := new(FieldDescriptorProto_Label) *p = x return p } func (x FieldDescriptorProto_Label) String() string { return proto.EnumName(FieldDescriptorProto_Label_name, int32(x)) } func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label") if err != nil { return err } *x = FieldDescriptorProto_Label(value) return nil } func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{4, 1} } // Generated classes can be optimized for speed or code size. type FileOptions_OptimizeMode int32 const ( FileOptions_SPEED FileOptions_OptimizeMode = 1 // etc. FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2 FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3 ) var FileOptions_OptimizeMode_name = map[int32]string{ 1: "SPEED", 2: "CODE_SIZE", 3: "LITE_RUNTIME", } var FileOptions_OptimizeMode_value = map[string]int32{ "SPEED": 1, "CODE_SIZE": 2, "LITE_RUNTIME": 3, } func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode { p := new(FileOptions_OptimizeMode) *p = x return p } func (x FileOptions_OptimizeMode) String() string { return proto.EnumName(FileOptions_OptimizeMode_name, int32(x)) } func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode") if err != nil { return err } *x = FileOptions_OptimizeMode(value) return nil } func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{10, 0} } type FieldOptions_CType int32 const ( // Default mode. FieldOptions_STRING FieldOptions_CType = 0 FieldOptions_CORD FieldOptions_CType = 1 FieldOptions_STRING_PIECE FieldOptions_CType = 2 ) var FieldOptions_CType_name = map[int32]string{ 0: "STRING", 1: "CORD", 2: "STRING_PIECE", } var FieldOptions_CType_value = map[string]int32{ "STRING": 0, "CORD": 1, "STRING_PIECE": 2, } func (x FieldOptions_CType) Enum() *FieldOptions_CType { p := new(FieldOptions_CType) *p = x return p } func (x FieldOptions_CType) String() string { return proto.EnumName(FieldOptions_CType_name, int32(x)) } func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType") if err != nil { return err } *x = FieldOptions_CType(value) return nil } func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{12, 0} } type FieldOptions_JSType int32 const ( // Use the default type. FieldOptions_JS_NORMAL FieldOptions_JSType = 0 // Use JavaScript strings. FieldOptions_JS_STRING FieldOptions_JSType = 1 // Use JavaScript numbers. FieldOptions_JS_NUMBER FieldOptions_JSType = 2 ) var FieldOptions_JSType_name = map[int32]string{ 0: "JS_NORMAL", 1: "JS_STRING", 2: "JS_NUMBER", } var FieldOptions_JSType_value = map[string]int32{ "JS_NORMAL": 0, "JS_STRING": 1, "JS_NUMBER": 2, } func (x FieldOptions_JSType) Enum() *FieldOptions_JSType { p := new(FieldOptions_JSType) *p = x return p } func (x FieldOptions_JSType) String() string { return proto.EnumName(FieldOptions_JSType_name, int32(x)) } func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType") if err != nil { return err } *x = FieldOptions_JSType(value) return nil } func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{12, 1} } // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, // or neither? HTTP based RPC implementation may choose GET verb for safe // methods, and PUT verb for idempotent methods instead of the default POST. type MethodOptions_IdempotencyLevel int32 const ( MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0 MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1 MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2 ) var MethodOptions_IdempotencyLevel_name = map[int32]string{ 0: "IDEMPOTENCY_UNKNOWN", 1: "NO_SIDE_EFFECTS", 2: "IDEMPOTENT", } var MethodOptions_IdempotencyLevel_value = map[string]int32{ "IDEMPOTENCY_UNKNOWN": 0, "NO_SIDE_EFFECTS": 1, "IDEMPOTENT": 2, } func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel { p := new(MethodOptions_IdempotencyLevel) *p = x return p } func (x MethodOptions_IdempotencyLevel) String() string { return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x)) } func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel") if err != nil { return err } *x = MethodOptions_IdempotencyLevel(value) return nil } func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{17, 0} } // The protocol compiler can output a FileDescriptorSet containing the .proto // files it parses. type FileDescriptorSet struct { File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} } func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) } func (*FileDescriptorSet) ProtoMessage() {} func (*FileDescriptorSet) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto { if m != nil { return m.File } return nil } // Describes a complete .proto file. type FileDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"` // Names of files imported by this file. Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"` // Indexes of the public imported files in the dependency list above. PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"` // Indexes of the weak imported files in the dependency list. // For Google-internal migration only. Do not use. WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"` // All top-level definitions in this file. MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"` EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"` Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"` Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` // This field contains optional information about the original source code. // You may safely remove this entire field without harming runtime // functionality of the descriptors -- the information is needed only by // development tools. SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"` // The syntax of the proto file. // The supported values are "proto2" and "proto3". Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} } func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) } func (*FileDescriptorProto) ProtoMessage() {} func (*FileDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *FileDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *FileDescriptorProto) GetPackage() string { if m != nil && m.Package != nil { return *m.Package } return "" } func (m *FileDescriptorProto) GetDependency() []string { if m != nil { return m.Dependency } return nil } func (m *FileDescriptorProto) GetPublicDependency() []int32 { if m != nil { return m.PublicDependency } return nil } func (m *FileDescriptorProto) GetWeakDependency() []int32 { if m != nil { return m.WeakDependency } return nil } func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto { if m != nil { return m.MessageType } return nil } func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto { if m != nil { return m.EnumType } return nil } func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto { if m != nil { return m.Service } return nil } func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto { if m != nil { return m.Extension } return nil } func (m *FileDescriptorProto) GetOptions() *FileOptions { if m != nil { return m.Options } return nil } func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo { if m != nil { return m.SourceCodeInfo } return nil } func (m *FileDescriptorProto) GetSyntax() string { if m != nil && m.Syntax != nil { return *m.Syntax } return "" } // Describes a message type. type DescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"` Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"` NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"` EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"` ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"` OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"` Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"` ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` // Reserved field names, which may not be used by fields in the same message. // A given name may only be reserved once. ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *DescriptorProto) Reset() { *m = DescriptorProto{} } func (m *DescriptorProto) String() string { return proto.CompactTextString(m) } func (*DescriptorProto) ProtoMessage() {} func (*DescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *DescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *DescriptorProto) GetField() []*FieldDescriptorProto { if m != nil { return m.Field } return nil } func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto { if m != nil { return m.Extension } return nil } func (m *DescriptorProto) GetNestedType() []*DescriptorProto { if m != nil { return m.NestedType } return nil } func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto { if m != nil { return m.EnumType } return nil } func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange { if m != nil { return m.ExtensionRange } return nil } func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto { if m != nil { return m.OneofDecl } return nil } func (m *DescriptorProto) GetOptions() *MessageOptions { if m != nil { return m.Options } return nil } func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange { if m != nil { return m.ReservedRange } return nil } func (m *DescriptorProto) GetReservedName() []string { if m != nil { return m.ReservedName } return nil } type DescriptorProto_ExtensionRange struct { Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} } func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) } func (*DescriptorProto_ExtensionRange) ProtoMessage() {} func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } func (m *DescriptorProto_ExtensionRange) GetStart() int32 { if m != nil && m.Start != nil { return *m.Start } return 0 } func (m *DescriptorProto_ExtensionRange) GetEnd() int32 { if m != nil && m.End != nil { return *m.End } return 0 } func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions { if m != nil { return m.Options } return nil } // Range of reserved tag numbers. Reserved tag numbers may not be used by // fields or extension ranges in the same message. Reserved ranges may // not overlap. type DescriptorProto_ReservedRange struct { Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} } func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) } func (*DescriptorProto_ReservedRange) ProtoMessage() {} func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 1} } func (m *DescriptorProto_ReservedRange) GetStart() int32 { if m != nil && m.Start != nil { return *m.Start } return 0 } func (m *DescriptorProto_ReservedRange) GetEnd() int32 { if m != nil && m.End != nil { return *m.End } return 0 } type ExtensionRangeOptions struct { // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} } func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) } func (*ExtensionRangeOptions) ProtoMessage() {} func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } var extRange_ExtensionRangeOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_ExtensionRangeOptions } func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } // Describes a field within a message. type FieldDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"` Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"` // If type_name is set, this need not be set. If both this and type_name // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"` // For message and enum types, this is the name of the type. If the name // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping // rules are used to find the type (i.e. first the nested types within this // message are searched, then within the parent, on up to the root // namespace). TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"` // For extensions, this is the name of the type being extended. It is // resolved in the same manner as type_name. Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"` // For numeric types, contains the original text representation of the value. // For booleans, "true" or "false". // For strings, contains the default text contents (not escaped in any way). // For bytes, contains the C escaped value. All bytes >= 128 are escaped. // TODO(kenton): Base-64 encode? DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"` // If set, gives the index of a oneof in the containing type's oneof_decl // list. This field is a member of that oneof. OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"` // JSON name of this field. The value is set by protocol compiler. If the // user has set a "json_name" option on this field, that option's value // will be used. Otherwise, it's deduced from the field's name by converting // it to camelCase. JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"` Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} } func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) } func (*FieldDescriptorProto) ProtoMessage() {} func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (m *FieldDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *FieldDescriptorProto) GetNumber() int32 { if m != nil && m.Number != nil { return *m.Number } return 0 } func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label { if m != nil && m.Label != nil { return *m.Label } return FieldDescriptorProto_LABEL_OPTIONAL } func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type { if m != nil && m.Type != nil { return *m.Type } return FieldDescriptorProto_TYPE_DOUBLE } func (m *FieldDescriptorProto) GetTypeName() string { if m != nil && m.TypeName != nil { return *m.TypeName } return "" } func (m *FieldDescriptorProto) GetExtendee() string { if m != nil && m.Extendee != nil { return *m.Extendee } return "" } func (m *FieldDescriptorProto) GetDefaultValue() string { if m != nil && m.DefaultValue != nil { return *m.DefaultValue } return "" } func (m *FieldDescriptorProto) GetOneofIndex() int32 { if m != nil && m.OneofIndex != nil { return *m.OneofIndex } return 0 } func (m *FieldDescriptorProto) GetJsonName() string { if m != nil && m.JsonName != nil { return *m.JsonName } return "" } func (m *FieldDescriptorProto) GetOptions() *FieldOptions { if m != nil { return m.Options } return nil } // Describes a oneof. type OneofDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} } func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) } func (*OneofDescriptorProto) ProtoMessage() {} func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } func (m *OneofDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *OneofDescriptorProto) GetOptions() *OneofOptions { if m != nil { return m.Options } return nil } // Describes an enum type. type EnumDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} } func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) } func (*EnumDescriptorProto) ProtoMessage() {} func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } func (m *EnumDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto { if m != nil { return m.Value } return nil } func (m *EnumDescriptorProto) GetOptions() *EnumOptions { if m != nil { return m.Options } return nil } // Describes a value within an enum. type EnumValueDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"` Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} } func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) } func (*EnumValueDescriptorProto) ProtoMessage() {} func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } func (m *EnumValueDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *EnumValueDescriptorProto) GetNumber() int32 { if m != nil && m.Number != nil { return *m.Number } return 0 } func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions { if m != nil { return m.Options } return nil } // Describes a service. type ServiceDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"` Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} } func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) } func (*ServiceDescriptorProto) ProtoMessage() {} func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } func (m *ServiceDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto { if m != nil { return m.Method } return nil } func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions { if m != nil { return m.Options } return nil } // Describes a method of a service. type MethodDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` // Input and output type names. These are resolved in the same way as // FieldDescriptorProto.type_name, but must refer to a message type. InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"` OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"` Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"` // Identifies if client streams multiple client messages ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"` // Identifies if server streams multiple server messages ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} } func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) } func (*MethodDescriptorProto) ProtoMessage() {} func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} } const Default_MethodDescriptorProto_ClientStreaming bool = false const Default_MethodDescriptorProto_ServerStreaming bool = false func (m *MethodDescriptorProto) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *MethodDescriptorProto) GetInputType() string { if m != nil && m.InputType != nil { return *m.InputType } return "" } func (m *MethodDescriptorProto) GetOutputType() string { if m != nil && m.OutputType != nil { return *m.OutputType } return "" } func (m *MethodDescriptorProto) GetOptions() *MethodOptions { if m != nil { return m.Options } return nil } func (m *MethodDescriptorProto) GetClientStreaming() bool { if m != nil && m.ClientStreaming != nil { return *m.ClientStreaming } return Default_MethodDescriptorProto_ClientStreaming } func (m *MethodDescriptorProto) GetServerStreaming() bool { if m != nil && m.ServerStreaming != nil { return *m.ServerStreaming } return Default_MethodDescriptorProto_ServerStreaming } type FileOptions struct { // Sets the Java package where classes generated from this .proto will be // placed. By default, the proto package is used, but this is often // inappropriate because proto packages do not normally start with backwards // domain names. JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"` // If set, all the classes from the .proto file are wrapped in a single // outer class with the given name. This applies to both Proto1 // (equivalent to the old "--one_java_file" option) and Proto2 (where // a .proto always translates to a single class, but you may want to // explicitly choose the class name). JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"` // If set true, then the Java code generator will generate a separate .java // file for each top-level message, enum, and service defined in the .proto // file. Thus, these types will *not* be nested inside the outer class // named by java_outer_classname. However, the outer class will still be // generated to contain the file's getDescriptor() method as well as any // top-level extensions defined in the file. JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"` // This option does nothing. JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` // If set true, then the Java2 code generator will generate code that // throws an exception whenever an attempt is made to assign a non-UTF-8 // byte sequence to a string field. // Message reflection will do the same. // However, an extension field still accepts non-UTF-8 byte sequences. // This option has no effect on when used with the lite runtime. JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"` OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"` // Sets the Go package where structs generated from this .proto will be // placed. If omitted, the Go package will be derived from the following: // - The basename of the package import path, if provided. // - Otherwise, the package statement in the .proto file, if present. // - Otherwise, the basename of the .proto file, without extension. GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"` // Should generic services be generated in each language? "Generic" services // are not specific to any particular RPC system. They are generated by the // main code generators in each language (without additional plugins). // Generic services were the only kind of service generation supported by // early versions of google.protobuf. // // Generic services are now considered deprecated in favor of using plugins // that generate code specific to your particular RPC system. Therefore, // these default to false. Old code which depends on generic services should // explicitly set them to true. CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"` JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"` PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"` PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"` // Is this file deprecated? // Depending on the target platform, this can emit Deprecated annotations // for everything in the file, or it will be completely ignored; in the very // least, this is a formalization for deprecating files. Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // Enables the use of arenas for the proto messages in this file. This applies // only to generated classes for C++. CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"` // Sets the objective c class prefix which is prepended to all objective c // generated classes from this .proto. There is no default. ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"` // Namespace for generated classes; defaults to the package. CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"` // By default Swift generators will take the proto package and CamelCase it // replacing '.' with underscore and use that to prefix the types/symbols // defined. When this options is provided, they will use this value instead // to prefix the types/symbols defined. SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"` // Sets the php class prefix which is prepended to all php generated classes // from this .proto. Default is empty. PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"` // Use this option to change the namespace of php generated classes. Default // is empty. When this option is empty, the package name will be used for // determining the namespace. PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *FileOptions) Reset() { *m = FileOptions{} } func (m *FileOptions) String() string { return proto.CompactTextString(m) } func (*FileOptions) ProtoMessage() {} func (*FileOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} } var extRange_FileOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_FileOptions } const Default_FileOptions_JavaMultipleFiles bool = false const Default_FileOptions_JavaStringCheckUtf8 bool = false const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED const Default_FileOptions_CcGenericServices bool = false const Default_FileOptions_JavaGenericServices bool = false const Default_FileOptions_PyGenericServices bool = false const Default_FileOptions_PhpGenericServices bool = false const Default_FileOptions_Deprecated bool = false const Default_FileOptions_CcEnableArenas bool = false func (m *FileOptions) GetJavaPackage() string { if m != nil && m.JavaPackage != nil { return *m.JavaPackage } return "" } func (m *FileOptions) GetJavaOuterClassname() string { if m != nil && m.JavaOuterClassname != nil { return *m.JavaOuterClassname } return "" } func (m *FileOptions) GetJavaMultipleFiles() bool { if m != nil && m.JavaMultipleFiles != nil { return *m.JavaMultipleFiles } return Default_FileOptions_JavaMultipleFiles } func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool { if m != nil && m.JavaGenerateEqualsAndHash != nil { return *m.JavaGenerateEqualsAndHash } return false } func (m *FileOptions) GetJavaStringCheckUtf8() bool { if m != nil && m.JavaStringCheckUtf8 != nil { return *m.JavaStringCheckUtf8 } return Default_FileOptions_JavaStringCheckUtf8 } func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode { if m != nil && m.OptimizeFor != nil { return *m.OptimizeFor } return Default_FileOptions_OptimizeFor } func (m *FileOptions) GetGoPackage() string { if m != nil && m.GoPackage != nil { return *m.GoPackage } return "" } func (m *FileOptions) GetCcGenericServices() bool { if m != nil && m.CcGenericServices != nil { return *m.CcGenericServices } return Default_FileOptions_CcGenericServices } func (m *FileOptions) GetJavaGenericServices() bool { if m != nil && m.JavaGenericServices != nil { return *m.JavaGenericServices } return Default_FileOptions_JavaGenericServices } func (m *FileOptions) GetPyGenericServices() bool { if m != nil && m.PyGenericServices != nil { return *m.PyGenericServices } return Default_FileOptions_PyGenericServices } func (m *FileOptions) GetPhpGenericServices() bool { if m != nil && m.PhpGenericServices != nil { return *m.PhpGenericServices } return Default_FileOptions_PhpGenericServices } func (m *FileOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_FileOptions_Deprecated } func (m *FileOptions) GetCcEnableArenas() bool { if m != nil && m.CcEnableArenas != nil { return *m.CcEnableArenas } return Default_FileOptions_CcEnableArenas } func (m *FileOptions) GetObjcClassPrefix() string { if m != nil && m.ObjcClassPrefix != nil { return *m.ObjcClassPrefix } return "" } func (m *FileOptions) GetCsharpNamespace() string { if m != nil && m.CsharpNamespace != nil { return *m.CsharpNamespace } return "" } func (m *FileOptions) GetSwiftPrefix() string { if m != nil && m.SwiftPrefix != nil { return *m.SwiftPrefix } return "" } func (m *FileOptions) GetPhpClassPrefix() string { if m != nil && m.PhpClassPrefix != nil { return *m.PhpClassPrefix } return "" } func (m *FileOptions) GetPhpNamespace() string { if m != nil && m.PhpNamespace != nil { return *m.PhpNamespace } return "" } func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type MessageOptions struct { // Set true to use the old proto1 MessageSet wire format for extensions. // This is provided for backwards-compatibility with the MessageSet wire // format. You should not use this for any other reason: It's less // efficient, has fewer features, and is more complicated. // // The message must be defined exactly as follows: // message Foo { // option message_set_wire_format = true; // extensions 4 to max; // } // Note that the message cannot have any defined fields; MessageSets only // have extensions. // // All extensions of your type must be singular messages; e.g. they cannot // be int32s, enums, or repeated messages. // // Because this is an option, the above two restrictions are not enforced by // the protocol compiler. MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"` // Disables the generation of the standard "descriptor()" accessor, which can // conflict with a field of the same name. This is meant to make migration // from proto1 easier; new code should avoid fields named "descriptor". NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"` // Is this message deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the message, or it will be completely ignored; in the very least, // this is a formalization for deprecating messages. Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // Whether the message is an automatically generated map entry type for the // maps field. // // For maps fields: // map map_field = 1; // The parsed descriptor looks like: // message MapFieldEntry { // option map_entry = true; // optional KeyType key = 1; // optional ValueType value = 2; // } // repeated MapFieldEntry map_field = 1; // // Implementations may choose not to generate the map_entry=true message, but // use a native map in the target language to hold the keys and values. // The reflection APIs in such implementions still need to work as // if the field is a repeated message field. // // NOTE: Do not set the option in .proto files. Always use the maps syntax // instead. The option should only be implicitly set by the proto compiler // parser. MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *MessageOptions) Reset() { *m = MessageOptions{} } func (m *MessageOptions) String() string { return proto.CompactTextString(m) } func (*MessageOptions) ProtoMessage() {} func (*MessageOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} } var extRange_MessageOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_MessageOptions } const Default_MessageOptions_MessageSetWireFormat bool = false const Default_MessageOptions_NoStandardDescriptorAccessor bool = false const Default_MessageOptions_Deprecated bool = false func (m *MessageOptions) GetMessageSetWireFormat() bool { if m != nil && m.MessageSetWireFormat != nil { return *m.MessageSetWireFormat } return Default_MessageOptions_MessageSetWireFormat } func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool { if m != nil && m.NoStandardDescriptorAccessor != nil { return *m.NoStandardDescriptorAccessor } return Default_MessageOptions_NoStandardDescriptorAccessor } func (m *MessageOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_MessageOptions_Deprecated } func (m *MessageOptions) GetMapEntry() bool { if m != nil && m.MapEntry != nil { return *m.MapEntry } return false } func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type FieldOptions struct { // The ctype option instructs the C++ code generator to use a different // representation of the field than it normally would. See the specific // options below. This option is not yet implemented in the open source // release -- sorry, we'll try to include it in a future version! Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"` // The packed option can be enabled for repeated primitive fields to enable // a more efficient representation on the wire. Rather than repeatedly // writing the tag and type for each element, the entire array is encoded as // a single length-delimited blob. In proto3, only explicit setting it to // false will avoid using packed encoding. Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"` // The jstype option determines the JavaScript type used for values of the // field. The option is permitted only for 64 bit integral and fixed types // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING // is represented as JavaScript string, which avoids loss of precision that // can happen when a large value is converted to a floating point JavaScript. // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to // use the JavaScript "number" type. The behavior of the default option // JS_NORMAL is implementation dependent. // // This option is an enum to permit additional types to be added, e.g. // goog.math.Integer. Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"` // Should this field be parsed lazily? Lazy applies only to message-type // fields. It means that when the outer message is initially parsed, the // inner message's contents will not be parsed but instead stored in encoded // form. The inner message will actually be parsed when it is first accessed. // // This is only a hint. Implementations are free to choose whether to use // eager or lazy parsing regardless of the value of this option. However, // setting this option true suggests that the protocol author believes that // using lazy parsing on this field is worth the additional bookkeeping // overhead typically needed to implement it. // // This option does not affect the public interface of any generated code; // all method signatures remain the same. Furthermore, thread-safety of the // interface is not affected by this option; const methods remain safe to // call from multiple threads concurrently, while non-const methods continue // to require exclusive access. // // // Note that implementations may choose not to check required fields within // a lazy sub-message. That is, calling IsInitialized() on the outer message // may return true even if the inner message has missing required fields. // This is necessary because otherwise the inner message would have to be // parsed in order to perform the check, defeating the purpose of lazy // parsing. An implementation which chooses not to check required fields // must be consistent about it. That is, for any particular sub-message, the // implementation must either *always* check its required fields, or *never* // check its required fields, regardless of whether or not the message has // been parsed. Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"` // Is this field deprecated? // Depending on the target platform, this can emit Deprecated annotations // for accessors, or it will be completely ignored; in the very least, this // is a formalization for deprecating fields. Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // For Google-internal migration only. Do not use. Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *FieldOptions) Reset() { *m = FieldOptions{} } func (m *FieldOptions) String() string { return proto.CompactTextString(m) } func (*FieldOptions) ProtoMessage() {} func (*FieldOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} } var extRange_FieldOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_FieldOptions } const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL const Default_FieldOptions_Lazy bool = false const Default_FieldOptions_Deprecated bool = false const Default_FieldOptions_Weak bool = false func (m *FieldOptions) GetCtype() FieldOptions_CType { if m != nil && m.Ctype != nil { return *m.Ctype } return Default_FieldOptions_Ctype } func (m *FieldOptions) GetPacked() bool { if m != nil && m.Packed != nil { return *m.Packed } return false } func (m *FieldOptions) GetJstype() FieldOptions_JSType { if m != nil && m.Jstype != nil { return *m.Jstype } return Default_FieldOptions_Jstype } func (m *FieldOptions) GetLazy() bool { if m != nil && m.Lazy != nil { return *m.Lazy } return Default_FieldOptions_Lazy } func (m *FieldOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_FieldOptions_Deprecated } func (m *FieldOptions) GetWeak() bool { if m != nil && m.Weak != nil { return *m.Weak } return Default_FieldOptions_Weak } func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type OneofOptions struct { // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OneofOptions) Reset() { *m = OneofOptions{} } func (m *OneofOptions) String() string { return proto.CompactTextString(m) } func (*OneofOptions) ProtoMessage() {} func (*OneofOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} } var extRange_OneofOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OneofOptions } func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type EnumOptions struct { // Set this option to true to allow mapping different tag names to the same // value. AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"` // Is this enum deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the enum, or it will be completely ignored; in the very least, this // is a formalization for deprecating enums. Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *EnumOptions) Reset() { *m = EnumOptions{} } func (m *EnumOptions) String() string { return proto.CompactTextString(m) } func (*EnumOptions) ProtoMessage() {} func (*EnumOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} } var extRange_EnumOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_EnumOptions } const Default_EnumOptions_Deprecated bool = false func (m *EnumOptions) GetAllowAlias() bool { if m != nil && m.AllowAlias != nil { return *m.AllowAlias } return false } func (m *EnumOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_EnumOptions_Deprecated } func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type EnumValueOptions struct { // Is this enum value deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the enum value, or it will be completely ignored; in the very least, // this is a formalization for deprecating enum values. Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} } func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) } func (*EnumValueOptions) ProtoMessage() {} func (*EnumValueOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} } var extRange_EnumValueOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_EnumValueOptions } const Default_EnumValueOptions_Deprecated bool = false func (m *EnumValueOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_EnumValueOptions_Deprecated } func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type ServiceOptions struct { // Is this service deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the service, or it will be completely ignored; in the very least, // this is a formalization for deprecating services. Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *ServiceOptions) Reset() { *m = ServiceOptions{} } func (m *ServiceOptions) String() string { return proto.CompactTextString(m) } func (*ServiceOptions) ProtoMessage() {} func (*ServiceOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} } var extRange_ServiceOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_ServiceOptions } const Default_ServiceOptions_Deprecated bool = false func (m *ServiceOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_ServiceOptions_Deprecated } func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } type MethodOptions struct { // Is this method deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the method, or it will be completely ignored; in the very least, // this is a formalization for deprecating methods. Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"` IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"` // The parser stores options it doesn't recognize here. See above. UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *MethodOptions) Reset() { *m = MethodOptions{} } func (m *MethodOptions) String() string { return proto.CompactTextString(m) } func (*MethodOptions) ProtoMessage() {} func (*MethodOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} } var extRange_MethodOptions = []proto.ExtensionRange{ {1000, 536870911}, } func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange { return extRange_MethodOptions } const Default_MethodOptions_Deprecated bool = false const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN func (m *MethodOptions) GetDeprecated() bool { if m != nil && m.Deprecated != nil { return *m.Deprecated } return Default_MethodOptions_Deprecated } func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel { if m != nil && m.IdempotencyLevel != nil { return *m.IdempotencyLevel } return Default_MethodOptions_IdempotencyLevel } func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption { if m != nil { return m.UninterpretedOption } return nil } // A message representing a option the parser does not recognize. This only // appears in options protos created by the compiler::Parser class. // DescriptorPool resolves these when building Descriptor objects. Therefore, // options protos in descriptor objects (e.g. returned by Descriptor::options(), // or produced by Descriptor::CopyTo()) will never have UninterpretedOptions // in them. type UninterpretedOption struct { Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"` // The value of the uninterpreted option, in whatever type the tokenizer // identified it as during parsing. Exactly one of these should be set. IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"` PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"` NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"` DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"` StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"` AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} } func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) } func (*UninterpretedOption) ProtoMessage() {} func (*UninterpretedOption) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} } func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart { if m != nil { return m.Name } return nil } func (m *UninterpretedOption) GetIdentifierValue() string { if m != nil && m.IdentifierValue != nil { return *m.IdentifierValue } return "" } func (m *UninterpretedOption) GetPositiveIntValue() uint64 { if m != nil && m.PositiveIntValue != nil { return *m.PositiveIntValue } return 0 } func (m *UninterpretedOption) GetNegativeIntValue() int64 { if m != nil && m.NegativeIntValue != nil { return *m.NegativeIntValue } return 0 } func (m *UninterpretedOption) GetDoubleValue() float64 { if m != nil && m.DoubleValue != nil { return *m.DoubleValue } return 0 } func (m *UninterpretedOption) GetStringValue() []byte { if m != nil { return m.StringValue } return nil } func (m *UninterpretedOption) GetAggregateValue() string { if m != nil && m.AggregateValue != nil { return *m.AggregateValue } return "" } // The name of the uninterpreted option. Each string represents a segment in // a dot-separated name. is_extension is true iff a segment represents an // extension (denoted with parentheses in options specs in .proto files). // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents // "foo.(bar.baz).qux". type UninterpretedOption_NamePart struct { NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"` IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} } func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) } func (*UninterpretedOption_NamePart) ProtoMessage() {} func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18, 0} } func (m *UninterpretedOption_NamePart) GetNamePart() string { if m != nil && m.NamePart != nil { return *m.NamePart } return "" } func (m *UninterpretedOption_NamePart) GetIsExtension() bool { if m != nil && m.IsExtension != nil { return *m.IsExtension } return false } // Encapsulates information about the original source file from which a // FileDescriptorProto was generated. type SourceCodeInfo struct { // A Location identifies a piece of source code in a .proto file which // corresponds to a particular definition. This information is intended // to be useful to IDEs, code indexers, documentation generators, and similar // tools. // // For example, say we have a file like: // message Foo { // optional string foo = 1; // } // Let's look at just the field definition: // optional string foo = 1; // ^ ^^ ^^ ^ ^^^ // a bc de f ghi // We have the following locations: // span path represents // [a,i) [ 4, 0, 2, 0 ] The whole field definition. // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). // // Notes: // - A location may refer to a repeated field itself (i.e. not to any // particular index within it). This is used whenever a set of elements are // logically enclosed in a single code segment. For example, an entire // extend block (possibly containing multiple extension definitions) will // have an outer location whose path refers to the "extensions" repeated // field without an index. // - Multiple locations may have the same path. This happens when a single // logical declaration is spread out across multiple places. The most // obvious example is the "extend" block again -- there may be multiple // extend blocks in the same scope, each of which will have the same path. // - A location's span is not always a subset of its parent's span. For // example, the "extendee" of an extension declaration appears at the // beginning of the "extend" block and is shared by all extensions within // the block. // - Just because a location's span is a subset of some other location's span // does not mean that it is a descendent. For example, a "group" defines // both a type and a field in a single declaration. Thus, the locations // corresponding to the type and field and their components will overlap. // - Code which tries to interpret locations should probably be designed to // ignore those that it doesn't understand, as more types of locations could // be recorded in the future. Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} } func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) } func (*SourceCodeInfo) ProtoMessage() {} func (*SourceCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} } func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location { if m != nil { return m.Location } return nil } type SourceCodeInfo_Location struct { // Identifies which part of the FileDescriptorProto was defined at this // location. // // Each element is a field number or an index. They form a path from // the root FileDescriptorProto to the place where the definition. For // example, this path: // [ 4, 3, 2, 7, 1 ] // refers to: // file.message_type(3) // 4, 3 // .field(7) // 2, 7 // .name() // 1 // This is because FileDescriptorProto.message_type has field number 4: // repeated DescriptorProto message_type = 4; // and DescriptorProto.field has field number 2: // repeated FieldDescriptorProto field = 2; // and FieldDescriptorProto.name has field number 1: // optional string name = 1; // // Thus, the above path gives the location of a field name. If we removed // the last element: // [ 4, 3, 2, 7 ] // this path refers to the whole field declaration (from the beginning // of the label to the terminating semicolon). Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` // Always has exactly three or four elements: start line, start column, // end line (optional, otherwise assumed same as start line), end column. // These are packed into a single field for efficiency. Note that line // and column numbers are zero-based -- typically you will want to add // 1 to each before displaying to a user. Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"` // If this SourceCodeInfo represents a complete declaration, these are any // comments appearing before and after the declaration which appear to be // attached to the declaration. // // A series of line comments appearing on consecutive lines, with no other // tokens appearing on those lines, will be treated as a single comment. // // leading_detached_comments will keep paragraphs of comments that appear // before (but not connected to) the current element. Each paragraph, // separated by empty lines, will be one comment element in the repeated // field. // // Only the comment content is provided; comment markers (e.g. //) are // stripped out. For block comments, leading whitespace and an asterisk // will be stripped from the beginning of each line other than the first. // Newlines are included in the output. // // Examples: // // optional int32 foo = 1; // Comment attached to foo. // // Comment attached to bar. // optional int32 bar = 2; // // optional string baz = 3; // // Comment attached to baz. // // Another line attached to baz. // // // Comment attached to qux. // // // // Another line attached to qux. // optional double qux = 4; // // // Detached comment for corge. This is not leading or trailing comments // // to qux or corge because there are blank lines separating it from // // both. // // // Detached comment for corge paragraph 2. // // optional string corge = 5; // /* Block comment attached // * to corge. Leading asterisks // * will be removed. */ // /* Block comment attached to // * grault. */ // optional int32 grault = 6; // // // ignored detached comments. LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"` TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"` LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} } func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) } func (*SourceCodeInfo_Location) ProtoMessage() {} func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19, 0} } func (m *SourceCodeInfo_Location) GetPath() []int32 { if m != nil { return m.Path } return nil } func (m *SourceCodeInfo_Location) GetSpan() []int32 { if m != nil { return m.Span } return nil } func (m *SourceCodeInfo_Location) GetLeadingComments() string { if m != nil && m.LeadingComments != nil { return *m.LeadingComments } return "" } func (m *SourceCodeInfo_Location) GetTrailingComments() string { if m != nil && m.TrailingComments != nil { return *m.TrailingComments } return "" } func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string { if m != nil { return m.LeadingDetachedComments } return nil } // Describes the relationship between generated code and its original source // file. A GeneratedCodeInfo message is associated with only one generated // source file, but may contain references to different source .proto files. type GeneratedCodeInfo struct { // An Annotation connects some span of text in generated code to an element // of its generating .proto file. Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} } func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) } func (*GeneratedCodeInfo) ProtoMessage() {} func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20} } func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation { if m != nil { return m.Annotation } return nil } type GeneratedCodeInfo_Annotation struct { // Identifies the element in the original source .proto file. This field // is formatted the same as SourceCodeInfo.Location.path. Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` // Identifies the filesystem path to the original source .proto. SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"` // Identifies the starting offset in bytes in the generated code // that relates to the identified object. Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"` // Identifies the ending offset in bytes in the generated code that // relates to the identified offset. The end offset should be one past // the last relevant byte (so the length of the text = end - begin). End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} } func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) } func (*GeneratedCodeInfo_Annotation) ProtoMessage() {} func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20, 0} } func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 { if m != nil { return m.Path } return nil } func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string { if m != nil && m.SourceFile != nil { return *m.SourceFile } return "" } func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 { if m != nil && m.Begin != nil { return *m.Begin } return 0 } func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 { if m != nil && m.End != nil { return *m.End } return 0 } func init() { proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet") proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto") proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto") proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange") proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange") proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions") proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto") proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto") proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto") proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto") proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto") proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto") proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions") proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions") proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions") proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions") proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions") proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions") proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions") proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions") proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption") proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart") proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo") proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location") proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo") proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation") proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value) proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value) proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value) proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value) proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value) proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value) } func init() { proto.RegisterFile("google/protobuf/descriptor.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 2519 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xdd, 0x6e, 0x1b, 0xc7, 0x15, 0x0e, 0x7f, 0x45, 0x1e, 0x52, 0xd4, 0x68, 0xa4, 0xd8, 0x6b, 0xe5, 0xc7, 0x32, 0xf3, 0x63, 0xd9, 0x69, 0xa8, 0x40, 0xb1, 0x1d, 0x47, 0x29, 0xd2, 0x52, 0xe4, 0x5a, 0xa1, 0x4a, 0x91, 0xec, 0x92, 0x6a, 0x7e, 0x6e, 0x16, 0xa3, 0xdd, 0x21, 0xb9, 0xf6, 0x72, 0x77, 0xb3, 0xbb, 0xb4, 0xad, 0xa0, 0x17, 0x06, 0x7a, 0x55, 0xa0, 0x0f, 0x50, 0x14, 0x45, 0x2f, 0x72, 0x13, 0xa0, 0x0f, 0x50, 0x20, 0x77, 0x7d, 0x82, 0x02, 0x79, 0x83, 0xa2, 0x28, 0xd0, 0x3e, 0x46, 0x31, 0x33, 0xbb, 0xcb, 0x5d, 0xfe, 0xc4, 0x6a, 0x80, 0x38, 0x57, 0xe4, 0x7c, 0xe7, 0x3b, 0x67, 0xce, 0x9c, 0x39, 0x33, 0x73, 0x66, 0x16, 0x76, 0x47, 0xb6, 0x3d, 0x32, 0xe9, 0xbe, 0xe3, 0xda, 0xbe, 0x7d, 0x3e, 0x1d, 0xee, 0xeb, 0xd4, 0xd3, 0x5c, 0xc3, 0xf1, 0x6d, 0xb7, 0xc6, 0x31, 0xbc, 0x21, 0x18, 0xb5, 0x90, 0x51, 0x3d, 0x85, 0xcd, 0x07, 0x86, 0x49, 0x9b, 0x11, 0xb1, 0x4f, 0x7d, 0x7c, 0x1f, 0xb2, 0x43, 0xc3, 0xa4, 0x52, 0x6a, 0x37, 0xb3, 0x57, 0x3a, 0x78, 0xb3, 0x36, 0xa7, 0x54, 0x4b, 0x6a, 0xf4, 0x18, 0xac, 0x70, 0x8d, 0xea, 0xbf, 0xb3, 0xb0, 0xb5, 0x44, 0x8a, 0x31, 0x64, 0x2d, 0x32, 0x61, 0x16, 0x53, 0x7b, 0x45, 0x85, 0xff, 0xc7, 0x12, 0xac, 0x39, 0x44, 0x7b, 0x44, 0x46, 0x54, 0x4a, 0x73, 0x38, 0x6c, 0xe2, 0xd7, 0x01, 0x74, 0xea, 0x50, 0x4b, 0xa7, 0x96, 0x76, 0x21, 0x65, 0x76, 0x33, 0x7b, 0x45, 0x25, 0x86, 0xe0, 0x77, 0x60, 0xd3, 0x99, 0x9e, 0x9b, 0x86, 0xa6, 0xc6, 0x68, 0xb0, 0x9b, 0xd9, 0xcb, 0x29, 0x48, 0x08, 0x9a, 0x33, 0xf2, 0x4d, 0xd8, 0x78, 0x42, 0xc9, 0xa3, 0x38, 0xb5, 0xc4, 0xa9, 0x15, 0x06, 0xc7, 0x88, 0x0d, 0x28, 0x4f, 0xa8, 0xe7, 0x91, 0x11, 0x55, 0xfd, 0x0b, 0x87, 0x4a, 0x59, 0x3e, 0xfa, 0xdd, 0x85, 0xd1, 0xcf, 0x8f, 0xbc, 0x14, 0x68, 0x0d, 0x2e, 0x1c, 0x8a, 0xeb, 0x50, 0xa4, 0xd6, 0x74, 0x22, 0x2c, 0xe4, 0x56, 0xc4, 0x4f, 0xb6, 0xa6, 0x93, 0x79, 0x2b, 0x05, 0xa6, 0x16, 0x98, 0x58, 0xf3, 0xa8, 0xfb, 0xd8, 0xd0, 0xa8, 0x94, 0xe7, 0x06, 0x6e, 0x2e, 0x18, 0xe8, 0x0b, 0xf9, 0xbc, 0x8d, 0x50, 0x0f, 0x37, 0xa0, 0x48, 0x9f, 0xfa, 0xd4, 0xf2, 0x0c, 0xdb, 0x92, 0xd6, 0xb8, 0x91, 0xb7, 0x96, 0xcc, 0x22, 0x35, 0xf5, 0x79, 0x13, 0x33, 0x3d, 0x7c, 0x0f, 0xd6, 0x6c, 0xc7, 0x37, 0x6c, 0xcb, 0x93, 0x0a, 0xbb, 0xa9, 0xbd, 0xd2, 0xc1, 0xab, 0x4b, 0x13, 0xa1, 0x2b, 0x38, 0x4a, 0x48, 0xc6, 0x2d, 0x40, 0x9e, 0x3d, 0x75, 0x35, 0xaa, 0x6a, 0xb6, 0x4e, 0x55, 0xc3, 0x1a, 0xda, 0x52, 0x91, 0x1b, 0xb8, 0xbe, 0x38, 0x10, 0x4e, 0x6c, 0xd8, 0x3a, 0x6d, 0x59, 0x43, 0x5b, 0xa9, 0x78, 0x89, 0x36, 0xbe, 0x02, 0x79, 0xef, 0xc2, 0xf2, 0xc9, 0x53, 0xa9, 0xcc, 0x33, 0x24, 0x68, 0x55, 0xbf, 0xcd, 0xc3, 0xc6, 0x65, 0x52, 0xec, 0x23, 0xc8, 0x0d, 0xd9, 0x28, 0xa5, 0xf4, 0xff, 0x13, 0x03, 0xa1, 0x93, 0x0c, 0x62, 0xfe, 0x07, 0x06, 0xb1, 0x0e, 0x25, 0x8b, 0x7a, 0x3e, 0xd5, 0x45, 0x46, 0x64, 0x2e, 0x99, 0x53, 0x20, 0x94, 0x16, 0x53, 0x2a, 0xfb, 0x83, 0x52, 0xea, 0x33, 0xd8, 0x88, 0x5c, 0x52, 0x5d, 0x62, 0x8d, 0xc2, 0xdc, 0xdc, 0x7f, 0x9e, 0x27, 0x35, 0x39, 0xd4, 0x53, 0x98, 0x9a, 0x52, 0xa1, 0x89, 0x36, 0x6e, 0x02, 0xd8, 0x16, 0xb5, 0x87, 0xaa, 0x4e, 0x35, 0x53, 0x2a, 0xac, 0x88, 0x52, 0x97, 0x51, 0x16, 0xa2, 0x64, 0x0b, 0x54, 0x33, 0xf1, 0x87, 0xb3, 0x54, 0x5b, 0x5b, 0x91, 0x29, 0xa7, 0x62, 0x91, 0x2d, 0x64, 0xdb, 0x19, 0x54, 0x5c, 0xca, 0xf2, 0x9e, 0xea, 0xc1, 0xc8, 0x8a, 0xdc, 0x89, 0xda, 0x73, 0x47, 0xa6, 0x04, 0x6a, 0x62, 0x60, 0xeb, 0x6e, 0xbc, 0x89, 0xdf, 0x80, 0x08, 0x50, 0x79, 0x5a, 0x01, 0xdf, 0x85, 0xca, 0x21, 0xd8, 0x21, 0x13, 0xba, 0xf3, 0x15, 0x54, 0x92, 0xe1, 0xc1, 0xdb, 0x90, 0xf3, 0x7c, 0xe2, 0xfa, 0x3c, 0x0b, 0x73, 0x8a, 0x68, 0x60, 0x04, 0x19, 0x6a, 0xe9, 0x7c, 0x97, 0xcb, 0x29, 0xec, 0x2f, 0xfe, 0xe5, 0x6c, 0xc0, 0x19, 0x3e, 0xe0, 0xb7, 0x17, 0x67, 0x34, 0x61, 0x79, 0x7e, 0xdc, 0x3b, 0x1f, 0xc0, 0x7a, 0x62, 0x00, 0x97, 0xed, 0xba, 0xfa, 0x5b, 0x78, 0x79, 0xa9, 0x69, 0xfc, 0x19, 0x6c, 0x4f, 0x2d, 0xc3, 0xf2, 0xa9, 0xeb, 0xb8, 0x94, 0x65, 0xac, 0xe8, 0x4a, 0xfa, 0xcf, 0xda, 0x8a, 0x9c, 0x3b, 0x8b, 0xb3, 0x85, 0x15, 0x65, 0x6b, 0xba, 0x08, 0xde, 0x2e, 0x16, 0xfe, 0xbb, 0x86, 0x9e, 0x3d, 0x7b, 0xf6, 0x2c, 0x5d, 0xfd, 0x63, 0x1e, 0xb6, 0x97, 0xad, 0x99, 0xa5, 0xcb, 0xf7, 0x0a, 0xe4, 0xad, 0xe9, 0xe4, 0x9c, 0xba, 0x3c, 0x48, 0x39, 0x25, 0x68, 0xe1, 0x3a, 0xe4, 0x4c, 0x72, 0x4e, 0x4d, 0x29, 0xbb, 0x9b, 0xda, 0xab, 0x1c, 0xbc, 0x73, 0xa9, 0x55, 0x59, 0x6b, 0x33, 0x15, 0x45, 0x68, 0xe2, 0x8f, 0x21, 0x1b, 0x6c, 0xd1, 0xcc, 0xc2, 0xed, 0xcb, 0x59, 0x60, 0x6b, 0x49, 0xe1, 0x7a, 0xf8, 0x15, 0x28, 0xb2, 0x5f, 0x91, 0x1b, 0x79, 0xee, 0x73, 0x81, 0x01, 0x2c, 0x2f, 0xf0, 0x0e, 0x14, 0xf8, 0x32, 0xd1, 0x69, 0x78, 0xb4, 0x45, 0x6d, 0x96, 0x58, 0x3a, 0x1d, 0x92, 0xa9, 0xe9, 0xab, 0x8f, 0x89, 0x39, 0xa5, 0x3c, 0xe1, 0x8b, 0x4a, 0x39, 0x00, 0x7f, 0xc3, 0x30, 0x7c, 0x1d, 0x4a, 0x62, 0x55, 0x19, 0x96, 0x4e, 0x9f, 0xf2, 0xdd, 0x33, 0xa7, 0x88, 0x85, 0xd6, 0x62, 0x08, 0xeb, 0xfe, 0xa1, 0x67, 0x5b, 0x61, 0x6a, 0xf2, 0x2e, 0x18, 0xc0, 0xbb, 0xff, 0x60, 0x7e, 0xe3, 0x7e, 0x6d, 0xf9, 0xf0, 0xe6, 0x73, 0xaa, 0xfa, 0xb7, 0x34, 0x64, 0xf9, 0x7e, 0xb1, 0x01, 0xa5, 0xc1, 0xe7, 0x3d, 0x59, 0x6d, 0x76, 0xcf, 0x8e, 0xda, 0x32, 0x4a, 0xe1, 0x0a, 0x00, 0x07, 0x1e, 0xb4, 0xbb, 0xf5, 0x01, 0x4a, 0x47, 0xed, 0x56, 0x67, 0x70, 0xef, 0x0e, 0xca, 0x44, 0x0a, 0x67, 0x02, 0xc8, 0xc6, 0x09, 0xef, 0x1f, 0xa0, 0x1c, 0x46, 0x50, 0x16, 0x06, 0x5a, 0x9f, 0xc9, 0xcd, 0x7b, 0x77, 0x50, 0x3e, 0x89, 0xbc, 0x7f, 0x80, 0xd6, 0xf0, 0x3a, 0x14, 0x39, 0x72, 0xd4, 0xed, 0xb6, 0x51, 0x21, 0xb2, 0xd9, 0x1f, 0x28, 0xad, 0xce, 0x31, 0x2a, 0x46, 0x36, 0x8f, 0x95, 0xee, 0x59, 0x0f, 0x41, 0x64, 0xe1, 0x54, 0xee, 0xf7, 0xeb, 0xc7, 0x32, 0x2a, 0x45, 0x8c, 0xa3, 0xcf, 0x07, 0x72, 0x1f, 0x95, 0x13, 0x6e, 0xbd, 0x7f, 0x80, 0xd6, 0xa3, 0x2e, 0xe4, 0xce, 0xd9, 0x29, 0xaa, 0xe0, 0x4d, 0x58, 0x17, 0x5d, 0x84, 0x4e, 0x6c, 0xcc, 0x41, 0xf7, 0xee, 0x20, 0x34, 0x73, 0x44, 0x58, 0xd9, 0x4c, 0x00, 0xf7, 0xee, 0x20, 0x5c, 0x6d, 0x40, 0x8e, 0x67, 0x17, 0xc6, 0x50, 0x69, 0xd7, 0x8f, 0xe4, 0xb6, 0xda, 0xed, 0x0d, 0x5a, 0xdd, 0x4e, 0xbd, 0x8d, 0x52, 0x33, 0x4c, 0x91, 0x7f, 0x7d, 0xd6, 0x52, 0xe4, 0x26, 0x4a, 0xc7, 0xb1, 0x9e, 0x5c, 0x1f, 0xc8, 0x4d, 0x94, 0xa9, 0x6a, 0xb0, 0xbd, 0x6c, 0x9f, 0x5c, 0xba, 0x32, 0x62, 0x53, 0x9c, 0x5e, 0x31, 0xc5, 0xdc, 0xd6, 0xc2, 0x14, 0x7f, 0x9d, 0x82, 0xad, 0x25, 0x67, 0xc5, 0xd2, 0x4e, 0x7e, 0x01, 0x39, 0x91, 0xa2, 0xe2, 0xf4, 0xbc, 0xb5, 0xf4, 0xd0, 0xe1, 0x09, 0xbb, 0x70, 0x82, 0x72, 0xbd, 0x78, 0x05, 0x91, 0x59, 0x51, 0x41, 0x30, 0x13, 0x0b, 0x4e, 0xfe, 0x2e, 0x05, 0xd2, 0x2a, 0xdb, 0xcf, 0xd9, 0x28, 0xd2, 0x89, 0x8d, 0xe2, 0xa3, 0x79, 0x07, 0x6e, 0xac, 0x1e, 0xc3, 0x82, 0x17, 0xdf, 0xa4, 0xe0, 0xca, 0xf2, 0x42, 0x6b, 0xa9, 0x0f, 0x1f, 0x43, 0x7e, 0x42, 0xfd, 0xb1, 0x1d, 0x16, 0x1b, 0x6f, 0x2f, 0x39, 0xc2, 0x98, 0x78, 0x3e, 0x56, 0x81, 0x56, 0xfc, 0x0c, 0xcc, 0xac, 0xaa, 0x96, 0x84, 0x37, 0x0b, 0x9e, 0xfe, 0x3e, 0x0d, 0x2f, 0x2f, 0x35, 0xbe, 0xd4, 0xd1, 0xd7, 0x00, 0x0c, 0xcb, 0x99, 0xfa, 0xa2, 0xa0, 0x10, 0xfb, 0x53, 0x91, 0x23, 0x7c, 0xed, 0xb3, 0xbd, 0x67, 0xea, 0x47, 0xf2, 0x0c, 0x97, 0x83, 0x80, 0x38, 0xe1, 0xfe, 0xcc, 0xd1, 0x2c, 0x77, 0xf4, 0xf5, 0x15, 0x23, 0x5d, 0x38, 0xab, 0xdf, 0x03, 0xa4, 0x99, 0x06, 0xb5, 0x7c, 0xd5, 0xf3, 0x5d, 0x4a, 0x26, 0x86, 0x35, 0xe2, 0x1b, 0x70, 0xe1, 0x30, 0x37, 0x24, 0xa6, 0x47, 0x95, 0x0d, 0x21, 0xee, 0x87, 0x52, 0xa6, 0xc1, 0xcf, 0x38, 0x37, 0xa6, 0x91, 0x4f, 0x68, 0x08, 0x71, 0xa4, 0x51, 0xfd, 0xb6, 0x00, 0xa5, 0x58, 0x59, 0x8a, 0x6f, 0x40, 0xf9, 0x21, 0x79, 0x4c, 0xd4, 0xf0, 0xaa, 0x21, 0x22, 0x51, 0x62, 0x58, 0x2f, 0xb8, 0x6e, 0xbc, 0x07, 0xdb, 0x9c, 0x62, 0x4f, 0x7d, 0xea, 0xaa, 0x9a, 0x49, 0x3c, 0x8f, 0x07, 0xad, 0xc0, 0xa9, 0x98, 0xc9, 0xba, 0x4c, 0xd4, 0x08, 0x25, 0xf8, 0x2e, 0x6c, 0x71, 0x8d, 0xc9, 0xd4, 0xf4, 0x0d, 0xc7, 0xa4, 0x2a, 0xbb, 0xfc, 0x78, 0x7c, 0x23, 0x8e, 0x3c, 0xdb, 0x64, 0x8c, 0xd3, 0x80, 0xc0, 0x3c, 0xf2, 0x70, 0x13, 0x5e, 0xe3, 0x6a, 0x23, 0x6a, 0x51, 0x97, 0xf8, 0x54, 0xa5, 0x5f, 0x4e, 0x89, 0xe9, 0xa9, 0xc4, 0xd2, 0xd5, 0x31, 0xf1, 0xc6, 0xd2, 0x36, 0x33, 0x70, 0x94, 0x96, 0x52, 0xca, 0x35, 0x46, 0x3c, 0x0e, 0x78, 0x32, 0xa7, 0xd5, 0x2d, 0xfd, 0x13, 0xe2, 0x8d, 0xf1, 0x21, 0x5c, 0xe1, 0x56, 0x3c, 0xdf, 0x35, 0xac, 0x91, 0xaa, 0x8d, 0xa9, 0xf6, 0x48, 0x9d, 0xfa, 0xc3, 0xfb, 0xd2, 0x2b, 0xf1, 0xfe, 0xb9, 0x87, 0x7d, 0xce, 0x69, 0x30, 0xca, 0x99, 0x3f, 0xbc, 0x8f, 0xfb, 0x50, 0x66, 0x93, 0x31, 0x31, 0xbe, 0xa2, 0xea, 0xd0, 0x76, 0xf9, 0xc9, 0x52, 0x59, 0xb2, 0xb2, 0x63, 0x11, 0xac, 0x75, 0x03, 0x85, 0x53, 0x5b, 0xa7, 0x87, 0xb9, 0x7e, 0x4f, 0x96, 0x9b, 0x4a, 0x29, 0xb4, 0xf2, 0xc0, 0x76, 0x59, 0x42, 0x8d, 0xec, 0x28, 0xc0, 0x25, 0x91, 0x50, 0x23, 0x3b, 0x0c, 0xef, 0x5d, 0xd8, 0xd2, 0x34, 0x31, 0x66, 0x43, 0x53, 0x83, 0x2b, 0x8a, 0x27, 0xa1, 0x44, 0xb0, 0x34, 0xed, 0x58, 0x10, 0x82, 0x1c, 0xf7, 0xf0, 0x87, 0xf0, 0xf2, 0x2c, 0x58, 0x71, 0xc5, 0xcd, 0x85, 0x51, 0xce, 0xab, 0xde, 0x85, 0x2d, 0xe7, 0x62, 0x51, 0x11, 0x27, 0x7a, 0x74, 0x2e, 0xe6, 0xd5, 0x3e, 0x80, 0x6d, 0x67, 0xec, 0x2c, 0xea, 0xdd, 0x8e, 0xeb, 0x61, 0x67, 0xec, 0xcc, 0x2b, 0xbe, 0xc5, 0xef, 0xab, 0x2e, 0xd5, 0x88, 0x4f, 0x75, 0xe9, 0x6a, 0x9c, 0x1e, 0x13, 0xe0, 0x7d, 0x40, 0x9a, 0xa6, 0x52, 0x8b, 0x9c, 0x9b, 0x54, 0x25, 0x2e, 0xb5, 0x88, 0x27, 0x5d, 0x8f, 0x93, 0x2b, 0x9a, 0x26, 0x73, 0x69, 0x9d, 0x0b, 0xf1, 0x6d, 0xd8, 0xb4, 0xcf, 0x1f, 0x6a, 0x22, 0x25, 0x55, 0xc7, 0xa5, 0x43, 0xe3, 0xa9, 0xf4, 0x26, 0x8f, 0xef, 0x06, 0x13, 0xf0, 0x84, 0xec, 0x71, 0x18, 0xdf, 0x02, 0xa4, 0x79, 0x63, 0xe2, 0x3a, 0xbc, 0x26, 0xf0, 0x1c, 0xa2, 0x51, 0xe9, 0x2d, 0x41, 0x15, 0x78, 0x27, 0x84, 0xd9, 0x92, 0xf0, 0x9e, 0x18, 0x43, 0x3f, 0xb4, 0x78, 0x53, 0x2c, 0x09, 0x8e, 0x05, 0xd6, 0xf6, 0x00, 0xb1, 0x50, 0x24, 0x3a, 0xde, 0xe3, 0xb4, 0x8a, 0x33, 0x76, 0xe2, 0xfd, 0xbe, 0x01, 0xeb, 0x8c, 0x39, 0xeb, 0xf4, 0x96, 0xa8, 0x67, 0x9c, 0x71, 0xac, 0xc7, 0x1f, 0xad, 0xb4, 0xac, 0x1e, 0x42, 0x39, 0x9e, 0x9f, 0xb8, 0x08, 0x22, 0x43, 0x51, 0x8a, 0x9d, 0xf5, 0x8d, 0x6e, 0x93, 0x9d, 0xd2, 0x5f, 0xc8, 0x28, 0xcd, 0xaa, 0x85, 0x76, 0x6b, 0x20, 0xab, 0xca, 0x59, 0x67, 0xd0, 0x3a, 0x95, 0x51, 0x26, 0x56, 0x96, 0x9e, 0x64, 0x0b, 0x6f, 0xa3, 0x9b, 0xd5, 0xef, 0xd2, 0x50, 0x49, 0xde, 0x33, 0xf0, 0xcf, 0xe1, 0x6a, 0xf8, 0x28, 0xe0, 0x51, 0x5f, 0x7d, 0x62, 0xb8, 0x7c, 0xe1, 0x4c, 0x88, 0xa8, 0xb3, 0xa3, 0xa9, 0xdb, 0x0e, 0x58, 0x7d, 0xea, 0x7f, 0x6a, 0xb8, 0x6c, 0x59, 0x4c, 0x88, 0x8f, 0xdb, 0x70, 0xdd, 0xb2, 0x55, 0xcf, 0x27, 0x96, 0x4e, 0x5c, 0x5d, 0x9d, 0x3d, 0xc7, 0xa8, 0x44, 0xd3, 0xa8, 0xe7, 0xd9, 0xe2, 0xc0, 0x8a, 0xac, 0xbc, 0x6a, 0xd9, 0xfd, 0x80, 0x3c, 0xdb, 0xc9, 0xeb, 0x01, 0x75, 0x2e, 0xcd, 0x32, 0xab, 0xd2, 0xec, 0x15, 0x28, 0x4e, 0x88, 0xa3, 0x52, 0xcb, 0x77, 0x2f, 0x78, 0x75, 0x59, 0x50, 0x0a, 0x13, 0xe2, 0xc8, 0xac, 0xfd, 0x42, 0x8a, 0xfc, 0x93, 0x6c, 0xa1, 0x80, 0x8a, 0x27, 0xd9, 0x42, 0x11, 0x41, 0xf5, 0x5f, 0x19, 0x28, 0xc7, 0xab, 0x4d, 0x56, 0xbc, 0x6b, 0xfc, 0x64, 0x49, 0xf1, 0xbd, 0xe7, 0x8d, 0xef, 0xad, 0x4d, 0x6b, 0x0d, 0x76, 0xe4, 0x1c, 0xe6, 0x45, 0x0d, 0xa8, 0x08, 0x4d, 0x76, 0xdc, 0xb3, 0xdd, 0x86, 0x8a, 0x7b, 0x4d, 0x41, 0x09, 0x5a, 0xf8, 0x18, 0xf2, 0x0f, 0x3d, 0x6e, 0x3b, 0xcf, 0x6d, 0xbf, 0xf9, 0xfd, 0xb6, 0x4f, 0xfa, 0xdc, 0x78, 0xf1, 0xa4, 0xaf, 0x76, 0xba, 0xca, 0x69, 0xbd, 0xad, 0x04, 0xea, 0xf8, 0x1a, 0x64, 0x4d, 0xf2, 0xd5, 0x45, 0xf2, 0x70, 0xe2, 0xd0, 0x65, 0x27, 0xe1, 0x1a, 0x64, 0x9f, 0x50, 0xf2, 0x28, 0x79, 0x24, 0x70, 0xe8, 0x47, 0x5c, 0x0c, 0xfb, 0x90, 0xe3, 0xf1, 0xc2, 0x00, 0x41, 0xc4, 0xd0, 0x4b, 0xb8, 0x00, 0xd9, 0x46, 0x57, 0x61, 0x0b, 0x02, 0x41, 0x59, 0xa0, 0x6a, 0xaf, 0x25, 0x37, 0x64, 0x94, 0xae, 0xde, 0x85, 0xbc, 0x08, 0x02, 0x5b, 0x2c, 0x51, 0x18, 0xd0, 0x4b, 0x41, 0x33, 0xb0, 0x91, 0x0a, 0xa5, 0x67, 0xa7, 0x47, 0xb2, 0x82, 0xd2, 0xc9, 0xa9, 0xce, 0xa2, 0x5c, 0xd5, 0x83, 0x72, 0xbc, 0xdc, 0x7c, 0x31, 0x57, 0xc9, 0xbf, 0xa7, 0xa0, 0x14, 0x2b, 0x1f, 0x59, 0xe1, 0x42, 0x4c, 0xd3, 0x7e, 0xa2, 0x12, 0xd3, 0x20, 0x5e, 0x90, 0x1a, 0xc0, 0xa1, 0x3a, 0x43, 0x2e, 0x3b, 0x75, 0x2f, 0x68, 0x89, 0xe4, 0x50, 0xbe, 0xfa, 0x97, 0x14, 0xa0, 0xf9, 0x02, 0x74, 0xce, 0xcd, 0xd4, 0x4f, 0xe9, 0x66, 0xf5, 0xcf, 0x29, 0xa8, 0x24, 0xab, 0xce, 0x39, 0xf7, 0x6e, 0xfc, 0xa4, 0xee, 0xfd, 0x33, 0x0d, 0xeb, 0x89, 0x5a, 0xf3, 0xb2, 0xde, 0x7d, 0x09, 0x9b, 0x86, 0x4e, 0x27, 0x8e, 0xed, 0x53, 0x4b, 0xbb, 0x50, 0x4d, 0xfa, 0x98, 0x9a, 0x52, 0x95, 0x6f, 0x1a, 0xfb, 0xdf, 0x5f, 0xcd, 0xd6, 0x5a, 0x33, 0xbd, 0x36, 0x53, 0x3b, 0xdc, 0x6a, 0x35, 0xe5, 0xd3, 0x5e, 0x77, 0x20, 0x77, 0x1a, 0x9f, 0xab, 0x67, 0x9d, 0x5f, 0x75, 0xba, 0x9f, 0x76, 0x14, 0x64, 0xcc, 0xd1, 0x7e, 0xc4, 0x65, 0xdf, 0x03, 0x34, 0xef, 0x14, 0xbe, 0x0a, 0xcb, 0xdc, 0x42, 0x2f, 0xe1, 0x2d, 0xd8, 0xe8, 0x74, 0xd5, 0x7e, 0xab, 0x29, 0xab, 0xf2, 0x83, 0x07, 0x72, 0x63, 0xd0, 0x17, 0xd7, 0xfb, 0x88, 0x3d, 0x48, 0x2c, 0xf0, 0xea, 0x9f, 0x32, 0xb0, 0xb5, 0xc4, 0x13, 0x5c, 0x0f, 0x6e, 0x16, 0xe2, 0xb2, 0xf3, 0xee, 0x65, 0xbc, 0xaf, 0xb1, 0x82, 0xa0, 0x47, 0x5c, 0x3f, 0xb8, 0x88, 0xdc, 0x02, 0x16, 0x25, 0xcb, 0x37, 0x86, 0x06, 0x75, 0x83, 0xd7, 0x10, 0x71, 0xdd, 0xd8, 0x98, 0xe1, 0xe2, 0x41, 0xe4, 0x67, 0x80, 0x1d, 0xdb, 0x33, 0x7c, 0xe3, 0x31, 0x55, 0x0d, 0x2b, 0x7c, 0x3a, 0x61, 0xd7, 0x8f, 0xac, 0x82, 0x42, 0x49, 0xcb, 0xf2, 0x23, 0xb6, 0x45, 0x47, 0x64, 0x8e, 0xcd, 0x36, 0xf3, 0x8c, 0x82, 0x42, 0x49, 0xc4, 0xbe, 0x01, 0x65, 0xdd, 0x9e, 0xb2, 0x9a, 0x4c, 0xf0, 0xd8, 0xd9, 0x91, 0x52, 0x4a, 0x02, 0x8b, 0x28, 0x41, 0xb5, 0x3d, 0x7b, 0xb3, 0x29, 0x2b, 0x25, 0x81, 0x09, 0xca, 0x4d, 0xd8, 0x20, 0xa3, 0x91, 0xcb, 0x8c, 0x87, 0x86, 0xc4, 0xfd, 0xa1, 0x12, 0xc1, 0x9c, 0xb8, 0x73, 0x02, 0x85, 0x30, 0x0e, 0xec, 0xa8, 0x66, 0x91, 0x50, 0x1d, 0xf1, 0x6e, 0x97, 0xde, 0x2b, 0x2a, 0x05, 0x2b, 0x14, 0xde, 0x80, 0xb2, 0xe1, 0xa9, 0xb3, 0x27, 0xe8, 0xf4, 0x6e, 0x7a, 0xaf, 0xa0, 0x94, 0x0c, 0x2f, 0x7a, 0xbe, 0xab, 0x7e, 0x93, 0x86, 0x4a, 0xf2, 0x09, 0x1d, 0x37, 0xa1, 0x60, 0xda, 0x1a, 0xe1, 0xa9, 0x25, 0xbe, 0xdf, 0xec, 0x3d, 0xe7, 0xd5, 0xbd, 0xd6, 0x0e, 0xf8, 0x4a, 0xa4, 0xb9, 0xf3, 0x8f, 0x14, 0x14, 0x42, 0x18, 0x5f, 0x81, 0xac, 0x43, 0xfc, 0x31, 0x37, 0x97, 0x3b, 0x4a, 0xa3, 0x94, 0xc2, 0xdb, 0x0c, 0xf7, 0x1c, 0x62, 0xf1, 0x14, 0x08, 0x70, 0xd6, 0x66, 0xf3, 0x6a, 0x52, 0xa2, 0xf3, 0xcb, 0x89, 0x3d, 0x99, 0x50, 0xcb, 0xf7, 0xc2, 0x79, 0x0d, 0xf0, 0x46, 0x00, 0xe3, 0x77, 0x60, 0xd3, 0x77, 0x89, 0x61, 0x26, 0xb8, 0x59, 0xce, 0x45, 0xa1, 0x20, 0x22, 0x1f, 0xc2, 0xb5, 0xd0, 0xae, 0x4e, 0x7d, 0xa2, 0x8d, 0xa9, 0x3e, 0x53, 0xca, 0xf3, 0xf7, 0xd9, 0xab, 0x01, 0xa1, 0x19, 0xc8, 0x43, 0xdd, 0xea, 0x77, 0x29, 0xd8, 0x0c, 0xaf, 0x53, 0x7a, 0x14, 0xac, 0x53, 0x00, 0x62, 0x59, 0xb6, 0x1f, 0x0f, 0xd7, 0x62, 0x2a, 0x2f, 0xe8, 0xd5, 0xea, 0x91, 0x92, 0x12, 0x33, 0xb0, 0x33, 0x01, 0x98, 0x49, 0x56, 0x86, 0xed, 0x3a, 0x94, 0x82, 0xef, 0x23, 0xfc, 0x23, 0x9b, 0xb8, 0x80, 0x83, 0x80, 0xd8, 0xbd, 0x0b, 0x6f, 0x43, 0xee, 0x9c, 0x8e, 0x0c, 0x2b, 0x78, 0xf5, 0x14, 0x8d, 0xf0, 0x25, 0x37, 0x1b, 0xbd, 0xe4, 0x1e, 0xfd, 0x21, 0x05, 0x5b, 0x9a, 0x3d, 0x99, 0xf7, 0xf7, 0x08, 0xcd, 0xbd, 0x02, 0x78, 0x9f, 0xa4, 0xbe, 0xf8, 0x78, 0x64, 0xf8, 0xe3, 0xe9, 0x79, 0x4d, 0xb3, 0x27, 0xfb, 0x23, 0xdb, 0x24, 0xd6, 0x68, 0xf6, 0x95, 0x90, 0xff, 0xd1, 0xde, 0x1d, 0x51, 0xeb, 0xdd, 0x91, 0x1d, 0xfb, 0x66, 0xf8, 0xd1, 0xec, 0xef, 0xd7, 0xe9, 0xcc, 0x71, 0xef, 0xe8, 0xaf, 0xe9, 0x9d, 0x63, 0xd1, 0x57, 0x2f, 0x8c, 0x8d, 0x42, 0x87, 0x26, 0xd5, 0xd8, 0x78, 0xff, 0x17, 0x00, 0x00, 0xff, 0xff, 0x0c, 0xab, 0xb6, 0x37, 0x7e, 0x1c, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // // The messages in this file describe the definitions found in .proto files. // A valid .proto file can be translated directly to a FileDescriptorProto // without any other information (e.g. without reading its imports). syntax = "proto2"; package google.protobuf; option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor"; option java_package = "com.google.protobuf"; option java_outer_classname = "DescriptorProtos"; option csharp_namespace = "Google.Protobuf.Reflection"; option objc_class_prefix = "GPB"; // descriptor.proto must be optimized for speed because reflection-based // algorithms don't work during bootstrapping. option optimize_for = SPEED; // The protocol compiler can output a FileDescriptorSet containing the .proto // files it parses. message FileDescriptorSet { repeated FileDescriptorProto file = 1; } // Describes a complete .proto file. message FileDescriptorProto { optional string name = 1; // file name, relative to root of source tree optional string package = 2; // e.g. "foo", "foo.bar", etc. // Names of files imported by this file. repeated string dependency = 3; // Indexes of the public imported files in the dependency list above. repeated int32 public_dependency = 10; // Indexes of the weak imported files in the dependency list. // For Google-internal migration only. Do not use. repeated int32 weak_dependency = 11; // All top-level definitions in this file. repeated DescriptorProto message_type = 4; repeated EnumDescriptorProto enum_type = 5; repeated ServiceDescriptorProto service = 6; repeated FieldDescriptorProto extension = 7; optional FileOptions options = 8; // This field contains optional information about the original source code. // You may safely remove this entire field without harming runtime // functionality of the descriptors -- the information is needed only by // development tools. optional SourceCodeInfo source_code_info = 9; // The syntax of the proto file. // The supported values are "proto2" and "proto3". optional string syntax = 12; } // Describes a message type. message DescriptorProto { optional string name = 1; repeated FieldDescriptorProto field = 2; repeated FieldDescriptorProto extension = 6; repeated DescriptorProto nested_type = 3; repeated EnumDescriptorProto enum_type = 4; message ExtensionRange { optional int32 start = 1; optional int32 end = 2; optional ExtensionRangeOptions options = 3; } repeated ExtensionRange extension_range = 5; repeated OneofDescriptorProto oneof_decl = 8; optional MessageOptions options = 7; // Range of reserved tag numbers. Reserved tag numbers may not be used by // fields or extension ranges in the same message. Reserved ranges may // not overlap. message ReservedRange { optional int32 start = 1; // Inclusive. optional int32 end = 2; // Exclusive. } repeated ReservedRange reserved_range = 9; // Reserved field names, which may not be used by fields in the same message. // A given name may only be reserved once. repeated string reserved_name = 10; } message ExtensionRangeOptions { // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } // Describes a field within a message. message FieldDescriptorProto { enum Type { // 0 is reserved for errors. // Order is weird for historical reasons. TYPE_DOUBLE = 1; TYPE_FLOAT = 2; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if // negative values are likely. TYPE_INT64 = 3; TYPE_UINT64 = 4; // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if // negative values are likely. TYPE_INT32 = 5; TYPE_FIXED64 = 6; TYPE_FIXED32 = 7; TYPE_BOOL = 8; TYPE_STRING = 9; // Tag-delimited aggregate. // Group type is deprecated and not supported in proto3. However, Proto3 // implementations should still be able to parse the group wire format and // treat group fields as unknown fields. TYPE_GROUP = 10; TYPE_MESSAGE = 11; // Length-delimited aggregate. // New in version 2. TYPE_BYTES = 12; TYPE_UINT32 = 13; TYPE_ENUM = 14; TYPE_SFIXED32 = 15; TYPE_SFIXED64 = 16; TYPE_SINT32 = 17; // Uses ZigZag encoding. TYPE_SINT64 = 18; // Uses ZigZag encoding. }; enum Label { // 0 is reserved for errors LABEL_OPTIONAL = 1; LABEL_REQUIRED = 2; LABEL_REPEATED = 3; }; optional string name = 1; optional int32 number = 3; optional Label label = 4; // If type_name is set, this need not be set. If both this and type_name // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. optional Type type = 5; // For message and enum types, this is the name of the type. If the name // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping // rules are used to find the type (i.e. first the nested types within this // message are searched, then within the parent, on up to the root // namespace). optional string type_name = 6; // For extensions, this is the name of the type being extended. It is // resolved in the same manner as type_name. optional string extendee = 2; // For numeric types, contains the original text representation of the value. // For booleans, "true" or "false". // For strings, contains the default text contents (not escaped in any way). // For bytes, contains the C escaped value. All bytes >= 128 are escaped. // TODO(kenton): Base-64 encode? optional string default_value = 7; // If set, gives the index of a oneof in the containing type's oneof_decl // list. This field is a member of that oneof. optional int32 oneof_index = 9; // JSON name of this field. The value is set by protocol compiler. If the // user has set a "json_name" option on this field, that option's value // will be used. Otherwise, it's deduced from the field's name by converting // it to camelCase. optional string json_name = 10; optional FieldOptions options = 8; } // Describes a oneof. message OneofDescriptorProto { optional string name = 1; optional OneofOptions options = 2; } // Describes an enum type. message EnumDescriptorProto { optional string name = 1; repeated EnumValueDescriptorProto value = 2; optional EnumOptions options = 3; } // Describes a value within an enum. message EnumValueDescriptorProto { optional string name = 1; optional int32 number = 2; optional EnumValueOptions options = 3; } // Describes a service. message ServiceDescriptorProto { optional string name = 1; repeated MethodDescriptorProto method = 2; optional ServiceOptions options = 3; } // Describes a method of a service. message MethodDescriptorProto { optional string name = 1; // Input and output type names. These are resolved in the same way as // FieldDescriptorProto.type_name, but must refer to a message type. optional string input_type = 2; optional string output_type = 3; optional MethodOptions options = 4; // Identifies if client streams multiple client messages optional bool client_streaming = 5 [default=false]; // Identifies if server streams multiple server messages optional bool server_streaming = 6 [default=false]; } // =================================================================== // Options // Each of the definitions above may have "options" attached. These are // just annotations which may cause code to be generated slightly differently // or may contain hints for code that manipulates protocol messages. // // Clients may define custom options as extensions of the *Options messages. // These extensions may not yet be known at parsing time, so the parser cannot // store the values in them. Instead it stores them in a field in the *Options // message called uninterpreted_option. This field must have the same name // across all *Options messages. We then use this field to populate the // extensions when we build a descriptor, at which point all protos have been // parsed and so all extensions are known. // // Extension numbers for custom options may be chosen as follows: // * For options which will only be used within a single application or // organization, or for experimental options, use field numbers 50000 // through 99999. It is up to you to ensure that you do not use the // same number for multiple options. // * For options which will be published and used publicly by multiple // independent entities, e-mail protobuf-global-extension-registry@google.com // to reserve extension numbers. Simply provide your project name (e.g. // Objective-C plugin) and your project website (if available) -- there's no // need to explain how you intend to use them. Usually you only need one // extension number. You can declare multiple options with only one extension // number by putting them in a sub-message. See the Custom Options section of // the docs for examples: // https://developers.google.com/protocol-buffers/docs/proto#options // If this turns out to be popular, a web service will be set up // to automatically assign option numbers. message FileOptions { // Sets the Java package where classes generated from this .proto will be // placed. By default, the proto package is used, but this is often // inappropriate because proto packages do not normally start with backwards // domain names. optional string java_package = 1; // If set, all the classes from the .proto file are wrapped in a single // outer class with the given name. This applies to both Proto1 // (equivalent to the old "--one_java_file" option) and Proto2 (where // a .proto always translates to a single class, but you may want to // explicitly choose the class name). optional string java_outer_classname = 8; // If set true, then the Java code generator will generate a separate .java // file for each top-level message, enum, and service defined in the .proto // file. Thus, these types will *not* be nested inside the outer class // named by java_outer_classname. However, the outer class will still be // generated to contain the file's getDescriptor() method as well as any // top-level extensions defined in the file. optional bool java_multiple_files = 10 [default=false]; // This option does nothing. optional bool java_generate_equals_and_hash = 20 [deprecated=true]; // If set true, then the Java2 code generator will generate code that // throws an exception whenever an attempt is made to assign a non-UTF-8 // byte sequence to a string field. // Message reflection will do the same. // However, an extension field still accepts non-UTF-8 byte sequences. // This option has no effect on when used with the lite runtime. optional bool java_string_check_utf8 = 27 [default=false]; // Generated classes can be optimized for speed or code size. enum OptimizeMode { SPEED = 1; // Generate complete code for parsing, serialization, // etc. CODE_SIZE = 2; // Use ReflectionOps to implement these methods. LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. } optional OptimizeMode optimize_for = 9 [default=SPEED]; // Sets the Go package where structs generated from this .proto will be // placed. If omitted, the Go package will be derived from the following: // - The basename of the package import path, if provided. // - Otherwise, the package statement in the .proto file, if present. // - Otherwise, the basename of the .proto file, without extension. optional string go_package = 11; // Should generic services be generated in each language? "Generic" services // are not specific to any particular RPC system. They are generated by the // main code generators in each language (without additional plugins). // Generic services were the only kind of service generation supported by // early versions of google.protobuf. // // Generic services are now considered deprecated in favor of using plugins // that generate code specific to your particular RPC system. Therefore, // these default to false. Old code which depends on generic services should // explicitly set them to true. optional bool cc_generic_services = 16 [default=false]; optional bool java_generic_services = 17 [default=false]; optional bool py_generic_services = 18 [default=false]; optional bool php_generic_services = 42 [default=false]; // Is this file deprecated? // Depending on the target platform, this can emit Deprecated annotations // for everything in the file, or it will be completely ignored; in the very // least, this is a formalization for deprecating files. optional bool deprecated = 23 [default=false]; // Enables the use of arenas for the proto messages in this file. This applies // only to generated classes for C++. optional bool cc_enable_arenas = 31 [default=false]; // Sets the objective c class prefix which is prepended to all objective c // generated classes from this .proto. There is no default. optional string objc_class_prefix = 36; // Namespace for generated classes; defaults to the package. optional string csharp_namespace = 37; // By default Swift generators will take the proto package and CamelCase it // replacing '.' with underscore and use that to prefix the types/symbols // defined. When this options is provided, they will use this value instead // to prefix the types/symbols defined. optional string swift_prefix = 39; // Sets the php class prefix which is prepended to all php generated classes // from this .proto. Default is empty. optional string php_class_prefix = 40; // Use this option to change the namespace of php generated classes. Default // is empty. When this option is empty, the package name will be used for // determining the namespace. optional string php_namespace = 41; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; reserved 38; } message MessageOptions { // Set true to use the old proto1 MessageSet wire format for extensions. // This is provided for backwards-compatibility with the MessageSet wire // format. You should not use this for any other reason: It's less // efficient, has fewer features, and is more complicated. // // The message must be defined exactly as follows: // message Foo { // option message_set_wire_format = true; // extensions 4 to max; // } // Note that the message cannot have any defined fields; MessageSets only // have extensions. // // All extensions of your type must be singular messages; e.g. they cannot // be int32s, enums, or repeated messages. // // Because this is an option, the above two restrictions are not enforced by // the protocol compiler. optional bool message_set_wire_format = 1 [default=false]; // Disables the generation of the standard "descriptor()" accessor, which can // conflict with a field of the same name. This is meant to make migration // from proto1 easier; new code should avoid fields named "descriptor". optional bool no_standard_descriptor_accessor = 2 [default=false]; // Is this message deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the message, or it will be completely ignored; in the very least, // this is a formalization for deprecating messages. optional bool deprecated = 3 [default=false]; // Whether the message is an automatically generated map entry type for the // maps field. // // For maps fields: // map map_field = 1; // The parsed descriptor looks like: // message MapFieldEntry { // option map_entry = true; // optional KeyType key = 1; // optional ValueType value = 2; // } // repeated MapFieldEntry map_field = 1; // // Implementations may choose not to generate the map_entry=true message, but // use a native map in the target language to hold the keys and values. // The reflection APIs in such implementions still need to work as // if the field is a repeated message field. // // NOTE: Do not set the option in .proto files. Always use the maps syntax // instead. The option should only be implicitly set by the proto compiler // parser. optional bool map_entry = 7; reserved 8; // javalite_serializable reserved 9; // javanano_as_lite // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message FieldOptions { // The ctype option instructs the C++ code generator to use a different // representation of the field than it normally would. See the specific // options below. This option is not yet implemented in the open source // release -- sorry, we'll try to include it in a future version! optional CType ctype = 1 [default = STRING]; enum CType { // Default mode. STRING = 0; CORD = 1; STRING_PIECE = 2; } // The packed option can be enabled for repeated primitive fields to enable // a more efficient representation on the wire. Rather than repeatedly // writing the tag and type for each element, the entire array is encoded as // a single length-delimited blob. In proto3, only explicit setting it to // false will avoid using packed encoding. optional bool packed = 2; // The jstype option determines the JavaScript type used for values of the // field. The option is permitted only for 64 bit integral and fixed types // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING // is represented as JavaScript string, which avoids loss of precision that // can happen when a large value is converted to a floating point JavaScript. // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to // use the JavaScript "number" type. The behavior of the default option // JS_NORMAL is implementation dependent. // // This option is an enum to permit additional types to be added, e.g. // goog.math.Integer. optional JSType jstype = 6 [default = JS_NORMAL]; enum JSType { // Use the default type. JS_NORMAL = 0; // Use JavaScript strings. JS_STRING = 1; // Use JavaScript numbers. JS_NUMBER = 2; } // Should this field be parsed lazily? Lazy applies only to message-type // fields. It means that when the outer message is initially parsed, the // inner message's contents will not be parsed but instead stored in encoded // form. The inner message will actually be parsed when it is first accessed. // // This is only a hint. Implementations are free to choose whether to use // eager or lazy parsing regardless of the value of this option. However, // setting this option true suggests that the protocol author believes that // using lazy parsing on this field is worth the additional bookkeeping // overhead typically needed to implement it. // // This option does not affect the public interface of any generated code; // all method signatures remain the same. Furthermore, thread-safety of the // interface is not affected by this option; const methods remain safe to // call from multiple threads concurrently, while non-const methods continue // to require exclusive access. // // // Note that implementations may choose not to check required fields within // a lazy sub-message. That is, calling IsInitialized() on the outer message // may return true even if the inner message has missing required fields. // This is necessary because otherwise the inner message would have to be // parsed in order to perform the check, defeating the purpose of lazy // parsing. An implementation which chooses not to check required fields // must be consistent about it. That is, for any particular sub-message, the // implementation must either *always* check its required fields, or *never* // check its required fields, regardless of whether or not the message has // been parsed. optional bool lazy = 5 [default=false]; // Is this field deprecated? // Depending on the target platform, this can emit Deprecated annotations // for accessors, or it will be completely ignored; in the very least, this // is a formalization for deprecating fields. optional bool deprecated = 3 [default=false]; // For Google-internal migration only. Do not use. optional bool weak = 10 [default=false]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; reserved 4; // removed jtype } message OneofOptions { // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message EnumOptions { // Set this option to true to allow mapping different tag names to the same // value. optional bool allow_alias = 2; // Is this enum deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the enum, or it will be completely ignored; in the very least, this // is a formalization for deprecating enums. optional bool deprecated = 3 [default=false]; reserved 5; // javanano_as_lite // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message EnumValueOptions { // Is this enum value deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the enum value, or it will be completely ignored; in the very least, // this is a formalization for deprecating enum values. optional bool deprecated = 1 [default=false]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message ServiceOptions { // Note: Field numbers 1 through 32 are reserved for Google's internal RPC // framework. We apologize for hoarding these numbers to ourselves, but // we were already using them long before we decided to release Protocol // Buffers. // Is this service deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the service, or it will be completely ignored; in the very least, // this is a formalization for deprecating services. optional bool deprecated = 33 [default=false]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } message MethodOptions { // Note: Field numbers 1 through 32 are reserved for Google's internal RPC // framework. We apologize for hoarding these numbers to ourselves, but // we were already using them long before we decided to release Protocol // Buffers. // Is this method deprecated? // Depending on the target platform, this can emit Deprecated annotations // for the method, or it will be completely ignored; in the very least, // this is a formalization for deprecating methods. optional bool deprecated = 33 [default=false]; // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, // or neither? HTTP based RPC implementation may choose GET verb for safe // methods, and PUT verb for idempotent methods instead of the default POST. enum IdempotencyLevel { IDEMPOTENCY_UNKNOWN = 0; NO_SIDE_EFFECTS = 1; // implies idempotent IDEMPOTENT = 2; // idempotent, but may have side effects } optional IdempotencyLevel idempotency_level = 34 [default=IDEMPOTENCY_UNKNOWN]; // The parser stores options it doesn't recognize here. See above. repeated UninterpretedOption uninterpreted_option = 999; // Clients can define custom options in extensions of this message. See above. extensions 1000 to max; } // A message representing a option the parser does not recognize. This only // appears in options protos created by the compiler::Parser class. // DescriptorPool resolves these when building Descriptor objects. Therefore, // options protos in descriptor objects (e.g. returned by Descriptor::options(), // or produced by Descriptor::CopyTo()) will never have UninterpretedOptions // in them. message UninterpretedOption { // The name of the uninterpreted option. Each string represents a segment in // a dot-separated name. is_extension is true iff a segment represents an // extension (denoted with parentheses in options specs in .proto files). // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents // "foo.(bar.baz).qux". message NamePart { required string name_part = 1; required bool is_extension = 2; } repeated NamePart name = 2; // The value of the uninterpreted option, in whatever type the tokenizer // identified it as during parsing. Exactly one of these should be set. optional string identifier_value = 3; optional uint64 positive_int_value = 4; optional int64 negative_int_value = 5; optional double double_value = 6; optional bytes string_value = 7; optional string aggregate_value = 8; } // =================================================================== // Optional source code info // Encapsulates information about the original source file from which a // FileDescriptorProto was generated. message SourceCodeInfo { // A Location identifies a piece of source code in a .proto file which // corresponds to a particular definition. This information is intended // to be useful to IDEs, code indexers, documentation generators, and similar // tools. // // For example, say we have a file like: // message Foo { // optional string foo = 1; // } // Let's look at just the field definition: // optional string foo = 1; // ^ ^^ ^^ ^ ^^^ // a bc de f ghi // We have the following locations: // span path represents // [a,i) [ 4, 0, 2, 0 ] The whole field definition. // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). // // Notes: // - A location may refer to a repeated field itself (i.e. not to any // particular index within it). This is used whenever a set of elements are // logically enclosed in a single code segment. For example, an entire // extend block (possibly containing multiple extension definitions) will // have an outer location whose path refers to the "extensions" repeated // field without an index. // - Multiple locations may have the same path. This happens when a single // logical declaration is spread out across multiple places. The most // obvious example is the "extend" block again -- there may be multiple // extend blocks in the same scope, each of which will have the same path. // - A location's span is not always a subset of its parent's span. For // example, the "extendee" of an extension declaration appears at the // beginning of the "extend" block and is shared by all extensions within // the block. // - Just because a location's span is a subset of some other location's span // does not mean that it is a descendent. For example, a "group" defines // both a type and a field in a single declaration. Thus, the locations // corresponding to the type and field and their components will overlap. // - Code which tries to interpret locations should probably be designed to // ignore those that it doesn't understand, as more types of locations could // be recorded in the future. repeated Location location = 1; message Location { // Identifies which part of the FileDescriptorProto was defined at this // location. // // Each element is a field number or an index. They form a path from // the root FileDescriptorProto to the place where the definition. For // example, this path: // [ 4, 3, 2, 7, 1 ] // refers to: // file.message_type(3) // 4, 3 // .field(7) // 2, 7 // .name() // 1 // This is because FileDescriptorProto.message_type has field number 4: // repeated DescriptorProto message_type = 4; // and DescriptorProto.field has field number 2: // repeated FieldDescriptorProto field = 2; // and FieldDescriptorProto.name has field number 1: // optional string name = 1; // // Thus, the above path gives the location of a field name. If we removed // the last element: // [ 4, 3, 2, 7 ] // this path refers to the whole field declaration (from the beginning // of the label to the terminating semicolon). repeated int32 path = 1 [packed=true]; // Always has exactly three or four elements: start line, start column, // end line (optional, otherwise assumed same as start line), end column. // These are packed into a single field for efficiency. Note that line // and column numbers are zero-based -- typically you will want to add // 1 to each before displaying to a user. repeated int32 span = 2 [packed=true]; // If this SourceCodeInfo represents a complete declaration, these are any // comments appearing before and after the declaration which appear to be // attached to the declaration. // // A series of line comments appearing on consecutive lines, with no other // tokens appearing on those lines, will be treated as a single comment. // // leading_detached_comments will keep paragraphs of comments that appear // before (but not connected to) the current element. Each paragraph, // separated by empty lines, will be one comment element in the repeated // field. // // Only the comment content is provided; comment markers (e.g. //) are // stripped out. For block comments, leading whitespace and an asterisk // will be stripped from the beginning of each line other than the first. // Newlines are included in the output. // // Examples: // // optional int32 foo = 1; // Comment attached to foo. // // Comment attached to bar. // optional int32 bar = 2; // // optional string baz = 3; // // Comment attached to baz. // // Another line attached to baz. // // // Comment attached to qux. // // // // Another line attached to qux. // optional double qux = 4; // // // Detached comment for corge. This is not leading or trailing comments // // to qux or corge because there are blank lines separating it from // // both. // // // Detached comment for corge paragraph 2. // // optional string corge = 5; // /* Block comment attached // * to corge. Leading asterisks // * will be removed. */ // /* Block comment attached to // * grault. */ // optional int32 grault = 6; // // // ignored detached comments. optional string leading_comments = 3; optional string trailing_comments = 4; repeated string leading_detached_comments = 6; } } // Describes the relationship between generated code and its original source // file. A GeneratedCodeInfo message is associated with only one generated // source file, but may contain references to different source .proto files. message GeneratedCodeInfo { // An Annotation connects some span of text in generated code to an element // of its generating .proto file. repeated Annotation annotation = 1; message Annotation { // Identifies the element in the original source .proto file. This field // is formatted the same as SourceCodeInfo.Location.path. repeated int32 path = 1 [packed=true]; // Identifies the filesystem path to the original source .proto. optional string source_file = 2; // Identifies the starting offset in bytes in the generated code // that relates to the identified object. optional int32 begin = 3; // Identifies the ending offset in bytes in the generated code that // relates to the identified offset. The end offset should be one past // the last relevant byte (so the length of the text = end - begin). optional int32 end = 4; } } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/doc.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. /* A plugin for the Google protocol buffer compiler to generate Go code. Run it by building this program and putting it in your path with the name protoc-gen-go That word 'go' at the end becomes part of the option string set for the protocol compiler, so once the protocol compiler (protoc) is installed you can run protoc --go_out=output_directory input_directory/file.proto to generate Go bindings for the protocol defined by file.proto. With that input, the output will be written to output_directory/file.pb.go The generated code is documented in the package comment for the library. See the README and documentation for protocol buffers to learn more: https://developers.google.com/protocol-buffers/ */ package documentation ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/generator/Makefile ================================================ # Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/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. include $(GOROOT)/src/Make.inc TARG=github.com/golang/protobuf/compiler/generator GOFILES=\ generator.go\ DEPS=../descriptor ../plugin ../../proto include $(GOROOT)/src/Make.pkg ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/generator/generator.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. /* The code generator for the plugin for the Google protocol buffer compiler. It generates Go code from the protocol buffer description files read by the main routine. */ package generator import ( "bufio" "bytes" "compress/gzip" "fmt" "go/parser" "go/printer" "go/token" "log" "os" "path" "strconv" "strings" "unicode" "unicode/utf8" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/protoc-gen-go/descriptor" plugin "github.com/golang/protobuf/protoc-gen-go/plugin" ) // generatedCodeVersion indicates a version of the generated code. // It is incremented whenever an incompatibility between the generated code and // proto package is introduced; the generated code references // a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion). const generatedCodeVersion = 2 // A Plugin provides functionality to add to the output during Go code generation, // such as to produce RPC stubs. type Plugin interface { // Name identifies the plugin. Name() string // Init is called once after data structures are built but before // code generation begins. Init(g *Generator) // Generate produces the code generated by the plugin for this file, // except for the imports, by calling the generator's methods P, In, and Out. Generate(file *FileDescriptor) // GenerateImports produces the import declarations for this file. // It is called after Generate. GenerateImports(file *FileDescriptor) } var plugins []Plugin // RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated. // It is typically called during initialization. func RegisterPlugin(p Plugin) { plugins = append(plugins, p) } // Each type we import as a protocol buffer (other than FileDescriptorProto) needs // a pointer to the FileDescriptorProto that represents it. These types achieve that // wrapping by placing each Proto inside a struct with the pointer to its File. The // structs have the same names as their contents, with "Proto" removed. // FileDescriptor is used to store the things that it points to. // The file and package name method are common to messages and enums. type common struct { file *descriptor.FileDescriptorProto // File this object comes from. } // PackageName is name in the package clause in the generated file. func (c *common) PackageName() string { return uniquePackageOf(c.file) } func (c *common) File() *descriptor.FileDescriptorProto { return c.file } func fileIsProto3(file *descriptor.FileDescriptorProto) bool { return file.GetSyntax() == "proto3" } func (c *common) proto3() bool { return fileIsProto3(c.file) } // Descriptor represents a protocol buffer message. type Descriptor struct { common *descriptor.DescriptorProto parent *Descriptor // The containing message, if any. nested []*Descriptor // Inner messages, if any. enums []*EnumDescriptor // Inner enums, if any. ext []*ExtensionDescriptor // Extensions, if any. typename []string // Cached typename vector. index int // The index into the container, whether the file or another message. path string // The SourceCodeInfo path as comma-separated integers. group bool } // TypeName returns the elements of the dotted type name. // The package name is not part of this name. func (d *Descriptor) TypeName() []string { if d.typename != nil { return d.typename } n := 0 for parent := d; parent != nil; parent = parent.parent { n++ } s := make([]string, n, n) for parent := d; parent != nil; parent = parent.parent { n-- s[n] = parent.GetName() } d.typename = s return s } // EnumDescriptor describes an enum. If it's at top level, its parent will be nil. // Otherwise it will be the descriptor of the message in which it is defined. type EnumDescriptor struct { common *descriptor.EnumDescriptorProto parent *Descriptor // The containing message, if any. typename []string // Cached typename vector. index int // The index into the container, whether the file or a message. path string // The SourceCodeInfo path as comma-separated integers. } // TypeName returns the elements of the dotted type name. // The package name is not part of this name. func (e *EnumDescriptor) TypeName() (s []string) { if e.typename != nil { return e.typename } name := e.GetName() if e.parent == nil { s = make([]string, 1) } else { pname := e.parent.TypeName() s = make([]string, len(pname)+1) copy(s, pname) } s[len(s)-1] = name e.typename = s return s } // Everything but the last element of the full type name, CamelCased. // The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... . func (e *EnumDescriptor) prefix() string { if e.parent == nil { // If the enum is not part of a message, the prefix is just the type name. return CamelCase(*e.Name) + "_" } typeName := e.TypeName() return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_" } // The integer value of the named constant in this enumerated type. func (e *EnumDescriptor) integerValueAsString(name string) string { for _, c := range e.Value { if c.GetName() == name { return fmt.Sprint(c.GetNumber()) } } log.Fatal("cannot find value for enum constant") return "" } // ExtensionDescriptor describes an extension. If it's at top level, its parent will be nil. // Otherwise it will be the descriptor of the message in which it is defined. type ExtensionDescriptor struct { common *descriptor.FieldDescriptorProto parent *Descriptor // The containing message, if any. } // TypeName returns the elements of the dotted type name. // The package name is not part of this name. func (e *ExtensionDescriptor) TypeName() (s []string) { name := e.GetName() if e.parent == nil { // top-level extension s = make([]string, 1) } else { pname := e.parent.TypeName() s = make([]string, len(pname)+1) copy(s, pname) } s[len(s)-1] = name return s } // DescName returns the variable name used for the generated descriptor. func (e *ExtensionDescriptor) DescName() string { // The full type name. typeName := e.TypeName() // Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix. for i, s := range typeName { typeName[i] = CamelCase(s) } return "E_" + strings.Join(typeName, "_") } // ImportedDescriptor describes a type that has been publicly imported from another file. type ImportedDescriptor struct { common o Object } func (id *ImportedDescriptor) TypeName() []string { return id.o.TypeName() } // FileDescriptor describes an protocol buffer descriptor file (.proto). // It includes slices of all the messages and enums defined within it. // Those slices are constructed by WrapTypes. type FileDescriptor struct { *descriptor.FileDescriptorProto desc []*Descriptor // All the messages defined in this file. enum []*EnumDescriptor // All the enums defined in this file. ext []*ExtensionDescriptor // All the top-level extensions defined in this file. imp []*ImportedDescriptor // All types defined in files publicly imported by this file. // Comments, stored as a map of path (comma-separated integers) to the comment. comments map[string]*descriptor.SourceCodeInfo_Location // The full list of symbols that are exported, // as a map from the exported object to its symbols. // This is used for supporting public imports. exported map[Object][]symbol index int // The index of this file in the list of files to generate code for proto3 bool // whether to generate proto3 code for this file } // PackageName is the package name we'll use in the generated code to refer to this file. func (d *FileDescriptor) PackageName() string { return uniquePackageOf(d.FileDescriptorProto) } // VarName is the variable name we'll use in the generated code to refer // to the compressed bytes of this descriptor. It is not exported, so // it is only valid inside the generated package. func (d *FileDescriptor) VarName() string { return fmt.Sprintf("fileDescriptor%d", d.index) } // goPackageOption interprets the file's go_package option. // If there is no go_package, it returns ("", "", false). // If there's a simple name, it returns ("", pkg, true). // If the option implies an import path, it returns (impPath, pkg, true). func (d *FileDescriptor) goPackageOption() (impPath, pkg string, ok bool) { pkg = d.GetOptions().GetGoPackage() if pkg == "" { return } ok = true // The presence of a slash implies there's an import path. slash := strings.LastIndex(pkg, "/") if slash < 0 { return } impPath, pkg = pkg, pkg[slash+1:] // A semicolon-delimited suffix overrides the package name. sc := strings.IndexByte(impPath, ';') if sc < 0 { return } impPath, pkg = impPath[:sc], impPath[sc+1:] return } // goPackageName returns the Go package name to use in the // generated Go file. The result explicit reports whether the name // came from an option go_package statement. If explicit is false, // the name was derived from the protocol buffer's package statement // or the input file name. func (d *FileDescriptor) goPackageName() (name string, explicit bool) { // Does the file have a "go_package" option? if _, pkg, ok := d.goPackageOption(); ok { return pkg, true } // Does the file have a package clause? if pkg := d.GetPackage(); pkg != "" { return pkg, false } // Use the file base name. return baseName(d.GetName()), false } // goFileName returns the output name for the generated Go file. func (d *FileDescriptor) goFileName() string { name := *d.Name if ext := path.Ext(name); ext == ".proto" || ext == ".protodevel" { name = name[:len(name)-len(ext)] } name += ".pb.go" // Does the file have a "go_package" option? // If it does, it may override the filename. if impPath, _, ok := d.goPackageOption(); ok && impPath != "" { // Replace the existing dirname with the declared import path. _, name = path.Split(name) name = path.Join(impPath, name) return name } return name } func (d *FileDescriptor) addExport(obj Object, sym symbol) { d.exported[obj] = append(d.exported[obj], sym) } // symbol is an interface representing an exported Go symbol. type symbol interface { // GenerateAlias should generate an appropriate alias // for the symbol from the named package. GenerateAlias(g *Generator, pkg string) } type messageSymbol struct { sym string hasExtensions, isMessageSet bool hasOneof bool getters []getterSymbol } type getterSymbol struct { name string typ string typeName string // canonical name in proto world; empty for proto.Message and similar genType bool // whether typ contains a generated type (message/group/enum) } func (ms *messageSymbol) GenerateAlias(g *Generator, pkg string) { remoteSym := pkg + "." + ms.sym g.P("type ", ms.sym, " ", remoteSym) g.P("func (m *", ms.sym, ") Reset() { (*", remoteSym, ")(m).Reset() }") g.P("func (m *", ms.sym, ") String() string { return (*", remoteSym, ")(m).String() }") g.P("func (*", ms.sym, ") ProtoMessage() {}") if ms.hasExtensions { g.P("func (*", ms.sym, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange ", "{ return (*", remoteSym, ")(nil).ExtensionRangeArray() }") if ms.isMessageSet { g.P("func (m *", ms.sym, ") Marshal() ([]byte, error) ", "{ return (*", remoteSym, ")(m).Marshal() }") g.P("func (m *", ms.sym, ") Unmarshal(buf []byte) error ", "{ return (*", remoteSym, ")(m).Unmarshal(buf) }") } } if ms.hasOneof { // Oneofs and public imports do not mix well. // We can make them work okay for the binary format, // but they're going to break weirdly for text/JSON. enc := "_" + ms.sym + "_OneofMarshaler" dec := "_" + ms.sym + "_OneofUnmarshaler" size := "_" + ms.sym + "_OneofSizer" encSig := "(msg " + g.Pkg["proto"] + ".Message, b *" + g.Pkg["proto"] + ".Buffer) error" decSig := "(msg " + g.Pkg["proto"] + ".Message, tag, wire int, b *" + g.Pkg["proto"] + ".Buffer) (bool, error)" sizeSig := "(msg " + g.Pkg["proto"] + ".Message) int" g.P("func (m *", ms.sym, ") XXX_OneofFuncs() (func", encSig, ", func", decSig, ", func", sizeSig, ", []interface{}) {") g.P("return ", enc, ", ", dec, ", ", size, ", nil") g.P("}") g.P("func ", enc, encSig, " {") g.P("m := msg.(*", ms.sym, ")") g.P("m0 := (*", remoteSym, ")(m)") g.P("enc, _, _, _ := m0.XXX_OneofFuncs()") g.P("return enc(m0, b)") g.P("}") g.P("func ", dec, decSig, " {") g.P("m := msg.(*", ms.sym, ")") g.P("m0 := (*", remoteSym, ")(m)") g.P("_, dec, _, _ := m0.XXX_OneofFuncs()") g.P("return dec(m0, tag, wire, b)") g.P("}") g.P("func ", size, sizeSig, " {") g.P("m := msg.(*", ms.sym, ")") g.P("m0 := (*", remoteSym, ")(m)") g.P("_, _, size, _ := m0.XXX_OneofFuncs()") g.P("return size(m0)") g.P("}") } for _, get := range ms.getters { if get.typeName != "" { g.RecordTypeUse(get.typeName) } typ := get.typ val := "(*" + remoteSym + ")(m)." + get.name + "()" if get.genType { // typ will be "*pkg.T" (message/group) or "pkg.T" (enum) // or "map[t]*pkg.T" (map to message/enum). // The first two of those might have a "[]" prefix if it is repeated. // Drop any package qualifier since we have hoisted the type into this package. rep := strings.HasPrefix(typ, "[]") if rep { typ = typ[2:] } isMap := strings.HasPrefix(typ, "map[") star := typ[0] == '*' if !isMap { // map types handled lower down typ = typ[strings.Index(typ, ".")+1:] } if star { typ = "*" + typ } if rep { // Go does not permit conversion between slice types where both // element types are named. That means we need to generate a bit // of code in this situation. // typ is the element type. // val is the expression to get the slice from the imported type. ctyp := typ // conversion type expression; "Foo" or "(*Foo)" if star { ctyp = "(" + typ + ")" } g.P("func (m *", ms.sym, ") ", get.name, "() []", typ, " {") g.In() g.P("o := ", val) g.P("if o == nil {") g.In() g.P("return nil") g.Out() g.P("}") g.P("s := make([]", typ, ", len(o))") g.P("for i, x := range o {") g.In() g.P("s[i] = ", ctyp, "(x)") g.Out() g.P("}") g.P("return s") g.Out() g.P("}") continue } if isMap { // Split map[keyTyp]valTyp. bra, ket := strings.Index(typ, "["), strings.Index(typ, "]") keyTyp, valTyp := typ[bra+1:ket], typ[ket+1:] // Drop any package qualifier. // Only the value type may be foreign. star := valTyp[0] == '*' valTyp = valTyp[strings.Index(valTyp, ".")+1:] if star { valTyp = "*" + valTyp } typ := "map[" + keyTyp + "]" + valTyp g.P("func (m *", ms.sym, ") ", get.name, "() ", typ, " {") g.P("o := ", val) g.P("if o == nil { return nil }") g.P("s := make(", typ, ", len(o))") g.P("for k, v := range o {") g.P("s[k] = (", valTyp, ")(v)") g.P("}") g.P("return s") g.P("}") continue } // Convert imported type into the forwarding type. val = "(" + typ + ")(" + val + ")" } g.P("func (m *", ms.sym, ") ", get.name, "() ", typ, " { return ", val, " }") } } type enumSymbol struct { name string proto3 bool // Whether this came from a proto3 file. } func (es enumSymbol) GenerateAlias(g *Generator, pkg string) { s := es.name g.P("type ", s, " ", pkg, ".", s) g.P("var ", s, "_name = ", pkg, ".", s, "_name") g.P("var ", s, "_value = ", pkg, ".", s, "_value") g.P("func (x ", s, ") String() string { return (", pkg, ".", s, ")(x).String() }") if !es.proto3 { g.P("func (x ", s, ") Enum() *", s, "{ return (*", s, ")((", pkg, ".", s, ")(x).Enum()) }") g.P("func (x *", s, ") UnmarshalJSON(data []byte) error { return (*", pkg, ".", s, ")(x).UnmarshalJSON(data) }") } } type constOrVarSymbol struct { sym string typ string // either "const" or "var" cast string // if non-empty, a type cast is required (used for enums) } func (cs constOrVarSymbol) GenerateAlias(g *Generator, pkg string) { v := pkg + "." + cs.sym if cs.cast != "" { v = cs.cast + "(" + v + ")" } g.P(cs.typ, " ", cs.sym, " = ", v) } // Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects. type Object interface { PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness. TypeName() []string File() *descriptor.FileDescriptorProto } // Each package name we generate must be unique. The package we're generating // gets its own name but every other package must have a unique name that does // not conflict in the code we generate. These names are chosen globally (although // they don't have to be, it simplifies things to do them globally). func uniquePackageOf(fd *descriptor.FileDescriptorProto) string { s, ok := uniquePackageName[fd] if !ok { log.Fatal("internal error: no package name defined for " + fd.GetName()) } return s } // Generator is the type whose methods generate the output, stored in the associated response structure. type Generator struct { *bytes.Buffer Request *plugin.CodeGeneratorRequest // The input. Response *plugin.CodeGeneratorResponse // The output. Param map[string]string // Command-line parameters. PackageImportPath string // Go import path of the package we're generating code for ImportPrefix string // String to prefix to imported package file names. ImportMap map[string]string // Mapping from .proto file name to import path Pkg map[string]string // The names under which we import support packages packageName string // What we're calling ourselves. allFiles []*FileDescriptor // All files in the tree allFilesByName map[string]*FileDescriptor // All files by filename. genFiles []*FileDescriptor // Those files we will generate output for. file *FileDescriptor // The file we are compiling now. usedPackages map[string]bool // Names of packages used in current file. typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax. init []string // Lines to emit in the init function. indent string writeOutput bool } // New creates a new generator and allocates the request and response protobufs. func New() *Generator { g := new(Generator) g.Buffer = new(bytes.Buffer) g.Request = new(plugin.CodeGeneratorRequest) g.Response = new(plugin.CodeGeneratorResponse) return g } // Error reports a problem, including an error, and exits the program. func (g *Generator) Error(err error, msgs ...string) { s := strings.Join(msgs, " ") + ":" + err.Error() log.Print("protoc-gen-go: error:", s) os.Exit(1) } // Fail reports a problem and exits the program. func (g *Generator) Fail(msgs ...string) { s := strings.Join(msgs, " ") log.Print("protoc-gen-go: error:", s) os.Exit(1) } // CommandLineParameters breaks the comma-separated list of key=value pairs // in the parameter (a member of the request protobuf) into a key/value map. // It then sets file name mappings defined by those entries. func (g *Generator) CommandLineParameters(parameter string) { g.Param = make(map[string]string) for _, p := range strings.Split(parameter, ",") { if i := strings.Index(p, "="); i < 0 { g.Param[p] = "" } else { g.Param[p[0:i]] = p[i+1:] } } g.ImportMap = make(map[string]string) pluginList := "none" // Default list of plugin names to enable (empty means all). for k, v := range g.Param { switch k { case "import_prefix": g.ImportPrefix = v case "import_path": g.PackageImportPath = v case "plugins": pluginList = v default: if len(k) > 0 && k[0] == 'M' { g.ImportMap[k[1:]] = v } } } if pluginList != "" { // Amend the set of plugins. enabled := make(map[string]bool) for _, name := range strings.Split(pluginList, "+") { enabled[name] = true } var nplugins []Plugin for _, p := range plugins { if enabled[p.Name()] { nplugins = append(nplugins, p) } } plugins = nplugins } } // DefaultPackageName returns the package name printed for the object. // If its file is in a different package, it returns the package name we're using for this file, plus ".". // Otherwise it returns the empty string. func (g *Generator) DefaultPackageName(obj Object) string { pkg := obj.PackageName() if pkg == g.packageName { return "" } return pkg + "." } // For each input file, the unique package name to use, underscored. var uniquePackageName = make(map[*descriptor.FileDescriptorProto]string) // Package names already registered. Key is the name from the .proto file; // value is the name that appears in the generated code. var pkgNamesInUse = make(map[string]bool) // Create and remember a guaranteed unique package name for this file descriptor. // Pkg is the candidate name. If f is nil, it's a builtin package like "proto" and // has no file descriptor. func RegisterUniquePackageName(pkg string, f *FileDescriptor) string { // Convert dots to underscores before finding a unique alias. pkg = strings.Map(badToUnderscore, pkg) for i, orig := 1, pkg; pkgNamesInUse[pkg]; i++ { // It's a duplicate; must rename. pkg = orig + strconv.Itoa(i) } // Install it. pkgNamesInUse[pkg] = true if f != nil { uniquePackageName[f.FileDescriptorProto] = pkg } return pkg } var isGoKeyword = map[string]bool{ "break": true, "case": true, "chan": true, "const": true, "continue": true, "default": true, "else": true, "defer": true, "fallthrough": true, "for": true, "func": true, "go": true, "goto": true, "if": true, "import": true, "interface": true, "map": true, "package": true, "range": true, "return": true, "select": true, "struct": true, "switch": true, "type": true, "var": true, } // defaultGoPackage returns the package name to use, // derived from the import path of the package we're building code for. func (g *Generator) defaultGoPackage() string { p := g.PackageImportPath if i := strings.LastIndex(p, "/"); i >= 0 { p = p[i+1:] } if p == "" { return "" } p = strings.Map(badToUnderscore, p) // Identifier must not be keyword: insert _. if isGoKeyword[p] { p = "_" + p } // Identifier must not begin with digit: insert _. if r, _ := utf8.DecodeRuneInString(p); unicode.IsDigit(r) { p = "_" + p } return p } // SetPackageNames sets the package name for this run. // The package name must agree across all files being generated. // It also defines unique package names for all imported files. func (g *Generator) SetPackageNames() { // Register the name for this package. It will be the first name // registered so is guaranteed to be unmodified. pkg, explicit := g.genFiles[0].goPackageName() // Check all files for an explicit go_package option. for _, f := range g.genFiles { thisPkg, thisExplicit := f.goPackageName() if thisExplicit { if !explicit { // Let this file's go_package option serve for all input files. pkg, explicit = thisPkg, true } else if thisPkg != pkg { g.Fail("inconsistent package names:", thisPkg, pkg) } } } // If we don't have an explicit go_package option but we have an // import path, use that. if !explicit { p := g.defaultGoPackage() if p != "" { pkg, explicit = p, true } } // If there was no go_package and no import path to use, // double-check that all the inputs have the same implicit // Go package name. if !explicit { for _, f := range g.genFiles { thisPkg, _ := f.goPackageName() if thisPkg != pkg { g.Fail("inconsistent package names:", thisPkg, pkg) } } } g.packageName = RegisterUniquePackageName(pkg, g.genFiles[0]) // Register the support package names. They might collide with the // name of a package we import. g.Pkg = map[string]string{ "fmt": RegisterUniquePackageName("fmt", nil), "math": RegisterUniquePackageName("math", nil), "proto": RegisterUniquePackageName("proto", nil), } AllFiles: for _, f := range g.allFiles { for _, genf := range g.genFiles { if f == genf { // In this package already. uniquePackageName[f.FileDescriptorProto] = g.packageName continue AllFiles } } // The file is a dependency, so we want to ignore its go_package option // because that is only relevant for its specific generated output. pkg := f.GetPackage() if pkg == "" { pkg = baseName(*f.Name) } RegisterUniquePackageName(pkg, f) } } // WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos // and FileDescriptorProtos into file-referenced objects within the Generator. // It also creates the list of files to generate and so should be called before GenerateAllFiles. func (g *Generator) WrapTypes() { g.allFiles = make([]*FileDescriptor, 0, len(g.Request.ProtoFile)) g.allFilesByName = make(map[string]*FileDescriptor, len(g.allFiles)) for _, f := range g.Request.ProtoFile { // We must wrap the descriptors before we wrap the enums descs := wrapDescriptors(f) g.buildNestedDescriptors(descs) enums := wrapEnumDescriptors(f, descs) g.buildNestedEnums(descs, enums) exts := wrapExtensions(f) fd := &FileDescriptor{ FileDescriptorProto: f, desc: descs, enum: enums, ext: exts, exported: make(map[Object][]symbol), proto3: fileIsProto3(f), } extractComments(fd) g.allFiles = append(g.allFiles, fd) g.allFilesByName[f.GetName()] = fd } for _, fd := range g.allFiles { fd.imp = wrapImported(fd.FileDescriptorProto, g) } g.genFiles = make([]*FileDescriptor, 0, len(g.Request.FileToGenerate)) for _, fileName := range g.Request.FileToGenerate { fd := g.allFilesByName[fileName] if fd == nil { g.Fail("could not find file named", fileName) } fd.index = len(g.genFiles) g.genFiles = append(g.genFiles, fd) } } // Scan the descriptors in this file. For each one, build the slice of nested descriptors func (g *Generator) buildNestedDescriptors(descs []*Descriptor) { for _, desc := range descs { if len(desc.NestedType) != 0 { for _, nest := range descs { if nest.parent == desc { desc.nested = append(desc.nested, nest) } } if len(desc.nested) != len(desc.NestedType) { g.Fail("internal error: nesting failure for", desc.GetName()) } } } } func (g *Generator) buildNestedEnums(descs []*Descriptor, enums []*EnumDescriptor) { for _, desc := range descs { if len(desc.EnumType) != 0 { for _, enum := range enums { if enum.parent == desc { desc.enums = append(desc.enums, enum) } } if len(desc.enums) != len(desc.EnumType) { g.Fail("internal error: enum nesting failure for", desc.GetName()) } } } } // Construct the Descriptor func newDescriptor(desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *Descriptor { d := &Descriptor{ common: common{file}, DescriptorProto: desc, parent: parent, index: index, } if parent == nil { d.path = fmt.Sprintf("%d,%d", messagePath, index) } else { d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index) } // The only way to distinguish a group from a message is whether // the containing message has a TYPE_GROUP field that matches. if parent != nil { parts := d.TypeName() if file.Package != nil { parts = append([]string{*file.Package}, parts...) } exp := "." + strings.Join(parts, ".") for _, field := range parent.Field { if field.GetType() == descriptor.FieldDescriptorProto_TYPE_GROUP && field.GetTypeName() == exp { d.group = true break } } } for _, field := range desc.Extension { d.ext = append(d.ext, &ExtensionDescriptor{common{file}, field, d}) } return d } // Return a slice of all the Descriptors defined within this file func wrapDescriptors(file *descriptor.FileDescriptorProto) []*Descriptor { sl := make([]*Descriptor, 0, len(file.MessageType)+10) for i, desc := range file.MessageType { sl = wrapThisDescriptor(sl, desc, nil, file, i) } return sl } // Wrap this Descriptor, recursively func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) []*Descriptor { sl = append(sl, newDescriptor(desc, parent, file, index)) me := sl[len(sl)-1] for i, nested := range desc.NestedType { sl = wrapThisDescriptor(sl, nested, me, file, i) } return sl } // Construct the EnumDescriptor func newEnumDescriptor(desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *EnumDescriptor { ed := &EnumDescriptor{ common: common{file}, EnumDescriptorProto: desc, parent: parent, index: index, } if parent == nil { ed.path = fmt.Sprintf("%d,%d", enumPath, index) } else { ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index) } return ed } // Return a slice of all the EnumDescriptors defined within this file func wrapEnumDescriptors(file *descriptor.FileDescriptorProto, descs []*Descriptor) []*EnumDescriptor { sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10) // Top-level enums. for i, enum := range file.EnumType { sl = append(sl, newEnumDescriptor(enum, nil, file, i)) } // Enums within messages. Enums within embedded messages appear in the outer-most message. for _, nested := range descs { for i, enum := range nested.EnumType { sl = append(sl, newEnumDescriptor(enum, nested, file, i)) } } return sl } // Return a slice of all the top-level ExtensionDescriptors defined within this file. func wrapExtensions(file *descriptor.FileDescriptorProto) []*ExtensionDescriptor { var sl []*ExtensionDescriptor for _, field := range file.Extension { sl = append(sl, &ExtensionDescriptor{common{file}, field, nil}) } return sl } // Return a slice of all the types that are publicly imported into this file. func wrapImported(file *descriptor.FileDescriptorProto, g *Generator) (sl []*ImportedDescriptor) { for _, index := range file.PublicDependency { df := g.fileByName(file.Dependency[index]) for _, d := range df.desc { if d.GetOptions().GetMapEntry() { continue } sl = append(sl, &ImportedDescriptor{common{file}, d}) } for _, e := range df.enum { sl = append(sl, &ImportedDescriptor{common{file}, e}) } for _, ext := range df.ext { sl = append(sl, &ImportedDescriptor{common{file}, ext}) } } return } func extractComments(file *FileDescriptor) { file.comments = make(map[string]*descriptor.SourceCodeInfo_Location) for _, loc := range file.GetSourceCodeInfo().GetLocation() { if loc.LeadingComments == nil { continue } var p []string for _, n := range loc.Path { p = append(p, strconv.Itoa(int(n))) } file.comments[strings.Join(p, ",")] = loc } } // BuildTypeNameMap builds the map from fully qualified type names to objects. // The key names for the map come from the input data, which puts a period at the beginning. // It should be called after SetPackageNames and before GenerateAllFiles. func (g *Generator) BuildTypeNameMap() { g.typeNameToObject = make(map[string]Object) for _, f := range g.allFiles { // The names in this loop are defined by the proto world, not us, so the // package name may be empty. If so, the dotted package name of X will // be ".X"; otherwise it will be ".pkg.X". dottedPkg := "." + f.GetPackage() if dottedPkg != "." { dottedPkg += "." } for _, enum := range f.enum { name := dottedPkg + dottedSlice(enum.TypeName()) g.typeNameToObject[name] = enum } for _, desc := range f.desc { name := dottedPkg + dottedSlice(desc.TypeName()) g.typeNameToObject[name] = desc } } } // ObjectNamed, given a fully-qualified input type name as it appears in the input data, // returns the descriptor for the message or enum with that name. func (g *Generator) ObjectNamed(typeName string) Object { o, ok := g.typeNameToObject[typeName] if !ok { g.Fail("can't find object with type", typeName) } // If the file of this object isn't a direct dependency of the current file, // or in the current file, then this object has been publicly imported into // a dependency of the current file. // We should return the ImportedDescriptor object for it instead. direct := *o.File().Name == *g.file.Name if !direct { for _, dep := range g.file.Dependency { if *g.fileByName(dep).Name == *o.File().Name { direct = true break } } } if !direct { found := false Loop: for _, dep := range g.file.Dependency { df := g.fileByName(*g.fileByName(dep).Name) for _, td := range df.imp { if td.o == o { // Found it! o = td found = true break Loop } } } if !found { log.Printf("protoc-gen-go: WARNING: failed finding publicly imported dependency for %v, used in %v", typeName, *g.file.Name) } } return o } // P prints the arguments to the generated output. It handles strings and int32s, plus // handling indirections because they may be *string, etc. func (g *Generator) P(str ...interface{}) { if !g.writeOutput { return } g.WriteString(g.indent) for _, v := range str { switch s := v.(type) { case string: g.WriteString(s) case *string: g.WriteString(*s) case bool: fmt.Fprintf(g, "%t", s) case *bool: fmt.Fprintf(g, "%t", *s) case int: fmt.Fprintf(g, "%d", s) case *int32: fmt.Fprintf(g, "%d", *s) case *int64: fmt.Fprintf(g, "%d", *s) case float64: fmt.Fprintf(g, "%g", s) case *float64: fmt.Fprintf(g, "%g", *s) default: g.Fail(fmt.Sprintf("unknown type in printer: %T", v)) } } g.WriteByte('\n') } // addInitf stores the given statement to be printed inside the file's init function. // The statement is given as a format specifier and arguments. func (g *Generator) addInitf(stmt string, a ...interface{}) { g.init = append(g.init, fmt.Sprintf(stmt, a...)) } // In Indents the output one tab stop. func (g *Generator) In() { g.indent += "\t" } // Out unindents the output one tab stop. func (g *Generator) Out() { if len(g.indent) > 0 { g.indent = g.indent[1:] } } // GenerateAllFiles generates the output for all the files we're outputting. func (g *Generator) GenerateAllFiles() { // Initialize the plugins for _, p := range plugins { p.Init(g) } // Generate the output. The generator runs for every file, even the files // that we don't generate output for, so that we can collate the full list // of exported symbols to support public imports. genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles)) for _, file := range g.genFiles { genFileMap[file] = true } for _, file := range g.allFiles { g.Reset() g.writeOutput = genFileMap[file] g.generate(file) if !g.writeOutput { continue } g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{ Name: proto.String(file.goFileName()), Content: proto.String(g.String()), }) } } // Run all the plugins associated with the file. func (g *Generator) runPlugins(file *FileDescriptor) { for _, p := range plugins { p.Generate(file) } } // FileOf return the FileDescriptor for this FileDescriptorProto. func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor { for _, file := range g.allFiles { if file.FileDescriptorProto == fd { return file } } g.Fail("could not find file in table:", fd.GetName()) return nil } // Fill the response protocol buffer with the generated output for all the files we're // supposed to generate. func (g *Generator) generate(file *FileDescriptor) { g.file = g.FileOf(file.FileDescriptorProto) g.usedPackages = make(map[string]bool) if g.file.index == 0 { // For one file in the package, assert version compatibility. g.P("// This is a compile-time assertion to ensure that this generated file") g.P("// is compatible with the proto package it is being compiled against.") g.P("// A compilation error at this line likely means your copy of the") g.P("// proto package needs to be updated.") g.P("const _ = ", g.Pkg["proto"], ".ProtoPackageIsVersion", generatedCodeVersion, " // please upgrade the proto package") g.P() } for _, td := range g.file.imp { g.generateImported(td) } for _, enum := range g.file.enum { g.generateEnum(enum) } for _, desc := range g.file.desc { // Don't generate virtual messages for maps. if desc.GetOptions().GetMapEntry() { continue } g.generateMessage(desc) } for _, ext := range g.file.ext { g.generateExtension(ext) } g.generateInitFunction() // Run the plugins before the imports so we know which imports are necessary. g.runPlugins(file) g.generateFileDescriptor(file) // Generate header and imports last, though they appear first in the output. rem := g.Buffer g.Buffer = new(bytes.Buffer) g.generateHeader() g.generateImports() if !g.writeOutput { return } g.Write(rem.Bytes()) // Reformat generated code. fset := token.NewFileSet() raw := g.Bytes() ast, err := parser.ParseFile(fset, "", g, parser.ParseComments) if err != nil { // Print out the bad code with line numbers. // This should never happen in practice, but it can while changing generated code, // so consider this a debugging aid. var src bytes.Buffer s := bufio.NewScanner(bytes.NewReader(raw)) for line := 1; s.Scan(); line++ { fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes()) } g.Fail("bad Go source code was generated:", err.Error(), "\n"+src.String()) } g.Reset() err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast) if err != nil { g.Fail("generated Go source code could not be reformatted:", err.Error()) } } // Generate the header, including package definition func (g *Generator) generateHeader() { g.P("// Code generated by protoc-gen-go. DO NOT EDIT.") g.P("// source: ", g.file.Name) g.P() name := g.file.PackageName() if g.file.index == 0 { // Generate package docs for the first file in the package. g.P("/*") g.P("Package ", name, " is a generated protocol buffer package.") g.P() if loc, ok := g.file.comments[strconv.Itoa(packagePath)]; ok { // not using g.PrintComments because this is a /* */ comment block. text := strings.TrimSuffix(loc.GetLeadingComments(), "\n") for _, line := range strings.Split(text, "\n") { line = strings.TrimPrefix(line, " ") // ensure we don't escape from the block comment line = strings.Replace(line, "*/", "* /", -1) g.P(line) } g.P() } var topMsgs []string g.P("It is generated from these files:") for _, f := range g.genFiles { g.P("\t", f.Name) for _, msg := range f.desc { if msg.parent != nil { continue } topMsgs = append(topMsgs, CamelCaseSlice(msg.TypeName())) } } g.P() g.P("It has these top-level messages:") for _, msg := range topMsgs { g.P("\t", msg) } g.P("*/") } g.P("package ", name) g.P() } // PrintComments prints any comments from the source .proto file. // The path is a comma-separated list of integers. // It returns an indication of whether any comments were printed. // See descriptor.proto for its format. func (g *Generator) PrintComments(path string) bool { if !g.writeOutput { return false } if loc, ok := g.file.comments[path]; ok { text := strings.TrimSuffix(loc.GetLeadingComments(), "\n") for _, line := range strings.Split(text, "\n") { g.P("// ", strings.TrimPrefix(line, " ")) } return true } return false } func (g *Generator) fileByName(filename string) *FileDescriptor { return g.allFilesByName[filename] } // weak returns whether the ith import of the current file is a weak import. func (g *Generator) weak(i int32) bool { for _, j := range g.file.WeakDependency { if j == i { return true } } return false } // Generate the imports func (g *Generator) generateImports() { // We almost always need a proto import. Rather than computing when we // do, which is tricky when there's a plugin, just import it and // reference it later. The same argument applies to the fmt and math packages. g.P("import " + g.Pkg["proto"] + " " + strconv.Quote(g.ImportPrefix+"github.com/golang/protobuf/proto")) g.P("import " + g.Pkg["fmt"] + ` "fmt"`) g.P("import " + g.Pkg["math"] + ` "math"`) for i, s := range g.file.Dependency { fd := g.fileByName(s) // Do not import our own package. if fd.PackageName() == g.packageName { continue } filename := fd.goFileName() // By default, import path is the dirname of the Go filename. importPath := path.Dir(filename) if substitution, ok := g.ImportMap[s]; ok { importPath = substitution } importPath = g.ImportPrefix + importPath // Skip weak imports. if g.weak(int32(i)) { g.P("// skipping weak import ", fd.PackageName(), " ", strconv.Quote(importPath)) continue } // We need to import all the dependencies, even if we don't reference them, // because other code and tools depend on having the full transitive closure // of protocol buffer types in the binary. pname := fd.PackageName() if _, ok := g.usedPackages[pname]; !ok { pname = "_" } g.P("import ", pname, " ", strconv.Quote(importPath)) } g.P() // TODO: may need to worry about uniqueness across plugins for _, p := range plugins { p.GenerateImports(g.file) g.P() } g.P("// Reference imports to suppress errors if they are not otherwise used.") g.P("var _ = ", g.Pkg["proto"], ".Marshal") g.P("var _ = ", g.Pkg["fmt"], ".Errorf") g.P("var _ = ", g.Pkg["math"], ".Inf") g.P() } func (g *Generator) generateImported(id *ImportedDescriptor) { // Don't generate public import symbols for files that we are generating // code for, since those symbols will already be in this package. // We can't simply avoid creating the ImportedDescriptor objects, // because g.genFiles isn't populated at that stage. tn := id.TypeName() sn := tn[len(tn)-1] df := g.FileOf(id.o.File()) filename := *df.Name for _, fd := range g.genFiles { if *fd.Name == filename { g.P("// Ignoring public import of ", sn, " from ", filename) g.P() return } } g.P("// ", sn, " from public import ", filename) g.usedPackages[df.PackageName()] = true for _, sym := range df.exported[id.o] { sym.GenerateAlias(g, df.PackageName()) } g.P() } // Generate the enum definitions for this EnumDescriptor. func (g *Generator) generateEnum(enum *EnumDescriptor) { // The full type name typeName := enum.TypeName() // The full type name, CamelCased. ccTypeName := CamelCaseSlice(typeName) ccPrefix := enum.prefix() g.PrintComments(enum.path) g.P("type ", ccTypeName, " int32") g.file.addExport(enum, enumSymbol{ccTypeName, enum.proto3()}) g.P("const (") g.In() for i, e := range enum.Value { g.PrintComments(fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i)) name := ccPrefix + *e.Name g.P(name, " ", ccTypeName, " = ", e.Number) g.file.addExport(enum, constOrVarSymbol{name, "const", ccTypeName}) } g.Out() g.P(")") g.P("var ", ccTypeName, "_name = map[int32]string{") g.In() generated := make(map[int32]bool) // avoid duplicate values for _, e := range enum.Value { duplicate := "" if _, present := generated[*e.Number]; present { duplicate = "// Duplicate value: " } g.P(duplicate, e.Number, ": ", strconv.Quote(*e.Name), ",") generated[*e.Number] = true } g.Out() g.P("}") g.P("var ", ccTypeName, "_value = map[string]int32{") g.In() for _, e := range enum.Value { g.P(strconv.Quote(*e.Name), ": ", e.Number, ",") } g.Out() g.P("}") if !enum.proto3() { g.P("func (x ", ccTypeName, ") Enum() *", ccTypeName, " {") g.In() g.P("p := new(", ccTypeName, ")") g.P("*p = x") g.P("return p") g.Out() g.P("}") } g.P("func (x ", ccTypeName, ") String() string {") g.In() g.P("return ", g.Pkg["proto"], ".EnumName(", ccTypeName, "_name, int32(x))") g.Out() g.P("}") if !enum.proto3() { g.P("func (x *", ccTypeName, ") UnmarshalJSON(data []byte) error {") g.In() g.P("value, err := ", g.Pkg["proto"], ".UnmarshalJSONEnum(", ccTypeName, `_value, data, "`, ccTypeName, `")`) g.P("if err != nil {") g.In() g.P("return err") g.Out() g.P("}") g.P("*x = ", ccTypeName, "(value)") g.P("return nil") g.Out() g.P("}") } var indexes []string for m := enum.parent; m != nil; m = m.parent { // XXX: skip groups? indexes = append([]string{strconv.Itoa(m.index)}, indexes...) } indexes = append(indexes, strconv.Itoa(enum.index)) g.P("func (", ccTypeName, ") EnumDescriptor() ([]byte, []int) { return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "} }") if enum.file.GetPackage() == "google.protobuf" && enum.GetName() == "NullValue" { g.P("func (", ccTypeName, `) XXX_WellKnownType() string { return "`, enum.GetName(), `" }`) } g.P() } // The tag is a string like "varint,2,opt,name=fieldname,def=7" that // identifies details of the field for the protocol buffer marshaling and unmarshaling // code. The fields are: // wire encoding // protocol tag number // opt,req,rep for optional, required, or repeated // packed whether the encoding is "packed" (optional; repeated primitives only) // name= the original declared name // enum= the name of the enum type if it is an enum-typed field. // proto3 if this field is in a proto3 message // def= string representation of the default value, if any. // The default value must be in a representation that can be used at run-time // to generate the default value. Thus bools become 0 and 1, for instance. func (g *Generator) goTag(message *Descriptor, field *descriptor.FieldDescriptorProto, wiretype string) string { optrepreq := "" switch { case isOptional(field): optrepreq = "opt" case isRequired(field): optrepreq = "req" case isRepeated(field): optrepreq = "rep" } var defaultValue string if dv := field.DefaultValue; dv != nil { // set means an explicit default defaultValue = *dv // Some types need tweaking. switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BOOL: if defaultValue == "true" { defaultValue = "1" } else { defaultValue = "0" } case descriptor.FieldDescriptorProto_TYPE_STRING, descriptor.FieldDescriptorProto_TYPE_BYTES: // Nothing to do. Quoting is done for the whole tag. case descriptor.FieldDescriptorProto_TYPE_ENUM: // For enums we need to provide the integer constant. obj := g.ObjectNamed(field.GetTypeName()) if id, ok := obj.(*ImportedDescriptor); ok { // It is an enum that was publicly imported. // We need the underlying type. obj = id.o } enum, ok := obj.(*EnumDescriptor) if !ok { log.Printf("obj is a %T", obj) if id, ok := obj.(*ImportedDescriptor); ok { log.Printf("id.o is a %T", id.o) } g.Fail("unknown enum type", CamelCaseSlice(obj.TypeName())) } defaultValue = enum.integerValueAsString(defaultValue) } defaultValue = ",def=" + defaultValue } enum := "" if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM { // We avoid using obj.PackageName(), because we want to use the // original (proto-world) package name. obj := g.ObjectNamed(field.GetTypeName()) if id, ok := obj.(*ImportedDescriptor); ok { obj = id.o } enum = ",enum=" if pkg := obj.File().GetPackage(); pkg != "" { enum += pkg + "." } enum += CamelCaseSlice(obj.TypeName()) } packed := "" if (field.Options != nil && field.Options.GetPacked()) || // Per https://developers.google.com/protocol-buffers/docs/proto3#simple: // "In proto3, repeated fields of scalar numeric types use packed encoding by default." (message.proto3() && (field.Options == nil || field.Options.Packed == nil) && isRepeated(field) && isScalar(field)) { packed = ",packed" } fieldName := field.GetName() name := fieldName if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { // We must use the type name for groups instead of // the field name to preserve capitalization. // type_name in FieldDescriptorProto is fully-qualified, // but we only want the local part. name = *field.TypeName if i := strings.LastIndex(name, "."); i >= 0 { name = name[i+1:] } } if json := field.GetJsonName(); json != "" && json != name { // TODO: escaping might be needed, in which case // perhaps this should be in its own "json" tag. name += ",json=" + json } name = ",name=" + name if message.proto3() { // We only need the extra tag for []byte fields; // no need to add noise for the others. if *field.Type == descriptor.FieldDescriptorProto_TYPE_BYTES { name += ",proto3" } } oneof := "" if field.OneofIndex != nil { oneof = ",oneof" } return strconv.Quote(fmt.Sprintf("%s,%d,%s%s%s%s%s%s", wiretype, field.GetNumber(), optrepreq, packed, name, enum, oneof, defaultValue)) } func needsStar(typ descriptor.FieldDescriptorProto_Type) bool { switch typ { case descriptor.FieldDescriptorProto_TYPE_GROUP: return false case descriptor.FieldDescriptorProto_TYPE_MESSAGE: return false case descriptor.FieldDescriptorProto_TYPE_BYTES: return false } return true } // TypeName is the printed name appropriate for an item. If the object is in the current file, // TypeName drops the package name and underscores the rest. // Otherwise the object is from another package; and the result is the underscored // package name followed by the item name. // The result always has an initial capital. func (g *Generator) TypeName(obj Object) string { return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName()) } // TypeNameWithPackage is like TypeName, but always includes the package // name even if the object is in our own package. func (g *Generator) TypeNameWithPackage(obj Object) string { return obj.PackageName() + CamelCaseSlice(obj.TypeName()) } // GoType returns a string representing the type name, and the wire type func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) { // TODO: Options. switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: typ, wire = "float64", "fixed64" case descriptor.FieldDescriptorProto_TYPE_FLOAT: typ, wire = "float32", "fixed32" case descriptor.FieldDescriptorProto_TYPE_INT64: typ, wire = "int64", "varint" case descriptor.FieldDescriptorProto_TYPE_UINT64: typ, wire = "uint64", "varint" case descriptor.FieldDescriptorProto_TYPE_INT32: typ, wire = "int32", "varint" case descriptor.FieldDescriptorProto_TYPE_UINT32: typ, wire = "uint32", "varint" case descriptor.FieldDescriptorProto_TYPE_FIXED64: typ, wire = "uint64", "fixed64" case descriptor.FieldDescriptorProto_TYPE_FIXED32: typ, wire = "uint32", "fixed32" case descriptor.FieldDescriptorProto_TYPE_BOOL: typ, wire = "bool", "varint" case descriptor.FieldDescriptorProto_TYPE_STRING: typ, wire = "string", "bytes" case descriptor.FieldDescriptorProto_TYPE_GROUP: desc := g.ObjectNamed(field.GetTypeName()) typ, wire = "*"+g.TypeName(desc), "group" case descriptor.FieldDescriptorProto_TYPE_MESSAGE: desc := g.ObjectNamed(field.GetTypeName()) typ, wire = "*"+g.TypeName(desc), "bytes" case descriptor.FieldDescriptorProto_TYPE_BYTES: typ, wire = "[]byte", "bytes" case descriptor.FieldDescriptorProto_TYPE_ENUM: desc := g.ObjectNamed(field.GetTypeName()) typ, wire = g.TypeName(desc), "varint" case descriptor.FieldDescriptorProto_TYPE_SFIXED32: typ, wire = "int32", "fixed32" case descriptor.FieldDescriptorProto_TYPE_SFIXED64: typ, wire = "int64", "fixed64" case descriptor.FieldDescriptorProto_TYPE_SINT32: typ, wire = "int32", "zigzag32" case descriptor.FieldDescriptorProto_TYPE_SINT64: typ, wire = "int64", "zigzag64" default: g.Fail("unknown type for", field.GetName()) } if isRepeated(field) { typ = "[]" + typ } else if message != nil && message.proto3() { return } else if field.OneofIndex != nil && message != nil { return } else if needsStar(*field.Type) { typ = "*" + typ } return } func (g *Generator) RecordTypeUse(t string) { if obj, ok := g.typeNameToObject[t]; ok { // Call ObjectNamed to get the true object to record the use. obj = g.ObjectNamed(t) g.usedPackages[obj.PackageName()] = true } } // Method names that may be generated. Fields with these names get an // underscore appended. Any change to this set is a potential incompatible // API change because it changes generated field names. var methodNames = [...]string{ "Reset", "String", "ProtoMessage", "Marshal", "Unmarshal", "ExtensionRangeArray", "ExtensionMap", "Descriptor", } // Names of messages in the `google.protobuf` package for which // we will generate XXX_WellKnownType methods. var wellKnownTypes = map[string]bool{ "Any": true, "Duration": true, "Empty": true, "Struct": true, "Timestamp": true, "Value": true, "ListValue": true, "DoubleValue": true, "FloatValue": true, "Int64Value": true, "UInt64Value": true, "Int32Value": true, "UInt32Value": true, "BoolValue": true, "StringValue": true, "BytesValue": true, } // Generate the type and default constant definitions for this Descriptor. func (g *Generator) generateMessage(message *Descriptor) { // The full type name typeName := message.TypeName() // The full type name, CamelCased. ccTypeName := CamelCaseSlice(typeName) usedNames := make(map[string]bool) for _, n := range methodNames { usedNames[n] = true } fieldNames := make(map[*descriptor.FieldDescriptorProto]string) fieldGetterNames := make(map[*descriptor.FieldDescriptorProto]string) fieldTypes := make(map[*descriptor.FieldDescriptorProto]string) mapFieldTypes := make(map[*descriptor.FieldDescriptorProto]string) oneofFieldName := make(map[int32]string) // indexed by oneof_index field of FieldDescriptorProto oneofDisc := make(map[int32]string) // name of discriminator method oneofTypeName := make(map[*descriptor.FieldDescriptorProto]string) // without star oneofInsertPoints := make(map[int32]int) // oneof_index => offset of g.Buffer g.PrintComments(message.path) g.P("type ", ccTypeName, " struct {") g.In() // allocNames finds a conflict-free variation of the given strings, // consistently mutating their suffixes. // It returns the same number of strings. allocNames := func(ns ...string) []string { Loop: for { for _, n := range ns { if usedNames[n] { for i := range ns { ns[i] += "_" } continue Loop } } for _, n := range ns { usedNames[n] = true } return ns } } for i, field := range message.Field { // Allocate the getter and the field at the same time so name // collisions create field/method consistent names. // TODO: This allocation occurs based on the order of the fields // in the proto file, meaning that a change in the field // ordering can change generated Method/Field names. base := CamelCase(*field.Name) ns := allocNames(base, "Get"+base) fieldName, fieldGetterName := ns[0], ns[1] typename, wiretype := g.GoType(message, field) jsonName := *field.Name tag := fmt.Sprintf("protobuf:%s json:%q", g.goTag(message, field, wiretype), jsonName+",omitempty") fieldNames[field] = fieldName fieldGetterNames[field] = fieldGetterName oneof := field.OneofIndex != nil if oneof && oneofFieldName[*field.OneofIndex] == "" { odp := message.OneofDecl[int(*field.OneofIndex)] fname := allocNames(CamelCase(odp.GetName()))[0] // This is the first field of a oneof we haven't seen before. // Generate the union field. com := g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageOneofPath, *field.OneofIndex)) if com { g.P("//") } g.P("// Types that are valid to be assigned to ", fname, ":") // Generate the rest of this comment later, // when we've computed any disambiguation. oneofInsertPoints[*field.OneofIndex] = g.Buffer.Len() dname := "is" + ccTypeName + "_" + fname oneofFieldName[*field.OneofIndex] = fname oneofDisc[*field.OneofIndex] = dname tag := `protobuf_oneof:"` + odp.GetName() + `"` g.P(fname, " ", dname, " `", tag, "`") } if *field.Type == descriptor.FieldDescriptorProto_TYPE_MESSAGE { desc := g.ObjectNamed(field.GetTypeName()) if d, ok := desc.(*Descriptor); ok && d.GetOptions().GetMapEntry() { // Figure out the Go types and tags for the key and value types. keyField, valField := d.Field[0], d.Field[1] keyType, keyWire := g.GoType(d, keyField) valType, valWire := g.GoType(d, valField) keyTag, valTag := g.goTag(d, keyField, keyWire), g.goTag(d, valField, valWire) // We don't use stars, except for message-typed values. // Message and enum types are the only two possibly foreign types used in maps, // so record their use. They are not permitted as map keys. keyType = strings.TrimPrefix(keyType, "*") switch *valField.Type { case descriptor.FieldDescriptorProto_TYPE_ENUM: valType = strings.TrimPrefix(valType, "*") g.RecordTypeUse(valField.GetTypeName()) case descriptor.FieldDescriptorProto_TYPE_MESSAGE: g.RecordTypeUse(valField.GetTypeName()) default: valType = strings.TrimPrefix(valType, "*") } typename = fmt.Sprintf("map[%s]%s", keyType, valType) mapFieldTypes[field] = typename // record for the getter generation tag += fmt.Sprintf(" protobuf_key:%s protobuf_val:%s", keyTag, valTag) } } fieldTypes[field] = typename if oneof { tname := ccTypeName + "_" + fieldName // It is possible for this to collide with a message or enum // nested in this message. Check for collisions. for { ok := true for _, desc := range message.nested { if CamelCaseSlice(desc.TypeName()) == tname { ok = false break } } for _, enum := range message.enums { if CamelCaseSlice(enum.TypeName()) == tname { ok = false break } } if !ok { tname += "_" continue } break } oneofTypeName[field] = tname continue } g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i)) g.P(fieldName, "\t", typename, "\t`", tag, "`") g.RecordTypeUse(field.GetTypeName()) } if len(message.ExtensionRange) > 0 { g.P(g.Pkg["proto"], ".XXX_InternalExtensions `json:\"-\"`") } if !message.proto3() { g.P("XXX_unrecognized\t[]byte `json:\"-\"`") } g.Out() g.P("}") // Update g.Buffer to list valid oneof types. // We do this down here, after we've disambiguated the oneof type names. // We go in reverse order of insertion point to avoid invalidating offsets. for oi := int32(len(message.OneofDecl)); oi >= 0; oi-- { ip := oneofInsertPoints[oi] all := g.Buffer.Bytes() rem := all[ip:] g.Buffer = bytes.NewBuffer(all[:ip:ip]) // set cap so we don't scribble on rem for _, field := range message.Field { if field.OneofIndex == nil || *field.OneofIndex != oi { continue } g.P("//\t*", oneofTypeName[field]) } g.Buffer.Write(rem) } // Reset, String and ProtoMessage methods. g.P("func (m *", ccTypeName, ") Reset() { *m = ", ccTypeName, "{} }") g.P("func (m *", ccTypeName, ") String() string { return ", g.Pkg["proto"], ".CompactTextString(m) }") g.P("func (*", ccTypeName, ") ProtoMessage() {}") var indexes []string for m := message; m != nil; m = m.parent { indexes = append([]string{strconv.Itoa(m.index)}, indexes...) } g.P("func (*", ccTypeName, ") Descriptor() ([]byte, []int) { return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "} }") // TODO: Revisit the decision to use a XXX_WellKnownType method // if we change proto.MessageName to work with multiple equivalents. if message.file.GetPackage() == "google.protobuf" && wellKnownTypes[message.GetName()] { g.P("func (*", ccTypeName, `) XXX_WellKnownType() string { return "`, message.GetName(), `" }`) } // Extension support methods var hasExtensions, isMessageSet bool if len(message.ExtensionRange) > 0 { hasExtensions = true // message_set_wire_format only makes sense when extensions are defined. if opts := message.Options; opts != nil && opts.GetMessageSetWireFormat() { isMessageSet = true g.P() g.P("func (m *", ccTypeName, ") Marshal() ([]byte, error) {") g.In() g.P("return ", g.Pkg["proto"], ".MarshalMessageSet(&m.XXX_InternalExtensions)") g.Out() g.P("}") g.P("func (m *", ccTypeName, ") Unmarshal(buf []byte) error {") g.In() g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSet(buf, &m.XXX_InternalExtensions)") g.Out() g.P("}") g.P("func (m *", ccTypeName, ") MarshalJSON() ([]byte, error) {") g.In() g.P("return ", g.Pkg["proto"], ".MarshalMessageSetJSON(&m.XXX_InternalExtensions)") g.Out() g.P("}") g.P("func (m *", ccTypeName, ") UnmarshalJSON(buf []byte) error {") g.In() g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions)") g.Out() g.P("}") g.P("// ensure ", ccTypeName, " satisfies proto.Marshaler and proto.Unmarshaler") g.P("var _ ", g.Pkg["proto"], ".Marshaler = (*", ccTypeName, ")(nil)") g.P("var _ ", g.Pkg["proto"], ".Unmarshaler = (*", ccTypeName, ")(nil)") } g.P() g.P("var extRange_", ccTypeName, " = []", g.Pkg["proto"], ".ExtensionRange{") g.In() for _, r := range message.ExtensionRange { end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends g.P("{", r.Start, ", ", end, "},") } g.Out() g.P("}") g.P("func (*", ccTypeName, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange {") g.In() g.P("return extRange_", ccTypeName) g.Out() g.P("}") } // Default constants defNames := make(map[*descriptor.FieldDescriptorProto]string) for _, field := range message.Field { def := field.GetDefaultValue() if def == "" { continue } fieldname := "Default_" + ccTypeName + "_" + CamelCase(*field.Name) defNames[field] = fieldname typename, _ := g.GoType(message, field) if typename[0] == '*' { typename = typename[1:] } kind := "const " switch { case typename == "bool": case typename == "string": def = strconv.Quote(def) case typename == "[]byte": def = "[]byte(" + strconv.Quote(unescape(def)) + ")" kind = "var " case def == "inf", def == "-inf", def == "nan": // These names are known to, and defined by, the protocol language. switch def { case "inf": def = "math.Inf(1)" case "-inf": def = "math.Inf(-1)" case "nan": def = "math.NaN()" } if *field.Type == descriptor.FieldDescriptorProto_TYPE_FLOAT { def = "float32(" + def + ")" } kind = "var " case *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM: // Must be an enum. Need to construct the prefixed name. obj := g.ObjectNamed(field.GetTypeName()) var enum *EnumDescriptor if id, ok := obj.(*ImportedDescriptor); ok { // The enum type has been publicly imported. enum, _ = id.o.(*EnumDescriptor) } else { enum, _ = obj.(*EnumDescriptor) } if enum == nil { log.Printf("don't know how to generate constant for %s", fieldname) continue } def = g.DefaultPackageName(obj) + enum.prefix() + def } g.P(kind, fieldname, " ", typename, " = ", def) g.file.addExport(message, constOrVarSymbol{fieldname, kind, ""}) } g.P() // Oneof per-field types, discriminants and getters. // // Generate unexported named types for the discriminant interfaces. // We shouldn't have to do this, but there was (~19 Aug 2015) a compiler/linker bug // that was triggered by using anonymous interfaces here. // TODO: Revisit this and consider reverting back to anonymous interfaces. for oi := range message.OneofDecl { dname := oneofDisc[int32(oi)] g.P("type ", dname, " interface {") g.In() g.P(dname, "()") g.Out() g.P("}") } g.P() for _, field := range message.Field { if field.OneofIndex == nil { continue } _, wiretype := g.GoType(message, field) tag := "protobuf:" + g.goTag(message, field, wiretype) g.P("type ", oneofTypeName[field], " struct{ ", fieldNames[field], " ", fieldTypes[field], " `", tag, "` }") g.RecordTypeUse(field.GetTypeName()) } g.P() for _, field := range message.Field { if field.OneofIndex == nil { continue } g.P("func (*", oneofTypeName[field], ") ", oneofDisc[*field.OneofIndex], "() {}") } g.P() for oi := range message.OneofDecl { fname := oneofFieldName[int32(oi)] g.P("func (m *", ccTypeName, ") Get", fname, "() ", oneofDisc[int32(oi)], " {") g.P("if m != nil { return m.", fname, " }") g.P("return nil") g.P("}") } g.P() // Field getters var getters []getterSymbol for _, field := range message.Field { oneof := field.OneofIndex != nil fname := fieldNames[field] typename, _ := g.GoType(message, field) if t, ok := mapFieldTypes[field]; ok { typename = t } mname := fieldGetterNames[field] star := "" if needsStar(*field.Type) && typename[0] == '*' { typename = typename[1:] star = "*" } // Only export getter symbols for basic types, // and for messages and enums in the same package. // Groups are not exported. // Foreign types can't be hoisted through a public import because // the importer may not already be importing the defining .proto. // As an example, imagine we have an import tree like this: // A.proto -> B.proto -> C.proto // If A publicly imports B, we need to generate the getters from B in A's output, // but if one such getter returns something from C then we cannot do that // because A is not importing C already. var getter, genType bool switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_GROUP: getter = false case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_ENUM: // Only export getter if its return type is in this package. getter = g.ObjectNamed(field.GetTypeName()).PackageName() == message.PackageName() genType = true default: getter = true } if getter { getters = append(getters, getterSymbol{ name: mname, typ: typename, typeName: field.GetTypeName(), genType: genType, }) } g.P("func (m *", ccTypeName, ") "+mname+"() "+typename+" {") g.In() def, hasDef := defNames[field] typeDefaultIsNil := false // whether this field type's default value is a literal nil unless specified switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BYTES: typeDefaultIsNil = !hasDef case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE: typeDefaultIsNil = true } if isRepeated(field) { typeDefaultIsNil = true } if typeDefaultIsNil && !oneof { // A bytes field with no explicit default needs less generated code, // as does a message or group field, or a repeated field. g.P("if m != nil {") g.In() g.P("return m." + fname) g.Out() g.P("}") g.P("return nil") g.Out() g.P("}") g.P() continue } if !oneof { if message.proto3() { g.P("if m != nil {") } else { g.P("if m != nil && m." + fname + " != nil {") } g.In() g.P("return " + star + "m." + fname) g.Out() g.P("}") } else { uname := oneofFieldName[*field.OneofIndex] tname := oneofTypeName[field] g.P("if x, ok := m.Get", uname, "().(*", tname, "); ok {") g.P("return x.", fname) g.P("}") } if hasDef { if *field.Type != descriptor.FieldDescriptorProto_TYPE_BYTES { g.P("return " + def) } else { // The default is a []byte var. // Make a copy when returning it to be safe. g.P("return append([]byte(nil), ", def, "...)") } } else { switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BOOL: g.P("return false") case descriptor.FieldDescriptorProto_TYPE_STRING: g.P(`return ""`) case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_BYTES: // This is only possible for oneof fields. g.P("return nil") case descriptor.FieldDescriptorProto_TYPE_ENUM: // The default default for an enum is the first value in the enum, // not zero. obj := g.ObjectNamed(field.GetTypeName()) var enum *EnumDescriptor if id, ok := obj.(*ImportedDescriptor); ok { // The enum type has been publicly imported. enum, _ = id.o.(*EnumDescriptor) } else { enum, _ = obj.(*EnumDescriptor) } if enum == nil { log.Printf("don't know how to generate getter for %s", field.GetName()) continue } if len(enum.Value) == 0 { g.P("return 0 // empty enum") } else { first := enum.Value[0].GetName() g.P("return ", g.DefaultPackageName(obj)+enum.prefix()+first) } default: g.P("return 0") } } g.Out() g.P("}") g.P() } if !message.group { ms := &messageSymbol{ sym: ccTypeName, hasExtensions: hasExtensions, isMessageSet: isMessageSet, hasOneof: len(message.OneofDecl) > 0, getters: getters, } g.file.addExport(message, ms) } // Oneof functions if len(message.OneofDecl) > 0 { fieldWire := make(map[*descriptor.FieldDescriptorProto]string) // method enc := "_" + ccTypeName + "_OneofMarshaler" dec := "_" + ccTypeName + "_OneofUnmarshaler" size := "_" + ccTypeName + "_OneofSizer" encSig := "(msg " + g.Pkg["proto"] + ".Message, b *" + g.Pkg["proto"] + ".Buffer) error" decSig := "(msg " + g.Pkg["proto"] + ".Message, tag, wire int, b *" + g.Pkg["proto"] + ".Buffer) (bool, error)" sizeSig := "(msg " + g.Pkg["proto"] + ".Message) (n int)" g.P("// XXX_OneofFuncs is for the internal use of the proto package.") g.P("func (*", ccTypeName, ") XXX_OneofFuncs() (func", encSig, ", func", decSig, ", func", sizeSig, ", []interface{}) {") g.P("return ", enc, ", ", dec, ", ", size, ", []interface{}{") for _, field := range message.Field { if field.OneofIndex == nil { continue } g.P("(*", oneofTypeName[field], ")(nil),") } g.P("}") g.P("}") g.P() // marshaler g.P("func ", enc, encSig, " {") g.P("m := msg.(*", ccTypeName, ")") for oi, odp := range message.OneofDecl { g.P("// ", odp.GetName()) fname := oneofFieldName[int32(oi)] g.P("switch x := m.", fname, ".(type) {") for _, field := range message.Field { if field.OneofIndex == nil || int(*field.OneofIndex) != oi { continue } g.P("case *", oneofTypeName[field], ":") var wire, pre, post string val := "x." + fieldNames[field] // overridden for TYPE_BOOL canFail := false // only TYPE_MESSAGE and TYPE_GROUP can fail switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: wire = "WireFixed64" pre = "b.EncodeFixed64(" + g.Pkg["math"] + ".Float64bits(" post = "))" case descriptor.FieldDescriptorProto_TYPE_FLOAT: wire = "WireFixed32" pre = "b.EncodeFixed32(uint64(" + g.Pkg["math"] + ".Float32bits(" post = ")))" case descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64: wire = "WireVarint" pre, post = "b.EncodeVarint(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_ENUM: wire = "WireVarint" pre, post = "b.EncodeVarint(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_SFIXED64: wire = "WireFixed64" pre, post = "b.EncodeFixed64(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED32: wire = "WireFixed32" pre, post = "b.EncodeFixed32(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_BOOL: // bool needs special handling. g.P("t := uint64(0)") g.P("if ", val, " { t = 1 }") val = "t" wire = "WireVarint" pre, post = "b.EncodeVarint(", ")" case descriptor.FieldDescriptorProto_TYPE_STRING: wire = "WireBytes" pre, post = "b.EncodeStringBytes(", ")" case descriptor.FieldDescriptorProto_TYPE_GROUP: wire = "WireStartGroup" pre, post = "b.Marshal(", ")" canFail = true case descriptor.FieldDescriptorProto_TYPE_MESSAGE: wire = "WireBytes" pre, post = "b.EncodeMessage(", ")" canFail = true case descriptor.FieldDescriptorProto_TYPE_BYTES: wire = "WireBytes" pre, post = "b.EncodeRawBytes(", ")" case descriptor.FieldDescriptorProto_TYPE_SINT32: wire = "WireVarint" pre, post = "b.EncodeZigzag32(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_SINT64: wire = "WireVarint" pre, post = "b.EncodeZigzag64(uint64(", "))" default: g.Fail("unhandled oneof field type ", field.Type.String()) } fieldWire[field] = wire g.P("b.EncodeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".", wire, ")") if !canFail { g.P(pre, val, post) } else { g.P("if err := ", pre, val, post, "; err != nil {") g.P("return err") g.P("}") } if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { g.P("b.EncodeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".WireEndGroup)") } } g.P("case nil:") g.P("default: return ", g.Pkg["fmt"], `.Errorf("`, ccTypeName, ".", fname, ` has unexpected type %T", x)`) g.P("}") } g.P("return nil") g.P("}") g.P() // unmarshaler g.P("func ", dec, decSig, " {") g.P("m := msg.(*", ccTypeName, ")") g.P("switch tag {") for _, field := range message.Field { if field.OneofIndex == nil { continue } odp := message.OneofDecl[int(*field.OneofIndex)] g.P("case ", field.Number, ": // ", odp.GetName(), ".", *field.Name) g.P("if wire != ", g.Pkg["proto"], ".", fieldWire[field], " {") g.P("return true, ", g.Pkg["proto"], ".ErrInternalBadWireType") g.P("}") lhs := "x, err" // overridden for TYPE_MESSAGE and TYPE_GROUP var dec, cast, cast2 string switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: dec, cast = "b.DecodeFixed64()", g.Pkg["math"]+".Float64frombits" case descriptor.FieldDescriptorProto_TYPE_FLOAT: dec, cast, cast2 = "b.DecodeFixed32()", "uint32", g.Pkg["math"]+".Float32frombits" case descriptor.FieldDescriptorProto_TYPE_INT64: dec, cast = "b.DecodeVarint()", "int64" case descriptor.FieldDescriptorProto_TYPE_UINT64: dec = "b.DecodeVarint()" case descriptor.FieldDescriptorProto_TYPE_INT32: dec, cast = "b.DecodeVarint()", "int32" case descriptor.FieldDescriptorProto_TYPE_FIXED64: dec = "b.DecodeFixed64()" case descriptor.FieldDescriptorProto_TYPE_FIXED32: dec, cast = "b.DecodeFixed32()", "uint32" case descriptor.FieldDescriptorProto_TYPE_BOOL: dec = "b.DecodeVarint()" // handled specially below case descriptor.FieldDescriptorProto_TYPE_STRING: dec = "b.DecodeStringBytes()" case descriptor.FieldDescriptorProto_TYPE_GROUP: g.P("msg := new(", fieldTypes[field][1:], ")") // drop star lhs = "err" dec = "b.DecodeGroup(msg)" // handled specially below case descriptor.FieldDescriptorProto_TYPE_MESSAGE: g.P("msg := new(", fieldTypes[field][1:], ")") // drop star lhs = "err" dec = "b.DecodeMessage(msg)" // handled specially below case descriptor.FieldDescriptorProto_TYPE_BYTES: dec = "b.DecodeRawBytes(true)" case descriptor.FieldDescriptorProto_TYPE_UINT32: dec, cast = "b.DecodeVarint()", "uint32" case descriptor.FieldDescriptorProto_TYPE_ENUM: dec, cast = "b.DecodeVarint()", fieldTypes[field] case descriptor.FieldDescriptorProto_TYPE_SFIXED32: dec, cast = "b.DecodeFixed32()", "int32" case descriptor.FieldDescriptorProto_TYPE_SFIXED64: dec, cast = "b.DecodeFixed64()", "int64" case descriptor.FieldDescriptorProto_TYPE_SINT32: dec, cast = "b.DecodeZigzag32()", "int32" case descriptor.FieldDescriptorProto_TYPE_SINT64: dec, cast = "b.DecodeZigzag64()", "int64" default: g.Fail("unhandled oneof field type ", field.Type.String()) } g.P(lhs, " := ", dec) val := "x" if cast != "" { val = cast + "(" + val + ")" } if cast2 != "" { val = cast2 + "(" + val + ")" } switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BOOL: val += " != 0" case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE: val = "msg" } g.P("m.", oneofFieldName[*field.OneofIndex], " = &", oneofTypeName[field], "{", val, "}") g.P("return true, err") } g.P("default: return false, nil") g.P("}") g.P("}") g.P() // sizer g.P("func ", size, sizeSig, " {") g.P("m := msg.(*", ccTypeName, ")") for oi, odp := range message.OneofDecl { g.P("// ", odp.GetName()) fname := oneofFieldName[int32(oi)] g.P("switch x := m.", fname, ".(type) {") for _, field := range message.Field { if field.OneofIndex == nil || int(*field.OneofIndex) != oi { continue } g.P("case *", oneofTypeName[field], ":") val := "x." + fieldNames[field] var wire, varint, fixed string switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: wire = "WireFixed64" fixed = "8" case descriptor.FieldDescriptorProto_TYPE_FLOAT: wire = "WireFixed32" fixed = "4" case descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64, descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_ENUM: wire = "WireVarint" varint = val case descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_SFIXED64: wire = "WireFixed64" fixed = "8" case descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED32: wire = "WireFixed32" fixed = "4" case descriptor.FieldDescriptorProto_TYPE_BOOL: wire = "WireVarint" fixed = "1" case descriptor.FieldDescriptorProto_TYPE_STRING: wire = "WireBytes" fixed = "len(" + val + ")" varint = fixed case descriptor.FieldDescriptorProto_TYPE_GROUP: wire = "WireStartGroup" fixed = g.Pkg["proto"] + ".Size(" + val + ")" case descriptor.FieldDescriptorProto_TYPE_MESSAGE: wire = "WireBytes" g.P("s := ", g.Pkg["proto"], ".Size(", val, ")") fixed = "s" varint = fixed case descriptor.FieldDescriptorProto_TYPE_BYTES: wire = "WireBytes" fixed = "len(" + val + ")" varint = fixed case descriptor.FieldDescriptorProto_TYPE_SINT32: wire = "WireVarint" varint = "(uint32(" + val + ") << 1) ^ uint32((int32(" + val + ") >> 31))" case descriptor.FieldDescriptorProto_TYPE_SINT64: wire = "WireVarint" varint = "uint64(" + val + " << 1) ^ uint64((int64(" + val + ") >> 63))" default: g.Fail("unhandled oneof field type ", field.Type.String()) } g.P("n += ", g.Pkg["proto"], ".SizeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".", wire, ")") if varint != "" { g.P("n += ", g.Pkg["proto"], ".SizeVarint(uint64(", varint, "))") } if fixed != "" { g.P("n += ", fixed) } if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { g.P("n += ", g.Pkg["proto"], ".SizeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".WireEndGroup)") } } g.P("case nil:") g.P("default:") g.P("panic(", g.Pkg["fmt"], ".Sprintf(\"proto: unexpected type %T in oneof\", x))") g.P("}") } g.P("return n") g.P("}") g.P() } for _, ext := range message.ext { g.generateExtension(ext) } fullName := strings.Join(message.TypeName(), ".") if g.file.Package != nil { fullName = *g.file.Package + "." + fullName } g.addInitf("%s.RegisterType((*%s)(nil), %q)", g.Pkg["proto"], ccTypeName, fullName) } var escapeChars = [256]byte{ 'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', 'v': '\v', '\\': '\\', '"': '"', '\'': '\'', '?': '?', } // unescape reverses the "C" escaping that protoc does for default values of bytes fields. // It is best effort in that it effectively ignores malformed input. Seemingly invalid escape // sequences are conveyed, unmodified, into the decoded result. func unescape(s string) string { // NB: Sadly, we can't use strconv.Unquote because protoc will escape both // single and double quotes, but strconv.Unquote only allows one or the // other (based on actual surrounding quotes of its input argument). var out []byte for len(s) > 0 { // regular character, or too short to be valid escape if s[0] != '\\' || len(s) < 2 { out = append(out, s[0]) s = s[1:] } else if c := escapeChars[s[1]]; c != 0 { // escape sequence out = append(out, c) s = s[2:] } else if s[1] == 'x' || s[1] == 'X' { // hex escape, e.g. "\x80 if len(s) < 4 { // too short to be valid out = append(out, s[:2]...) s = s[2:] continue } v, err := strconv.ParseUint(s[2:4], 16, 8) if err != nil { out = append(out, s[:4]...) } else { out = append(out, byte(v)) } s = s[4:] } else if '0' <= s[1] && s[1] <= '7' { // octal escape, can vary from 1 to 3 octal digits; e.g., "\0" "\40" or "\164" // so consume up to 2 more bytes or up to end-of-string n := len(s[1:]) - len(strings.TrimLeft(s[1:], "01234567")) if n > 3 { n = 3 } v, err := strconv.ParseUint(s[1:1+n], 8, 8) if err != nil { out = append(out, s[:1+n]...) } else { out = append(out, byte(v)) } s = s[1+n:] } else { // bad escape, just propagate the slash as-is out = append(out, s[0]) s = s[1:] } } return string(out) } func (g *Generator) generateExtension(ext *ExtensionDescriptor) { ccTypeName := ext.DescName() extObj := g.ObjectNamed(*ext.Extendee) var extDesc *Descriptor if id, ok := extObj.(*ImportedDescriptor); ok { // This is extending a publicly imported message. // We need the underlying type for goTag. extDesc = id.o.(*Descriptor) } else { extDesc = extObj.(*Descriptor) } extendedType := "*" + g.TypeName(extObj) // always use the original field := ext.FieldDescriptorProto fieldType, wireType := g.GoType(ext.parent, field) tag := g.goTag(extDesc, field, wireType) g.RecordTypeUse(*ext.Extendee) if n := ext.FieldDescriptorProto.TypeName; n != nil { // foreign extension type g.RecordTypeUse(*n) } typeName := ext.TypeName() // Special case for proto2 message sets: If this extension is extending // proto2_bridge.MessageSet, and its final name component is "message_set_extension", // then drop that last component. mset := false if extendedType == "*proto2_bridge.MessageSet" && typeName[len(typeName)-1] == "message_set_extension" { typeName = typeName[:len(typeName)-1] mset = true } // For text formatting, the package must be exactly what the .proto file declares, // ignoring overrides such as the go_package option, and with no dot/underscore mapping. extName := strings.Join(typeName, ".") if g.file.Package != nil { extName = *g.file.Package + "." + extName } g.P("var ", ccTypeName, " = &", g.Pkg["proto"], ".ExtensionDesc{") g.In() g.P("ExtendedType: (", extendedType, ")(nil),") g.P("ExtensionType: (", fieldType, ")(nil),") g.P("Field: ", field.Number, ",") g.P(`Name: "`, extName, `",`) g.P("Tag: ", tag, ",") g.P(`Filename: "`, g.file.GetName(), `",`) g.Out() g.P("}") g.P() if mset { // Generate a bit more code to register with message_set.go. g.addInitf("%s.RegisterMessageSetType((%s)(nil), %d, %q)", g.Pkg["proto"], fieldType, *field.Number, extName) } g.file.addExport(ext, constOrVarSymbol{ccTypeName, "var", ""}) } func (g *Generator) generateInitFunction() { for _, enum := range g.file.enum { g.generateEnumRegistration(enum) } for _, d := range g.file.desc { for _, ext := range d.ext { g.generateExtensionRegistration(ext) } } for _, ext := range g.file.ext { g.generateExtensionRegistration(ext) } if len(g.init) == 0 { return } g.P("func init() {") g.In() for _, l := range g.init { g.P(l) } g.Out() g.P("}") g.init = nil } func (g *Generator) generateFileDescriptor(file *FileDescriptor) { // Make a copy and trim source_code_info data. // TODO: Trim this more when we know exactly what we need. pb := proto.Clone(file.FileDescriptorProto).(*descriptor.FileDescriptorProto) pb.SourceCodeInfo = nil b, err := proto.Marshal(pb) if err != nil { g.Fail(err.Error()) } var buf bytes.Buffer w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression) w.Write(b) w.Close() b = buf.Bytes() v := file.VarName() g.P() g.P("func init() { ", g.Pkg["proto"], ".RegisterFile(", strconv.Quote(*file.Name), ", ", v, ") }") g.P("var ", v, " = []byte{") g.In() g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto") for len(b) > 0 { n := 16 if n > len(b) { n = len(b) } s := "" for _, c := range b[:n] { s += fmt.Sprintf("0x%02x,", c) } g.P(s) b = b[n:] } g.Out() g.P("}") } func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) { // // We always print the full (proto-world) package name here. pkg := enum.File().GetPackage() if pkg != "" { pkg += "." } // The full type name typeName := enum.TypeName() // The full type name, CamelCased. ccTypeName := CamelCaseSlice(typeName) g.addInitf("%s.RegisterEnum(%q, %[3]s_name, %[3]s_value)", g.Pkg["proto"], pkg+ccTypeName, ccTypeName) } func (g *Generator) generateExtensionRegistration(ext *ExtensionDescriptor) { g.addInitf("%s.RegisterExtension(%s)", g.Pkg["proto"], ext.DescName()) } // And now lots of helper functions. // Is c an ASCII lower-case letter? func isASCIILower(c byte) bool { return 'a' <= c && c <= 'z' } // Is c an ASCII digit? func isASCIIDigit(c byte) bool { return '0' <= c && c <= '9' } // CamelCase returns the CamelCased name. // If there is an interior underscore followed by a lower case letter, // drop the underscore and convert the letter to upper case. // There is a remote possibility of this rewrite causing a name collision, // but it's so remote we're prepared to pretend it's nonexistent - since the // C++ generator lowercases names, it's extremely unlikely to have two fields // with different capitalizations. // In short, _my_field_name_2 becomes XMyFieldName_2. func CamelCase(s string) string { if s == "" { return "" } t := make([]byte, 0, 32) i := 0 if s[0] == '_' { // Need a capital letter; drop the '_'. t = append(t, 'X') i++ } // Invariant: if the next letter is lower case, it must be converted // to upper case. // That is, we process a word at a time, where words are marked by _ or // upper case letter. Digits are treated as words. for ; i < len(s); i++ { c := s[i] if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) { continue // Skip the underscore in s. } if isASCIIDigit(c) { t = append(t, c) continue } // Assume we have a letter now - if not, it's a bogus identifier. // The next word is a sequence of characters that must start upper case. if isASCIILower(c) { c ^= ' ' // Make it a capital letter. } t = append(t, c) // Guaranteed not lower case. // Accept lower case sequence that follows. for i+1 < len(s) && isASCIILower(s[i+1]) { i++ t = append(t, s[i]) } } return string(t) } // CamelCaseSlice is like CamelCase, but the argument is a slice of strings to // be joined with "_". func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) } // dottedSlice turns a sliced name into a dotted name. func dottedSlice(elem []string) string { return strings.Join(elem, ".") } // Is this field optional? func isOptional(field *descriptor.FieldDescriptorProto) bool { return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL } // Is this field required? func isRequired(field *descriptor.FieldDescriptorProto) bool { return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED } // Is this field repeated? func isRepeated(field *descriptor.FieldDescriptorProto) bool { return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED } // Is this field a scalar numeric type? func isScalar(field *descriptor.FieldDescriptorProto) bool { if field.Type == nil { return false } switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE, descriptor.FieldDescriptorProto_TYPE_FLOAT, descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64, descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_BOOL, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_ENUM, descriptor.FieldDescriptorProto_TYPE_SFIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED64, descriptor.FieldDescriptorProto_TYPE_SINT32, descriptor.FieldDescriptorProto_TYPE_SINT64: return true default: return false } } // badToUnderscore is the mapping function used to generate Go names from package names, // which can be dotted in the input .proto file. It replaces non-identifier characters such as // dot or dash with underscore. func badToUnderscore(r rune) rune { if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' { return r } return '_' } // baseName returns the last path element of the name, with the last dotted suffix removed. func baseName(name string) string { // First, find the last element if i := strings.LastIndex(name, "/"); i >= 0 { name = name[i+1:] } // Now drop the suffix if i := strings.LastIndex(name, "."); i >= 0 { name = name[0:i] } return name } // The SourceCodeInfo message describes the location of elements of a parsed // .proto file by way of a "path", which is a sequence of integers that // describe the route from a FileDescriptorProto to the relevant submessage. // The path alternates between a field number of a repeated field, and an index // into that repeated field. The constants below define the field numbers that // are used. // // See descriptor.proto for more information about this. const ( // tag numbers in FileDescriptorProto packagePath = 2 // package messagePath = 4 // message_type enumPath = 5 // enum_type // tag numbers in DescriptorProto messageFieldPath = 2 // field messageMessagePath = 3 // nested_type messageEnumPath = 4 // enum_type messageOneofPath = 8 // oneof_decl // tag numbers in EnumDescriptorProto enumValuePath = 2 // value ) ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2013 The Go Authors. All rights reserved. // https://github.com/golang/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. package generator import ( "testing" "github.com/golang/protobuf/protoc-gen-go/descriptor" ) func TestCamelCase(t *testing.T) { tests := []struct { in, want string }{ {"one", "One"}, {"one_two", "OneTwo"}, {"_my_field_name_2", "XMyFieldName_2"}, {"Something_Capped", "Something_Capped"}, {"my_Name", "My_Name"}, {"OneTwo", "OneTwo"}, {"_", "X"}, {"_a_", "XA_"}, } for _, tc := range tests { if got := CamelCase(tc.in); got != tc.want { t.Errorf("CamelCase(%q) = %q, want %q", tc.in, got, tc.want) } } } func TestGoPackageOption(t *testing.T) { tests := []struct { in string impPath, pkg string ok bool }{ {"", "", "", false}, {"foo", "", "foo", true}, {"github.com/golang/bar", "github.com/golang/bar", "bar", true}, {"github.com/golang/bar;baz", "github.com/golang/bar", "baz", true}, } for _, tc := range tests { d := &FileDescriptor{ FileDescriptorProto: &descriptor.FileDescriptorProto{ Options: &descriptor.FileOptions{ GoPackage: &tc.in, }, }, } impPath, pkg, ok := d.goPackageOption() if impPath != tc.impPath || pkg != tc.pkg || ok != tc.ok { t.Errorf("go_package = %q => (%q, %q, %t), want (%q, %q, %t)", tc.in, impPath, pkg, ok, tc.impPath, tc.pkg, tc.ok) } } } func TestUnescape(t *testing.T) { tests := []struct { in string out string }{ // successful cases, including all kinds of escapes {"", ""}, {"foo bar baz frob nitz", "foo bar baz frob nitz"}, {`\000\001\002\003\004\005\006\007`, string([]byte{0, 1, 2, 3, 4, 5, 6, 7})}, {`\a\b\f\n\r\t\v\\\?\'\"`, string([]byte{'\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\', '?', '\'', '"'})}, {`\x10\x20\x30\x40\x50\x60\x70\x80`, string([]byte{16, 32, 48, 64, 80, 96, 112, 128})}, // variable length octal escapes {`\0\018\222\377\3\04\005\6\07`, string([]byte{0, 1, '8', 0222, 255, 3, 4, 5, 6, 7})}, // malformed escape sequences left as is {"foo \\g bar", "foo \\g bar"}, {"foo \\xg0 bar", "foo \\xg0 bar"}, {"\\", "\\"}, {"\\x", "\\x"}, {"\\xf", "\\xf"}, {"\\777", "\\777"}, // overflows byte } for _, tc := range tests { s := unescape(tc.in) if s != tc.out { t.Errorf("doUnescape(%q) = %q; should have been %q", tc.in, s, tc.out) } } } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/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. // Package grpc outputs gRPC service descriptions in Go code. // It runs as a plugin for the Go protocol buffer compiler plugin. // It is linked in to protoc-gen-go. package grpc import ( "fmt" "path" "strconv" "strings" pb "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/golang/protobuf/protoc-gen-go/generator" ) // generatedCodeVersion indicates a version of the generated code. // It is incremented whenever an incompatibility between the generated code and // the grpc package is introduced; the generated code references // a constant, grpc.SupportPackageIsVersionN (where N is generatedCodeVersion). const generatedCodeVersion = 4 // Paths for packages used by code generated in this file, // relative to the import_prefix of the generator.Generator. const ( contextPkgPath = "golang.org/x/net/context" grpcPkgPath = "google.golang.org/grpc" ) func init() { generator.RegisterPlugin(new(grpc)) } // grpc is an implementation of the Go protocol buffer compiler's // plugin architecture. It generates bindings for gRPC support. type grpc struct { gen *generator.Generator } // Name returns the name of this plugin, "grpc". func (g *grpc) Name() string { return "grpc" } // The names for packages imported in the generated code. // They may vary from the final path component of the import path // if the name is used by other packages. var ( contextPkg string grpcPkg string ) // Init initializes the plugin. func (g *grpc) Init(gen *generator.Generator) { g.gen = gen contextPkg = generator.RegisterUniquePackageName("context", nil) grpcPkg = generator.RegisterUniquePackageName("grpc", nil) } // Given a type name defined in a .proto, return its object. // Also record that we're using it, to guarantee the associated import. func (g *grpc) objectNamed(name string) generator.Object { g.gen.RecordTypeUse(name) return g.gen.ObjectNamed(name) } // Given a type name defined in a .proto, return its name as we will print it. func (g *grpc) typeName(str string) string { return g.gen.TypeName(g.objectNamed(str)) } // P forwards to g.gen.P. func (g *grpc) P(args ...interface{}) { g.gen.P(args...) } // Generate generates code for the services in the given file. func (g *grpc) Generate(file *generator.FileDescriptor) { if len(file.FileDescriptorProto.Service) == 0 { return } g.P("// Reference imports to suppress errors if they are not otherwise used.") g.P("var _ ", contextPkg, ".Context") g.P("var _ ", grpcPkg, ".ClientConn") g.P() // Assert version compatibility. g.P("// This is a compile-time assertion to ensure that this generated file") g.P("// is compatible with the grpc package it is being compiled against.") g.P("const _ = ", grpcPkg, ".SupportPackageIsVersion", generatedCodeVersion) g.P() for i, service := range file.FileDescriptorProto.Service { g.generateService(file, service, i) } } // GenerateImports generates the import declaration for this file. func (g *grpc) GenerateImports(file *generator.FileDescriptor) { if len(file.FileDescriptorProto.Service) == 0 { return } g.P("import (") g.P(contextPkg, " ", strconv.Quote(path.Join(g.gen.ImportPrefix, contextPkgPath))) g.P(grpcPkg, " ", strconv.Quote(path.Join(g.gen.ImportPrefix, grpcPkgPath))) g.P(")") g.P() } // reservedClientName records whether a client name is reserved on the client side. var reservedClientName = map[string]bool{ // TODO: do we need any in gRPC? } func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] } // generateService generates all the code for the named service. func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) { path := fmt.Sprintf("6,%d", index) // 6 means service. origServName := service.GetName() fullServName := origServName if pkg := file.GetPackage(); pkg != "" { fullServName = pkg + "." + fullServName } servName := generator.CamelCase(origServName) g.P() g.P("// Client API for ", servName, " service") g.P() // Client interface. g.P("type ", servName, "Client interface {") for i, method := range service.Method { g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service. g.P(g.generateClientSignature(servName, method)) } g.P("}") g.P() // Client structure. g.P("type ", unexport(servName), "Client struct {") g.P("cc *", grpcPkg, ".ClientConn") g.P("}") g.P() // NewClient factory. g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {") g.P("return &", unexport(servName), "Client{cc}") g.P("}") g.P() var methodIndex, streamIndex int serviceDescVar := "_" + servName + "_serviceDesc" // Client method implementations. for _, method := range service.Method { var descExpr string if !method.GetServerStreaming() && !method.GetClientStreaming() { // Unary RPC method descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex) methodIndex++ } else { // Streaming RPC method descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex) streamIndex++ } g.generateClientMethod(servName, fullServName, serviceDescVar, method, descExpr) } g.P("// Server API for ", servName, " service") g.P() // Server interface. serverType := servName + "Server" g.P("type ", serverType, " interface {") for i, method := range service.Method { g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service. g.P(g.generateServerSignature(servName, method)) } g.P("}") g.P() // Server registration. g.P("func Register", servName, "Server(s *", grpcPkg, ".Server, srv ", serverType, ") {") g.P("s.RegisterService(&", serviceDescVar, `, srv)`) g.P("}") g.P() // Server handler implementations. var handlerNames []string for _, method := range service.Method { hname := g.generateServerMethod(servName, fullServName, method) handlerNames = append(handlerNames, hname) } // Service descriptor. g.P("var ", serviceDescVar, " = ", grpcPkg, ".ServiceDesc {") g.P("ServiceName: ", strconv.Quote(fullServName), ",") g.P("HandlerType: (*", serverType, ")(nil),") g.P("Methods: []", grpcPkg, ".MethodDesc{") for i, method := range service.Method { if method.GetServerStreaming() || method.GetClientStreaming() { continue } g.P("{") g.P("MethodName: ", strconv.Quote(method.GetName()), ",") g.P("Handler: ", handlerNames[i], ",") g.P("},") } g.P("},") g.P("Streams: []", grpcPkg, ".StreamDesc{") for i, method := range service.Method { if !method.GetServerStreaming() && !method.GetClientStreaming() { continue } g.P("{") g.P("StreamName: ", strconv.Quote(method.GetName()), ",") g.P("Handler: ", handlerNames[i], ",") if method.GetServerStreaming() { g.P("ServerStreams: true,") } if method.GetClientStreaming() { g.P("ClientStreams: true,") } g.P("},") } g.P("},") g.P("Metadata: \"", file.GetName(), "\",") g.P("}") g.P() } // generateClientSignature returns the client-side signature for a method. func (g *grpc) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string { origMethName := method.GetName() methName := generator.CamelCase(origMethName) if reservedClientName[methName] { methName += "_" } reqArg := ", in *" + g.typeName(method.GetInputType()) if method.GetClientStreaming() { reqArg = "" } respName := "*" + g.typeName(method.GetOutputType()) if method.GetServerStreaming() || method.GetClientStreaming() { respName = servName + "_" + generator.CamelCase(origMethName) + "Client" } return fmt.Sprintf("%s(ctx %s.Context%s, opts ...%s.CallOption) (%s, error)", methName, contextPkg, reqArg, grpcPkg, respName) } func (g *grpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) { sname := fmt.Sprintf("/%s/%s", fullServName, method.GetName()) methName := generator.CamelCase(method.GetName()) inType := g.typeName(method.GetInputType()) outType := g.typeName(method.GetOutputType()) g.P("func (c *", unexport(servName), "Client) ", g.generateClientSignature(servName, method), "{") if !method.GetServerStreaming() && !method.GetClientStreaming() { g.P("out := new(", outType, ")") // TODO: Pass descExpr to Invoke. g.P("err := ", grpcPkg, `.Invoke(ctx, "`, sname, `", in, out, c.cc, opts...)`) g.P("if err != nil { return nil, err }") g.P("return out, nil") g.P("}") g.P() return } streamType := unexport(servName) + methName + "Client" g.P("stream, err := ", grpcPkg, ".NewClientStream(ctx, ", descExpr, `, c.cc, "`, sname, `", opts...)`) g.P("if err != nil { return nil, err }") g.P("x := &", streamType, "{stream}") if !method.GetClientStreaming() { g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }") g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") } g.P("return x, nil") g.P("}") g.P() genSend := method.GetClientStreaming() genRecv := method.GetServerStreaming() genCloseAndRecv := !method.GetServerStreaming() // Stream auxiliary types and methods. g.P("type ", servName, "_", methName, "Client interface {") if genSend { g.P("Send(*", inType, ") error") } if genRecv { g.P("Recv() (*", outType, ", error)") } if genCloseAndRecv { g.P("CloseAndRecv() (*", outType, ", error)") } g.P(grpcPkg, ".ClientStream") g.P("}") g.P() g.P("type ", streamType, " struct {") g.P(grpcPkg, ".ClientStream") g.P("}") g.P() if genSend { g.P("func (x *", streamType, ") Send(m *", inType, ") error {") g.P("return x.ClientStream.SendMsg(m)") g.P("}") g.P() } if genRecv { g.P("func (x *", streamType, ") Recv() (*", outType, ", error) {") g.P("m := new(", outType, ")") g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } if genCloseAndRecv { g.P("func (x *", streamType, ") CloseAndRecv() (*", outType, ", error) {") g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") g.P("m := new(", outType, ")") g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } } // generateServerSignature returns the server-side signature for a method. func (g *grpc) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string { origMethName := method.GetName() methName := generator.CamelCase(origMethName) if reservedClientName[methName] { methName += "_" } var reqArgs []string ret := "error" if !method.GetServerStreaming() && !method.GetClientStreaming() { reqArgs = append(reqArgs, contextPkg+".Context") ret = "(*" + g.typeName(method.GetOutputType()) + ", error)" } if !method.GetClientStreaming() { reqArgs = append(reqArgs, "*"+g.typeName(method.GetInputType())) } if method.GetServerStreaming() || method.GetClientStreaming() { reqArgs = append(reqArgs, servName+"_"+generator.CamelCase(origMethName)+"Server") } return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret } func (g *grpc) generateServerMethod(servName, fullServName string, method *pb.MethodDescriptorProto) string { methName := generator.CamelCase(method.GetName()) hname := fmt.Sprintf("_%s_%s_Handler", servName, methName) inType := g.typeName(method.GetInputType()) outType := g.typeName(method.GetOutputType()) if !method.GetServerStreaming() && !method.GetClientStreaming() { g.P("func ", hname, "(srv interface{}, ctx ", contextPkg, ".Context, dec func(interface{}) error, interceptor ", grpcPkg, ".UnaryServerInterceptor) (interface{}, error) {") g.P("in := new(", inType, ")") g.P("if err := dec(in); err != nil { return nil, err }") g.P("if interceptor == nil { return srv.(", servName, "Server).", methName, "(ctx, in) }") g.P("info := &", grpcPkg, ".UnaryServerInfo{") g.P("Server: srv,") g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", fullServName, methName)), ",") g.P("}") g.P("handler := func(ctx ", contextPkg, ".Context, req interface{}) (interface{}, error) {") g.P("return srv.(", servName, "Server).", methName, "(ctx, req.(*", inType, "))") g.P("}") g.P("return interceptor(ctx, in, info, handler)") g.P("}") g.P() return hname } streamType := unexport(servName) + methName + "Server" g.P("func ", hname, "(srv interface{}, stream ", grpcPkg, ".ServerStream) error {") if !method.GetClientStreaming() { g.P("m := new(", inType, ")") g.P("if err := stream.RecvMsg(m); err != nil { return err }") g.P("return srv.(", servName, "Server).", methName, "(m, &", streamType, "{stream})") } else { g.P("return srv.(", servName, "Server).", methName, "(&", streamType, "{stream})") } g.P("}") g.P() genSend := method.GetServerStreaming() genSendAndClose := !method.GetServerStreaming() genRecv := method.GetClientStreaming() // Stream auxiliary types and methods. g.P("type ", servName, "_", methName, "Server interface {") if genSend { g.P("Send(*", outType, ") error") } if genSendAndClose { g.P("SendAndClose(*", outType, ") error") } if genRecv { g.P("Recv() (*", inType, ", error)") } g.P(grpcPkg, ".ServerStream") g.P("}") g.P() g.P("type ", streamType, " struct {") g.P(grpcPkg, ".ServerStream") g.P("}") g.P() if genSend { g.P("func (x *", streamType, ") Send(m *", outType, ") error {") g.P("return x.ServerStream.SendMsg(m)") g.P("}") g.P() } if genSendAndClose { g.P("func (x *", streamType, ") SendAndClose(m *", outType, ") error {") g.P("return x.ServerStream.SendMsg(m)") g.P("}") g.P() } if genRecv { g.P("func (x *", streamType, ") Recv() (*", inType, ", error) {") g.P("m := new(", inType, ")") g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } return hname } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/link_grpc.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/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. package main import _ "github.com/golang/protobuf/protoc-gen-go/grpc" ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/main.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. // protoc-gen-go is a plugin for the Google protocol buffer compiler to generate // Go code. Run it by building this program and putting it in your path with // the name // protoc-gen-go // That word 'go' at the end becomes part of the option string set for the // protocol compiler, so once the protocol compiler (protoc) is installed // you can run // protoc --go_out=output_directory input_directory/file.proto // to generate Go bindings for the protocol defined by file.proto. // With that input, the output will be written to // output_directory/file.pb.go // // The generated code is documented in the package comment for // the library. // // See the README and documentation for protocol buffers to learn more: // https://developers.google.com/protocol-buffers/ package main import ( "io/ioutil" "os" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/protoc-gen-go/generator" ) func main() { // Begin by allocating a generator. The request and response structures are stored there // so we can do error handling easily - the response structure contains the field to // report failure. g := generator.New() data, err := ioutil.ReadAll(os.Stdin) if err != nil { g.Error(err, "reading input") } if err := proto.Unmarshal(data, g.Request); err != nil { g.Error(err, "parsing input proto") } if len(g.Request.FileToGenerate) == 0 { g.Fail("no files to generate") } g.CommandLineParameters(g.Request.GetParameter()) // Create a wrapped version of the Descriptors and EnumDescriptors that // point to the file that defines them. g.WrapTypes() g.SetPackageNames() g.BuildTypeNameMap() g.GenerateAllFiles() // Send back the results. data, err = proto.Marshal(g.Response) if err != nil { g.Error(err, "failed to marshal output proto") } _, err = os.Stdout.Write(data) if err != nil { g.Error(err, "failed to write output proto") } } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/plugin/Makefile ================================================ # Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/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. # Not stored here, but plugin.proto is in https://github.com/google/protobuf/ # at src/google/protobuf/compiler/plugin.proto # Also we need to fix an import. regenerate: @echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION cp $(HOME)/src/protobuf/include/google/protobuf/compiler/plugin.proto . protoc --go_out=Mgoogle/protobuf/descriptor.proto=github.com/golang/protobuf/protoc-gen-go/descriptor:../../../../.. \ -I$(HOME)/src/protobuf/include $(HOME)/src/protobuf/include/google/protobuf/compiler/plugin.proto restore: cp plugin.pb.golden plugin.pb.go preserve: cp plugin.pb.go plugin.pb.golden ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/compiler/plugin.proto /* Package plugin_go is a generated protocol buffer package. It is generated from these files: google/protobuf/compiler/plugin.proto It has these top-level messages: Version CodeGeneratorRequest CodeGeneratorResponse */ package plugin_go import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // The version number of protocol compiler. type Version struct { Major *int32 `protobuf:"varint,1,opt,name=major" json:"major,omitempty"` Minor *int32 `protobuf:"varint,2,opt,name=minor" json:"minor,omitempty"` Patch *int32 `protobuf:"varint,3,opt,name=patch" json:"patch,omitempty"` // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should // be empty for mainline stable releases. Suffix *string `protobuf:"bytes,4,opt,name=suffix" json:"suffix,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Version) Reset() { *m = Version{} } func (m *Version) String() string { return proto.CompactTextString(m) } func (*Version) ProtoMessage() {} func (*Version) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (m *Version) GetMajor() int32 { if m != nil && m.Major != nil { return *m.Major } return 0 } func (m *Version) GetMinor() int32 { if m != nil && m.Minor != nil { return *m.Minor } return 0 } func (m *Version) GetPatch() int32 { if m != nil && m.Patch != nil { return *m.Patch } return 0 } func (m *Version) GetSuffix() string { if m != nil && m.Suffix != nil { return *m.Suffix } return "" } // An encoded CodeGeneratorRequest is written to the plugin's stdin. type CodeGeneratorRequest struct { // The .proto files that were explicitly listed on the command-line. The // code generator should generate code only for these files. Each file's // descriptor will be included in proto_file, below. FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate,json=fileToGenerate" json:"file_to_generate,omitempty"` // The generator parameter passed on the command-line. Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"` // FileDescriptorProtos for all files in files_to_generate and everything // they import. The files will appear in topological order, so each file // appears before any file that imports it. // // protoc guarantees that all proto_files will be written after // the fields above, even though this is not technically guaranteed by the // protobuf wire format. This theoretically could allow a plugin to stream // in the FileDescriptorProtos and handle them one by one rather than read // the entire set into memory at once. However, as of this writing, this // is not similarly optimized on protoc's end -- it will store all fields in // memory at once before sending them to the plugin. // // Type names of fields and extensions in the FileDescriptorProto are always // fully qualified. ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file,json=protoFile" json:"proto_file,omitempty"` // The version number of protocol compiler. CompilerVersion *Version `protobuf:"bytes,3,opt,name=compiler_version,json=compilerVersion" json:"compiler_version,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CodeGeneratorRequest) Reset() { *m = CodeGeneratorRequest{} } func (m *CodeGeneratorRequest) String() string { return proto.CompactTextString(m) } func (*CodeGeneratorRequest) ProtoMessage() {} func (*CodeGeneratorRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (m *CodeGeneratorRequest) GetFileToGenerate() []string { if m != nil { return m.FileToGenerate } return nil } func (m *CodeGeneratorRequest) GetParameter() string { if m != nil && m.Parameter != nil { return *m.Parameter } return "" } func (m *CodeGeneratorRequest) GetProtoFile() []*google_protobuf.FileDescriptorProto { if m != nil { return m.ProtoFile } return nil } func (m *CodeGeneratorRequest) GetCompilerVersion() *Version { if m != nil { return m.CompilerVersion } return nil } // The plugin writes an encoded CodeGeneratorResponse to stdout. type CodeGeneratorResponse struct { // Error message. If non-empty, code generation failed. The plugin process // should exit with status code zero even if it reports an error in this way. // // This should be used to indicate errors in .proto files which prevent the // code generator from generating correct code. Errors which indicate a // problem in protoc itself -- such as the input CodeGeneratorRequest being // unparseable -- should be reported by writing a message to stderr and // exiting with a non-zero status code. Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"` File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CodeGeneratorResponse) Reset() { *m = CodeGeneratorResponse{} } func (m *CodeGeneratorResponse) String() string { return proto.CompactTextString(m) } func (*CodeGeneratorResponse) ProtoMessage() {} func (*CodeGeneratorResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *CodeGeneratorResponse) GetError() string { if m != nil && m.Error != nil { return *m.Error } return "" } func (m *CodeGeneratorResponse) GetFile() []*CodeGeneratorResponse_File { if m != nil { return m.File } return nil } // Represents a single generated file. type CodeGeneratorResponse_File struct { // The file name, relative to the output directory. The name must not // contain "." or ".." components and must be relative, not be absolute (so, // the file cannot lie outside the output directory). "/" must be used as // the path separator, not "\". // // If the name is omitted, the content will be appended to the previous // file. This allows the generator to break large files into small chunks, // and allows the generated text to be streamed back to protoc so that large // files need not reside completely in memory at one time. Note that as of // this writing protoc does not optimize for this -- it will read the entire // CodeGeneratorResponse before writing files to disk. Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` // If non-empty, indicates that the named file should already exist, and the // content here is to be inserted into that file at a defined insertion // point. This feature allows a code generator to extend the output // produced by another code generator. The original generator may provide // insertion points by placing special annotations in the file that look // like: // @@protoc_insertion_point(NAME) // The annotation can have arbitrary text before and after it on the line, // which allows it to be placed in a comment. NAME should be replaced with // an identifier naming the point -- this is what other generators will use // as the insertion_point. Code inserted at this point will be placed // immediately above the line containing the insertion point (thus multiple // insertions to the same point will come out in the order they were added). // The double-@ is intended to make it unlikely that the generated code // could contain things that look like insertion points by accident. // // For example, the C++ code generator places the following line in the // .pb.h files that it generates: // // @@protoc_insertion_point(namespace_scope) // This line appears within the scope of the file's package namespace, but // outside of any particular class. Another plugin can then specify the // insertion_point "namespace_scope" to generate additional classes or // other declarations that should be placed in this scope. // // Note that if the line containing the insertion point begins with // whitespace, the same whitespace will be added to every line of the // inserted text. This is useful for languages like Python, where // indentation matters. In these languages, the insertion point comment // should be indented the same amount as any inserted code will need to be // in order to work correctly in that context. // // The code generator that generates the initial file and the one which // inserts into it must both run as part of a single invocation of protoc. // Code generators are executed in the order in which they appear on the // command line. // // If |insertion_point| is present, |name| must also be present. InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point,json=insertionPoint" json:"insertion_point,omitempty"` // The file contents. Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CodeGeneratorResponse_File) Reset() { *m = CodeGeneratorResponse_File{} } func (m *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(m) } func (*CodeGeneratorResponse_File) ProtoMessage() {} func (*CodeGeneratorResponse_File) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} } func (m *CodeGeneratorResponse_File) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *CodeGeneratorResponse_File) GetInsertionPoint() string { if m != nil && m.InsertionPoint != nil { return *m.InsertionPoint } return "" } func (m *CodeGeneratorResponse_File) GetContent() string { if m != nil && m.Content != nil { return *m.Content } return "" } func init() { proto.RegisterType((*Version)(nil), "google.protobuf.compiler.Version") proto.RegisterType((*CodeGeneratorRequest)(nil), "google.protobuf.compiler.CodeGeneratorRequest") proto.RegisterType((*CodeGeneratorResponse)(nil), "google.protobuf.compiler.CodeGeneratorResponse") proto.RegisterType((*CodeGeneratorResponse_File)(nil), "google.protobuf.compiler.CodeGeneratorResponse.File") } func init() { proto.RegisterFile("google/protobuf/compiler/plugin.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 417 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0xcf, 0x6a, 0x14, 0x41, 0x10, 0xc6, 0x19, 0x77, 0x63, 0x98, 0x8a, 0x64, 0x43, 0x13, 0xa5, 0x09, 0x39, 0x8c, 0x8b, 0xe2, 0x5c, 0x32, 0x0b, 0xc1, 0x8b, 0x78, 0x4b, 0x44, 0x3d, 0x78, 0x58, 0x1a, 0xf1, 0x20, 0xc8, 0x30, 0x99, 0xd4, 0x74, 0x5a, 0x66, 0xba, 0xc6, 0xee, 0x1e, 0xf1, 0x49, 0x7d, 0x0f, 0xdf, 0x40, 0xfa, 0xcf, 0x24, 0xb2, 0xb8, 0xa7, 0xee, 0xef, 0x57, 0xd5, 0xd5, 0x55, 0x1f, 0x05, 0x2f, 0x25, 0x91, 0xec, 0x71, 0x33, 0x1a, 0x72, 0x74, 0x33, 0x75, 0x9b, 0x96, 0x86, 0x51, 0xf5, 0x68, 0x36, 0x63, 0x3f, 0x49, 0xa5, 0xab, 0x10, 0x60, 0x3c, 0xa6, 0x55, 0x73, 0x5a, 0x35, 0xa7, 0x9d, 0x15, 0xbb, 0x05, 0x6e, 0xd1, 0xb6, 0x46, 0x8d, 0x8e, 0x4c, 0xcc, 0x5e, 0xb7, 0x70, 0xf8, 0x05, 0x8d, 0x55, 0xa4, 0xd9, 0x29, 0x1c, 0x0c, 0xcd, 0x77, 0x32, 0x3c, 0x2b, 0xb2, 0xf2, 0x40, 0x44, 0x11, 0xa8, 0xd2, 0x64, 0xf8, 0xa3, 0x44, 0xbd, 0xf0, 0x74, 0x6c, 0x5c, 0x7b, 0xc7, 0x17, 0x91, 0x06, 0xc1, 0x9e, 0xc1, 0x63, 0x3b, 0x75, 0x9d, 0xfa, 0xc5, 0x97, 0x45, 0x56, 0xe6, 0x22, 0xa9, 0xf5, 0x9f, 0x0c, 0x4e, 0xaf, 0xe9, 0x16, 0x3f, 0xa0, 0x46, 0xd3, 0x38, 0x32, 0x02, 0x7f, 0x4c, 0x68, 0x1d, 0x2b, 0xe1, 0xa4, 0x53, 0x3d, 0xd6, 0x8e, 0x6a, 0x19, 0x63, 0xc8, 0xb3, 0x62, 0x51, 0xe6, 0xe2, 0xd8, 0xf3, 0xcf, 0x94, 0x5e, 0x20, 0x3b, 0x87, 0x7c, 0x6c, 0x4c, 0x33, 0xa0, 0xc3, 0xd8, 0x4a, 0x2e, 0x1e, 0x00, 0xbb, 0x06, 0x08, 0xe3, 0xd4, 0xfe, 0x15, 0x5f, 0x15, 0x8b, 0xf2, 0xe8, 0xf2, 0x45, 0xb5, 0x6b, 0xcb, 0x7b, 0xd5, 0xe3, 0xbb, 0x7b, 0x03, 0xb6, 0x1e, 0x8b, 0x3c, 0x44, 0x7d, 0x84, 0x7d, 0x82, 0x93, 0xd9, 0xb8, 0xfa, 0x67, 0xf4, 0x24, 0x8c, 0x77, 0x74, 0xf9, 0xbc, 0xda, 0xe7, 0x70, 0x95, 0xcc, 0x13, 0xab, 0x99, 0x24, 0xb0, 0xfe, 0x9d, 0xc1, 0xd3, 0x9d, 0x99, 0xed, 0x48, 0xda, 0xa2, 0xf7, 0x0e, 0x8d, 0x49, 0x3e, 0xe7, 0x22, 0x0a, 0xf6, 0x11, 0x96, 0xff, 0x34, 0xff, 0x7a, 0xff, 0x8f, 0xff, 0x2d, 0x1a, 0x66, 0x13, 0xa1, 0xc2, 0xd9, 0x37, 0x58, 0x86, 0x79, 0x18, 0x2c, 0x75, 0x33, 0x60, 0xfa, 0x26, 0xdc, 0xd9, 0x2b, 0x58, 0x29, 0x6d, 0xd1, 0x38, 0x45, 0xba, 0x1e, 0x49, 0x69, 0x97, 0xcc, 0x3c, 0xbe, 0xc7, 0x5b, 0x4f, 0x19, 0x87, 0xc3, 0x96, 0xb4, 0x43, 0xed, 0xf8, 0x2a, 0x24, 0xcc, 0xf2, 0x4a, 0xc2, 0x79, 0x4b, 0xc3, 0xde, 0xfe, 0xae, 0x9e, 0x6c, 0xc3, 0x6e, 0x06, 0x7b, 0xed, 0xd7, 0x37, 0x52, 0xb9, 0xbb, 0xe9, 0xc6, 0x87, 0x37, 0x92, 0xfa, 0x46, 0xcb, 0x87, 0x65, 0x0c, 0x97, 0xf6, 0x42, 0xa2, 0xbe, 0x90, 0x94, 0x56, 0xfa, 0x6d, 0x3c, 0x6a, 0x49, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xf7, 0x15, 0x40, 0xc5, 0xfe, 0x02, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden ================================================ // Code generated by protoc-gen-go. // source: google/protobuf/compiler/plugin.proto // DO NOT EDIT! package google_protobuf_compiler import proto "github.com/golang/protobuf/proto" import "math" import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" // Reference proto and math imports to suppress error if they are not otherwise used. var _ = proto.GetString var _ = math.Inf type CodeGeneratorRequest struct { FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate" json:"file_to_generate,omitempty"` Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"` ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file" json:"proto_file,omitempty"` XXX_unrecognized []byte `json:"-"` } func (this *CodeGeneratorRequest) Reset() { *this = CodeGeneratorRequest{} } func (this *CodeGeneratorRequest) String() string { return proto.CompactTextString(this) } func (*CodeGeneratorRequest) ProtoMessage() {} func (this *CodeGeneratorRequest) GetParameter() string { if this != nil && this.Parameter != nil { return *this.Parameter } return "" } type CodeGeneratorResponse struct { Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"` File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"` XXX_unrecognized []byte `json:"-"` } func (this *CodeGeneratorResponse) Reset() { *this = CodeGeneratorResponse{} } func (this *CodeGeneratorResponse) String() string { return proto.CompactTextString(this) } func (*CodeGeneratorResponse) ProtoMessage() {} func (this *CodeGeneratorResponse) GetError() string { if this != nil && this.Error != nil { return *this.Error } return "" } type CodeGeneratorResponse_File struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point" json:"insertion_point,omitempty"` Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"` XXX_unrecognized []byte `json:"-"` } func (this *CodeGeneratorResponse_File) Reset() { *this = CodeGeneratorResponse_File{} } func (this *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(this) } func (*CodeGeneratorResponse_File) ProtoMessage() {} func (this *CodeGeneratorResponse_File) GetName() string { if this != nil && this.Name != nil { return *this.Name } return "" } func (this *CodeGeneratorResponse_File) GetInsertionPoint() string { if this != nil && this.InsertionPoint != nil { return *this.InsertionPoint } return "" } func (this *CodeGeneratorResponse_File) GetContent() string { if this != nil && this.Content != nil { return *this.Content } return "" } func init() { } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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: kenton@google.com (Kenton Varda) // // WARNING: The plugin interface is currently EXPERIMENTAL and is subject to // change. // // protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is // just a program that reads a CodeGeneratorRequest from stdin and writes a // CodeGeneratorResponse to stdout. // // Plugins written using C++ can use google/protobuf/compiler/plugin.h instead // of dealing with the raw protocol defined here. // // A plugin executable needs only to be placed somewhere in the path. The // plugin should be named "protoc-gen-$NAME", and will then be used when the // flag "--${NAME}_out" is passed to protoc. syntax = "proto2"; package google.protobuf.compiler; option java_package = "com.google.protobuf.compiler"; option java_outer_classname = "PluginProtos"; option go_package = "github.com/golang/protobuf/protoc-gen-go/plugin;plugin_go"; import "google/protobuf/descriptor.proto"; // The version number of protocol compiler. message Version { optional int32 major = 1; optional int32 minor = 2; optional int32 patch = 3; // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should // be empty for mainline stable releases. optional string suffix = 4; } // An encoded CodeGeneratorRequest is written to the plugin's stdin. message CodeGeneratorRequest { // The .proto files that were explicitly listed on the command-line. The // code generator should generate code only for these files. Each file's // descriptor will be included in proto_file, below. repeated string file_to_generate = 1; // The generator parameter passed on the command-line. optional string parameter = 2; // FileDescriptorProtos for all files in files_to_generate and everything // they import. The files will appear in topological order, so each file // appears before any file that imports it. // // protoc guarantees that all proto_files will be written after // the fields above, even though this is not technically guaranteed by the // protobuf wire format. This theoretically could allow a plugin to stream // in the FileDescriptorProtos and handle them one by one rather than read // the entire set into memory at once. However, as of this writing, this // is not similarly optimized on protoc's end -- it will store all fields in // memory at once before sending them to the plugin. // // Type names of fields and extensions in the FileDescriptorProto are always // fully qualified. repeated FileDescriptorProto proto_file = 15; // The version number of protocol compiler. optional Version compiler_version = 3; } // The plugin writes an encoded CodeGeneratorResponse to stdout. message CodeGeneratorResponse { // Error message. If non-empty, code generation failed. The plugin process // should exit with status code zero even if it reports an error in this way. // // This should be used to indicate errors in .proto files which prevent the // code generator from generating correct code. Errors which indicate a // problem in protoc itself -- such as the input CodeGeneratorRequest being // unparseable -- should be reported by writing a message to stderr and // exiting with a non-zero status code. optional string error = 1; // Represents a single generated file. message File { // The file name, relative to the output directory. The name must not // contain "." or ".." components and must be relative, not be absolute (so, // the file cannot lie outside the output directory). "/" must be used as // the path separator, not "\". // // If the name is omitted, the content will be appended to the previous // file. This allows the generator to break large files into small chunks, // and allows the generated text to be streamed back to protoc so that large // files need not reside completely in memory at one time. Note that as of // this writing protoc does not optimize for this -- it will read the entire // CodeGeneratorResponse before writing files to disk. optional string name = 1; // If non-empty, indicates that the named file should already exist, and the // content here is to be inserted into that file at a defined insertion // point. This feature allows a code generator to extend the output // produced by another code generator. The original generator may provide // insertion points by placing special annotations in the file that look // like: // @@protoc_insertion_point(NAME) // The annotation can have arbitrary text before and after it on the line, // which allows it to be placed in a comment. NAME should be replaced with // an identifier naming the point -- this is what other generators will use // as the insertion_point. Code inserted at this point will be placed // immediately above the line containing the insertion point (thus multiple // insertions to the same point will come out in the order they were added). // The double-@ is intended to make it unlikely that the generated code // could contain things that look like insertion points by accident. // // For example, the C++ code generator places the following line in the // .pb.h files that it generates: // // @@protoc_insertion_point(namespace_scope) // This line appears within the scope of the file's package namespace, but // outside of any particular class. Another plugin can then specify the // insertion_point "namespace_scope" to generate additional classes or // other declarations that should be placed in this scope. // // Note that if the line containing the insertion point begins with // whitespace, the same whitespace will be added to every line of the // inserted text. This is useful for languages like Python, where // indentation matters. In these languages, the insertion point comment // should be indented the same amount as any inserted code will need to be // in order to work correctly in that context. // // The code generator that generates the initial file and the one which // inserts into it must both run as part of a single invocation of protoc. // Code generators are executed in the order in which they appear on the // command line. // // If |insertion_point| is present, |name| must also be present. optional string insertion_point = 2; // The file contents. optional string content = 15; } repeated File file = 15; } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/Makefile ================================================ # Go support for Protocol Buffers - Google's data interchange format # # Copyright 2010 The Go Authors. All rights reserved. # https://github.com/golang/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. all: @echo run make test include ../../Make.protobuf test: golden testbuild #test: golden testbuild extension_test # ./extension_test # @echo PASS my_test/test.pb.go: my_test/test.proto protoc --go_out=Mmulti/multi1.proto=github.com/golang/protobuf/protoc-gen-go/testdata/multi:. $< golden: make -B my_test/test.pb.go sed -i -e '/return.*fileDescriptor/d' my_test/test.pb.go sed -i -e '/^var fileDescriptor/,/^}/d' my_test/test.pb.go sed -i -e '/proto.RegisterFile.*fileDescriptor/d' my_test/test.pb.go gofmt -w my_test/test.pb.go diff -w my_test/test.pb.go my_test/test.pb.go.golden nuke: clean testbuild: regenerate go test regenerate: # Invoke protoc once to generate three independent .pb.go files in the same package. protoc --go_out=. multi/multi1.proto multi/multi2.proto multi/multi3.proto #extension_test: extension_test.$O # $(LD) -L. -o $@ $< #multi.a: multi3.pb.$O multi2.pb.$O multi1.pb.$O # rm -f multi.a # $(QUOTED_GOBIN)/gopack grc $@ $< #test.pb.go: imp.pb.go #multi1.pb.go: multi2.pb.go multi3.pb.go #main.$O: imp.pb.$O test.pb.$O multi.a #extension_test.$O: extension_base.pb.$O extension_extra.pb.$O extension_user.pb.$O ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto2"; package extension_base; message BaseMessage { optional int32 height = 1; extensions 4 to 9; extensions 16 to max; } // Another message that may be extended, using message_set_wire_format. message OldStyleMessage { option message_set_wire_format = true; extensions 100 to max; } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto2"; package extension_extra; message ExtraMessage { optional int32 width = 1; } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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 that we can use protocol buffers that use extensions. package testdata /* import ( "bytes" "regexp" "testing" "github.com/golang/protobuf/proto" base "extension_base.pb" user "extension_user.pb" ) func TestSingleFieldExtension(t *testing.T) { bm := &base.BaseMessage{ Height: proto.Int32(178), } // Use extension within scope of another type. vol := proto.Uint32(11) err := proto.SetExtension(bm, user.E_LoudMessage_Volume, vol) if err != nil { t.Fatal("Failed setting extension:", err) } buf, err := proto.Marshal(bm) if err != nil { t.Fatal("Failed encoding message with extension:", err) } bm_new := new(base.BaseMessage) if err := proto.Unmarshal(buf, bm_new); err != nil { t.Fatal("Failed decoding message with extension:", err) } if !proto.HasExtension(bm_new, user.E_LoudMessage_Volume) { t.Fatal("Decoded message didn't contain extension.") } vol_out, err := proto.GetExtension(bm_new, user.E_LoudMessage_Volume) if err != nil { t.Fatal("Failed getting extension:", err) } if v := vol_out.(*uint32); *v != *vol { t.Errorf("vol_out = %v, expected %v", *v, *vol) } proto.ClearExtension(bm_new, user.E_LoudMessage_Volume) if proto.HasExtension(bm_new, user.E_LoudMessage_Volume) { t.Fatal("Failed clearing extension.") } } func TestMessageExtension(t *testing.T) { bm := &base.BaseMessage{ Height: proto.Int32(179), } // Use extension that is itself a message. um := &user.UserMessage{ Name: proto.String("Dave"), Rank: proto.String("Major"), } err := proto.SetExtension(bm, user.E_LoginMessage_UserMessage, um) if err != nil { t.Fatal("Failed setting extension:", err) } buf, err := proto.Marshal(bm) if err != nil { t.Fatal("Failed encoding message with extension:", err) } bm_new := new(base.BaseMessage) if err := proto.Unmarshal(buf, bm_new); err != nil { t.Fatal("Failed decoding message with extension:", err) } if !proto.HasExtension(bm_new, user.E_LoginMessage_UserMessage) { t.Fatal("Decoded message didn't contain extension.") } um_out, err := proto.GetExtension(bm_new, user.E_LoginMessage_UserMessage) if err != nil { t.Fatal("Failed getting extension:", err) } if n := um_out.(*user.UserMessage).Name; *n != *um.Name { t.Errorf("um_out.Name = %q, expected %q", *n, *um.Name) } if r := um_out.(*user.UserMessage).Rank; *r != *um.Rank { t.Errorf("um_out.Rank = %q, expected %q", *r, *um.Rank) } proto.ClearExtension(bm_new, user.E_LoginMessage_UserMessage) if proto.HasExtension(bm_new, user.E_LoginMessage_UserMessage) { t.Fatal("Failed clearing extension.") } } func TestTopLevelExtension(t *testing.T) { bm := &base.BaseMessage{ Height: proto.Int32(179), } width := proto.Int32(17) err := proto.SetExtension(bm, user.E_Width, width) if err != nil { t.Fatal("Failed setting extension:", err) } buf, err := proto.Marshal(bm) if err != nil { t.Fatal("Failed encoding message with extension:", err) } bm_new := new(base.BaseMessage) if err := proto.Unmarshal(buf, bm_new); err != nil { t.Fatal("Failed decoding message with extension:", err) } if !proto.HasExtension(bm_new, user.E_Width) { t.Fatal("Decoded message didn't contain extension.") } width_out, err := proto.GetExtension(bm_new, user.E_Width) if err != nil { t.Fatal("Failed getting extension:", err) } if w := width_out.(*int32); *w != *width { t.Errorf("width_out = %v, expected %v", *w, *width) } proto.ClearExtension(bm_new, user.E_Width) if proto.HasExtension(bm_new, user.E_Width) { t.Fatal("Failed clearing extension.") } } func TestMessageSetWireFormat(t *testing.T) { osm := new(base.OldStyleMessage) osp := &user.OldStyleParcel{ Name: proto.String("Dave"), Height: proto.Int32(178), } err := proto.SetExtension(osm, user.E_OldStyleParcel_MessageSetExtension, osp) if err != nil { t.Fatal("Failed setting extension:", err) } buf, err := proto.Marshal(osm) if err != nil { t.Fatal("Failed encoding message:", err) } // Data generated from Python implementation. expected := []byte{ 11, 16, 209, 15, 26, 9, 10, 4, 68, 97, 118, 101, 16, 178, 1, 12, } if !bytes.Equal(expected, buf) { t.Errorf("Encoding mismatch.\nwant %+v\n got %+v", expected, buf) } // Check that it is restored correctly. osm = new(base.OldStyleMessage) if err := proto.Unmarshal(buf, osm); err != nil { t.Fatal("Failed decoding message:", err) } osp_out, err := proto.GetExtension(osm, user.E_OldStyleParcel_MessageSetExtension) if err != nil { t.Fatal("Failed getting extension:", err) } osp = osp_out.(*user.OldStyleParcel) if *osp.Name != "Dave" || *osp.Height != 178 { t.Errorf("Retrieved extension from decoded message is not correct: %+v", osp) } } func main() { // simpler than rigging up gotest testing.Main(regexp.MatchString, []testing.InternalTest{ {"TestSingleFieldExtension", TestSingleFieldExtension}, {"TestMessageExtension", TestMessageExtension}, {"TestTopLevelExtension", TestTopLevelExtension}, }, []testing.InternalBenchmark{}, []testing.InternalExample{}) } */ ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto2"; import "extension_base.proto"; import "extension_extra.proto"; package extension_user; message UserMessage { optional string name = 1; optional string rank = 2; } // Extend with a message extend extension_base.BaseMessage { optional UserMessage user_message = 5; } // Extend with a foreign message extend extension_base.BaseMessage { optional extension_extra.ExtraMessage extra_message = 9; } // Extend with some primitive types extend extension_base.BaseMessage { optional int32 width = 6; optional int64 area = 7; } // Extend inside the scope of another type message LoudMessage { extend extension_base.BaseMessage { optional uint32 volume = 8; } extensions 100 to max; } // Extend inside the scope of another type, using a message. message LoginMessage { extend extension_base.BaseMessage { optional UserMessage user_message = 16; } } // Extend with a repeated field extend extension_base.BaseMessage { repeated Detail detail = 17; } message Detail { optional string color = 1; } // An extension of an extension message Announcement { optional string words = 1; extend LoudMessage { optional Announcement loud_ext = 100; } } // Something that can be put in a message set. message OldStyleParcel { extend extension_base.OldStyleMessage { optional OldStyleParcel message_set_extension = 2001; } required string name = 1; optional int32 height = 2; } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/grpc.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto3"; package grpc.testing; message SimpleRequest { } message SimpleResponse { } message StreamMsg { } message StreamMsg2 { } service Test { rpc UnaryCall(SimpleRequest) returns (SimpleResponse); // This RPC streams from the server only. rpc Downstream(SimpleRequest) returns (stream StreamMsg); // This RPC streams from the client. rpc Upstream(stream StreamMsg) returns (SimpleResponse); // This one streams in both directions. rpc Bidi(stream StreamMsg) returns (stream StreamMsg2); } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/imp.pb.go.golden ================================================ // Code generated by protoc-gen-go. // source: imp.proto // DO NOT EDIT! package imp import proto "github.com/golang/protobuf/proto" import "math" import "os" import imp1 "imp2.pb" // Reference proto & math imports to suppress error if they are not otherwise used. var _ = proto.GetString var _ = math.Inf // Types from public import imp2.proto type PubliclyImportedMessage imp1.PubliclyImportedMessage func (this *PubliclyImportedMessage) Reset() { (*imp1.PubliclyImportedMessage)(this).Reset() } func (this *PubliclyImportedMessage) String() string { return (*imp1.PubliclyImportedMessage)(this).String() } // PubliclyImportedMessage from public import imp.proto type ImportedMessage_Owner int32 const ( ImportedMessage_DAVE ImportedMessage_Owner = 1 ImportedMessage_MIKE ImportedMessage_Owner = 2 ) var ImportedMessage_Owner_name = map[int32]string{ 1: "DAVE", 2: "MIKE", } var ImportedMessage_Owner_value = map[string]int32{ "DAVE": 1, "MIKE": 2, } // NewImportedMessage_Owner is deprecated. Use x.Enum() instead. func NewImportedMessage_Owner(x ImportedMessage_Owner) *ImportedMessage_Owner { e := ImportedMessage_Owner(x) return &e } func (x ImportedMessage_Owner) Enum() *ImportedMessage_Owner { p := new(ImportedMessage_Owner) *p = x return p } func (x ImportedMessage_Owner) String() string { return proto.EnumName(ImportedMessage_Owner_name, int32(x)) } type ImportedMessage struct { Field *int64 `protobuf:"varint,1,req,name=field" json:"field,omitempty"` XXX_extensions map[int32][]byte `json:",omitempty"` XXX_unrecognized []byte `json:",omitempty"` } func (this *ImportedMessage) Reset() { *this = ImportedMessage{} } func (this *ImportedMessage) String() string { return proto.CompactTextString(this) } var extRange_ImportedMessage = []proto.ExtensionRange{ proto.ExtensionRange{90, 100}, } func (*ImportedMessage) ExtensionRangeArray() []proto.ExtensionRange { return extRange_ImportedMessage } func (this *ImportedMessage) ExtensionMap() map[int32][]byte { if this.XXX_extensions == nil { this.XXX_extensions = make(map[int32][]byte) } return this.XXX_extensions } type ImportedExtendable struct { XXX_extensions map[int32][]byte `json:",omitempty"` XXX_unrecognized []byte `json:",omitempty"` } func (this *ImportedExtendable) Reset() { *this = ImportedExtendable{} } func (this *ImportedExtendable) String() string { return proto.CompactTextString(this) } func (this *ImportedExtendable) Marshal() ([]byte, error) { return proto.MarshalMessageSet(this.ExtensionMap()) } func (this *ImportedExtendable) Unmarshal(buf []byte) error { return proto.UnmarshalMessageSet(buf, this.ExtensionMap()) } // ensure ImportedExtendable satisfies proto.Marshaler and proto.Unmarshaler var _ proto.Marshaler = (*ImportedExtendable)(nil) var _ proto.Unmarshaler = (*ImportedExtendable)(nil) var extRange_ImportedExtendable = []proto.ExtensionRange{ proto.ExtensionRange{100, 536870911}, } func (*ImportedExtendable) ExtensionRangeArray() []proto.ExtensionRange { return extRange_ImportedExtendable } func (this *ImportedExtendable) ExtensionMap() map[int32][]byte { if this.XXX_extensions == nil { this.XXX_extensions = make(map[int32][]byte) } return this.XXX_extensions } func init() { proto.RegisterEnum("imp.ImportedMessage_Owner", ImportedMessage_Owner_name, ImportedMessage_Owner_value) } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/imp.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto2"; package imp; import "imp2.proto"; import "imp3.proto"; message ImportedMessage { required int64 field = 1; // The forwarded getters for these fields are fiddly to get right. optional ImportedMessage2 local_msg = 2; optional ForeignImportedMessage foreign_msg = 3; // in imp3.proto optional Owner enum_field = 4; oneof union { int32 state = 9; } repeated string name = 5; repeated Owner boss = 6; repeated ImportedMessage2 memo = 7; map msg_map = 8; enum Owner { DAVE = 1; MIKE = 2; } extensions 90 to 100; } message ImportedMessage2 { } message ImportedExtendable { option message_set_wire_format = true; extensions 100 to max; } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/imp2.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto2"; package imp; message PubliclyImportedMessage { optional int64 field = 1; } enum PubliclyImportedEnum { GLASSES = 1; HAIR = 2; } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/imp3.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto2"; package imp; message ForeignImportedMessage { optional string tuber = 1; } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. // A simple binary to link together the protocol buffers in this test. package testdata import ( "testing" mytestpb "./my_test" multipb "github.com/golang/protobuf/protoc-gen-go/testdata/multi" ) func TestLink(t *testing.T) { _ = &multipb.Multi1{} _ = &mytestpb.Request{} } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto2"; import "multi/multi2.proto"; import "multi/multi3.proto"; package multitest; message Multi1 { required Multi2 multi2 = 1; optional Multi2.Color color = 2; optional Multi3.HatType hat_type = 3; } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto2"; package multitest; message Multi2 { required int32 required_value = 1; enum Color { BLUE = 1; GREEN = 2; RED = 3; }; optional Color color = 2; } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto2"; package multitest; message Multi3 { enum HatType { FEDORA = 1; FEZ = 2; }; optional HatType hat_type = 1; } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: my_test/test.proto /* Package my_test is a generated protocol buffer package. This package holds interesting messages. It is generated from these files: my_test/test.proto It has these top-level messages: Request Reply OtherBase ReplyExtensions OtherReplyExtensions OldReply Communique */ package my_test import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/golang/protobuf/protoc-gen-go/testdata/multi" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type HatType int32 const ( // deliberately skipping 0 HatType_FEDORA HatType = 1 HatType_FEZ HatType = 2 ) var HatType_name = map[int32]string{ 1: "FEDORA", 2: "FEZ", } var HatType_value = map[string]int32{ "FEDORA": 1, "FEZ": 2, } func (x HatType) Enum() *HatType { p := new(HatType) *p = x return p } func (x HatType) String() string { return proto.EnumName(HatType_name, int32(x)) } func (x *HatType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(HatType_value, data, "HatType") if err != nil { return err } *x = HatType(value) return nil } // This enum represents days of the week. type Days int32 const ( Days_MONDAY Days = 1 Days_TUESDAY Days = 2 Days_LUNDI Days = 1 ) var Days_name = map[int32]string{ 1: "MONDAY", 2: "TUESDAY", // Duplicate value: 1: "LUNDI", } var Days_value = map[string]int32{ "MONDAY": 1, "TUESDAY": 2, "LUNDI": 1, } func (x Days) Enum() *Days { p := new(Days) *p = x return p } func (x Days) String() string { return proto.EnumName(Days_name, int32(x)) } func (x *Days) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Days_value, data, "Days") if err != nil { return err } *x = Days(value) return nil } type Request_Color int32 const ( Request_RED Request_Color = 0 Request_GREEN Request_Color = 1 Request_BLUE Request_Color = 2 ) var Request_Color_name = map[int32]string{ 0: "RED", 1: "GREEN", 2: "BLUE", } var Request_Color_value = map[string]int32{ "RED": 0, "GREEN": 1, "BLUE": 2, } func (x Request_Color) Enum() *Request_Color { p := new(Request_Color) *p = x return p } func (x Request_Color) String() string { return proto.EnumName(Request_Color_name, int32(x)) } func (x *Request_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Request_Color_value, data, "Request_Color") if err != nil { return err } *x = Request_Color(value) return nil } type Reply_Entry_Game int32 const ( Reply_Entry_FOOTBALL Reply_Entry_Game = 1 Reply_Entry_TENNIS Reply_Entry_Game = 2 ) var Reply_Entry_Game_name = map[int32]string{ 1: "FOOTBALL", 2: "TENNIS", } var Reply_Entry_Game_value = map[string]int32{ "FOOTBALL": 1, "TENNIS": 2, } func (x Reply_Entry_Game) Enum() *Reply_Entry_Game { p := new(Reply_Entry_Game) *p = x return p } func (x Reply_Entry_Game) String() string { return proto.EnumName(Reply_Entry_Game_name, int32(x)) } func (x *Reply_Entry_Game) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Reply_Entry_Game_value, data, "Reply_Entry_Game") if err != nil { return err } *x = Reply_Entry_Game(value) return nil } // This is a message that might be sent somewhere. type Request struct { Key []int64 `protobuf:"varint,1,rep,name=key" json:"key,omitempty"` // optional imp.ImportedMessage imported_message = 2; Hue *Request_Color `protobuf:"varint,3,opt,name=hue,enum=my.test.Request_Color" json:"hue,omitempty"` Hat *HatType `protobuf:"varint,4,opt,name=hat,enum=my.test.HatType,def=1" json:"hat,omitempty"` // optional imp.ImportedMessage.Owner owner = 6; Deadline *float32 `protobuf:"fixed32,7,opt,name=deadline,def=inf" json:"deadline,omitempty"` Somegroup *Request_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"` // This is a map field. It will generate map[int32]string. NameMapping map[int32]string `protobuf:"bytes,14,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // This is a map field whose value type is a message. MsgMapping map[int64]*Reply `protobuf:"bytes,15,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Reset_ *int32 `protobuf:"varint,12,opt,name=reset" json:"reset,omitempty"` // This field should not conflict with any getters. GetKey_ *string `protobuf:"bytes,16,opt,name=get_key,json=getKey" json:"get_key,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Request) Reset() { *m = Request{} } func (m *Request) String() string { return proto.CompactTextString(m) } func (*Request) ProtoMessage() {} const Default_Request_Hat HatType = HatType_FEDORA var Default_Request_Deadline float32 = float32(math.Inf(1)) func (m *Request) GetKey() []int64 { if m != nil { return m.Key } return nil } func (m *Request) GetHue() Request_Color { if m != nil && m.Hue != nil { return *m.Hue } return Request_RED } func (m *Request) GetHat() HatType { if m != nil && m.Hat != nil { return *m.Hat } return Default_Request_Hat } func (m *Request) GetDeadline() float32 { if m != nil && m.Deadline != nil { return *m.Deadline } return Default_Request_Deadline } func (m *Request) GetSomegroup() *Request_SomeGroup { if m != nil { return m.Somegroup } return nil } func (m *Request) GetNameMapping() map[int32]string { if m != nil { return m.NameMapping } return nil } func (m *Request) GetMsgMapping() map[int64]*Reply { if m != nil { return m.MsgMapping } return nil } func (m *Request) GetReset_() int32 { if m != nil && m.Reset_ != nil { return *m.Reset_ } return 0 } func (m *Request) GetGetKey_() string { if m != nil && m.GetKey_ != nil { return *m.GetKey_ } return "" } type Request_SomeGroup struct { GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Request_SomeGroup) Reset() { *m = Request_SomeGroup{} } func (m *Request_SomeGroup) String() string { return proto.CompactTextString(m) } func (*Request_SomeGroup) ProtoMessage() {} func (m *Request_SomeGroup) GetGroupField() int32 { if m != nil && m.GroupField != nil { return *m.GroupField } return 0 } type Reply struct { Found []*Reply_Entry `protobuf:"bytes,1,rep,name=found" json:"found,omitempty"` CompactKeys []int32 `protobuf:"varint,2,rep,packed,name=compact_keys,json=compactKeys" json:"compact_keys,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *Reply) Reset() { *m = Reply{} } func (m *Reply) String() string { return proto.CompactTextString(m) } func (*Reply) ProtoMessage() {} var extRange_Reply = []proto.ExtensionRange{ {100, 536870911}, } func (*Reply) ExtensionRangeArray() []proto.ExtensionRange { return extRange_Reply } func (m *Reply) GetFound() []*Reply_Entry { if m != nil { return m.Found } return nil } func (m *Reply) GetCompactKeys() []int32 { if m != nil { return m.CompactKeys } return nil } type Reply_Entry struct { KeyThatNeeds_1234Camel_CasIng *int64 `protobuf:"varint,1,req,name=key_that_needs_1234camel_CasIng,json=keyThatNeeds1234camelCasIng" json:"key_that_needs_1234camel_CasIng,omitempty"` Value *int64 `protobuf:"varint,2,opt,name=value,def=7" json:"value,omitempty"` XMyFieldName_2 *int64 `protobuf:"varint,3,opt,name=_my_field_name_2,json=MyFieldName2" json:"_my_field_name_2,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Reply_Entry) Reset() { *m = Reply_Entry{} } func (m *Reply_Entry) String() string { return proto.CompactTextString(m) } func (*Reply_Entry) ProtoMessage() {} const Default_Reply_Entry_Value int64 = 7 func (m *Reply_Entry) GetKeyThatNeeds_1234Camel_CasIng() int64 { if m != nil && m.KeyThatNeeds_1234Camel_CasIng != nil { return *m.KeyThatNeeds_1234Camel_CasIng } return 0 } func (m *Reply_Entry) GetValue() int64 { if m != nil && m.Value != nil { return *m.Value } return Default_Reply_Entry_Value } func (m *Reply_Entry) GetXMyFieldName_2() int64 { if m != nil && m.XMyFieldName_2 != nil { return *m.XMyFieldName_2 } return 0 } type OtherBase struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OtherBase) Reset() { *m = OtherBase{} } func (m *OtherBase) String() string { return proto.CompactTextString(m) } func (*OtherBase) ProtoMessage() {} var extRange_OtherBase = []proto.ExtensionRange{ {100, 536870911}, } func (*OtherBase) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OtherBase } func (m *OtherBase) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } type ReplyExtensions struct { XXX_unrecognized []byte `json:"-"` } func (m *ReplyExtensions) Reset() { *m = ReplyExtensions{} } func (m *ReplyExtensions) String() string { return proto.CompactTextString(m) } func (*ReplyExtensions) ProtoMessage() {} var E_ReplyExtensions_Time = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*float64)(nil), Field: 101, Name: "my.test.ReplyExtensions.time", Tag: "fixed64,101,opt,name=time", Filename: "my_test/test.proto", } var E_ReplyExtensions_Carrot = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*ReplyExtensions)(nil), Field: 105, Name: "my.test.ReplyExtensions.carrot", Tag: "bytes,105,opt,name=carrot", Filename: "my_test/test.proto", } var E_ReplyExtensions_Donut = &proto.ExtensionDesc{ ExtendedType: (*OtherBase)(nil), ExtensionType: (*ReplyExtensions)(nil), Field: 101, Name: "my.test.ReplyExtensions.donut", Tag: "bytes,101,opt,name=donut", Filename: "my_test/test.proto", } type OtherReplyExtensions struct { Key *int32 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *OtherReplyExtensions) Reset() { *m = OtherReplyExtensions{} } func (m *OtherReplyExtensions) String() string { return proto.CompactTextString(m) } func (*OtherReplyExtensions) ProtoMessage() {} func (m *OtherReplyExtensions) GetKey() int32 { if m != nil && m.Key != nil { return *m.Key } return 0 } type OldReply struct { proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OldReply) Reset() { *m = OldReply{} } func (m *OldReply) String() string { return proto.CompactTextString(m) } func (*OldReply) ProtoMessage() {} func (m *OldReply) Marshal() ([]byte, error) { return proto.MarshalMessageSet(&m.XXX_InternalExtensions) } func (m *OldReply) Unmarshal(buf []byte) error { return proto.UnmarshalMessageSet(buf, &m.XXX_InternalExtensions) } func (m *OldReply) MarshalJSON() ([]byte, error) { return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions) } func (m *OldReply) UnmarshalJSON(buf []byte) error { return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions) } // ensure OldReply satisfies proto.Marshaler and proto.Unmarshaler var _ proto.Marshaler = (*OldReply)(nil) var _ proto.Unmarshaler = (*OldReply)(nil) var extRange_OldReply = []proto.ExtensionRange{ {100, 2147483646}, } func (*OldReply) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OldReply } type Communique struct { MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"` // This is a oneof, called "union". // // Types that are valid to be assigned to Union: // *Communique_Number // *Communique_Name // *Communique_Data // *Communique_TempC // *Communique_Height // *Communique_Today // *Communique_Maybe // *Communique_Delta_ // *Communique_Msg // *Communique_Somegroup Union isCommunique_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *Communique) Reset() { *m = Communique{} } func (m *Communique) String() string { return proto.CompactTextString(m) } func (*Communique) ProtoMessage() {} type isCommunique_Union interface { isCommunique_Union() } type Communique_Number struct { Number int32 `protobuf:"varint,5,opt,name=number,oneof"` } type Communique_Name struct { Name string `protobuf:"bytes,6,opt,name=name,oneof"` } type Communique_Data struct { Data []byte `protobuf:"bytes,7,opt,name=data,oneof"` } type Communique_TempC struct { TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"` } type Communique_Height struct { Height float32 `protobuf:"fixed32,9,opt,name=height,oneof"` } type Communique_Today struct { Today Days `protobuf:"varint,10,opt,name=today,enum=my.test.Days,oneof"` } type Communique_Maybe struct { Maybe bool `protobuf:"varint,11,opt,name=maybe,oneof"` } type Communique_Delta_ struct { Delta int32 `protobuf:"zigzag32,12,opt,name=delta,oneof"` } type Communique_Msg struct { Msg *Reply `protobuf:"bytes,13,opt,name=msg,oneof"` } type Communique_Somegroup struct { Somegroup *Communique_SomeGroup `protobuf:"group,14,opt,name=SomeGroup,json=somegroup,oneof"` } func (*Communique_Number) isCommunique_Union() {} func (*Communique_Name) isCommunique_Union() {} func (*Communique_Data) isCommunique_Union() {} func (*Communique_TempC) isCommunique_Union() {} func (*Communique_Height) isCommunique_Union() {} func (*Communique_Today) isCommunique_Union() {} func (*Communique_Maybe) isCommunique_Union() {} func (*Communique_Delta_) isCommunique_Union() {} func (*Communique_Msg) isCommunique_Union() {} func (*Communique_Somegroup) isCommunique_Union() {} func (m *Communique) GetUnion() isCommunique_Union { if m != nil { return m.Union } return nil } func (m *Communique) GetMakeMeCry() bool { if m != nil && m.MakeMeCry != nil { return *m.MakeMeCry } return false } func (m *Communique) GetNumber() int32 { if x, ok := m.GetUnion().(*Communique_Number); ok { return x.Number } return 0 } func (m *Communique) GetName() string { if x, ok := m.GetUnion().(*Communique_Name); ok { return x.Name } return "" } func (m *Communique) GetData() []byte { if x, ok := m.GetUnion().(*Communique_Data); ok { return x.Data } return nil } func (m *Communique) GetTempC() float64 { if x, ok := m.GetUnion().(*Communique_TempC); ok { return x.TempC } return 0 } func (m *Communique) GetHeight() float32 { if x, ok := m.GetUnion().(*Communique_Height); ok { return x.Height } return 0 } func (m *Communique) GetToday() Days { if x, ok := m.GetUnion().(*Communique_Today); ok { return x.Today } return Days_MONDAY } func (m *Communique) GetMaybe() bool { if x, ok := m.GetUnion().(*Communique_Maybe); ok { return x.Maybe } return false } func (m *Communique) GetDelta() int32 { if x, ok := m.GetUnion().(*Communique_Delta_); ok { return x.Delta } return 0 } func (m *Communique) GetMsg() *Reply { if x, ok := m.GetUnion().(*Communique_Msg); ok { return x.Msg } return nil } func (m *Communique) GetSomegroup() *Communique_SomeGroup { if x, ok := m.GetUnion().(*Communique_Somegroup); ok { return x.Somegroup } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{ (*Communique_Number)(nil), (*Communique_Name)(nil), (*Communique_Data)(nil), (*Communique_TempC)(nil), (*Communique_Height)(nil), (*Communique_Today)(nil), (*Communique_Maybe)(nil), (*Communique_Delta_)(nil), (*Communique_Msg)(nil), (*Communique_Somegroup)(nil), } } func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: b.EncodeVarint(5<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Number)) case *Communique_Name: b.EncodeVarint(6<<3 | proto.WireBytes) b.EncodeStringBytes(x.Name) case *Communique_Data: b.EncodeVarint(7<<3 | proto.WireBytes) b.EncodeRawBytes(x.Data) case *Communique_TempC: b.EncodeVarint(8<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.TempC)) case *Communique_Height: b.EncodeVarint(9<<3 | proto.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.Height))) case *Communique_Today: b.EncodeVarint(10<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Today)) case *Communique_Maybe: t := uint64(0) if x.Maybe { t = 1 } b.EncodeVarint(11<<3 | proto.WireVarint) b.EncodeVarint(t) case *Communique_Delta_: b.EncodeVarint(12<<3 | proto.WireVarint) b.EncodeZigzag32(uint64(x.Delta)) case *Communique_Msg: b.EncodeVarint(13<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Msg); err != nil { return err } case *Communique_Somegroup: b.EncodeVarint(14<<3 | proto.WireStartGroup) if err := b.Marshal(x.Somegroup); err != nil { return err } b.EncodeVarint(14<<3 | proto.WireEndGroup) case nil: default: return fmt.Errorf("Communique.Union has unexpected type %T", x) } return nil } func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Communique) switch tag { case 5: // union.number if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Number{int32(x)} return true, err case 6: // union.name if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &Communique_Name{x} return true, err case 7: // union.data if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Union = &Communique_Data{x} return true, err case 8: // union.temp_c if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Union = &Communique_TempC{math.Float64frombits(x)} return true, err case 9: // union.height if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.Union = &Communique_Height{math.Float32frombits(uint32(x))} return true, err case 10: // union.today if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Today{Days(x)} return true, err case 11: // union.maybe if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Maybe{x != 0} return true, err case 12: // union.delta if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag32() m.Union = &Communique_Delta_{int32(x)} return true, err case 13: // union.msg if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Reply) err := b.DecodeMessage(msg) m.Union = &Communique_Msg{msg} return true, err case 14: // union.somegroup if wire != proto.WireStartGroup { return true, proto.ErrInternalBadWireType } msg := new(Communique_SomeGroup) err := b.DecodeGroup(msg) m.Union = &Communique_Somegroup{msg} return true, err default: return false, nil } } func _Communique_OneofSizer(msg proto.Message) (n int) { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: n += proto.SizeVarint(5<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Number)) case *Communique_Name: n += proto.SizeVarint(6<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Name))) n += len(x.Name) case *Communique_Data: n += proto.SizeVarint(7<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Data))) n += len(x.Data) case *Communique_TempC: n += proto.SizeVarint(8<<3 | proto.WireFixed64) n += 8 case *Communique_Height: n += proto.SizeVarint(9<<3 | proto.WireFixed32) n += 4 case *Communique_Today: n += proto.SizeVarint(10<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Today)) case *Communique_Maybe: n += proto.SizeVarint(11<<3 | proto.WireVarint) n += 1 case *Communique_Delta_: n += proto.SizeVarint(12<<3 | proto.WireVarint) n += proto.SizeVarint(uint64((uint32(x.Delta) << 1) ^ uint32((int32(x.Delta) >> 31)))) case *Communique_Msg: s := proto.Size(x.Msg) n += proto.SizeVarint(13<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Communique_Somegroup: n += proto.SizeVarint(14<<3 | proto.WireStartGroup) n += proto.Size(x.Somegroup) n += proto.SizeVarint(14<<3 | proto.WireEndGroup) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type Communique_SomeGroup struct { Member *string `protobuf:"bytes,15,opt,name=member" json:"member,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Communique_SomeGroup) Reset() { *m = Communique_SomeGroup{} } func (m *Communique_SomeGroup) String() string { return proto.CompactTextString(m) } func (*Communique_SomeGroup) ProtoMessage() {} func (m *Communique_SomeGroup) GetMember() string { if m != nil && m.Member != nil { return *m.Member } return "" } type Communique_Delta struct { XXX_unrecognized []byte `json:"-"` } func (m *Communique_Delta) Reset() { *m = Communique_Delta{} } func (m *Communique_Delta) String() string { return proto.CompactTextString(m) } func (*Communique_Delta) ProtoMessage() {} var E_Tag = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*string)(nil), Field: 103, Name: "my.test.tag", Tag: "bytes,103,opt,name=tag", Filename: "my_test/test.proto", } var E_Donut = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*OtherReplyExtensions)(nil), Field: 106, Name: "my.test.donut", Tag: "bytes,106,opt,name=donut", Filename: "my_test/test.proto", } func init() { proto.RegisterType((*Request)(nil), "my.test.Request") proto.RegisterType((*Request_SomeGroup)(nil), "my.test.Request.SomeGroup") proto.RegisterType((*Reply)(nil), "my.test.Reply") proto.RegisterType((*Reply_Entry)(nil), "my.test.Reply.Entry") proto.RegisterType((*OtherBase)(nil), "my.test.OtherBase") proto.RegisterType((*ReplyExtensions)(nil), "my.test.ReplyExtensions") proto.RegisterType((*OtherReplyExtensions)(nil), "my.test.OtherReplyExtensions") proto.RegisterType((*OldReply)(nil), "my.test.OldReply") proto.RegisterType((*Communique)(nil), "my.test.Communique") proto.RegisterType((*Communique_SomeGroup)(nil), "my.test.Communique.SomeGroup") proto.RegisterType((*Communique_Delta)(nil), "my.test.Communique.Delta") proto.RegisterEnum("my.test.HatType", HatType_name, HatType_value) proto.RegisterEnum("my.test.Days", Days_name, Days_value) proto.RegisterEnum("my.test.Request_Color", Request_Color_name, Request_Color_value) proto.RegisterEnum("my.test.Reply_Entry_Game", Reply_Entry_Game_name, Reply_Entry_Game_value) proto.RegisterExtension(E_ReplyExtensions_Time) proto.RegisterExtension(E_ReplyExtensions_Carrot) proto.RegisterExtension(E_ReplyExtensions_Donut) proto.RegisterExtension(E_Tag) proto.RegisterExtension(E_Donut) } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go.golden ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: my_test/test.proto /* Package my_test is a generated protocol buffer package. This package holds interesting messages. It is generated from these files: my_test/test.proto It has these top-level messages: Request Reply OtherBase ReplyExtensions OtherReplyExtensions OldReply Communique */ package my_test import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/golang/protobuf/protoc-gen-go/testdata/multi" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type HatType int32 const ( // deliberately skipping 0 HatType_FEDORA HatType = 1 HatType_FEZ HatType = 2 ) var HatType_name = map[int32]string{ 1: "FEDORA", 2: "FEZ", } var HatType_value = map[string]int32{ "FEDORA": 1, "FEZ": 2, } func (x HatType) Enum() *HatType { p := new(HatType) *p = x return p } func (x HatType) String() string { return proto.EnumName(HatType_name, int32(x)) } func (x *HatType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(HatType_value, data, "HatType") if err != nil { return err } *x = HatType(value) return nil } // This enum represents days of the week. type Days int32 const ( Days_MONDAY Days = 1 Days_TUESDAY Days = 2 Days_LUNDI Days = 1 ) var Days_name = map[int32]string{ 1: "MONDAY", 2: "TUESDAY", // Duplicate value: 1: "LUNDI", } var Days_value = map[string]int32{ "MONDAY": 1, "TUESDAY": 2, "LUNDI": 1, } func (x Days) Enum() *Days { p := new(Days) *p = x return p } func (x Days) String() string { return proto.EnumName(Days_name, int32(x)) } func (x *Days) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Days_value, data, "Days") if err != nil { return err } *x = Days(value) return nil } type Request_Color int32 const ( Request_RED Request_Color = 0 Request_GREEN Request_Color = 1 Request_BLUE Request_Color = 2 ) var Request_Color_name = map[int32]string{ 0: "RED", 1: "GREEN", 2: "BLUE", } var Request_Color_value = map[string]int32{ "RED": 0, "GREEN": 1, "BLUE": 2, } func (x Request_Color) Enum() *Request_Color { p := new(Request_Color) *p = x return p } func (x Request_Color) String() string { return proto.EnumName(Request_Color_name, int32(x)) } func (x *Request_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Request_Color_value, data, "Request_Color") if err != nil { return err } *x = Request_Color(value) return nil } type Reply_Entry_Game int32 const ( Reply_Entry_FOOTBALL Reply_Entry_Game = 1 Reply_Entry_TENNIS Reply_Entry_Game = 2 ) var Reply_Entry_Game_name = map[int32]string{ 1: "FOOTBALL", 2: "TENNIS", } var Reply_Entry_Game_value = map[string]int32{ "FOOTBALL": 1, "TENNIS": 2, } func (x Reply_Entry_Game) Enum() *Reply_Entry_Game { p := new(Reply_Entry_Game) *p = x return p } func (x Reply_Entry_Game) String() string { return proto.EnumName(Reply_Entry_Game_name, int32(x)) } func (x *Reply_Entry_Game) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Reply_Entry_Game_value, data, "Reply_Entry_Game") if err != nil { return err } *x = Reply_Entry_Game(value) return nil } // This is a message that might be sent somewhere. type Request struct { Key []int64 `protobuf:"varint,1,rep,name=key" json:"key,omitempty"` // optional imp.ImportedMessage imported_message = 2; Hue *Request_Color `protobuf:"varint,3,opt,name=hue,enum=my.test.Request_Color" json:"hue,omitempty"` Hat *HatType `protobuf:"varint,4,opt,name=hat,enum=my.test.HatType,def=1" json:"hat,omitempty"` // optional imp.ImportedMessage.Owner owner = 6; Deadline *float32 `protobuf:"fixed32,7,opt,name=deadline,def=inf" json:"deadline,omitempty"` Somegroup *Request_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"` // This is a map field. It will generate map[int32]string. NameMapping map[int32]string `protobuf:"bytes,14,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // This is a map field whose value type is a message. MsgMapping map[int64]*Reply `protobuf:"bytes,15,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Reset_ *int32 `protobuf:"varint,12,opt,name=reset" json:"reset,omitempty"` // This field should not conflict with any getters. GetKey_ *string `protobuf:"bytes,16,opt,name=get_key,json=getKey" json:"get_key,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Request) Reset() { *m = Request{} } func (m *Request) String() string { return proto.CompactTextString(m) } func (*Request) ProtoMessage() {} const Default_Request_Hat HatType = HatType_FEDORA var Default_Request_Deadline float32 = float32(math.Inf(1)) func (m *Request) GetKey() []int64 { if m != nil { return m.Key } return nil } func (m *Request) GetHue() Request_Color { if m != nil && m.Hue != nil { return *m.Hue } return Request_RED } func (m *Request) GetHat() HatType { if m != nil && m.Hat != nil { return *m.Hat } return Default_Request_Hat } func (m *Request) GetDeadline() float32 { if m != nil && m.Deadline != nil { return *m.Deadline } return Default_Request_Deadline } func (m *Request) GetSomegroup() *Request_SomeGroup { if m != nil { return m.Somegroup } return nil } func (m *Request) GetNameMapping() map[int32]string { if m != nil { return m.NameMapping } return nil } func (m *Request) GetMsgMapping() map[int64]*Reply { if m != nil { return m.MsgMapping } return nil } func (m *Request) GetReset_() int32 { if m != nil && m.Reset_ != nil { return *m.Reset_ } return 0 } func (m *Request) GetGetKey_() string { if m != nil && m.GetKey_ != nil { return *m.GetKey_ } return "" } type Request_SomeGroup struct { GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Request_SomeGroup) Reset() { *m = Request_SomeGroup{} } func (m *Request_SomeGroup) String() string { return proto.CompactTextString(m) } func (*Request_SomeGroup) ProtoMessage() {} func (m *Request_SomeGroup) GetGroupField() int32 { if m != nil && m.GroupField != nil { return *m.GroupField } return 0 } type Reply struct { Found []*Reply_Entry `protobuf:"bytes,1,rep,name=found" json:"found,omitempty"` CompactKeys []int32 `protobuf:"varint,2,rep,packed,name=compact_keys,json=compactKeys" json:"compact_keys,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *Reply) Reset() { *m = Reply{} } func (m *Reply) String() string { return proto.CompactTextString(m) } func (*Reply) ProtoMessage() {} var extRange_Reply = []proto.ExtensionRange{ {100, 536870911}, } func (*Reply) ExtensionRangeArray() []proto.ExtensionRange { return extRange_Reply } func (m *Reply) GetFound() []*Reply_Entry { if m != nil { return m.Found } return nil } func (m *Reply) GetCompactKeys() []int32 { if m != nil { return m.CompactKeys } return nil } type Reply_Entry struct { KeyThatNeeds_1234Camel_CasIng *int64 `protobuf:"varint,1,req,name=key_that_needs_1234camel_CasIng,json=keyThatNeeds1234camelCasIng" json:"key_that_needs_1234camel_CasIng,omitempty"` Value *int64 `protobuf:"varint,2,opt,name=value,def=7" json:"value,omitempty"` XMyFieldName_2 *int64 `protobuf:"varint,3,opt,name=_my_field_name_2,json=MyFieldName2" json:"_my_field_name_2,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Reply_Entry) Reset() { *m = Reply_Entry{} } func (m *Reply_Entry) String() string { return proto.CompactTextString(m) } func (*Reply_Entry) ProtoMessage() {} const Default_Reply_Entry_Value int64 = 7 func (m *Reply_Entry) GetKeyThatNeeds_1234Camel_CasIng() int64 { if m != nil && m.KeyThatNeeds_1234Camel_CasIng != nil { return *m.KeyThatNeeds_1234Camel_CasIng } return 0 } func (m *Reply_Entry) GetValue() int64 { if m != nil && m.Value != nil { return *m.Value } return Default_Reply_Entry_Value } func (m *Reply_Entry) GetXMyFieldName_2() int64 { if m != nil && m.XMyFieldName_2 != nil { return *m.XMyFieldName_2 } return 0 } type OtherBase struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OtherBase) Reset() { *m = OtherBase{} } func (m *OtherBase) String() string { return proto.CompactTextString(m) } func (*OtherBase) ProtoMessage() {} var extRange_OtherBase = []proto.ExtensionRange{ {100, 536870911}, } func (*OtherBase) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OtherBase } func (m *OtherBase) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } type ReplyExtensions struct { XXX_unrecognized []byte `json:"-"` } func (m *ReplyExtensions) Reset() { *m = ReplyExtensions{} } func (m *ReplyExtensions) String() string { return proto.CompactTextString(m) } func (*ReplyExtensions) ProtoMessage() {} var E_ReplyExtensions_Time = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*float64)(nil), Field: 101, Name: "my.test.ReplyExtensions.time", Tag: "fixed64,101,opt,name=time", Filename: "my_test/test.proto", } var E_ReplyExtensions_Carrot = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*ReplyExtensions)(nil), Field: 105, Name: "my.test.ReplyExtensions.carrot", Tag: "bytes,105,opt,name=carrot", Filename: "my_test/test.proto", } var E_ReplyExtensions_Donut = &proto.ExtensionDesc{ ExtendedType: (*OtherBase)(nil), ExtensionType: (*ReplyExtensions)(nil), Field: 101, Name: "my.test.ReplyExtensions.donut", Tag: "bytes,101,opt,name=donut", Filename: "my_test/test.proto", } type OtherReplyExtensions struct { Key *int32 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *OtherReplyExtensions) Reset() { *m = OtherReplyExtensions{} } func (m *OtherReplyExtensions) String() string { return proto.CompactTextString(m) } func (*OtherReplyExtensions) ProtoMessage() {} func (m *OtherReplyExtensions) GetKey() int32 { if m != nil && m.Key != nil { return *m.Key } return 0 } type OldReply struct { proto.XXX_InternalExtensions `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OldReply) Reset() { *m = OldReply{} } func (m *OldReply) String() string { return proto.CompactTextString(m) } func (*OldReply) ProtoMessage() {} func (m *OldReply) Marshal() ([]byte, error) { return proto.MarshalMessageSet(&m.XXX_InternalExtensions) } func (m *OldReply) Unmarshal(buf []byte) error { return proto.UnmarshalMessageSet(buf, &m.XXX_InternalExtensions) } func (m *OldReply) MarshalJSON() ([]byte, error) { return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions) } func (m *OldReply) UnmarshalJSON(buf []byte) error { return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions) } // ensure OldReply satisfies proto.Marshaler and proto.Unmarshaler var _ proto.Marshaler = (*OldReply)(nil) var _ proto.Unmarshaler = (*OldReply)(nil) var extRange_OldReply = []proto.ExtensionRange{ {100, 2147483646}, } func (*OldReply) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OldReply } type Communique struct { MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"` // This is a oneof, called "union". // // Types that are valid to be assigned to Union: // *Communique_Number // *Communique_Name // *Communique_Data // *Communique_TempC // *Communique_Height // *Communique_Today // *Communique_Maybe // *Communique_Delta_ // *Communique_Msg // *Communique_Somegroup Union isCommunique_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *Communique) Reset() { *m = Communique{} } func (m *Communique) String() string { return proto.CompactTextString(m) } func (*Communique) ProtoMessage() {} type isCommunique_Union interface { isCommunique_Union() } type Communique_Number struct { Number int32 `protobuf:"varint,5,opt,name=number,oneof"` } type Communique_Name struct { Name string `protobuf:"bytes,6,opt,name=name,oneof"` } type Communique_Data struct { Data []byte `protobuf:"bytes,7,opt,name=data,oneof"` } type Communique_TempC struct { TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"` } type Communique_Height struct { Height float32 `protobuf:"fixed32,9,opt,name=height,oneof"` } type Communique_Today struct { Today Days `protobuf:"varint,10,opt,name=today,enum=my.test.Days,oneof"` } type Communique_Maybe struct { Maybe bool `protobuf:"varint,11,opt,name=maybe,oneof"` } type Communique_Delta_ struct { Delta int32 `protobuf:"zigzag32,12,opt,name=delta,oneof"` } type Communique_Msg struct { Msg *Reply `protobuf:"bytes,13,opt,name=msg,oneof"` } type Communique_Somegroup struct { Somegroup *Communique_SomeGroup `protobuf:"group,14,opt,name=SomeGroup,json=somegroup,oneof"` } func (*Communique_Number) isCommunique_Union() {} func (*Communique_Name) isCommunique_Union() {} func (*Communique_Data) isCommunique_Union() {} func (*Communique_TempC) isCommunique_Union() {} func (*Communique_Height) isCommunique_Union() {} func (*Communique_Today) isCommunique_Union() {} func (*Communique_Maybe) isCommunique_Union() {} func (*Communique_Delta_) isCommunique_Union() {} func (*Communique_Msg) isCommunique_Union() {} func (*Communique_Somegroup) isCommunique_Union() {} func (m *Communique) GetUnion() isCommunique_Union { if m != nil { return m.Union } return nil } func (m *Communique) GetMakeMeCry() bool { if m != nil && m.MakeMeCry != nil { return *m.MakeMeCry } return false } func (m *Communique) GetNumber() int32 { if x, ok := m.GetUnion().(*Communique_Number); ok { return x.Number } return 0 } func (m *Communique) GetName() string { if x, ok := m.GetUnion().(*Communique_Name); ok { return x.Name } return "" } func (m *Communique) GetData() []byte { if x, ok := m.GetUnion().(*Communique_Data); ok { return x.Data } return nil } func (m *Communique) GetTempC() float64 { if x, ok := m.GetUnion().(*Communique_TempC); ok { return x.TempC } return 0 } func (m *Communique) GetHeight() float32 { if x, ok := m.GetUnion().(*Communique_Height); ok { return x.Height } return 0 } func (m *Communique) GetToday() Days { if x, ok := m.GetUnion().(*Communique_Today); ok { return x.Today } return Days_MONDAY } func (m *Communique) GetMaybe() bool { if x, ok := m.GetUnion().(*Communique_Maybe); ok { return x.Maybe } return false } func (m *Communique) GetDelta() int32 { if x, ok := m.GetUnion().(*Communique_Delta_); ok { return x.Delta } return 0 } func (m *Communique) GetMsg() *Reply { if x, ok := m.GetUnion().(*Communique_Msg); ok { return x.Msg } return nil } func (m *Communique) GetSomegroup() *Communique_SomeGroup { if x, ok := m.GetUnion().(*Communique_Somegroup); ok { return x.Somegroup } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{ (*Communique_Number)(nil), (*Communique_Name)(nil), (*Communique_Data)(nil), (*Communique_TempC)(nil), (*Communique_Height)(nil), (*Communique_Today)(nil), (*Communique_Maybe)(nil), (*Communique_Delta_)(nil), (*Communique_Msg)(nil), (*Communique_Somegroup)(nil), } } func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: b.EncodeVarint(5<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Number)) case *Communique_Name: b.EncodeVarint(6<<3 | proto.WireBytes) b.EncodeStringBytes(x.Name) case *Communique_Data: b.EncodeVarint(7<<3 | proto.WireBytes) b.EncodeRawBytes(x.Data) case *Communique_TempC: b.EncodeVarint(8<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.TempC)) case *Communique_Height: b.EncodeVarint(9<<3 | proto.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.Height))) case *Communique_Today: b.EncodeVarint(10<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Today)) case *Communique_Maybe: t := uint64(0) if x.Maybe { t = 1 } b.EncodeVarint(11<<3 | proto.WireVarint) b.EncodeVarint(t) case *Communique_Delta_: b.EncodeVarint(12<<3 | proto.WireVarint) b.EncodeZigzag32(uint64(x.Delta)) case *Communique_Msg: b.EncodeVarint(13<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Msg); err != nil { return err } case *Communique_Somegroup: b.EncodeVarint(14<<3 | proto.WireStartGroup) if err := b.Marshal(x.Somegroup); err != nil { return err } b.EncodeVarint(14<<3 | proto.WireEndGroup) case nil: default: return fmt.Errorf("Communique.Union has unexpected type %T", x) } return nil } func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Communique) switch tag { case 5: // union.number if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Number{int32(x)} return true, err case 6: // union.name if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &Communique_Name{x} return true, err case 7: // union.data if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Union = &Communique_Data{x} return true, err case 8: // union.temp_c if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Union = &Communique_TempC{math.Float64frombits(x)} return true, err case 9: // union.height if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.Union = &Communique_Height{math.Float32frombits(uint32(x))} return true, err case 10: // union.today if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Today{Days(x)} return true, err case 11: // union.maybe if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Maybe{x != 0} return true, err case 12: // union.delta if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag32() m.Union = &Communique_Delta_{int32(x)} return true, err case 13: // union.msg if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Reply) err := b.DecodeMessage(msg) m.Union = &Communique_Msg{msg} return true, err case 14: // union.somegroup if wire != proto.WireStartGroup { return true, proto.ErrInternalBadWireType } msg := new(Communique_SomeGroup) err := b.DecodeGroup(msg) m.Union = &Communique_Somegroup{msg} return true, err default: return false, nil } } func _Communique_OneofSizer(msg proto.Message) (n int) { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: n += proto.SizeVarint(5<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Number)) case *Communique_Name: n += proto.SizeVarint(6<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Name))) n += len(x.Name) case *Communique_Data: n += proto.SizeVarint(7<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Data))) n += len(x.Data) case *Communique_TempC: n += proto.SizeVarint(8<<3 | proto.WireFixed64) n += 8 case *Communique_Height: n += proto.SizeVarint(9<<3 | proto.WireFixed32) n += 4 case *Communique_Today: n += proto.SizeVarint(10<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Today)) case *Communique_Maybe: n += proto.SizeVarint(11<<3 | proto.WireVarint) n += 1 case *Communique_Delta_: n += proto.SizeVarint(12<<3 | proto.WireVarint) n += proto.SizeVarint(uint64((uint32(x.Delta) << 1) ^ uint32((int32(x.Delta) >> 31)))) case *Communique_Msg: s := proto.Size(x.Msg) n += proto.SizeVarint(13<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Communique_Somegroup: n += proto.SizeVarint(14<<3 | proto.WireStartGroup) n += proto.Size(x.Somegroup) n += proto.SizeVarint(14<<3 | proto.WireEndGroup) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type Communique_SomeGroup struct { Member *string `protobuf:"bytes,15,opt,name=member" json:"member,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Communique_SomeGroup) Reset() { *m = Communique_SomeGroup{} } func (m *Communique_SomeGroup) String() string { return proto.CompactTextString(m) } func (*Communique_SomeGroup) ProtoMessage() {} func (m *Communique_SomeGroup) GetMember() string { if m != nil && m.Member != nil { return *m.Member } return "" } type Communique_Delta struct { XXX_unrecognized []byte `json:"-"` } func (m *Communique_Delta) Reset() { *m = Communique_Delta{} } func (m *Communique_Delta) String() string { return proto.CompactTextString(m) } func (*Communique_Delta) ProtoMessage() {} var E_Tag = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*string)(nil), Field: 103, Name: "my.test.tag", Tag: "bytes,103,opt,name=tag", Filename: "my_test/test.proto", } var E_Donut = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*OtherReplyExtensions)(nil), Field: 106, Name: "my.test.donut", Tag: "bytes,106,opt,name=donut", Filename: "my_test/test.proto", } func init() { proto.RegisterType((*Request)(nil), "my.test.Request") proto.RegisterType((*Request_SomeGroup)(nil), "my.test.Request.SomeGroup") proto.RegisterType((*Reply)(nil), "my.test.Reply") proto.RegisterType((*Reply_Entry)(nil), "my.test.Reply.Entry") proto.RegisterType((*OtherBase)(nil), "my.test.OtherBase") proto.RegisterType((*ReplyExtensions)(nil), "my.test.ReplyExtensions") proto.RegisterType((*OtherReplyExtensions)(nil), "my.test.OtherReplyExtensions") proto.RegisterType((*OldReply)(nil), "my.test.OldReply") proto.RegisterType((*Communique)(nil), "my.test.Communique") proto.RegisterType((*Communique_SomeGroup)(nil), "my.test.Communique.SomeGroup") proto.RegisterType((*Communique_Delta)(nil), "my.test.Communique.Delta") proto.RegisterEnum("my.test.HatType", HatType_name, HatType_value) proto.RegisterEnum("my.test.Days", Days_name, Days_value) proto.RegisterEnum("my.test.Request_Color", Request_Color_name, Request_Color_value) proto.RegisterEnum("my.test.Reply_Entry_Game", Reply_Entry_Game_name, Reply_Entry_Game_value) proto.RegisterExtension(E_ReplyExtensions_Time) proto.RegisterExtension(E_ReplyExtensions_Carrot) proto.RegisterExtension(E_ReplyExtensions_Donut) proto.RegisterExtension(E_Tag) proto.RegisterExtension(E_Donut) } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto2"; // This package holds interesting messages. package my.test; // dotted package name //import "imp.proto"; import "multi/multi1.proto"; // unused import enum HatType { // deliberately skipping 0 FEDORA = 1; FEZ = 2; } // This enum represents days of the week. enum Days { option allow_alias = true; MONDAY = 1; TUESDAY = 2; LUNDI = 1; // same value as MONDAY } // This is a message that might be sent somewhere. message Request { enum Color { RED = 0; GREEN = 1; BLUE = 2; } repeated int64 key = 1; // optional imp.ImportedMessage imported_message = 2; optional Color hue = 3; // no default optional HatType hat = 4 [default=FEDORA]; // optional imp.ImportedMessage.Owner owner = 6; optional float deadline = 7 [default=inf]; optional group SomeGroup = 8 { optional int32 group_field = 9; } // These foreign types are in imp2.proto, // which is publicly imported by imp.proto. // optional imp.PubliclyImportedMessage pub = 10; // optional imp.PubliclyImportedEnum pub_enum = 13 [default=HAIR]; // This is a map field. It will generate map[int32]string. map name_mapping = 14; // This is a map field whose value type is a message. map msg_mapping = 15; optional int32 reset = 12; // This field should not conflict with any getters. optional string get_key = 16; } message Reply { message Entry { required int64 key_that_needs_1234camel_CasIng = 1; optional int64 value = 2 [default=7]; optional int64 _my_field_name_2 = 3; enum Game { FOOTBALL = 1; TENNIS = 2; } } repeated Entry found = 1; repeated int32 compact_keys = 2 [packed=true]; extensions 100 to max; } message OtherBase { optional string name = 1; extensions 100 to max; } message ReplyExtensions { extend Reply { optional double time = 101; optional ReplyExtensions carrot = 105; } extend OtherBase { optional ReplyExtensions donut = 101; } } message OtherReplyExtensions { optional int32 key = 1; } // top-level extension extend Reply { optional string tag = 103; optional OtherReplyExtensions donut = 106; // optional imp.ImportedMessage elephant = 107; // extend with message from another file. } message OldReply { // Extensions will be encoded in MessageSet wire format. option message_set_wire_format = true; extensions 100 to max; } message Communique { optional bool make_me_cry = 1; // This is a oneof, called "union". oneof union { int32 number = 5; string name = 6; bytes data = 7; double temp_c = 8; float height = 9; Days today = 10; bool maybe = 11; sint32 delta = 12; // name will conflict with Delta below Reply msg = 13; group SomeGroup = 14 { optional string member = 15; } } message Delta {} } ================================================ FILE: src/github.com/golang/protobuf/protoc-gen-go/testdata/proto3.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 The Go Authors. All rights reserved. // https://github.com/golang/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. syntax = "proto3"; package proto3; message Request { enum Flavour { SWEET = 0; SOUR = 1; UMAMI = 2; GOPHERLICIOUS = 3; } string name = 1; repeated int64 key = 2; Flavour taste = 3; Book book = 4; repeated int64 unpacked = 5 [packed=false]; } message Book { string title = 1; bytes raw_data = 2; } ================================================ FILE: src/github.com/golang/protobuf/ptypes/any/any.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/any.proto /* Package any is a generated protocol buffer package. It is generated from these files: google/protobuf/any.proto It has these top-level messages: Any */ package any import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // `Any` contains an arbitrary serialized protocol buffer message along with a // URL that describes the type of the serialized message. // // Protobuf library provides support to pack/unpack Any values in the form // of utility functions or additional generated methods of the Any type. // // Example 1: Pack and unpack a message in C++. // // Foo foo = ...; // Any any; // any.PackFrom(foo); // ... // if (any.UnpackTo(&foo)) { // ... // } // // Example 2: Pack and unpack a message in Java. // // Foo foo = ...; // Any any = Any.pack(foo); // ... // if (any.is(Foo.class)) { // foo = any.unpack(Foo.class); // } // // Example 3: Pack and unpack a message in Python. // // foo = Foo(...) // any = Any() // any.Pack(foo) // ... // if any.Is(Foo.DESCRIPTOR): // any.Unpack(foo) // ... // // Example 4: Pack and unpack a message in Go // // foo := &pb.Foo{...} // any, err := ptypes.MarshalAny(foo) // ... // foo := &pb.Foo{} // if err := ptypes.UnmarshalAny(any, foo); err != nil { // ... // } // // The pack methods provided by protobuf library will by default use // 'type.googleapis.com/full.type.name' as the type URL and the unpack // methods only use the fully qualified type name after the last '/' // in the type URL, for example "foo.bar.com/x/y.z" will yield type // name "y.z". // // // JSON // // The JSON representation of an `Any` value uses the regular // representation of the deserialized, embedded message, with an // additional field `@type` which contains the type URL. Example: // // package google.profile; // message Person { // string first_name = 1; // string last_name = 2; // } // // { // "@type": "type.googleapis.com/google.profile.Person", // "firstName": , // "lastName": // } // // If the embedded message type is well-known and has a custom JSON // representation, that representation will be embedded adding a field // `value` which holds the custom JSON in addition to the `@type` // field. Example (for message [google.protobuf.Duration][]): // // { // "@type": "type.googleapis.com/google.protobuf.Duration", // "value": "1.212s" // } // type Any struct { // A URL/resource name whose content describes the type of the // serialized protocol buffer message. // // For URLs which use the scheme `http`, `https`, or no scheme, the // following restrictions and interpretations apply: // // * If no scheme is provided, `https` is assumed. // * The last segment of the URL's path must represent the fully // qualified name of the type (as in `path/google.protobuf.Duration`). // The name should be in a canonical form (e.g., leading "." is // not accepted). // * An HTTP GET on the URL must yield a [google.protobuf.Type][] // value in binary format, or produce an error. // * Applications are allowed to cache lookup results based on the // URL, or have them precompiled into a binary to avoid any // lookup. Therefore, binary compatibility needs to be preserved // on changes to types. (Use versioned type names to manage // breaking changes.) // // Schemes other than `http`, `https` (or the empty scheme) might be // used with implementation specific semantics. // TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl" json:"type_url,omitempty"` // Must be a valid serialized protocol buffer of the above specified type. Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` } func (m *Any) Reset() { *m = Any{} } func (m *Any) String() string { return proto.CompactTextString(m) } func (*Any) ProtoMessage() {} func (*Any) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (*Any) XXX_WellKnownType() string { return "Any" } func (m *Any) GetTypeUrl() string { if m != nil { return m.TypeUrl } return "" } func (m *Any) GetValue() []byte { if m != nil { return m.Value } return nil } func init() { proto.RegisterType((*Any)(nil), "google.protobuf.Any") } func init() { proto.RegisterFile("google/protobuf/any.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 185 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcc, 0xab, 0xd4, 0x03, 0x73, 0x84, 0xf8, 0x21, 0x52, 0x7a, 0x30, 0x29, 0x25, 0x33, 0x2e, 0x66, 0xc7, 0xbc, 0x4a, 0x21, 0x49, 0x2e, 0x8e, 0x92, 0xca, 0x82, 0xd4, 0xf8, 0xd2, 0xa2, 0x1c, 0x09, 0x46, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x76, 0x10, 0x3f, 0xb4, 0x28, 0x47, 0x48, 0x84, 0x8b, 0xb5, 0x2c, 0x31, 0xa7, 0x34, 0x55, 0x82, 0x49, 0x81, 0x51, 0x83, 0x27, 0x08, 0xc2, 0x71, 0xca, 0xe7, 0x12, 0x4e, 0xce, 0xcf, 0xd5, 0x43, 0x33, 0xce, 0x89, 0xc3, 0x31, 0xaf, 0x32, 0x00, 0xc4, 0x09, 0x60, 0x8c, 0x52, 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0x47, 0xb8, 0xa8, 0x00, 0x64, 0x7a, 0x31, 0xc8, 0x61, 0x8b, 0x98, 0x98, 0xdd, 0x03, 0x9c, 0x56, 0x31, 0xc9, 0xb9, 0x43, 0x8c, 0x0a, 0x80, 0x2a, 0xd1, 0x0b, 0x4f, 0xcd, 0xc9, 0xf1, 0xce, 0xcb, 0x2f, 0xcf, 0x0b, 0x01, 0x29, 0x4d, 0x62, 0x03, 0xeb, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x13, 0xf8, 0xe8, 0x42, 0xdd, 0x00, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/ptypes/any/any.proto ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option go_package = "github.com/golang/protobuf/ptypes/any"; option java_package = "com.google.protobuf"; option java_outer_classname = "AnyProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // `Any` contains an arbitrary serialized protocol buffer message along with a // URL that describes the type of the serialized message. // // Protobuf library provides support to pack/unpack Any values in the form // of utility functions or additional generated methods of the Any type. // // Example 1: Pack and unpack a message in C++. // // Foo foo = ...; // Any any; // any.PackFrom(foo); // ... // if (any.UnpackTo(&foo)) { // ... // } // // Example 2: Pack and unpack a message in Java. // // Foo foo = ...; // Any any = Any.pack(foo); // ... // if (any.is(Foo.class)) { // foo = any.unpack(Foo.class); // } // // Example 3: Pack and unpack a message in Python. // // foo = Foo(...) // any = Any() // any.Pack(foo) // ... // if any.Is(Foo.DESCRIPTOR): // any.Unpack(foo) // ... // // Example 4: Pack and unpack a message in Go // // foo := &pb.Foo{...} // any, err := ptypes.MarshalAny(foo) // ... // foo := &pb.Foo{} // if err := ptypes.UnmarshalAny(any, foo); err != nil { // ... // } // // The pack methods provided by protobuf library will by default use // 'type.googleapis.com/full.type.name' as the type URL and the unpack // methods only use the fully qualified type name after the last '/' // in the type URL, for example "foo.bar.com/x/y.z" will yield type // name "y.z". // // // JSON // // The JSON representation of an `Any` value uses the regular // representation of the deserialized, embedded message, with an // additional field `@type` which contains the type URL. Example: // // package google.profile; // message Person { // string first_name = 1; // string last_name = 2; // } // // { // "@type": "type.googleapis.com/google.profile.Person", // "firstName": , // "lastName": // } // // If the embedded message type is well-known and has a custom JSON // representation, that representation will be embedded adding a field // `value` which holds the custom JSON in addition to the `@type` // field. Example (for message [google.protobuf.Duration][]): // // { // "@type": "type.googleapis.com/google.protobuf.Duration", // "value": "1.212s" // } // message Any { // A URL/resource name whose content describes the type of the // serialized protocol buffer message. // // For URLs which use the scheme `http`, `https`, or no scheme, the // following restrictions and interpretations apply: // // * If no scheme is provided, `https` is assumed. // * The last segment of the URL's path must represent the fully // qualified name of the type (as in `path/google.protobuf.Duration`). // The name should be in a canonical form (e.g., leading "." is // not accepted). // * An HTTP GET on the URL must yield a [google.protobuf.Type][] // value in binary format, or produce an error. // * Applications are allowed to cache lookup results based on the // URL, or have them precompiled into a binary to avoid any // lookup. Therefore, binary compatibility needs to be preserved // on changes to types. (Use versioned type names to manage // breaking changes.) // // Schemes other than `http`, `https` (or the empty scheme) might be // used with implementation specific semantics. // string type_url = 1; // Must be a valid serialized protocol buffer of the above specified type. bytes value = 2; } ================================================ FILE: src/github.com/golang/protobuf/ptypes/any.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/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. package ptypes // This file implements functions to marshal proto.Message to/from // google.protobuf.Any message. import ( "fmt" "reflect" "strings" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/any" ) const googleApis = "type.googleapis.com/" // AnyMessageName returns the name of the message contained in a google.protobuf.Any message. // // Note that regular type assertions should be done using the Is // function. AnyMessageName is provided for less common use cases like filtering a // sequence of Any messages based on a set of allowed message type names. func AnyMessageName(any *any.Any) (string, error) { if any == nil { return "", fmt.Errorf("message is nil") } slash := strings.LastIndex(any.TypeUrl, "/") if slash < 0 { return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl) } return any.TypeUrl[slash+1:], nil } // MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any. func MarshalAny(pb proto.Message) (*any.Any, error) { value, err := proto.Marshal(pb) if err != nil { return nil, err } return &any.Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil } // DynamicAny is a value that can be passed to UnmarshalAny to automatically // allocate a proto.Message for the type specified in a google.protobuf.Any // message. The allocated message is stored in the embedded proto.Message. // // Example: // // var x ptypes.DynamicAny // if err := ptypes.UnmarshalAny(a, &x); err != nil { ... } // fmt.Printf("unmarshaled message: %v", x.Message) type DynamicAny struct { proto.Message } // Empty returns a new proto.Message of the type specified in a // google.protobuf.Any message. It returns an error if corresponding message // type isn't linked in. func Empty(any *any.Any) (proto.Message, error) { aname, err := AnyMessageName(any) if err != nil { return nil, err } t := proto.MessageType(aname) if t == nil { return nil, fmt.Errorf("any: message type %q isn't linked in", aname) } return reflect.New(t.Elem()).Interface().(proto.Message), nil } // UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any // message and places the decoded result in pb. It returns an error if type of // contents of Any message does not match type of pb message. // // pb can be a proto.Message, or a *DynamicAny. func UnmarshalAny(any *any.Any, pb proto.Message) error { if d, ok := pb.(*DynamicAny); ok { if d.Message == nil { var err error d.Message, err = Empty(any) if err != nil { return err } } return UnmarshalAny(any, d.Message) } aname, err := AnyMessageName(any) if err != nil { return err } mname := proto.MessageName(pb) if aname != mname { return fmt.Errorf("mismatched message type: got %q want %q", aname, mname) } return proto.Unmarshal(any.Value, pb) } // Is returns true if any value contains a given message type. func Is(any *any.Any, pb proto.Message) bool { aname, err := AnyMessageName(any) if err != nil { return false } return aname == proto.MessageName(pb) } ================================================ FILE: src/github.com/golang/protobuf/ptypes/any_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/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. package ptypes import ( "testing" "github.com/golang/protobuf/proto" pb "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/golang/protobuf/ptypes/any" ) func TestMarshalUnmarshal(t *testing.T) { orig := &any.Any{Value: []byte("test")} packed, err := MarshalAny(orig) if err != nil { t.Errorf("MarshalAny(%+v): got: _, %v exp: _, nil", orig, err) } unpacked := &any.Any{} err = UnmarshalAny(packed, unpacked) if err != nil || !proto.Equal(unpacked, orig) { t.Errorf("got: %v, %+v; want nil, %+v", err, unpacked, orig) } } func TestIs(t *testing.T) { a, err := MarshalAny(&pb.FileDescriptorProto{}) if err != nil { t.Fatal(err) } if Is(a, &pb.DescriptorProto{}) { t.Error("FileDescriptorProto is not a DescriptorProto, but Is says it is") } if !Is(a, &pb.FileDescriptorProto{}) { t.Error("FileDescriptorProto is indeed a FileDescriptorProto, but Is says it is not") } } func TestIsDifferentUrlPrefixes(t *testing.T) { m := &pb.FileDescriptorProto{} a := &any.Any{TypeUrl: "foo/bar/" + proto.MessageName(m)} if !Is(a, m) { t.Errorf("message with type url %q didn't satisfy Is for type %q", a.TypeUrl, proto.MessageName(m)) } } func TestUnmarshalDynamic(t *testing.T) { want := &pb.FileDescriptorProto{Name: proto.String("foo")} a, err := MarshalAny(want) if err != nil { t.Fatal(err) } var got DynamicAny if err := UnmarshalAny(a, &got); err != nil { t.Fatal(err) } if !proto.Equal(got.Message, want) { t.Errorf("invalid result from UnmarshalAny, got %q want %q", got.Message, want) } } func TestEmpty(t *testing.T) { want := &pb.FileDescriptorProto{} a, err := MarshalAny(want) if err != nil { t.Fatal(err) } got, err := Empty(a) if err != nil { t.Fatal(err) } if !proto.Equal(got, want) { t.Errorf("unequal empty message, got %q, want %q", got, want) } // that's a valid type_url for a message which shouldn't be linked into this // test binary. We want an error. a.TypeUrl = "type.googleapis.com/google.protobuf.FieldMask" if _, err := Empty(a); err == nil { t.Errorf("got no error for an attempt to create a message of type %q, which shouldn't be linked in", a.TypeUrl) } } ================================================ FILE: src/github.com/golang/protobuf/ptypes/doc.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/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. /* Package ptypes contains code for interacting with well-known types. */ package ptypes ================================================ FILE: src/github.com/golang/protobuf/ptypes/duration/duration.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/duration.proto /* Package duration is a generated protocol buffer package. It is generated from these files: google/protobuf/duration.proto It has these top-level messages: Duration */ package duration import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // A Duration represents a signed, fixed-length span of time represented // as a count of seconds and fractions of seconds at nanosecond // resolution. It is independent of any calendar and concepts like "day" // or "month". It is related to Timestamp in that the difference between // two Timestamp values is a Duration and it can be added or subtracted // from a Timestamp. Range is approximately +-10,000 years. // // # Examples // // Example 1: Compute Duration from two Timestamps in pseudo code. // // Timestamp start = ...; // Timestamp end = ...; // Duration duration = ...; // // duration.seconds = end.seconds - start.seconds; // duration.nanos = end.nanos - start.nanos; // // if (duration.seconds < 0 && duration.nanos > 0) { // duration.seconds += 1; // duration.nanos -= 1000000000; // } else if (durations.seconds > 0 && duration.nanos < 0) { // duration.seconds -= 1; // duration.nanos += 1000000000; // } // // Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. // // Timestamp start = ...; // Duration duration = ...; // Timestamp end = ...; // // end.seconds = start.seconds + duration.seconds; // end.nanos = start.nanos + duration.nanos; // // if (end.nanos < 0) { // end.seconds -= 1; // end.nanos += 1000000000; // } else if (end.nanos >= 1000000000) { // end.seconds += 1; // end.nanos -= 1000000000; // } // // Example 3: Compute Duration from datetime.timedelta in Python. // // td = datetime.timedelta(days=3, minutes=10) // duration = Duration() // duration.FromTimedelta(td) // // # JSON Mapping // // In JSON format, the Duration type is encoded as a string rather than an // object, where the string ends in the suffix "s" (indicating seconds) and // is preceded by the number of seconds, with nanoseconds expressed as // fractional seconds. For example, 3 seconds with 0 nanoseconds should be // encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should // be expressed in JSON format as "3.000000001s", and 3 seconds and 1 // microsecond should be expressed in JSON format as "3.000001s". // // type Duration struct { // Signed seconds of the span of time. Must be from -315,576,000,000 // to +315,576,000,000 inclusive. Note: these bounds are computed from: // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"` // Signed fractions of a second at nanosecond resolution of the span // of time. Durations less than one second are represented with a 0 // `seconds` field and a positive or negative `nanos` field. For durations // of one second or more, a non-zero value for the `nanos` field must be // of the same sign as the `seconds` field. Must be from -999,999,999 // to +999,999,999 inclusive. Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` } func (m *Duration) Reset() { *m = Duration{} } func (m *Duration) String() string { return proto.CompactTextString(m) } func (*Duration) ProtoMessage() {} func (*Duration) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (*Duration) XXX_WellKnownType() string { return "Duration" } func (m *Duration) GetSeconds() int64 { if m != nil { return m.Seconds } return 0 } func (m *Duration) GetNanos() int32 { if m != nil { return m.Nanos } return 0 } func init() { proto.RegisterType((*Duration)(nil), "google.protobuf.Duration") } func init() { proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 190 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, 0x4a, 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0x56, 0x5c, 0x1c, 0x2e, 0x50, 0x25, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0xa9, 0xc9, 0xf9, 0x79, 0x29, 0xc5, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xcc, 0x41, 0x30, 0xae, 0x90, 0x08, 0x17, 0x6b, 0x5e, 0x62, 0x5e, 0x7e, 0xb1, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x84, 0xe3, 0x54, 0xc3, 0x25, 0x9c, 0x9c, 0x9f, 0xab, 0x87, 0x66, 0xa4, 0x13, 0x2f, 0xcc, 0xc0, 0x00, 0x90, 0x48, 0x00, 0x63, 0x94, 0x56, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e, 0x3a, 0xc2, 0x7d, 0x05, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x70, 0x67, 0xfe, 0x60, 0x64, 0x5c, 0xc4, 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, 0x00, 0x54, 0xa9, 0x5e, 0x78, 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, 0x12, 0x1b, 0xd8, 0x0c, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x30, 0xff, 0xf3, 0x00, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/ptypes/duration/duration.proto ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "github.com/golang/protobuf/ptypes/duration"; option java_package = "com.google.protobuf"; option java_outer_classname = "DurationProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // A Duration represents a signed, fixed-length span of time represented // as a count of seconds and fractions of seconds at nanosecond // resolution. It is independent of any calendar and concepts like "day" // or "month". It is related to Timestamp in that the difference between // two Timestamp values is a Duration and it can be added or subtracted // from a Timestamp. Range is approximately +-10,000 years. // // # Examples // // Example 1: Compute Duration from two Timestamps in pseudo code. // // Timestamp start = ...; // Timestamp end = ...; // Duration duration = ...; // // duration.seconds = end.seconds - start.seconds; // duration.nanos = end.nanos - start.nanos; // // if (duration.seconds < 0 && duration.nanos > 0) { // duration.seconds += 1; // duration.nanos -= 1000000000; // } else if (durations.seconds > 0 && duration.nanos < 0) { // duration.seconds -= 1; // duration.nanos += 1000000000; // } // // Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. // // Timestamp start = ...; // Duration duration = ...; // Timestamp end = ...; // // end.seconds = start.seconds + duration.seconds; // end.nanos = start.nanos + duration.nanos; // // if (end.nanos < 0) { // end.seconds -= 1; // end.nanos += 1000000000; // } else if (end.nanos >= 1000000000) { // end.seconds += 1; // end.nanos -= 1000000000; // } // // Example 3: Compute Duration from datetime.timedelta in Python. // // td = datetime.timedelta(days=3, minutes=10) // duration = Duration() // duration.FromTimedelta(td) // // # JSON Mapping // // In JSON format, the Duration type is encoded as a string rather than an // object, where the string ends in the suffix "s" (indicating seconds) and // is preceded by the number of seconds, with nanoseconds expressed as // fractional seconds. For example, 3 seconds with 0 nanoseconds should be // encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should // be expressed in JSON format as "3.000000001s", and 3 seconds and 1 // microsecond should be expressed in JSON format as "3.000001s". // // message Duration { // Signed seconds of the span of time. Must be from -315,576,000,000 // to +315,576,000,000 inclusive. Note: these bounds are computed from: // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years int64 seconds = 1; // Signed fractions of a second at nanosecond resolution of the span // of time. Durations less than one second are represented with a 0 // `seconds` field and a positive or negative `nanos` field. For durations // of one second or more, a non-zero value for the `nanos` field must be // of the same sign as the `seconds` field. Must be from -999,999,999 // to +999,999,999 inclusive. int32 nanos = 2; } ================================================ FILE: src/github.com/golang/protobuf/ptypes/duration.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/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. package ptypes // This file implements conversions between google.protobuf.Duration // and time.Duration. import ( "errors" "fmt" "time" durpb "github.com/golang/protobuf/ptypes/duration" ) const ( // Range of a durpb.Duration in seconds, as specified in // google/protobuf/duration.proto. This is about 10,000 years in seconds. maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60) minSeconds = -maxSeconds ) // validateDuration determines whether the durpb.Duration is valid according to the // definition in google/protobuf/duration.proto. A valid durpb.Duration // may still be too large to fit into a time.Duration (the range of durpb.Duration // is about 10,000 years, and the range of time.Duration is about 290). func validateDuration(d *durpb.Duration) error { if d == nil { return errors.New("duration: nil Duration") } if d.Seconds < minSeconds || d.Seconds > maxSeconds { return fmt.Errorf("duration: %v: seconds out of range", d) } if d.Nanos <= -1e9 || d.Nanos >= 1e9 { return fmt.Errorf("duration: %v: nanos out of range", d) } // Seconds and Nanos must have the same sign, unless d.Nanos is zero. if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) { return fmt.Errorf("duration: %v: seconds and nanos have different signs", d) } return nil } // Duration converts a durpb.Duration to a time.Duration. Duration // returns an error if the durpb.Duration is invalid or is too large to be // represented in a time.Duration. func Duration(p *durpb.Duration) (time.Duration, error) { if err := validateDuration(p); err != nil { return 0, err } d := time.Duration(p.Seconds) * time.Second if int64(d/time.Second) != p.Seconds { return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p) } if p.Nanos != 0 { d += time.Duration(p.Nanos) if (d < 0) != (p.Nanos < 0) { return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p) } } return d, nil } // DurationProto converts a time.Duration to a durpb.Duration. func DurationProto(d time.Duration) *durpb.Duration { nanos := d.Nanoseconds() secs := nanos / 1e9 nanos -= secs * 1e9 return &durpb.Duration{ Seconds: secs, Nanos: int32(nanos), } } ================================================ FILE: src/github.com/golang/protobuf/ptypes/duration_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/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. package ptypes import ( "math" "testing" "time" "github.com/golang/protobuf/proto" durpb "github.com/golang/protobuf/ptypes/duration" ) const ( minGoSeconds = math.MinInt64 / int64(1e9) maxGoSeconds = math.MaxInt64 / int64(1e9) ) var durationTests = []struct { proto *durpb.Duration isValid bool inRange bool dur time.Duration }{ // The zero duration. {&durpb.Duration{Seconds: 0, Nanos: 0}, true, true, 0}, // Some ordinary non-zero durations. {&durpb.Duration{Seconds: 100, Nanos: 0}, true, true, 100 * time.Second}, {&durpb.Duration{Seconds: -100, Nanos: 0}, true, true, -100 * time.Second}, {&durpb.Duration{Seconds: 100, Nanos: 987}, true, true, 100*time.Second + 987}, {&durpb.Duration{Seconds: -100, Nanos: -987}, true, true, -(100*time.Second + 987)}, // The largest duration representable in Go. {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, true, math.MaxInt64}, // The smallest duration representable in Go. {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, true, math.MinInt64}, {nil, false, false, 0}, {&durpb.Duration{Seconds: -100, Nanos: 987}, false, false, 0}, {&durpb.Duration{Seconds: 100, Nanos: -987}, false, false, 0}, {&durpb.Duration{Seconds: math.MinInt64, Nanos: 0}, false, false, 0}, {&durpb.Duration{Seconds: math.MaxInt64, Nanos: 0}, false, false, 0}, // The largest valid duration. {&durpb.Duration{Seconds: maxSeconds, Nanos: 1e9 - 1}, true, false, 0}, // The smallest valid duration. {&durpb.Duration{Seconds: minSeconds, Nanos: -(1e9 - 1)}, true, false, 0}, // The smallest invalid duration above the valid range. {&durpb.Duration{Seconds: maxSeconds + 1, Nanos: 0}, false, false, 0}, // The largest invalid duration below the valid range. {&durpb.Duration{Seconds: minSeconds - 1, Nanos: -(1e9 - 1)}, false, false, 0}, // One nanosecond past the largest duration representable in Go. {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64-1e9*maxGoSeconds) + 1}, true, false, 0}, // One nanosecond past the smallest duration representable in Go. {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64-1e9*minGoSeconds) - 1}, true, false, 0}, // One second past the largest duration representable in Go. {&durpb.Duration{Seconds: maxGoSeconds + 1, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, false, 0}, // One second past the smallest duration representable in Go. {&durpb.Duration{Seconds: minGoSeconds - 1, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, false, 0}, } func TestValidateDuration(t *testing.T) { for _, test := range durationTests { err := validateDuration(test.proto) gotValid := (err == nil) if gotValid != test.isValid { t.Errorf("validateDuration(%v) = %t, want %t", test.proto, gotValid, test.isValid) } } } func TestDuration(t *testing.T) { for _, test := range durationTests { got, err := Duration(test.proto) gotOK := (err == nil) wantOK := test.isValid && test.inRange if gotOK != wantOK { t.Errorf("Duration(%v) ok = %t, want %t", test.proto, gotOK, wantOK) } if err == nil && got != test.dur { t.Errorf("Duration(%v) = %v, want %v", test.proto, got, test.dur) } } } func TestDurationProto(t *testing.T) { for _, test := range durationTests { if test.isValid && test.inRange { got := DurationProto(test.dur) if !proto.Equal(got, test.proto) { t.Errorf("DurationProto(%v) = %v, want %v", test.dur, got, test.proto) } } } } ================================================ FILE: src/github.com/golang/protobuf/ptypes/empty/empty.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/empty.proto /* Package empty is a generated protocol buffer package. It is generated from these files: google/protobuf/empty.proto It has these top-level messages: Empty */ package empty import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // A generic empty message that you can re-use to avoid defining duplicated // empty messages in your APIs. A typical example is to use it as the request // or the response type of an API method. For instance: // // service Foo { // rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); // } // // The JSON representation for `Empty` is empty JSON object `{}`. type Empty struct { } func (m *Empty) Reset() { *m = Empty{} } func (m *Empty) String() string { return proto.CompactTextString(m) } func (*Empty) ProtoMessage() {} func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (*Empty) XXX_WellKnownType() string { return "Empty" } func init() { proto.RegisterType((*Empty)(nil), "google.protobuf.Empty") } func init() { proto.RegisterFile("google/protobuf/empty.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 148 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcd, 0x2d, 0x28, 0xa9, 0xd4, 0x03, 0x73, 0x85, 0xf8, 0x21, 0x92, 0x7a, 0x30, 0x49, 0x25, 0x76, 0x2e, 0x56, 0x57, 0x90, 0xbc, 0x53, 0x19, 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0xbc, 0x13, 0x17, 0x58, 0x36, 0x00, 0xc4, 0x0d, 0x60, 0x8c, 0x52, 0x4f, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0x47, 0x58, 0x53, 0x50, 0x52, 0x59, 0x90, 0x5a, 0x0c, 0xb1, 0xed, 0x07, 0x23, 0xe3, 0x22, 0x26, 0x66, 0xf7, 0x00, 0xa7, 0x55, 0x4c, 0x72, 0xee, 0x10, 0x13, 0x03, 0xa0, 0xea, 0xf4, 0xc2, 0x53, 0x73, 0x72, 0xbc, 0xf3, 0xf2, 0xcb, 0xf3, 0x42, 0x40, 0xea, 0x93, 0xd8, 0xc0, 0x06, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x64, 0xd4, 0xb3, 0xa6, 0xb7, 0x00, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/ptypes/empty/empty.proto ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option go_package = "github.com/golang/protobuf/ptypes/empty"; option java_package = "com.google.protobuf"; option java_outer_classname = "EmptyProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option cc_enable_arenas = true; // A generic empty message that you can re-use to avoid defining duplicated // empty messages in your APIs. A typical example is to use it as the request // or the response type of an API method. For instance: // // service Foo { // rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); // } // // The JSON representation for `Empty` is empty JSON object `{}`. message Empty {} ================================================ FILE: src/github.com/golang/protobuf/ptypes/regen.sh ================================================ #!/bin/bash -e # # This script fetches and rebuilds the "well-known types" protocol buffers. # To run this you will need protoc and goprotobuf installed; # see https://github.com/golang/protobuf for instructions. # You also need Go and Git installed. PKG=github.com/golang/protobuf/ptypes UPSTREAM=https://github.com/google/protobuf UPSTREAM_SUBDIR=src/google/protobuf PROTO_FILES=(any duration empty struct timestamp wrappers) function die() { echo 1>&2 $* exit 1 } # Sanity check that the right tools are accessible. for tool in go git protoc protoc-gen-go; do q=$(which $tool) || die "didn't find $tool" echo 1>&2 "$tool: $q" done tmpdir=$(mktemp -d -t regen-wkt.XXXXXX) trap 'rm -rf $tmpdir' EXIT echo -n 1>&2 "finding package dir... " pkgdir=$(go list -f '{{.Dir}}' $PKG) echo 1>&2 $pkgdir base=$(echo $pkgdir | sed "s,/$PKG\$,,") echo 1>&2 "base: $base" cd "$base" echo 1>&2 "fetching latest protos... " git clone -q $UPSTREAM $tmpdir for file in ${PROTO_FILES[@]}; do echo 1>&2 "* $file" protoc --go_out=. -I$tmpdir/src $tmpdir/src/google/protobuf/$file.proto || die cp $tmpdir/src/google/protobuf/$file.proto $PKG/$file done echo 1>&2 "All OK" ================================================ FILE: src/github.com/golang/protobuf/ptypes/struct/struct.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/struct.proto /* Package structpb is a generated protocol buffer package. It is generated from these files: google/protobuf/struct.proto It has these top-level messages: Struct Value ListValue */ package structpb import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // `NullValue` is a singleton enumeration to represent the null value for the // `Value` type union. // // The JSON representation for `NullValue` is JSON `null`. type NullValue int32 const ( // Null value. NullValue_NULL_VALUE NullValue = 0 ) var NullValue_name = map[int32]string{ 0: "NULL_VALUE", } var NullValue_value = map[string]int32{ "NULL_VALUE": 0, } func (x NullValue) String() string { return proto.EnumName(NullValue_name, int32(x)) } func (NullValue) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (NullValue) XXX_WellKnownType() string { return "NullValue" } // `Struct` represents a structured data value, consisting of fields // which map to dynamically typed values. In some languages, `Struct` // might be supported by a native representation. For example, in // scripting languages like JS a struct is represented as an // object. The details of that representation are described together // with the proto support for the language. // // The JSON representation for `Struct` is JSON object. type Struct struct { // Unordered map of dynamically typed values. Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` } func (m *Struct) Reset() { *m = Struct{} } func (m *Struct) String() string { return proto.CompactTextString(m) } func (*Struct) ProtoMessage() {} func (*Struct) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (*Struct) XXX_WellKnownType() string { return "Struct" } func (m *Struct) GetFields() map[string]*Value { if m != nil { return m.Fields } return nil } // `Value` represents a dynamically typed value which can be either // null, a number, a string, a boolean, a recursive struct value, or a // list of values. A producer of value is expected to set one of that // variants, absence of any variant indicates an error. // // The JSON representation for `Value` is JSON value. type Value struct { // The kind of value. // // Types that are valid to be assigned to Kind: // *Value_NullValue // *Value_NumberValue // *Value_StringValue // *Value_BoolValue // *Value_StructValue // *Value_ListValue Kind isValue_Kind `protobuf_oneof:"kind"` } func (m *Value) Reset() { *m = Value{} } func (m *Value) String() string { return proto.CompactTextString(m) } func (*Value) ProtoMessage() {} func (*Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (*Value) XXX_WellKnownType() string { return "Value" } type isValue_Kind interface { isValue_Kind() } type Value_NullValue struct { NullValue NullValue `protobuf:"varint,1,opt,name=null_value,json=nullValue,enum=google.protobuf.NullValue,oneof"` } type Value_NumberValue struct { NumberValue float64 `protobuf:"fixed64,2,opt,name=number_value,json=numberValue,oneof"` } type Value_StringValue struct { StringValue string `protobuf:"bytes,3,opt,name=string_value,json=stringValue,oneof"` } type Value_BoolValue struct { BoolValue bool `protobuf:"varint,4,opt,name=bool_value,json=boolValue,oneof"` } type Value_StructValue struct { StructValue *Struct `protobuf:"bytes,5,opt,name=struct_value,json=structValue,oneof"` } type Value_ListValue struct { ListValue *ListValue `protobuf:"bytes,6,opt,name=list_value,json=listValue,oneof"` } func (*Value_NullValue) isValue_Kind() {} func (*Value_NumberValue) isValue_Kind() {} func (*Value_StringValue) isValue_Kind() {} func (*Value_BoolValue) isValue_Kind() {} func (*Value_StructValue) isValue_Kind() {} func (*Value_ListValue) isValue_Kind() {} func (m *Value) GetKind() isValue_Kind { if m != nil { return m.Kind } return nil } func (m *Value) GetNullValue() NullValue { if x, ok := m.GetKind().(*Value_NullValue); ok { return x.NullValue } return NullValue_NULL_VALUE } func (m *Value) GetNumberValue() float64 { if x, ok := m.GetKind().(*Value_NumberValue); ok { return x.NumberValue } return 0 } func (m *Value) GetStringValue() string { if x, ok := m.GetKind().(*Value_StringValue); ok { return x.StringValue } return "" } func (m *Value) GetBoolValue() bool { if x, ok := m.GetKind().(*Value_BoolValue); ok { return x.BoolValue } return false } func (m *Value) GetStructValue() *Struct { if x, ok := m.GetKind().(*Value_StructValue); ok { return x.StructValue } return nil } func (m *Value) GetListValue() *ListValue { if x, ok := m.GetKind().(*Value_ListValue); ok { return x.ListValue } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*Value) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) { return _Value_OneofMarshaler, _Value_OneofUnmarshaler, _Value_OneofSizer, []interface{}{ (*Value_NullValue)(nil), (*Value_NumberValue)(nil), (*Value_StringValue)(nil), (*Value_BoolValue)(nil), (*Value_StructValue)(nil), (*Value_ListValue)(nil), } } func _Value_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Value) // kind switch x := m.Kind.(type) { case *Value_NullValue: b.EncodeVarint(1<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.NullValue)) case *Value_NumberValue: b.EncodeVarint(2<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.NumberValue)) case *Value_StringValue: b.EncodeVarint(3<<3 | proto.WireBytes) b.EncodeStringBytes(x.StringValue) case *Value_BoolValue: t := uint64(0) if x.BoolValue { t = 1 } b.EncodeVarint(4<<3 | proto.WireVarint) b.EncodeVarint(t) case *Value_StructValue: b.EncodeVarint(5<<3 | proto.WireBytes) if err := b.EncodeMessage(x.StructValue); err != nil { return err } case *Value_ListValue: b.EncodeVarint(6<<3 | proto.WireBytes) if err := b.EncodeMessage(x.ListValue); err != nil { return err } case nil: default: return fmt.Errorf("Value.Kind has unexpected type %T", x) } return nil } func _Value_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Value) switch tag { case 1: // kind.null_value if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Kind = &Value_NullValue{NullValue(x)} return true, err case 2: // kind.number_value if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Kind = &Value_NumberValue{math.Float64frombits(x)} return true, err case 3: // kind.string_value if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Kind = &Value_StringValue{x} return true, err case 4: // kind.bool_value if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Kind = &Value_BoolValue{x != 0} return true, err case 5: // kind.struct_value if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Struct) err := b.DecodeMessage(msg) m.Kind = &Value_StructValue{msg} return true, err case 6: // kind.list_value if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(ListValue) err := b.DecodeMessage(msg) m.Kind = &Value_ListValue{msg} return true, err default: return false, nil } } func _Value_OneofSizer(msg proto.Message) (n int) { m := msg.(*Value) // kind switch x := m.Kind.(type) { case *Value_NullValue: n += proto.SizeVarint(1<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.NullValue)) case *Value_NumberValue: n += proto.SizeVarint(2<<3 | proto.WireFixed64) n += 8 case *Value_StringValue: n += proto.SizeVarint(3<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.StringValue))) n += len(x.StringValue) case *Value_BoolValue: n += proto.SizeVarint(4<<3 | proto.WireVarint) n += 1 case *Value_StructValue: s := proto.Size(x.StructValue) n += proto.SizeVarint(5<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Value_ListValue: s := proto.Size(x.ListValue) n += proto.SizeVarint(6<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } // `ListValue` is a wrapper around a repeated field of values. // // The JSON representation for `ListValue` is JSON array. type ListValue struct { // Repeated field of dynamically typed values. Values []*Value `protobuf:"bytes,1,rep,name=values" json:"values,omitempty"` } func (m *ListValue) Reset() { *m = ListValue{} } func (m *ListValue) String() string { return proto.CompactTextString(m) } func (*ListValue) ProtoMessage() {} func (*ListValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (*ListValue) XXX_WellKnownType() string { return "ListValue" } func (m *ListValue) GetValues() []*Value { if m != nil { return m.Values } return nil } func init() { proto.RegisterType((*Struct)(nil), "google.protobuf.Struct") proto.RegisterType((*Value)(nil), "google.protobuf.Value") proto.RegisterType((*ListValue)(nil), "google.protobuf.ListValue") proto.RegisterEnum("google.protobuf.NullValue", NullValue_name, NullValue_value) } func init() { proto.RegisterFile("google/protobuf/struct.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 417 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0x41, 0x8b, 0xd3, 0x40, 0x14, 0xc7, 0x3b, 0xc9, 0x36, 0x98, 0x17, 0x59, 0x97, 0x11, 0xb4, 0xac, 0xa2, 0xa1, 0x7b, 0x09, 0x22, 0x29, 0xd6, 0x8b, 0x18, 0x2f, 0x06, 0xd6, 0x5d, 0x30, 0x2c, 0x31, 0xba, 0x15, 0xbc, 0x94, 0x26, 0x4d, 0x63, 0xe8, 0x74, 0x26, 0x24, 0x33, 0x4a, 0x8f, 0x7e, 0x0b, 0xcf, 0x1e, 0x3d, 0xfa, 0xe9, 0x3c, 0xca, 0xcc, 0x24, 0xa9, 0xb4, 0xf4, 0x94, 0xbc, 0xf7, 0x7e, 0xef, 0x3f, 0xef, 0xff, 0x66, 0xe0, 0x71, 0xc1, 0x58, 0x41, 0xf2, 0x49, 0x55, 0x33, 0xce, 0x52, 0xb1, 0x9a, 0x34, 0xbc, 0x16, 0x19, 0xf7, 0x55, 0x8c, 0xef, 0xe9, 0xaa, 0xdf, 0x55, 0xc7, 0x3f, 0x11, 0x58, 0x1f, 0x15, 0x81, 0x03, 0xb0, 0x56, 0x65, 0x4e, 0x96, 0xcd, 0x08, 0xb9, 0xa6, 0xe7, 0x4c, 0x2f, 0xfc, 0x3d, 0xd8, 0xd7, 0xa0, 0xff, 0x4e, 0x51, 0x97, 0x94, 0xd7, 0xdb, 0xa4, 0x6d, 0x39, 0xff, 0x00, 0xce, 0x7f, 0x69, 0x7c, 0x06, 0xe6, 0x3a, 0xdf, 0x8e, 0x90, 0x8b, 0x3c, 0x3b, 0x91, 0xbf, 0xf8, 0x39, 0x0c, 0xbf, 0x2d, 0x88, 0xc8, 0x47, 0x86, 0x8b, 0x3c, 0x67, 0xfa, 0xe0, 0x40, 0x7c, 0x26, 0xab, 0x89, 0x86, 0x5e, 0x1b, 0xaf, 0xd0, 0xf8, 0x8f, 0x01, 0x43, 0x95, 0xc4, 0x01, 0x00, 0x15, 0x84, 0xcc, 0xb5, 0x80, 0x14, 0x3d, 0x9d, 0x9e, 0x1f, 0x08, 0xdc, 0x08, 0x42, 0x14, 0x7f, 0x3d, 0x48, 0x6c, 0xda, 0x05, 0xf8, 0x02, 0xee, 0x52, 0xb1, 0x49, 0xf3, 0x7a, 0xbe, 0x3b, 0x1f, 0x5d, 0x0f, 0x12, 0x47, 0x67, 0x7b, 0xa8, 0xe1, 0x75, 0x49, 0x8b, 0x16, 0x32, 0xe5, 0xe0, 0x12, 0xd2, 0x59, 0x0d, 0x3d, 0x05, 0x48, 0x19, 0xeb, 0xc6, 0x38, 0x71, 0x91, 0x77, 0x47, 0x1e, 0x25, 0x73, 0x1a, 0x78, 0xa3, 0x54, 0x44, 0xc6, 0x5b, 0x64, 0xa8, 0xac, 0x3e, 0x3c, 0xb2, 0xc7, 0x56, 0x5e, 0x64, 0xbc, 0x77, 0x49, 0xca, 0xa6, 0xeb, 0xb5, 0x54, 0xef, 0xa1, 0xcb, 0xa8, 0x6c, 0x78, 0xef, 0x92, 0x74, 0x41, 0x68, 0xc1, 0xc9, 0xba, 0xa4, 0xcb, 0x71, 0x00, 0x76, 0x4f, 0x60, 0x1f, 0x2c, 0x25, 0xd6, 0xdd, 0xe8, 0xb1, 0xa5, 0xb7, 0xd4, 0xb3, 0x47, 0x60, 0xf7, 0x4b, 0xc4, 0xa7, 0x00, 0x37, 0xb7, 0x51, 0x34, 0x9f, 0xbd, 0x8d, 0x6e, 0x2f, 0xcf, 0x06, 0xe1, 0x0f, 0x04, 0xf7, 0x33, 0xb6, 0xd9, 0x97, 0x08, 0x1d, 0xed, 0x26, 0x96, 0x71, 0x8c, 0xbe, 0xbc, 0x28, 0x4a, 0xfe, 0x55, 0xa4, 0x7e, 0xc6, 0x36, 0x93, 0x82, 0x91, 0x05, 0x2d, 0x76, 0x4f, 0xb1, 0xe2, 0xdb, 0x2a, 0x6f, 0xda, 0x17, 0x19, 0xe8, 0x4f, 0x95, 0xfe, 0x45, 0xe8, 0x97, 0x61, 0x5e, 0xc5, 0xe1, 0x6f, 0xe3, 0xc9, 0x95, 0x16, 0x8f, 0xbb, 0xf9, 0x3e, 0xe7, 0x84, 0xbc, 0xa7, 0xec, 0x3b, 0xfd, 0x24, 0x3b, 0x53, 0x4b, 0x49, 0xbd, 0xfc, 0x17, 0x00, 0x00, 0xff, 0xff, 0xe8, 0x1b, 0x59, 0xf8, 0xe5, 0x02, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/ptypes/struct/struct.proto ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "github.com/golang/protobuf/ptypes/struct;structpb"; option java_package = "com.google.protobuf"; option java_outer_classname = "StructProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // `Struct` represents a structured data value, consisting of fields // which map to dynamically typed values. In some languages, `Struct` // might be supported by a native representation. For example, in // scripting languages like JS a struct is represented as an // object. The details of that representation are described together // with the proto support for the language. // // The JSON representation for `Struct` is JSON object. message Struct { // Unordered map of dynamically typed values. map fields = 1; } // `Value` represents a dynamically typed value which can be either // null, a number, a string, a boolean, a recursive struct value, or a // list of values. A producer of value is expected to set one of that // variants, absence of any variant indicates an error. // // The JSON representation for `Value` is JSON value. message Value { // The kind of value. oneof kind { // Represents a null value. NullValue null_value = 1; // Represents a double value. double number_value = 2; // Represents a string value. string string_value = 3; // Represents a boolean value. bool bool_value = 4; // Represents a structured value. Struct struct_value = 5; // Represents a repeated `Value`. ListValue list_value = 6; } } // `NullValue` is a singleton enumeration to represent the null value for the // `Value` type union. // // The JSON representation for `NullValue` is JSON `null`. enum NullValue { // Null value. NULL_VALUE = 0; } // `ListValue` is a wrapper around a repeated field of values. // // The JSON representation for `ListValue` is JSON array. message ListValue { // Repeated field of dynamically typed values. repeated Value values = 1; } ================================================ FILE: src/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/timestamp.proto /* Package timestamp is a generated protocol buffer package. It is generated from these files: google/protobuf/timestamp.proto It has these top-level messages: Timestamp */ package timestamp import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // A Timestamp represents a point in time independent of any time zone // or calendar, represented as seconds and fractions of seconds at // nanosecond resolution in UTC Epoch time. It is encoded using the // Proleptic Gregorian Calendar which extends the Gregorian calendar // backwards to year one. It is encoded assuming all minutes are 60 // seconds long, i.e. leap seconds are "smeared" so that no leap second // table is needed for interpretation. Range is from // 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. // By restricting to that range, we ensure that we can convert to // and from RFC 3339 date strings. // See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). // // # Examples // // Example 1: Compute Timestamp from POSIX `time()`. // // Timestamp timestamp; // timestamp.set_seconds(time(NULL)); // timestamp.set_nanos(0); // // Example 2: Compute Timestamp from POSIX `gettimeofday()`. // // struct timeval tv; // gettimeofday(&tv, NULL); // // Timestamp timestamp; // timestamp.set_seconds(tv.tv_sec); // timestamp.set_nanos(tv.tv_usec * 1000); // // Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. // // FILETIME ft; // GetSystemTimeAsFileTime(&ft); // UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; // // // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z // // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. // Timestamp timestamp; // timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); // timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); // // Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. // // long millis = System.currentTimeMillis(); // // Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) // .setNanos((int) ((millis % 1000) * 1000000)).build(); // // // Example 5: Compute Timestamp from current time in Python. // // timestamp = Timestamp() // timestamp.GetCurrentTime() // // # JSON Mapping // // In JSON format, the Timestamp type is encoded as a string in the // [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the // format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" // where {year} is always expressed using four digits while {month}, {day}, // {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional // seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), // are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone // is required, though only UTC (as indicated by "Z") is presently supported. // // For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past // 01:30 UTC on January 15, 2017. // // In JavaScript, one can convert a Date object to this format using the // standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] // method. In Python, a standard `datetime.datetime` object can be converted // to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) // with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one // can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( // http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()) // to obtain a formatter capable of generating timestamps in this format. // // type Timestamp struct { // Represents seconds of UTC time since Unix epoch // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to // 9999-12-31T23:59:59Z inclusive. Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"` // Non-negative fractions of a second at nanosecond resolution. Negative // second values with fractions must still have non-negative nanos values // that count forward in time. Must be from 0 to 999,999,999 // inclusive. Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` } func (m *Timestamp) Reset() { *m = Timestamp{} } func (m *Timestamp) String() string { return proto.CompactTextString(m) } func (*Timestamp) ProtoMessage() {} func (*Timestamp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" } func (m *Timestamp) GetSeconds() int64 { if m != nil { return m.Seconds } return 0 } func (m *Timestamp) GetNanos() int32 { if m != nil { return m.Nanos } return 0 } func init() { proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp") } func init() { proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 191 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d, 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x03, 0x0b, 0x09, 0xf1, 0x43, 0x14, 0xe8, 0xc1, 0x14, 0x28, 0x59, 0x73, 0x71, 0x86, 0xc0, 0xd4, 0x08, 0x49, 0x70, 0xb1, 0x17, 0xa7, 0x26, 0xe7, 0xe7, 0xa5, 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0xc1, 0xb8, 0x42, 0x22, 0x5c, 0xac, 0x79, 0x89, 0x79, 0xf9, 0xc5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x53, 0x1d, 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0x99, 0x4e, 0x7c, 0x70, 0x13, 0x03, 0x40, 0x42, 0x01, 0x8c, 0x51, 0xda, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xe9, 0xf9, 0x39, 0x89, 0x79, 0xe9, 0x08, 0x27, 0x16, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x23, 0x5c, 0xfa, 0x83, 0x91, 0x71, 0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xc9, 0x01, 0x50, 0xb5, 0x7a, 0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x3d, 0x49, 0x6c, 0x60, 0x43, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x77, 0x4a, 0x07, 0xf7, 0x00, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "github.com/golang/protobuf/ptypes/timestamp"; option java_package = "com.google.protobuf"; option java_outer_classname = "TimestampProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // A Timestamp represents a point in time independent of any time zone // or calendar, represented as seconds and fractions of seconds at // nanosecond resolution in UTC Epoch time. It is encoded using the // Proleptic Gregorian Calendar which extends the Gregorian calendar // backwards to year one. It is encoded assuming all minutes are 60 // seconds long, i.e. leap seconds are "smeared" so that no leap second // table is needed for interpretation. Range is from // 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. // By restricting to that range, we ensure that we can convert to // and from RFC 3339 date strings. // See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). // // # Examples // // Example 1: Compute Timestamp from POSIX `time()`. // // Timestamp timestamp; // timestamp.set_seconds(time(NULL)); // timestamp.set_nanos(0); // // Example 2: Compute Timestamp from POSIX `gettimeofday()`. // // struct timeval tv; // gettimeofday(&tv, NULL); // // Timestamp timestamp; // timestamp.set_seconds(tv.tv_sec); // timestamp.set_nanos(tv.tv_usec * 1000); // // Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. // // FILETIME ft; // GetSystemTimeAsFileTime(&ft); // UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; // // // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z // // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. // Timestamp timestamp; // timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); // timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); // // Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. // // long millis = System.currentTimeMillis(); // // Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) // .setNanos((int) ((millis % 1000) * 1000000)).build(); // // // Example 5: Compute Timestamp from current time in Python. // // timestamp = Timestamp() // timestamp.GetCurrentTime() // // # JSON Mapping // // In JSON format, the Timestamp type is encoded as a string in the // [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the // format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" // where {year} is always expressed using four digits while {month}, {day}, // {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional // seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), // are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone // is required, though only UTC (as indicated by "Z") is presently supported. // // For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past // 01:30 UTC on January 15, 2017. // // In JavaScript, one can convert a Date object to this format using the // standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] // method. In Python, a standard `datetime.datetime` object can be converted // to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) // with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one // can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( // http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()) // to obtain a formatter capable of generating timestamps in this format. // // message Timestamp { // Represents seconds of UTC time since Unix epoch // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to // 9999-12-31T23:59:59Z inclusive. int64 seconds = 1; // Non-negative fractions of a second at nanosecond resolution. Negative // second values with fractions must still have non-negative nanos values // that count forward in time. Must be from 0 to 999,999,999 // inclusive. int32 nanos = 2; } ================================================ FILE: src/github.com/golang/protobuf/ptypes/timestamp.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/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. package ptypes // This file implements operations on google.protobuf.Timestamp. import ( "errors" "fmt" "time" tspb "github.com/golang/protobuf/ptypes/timestamp" ) const ( // Seconds field of the earliest valid Timestamp. // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). minValidSeconds = -62135596800 // Seconds field just after the latest valid Timestamp. // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). maxValidSeconds = 253402300800 ) // validateTimestamp determines whether a Timestamp is valid. // A valid timestamp represents a time in the range // [0001-01-01, 10000-01-01) and has a Nanos field // in the range [0, 1e9). // // If the Timestamp is valid, validateTimestamp returns nil. // Otherwise, it returns an error that describes // the problem. // // Every valid Timestamp can be represented by a time.Time, but the converse is not true. func validateTimestamp(ts *tspb.Timestamp) error { if ts == nil { return errors.New("timestamp: nil Timestamp") } if ts.Seconds < minValidSeconds { return fmt.Errorf("timestamp: %v before 0001-01-01", ts) } if ts.Seconds >= maxValidSeconds { return fmt.Errorf("timestamp: %v after 10000-01-01", ts) } if ts.Nanos < 0 || ts.Nanos >= 1e9 { return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts) } return nil } // Timestamp converts a google.protobuf.Timestamp proto to a time.Time. // It returns an error if the argument is invalid. // // Unlike most Go functions, if Timestamp returns an error, the first return value // is not the zero time.Time. Instead, it is the value obtained from the // time.Unix function when passed the contents of the Timestamp, in the UTC // locale. This may or may not be a meaningful time; many invalid Timestamps // do map to valid time.Times. // // A nil Timestamp returns an error. The first return value in that case is // undefined. func Timestamp(ts *tspb.Timestamp) (time.Time, error) { // Don't return the zero value on error, because corresponds to a valid // timestamp. Instead return whatever time.Unix gives us. var t time.Time if ts == nil { t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp } else { t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC() } return t, validateTimestamp(ts) } // TimestampNow returns a google.protobuf.Timestamp for the current time. func TimestampNow() *tspb.Timestamp { ts, err := TimestampProto(time.Now()) if err != nil { panic("ptypes: time.Now() out of Timestamp range") } return ts } // TimestampProto converts the time.Time to a google.protobuf.Timestamp proto. // It returns an error if the resulting Timestamp is invalid. func TimestampProto(t time.Time) (*tspb.Timestamp, error) { seconds := t.Unix() nanos := int32(t.Sub(time.Unix(seconds, 0))) ts := &tspb.Timestamp{ Seconds: seconds, Nanos: nanos, } if err := validateTimestamp(ts); err != nil { return nil, err } return ts, nil } // TimestampString returns the RFC 3339 string for valid Timestamps. For invalid // Timestamps, it returns an error message in parentheses. func TimestampString(ts *tspb.Timestamp) string { t, err := Timestamp(ts) if err != nil { return fmt.Sprintf("(%v)", err) } return t.Format(time.RFC3339Nano) } ================================================ FILE: src/github.com/golang/protobuf/ptypes/timestamp_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/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. package ptypes import ( "math" "testing" "time" "github.com/golang/protobuf/proto" tspb "github.com/golang/protobuf/ptypes/timestamp" ) var tests = []struct { ts *tspb.Timestamp valid bool t time.Time }{ // The timestamp representing the Unix epoch date. {&tspb.Timestamp{Seconds: 0, Nanos: 0}, true, utcDate(1970, 1, 1)}, // The smallest representable timestamp. {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: math.MinInt32}, false, time.Unix(math.MinInt64, math.MinInt32).UTC()}, // The smallest representable timestamp with non-negative nanos. {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: 0}, false, time.Unix(math.MinInt64, 0).UTC()}, // The earliest valid timestamp. {&tspb.Timestamp{Seconds: minValidSeconds, Nanos: 0}, true, utcDate(1, 1, 1)}, //"0001-01-01T00:00:00Z"}, // The largest representable timestamp. {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: math.MaxInt32}, false, time.Unix(math.MaxInt64, math.MaxInt32).UTC()}, // The largest representable timestamp with nanos in range. {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: 1e9 - 1}, false, time.Unix(math.MaxInt64, 1e9-1).UTC()}, // The largest valid timestamp. {&tspb.Timestamp{Seconds: maxValidSeconds - 1, Nanos: 1e9 - 1}, true, time.Date(9999, 12, 31, 23, 59, 59, 1e9-1, time.UTC)}, // The smallest invalid timestamp that is larger than the valid range. {&tspb.Timestamp{Seconds: maxValidSeconds, Nanos: 0}, false, time.Unix(maxValidSeconds, 0).UTC()}, // A date before the epoch. {&tspb.Timestamp{Seconds: -281836800, Nanos: 0}, true, utcDate(1961, 1, 26)}, // A date after the epoch. {&tspb.Timestamp{Seconds: 1296000000, Nanos: 0}, true, utcDate(2011, 1, 26)}, // A date after the epoch, in the middle of the day. {&tspb.Timestamp{Seconds: 1296012345, Nanos: 940483}, true, time.Date(2011, 1, 26, 3, 25, 45, 940483, time.UTC)}, } func TestValidateTimestamp(t *testing.T) { for _, s := range tests { got := validateTimestamp(s.ts) if (got == nil) != s.valid { t.Errorf("validateTimestamp(%v) = %v, want %v", s.ts, got, s.valid) } } } func TestTimestamp(t *testing.T) { for _, s := range tests { got, err := Timestamp(s.ts) if (err == nil) != s.valid { t.Errorf("Timestamp(%v) error = %v, but valid = %t", s.ts, err, s.valid) } else if s.valid && got != s.t { t.Errorf("Timestamp(%v) = %v, want %v", s.ts, got, s.t) } } // Special case: a nil Timestamp is an error, but returns the 0 Unix time. got, err := Timestamp(nil) want := time.Unix(0, 0).UTC() if got != want { t.Errorf("Timestamp(nil) = %v, want %v", got, want) } if err == nil { t.Errorf("Timestamp(nil) error = nil, expected error") } } func TestTimestampProto(t *testing.T) { for _, s := range tests { got, err := TimestampProto(s.t) if (err == nil) != s.valid { t.Errorf("TimestampProto(%v) error = %v, but valid = %t", s.t, err, s.valid) } else if s.valid && !proto.Equal(got, s.ts) { t.Errorf("TimestampProto(%v) = %v, want %v", s.t, got, s.ts) } } // No corresponding special case here: no time.Time results in a nil Timestamp. } func TestTimestampString(t *testing.T) { for _, test := range []struct { ts *tspb.Timestamp want string }{ // Not much testing needed because presumably time.Format is // well-tested. {&tspb.Timestamp{Seconds: 0, Nanos: 0}, "1970-01-01T00:00:00Z"}, {&tspb.Timestamp{Seconds: minValidSeconds - 1, Nanos: 0}, "(timestamp: seconds:-62135596801 before 0001-01-01)"}, } { got := TimestampString(test.ts) if got != test.want { t.Errorf("TimestampString(%v) = %q, want %q", test.ts, got, test.want) } } } func utcDate(year, month, day int) time.Time { return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC) } func TestTimestampNow(t *testing.T) { // Bracket the expected time. before := time.Now() ts := TimestampNow() after := time.Now() tm, err := Timestamp(ts) if err != nil { t.Errorf("between %v and %v\nTimestampNow() = %v\nwhich is invalid (%v)", before, after, ts, err) } if tm.Before(before) || tm.After(after) { t.Errorf("between %v and %v\nTimestamp(TimestampNow()) = %v", before, after, tm) } } ================================================ FILE: src/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go ================================================ // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/wrappers.proto /* Package wrappers is a generated protocol buffer package. It is generated from these files: google/protobuf/wrappers.proto It has these top-level messages: DoubleValue FloatValue Int64Value UInt64Value Int32Value UInt32Value BoolValue StringValue BytesValue */ package wrappers import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // Wrapper message for `double`. // // The JSON representation for `DoubleValue` is JSON number. type DoubleValue struct { // The double value. Value float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"` } func (m *DoubleValue) Reset() { *m = DoubleValue{} } func (m *DoubleValue) String() string { return proto.CompactTextString(m) } func (*DoubleValue) ProtoMessage() {} func (*DoubleValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } func (*DoubleValue) XXX_WellKnownType() string { return "DoubleValue" } func (m *DoubleValue) GetValue() float64 { if m != nil { return m.Value } return 0 } // Wrapper message for `float`. // // The JSON representation for `FloatValue` is JSON number. type FloatValue struct { // The float value. Value float32 `protobuf:"fixed32,1,opt,name=value" json:"value,omitempty"` } func (m *FloatValue) Reset() { *m = FloatValue{} } func (m *FloatValue) String() string { return proto.CompactTextString(m) } func (*FloatValue) ProtoMessage() {} func (*FloatValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } func (*FloatValue) XXX_WellKnownType() string { return "FloatValue" } func (m *FloatValue) GetValue() float32 { if m != nil { return m.Value } return 0 } // Wrapper message for `int64`. // // The JSON representation for `Int64Value` is JSON string. type Int64Value struct { // The int64 value. Value int64 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` } func (m *Int64Value) Reset() { *m = Int64Value{} } func (m *Int64Value) String() string { return proto.CompactTextString(m) } func (*Int64Value) ProtoMessage() {} func (*Int64Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (*Int64Value) XXX_WellKnownType() string { return "Int64Value" } func (m *Int64Value) GetValue() int64 { if m != nil { return m.Value } return 0 } // Wrapper message for `uint64`. // // The JSON representation for `UInt64Value` is JSON string. type UInt64Value struct { // The uint64 value. Value uint64 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` } func (m *UInt64Value) Reset() { *m = UInt64Value{} } func (m *UInt64Value) String() string { return proto.CompactTextString(m) } func (*UInt64Value) ProtoMessage() {} func (*UInt64Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } func (*UInt64Value) XXX_WellKnownType() string { return "UInt64Value" } func (m *UInt64Value) GetValue() uint64 { if m != nil { return m.Value } return 0 } // Wrapper message for `int32`. // // The JSON representation for `Int32Value` is JSON number. type Int32Value struct { // The int32 value. Value int32 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` } func (m *Int32Value) Reset() { *m = Int32Value{} } func (m *Int32Value) String() string { return proto.CompactTextString(m) } func (*Int32Value) ProtoMessage() {} func (*Int32Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } func (*Int32Value) XXX_WellKnownType() string { return "Int32Value" } func (m *Int32Value) GetValue() int32 { if m != nil { return m.Value } return 0 } // Wrapper message for `uint32`. // // The JSON representation for `UInt32Value` is JSON number. type UInt32Value struct { // The uint32 value. Value uint32 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` } func (m *UInt32Value) Reset() { *m = UInt32Value{} } func (m *UInt32Value) String() string { return proto.CompactTextString(m) } func (*UInt32Value) ProtoMessage() {} func (*UInt32Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } func (*UInt32Value) XXX_WellKnownType() string { return "UInt32Value" } func (m *UInt32Value) GetValue() uint32 { if m != nil { return m.Value } return 0 } // Wrapper message for `bool`. // // The JSON representation for `BoolValue` is JSON `true` and `false`. type BoolValue struct { // The bool value. Value bool `protobuf:"varint,1,opt,name=value" json:"value,omitempty"` } func (m *BoolValue) Reset() { *m = BoolValue{} } func (m *BoolValue) String() string { return proto.CompactTextString(m) } func (*BoolValue) ProtoMessage() {} func (*BoolValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } func (*BoolValue) XXX_WellKnownType() string { return "BoolValue" } func (m *BoolValue) GetValue() bool { if m != nil { return m.Value } return false } // Wrapper message for `string`. // // The JSON representation for `StringValue` is JSON string. type StringValue struct { // The string value. Value string `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"` } func (m *StringValue) Reset() { *m = StringValue{} } func (m *StringValue) String() string { return proto.CompactTextString(m) } func (*StringValue) ProtoMessage() {} func (*StringValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } func (*StringValue) XXX_WellKnownType() string { return "StringValue" } func (m *StringValue) GetValue() string { if m != nil { return m.Value } return "" } // Wrapper message for `bytes`. // // The JSON representation for `BytesValue` is JSON string. type BytesValue struct { // The bytes value. Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` } func (m *BytesValue) Reset() { *m = BytesValue{} } func (m *BytesValue) String() string { return proto.CompactTextString(m) } func (*BytesValue) ProtoMessage() {} func (*BytesValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } func (*BytesValue) XXX_WellKnownType() string { return "BytesValue" } func (m *BytesValue) GetValue() []byte { if m != nil { return m.Value } return nil } func init() { proto.RegisterType((*DoubleValue)(nil), "google.protobuf.DoubleValue") proto.RegisterType((*FloatValue)(nil), "google.protobuf.FloatValue") proto.RegisterType((*Int64Value)(nil), "google.protobuf.Int64Value") proto.RegisterType((*UInt64Value)(nil), "google.protobuf.UInt64Value") proto.RegisterType((*Int32Value)(nil), "google.protobuf.Int32Value") proto.RegisterType((*UInt32Value)(nil), "google.protobuf.UInt32Value") proto.RegisterType((*BoolValue)(nil), "google.protobuf.BoolValue") proto.RegisterType((*StringValue)(nil), "google.protobuf.StringValue") proto.RegisterType((*BytesValue)(nil), "google.protobuf.BytesValue") } func init() { proto.RegisterFile("google/protobuf/wrappers.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 259 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0x2f, 0x4a, 0x2c, 0x28, 0x48, 0x2d, 0x2a, 0xd6, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0xca, 0x5c, 0xdc, 0x2e, 0xf9, 0xa5, 0x49, 0x39, 0xa9, 0x61, 0x89, 0x39, 0xa5, 0xa9, 0x42, 0x22, 0x5c, 0xac, 0x65, 0x20, 0x86, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x63, 0x10, 0x84, 0xa3, 0xa4, 0xc4, 0xc5, 0xe5, 0x96, 0x93, 0x9f, 0x58, 0x82, 0x45, 0x0d, 0x13, 0x92, 0x1a, 0xcf, 0xbc, 0x12, 0x33, 0x13, 0x2c, 0x6a, 0x98, 0x61, 0x6a, 0x94, 0xb9, 0xb8, 0x43, 0x71, 0x29, 0x62, 0x41, 0x35, 0xc8, 0xd8, 0x08, 0x8b, 0x1a, 0x56, 0x34, 0x83, 0xb0, 0x2a, 0xe2, 0x85, 0x29, 0x52, 0xe4, 0xe2, 0x74, 0xca, 0xcf, 0xcf, 0xc1, 0xa2, 0x84, 0x03, 0xc9, 0x9c, 0xe0, 0x92, 0xa2, 0xcc, 0xbc, 0x74, 0x2c, 0x8a, 0x38, 0x91, 0x1c, 0xe4, 0x54, 0x59, 0x92, 0x5a, 0x8c, 0x45, 0x0d, 0x0f, 0x54, 0x8d, 0x53, 0x0d, 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x5a, 0xe8, 0x3a, 0xf1, 0x86, 0x43, 0x83, 0x3f, 0x00, 0x24, 0x12, 0xc0, 0x18, 0xa5, 0x95, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x9f, 0x9e, 0x9f, 0x93, 0x98, 0x97, 0x8e, 0x88, 0xaa, 0x82, 0x92, 0xca, 0x82, 0xd4, 0x62, 0x78, 0x8c, 0xfd, 0x60, 0x64, 0x5c, 0xc4, 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, 0x00, 0x54, 0xa9, 0x5e, 0x78, 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, 0x12, 0x1b, 0xd8, 0x0c, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x19, 0x6c, 0xb9, 0xb8, 0xfe, 0x01, 0x00, 0x00, } ================================================ FILE: src/github.com/golang/protobuf/ptypes/wrappers/wrappers.proto ================================================ // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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. // Wrappers for primitive (non-message) types. These types are useful // for embedding primitives in the `google.protobuf.Any` type and for places // where we need to distinguish between the absence of a primitive // typed field and its default value. syntax = "proto3"; package google.protobuf; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; option go_package = "github.com/golang/protobuf/ptypes/wrappers"; option java_package = "com.google.protobuf"; option java_outer_classname = "WrappersProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; // Wrapper message for `double`. // // The JSON representation for `DoubleValue` is JSON number. message DoubleValue { // The double value. double value = 1; } // Wrapper message for `float`. // // The JSON representation for `FloatValue` is JSON number. message FloatValue { // The float value. float value = 1; } // Wrapper message for `int64`. // // The JSON representation for `Int64Value` is JSON string. message Int64Value { // The int64 value. int64 value = 1; } // Wrapper message for `uint64`. // // The JSON representation for `UInt64Value` is JSON string. message UInt64Value { // The uint64 value. uint64 value = 1; } // Wrapper message for `int32`. // // The JSON representation for `Int32Value` is JSON number. message Int32Value { // The int32 value. int32 value = 1; } // Wrapper message for `uint32`. // // The JSON representation for `UInt32Value` is JSON number. message UInt32Value { // The uint32 value. uint32 value = 1; } // Wrapper message for `bool`. // // The JSON representation for `BoolValue` is JSON `true` and `false`. message BoolValue { // The bool value. bool value = 1; } // Wrapper message for `string`. // // The JSON representation for `StringValue` is JSON string. message StringValue { // The string value. string value = 1; } // Wrapper message for `bytes`. // // The JSON representation for `BytesValue` is JSON string. message BytesValue { // The bytes value. bytes value = 1; } ================================================ FILE: src/github.com/gorilla/websocket/.gitignore ================================================ # Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe .idea/ *.iml ================================================ FILE: src/github.com/gorilla/websocket/.travis.yml ================================================ language: go sudo: false matrix: include: - go: 1.4 - go: 1.5.x - go: 1.6.x - go: 1.7.x - go: 1.8.x - go: 1.9.x - go: 1.10.x - go: tip allow_failures: - go: tip script: - go get -t -v ./... - diff -u <(echo -n) <(gofmt -d .) - go vet $(go list ./... | grep -v /vendor/) - go test -v -race ./... ================================================ FILE: src/github.com/gorilla/websocket/AUTHORS ================================================ # This is the official list of Gorilla WebSocket authors for copyright # purposes. # # Please keep the list sorted. Gary Burd Joachim Bauch ================================================ FILE: src/github.com/gorilla/websocket/LICENSE ================================================ Copyright (c) 2013 The Gorilla WebSocket Authors. All rights reserved. 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. 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 HOLDER 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. ================================================ FILE: src/github.com/gorilla/websocket/README.md ================================================ # Gorilla WebSocket Gorilla WebSocket is a [Go](http://golang.org/) implementation of the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. [![Build Status](https://travis-ci.org/gorilla/websocket.svg?branch=master)](https://travis-ci.org/gorilla/websocket) [![GoDoc](https://godoc.org/github.com/gorilla/websocket?status.svg)](https://godoc.org/github.com/gorilla/websocket) ### Documentation * [API Reference](http://godoc.org/github.com/gorilla/websocket) * [Chat example](https://github.com/gorilla/websocket/tree/master/examples/chat) * [Command example](https://github.com/gorilla/websocket/tree/master/examples/command) * [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo) * [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch) ### Status The Gorilla WebSocket package provides a complete and tested implementation of the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. The package API is stable. ### Installation go get github.com/gorilla/websocket ### Protocol Compliance The Gorilla WebSocket package passes the server tests in the [Autobahn Test Suite](http://autobahn.ws/testsuite) using the application in the [examples/autobahn subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn). ### Gorilla WebSocket compared with other packages
github.com/gorilla golang.org/x/net
RFC 6455 Features
Passes Autobahn Test SuiteYesNo
Receive fragmented messageYesNo, see note 1
Send close messageYesNo
Send pings and receive pongsYesNo
Get the type of a received data messageYesYes, see note 2
Other Features
Compression ExtensionsExperimentalNo
Read message using io.ReaderYesNo, see note 3
Write message using io.WriteCloserYesNo, see note 3
Notes: 1. Large messages are fragmented in [Chrome's new WebSocket implementation](http://www.ietf.org/mail-archive/web/hybi/current/msg10503.html). 2. The application can get the type of a received data message by implementing a [Codec marshal](http://godoc.org/golang.org/x/net/websocket#Codec.Marshal) function. 3. The go.net io.Reader and io.Writer operate across WebSocket frame boundaries. Read returns when the input buffer is full or a frame boundary is encountered. Each call to Write sends a single frame message. The Gorilla io.Reader and io.WriteCloser operate on a single WebSocket message. ================================================ FILE: src/github.com/gorilla/websocket/client.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bytes" "crypto/tls" "errors" "io" "io/ioutil" "net" "net/http" "net/url" "strings" "time" ) // ErrBadHandshake is returned when the server response to opening handshake is // invalid. var ErrBadHandshake = errors.New("websocket: bad handshake") var errInvalidCompression = errors.New("websocket: invalid compression negotiation") // NewClient creates a new client connection using the given net connection. // The URL u specifies the host and request URI. Use requestHeader to specify // the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies // (Cookie). Use the response.Header to get the selected subprotocol // (Sec-WebSocket-Protocol) and cookies (Set-Cookie). // // If the WebSocket handshake fails, ErrBadHandshake is returned along with a // non-nil *http.Response so that callers can handle redirects, authentication, // etc. // // Deprecated: Use Dialer instead. func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) { d := Dialer{ ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize, NetDial: func(net, addr string) (net.Conn, error) { return netConn, nil }, } return d.Dial(u.String(), requestHeader) } // A Dialer contains options for connecting to WebSocket server. type Dialer struct { // NetDial specifies the dial function for creating TCP connections. If // NetDial is nil, net.Dial is used. NetDial func(network, addr string) (net.Conn, error) // Proxy specifies a function to return a proxy for a given // Request. If the function returns a non-nil error, the // request is aborted with the provided error. // If Proxy is nil or returns a nil *URL, no proxy is used. Proxy func(*http.Request) (*url.URL, error) // TLSClientConfig specifies the TLS configuration to use with tls.Client. // If nil, the default configuration is used. TLSClientConfig *tls.Config // HandshakeTimeout specifies the duration for the handshake to complete. HandshakeTimeout time.Duration // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer // size is zero, then a useful default size is used. The I/O buffer sizes // do not limit the size of the messages that can be sent or received. ReadBufferSize, WriteBufferSize int // Subprotocols specifies the client's requested subprotocols. Subprotocols []string // EnableCompression specifies if the client should attempt to negotiate // per message compression (RFC 7692). Setting this value to true does not // guarantee that compression will be supported. Currently only "no context // takeover" modes are supported. EnableCompression bool // Jar specifies the cookie jar. // If Jar is nil, cookies are not sent in requests and ignored // in responses. Jar http.CookieJar } var errMalformedURL = errors.New("malformed ws or wss URL") func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) { hostPort = u.Host hostNoPort = u.Host if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") { hostNoPort = hostNoPort[:i] } else { switch u.Scheme { case "wss": hostPort += ":443" case "https": hostPort += ":443" default: hostPort += ":80" } } return hostPort, hostNoPort } // DefaultDialer is a dialer with all fields set to the default values. var DefaultDialer = &Dialer{ Proxy: http.ProxyFromEnvironment, HandshakeTimeout: 45 * time.Second, } // nilDialer is dialer to use when receiver is nil. var nilDialer Dialer = *DefaultDialer // Dial creates a new client connection. Use requestHeader to specify the // origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie). // Use the response.Header to get the selected subprotocol // (Sec-WebSocket-Protocol) and cookies (Set-Cookie). // // If the WebSocket handshake fails, ErrBadHandshake is returned along with a // non-nil *http.Response so that callers can handle redirects, authentication, // etcetera. The response body may not contain the entire response and does not // need to be closed by the application. func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) { if d == nil { d = &nilDialer } challengeKey, err := generateChallengeKey() if err != nil { return nil, nil, err } u, err := url.Parse(urlStr) if err != nil { return nil, nil, err } switch u.Scheme { case "ws": u.Scheme = "http" case "wss": u.Scheme = "https" default: return nil, nil, errMalformedURL } if u.User != nil { // User name and password are not allowed in websocket URIs. return nil, nil, errMalformedURL } req := &http.Request{ Method: "GET", URL: u, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: make(http.Header), Host: u.Host, } // Set the cookies present in the cookie jar of the dialer if d.Jar != nil { for _, cookie := range d.Jar.Cookies(u) { req.AddCookie(cookie) } } // Set the request headers using the capitalization for names and values in // RFC examples. Although the capitalization shouldn't matter, there are // servers that depend on it. The Header.Set method is not used because the // method canonicalizes the header names. req.Header["Upgrade"] = []string{"websocket"} req.Header["Connection"] = []string{"Upgrade"} req.Header["Sec-WebSocket-Key"] = []string{challengeKey} req.Header["Sec-WebSocket-Version"] = []string{"13"} if len(d.Subprotocols) > 0 { req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")} } for k, vs := range requestHeader { switch { case k == "Host": if len(vs) > 0 { req.Host = vs[0] } case k == "Upgrade" || k == "Connection" || k == "Sec-Websocket-Key" || k == "Sec-Websocket-Version" || k == "Sec-Websocket-Extensions" || (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0): return nil, nil, errors.New("websocket: duplicate header not allowed: " + k) case k == "Sec-Websocket-Protocol": req.Header["Sec-WebSocket-Protocol"] = vs default: req.Header[k] = vs } } if d.EnableCompression { req.Header.Set("Sec-Websocket-Extensions", "permessage-deflate; server_no_context_takeover; client_no_context_takeover") } var deadline time.Time if d.HandshakeTimeout != 0 { deadline = time.Now().Add(d.HandshakeTimeout) } // Get network dial function. netDial := d.NetDial if netDial == nil { netDialer := &net.Dialer{Deadline: deadline} netDial = netDialer.Dial } // If needed, wrap the dial function to set the connection deadline. if !deadline.Equal(time.Time{}) { forwardDial := netDial netDial = func(network, addr string) (net.Conn, error) { c, err := forwardDial(network, addr) if err != nil { return nil, err } err = c.SetDeadline(deadline) if err != nil { c.Close() return nil, err } return c, nil } } // If needed, wrap the dial function to connect through a proxy. if d.Proxy != nil { proxyURL, err := d.Proxy(req) if err != nil { return nil, nil, err } if proxyURL != nil { dialer, err := proxy_FromURL(proxyURL, netDialerFunc(netDial)) if err != nil { return nil, nil, err } netDial = dialer.Dial } } hostPort, hostNoPort := hostPortNoPort(u) netConn, err := netDial("tcp", hostPort) if err != nil { return nil, nil, err } defer func() { if netConn != nil { netConn.Close() } }() if u.Scheme == "https" { cfg := cloneTLSConfig(d.TLSClientConfig) if cfg.ServerName == "" { cfg.ServerName = hostNoPort } tlsConn := tls.Client(netConn, cfg) netConn = tlsConn if err := tlsConn.Handshake(); err != nil { return nil, nil, err } if !cfg.InsecureSkipVerify { if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil { return nil, nil, err } } } conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize) if err := req.Write(netConn); err != nil { return nil, nil, err } resp, err := http.ReadResponse(conn.br, req) if err != nil { return nil, nil, err } if d.Jar != nil { if rc := resp.Cookies(); len(rc) > 0 { d.Jar.SetCookies(u, rc) } } if resp.StatusCode != 101 || !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") || !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") || resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) { // Before closing the network connection on return from this // function, slurp up some of the response to aid application // debugging. buf := make([]byte, 1024) n, _ := io.ReadFull(resp.Body, buf) resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n])) return nil, resp, ErrBadHandshake } for _, ext := range parseExtensions(resp.Header) { if ext[""] != "permessage-deflate" { continue } _, snct := ext["server_no_context_takeover"] _, cnct := ext["client_no_context_takeover"] if !snct || !cnct { return nil, resp, errInvalidCompression } conn.newCompressionWriter = compressNoContextTakeover conn.newDecompressionReader = decompressNoContextTakeover break } resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol") netConn.SetDeadline(time.Time{}) netConn = nil // to avoid close in defer. return conn, resp, nil } ================================================ FILE: src/github.com/gorilla/websocket/client_clone.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.8 package websocket import "crypto/tls" func cloneTLSConfig(cfg *tls.Config) *tls.Config { if cfg == nil { return &tls.Config{} } return cfg.Clone() } ================================================ FILE: src/github.com/gorilla/websocket/client_clone_legacy.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.8 package websocket import "crypto/tls" // cloneTLSConfig clones all public fields except the fields // SessionTicketsDisabled and SessionTicketKey. This avoids copying the // sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a // config in active use. func cloneTLSConfig(cfg *tls.Config) *tls.Config { if cfg == nil { return &tls.Config{} } return &tls.Config{ Rand: cfg.Rand, Time: cfg.Time, Certificates: cfg.Certificates, NameToCertificate: cfg.NameToCertificate, GetCertificate: cfg.GetCertificate, RootCAs: cfg.RootCAs, NextProtos: cfg.NextProtos, ServerName: cfg.ServerName, ClientAuth: cfg.ClientAuth, ClientCAs: cfg.ClientCAs, InsecureSkipVerify: cfg.InsecureSkipVerify, CipherSuites: cfg.CipherSuites, PreferServerCipherSuites: cfg.PreferServerCipherSuites, ClientSessionCache: cfg.ClientSessionCache, MinVersion: cfg.MinVersion, MaxVersion: cfg.MaxVersion, CurvePreferences: cfg.CurvePreferences, } } ================================================ FILE: src/github.com/gorilla/websocket/client_server_test.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bytes" "crypto/tls" "crypto/x509" "encoding/base64" "encoding/binary" "io" "io/ioutil" "net" "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "reflect" "strings" "testing" "time" ) var cstUpgrader = Upgrader{ Subprotocols: []string{"p0", "p1"}, ReadBufferSize: 1024, WriteBufferSize: 1024, EnableCompression: true, Error: func(w http.ResponseWriter, r *http.Request, status int, reason error) { http.Error(w, reason.Error(), status) }, } var cstDialer = Dialer{ Subprotocols: []string{"p1", "p2"}, ReadBufferSize: 1024, WriteBufferSize: 1024, HandshakeTimeout: 30 * time.Second, } type cstHandler struct{ *testing.T } type cstServer struct { *httptest.Server URL string } const ( cstPath = "/a/b" cstRawQuery = "x=y" cstRequestURI = cstPath + "?" + cstRawQuery ) func newServer(t *testing.T) *cstServer { var s cstServer s.Server = httptest.NewServer(cstHandler{t}) s.Server.URL += cstRequestURI s.URL = makeWsProto(s.Server.URL) return &s } func newTLSServer(t *testing.T) *cstServer { var s cstServer s.Server = httptest.NewTLSServer(cstHandler{t}) s.Server.URL += cstRequestURI s.URL = makeWsProto(s.Server.URL) return &s } func (t cstHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.URL.Path != cstPath { t.Logf("path=%v, want %v", r.URL.Path, cstPath) http.Error(w, "bad path", http.StatusBadRequest) return } if r.URL.RawQuery != cstRawQuery { t.Logf("query=%v, want %v", r.URL.RawQuery, cstRawQuery) http.Error(w, "bad path", http.StatusBadRequest) return } subprotos := Subprotocols(r) if !reflect.DeepEqual(subprotos, cstDialer.Subprotocols) { t.Logf("subprotols=%v, want %v", subprotos, cstDialer.Subprotocols) http.Error(w, "bad protocol", http.StatusBadRequest) return } ws, err := cstUpgrader.Upgrade(w, r, http.Header{"Set-Cookie": {"sessionID=1234"}}) if err != nil { t.Logf("Upgrade: %v", err) return } defer ws.Close() if ws.Subprotocol() != "p1" { t.Logf("Subprotocol() = %s, want p1", ws.Subprotocol()) ws.Close() return } op, rd, err := ws.NextReader() if err != nil { t.Logf("NextReader: %v", err) return } wr, err := ws.NextWriter(op) if err != nil { t.Logf("NextWriter: %v", err) return } if _, err = io.Copy(wr, rd); err != nil { t.Logf("NextWriter: %v", err) return } if err := wr.Close(); err != nil { t.Logf("Close: %v", err) return } } func makeWsProto(s string) string { return "ws" + strings.TrimPrefix(s, "http") } func sendRecv(t *testing.T, ws *Conn) { const message = "Hello World!" if err := ws.SetWriteDeadline(time.Now().Add(time.Second)); err != nil { t.Fatalf("SetWriteDeadline: %v", err) } if err := ws.WriteMessage(TextMessage, []byte(message)); err != nil { t.Fatalf("WriteMessage: %v", err) } if err := ws.SetReadDeadline(time.Now().Add(time.Second)); err != nil { t.Fatalf("SetReadDeadline: %v", err) } _, p, err := ws.ReadMessage() if err != nil { t.Fatalf("ReadMessage: %v", err) } if string(p) != message { t.Fatalf("message=%s, want %s", p, message) } } func TestProxyDial(t *testing.T) { s := newServer(t) defer s.Close() surl, _ := url.Parse(s.Server.URL) cstDialer := cstDialer // make local copy for modification on next line. cstDialer.Proxy = http.ProxyURL(surl) connect := false origHandler := s.Server.Config.Handler // Capture the request Host header. s.Server.Config.Handler = http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { if r.Method == "CONNECT" { connect = true w.WriteHeader(http.StatusOK) return } if !connect { t.Log("connect not received") http.Error(w, "connect not received", http.StatusMethodNotAllowed) return } origHandler.ServeHTTP(w, r) }) ws, _, err := cstDialer.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) } func TestProxyAuthorizationDial(t *testing.T) { s := newServer(t) defer s.Close() surl, _ := url.Parse(s.Server.URL) surl.User = url.UserPassword("username", "password") cstDialer := cstDialer // make local copy for modification on next line. cstDialer.Proxy = http.ProxyURL(surl) connect := false origHandler := s.Server.Config.Handler // Capture the request Host header. s.Server.Config.Handler = http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { proxyAuth := r.Header.Get("Proxy-Authorization") expectedProxyAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte("username:password")) if r.Method == "CONNECT" && proxyAuth == expectedProxyAuth { connect = true w.WriteHeader(http.StatusOK) return } if !connect { t.Log("connect with proxy authorization not received") http.Error(w, "connect with proxy authorization not received", http.StatusMethodNotAllowed) return } origHandler.ServeHTTP(w, r) }) ws, _, err := cstDialer.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) } func TestDial(t *testing.T) { s := newServer(t) defer s.Close() ws, _, err := cstDialer.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) } func TestDialCookieJar(t *testing.T) { s := newServer(t) defer s.Close() jar, _ := cookiejar.New(nil) d := cstDialer d.Jar = jar u, _ := url.Parse(s.URL) switch u.Scheme { case "ws": u.Scheme = "http" case "wss": u.Scheme = "https" } cookies := []*http.Cookie{{Name: "gorilla", Value: "ws", Path: "/"}} d.Jar.SetCookies(u, cookies) ws, _, err := d.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() var gorilla string var sessionID string for _, c := range d.Jar.Cookies(u) { if c.Name == "gorilla" { gorilla = c.Value } if c.Name == "sessionID" { sessionID = c.Value } } if gorilla != "ws" { t.Error("Cookie not present in jar.") } if sessionID != "1234" { t.Error("Set-Cookie not received from the server.") } sendRecv(t, ws) } func TestDialTLS(t *testing.T) { s := newTLSServer(t) defer s.Close() certs := x509.NewCertPool() for _, c := range s.TLS.Certificates { roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1]) if err != nil { t.Fatalf("error parsing server's root cert: %v", err) } for _, root := range roots { certs.AddCert(root) } } d := cstDialer d.TLSClientConfig = &tls.Config{RootCAs: certs} ws, _, err := d.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) } func xTestDialTLSBadCert(t *testing.T) { // This test is deactivated because of noisy logging from the net/http package. s := newTLSServer(t) defer s.Close() ws, _, err := cstDialer.Dial(s.URL, nil) if err == nil { ws.Close() t.Fatalf("Dial: nil") } } func TestDialTLSNoVerify(t *testing.T) { s := newTLSServer(t) defer s.Close() d := cstDialer d.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} ws, _, err := d.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) } func TestDialTimeout(t *testing.T) { s := newServer(t) defer s.Close() d := cstDialer d.HandshakeTimeout = -1 ws, _, err := d.Dial(s.URL, nil) if err == nil { ws.Close() t.Fatalf("Dial: nil") } } func TestDialBadScheme(t *testing.T) { s := newServer(t) defer s.Close() ws, _, err := cstDialer.Dial(s.Server.URL, nil) if err == nil { ws.Close() t.Fatalf("Dial: nil") } } func TestDialBadOrigin(t *testing.T) { s := newServer(t) defer s.Close() ws, resp, err := cstDialer.Dial(s.URL, http.Header{"Origin": {"bad"}}) if err == nil { ws.Close() t.Fatalf("Dial: nil") } if resp == nil { t.Fatalf("resp=nil, err=%v", err) } if resp.StatusCode != http.StatusForbidden { t.Fatalf("status=%d, want %d", resp.StatusCode, http.StatusForbidden) } } func TestDialBadHeader(t *testing.T) { s := newServer(t) defer s.Close() for _, k := range []string{"Upgrade", "Connection", "Sec-Websocket-Key", "Sec-Websocket-Version", "Sec-Websocket-Protocol"} { h := http.Header{} h.Set(k, "bad") ws, _, err := cstDialer.Dial(s.URL, http.Header{"Origin": {"bad"}}) if err == nil { ws.Close() t.Errorf("Dial with header %s returned nil", k) } } } func TestBadMethod(t *testing.T) { s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ws, err := cstUpgrader.Upgrade(w, r, nil) if err == nil { t.Errorf("handshake succeeded, expect fail") ws.Close() } })) defer s.Close() req, err := http.NewRequest("POST", s.URL, strings.NewReader("")) if err != nil { t.Fatalf("NewRequest returned error %v", err) } req.Header.Set("Connection", "upgrade") req.Header.Set("Upgrade", "websocket") req.Header.Set("Sec-Websocket-Version", "13") resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("Do returned error %v", err) } resp.Body.Close() if resp.StatusCode != http.StatusMethodNotAllowed { t.Errorf("Status = %d, want %d", resp.StatusCode, http.StatusMethodNotAllowed) } } func TestHandshake(t *testing.T) { s := newServer(t) defer s.Close() ws, resp, err := cstDialer.Dial(s.URL, http.Header{"Origin": {s.URL}}) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() var sessionID string for _, c := range resp.Cookies() { if c.Name == "sessionID" { sessionID = c.Value } } if sessionID != "1234" { t.Error("Set-Cookie not received from the server.") } if ws.Subprotocol() != "p1" { t.Errorf("ws.Subprotocol() = %s, want p1", ws.Subprotocol()) } sendRecv(t, ws) } func TestRespOnBadHandshake(t *testing.T) { const expectedStatus = http.StatusGone const expectedBody = "This is the response body." s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(expectedStatus) io.WriteString(w, expectedBody) })) defer s.Close() ws, resp, err := cstDialer.Dial(makeWsProto(s.URL), nil) if err == nil { ws.Close() t.Fatalf("Dial: nil") } if resp == nil { t.Fatalf("resp=nil, err=%v", err) } if resp.StatusCode != expectedStatus { t.Errorf("resp.StatusCode=%d, want %d", resp.StatusCode, expectedStatus) } p, err := ioutil.ReadAll(resp.Body) if err != nil { t.Fatalf("ReadFull(resp.Body) returned error %v", err) } if string(p) != expectedBody { t.Errorf("resp.Body=%s, want %s", p, expectedBody) } } // TestHostHeader confirms that the host header provided in the call to Dial is // sent to the server. func TestHostHeader(t *testing.T) { s := newServer(t) defer s.Close() specifiedHost := make(chan string, 1) origHandler := s.Server.Config.Handler // Capture the request Host header. s.Server.Config.Handler = http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { specifiedHost <- r.Host origHandler.ServeHTTP(w, r) }) ws, _, err := cstDialer.Dial(s.URL, http.Header{"Host": {"testhost"}}) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() if gotHost := <-specifiedHost; gotHost != "testhost" { t.Fatalf("gotHost = %q, want \"testhost\"", gotHost) } sendRecv(t, ws) } func TestDialCompression(t *testing.T) { s := newServer(t) defer s.Close() dialer := cstDialer dialer.EnableCompression = true ws, _, err := dialer.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) } func TestSocksProxyDial(t *testing.T) { s := newServer(t) defer s.Close() proxyListener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("listen failed: %v", err) } defer proxyListener.Close() go func() { c1, err := proxyListener.Accept() if err != nil { t.Errorf("proxy accept failed: %v", err) return } defer c1.Close() c1.SetDeadline(time.Now().Add(30 * time.Second)) buf := make([]byte, 32) if _, err := io.ReadFull(c1, buf[:3]); err != nil { t.Errorf("read failed: %v", err) return } if want := []byte{5, 1, 0}; !bytes.Equal(want, buf[:len(want)]) { t.Errorf("read %x, want %x", buf[:len(want)], want) } if _, err := c1.Write([]byte{5, 0}); err != nil { t.Errorf("write failed: %v", err) return } if _, err := io.ReadFull(c1, buf[:10]); err != nil { t.Errorf("read failed: %v", err) return } if want := []byte{5, 1, 0, 1}; !bytes.Equal(want, buf[:len(want)]) { t.Errorf("read %x, want %x", buf[:len(want)], want) return } buf[1] = 0 if _, err := c1.Write(buf[:10]); err != nil { t.Errorf("write failed: %v", err) return } ip := net.IP(buf[4:8]) port := binary.BigEndian.Uint16(buf[8:10]) c2, err := net.DialTCP("tcp", nil, &net.TCPAddr{IP: ip, Port: int(port)}) if err != nil { t.Errorf("dial failed; %v", err) return } defer c2.Close() done := make(chan struct{}) go func() { io.Copy(c1, c2) close(done) }() io.Copy(c2, c1) <-done }() purl, err := url.Parse("socks5://" + proxyListener.Addr().String()) if err != nil { t.Fatalf("parse failed: %v", err) } cstDialer := cstDialer // make local copy for modification on next line. cstDialer.Proxy = http.ProxyURL(purl) ws, _, err := cstDialer.Dial(s.URL, nil) if err != nil { t.Fatalf("Dial: %v", err) } defer ws.Close() sendRecv(t, ws) } ================================================ FILE: src/github.com/gorilla/websocket/client_test.go ================================================ // Copyright 2014 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "net/url" "testing" ) var hostPortNoPortTests = []struct { u *url.URL hostPort, hostNoPort string }{ {&url.URL{Scheme: "ws", Host: "example.com"}, "example.com:80", "example.com"}, {&url.URL{Scheme: "wss", Host: "example.com"}, "example.com:443", "example.com"}, {&url.URL{Scheme: "ws", Host: "example.com:7777"}, "example.com:7777", "example.com"}, {&url.URL{Scheme: "wss", Host: "example.com:7777"}, "example.com:7777", "example.com"}, } func TestHostPortNoPort(t *testing.T) { for _, tt := range hostPortNoPortTests { hostPort, hostNoPort := hostPortNoPort(tt.u) if hostPort != tt.hostPort { t.Errorf("hostPortNoPort(%v) returned hostPort %q, want %q", tt.u, hostPort, tt.hostPort) } if hostNoPort != tt.hostNoPort { t.Errorf("hostPortNoPort(%v) returned hostNoPort %q, want %q", tt.u, hostNoPort, tt.hostNoPort) } } } ================================================ FILE: src/github.com/gorilla/websocket/compression.go ================================================ // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "compress/flate" "errors" "io" "strings" "sync" ) const ( minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6 maxCompressionLevel = flate.BestCompression defaultCompressionLevel = 1 ) var ( flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool flateReaderPool = sync.Pool{New: func() interface{} { return flate.NewReader(nil) }} ) func decompressNoContextTakeover(r io.Reader) io.ReadCloser { const tail = // Add four bytes as specified in RFC "\x00\x00\xff\xff" + // Add final block to squelch unexpected EOF error from flate reader. "\x01\x00\x00\xff\xff" fr, _ := flateReaderPool.Get().(io.ReadCloser) fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil) return &flateReadWrapper{fr} } func isValidCompressionLevel(level int) bool { return minCompressionLevel <= level && level <= maxCompressionLevel } func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser { p := &flateWriterPools[level-minCompressionLevel] tw := &truncWriter{w: w} fw, _ := p.Get().(*flate.Writer) if fw == nil { fw, _ = flate.NewWriter(tw, level) } else { fw.Reset(tw) } return &flateWriteWrapper{fw: fw, tw: tw, p: p} } // truncWriter is an io.Writer that writes all but the last four bytes of the // stream to another io.Writer. type truncWriter struct { w io.WriteCloser n int p [4]byte } func (w *truncWriter) Write(p []byte) (int, error) { n := 0 // fill buffer first for simplicity. if w.n < len(w.p) { n = copy(w.p[w.n:], p) p = p[n:] w.n += n if len(p) == 0 { return n, nil } } m := len(p) if m > len(w.p) { m = len(w.p) } if nn, err := w.w.Write(w.p[:m]); err != nil { return n + nn, err } copy(w.p[:], w.p[m:]) copy(w.p[len(w.p)-m:], p[len(p)-m:]) nn, err := w.w.Write(p[:len(p)-m]) return n + nn, err } type flateWriteWrapper struct { fw *flate.Writer tw *truncWriter p *sync.Pool } func (w *flateWriteWrapper) Write(p []byte) (int, error) { if w.fw == nil { return 0, errWriteClosed } return w.fw.Write(p) } func (w *flateWriteWrapper) Close() error { if w.fw == nil { return errWriteClosed } err1 := w.fw.Flush() w.p.Put(w.fw) w.fw = nil if w.tw.p != [4]byte{0, 0, 0xff, 0xff} { return errors.New("websocket: internal error, unexpected bytes at end of flate stream") } err2 := w.tw.w.Close() if err1 != nil { return err1 } return err2 } type flateReadWrapper struct { fr io.ReadCloser } func (r *flateReadWrapper) Read(p []byte) (int, error) { if r.fr == nil { return 0, io.ErrClosedPipe } n, err := r.fr.Read(p) if err == io.EOF { // Preemptively place the reader back in the pool. This helps with // scenarios where the application does not call NextReader() soon after // this final read. r.Close() } return n, err } func (r *flateReadWrapper) Close() error { if r.fr == nil { return io.ErrClosedPipe } err := r.fr.Close() flateReaderPool.Put(r.fr) r.fr = nil return err } ================================================ FILE: src/github.com/gorilla/websocket/compression_test.go ================================================ package websocket import ( "bytes" "fmt" "io" "io/ioutil" "testing" ) type nopCloser struct{ io.Writer } func (nopCloser) Close() error { return nil } func TestTruncWriter(t *testing.T) { const data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijlkmnopqrstuvwxyz987654321" for n := 1; n <= 10; n++ { var b bytes.Buffer w := &truncWriter{w: nopCloser{&b}} p := []byte(data) for len(p) > 0 { m := len(p) if m > n { m = n } w.Write(p[:m]) p = p[m:] } if b.String() != data[:len(data)-len(w.p)] { t.Errorf("%d: %q", n, b.String()) } } } func textMessages(num int) [][]byte { messages := make([][]byte, num) for i := 0; i < num; i++ { msg := fmt.Sprintf("planet: %d, country: %d, city: %d, street: %d", i, i, i, i) messages[i] = []byte(msg) } return messages } func BenchmarkWriteNoCompression(b *testing.B) { w := ioutil.Discard c := newConn(fakeNetConn{Reader: nil, Writer: w}, false, 1024, 1024) messages := textMessages(100) b.ResetTimer() for i := 0; i < b.N; i++ { c.WriteMessage(TextMessage, messages[i%len(messages)]) } b.ReportAllocs() } func BenchmarkWriteWithCompression(b *testing.B) { w := ioutil.Discard c := newConn(fakeNetConn{Reader: nil, Writer: w}, false, 1024, 1024) messages := textMessages(100) c.enableWriteCompression = true c.newCompressionWriter = compressNoContextTakeover b.ResetTimer() for i := 0; i < b.N; i++ { c.WriteMessage(TextMessage, messages[i%len(messages)]) } b.ReportAllocs() } func TestValidCompressionLevel(t *testing.T) { c := newConn(fakeNetConn{}, false, 1024, 1024) for _, level := range []int{minCompressionLevel - 1, maxCompressionLevel + 1} { if err := c.SetCompressionLevel(level); err == nil { t.Errorf("no error for level %d", level) } } for _, level := range []int{minCompressionLevel, maxCompressionLevel} { if err := c.SetCompressionLevel(level); err != nil { t.Errorf("error for level %d", level) } } } ================================================ FILE: src/github.com/gorilla/websocket/conn.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bufio" "encoding/binary" "errors" "io" "io/ioutil" "math/rand" "net" "strconv" "sync" "time" "unicode/utf8" ) const ( // Frame header byte 0 bits from Section 5.2 of RFC 6455 finalBit = 1 << 7 rsv1Bit = 1 << 6 rsv2Bit = 1 << 5 rsv3Bit = 1 << 4 // Frame header byte 1 bits from Section 5.2 of RFC 6455 maskBit = 1 << 7 maxFrameHeaderSize = 2 + 8 + 4 // Fixed header + length + mask maxControlFramePayloadSize = 125 writeWait = time.Second defaultReadBufferSize = 4096 defaultWriteBufferSize = 4096 continuationFrame = 0 noFrame = -1 ) // Close codes defined in RFC 6455, section 11.7. const ( CloseNormalClosure = 1000 CloseGoingAway = 1001 CloseProtocolError = 1002 CloseUnsupportedData = 1003 CloseNoStatusReceived = 1005 CloseAbnormalClosure = 1006 CloseInvalidFramePayloadData = 1007 ClosePolicyViolation = 1008 CloseMessageTooBig = 1009 CloseMandatoryExtension = 1010 CloseInternalServerErr = 1011 CloseServiceRestart = 1012 CloseTryAgainLater = 1013 CloseTLSHandshake = 1015 ) // The message types are defined in RFC 6455, section 11.8. const ( // TextMessage denotes a text data message. The text message payload is // interpreted as UTF-8 encoded text data. TextMessage = 1 // BinaryMessage denotes a binary data message. BinaryMessage = 2 // CloseMessage denotes a close control message. The optional message // payload contains a numeric code and text. Use the FormatCloseMessage // function to format a close message payload. CloseMessage = 8 // PingMessage denotes a ping control message. The optional message payload // is UTF-8 encoded text. PingMessage = 9 // PongMessage denotes a pong control message. The optional message payload // is UTF-8 encoded text. PongMessage = 10 ) // ErrCloseSent is returned when the application writes a message to the // connection after sending a close message. var ErrCloseSent = errors.New("websocket: close sent") // ErrReadLimit is returned when reading a message that is larger than the // read limit set for the connection. var ErrReadLimit = errors.New("websocket: read limit exceeded") // netError satisfies the net Error interface. type netError struct { msg string temporary bool timeout bool } func (e *netError) Error() string { return e.msg } func (e *netError) Temporary() bool { return e.temporary } func (e *netError) Timeout() bool { return e.timeout } // CloseError represents a close message. type CloseError struct { // Code is defined in RFC 6455, section 11.7. Code int // Text is the optional text payload. Text string } func (e *CloseError) Error() string { s := []byte("websocket: close ") s = strconv.AppendInt(s, int64(e.Code), 10) switch e.Code { case CloseNormalClosure: s = append(s, " (normal)"...) case CloseGoingAway: s = append(s, " (going away)"...) case CloseProtocolError: s = append(s, " (protocol error)"...) case CloseUnsupportedData: s = append(s, " (unsupported data)"...) case CloseNoStatusReceived: s = append(s, " (no status)"...) case CloseAbnormalClosure: s = append(s, " (abnormal closure)"...) case CloseInvalidFramePayloadData: s = append(s, " (invalid payload data)"...) case ClosePolicyViolation: s = append(s, " (policy violation)"...) case CloseMessageTooBig: s = append(s, " (message too big)"...) case CloseMandatoryExtension: s = append(s, " (mandatory extension missing)"...) case CloseInternalServerErr: s = append(s, " (internal server error)"...) case CloseTLSHandshake: s = append(s, " (TLS handshake error)"...) } if e.Text != "" { s = append(s, ": "...) s = append(s, e.Text...) } return string(s) } // IsCloseError returns boolean indicating whether the error is a *CloseError // with one of the specified codes. func IsCloseError(err error, codes ...int) bool { if e, ok := err.(*CloseError); ok { for _, code := range codes { if e.Code == code { return true } } } return false } // IsUnexpectedCloseError returns boolean indicating whether the error is a // *CloseError with a code not in the list of expected codes. func IsUnexpectedCloseError(err error, expectedCodes ...int) bool { if e, ok := err.(*CloseError); ok { for _, code := range expectedCodes { if e.Code == code { return false } } return true } return false } var ( errWriteTimeout = &netError{msg: "websocket: write timeout", timeout: true, temporary: true} errUnexpectedEOF = &CloseError{Code: CloseAbnormalClosure, Text: io.ErrUnexpectedEOF.Error()} errBadWriteOpCode = errors.New("websocket: bad write message type") errWriteClosed = errors.New("websocket: write closed") errInvalidControlFrame = errors.New("websocket: invalid control frame") ) func newMaskKey() [4]byte { n := rand.Uint32() return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)} } func hideTempErr(err error) error { if e, ok := err.(net.Error); ok && e.Temporary() { err = &netError{msg: e.Error(), timeout: e.Timeout()} } return err } func isControl(frameType int) bool { return frameType == CloseMessage || frameType == PingMessage || frameType == PongMessage } func isData(frameType int) bool { return frameType == TextMessage || frameType == BinaryMessage } var validReceivedCloseCodes = map[int]bool{ // see http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number CloseNormalClosure: true, CloseGoingAway: true, CloseProtocolError: true, CloseUnsupportedData: true, CloseNoStatusReceived: false, CloseAbnormalClosure: false, CloseInvalidFramePayloadData: true, ClosePolicyViolation: true, CloseMessageTooBig: true, CloseMandatoryExtension: true, CloseInternalServerErr: true, CloseServiceRestart: true, CloseTryAgainLater: true, CloseTLSHandshake: false, } func isValidReceivedCloseCode(code int) bool { return validReceivedCloseCodes[code] || (code >= 3000 && code <= 4999) } // The Conn type represents a WebSocket connection. type Conn struct { conn net.Conn isServer bool subprotocol string // Write fields mu chan bool // used as mutex to protect write to conn writeBuf []byte // frame is constructed in this buffer. writeDeadline time.Time writer io.WriteCloser // the current writer returned to the application isWriting bool // for best-effort concurrent write detection writeErrMu sync.Mutex writeErr error enableWriteCompression bool compressionLevel int newCompressionWriter func(io.WriteCloser, int) io.WriteCloser // Read fields reader io.ReadCloser // the current reader returned to the application readErr error br *bufio.Reader readRemaining int64 // bytes remaining in current frame. readFinal bool // true the current message has more frames. readLength int64 // Message size. readLimit int64 // Maximum message size. readMaskPos int readMaskKey [4]byte handlePong func(string) error handlePing func(string) error handleClose func(int, string) error readErrCount int messageReader *messageReader // the current low-level reader readDecompress bool // whether last read frame had RSV1 set newDecompressionReader func(io.Reader) io.ReadCloser } func newConn(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int) *Conn { return newConnBRW(conn, isServer, readBufferSize, writeBufferSize, nil) } type writeHook struct { p []byte } func (wh *writeHook) Write(p []byte) (int, error) { wh.p = p return len(p), nil } func newConnBRW(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int, brw *bufio.ReadWriter) *Conn { mu := make(chan bool, 1) mu <- true var br *bufio.Reader if readBufferSize == 0 && brw != nil && brw.Reader != nil { // Reuse the supplied bufio.Reader if the buffer has a useful size. // This code assumes that peek on a reader returns // bufio.Reader.buf[:0]. brw.Reader.Reset(conn) if p, err := brw.Reader.Peek(0); err == nil && cap(p) >= 256 { br = brw.Reader } } if br == nil { if readBufferSize == 0 { readBufferSize = defaultReadBufferSize } if readBufferSize < maxControlFramePayloadSize { readBufferSize = maxControlFramePayloadSize } br = bufio.NewReaderSize(conn, readBufferSize) } var writeBuf []byte if writeBufferSize == 0 && brw != nil && brw.Writer != nil { // Use the bufio.Writer's buffer if the buffer has a useful size. This // code assumes that bufio.Writer.buf[:1] is passed to the // bufio.Writer's underlying writer. var wh writeHook brw.Writer.Reset(&wh) brw.Writer.WriteByte(0) brw.Flush() if cap(wh.p) >= maxFrameHeaderSize+256 { writeBuf = wh.p[:cap(wh.p)] } } if writeBuf == nil { if writeBufferSize == 0 { writeBufferSize = defaultWriteBufferSize } writeBuf = make([]byte, writeBufferSize+maxFrameHeaderSize) } c := &Conn{ isServer: isServer, br: br, conn: conn, mu: mu, readFinal: true, writeBuf: writeBuf, enableWriteCompression: true, compressionLevel: defaultCompressionLevel, } c.SetCloseHandler(nil) c.SetPingHandler(nil) c.SetPongHandler(nil) return c } // Subprotocol returns the negotiated protocol for the connection. func (c *Conn) Subprotocol() string { return c.subprotocol } // Close closes the underlying network connection without sending or waiting // for a close message. func (c *Conn) Close() error { return c.conn.Close() } // LocalAddr returns the local network address. func (c *Conn) LocalAddr() net.Addr { return c.conn.LocalAddr() } // RemoteAddr returns the remote network address. func (c *Conn) RemoteAddr() net.Addr { return c.conn.RemoteAddr() } // Write methods func (c *Conn) writeFatal(err error) error { err = hideTempErr(err) c.writeErrMu.Lock() if c.writeErr == nil { c.writeErr = err } c.writeErrMu.Unlock() return err } func (c *Conn) write(frameType int, deadline time.Time, buf0, buf1 []byte) error { <-c.mu defer func() { c.mu <- true }() c.writeErrMu.Lock() err := c.writeErr c.writeErrMu.Unlock() if err != nil { return err } c.conn.SetWriteDeadline(deadline) if len(buf1) == 0 { _, err = c.conn.Write(buf0) } else { err = c.writeBufs(buf0, buf1) } if err != nil { return c.writeFatal(err) } if frameType == CloseMessage { c.writeFatal(ErrCloseSent) } return nil } // WriteControl writes a control message with the given deadline. The allowed // message types are CloseMessage, PingMessage and PongMessage. func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error { if !isControl(messageType) { return errBadWriteOpCode } if len(data) > maxControlFramePayloadSize { return errInvalidControlFrame } b0 := byte(messageType) | finalBit b1 := byte(len(data)) if !c.isServer { b1 |= maskBit } buf := make([]byte, 0, maxFrameHeaderSize+maxControlFramePayloadSize) buf = append(buf, b0, b1) if c.isServer { buf = append(buf, data...) } else { key := newMaskKey() buf = append(buf, key[:]...) buf = append(buf, data...) maskBytes(key, 0, buf[6:]) } d := time.Hour * 1000 if !deadline.IsZero() { d = deadline.Sub(time.Now()) if d < 0 { return errWriteTimeout } } timer := time.NewTimer(d) select { case <-c.mu: timer.Stop() case <-timer.C: return errWriteTimeout } defer func() { c.mu <- true }() c.writeErrMu.Lock() err := c.writeErr c.writeErrMu.Unlock() if err != nil { return err } c.conn.SetWriteDeadline(deadline) _, err = c.conn.Write(buf) if err != nil { return c.writeFatal(err) } if messageType == CloseMessage { c.writeFatal(ErrCloseSent) } return err } func (c *Conn) prepWrite(messageType int) error { // Close previous writer if not already closed by the application. It's // probably better to return an error in this situation, but we cannot // change this without breaking existing applications. if c.writer != nil { c.writer.Close() c.writer = nil } if !isControl(messageType) && !isData(messageType) { return errBadWriteOpCode } c.writeErrMu.Lock() err := c.writeErr c.writeErrMu.Unlock() return err } // NextWriter returns a writer for the next message to send. The writer's Close // method flushes the complete message to the network. // // There can be at most one open writer on a connection. NextWriter closes the // previous writer if the application has not already done so. // // All message types (TextMessage, BinaryMessage, CloseMessage, PingMessage and // PongMessage) are supported. func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error) { if err := c.prepWrite(messageType); err != nil { return nil, err } mw := &messageWriter{ c: c, frameType: messageType, pos: maxFrameHeaderSize, } c.writer = mw if c.newCompressionWriter != nil && c.enableWriteCompression && isData(messageType) { w := c.newCompressionWriter(c.writer, c.compressionLevel) mw.compress = true c.writer = w } return c.writer, nil } type messageWriter struct { c *Conn compress bool // whether next call to flushFrame should set RSV1 pos int // end of data in writeBuf. frameType int // type of the current frame. err error } func (w *messageWriter) fatal(err error) error { if w.err != nil { w.err = err w.c.writer = nil } return err } // flushFrame writes buffered data and extra as a frame to the network. The // final argument indicates that this is the last frame in the message. func (w *messageWriter) flushFrame(final bool, extra []byte) error { c := w.c length := w.pos - maxFrameHeaderSize + len(extra) // Check for invalid control frames. if isControl(w.frameType) && (!final || length > maxControlFramePayloadSize) { return w.fatal(errInvalidControlFrame) } b0 := byte(w.frameType) if final { b0 |= finalBit } if w.compress { b0 |= rsv1Bit } w.compress = false b1 := byte(0) if !c.isServer { b1 |= maskBit } // Assume that the frame starts at beginning of c.writeBuf. framePos := 0 if c.isServer { // Adjust up if mask not included in the header. framePos = 4 } switch { case length >= 65536: c.writeBuf[framePos] = b0 c.writeBuf[framePos+1] = b1 | 127 binary.BigEndian.PutUint64(c.writeBuf[framePos+2:], uint64(length)) case length > 125: framePos += 6 c.writeBuf[framePos] = b0 c.writeBuf[framePos+1] = b1 | 126 binary.BigEndian.PutUint16(c.writeBuf[framePos+2:], uint16(length)) default: framePos += 8 c.writeBuf[framePos] = b0 c.writeBuf[framePos+1] = b1 | byte(length) } if !c.isServer { key := newMaskKey() copy(c.writeBuf[maxFrameHeaderSize-4:], key[:]) maskBytes(key, 0, c.writeBuf[maxFrameHeaderSize:w.pos]) if len(extra) > 0 { return c.writeFatal(errors.New("websocket: internal error, extra used in client mode")) } } // Write the buffers to the connection with best-effort detection of // concurrent writes. See the concurrency section in the package // documentation for more info. if c.isWriting { panic("concurrent write to websocket connection") } c.isWriting = true err := c.write(w.frameType, c.writeDeadline, c.writeBuf[framePos:w.pos], extra) if !c.isWriting { panic("concurrent write to websocket connection") } c.isWriting = false if err != nil { return w.fatal(err) } if final { c.writer = nil return nil } // Setup for next frame. w.pos = maxFrameHeaderSize w.frameType = continuationFrame return nil } func (w *messageWriter) ncopy(max int) (int, error) { n := len(w.c.writeBuf) - w.pos if n <= 0 { if err := w.flushFrame(false, nil); err != nil { return 0, err } n = len(w.c.writeBuf) - w.pos } if n > max { n = max } return n, nil } func (w *messageWriter) Write(p []byte) (int, error) { if w.err != nil { return 0, w.err } if len(p) > 2*len(w.c.writeBuf) && w.c.isServer { // Don't buffer large messages. err := w.flushFrame(false, p) if err != nil { return 0, err } return len(p), nil } nn := len(p) for len(p) > 0 { n, err := w.ncopy(len(p)) if err != nil { return 0, err } copy(w.c.writeBuf[w.pos:], p[:n]) w.pos += n p = p[n:] } return nn, nil } func (w *messageWriter) WriteString(p string) (int, error) { if w.err != nil { return 0, w.err } nn := len(p) for len(p) > 0 { n, err := w.ncopy(len(p)) if err != nil { return 0, err } copy(w.c.writeBuf[w.pos:], p[:n]) w.pos += n p = p[n:] } return nn, nil } func (w *messageWriter) ReadFrom(r io.Reader) (nn int64, err error) { if w.err != nil { return 0, w.err } for { if w.pos == len(w.c.writeBuf) { err = w.flushFrame(false, nil) if err != nil { break } } var n int n, err = r.Read(w.c.writeBuf[w.pos:]) w.pos += n nn += int64(n) if err != nil { if err == io.EOF { err = nil } break } } return nn, err } func (w *messageWriter) Close() error { if w.err != nil { return w.err } if err := w.flushFrame(true, nil); err != nil { return err } w.err = errWriteClosed return nil } // WritePreparedMessage writes prepared message into connection. func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error { frameType, frameData, err := pm.frame(prepareKey{ isServer: c.isServer, compress: c.newCompressionWriter != nil && c.enableWriteCompression && isData(pm.messageType), compressionLevel: c.compressionLevel, }) if err != nil { return err } if c.isWriting { panic("concurrent write to websocket connection") } c.isWriting = true err = c.write(frameType, c.writeDeadline, frameData, nil) if !c.isWriting { panic("concurrent write to websocket connection") } c.isWriting = false return err } // WriteMessage is a helper method for getting a writer using NextWriter, // writing the message and closing the writer. func (c *Conn) WriteMessage(messageType int, data []byte) error { if c.isServer && (c.newCompressionWriter == nil || !c.enableWriteCompression) { // Fast path with no allocations and single frame. if err := c.prepWrite(messageType); err != nil { return err } mw := messageWriter{c: c, frameType: messageType, pos: maxFrameHeaderSize} n := copy(c.writeBuf[mw.pos:], data) mw.pos += n data = data[n:] return mw.flushFrame(true, data) } w, err := c.NextWriter(messageType) if err != nil { return err } if _, err = w.Write(data); err != nil { return err } return w.Close() } // SetWriteDeadline sets the write deadline on the underlying network // connection. After a write has timed out, the websocket state is corrupt and // all future writes will return an error. A zero value for t means writes will // not time out. func (c *Conn) SetWriteDeadline(t time.Time) error { c.writeDeadline = t return nil } // Read methods func (c *Conn) advanceFrame() (int, error) { // 1. Skip remainder of previous frame. if c.readRemaining > 0 { if _, err := io.CopyN(ioutil.Discard, c.br, c.readRemaining); err != nil { return noFrame, err } } // 2. Read and parse first two bytes of frame header. p, err := c.read(2) if err != nil { return noFrame, err } final := p[0]&finalBit != 0 frameType := int(p[0] & 0xf) mask := p[1]&maskBit != 0 c.readRemaining = int64(p[1] & 0x7f) c.readDecompress = false if c.newDecompressionReader != nil && (p[0]&rsv1Bit) != 0 { c.readDecompress = true p[0] &^= rsv1Bit } if rsv := p[0] & (rsv1Bit | rsv2Bit | rsv3Bit); rsv != 0 { return noFrame, c.handleProtocolError("unexpected reserved bits 0x" + strconv.FormatInt(int64(rsv), 16)) } switch frameType { case CloseMessage, PingMessage, PongMessage: if c.readRemaining > maxControlFramePayloadSize { return noFrame, c.handleProtocolError("control frame length > 125") } if !final { return noFrame, c.handleProtocolError("control frame not final") } case TextMessage, BinaryMessage: if !c.readFinal { return noFrame, c.handleProtocolError("message start before final message frame") } c.readFinal = final case continuationFrame: if c.readFinal { return noFrame, c.handleProtocolError("continuation after final message frame") } c.readFinal = final default: return noFrame, c.handleProtocolError("unknown opcode " + strconv.Itoa(frameType)) } // 3. Read and parse frame length. switch c.readRemaining { case 126: p, err := c.read(2) if err != nil { return noFrame, err } c.readRemaining = int64(binary.BigEndian.Uint16(p)) case 127: p, err := c.read(8) if err != nil { return noFrame, err } c.readRemaining = int64(binary.BigEndian.Uint64(p)) } // 4. Handle frame masking. if mask != c.isServer { return noFrame, c.handleProtocolError("incorrect mask flag") } if mask { c.readMaskPos = 0 p, err := c.read(len(c.readMaskKey)) if err != nil { return noFrame, err } copy(c.readMaskKey[:], p) } // 5. For text and binary messages, enforce read limit and return. if frameType == continuationFrame || frameType == TextMessage || frameType == BinaryMessage { c.readLength += c.readRemaining if c.readLimit > 0 && c.readLength > c.readLimit { c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait)) return noFrame, ErrReadLimit } return frameType, nil } // 6. Read control frame payload. var payload []byte if c.readRemaining > 0 { payload, err = c.read(int(c.readRemaining)) c.readRemaining = 0 if err != nil { return noFrame, err } if c.isServer { maskBytes(c.readMaskKey, 0, payload) } } // 7. Process control frame payload. switch frameType { case PongMessage: if err := c.handlePong(string(payload)); err != nil { return noFrame, err } case PingMessage: if err := c.handlePing(string(payload)); err != nil { return noFrame, err } case CloseMessage: closeCode := CloseNoStatusReceived closeText := "" if len(payload) >= 2 { closeCode = int(binary.BigEndian.Uint16(payload)) if !isValidReceivedCloseCode(closeCode) { return noFrame, c.handleProtocolError("invalid close code") } closeText = string(payload[2:]) if !utf8.ValidString(closeText) { return noFrame, c.handleProtocolError("invalid utf8 payload in close frame") } } if err := c.handleClose(closeCode, closeText); err != nil { return noFrame, err } return noFrame, &CloseError{Code: closeCode, Text: closeText} } return frameType, nil } func (c *Conn) handleProtocolError(message string) error { c.WriteControl(CloseMessage, FormatCloseMessage(CloseProtocolError, message), time.Now().Add(writeWait)) return errors.New("websocket: " + message) } // NextReader returns the next data message received from the peer. The // returned messageType is either TextMessage or BinaryMessage. // // There can be at most one open reader on a connection. NextReader discards // the previous message if the application has not already consumed it. // // Applications must break out of the application's read loop when this method // returns a non-nil error value. Errors returned from this method are // permanent. Once this method returns a non-nil error, all subsequent calls to // this method return the same error. func (c *Conn) NextReader() (messageType int, r io.Reader, err error) { // Close previous reader, only relevant for decompression. if c.reader != nil { c.reader.Close() c.reader = nil } c.messageReader = nil c.readLength = 0 for c.readErr == nil { frameType, err := c.advanceFrame() if err != nil { c.readErr = hideTempErr(err) break } if frameType == TextMessage || frameType == BinaryMessage { c.messageReader = &messageReader{c} c.reader = c.messageReader if c.readDecompress { c.reader = c.newDecompressionReader(c.reader) } return frameType, c.reader, nil } } // Applications that do handle the error returned from this method spin in // tight loop on connection failure. To help application developers detect // this error, panic on repeated reads to the failed connection. c.readErrCount++ if c.readErrCount >= 1000 { panic("repeated read on failed websocket connection") } return noFrame, nil, c.readErr } type messageReader struct{ c *Conn } func (r *messageReader) Read(b []byte) (int, error) { c := r.c if c.messageReader != r { return 0, io.EOF } for c.readErr == nil { if c.readRemaining > 0 { if int64(len(b)) > c.readRemaining { b = b[:c.readRemaining] } n, err := c.br.Read(b) c.readErr = hideTempErr(err) if c.isServer { c.readMaskPos = maskBytes(c.readMaskKey, c.readMaskPos, b[:n]) } c.readRemaining -= int64(n) if c.readRemaining > 0 && c.readErr == io.EOF { c.readErr = errUnexpectedEOF } return n, c.readErr } if c.readFinal { c.messageReader = nil return 0, io.EOF } frameType, err := c.advanceFrame() switch { case err != nil: c.readErr = hideTempErr(err) case frameType == TextMessage || frameType == BinaryMessage: c.readErr = errors.New("websocket: internal error, unexpected text or binary in Reader") } } err := c.readErr if err == io.EOF && c.messageReader == r { err = errUnexpectedEOF } return 0, err } func (r *messageReader) Close() error { return nil } // ReadMessage is a helper method for getting a reader using NextReader and // reading from that reader to a buffer. func (c *Conn) ReadMessage() (messageType int, p []byte, err error) { var r io.Reader messageType, r, err = c.NextReader() if err != nil { return messageType, nil, err } p, err = ioutil.ReadAll(r) return messageType, p, err } // SetReadDeadline sets the read deadline on the underlying network connection. // After a read has timed out, the websocket connection state is corrupt and // all future reads will return an error. A zero value for t means reads will // not time out. func (c *Conn) SetReadDeadline(t time.Time) error { return c.conn.SetReadDeadline(t) } // SetReadLimit sets the maximum size for a message read from the peer. If a // message exceeds the limit, the connection sends a close message to the peer // and returns ErrReadLimit to the application. func (c *Conn) SetReadLimit(limit int64) { c.readLimit = limit } // CloseHandler returns the current close handler func (c *Conn) CloseHandler() func(code int, text string) error { return c.handleClose } // SetCloseHandler sets the handler for close messages received from the peer. // The code argument to h is the received close code or CloseNoStatusReceived // if the close message is empty. The default close handler sends a close // message back to the peer. // // The handler function is called from the NextReader, ReadMessage and message // reader Read methods. The application must read the connection to process // close messages as described in the section on Control Messages above. // // The connection read methods return a CloseError when a close message is // received. Most applications should handle close messages as part of their // normal error handling. Applications should only set a close handler when the // application must perform some action before sending a close message back to // the peer. func (c *Conn) SetCloseHandler(h func(code int, text string) error) { if h == nil { h = func(code int, text string) error { message := FormatCloseMessage(code, "") c.WriteControl(CloseMessage, message, time.Now().Add(writeWait)) return nil } } c.handleClose = h } // PingHandler returns the current ping handler func (c *Conn) PingHandler() func(appData string) error { return c.handlePing } // SetPingHandler sets the handler for ping messages received from the peer. // The appData argument to h is the PING message application data. The default // ping handler sends a pong to the peer. // // The handler function is called from the NextReader, ReadMessage and message // reader Read methods. The application must read the connection to process // ping messages as described in the section on Control Messages above. func (c *Conn) SetPingHandler(h func(appData string) error) { if h == nil { h = func(message string) error { err := c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait)) if err == ErrCloseSent { return nil } else if e, ok := err.(net.Error); ok && e.Temporary() { return nil } return err } } c.handlePing = h } // PongHandler returns the current pong handler func (c *Conn) PongHandler() func(appData string) error { return c.handlePong } // SetPongHandler sets the handler for pong messages received from the peer. // The appData argument to h is the PONG message application data. The default // pong handler does nothing. // // The handler function is called from the NextReader, ReadMessage and message // reader Read methods. The application must read the connection to process // pong messages as described in the section on Control Messages above. func (c *Conn) SetPongHandler(h func(appData string) error) { if h == nil { h = func(string) error { return nil } } c.handlePong = h } // UnderlyingConn returns the internal net.Conn. This can be used to further // modifications to connection specific flags. func (c *Conn) UnderlyingConn() net.Conn { return c.conn } // EnableWriteCompression enables and disables write compression of // subsequent text and binary messages. This function is a noop if // compression was not negotiated with the peer. func (c *Conn) EnableWriteCompression(enable bool) { c.enableWriteCompression = enable } // SetCompressionLevel sets the flate compression level for subsequent text and // binary messages. This function is a noop if compression was not negotiated // with the peer. See the compress/flate package for a description of // compression levels. func (c *Conn) SetCompressionLevel(level int) error { if !isValidCompressionLevel(level) { return errors.New("websocket: invalid compression level") } c.compressionLevel = level return nil } // FormatCloseMessage formats closeCode and text as a WebSocket close message. // An empty message is returned for code CloseNoStatusReceived. func FormatCloseMessage(closeCode int, text string) []byte { if closeCode == CloseNoStatusReceived { // Return empty message because it's illegal to send // CloseNoStatusReceived. Return non-nil value in case application // checks for nil. return []byte{} } buf := make([]byte, 2+len(text)) binary.BigEndian.PutUint16(buf, uint16(closeCode)) copy(buf[2:], text) return buf } ================================================ FILE: src/github.com/gorilla/websocket/conn_broadcast_test.go ================================================ // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.7 package websocket import ( "io" "io/ioutil" "sync/atomic" "testing" ) // broadcastBench allows to run broadcast benchmarks. // In every broadcast benchmark we create many connections, then send the same // message into every connection and wait for all writes complete. This emulates // an application where many connections listen to the same data - i.e. PUB/SUB // scenarios with many subscribers in one channel. type broadcastBench struct { w io.Writer message *broadcastMessage closeCh chan struct{} doneCh chan struct{} count int32 conns []*broadcastConn compression bool usePrepared bool } type broadcastMessage struct { payload []byte prepared *PreparedMessage } type broadcastConn struct { conn *Conn msgCh chan *broadcastMessage } func newBroadcastConn(c *Conn) *broadcastConn { return &broadcastConn{ conn: c, msgCh: make(chan *broadcastMessage, 1), } } func newBroadcastBench(usePrepared, compression bool) *broadcastBench { bench := &broadcastBench{ w: ioutil.Discard, doneCh: make(chan struct{}), closeCh: make(chan struct{}), usePrepared: usePrepared, compression: compression, } msg := &broadcastMessage{ payload: textMessages(1)[0], } if usePrepared { pm, _ := NewPreparedMessage(TextMessage, msg.payload) msg.prepared = pm } bench.message = msg bench.makeConns(10000) return bench } func (b *broadcastBench) makeConns(numConns int) { conns := make([]*broadcastConn, numConns) for i := 0; i < numConns; i++ { c := newConn(fakeNetConn{Reader: nil, Writer: b.w}, true, 1024, 1024) if b.compression { c.enableWriteCompression = true c.newCompressionWriter = compressNoContextTakeover } conns[i] = newBroadcastConn(c) go func(c *broadcastConn) { for { select { case msg := <-c.msgCh: if b.usePrepared { c.conn.WritePreparedMessage(msg.prepared) } else { c.conn.WriteMessage(TextMessage, msg.payload) } val := atomic.AddInt32(&b.count, 1) if val%int32(numConns) == 0 { b.doneCh <- struct{}{} } case <-b.closeCh: return } } }(conns[i]) } b.conns = conns } func (b *broadcastBench) close() { close(b.closeCh) } func (b *broadcastBench) runOnce() { for _, c := range b.conns { c.msgCh <- b.message } <-b.doneCh } func BenchmarkBroadcast(b *testing.B) { benchmarks := []struct { name string usePrepared bool compression bool }{ {"NoCompression", false, false}, {"WithCompression", false, true}, {"NoCompressionPrepared", true, false}, {"WithCompressionPrepared", true, true}, } for _, bm := range benchmarks { b.Run(bm.name, func(b *testing.B) { bench := newBroadcastBench(bm.usePrepared, bm.compression) defer bench.close() b.ResetTimer() for i := 0; i < b.N; i++ { bench.runOnce() } b.ReportAllocs() }) } } ================================================ FILE: src/github.com/gorilla/websocket/conn_read.go ================================================ // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.5 package websocket import "io" func (c *Conn) read(n int) ([]byte, error) { p, err := c.br.Peek(n) if err == io.EOF { err = errUnexpectedEOF } c.br.Discard(len(p)) return p, err } ================================================ FILE: src/github.com/gorilla/websocket/conn_read_legacy.go ================================================ // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.5 package websocket import "io" func (c *Conn) read(n int) ([]byte, error) { p, err := c.br.Peek(n) if err == io.EOF { err = errUnexpectedEOF } if len(p) > 0 { // advance over the bytes just read io.ReadFull(c.br, p) } return p, err } ================================================ FILE: src/github.com/gorilla/websocket/conn_test.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bufio" "bytes" "errors" "fmt" "io" "io/ioutil" "net" "reflect" "testing" "testing/iotest" "time" ) var _ net.Error = errWriteTimeout type fakeNetConn struct { io.Reader io.Writer } func (c fakeNetConn) Close() error { return nil } func (c fakeNetConn) LocalAddr() net.Addr { return localAddr } func (c fakeNetConn) RemoteAddr() net.Addr { return remoteAddr } func (c fakeNetConn) SetDeadline(t time.Time) error { return nil } func (c fakeNetConn) SetReadDeadline(t time.Time) error { return nil } func (c fakeNetConn) SetWriteDeadline(t time.Time) error { return nil } type fakeAddr int var ( localAddr = fakeAddr(1) remoteAddr = fakeAddr(2) ) func (a fakeAddr) Network() string { return "net" } func (a fakeAddr) String() string { return "str" } func TestFraming(t *testing.T) { frameSizes := []int{0, 1, 2, 124, 125, 126, 127, 128, 129, 65534, 65535, 65536, 65537} var readChunkers = []struct { name string f func(io.Reader) io.Reader }{ {"half", iotest.HalfReader}, {"one", iotest.OneByteReader}, {"asis", func(r io.Reader) io.Reader { return r }}, } writeBuf := make([]byte, 65537) for i := range writeBuf { writeBuf[i] = byte(i) } var writers = []struct { name string f func(w io.Writer, n int) (int, error) }{ {"iocopy", func(w io.Writer, n int) (int, error) { nn, err := io.Copy(w, bytes.NewReader(writeBuf[:n])) return int(nn), err }}, {"write", func(w io.Writer, n int) (int, error) { return w.Write(writeBuf[:n]) }}, {"string", func(w io.Writer, n int) (int, error) { return io.WriteString(w, string(writeBuf[:n])) }}, } for _, compress := range []bool{false, true} { for _, isServer := range []bool{true, false} { for _, chunker := range readChunkers { var connBuf bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &connBuf}, isServer, 1024, 1024) rc := newConn(fakeNetConn{Reader: chunker.f(&connBuf), Writer: nil}, !isServer, 1024, 1024) if compress { wc.newCompressionWriter = compressNoContextTakeover rc.newDecompressionReader = decompressNoContextTakeover } for _, n := range frameSizes { for _, writer := range writers { name := fmt.Sprintf("z:%v, s:%v, r:%s, n:%d w:%s", compress, isServer, chunker.name, n, writer.name) w, err := wc.NextWriter(TextMessage) if err != nil { t.Errorf("%s: wc.NextWriter() returned %v", name, err) continue } nn, err := writer.f(w, n) if err != nil || nn != n { t.Errorf("%s: w.Write(writeBuf[:n]) returned %d, %v", name, nn, err) continue } err = w.Close() if err != nil { t.Errorf("%s: w.Close() returned %v", name, err) continue } opCode, r, err := rc.NextReader() if err != nil || opCode != TextMessage { t.Errorf("%s: NextReader() returned %d, r, %v", name, opCode, err) continue } rbuf, err := ioutil.ReadAll(r) if err != nil { t.Errorf("%s: ReadFull() returned rbuf, %v", name, err) continue } if len(rbuf) != n { t.Errorf("%s: len(rbuf) is %d, want %d", name, len(rbuf), n) continue } for i, b := range rbuf { if byte(i) != b { t.Errorf("%s: bad byte at offset %d", name, i) break } } } } } } } } func TestControl(t *testing.T) { const message = "this is a ping/pong messsage" for _, isServer := range []bool{true, false} { for _, isWriteControl := range []bool{true, false} { name := fmt.Sprintf("s:%v, wc:%v", isServer, isWriteControl) var connBuf bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &connBuf}, isServer, 1024, 1024) rc := newConn(fakeNetConn{Reader: &connBuf, Writer: nil}, !isServer, 1024, 1024) if isWriteControl { wc.WriteControl(PongMessage, []byte(message), time.Now().Add(time.Second)) } else { w, err := wc.NextWriter(PongMessage) if err != nil { t.Errorf("%s: wc.NextWriter() returned %v", name, err) continue } if _, err := w.Write([]byte(message)); err != nil { t.Errorf("%s: w.Write() returned %v", name, err) continue } if err := w.Close(); err != nil { t.Errorf("%s: w.Close() returned %v", name, err) continue } var actualMessage string rc.SetPongHandler(func(s string) error { actualMessage = s; return nil }) rc.NextReader() if actualMessage != message { t.Errorf("%s: pong=%q, want %q", name, actualMessage, message) continue } } } } } func TestCloseFrameBeforeFinalMessageFrame(t *testing.T) { const bufSize = 512 expectedErr := &CloseError{Code: CloseNormalClosure, Text: "hello"} var b1, b2 bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &b1}, false, 1024, bufSize) rc := newConn(fakeNetConn{Reader: &b1, Writer: &b2}, true, 1024, 1024) w, _ := wc.NextWriter(BinaryMessage) w.Write(make([]byte, bufSize+bufSize/2)) wc.WriteControl(CloseMessage, FormatCloseMessage(expectedErr.Code, expectedErr.Text), time.Now().Add(10*time.Second)) w.Close() op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("NextReader() returned %d, %v", op, err) } _, err = io.Copy(ioutil.Discard, r) if !reflect.DeepEqual(err, expectedErr) { t.Fatalf("io.Copy() returned %v, want %v", err, expectedErr) } _, _, err = rc.NextReader() if !reflect.DeepEqual(err, expectedErr) { t.Fatalf("NextReader() returned %v, want %v", err, expectedErr) } } func TestEOFWithinFrame(t *testing.T) { const bufSize = 64 for n := 0; ; n++ { var b bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &b}, false, 1024, 1024) rc := newConn(fakeNetConn{Reader: &b, Writer: nil}, true, 1024, 1024) w, _ := wc.NextWriter(BinaryMessage) w.Write(make([]byte, bufSize)) w.Close() if n >= b.Len() { break } b.Truncate(n) op, r, err := rc.NextReader() if err == errUnexpectedEOF { continue } if op != BinaryMessage || err != nil { t.Fatalf("%d: NextReader() returned %d, %v", n, op, err) } _, err = io.Copy(ioutil.Discard, r) if err != errUnexpectedEOF { t.Fatalf("%d: io.Copy() returned %v, want %v", n, err, errUnexpectedEOF) } _, _, err = rc.NextReader() if err != errUnexpectedEOF { t.Fatalf("%d: NextReader() returned %v, want %v", n, err, errUnexpectedEOF) } } } func TestEOFBeforeFinalFrame(t *testing.T) { const bufSize = 512 var b1, b2 bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &b1}, false, 1024, bufSize) rc := newConn(fakeNetConn{Reader: &b1, Writer: &b2}, true, 1024, 1024) w, _ := wc.NextWriter(BinaryMessage) w.Write(make([]byte, bufSize+bufSize/2)) op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("NextReader() returned %d, %v", op, err) } _, err = io.Copy(ioutil.Discard, r) if err != errUnexpectedEOF { t.Fatalf("io.Copy() returned %v, want %v", err, errUnexpectedEOF) } _, _, err = rc.NextReader() if err != errUnexpectedEOF { t.Fatalf("NextReader() returned %v, want %v", err, errUnexpectedEOF) } } func TestWriteAfterMessageWriterClose(t *testing.T) { wc := newConn(fakeNetConn{Reader: nil, Writer: &bytes.Buffer{}}, false, 1024, 1024) w, _ := wc.NextWriter(BinaryMessage) io.WriteString(w, "hello") if err := w.Close(); err != nil { t.Fatalf("unxpected error closing message writer, %v", err) } if _, err := io.WriteString(w, "world"); err == nil { t.Fatalf("no error writing after close") } w, _ = wc.NextWriter(BinaryMessage) io.WriteString(w, "hello") // close w by getting next writer _, err := wc.NextWriter(BinaryMessage) if err != nil { t.Fatalf("unexpected error getting next writer, %v", err) } if _, err := io.WriteString(w, "world"); err == nil { t.Fatalf("no error writing after close") } } func TestReadLimit(t *testing.T) { const readLimit = 512 message := make([]byte, readLimit+1) var b1, b2 bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &b1}, false, 1024, readLimit-2) rc := newConn(fakeNetConn{Reader: &b1, Writer: &b2}, true, 1024, 1024) rc.SetReadLimit(readLimit) // Send message at the limit with interleaved pong. w, _ := wc.NextWriter(BinaryMessage) w.Write(message[:readLimit-1]) wc.WriteControl(PongMessage, []byte("this is a pong"), time.Now().Add(10*time.Second)) w.Write(message[:1]) w.Close() // Send message larger than the limit. wc.WriteMessage(BinaryMessage, message[:readLimit+1]) op, _, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("1: NextReader() returned %d, %v", op, err) } op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("2: NextReader() returned %d, %v", op, err) } _, err = io.Copy(ioutil.Discard, r) if err != ErrReadLimit { t.Fatalf("io.Copy() returned %v", err) } } func TestAddrs(t *testing.T) { c := newConn(&fakeNetConn{}, true, 1024, 1024) if c.LocalAddr() != localAddr { t.Errorf("LocalAddr = %v, want %v", c.LocalAddr(), localAddr) } if c.RemoteAddr() != remoteAddr { t.Errorf("RemoteAddr = %v, want %v", c.RemoteAddr(), remoteAddr) } } func TestUnderlyingConn(t *testing.T) { var b1, b2 bytes.Buffer fc := fakeNetConn{Reader: &b1, Writer: &b2} c := newConn(fc, true, 1024, 1024) ul := c.UnderlyingConn() if ul != fc { t.Fatalf("Underlying conn is not what it should be.") } } func TestBufioReadBytes(t *testing.T) { // Test calling bufio.ReadBytes for value longer than read buffer size. m := make([]byte, 512) m[len(m)-1] = '\n' var b1, b2 bytes.Buffer wc := newConn(fakeNetConn{Reader: nil, Writer: &b1}, false, len(m)+64, len(m)+64) rc := newConn(fakeNetConn{Reader: &b1, Writer: &b2}, true, len(m)-64, len(m)-64) w, _ := wc.NextWriter(BinaryMessage) w.Write(m) w.Close() op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("NextReader() returned %d, %v", op, err) } br := bufio.NewReader(r) p, err := br.ReadBytes('\n') if err != nil { t.Fatalf("ReadBytes() returned %v", err) } if len(p) != len(m) { t.Fatalf("read returned %d bytes, want %d bytes", len(p), len(m)) } } var closeErrorTests = []struct { err error codes []int ok bool }{ {&CloseError{Code: CloseNormalClosure}, []int{CloseNormalClosure}, true}, {&CloseError{Code: CloseNormalClosure}, []int{CloseNoStatusReceived}, false}, {&CloseError{Code: CloseNormalClosure}, []int{CloseNoStatusReceived, CloseNormalClosure}, true}, {errors.New("hello"), []int{CloseNormalClosure}, false}, } func TestCloseError(t *testing.T) { for _, tt := range closeErrorTests { ok := IsCloseError(tt.err, tt.codes...) if ok != tt.ok { t.Errorf("IsCloseError(%#v, %#v) returned %v, want %v", tt.err, tt.codes, ok, tt.ok) } } } var unexpectedCloseErrorTests = []struct { err error codes []int ok bool }{ {&CloseError{Code: CloseNormalClosure}, []int{CloseNormalClosure}, false}, {&CloseError{Code: CloseNormalClosure}, []int{CloseNoStatusReceived}, true}, {&CloseError{Code: CloseNormalClosure}, []int{CloseNoStatusReceived, CloseNormalClosure}, false}, {errors.New("hello"), []int{CloseNormalClosure}, false}, } func TestUnexpectedCloseErrors(t *testing.T) { for _, tt := range unexpectedCloseErrorTests { ok := IsUnexpectedCloseError(tt.err, tt.codes...) if ok != tt.ok { t.Errorf("IsUnexpectedCloseError(%#v, %#v) returned %v, want %v", tt.err, tt.codes, ok, tt.ok) } } } type blockingWriter struct { c1, c2 chan struct{} } func (w blockingWriter) Write(p []byte) (int, error) { // Allow main to continue close(w.c1) // Wait for panic in main <-w.c2 return len(p), nil } func TestConcurrentWritePanic(t *testing.T) { w := blockingWriter{make(chan struct{}), make(chan struct{})} c := newConn(fakeNetConn{Reader: nil, Writer: w}, false, 1024, 1024) go func() { c.WriteMessage(TextMessage, []byte{}) }() // wait for goroutine to block in write. <-w.c1 defer func() { close(w.c2) if v := recover(); v != nil { return } }() c.WriteMessage(TextMessage, []byte{}) t.Fatal("should not get here") } type failingReader struct{} func (r failingReader) Read(p []byte) (int, error) { return 0, io.EOF } func TestFailedConnectionReadPanic(t *testing.T) { c := newConn(fakeNetConn{Reader: failingReader{}, Writer: nil}, false, 1024, 1024) defer func() { if v := recover(); v != nil { return } }() for i := 0; i < 20000; i++ { c.ReadMessage() } t.Fatal("should not get here") } func TestBufioReuse(t *testing.T) { brw := bufio.NewReadWriter(bufio.NewReader(nil), bufio.NewWriter(nil)) c := newConnBRW(nil, false, 0, 0, brw) if c.br != brw.Reader { t.Error("connection did not reuse bufio.Reader") } var wh writeHook brw.Writer.Reset(&wh) brw.WriteByte(0) brw.Flush() if &c.writeBuf[0] != &wh.p[0] { t.Error("connection did not reuse bufio.Writer") } brw = bufio.NewReadWriter(bufio.NewReaderSize(nil, 0), bufio.NewWriterSize(nil, 0)) c = newConnBRW(nil, false, 0, 0, brw) if c.br == brw.Reader { t.Error("connection used bufio.Reader with small size") } brw.Writer.Reset(&wh) brw.WriteByte(0) brw.Flush() if &c.writeBuf[0] != &wh.p[0] { t.Error("connection used bufio.Writer with small size") } } ================================================ FILE: src/github.com/gorilla/websocket/conn_write.go ================================================ // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build go1.8 package websocket import "net" func (c *Conn) writeBufs(bufs ...[]byte) error { b := net.Buffers(bufs) _, err := b.WriteTo(c.conn) return err } ================================================ FILE: src/github.com/gorilla/websocket/conn_write_legacy.go ================================================ // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.8 package websocket func (c *Conn) writeBufs(bufs ...[]byte) error { for _, buf := range bufs { if len(buf) > 0 { if _, err := c.conn.Write(buf); err != nil { return err } } } return nil } ================================================ FILE: src/github.com/gorilla/websocket/doc.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package websocket implements the WebSocket protocol defined in RFC 6455. // // Overview // // The Conn type represents a WebSocket connection. A server application calls // the Upgrader.Upgrade method from an HTTP request handler to get a *Conn: // // var upgrader = websocket.Upgrader{ // ReadBufferSize: 1024, // WriteBufferSize: 1024, // } // // func handler(w http.ResponseWriter, r *http.Request) { // conn, err := upgrader.Upgrade(w, r, nil) // if err != nil { // glog.Println(err) // return // } // ... Use conn to send and receive messages. // } // // Call the connection's WriteMessage and ReadMessage methods to send and // receive messages as a slice of bytes. This snippet of code shows how to echo // messages using these methods: // // for { // messageType, p, err := conn.ReadMessage() // if err != nil { // glog.Println(err) // return // } // if err := conn.WriteMessage(messageType, p); err != nil { // glog.Println(err) // return // } // } // // In above snippet of code, p is a []byte and messageType is an int with value // websocket.BinaryMessage or websocket.TextMessage. // // An application can also send and receive messages using the io.WriteCloser // and io.Reader interfaces. To send a message, call the connection NextWriter // method to get an io.WriteCloser, write the message to the writer and close // the writer when done. To receive a message, call the connection NextReader // method to get an io.Reader and read until io.EOF is returned. This snippet // shows how to echo messages using the NextWriter and NextReader methods: // // for { // messageType, r, err := conn.NextReader() // if err != nil { // return // } // w, err := conn.NextWriter(messageType) // if err != nil { // return err // } // if _, err := io.Copy(w, r); err != nil { // return err // } // if err := w.Close(); err != nil { // return err // } // } // // Data Messages // // The WebSocket protocol distinguishes between text and binary data messages. // Text messages are interpreted as UTF-8 encoded text. The interpretation of // binary messages is left to the application. // // This package uses the TextMessage and BinaryMessage integer constants to // identify the two data message types. The ReadMessage and NextReader methods // return the type of the received message. The messageType argument to the // WriteMessage and NextWriter methods specifies the type of a sent message. // // It is the application's responsibility to ensure that text messages are // valid UTF-8 encoded text. // // Control Messages // // The WebSocket protocol defines three types of control messages: close, ping // and pong. Call the connection WriteControl, WriteMessage or NextWriter // methods to send a control message to the peer. // // Connections handle received close messages by calling the handler function // set with the SetCloseHandler method and by returning a *CloseError from the // NextReader, ReadMessage or the message Read method. The default close // handler sends a close message to the peer. // // Connections handle received ping messages by calling the handler function // set with the SetPingHandler method. The default ping handler sends a pong // message to the peer. // // Connections handle received pong messages by calling the handler function // set with the SetPongHandler method. The default pong handler does nothing. // If an application sends ping messages, then the application should set a // pong handler to receive the corresponding pong. // // The control message handler functions are called from the NextReader, // ReadMessage and message reader Read methods. The default close and ping // handlers can block these methods for a short time when the handler writes to // the connection. // // The application must read the connection to process close, ping and pong // messages sent from the peer. If the application is not otherwise interested // in messages from the peer, then the application should start a goroutine to // read and discard messages from the peer. A simple example is: // // func readLoop(c *websocket.Conn) { // for { // if _, _, err := c.NextReader(); err != nil { // c.Close() // break // } // } // } // // Concurrency // // Connections support one concurrent reader and one concurrent writer. // // Applications are responsible for ensuring that no more than one goroutine // calls the write methods (NextWriter, SetWriteDeadline, WriteMessage, // WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and // that no more than one goroutine calls the read methods (NextReader, // SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler) // concurrently. // // The Close and WriteControl methods can be called concurrently with all other // methods. // // Origin Considerations // // Web browsers allow Javascript applications to open a WebSocket connection to // any host. It's up to the server to enforce an origin policy using the Origin // request header sent by the browser. // // The Upgrader calls the function specified in the CheckOrigin field to check // the origin. If the CheckOrigin function returns false, then the Upgrade // method fails the WebSocket handshake with HTTP status 403. // // If the CheckOrigin field is nil, then the Upgrader uses a safe default: fail // the handshake if the Origin request header is present and the Origin host is // not equal to the Host request header. // // The deprecated package-level Upgrade function does not perform origin // checking. The application is responsible for checking the Origin header // before calling the Upgrade function. // // Compression EXPERIMENTAL // // Per message compression extensions (RFC 7692) are experimentally supported // by this package in a limited capacity. Setting the EnableCompression option // to true in Dialer or Upgrader will attempt to negotiate per message deflate // support. // // var upgrader = websocket.Upgrader{ // EnableCompression: true, // } // // If compression was successfully negotiated with the connection's peer, any // message received in compressed form will be automatically decompressed. // All Read methods will return uncompressed bytes. // // Per message compression of messages written to a connection can be enabled // or disabled by calling the corresponding Conn method: // // conn.EnableWriteCompression(false) // // Currently this package does not support compression with "context takeover". // This means that messages must be compressed and decompressed in isolation, // without retaining sliding window or dictionary state across messages. For // more details refer to RFC 7692. // // Use of compression is experimental and may result in decreased performance. package websocket ================================================ FILE: src/github.com/gorilla/websocket/example_test.go ================================================ // Copyright 2015 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket_test import ( "log" "net/http" "testing" "github.com/gorilla/websocket" ) var ( c *websocket.Conn req *http.Request ) // The websocket.IsUnexpectedCloseError function is useful for identifying // application and protocol errors. // // This server application works with a client application running in the // browser. The client application does not explicitly close the websocket. The // only expected close message from the client has the code // websocket.CloseGoingAway. All other other close messages are likely the // result of an application or protocol error and are logged to aid debugging. func ExampleIsUnexpectedCloseError() { for { messageType, p, err := c.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) { log.Printf("error: %v, user-agent: %v", err, req.Header.Get("User-Agent")) } return } processMesage(messageType, p) } } func processMesage(mt int, p []byte) {} // TestX prevents godoc from showing this entire file in the example. Remove // this function when a second example is added. func TestX(t *testing.T) {} ================================================ FILE: src/github.com/gorilla/websocket/examples/autobahn/README.md ================================================ # Test Server This package contains a server for the [Autobahn WebSockets Test Suite](http://autobahn.ws/testsuite). To test the server, run go run server.go and start the client test driver wstest -m fuzzingclient -s fuzzingclient.json When the client completes, it writes a report to reports/clients/index.html. ================================================ FILE: src/github.com/gorilla/websocket/examples/autobahn/fuzzingclient.json ================================================ { "options": {"failByDrop": false}, "outdir": "./reports/clients", "servers": [ {"agent": "ReadAllWriteMessage", "url": "ws://localhost:9000/m", "options": {"version": 18}}, {"agent": "ReadAllWritePreparedMessage", "url": "ws://localhost:9000/p", "options": {"version": 18}}, {"agent": "ReadAllWrite", "url": "ws://localhost:9000/r", "options": {"version": 18}}, {"agent": "CopyFull", "url": "ws://localhost:9000/f", "options": {"version": 18}}, {"agent": "CopyWriterOnly", "url": "ws://localhost:9000/c", "options": {"version": 18}} ], "cases": ["*"], "exclude-cases": [], "exclude-agent-cases": {} } ================================================ FILE: src/github.com/gorilla/websocket/examples/autobahn/server.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Command server is a test server for the Autobahn WebSockets Test Suite. package main import ( "errors" "flag" "io" "log" "net/http" "time" "unicode/utf8" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{ ReadBufferSize: 4096, WriteBufferSize: 4096, EnableCompression: true, CheckOrigin: func(r *http.Request) bool { return true }, } // echoCopy echoes messages from the client using io.Copy. func echoCopy(w http.ResponseWriter, r *http.Request, writerOnly bool) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("Upgrade:", err) return } defer conn.Close() for { mt, r, err := conn.NextReader() if err != nil { if err != io.EOF { log.Println("NextReader:", err) } return } if mt == websocket.TextMessage { r = &validator{r: r} } w, err := conn.NextWriter(mt) if err != nil { log.Println("NextWriter:", err) return } if mt == websocket.TextMessage { r = &validator{r: r} } if writerOnly { _, err = io.Copy(struct{ io.Writer }{w}, r) } else { _, err = io.Copy(w, r) } if err != nil { if err == errInvalidUTF8 { conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseInvalidFramePayloadData, ""), time.Time{}) } log.Println("Copy:", err) return } err = w.Close() if err != nil { log.Println("Close:", err) return } } } func echoCopyWriterOnly(w http.ResponseWriter, r *http.Request) { echoCopy(w, r, true) } func echoCopyFull(w http.ResponseWriter, r *http.Request) { echoCopy(w, r, false) } // echoReadAll echoes messages from the client by reading the entire message // with ioutil.ReadAll. func echoReadAll(w http.ResponseWriter, r *http.Request, writeMessage, writePrepared bool) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("Upgrade:", err) return } defer conn.Close() for { mt, b, err := conn.ReadMessage() if err != nil { if err != io.EOF { log.Println("NextReader:", err) } return } if mt == websocket.TextMessage { if !utf8.Valid(b) { conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseInvalidFramePayloadData, ""), time.Time{}) log.Println("ReadAll: invalid utf8") } } if writeMessage { if !writePrepared { err = conn.WriteMessage(mt, b) if err != nil { log.Println("WriteMessage:", err) } } else { pm, err := websocket.NewPreparedMessage(mt, b) if err != nil { log.Println("NewPreparedMessage:", err) return } err = conn.WritePreparedMessage(pm) if err != nil { log.Println("WritePreparedMessage:", err) } } } else { w, err := conn.NextWriter(mt) if err != nil { log.Println("NextWriter:", err) return } if _, err := w.Write(b); err != nil { log.Println("Writer:", err) return } if err := w.Close(); err != nil { log.Println("Close:", err) return } } } } func echoReadAllWriter(w http.ResponseWriter, r *http.Request) { echoReadAll(w, r, false, false) } func echoReadAllWriteMessage(w http.ResponseWriter, r *http.Request) { echoReadAll(w, r, true, false) } func echoReadAllWritePreparedMessage(w http.ResponseWriter, r *http.Request) { echoReadAll(w, r, true, true) } func serveHome(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "Not found.", http.StatusNotFound) return } if r.Method != "GET" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") io.WriteString(w, "Echo Server") } var addr = flag.String("addr", ":9000", "http service address") func main() { flag.Parse() http.HandleFunc("/", serveHome) http.HandleFunc("/c", echoCopyWriterOnly) http.HandleFunc("/f", echoCopyFull) http.HandleFunc("/r", echoReadAllWriter) http.HandleFunc("/m", echoReadAllWriteMessage) http.HandleFunc("/p", echoReadAllWritePreparedMessage) err := http.ListenAndServe(*addr, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } type validator struct { state int x rune r io.Reader } var errInvalidUTF8 = errors.New("invalid utf8") func (r *validator) Read(p []byte) (int, error) { n, err := r.r.Read(p) state := r.state x := r.x for _, b := range p[:n] { state, x = decode(state, x, b) if state == utf8Reject { break } } r.state = state r.x = x if state == utf8Reject || (err == io.EOF && state != utf8Accept) { return n, errInvalidUTF8 } return n, err } // UTF-8 decoder from http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ // // Copyright (c) 2008-2009 Bjoern Hoehrmann // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. var utf8d = [...]byte{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7f 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9f 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // a0..bf 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // c0..df 0xa, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // e0..ef 0xb, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // f0..ff 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // s7..s8 } const ( utf8Accept = 0 utf8Reject = 1 ) func decode(state int, x rune, b byte) (int, rune) { t := utf8d[b] if state != utf8Accept { x = rune(b&0x3f) | (x << 6) } else { x = rune((0xff >> t) & b) } state = int(utf8d[256+state*16+int(t)]) return state, x } ================================================ FILE: src/github.com/gorilla/websocket/examples/chat/README.md ================================================ # Chat Example This application shows how to use the [websocket](https://github.com/gorilla/websocket) package to implement a simple web chat application. ## Running the example The example requires a working Go development environment. The [Getting Started](http://golang.org/doc/install) page describes how to install the development environment. Once you have Go up and running, you can download, build and run the example using the following commands. $ go get github.com/gorilla/websocket $ cd `go list -f '{{.Dir}}' github.com/gorilla/websocket/examples/chat` $ go run *.go To use the chat example, open http://localhost:8080/ in your browser. ## Server The server application defines two types, `Client` and `Hub`. The server creates an instance of the `Client` type for each websocket connection. A `Client` acts as an intermediary between the websocket connection and a single instance of the `Hub` type. The `Hub` maintains a set of registered clients and broadcasts messages to the clients. The application runs one goroutine for the `Hub` and two goroutines for each `Client`. The goroutines communicate with each other using channels. The `Hub` has channels for registering clients, unregistering clients and broadcasting messages. A `Client` has a buffered channel of outbound messages. One of the client's goroutines reads messages from this channel and writes the messages to the websocket. The other client goroutine reads messages from the websocket and sends them to the hub. ### Hub The code for the `Hub` type is in [hub.go](https://github.com/gorilla/websocket/blob/master/examples/chat/hub.go). The application's `main` function starts the hub's `run` method as a goroutine. Clients send requests to the hub using the `register`, `unregister` and `broadcast` channels. The hub registers clients by adding the client pointer as a key in the `clients` map. The map value is always true. The unregister code is a little more complicated. In addition to deleting the client pointer from the `clients` map, the hub closes the clients's `send` channel to signal the client that no more messages will be sent to the client. The hub handles messages by looping over the registered clients and sending the message to the client's `send` channel. If the client's `send` buffer is full, then the hub assumes that the client is dead or stuck. In this case, the hub unregisters the client and closes the websocket. ### Client The code for the `Client` type is in [client.go](https://github.com/gorilla/websocket/blob/master/examples/chat/client.go). The `serveWs` function is registered by the application's `main` function as an HTTP handler. The handler upgrades the HTTP connection to the WebSocket protocol, creates a client, registers the client with the hub and schedules the client to be unregistered using a defer statement. Next, the HTTP handler starts the client's `writePump` method as a goroutine. This method transfers messages from the client's send channel to the websocket connection. The writer method exits when the channel is closed by the hub or there's an error writing to the websocket connection. Finally, the HTTP handler calls the client's `readPump` method. This method transfers inbound messages from the websocket to the hub. WebSocket connections [support one concurrent reader and one concurrent writer](https://godoc.org/github.com/gorilla/websocket#hdr-Concurrency). The application ensures that these concurrency requirements are met by executing all reads from the `readPump` goroutine and all writes from the `writePump` goroutine. To improve efficiency under high load, the `writePump` function coalesces pending chat messages in the `send` channel to a single WebSocket message. This reduces the number of system calls and the amount of data sent over the network. ## Frontend The frontend code is in [home.html](https://github.com/gorilla/websocket/blob/master/examples/chat/home.html). On document load, the script checks for websocket functionality in the browser. If websocket functionality is available, then the script opens a connection to the server and registers a callback to handle messages from the server. The callback appends the message to the chat log using the appendLog function. To allow the user to manually scroll through the chat log without interruption from new messages, the `appendLog` function checks the scroll position before adding new content. If the chat log is scrolled to the bottom, then the function scrolls new content into view after adding the content. Otherwise, the scroll position is not changed. The form handler writes the user input to the websocket and clears the input field. ================================================ FILE: src/github.com/gorilla/websocket/examples/chat/client.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bytes" "log" "net/http" "time" "github.com/gorilla/websocket" ) const ( // Time allowed to write a message to the peer. writeWait = 10 * time.Second // Time allowed to read the next pong message from the peer. pongWait = 60 * time.Second // Send pings to peer with this period. Must be less than pongWait. pingPeriod = (pongWait * 9) / 10 // Maximum message size allowed from peer. maxMessageSize = 512 ) var ( newline = []byte{'\n'} space = []byte{' '} ) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } // Client is a middleman between the websocket connection and the hub. type Client struct { hub *Hub // The websocket connection. conn *websocket.Conn // Buffered channel of outbound messages. send chan []byte } // readPump pumps messages from the websocket connection to the hub. // // The application runs readPump in a per-connection goroutine. The application // ensures that there is at most one reader on a connection by executing all // reads from this goroutine. func (c *Client) readPump() { defer func() { c.hub.unregister <- c c.conn.Close() }() c.conn.SetReadLimit(maxMessageSize) c.conn.SetReadDeadline(time.Now().Add(pongWait)) c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, message, err := c.conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { log.Printf("error: %v", err) } break } message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1)) c.hub.broadcast <- message } } // writePump pumps messages from the hub to the websocket connection. // // A goroutine running writePump is started for each connection. The // application ensures that there is at most one writer to a connection by // executing all writes from this goroutine. func (c *Client) writePump() { ticker := time.NewTicker(pingPeriod) defer func() { ticker.Stop() c.conn.Close() }() for { select { case message, ok := <-c.send: c.conn.SetWriteDeadline(time.Now().Add(writeWait)) if !ok { // The hub closed the channel. c.conn.WriteMessage(websocket.CloseMessage, []byte{}) return } w, err := c.conn.NextWriter(websocket.TextMessage) if err != nil { return } w.Write(message) // Add queued chat messages to the current websocket message. n := len(c.send) for i := 0; i < n; i++ { w.Write(newline) w.Write(<-c.send) } if err := w.Close(); err != nil { return } case <-ticker.C: c.conn.SetWriteDeadline(time.Now().Add(writeWait)) if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil { return } } } } // serveWs handles websocket requests from the peer. func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println(err) return } client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)} client.hub.register <- client // Allow collection of memory referenced by the caller by doing all work in // new goroutines. go client.writePump() go client.readPump() } ================================================ FILE: src/github.com/gorilla/websocket/examples/chat/home.html ================================================ Chat Example
================================================ FILE: src/github.com/gorilla/websocket/examples/chat/hub.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main // hub maintains the set of active clients and broadcasts messages to the // clients. type Hub struct { // Registered clients. clients map[*Client]bool // Inbound messages from the clients. broadcast chan []byte // Register requests from the clients. register chan *Client // Unregister requests from clients. unregister chan *Client } func newHub() *Hub { return &Hub{ broadcast: make(chan []byte), register: make(chan *Client), unregister: make(chan *Client), clients: make(map[*Client]bool), } } func (h *Hub) run() { for { select { case client := <-h.register: h.clients[client] = true case client := <-h.unregister: if _, ok := h.clients[client]; ok { delete(h.clients, client) close(client.send) } case message := <-h.broadcast: for client := range h.clients { select { case client.send <- message: default: close(client.send) delete(h.clients, client) } } } } } ================================================ FILE: src/github.com/gorilla/websocket/examples/chat/main.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "flag" "log" "net/http" ) var addr = flag.String("addr", ":8080", "http service address") func serveHome(w http.ResponseWriter, r *http.Request) { log.Println(r.URL) if r.URL.Path != "/" { http.Error(w, "Not found", http.StatusNotFound) return } if r.Method != "GET" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } http.ServeFile(w, r, "home.html") } func main() { flag.Parse() hub := newHub() go hub.run() http.HandleFunc("/", serveHome) http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { serveWs(hub, w, r) }) err := http.ListenAndServe(*addr, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } ================================================ FILE: src/github.com/gorilla/websocket/examples/command/README.md ================================================ # Command example This example connects a websocket connection to stdin and stdout of a command. Received messages are written to stdin followed by a `\n`. Each line read from standard out is sent as a message to the client. $ go get github.com/gorilla/websocket $ cd `go list -f '{{.Dir}}' github.com/gorilla/websocket/examples/command` $ go run main.go # Open http://localhost:8080/ . Try the following commands. # Echo sent messages to the output area. $ go run main.go cat # Run a shell.Try sending "ls" and "cat main.go". $ go run main.go sh ================================================ FILE: src/github.com/gorilla/websocket/examples/command/home.html ================================================ Command Example
================================================ FILE: src/github.com/gorilla/websocket/examples/command/main.go ================================================ // Copyright 2015 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "bufio" "flag" "io" "log" "net/http" "os" "os/exec" "time" "github.com/gorilla/websocket" ) var ( addr = flag.String("addr", "127.0.0.1:8080", "http service address") cmdPath string ) const ( // Time allowed to write a message to the peer. writeWait = 10 * time.Second // Maximum message size allowed from peer. maxMessageSize = 8192 // Time allowed to read the next pong message from the peer. pongWait = 60 * time.Second // Send pings to peer with this period. Must be less than pongWait. pingPeriod = (pongWait * 9) / 10 // Time to wait before force close on connection. closeGracePeriod = 10 * time.Second ) func pumpStdin(ws *websocket.Conn, w io.Writer) { defer ws.Close() ws.SetReadLimit(maxMessageSize) ws.SetReadDeadline(time.Now().Add(pongWait)) ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, message, err := ws.ReadMessage() if err != nil { break } message = append(message, '\n') if _, err := w.Write(message); err != nil { break } } } func pumpStdout(ws *websocket.Conn, r io.Reader, done chan struct{}) { defer func() { }() s := bufio.NewScanner(r) for s.Scan() { ws.SetWriteDeadline(time.Now().Add(writeWait)) if err := ws.WriteMessage(websocket.TextMessage, s.Bytes()); err != nil { ws.Close() break } } if s.Err() != nil { log.Println("scan:", s.Err()) } close(done) ws.SetWriteDeadline(time.Now().Add(writeWait)) ws.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) time.Sleep(closeGracePeriod) ws.Close() } func ping(ws *websocket.Conn, done chan struct{}) { ticker := time.NewTicker(pingPeriod) defer ticker.Stop() for { select { case <-ticker.C: if err := ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(writeWait)); err != nil { log.Println("ping:", err) } case <-done: return } } } func internalError(ws *websocket.Conn, msg string, err error) { log.Println(msg, err) ws.WriteMessage(websocket.TextMessage, []byte("Internal server error.")) } var upgrader = websocket.Upgrader{} func serveWs(w http.ResponseWriter, r *http.Request) { ws, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("upgrade:", err) return } defer ws.Close() outr, outw, err := os.Pipe() if err != nil { internalError(ws, "stdout:", err) return } defer outr.Close() defer outw.Close() inr, inw, err := os.Pipe() if err != nil { internalError(ws, "stdin:", err) return } defer inr.Close() defer inw.Close() proc, err := os.StartProcess(cmdPath, flag.Args(), &os.ProcAttr{ Files: []*os.File{inr, outw, outw}, }) if err != nil { internalError(ws, "start:", err) return } inr.Close() outw.Close() stdoutDone := make(chan struct{}) go pumpStdout(ws, outr, stdoutDone) go ping(ws, stdoutDone) pumpStdin(ws, inw) // Some commands will exit when stdin is closed. inw.Close() // Other commands need a bonk on the head. if err := proc.Signal(os.Interrupt); err != nil { log.Println("inter:", err) } select { case <-stdoutDone: case <-time.After(time.Second): // A bigger bonk on the head. if err := proc.Signal(os.Kill); err != nil { log.Println("term:", err) } <-stdoutDone } if _, err := proc.Wait(); err != nil { log.Println("wait:", err) } } func serveHome(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "Not found", http.StatusNotFound) return } if r.Method != "GET" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } http.ServeFile(w, r, "home.html") } func main() { flag.Parse() if len(flag.Args()) < 1 { log.Fatal("must specify at least one argument") } var err error cmdPath, err = exec.LookPath(flag.Args()[0]) if err != nil { log.Fatal(err) } http.HandleFunc("/", serveHome) http.HandleFunc("/ws", serveWs) log.Fatal(http.ListenAndServe(*addr, nil)) } ================================================ FILE: src/github.com/gorilla/websocket/examples/echo/README.md ================================================ # Client and server example This example shows a simple client and server. The server echoes messages sent to it. The client sends a message every second and prints all messages received. To run the example, start the server: $ go run server.go Next, start the client: $ go run client.go The server includes a simple web client. To use the client, open http://127.0.0.1:8080 in the browser and follow the instructions on the page. ================================================ FILE: src/github.com/gorilla/websocket/examples/echo/client.go ================================================ // Copyright 2015 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package main import ( "flag" "log" "net/url" "os" "os/signal" "time" "github.com/gorilla/websocket" ) var addr = flag.String("addr", "localhost:8080", "http service address") func main() { flag.Parse() log.SetFlags(0) interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt) u := url.URL{Scheme: "ws", Host: *addr, Path: "/echo"} log.Printf("connecting to %s", u.String()) c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { log.Fatal("dial:", err) } defer c.Close() done := make(chan struct{}) go func() { defer close(done) for { _, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) return } log.Printf("recv: %s", message) } }() ticker := time.NewTicker(time.Second) defer ticker.Stop() for { select { case <-done: return case t := <-ticker.C: err := c.WriteMessage(websocket.TextMessage, []byte(t.String())) if err != nil { log.Println("write:", err) return } case <-interrupt: log.Println("interrupt") // Cleanly close the connection by sending a close message and then // waiting (with timeout) for the server to close the connection. err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) if err != nil { log.Println("write close:", err) return } select { case <-done: case <-time.After(time.Second): } return } } } ================================================ FILE: src/github.com/gorilla/websocket/examples/echo/server.go ================================================ // Copyright 2015 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package main import ( "flag" "html/template" "log" "net/http" "github.com/gorilla/websocket" ) var addr = flag.String("addr", "localhost:8080", "http service address") var upgrader = websocket.Upgrader{} // use default options func echo(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print("upgrade:", err) return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) break } log.Printf("recv: %s", message) err = c.WriteMessage(mt, message) if err != nil { log.Println("write:", err) break } } } func home(w http.ResponseWriter, r *http.Request) { homeTemplate.Execute(w, "ws://"+r.Host+"/echo") } func main() { flag.Parse() log.SetFlags(0) http.HandleFunc("/echo", echo) http.HandleFunc("/", home) log.Fatal(http.ListenAndServe(*addr, nil)) } var homeTemplate = template.Must(template.New("").Parse(`

Click "Open" to create a connection to the server, "Send" to send a message to the server and "Close" to close the connection. You can change the message and send multiple times.

`)) ================================================ FILE: src/github.com/gorilla/websocket/examples/filewatch/README.md ================================================ # File Watch example. This example sends a file to the browser client for display whenever the file is modified. $ go get github.com/gorilla/websocket $ cd `go list -f '{{.Dir}}' github.com/gorilla/websocket/examples/filewatch` $ go run main.go # Open http://localhost:8080/ . # Modify the file to see it update in the browser. ================================================ FILE: src/github.com/gorilla/websocket/examples/filewatch/main.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "flag" "html/template" "io/ioutil" "log" "net/http" "os" "strconv" "time" "github.com/gorilla/websocket" ) const ( // Time allowed to write the file to the client. writeWait = 10 * time.Second // Time allowed to read the next pong message from the client. pongWait = 60 * time.Second // Send pings to client with this period. Must be less than pongWait. pingPeriod = (pongWait * 9) / 10 // Poll file for changes with this period. filePeriod = 10 * time.Second ) var ( addr = flag.String("addr", ":8080", "http service address") homeTempl = template.Must(template.New("").Parse(homeHTML)) filename string upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } ) func readFileIfModified(lastMod time.Time) ([]byte, time.Time, error) { fi, err := os.Stat(filename) if err != nil { return nil, lastMod, err } if !fi.ModTime().After(lastMod) { return nil, lastMod, nil } p, err := ioutil.ReadFile(filename) if err != nil { return nil, fi.ModTime(), err } return p, fi.ModTime(), nil } func reader(ws *websocket.Conn) { defer ws.Close() ws.SetReadLimit(512) ws.SetReadDeadline(time.Now().Add(pongWait)) ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, _, err := ws.ReadMessage() if err != nil { break } } } func writer(ws *websocket.Conn, lastMod time.Time) { lastError := "" pingTicker := time.NewTicker(pingPeriod) fileTicker := time.NewTicker(filePeriod) defer func() { pingTicker.Stop() fileTicker.Stop() ws.Close() }() for { select { case <-fileTicker.C: var p []byte var err error p, lastMod, err = readFileIfModified(lastMod) if err != nil { if s := err.Error(); s != lastError { lastError = s p = []byte(lastError) } } else { lastError = "" } if p != nil { ws.SetWriteDeadline(time.Now().Add(writeWait)) if err := ws.WriteMessage(websocket.TextMessage, p); err != nil { return } } case <-pingTicker.C: ws.SetWriteDeadline(time.Now().Add(writeWait)) if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil { return } } } } func serveWs(w http.ResponseWriter, r *http.Request) { ws, err := upgrader.Upgrade(w, r, nil) if err != nil { if _, ok := err.(websocket.HandshakeError); !ok { log.Println(err) } return } var lastMod time.Time if n, err := strconv.ParseInt(r.FormValue("lastMod"), 16, 64); err == nil { lastMod = time.Unix(0, n) } go writer(ws, lastMod) reader(ws) } func serveHome(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "Not found", http.StatusNotFound) return } if r.Method != "GET" { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") p, lastMod, err := readFileIfModified(time.Time{}) if err != nil { p = []byte(err.Error()) lastMod = time.Unix(0, 0) } var v = struct { Host string Data string LastMod string }{ r.Host, string(p), strconv.FormatInt(lastMod.UnixNano(), 16), } homeTempl.Execute(w, &v) } func main() { flag.Parse() if flag.NArg() != 1 { log.Fatal("filename not specified") } filename = flag.Args()[0] http.HandleFunc("/", serveHome) http.HandleFunc("/ws", serveWs) if err := http.ListenAndServe(*addr, nil); err != nil { log.Fatal(err) } } const homeHTML = ` WebSocket Example
{{.Data}}
` ================================================ FILE: src/github.com/gorilla/websocket/json.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "encoding/json" "io" ) // WriteJSON writes the JSON encoding of v as a message. // // Deprecated: Use c.WriteJSON instead. func WriteJSON(c *Conn, v interface{}) error { return c.WriteJSON(v) } // WriteJSON writes the JSON encoding of v as a message. // // See the documentation for encoding/json Marshal for details about the // conversion of Go values to JSON. func (c *Conn) WriteJSON(v interface{}) error { w, err := c.NextWriter(TextMessage) if err != nil { return err } err1 := json.NewEncoder(w).Encode(v) err2 := w.Close() if err1 != nil { return err1 } return err2 } // ReadJSON reads the next JSON-encoded message from the connection and stores // it in the value pointed to by v. // // Deprecated: Use c.ReadJSON instead. func ReadJSON(c *Conn, v interface{}) error { return c.ReadJSON(v) } // ReadJSON reads the next JSON-encoded message from the connection and stores // it in the value pointed to by v. // // See the documentation for the encoding/json Unmarshal function for details // about the conversion of JSON to a Go value. func (c *Conn) ReadJSON(v interface{}) error { _, r, err := c.NextReader() if err != nil { return err } err = json.NewDecoder(r).Decode(v) if err == io.EOF { // One value is expected in the message. err = io.ErrUnexpectedEOF } return err } ================================================ FILE: src/github.com/gorilla/websocket/json_test.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bytes" "encoding/json" "io" "reflect" "testing" ) func TestJSON(t *testing.T) { var buf bytes.Buffer c := fakeNetConn{&buf, &buf} wc := newConn(c, true, 1024, 1024) rc := newConn(c, false, 1024, 1024) var actual, expect struct { A int B string } expect.A = 1 expect.B = "hello" if err := wc.WriteJSON(&expect); err != nil { t.Fatal("write", err) } if err := rc.ReadJSON(&actual); err != nil { t.Fatal("read", err) } if !reflect.DeepEqual(&actual, &expect) { t.Fatal("equal", actual, expect) } } func TestPartialJSONRead(t *testing.T) { var buf bytes.Buffer c := fakeNetConn{&buf, &buf} wc := newConn(c, true, 1024, 1024) rc := newConn(c, false, 1024, 1024) var v struct { A int B string } v.A = 1 v.B = "hello" messageCount := 0 // Partial JSON values. data, err := json.Marshal(v) if err != nil { t.Fatal(err) } for i := len(data) - 1; i >= 0; i-- { if err := wc.WriteMessage(TextMessage, data[:i]); err != nil { t.Fatal(err) } messageCount++ } // Whitespace. if err := wc.WriteMessage(TextMessage, []byte(" ")); err != nil { t.Fatal(err) } messageCount++ // Close. if err := wc.WriteMessage(CloseMessage, FormatCloseMessage(CloseNormalClosure, "")); err != nil { t.Fatal(err) } for i := 0; i < messageCount; i++ { err := rc.ReadJSON(&v) if err != io.ErrUnexpectedEOF { t.Error("read", i, err) } } err = rc.ReadJSON(&v) if _, ok := err.(*CloseError); !ok { t.Error("final", err) } } func TestDeprecatedJSON(t *testing.T) { var buf bytes.Buffer c := fakeNetConn{&buf, &buf} wc := newConn(c, true, 1024, 1024) rc := newConn(c, false, 1024, 1024) var actual, expect struct { A int B string } expect.A = 1 expect.B = "hello" if err := WriteJSON(wc, &expect); err != nil { t.Fatal("write", err) } if err := ReadJSON(rc, &actual); err != nil { t.Fatal("read", err) } if !reflect.DeepEqual(&actual, &expect) { t.Fatal("equal", actual, expect) } } ================================================ FILE: src/github.com/gorilla/websocket/mask.go ================================================ // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of // this source code is governed by a BSD-style license that can be found in the // LICENSE file. // +build !appengine package websocket import "unsafe" const wordSize = int(unsafe.Sizeof(uintptr(0))) func maskBytes(key [4]byte, pos int, b []byte) int { // Mask one byte at a time for small buffers. if len(b) < 2*wordSize { for i := range b { b[i] ^= key[pos&3] pos++ } return pos & 3 } // Mask one byte at a time to word boundary. if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 { n = wordSize - n for i := range b[:n] { b[i] ^= key[pos&3] pos++ } b = b[n:] } // Create aligned word size key. var k [wordSize]byte for i := range k { k[i] = key[(pos+i)&3] } kw := *(*uintptr)(unsafe.Pointer(&k)) // Mask one word at a time. n := (len(b) / wordSize) * wordSize for i := 0; i < n; i += wordSize { *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw } // Mask one byte at a time for remaining bytes. b = b[n:] for i := range b { b[i] ^= key[pos&3] pos++ } return pos & 3 } ================================================ FILE: src/github.com/gorilla/websocket/mask_safe.go ================================================ // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of // this source code is governed by a BSD-style license that can be found in the // LICENSE file. // +build appengine package websocket func maskBytes(key [4]byte, pos int, b []byte) int { for i := range b { b[i] ^= key[pos&3] pos++ } return pos & 3 } ================================================ FILE: src/github.com/gorilla/websocket/mask_test.go ================================================ // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of // this source code is governed by a BSD-style license that can be found in the // LICENSE file. // Require 1.7 for sub-bencmarks // +build go1.7,!appengine package websocket import ( "fmt" "testing" ) func maskBytesByByte(key [4]byte, pos int, b []byte) int { for i := range b { b[i] ^= key[pos&3] pos++ } return pos & 3 } func notzero(b []byte) int { for i := range b { if b[i] != 0 { return i } } return -1 } func TestMaskBytes(t *testing.T) { key := [4]byte{1, 2, 3, 4} for size := 1; size <= 1024; size++ { for align := 0; align < wordSize; align++ { for pos := 0; pos < 4; pos++ { b := make([]byte, size+align)[align:] maskBytes(key, pos, b) maskBytesByByte(key, pos, b) if i := notzero(b); i >= 0 { t.Errorf("size:%d, align:%d, pos:%d, offset:%d", size, align, pos, i) } } } } } func BenchmarkMaskBytes(b *testing.B) { for _, size := range []int{2, 4, 8, 16, 32, 512, 1024} { b.Run(fmt.Sprintf("size-%d", size), func(b *testing.B) { for _, align := range []int{wordSize / 2} { b.Run(fmt.Sprintf("align-%d", align), func(b *testing.B) { for _, fn := range []struct { name string fn func(key [4]byte, pos int, b []byte) int }{ {"byte", maskBytesByByte}, {"word", maskBytes}, } { b.Run(fn.name, func(b *testing.B) { key := newMaskKey() data := make([]byte, size+align)[align:] for i := 0; i < b.N; i++ { fn.fn(key, 0, data) } b.SetBytes(int64(len(data))) }) } }) } }) } } ================================================ FILE: src/github.com/gorilla/websocket/prepared.go ================================================ // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bytes" "net" "sync" "time" ) // PreparedMessage caches on the wire representations of a message payload. // Use PreparedMessage to efficiently send a message payload to multiple // connections. PreparedMessage is especially useful when compression is used // because the CPU and memory expensive compression operation can be executed // once for a given set of compression options. type PreparedMessage struct { messageType int data []byte err error mu sync.Mutex frames map[prepareKey]*preparedFrame } // prepareKey defines a unique set of options to cache prepared frames in PreparedMessage. type prepareKey struct { isServer bool compress bool compressionLevel int } // preparedFrame contains data in wire representation. type preparedFrame struct { once sync.Once data []byte } // NewPreparedMessage returns an initialized PreparedMessage. You can then send // it to connection using WritePreparedMessage method. Valid wire // representation will be calculated lazily only once for a set of current // connection options. func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) { pm := &PreparedMessage{ messageType: messageType, frames: make(map[prepareKey]*preparedFrame), data: data, } // Prepare a plain server frame. _, frameData, err := pm.frame(prepareKey{isServer: true, compress: false}) if err != nil { return nil, err } // To protect against caller modifying the data argument, remember the data // copied to the plain server frame. pm.data = frameData[len(frameData)-len(data):] return pm, nil } func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) { pm.mu.Lock() frame, ok := pm.frames[key] if !ok { frame = &preparedFrame{} pm.frames[key] = frame } pm.mu.Unlock() var err error frame.once.Do(func() { // Prepare a frame using a 'fake' connection. // TODO: Refactor code in conn.go to allow more direct construction of // the frame. mu := make(chan bool, 1) mu <- true var nc prepareConn c := &Conn{ conn: &nc, mu: mu, isServer: key.isServer, compressionLevel: key.compressionLevel, enableWriteCompression: true, writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize), } if key.compress { c.newCompressionWriter = compressNoContextTakeover } err = c.WriteMessage(pm.messageType, pm.data) frame.data = nc.buf.Bytes() }) return pm.messageType, frame.data, err } type prepareConn struct { buf bytes.Buffer net.Conn } func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) } func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil } ================================================ FILE: src/github.com/gorilla/websocket/prepared_test.go ================================================ // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bytes" "compress/flate" "math/rand" "testing" ) var preparedMessageTests = []struct { messageType int isServer bool enableWriteCompression bool compressionLevel int }{ // Server {TextMessage, true, false, flate.BestSpeed}, {TextMessage, true, true, flate.BestSpeed}, {TextMessage, true, true, flate.BestCompression}, {PingMessage, true, false, flate.BestSpeed}, {PingMessage, true, true, flate.BestSpeed}, // Client {TextMessage, false, false, flate.BestSpeed}, {TextMessage, false, true, flate.BestSpeed}, {TextMessage, false, true, flate.BestCompression}, {PingMessage, false, false, flate.BestSpeed}, {PingMessage, false, true, flate.BestSpeed}, } func TestPreparedMessage(t *testing.T) { for _, tt := range preparedMessageTests { var data = []byte("this is a test") var buf bytes.Buffer c := newConn(fakeNetConn{Reader: nil, Writer: &buf}, tt.isServer, 1024, 1024) if tt.enableWriteCompression { c.newCompressionWriter = compressNoContextTakeover } c.SetCompressionLevel(tt.compressionLevel) // Seed random number generator for consistent frame mask. rand.Seed(1234) if err := c.WriteMessage(tt.messageType, data); err != nil { t.Fatal(err) } want := buf.String() pm, err := NewPreparedMessage(tt.messageType, data) if err != nil { t.Fatal(err) } // Scribble on data to ensure that NewPreparedMessage takes a snapshot. copy(data, "hello world") // Seed random number generator for consistent frame mask. rand.Seed(1234) buf.Reset() if err := c.WritePreparedMessage(pm); err != nil { t.Fatal(err) } got := buf.String() if got != want { t.Errorf("write message != prepared message for %+v", tt) } } } ================================================ FILE: src/github.com/gorilla/websocket/proxy.go ================================================ // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bufio" "encoding/base64" "errors" "net" "net/http" "net/url" "strings" ) type netDialerFunc func(netowrk, addr string) (net.Conn, error) func (fn netDialerFunc) Dial(network, addr string) (net.Conn, error) { return fn(network, addr) } func init() { proxy_RegisterDialerType("http", func(proxyURL *url.URL, forwardDialer proxy_Dialer) (proxy_Dialer, error) { return &httpProxyDialer{proxyURL: proxyURL, fowardDial: forwardDialer.Dial}, nil }) } type httpProxyDialer struct { proxyURL *url.URL fowardDial func(network, addr string) (net.Conn, error) } func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) { hostPort, _ := hostPortNoPort(hpd.proxyURL) conn, err := hpd.fowardDial(network, hostPort) if err != nil { return nil, err } connectHeader := make(http.Header) if user := hpd.proxyURL.User; user != nil { proxyUser := user.Username() if proxyPassword, passwordSet := user.Password(); passwordSet { credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword)) connectHeader.Set("Proxy-Authorization", "Basic "+credential) } } connectReq := &http.Request{ Method: "CONNECT", URL: &url.URL{Opaque: addr}, Host: addr, Header: connectHeader, } if err := connectReq.Write(conn); err != nil { conn.Close() return nil, err } // Read response. It's OK to use and discard buffered reader here becaue // the remote server does not speak until spoken to. br := bufio.NewReader(conn) resp, err := http.ReadResponse(br, connectReq) if err != nil { conn.Close() return nil, err } if resp.StatusCode != 200 { conn.Close() f := strings.SplitN(resp.Status, " ", 2) return nil, errors.New(f[1]) } return conn, nil } ================================================ FILE: src/github.com/gorilla/websocket/server.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "bufio" "errors" "net" "net/http" "net/url" "strings" "time" ) // HandshakeError describes an error with the handshake from the peer. type HandshakeError struct { message string } func (e HandshakeError) Error() string { return e.message } // Upgrader specifies parameters for upgrading an HTTP connection to a // WebSocket connection. type Upgrader struct { // HandshakeTimeout specifies the duration for the handshake to complete. HandshakeTimeout time.Duration // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer // size is zero, then buffers allocated by the HTTP server are used. The // I/O buffer sizes do not limit the size of the messages that can be sent // or received. ReadBufferSize, WriteBufferSize int // Subprotocols specifies the server's supported protocols in order of // preference. If this field is set, then the Upgrade method negotiates a // subprotocol by selecting the first match in this list with a protocol // requested by the client. Subprotocols []string // Error specifies the function for generating HTTP error responses. If Error // is nil, then http.Error is used to generate the HTTP response. Error func(w http.ResponseWriter, r *http.Request, status int, reason error) // CheckOrigin returns true if the request Origin header is acceptable. If // CheckOrigin is nil, then a safe default is used: return false if the // Origin request header is present and the origin host is not equal to // request Host header. // // A CheckOrigin function should carefully validate the request origin to // prevent cross-site request forgery. CheckOrigin func(r *http.Request) bool // EnableCompression specify if the server should attempt to negotiate per // message compression (RFC 7692). Setting this value to true does not // guarantee that compression will be supported. Currently only "no context // takeover" modes are supported. EnableCompression bool } func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) { err := HandshakeError{reason} if u.Error != nil { u.Error(w, r, status, err) } else { w.Header().Set("Sec-Websocket-Version", "13") http.Error(w, http.StatusText(status), status) } return nil, err } // checkSameOrigin returns true if the origin is not set or is equal to the request host. func checkSameOrigin(r *http.Request) bool { origin := r.Header["Origin"] if len(origin) == 0 { return true } u, err := url.Parse(origin[0]) if err != nil { return false } return equalASCIIFold(u.Host, r.Host) } func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string { if u.Subprotocols != nil { clientProtocols := Subprotocols(r) for _, serverProtocol := range u.Subprotocols { for _, clientProtocol := range clientProtocols { if clientProtocol == serverProtocol { return clientProtocol } } } } else if responseHeader != nil { return responseHeader.Get("Sec-Websocket-Protocol") } return "" } // Upgrade upgrades the HTTP server connection to the WebSocket protocol. // // The responseHeader is included in the response to the client's upgrade // request. Use the responseHeader to specify cookies (Set-Cookie) and the // application negotiated subprotocol (Sec-Websocket-Protocol). // // If the upgrade fails, then Upgrade replies to the client with an HTTP error // response. func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) { const badHandshake = "websocket: the client is not using the websocket protocol: " if !tokenListContainsValue(r.Header, "Connection", "upgrade") { return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'upgrade' token not found in 'Connection' header") } if !tokenListContainsValue(r.Header, "Upgrade", "websocket") { return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header") } if r.Method != "GET" { return u.returnError(w, r, http.StatusMethodNotAllowed, badHandshake+"request method is not GET") } if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") { return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header") } if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok { return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-Websocket-Extensions' headers are unsupported") } checkOrigin := u.CheckOrigin if checkOrigin == nil { checkOrigin = checkSameOrigin } if !checkOrigin(r) { return u.returnError(w, r, http.StatusForbidden, "websocket: request origin not allowed by Upgrader.CheckOrigin") } challengeKey := r.Header.Get("Sec-Websocket-Key") if challengeKey == "" { return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: `Sec-Websocket-Key' header is missing or blank") } subprotocol := u.selectSubprotocol(r, responseHeader) // Negotiate PMCE var compress bool if u.EnableCompression { for _, ext := range parseExtensions(r.Header) { if ext[""] != "permessage-deflate" { continue } compress = true break } } var ( netConn net.Conn err error ) h, ok := w.(http.Hijacker) if !ok { return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker") } var brw *bufio.ReadWriter netConn, brw, err = h.Hijack() if err != nil { return u.returnError(w, r, http.StatusInternalServerError, err.Error()) } if brw.Reader.Buffered() > 0 { netConn.Close() return nil, errors.New("websocket: client sent data before handshake is complete") } c := newConnBRW(netConn, true, u.ReadBufferSize, u.WriteBufferSize, brw) c.subprotocol = subprotocol if compress { c.newCompressionWriter = compressNoContextTakeover c.newDecompressionReader = decompressNoContextTakeover } p := c.writeBuf[:0] p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...) p = append(p, computeAcceptKey(challengeKey)...) p = append(p, "\r\n"...) if c.subprotocol != "" { p = append(p, "Sec-Websocket-Protocol: "...) p = append(p, c.subprotocol...) p = append(p, "\r\n"...) } if compress { p = append(p, "Sec-Websocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...) } for k, vs := range responseHeader { if k == "Sec-Websocket-Protocol" { continue } for _, v := range vs { p = append(p, k...) p = append(p, ": "...) for i := 0; i < len(v); i++ { b := v[i] if b <= 31 { // prevent response splitting. b = ' ' } p = append(p, b) } p = append(p, "\r\n"...) } } p = append(p, "\r\n"...) // Clear deadlines set by HTTP server. netConn.SetDeadline(time.Time{}) if u.HandshakeTimeout > 0 { netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout)) } if _, err = netConn.Write(p); err != nil { netConn.Close() return nil, err } if u.HandshakeTimeout > 0 { netConn.SetWriteDeadline(time.Time{}) } return c, nil } // Upgrade upgrades the HTTP server connection to the WebSocket protocol. // // Deprecated: Use websocket.Upgrader instead. // // Upgrade does not perform origin checking. The application is responsible for // checking the Origin header before calling Upgrade. An example implementation // of the same origin policy check is: // // if req.Header.Get("Origin") != "http://"+req.Host { // http.Error(w, "Origin not allowed", http.StatusForbidden) // return // } // // If the endpoint supports subprotocols, then the application is responsible // for negotiating the protocol used on the connection. Use the Subprotocols() // function to get the subprotocols requested by the client. Use the // Sec-Websocket-Protocol response header to specify the subprotocol selected // by the application. // // The responseHeader is included in the response to the client's upgrade // request. Use the responseHeader to specify cookies (Set-Cookie) and the // negotiated subprotocol (Sec-Websocket-Protocol). // // The connection buffers IO to the underlying network connection. The // readBufSize and writeBufSize parameters specify the size of the buffers to // use. Messages can be larger than the buffers. // // If the request is not a valid WebSocket handshake, then Upgrade returns an // error of type HandshakeError. Applications should handle this error by // replying to the client with an HTTP error response. func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) { u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize} u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) { // don't return errors to maintain backwards compatibility } u.CheckOrigin = func(r *http.Request) bool { // allow all connections by default return true } return u.Upgrade(w, r, responseHeader) } // Subprotocols returns the subprotocols requested by the client in the // Sec-Websocket-Protocol header. func Subprotocols(r *http.Request) []string { h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol")) if h == "" { return nil } protocols := strings.Split(h, ",") for i := range protocols { protocols[i] = strings.TrimSpace(protocols[i]) } return protocols } // IsWebSocketUpgrade returns true if the client requested upgrade to the // WebSocket protocol. func IsWebSocketUpgrade(r *http.Request) bool { return tokenListContainsValue(r.Header, "Connection", "upgrade") && tokenListContainsValue(r.Header, "Upgrade", "websocket") } ================================================ FILE: src/github.com/gorilla/websocket/server_test.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "net/http" "reflect" "testing" ) var subprotocolTests = []struct { h string protocols []string }{ {"", nil}, {"foo", []string{"foo"}}, {"foo,bar", []string{"foo", "bar"}}, {"foo, bar", []string{"foo", "bar"}}, {" foo, bar", []string{"foo", "bar"}}, {" foo, bar ", []string{"foo", "bar"}}, } func TestSubprotocols(t *testing.T) { for _, st := range subprotocolTests { r := http.Request{Header: http.Header{"Sec-Websocket-Protocol": {st.h}}} protocols := Subprotocols(&r) if !reflect.DeepEqual(st.protocols, protocols) { t.Errorf("SubProtocols(%q) returned %#v, want %#v", st.h, protocols, st.protocols) } } } var isWebSocketUpgradeTests = []struct { ok bool h http.Header }{ {false, http.Header{"Upgrade": {"websocket"}}}, {false, http.Header{"Connection": {"upgrade"}}}, {true, http.Header{"Connection": {"upgRade"}, "Upgrade": {"WebSocket"}}}, } func TestIsWebSocketUpgrade(t *testing.T) { for _, tt := range isWebSocketUpgradeTests { ok := IsWebSocketUpgrade(&http.Request{Header: tt.h}) if tt.ok != ok { t.Errorf("IsWebSocketUpgrade(%v) returned %v, want %v", tt.h, ok, tt.ok) } } } var checkSameOriginTests = []struct { ok bool r *http.Request }{ {false, &http.Request{Host: "example.org", Header: map[string][]string{"Origin": []string{"https://other.org"}}}}, {true, &http.Request{Host: "example.org", Header: map[string][]string{"Origin": []string{"https://example.org"}}}}, {true, &http.Request{Host: "Example.org", Header: map[string][]string{"Origin": []string{"https://example.org"}}}}, } func TestCheckSameOrigin(t *testing.T) { for _, tt := range checkSameOriginTests { ok := checkSameOrigin(tt.r) if tt.ok != ok { t.Errorf("checkSameOrigin(%+v) returned %v, want %v", tt.r, ok, tt.ok) } } } ================================================ FILE: src/github.com/gorilla/websocket/util.go ================================================ // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "crypto/rand" "crypto/sha1" "encoding/base64" "io" "net/http" "strings" "unicode/utf8" ) var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11") func computeAcceptKey(challengeKey string) string { h := sha1.New() h.Write([]byte(challengeKey)) h.Write(keyGUID) return base64.StdEncoding.EncodeToString(h.Sum(nil)) } func generateChallengeKey() (string, error) { p := make([]byte, 16) if _, err := io.ReadFull(rand.Reader, p); err != nil { return "", err } return base64.StdEncoding.EncodeToString(p), nil } // Octet types from RFC 2616. var octetTypes [256]byte const ( isTokenOctet = 1 << iota isSpaceOctet ) func init() { // From RFC 2616 // // OCTET = // CHAR = // CTL = // CR = // LF = // SP = // HT = // <"> = // CRLF = CR LF // LWS = [CRLF] 1*( SP | HT ) // TEXT = // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT // token = 1* // qdtext = > for c := 0; c < 256; c++ { var t byte isCtl := c <= 31 || c == 127 isChar := 0 <= c && c <= 127 isSeparator := strings.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0 if strings.IndexRune(" \t\r\n", rune(c)) >= 0 { t |= isSpaceOctet } if isChar && !isCtl && !isSeparator { t |= isTokenOctet } octetTypes[c] = t } } func skipSpace(s string) (rest string) { i := 0 for ; i < len(s); i++ { if octetTypes[s[i]]&isSpaceOctet == 0 { break } } return s[i:] } func nextToken(s string) (token, rest string) { i := 0 for ; i < len(s); i++ { if octetTypes[s[i]]&isTokenOctet == 0 { break } } return s[:i], s[i:] } func nextTokenOrQuoted(s string) (value string, rest string) { if !strings.HasPrefix(s, "\"") { return nextToken(s) } s = s[1:] for i := 0; i < len(s); i++ { switch s[i] { case '"': return s[:i], s[i+1:] case '\\': p := make([]byte, len(s)-1) j := copy(p, s[:i]) escape := true for i = i + 1; i < len(s); i++ { b := s[i] switch { case escape: escape = false p[j] = b j++ case b == '\\': escape = true case b == '"': return string(p[:j]), s[i+1:] default: p[j] = b j++ } } return "", "" } } return "", "" } // equalASCIIFold returns true if s is equal to t with ASCII case folding. func equalASCIIFold(s, t string) bool { for s != "" && t != "" { sr, size := utf8.DecodeRuneInString(s) s = s[size:] tr, size := utf8.DecodeRuneInString(t) t = t[size:] if sr == tr { continue } if 'A' <= sr && sr <= 'Z' { sr = sr + 'a' - 'A' } if 'A' <= tr && tr <= 'Z' { tr = tr + 'a' - 'A' } if sr != tr { return false } } return s == t } // tokenListContainsValue returns true if the 1#token header with the given // name contains a token equal to value with ASCII case folding. func tokenListContainsValue(header http.Header, name string, value string) bool { headers: for _, s := range header[name] { for { var t string t, s = nextToken(skipSpace(s)) if t == "" { continue headers } s = skipSpace(s) if s != "" && s[0] != ',' { continue headers } if equalASCIIFold(t, value) { return true } if s == "" { continue headers } s = s[1:] } } return false } // parseExtensiosn parses WebSocket extensions from a header. func parseExtensions(header http.Header) []map[string]string { // From RFC 6455: // // Sec-WebSocket-Extensions = extension-list // extension-list = 1#extension // extension = extension-token *( ";" extension-param ) // extension-token = registered-token // registered-token = token // extension-param = token [ "=" (token | quoted-string) ] // ;When using the quoted-string syntax variant, the value // ;after quoted-string unescaping MUST conform to the // ;'token' ABNF. var result []map[string]string headers: for _, s := range header["Sec-Websocket-Extensions"] { for { var t string t, s = nextToken(skipSpace(s)) if t == "" { continue headers } ext := map[string]string{"": t} for { s = skipSpace(s) if !strings.HasPrefix(s, ";") { break } var k string k, s = nextToken(skipSpace(s[1:])) if k == "" { continue headers } s = skipSpace(s) var v string if strings.HasPrefix(s, "=") { v, s = nextTokenOrQuoted(skipSpace(s[1:])) s = skipSpace(s) } if s != "" && s[0] != ',' && s[0] != ';' { continue headers } ext[k] = v } if s != "" && s[0] != ',' { continue headers } result = append(result, ext) if s == "" { continue headers } s = s[1:] } } return result } ================================================ FILE: src/github.com/gorilla/websocket/util_test.go ================================================ // Copyright 2014 The Gorilla WebSocket Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package websocket import ( "net/http" "reflect" "testing" ) var equalASCIIFoldTests = []struct { t, s string eq bool }{ {"WebSocket", "websocket", true}, {"websocket", "WebSocket", true}, {"Öyster", "öyster", false}, } func TestEqualASCIIFold(t *testing.T) { for _, tt := range equalASCIIFoldTests { eq := equalASCIIFold(tt.s, tt.t) if eq != tt.eq { t.Errorf("equalASCIIFold(%q, %q) = %v, want %v", tt.s, tt.t, eq, tt.eq) } } } var tokenListContainsValueTests = []struct { value string ok bool }{ {"WebSocket", true}, {"WEBSOCKET", true}, {"websocket", true}, {"websockets", false}, {"x websocket", false}, {"websocket x", false}, {"other,websocket,more", true}, {"other, websocket, more", true}, } func TestTokenListContainsValue(t *testing.T) { for _, tt := range tokenListContainsValueTests { h := http.Header{"Upgrade": {tt.value}} ok := tokenListContainsValue(h, "Upgrade", "websocket") if ok != tt.ok { t.Errorf("tokenListContainsValue(h, n, %q) = %v, want %v", tt.value, ok, tt.ok) } } } var parseExtensionTests = []struct { value string extensions []map[string]string }{ {`foo`, []map[string]string{{"": "foo"}}}, {`foo, bar; baz=2`, []map[string]string{ {"": "foo"}, {"": "bar", "baz": "2"}}}, {`foo; bar="b,a;z"`, []map[string]string{ {"": "foo", "bar": "b,a;z"}}}, {`foo , bar; baz = 2`, []map[string]string{ {"": "foo"}, {"": "bar", "baz": "2"}}}, {`foo, bar; baz=2 junk`, []map[string]string{ {"": "foo"}}}, {`foo junk, bar; baz=2 junk`, nil}, {`mux; max-channels=4; flow-control, deflate-stream`, []map[string]string{ {"": "mux", "max-channels": "4", "flow-control": ""}, {"": "deflate-stream"}}}, {`permessage-foo; x="10"`, []map[string]string{ {"": "permessage-foo", "x": "10"}}}, {`permessage-foo; use_y, permessage-foo`, []map[string]string{ {"": "permessage-foo", "use_y": ""}, {"": "permessage-foo"}}}, {`permessage-deflate; client_max_window_bits; server_max_window_bits=10 , permessage-deflate; client_max_window_bits`, []map[string]string{ {"": "permessage-deflate", "client_max_window_bits": "", "server_max_window_bits": "10"}, {"": "permessage-deflate", "client_max_window_bits": ""}}}, {"permessage-deflate; server_no_context_takeover; client_max_window_bits=15", []map[string]string{ {"": "permessage-deflate", "server_no_context_takeover": "", "client_max_window_bits": "15"}, }}, } func TestParseExtensions(t *testing.T) { for _, tt := range parseExtensionTests { h := http.Header{http.CanonicalHeaderKey("Sec-WebSocket-Extensions"): {tt.value}} extensions := parseExtensions(h) if !reflect.DeepEqual(extensions, tt.extensions) { t.Errorf("parseExtensions(%q)\n = %v,\nwant %v", tt.value, extensions, tt.extensions) } } } ================================================ FILE: src/github.com/gorilla/websocket/x_net_proxy.go ================================================ // Code generated by golang.org/x/tools/cmd/bundle. DO NOT EDIT. //go:generate bundle -o x_net_proxy.go golang.org/x/net/proxy // Package proxy provides support for a variety of protocols to proxy network // data. // package websocket import ( "errors" "io" "net" "net/url" "os" "strconv" "strings" "sync" ) type proxy_direct struct{} // Direct is a direct proxy: one that makes network connections directly. var proxy_Direct = proxy_direct{} func (proxy_direct) Dial(network, addr string) (net.Conn, error) { return net.Dial(network, addr) } // A PerHost directs connections to a default Dialer unless the host name // requested matches one of a number of exceptions. type proxy_PerHost struct { def, bypass proxy_Dialer bypassNetworks []*net.IPNet bypassIPs []net.IP bypassZones []string bypassHosts []string } // NewPerHost returns a PerHost Dialer that directs connections to either // defaultDialer or bypass, depending on whether the connection matches one of // the configured rules. func proxy_NewPerHost(defaultDialer, bypass proxy_Dialer) *proxy_PerHost { return &proxy_PerHost{ def: defaultDialer, bypass: bypass, } } // Dial connects to the address addr on the given network through either // defaultDialer or bypass. func (p *proxy_PerHost) Dial(network, addr string) (c net.Conn, err error) { host, _, err := net.SplitHostPort(addr) if err != nil { return nil, err } return p.dialerForRequest(host).Dial(network, addr) } func (p *proxy_PerHost) dialerForRequest(host string) proxy_Dialer { if ip := net.ParseIP(host); ip != nil { for _, net := range p.bypassNetworks { if net.Contains(ip) { return p.bypass } } for _, bypassIP := range p.bypassIPs { if bypassIP.Equal(ip) { return p.bypass } } return p.def } for _, zone := range p.bypassZones { if strings.HasSuffix(host, zone) { return p.bypass } if host == zone[1:] { // For a zone ".example.com", we match "example.com" // too. return p.bypass } } for _, bypassHost := range p.bypassHosts { if bypassHost == host { return p.bypass } } return p.def } // AddFromString parses a string that contains comma-separated values // specifying hosts that should use the bypass proxy. Each value is either an // IP address, a CIDR range, a zone (*.example.com) or a host name // (localhost). A best effort is made to parse the string and errors are // ignored. func (p *proxy_PerHost) AddFromString(s string) { hosts := strings.Split(s, ",") for _, host := range hosts { host = strings.TrimSpace(host) if len(host) == 0 { continue } if strings.Contains(host, "/") { // We assume that it's a CIDR address like 127.0.0.0/8 if _, net, err := net.ParseCIDR(host); err == nil { p.AddNetwork(net) } continue } if ip := net.ParseIP(host); ip != nil { p.AddIP(ip) continue } if strings.HasPrefix(host, "*.") { p.AddZone(host[1:]) continue } p.AddHost(host) } } // AddIP specifies an IP address that will use the bypass proxy. Note that // this will only take effect if a literal IP address is dialed. A connection // to a named host will never match an IP. func (p *proxy_PerHost) AddIP(ip net.IP) { p.bypassIPs = append(p.bypassIPs, ip) } // AddNetwork specifies an IP range that will use the bypass proxy. Note that // this will only take effect if a literal IP address is dialed. A connection // to a named host will never match. func (p *proxy_PerHost) AddNetwork(net *net.IPNet) { p.bypassNetworks = append(p.bypassNetworks, net) } // AddZone specifies a DNS suffix that will use the bypass proxy. A zone of // "example.com" matches "example.com" and all of its subdomains. func (p *proxy_PerHost) AddZone(zone string) { if strings.HasSuffix(zone, ".") { zone = zone[:len(zone)-1] } if !strings.HasPrefix(zone, ".") { zone = "." + zone } p.bypassZones = append(p.bypassZones, zone) } // AddHost specifies a host name that will use the bypass proxy. func (p *proxy_PerHost) AddHost(host string) { if strings.HasSuffix(host, ".") { host = host[:len(host)-1] } p.bypassHosts = append(p.bypassHosts, host) } // A Dialer is a means to establish a connection. type proxy_Dialer interface { // Dial connects to the given address via the proxy. Dial(network, addr string) (c net.Conn, err error) } // Auth contains authentication parameters that specific Dialers may require. type proxy_Auth struct { User, Password string } // FromEnvironment returns the dialer specified by the proxy related variables in // the environment. func proxy_FromEnvironment() proxy_Dialer { allProxy := proxy_allProxyEnv.Get() if len(allProxy) == 0 { return proxy_Direct } proxyURL, err := url.Parse(allProxy) if err != nil { return proxy_Direct } proxy, err := proxy_FromURL(proxyURL, proxy_Direct) if err != nil { return proxy_Direct } noProxy := proxy_noProxyEnv.Get() if len(noProxy) == 0 { return proxy } perHost := proxy_NewPerHost(proxy, proxy_Direct) perHost.AddFromString(noProxy) return perHost } // proxySchemes is a map from URL schemes to a function that creates a Dialer // from a URL with such a scheme. var proxy_proxySchemes map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error) // RegisterDialerType takes a URL scheme and a function to generate Dialers from // a URL with that scheme and a forwarding Dialer. Registered schemes are used // by FromURL. func proxy_RegisterDialerType(scheme string, f func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) { if proxy_proxySchemes == nil { proxy_proxySchemes = make(map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) } proxy_proxySchemes[scheme] = f } // FromURL returns a Dialer given a URL specification and an underlying // Dialer for it to make network requests. func proxy_FromURL(u *url.URL, forward proxy_Dialer) (proxy_Dialer, error) { var auth *proxy_Auth if u.User != nil { auth = new(proxy_Auth) auth.User = u.User.Username() if p, ok := u.User.Password(); ok { auth.Password = p } } switch u.Scheme { case "socks5": return proxy_SOCKS5("tcp", u.Host, auth, forward) } // If the scheme doesn't match any of the built-in schemes, see if it // was registered by another package. if proxy_proxySchemes != nil { if f, ok := proxy_proxySchemes[u.Scheme]; ok { return f(u, forward) } } return nil, errors.New("proxy: unknown scheme: " + u.Scheme) } var ( proxy_allProxyEnv = &proxy_envOnce{ names: []string{"ALL_PROXY", "all_proxy"}, } proxy_noProxyEnv = &proxy_envOnce{ names: []string{"NO_PROXY", "no_proxy"}, } ) // envOnce looks up an environment variable (optionally by multiple // names) once. It mitigates expensive lookups on some platforms // (e.g. Windows). // (Borrowed from net/http/transport.go) type proxy_envOnce struct { names []string once sync.Once val string } func (e *proxy_envOnce) Get() string { e.once.Do(e.init) return e.val } func (e *proxy_envOnce) init() { for _, n := range e.names { e.val = os.Getenv(n) if e.val != "" { return } } } // SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address // with an optional username and password. See RFC 1928 and RFC 1929. func proxy_SOCKS5(network, addr string, auth *proxy_Auth, forward proxy_Dialer) (proxy_Dialer, error) { s := &proxy_socks5{ network: network, addr: addr, forward: forward, } if auth != nil { s.user = auth.User s.password = auth.Password } return s, nil } type proxy_socks5 struct { user, password string network, addr string forward proxy_Dialer } const proxy_socks5Version = 5 const ( proxy_socks5AuthNone = 0 proxy_socks5AuthPassword = 2 ) const proxy_socks5Connect = 1 const ( proxy_socks5IP4 = 1 proxy_socks5Domain = 3 proxy_socks5IP6 = 4 ) var proxy_socks5Errors = []string{ "", "general failure", "connection forbidden", "network unreachable", "host unreachable", "connection refused", "TTL expired", "command not supported", "address type not supported", } // Dial connects to the address addr on the given network via the SOCKS5 proxy. func (s *proxy_socks5) Dial(network, addr string) (net.Conn, error) { switch network { case "tcp", "tcp6", "tcp4": default: return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network) } conn, err := s.forward.Dial(s.network, s.addr) if err != nil { return nil, err } if err := s.connect(conn, addr); err != nil { conn.Close() return nil, err } return conn, nil } // connect takes an existing connection to a socks5 proxy server, // and commands the server to extend that connection to target, // which must be a canonical address with a host and port. func (s *proxy_socks5) connect(conn net.Conn, target string) error { host, portStr, err := net.SplitHostPort(target) if err != nil { return err } port, err := strconv.Atoi(portStr) if err != nil { return errors.New("proxy: failed to parse port number: " + portStr) } if port < 1 || port > 0xffff { return errors.New("proxy: port number out of range: " + portStr) } // the size here is just an estimate buf := make([]byte, 0, 6+len(host)) buf = append(buf, proxy_socks5Version) if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 { buf = append(buf, 2 /* num auth methods */, proxy_socks5AuthNone, proxy_socks5AuthPassword) } else { buf = append(buf, 1 /* num auth methods */, proxy_socks5AuthNone) } if _, err := conn.Write(buf); err != nil { return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error()) } if _, err := io.ReadFull(conn, buf[:2]); err != nil { return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } if buf[0] != 5 { return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0]))) } if buf[1] == 0xff { return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication") } // See RFC 1929 if buf[1] == proxy_socks5AuthPassword { buf = buf[:0] buf = append(buf, 1 /* password protocol version */) buf = append(buf, uint8(len(s.user))) buf = append(buf, s.user...) buf = append(buf, uint8(len(s.password))) buf = append(buf, s.password...) if _, err := conn.Write(buf); err != nil { return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) } if _, err := io.ReadFull(conn, buf[:2]); err != nil { return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } if buf[1] != 0 { return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password") } } buf = buf[:0] buf = append(buf, proxy_socks5Version, proxy_socks5Connect, 0 /* reserved */) if ip := net.ParseIP(host); ip != nil { if ip4 := ip.To4(); ip4 != nil { buf = append(buf, proxy_socks5IP4) ip = ip4 } else { buf = append(buf, proxy_socks5IP6) } buf = append(buf, ip...) } else { if len(host) > 255 { return errors.New("proxy: destination host name too long: " + host) } buf = append(buf, proxy_socks5Domain) buf = append(buf, byte(len(host))) buf = append(buf, host...) } buf = append(buf, byte(port>>8), byte(port)) if _, err := conn.Write(buf); err != nil { return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) } if _, err := io.ReadFull(conn, buf[:4]); err != nil { return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } failure := "unknown error" if int(buf[1]) < len(proxy_socks5Errors) { failure = proxy_socks5Errors[buf[1]] } if len(failure) > 0 { return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure) } bytesToDiscard := 0 switch buf[3] { case proxy_socks5IP4: bytesToDiscard = net.IPv4len case proxy_socks5IP6: bytesToDiscard = net.IPv6len case proxy_socks5Domain: _, err := io.ReadFull(conn, buf[:1]) if err != nil { return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } bytesToDiscard = int(buf[0]) default: return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr) } if cap(buf) < bytesToDiscard { buf = make([]byte, bytesToDiscard) } else { buf = buf[:bytesToDiscard] } if _, err := io.ReadFull(conn, buf); err != nil { return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } // Also need to discard the port number if _, err := io.ReadFull(conn, buf[:2]); err != nil { return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } return nil } ================================================ FILE: src/github.com/labstack/gommon/bytes/README.md ================================================ # Bytes - Format bytes integer to human readable bytes string. - Parse human readable bytes string to bytes integer. ## Installation ```go go get github.com/labstack/gommon/bytes ``` ## [Usage](https://github.com/labstack/gommon/blob/master/bytes/bytes_test.go) ### Format ```go println(bytes.Format(13231323)) ``` `12.62MB` ### Parse ```go b, _ = Parse("2M") println(b) ``` `2097152` ================================================ FILE: src/github.com/labstack/gommon/bytes/bytes.go ================================================ package bytes import ( "fmt" "regexp" "strconv" ) type ( Bytes struct { } ) const ( B = 1 << (10 * iota) KB MB GB TB PB EB ) var ( pattern = regexp.MustCompile(`(?i)^(-?\d+)([KMGTP]B?|B)$`) global = New() ) // New creates a Bytes instance. func New() *Bytes { return &Bytes{} } // Format formats bytes integer to human readable string. // For example, 31323 bytes will return 30.59KB. func (*Bytes) Format(b int64) string { multiple := "" value := float64(b) switch { case b < KB: return strconv.FormatInt(b, 10) + "B" case b < MB: value /= KB multiple = "KB" case b < MB: value /= KB multiple = "KB" case b < GB: value /= MB multiple = "MB" case b < TB: value /= GB multiple = "GB" case b < PB: value /= TB multiple = "TB" case b < EB: value /= PB multiple = "PB" } return fmt.Sprintf("%.02f%s", value, multiple) } // Parse parses human readable bytes string to bytes integer. // For example, 6GB (6G is also valid) will return 6442450944. func (*Bytes) Parse(value string) (i int64, err error) { parts := pattern.FindStringSubmatch(value) if len(parts) < 3 { return 0, fmt.Errorf("error parsing value=%s", value) } bytesString := parts[1] multiple := parts[2] bytes, err := strconv.ParseInt(bytesString, 10, 64) if err != nil { return } switch multiple { case "B": return bytes * B, nil case "K", "KB": return bytes * KB, nil case "M", "MB": return bytes * MB, nil case "G", "GB": return bytes * GB, nil case "T", "TB": return bytes * TB, nil case "P", "PB": return bytes * PB, nil } return } // Format wraps global Bytes's Format function. func Format(b int64) string { return global.Format(b) } // Parse wraps global Bytes's Parse function. func Parse(val string) (int64, error) { return global.Parse(val) } ================================================ FILE: src/github.com/labstack/gommon/bytes/bytes_test.go ================================================ package bytes import ( "testing" "github.com/stretchr/testify/assert" ) func TestBytesFormat(t *testing.T) { // B b := Format(515) assert.Equal(t, "515B", b) // KB b = Format(31323) assert.Equal(t, "30.59KB", b) // MB b = Format(13231323) assert.Equal(t, "12.62MB", b) // GB b = Format(7323232398) assert.Equal(t, "6.82GB", b) // TB b = Format(7323232398434) assert.Equal(t, "6.66TB", b) // PB b = Format(9923232398434432) assert.Equal(t, "8.81PB", b) } func TestBytesParse(t *testing.T) { // B b, err := Parse("515B") if assert.NoError(t, err) { assert.Equal(t, int64(515), b) } // KB b, err = Parse("12KB") if assert.NoError(t, err) { assert.Equal(t, int64(12288), b) } b, err = Parse("12K") if assert.NoError(t, err) { assert.Equal(t, int64(12288), b) } // MB b, err = Parse("2MB") if assert.NoError(t, err) { assert.Equal(t, int64(2097152), b) } b, err = Parse("2M") if assert.NoError(t, err) { assert.Equal(t, int64(2097152), b) } // GB b, err = Parse("6GB") if assert.NoError(t, err) { assert.Equal(t, int64(6442450944), b) } b, err = Parse("6G") if assert.NoError(t, err) { assert.Equal(t, int64(6442450944), b) } // TB b, err = Parse("5TB") if assert.NoError(t, err) { assert.Equal(t, int64(5497558138880), b) } b, err = Parse("5T") if assert.NoError(t, err) { assert.Equal(t, int64(5497558138880), b) } // PB b, err = Parse("9PB") if assert.NoError(t, err) { assert.Equal(t, int64(10133099161583616), b) } b, err = Parse("9P") if assert.NoError(t, err) { assert.Equal(t, int64(10133099161583616), b) } } ================================================ FILE: src/github.com/labstack/gommon/color/README.md ================================================ # Color Style terminal text. ## Installation ```sh go get github.com/labstack/gommon/color ``` ## Windows? Try [cmder](http://bliker.github.io/cmder) or https://github.com/mattn/go-colorable ## [Usage](https://github.com/labstack/gommon/blob/master/color/color_test.go) ```sh import github.com/labstack/gommon/color ``` ### Colored text ```go color.Println(color.Black("black")) color.Println(color.Red("red")) color.Println(color.Green("green")) color.Println(color.Yellow("yellow")) color.Println(color.Blue("blue")) color.Println(color.Magenta("magenta")) color.Println(color.Cyan("cyan")) color.Println(color.White("white")) color.Println(color.Grey("grey")) ``` ![Colored Text](http://i.imgur.com/8RtY1QR.png) ### Colored background ```go color.Println(color.BlackBg("black background", color.Wht)) color.Println(color.RedBg("red background")) color.Println(color.GreenBg("green background")) color.Println(color.YellowBg("yellow background")) color.Println(color.BlueBg("blue background")) color.Println(color.MagentaBg("magenta background")) color.Println(color.CyanBg("cyan background")) color.Println(color.WhiteBg("white background")) ``` ![Colored Background](http://i.imgur.com/SrrS6lw.png) ### Emphasis ```go color.Println(color.Bold("bold")) color.Println(color.Dim("dim")) color.Println(color.Italic("italic")) color.Println(color.Underline("underline")) color.Println(color.Inverse("inverse")) color.Println(color.Hidden("hidden")) color.Println(color.Strikeout("strikeout")) ``` ![Emphasis](http://i.imgur.com/3RSJBbc.png) ### Mix and match ```go color.Println(color.Green("bold green with white background", color.B, color.WhtBg)) color.Println(color.Red("underline red", color.U)) color.Println(color.Yellow("dim yellow", color.D)) color.Println(color.Cyan("inverse cyan", color.In)) color.Println(color.Blue("bold underline dim blue", color.B, color.U, color.D)) ``` ![Mix and match](http://i.imgur.com/jWGq9Ca.png) ### Enable/Disable the package ```go color.Disable() color.Enable() ``` ### New instance ```go c := New() c.Green("green") ``` ================================================ FILE: src/github.com/labstack/gommon/color/color.go ================================================ package color import ( "bytes" "fmt" "io" "os" "github.com/mattn/go-colorable" "github.com/mattn/go-isatty" ) type ( inner func(interface{}, []string, *Color) string ) // Color styles const ( // Blk Black text style Blk = "30" // Rd red text style Rd = "31" // Grn green text style Grn = "32" // Yel yellow text style Yel = "33" // Blu blue text style Blu = "34" // Mgn magenta text style Mgn = "35" // Cyn cyan text style Cyn = "36" // Wht white text style Wht = "37" // Gry grey text style Gry = "90" // BlkBg black background style BlkBg = "40" // RdBg red background style RdBg = "41" // GrnBg green background style GrnBg = "42" // YelBg yellow background style YelBg = "43" // BluBg blue background style BluBg = "44" // MgnBg magenta background style MgnBg = "45" // CynBg cyan background style CynBg = "46" // WhtBg white background style WhtBg = "47" // R reset emphasis style R = "0" // B bold emphasis style B = "1" // D dim emphasis style D = "2" // I italic emphasis style I = "3" // U underline emphasis style U = "4" // In inverse emphasis style In = "7" // H hidden emphasis style H = "8" // S strikeout emphasis style S = "9" ) var ( black = outer(Blk) red = outer(Rd) green = outer(Grn) yellow = outer(Yel) blue = outer(Blu) magenta = outer(Mgn) cyan = outer(Cyn) white = outer(Wht) grey = outer(Gry) blackBg = outer(BlkBg) redBg = outer(RdBg) greenBg = outer(GrnBg) yellowBg = outer(YelBg) blueBg = outer(BluBg) magentaBg = outer(MgnBg) cyanBg = outer(CynBg) whiteBg = outer(WhtBg) reset = outer(R) bold = outer(B) dim = outer(D) italic = outer(I) underline = outer(U) inverse = outer(In) hidden = outer(H) strikeout = outer(S) global = New() ) func outer(n string) inner { return func(msg interface{}, styles []string, c *Color) string { // TODO: Drop fmt to boost performance? if c.disabled { return fmt.Sprintf("%v", msg) } b := new(bytes.Buffer) b.WriteString("\x1b[") b.WriteString(n) for _, s := range styles { b.WriteString(";") b.WriteString(s) } b.WriteString("m") return fmt.Sprintf("%s%v\x1b[0m", b.String(), msg) } } type ( Color struct { output io.Writer disabled bool } ) // New creates a Color instance. func New() (c *Color) { c = new(Color) c.SetOutput(colorable.NewColorableStdout()) return } // Output returns the output. func (c *Color) Output() io.Writer { return c.output } // SetOutput sets the output. func (c *Color) SetOutput(w io.Writer) { c.output = w if w, ok := w.(*os.File); !ok || !isatty.IsTerminal(w.Fd()) { c.disabled = true } } // Disable disables the colors and styles. func (c *Color) Disable() { c.disabled = true } // Enable enables the colors and styles. func (c *Color) Enable() { c.disabled = false } // Print is analogous to `fmt.Print` with termial detection. func (c *Color) Print(args ...interface{}) { fmt.Fprint(c.output, args...) } // Println is analogous to `fmt.Println` with termial detection. func (c *Color) Println(args ...interface{}) { fmt.Fprintln(c.output, args...) } // Printf is analogous to `fmt.Printf` with termial detection. func (c *Color) Printf(format string, args ...interface{}) { fmt.Fprintf(c.output, format, args...) } func (c *Color) Black(msg interface{}, styles ...string) string { return black(msg, styles, c) } func (c *Color) Red(msg interface{}, styles ...string) string { return red(msg, styles, c) } func (c *Color) Green(msg interface{}, styles ...string) string { return green(msg, styles, c) } func (c *Color) Yellow(msg interface{}, styles ...string) string { return yellow(msg, styles, c) } func (c *Color) Blue(msg interface{}, styles ...string) string { return blue(msg, styles, c) } func (c *Color) Magenta(msg interface{}, styles ...string) string { return magenta(msg, styles, c) } func (c *Color) Cyan(msg interface{}, styles ...string) string { return cyan(msg, styles, c) } func (c *Color) White(msg interface{}, styles ...string) string { return white(msg, styles, c) } func (c *Color) Grey(msg interface{}, styles ...string) string { return grey(msg, styles, c) } func (c *Color) BlackBg(msg interface{}, styles ...string) string { return blackBg(msg, styles, c) } func (c *Color) RedBg(msg interface{}, styles ...string) string { return redBg(msg, styles, c) } func (c *Color) GreenBg(msg interface{}, styles ...string) string { return greenBg(msg, styles, c) } func (c *Color) YellowBg(msg interface{}, styles ...string) string { return yellowBg(msg, styles, c) } func (c *Color) BlueBg(msg interface{}, styles ...string) string { return blueBg(msg, styles, c) } func (c *Color) MagentaBg(msg interface{}, styles ...string) string { return magentaBg(msg, styles, c) } func (c *Color) CyanBg(msg interface{}, styles ...string) string { return cyanBg(msg, styles, c) } func (c *Color) WhiteBg(msg interface{}, styles ...string) string { return whiteBg(msg, styles, c) } func (c *Color) Reset(msg interface{}, styles ...string) string { return reset(msg, styles, c) } func (c *Color) Bold(msg interface{}, styles ...string) string { return bold(msg, styles, c) } func (c *Color) Dim(msg interface{}, styles ...string) string { return dim(msg, styles, c) } func (c *Color) Italic(msg interface{}, styles ...string) string { return italic(msg, styles, c) } func (c *Color) Underline(msg interface{}, styles ...string) string { return underline(msg, styles, c) } func (c *Color) Inverse(msg interface{}, styles ...string) string { return inverse(msg, styles, c) } func (c *Color) Hidden(msg interface{}, styles ...string) string { return hidden(msg, styles, c) } func (c *Color) Strikeout(msg interface{}, styles ...string) string { return strikeout(msg, styles, c) } // Output returns the output. func Output() io.Writer { return global.output } // SetOutput sets the output. func SetOutput(w io.Writer) { global.SetOutput(w) } func Disable() { global.Disable() } func Enable() { global.Enable() } // Print is analogous to `fmt.Print` with termial detection. func Print(args ...interface{}) { global.Print(args...) } // Println is analogous to `fmt.Println` with termial detection. func Println(args ...interface{}) { global.Println(args...) } // Printf is analogous to `fmt.Printf` with termial detection. func Printf(format string, args ...interface{}) { global.Printf(format, args...) } func Black(msg interface{}, styles ...string) string { return global.Black(msg, styles...) } func Red(msg interface{}, styles ...string) string { return global.Red(msg, styles...) } func Green(msg interface{}, styles ...string) string { return global.Green(msg, styles...) } func Yellow(msg interface{}, styles ...string) string { return global.Yellow(msg, styles...) } func Blue(msg interface{}, styles ...string) string { return global.Blue(msg, styles...) } func Magenta(msg interface{}, styles ...string) string { return global.Magenta(msg, styles...) } func Cyan(msg interface{}, styles ...string) string { return global.Cyan(msg, styles...) } func White(msg interface{}, styles ...string) string { return global.White(msg, styles...) } func Grey(msg interface{}, styles ...string) string { return global.Grey(msg, styles...) } func BlackBg(msg interface{}, styles ...string) string { return global.BlackBg(msg, styles...) } func RedBg(msg interface{}, styles ...string) string { return global.RedBg(msg, styles...) } func GreenBg(msg interface{}, styles ...string) string { return global.GreenBg(msg, styles...) } func YellowBg(msg interface{}, styles ...string) string { return global.YellowBg(msg, styles...) } func BlueBg(msg interface{}, styles ...string) string { return global.BlueBg(msg, styles...) } func MagentaBg(msg interface{}, styles ...string) string { return global.MagentaBg(msg, styles...) } func CyanBg(msg interface{}, styles ...string) string { return global.CyanBg(msg, styles...) } func WhiteBg(msg interface{}, styles ...string) string { return global.WhiteBg(msg, styles...) } func Reset(msg interface{}, styles ...string) string { return global.Reset(msg, styles...) } func Bold(msg interface{}, styles ...string) string { return global.Bold(msg, styles...) } func Dim(msg interface{}, styles ...string) string { return global.Dim(msg, styles...) } func Italic(msg interface{}, styles ...string) string { return global.Italic(msg, styles...) } func Underline(msg interface{}, styles ...string) string { return global.Underline(msg, styles...) } func Inverse(msg interface{}, styles ...string) string { return global.Inverse(msg, styles...) } func Hidden(msg interface{}, styles ...string) string { return global.Hidden(msg, styles...) } func Strikeout(msg interface{}, styles ...string) string { return global.Strikeout(msg, styles...) } ================================================ FILE: src/github.com/labstack/gommon/color/color_test.go ================================================ package color import ( "testing" "github.com/stretchr/testify/assert" ) func TestText(t *testing.T) { Println("*** colored text ***") Println(Black("black")) Println(Red("red")) Println(Green("green")) Println(Yellow("yellow")) Println(Blue("blue")) Println(Magenta("magenta")) Println(Cyan("cyan")) Println(White("white")) Println(Grey("grey")) } func TestBackground(t *testing.T) { Println("*** colored background ***") Println(BlackBg("black background", Wht)) Println(RedBg("red background")) Println(GreenBg("green background")) Println(YellowBg("yellow background")) Println(BlueBg("blue background")) Println(MagentaBg("magenta background")) Println(CyanBg("cyan background")) Println(WhiteBg("white background")) } func TestEmphasis(t *testing.T) { Println("*** emphasis ***") Println(Reset("reset")) Println(Bold("bold")) Println(Dim("dim")) Println(Italic("italic")) Println(Underline("underline")) Println(Inverse("inverse")) Println(Hidden("hidden")) Println(Strikeout("strikeout")) } func TestMixMatch(t *testing.T) { Println("*** mix and match ***") Println(Green("bold green with white background", B, WhtBg)) Println(Red("underline red", U)) Println(Yellow("dim yellow", D)) Println(Cyan("inverse cyan", In)) Println(Blue("bold underline dim blue", B, U, D)) } func TestEnableDisable(t *testing.T) { Disable() assert.Equal(t, "red", Red("red")) Enable() assert.NotEqual(t, "green", Green("green")) } ================================================ FILE: src/github.com/labstack/gommon/gommon.go ================================================ package gommon ================================================ FILE: src/github.com/labstack/gommon/log/README.md ================================================ ## WORK IN PROGRESS ### Usage [log_test.go](log_test.go) ================================================ FILE: src/github.com/labstack/gommon/log/color.go ================================================ // +build !appengine package log import ( "io" "github.com/mattn/go-colorable" ) func output() io.Writer { return colorable.NewColorableStdout() } ================================================ FILE: src/github.com/labstack/gommon/log/log.go ================================================ package log import ( "bytes" "encoding/json" "fmt" "io" "os" "path" "runtime" "sync" "time" "strconv" "github.com/mattn/go-isatty" "github.com/valyala/fasttemplate" "github.com/labstack/gommon/color" ) type ( Logger struct { prefix string level Lvl output io.Writer template *fasttemplate.Template levels []string color *color.Color bufferPool sync.Pool mutex sync.Mutex } Lvl uint8 JSON map[string]interface{} ) const ( DEBUG Lvl = iota + 1 INFO WARN ERROR OFF ) var ( global = New("-") defaultHeader = `{"time":"${time_rfc3339}","level":"${level}","prefix":"${prefix}",` + `"file":"${short_file}","line":"${line}"}` ) func New(prefix string) (l *Logger) { l = &Logger{ level: INFO, prefix: prefix, template: l.newTemplate(defaultHeader), color: color.New(), bufferPool: sync.Pool{ New: func() interface{} { return bytes.NewBuffer(make([]byte, 256)) }, }, } l.initLevels() l.SetOutput(output()) return } func (l *Logger) initLevels() { l.levels = []string{ "-", l.color.Blue("DEBUG"), l.color.Green("INFO"), l.color.Yellow("WARN"), l.color.Red("ERROR"), } } func (l *Logger) newTemplate(format string) *fasttemplate.Template { return fasttemplate.New(format, "${", "}") } func (l *Logger) DisableColor() { l.color.Disable() l.initLevels() } func (l *Logger) EnableColor() { l.color.Enable() l.initLevels() } func (l *Logger) Prefix() string { return l.prefix } func (l *Logger) SetPrefix(p string) { l.prefix = p } func (l *Logger) Level() Lvl { return l.level } func (l *Logger) SetLevel(v Lvl) { l.level = v } func (l *Logger) Output() io.Writer { return l.output } func (l *Logger) SetOutput(w io.Writer) { l.output = w if w, ok := w.(*os.File); !ok || !isatty.IsTerminal(w.Fd()) { l.DisableColor() } } func (l *Logger) Color() *color.Color { return l.color } func (l *Logger) SetHeader(h string) { l.template = l.newTemplate(h) } func (l *Logger) Print(i ...interface{}) { l.log(0, "", i...) // fmt.Fprintln(l.output, i...) } func (l *Logger) Printf(format string, args ...interface{}) { l.log(0, format, args...) } func (l *Logger) Printj(j JSON) { l.log(0, "json", j) } func (l *Logger) Debug(i ...interface{}) { l.log(DEBUG, "", i...) } func (l *Logger) Debugf(format string, args ...interface{}) { l.log(DEBUG, format, args...) } func (l *Logger) Debugj(j JSON) { l.log(DEBUG, "json", j) } func (l *Logger) Info(i ...interface{}) { l.log(INFO, "", i...) } func (l *Logger) Infof(format string, args ...interface{}) { l.log(INFO, format, args...) } func (l *Logger) Infoj(j JSON) { l.log(INFO, "json", j) } func (l *Logger) Warn(i ...interface{}) { l.log(WARN, "", i...) } func (l *Logger) Warnf(format string, args ...interface{}) { l.log(WARN, format, args...) } func (l *Logger) Warnj(j JSON) { l.log(WARN, "json", j) } func (l *Logger) Error(i ...interface{}) { l.log(ERROR, "", i...) } func (l *Logger) Errorf(format string, args ...interface{}) { l.log(ERROR, format, args...) } func (l *Logger) Errorj(j JSON) { l.log(ERROR, "json", j) } func (l *Logger) Fatal(i ...interface{}) { l.Print(i...) os.Exit(1) } func (l *Logger) Fatalf(format string, args ...interface{}) { l.Printf(format, args...) os.Exit(1) } func (l *Logger) Fatalj(j JSON) { l.Printj(j) os.Exit(1) } func (l *Logger) Panic(i ...interface{}) { l.Print(i...) panic(fmt.Sprint(i...)) } func (l *Logger) Panicf(format string, args ...interface{}) { l.Printf(format, args...) panic(fmt.Sprintf(format, args)) } func (l *Logger) Panicj(j JSON) { l.Printj(j) panic(j) } func DisableColor() { global.DisableColor() } func EnableColor() { global.EnableColor() } func Prefix() string { return global.Prefix() } func SetPrefix(p string) { global.SetPrefix(p) } func Level() Lvl { return global.Level() } func SetLevel(v Lvl) { global.SetLevel(v) } func Output() io.Writer { return global.Output() } func SetOutput(w io.Writer) { global.SetOutput(w) } func SetHeader(h string) { global.SetHeader(h) } func Print(i ...interface{}) { global.Print(i...) } func Printf(format string, args ...interface{}) { global.Printf(format, args...) } func Printj(j JSON) { global.Printj(j) } func Debug(i ...interface{}) { global.Debug(i...) } func Debugf(format string, args ...interface{}) { global.Debugf(format, args...) } func Debugj(j JSON) { global.Debugj(j) } func Info(i ...interface{}) { global.Info(i...) } func Infof(format string, args ...interface{}) { global.Infof(format, args...) } func Infoj(j JSON) { global.Infoj(j) } func Warn(i ...interface{}) { global.Warn(i...) } func Warnf(format string, args ...interface{}) { global.Warnf(format, args...) } func Warnj(j JSON) { global.Warnj(j) } func Error(i ...interface{}) { global.Error(i...) } func Errorf(format string, args ...interface{}) { global.Errorf(format, args...) } func Errorj(j JSON) { global.Errorj(j) } func Fatal(i ...interface{}) { global.Fatal(i...) } func Fatalf(format string, args ...interface{}) { global.Fatalf(format, args...) } func Fatalj(j JSON) { global.Fatalj(j) } func Panic(i ...interface{}) { global.Panic(i...) } func Panicf(format string, args ...interface{}) { global.Panicf(format, args...) } func Panicj(j JSON) { global.Panicj(j) } func (l *Logger) log(v Lvl, format string, args ...interface{}) { l.mutex.Lock() defer l.mutex.Unlock() buf := l.bufferPool.Get().(*bytes.Buffer) buf.Reset() defer l.bufferPool.Put(buf) _, file, line, _ := runtime.Caller(3) if v >= l.level || v == 0 { message := "" if format == "" { message = fmt.Sprint(args...) } else if format == "json" { b, err := json.Marshal(args[0]) if err != nil { panic(err) } message = string(b) } else { message = fmt.Sprintf(format, args...) } _, err := l.template.ExecuteFunc(buf, func(w io.Writer, tag string) (int, error) { switch tag { case "time_rfc3339": return w.Write([]byte(time.Now().Format(time.RFC3339))) case "level": return w.Write([]byte(l.levels[v])) case "prefix": return w.Write([]byte(l.prefix)) case "long_file": return w.Write([]byte(file)) case "short_file": return w.Write([]byte(path.Base(file))) case "line": return w.Write([]byte(strconv.Itoa(line))) } return 0, nil }) if err == nil { s := buf.String() i := buf.Len() - 1 if s[i] == '}' { // JSON header buf.Truncate(i) buf.WriteByte(',') if format == "json" { buf.WriteString(message[1:]) } else { buf.WriteString(`"message":"`) buf.WriteString(message) buf.WriteString(`"}`) } } else { // Text header buf.WriteByte(' ') buf.WriteString(message) } buf.WriteByte('\n') l.output.Write(buf.Bytes()) } } } ================================================ FILE: src/github.com/labstack/gommon/log/log_test.go ================================================ package log import ( "bytes" "os" "os/exec" "sync" "testing" "github.com/stretchr/testify/assert" ) func test(l *Logger, t *testing.T) { b := new(bytes.Buffer) l.SetOutput(b) l.DisableColor() l.SetLevel(WARN) l.Print("print") l.Printf("print%s", "f") l.Debug("debug") l.Debugf("debug%s", "f") l.Info("info") l.Infof("info%s", "f") l.Warn("warn") l.Warnf("warn%s", "f") l.Error("error") l.Errorf("error%s", "f") assert.Contains(t, b.String(), "print") assert.Contains(t, b.String(), "printf") assert.NotContains(t, b.String(), "debug") assert.NotContains(t, b.String(), "debugf") assert.NotContains(t, b.String(), "info") assert.NotContains(t, b.String(), "infof") assert.Contains(t, b.String(), `"level":"WARN","prefix":"`+l.prefix+`"`) assert.Contains(t, b.String(), `"message":"warn"`) assert.Contains(t, b.String(), `"level":"ERROR","prefix":"`+l.prefix+`"`) assert.Contains(t, b.String(), `"message":"errorf"`) } func TestLog(t *testing.T) { l := New("test") test(l, t) } func TestGlobal(t *testing.T) { test(global, t) } func TestLogConcurrent(t *testing.T) { var wg sync.WaitGroup for i := 0; i < 2; i++ { wg.Add(1) go func() { TestLog(t) wg.Done() }() } wg.Wait() } func TestFatal(t *testing.T) { l := New("test") switch os.Getenv("TEST_LOGGER_FATAL") { case "fatal": l.Fatal("fatal") return case "fatalf": l.Fatalf("fatal-%s", "f") return } loggerFatalTest(t, "fatal", "fatal") loggerFatalTest(t, "fatalf", "fatal-f") } func loggerFatalTest(t *testing.T, env string, contains string) { buf := new(bytes.Buffer) cmd := exec.Command(os.Args[0], "-test.run=TestFatal") cmd.Env = append(os.Environ(), "TEST_LOGGER_FATAL="+env) cmd.Stdout = buf cmd.Stderr = buf err := cmd.Run() if e, ok := err.(*exec.ExitError); ok && !e.Success() { assert.Contains(t, buf.String(), contains) return } t.Fatalf("process ran with err %v, want exit status 1", err) } func TestNoFormat(t *testing.T) { } func TestFormat(t *testing.T) { l := New("test") l.SetHeader("${level} | ${prefix}") b := new(bytes.Buffer) l.SetOutput(b) l.Info("info") assert.Equal(t, "INFO | test info\n", b.String()) } func TestJSON(t *testing.T) { l := New("test") b := new(bytes.Buffer) l.SetOutput(b) l.SetLevel(DEBUG) l.Debugj(JSON{"name": "value"}) assert.Contains(t, b.String(), `"name":"value"`) } func BenchmarkLog(b *testing.B) { l := New("test") l.SetOutput(new(bytes.Buffer)) for i := 0; i < b.N; i++ { l.Infof("Info=%s, Debug=%s", "info", "debug") } } ================================================ FILE: src/github.com/labstack/gommon/log/white.go ================================================ // +build appengine package log import ( "io" "os" ) func output() io.Writer { return os.Stdout } ================================================ FILE: src/github.com/labstack/gommon/random/random.go ================================================ package random import ( "math/rand" "time" ) type ( Random struct { charset Charset } Charset string ) const ( Alphanumeric Charset = Alphabetic + Numeric Alphabetic Charset = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" Numeric Charset = "0123456789" Hex Charset = Numeric + "abcdef" ) var ( global = New() ) func New() *Random { rand.Seed(time.Now().UnixNano()) return &Random{ charset: Alphanumeric, } } func (r *Random) SetCharset(c Charset) { r.charset = c } func (r *Random) String(length uint8) string { b := make([]byte, length) for i := range b { b[i] = r.charset[rand.Int63()%int64(len(r.charset))] } return string(b) } func SetCharset(c Charset) { global.SetCharset(c) } func String(length uint8) string { return global.String(length) } ================================================ FILE: src/github.com/labstack/gommon/random/random_test.go ================================================ package random import ( "testing" "github.com/stretchr/testify/assert" ) func Test(t *testing.T) { assert.Len(t, String(32), 32) r := New() r.SetCharset(Numeric) assert.Len(t, r.String(8), 8) } ================================================ FILE: src/github.com/lib/pq/CONTRIBUTING.md ================================================ ## Contributing to pq `pq` has a backlog of pull requests, but contributions are still very much welcome. You can help with patch review, submitting bug reports, or adding new functionality. There is no formal style guide, but please conform to the style of existing code and general Go formatting conventions when submitting patches. ### Patch review Help review existing open pull requests by commenting on the code or proposed functionality. ### Bug reports We appreciate any bug reports, but especially ones with self-contained (doesn't depend on code outside of pq), minimal (can't be simplified further) test cases. It's especially helpful if you can submit a pull request with just the failing test case (you'll probably want to pattern it after the tests in [conn_test.go](https://github.com/lib/pq/blob/master/conn_test.go). ### New functionality There are a number of pending patches for new functionality, so additional feature patches will take a while to merge. Still, patches are generally reviewed based on usefulness and complexity in addition to time-in-queue, so if you have a knockout idea, take a shot. Feel free to open an issue discussion your proposed patch beforehand. ================================================ FILE: src/github.com/lib/pq/LICENSE.md ================================================ Copyright (c) 2011-2013, 'pq' Contributors Portions Copyright (C) 2011 Blake Mizerany Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: src/github.com/lib/pq/README.md ================================================ # pq - A pure Go postgres driver for Go's database/sql package [![Build Status](https://travis-ci.org/lib/pq.png?branch=master)](https://travis-ci.org/lib/pq) ## Install go get github.com/lib/pq ## Docs For detailed documentation and basic usage examples, please see the package documentation at . ## Tests `go test` is used for testing. A running PostgreSQL server is required, with the ability to log in. The default database to connect to test with is "pqgotest," but it can be overridden using environment variables. Example: PGHOST=/var/run/postgresql go test github.com/lib/pq Optionally, a benchmark suite can be run as part of the tests: PGHOST=/var/run/postgresql go test -bench . ## Features * SSL * Handles bad connections for `database/sql` * Scan `time.Time` correctly (i.e. `timestamp[tz]`, `time[tz]`, `date`) * Scan binary blobs correctly (i.e. `bytea`) * Package for `hstore` support * COPY FROM support * pq.ParseURL for converting urls to connection strings for sql.Open. * Many libpq compatible environment variables * Unix socket support * Notifications: `LISTEN`/`NOTIFY` ## Future / Things you can help with * Better COPY FROM / COPY TO (see discussion in #181) ## Thank you (alphabetical) Some of these contributors are from the original library `bmizerany/pq.go` whose code still exists in here. * Andy Balholm (andybalholm) * Ben Berkert (benburkert) * Benjamin Heatwole (bheatwole) * Bill Mill (llimllib) * Bjørn Madsen (aeons) * Blake Gentry (bgentry) * Brad Fitzpatrick (bradfitz) * Charlie Melbye (cmelbye) * Chris Bandy (cbandy) * Chris Gilling (cgilling) * Chris Walsh (cwds) * Dan Sosedoff (sosedoff) * Daniel Farina (fdr) * Eric Chlebek (echlebek) * Eric Garrido (minusnine) * Eric Urban (hydrogen18) * Everyone at The Go Team * Evan Shaw (edsrzf) * Ewan Chou (coocood) * Federico Romero (federomero) * Fumin (fumin) * Gary Burd (garyburd) * Heroku (heroku) * James Pozdena (jpoz) * Jason McVetta (jmcvetta) * Jeremy Jay (pbnjay) * Joakim Sernbrant (serbaut) * John Gallagher (jgallagher) * Jonathan Rudenberg (titanous) * Joël Stemmer (jstemmer) * Kamil Kisiel (kisielk) * Kelly Dunn (kellydunn) * Keith Rarick (kr) * Kir Shatrov (kirs) * Lann Martin (lann) * Maciek Sakrejda (deafbybeheading) * Marc Brinkmann (mbr) * Marko Tiikkaja (johto) * Matt Newberry (MattNewberry) * Matt Robenolt (mattrobenolt) * Martin Olsen (martinolsen) * Mike Lewis (mikelikespie) * Nicolas Patry (Narsil) * Oliver Tonnhofer (olt) * Patrick Hayes (phayes) * Paul Hammond (paulhammond) * Ryan Smith (ryandotsmith) * Samuel Stauffer (samuel) * Timothée Peignier (cyberdelia) * Travis Cline (tmc) * TruongSinh Tran-Nguyen (truongsinh) * Yaismel Miranda (ympons) * notedit (notedit) ================================================ FILE: src/github.com/lib/pq/buf.go ================================================ package pq import ( "bytes" "encoding/binary" "github.com/lib/pq/oid" ) type readBuf []byte func (b *readBuf) int32() (n int) { n = int(int32(binary.BigEndian.Uint32(*b))) *b = (*b)[4:] return } func (b *readBuf) oid() (n oid.Oid) { n = oid.Oid(binary.BigEndian.Uint32(*b)) *b = (*b)[4:] return } // N.B: this is actually an unsigned 16-bit integer, unlike int32 func (b *readBuf) int16() (n int) { n = int(binary.BigEndian.Uint16(*b)) *b = (*b)[2:] return } func (b *readBuf) string() string { i := bytes.IndexByte(*b, 0) if i < 0 { errorf("invalid message format; expected string terminator") } s := (*b)[:i] *b = (*b)[i+1:] return string(s) } func (b *readBuf) next(n int) (v []byte) { v = (*b)[:n] *b = (*b)[n:] return } func (b *readBuf) byte() byte { return b.next(1)[0] } type writeBuf struct { buf []byte pos int } func (b *writeBuf) int32(n int) { x := make([]byte, 4) binary.BigEndian.PutUint32(x, uint32(n)) b.buf = append(b.buf, x...) } func (b *writeBuf) int16(n int) { x := make([]byte, 2) binary.BigEndian.PutUint16(x, uint16(n)) b.buf = append(b.buf, x...) } func (b *writeBuf) string(s string) { b.buf = append(b.buf, (s + "\000")...) } func (b *writeBuf) byte(c byte) { b.buf = append(b.buf, c) } func (b *writeBuf) bytes(v []byte) { b.buf = append(b.buf, v...) } func (b *writeBuf) wrap() []byte { p := b.buf[b.pos:] binary.BigEndian.PutUint32(p, uint32(len(p))) return b.buf } func (b *writeBuf) next(c byte) { p := b.buf[b.pos:] binary.BigEndian.PutUint32(p, uint32(len(p))) b.pos = len(b.buf) + 1 b.buf = append(b.buf, c, 0, 0, 0, 0) } ================================================ FILE: src/github.com/lib/pq/conn.go ================================================ package pq import ( "bufio" "crypto/md5" "crypto/tls" "crypto/x509" "database/sql" "database/sql/driver" "encoding/binary" "errors" "fmt" "io" "io/ioutil" "net" "os" "os/user" "path" "path/filepath" "strconv" "strings" "time" "unicode" "github.com/lib/pq/oid" ) // Common error types var ( ErrNotSupported = errors.New("pq: Unsupported command") ErrInFailedTransaction = errors.New("pq: Could not complete operation in a failed transaction") ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server") ErrSSLKeyHasWorldPermissions = errors.New("pq: Private key file has group or world access. Permissions should be u=rw (0600) or less.") ErrCouldNotDetectUsername = errors.New("pq: Could not detect default username. Please provide one explicitly.") ) type drv struct{} func (d *drv) Open(name string) (driver.Conn, error) { return Open(name) } func init() { sql.Register("postgres", &drv{}) } type parameterStatus struct { // server version in the same format as server_version_num, or 0 if // unavailable serverVersion int // the current location based on the TimeZone value of the session, if // available currentLocation *time.Location } type transactionStatus byte const ( txnStatusIdle transactionStatus = 'I' txnStatusIdleInTransaction transactionStatus = 'T' txnStatusInFailedTransaction transactionStatus = 'E' ) func (s transactionStatus) String() string { switch s { case txnStatusIdle: return "idle" case txnStatusIdleInTransaction: return "idle in transaction" case txnStatusInFailedTransaction: return "in a failed transaction" default: errorf("unknown transactionStatus %d", s) } panic("not reached") } type Dialer interface { Dial(network, address string) (net.Conn, error) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) } type defaultDialer struct{} func (d defaultDialer) Dial(ntw, addr string) (net.Conn, error) { return net.Dial(ntw, addr) } func (d defaultDialer) DialTimeout(ntw, addr string, timeout time.Duration) (net.Conn, error) { return net.DialTimeout(ntw, addr, timeout) } type conn struct { c net.Conn buf *bufio.Reader namei int scratch [512]byte txnStatus transactionStatus parameterStatus parameterStatus saveMessageType byte saveMessageBuffer []byte // If true, this connection is bad and all public-facing functions should // return ErrBadConn. bad bool // If set, this connection should never use the binary format when // receiving query results from prepared statements. Only provided for // debugging. disablePreparedBinaryResult bool // Whether to always send []byte parameters over as binary. Enables single // round-trip mode for non-prepared Query calls. binaryParameters bool } // Handle driver-side settings in parsed connection string. func (c *conn) handleDriverSettings(o values) (err error) { boolSetting := func(key string, val *bool) error { if value := o.Get(key); value != "" { if value == "yes" { *val = true } else if value == "no" { *val = false } else { return fmt.Errorf("unrecognized value %q for %s", value, key) } } return nil } err = boolSetting("disable_prepared_binary_result", &c.disablePreparedBinaryResult) if err != nil { return err } err = boolSetting("binary_parameters", &c.binaryParameters) if err != nil { return err } return nil } func (c *conn) writeBuf(b byte) *writeBuf { c.scratch[0] = b return &writeBuf{ buf: c.scratch[:5], pos: 1, } } func Open(name string) (_ driver.Conn, err error) { return DialOpen(defaultDialer{}, name) } func DialOpen(d Dialer, name string) (_ driver.Conn, err error) { // Handle any panics during connection initialization. Note that we // specifically do *not* want to use errRecover(), as that would turn any // connection errors into ErrBadConns, hiding the real error message from // the user. defer errRecoverNoErrBadConn(&err) o := make(values) // A number of defaults are applied here, in this order: // // * Very low precedence defaults applied in every situation // * Environment variables // * Explicitly passed connection information o.Set("host", "localhost") o.Set("port", "5432") // N.B.: Extra float digits should be set to 3, but that breaks // Postgres 8.4 and older, where the max is 2. o.Set("extra_float_digits", "2") for k, v := range parseEnviron(os.Environ()) { o.Set(k, v) } if strings.HasPrefix(name, "postgres://") || strings.HasPrefix(name, "postgresql://") { name, err = ParseURL(name) if err != nil { return nil, err } } if err := parseOpts(name, o); err != nil { return nil, err } // Use the "fallback" application name if necessary if fallback := o.Get("fallback_application_name"); fallback != "" { if !o.Isset("application_name") { o.Set("application_name", fallback) } } // We can't work with any client_encoding other than UTF-8 currently. // However, we have historically allowed the user to set it to UTF-8 // explicitly, and there's no reason to break such programs, so allow that. // Note that the "options" setting could also set client_encoding, but // parsing its value is not worth it. Instead, we always explicitly send // client_encoding as a separate run-time parameter, which should override // anything set in options. if enc := o.Get("client_encoding"); enc != "" && !isUTF8(enc) { return nil, errors.New("client_encoding must be absent or 'UTF8'") } o.Set("client_encoding", "UTF8") // DateStyle needs a similar treatment. if datestyle := o.Get("datestyle"); datestyle != "" { if datestyle != "ISO, MDY" { panic(fmt.Sprintf("setting datestyle must be absent or %v; got %v", "ISO, MDY", datestyle)) } } else { o.Set("datestyle", "ISO, MDY") } // If a user is not provided by any other means, the last // resort is to use the current operating system provided user // name. if o.Get("user") == "" { u, err := userCurrent() if err != nil { return nil, err } else { o.Set("user", u) } } cn := &conn{} err = cn.handleDriverSettings(o) if err != nil { return nil, err } cn.c, err = dial(d, o) if err != nil { return nil, err } cn.ssl(o) cn.buf = bufio.NewReader(cn.c) cn.startup(o) // reset the deadline, in case one was set (see dial) if timeout := o.Get("connect_timeout"); timeout != "" && timeout != "0" { err = cn.c.SetDeadline(time.Time{}) } return cn, err } func dial(d Dialer, o values) (net.Conn, error) { ntw, addr := network(o) // SSL is not necessary or supported over UNIX domain sockets if ntw == "unix" { o["sslmode"] = "disable" } // Zero or not specified means wait indefinitely. if timeout := o.Get("connect_timeout"); timeout != "" && timeout != "0" { seconds, err := strconv.ParseInt(timeout, 10, 0) if err != nil { return nil, fmt.Errorf("invalid value for parameter connect_timeout: %s", err) } duration := time.Duration(seconds) * time.Second // connect_timeout should apply to the entire connection establishment // procedure, so we both use a timeout for the TCP connection // establishment and set a deadline for doing the initial handshake. // The deadline is then reset after startup() is done. deadline := time.Now().Add(duration) conn, err := d.DialTimeout(ntw, addr, duration) if err != nil { return nil, err } err = conn.SetDeadline(deadline) return conn, err } return d.Dial(ntw, addr) } func network(o values) (string, string) { host := o.Get("host") if strings.HasPrefix(host, "/") { sockPath := path.Join(host, ".s.PGSQL."+o.Get("port")) return "unix", sockPath } return "tcp", host + ":" + o.Get("port") } type values map[string]string func (vs values) Set(k, v string) { vs[k] = v } func (vs values) Get(k string) (v string) { return vs[k] } func (vs values) Isset(k string) bool { _, ok := vs[k] return ok } // scanner implements a tokenizer for libpq-style option strings. type scanner struct { s []rune i int } // newScanner returns a new scanner initialized with the option string s. func newScanner(s string) *scanner { return &scanner{[]rune(s), 0} } // Next returns the next rune. // It returns 0, false if the end of the text has been reached. func (s *scanner) Next() (rune, bool) { if s.i >= len(s.s) { return 0, false } r := s.s[s.i] s.i++ return r, true } // SkipSpaces returns the next non-whitespace rune. // It returns 0, false if the end of the text has been reached. func (s *scanner) SkipSpaces() (rune, bool) { r, ok := s.Next() for unicode.IsSpace(r) && ok { r, ok = s.Next() } return r, ok } // parseOpts parses the options from name and adds them to the values. // // The parsing code is based on conninfo_parse from libpq's fe-connect.c func parseOpts(name string, o values) error { s := newScanner(name) for { var ( keyRunes, valRunes []rune r rune ok bool ) if r, ok = s.SkipSpaces(); !ok { break } // Scan the key for !unicode.IsSpace(r) && r != '=' { keyRunes = append(keyRunes, r) if r, ok = s.Next(); !ok { break } } // Skip any whitespace if we're not at the = yet if r != '=' { r, ok = s.SkipSpaces() } // The current character should be = if r != '=' || !ok { return fmt.Errorf(`missing "=" after %q in connection info string"`, string(keyRunes)) } // Skip any whitespace after the = if r, ok = s.SkipSpaces(); !ok { // If we reach the end here, the last value is just an empty string as per libpq. o.Set(string(keyRunes), "") break } if r != '\'' { for !unicode.IsSpace(r) { if r == '\\' { if r, ok = s.Next(); !ok { return fmt.Errorf(`missing character after backslash`) } } valRunes = append(valRunes, r) if r, ok = s.Next(); !ok { break } } } else { quote: for { if r, ok = s.Next(); !ok { return fmt.Errorf(`unterminated quoted string literal in connection string`) } switch r { case '\'': break quote case '\\': r, _ = s.Next() fallthrough default: valRunes = append(valRunes, r) } } } o.Set(string(keyRunes), string(valRunes)) } return nil } func (cn *conn) isInTransaction() bool { return cn.txnStatus == txnStatusIdleInTransaction || cn.txnStatus == txnStatusInFailedTransaction } func (cn *conn) checkIsInTransaction(intxn bool) { if cn.isInTransaction() != intxn { cn.bad = true errorf("unexpected transaction status %v", cn.txnStatus) } } func (cn *conn) Begin() (_ driver.Tx, err error) { if cn.bad { return nil, driver.ErrBadConn } defer cn.errRecover(&err) cn.checkIsInTransaction(false) _, commandTag, err := cn.simpleExec("BEGIN") if err != nil { return nil, err } if commandTag != "BEGIN" { cn.bad = true return nil, fmt.Errorf("unexpected command tag %s", commandTag) } if cn.txnStatus != txnStatusIdleInTransaction { cn.bad = true return nil, fmt.Errorf("unexpected transaction status %v", cn.txnStatus) } return cn, nil } func (cn *conn) Commit() (err error) { if cn.bad { return driver.ErrBadConn } defer cn.errRecover(&err) cn.checkIsInTransaction(true) // We don't want the client to think that everything is okay if it tries // to commit a failed transaction. However, no matter what we return, // database/sql will release this connection back into the free connection // pool so we have to abort the current transaction here. Note that you // would get the same behaviour if you issued a COMMIT in a failed // transaction, so it's also the least surprising thing to do here. if cn.txnStatus == txnStatusInFailedTransaction { if err := cn.Rollback(); err != nil { return err } return ErrInFailedTransaction } _, commandTag, err := cn.simpleExec("COMMIT") if err != nil { if cn.isInTransaction() { cn.bad = true } return err } if commandTag != "COMMIT" { cn.bad = true return fmt.Errorf("unexpected command tag %s", commandTag) } cn.checkIsInTransaction(false) return nil } func (cn *conn) Rollback() (err error) { if cn.bad { return driver.ErrBadConn } defer cn.errRecover(&err) cn.checkIsInTransaction(true) _, commandTag, err := cn.simpleExec("ROLLBACK") if err != nil { if cn.isInTransaction() { cn.bad = true } return err } if commandTag != "ROLLBACK" { return fmt.Errorf("unexpected command tag %s", commandTag) } cn.checkIsInTransaction(false) return nil } func (cn *conn) gname() string { cn.namei++ return strconv.FormatInt(int64(cn.namei), 10) } func (cn *conn) simpleExec(q string) (res driver.Result, commandTag string, err error) { b := cn.writeBuf('Q') b.string(q) cn.send(b) for { t, r := cn.recv1() switch t { case 'C': res, commandTag = cn.parseComplete(r.string()) case 'Z': cn.processReadyForQuery(r) // done return case 'E': err = parseError(r) case 'T', 'D', 'I': // ignore any results default: cn.bad = true errorf("unknown response for simple query: %q", t) } } } func (cn *conn) simpleQuery(q string) (res *rows, err error) { defer cn.errRecover(&err) st := &stmt{cn: cn, name: ""} b := cn.writeBuf('Q') b.string(q) cn.send(b) for { t, r := cn.recv1() switch t { case 'C', 'I': // We allow queries which don't return any results through Query as // well as Exec. We still have to give database/sql a rows object // the user can close, though, to avoid connections from being // leaked. A "rows" with done=true works fine for that purpose. if err != nil { cn.bad = true errorf("unexpected message %q in simple query execution", t) } res = &rows{ cn: cn, colNames: st.colNames, colTyps: st.colTyps, colFmts: st.colFmts, done: true, } case 'Z': cn.processReadyForQuery(r) // done return case 'E': res = nil err = parseError(r) case 'D': if res == nil { cn.bad = true errorf("unexpected DataRow in simple query execution") } // the query didn't fail; kick off to Next cn.saveMessage(t, r) return case 'T': // res might be non-nil here if we received a previous // CommandComplete, but that's fine; just overwrite it res = &rows{cn: cn} res.colNames, res.colFmts, res.colTyps = parsePortalRowDescribe(r) // To work around a bug in QueryRow in Go 1.2 and earlier, wait // until the first DataRow has been received. default: cn.bad = true errorf("unknown response for simple query: %q", t) } } } // Decides which column formats to use for a prepared statement. The input is // an array of type oids, one element per result column. func decideColumnFormats(colTyps []oid.Oid, forceText bool) (colFmts []format, colFmtData []byte) { if len(colTyps) == 0 { return nil, colFmtDataAllText } colFmts = make([]format, len(colTyps)) if forceText { return colFmts, colFmtDataAllText } allBinary := true allText := true for i, o := range colTyps { switch o { // This is the list of types to use binary mode for when receiving them // through a prepared statement. If a type appears in this list, it // must also be implemented in binaryDecode in encode.go. case oid.T_bytea: fallthrough case oid.T_int8: fallthrough case oid.T_int4: fallthrough case oid.T_int2: colFmts[i] = formatBinary allText = false default: allBinary = false } } if allBinary { return colFmts, colFmtDataAllBinary } else if allText { return colFmts, colFmtDataAllText } else { colFmtData = make([]byte, 2+len(colFmts)*2) binary.BigEndian.PutUint16(colFmtData, uint16(len(colFmts))) for i, v := range colFmts { binary.BigEndian.PutUint16(colFmtData[2+i*2:], uint16(v)) } return colFmts, colFmtData } } func (cn *conn) prepareTo(q, stmtName string) *stmt { st := &stmt{cn: cn, name: stmtName} b := cn.writeBuf('P') b.string(st.name) b.string(q) b.int16(0) b.next('D') b.byte('S') b.string(st.name) b.next('S') cn.send(b) cn.readParseResponse() st.paramTyps, st.colNames, st.colTyps = cn.readStatementDescribeResponse() st.colFmts, st.colFmtData = decideColumnFormats(st.colTyps, cn.disablePreparedBinaryResult) cn.readReadyForQuery() return st } func (cn *conn) Prepare(q string) (_ driver.Stmt, err error) { if cn.bad { return nil, driver.ErrBadConn } defer cn.errRecover(&err) if len(q) >= 4 && strings.EqualFold(q[:4], "COPY") { return cn.prepareCopyIn(q) } return cn.prepareTo(q, cn.gname()), nil } func (cn *conn) Close() (err error) { if cn.bad { return driver.ErrBadConn } defer cn.errRecover(&err) // Don't go through send(); ListenerConn relies on us not scribbling on the // scratch buffer of this connection. err = cn.sendSimpleMessage('X') if err != nil { return err } return cn.c.Close() } // Implement the "Queryer" interface func (cn *conn) Query(query string, args []driver.Value) (_ driver.Rows, err error) { if cn.bad { return nil, driver.ErrBadConn } defer cn.errRecover(&err) // Check to see if we can use the "simpleQuery" interface, which is // *much* faster than going through prepare/exec if len(args) == 0 { return cn.simpleQuery(query) } if cn.binaryParameters { cn.sendBinaryModeQuery(query, args) cn.readParseResponse() cn.readBindResponse() rows := &rows{cn: cn} rows.colNames, rows.colFmts, rows.colTyps = cn.readPortalDescribeResponse() cn.postExecuteWorkaround() return rows, nil } else { st := cn.prepareTo(query, "") st.exec(args) return &rows{ cn: cn, colNames: st.colNames, colTyps: st.colTyps, colFmts: st.colFmts, }, nil } } // Implement the optional "Execer" interface for one-shot queries func (cn *conn) Exec(query string, args []driver.Value) (res driver.Result, err error) { if cn.bad { return nil, driver.ErrBadConn } defer cn.errRecover(&err) // Check to see if we can use the "simpleExec" interface, which is // *much* faster than going through prepare/exec if len(args) == 0 { // ignore commandTag, our caller doesn't care r, _, err := cn.simpleExec(query) return r, err } if cn.binaryParameters { cn.sendBinaryModeQuery(query, args) cn.readParseResponse() cn.readBindResponse() cn.readPortalDescribeResponse() cn.postExecuteWorkaround() res, _, err = cn.readExecuteResponse("Execute") return res, err } else { // Use the unnamed statement to defer planning until bind // time, or else value-based selectivity estimates cannot be // used. st := cn.prepareTo(query, "") r, err := st.Exec(args) if err != nil { panic(err) } return r, err } } func (cn *conn) send(m *writeBuf) { _, err := cn.c.Write(m.wrap()) if err != nil { panic(err) } } func (cn *conn) sendStartupPacket(m *writeBuf) { // sanity check if m.buf[0] != 0 { panic("oops") } _, err := cn.c.Write((m.wrap())[1:]) if err != nil { panic(err) } } // Send a message of type typ to the server on the other end of cn. The // message should have no payload. This method does not use the scratch // buffer. func (cn *conn) sendSimpleMessage(typ byte) (err error) { _, err = cn.c.Write([]byte{typ, '\x00', '\x00', '\x00', '\x04'}) return err } // saveMessage memorizes a message and its buffer in the conn struct. // recvMessage will then return these values on the next call to it. This // method is useful in cases where you have to see what the next message is // going to be (e.g. to see whether it's an error or not) but you can't handle // the message yourself. func (cn *conn) saveMessage(typ byte, buf *readBuf) { if cn.saveMessageType != 0 { cn.bad = true errorf("unexpected saveMessageType %d", cn.saveMessageType) } cn.saveMessageType = typ cn.saveMessageBuffer = *buf } // recvMessage receives any message from the backend, or returns an error if // a problem occurred while reading the message. func (cn *conn) recvMessage(r *readBuf) (byte, error) { // workaround for a QueryRow bug, see exec if cn.saveMessageType != 0 { t := cn.saveMessageType *r = cn.saveMessageBuffer cn.saveMessageType = 0 cn.saveMessageBuffer = nil return t, nil } x := cn.scratch[:5] _, err := io.ReadFull(cn.buf, x) if err != nil { return 0, err } // read the type and length of the message that follows t := x[0] n := int(binary.BigEndian.Uint32(x[1:])) - 4 var y []byte if n <= len(cn.scratch) { y = cn.scratch[:n] } else { y = make([]byte, n) } _, err = io.ReadFull(cn.buf, y) if err != nil { return 0, err } *r = y return t, nil } // recv receives a message from the backend, but if an error happened while // reading the message or the received message was an ErrorResponse, it panics. // NoticeResponses are ignored. This function should generally be used only // during the startup sequence. func (cn *conn) recv() (t byte, r *readBuf) { for { var err error r = &readBuf{} t, err = cn.recvMessage(r) if err != nil { panic(err) } switch t { case 'E': panic(parseError(r)) case 'N': // ignore default: return } } } // recv1Buf is exactly equivalent to recv1, except it uses a buffer supplied by // the caller to avoid an allocation. func (cn *conn) recv1Buf(r *readBuf) byte { for { t, err := cn.recvMessage(r) if err != nil { panic(err) } switch t { case 'A', 'N': // ignore case 'S': cn.processParameterStatus(r) default: return t } } } // recv1 receives a message from the backend, panicking if an error occurs // while attempting to read it. All asynchronous messages are ignored, with // the exception of ErrorResponse. func (cn *conn) recv1() (t byte, r *readBuf) { r = &readBuf{} t = cn.recv1Buf(r) return t, r } func (cn *conn) ssl(o values) { verifyCaOnly := false tlsConf := tls.Config{} switch mode := o.Get("sslmode"); mode { case "require", "": tlsConf.InsecureSkipVerify = true case "verify-ca": // We must skip TLS's own verification since it requires full // verification since Go 1.3. tlsConf.InsecureSkipVerify = true verifyCaOnly = true case "verify-full": tlsConf.ServerName = o.Get("host") case "disable": return default: errorf(`unsupported sslmode %q; only "require" (default), "verify-full", and "disable" supported`, mode) } cn.setupSSLClientCertificates(&tlsConf, o) cn.setupSSLCA(&tlsConf, o) w := cn.writeBuf(0) w.int32(80877103) cn.sendStartupPacket(w) b := cn.scratch[:1] _, err := io.ReadFull(cn.c, b) if err != nil { panic(err) } if b[0] != 'S' { panic(ErrSSLNotSupported) } client := tls.Client(cn.c, &tlsConf) if verifyCaOnly { cn.verifyCA(client, &tlsConf) } cn.c = client } // verifyCA carries out a TLS handshake to the server and verifies the // presented certificate against the effective CA, i.e. the one specified in // sslrootcert or the system CA if sslrootcert was not specified. func (cn *conn) verifyCA(client *tls.Conn, tlsConf *tls.Config) { err := client.Handshake() if err != nil { panic(err) } certs := client.ConnectionState().PeerCertificates opts := x509.VerifyOptions{ DNSName: client.ConnectionState().ServerName, Intermediates: x509.NewCertPool(), Roots: tlsConf.RootCAs, } for i, cert := range certs { if i == 0 { continue } opts.Intermediates.AddCert(cert) } _, err = certs[0].Verify(opts) if err != nil { panic(err) } } // This function sets up SSL client certificates based on either the "sslkey" // and "sslcert" settings (possibly set via the environment variables PGSSLKEY // and PGSSLCERT, respectively), or if they aren't set, from the .postgresql // directory in the user's home directory. If the file paths are set // explicitly, the files must exist. The key file must also not be // world-readable, or this function will panic with // ErrSSLKeyHasWorldPermissions. func (cn *conn) setupSSLClientCertificates(tlsConf *tls.Config, o values) { var missingOk bool sslkey := o.Get("sslkey") sslcert := o.Get("sslcert") if sslkey != "" && sslcert != "" { // If the user has set an sslkey and sslcert, they *must* exist. missingOk = false } else { // Automatically load certificates from ~/.postgresql. user, err := user.Current() if err != nil { // user.Current() might fail when cross-compiling. We have to // ignore the error and continue without client certificates, since // we wouldn't know where to load them from. return } sslkey = filepath.Join(user.HomeDir, ".postgresql", "postgresql.key") sslcert = filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt") missingOk = true } // Check that both files exist, and report the error or stop, depending on // which behaviour we want. Note that we don't do any more extensive // checks than this (such as checking that the paths aren't directories); // LoadX509KeyPair() will take care of the rest. keyfinfo, err := os.Stat(sslkey) if err != nil && missingOk { return } else if err != nil { panic(err) } _, err = os.Stat(sslcert) if err != nil && missingOk { return } else if err != nil { panic(err) } // If we got this far, the key file must also have the correct permissions kmode := keyfinfo.Mode() if kmode != kmode&0600 { panic(ErrSSLKeyHasWorldPermissions) } cert, err := tls.LoadX509KeyPair(sslcert, sslkey) if err != nil { panic(err) } tlsConf.Certificates = []tls.Certificate{cert} } // Sets up RootCAs in the TLS configuration if sslrootcert is set. func (cn *conn) setupSSLCA(tlsConf *tls.Config, o values) { if sslrootcert := o.Get("sslrootcert"); sslrootcert != "" { tlsConf.RootCAs = x509.NewCertPool() cert, err := ioutil.ReadFile(sslrootcert) if err != nil { panic(err) } ok := tlsConf.RootCAs.AppendCertsFromPEM(cert) if !ok { errorf("couldn't parse pem in sslrootcert") } } } // isDriverSetting returns true iff a setting is purely for configuring the // driver's options and should not be sent to the server in the connection // startup packet. func isDriverSetting(key string) bool { switch key { case "host", "port": return true case "password": return true case "sslmode", "sslcert", "sslkey", "sslrootcert": return true case "fallback_application_name": return true case "connect_timeout": return true case "disable_prepared_binary_result": return true case "binary_parameters": return true default: return false } } func (cn *conn) startup(o values) { w := cn.writeBuf(0) w.int32(196608) // Send the backend the name of the database we want to connect to, and the // user we want to connect as. Additionally, we send over any run-time // parameters potentially included in the connection string. If the server // doesn't recognize any of them, it will reply with an error. for k, v := range o { if isDriverSetting(k) { // skip options which can't be run-time parameters continue } // The protocol requires us to supply the database name as "database" // instead of "dbname". if k == "dbname" { k = "database" } w.string(k) w.string(v) } w.string("") cn.sendStartupPacket(w) for { t, r := cn.recv() switch t { case 'K': case 'S': cn.processParameterStatus(r) case 'R': cn.auth(r, o) case 'Z': cn.processReadyForQuery(r) return default: errorf("unknown response for startup: %q", t) } } } func (cn *conn) auth(r *readBuf, o values) { switch code := r.int32(); code { case 0: // OK case 3: w := cn.writeBuf('p') w.string(o.Get("password")) cn.send(w) t, r := cn.recv() if t != 'R' { errorf("unexpected password response: %q", t) } if r.int32() != 0 { errorf("unexpected authentication response: %q", t) } case 5: s := string(r.next(4)) w := cn.writeBuf('p') w.string("md5" + md5s(md5s(o.Get("password")+o.Get("user"))+s)) cn.send(w) t, r := cn.recv() if t != 'R' { errorf("unexpected password response: %q", t) } if r.int32() != 0 { errorf("unexpected authentication response: %q", t) } default: errorf("unknown authentication response: %d", code) } } type format int const formatText format = 0 const formatBinary format = 1 // One result-column format code with the value 1 (i.e. all binary). var colFmtDataAllBinary []byte = []byte{0, 1, 0, 1} // No result-column format codes (i.e. all text). var colFmtDataAllText []byte = []byte{0, 0} type stmt struct { cn *conn name string colNames []string colFmts []format colFmtData []byte colTyps []oid.Oid paramTyps []oid.Oid closed bool } func (st *stmt) Close() (err error) { if st.closed { return nil } if st.cn.bad { return driver.ErrBadConn } defer st.cn.errRecover(&err) w := st.cn.writeBuf('C') w.byte('S') w.string(st.name) st.cn.send(w) st.cn.send(st.cn.writeBuf('S')) t, _ := st.cn.recv1() if t != '3' { st.cn.bad = true errorf("unexpected close response: %q", t) } st.closed = true t, r := st.cn.recv1() if t != 'Z' { st.cn.bad = true errorf("expected ready for query, but got: %q", t) } st.cn.processReadyForQuery(r) return nil } func (st *stmt) Query(v []driver.Value) (r driver.Rows, err error) { if st.cn.bad { return nil, driver.ErrBadConn } defer st.cn.errRecover(&err) st.exec(v) return &rows{ cn: st.cn, colNames: st.colNames, colTyps: st.colTyps, colFmts: st.colFmts, }, nil } func (st *stmt) Exec(v []driver.Value) (res driver.Result, err error) { if st.cn.bad { return nil, driver.ErrBadConn } defer st.cn.errRecover(&err) st.exec(v) res, _, err = st.cn.readExecuteResponse("simple query") return res, err } func (st *stmt) exec(v []driver.Value) { if len(v) >= 65536 { errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(v)) } if len(v) != len(st.paramTyps) { errorf("got %d parameters but the statement requires %d", len(v), len(st.paramTyps)) } cn := st.cn w := cn.writeBuf('B') w.byte(0) // unnamed portal w.string(st.name) if cn.binaryParameters { cn.sendBinaryParameters(w, v) } else { w.int16(0) w.int16(len(v)) for i, x := range v { if x == nil { w.int32(-1) } else { b := encode(&cn.parameterStatus, x, st.paramTyps[i]) w.int32(len(b)) w.bytes(b) } } } w.bytes(st.colFmtData) w.next('E') w.byte(0) w.int32(0) w.next('S') cn.send(w) cn.readBindResponse() cn.postExecuteWorkaround() } func (st *stmt) NumInput() int { return len(st.paramTyps) } // parseComplete parses the "command tag" from a CommandComplete message, and // returns the number of rows affected (if applicable) and a string // identifying only the command that was executed, e.g. "ALTER TABLE". If the // command tag could not be parsed, parseComplete panics. func (cn *conn) parseComplete(commandTag string) (driver.Result, string) { commandsWithAffectedRows := []string{ "SELECT ", // INSERT is handled below "UPDATE ", "DELETE ", "FETCH ", "MOVE ", "COPY ", } var affectedRows *string for _, tag := range commandsWithAffectedRows { if strings.HasPrefix(commandTag, tag) { t := commandTag[len(tag):] affectedRows = &t commandTag = tag[:len(tag)-1] break } } // INSERT also includes the oid of the inserted row in its command tag. // Oids in user tables are deprecated, and the oid is only returned when // exactly one row is inserted, so it's unlikely to be of value to any // real-world application and we can ignore it. if affectedRows == nil && strings.HasPrefix(commandTag, "INSERT ") { parts := strings.Split(commandTag, " ") if len(parts) != 3 { cn.bad = true errorf("unexpected INSERT command tag %s", commandTag) } affectedRows = &parts[len(parts)-1] commandTag = "INSERT" } // There should be no affected rows attached to the tag, just return it if affectedRows == nil { return driver.RowsAffected(0), commandTag } n, err := strconv.ParseInt(*affectedRows, 10, 64) if err != nil { cn.bad = true errorf("could not parse commandTag: %s", err) } return driver.RowsAffected(n), commandTag } type rows struct { cn *conn colNames []string colTyps []oid.Oid colFmts []format done bool rb readBuf } func (rs *rows) Close() error { // no need to look at cn.bad as Next() will for { err := rs.Next(nil) switch err { case nil: case io.EOF: return nil default: return err } } } func (rs *rows) Columns() []string { return rs.colNames } func (rs *rows) Next(dest []driver.Value) (err error) { if rs.done { return io.EOF } conn := rs.cn if conn.bad { return driver.ErrBadConn } defer conn.errRecover(&err) for { t := conn.recv1Buf(&rs.rb) switch t { case 'E': err = parseError(&rs.rb) case 'C', 'I': continue case 'Z': conn.processReadyForQuery(&rs.rb) rs.done = true if err != nil { return err } return io.EOF case 'D': n := rs.rb.int16() if err != nil { conn.bad = true errorf("unexpected DataRow after error %s", err) } if n < len(dest) { dest = dest[:n] } for i := range dest { l := rs.rb.int32() if l == -1 { dest[i] = nil continue } dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.colTyps[i], rs.colFmts[i]) } return default: errorf("unexpected message after execute: %q", t) } } } // QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be // used as part of an SQL statement. For example: // // tblname := "my_table" // data := "my_data" // err = db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", pq.QuoteIdentifier(tblname)), data) // // Any double quotes in name will be escaped. The quoted identifier will be // case sensitive when used in a query. If the input string contains a zero // byte, the result will be truncated immediately before it. func QuoteIdentifier(name string) string { end := strings.IndexRune(name, 0) if end > -1 { name = name[:end] } return `"` + strings.Replace(name, `"`, `""`, -1) + `"` } func md5s(s string) string { h := md5.New() h.Write([]byte(s)) return fmt.Sprintf("%x", h.Sum(nil)) } func (cn *conn) sendBinaryParameters(b *writeBuf, args []driver.Value) { // Do one pass over the parameters to see if we're going to send any of // them over in binary. If we are, create a paramFormats array at the // same time. var paramFormats []int for i, x := range args { _, ok := x.([]byte) if ok { if paramFormats == nil { paramFormats = make([]int, len(args)) } paramFormats[i] = 1 } } if paramFormats == nil { b.int16(0) } else { b.int16(len(paramFormats)) for _, x := range paramFormats { b.int16(x) } } b.int16(len(args)) for _, x := range args { if x == nil { b.int32(-1) } else { datum := binaryEncode(&cn.parameterStatus, x) b.int32(len(datum)) b.bytes(datum) } } } func (cn *conn) sendBinaryModeQuery(query string, args []driver.Value) { if len(args) >= 65536 { errorf("got %d parameters but PostgreSQL only supports 65535 parameters", len(args)) } b := cn.writeBuf('P') b.byte(0) // unnamed statement b.string(query) b.int16(0) b.next('B') b.int16(0) // unnamed portal and statement cn.sendBinaryParameters(b, args) b.bytes(colFmtDataAllText) b.next('D') b.byte('P') b.byte(0) // unnamed portal b.next('E') b.byte(0) b.int32(0) b.next('S') cn.send(b) } func (c *conn) processParameterStatus(r *readBuf) { var err error param := r.string() switch param { case "server_version": var major1 int var major2 int var minor int _, err = fmt.Sscanf(r.string(), "%d.%d.%d", &major1, &major2, &minor) if err == nil { c.parameterStatus.serverVersion = major1*10000 + major2*100 + minor } case "TimeZone": c.parameterStatus.currentLocation, err = time.LoadLocation(r.string()) if err != nil { c.parameterStatus.currentLocation = nil } default: // ignore } } func (c *conn) processReadyForQuery(r *readBuf) { c.txnStatus = transactionStatus(r.byte()) } func (cn *conn) readReadyForQuery() { t, r := cn.recv1() switch t { case 'Z': cn.processReadyForQuery(r) return default: cn.bad = true errorf("unexpected message %q; expected ReadyForQuery", t) } } func (cn *conn) readParseResponse() { t, r := cn.recv1() switch t { case '1': return case 'E': err := parseError(r) cn.readReadyForQuery() panic(err) default: cn.bad = true errorf("unexpected Parse response %q", t) } } func (cn *conn) readStatementDescribeResponse() (paramTyps []oid.Oid, colNames []string, colTyps []oid.Oid) { for { t, r := cn.recv1() switch t { case 't': nparams := r.int16() paramTyps = make([]oid.Oid, nparams) for i := range paramTyps { paramTyps[i] = r.oid() } case 'n': return paramTyps, nil, nil case 'T': colNames, colTyps = parseStatementRowDescribe(r) return paramTyps, colNames, colTyps case 'E': err := parseError(r) cn.readReadyForQuery() panic(err) default: cn.bad = true errorf("unexpected Describe statement response %q", t) } } } func (cn *conn) readPortalDescribeResponse() (colNames []string, colFmts []format, colTyps []oid.Oid) { t, r := cn.recv1() switch t { case 'T': return parsePortalRowDescribe(r) case 'n': return nil, nil, nil case 'E': err := parseError(r) cn.readReadyForQuery() panic(err) default: cn.bad = true errorf("unexpected Describe response %q", t) } panic("not reached") } func (cn *conn) readBindResponse() { t, r := cn.recv1() switch t { case '2': return case 'E': err := parseError(r) cn.readReadyForQuery() panic(err) default: cn.bad = true errorf("unexpected Bind response %q", t) } } func (cn *conn) postExecuteWorkaround() { // Work around a bug in sql.DB.QueryRow: in Go 1.2 and earlier it ignores // any errors from rows.Next, which masks errors that happened during the // execution of the query. To avoid the problem in common cases, we wait // here for one more message from the database. If it's not an error the // query will likely succeed (or perhaps has already, if it's a // CommandComplete), so we push the message into the conn struct; recv1 // will return it as the next message for rows.Next or rows.Close. // However, if it's an error, we wait until ReadyForQuery and then return // the error to our caller. for { t, r := cn.recv1() switch t { case 'E': err := parseError(r) cn.readReadyForQuery() panic(err) case 'C', 'D', 'I': // the query didn't fail, but we can't process this message cn.saveMessage(t, r) return default: cn.bad = true errorf("unexpected message during extended query execution: %q", t) } } } // Only for Exec(), since we ignore the returned data func (cn *conn) readExecuteResponse(protocolState string) (res driver.Result, commandTag string, err error) { for { t, r := cn.recv1() switch t { case 'C': res, commandTag = cn.parseComplete(r.string()) case 'Z': cn.processReadyForQuery(r) return res, commandTag, err case 'E': err = parseError(r) case 'T', 'D', 'I': // ignore any results default: cn.bad = true errorf("unknown %s response: %q", protocolState, t) } } } func parseStatementRowDescribe(r *readBuf) (colNames []string, colTyps []oid.Oid) { n := r.int16() colNames = make([]string, n) colTyps = make([]oid.Oid, n) for i := range colNames { colNames[i] = r.string() r.next(6) colTyps[i] = r.oid() r.next(6) // format code not known when describing a statement; always 0 r.next(2) } return } func parsePortalRowDescribe(r *readBuf) (colNames []string, colFmts []format, colTyps []oid.Oid) { n := r.int16() colNames = make([]string, n) colFmts = make([]format, n) colTyps = make([]oid.Oid, n) for i := range colNames { colNames[i] = r.string() r.next(6) colTyps[i] = r.oid() r.next(6) colFmts[i] = format(r.int16()) } return } // parseEnviron tries to mimic some of libpq's environment handling // // To ease testing, it does not directly reference os.Environ, but is // designed to accept its output. // // Environment-set connection information is intended to have a higher // precedence than a library default but lower than any explicitly // passed information (such as in the URL or connection string). func parseEnviron(env []string) (out map[string]string) { out = make(map[string]string) for _, v := range env { parts := strings.SplitN(v, "=", 2) accrue := func(keyname string) { out[keyname] = parts[1] } unsupported := func() { panic(fmt.Sprintf("setting %v not supported", parts[0])) } // The order of these is the same as is seen in the // PostgreSQL 9.1 manual. Unsupported but well-defined // keys cause a panic; these should be unset prior to // execution. Options which pq expects to be set to a // certain value are allowed, but must be set to that // value if present (they can, of course, be absent). switch parts[0] { case "PGHOST": accrue("host") case "PGHOSTADDR": unsupported() case "PGPORT": accrue("port") case "PGDATABASE": accrue("dbname") case "PGUSER": accrue("user") case "PGPASSWORD": accrue("password") case "PGPASSFILE", "PGSERVICE", "PGSERVICEFILE", "PGREALM": unsupported() case "PGOPTIONS": accrue("options") case "PGAPPNAME": accrue("application_name") case "PGSSLMODE": accrue("sslmode") case "PGSSLCERT": accrue("sslcert") case "PGSSLKEY": accrue("sslkey") case "PGSSLROOTCERT": accrue("sslrootcert") case "PGREQUIRESSL", "PGSSLCRL": unsupported() case "PGREQUIREPEER": unsupported() case "PGKRBSRVNAME", "PGGSSLIB": unsupported() case "PGCONNECT_TIMEOUT": accrue("connect_timeout") case "PGCLIENTENCODING": accrue("client_encoding") case "PGDATESTYLE": accrue("datestyle") case "PGTZ": accrue("timezone") case "PGGEQO": accrue("geqo") case "PGSYSCONFDIR", "PGLOCALEDIR": unsupported() } } return out } // isUTF8 returns whether name is a fuzzy variation of the string "UTF-8". func isUTF8(name string) bool { // Recognize all sorts of silly things as "UTF-8", like Postgres does s := strings.Map(alnumLowerASCII, name) return s == "utf8" || s == "unicode" } func alnumLowerASCII(ch rune) rune { if 'A' <= ch && ch <= 'Z' { return ch + ('a' - 'A') } if 'a' <= ch && ch <= 'z' || '0' <= ch && ch <= '9' { return ch } return -1 // discard } ================================================ FILE: src/github.com/lib/pq/copy.go ================================================ package pq import ( "database/sql/driver" "encoding/binary" "errors" "fmt" "sync" ) var ( errCopyInClosed = errors.New("pq: copyin statement has already been closed") errBinaryCopyNotSupported = errors.New("pq: only text format supported for COPY") errCopyToNotSupported = errors.New("pq: COPY TO is not supported") errCopyNotSupportedOutsideTxn = errors.New("pq: COPY is only allowed inside a transaction") ) // CopyIn creates a COPY FROM statement which can be prepared with // Tx.Prepare(). The target table should be visible in search_path. func CopyIn(table string, columns ...string) string { stmt := "COPY " + QuoteIdentifier(table) + " (" for i, col := range columns { if i != 0 { stmt += ", " } stmt += QuoteIdentifier(col) } stmt += ") FROM STDIN" return stmt } // CopyInSchema creates a COPY FROM statement which can be prepared with // Tx.Prepare(). func CopyInSchema(schema, table string, columns ...string) string { stmt := "COPY " + QuoteIdentifier(schema) + "." + QuoteIdentifier(table) + " (" for i, col := range columns { if i != 0 { stmt += ", " } stmt += QuoteIdentifier(col) } stmt += ") FROM STDIN" return stmt } type copyin struct { cn *conn buffer []byte rowData chan []byte done chan bool closed bool sync.Mutex // guards err err error } const ciBufferSize = 64 * 1024 // flush buffer before the buffer is filled up and needs reallocation const ciBufferFlushSize = 63 * 1024 func (cn *conn) prepareCopyIn(q string) (_ driver.Stmt, err error) { if !cn.isInTransaction() { return nil, errCopyNotSupportedOutsideTxn } ci := ©in{ cn: cn, buffer: make([]byte, 0, ciBufferSize), rowData: make(chan []byte), done: make(chan bool, 1), } // add CopyData identifier + 4 bytes for message length ci.buffer = append(ci.buffer, 'd', 0, 0, 0, 0) b := cn.writeBuf('Q') b.string(q) cn.send(b) awaitCopyInResponse: for { t, r := cn.recv1() switch t { case 'G': if r.byte() != 0 { err = errBinaryCopyNotSupported break awaitCopyInResponse } go ci.resploop() return ci, nil case 'H': err = errCopyToNotSupported break awaitCopyInResponse case 'E': err = parseError(r) case 'Z': if err == nil { cn.bad = true errorf("unexpected ReadyForQuery in response to COPY") } cn.processReadyForQuery(r) return nil, err default: cn.bad = true errorf("unknown response for copy query: %q", t) } } // something went wrong, abort COPY before we return b = cn.writeBuf('f') b.string(err.Error()) cn.send(b) for { t, r := cn.recv1() switch t { case 'c', 'C', 'E': case 'Z': // correctly aborted, we're done cn.processReadyForQuery(r) return nil, err default: cn.bad = true errorf("unknown response for CopyFail: %q", t) } } } func (ci *copyin) flush(buf []byte) { // set message length (without message identifier) binary.BigEndian.PutUint32(buf[1:], uint32(len(buf)-1)) _, err := ci.cn.c.Write(buf) if err != nil { panic(err) } } func (ci *copyin) resploop() { for { var r readBuf t, err := ci.cn.recvMessage(&r) if err != nil { ci.cn.bad = true ci.setError(err) ci.done <- true return } switch t { case 'C': // complete case 'N': // NoticeResponse case 'Z': ci.cn.processReadyForQuery(&r) ci.done <- true return case 'E': err := parseError(&r) ci.setError(err) default: ci.cn.bad = true ci.setError(fmt.Errorf("unknown response during CopyIn: %q", t)) ci.done <- true return } } } func (ci *copyin) isErrorSet() bool { ci.Lock() isSet := (ci.err != nil) ci.Unlock() return isSet } // setError() sets ci.err if one has not been set already. Caller must not be // holding ci.Mutex. func (ci *copyin) setError(err error) { ci.Lock() if ci.err == nil { ci.err = err } ci.Unlock() } func (ci *copyin) NumInput() int { return -1 } func (ci *copyin) Query(v []driver.Value) (r driver.Rows, err error) { return nil, ErrNotSupported } // Exec inserts values into the COPY stream. The insert is asynchronous // and Exec can return errors from previous Exec calls to the same // COPY stmt. // // You need to call Exec(nil) to sync the COPY stream and to get any // errors from pending data, since Stmt.Close() doesn't return errors // to the user. func (ci *copyin) Exec(v []driver.Value) (r driver.Result, err error) { if ci.closed { return nil, errCopyInClosed } if ci.cn.bad { return nil, driver.ErrBadConn } defer ci.cn.errRecover(&err) if ci.isErrorSet() { return nil, ci.err } if len(v) == 0 { err = ci.Close() ci.closed = true return nil, err } numValues := len(v) for i, value := range v { ci.buffer = appendEncodedText(&ci.cn.parameterStatus, ci.buffer, value) if i < numValues-1 { ci.buffer = append(ci.buffer, '\t') } } ci.buffer = append(ci.buffer, '\n') if len(ci.buffer) > ciBufferFlushSize { ci.flush(ci.buffer) // reset buffer, keep bytes for message identifier and length ci.buffer = ci.buffer[:5] } return driver.RowsAffected(0), nil } func (ci *copyin) Close() (err error) { if ci.closed { return errCopyInClosed } if ci.cn.bad { return driver.ErrBadConn } defer ci.cn.errRecover(&err) if len(ci.buffer) > 0 { ci.flush(ci.buffer) } // Avoid touching the scratch buffer as resploop could be using it. err = ci.cn.sendSimpleMessage('c') if err != nil { return err } <-ci.done if ci.isErrorSet() { err = ci.err return err } return nil } ================================================ FILE: src/github.com/lib/pq/doc.go ================================================ /* Package pq is a pure Go Postgres driver for the database/sql package. In most cases clients will use the database/sql package instead of using this package directly. For example: import ( "database/sql" _ "github.com/lib/pq" ) func main() { db, err := sql.Open("postgres", "user=pqgotest dbname=pqgotest sslmode=verify-full") if err != nil { log.Fatal(err) } age := 21 rows, err := db.Query("SELECT name FROM users WHERE age = $1", age) … } You can also connect to a database using a URL. For example: db, err := sql.Open("postgres", "postgres://pqgotest:password@localhost/pqgotest?sslmode=verify-full") Connection String Parameters Similarly to libpq, when establishing a connection using pq you are expected to supply a connection string containing zero or more parameters. A subset of the connection parameters supported by libpq are also supported by pq. Additionally, pq also lets you specify run-time parameters (such as search_path or work_mem) directly in the connection string. This is different from libpq, which does not allow run-time parameters in the connection string, instead requiring you to supply them in the options parameter. For compatibility with libpq, the following special connection parameters are supported: * dbname - The name of the database to connect to * user - The user to sign in as * password - The user's password * host - The host to connect to. Values that start with / are for unix domain sockets. (default is localhost) * port - The port to bind to. (default is 5432) * sslmode - Whether or not to use SSL (default is require, this is not the default for libpq) * fallback_application_name - An application_name to fall back to if one isn't provided. * connect_timeout - Maximum wait for connection, in seconds. Zero or not specified means wait indefinitely. * sslcert - Cert file location. The file must contain PEM encoded data. * sslkey - Key file location. The file must contain PEM encoded data. * sslrootcert - The location of the root certificate file. The file must contain PEM encoded data. Valid values for sslmode are: * disable - No SSL * require - Always SSL (skip verification) * verify-ca - Always SSL (verify that the certificate presented by the server was signed by a trusted CA) * verify-full - Always SSL (verify that the certification presented by the server was signed by a trusted CA and the server host name matches the one in the certificate) See http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING for more information about connection string parameters. Use single quotes for values that contain whitespace: "user=pqgotest password='with spaces'" A backslash will escape the next character in values: "user=space\ man password='it\'s valid' Note that the connection parameter client_encoding (which sets the text encoding for the connection) may be set but must be "UTF8", matching with the same rules as Postgres. It is an error to provide any other value. In addition to the parameters listed above, any run-time parameter that can be set at backend start time can be set in the connection string. For more information, see http://www.postgresql.org/docs/current/static/runtime-config.html. Most environment variables as specified at http://www.postgresql.org/docs/current/static/libpq-envars.html supported by libpq are also supported by pq. If any of the environment variables not supported by pq are set, pq will panic during connection establishment. Environment variables have a lower precedence than explicitly provided connection parameters. Queries database/sql does not dictate any specific format for parameter markers in query strings, and pq uses the Postgres-native ordinal markers, as shown above. The same marker can be reused for the same parameter: rows, err := db.Query(`SELECT name FROM users WHERE favorite_fruit = $1 OR age BETWEEN $2 AND $2 + 3`, "orange", 64) pq does not support the LastInsertId() method of the Result type in database/sql. To return the identifier of an INSERT (or UPDATE or DELETE), use the Postgres RETURNING clause with a standard Query or QueryRow call: var userid int err := db.QueryRow(`INSERT INTO users(name, favorite_fruit, age) VALUES('beatrice', 'starfruit', 93) RETURNING id`).Scan(&userid) For more details on RETURNING, see the Postgres documentation: http://www.postgresql.org/docs/current/static/sql-insert.html http://www.postgresql.org/docs/current/static/sql-update.html http://www.postgresql.org/docs/current/static/sql-delete.html For additional instructions on querying see the documentation for the database/sql package. Errors pq may return errors of type *pq.Error which can be interrogated for error details: if err, ok := err.(*pq.Error); ok { fmt.Println("pq error:", err.Code.Name()) } See the pq.Error type for details. Bulk imports You can perform bulk imports by preparing a statement returned by pq.CopyIn (or pq.CopyInSchema) in an explicit transaction (sql.Tx). The returned statement handle can then be repeatedly "executed" to copy data into the target table. After all data has been processed you should call Exec() once with no arguments to flush all buffered data. Any call to Exec() might return an error which should be handled appropriately, but because of the internal buffering an error returned by Exec() might not be related to the data passed in the call that failed. CopyIn uses COPY FROM internally. It is not possible to COPY outside of an explicit transaction in pq. Usage example: txn, err := db.Begin() if err != nil { log.Fatal(err) } stmt, err := txn.Prepare(pq.CopyIn("users", "name", "age")) if err != nil { log.Fatal(err) } for _, user := range users { _, err = stmt.Exec(user.Name, int64(user.Age)) if err != nil { log.Fatal(err) } } _, err = stmt.Exec() if err != nil { log.Fatal(err) } err = stmt.Close() if err != nil { log.Fatal(err) } err = txn.Commit() if err != nil { log.Fatal(err) } Notifications PostgreSQL supports a simple publish/subscribe model over database connections. See http://www.postgresql.org/docs/current/static/sql-notify.html for more information about the general mechanism. To start listening for notifications, you first have to open a new connection to the database by calling NewListener. This connection can not be used for anything other than LISTEN / NOTIFY. Calling Listen will open a "notification channel"; once a notification channel is open, a notification generated on that channel will effect a send on the Listener.Notify channel. A notification channel will remain open until Unlisten is called, though connection loss might result in some notifications being lost. To solve this problem, Listener sends a nil pointer over the Notify channel any time the connection is re-established following a connection loss. The application can get information about the state of the underlying connection by setting an event callback in the call to NewListener. A single Listener can safely be used from concurrent goroutines, which means that there is often no need to create more than one Listener in your application. However, a Listener is always connected to a single database, so you will need to create a new Listener instance for every database you want to receive notifications in. The channel name in both Listen and Unlisten is case sensitive, and can contain any characters legal in an identifier (see http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS for more information). Note that the channel name will be truncated to 63 bytes by the PostgreSQL server. You can find a complete, working example of Listener usage at http://godoc.org/github.com/lib/pq/listen_example. */ package pq ================================================ FILE: src/github.com/lib/pq/encode.go ================================================ package pq import ( "bytes" "database/sql/driver" "encoding/binary" "encoding/hex" "fmt" "math" "strconv" "strings" "sync" "time" "github.com/lib/pq/oid" ) func binaryEncode(parameterStatus *parameterStatus, x interface{}) []byte { switch v := x.(type) { case []byte: return v default: return encode(parameterStatus, x, oid.T_unknown) } panic("not reached") } func encode(parameterStatus *parameterStatus, x interface{}, pgtypOid oid.Oid) []byte { switch v := x.(type) { case int64: return strconv.AppendInt(nil, v, 10) case float64: return strconv.AppendFloat(nil, v, 'f', -1, 64) case []byte: if pgtypOid == oid.T_bytea { return encodeBytea(parameterStatus.serverVersion, v) } return v case string: if pgtypOid == oid.T_bytea { return encodeBytea(parameterStatus.serverVersion, []byte(v)) } return []byte(v) case bool: return strconv.AppendBool(nil, v) case time.Time: return formatTs(v) default: errorf("encode: unknown type for %T", v) } panic("not reached") } func decode(parameterStatus *parameterStatus, s []byte, typ oid.Oid, f format) interface{} { if f == formatBinary { return binaryDecode(parameterStatus, s, typ) } else { return textDecode(parameterStatus, s, typ) } } func binaryDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { switch typ { case oid.T_bytea: return s case oid.T_int8: return int64(binary.BigEndian.Uint64(s)) case oid.T_int4: return int64(int32(binary.BigEndian.Uint32(s))) case oid.T_int2: return int64(int16(binary.BigEndian.Uint16(s))) default: errorf("don't know how to decode binary parameter of type %u", uint32(typ)) } panic("not reached") } func textDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { switch typ { case oid.T_bytea: return parseBytea(s) case oid.T_timestamptz: return parseTs(parameterStatus.currentLocation, string(s)) case oid.T_timestamp, oid.T_date: return parseTs(nil, string(s)) case oid.T_time: return mustParse("15:04:05", typ, s) case oid.T_timetz: return mustParse("15:04:05-07", typ, s) case oid.T_bool: return s[0] == 't' case oid.T_int8, oid.T_int4, oid.T_int2: i, err := strconv.ParseInt(string(s), 10, 64) if err != nil { errorf("%s", err) } return i case oid.T_float4, oid.T_float8: bits := 64 if typ == oid.T_float4 { bits = 32 } f, err := strconv.ParseFloat(string(s), bits) if err != nil { errorf("%s", err) } return f } return s } // appendEncodedText encodes item in text format as required by COPY // and appends to buf func appendEncodedText(parameterStatus *parameterStatus, buf []byte, x interface{}) []byte { switch v := x.(type) { case int64: return strconv.AppendInt(buf, v, 10) case float64: return strconv.AppendFloat(buf, v, 'f', -1, 64) case []byte: encodedBytea := encodeBytea(parameterStatus.serverVersion, v) return appendEscapedText(buf, string(encodedBytea)) case string: return appendEscapedText(buf, v) case bool: return strconv.AppendBool(buf, v) case time.Time: return append(buf, formatTs(v)...) case nil: return append(buf, "\\N"...) default: errorf("encode: unknown type for %T", v) } panic("not reached") } func appendEscapedText(buf []byte, text string) []byte { escapeNeeded := false startPos := 0 var c byte // check if we need to escape for i := 0; i < len(text); i++ { c = text[i] if c == '\\' || c == '\n' || c == '\r' || c == '\t' { escapeNeeded = true startPos = i break } } if !escapeNeeded { return append(buf, text...) } // copy till first char to escape, iterate the rest result := append(buf, text[:startPos]...) for i := startPos; i < len(text); i++ { c = text[i] switch c { case '\\': result = append(result, '\\', '\\') case '\n': result = append(result, '\\', 'n') case '\r': result = append(result, '\\', 'r') case '\t': result = append(result, '\\', 't') default: result = append(result, c) } } return result } func mustParse(f string, typ oid.Oid, s []byte) time.Time { str := string(s) // check for a 30-minute-offset timezone if (typ == oid.T_timestamptz || typ == oid.T_timetz) && str[len(str)-3] == ':' { f += ":00" } t, err := time.Parse(f, str) if err != nil { errorf("decode: %s", err) } return t } func expect(str, char string, pos int) { if c := str[pos : pos+1]; c != char { errorf("expected '%v' at position %v; got '%v'", char, pos, c) } } func mustAtoi(str string) int { result, err := strconv.Atoi(str) if err != nil { errorf("expected number; got '%v'", str) } return result } // The location cache caches the time zones typically used by the client. type locationCache struct { cache map[int]*time.Location lock sync.Mutex } // All connections share the same list of timezones. Benchmarking shows that // about 5% speed could be gained by putting the cache in the connection and // losing the mutex, at the cost of a small amount of memory and a somewhat // significant increase in code complexity. var globalLocationCache *locationCache = newLocationCache() func newLocationCache() *locationCache { return &locationCache{cache: make(map[int]*time.Location)} } // Returns the cached timezone for the specified offset, creating and caching // it if necessary. func (c *locationCache) getLocation(offset int) *time.Location { c.lock.Lock() defer c.lock.Unlock() location, ok := c.cache[offset] if !ok { location = time.FixedZone("", offset) c.cache[offset] = location } return location } var infinityTsEnabled = false var infinityTsNegative time.Time var infinityTsPositive time.Time const ( infinityTsEnabledAlready = "pq: infinity timestamp enabled already" infinityTsNegativeMustBeSmaller = "pq: infinity timestamp: negative value must be smaller (before) than positive" ) /* * If EnableInfinityTs is not called, "-infinity" and "infinity" will return * []byte("-infinity") and []byte("infinity") respectively, and potentially * cause error "sql: Scan error on column index 0: unsupported driver -> Scan pair: []uint8 -> *time.Time", * when scanning into a time.Time value. * * Once EnableInfinityTs has been called, all connections created using this * driver will decode Postgres' "-infinity" and "infinity" for "timestamp", * "timestamp with time zone" and "date" types to the predefined minimum and * maximum times, respectively. When encoding time.Time values, any time which * equals or preceeds the predefined minimum time will be encoded to * "-infinity". Any values at or past the maximum time will similarly be * encoded to "infinity". * * * If EnableInfinityTs is called with negative >= positive, it will panic. * Calling EnableInfinityTs after a connection has been established results in * undefined behavior. If EnableInfinityTs is called more than once, it will * panic. */ func EnableInfinityTs(negative time.Time, positive time.Time) { if infinityTsEnabled { panic(infinityTsEnabledAlready) } if !negative.Before(positive) { panic(infinityTsNegativeMustBeSmaller) } infinityTsEnabled = true infinityTsNegative = negative infinityTsPositive = positive } /* * Testing might want to toggle infinityTsEnabled */ func disableInfinityTs() { infinityTsEnabled = false } // This is a time function specific to the Postgres default DateStyle // setting ("ISO, MDY"), the only one we currently support. This // accounts for the discrepancies between the parsing available with // time.Parse and the Postgres date formatting quirks. func parseTs(currentLocation *time.Location, str string) interface{} { switch str { case "-infinity": if infinityTsEnabled { return infinityTsNegative } return []byte(str) case "infinity": if infinityTsEnabled { return infinityTsPositive } return []byte(str) } monSep := strings.IndexRune(str, '-') // this is Gregorian year, not ISO Year // In Gregorian system, the year 1 BC is followed by AD 1 year := mustAtoi(str[:monSep]) daySep := monSep + 3 month := mustAtoi(str[monSep+1 : daySep]) expect(str, "-", daySep) timeSep := daySep + 3 day := mustAtoi(str[daySep+1 : timeSep]) var hour, minute, second int if len(str) > monSep+len("01-01")+1 { expect(str, " ", timeSep) minSep := timeSep + 3 expect(str, ":", minSep) hour = mustAtoi(str[timeSep+1 : minSep]) secSep := minSep + 3 expect(str, ":", secSep) minute = mustAtoi(str[minSep+1 : secSep]) secEnd := secSep + 3 second = mustAtoi(str[secSep+1 : secEnd]) } remainderIdx := monSep + len("01-01 00:00:00") + 1 // Three optional (but ordered) sections follow: the // fractional seconds, the time zone offset, and the BC // designation. We set them up here and adjust the other // offsets if the preceding sections exist. nanoSec := 0 tzOff := 0 if remainderIdx < len(str) && str[remainderIdx:remainderIdx+1] == "." { fracStart := remainderIdx + 1 fracOff := strings.IndexAny(str[fracStart:], "-+ ") if fracOff < 0 { fracOff = len(str) - fracStart } fracSec := mustAtoi(str[fracStart : fracStart+fracOff]) nanoSec = fracSec * (1000000000 / int(math.Pow(10, float64(fracOff)))) remainderIdx += fracOff + 1 } if tzStart := remainderIdx; tzStart < len(str) && (str[tzStart:tzStart+1] == "-" || str[tzStart:tzStart+1] == "+") { // time zone separator is always '-' or '+' (UTC is +00) var tzSign int if c := str[tzStart : tzStart+1]; c == "-" { tzSign = -1 } else if c == "+" { tzSign = +1 } else { errorf("expected '-' or '+' at position %v; got %v", tzStart, c) } tzHours := mustAtoi(str[tzStart+1 : tzStart+3]) remainderIdx += 3 var tzMin, tzSec int if tzStart+3 < len(str) && str[tzStart+3:tzStart+4] == ":" { tzMin = mustAtoi(str[tzStart+4 : tzStart+6]) remainderIdx += 3 } if tzStart+6 < len(str) && str[tzStart+6:tzStart+7] == ":" { tzSec = mustAtoi(str[tzStart+7 : tzStart+9]) remainderIdx += 3 } tzOff = tzSign * ((tzHours * 60 * 60) + (tzMin * 60) + tzSec) } var isoYear int if remainderIdx < len(str) && str[remainderIdx:remainderIdx+3] == " BC" { isoYear = 1 - year remainderIdx += 3 } else { isoYear = year } if remainderIdx < len(str) { errorf("expected end of input, got %v", str[remainderIdx:]) } t := time.Date(isoYear, time.Month(month), day, hour, minute, second, nanoSec, globalLocationCache.getLocation(tzOff)) if currentLocation != nil { // Set the location of the returned Time based on the session's // TimeZone value, but only if the local time zone database agrees with // the remote database on the offset. lt := t.In(currentLocation) _, newOff := lt.Zone() if newOff == tzOff { t = lt } } return t } // formatTs formats t into a format postgres understands. func formatTs(t time.Time) (b []byte) { if infinityTsEnabled { // t <= -infinity : ! (t > -infinity) if !t.After(infinityTsNegative) { return []byte("-infinity") } // t >= infinity : ! (!t < infinity) if !t.Before(infinityTsPositive) { return []byte("infinity") } } // Need to send dates before 0001 A.D. with " BC" suffix, instead of the // minus sign preferred by Go. // Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on bc := false if t.Year() <= 0 { // flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11" t = t.AddDate((-t.Year())*2+1, 0, 0) bc = true } b = []byte(t.Format(time.RFC3339Nano)) _, offset := t.Zone() offset = offset % 60 if offset != 0 { // RFC3339Nano already printed the minus sign if offset < 0 { offset = -offset } b = append(b, ':') if offset < 10 { b = append(b, '0') } b = strconv.AppendInt(b, int64(offset), 10) } if bc { b = append(b, " BC"...) } return b } // Parse a bytea value received from the server. Both "hex" and the legacy // "escape" format are supported. func parseBytea(s []byte) (result []byte) { if len(s) >= 2 && bytes.Equal(s[:2], []byte("\\x")) { // bytea_output = hex s = s[2:] // trim off leading "\\x" result = make([]byte, hex.DecodedLen(len(s))) _, err := hex.Decode(result, s) if err != nil { errorf("%s", err) } } else { // bytea_output = escape for len(s) > 0 { if s[0] == '\\' { // escaped '\\' if len(s) >= 2 && s[1] == '\\' { result = append(result, '\\') s = s[2:] continue } // '\\' followed by an octal number if len(s) < 4 { errorf("invalid bytea sequence %v", s) } r, err := strconv.ParseInt(string(s[1:4]), 8, 9) if err != nil { errorf("could not parse bytea value: %s", err.Error()) } result = append(result, byte(r)) s = s[4:] } else { // We hit an unescaped, raw byte. Try to read in as many as // possible in one go. i := bytes.IndexByte(s, '\\') if i == -1 { result = append(result, s...) break } result = append(result, s[:i]...) s = s[i:] } } } return result } func encodeBytea(serverVersion int, v []byte) (result []byte) { if serverVersion >= 90000 { // Use the hex format if we know that the server supports it result = make([]byte, 2+hex.EncodedLen(len(v))) result[0] = '\\' result[1] = 'x' hex.Encode(result[2:], v) } else { // .. or resort to "escape" for _, b := range v { if b == '\\' { result = append(result, '\\', '\\') } else if b < 0x20 || b > 0x7e { result = append(result, []byte(fmt.Sprintf("\\%03o", b))...) } else { result = append(result, b) } } } return result } // NullTime represents a time.Time that may be null. NullTime implements the // sql.Scanner interface so it can be used as a scan destination, similar to // sql.NullString. type NullTime struct { Time time.Time Valid bool // Valid is true if Time is not NULL } // Scan implements the Scanner interface. func (nt *NullTime) Scan(value interface{}) error { nt.Time, nt.Valid = value.(time.Time) return nil } // Value implements the driver Valuer interface. func (nt NullTime) Value() (driver.Value, error) { if !nt.Valid { return nil, nil } return nt.Time, nil } ================================================ FILE: src/github.com/lib/pq/error.go ================================================ package pq import ( "database/sql/driver" "fmt" "io" "net" "runtime" ) // Error severities const ( Efatal = "FATAL" Epanic = "PANIC" Ewarning = "WARNING" Enotice = "NOTICE" Edebug = "DEBUG" Einfo = "INFO" Elog = "LOG" ) // Error represents an error communicating with the server. // // See http://www.postgresql.org/docs/current/static/protocol-error-fields.html for details of the fields type Error struct { Severity string Code ErrorCode Message string Detail string Hint string Position string InternalPosition string InternalQuery string Where string Schema string Table string Column string DataTypeName string Constraint string File string Line string Routine string } // ErrorCode is a five-character error code. type ErrorCode string // Name returns a more human friendly rendering of the error code, namely the // "condition name". // // See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for // details. func (ec ErrorCode) Name() string { return errorCodeNames[ec] } // ErrorClass is only the class part of an error code. type ErrorClass string // Name returns the condition name of an error class. It is equivalent to the // condition name of the "standard" error code (i.e. the one having the last // three characters "000"). func (ec ErrorClass) Name() string { return errorCodeNames[ErrorCode(ec+"000")] } // Class returns the error class, e.g. "28". // // See http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html for // details. func (ec ErrorCode) Class() ErrorClass { return ErrorClass(ec[0:2]) } // errorCodeNames is a mapping between the five-character error codes and the // human readable "condition names". It is derived from the list at // http://www.postgresql.org/docs/9.3/static/errcodes-appendix.html var errorCodeNames = map[ErrorCode]string{ // Class 00 - Successful Completion "00000": "successful_completion", // Class 01 - Warning "01000": "warning", "0100C": "dynamic_result_sets_returned", "01008": "implicit_zero_bit_padding", "01003": "null_value_eliminated_in_set_function", "01007": "privilege_not_granted", "01006": "privilege_not_revoked", "01004": "string_data_right_truncation", "01P01": "deprecated_feature", // Class 02 - No Data (this is also a warning class per the SQL standard) "02000": "no_data", "02001": "no_additional_dynamic_result_sets_returned", // Class 03 - SQL Statement Not Yet Complete "03000": "sql_statement_not_yet_complete", // Class 08 - Connection Exception "08000": "connection_exception", "08003": "connection_does_not_exist", "08006": "connection_failure", "08001": "sqlclient_unable_to_establish_sqlconnection", "08004": "sqlserver_rejected_establishment_of_sqlconnection", "08007": "transaction_resolution_unknown", "08P01": "protocol_violation", // Class 09 - Triggered Action Exception "09000": "triggered_action_exception", // Class 0A - Feature Not Supported "0A000": "feature_not_supported", // Class 0B - Invalid Transaction Initiation "0B000": "invalid_transaction_initiation", // Class 0F - Locator Exception "0F000": "locator_exception", "0F001": "invalid_locator_specification", // Class 0L - Invalid Grantor "0L000": "invalid_grantor", "0LP01": "invalid_grant_operation", // Class 0P - Invalid Role Specification "0P000": "invalid_role_specification", // Class 0Z - Diagnostics Exception "0Z000": "diagnostics_exception", "0Z002": "stacked_diagnostics_accessed_without_active_handler", // Class 20 - Case Not Found "20000": "case_not_found", // Class 21 - Cardinality Violation "21000": "cardinality_violation", // Class 22 - Data Exception "22000": "data_exception", "2202E": "array_subscript_error", "22021": "character_not_in_repertoire", "22008": "datetime_field_overflow", "22012": "division_by_zero", "22005": "error_in_assignment", "2200B": "escape_character_conflict", "22022": "indicator_overflow", "22015": "interval_field_overflow", "2201E": "invalid_argument_for_logarithm", "22014": "invalid_argument_for_ntile_function", "22016": "invalid_argument_for_nth_value_function", "2201F": "invalid_argument_for_power_function", "2201G": "invalid_argument_for_width_bucket_function", "22018": "invalid_character_value_for_cast", "22007": "invalid_datetime_format", "22019": "invalid_escape_character", "2200D": "invalid_escape_octet", "22025": "invalid_escape_sequence", "22P06": "nonstandard_use_of_escape_character", "22010": "invalid_indicator_parameter_value", "22023": "invalid_parameter_value", "2201B": "invalid_regular_expression", "2201W": "invalid_row_count_in_limit_clause", "2201X": "invalid_row_count_in_result_offset_clause", "22009": "invalid_time_zone_displacement_value", "2200C": "invalid_use_of_escape_character", "2200G": "most_specific_type_mismatch", "22004": "null_value_not_allowed", "22002": "null_value_no_indicator_parameter", "22003": "numeric_value_out_of_range", "22026": "string_data_length_mismatch", "22001": "string_data_right_truncation", "22011": "substring_error", "22027": "trim_error", "22024": "unterminated_c_string", "2200F": "zero_length_character_string", "22P01": "floating_point_exception", "22P02": "invalid_text_representation", "22P03": "invalid_binary_representation", "22P04": "bad_copy_file_format", "22P05": "untranslatable_character", "2200L": "not_an_xml_document", "2200M": "invalid_xml_document", "2200N": "invalid_xml_content", "2200S": "invalid_xml_comment", "2200T": "invalid_xml_processing_instruction", // Class 23 - Integrity Constraint Violation "23000": "integrity_constraint_violation", "23001": "restrict_violation", "23502": "not_null_violation", "23503": "foreign_key_violation", "23505": "unique_violation", "23514": "check_violation", "23P01": "exclusion_violation", // Class 24 - Invalid Cursor State "24000": "invalid_cursor_state", // Class 25 - Invalid Transaction State "25000": "invalid_transaction_state", "25001": "active_sql_transaction", "25002": "branch_transaction_already_active", "25008": "held_cursor_requires_same_isolation_level", "25003": "inappropriate_access_mode_for_branch_transaction", "25004": "inappropriate_isolation_level_for_branch_transaction", "25005": "no_active_sql_transaction_for_branch_transaction", "25006": "read_only_sql_transaction", "25007": "schema_and_data_statement_mixing_not_supported", "25P01": "no_active_sql_transaction", "25P02": "in_failed_sql_transaction", // Class 26 - Invalid SQL Statement Name "26000": "invalid_sql_statement_name", // Class 27 - Triggered Data Change Violation "27000": "triggered_data_change_violation", // Class 28 - Invalid Authorization Specification "28000": "invalid_authorization_specification", "28P01": "invalid_password", // Class 2B - Dependent Privilege Descriptors Still Exist "2B000": "dependent_privilege_descriptors_still_exist", "2BP01": "dependent_objects_still_exist", // Class 2D - Invalid Transaction Termination "2D000": "invalid_transaction_termination", // Class 2F - SQL Routine Exception "2F000": "sql_routine_exception", "2F005": "function_executed_no_return_statement", "2F002": "modifying_sql_data_not_permitted", "2F003": "prohibited_sql_statement_attempted", "2F004": "reading_sql_data_not_permitted", // Class 34 - Invalid Cursor Name "34000": "invalid_cursor_name", // Class 38 - External Routine Exception "38000": "external_routine_exception", "38001": "containing_sql_not_permitted", "38002": "modifying_sql_data_not_permitted", "38003": "prohibited_sql_statement_attempted", "38004": "reading_sql_data_not_permitted", // Class 39 - External Routine Invocation Exception "39000": "external_routine_invocation_exception", "39001": "invalid_sqlstate_returned", "39004": "null_value_not_allowed", "39P01": "trigger_protocol_violated", "39P02": "srf_protocol_violated", // Class 3B - Savepoint Exception "3B000": "savepoint_exception", "3B001": "invalid_savepoint_specification", // Class 3D - Invalid Catalog Name "3D000": "invalid_catalog_name", // Class 3F - Invalid Schema Name "3F000": "invalid_schema_name", // Class 40 - Transaction Rollback "40000": "transaction_rollback", "40002": "transaction_integrity_constraint_violation", "40001": "serialization_failure", "40003": "statement_completion_unknown", "40P01": "deadlock_detected", // Class 42 - Syntax Error or Access Rule Violation "42000": "syntax_error_or_access_rule_violation", "42601": "syntax_error", "42501": "insufficient_privilege", "42846": "cannot_coerce", "42803": "grouping_error", "42P20": "windowing_error", "42P19": "invalid_recursion", "42830": "invalid_foreign_key", "42602": "invalid_name", "42622": "name_too_long", "42939": "reserved_name", "42804": "datatype_mismatch", "42P18": "indeterminate_datatype", "42P21": "collation_mismatch", "42P22": "indeterminate_collation", "42809": "wrong_object_type", "42703": "undefined_column", "42883": "undefined_function", "42P01": "undefined_table", "42P02": "undefined_parameter", "42704": "undefined_object", "42701": "duplicate_column", "42P03": "duplicate_cursor", "42P04": "duplicate_database", "42723": "duplicate_function", "42P05": "duplicate_prepared_statement", "42P06": "duplicate_schema", "42P07": "duplicate_table", "42712": "duplicate_alias", "42710": "duplicate_object", "42702": "ambiguous_column", "42725": "ambiguous_function", "42P08": "ambiguous_parameter", "42P09": "ambiguous_alias", "42P10": "invalid_column_reference", "42611": "invalid_column_definition", "42P11": "invalid_cursor_definition", "42P12": "invalid_database_definition", "42P13": "invalid_function_definition", "42P14": "invalid_prepared_statement_definition", "42P15": "invalid_schema_definition", "42P16": "invalid_table_definition", "42P17": "invalid_object_definition", // Class 44 - WITH CHECK OPTION Violation "44000": "with_check_option_violation", // Class 53 - Insufficient Resources "53000": "insufficient_resources", "53100": "disk_full", "53200": "out_of_memory", "53300": "too_many_connections", "53400": "configuration_limit_exceeded", // Class 54 - Program Limit Exceeded "54000": "program_limit_exceeded", "54001": "statement_too_complex", "54011": "too_many_columns", "54023": "too_many_arguments", // Class 55 - Object Not In Prerequisite State "55000": "object_not_in_prerequisite_state", "55006": "object_in_use", "55P02": "cant_change_runtime_param", "55P03": "lock_not_available", // Class 57 - Operator Intervention "57000": "operator_intervention", "57014": "query_canceled", "57P01": "admin_shutdown", "57P02": "crash_shutdown", "57P03": "cannot_connect_now", "57P04": "database_dropped", // Class 58 - System Error (errors external to PostgreSQL itself) "58000": "system_error", "58030": "io_error", "58P01": "undefined_file", "58P02": "duplicate_file", // Class F0 - Configuration File Error "F0000": "config_file_error", "F0001": "lock_file_exists", // Class HV - Foreign Data Wrapper Error (SQL/MED) "HV000": "fdw_error", "HV005": "fdw_column_name_not_found", "HV002": "fdw_dynamic_parameter_value_needed", "HV010": "fdw_function_sequence_error", "HV021": "fdw_inconsistent_descriptor_information", "HV024": "fdw_invalid_attribute_value", "HV007": "fdw_invalid_column_name", "HV008": "fdw_invalid_column_number", "HV004": "fdw_invalid_data_type", "HV006": "fdw_invalid_data_type_descriptors", "HV091": "fdw_invalid_descriptor_field_identifier", "HV00B": "fdw_invalid_handle", "HV00C": "fdw_invalid_option_index", "HV00D": "fdw_invalid_option_name", "HV090": "fdw_invalid_string_length_or_buffer_length", "HV00A": "fdw_invalid_string_format", "HV009": "fdw_invalid_use_of_null_pointer", "HV014": "fdw_too_many_handles", "HV001": "fdw_out_of_memory", "HV00P": "fdw_no_schemas", "HV00J": "fdw_option_name_not_found", "HV00K": "fdw_reply_handle", "HV00Q": "fdw_schema_not_found", "HV00R": "fdw_table_not_found", "HV00L": "fdw_unable_to_create_execution", "HV00M": "fdw_unable_to_create_reply", "HV00N": "fdw_unable_to_establish_connection", // Class P0 - PL/pgSQL Error "P0000": "plpgsql_error", "P0001": "raise_exception", "P0002": "no_data_found", "P0003": "too_many_rows", // Class XX - Internal Error "XX000": "internal_error", "XX001": "data_corrupted", "XX002": "index_corrupted", } func parseError(r *readBuf) *Error { err := new(Error) for t := r.byte(); t != 0; t = r.byte() { msg := r.string() switch t { case 'S': err.Severity = msg case 'C': err.Code = ErrorCode(msg) case 'M': err.Message = msg case 'D': err.Detail = msg case 'H': err.Hint = msg case 'P': err.Position = msg case 'p': err.InternalPosition = msg case 'q': err.InternalQuery = msg case 'W': err.Where = msg case 's': err.Schema = msg case 't': err.Table = msg case 'c': err.Column = msg case 'd': err.DataTypeName = msg case 'n': err.Constraint = msg case 'F': err.File = msg case 'L': err.Line = msg case 'R': err.Routine = msg } } return err } // Fatal returns true if the Error Severity is fatal. func (err *Error) Fatal() bool { return err.Severity == Efatal } // Get implements the legacy PGError interface. New code should use the fields // of the Error struct directly. func (err *Error) Get(k byte) (v string) { switch k { case 'S': return err.Severity case 'C': return string(err.Code) case 'M': return err.Message case 'D': return err.Detail case 'H': return err.Hint case 'P': return err.Position case 'p': return err.InternalPosition case 'q': return err.InternalQuery case 'W': return err.Where case 's': return err.Schema case 't': return err.Table case 'c': return err.Column case 'd': return err.DataTypeName case 'n': return err.Constraint case 'F': return err.File case 'L': return err.Line case 'R': return err.Routine } return "" } func (err Error) Error() string { return "pq: " + err.Message } // PGError is an interface used by previous versions of pq. It is provided // only to support legacy code. New code should use the Error type. type PGError interface { Error() string Fatal() bool Get(k byte) (v string) } func errorf(s string, args ...interface{}) { panic(fmt.Errorf("pq: %s", fmt.Sprintf(s, args...))) } func errRecoverNoErrBadConn(err *error) { e := recover() if e == nil { // Do nothing return } var ok bool *err, ok = e.(error) if !ok { *err = fmt.Errorf("pq: unexpected error: %#v", e) } } func (c *conn) errRecover(err *error) { e := recover() switch v := e.(type) { case nil: // Do nothing case runtime.Error: c.bad = true panic(v) case *Error: if v.Fatal() { *err = driver.ErrBadConn } else { *err = v } case *net.OpError: *err = driver.ErrBadConn case error: if v == io.EOF || v.(error).Error() == "remote error: handshake failure" { *err = driver.ErrBadConn } else { *err = v } default: c.bad = true panic(fmt.Sprintf("unknown error: %#v", e)) } // Any time we return ErrBadConn, we need to remember it since *Tx doesn't // mark the connection bad in database/sql. if *err == driver.ErrBadConn { c.bad = true } } ================================================ FILE: src/github.com/lib/pq/notify.go ================================================ package pq // Package pq is a pure Go Postgres driver for the database/sql package. // This module contains support for Postgres LISTEN/NOTIFY. import ( "errors" "fmt" "sync" "sync/atomic" "time" ) // Notification represents a single notification from the database. type Notification struct { // Process ID (PID) of the notifying postgres backend. BePid int // Name of the channel the notification was sent on. Channel string // Payload, or the empty string if unspecified. Extra string } func recvNotification(r *readBuf) *Notification { bePid := r.int32() channel := r.string() extra := r.string() return &Notification{bePid, channel, extra} } const ( connStateIdle int32 = iota connStateExpectResponse connStateExpectReadyForQuery ) type message struct { typ byte err error } var errListenerConnClosed = errors.New("pq: ListenerConn has been closed") // ListenerConn is a low-level interface for waiting for notifications. You // should use Listener instead. type ListenerConn struct { // guards cn and err connectionLock sync.Mutex cn *conn err error connState int32 // the sending goroutine will be holding this lock senderLock sync.Mutex notificationChan chan<- *Notification replyChan chan message } // Creates a new ListenerConn. Use NewListener instead. func NewListenerConn(name string, notificationChan chan<- *Notification) (*ListenerConn, error) { cn, err := Open(name) if err != nil { return nil, err } l := &ListenerConn{ cn: cn.(*conn), notificationChan: notificationChan, connState: connStateIdle, replyChan: make(chan message, 2), } go l.listenerConnMain() return l, nil } // We can only allow one goroutine at a time to be running a query on the // connection for various reasons, so the goroutine sending on the connection // must be holding senderLock. // // Returns an error if an unrecoverable error has occurred and the ListenerConn // should be abandoned. func (l *ListenerConn) acquireSenderLock() error { // we must acquire senderLock first to avoid deadlocks; see ExecSimpleQuery l.senderLock.Lock() l.connectionLock.Lock() err := l.err l.connectionLock.Unlock() if err != nil { l.senderLock.Unlock() return err } return nil } func (l *ListenerConn) releaseSenderLock() { l.senderLock.Unlock() } // setState advances the protocol state to newState. Returns false if moving // to that state from the current state is not allowed. func (l *ListenerConn) setState(newState int32) bool { var expectedState int32 switch newState { case connStateIdle: expectedState = connStateExpectReadyForQuery case connStateExpectResponse: expectedState = connStateIdle case connStateExpectReadyForQuery: expectedState = connStateExpectResponse default: panic(fmt.Sprintf("unexpected listenerConnState %d", newState)) } return atomic.CompareAndSwapInt32(&l.connState, expectedState, newState) } // Main logic is here: receive messages from the postgres backend, forward // notifications and query replies and keep the internal state in sync with the // protocol state. Returns when the connection has been lost, is about to go // away or should be discarded because we couldn't agree on the state with the // server backend. func (l *ListenerConn) listenerConnLoop() (err error) { defer errRecoverNoErrBadConn(&err) r := &readBuf{} for { t, err := l.cn.recvMessage(r) if err != nil { return err } switch t { case 'A': // recvNotification copies all the data so we don't need to worry // about the scratch buffer being overwritten. l.notificationChan <- recvNotification(r) case 'T', 'D': // only used by tests; ignore case 'E': // We might receive an ErrorResponse even when not in a query; it // is expected that the server will close the connection after // that, but we should make sure that the error we display is the // one from the stray ErrorResponse, not io.ErrUnexpectedEOF. if !l.setState(connStateExpectReadyForQuery) { return parseError(r) } l.replyChan <- message{t, parseError(r)} case 'C', 'I': if !l.setState(connStateExpectReadyForQuery) { // protocol out of sync return fmt.Errorf("unexpected CommandComplete") } // ExecSimpleQuery doesn't need to know about this message case 'Z': if !l.setState(connStateIdle) { // protocol out of sync return fmt.Errorf("unexpected ReadyForQuery") } l.replyChan <- message{t, nil} case 'N', 'S': // ignore default: return fmt.Errorf("unexpected message %q from server in listenerConnLoop", t) } } } // This is the main routine for the goroutine receiving on the database // connection. Most of the main logic is in listenerConnLoop. func (l *ListenerConn) listenerConnMain() { err := l.listenerConnLoop() // listenerConnLoop terminated; we're done, but we still have to clean up. // Make sure nobody tries to start any new queries by making sure the err // pointer is set. It is important that we do not overwrite its value; a // connection could be closed by either this goroutine or one sending on // the connection -- whoever closes the connection is assumed to have the // more meaningful error message (as the other one will probably get // net.errClosed), so that goroutine sets the error we expose while the // other error is discarded. If the connection is lost while two // goroutines are operating on the socket, it probably doesn't matter which // error we expose so we don't try to do anything more complex. l.connectionLock.Lock() if l.err == nil { l.err = err } l.cn.Close() l.connectionLock.Unlock() // There might be a query in-flight; make sure nobody's waiting for a // response to it, since there's not going to be one. close(l.replyChan) // let the listener know we're done close(l.notificationChan) // this ListenerConn is done } // Send a LISTEN query to the server. See ExecSimpleQuery. func (l *ListenerConn) Listen(channel string) (bool, error) { return l.ExecSimpleQuery("LISTEN " + QuoteIdentifier(channel)) } // Send an UNLISTEN query to the server. See ExecSimpleQuery. func (l *ListenerConn) Unlisten(channel string) (bool, error) { return l.ExecSimpleQuery("UNLISTEN " + QuoteIdentifier(channel)) } // Send `UNLISTEN *` to the server. See ExecSimpleQuery. func (l *ListenerConn) UnlistenAll() (bool, error) { return l.ExecSimpleQuery("UNLISTEN *") } // Ping the remote server to make sure it's alive. Non-nil error means the // connection has failed and should be abandoned. func (l *ListenerConn) Ping() error { sent, err := l.ExecSimpleQuery("") if !sent { return err } if err != nil { // shouldn't happen panic(err) } return nil } // Attempt to send a query on the connection. Returns an error if sending the // query failed, and the caller should initiate closure of this connection. // The caller must be holding senderLock (see acquireSenderLock and // releaseSenderLock). func (l *ListenerConn) sendSimpleQuery(q string) (err error) { defer errRecoverNoErrBadConn(&err) // must set connection state before sending the query if !l.setState(connStateExpectResponse) { panic("two queries running at the same time") } // Can't use l.cn.writeBuf here because it uses the scratch buffer which // might get overwritten by listenerConnLoop. b := &writeBuf{ buf: []byte("Q\x00\x00\x00\x00"), pos: 1, } b.string(q) l.cn.send(b) return nil } // Execute a "simple query" (i.e. one with no bindable parameters) on the // connection. The possible return values are: // 1) "executed" is true; the query was executed to completion on the // database server. If the query failed, err will be set to the error // returned by the database, otherwise err will be nil. // 2) If "executed" is false, the query could not be executed on the remote // server. err will be non-nil. // // After a call to ExecSimpleQuery has returned an executed=false value, the // connection has either been closed or will be closed shortly thereafter, and // all subsequently executed queries will return an error. func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error) { if err = l.acquireSenderLock(); err != nil { return false, err } defer l.releaseSenderLock() err = l.sendSimpleQuery(q) if err != nil { // We can't know what state the protocol is in, so we need to abandon // this connection. l.connectionLock.Lock() // Set the error pointer if it hasn't been set already; see // listenerConnMain. if l.err == nil { l.err = err } l.connectionLock.Unlock() l.cn.c.Close() return false, err } // now we just wait for a reply.. for { m, ok := <-l.replyChan if !ok { // We lost the connection to server, don't bother waiting for a // a response. err should have been set already. l.connectionLock.Lock() err := l.err l.connectionLock.Unlock() return false, err } switch m.typ { case 'Z': // sanity check if m.err != nil { panic("m.err != nil") } // done; err might or might not be set return true, err case 'E': // sanity check if m.err == nil { panic("m.err == nil") } // server responded with an error; ReadyForQuery to follow err = m.err default: return false, fmt.Errorf("unknown response for simple query: %q", m.typ) } } } func (l *ListenerConn) Close() error { l.connectionLock.Lock() if l.err != nil { l.connectionLock.Unlock() return errListenerConnClosed } l.err = errListenerConnClosed l.connectionLock.Unlock() // We can't send anything on the connection without holding senderLock. // Simply close the net.Conn to wake up everyone operating on it. return l.cn.c.Close() } // Err() returns the reason the connection was closed. It is not safe to call // this function until l.Notify has been closed. func (l *ListenerConn) Err() error { return l.err } var errListenerClosed = errors.New("pq: Listener has been closed") var ErrChannelAlreadyOpen = errors.New("pq: channel is already open") var ErrChannelNotOpen = errors.New("pq: channel is not open") type ListenerEventType int const ( // Emitted only when the database connection has been initially // initialized. err will always be nil. ListenerEventConnected ListenerEventType = iota // Emitted after a database connection has been lost, either because of an // error or because Close has been called. err will be set to the reason // the database connection was lost. ListenerEventDisconnected // Emitted after a database connection has been re-established after // connection loss. err will always be nil. After this event has been // emitted, a nil pq.Notification is sent on the Listener.Notify channel. ListenerEventReconnected // Emitted after a connection to the database was attempted, but failed. // err will be set to an error describing why the connection attempt did // not succeed. ListenerEventConnectionAttemptFailed ) type EventCallbackType func(event ListenerEventType, err error) // Listener provides an interface for listening to notifications from a // PostgreSQL database. For general usage information, see section // "Notifications". // // Listener can safely be used from concurrently running goroutines. type Listener struct { // Channel for receiving notifications from the database. In some cases a // nil value will be sent. See section "Notifications" above. Notify chan *Notification name string minReconnectInterval time.Duration maxReconnectInterval time.Duration eventCallback EventCallbackType lock sync.Mutex isClosed bool reconnectCond *sync.Cond cn *ListenerConn connNotificationChan <-chan *Notification channels map[string]struct{} } // NewListener creates a new database connection dedicated to LISTEN / NOTIFY. // // name should be set to a connection string to be used to establish the // database connection (see section "Connection String Parameters" above). // // minReconnectInterval controls the duration to wait before trying to // re-establish the database connection after connection loss. After each // consecutive failure this interval is doubled, until maxReconnectInterval is // reached. Successfully completing the connection establishment procedure // resets the interval back to minReconnectInterval. // // The last parameter eventCallback can be set to a function which will be // called by the Listener when the state of the underlying database connection // changes. This callback will be called by the goroutine which dispatches the // notifications over the Notify channel, so you should try to avoid doing // potentially time-consuming operations from the callback. func NewListener(name string, minReconnectInterval time.Duration, maxReconnectInterval time.Duration, eventCallback EventCallbackType) *Listener { l := &Listener{ name: name, minReconnectInterval: minReconnectInterval, maxReconnectInterval: maxReconnectInterval, eventCallback: eventCallback, channels: make(map[string]struct{}), Notify: make(chan *Notification, 32), } l.reconnectCond = sync.NewCond(&l.lock) go l.listenerMain() return l } // Returns the notification channel for this listener. This is the same // channel as Notify, and will not be recreated during the life time of the // Listener. func (l *Listener) NotificationChannel() <-chan *Notification { return l.Notify } // Listen starts listening for notifications on a channel. Calls to this // function will block until an acknowledgement has been received from the // server. Note that Listener automatically re-establishes the connection // after connection loss, so this function may block indefinitely if the // connection can not be re-established. // // Listen will only fail in three conditions: // 1) The channel is already open. The returned error will be // ErrChannelAlreadyOpen. // 2) The query was executed on the remote server, but PostgreSQL returned an // error message in response to the query. The returned error will be a // pq.Error containing the information the server supplied. // 3) Close is called on the Listener before the request could be completed. // // The channel name is case-sensitive. func (l *Listener) Listen(channel string) error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } // The server allows you to issue a LISTEN on a channel which is already // open, but it seems useful to be able to detect this case to spot for // mistakes in application logic. If the application genuinely does't // care, it can check the exported error and ignore it. _, exists := l.channels[channel] if exists { return ErrChannelAlreadyOpen } if l.cn != nil { // If gotResponse is true but error is set, the query was executed on // the remote server, but resulted in an error. This should be // relatively rare, so it's fine if we just pass the error to our // caller. However, if gotResponse is false, we could not complete the // query on the remote server and our underlying connection is about // to go away, so we only add relname to l.channels, and wait for // resync() to take care of the rest. gotResponse, err := l.cn.Listen(channel) if gotResponse && err != nil { return err } } l.channels[channel] = struct{}{} for l.cn == nil { l.reconnectCond.Wait() // we let go of the mutex for a while if l.isClosed { return errListenerClosed } } return nil } // Unlisten removes a channel from the Listener's channel list. Returns // ErrChannelNotOpen if the Listener is not listening on the specified channel. // Returns immediately with no error if there is no connection. Note that you // might still get notifications for this channel even after Unlisten has // returned. // // The channel name is case-sensitive. func (l *Listener) Unlisten(channel string) error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } // Similarly to LISTEN, this is not an error in Postgres, but it seems // useful to distinguish from the normal conditions. _, exists := l.channels[channel] if !exists { return ErrChannelNotOpen } if l.cn != nil { // Similarly to Listen (see comment in that function), the caller // should only be bothered with an error if it came from the backend as // a response to our query. gotResponse, err := l.cn.Unlisten(channel) if gotResponse && err != nil { return err } } // Don't bother waiting for resync if there's no connection. delete(l.channels, channel) return nil } // UnlistenAll removes all channels from the Listener's channel list. Returns // immediately with no error if there is no connection. Note that you might // still get notifications for any of the deleted channels even after // UnlistenAll has returned. func (l *Listener) UnlistenAll() error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } if l.cn != nil { // Similarly to Listen (see comment in that function), the caller // should only be bothered with an error if it came from the backend as // a response to our query. gotResponse, err := l.cn.UnlistenAll() if gotResponse && err != nil { return err } } // Don't bother waiting for resync if there's no connection. l.channels = make(map[string]struct{}) return nil } // Ping the remote server to make sure it's alive. Non-nil return value means // that there is no active connection. func (l *Listener) Ping() error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } if l.cn == nil { return errors.New("no connection") } return l.cn.Ping() } // Clean up after losing the server connection. Returns l.cn.Err(), which // should have the reason the connection was lost. func (l *Listener) disconnectCleanup() error { l.lock.Lock() defer l.lock.Unlock() // sanity check; can't look at Err() until the channel has been closed select { case _, ok := <-l.connNotificationChan: if ok { panic("connNotificationChan not closed") } default: panic("connNotificationChan not closed") } err := l.cn.Err() l.cn.Close() l.cn = nil return err } // Synchronize the list of channels we want to be listening on with the server // after the connection has been established. func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notification) error { doneChan := make(chan error) go func() { for channel := range l.channels { // If we got a response, return that error to our caller as it's // going to be more descriptive than cn.Err(). gotResponse, err := cn.Listen(channel) if gotResponse && err != nil { doneChan <- err return } // If we couldn't reach the server, wait for notificationChan to // close and then return the error message from the connection, as // per ListenerConn's interface. if err != nil { for _ = range notificationChan { } doneChan <- cn.Err() return } } doneChan <- nil }() // Ignore notifications while synchronization is going on to avoid // deadlocks. We have to send a nil notification over Notify anyway as // we can't possibly know which notifications (if any) were lost while // the connection was down, so there's no reason to try and process // these messages at all. for { select { case _, ok := <-notificationChan: if !ok { notificationChan = nil } case err := <-doneChan: return err } } } // caller should NOT be holding l.lock func (l *Listener) closed() bool { l.lock.Lock() defer l.lock.Unlock() return l.isClosed } func (l *Listener) connect() error { notificationChan := make(chan *Notification, 32) cn, err := NewListenerConn(l.name, notificationChan) if err != nil { return err } l.lock.Lock() defer l.lock.Unlock() err = l.resync(cn, notificationChan) if err != nil { cn.Close() return err } l.cn = cn l.connNotificationChan = notificationChan l.reconnectCond.Broadcast() return nil } // Close disconnects the Listener from the database and shuts it down. // Subsequent calls to its methods will return an error. Close returns an // error if the connection has already been closed. func (l *Listener) Close() error { l.lock.Lock() defer l.lock.Unlock() if l.isClosed { return errListenerClosed } if l.cn != nil { l.cn.Close() } l.isClosed = true return nil } func (l *Listener) emitEvent(event ListenerEventType, err error) { if l.eventCallback != nil { l.eventCallback(event, err) } } // Main logic here: maintain a connection to the server when possible, wait // for notifications and emit events. func (l *Listener) listenerConnLoop() { var nextReconnect time.Time reconnectInterval := l.minReconnectInterval for { for { err := l.connect() if err == nil { break } if l.closed() { return } l.emitEvent(ListenerEventConnectionAttemptFailed, err) time.Sleep(reconnectInterval) reconnectInterval *= 2 if reconnectInterval > l.maxReconnectInterval { reconnectInterval = l.maxReconnectInterval } } if nextReconnect.IsZero() { l.emitEvent(ListenerEventConnected, nil) } else { l.emitEvent(ListenerEventReconnected, nil) l.Notify <- nil } reconnectInterval = l.minReconnectInterval nextReconnect = time.Now().Add(reconnectInterval) for { notification, ok := <-l.connNotificationChan if !ok { // lost connection, loop again break } l.Notify <- notification } err := l.disconnectCleanup() if l.closed() { return } l.emitEvent(ListenerEventDisconnected, err) time.Sleep(nextReconnect.Sub(time.Now())) } } func (l *Listener) listenerMain() { l.listenerConnLoop() close(l.Notify) } ================================================ FILE: src/github.com/lib/pq/oid/doc.go ================================================ // Package oid contains OID constants // as defined by the Postgres server. package oid // Oid is a Postgres Object ID. type Oid uint32 ================================================ FILE: src/github.com/lib/pq/oid/gen.go ================================================ // +build ignore // Generate the table of OID values // Run with 'go run gen.go'. package main import ( "database/sql" "fmt" "log" "os" "os/exec" _ "github.com/lib/pq" ) func main() { datname := os.Getenv("PGDATABASE") sslmode := os.Getenv("PGSSLMODE") if datname == "" { os.Setenv("PGDATABASE", "pqgotest") } if sslmode == "" { os.Setenv("PGSSLMODE", "disable") } db, err := sql.Open("postgres", "") if err != nil { log.Fatal(err) } cmd := exec.Command("gofmt") cmd.Stderr = os.Stderr w, err := cmd.StdinPipe() if err != nil { log.Fatal(err) } f, err := os.Create("types.go") if err != nil { log.Fatal(err) } cmd.Stdout = f err = cmd.Start() if err != nil { log.Fatal(err) } fmt.Fprintln(w, "// generated by 'go run gen.go'; do not edit") fmt.Fprintln(w, "\npackage oid") fmt.Fprintln(w, "const (") rows, err := db.Query(` SELECT typname, oid FROM pg_type WHERE oid < 10000 ORDER BY oid; `) if err != nil { log.Fatal(err) } var name string var oid int for rows.Next() { err = rows.Scan(&name, &oid) if err != nil { log.Fatal(err) } fmt.Fprintf(w, "T_%s Oid = %d\n", name, oid) } if err = rows.Err(); err != nil { log.Fatal(err) } fmt.Fprintln(w, ")") w.Close() cmd.Wait() } ================================================ FILE: src/github.com/lib/pq/oid/types.go ================================================ // generated by 'go run gen.go'; do not edit package oid const ( T_bool Oid = 16 T_bytea Oid = 17 T_char Oid = 18 T_name Oid = 19 T_int8 Oid = 20 T_int2 Oid = 21 T_int2vector Oid = 22 T_int4 Oid = 23 T_regproc Oid = 24 T_text Oid = 25 T_oid Oid = 26 T_tid Oid = 27 T_xid Oid = 28 T_cid Oid = 29 T_oidvector Oid = 30 T_pg_type Oid = 71 T_pg_attribute Oid = 75 T_pg_proc Oid = 81 T_pg_class Oid = 83 T_json Oid = 114 T_xml Oid = 142 T__xml Oid = 143 T_pg_node_tree Oid = 194 T__json Oid = 199 T_smgr Oid = 210 T_point Oid = 600 T_lseg Oid = 601 T_path Oid = 602 T_box Oid = 603 T_polygon Oid = 604 T_line Oid = 628 T__line Oid = 629 T_cidr Oid = 650 T__cidr Oid = 651 T_float4 Oid = 700 T_float8 Oid = 701 T_abstime Oid = 702 T_reltime Oid = 703 T_tinterval Oid = 704 T_unknown Oid = 705 T_circle Oid = 718 T__circle Oid = 719 T_money Oid = 790 T__money Oid = 791 T_macaddr Oid = 829 T_inet Oid = 869 T__bool Oid = 1000 T__bytea Oid = 1001 T__char Oid = 1002 T__name Oid = 1003 T__int2 Oid = 1005 T__int2vector Oid = 1006 T__int4 Oid = 1007 T__regproc Oid = 1008 T__text Oid = 1009 T__tid Oid = 1010 T__xid Oid = 1011 T__cid Oid = 1012 T__oidvector Oid = 1013 T__bpchar Oid = 1014 T__varchar Oid = 1015 T__int8 Oid = 1016 T__point Oid = 1017 T__lseg Oid = 1018 T__path Oid = 1019 T__box Oid = 1020 T__float4 Oid = 1021 T__float8 Oid = 1022 T__abstime Oid = 1023 T__reltime Oid = 1024 T__tinterval Oid = 1025 T__polygon Oid = 1027 T__oid Oid = 1028 T_aclitem Oid = 1033 T__aclitem Oid = 1034 T__macaddr Oid = 1040 T__inet Oid = 1041 T_bpchar Oid = 1042 T_varchar Oid = 1043 T_date Oid = 1082 T_time Oid = 1083 T_timestamp Oid = 1114 T__timestamp Oid = 1115 T__date Oid = 1182 T__time Oid = 1183 T_timestamptz Oid = 1184 T__timestamptz Oid = 1185 T_interval Oid = 1186 T__interval Oid = 1187 T__numeric Oid = 1231 T_pg_database Oid = 1248 T__cstring Oid = 1263 T_timetz Oid = 1266 T__timetz Oid = 1270 T_bit Oid = 1560 T__bit Oid = 1561 T_varbit Oid = 1562 T__varbit Oid = 1563 T_numeric Oid = 1700 T_refcursor Oid = 1790 T__refcursor Oid = 2201 T_regprocedure Oid = 2202 T_regoper Oid = 2203 T_regoperator Oid = 2204 T_regclass Oid = 2205 T_regtype Oid = 2206 T__regprocedure Oid = 2207 T__regoper Oid = 2208 T__regoperator Oid = 2209 T__regclass Oid = 2210 T__regtype Oid = 2211 T_record Oid = 2249 T_cstring Oid = 2275 T_any Oid = 2276 T_anyarray Oid = 2277 T_void Oid = 2278 T_trigger Oid = 2279 T_language_handler Oid = 2280 T_internal Oid = 2281 T_opaque Oid = 2282 T_anyelement Oid = 2283 T__record Oid = 2287 T_anynonarray Oid = 2776 T_pg_authid Oid = 2842 T_pg_auth_members Oid = 2843 T__txid_snapshot Oid = 2949 T_uuid Oid = 2950 T__uuid Oid = 2951 T_txid_snapshot Oid = 2970 T_fdw_handler Oid = 3115 T_anyenum Oid = 3500 T_tsvector Oid = 3614 T_tsquery Oid = 3615 T_gtsvector Oid = 3642 T__tsvector Oid = 3643 T__gtsvector Oid = 3644 T__tsquery Oid = 3645 T_regconfig Oid = 3734 T__regconfig Oid = 3735 T_regdictionary Oid = 3769 T__regdictionary Oid = 3770 T_anyrange Oid = 3831 T_event_trigger Oid = 3838 T_int4range Oid = 3904 T__int4range Oid = 3905 T_numrange Oid = 3906 T__numrange Oid = 3907 T_tsrange Oid = 3908 T__tsrange Oid = 3909 T_tstzrange Oid = 3910 T__tstzrange Oid = 3911 T_daterange Oid = 3912 T__daterange Oid = 3913 T_int8range Oid = 3926 T__int8range Oid = 3927 ) ================================================ FILE: src/github.com/lib/pq/url.go ================================================ package pq import ( "fmt" nurl "net/url" "sort" "strings" ) // ParseURL no longer needs to be used by clients of this library since supplying a URL as a // connection string to sql.Open() is now supported: // // sql.Open("postgres", "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full") // // It remains exported here for backwards-compatibility. // // ParseURL converts a url to a connection string for driver.Open. // Example: // // "postgres://bob:secret@1.2.3.4:5432/mydb?sslmode=verify-full" // // converts to: // // "user=bob password=secret host=1.2.3.4 port=5432 dbname=mydb sslmode=verify-full" // // A minimal example: // // "postgres://" // // This will be blank, causing driver.Open to use all of the defaults func ParseURL(url string) (string, error) { u, err := nurl.Parse(url) if err != nil { return "", err } if u.Scheme != "postgres" && u.Scheme != "postgresql" { return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme) } var kvs []string escaper := strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`) accrue := func(k, v string) { if v != "" { kvs = append(kvs, k+"="+escaper.Replace(v)) } } if u.User != nil { v := u.User.Username() accrue("user", v) v, _ = u.User.Password() accrue("password", v) } i := strings.Index(u.Host, ":") if i < 0 { accrue("host", u.Host) } else { accrue("host", u.Host[:i]) accrue("port", u.Host[i+1:]) } if u.Path != "" { accrue("dbname", u.Path[1:]) } q := u.Query() for k := range q { accrue(k, q.Get(k)) } sort.Strings(kvs) // Makes testing easier (not a performance concern) return strings.Join(kvs, " "), nil } ================================================ FILE: src/github.com/lib/pq/user_posix.go ================================================ // Package pq is a pure Go Postgres driver for the database/sql package. // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris package pq import ( "os" "os/user" ) func userCurrent() (string, error) { u, err := user.Current() if err == nil { return u.Username, nil } name := os.Getenv("USER") if name != "" { return name, nil } return "", ErrCouldNotDetectUsername } ================================================ FILE: src/github.com/lib/pq/user_windows.go ================================================ // Package pq is a pure Go Postgres driver for the database/sql package. package pq import ( "path/filepath" "syscall" ) // Perform Windows user name lookup identically to libpq. // // The PostgreSQL code makes use of the legacy Win32 function // GetUserName, and that function has not been imported into stock Go. // GetUserNameEx is available though, the difference being that a // wider range of names are available. To get the output to be the // same as GetUserName, only the base (or last) component of the // result is returned. func userCurrent() (string, error) { pw_name := make([]uint16, 128) pwname_size := uint32(len(pw_name)) - 1 err := syscall.GetUserNameEx(syscall.NameSamCompatible, &pw_name[0], &pwname_size) if err != nil { return "", ErrCouldNotDetectUsername } s := syscall.UTF16ToString(pw_name) u := filepath.Base(s) return u, nil } ================================================ FILE: src/github.com/stretchr/testify/Gopkg.toml ================================================ [prune] unused-packages = true non-go = true go-tests = true [[constraint]] name = "github.com/davecgh/go-spew" version = "~1.1.0" [[constraint]] name = "github.com/pmezard/go-difflib" version = "~1.0.0" [[constraint]] name = "github.com/stretchr/objx" version = "~0.1.0" ================================================ FILE: src/github.com/stretchr/testify/LICENSE ================================================ Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell Please consider promoting this project if you find it useful. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: src/github.com/stretchr/testify/README.md ================================================ Testify - Thou Shalt Write Tests ================================ [![Build Status](https://travis-ci.org/stretchr/testify.svg)](https://travis-ci.org/stretchr/testify) [![Go Report Card](https://goreportcard.com/badge/github.com/stretchr/testify)](https://goreportcard.com/report/github.com/stretchr/testify) [![GoDoc](https://godoc.org/github.com/stretchr/testify?status.svg)](https://godoc.org/github.com/stretchr/testify) Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend. Features include: * [Easy assertions](#assert-package) * [Mocking](#mock-package) * [Testing suite interfaces and functions](#suite-package) Get started: * Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date) * For an introduction to writing test code in Go, see http://golang.org/doc/code.html#Testing * Check out the API Documentation http://godoc.org/github.com/stretchr/testify * To make your testing life easier, check out our other project, [gorc](http://github.com/stretchr/gorc) * A little about [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development) [`assert`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package ------------------------------------------------------------------------------------------- The `assert` package provides some helpful methods that allow you to write better test code in Go. * Prints friendly, easy to read failure descriptions * Allows for very readable code * Optionally annotate each assertion with a message See it in action: ```go package yours import ( "testing" "github.com/stretchr/testify/assert" ) func TestSomething(t *testing.T) { // assert equality assert.Equal(t, 123, 123, "they should be equal") // assert inequality assert.NotEqual(t, 123, 456, "they should not be equal") // assert for nil (good for errors) assert.Nil(t, object) // assert for not nil (good when you expect something) if assert.NotNil(t, object) { // now we know that object isn't nil, we are safe to make // further assertions without causing any errors assert.Equal(t, "Something", object.Value) } } ``` * Every assert func takes the `testing.T` object as the first argument. This is how it writes the errors out through the normal `go test` capabilities. * Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions. if you assert many times, use the below: ```go package yours import ( "testing" "github.com/stretchr/testify/assert" ) func TestSomething(t *testing.T) { assert := assert.New(t) // assert equality assert.Equal(123, 123, "they should be equal") // assert inequality assert.NotEqual(123, 456, "they should not be equal") // assert for nil (good for errors) assert.Nil(object) // assert for not nil (good when you expect something) if assert.NotNil(object) { // now we know that object isn't nil, we are safe to make // further assertions without causing any errors assert.Equal("Something", object.Value) } } ``` [`require`](http://godoc.org/github.com/stretchr/testify/require "API documentation") package --------------------------------------------------------------------------------------------- The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test. See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details. [`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") package ---------------------------------------------------------------------------------------- The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code. An example test function that tests a piece of code that relies on an external object `testObj`, can setup expectations (testify) and assert that they indeed happened: ```go package yours import ( "testing" "github.com/stretchr/testify/mock" ) /* Test objects */ // MyMockedObject is a mocked object that implements an interface // that describes an object that the code I am testing relies on. type MyMockedObject struct{ mock.Mock } // DoSomething is a method on MyMockedObject that implements some interface // and just records the activity, and returns what the Mock object tells it to. // // In the real object, this method would do something useful, but since this // is a mocked object - we're just going to stub it out. // // NOTE: This method is not being tested here, code that uses this object is. func (m *MyMockedObject) DoSomething(number int) (bool, error) { args := m.Called(number) return args.Bool(0), args.Error(1) } /* Actual test functions */ // TestSomething is an example of how to use our test object to // make assertions about some target code we are testing. func TestSomething(t *testing.T) { // create an instance of our test object testObj := new(MyMockedObject) // setup expectations testObj.On("DoSomething", 123).Return(true, nil) // call the code we are testing targetFuncThatDoesSomethingWithObj(testObj) // assert that the expectations were met testObj.AssertExpectations(t) } // TestSomethingElse is a second example of how to use our test object to // make assertions about some target code we are testing. // This time using a placeholder. Placeholders might be used when the // data being passed in is normally dynamically generated and cannot be // predicted beforehand (eg. containing hashes that are time sensitive) func TestSomethingElse(t *testing.T) { // create an instance of our test object testObj := new(MyMockedObject) // setup expectations with a placeholder in the argument list testObj.On("DoSomething", mock.Anything).Return(true, nil) // call the code we are testing targetFuncThatDoesSomethingWithObj(testObj) // assert that the expectations were met testObj.AssertExpectations(t) } ``` For more information on how to write mock code, check out the [API documentation for the `mock` package](http://godoc.org/github.com/stretchr/testify/mock). You can use the [mockery tool](http://github.com/vektra/mockery) to autogenerate the mock code against an interface as well, making using mocks much quicker. [`suite`](http://godoc.org/github.com/stretchr/testify/suite "API documentation") package ----------------------------------------------------------------------------------------- The `suite` package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal. An example suite is shown below: ```go // Basic imports import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) // Define the suite, and absorb the built-in basic suite // functionality from testify - including a T() method which // returns the current testing context type ExampleTestSuite struct { suite.Suite VariableThatShouldStartAtFive int } // Make sure that VariableThatShouldStartAtFive is set to five // before each test func (suite *ExampleTestSuite) SetupTest() { suite.VariableThatShouldStartAtFive = 5 } // All methods that begin with "Test" are run as tests within a // suite. func (suite *ExampleTestSuite) TestExample() { assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) } // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run func TestExampleTestSuite(t *testing.T) { suite.Run(t, new(ExampleTestSuite)) } ``` For a more complete example, using all of the functionality provided by the suite package, look at our [example testing suite](https://github.com/stretchr/testify/blob/master/suite/suite_test.go) For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite). `Suite` object has assertion methods: ```go // Basic imports import ( "testing" "github.com/stretchr/testify/suite" ) // Define the suite, and absorb the built-in basic suite // functionality from testify - including assertion methods. type ExampleTestSuite struct { suite.Suite VariableThatShouldStartAtFive int } // Make sure that VariableThatShouldStartAtFive is set to five // before each test func (suite *ExampleTestSuite) SetupTest() { suite.VariableThatShouldStartAtFive = 5 } // All methods that begin with "Test" are run as tests within a // suite. func (suite *ExampleTestSuite) TestExample() { suite.Equal(suite.VariableThatShouldStartAtFive, 5) } // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run func TestExampleTestSuite(t *testing.T) { suite.Run(t, new(ExampleTestSuite)) } ``` ------ Installation ============ To install Testify, use `go get`: go get github.com/stretchr/testify This will then make the following packages available to you: github.com/stretchr/testify/assert github.com/stretchr/testify/mock github.com/stretchr/testify/http Import the `testify/assert` package into your code using this template: ```go package yours import ( "testing" "github.com/stretchr/testify/assert" ) func TestSomething(t *testing.T) { assert.True(t, true, "True is true!") } ``` ------ Staying up to date ================== To update Testify to the latest version, use `go get -u github.com/stretchr/testify`. ------ Supported go versions ================== We support the three major Go versions, which are 1.8, 1.9 and 1.10 at the moment. ------ Contributing ============ Please feel free to submit issues, fork the repository and send pull requests! When submitting an issue, we ask that you please include a complete test function that demonstrates the issue. Extra credit for those using Testify to write the test code that demonstrates it. ================================================ FILE: src/github.com/stretchr/testify/_codegen/main.go ================================================ // This program reads all assertion functions from the assert package and // automatically generates the corresponding requires and forwarded assertions package main import ( "bytes" "flag" "fmt" "go/ast" "go/build" "go/doc" "go/format" "go/importer" "go/parser" "go/token" "go/types" "io" "io/ioutil" "log" "os" "path" "regexp" "strings" "text/template" "github.com/ernesto-jimenez/gogen/imports" ) var ( pkg = flag.String("assert-path", "github.com/stretchr/testify/assert", "Path to the assert package") includeF = flag.Bool("include-format-funcs", false, "include format functions such as Errorf and Equalf") outputPkg = flag.String("output-package", "", "package for the resulting code") tmplFile = flag.String("template", "", "What file to load the function template from") out = flag.String("out", "", "What file to write the source code to") ) func main() { flag.Parse() scope, docs, err := parsePackageSource(*pkg) if err != nil { log.Fatal(err) } importer, funcs, err := analyzeCode(scope, docs) if err != nil { log.Fatal(err) } if err := generateCode(importer, funcs); err != nil { log.Fatal(err) } } func generateCode(importer imports.Importer, funcs []testFunc) error { buff := bytes.NewBuffer(nil) tmplHead, tmplFunc, err := parseTemplates() if err != nil { return err } // Generate header if err := tmplHead.Execute(buff, struct { Name string Imports map[string]string }{ *outputPkg, importer.Imports(), }); err != nil { return err } // Generate funcs for _, fn := range funcs { buff.Write([]byte("\n\n")) if err := tmplFunc.Execute(buff, &fn); err != nil { return err } } code, err := format.Source(buff.Bytes()) if err != nil { return err } // Write file output, err := outputFile() if err != nil { return err } defer output.Close() _, err = io.Copy(output, bytes.NewReader(code)) return err } func parseTemplates() (*template.Template, *template.Template, error) { tmplHead, err := template.New("header").Parse(headerTemplate) if err != nil { return nil, nil, err } if *tmplFile != "" { f, err := ioutil.ReadFile(*tmplFile) if err != nil { return nil, nil, err } funcTemplate = string(f) } tmpl, err := template.New("function").Parse(funcTemplate) if err != nil { return nil, nil, err } return tmplHead, tmpl, nil } func outputFile() (*os.File, error) { filename := *out if filename == "-" || (filename == "" && *tmplFile == "") { return os.Stdout, nil } if filename == "" { filename = strings.TrimSuffix(strings.TrimSuffix(*tmplFile, ".tmpl"), ".go") + ".go" } return os.Create(filename) } // analyzeCode takes the types scope and the docs and returns the import // information and information about all the assertion functions. func analyzeCode(scope *types.Scope, docs *doc.Package) (imports.Importer, []testFunc, error) { testingT := scope.Lookup("TestingT").Type().Underlying().(*types.Interface) importer := imports.New(*outputPkg) var funcs []testFunc // Go through all the top level functions for _, fdocs := range docs.Funcs { // Find the function obj := scope.Lookup(fdocs.Name) fn, ok := obj.(*types.Func) if !ok { continue } // Check function signature has at least two arguments sig := fn.Type().(*types.Signature) if sig.Params().Len() < 2 { continue } // Check first argument is of type testingT first, ok := sig.Params().At(0).Type().(*types.Named) if !ok { continue } firstType, ok := first.Underlying().(*types.Interface) if !ok { continue } if !types.Implements(firstType, testingT) { continue } // Skip functions ending with f if strings.HasSuffix(fdocs.Name, "f") && !*includeF { continue } funcs = append(funcs, testFunc{*outputPkg, fdocs, fn}) importer.AddImportsFrom(sig.Params()) } return importer, funcs, nil } // parsePackageSource returns the types scope and the package documentation from the package func parsePackageSource(pkg string) (*types.Scope, *doc.Package, error) { pd, err := build.Import(pkg, ".", 0) if err != nil { return nil, nil, err } fset := token.NewFileSet() files := make(map[string]*ast.File) fileList := make([]*ast.File, len(pd.GoFiles)) for i, fname := range pd.GoFiles { src, err := ioutil.ReadFile(path.Join(pd.SrcRoot, pd.ImportPath, fname)) if err != nil { return nil, nil, err } f, err := parser.ParseFile(fset, fname, src, parser.ParseComments|parser.AllErrors) if err != nil { return nil, nil, err } files[fname] = f fileList[i] = f } cfg := types.Config{ Importer: importer.Default(), } info := types.Info{ Defs: make(map[*ast.Ident]types.Object), } tp, err := cfg.Check(pkg, fset, fileList, &info) if err != nil { return nil, nil, err } scope := tp.Scope() ap, _ := ast.NewPackage(fset, files, nil, nil) docs := doc.New(ap, pkg, 0) return scope, docs, nil } type testFunc struct { CurrentPkg string DocInfo *doc.Func TypeInfo *types.Func } func (f *testFunc) Qualifier(p *types.Package) string { if p == nil || p.Name() == f.CurrentPkg { return "" } return p.Name() } func (f *testFunc) Params() string { sig := f.TypeInfo.Type().(*types.Signature) params := sig.Params() p := "" comma := "" to := params.Len() var i int if sig.Variadic() { to-- } for i = 1; i < to; i++ { param := params.At(i) p += fmt.Sprintf("%s%s %s", comma, param.Name(), types.TypeString(param.Type(), f.Qualifier)) comma = ", " } if sig.Variadic() { param := params.At(params.Len() - 1) p += fmt.Sprintf("%s%s ...%s", comma, param.Name(), types.TypeString(param.Type().(*types.Slice).Elem(), f.Qualifier)) } return p } func (f *testFunc) ForwardedParams() string { sig := f.TypeInfo.Type().(*types.Signature) params := sig.Params() p := "" comma := "" to := params.Len() var i int if sig.Variadic() { to-- } for i = 1; i < to; i++ { param := params.At(i) p += fmt.Sprintf("%s%s", comma, param.Name()) comma = ", " } if sig.Variadic() { param := params.At(params.Len() - 1) p += fmt.Sprintf("%s%s...", comma, param.Name()) } return p } func (f *testFunc) ParamsFormat() string { return strings.Replace(f.Params(), "msgAndArgs", "msg string, args", 1) } func (f *testFunc) ForwardedParamsFormat() string { return strings.Replace(f.ForwardedParams(), "msgAndArgs", "append([]interface{}{msg}, args...)", 1) } func (f *testFunc) Comment() string { return "// " + strings.Replace(strings.TrimSpace(f.DocInfo.Doc), "\n", "\n// ", -1) } func (f *testFunc) CommentFormat() string { search := fmt.Sprintf("%s", f.DocInfo.Name) replace := fmt.Sprintf("%sf", f.DocInfo.Name) comment := strings.Replace(f.Comment(), search, replace, -1) exp := regexp.MustCompile(replace + `\(((\(\)|[^)])+)\)`) return exp.ReplaceAllString(comment, replace+`($1, "error message %s", "formatted")`) } func (f *testFunc) CommentWithoutT(receiver string) string { search := fmt.Sprintf("assert.%s(t, ", f.DocInfo.Name) replace := fmt.Sprintf("%s.%s(", receiver, f.DocInfo.Name) return strings.Replace(f.Comment(), search, replace, -1) } var headerTemplate = `/* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package {{.Name}} import ( {{range $path, $name := .Imports}} {{$name}} "{{$path}}"{{end}} ) ` var funcTemplate = `{{.Comment}} func (fwd *AssertionsForwarder) {{.DocInfo.Name}}({{.Params}}) bool { return assert.{{.DocInfo.Name}}({{.ForwardedParams}}) }` ================================================ FILE: src/github.com/stretchr/testify/assert/assertion_format.go ================================================ /* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package assert import ( http "net/http" url "net/url" time "time" ) // Conditionf uses a Comparison to assert a complex condition. func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Condition(t, comp, append([]interface{}{msg}, args...)...) } // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") // assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") // assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Contains(t, s, contains, append([]interface{}{msg}, args...)...) } // DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return DirExists(t, path, append([]interface{}{msg}, args...)...) } // ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return ElementsMatch(t, listA, listB, append([]interface{}{msg}, args...)...) } // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Emptyf(t, obj, "error message %s", "formatted") func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Empty(t, object, append([]interface{}{msg}, args...)...) } // Equalf asserts that two objects are equal. // // assert.Equalf(t, 123, 123, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Equal(t, expected, actual, append([]interface{}{msg}, args...)...) } // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return EqualError(t, theError, errString, append([]interface{}{msg}, args...)...) } // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValuesf(t, uint32(123, "error message %s", "formatted"), int32(123)) func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) } // Errorf asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Errorf(t, err, "error message %s", "formatted") { // assert.Equal(t, expectedErrorf, err) // } func Errorf(t TestingT, err error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Error(t, err, append([]interface{}{msg}, args...)...) } // Exactlyf asserts that two objects are equal in value and type. // // assert.Exactlyf(t, int32(123, "error message %s", "formatted"), int64(123)) func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Exactly(t, expected, actual, append([]interface{}{msg}, args...)...) } // Failf reports a failure through func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Fail(t, failureMessage, append([]interface{}{msg}, args...)...) } // FailNowf fails test func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return FailNow(t, failureMessage, append([]interface{}{msg}, args...)...) } // Falsef asserts that the specified value is false. // // assert.Falsef(t, myBool, "error message %s", "formatted") func Falsef(t TestingT, value bool, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return False(t, value, append([]interface{}{msg}, args...)...) } // FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return FileExists(t, path, append([]interface{}{msg}, args...)...) } // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPBodyContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...) } // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPBodyNotContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...) } // HTTPErrorf asserts that a specified handler returns an error status code. // // assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPError(t, handler, method, url, values, append([]interface{}{msg}, args...)...) } // HTTPRedirectf asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPRedirect(t, handler, method, url, values, append([]interface{}{msg}, args...)...) } // HTTPSuccessf asserts that a specified handler returns a success status code. // // assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return HTTPSuccess(t, handler, method, url, values, append([]interface{}{msg}, args...)...) } // Implementsf asserts that an object is implemented by the specified interface. // // assert.Implementsf(t, (*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Implements(t, interfaceObject, object, append([]interface{}{msg}, args...)...) } // InDeltaf asserts that the two numerals are within delta of each other. // // assert.InDeltaf(t, math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InDelta(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InDeltaMapValues(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // InDeltaSlicef is the same as InDelta, except it compares two slices. func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InDeltaSlice(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // InEpsilonf asserts that expected and actual have a relative error less than epsilon func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InEpsilon(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) } // InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return InEpsilonSlice(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) } // IsTypef asserts that the specified objects are of the same type. func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return IsType(t, expectedType, object, append([]interface{}{msg}, args...)...) } // JSONEqf asserts that two JSON strings are equivalent. // // assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return JSONEq(t, expected, actual, append([]interface{}{msg}, args...)...) } // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // // assert.Lenf(t, mySlice, 3, "error message %s", "formatted") func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Len(t, object, length, append([]interface{}{msg}, args...)...) } // Nilf asserts that the specified object is nil. // // assert.Nilf(t, err, "error message %s", "formatted") func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Nil(t, object, append([]interface{}{msg}, args...)...) } // NoErrorf asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoErrorf(t, err, "error message %s", "formatted") { // assert.Equal(t, expectedObj, actualObj) // } func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NoError(t, err, append([]interface{}{msg}, args...)...) } // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") // assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") // assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotContains(t, s, contains, append([]interface{}{msg}, args...)...) } // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if assert.NotEmptyf(t, obj, "error message %s", "formatted") { // assert.Equal(t, "two", obj[1]) // } func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotEmpty(t, object, append([]interface{}{msg}, args...)...) } // NotEqualf asserts that the specified values are NOT equal. // // assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotEqual(t, expected, actual, append([]interface{}{msg}, args...)...) } // NotNilf asserts that the specified object is not nil. // // assert.NotNilf(t, err, "error message %s", "formatted") func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotNil(t, object, append([]interface{}{msg}, args...)...) } // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // // assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotPanics(t, f, append([]interface{}{msg}, args...)...) } // NotRegexpf asserts that a specified regexp does not match a string. // // assert.NotRegexpf(t, regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") // assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotRegexp(t, rx, str, append([]interface{}{msg}, args...)...) } // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotSubset(t, list, subset, append([]interface{}{msg}, args...)...) } // NotZerof asserts that i is not the zero value for its type. func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return NotZero(t, i, append([]interface{}{msg}, args...)...) } // Panicsf asserts that the code inside the specified PanicTestFunc panics. // // assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Panics(t, f, append([]interface{}{msg}, args...)...) } // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return PanicsWithValue(t, expected, f, append([]interface{}{msg}, args...)...) } // Regexpf asserts that a specified regexp matches a string. // // assert.Regexpf(t, regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") // assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Regexp(t, rx, str, append([]interface{}{msg}, args...)...) } // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Subset(t, list, subset, append([]interface{}{msg}, args...)...) } // Truef asserts that the specified value is true. // // assert.Truef(t, myBool, "error message %s", "formatted") func Truef(t TestingT, value bool, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return True(t, value, append([]interface{}{msg}, args...)...) } // WithinDurationf asserts that the two times are within duration delta of each other. // // assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return WithinDuration(t, expected, actual, delta, append([]interface{}{msg}, args...)...) } // Zerof asserts that i is the zero value for its type. func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return Zero(t, i, append([]interface{}{msg}, args...)...) } ================================================ FILE: src/github.com/stretchr/testify/assert/assertion_format.go.tmpl ================================================ {{.CommentFormat}} func {{.DocInfo.Name}}f(t TestingT, {{.ParamsFormat}}) bool { if h, ok := t.(tHelper); ok { h.Helper() } return {{.DocInfo.Name}}(t, {{.ForwardedParamsFormat}}) } ================================================ FILE: src/github.com/stretchr/testify/assert/assertion_forward.go ================================================ /* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package assert import ( http "net/http" url "net/url" time "time" ) // Condition uses a Comparison to assert a complex condition. func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Condition(a.t, comp, msgAndArgs...) } // Conditionf uses a Comparison to assert a complex condition. func (a *Assertions) Conditionf(comp Comparison, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Conditionf(a.t, comp, msg, args...) } // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // a.Contains("Hello World", "World") // a.Contains(["Hello", "World"], "World") // a.Contains({"Hello": "World"}, "Hello") func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Contains(a.t, s, contains, msgAndArgs...) } // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // a.Containsf("Hello World", "World", "error message %s", "formatted") // a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") // a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Containsf(a.t, s, contains, msg, args...) } // DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return DirExists(a.t, path, msgAndArgs...) } // DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return DirExistsf(a.t, path, msg, args...) } // ElementsMatch asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2]) func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return ElementsMatch(a.t, listA, listB, msgAndArgs...) } // ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return ElementsMatchf(a.t, listA, listB, msg, args...) } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // a.Empty(obj) func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Empty(a.t, object, msgAndArgs...) } // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // a.Emptyf(obj, "error message %s", "formatted") func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Emptyf(a.t, object, msg, args...) } // Equal asserts that two objects are equal. // // a.Equal(123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Equal(a.t, expected, actual, msgAndArgs...) } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // a.EqualError(err, expectedErrorString) func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return EqualError(a.t, theError, errString, msgAndArgs...) } // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return EqualErrorf(a.t, theError, errString, msg, args...) } // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // a.EqualValues(uint32(123), int32(123)) func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return EqualValues(a.t, expected, actual, msgAndArgs...) } // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // // a.EqualValuesf(uint32(123, "error message %s", "formatted"), int32(123)) func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return EqualValuesf(a.t, expected, actual, msg, args...) } // Equalf asserts that two objects are equal. // // a.Equalf(123, 123, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Equalf(a.t, expected, actual, msg, args...) } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if a.Error(err) { // assert.Equal(t, expectedError, err) // } func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Error(a.t, err, msgAndArgs...) } // Errorf asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if a.Errorf(err, "error message %s", "formatted") { // assert.Equal(t, expectedErrorf, err) // } func (a *Assertions) Errorf(err error, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Errorf(a.t, err, msg, args...) } // Exactly asserts that two objects are equal in value and type. // // a.Exactly(int32(123), int64(123)) func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Exactly(a.t, expected, actual, msgAndArgs...) } // Exactlyf asserts that two objects are equal in value and type. // // a.Exactlyf(int32(123, "error message %s", "formatted"), int64(123)) func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Exactlyf(a.t, expected, actual, msg, args...) } // Fail reports a failure through func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Fail(a.t, failureMessage, msgAndArgs...) } // FailNow fails test func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return FailNow(a.t, failureMessage, msgAndArgs...) } // FailNowf fails test func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return FailNowf(a.t, failureMessage, msg, args...) } // Failf reports a failure through func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Failf(a.t, failureMessage, msg, args...) } // False asserts that the specified value is false. // // a.False(myBool) func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return False(a.t, value, msgAndArgs...) } // Falsef asserts that the specified value is false. // // a.Falsef(myBool, "error message %s", "formatted") func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Falsef(a.t, value, msg, args...) } // FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return FileExists(a.t, path, msgAndArgs...) } // FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return FileExistsf(a.t, path, msg, args...) } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...) } // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // // a.HTTPBodyContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...) } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...) } // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // // a.HTTPBodyNotContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...) } // HTTPError asserts that a specified handler returns an error status code. // // a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPError(a.t, handler, method, url, values, msgAndArgs...) } // HTTPErrorf asserts that a specified handler returns an error status code. // // a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPErrorf(a.t, handler, method, url, values, msg, args...) } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...) } // HTTPRedirectf asserts that a specified handler returns a redirect status code. // // a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPRedirectf(a.t, handler, method, url, values, msg, args...) } // HTTPSuccess asserts that a specified handler returns a success status code. // // a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...) } // HTTPSuccessf asserts that a specified handler returns a success status code. // // a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return HTTPSuccessf(a.t, handler, method, url, values, msg, args...) } // Implements asserts that an object is implemented by the specified interface. // // a.Implements((*MyInterface)(nil), new(MyObject)) func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Implements(a.t, interfaceObject, object, msgAndArgs...) } // Implementsf asserts that an object is implemented by the specified interface. // // a.Implementsf((*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Implementsf(a.t, interfaceObject, object, msg, args...) } // InDelta asserts that the two numerals are within delta of each other. // // a.InDelta(math.Pi, (22 / 7.0), 0.01) func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InDelta(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...) } // InDeltaSlice is the same as InDelta, except it compares two slices. func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaSlicef is the same as InDelta, except it compares two slices. func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InDeltaSlicef(a.t, expected, actual, delta, msg, args...) } // InDeltaf asserts that the two numerals are within delta of each other. // // a.InDeltaf(math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InDeltaf(a.t, expected, actual, delta, msg, args...) } // InEpsilon asserts that expected and actual have a relative error less than epsilon func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) } // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) } // InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) } // InEpsilonf asserts that expected and actual have a relative error less than epsilon func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return InEpsilonf(a.t, expected, actual, epsilon, msg, args...) } // IsType asserts that the specified objects are of the same type. func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return IsType(a.t, expectedType, object, msgAndArgs...) } // IsTypef asserts that the specified objects are of the same type. func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return IsTypef(a.t, expectedType, object, msg, args...) } // JSONEq asserts that two JSON strings are equivalent. // // a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return JSONEq(a.t, expected, actual, msgAndArgs...) } // JSONEqf asserts that two JSON strings are equivalent. // // a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return JSONEqf(a.t, expected, actual, msg, args...) } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // a.Len(mySlice, 3) func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Len(a.t, object, length, msgAndArgs...) } // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // // a.Lenf(mySlice, 3, "error message %s", "formatted") func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Lenf(a.t, object, length, msg, args...) } // Nil asserts that the specified object is nil. // // a.Nil(err) func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Nil(a.t, object, msgAndArgs...) } // Nilf asserts that the specified object is nil. // // a.Nilf(err, "error message %s", "formatted") func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Nilf(a.t, object, msg, args...) } // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if a.NoError(err) { // assert.Equal(t, expectedObj, actualObj) // } func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NoError(a.t, err, msgAndArgs...) } // NoErrorf asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if a.NoErrorf(err, "error message %s", "formatted") { // assert.Equal(t, expectedObj, actualObj) // } func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NoErrorf(a.t, err, msg, args...) } // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // a.NotContains("Hello World", "Earth") // a.NotContains(["Hello", "World"], "Earth") // a.NotContains({"Hello": "World"}, "Earth") func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotContains(a.t, s, contains, msgAndArgs...) } // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") // a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") // a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotContainsf(a.t, s, contains, msg, args...) } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if a.NotEmpty(obj) { // assert.Equal(t, "two", obj[1]) // } func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotEmpty(a.t, object, msgAndArgs...) } // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if a.NotEmptyf(obj, "error message %s", "formatted") { // assert.Equal(t, "two", obj[1]) // } func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotEmptyf(a.t, object, msg, args...) } // NotEqual asserts that the specified values are NOT equal. // // a.NotEqual(obj1, obj2) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotEqual(a.t, expected, actual, msgAndArgs...) } // NotEqualf asserts that the specified values are NOT equal. // // a.NotEqualf(obj1, obj2, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotEqualf(a.t, expected, actual, msg, args...) } // NotNil asserts that the specified object is not nil. // // a.NotNil(err) func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotNil(a.t, object, msgAndArgs...) } // NotNilf asserts that the specified object is not nil. // // a.NotNilf(err, "error message %s", "formatted") func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotNilf(a.t, object, msg, args...) } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // a.NotPanics(func(){ RemainCalm() }) func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotPanics(a.t, f, msgAndArgs...) } // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // // a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") func (a *Assertions) NotPanicsf(f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotPanicsf(a.t, f, msg, args...) } // NotRegexp asserts that a specified regexp does not match a string. // // a.NotRegexp(regexp.MustCompile("starts"), "it's starting") // a.NotRegexp("^start", "it's not starting") func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotRegexp(a.t, rx, str, msgAndArgs...) } // NotRegexpf asserts that a specified regexp does not match a string. // // a.NotRegexpf(regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") // a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotRegexpf(a.t, rx, str, msg, args...) } // NotSubset asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotSubset(a.t, list, subset, msgAndArgs...) } // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotSubsetf(a.t, list, subset, msg, args...) } // NotZero asserts that i is not the zero value for its type. func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotZero(a.t, i, msgAndArgs...) } // NotZerof asserts that i is not the zero value for its type. func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return NotZerof(a.t, i, msg, args...) } // Panics asserts that the code inside the specified PanicTestFunc panics. // // a.Panics(func(){ GoCrazy() }) func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Panics(a.t, f, msgAndArgs...) } // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // a.PanicsWithValue("crazy error", func(){ GoCrazy() }) func (a *Assertions) PanicsWithValue(expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return PanicsWithValue(a.t, expected, f, msgAndArgs...) } // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func (a *Assertions) PanicsWithValuef(expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return PanicsWithValuef(a.t, expected, f, msg, args...) } // Panicsf asserts that the code inside the specified PanicTestFunc panics. // // a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") func (a *Assertions) Panicsf(f PanicTestFunc, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Panicsf(a.t, f, msg, args...) } // Regexp asserts that a specified regexp matches a string. // // a.Regexp(regexp.MustCompile("start"), "it's starting") // a.Regexp("start...$", "it's not starting") func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Regexp(a.t, rx, str, msgAndArgs...) } // Regexpf asserts that a specified regexp matches a string. // // a.Regexpf(regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") // a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Regexpf(a.t, rx, str, msg, args...) } // Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Subset(a.t, list, subset, msgAndArgs...) } // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Subsetf(a.t, list, subset, msg, args...) } // True asserts that the specified value is true. // // a.True(myBool) func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return True(a.t, value, msgAndArgs...) } // Truef asserts that the specified value is true. // // a.Truef(myBool, "error message %s", "formatted") func (a *Assertions) Truef(value bool, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Truef(a.t, value, msg, args...) } // WithinDuration asserts that the two times are within duration delta of each other. // // a.WithinDuration(time.Now(), time.Now(), 10*time.Second) func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) } // WithinDurationf asserts that the two times are within duration delta of each other. // // a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return WithinDurationf(a.t, expected, actual, delta, msg, args...) } // Zero asserts that i is the zero value for its type. func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Zero(a.t, i, msgAndArgs...) } // Zerof asserts that i is the zero value for its type. func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return Zerof(a.t, i, msg, args...) } ================================================ FILE: src/github.com/stretchr/testify/assert/assertion_forward.go.tmpl ================================================ {{.CommentWithoutT "a"}} func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) bool { if h, ok := a.t.(tHelper); ok { h.Helper() } return {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) } ================================================ FILE: src/github.com/stretchr/testify/assert/assertions.go ================================================ package assert import ( "bufio" "bytes" "encoding/json" "errors" "fmt" "math" "os" "reflect" "regexp" "runtime" "strings" "time" "unicode" "unicode/utf8" "github.com/davecgh/go-spew/spew" "github.com/pmezard/go-difflib/difflib" ) //go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_format.go.tmpl // TestingT is an interface wrapper around *testing.T type TestingT interface { Errorf(format string, args ...interface{}) } // ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful // for table driven tests. type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool // ValueAssertionFunc is a common function prototype when validating a single value. Can be useful // for table driven tests. type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool // BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful // for table driven tests. type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool // ValuesAssertionFunc is a common function prototype when validating an error value. Can be useful // for table driven tests. type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool // Comparison a custom function that returns true on success and false on failure type Comparison func() (success bool) /* Helper functions */ // ObjectsAreEqual determines if two objects are considered equal. // // This function does no assertion of any kind. func ObjectsAreEqual(expected, actual interface{}) bool { if expected == nil || actual == nil { return expected == actual } if exp, ok := expected.([]byte); ok { act, ok := actual.([]byte) if !ok { return false } else if exp == nil || act == nil { return exp == nil && act == nil } return bytes.Equal(exp, act) } return reflect.DeepEqual(expected, actual) } // ObjectsAreEqualValues gets whether two objects are equal, or if their // values are equal. func ObjectsAreEqualValues(expected, actual interface{}) bool { if ObjectsAreEqual(expected, actual) { return true } actualType := reflect.TypeOf(actual) if actualType == nil { return false } expectedValue := reflect.ValueOf(expected) if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { // Attempt comparison after type conversion return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) } return false } /* CallerInfo is necessary because the assert functions use the testing object internally, causing it to print the file:line of the assert method, rather than where the problem actually occurred in calling code.*/ // CallerInfo returns an array of strings containing the file and line number // of each stack frame leading from the current test to the assert call that // failed. func CallerInfo() []string { pc := uintptr(0) file := "" line := 0 ok := false name := "" callers := []string{} for i := 0; ; i++ { pc, file, line, ok = runtime.Caller(i) if !ok { // The breaks below failed to terminate the loop, and we ran off the // end of the call stack. break } // This is a huge edge case, but it will panic if this is the case, see #180 if file == "" { break } f := runtime.FuncForPC(pc) if f == nil { break } name = f.Name() // testing.tRunner is the standard library function that calls // tests. Subtests are called directly by tRunner, without going through // the Test/Benchmark/Example function that contains the t.Run calls, so // with subtests we should break when we hit tRunner, without adding it // to the list of callers. if name == "testing.tRunner" { break } parts := strings.Split(file, "/") file = parts[len(parts)-1] if len(parts) > 1 { dir := parts[len(parts)-2] if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { callers = append(callers, fmt.Sprintf("%s:%d", file, line)) } } // Drop the package segments := strings.Split(name, ".") name = segments[len(segments)-1] if isTest(name, "Test") || isTest(name, "Benchmark") || isTest(name, "Example") { break } } return callers } // Stolen from the `go test` tool. // isTest tells whether name looks like a test (or benchmark, according to prefix). // It is a Test (say) if there is a character after Test that is not a lower-case letter. // We don't want TesticularCancer. func isTest(name, prefix string) bool { if !strings.HasPrefix(name, prefix) { return false } if len(name) == len(prefix) { // "Test" is ok return true } rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) return !unicode.IsLower(rune) } func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { if len(msgAndArgs) == 0 || msgAndArgs == nil { return "" } if len(msgAndArgs) == 1 { return msgAndArgs[0].(string) } if len(msgAndArgs) > 1 { return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) } return "" } // Aligns the provided message so that all lines after the first line start at the same location as the first line. // Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab). // The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the // basis on which the alignment occurs). func indentMessageLines(message string, longestLabelLen int) string { outBuf := new(bytes.Buffer) for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { // no need to align first line because it starts at the correct location (after the label) if i != 0 { // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t") } outBuf.WriteString(scanner.Text()) } return outBuf.String() } type failNower interface { FailNow() } // FailNow fails test func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } Fail(t, failureMessage, msgAndArgs...) // We cannot extend TestingT with FailNow() and // maintain backwards compatibility, so we fallback // to panicking when FailNow is not available in // TestingT. // See issue #263 if t, ok := t.(failNower); ok { t.FailNow() } else { panic("test failed and t is missing `FailNow()`") } return false } // Fail reports a failure through func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } content := []labeledContent{ {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")}, {"Error", failureMessage}, } // Add test name if the Go version supports it if n, ok := t.(interface { Name() string }); ok { content = append(content, labeledContent{"Test", n.Name()}) } message := messageFromMsgAndArgs(msgAndArgs...) if len(message) > 0 { content = append(content, labeledContent{"Messages", message}) } t.Errorf("\n%s", ""+labeledOutput(content...)) return false } type labeledContent struct { label string content string } // labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner: // // \t{{label}}:{{align_spaces}}\t{{content}}\n // // The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label. // If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this // alignment is achieved, "\t{{content}}\n" is added for the output. // // If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line. func labeledOutput(content ...labeledContent) string { longestLabel := 0 for _, v := range content { if len(v.label) > longestLabel { longestLabel = len(v.label) } } var output string for _, v := range content { output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n" } return output } // Implements asserts that an object is implemented by the specified interface. // // assert.Implements(t, (*MyInterface)(nil), new(MyObject)) func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } interfaceType := reflect.TypeOf(interfaceObject).Elem() if object == nil { return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...) } if !reflect.TypeOf(object).Implements(interfaceType) { return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) } return true } // IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) } return true } // Equal asserts that two objects are equal. // // assert.Equal(t, 123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if err := validateEqualArgs(expected, actual); err != nil { return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)", expected, actual, err), msgAndArgs...) } if !ObjectsAreEqual(expected, actual) { diff := diff(expected, actual) expected, actual = formatUnequalValues(expected, actual) return Fail(t, fmt.Sprintf("Not equal: \n"+ "expected: %s\n"+ "actual : %s%s", expected, actual, diff), msgAndArgs...) } return true } // formatUnequalValues takes two values of arbitrary types and returns string // representations appropriate to be presented to the user. // // If the values are not of like type, the returned strings will be prefixed // with the type name, and the value will be enclosed in parenthesis similar // to a type conversion in the Go grammar. func formatUnequalValues(expected, actual interface{}) (e string, a string) { if reflect.TypeOf(expected) != reflect.TypeOf(actual) { return fmt.Sprintf("%T(%#v)", expected, expected), fmt.Sprintf("%T(%#v)", actual, actual) } return fmt.Sprintf("%#v", expected), fmt.Sprintf("%#v", actual) } // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValues(t, uint32(123), int32(123)) func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if !ObjectsAreEqualValues(expected, actual) { diff := diff(expected, actual) expected, actual = formatUnequalValues(expected, actual) return Fail(t, fmt.Sprintf("Not equal: \n"+ "expected: %s\n"+ "actual : %s%s", expected, actual, diff), msgAndArgs...) } return true } // Exactly asserts that two objects are equal in value and type. // // assert.Exactly(t, int32(123), int64(123)) func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } aType := reflect.TypeOf(expected) bType := reflect.TypeOf(actual) if aType != bType { return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...) } return Equal(t, expected, actual, msgAndArgs...) } // NotNil asserts that the specified object is not nil. // // assert.NotNil(t, err) func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if !isNil(object) { return true } return Fail(t, "Expected value not to be nil.", msgAndArgs...) } // isNil checks if a specified object is nil or not, without Failing. func isNil(object interface{}) bool { if object == nil { return true } value := reflect.ValueOf(object) kind := value.Kind() if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { return true } return false } // Nil asserts that the specified object is nil. // // assert.Nil(t, err) func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if isNil(object) { return true } return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) } // isEmpty gets whether the specified object is considered empty or not. func isEmpty(object interface{}) bool { // get nil case out of the way if object == nil { return true } objValue := reflect.ValueOf(object) switch objValue.Kind() { // collection types are empty when they have no element case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: return objValue.Len() == 0 // pointers are empty if nil or if the value they point to is empty case reflect.Ptr: if objValue.IsNil() { return true } deref := objValue.Elem().Interface() return isEmpty(deref) // for all other types, compare against the zero value default: zero := reflect.Zero(objValue.Type()) return reflect.DeepEqual(object, zero.Interface()) } } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Empty(t, obj) func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } pass := isEmpty(object) if !pass { Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) } return pass } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if assert.NotEmpty(t, obj) { // assert.Equal(t, "two", obj[1]) // } func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } pass := !isEmpty(object) if !pass { Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) } return pass } // getLen try to get length of object. // return (false, 0) if impossible. func getLen(x interface{}) (ok bool, length int) { v := reflect.ValueOf(x) defer func() { if e := recover(); e != nil { ok = false } }() return true, v.Len() } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // assert.Len(t, mySlice, 3) func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } ok, l := getLen(object) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) } if l != length { return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) } return true } // True asserts that the specified value is true. // // assert.True(t, myBool) func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if h, ok := t.(interface { Helper() }); ok { h.Helper() } if value != true { return Fail(t, "Should be true", msgAndArgs...) } return true } // False asserts that the specified value is false. // // assert.False(t, myBool) func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if value != false { return Fail(t, "Should be false", msgAndArgs...) } return true } // NotEqual asserts that the specified values are NOT equal. // // assert.NotEqual(t, obj1, obj2) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if err := validateEqualArgs(expected, actual); err != nil { return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)", expected, actual, err), msgAndArgs...) } if ObjectsAreEqual(expected, actual) { return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) } return true } // containsElement try loop over the list check if the list includes the element. // return (false, false) if impossible. // return (true, false) if element was not found. // return (true, true) if element was found. func includeElement(list interface{}, element interface{}) (ok, found bool) { listValue := reflect.ValueOf(list) elementValue := reflect.ValueOf(element) defer func() { if e := recover(); e != nil { ok = false found = false } }() if reflect.TypeOf(list).Kind() == reflect.String { return true, strings.Contains(listValue.String(), elementValue.String()) } if reflect.TypeOf(list).Kind() == reflect.Map { mapKeys := listValue.MapKeys() for i := 0; i < len(mapKeys); i++ { if ObjectsAreEqual(mapKeys[i].Interface(), element) { return true, true } } return true, false } for i := 0; i < listValue.Len(); i++ { if ObjectsAreEqual(listValue.Index(i).Interface(), element) { return true, true } } return true, false } // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Contains(t, "Hello World", "World") // assert.Contains(t, ["Hello", "World"], "World") // assert.Contains(t, {"Hello": "World"}, "Hello") func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } ok, found := includeElement(s, contains) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) } if !found { return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) } return true } // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // assert.NotContains(t, "Hello World", "Earth") // assert.NotContains(t, ["Hello", "World"], "Earth") // assert.NotContains(t, {"Hello": "World"}, "Earth") func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } ok, found := includeElement(s, contains) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) } if found { return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) } return true } // Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { if h, ok := t.(tHelper); ok { h.Helper() } if subset == nil { return true // we consider nil to be equal to the nil set } subsetValue := reflect.ValueOf(subset) defer func() { if e := recover(); e != nil { ok = false } }() listKind := reflect.TypeOf(list).Kind() subsetKind := reflect.TypeOf(subset).Kind() if listKind != reflect.Array && listKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) } if subsetKind != reflect.Array && subsetKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) } for i := 0; i < subsetValue.Len(); i++ { element := subsetValue.Index(i).Interface() ok, found := includeElement(list, element) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) } if !found { return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...) } } return true } // NotSubset asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { if h, ok := t.(tHelper); ok { h.Helper() } if subset == nil { return Fail(t, fmt.Sprintf("nil is the empty set which is a subset of every set"), msgAndArgs...) } subsetValue := reflect.ValueOf(subset) defer func() { if e := recover(); e != nil { ok = false } }() listKind := reflect.TypeOf(list).Kind() subsetKind := reflect.TypeOf(subset).Kind() if listKind != reflect.Array && listKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) } if subsetKind != reflect.Array && subsetKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) } for i := 0; i < subsetValue.Len(); i++ { element := subsetValue.Index(i).Interface() ok, found := includeElement(list, element) if !ok { return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) } if !found { return true } } return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...) } // ElementsMatch asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) { if h, ok := t.(tHelper); ok { h.Helper() } if isEmpty(listA) && isEmpty(listB) { return true } aKind := reflect.TypeOf(listA).Kind() bKind := reflect.TypeOf(listB).Kind() if aKind != reflect.Array && aKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listA, aKind), msgAndArgs...) } if bKind != reflect.Array && bKind != reflect.Slice { return Fail(t, fmt.Sprintf("%q has an unsupported type %s", listB, bKind), msgAndArgs...) } aValue := reflect.ValueOf(listA) bValue := reflect.ValueOf(listB) aLen := aValue.Len() bLen := bValue.Len() if aLen != bLen { return Fail(t, fmt.Sprintf("lengths don't match: %d != %d", aLen, bLen), msgAndArgs...) } // Mark indexes in bValue that we already used visited := make([]bool, bLen) for i := 0; i < aLen; i++ { element := aValue.Index(i).Interface() found := false for j := 0; j < bLen; j++ { if visited[j] { continue } if ObjectsAreEqual(bValue.Index(j).Interface(), element) { visited[j] = true found = true break } } if !found { return Fail(t, fmt.Sprintf("element %s appears more times in %s than in %s", element, aValue, bValue), msgAndArgs...) } } return true } // Condition uses a Comparison to assert a complex condition. func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } result := comp() if !result { Fail(t, "Condition failed!", msgAndArgs...) } return result } // PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics // methods, and represents a simple func that takes no arguments, and returns nothing. type PanicTestFunc func() // didPanic returns true if the function passed to it panics. Otherwise, it returns false. func didPanic(f PanicTestFunc) (bool, interface{}) { didPanic := false var message interface{} func() { defer func() { if message = recover(); message != nil { didPanic = true } }() // call the target function f() }() return didPanic, message } // Panics asserts that the code inside the specified PanicTestFunc panics. // // assert.Panics(t, func(){ GoCrazy() }) func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%v", f, panicValue), msgAndArgs...) } return true } // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } funcDidPanic, panicValue := didPanic(f) if !funcDidPanic { return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%v", f, panicValue), msgAndArgs...) } if panicValue != expected { return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%v\n\tPanic value:\t%v", f, expected, panicValue), msgAndArgs...) } return true } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // assert.NotPanics(t, func(){ RemainCalm() }) func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if funcDidPanic, panicValue := didPanic(f); funcDidPanic { return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v", f, panicValue), msgAndArgs...) } return true } // WithinDuration asserts that the two times are within duration delta of each other. // // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } dt := expected.Sub(actual) if dt < -delta || dt > delta { return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) } return true } func toFloat(x interface{}) (float64, bool) { var xf float64 xok := true switch xn := x.(type) { case uint8: xf = float64(xn) case uint16: xf = float64(xn) case uint32: xf = float64(xn) case uint64: xf = float64(xn) case int: xf = float64(xn) case int8: xf = float64(xn) case int16: xf = float64(xn) case int32: xf = float64(xn) case int64: xf = float64(xn) case float32: xf = float64(xn) case float64: xf = float64(xn) case time.Duration: xf = float64(xn) default: xok = false } return xf, xok } // InDelta asserts that the two numerals are within delta of each other. // // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } af, aok := toFloat(expected) bf, bok := toFloat(actual) if !aok || !bok { return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) } if math.IsNaN(af) { return Fail(t, fmt.Sprintf("Expected must not be NaN"), msgAndArgs...) } if math.IsNaN(bf) { return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) } dt := af - bf if dt < -delta || dt > delta { return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) } return true } // InDeltaSlice is the same as InDelta, except it compares two slices. func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if expected == nil || actual == nil || reflect.TypeOf(actual).Kind() != reflect.Slice || reflect.TypeOf(expected).Kind() != reflect.Slice { return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) } actualSlice := reflect.ValueOf(actual) expectedSlice := reflect.ValueOf(expected) for i := 0; i < actualSlice.Len(); i++ { result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...) if !result { return result } } return true } // InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if expected == nil || actual == nil || reflect.TypeOf(actual).Kind() != reflect.Map || reflect.TypeOf(expected).Kind() != reflect.Map { return Fail(t, "Arguments must be maps", msgAndArgs...) } expectedMap := reflect.ValueOf(expected) actualMap := reflect.ValueOf(actual) if expectedMap.Len() != actualMap.Len() { return Fail(t, "Arguments must have the same number of keys", msgAndArgs...) } for _, k := range expectedMap.MapKeys() { ev := expectedMap.MapIndex(k) av := actualMap.MapIndex(k) if !ev.IsValid() { return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...) } if !av.IsValid() { return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...) } if !InDelta( t, ev.Interface(), av.Interface(), delta, msgAndArgs..., ) { return false } } return true } func calcRelativeError(expected, actual interface{}) (float64, error) { af, aok := toFloat(expected) if !aok { return 0, fmt.Errorf("expected value %q cannot be converted to float", expected) } if af == 0 { return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error") } bf, bok := toFloat(actual) if !bok { return 0, fmt.Errorf("actual value %q cannot be converted to float", actual) } return math.Abs(af-bf) / math.Abs(af), nil } // InEpsilon asserts that expected and actual have a relative error less than epsilon func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } actualEpsilon, err := calcRelativeError(expected, actual) if err != nil { return Fail(t, err.Error(), msgAndArgs...) } if actualEpsilon > epsilon { return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+ " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...) } return true } // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if expected == nil || actual == nil || reflect.TypeOf(actual).Kind() != reflect.Slice || reflect.TypeOf(expected).Kind() != reflect.Slice { return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) } actualSlice := reflect.ValueOf(actual) expectedSlice := reflect.ValueOf(expected) for i := 0; i < actualSlice.Len(); i++ { result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon) if !result { return result } } return true } /* Errors */ // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoError(t, err) { // assert.Equal(t, expectedObj, actualObj) // } func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if err != nil { return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...) } return true } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Error(t, err) { // assert.Equal(t, expectedError, err) // } func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if err == nil { return Fail(t, "An error is expected but got nil.", msgAndArgs...) } return true } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // assert.EqualError(t, err, expectedErrorString) func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if !Error(t, theError, msgAndArgs...) { return false } expected := errString actual := theError.Error() // don't need to use deep equals here, we know they are both strings if expected != actual { return Fail(t, fmt.Sprintf("Error message not equal:\n"+ "expected: %q\n"+ "actual : %q", expected, actual), msgAndArgs...) } return true } // matchRegexp return true if a specified regexp matches a string. func matchRegexp(rx interface{}, str interface{}) bool { var r *regexp.Regexp if rr, ok := rx.(*regexp.Regexp); ok { r = rr } else { r = regexp.MustCompile(fmt.Sprint(rx)) } return (r.FindStringIndex(fmt.Sprint(str)) != nil) } // Regexp asserts that a specified regexp matches a string. // // assert.Regexp(t, regexp.MustCompile("start"), "it's starting") // assert.Regexp(t, "start...$", "it's not starting") func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } match := matchRegexp(rx, str) if !match { Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) } return match } // NotRegexp asserts that a specified regexp does not match a string. // // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") // assert.NotRegexp(t, "^start", "it's not starting") func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } match := matchRegexp(rx, str) if match { Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) } return !match } // Zero asserts that i is the zero value for its type. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) } return true } // NotZero asserts that i is not the zero value for its type. func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...) } return true } // FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } info, err := os.Lstat(path) if err != nil { if os.IsNotExist(err) { return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...) } return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...) } if info.IsDir() { return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...) } return true } // DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } info, err := os.Lstat(path) if err != nil { if os.IsNotExist(err) { return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...) } return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...) } if !info.IsDir() { return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...) } return true } // JSONEq asserts that two JSON strings are equivalent. // // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } var expectedJSONAsInterface, actualJSONAsInterface interface{} if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil { return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...) } if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil { return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...) } return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...) } func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { t := reflect.TypeOf(v) k := t.Kind() if k == reflect.Ptr { t = t.Elem() k = t.Kind() } return t, k } // diff returns a diff of both values as long as both are of the same type and // are a struct, map, slice or array. Otherwise it returns an empty string. func diff(expected interface{}, actual interface{}) string { if expected == nil || actual == nil { return "" } et, ek := typeAndKind(expected) at, _ := typeAndKind(actual) if et != at { return "" } if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { return "" } e := spewConfig.Sdump(expected) a := spewConfig.Sdump(actual) diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ A: difflib.SplitLines(e), B: difflib.SplitLines(a), FromFile: "Expected", FromDate: "", ToFile: "Actual", ToDate: "", Context: 1, }) return "\n\nDiff:\n" + diff } // validateEqualArgs checks whether provided arguments can be safely used in the // Equal/NotEqual functions. func validateEqualArgs(expected, actual interface{}) error { if isFunction(expected) || isFunction(actual) { return errors.New("cannot take func type as argument") } return nil } func isFunction(arg interface{}) bool { if arg == nil { return false } return reflect.TypeOf(arg).Kind() == reflect.Func } var spewConfig = spew.ConfigState{ Indent: " ", DisablePointerAddresses: true, DisableCapacities: true, SortKeys: true, } type tHelper interface { Helper() } ================================================ FILE: src/github.com/stretchr/testify/assert/assertions_test.go ================================================ package assert import ( "bytes" "encoding/json" "errors" "fmt" "io" "math" "os" "reflect" "regexp" "runtime" "strings" "testing" "time" ) var ( i interface{} zeros = []interface{}{ false, byte(0), complex64(0), complex128(0), float32(0), float64(0), int(0), int8(0), int16(0), int32(0), int64(0), rune(0), uint(0), uint8(0), uint16(0), uint32(0), uint64(0), uintptr(0), "", [0]interface{}{}, []interface{}(nil), struct{ x int }{}, (*interface{})(nil), (func())(nil), nil, interface{}(nil), map[interface{}]interface{}(nil), (chan interface{})(nil), (<-chan interface{})(nil), (chan<- interface{})(nil), } nonZeros = []interface{}{ true, byte(1), complex64(1), complex128(1), float32(1), float64(1), int(1), int8(1), int16(1), int32(1), int64(1), rune(1), uint(1), uint8(1), uint16(1), uint32(1), uint64(1), uintptr(1), "s", [1]interface{}{1}, []interface{}{}, struct{ x int }{1}, (*interface{})(&i), (func())(func() {}), interface{}(1), map[interface{}]interface{}{}, (chan interface{})(make(chan interface{})), (<-chan interface{})(make(chan interface{})), (chan<- interface{})(make(chan interface{})), } ) // AssertionTesterInterface defines an interface to be used for testing assertion methods type AssertionTesterInterface interface { TestMethod() } // AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface type AssertionTesterConformingObject struct { } func (a *AssertionTesterConformingObject) TestMethod() { } // AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface type AssertionTesterNonConformingObject struct { } func TestObjectsAreEqual(t *testing.T) { if !ObjectsAreEqual("Hello World", "Hello World") { t.Error("objectsAreEqual should return true") } if !ObjectsAreEqual(123, 123) { t.Error("objectsAreEqual should return true") } if !ObjectsAreEqual(123.5, 123.5) { t.Error("objectsAreEqual should return true") } if !ObjectsAreEqual([]byte("Hello World"), []byte("Hello World")) { t.Error("objectsAreEqual should return true") } if !ObjectsAreEqual(nil, nil) { t.Error("objectsAreEqual should return true") } if ObjectsAreEqual(map[int]int{5: 10}, map[int]int{10: 20}) { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual('x', "x") { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual("x", 'x') { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual(0, 0.1) { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual(0.1, 0) { t.Error("objectsAreEqual should return false") } if ObjectsAreEqual(uint32(10), int32(10)) { t.Error("objectsAreEqual should return false") } if !ObjectsAreEqualValues(uint32(10), int32(10)) { t.Error("ObjectsAreEqualValues should return true") } if ObjectsAreEqualValues(0, nil) { t.Fail() } if ObjectsAreEqualValues(nil, 0) { t.Fail() } } func TestImplements(t *testing.T) { mockT := new(testing.T) if !Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") } if Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") } if Implements(mockT, (*AssertionTesterInterface)(nil), nil) { t.Error("Implements method should return false: nil does not implement AssertionTesterInterface") } } func TestIsType(t *testing.T) { mockT := new(testing.T) if !IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") } if IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") } } func TestEqual(t *testing.T) { mockT := new(testing.T) if !Equal(mockT, "Hello World", "Hello World") { t.Error("Equal should return true") } if !Equal(mockT, 123, 123) { t.Error("Equal should return true") } if !Equal(mockT, 123.5, 123.5) { t.Error("Equal should return true") } if !Equal(mockT, []byte("Hello World"), []byte("Hello World")) { t.Error("Equal should return true") } if !Equal(mockT, nil, nil) { t.Error("Equal should return true") } if !Equal(mockT, int32(123), int32(123)) { t.Error("Equal should return true") } if !Equal(mockT, uint64(123), uint64(123)) { t.Error("Equal should return true") } if !Equal(mockT, &struct{}{}, &struct{}{}) { t.Error("Equal should return true (pointer equality is based on equality of underlying value)") } var m map[string]interface{} if Equal(mockT, m["bar"], "something") { t.Error("Equal should return false") } } // bufferT implements TestingT. Its implementation of Errorf writes the output that would be produced by // testing.T.Errorf to an internal bytes.Buffer. type bufferT struct { buf bytes.Buffer } func (t *bufferT) Errorf(format string, args ...interface{}) { // implementation of decorate is copied from testing.T decorate := func(s string) string { _, file, line, ok := runtime.Caller(3) // decorate + glog + public function. if ok { // Truncate file name at last file name separator. if index := strings.LastIndex(file, "/"); index >= 0 { file = file[index+1:] } else if index = strings.LastIndex(file, "\\"); index >= 0 { file = file[index+1:] } } else { file = "???" line = 1 } buf := new(bytes.Buffer) // Every line is indented at least one tab. buf.WriteByte('\t') fmt.Fprintf(buf, "%s:%d: ", file, line) lines := strings.Split(s, "\n") if l := len(lines); l > 1 && lines[l-1] == "" { lines = lines[:l-1] } for i, line := range lines { if i > 0 { // Second and subsequent lines are indented an extra tab. buf.WriteString("\n\t\t") } buf.WriteString(line) } buf.WriteByte('\n') return buf.String() } t.buf.WriteString(decorate(fmt.Sprintf(format, args...))) } func TestEqualFormatting(t *testing.T) { for i, currCase := range []struct { equalWant string equalGot string msgAndArgs []interface{} want string }{ {equalWant: "want", equalGot: "got", want: "\tassertions.go:[0-9]+: \n\t\t\tError Trace:\t\n\t\t\tError: \tNot equal: \n\t\t\t \texpected: \"want\"\n\t\t\t \tactual : \"got\"\n"}, {equalWant: "want", equalGot: "got", msgAndArgs: []interface{}{"hello, %v!", "world"}, want: "\tassertions.go:[0-9]+: \n\t\t\tError Trace:\t\n\t\t\tError: \tNot equal: \n\t\t\t \texpected: \"want\"\n\t\t\t \tactual : \"got\"\n\t\t\tMessages: \thello, world!\n"}, } { mockT := &bufferT{} Equal(mockT, currCase.equalWant, currCase.equalGot, currCase.msgAndArgs...) Regexp(t, regexp.MustCompile(currCase.want), mockT.buf.String(), "Case %d", i) } } func TestFormatUnequalValues(t *testing.T) { expected, actual := formatUnequalValues("foo", "bar") Equal(t, `"foo"`, expected, "value should not include type") Equal(t, `"bar"`, actual, "value should not include type") expected, actual = formatUnequalValues(123, 123) Equal(t, `123`, expected, "value should not include type") Equal(t, `123`, actual, "value should not include type") expected, actual = formatUnequalValues(int64(123), int32(123)) Equal(t, `int64(123)`, expected, "value should include type") Equal(t, `int32(123)`, actual, "value should include type") expected, actual = formatUnequalValues(int64(123), nil) Equal(t, `int64(123)`, expected, "value should include type") Equal(t, `()`, actual, "value should include type") type testStructType struct { Val string } expected, actual = formatUnequalValues(&testStructType{Val: "test"}, &testStructType{Val: "test"}) Equal(t, `&assert.testStructType{Val:"test"}`, expected, "value should not include type annotation") Equal(t, `&assert.testStructType{Val:"test"}`, actual, "value should not include type annotation") } func TestNotNil(t *testing.T) { mockT := new(testing.T) if !NotNil(mockT, new(AssertionTesterConformingObject)) { t.Error("NotNil should return true: object is not nil") } if NotNil(mockT, nil) { t.Error("NotNil should return false: object is nil") } if NotNil(mockT, (*struct{})(nil)) { t.Error("NotNil should return false: object is (*struct{})(nil)") } } func TestNil(t *testing.T) { mockT := new(testing.T) if !Nil(mockT, nil) { t.Error("Nil should return true: object is nil") } if !Nil(mockT, (*struct{})(nil)) { t.Error("Nil should return true: object is (*struct{})(nil)") } if Nil(mockT, new(AssertionTesterConformingObject)) { t.Error("Nil should return false: object is not nil") } } func TestTrue(t *testing.T) { mockT := new(testing.T) if !True(mockT, true) { t.Error("True should return true") } if True(mockT, false) { t.Error("True should return false") } } func TestFalse(t *testing.T) { mockT := new(testing.T) if !False(mockT, false) { t.Error("False should return true") } if False(mockT, true) { t.Error("False should return false") } } func TestExactly(t *testing.T) { mockT := new(testing.T) a := float32(1) b := float64(1) c := float32(1) d := float32(2) if Exactly(mockT, a, b) { t.Error("Exactly should return false") } if Exactly(mockT, a, d) { t.Error("Exactly should return false") } if !Exactly(mockT, a, c) { t.Error("Exactly should return true") } if Exactly(mockT, nil, a) { t.Error("Exactly should return false") } if Exactly(mockT, a, nil) { t.Error("Exactly should return false") } } func TestNotEqual(t *testing.T) { mockT := new(testing.T) if !NotEqual(mockT, "Hello World", "Hello World!") { t.Error("NotEqual should return true") } if !NotEqual(mockT, 123, 1234) { t.Error("NotEqual should return true") } if !NotEqual(mockT, 123.5, 123.55) { t.Error("NotEqual should return true") } if !NotEqual(mockT, []byte("Hello World"), []byte("Hello World!")) { t.Error("NotEqual should return true") } if !NotEqual(mockT, nil, new(AssertionTesterConformingObject)) { t.Error("NotEqual should return true") } funcA := func() int { return 23 } funcB := func() int { return 42 } if NotEqual(mockT, funcA, funcB) { t.Error("NotEqual should return false") } if NotEqual(mockT, "Hello World", "Hello World") { t.Error("NotEqual should return false") } if NotEqual(mockT, 123, 123) { t.Error("NotEqual should return false") } if NotEqual(mockT, 123.5, 123.5) { t.Error("NotEqual should return false") } if NotEqual(mockT, []byte("Hello World"), []byte("Hello World")) { t.Error("NotEqual should return false") } if NotEqual(mockT, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { t.Error("NotEqual should return false") } if NotEqual(mockT, &struct{}{}, &struct{}{}) { t.Error("NotEqual should return false") } } type A struct { Name, Value string } func TestContains(t *testing.T) { mockT := new(testing.T) list := []string{"Foo", "Bar"} complexList := []*A{ {"b", "c"}, {"d", "e"}, {"g", "h"}, {"j", "k"}, } simpleMap := map[interface{}]interface{}{"Foo": "Bar"} if !Contains(mockT, "Hello World", "Hello") { t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") } if Contains(mockT, "Hello World", "Salut") { t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") } if !Contains(mockT, list, "Bar") { t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Bar\"") } if Contains(mockT, list, "Salut") { t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") } if !Contains(mockT, complexList, &A{"g", "h"}) { t.Error("Contains should return true: complexList contains {\"g\", \"h\"}") } if Contains(mockT, complexList, &A{"g", "e"}) { t.Error("Contains should return false: complexList contains {\"g\", \"e\"}") } if Contains(mockT, complexList, &A{"g", "e"}) { t.Error("Contains should return false: complexList contains {\"g\", \"e\"}") } if !Contains(mockT, simpleMap, "Foo") { t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"") } if Contains(mockT, simpleMap, "Bar") { t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"") } } func TestNotContains(t *testing.T) { mockT := new(testing.T) list := []string{"Foo", "Bar"} simpleMap := map[interface{}]interface{}{"Foo": "Bar"} if !NotContains(mockT, "Hello World", "Hello!") { t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") } if NotContains(mockT, "Hello World", "Hello") { t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") } if !NotContains(mockT, list, "Foo!") { t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") } if NotContains(mockT, list, "Foo") { t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") } if NotContains(mockT, simpleMap, "Foo") { t.Error("Contains should return true: \"{\"Foo\": \"Bar\"}\" contains \"Foo\"") } if !NotContains(mockT, simpleMap, "Bar") { t.Error("Contains should return false: \"{\"Foo\": \"Bar\"}\" does not contains \"Bar\"") } } func TestSubset(t *testing.T) { mockT := new(testing.T) if !Subset(mockT, []int{1, 2, 3}, nil) { t.Error("Subset should return true: given subset is nil") } if !Subset(mockT, []int{1, 2, 3}, []int{}) { t.Error("Subset should return true: any set contains the nil set") } if !Subset(mockT, []int{1, 2, 3}, []int{1, 2}) { t.Error("Subset should return true: [1, 2, 3] contains [1, 2]") } if !Subset(mockT, []int{1, 2, 3}, []int{1, 2, 3}) { t.Error("Subset should return true: [1, 2, 3] contains [1, 2, 3]") } if !Subset(mockT, []string{"hello", "world"}, []string{"hello"}) { t.Error("Subset should return true: [\"hello\", \"world\"] contains [\"hello\"]") } if Subset(mockT, []string{"hello", "world"}, []string{"hello", "testify"}) { t.Error("Subset should return false: [\"hello\", \"world\"] does not contain [\"hello\", \"testify\"]") } if Subset(mockT, []int{1, 2, 3}, []int{4, 5}) { t.Error("Subset should return false: [1, 2, 3] does not contain [4, 5]") } if Subset(mockT, []int{1, 2, 3}, []int{1, 5}) { t.Error("Subset should return false: [1, 2, 3] does not contain [1, 5]") } } func TestNotSubset(t *testing.T) { mockT := new(testing.T) if NotSubset(mockT, []int{1, 2, 3}, nil) { t.Error("NotSubset should return false: given subset is nil") } if NotSubset(mockT, []int{1, 2, 3}, []int{}) { t.Error("NotSubset should return false: any set contains the nil set") } if NotSubset(mockT, []int{1, 2, 3}, []int{1, 2}) { t.Error("NotSubset should return false: [1, 2, 3] contains [1, 2]") } if NotSubset(mockT, []int{1, 2, 3}, []int{1, 2, 3}) { t.Error("NotSubset should return false: [1, 2, 3] contains [1, 2, 3]") } if NotSubset(mockT, []string{"hello", "world"}, []string{"hello"}) { t.Error("NotSubset should return false: [\"hello\", \"world\"] contains [\"hello\"]") } if !NotSubset(mockT, []string{"hello", "world"}, []string{"hello", "testify"}) { t.Error("NotSubset should return true: [\"hello\", \"world\"] does not contain [\"hello\", \"testify\"]") } if !NotSubset(mockT, []int{1, 2, 3}, []int{4, 5}) { t.Error("NotSubset should return true: [1, 2, 3] does not contain [4, 5]") } if !NotSubset(mockT, []int{1, 2, 3}, []int{1, 5}) { t.Error("NotSubset should return true: [1, 2, 3] does not contain [1, 5]") } } func TestNotSubsetNil(t *testing.T) { mockT := new(testing.T) NotSubset(mockT, []string{"foo"}, nil) if !mockT.Failed() { t.Error("NotSubset on nil set should have failed the test") } } func Test_includeElement(t *testing.T) { list1 := []string{"Foo", "Bar"} list2 := []int{1, 2} simpleMap := map[interface{}]interface{}{"Foo": "Bar"} ok, found := includeElement("Hello World", "World") True(t, ok) True(t, found) ok, found = includeElement(list1, "Foo") True(t, ok) True(t, found) ok, found = includeElement(list1, "Bar") True(t, ok) True(t, found) ok, found = includeElement(list2, 1) True(t, ok) True(t, found) ok, found = includeElement(list2, 2) True(t, ok) True(t, found) ok, found = includeElement(list1, "Foo!") True(t, ok) False(t, found) ok, found = includeElement(list2, 3) True(t, ok) False(t, found) ok, found = includeElement(list2, "1") True(t, ok) False(t, found) ok, found = includeElement(simpleMap, "Foo") True(t, ok) True(t, found) ok, found = includeElement(simpleMap, "Bar") True(t, ok) False(t, found) ok, found = includeElement(1433, "1") False(t, ok) False(t, found) } func TestElementsMatch(t *testing.T) { mockT := new(testing.T) if !ElementsMatch(mockT, nil, nil) { t.Error("ElementsMatch should return true") } if !ElementsMatch(mockT, []int{}, []int{}) { t.Error("ElementsMatch should return true") } if !ElementsMatch(mockT, []int{1}, []int{1}) { t.Error("ElementsMatch should return true") } if !ElementsMatch(mockT, []int{1, 1}, []int{1, 1}) { t.Error("ElementsMatch should return true") } if !ElementsMatch(mockT, []int{1, 2}, []int{1, 2}) { t.Error("ElementsMatch should return true") } if !ElementsMatch(mockT, []int{1, 2}, []int{2, 1}) { t.Error("ElementsMatch should return true") } if !ElementsMatch(mockT, [2]int{1, 2}, [2]int{2, 1}) { t.Error("ElementsMatch should return true") } if !ElementsMatch(mockT, []string{"hello", "world"}, []string{"world", "hello"}) { t.Error("ElementsMatch should return true") } if !ElementsMatch(mockT, []string{"hello", "hello"}, []string{"hello", "hello"}) { t.Error("ElementsMatch should return true") } if !ElementsMatch(mockT, []string{"hello", "hello", "world"}, []string{"hello", "world", "hello"}) { t.Error("ElementsMatch should return true") } if !ElementsMatch(mockT, [3]string{"hello", "hello", "world"}, [3]string{"hello", "world", "hello"}) { t.Error("ElementsMatch should return true") } if !ElementsMatch(mockT, []int{}, nil) { t.Error("ElementsMatch should return true") } if ElementsMatch(mockT, []int{1}, []int{1, 1}) { t.Error("ElementsMatch should return false") } if ElementsMatch(mockT, []int{1, 2}, []int{2, 2}) { t.Error("ElementsMatch should return false") } if ElementsMatch(mockT, []string{"hello", "hello"}, []string{"hello"}) { t.Error("ElementsMatch should return false") } } func TestCondition(t *testing.T) { mockT := new(testing.T) if !Condition(mockT, func() bool { return true }, "Truth") { t.Error("Condition should return true") } if Condition(mockT, func() bool { return false }, "Lie") { t.Error("Condition should return false") } } func TestDidPanic(t *testing.T) { if funcDidPanic, _ := didPanic(func() { panic("Panic!") }); !funcDidPanic { t.Error("didPanic should return true") } if funcDidPanic, _ := didPanic(func() { }); funcDidPanic { t.Error("didPanic should return false") } } func TestPanics(t *testing.T) { mockT := new(testing.T) if !Panics(mockT, func() { panic("Panic!") }) { t.Error("Panics should return true") } if Panics(mockT, func() { }) { t.Error("Panics should return false") } } func TestPanicsWithValue(t *testing.T) { mockT := new(testing.T) if !PanicsWithValue(mockT, "Panic!", func() { panic("Panic!") }) { t.Error("PanicsWithValue should return true") } if PanicsWithValue(mockT, "Panic!", func() { }) { t.Error("PanicsWithValue should return false") } if PanicsWithValue(mockT, "at the disco", func() { panic("Panic!") }) { t.Error("PanicsWithValue should return false") } } func TestNotPanics(t *testing.T) { mockT := new(testing.T) if !NotPanics(mockT, func() { }) { t.Error("NotPanics should return true") } if NotPanics(mockT, func() { panic("Panic!") }) { t.Error("NotPanics should return false") } } func TestNoError(t *testing.T) { mockT := new(testing.T) // start with a nil error var err error True(t, NoError(mockT, err), "NoError should return True for nil arg") // now set an error err = errors.New("some error") False(t, NoError(mockT, err), "NoError with error should return False") // returning an empty error interface err = func() error { var err *customError if err != nil { t.Fatal("err should be nil here") } return err }() if err == nil { // err is not nil here! t.Errorf("Error should be nil due to empty interface: %s", err) } False(t, NoError(mockT, err), "NoError should fail with empty error interface") } type customError struct{} func (*customError) Error() string { return "fail" } func TestError(t *testing.T) { mockT := new(testing.T) // start with a nil error var err error False(t, Error(mockT, err), "Error should return False for nil arg") // now set an error err = errors.New("some error") True(t, Error(mockT, err), "Error with error should return True") // go vet check True(t, Errorf(mockT, err, "example with %s", "formatted message"), "Errorf with error should rturn True") // returning an empty error interface err = func() error { var err *customError if err != nil { t.Fatal("err should be nil here") } return err }() if err == nil { // err is not nil here! t.Errorf("Error should be nil due to empty interface: %s", err) } True(t, Error(mockT, err), "Error should pass with empty error interface") } func TestEqualError(t *testing.T) { mockT := new(testing.T) // start with a nil error var err error False(t, EqualError(mockT, err, ""), "EqualError should return false for nil arg") // now set an error err = errors.New("some error") False(t, EqualError(mockT, err, "Not some error"), "EqualError should return false for different error string") True(t, EqualError(mockT, err, "some error"), "EqualError should return true") } func Test_isEmpty(t *testing.T) { chWithValue := make(chan struct{}, 1) chWithValue <- struct{}{} True(t, isEmpty("")) True(t, isEmpty(nil)) True(t, isEmpty([]string{})) True(t, isEmpty(0)) True(t, isEmpty(int32(0))) True(t, isEmpty(int64(0))) True(t, isEmpty(false)) True(t, isEmpty(map[string]string{})) True(t, isEmpty(new(time.Time))) True(t, isEmpty(time.Time{})) True(t, isEmpty(make(chan struct{}))) False(t, isEmpty("something")) False(t, isEmpty(errors.New("something"))) False(t, isEmpty([]string{"something"})) False(t, isEmpty(1)) False(t, isEmpty(true)) False(t, isEmpty(map[string]string{"Hello": "World"})) False(t, isEmpty(chWithValue)) } func TestEmpty(t *testing.T) { mockT := new(testing.T) chWithValue := make(chan struct{}, 1) chWithValue <- struct{}{} var tiP *time.Time var tiNP time.Time var s *string var f *os.File sP := &s x := 1 xP := &x type TString string type TStruct struct { x int s []int } True(t, Empty(mockT, ""), "Empty string is empty") True(t, Empty(mockT, nil), "Nil is empty") True(t, Empty(mockT, []string{}), "Empty string array is empty") True(t, Empty(mockT, 0), "Zero int value is empty") True(t, Empty(mockT, false), "False value is empty") True(t, Empty(mockT, make(chan struct{})), "Channel without values is empty") True(t, Empty(mockT, s), "Nil string pointer is empty") True(t, Empty(mockT, f), "Nil os.File pointer is empty") True(t, Empty(mockT, tiP), "Nil time.Time pointer is empty") True(t, Empty(mockT, tiNP), "time.Time is empty") True(t, Empty(mockT, TStruct{}), "struct with zero values is empty") True(t, Empty(mockT, TString("")), "empty aliased string is empty") True(t, Empty(mockT, sP), "ptr to nil value is empty") False(t, Empty(mockT, "something"), "Non Empty string is not empty") False(t, Empty(mockT, errors.New("something")), "Non nil object is not empty") False(t, Empty(mockT, []string{"something"}), "Non empty string array is not empty") False(t, Empty(mockT, 1), "Non-zero int value is not empty") False(t, Empty(mockT, true), "True value is not empty") False(t, Empty(mockT, chWithValue), "Channel with values is not empty") False(t, Empty(mockT, TStruct{x: 1}), "struct with initialized values is empty") False(t, Empty(mockT, TString("abc")), "non-empty aliased string is empty") False(t, Empty(mockT, xP), "ptr to non-nil value is not empty") } func TestNotEmpty(t *testing.T) { mockT := new(testing.T) chWithValue := make(chan struct{}, 1) chWithValue <- struct{}{} False(t, NotEmpty(mockT, ""), "Empty string is empty") False(t, NotEmpty(mockT, nil), "Nil is empty") False(t, NotEmpty(mockT, []string{}), "Empty string array is empty") False(t, NotEmpty(mockT, 0), "Zero int value is empty") False(t, NotEmpty(mockT, false), "False value is empty") False(t, NotEmpty(mockT, make(chan struct{})), "Channel without values is empty") True(t, NotEmpty(mockT, "something"), "Non Empty string is not empty") True(t, NotEmpty(mockT, errors.New("something")), "Non nil object is not empty") True(t, NotEmpty(mockT, []string{"something"}), "Non empty string array is not empty") True(t, NotEmpty(mockT, 1), "Non-zero int value is not empty") True(t, NotEmpty(mockT, true), "True value is not empty") True(t, NotEmpty(mockT, chWithValue), "Channel with values is not empty") } func Test_getLen(t *testing.T) { falseCases := []interface{}{ nil, 0, true, false, 'A', struct{}{}, } for _, v := range falseCases { ok, l := getLen(v) False(t, ok, "Expected getLen fail to get length of %#v", v) Equal(t, 0, l, "getLen should return 0 for %#v", v) } ch := make(chan int, 5) ch <- 1 ch <- 2 ch <- 3 trueCases := []struct { v interface{} l int }{ {[]int{1, 2, 3}, 3}, {[...]int{1, 2, 3}, 3}, {"ABC", 3}, {map[int]int{1: 2, 2: 4, 3: 6}, 3}, {ch, 3}, {[]int{}, 0}, {map[int]int{}, 0}, {make(chan int), 0}, {[]int(nil), 0}, {map[int]int(nil), 0}, {(chan int)(nil), 0}, } for _, c := range trueCases { ok, l := getLen(c.v) True(t, ok, "Expected getLen success to get length of %#v", c.v) Equal(t, c.l, l) } } func TestLen(t *testing.T) { mockT := new(testing.T) False(t, Len(mockT, nil, 0), "nil does not have length") False(t, Len(mockT, 0, 0), "int does not have length") False(t, Len(mockT, true, 0), "true does not have length") False(t, Len(mockT, false, 0), "false does not have length") False(t, Len(mockT, 'A', 0), "Rune does not have length") False(t, Len(mockT, struct{}{}, 0), "Struct does not have length") ch := make(chan int, 5) ch <- 1 ch <- 2 ch <- 3 cases := []struct { v interface{} l int }{ {[]int{1, 2, 3}, 3}, {[...]int{1, 2, 3}, 3}, {"ABC", 3}, {map[int]int{1: 2, 2: 4, 3: 6}, 3}, {ch, 3}, {[]int{}, 0}, {map[int]int{}, 0}, {make(chan int), 0}, {[]int(nil), 0}, {map[int]int(nil), 0}, {(chan int)(nil), 0}, } for _, c := range cases { True(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) } cases = []struct { v interface{} l int }{ {[]int{1, 2, 3}, 4}, {[...]int{1, 2, 3}, 2}, {"ABC", 2}, {map[int]int{1: 2, 2: 4, 3: 6}, 4}, {ch, 2}, {[]int{}, 1}, {map[int]int{}, 1}, {make(chan int), 1}, {[]int(nil), 1}, {map[int]int(nil), 1}, {(chan int)(nil), 1}, } for _, c := range cases { False(t, Len(mockT, c.v, c.l), "%#v have %d items", c.v, c.l) } } func TestWithinDuration(t *testing.T) { mockT := new(testing.T) a := time.Now() b := a.Add(10 * time.Second) True(t, WithinDuration(mockT, a, b, 10*time.Second), "A 10s difference is within a 10s time difference") True(t, WithinDuration(mockT, b, a, 10*time.Second), "A 10s difference is within a 10s time difference") False(t, WithinDuration(mockT, a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") False(t, WithinDuration(mockT, b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") False(t, WithinDuration(mockT, a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") False(t, WithinDuration(mockT, b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") False(t, WithinDuration(mockT, a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") False(t, WithinDuration(mockT, b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") } func TestInDelta(t *testing.T) { mockT := new(testing.T) True(t, InDelta(mockT, 1.001, 1, 0.01), "|1.001 - 1| <= 0.01") True(t, InDelta(mockT, 1, 1.001, 0.01), "|1 - 1.001| <= 0.01") True(t, InDelta(mockT, 1, 2, 1), "|1 - 2| <= 1") False(t, InDelta(mockT, 1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") False(t, InDelta(mockT, 2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") False(t, InDelta(mockT, "", nil, 1), "Expected non numerals to fail") False(t, InDelta(mockT, 42, math.NaN(), 0.01), "Expected NaN for actual to fail") False(t, InDelta(mockT, math.NaN(), 42, 0.01), "Expected NaN for expected to fail") cases := []struct { a, b interface{} delta float64 }{ {uint8(2), uint8(1), 1}, {uint16(2), uint16(1), 1}, {uint32(2), uint32(1), 1}, {uint64(2), uint64(1), 1}, {int(2), int(1), 1}, {int8(2), int8(1), 1}, {int16(2), int16(1), 1}, {int32(2), int32(1), 1}, {int64(2), int64(1), 1}, {float32(2), float32(1), 1}, {float64(2), float64(1), 1}, } for _, tc := range cases { True(t, InDelta(mockT, tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) } } func TestInDeltaSlice(t *testing.T) { mockT := new(testing.T) True(t, InDeltaSlice(mockT, []float64{1.001, 0.999}, []float64{1, 1}, 0.1), "{1.001, 0.009} is element-wise close to {1, 1} in delta=0.1") True(t, InDeltaSlice(mockT, []float64{1, 2}, []float64{0, 3}, 1), "{1, 2} is element-wise close to {0, 3} in delta=1") False(t, InDeltaSlice(mockT, []float64{1, 2}, []float64{0, 3}, 0.1), "{1, 2} is not element-wise close to {0, 3} in delta=0.1") False(t, InDeltaSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") } func TestInDeltaMapValues(t *testing.T) { mockT := new(testing.T) for _, tc := range []struct { title string expect interface{} actual interface{} f func(TestingT, bool, ...interface{}) bool delta float64 }{ { title: "Within delta", expect: map[string]float64{ "foo": 1.0, "bar": 2.0, }, actual: map[string]float64{ "foo": 1.01, "bar": 1.99, }, delta: 0.1, f: True, }, { title: "Within delta", expect: map[int]float64{ 1: 1.0, 2: 2.0, }, actual: map[int]float64{ 1: 1.0, 2: 1.99, }, delta: 0.1, f: True, }, { title: "Different number of keys", expect: map[int]float64{ 1: 1.0, 2: 2.0, }, actual: map[int]float64{ 1: 1.0, }, delta: 0.1, f: False, }, { title: "Within delta with zero value", expect: map[string]float64{ "zero": 0.0, }, actual: map[string]float64{ "zero": 0.0, }, delta: 0.1, f: True, }, { title: "With missing key with zero value", expect: map[string]float64{ "zero": 0.0, "foo": 0.0, }, actual: map[string]float64{ "zero": 0.0, "bar": 0.0, }, f: False, }, } { tc.f(t, InDeltaMapValues(mockT, tc.expect, tc.actual, tc.delta), tc.title+"\n"+diff(tc.expect, tc.actual)) } } func TestInEpsilon(t *testing.T) { mockT := new(testing.T) cases := []struct { a, b interface{} epsilon float64 }{ {uint8(2), uint16(2), .001}, {2.1, 2.2, 0.1}, {2.2, 2.1, 0.1}, {-2.1, -2.2, 0.1}, {-2.2, -2.1, 0.1}, {uint64(100), uint8(101), 0.01}, {0.1, -0.1, 2}, {0.1, 0, 2}, {time.Second, time.Second + time.Millisecond, 0.002}, } for _, tc := range cases { True(t, InEpsilon(t, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon), "test: %q", tc) } cases = []struct { a, b interface{} epsilon float64 }{ {uint8(2), int16(-2), .001}, {uint64(100), uint8(102), 0.01}, {2.1, 2.2, 0.001}, {2.2, 2.1, 0.001}, {2.1, -2.2, 1}, {2.1, "bla-bla", 0}, {0.1, -0.1, 1.99}, {0, 0.1, 2}, // expected must be different to zero {time.Second, time.Second + 10*time.Millisecond, 0.002}, } for _, tc := range cases { False(t, InEpsilon(mockT, tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) } } func TestInEpsilonSlice(t *testing.T) { mockT := new(testing.T) True(t, InEpsilonSlice(mockT, []float64{2.2, 2.0}, []float64{2.1, 2.1}, 0.06), "{2.2, 2.0} is element-wise close to {2.1, 2.1} in espilon=0.06") False(t, InEpsilonSlice(mockT, []float64{2.2, 2.0}, []float64{2.1, 2.1}, 0.04), "{2.2, 2.0} is not element-wise close to {2.1, 2.1} in espilon=0.04") False(t, InEpsilonSlice(mockT, "", nil, 1), "Expected non numeral slices to fail") } func TestRegexp(t *testing.T) { mockT := new(testing.T) cases := []struct { rx, str string }{ {"^start", "start of the line"}, {"end$", "in the end"}, {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, } for _, tc := range cases { True(t, Regexp(mockT, tc.rx, tc.str)) True(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) False(t, NotRegexp(mockT, tc.rx, tc.str)) False(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) } cases = []struct { rx, str string }{ {"^asdfastart", "Not the start of the line"}, {"end$", "in the end."}, {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, } for _, tc := range cases { False(t, Regexp(mockT, tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) False(t, Regexp(mockT, regexp.MustCompile(tc.rx), tc.str)) True(t, NotRegexp(mockT, tc.rx, tc.str)) True(t, NotRegexp(mockT, regexp.MustCompile(tc.rx), tc.str)) } } func testAutogeneratedFunction() { defer func() { if err := recover(); err == nil { panic("did not panic") } CallerInfo() }() t := struct { io.Closer }{} var c io.Closer c = t c.Close() } func TestCallerInfoWithAutogeneratedFunctions(t *testing.T) { NotPanics(t, func() { testAutogeneratedFunction() }) } func TestZero(t *testing.T) { mockT := new(testing.T) for _, test := range zeros { True(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) } for _, test := range nonZeros { False(t, Zero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) } } func TestNotZero(t *testing.T) { mockT := new(testing.T) for _, test := range zeros { False(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) } for _, test := range nonZeros { True(t, NotZero(mockT, test, "%#v is not the %v zero value", test, reflect.TypeOf(test))) } } func TestFileExists(t *testing.T) { mockT := new(testing.T) True(t, FileExists(mockT, "assertions.go")) mockT = new(testing.T) False(t, FileExists(mockT, "random_file")) mockT = new(testing.T) False(t, FileExists(mockT, "../_codegen")) } func TestDirExists(t *testing.T) { mockT := new(testing.T) False(t, DirExists(mockT, "assertions.go")) mockT = new(testing.T) False(t, DirExists(mockT, "random_dir")) mockT = new(testing.T) True(t, DirExists(mockT, "../_codegen")) } func TestJSONEq_EqualSONString(t *testing.T) { mockT := new(testing.T) True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`)) } func TestJSONEq_EquivalentButNotEqual(t *testing.T) { mockT := new(testing.T) True(t, JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)) } func TestJSONEq_HashOfArraysAndHashes(t *testing.T) { mockT := new(testing.T) True(t, JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}")) } func TestJSONEq_Array(t *testing.T) { mockT := new(testing.T) True(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`)) } func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) { mockT := new(testing.T) False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`)) } func TestJSONEq_HashesNotEquivalent(t *testing.T) { mockT := new(testing.T) False(t, JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)) } func TestJSONEq_ActualIsNotJSON(t *testing.T) { mockT := new(testing.T) False(t, JSONEq(mockT, `{"foo": "bar"}`, "Not JSON")) } func TestJSONEq_ExpectedIsNotJSON(t *testing.T) { mockT := new(testing.T) False(t, JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`)) } func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) { mockT := new(testing.T) False(t, JSONEq(mockT, "Not JSON", "Not JSON")) } func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) { mockT := new(testing.T) False(t, JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`)) } func TestDiff(t *testing.T) { expected := ` Diff: --- Expected +++ Actual @@ -1,3 +1,3 @@ (struct { foo string }) { - foo: (string) (len=5) "hello" + foo: (string) (len=3) "bar" } ` actual := diff( struct{ foo string }{"hello"}, struct{ foo string }{"bar"}, ) Equal(t, expected, actual) expected = ` Diff: --- Expected +++ Actual @@ -2,5 +2,5 @@ (int) 1, - (int) 2, (int) 3, - (int) 4 + (int) 5, + (int) 7 } ` actual = diff( []int{1, 2, 3, 4}, []int{1, 3, 5, 7}, ) Equal(t, expected, actual) expected = ` Diff: --- Expected +++ Actual @@ -2,4 +2,4 @@ (int) 1, - (int) 2, - (int) 3 + (int) 3, + (int) 5 } ` actual = diff( []int{1, 2, 3, 4}[0:3], []int{1, 3, 5, 7}[0:3], ) Equal(t, expected, actual) expected = ` Diff: --- Expected +++ Actual @@ -1,6 +1,6 @@ (map[string]int) (len=4) { - (string) (len=4) "four": (int) 4, + (string) (len=4) "five": (int) 5, (string) (len=3) "one": (int) 1, - (string) (len=5) "three": (int) 3, - (string) (len=3) "two": (int) 2 + (string) (len=5) "seven": (int) 7, + (string) (len=5) "three": (int) 3 } ` actual = diff( map[string]int{"one": 1, "two": 2, "three": 3, "four": 4}, map[string]int{"one": 1, "three": 3, "five": 5, "seven": 7}, ) Equal(t, expected, actual) } func TestDiffEmptyCases(t *testing.T) { Equal(t, "", diff(nil, nil)) Equal(t, "", diff(struct{ foo string }{}, nil)) Equal(t, "", diff(nil, struct{ foo string }{})) Equal(t, "", diff(1, 2)) Equal(t, "", diff(1, 2)) Equal(t, "", diff([]int{1}, []bool{true})) } // Ensure there are no data races func TestDiffRace(t *testing.T) { t.Parallel() expected := map[string]string{ "a": "A", "b": "B", "c": "C", } actual := map[string]string{ "d": "D", "e": "E", "f": "F", } // run diffs in parallel simulating tests with t.Parallel() numRoutines := 10 rChans := make([]chan string, numRoutines) for idx := range rChans { rChans[idx] = make(chan string) go func(ch chan string) { defer close(ch) ch <- diff(expected, actual) }(rChans[idx]) } for _, ch := range rChans { for msg := range ch { NotZero(t, msg) // dummy assert } } } type mockTestingT struct { } func (m *mockTestingT) Errorf(format string, args ...interface{}) {} func TestFailNowWithPlainTestingT(t *testing.T) { mockT := &mockTestingT{} Panics(t, func() { FailNow(mockT, "failed") }, "should panic since mockT is missing FailNow()") } type mockFailNowTestingT struct { } func (m *mockFailNowTestingT) Errorf(format string, args ...interface{}) {} func (m *mockFailNowTestingT) FailNow() {} func TestFailNowWithFullTestingT(t *testing.T) { mockT := &mockFailNowTestingT{} NotPanics(t, func() { FailNow(mockT, "failed") }, "should call mockT.FailNow() rather than panicking") } func TestBytesEqual(t *testing.T) { var cases = []struct { a, b []byte }{ {make([]byte, 2), make([]byte, 2)}, {make([]byte, 2), make([]byte, 2, 3)}, {nil, make([]byte, 0)}, } for i, c := range cases { Equal(t, reflect.DeepEqual(c.a, c.b), ObjectsAreEqual(c.a, c.b), "case %d failed", i+1) } } func BenchmarkBytesEqual(b *testing.B) { const size = 1024 * 8 s := make([]byte, size) for i := range s { s[i] = byte(i % 255) } s2 := make([]byte, size) copy(s2, s) mockT := &mockFailNowTestingT{} b.ResetTimer() for i := 0; i < b.N; i++ { Equal(mockT, s, s2) } } func TestEqualArgsValidation(t *testing.T) { err := validateEqualArgs(time.Now, time.Now) EqualError(t, err, "cannot take func type as argument") } func ExampleComparisonAssertionFunc() { t := &testing.T{} // provided by test adder := func(x, y int) int { return x + y } type args struct { x int y int } tests := []struct { name string args args expect int assertion ComparisonAssertionFunc }{ {"2+2=4", args{2, 2}, 4, Equal}, {"2+2!=5", args{2, 2}, 5, NotEqual}, {"2+3==5", args{2, 3}, 5, Exactly}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, tt.expect, adder(tt.args.x, tt.args.y)) }) } } func TestComparisonAssertionFunc(t *testing.T) { type iface interface { Name() string } tests := []struct { name string expect interface{} got interface{} assertion ComparisonAssertionFunc }{ {"implements", (*iface)(nil), t, Implements}, {"isType", (*testing.T)(nil), t, IsType}, {"equal", t, t, Equal}, {"equalValues", t, t, EqualValues}, {"exactly", t, t, Exactly}, {"notEqual", t, nil, NotEqual}, {"notContains", []int{1, 2, 3}, 4, NotContains}, {"subset", []int{1, 2, 3, 4}, []int{2, 3}, Subset}, {"notSubset", []int{1, 2, 3, 4}, []int{0, 3}, NotSubset}, {"elementsMatch", []byte("abc"), []byte("bac"), ElementsMatch}, {"regexp", "^t.*y$", "testify", Regexp}, {"notRegexp", "^t.*y$", "Testify", NotRegexp}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, tt.expect, tt.got) }) } } func ExampleValueAssertionFunc() { t := &testing.T{} // provided by test dumbParse := func(input string) interface{} { var x interface{} json.Unmarshal([]byte(input), &x) return x } tests := []struct { name string arg string assertion ValueAssertionFunc }{ {"true is not nil", "true", NotNil}, {"empty string is nil", "", Nil}, {"zero is not nil", "0", NotNil}, {"zero is zero", "0", Zero}, {"false is zero", "false", Zero}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, dumbParse(tt.arg)) }) } } func TestValueAssertionFunc(t *testing.T) { tests := []struct { name string value interface{} assertion ValueAssertionFunc }{ {"notNil", true, NotNil}, {"nil", nil, Nil}, {"empty", []int{}, Empty}, {"notEmpty", []int{1}, NotEmpty}, {"zero", false, Zero}, {"notZero", 42, NotZero}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, tt.value) }) } } func ExampleBoolAssertionFunc() { t := &testing.T{} // provided by test isOkay := func(x int) bool { return x >= 42 } tests := []struct { name string arg int assertion BoolAssertionFunc }{ {"-1 is bad", -1, False}, {"42 is good", 42, True}, {"41 is bad", 41, False}, {"45 is cool", 45, True}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, isOkay(tt.arg)) }) } } func TestBoolAssertionFunc(t *testing.T) { tests := []struct { name string value bool assertion BoolAssertionFunc }{ {"true", true, True}, {"false", false, False}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, tt.value) }) } } func ExampleErrorAssertionFunc() { t := &testing.T{} // provided by test dumbParseNum := func(input string, v interface{}) error { return json.Unmarshal([]byte(input), v) } tests := []struct { name string arg string assertion ErrorAssertionFunc }{ {"1.2 is number", "1.2", NoError}, {"1.2.3 not number", "1.2.3", Error}, {"true is not number", "true", Error}, {"3 is number", "3", NoError}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var x float64 tt.assertion(t, dumbParseNum(tt.arg, &x)) }) } } func TestErrorAssertionFunc(t *testing.T) { tests := []struct { name string err error assertion ErrorAssertionFunc }{ {"noError", nil, NoError}, {"error", errors.New("whoops"), Error}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, tt.err) }) } } ================================================ FILE: src/github.com/stretchr/testify/assert/doc.go ================================================ // Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. // // Example Usage // // The following is a complete example using assert in a standard test function: // import ( // "testing" // "github.com/stretchr/testify/assert" // ) // // func TestSomething(t *testing.T) { // // var a string = "Hello" // var b string = "Hello" // // assert.Equal(t, a, b, "The two words should be the same.") // // } // // if you assert many times, use the format below: // // import ( // "testing" // "github.com/stretchr/testify/assert" // ) // // func TestSomething(t *testing.T) { // assert := assert.New(t) // // var a string = "Hello" // var b string = "Hello" // // assert.Equal(a, b, "The two words should be the same.") // } // // Assertions // // Assertions allow you to easily write test code, and are global funcs in the `assert` package. // All assertion functions take, as the first argument, the `*testing.T` object provided by the // testing framework. This allows the assertion funcs to write the failings and other details to // the correct place. // // Every assertion function also takes an optional string message as the final argument, // allowing custom error messages to be appended to the message the assertion method outputs. package assert ================================================ FILE: src/github.com/stretchr/testify/assert/errors.go ================================================ package assert import ( "errors" ) // AnError is an error instance useful for testing. If the code does not care // about error specifics, and only needs to return the error for example, this // error should be used to make the test code more readable. var AnError = errors.New("assert.AnError general error for testing") ================================================ FILE: src/github.com/stretchr/testify/assert/forward_assertions.go ================================================ package assert // Assertions provides assertion methods around the // TestingT interface. type Assertions struct { t TestingT } // New makes a new Assertions object for the specified TestingT. func New(t TestingT) *Assertions { return &Assertions{ t: t, } } //go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_forward.go.tmpl -include-format-funcs ================================================ FILE: src/github.com/stretchr/testify/assert/forward_assertions_test.go ================================================ package assert import ( "errors" "regexp" "testing" "time" ) func TestImplementsWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) { t.Error("Implements method should return true: AssertionTesterConformingObject implements AssertionTesterInterface") } if assert.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) { t.Error("Implements method should return false: AssertionTesterNonConformingObject does not implements AssertionTesterInterface") } } func TestIsTypeWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) { t.Error("IsType should return true: AssertionTesterConformingObject is the same type as AssertionTesterConformingObject") } if assert.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) { t.Error("IsType should return false: AssertionTesterConformingObject is not the same type as AssertionTesterNonConformingObject") } } func TestEqualWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Equal("Hello World", "Hello World") { t.Error("Equal should return true") } if !assert.Equal(123, 123) { t.Error("Equal should return true") } if !assert.Equal(123.5, 123.5) { t.Error("Equal should return true") } if !assert.Equal([]byte("Hello World"), []byte("Hello World")) { t.Error("Equal should return true") } if !assert.Equal(nil, nil) { t.Error("Equal should return true") } } func TestEqualValuesWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.EqualValues(uint32(10), int32(10)) { t.Error("EqualValues should return true") } } func TestNotNilWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.NotNil(new(AssertionTesterConformingObject)) { t.Error("NotNil should return true: object is not nil") } if assert.NotNil(nil) { t.Error("NotNil should return false: object is nil") } } func TestNilWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Nil(nil) { t.Error("Nil should return true: object is nil") } if assert.Nil(new(AssertionTesterConformingObject)) { t.Error("Nil should return false: object is not nil") } } func TestTrueWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.True(true) { t.Error("True should return true") } if assert.True(false) { t.Error("True should return false") } } func TestFalseWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.False(false) { t.Error("False should return true") } if assert.False(true) { t.Error("False should return false") } } func TestExactlyWrapper(t *testing.T) { assert := New(new(testing.T)) a := float32(1) b := float64(1) c := float32(1) d := float32(2) if assert.Exactly(a, b) { t.Error("Exactly should return false") } if assert.Exactly(a, d) { t.Error("Exactly should return false") } if !assert.Exactly(a, c) { t.Error("Exactly should return true") } if assert.Exactly(nil, a) { t.Error("Exactly should return false") } if assert.Exactly(a, nil) { t.Error("Exactly should return false") } } func TestNotEqualWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.NotEqual("Hello World", "Hello World!") { t.Error("NotEqual should return true") } if !assert.NotEqual(123, 1234) { t.Error("NotEqual should return true") } if !assert.NotEqual(123.5, 123.55) { t.Error("NotEqual should return true") } if !assert.NotEqual([]byte("Hello World"), []byte("Hello World!")) { t.Error("NotEqual should return true") } if !assert.NotEqual(nil, new(AssertionTesterConformingObject)) { t.Error("NotEqual should return true") } } func TestContainsWrapper(t *testing.T) { assert := New(new(testing.T)) list := []string{"Foo", "Bar"} if !assert.Contains("Hello World", "Hello") { t.Error("Contains should return true: \"Hello World\" contains \"Hello\"") } if assert.Contains("Hello World", "Salut") { t.Error("Contains should return false: \"Hello World\" does not contain \"Salut\"") } if !assert.Contains(list, "Foo") { t.Error("Contains should return true: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") } if assert.Contains(list, "Salut") { t.Error("Contains should return false: \"[\"Foo\", \"Bar\"]\" does not contain \"Salut\"") } } func TestNotContainsWrapper(t *testing.T) { assert := New(new(testing.T)) list := []string{"Foo", "Bar"} if !assert.NotContains("Hello World", "Hello!") { t.Error("NotContains should return true: \"Hello World\" does not contain \"Hello!\"") } if assert.NotContains("Hello World", "Hello") { t.Error("NotContains should return false: \"Hello World\" contains \"Hello\"") } if !assert.NotContains(list, "Foo!") { t.Error("NotContains should return true: \"[\"Foo\", \"Bar\"]\" does not contain \"Foo!\"") } if assert.NotContains(list, "Foo") { t.Error("NotContains should return false: \"[\"Foo\", \"Bar\"]\" contains \"Foo\"") } } func TestConditionWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Condition(func() bool { return true }, "Truth") { t.Error("Condition should return true") } if assert.Condition(func() bool { return false }, "Lie") { t.Error("Condition should return false") } } func TestDidPanicWrapper(t *testing.T) { if funcDidPanic, _ := didPanic(func() { panic("Panic!") }); !funcDidPanic { t.Error("didPanic should return true") } if funcDidPanic, _ := didPanic(func() { }); funcDidPanic { t.Error("didPanic should return false") } } func TestPanicsWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.Panics(func() { panic("Panic!") }) { t.Error("Panics should return true") } if assert.Panics(func() { }) { t.Error("Panics should return false") } } func TestNotPanicsWrapper(t *testing.T) { assert := New(new(testing.T)) if !assert.NotPanics(func() { }) { t.Error("NotPanics should return true") } if assert.NotPanics(func() { panic("Panic!") }) { t.Error("NotPanics should return false") } } func TestNoErrorWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) // start with a nil error var err error assert.True(mockAssert.NoError(err), "NoError should return True for nil arg") // now set an error err = errors.New("Some error") assert.False(mockAssert.NoError(err), "NoError with error should return False") } func TestErrorWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) // start with a nil error var err error assert.False(mockAssert.Error(err), "Error should return False for nil arg") // now set an error err = errors.New("Some error") assert.True(mockAssert.Error(err), "Error with error should return True") } func TestEqualErrorWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) // start with a nil error var err error assert.False(mockAssert.EqualError(err, ""), "EqualError should return false for nil arg") // now set an error err = errors.New("some error") assert.False(mockAssert.EqualError(err, "Not some error"), "EqualError should return false for different error string") assert.True(mockAssert.EqualError(err, "some error"), "EqualError should return true") } func TestEmptyWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.True(mockAssert.Empty(""), "Empty string is empty") assert.True(mockAssert.Empty(nil), "Nil is empty") assert.True(mockAssert.Empty([]string{}), "Empty string array is empty") assert.True(mockAssert.Empty(0), "Zero int value is empty") assert.True(mockAssert.Empty(false), "False value is empty") assert.False(mockAssert.Empty("something"), "Non Empty string is not empty") assert.False(mockAssert.Empty(errors.New("something")), "Non nil object is not empty") assert.False(mockAssert.Empty([]string{"something"}), "Non empty string array is not empty") assert.False(mockAssert.Empty(1), "Non-zero int value is not empty") assert.False(mockAssert.Empty(true), "True value is not empty") } func TestNotEmptyWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.False(mockAssert.NotEmpty(""), "Empty string is empty") assert.False(mockAssert.NotEmpty(nil), "Nil is empty") assert.False(mockAssert.NotEmpty([]string{}), "Empty string array is empty") assert.False(mockAssert.NotEmpty(0), "Zero int value is empty") assert.False(mockAssert.NotEmpty(false), "False value is empty") assert.True(mockAssert.NotEmpty("something"), "Non Empty string is not empty") assert.True(mockAssert.NotEmpty(errors.New("something")), "Non nil object is not empty") assert.True(mockAssert.NotEmpty([]string{"something"}), "Non empty string array is not empty") assert.True(mockAssert.NotEmpty(1), "Non-zero int value is not empty") assert.True(mockAssert.NotEmpty(true), "True value is not empty") } func TestLenWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.False(mockAssert.Len(nil, 0), "nil does not have length") assert.False(mockAssert.Len(0, 0), "int does not have length") assert.False(mockAssert.Len(true, 0), "true does not have length") assert.False(mockAssert.Len(false, 0), "false does not have length") assert.False(mockAssert.Len('A', 0), "Rune does not have length") assert.False(mockAssert.Len(struct{}{}, 0), "Struct does not have length") ch := make(chan int, 5) ch <- 1 ch <- 2 ch <- 3 cases := []struct { v interface{} l int }{ {[]int{1, 2, 3}, 3}, {[...]int{1, 2, 3}, 3}, {"ABC", 3}, {map[int]int{1: 2, 2: 4, 3: 6}, 3}, {ch, 3}, {[]int{}, 0}, {map[int]int{}, 0}, {make(chan int), 0}, {[]int(nil), 0}, {map[int]int(nil), 0}, {(chan int)(nil), 0}, } for _, c := range cases { assert.True(mockAssert.Len(c.v, c.l), "%#v have %d items", c.v, c.l) } } func TestWithinDurationWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) a := time.Now() b := a.Add(10 * time.Second) assert.True(mockAssert.WithinDuration(a, b, 10*time.Second), "A 10s difference is within a 10s time difference") assert.True(mockAssert.WithinDuration(b, a, 10*time.Second), "A 10s difference is within a 10s time difference") assert.False(mockAssert.WithinDuration(a, b, 9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(b, a, 9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(a, b, -9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(b, a, -9*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(a, b, -11*time.Second), "A 10s difference is not within a 9s time difference") assert.False(mockAssert.WithinDuration(b, a, -11*time.Second), "A 10s difference is not within a 9s time difference") } func TestInDeltaWrapper(t *testing.T) { assert := New(new(testing.T)) True(t, assert.InDelta(1.001, 1, 0.01), "|1.001 - 1| <= 0.01") True(t, assert.InDelta(1, 1.001, 0.01), "|1 - 1.001| <= 0.01") True(t, assert.InDelta(1, 2, 1), "|1 - 2| <= 1") False(t, assert.InDelta(1, 2, 0.5), "Expected |1 - 2| <= 0.5 to fail") False(t, assert.InDelta(2, 1, 0.5), "Expected |2 - 1| <= 0.5 to fail") False(t, assert.InDelta("", nil, 1), "Expected non numerals to fail") cases := []struct { a, b interface{} delta float64 }{ {uint8(2), uint8(1), 1}, {uint16(2), uint16(1), 1}, {uint32(2), uint32(1), 1}, {uint64(2), uint64(1), 1}, {int(2), int(1), 1}, {int8(2), int8(1), 1}, {int16(2), int16(1), 1}, {int32(2), int32(1), 1}, {int64(2), int64(1), 1}, {float32(2), float32(1), 1}, {float64(2), float64(1), 1}, } for _, tc := range cases { True(t, assert.InDelta(tc.a, tc.b, tc.delta), "Expected |%V - %V| <= %v", tc.a, tc.b, tc.delta) } } func TestInEpsilonWrapper(t *testing.T) { assert := New(new(testing.T)) cases := []struct { a, b interface{} epsilon float64 }{ {uint8(2), uint16(2), .001}, {2.1, 2.2, 0.1}, {2.2, 2.1, 0.1}, {-2.1, -2.2, 0.1}, {-2.2, -2.1, 0.1}, {uint64(100), uint8(101), 0.01}, {0.1, -0.1, 2}, } for _, tc := range cases { True(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) } cases = []struct { a, b interface{} epsilon float64 }{ {uint8(2), int16(-2), .001}, {uint64(100), uint8(102), 0.01}, {2.1, 2.2, 0.001}, {2.2, 2.1, 0.001}, {2.1, -2.2, 1}, {2.1, "bla-bla", 0}, {0.1, -0.1, 1.99}, } for _, tc := range cases { False(t, assert.InEpsilon(tc.a, tc.b, tc.epsilon, "Expected %V and %V to have a relative difference of %v", tc.a, tc.b, tc.epsilon)) } } func TestRegexpWrapper(t *testing.T) { assert := New(new(testing.T)) cases := []struct { rx, str string }{ {"^start", "start of the line"}, {"end$", "in the end"}, {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12.34"}, } for _, tc := range cases { True(t, assert.Regexp(tc.rx, tc.str)) True(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) False(t, assert.NotRegexp(tc.rx, tc.str)) False(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) } cases = []struct { rx, str string }{ {"^asdfastart", "Not the start of the line"}, {"end$", "in the end."}, {"[0-9]{3}[.-]?[0-9]{2}[.-]?[0-9]{2}", "My phone number is 650.12a.34"}, } for _, tc := range cases { False(t, assert.Regexp(tc.rx, tc.str), "Expected \"%s\" to not match \"%s\"", tc.rx, tc.str) False(t, assert.Regexp(regexp.MustCompile(tc.rx), tc.str)) True(t, assert.NotRegexp(tc.rx, tc.str)) True(t, assert.NotRegexp(regexp.MustCompile(tc.rx), tc.str)) } } func TestZeroWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) for _, test := range zeros { assert.True(mockAssert.Zero(test), "Zero should return true for %v", test) } for _, test := range nonZeros { assert.False(mockAssert.Zero(test), "Zero should return false for %v", test) } } func TestNotZeroWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) for _, test := range zeros { assert.False(mockAssert.NotZero(test), "Zero should return true for %v", test) } for _, test := range nonZeros { assert.True(mockAssert.NotZero(test), "Zero should return false for %v", test) } } func TestJSONEqWrapper_EqualSONString(t *testing.T) { assert := New(new(testing.T)) if !assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) { t.Error("JSONEq should return true") } } func TestJSONEqWrapper_EquivalentButNotEqual(t *testing.T) { assert := New(new(testing.T)) if !assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) { t.Error("JSONEq should return true") } } func TestJSONEqWrapper_HashOfArraysAndHashes(t *testing.T) { assert := New(new(testing.T)) if !assert.JSONEq("{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") { t.Error("JSONEq should return true") } } func TestJSONEqWrapper_Array(t *testing.T) { assert := New(new(testing.T)) if !assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) { t.Error("JSONEq should return true") } } func TestJSONEqWrapper_HashAndArrayNotEquivalent(t *testing.T) { assert := New(new(testing.T)) if assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) { t.Error("JSONEq should return false") } } func TestJSONEqWrapper_HashesNotEquivalent(t *testing.T) { assert := New(new(testing.T)) if assert.JSONEq(`{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) { t.Error("JSONEq should return false") } } func TestJSONEqWrapper_ActualIsNotJSON(t *testing.T) { assert := New(new(testing.T)) if assert.JSONEq(`{"foo": "bar"}`, "Not JSON") { t.Error("JSONEq should return false") } } func TestJSONEqWrapper_ExpectedIsNotJSON(t *testing.T) { assert := New(new(testing.T)) if assert.JSONEq("Not JSON", `{"foo": "bar", "hello": "world"}`) { t.Error("JSONEq should return false") } } func TestJSONEqWrapper_ExpectedAndActualNotJSON(t *testing.T) { assert := New(new(testing.T)) if assert.JSONEq("Not JSON", "Not JSON") { t.Error("JSONEq should return false") } } func TestJSONEqWrapper_ArraysOfDifferentOrder(t *testing.T) { assert := New(new(testing.T)) if assert.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) { t.Error("JSONEq should return false") } } ================================================ FILE: src/github.com/stretchr/testify/assert/http_assertions.go ================================================ package assert import ( "fmt" "net/http" "net/http/httptest" "net/url" "strings" ) // httpCode is a helper that returns HTTP code of the response. It returns -1 and // an error if building a new request fails. func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (int, error) { w := httptest.NewRecorder() req, err := http.NewRequest(method, url, nil) if err != nil { return -1, err } req.URL.RawQuery = values.Encode() handler(w, req) return w.Code, nil } // HTTPSuccess asserts that a specified handler returns a success status code. // // assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) return false } isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent if !isSuccessCode { Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code)) } return isSuccessCode } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) return false } isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect if !isRedirectCode { Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code)) } return isRedirectCode } // HTTPError asserts that a specified handler returns an error status code. // // assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } code, err := httpCode(handler, method, url, values) if err != nil { Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) return false } isErrorCode := code >= http.StatusBadRequest if !isErrorCode { Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code)) } return isErrorCode } // HTTPBody is a helper that returns HTTP body of the response. It returns // empty string if building a new request fails. func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { w := httptest.NewRecorder() req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) if err != nil { return "" } handler(w, req) return w.Body.String() } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } body := HTTPBody(handler, method, url, values) contains := strings.Contains(body, fmt.Sprint(str)) if !contains { Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) } return contains } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } body := HTTPBody(handler, method, url, values) contains := strings.Contains(body, fmt.Sprint(str)) if contains { Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) } return !contains } ================================================ FILE: src/github.com/stretchr/testify/assert/http_assertions_test.go ================================================ package assert import ( "fmt" "net/http" "net/url" "testing" ) func httpOK(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } func httpRedirect(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTemporaryRedirect) } func httpError(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) } func TestHTTPSuccess(t *testing.T) { assert := New(t) mockT1 := new(testing.T) assert.Equal(HTTPSuccess(mockT1, httpOK, "GET", "/", nil), true) assert.False(mockT1.Failed()) mockT2 := new(testing.T) assert.Equal(HTTPSuccess(mockT2, httpRedirect, "GET", "/", nil), false) assert.True(mockT2.Failed()) mockT3 := new(testing.T) assert.Equal(HTTPSuccess(mockT3, httpError, "GET", "/", nil), false) assert.True(mockT3.Failed()) } func TestHTTPRedirect(t *testing.T) { assert := New(t) mockT1 := new(testing.T) assert.Equal(HTTPRedirect(mockT1, httpOK, "GET", "/", nil), false) assert.True(mockT1.Failed()) mockT2 := new(testing.T) assert.Equal(HTTPRedirect(mockT2, httpRedirect, "GET", "/", nil), true) assert.False(mockT2.Failed()) mockT3 := new(testing.T) assert.Equal(HTTPRedirect(mockT3, httpError, "GET", "/", nil), false) assert.True(mockT3.Failed()) } func TestHTTPError(t *testing.T) { assert := New(t) mockT1 := new(testing.T) assert.Equal(HTTPError(mockT1, httpOK, "GET", "/", nil), false) assert.True(mockT1.Failed()) mockT2 := new(testing.T) assert.Equal(HTTPError(mockT2, httpRedirect, "GET", "/", nil), false) assert.True(mockT2.Failed()) mockT3 := new(testing.T) assert.Equal(HTTPError(mockT3, httpError, "GET", "/", nil), true) assert.False(mockT3.Failed()) } func TestHTTPStatusesWrapper(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true) assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true) assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false) assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true) } func httpHelloName(w http.ResponseWriter, r *http.Request) { name := r.FormValue("name") w.Write([]byte(fmt.Sprintf("Hello, %s!", name))) } func TestHTTPRequestWithNoParams(t *testing.T) { var got *http.Request handler := func(w http.ResponseWriter, r *http.Request) { got = r w.WriteHeader(http.StatusOK) } True(t, HTTPSuccess(t, handler, "GET", "/url", nil)) Empty(t, got.URL.Query()) Equal(t, "/url", got.URL.RequestURI()) } func TestHTTPRequestWithParams(t *testing.T) { var got *http.Request handler := func(w http.ResponseWriter, r *http.Request) { got = r w.WriteHeader(http.StatusOK) } params := url.Values{} params.Add("id", "12345") True(t, HTTPSuccess(t, handler, "GET", "/url", params)) Equal(t, url.Values{"id": []string{"12345"}}, got.URL.Query()) Equal(t, "/url?id=12345", got.URL.String()) Equal(t, "/url?id=12345", got.URL.RequestURI()) } func TestHttpBody(t *testing.T) { assert := New(t) mockT := new(testing.T) assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) } func TestHttpBodyWrappers(t *testing.T) { assert := New(t) mockAssert := New(new(testing.T)) assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) } ================================================ FILE: src/github.com/stretchr/testify/doc.go ================================================ // Package testify is a set of packages that provide many tools for testifying that your code will behave as you intend. // // testify contains the following packages: // // The assert package provides a comprehensive set of assertion functions that tie in to the Go testing system. // // The http package contains tools to make it easier to test http activity using the Go testing system. // // The mock package provides a system by which it is possible to mock your objects and verify calls are happening as expected. // // The suite package provides a basic structure for using structs as testing suites, and methods on those structs as tests. It includes setup/teardown functionality in the way of interfaces. package testify // blank imports help docs. import ( // assert package _ "github.com/stretchr/testify/assert" // http package _ "github.com/stretchr/testify/http" // mock package _ "github.com/stretchr/testify/mock" ) ================================================ FILE: src/github.com/stretchr/testify/http/doc.go ================================================ // Package http DEPRECATED USE net/http/httptest package http ================================================ FILE: src/github.com/stretchr/testify/http/test_response_writer.go ================================================ package http import ( "net/http" ) // TestResponseWriter DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. type TestResponseWriter struct { // StatusCode is the last int written by the call to WriteHeader(int) StatusCode int // Output is a string containing the written bytes using the Write([]byte) func. Output string // header is the internal storage of the http.Header object header http.Header } // Header DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. func (rw *TestResponseWriter) Header() http.Header { if rw.header == nil { rw.header = make(http.Header) } return rw.header } // Write DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. func (rw *TestResponseWriter) Write(bytes []byte) (int, error) { // assume 200 success if no header has been set if rw.StatusCode == 0 { rw.WriteHeader(200) } // add these bytes to the output string rw.Output = rw.Output + string(bytes) // return normal values return 0, nil } // WriteHeader DEPRECATED: We recommend you use http://golang.org/pkg/net/http/httptest instead. func (rw *TestResponseWriter) WriteHeader(i int) { rw.StatusCode = i } ================================================ FILE: src/github.com/stretchr/testify/http/test_round_tripper.go ================================================ package http import ( "github.com/stretchr/testify/mock" "net/http" ) // TestRoundTripper DEPRECATED USE net/http/httptest type TestRoundTripper struct { mock.Mock } // RoundTrip DEPRECATED USE net/http/httptest func (t *TestRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { args := t.Called(req) return args.Get(0).(*http.Response), args.Error(1) } ================================================ FILE: src/github.com/stretchr/testify/mock/doc.go ================================================ // Package mock provides a system by which it is possible to mock your objects // and verify calls are happening as expected. // // Example Usage // // The mock package provides an object, Mock, that tracks activity on another object. It is usually // embedded into a test object as shown below: // // type MyTestObject struct { // // add a Mock object instance // mock.Mock // // // other fields go here as normal // } // // When implementing the methods of an interface, you wire your functions up // to call the Mock.Called(args...) method, and return the appropriate values. // // For example, to mock a method that saves the name and age of a person and returns // the year of their birth or an error, you might write this: // // func (o *MyTestObject) SavePersonDetails(firstname, lastname string, age int) (int, error) { // args := o.Called(firstname, lastname, age) // return args.Int(0), args.Error(1) // } // // The Int, Error and Bool methods are examples of strongly typed getters that take the argument // index position. Given this argument list: // // (12, true, "Something") // // You could read them out strongly typed like this: // // args.Int(0) // args.Bool(1) // args.String(2) // // For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion: // // return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine) // // This may cause a panic if the object you are getting is nil (the type assertion will fail), in those // cases you should check for nil first. package mock ================================================ FILE: src/github.com/stretchr/testify/mock/mock.go ================================================ package mock import ( "errors" "fmt" "reflect" "regexp" "runtime" "strings" "sync" "time" "github.com/davecgh/go-spew/spew" "github.com/pmezard/go-difflib/difflib" "github.com/stretchr/objx" "github.com/stretchr/testify/assert" ) // TestingT is an interface wrapper around *testing.T type TestingT interface { Logf(format string, args ...interface{}) Errorf(format string, args ...interface{}) FailNow() } /* Call */ // Call represents a method call and is used for setting expectations, // as well as recording activity. type Call struct { Parent *Mock // The name of the method that was or will be called. Method string // Holds the arguments of the method. Arguments Arguments // Holds the arguments that should be returned when // this method is called. ReturnArguments Arguments // Holds the caller info for the On() call callerInfo []string // The number of times to return the return arguments when setting // expectations. 0 means to always return the value. Repeatability int // Amount of times this call has been called totalCalls int // Call to this method can be optional optional bool // Holds a channel that will be used to block the Return until it either // receives a message or is closed. nil means it returns immediately. WaitFor <-chan time.Time waitTime time.Duration // Holds a handler used to manipulate arguments content that are passed by // reference. It's useful when mocking methods such as unmarshalers or // decoders. RunFn func(Arguments) } func newCall(parent *Mock, methodName string, callerInfo []string, methodArguments ...interface{}) *Call { return &Call{ Parent: parent, Method: methodName, Arguments: methodArguments, ReturnArguments: make([]interface{}, 0), callerInfo: callerInfo, Repeatability: 0, WaitFor: nil, RunFn: nil, } } func (c *Call) lock() { c.Parent.mutex.Lock() } func (c *Call) unlock() { c.Parent.mutex.Unlock() } // Return specifies the return arguments for the expectation. // // Mock.On("DoSomething").Return(errors.New("failed")) func (c *Call) Return(returnArguments ...interface{}) *Call { c.lock() defer c.unlock() c.ReturnArguments = returnArguments return c } // Once indicates that that the mock should only return the value once. // // Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Once() func (c *Call) Once() *Call { return c.Times(1) } // Twice indicates that that the mock should only return the value twice. // // Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Twice() func (c *Call) Twice() *Call { return c.Times(2) } // Times indicates that that the mock should only return the indicated number // of times. // // Mock.On("MyMethod", arg1, arg2).Return(returnArg1, returnArg2).Times(5) func (c *Call) Times(i int) *Call { c.lock() defer c.unlock() c.Repeatability = i return c } // WaitUntil sets the channel that will block the mock's return until its closed // or a message is received. // // Mock.On("MyMethod", arg1, arg2).WaitUntil(time.After(time.Second)) func (c *Call) WaitUntil(w <-chan time.Time) *Call { c.lock() defer c.unlock() c.WaitFor = w return c } // After sets how long to block until the call returns // // Mock.On("MyMethod", arg1, arg2).After(time.Second) func (c *Call) After(d time.Duration) *Call { c.lock() defer c.unlock() c.waitTime = d return c } // Run sets a handler to be called before returning. It can be used when // mocking a method such as unmarshalers that takes a pointer to a struct and // sets properties in such struct // // Mock.On("Unmarshal", AnythingOfType("*map[string]interface{}").Return().Run(func(args Arguments) { // arg := args.Get(0).(*map[string]interface{}) // arg["foo"] = "bar" // }) func (c *Call) Run(fn func(args Arguments)) *Call { c.lock() defer c.unlock() c.RunFn = fn return c } // Maybe allows the method call to be optional. Not calling an optional method // will not cause an error while asserting expectations func (c *Call) Maybe() *Call { c.lock() defer c.unlock() c.optional = true return c } // On chains a new expectation description onto the mocked interface. This // allows syntax like. // // Mock. // On("MyMethod", 1).Return(nil). // On("MyOtherMethod", 'a', 'b', 'c').Return(errors.New("Some Error")) func (c *Call) On(methodName string, arguments ...interface{}) *Call { return c.Parent.On(methodName, arguments...) } // Mock is the workhorse used to track activity on another object. // For an example of its usage, refer to the "Example Usage" section at the top // of this document. type Mock struct { // Represents the calls that are expected of // an object. ExpectedCalls []*Call // Holds the calls that were made to this mocked object. Calls []Call // test is An optional variable that holds the test struct, to be used when an // invalid mock call was made. test TestingT // TestData holds any data that might be useful for testing. Testify ignores // this data completely allowing you to do whatever you like with it. testData objx.Map mutex sync.Mutex } // TestData holds any data that might be useful for testing. Testify ignores // this data completely allowing you to do whatever you like with it. func (m *Mock) TestData() objx.Map { if m.testData == nil { m.testData = make(objx.Map) } return m.testData } /* Setting expectations */ // Test sets the test struct variable of the mock object func (m *Mock) Test(t TestingT) { m.mutex.Lock() defer m.mutex.Unlock() m.test = t } // fail fails the current test with the given formatted format and args. // In case that a test was defined, it uses the test APIs for failing a test, // otherwise it uses panic. func (m *Mock) fail(format string, args ...interface{}) { m.mutex.Lock() defer m.mutex.Unlock() if m.test == nil { panic(fmt.Sprintf(format, args...)) } m.test.Errorf(format, args...) m.test.FailNow() } // On starts a description of an expectation of the specified method // being called. // // Mock.On("MyMethod", arg1, arg2) func (m *Mock) On(methodName string, arguments ...interface{}) *Call { for _, arg := range arguments { if v := reflect.ValueOf(arg); v.Kind() == reflect.Func { panic(fmt.Sprintf("cannot use Func in expectations. Use mock.AnythingOfType(\"%T\")", arg)) } } m.mutex.Lock() defer m.mutex.Unlock() c := newCall(m, methodName, assert.CallerInfo(), arguments...) m.ExpectedCalls = append(m.ExpectedCalls, c) return c } // /* // Recording and responding to activity // */ func (m *Mock) findExpectedCall(method string, arguments ...interface{}) (int, *Call) { for i, call := range m.ExpectedCalls { if call.Method == method && call.Repeatability > -1 { _, diffCount := call.Arguments.Diff(arguments) if diffCount == 0 { return i, call } } } return -1, nil } func (m *Mock) findClosestCall(method string, arguments ...interface{}) (*Call, string) { var diffCount int var closestCall *Call var err string for _, call := range m.expectedCalls() { if call.Method == method { errInfo, tempDiffCount := call.Arguments.Diff(arguments) if tempDiffCount < diffCount || diffCount == 0 { diffCount = tempDiffCount closestCall = call err = errInfo } } } return closestCall, err } func callString(method string, arguments Arguments, includeArgumentValues bool) string { var argValsString string if includeArgumentValues { var argVals []string for argIndex, arg := range arguments { argVals = append(argVals, fmt.Sprintf("%d: %#v", argIndex, arg)) } argValsString = fmt.Sprintf("\n\t\t%s", strings.Join(argVals, "\n\t\t")) } return fmt.Sprintf("%s(%s)%s", method, arguments.String(), argValsString) } // Called tells the mock object that a method has been called, and gets an array // of arguments to return. Panics if the call is unexpected (i.e. not preceded by // appropriate .On .Return() calls) // If Call.WaitFor is set, blocks until the channel is closed or receives a message. func (m *Mock) Called(arguments ...interface{}) Arguments { // get the calling function's name pc, _, _, ok := runtime.Caller(1) if !ok { panic("Couldn't get the caller information") } functionPath := runtime.FuncForPC(pc).Name() //Next four lines are required to use GCCGO function naming conventions. //For Ex: github_com_docker_libkv_store_mock.WatchTree.pN39_github_com_docker_libkv_store_mock.Mock //uses interface information unlike golang github.com/docker/libkv/store/mock.(*Mock).WatchTree //With GCCGO we need to remove interface information starting from pN
. re := regexp.MustCompile("\\.pN\\d+_") if re.MatchString(functionPath) { functionPath = re.Split(functionPath, -1)[0] } parts := strings.Split(functionPath, ".") functionName := parts[len(parts)-1] return m.MethodCalled(functionName, arguments...) } // MethodCalled tells the mock object that the given method has been called, and gets // an array of arguments to return. Panics if the call is unexpected (i.e. not preceded // by appropriate .On .Return() calls) // If Call.WaitFor is set, blocks until the channel is closed or receives a message. func (m *Mock) MethodCalled(methodName string, arguments ...interface{}) Arguments { m.mutex.Lock() //TODO: could combine expected and closes in single loop found, call := m.findExpectedCall(methodName, arguments...) if found < 0 { // we have to fail here - because we don't know what to do // as the return arguments. This is because: // // a) this is a totally unexpected call to this method, // b) the arguments are not what was expected, or // c) the developer has forgotten to add an accompanying On...Return pair. closestCall, mismatch := m.findClosestCall(methodName, arguments...) m.mutex.Unlock() if closestCall != nil { m.fail("\n\nmock: Unexpected Method Call\n-----------------------------\n\n%s\n\nThe closest call I have is: \n\n%s\n\n%s\nDiff: %s", callString(methodName, arguments, true), callString(methodName, closestCall.Arguments, true), diffArguments(closestCall.Arguments, arguments), strings.TrimSpace(mismatch), ) } else { m.fail("\nassert: mock: I don't know what to return because the method call was unexpected.\n\tEither do Mock.On(\"%s\").Return(...) first, or remove the %s() call.\n\tThis method was unexpected:\n\t\t%s\n\tat: %s", methodName, methodName, callString(methodName, arguments, true), assert.CallerInfo()) } } if call.Repeatability == 1 { call.Repeatability = -1 } else if call.Repeatability > 1 { call.Repeatability-- } call.totalCalls++ // add the call m.Calls = append(m.Calls, *newCall(m, methodName, assert.CallerInfo(), arguments...)) m.mutex.Unlock() // block if specified if call.WaitFor != nil { <-call.WaitFor } else { time.Sleep(call.waitTime) } m.mutex.Lock() runFn := call.RunFn m.mutex.Unlock() if runFn != nil { runFn(arguments) } m.mutex.Lock() returnArgs := call.ReturnArguments m.mutex.Unlock() return returnArgs } /* Assertions */ type assertExpectationser interface { AssertExpectations(TestingT) bool } // AssertExpectationsForObjects asserts that everything specified with On and Return // of the specified objects was in fact called as expected. // // Calls may have occurred in any order. func AssertExpectationsForObjects(t TestingT, testObjects ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } for _, obj := range testObjects { if m, ok := obj.(Mock); ok { t.Logf("Deprecated mock.AssertExpectationsForObjects(myMock.Mock) use mock.AssertExpectationsForObjects(myMock)") obj = &m } m := obj.(assertExpectationser) if !m.AssertExpectations(t) { t.Logf("Expectations didn't match for Mock: %+v", reflect.TypeOf(m)) return false } } return true } // AssertExpectations asserts that everything specified with On and Return was // in fact called as expected. Calls may have occurred in any order. func (m *Mock) AssertExpectations(t TestingT) bool { if h, ok := t.(tHelper); ok { h.Helper() } m.mutex.Lock() defer m.mutex.Unlock() var somethingMissing bool var failedExpectations int // iterate through each expectation expectedCalls := m.expectedCalls() for _, expectedCall := range expectedCalls { if !expectedCall.optional && !m.methodWasCalled(expectedCall.Method, expectedCall.Arguments) && expectedCall.totalCalls == 0 { somethingMissing = true failedExpectations++ t.Logf("FAIL:\t%s(%s)\n\t\tat: %s", expectedCall.Method, expectedCall.Arguments.String(), expectedCall.callerInfo) } else { if expectedCall.Repeatability > 0 { somethingMissing = true failedExpectations++ t.Logf("FAIL:\t%s(%s)\n\t\tat: %s", expectedCall.Method, expectedCall.Arguments.String(), expectedCall.callerInfo) } else { t.Logf("PASS:\t%s(%s)", expectedCall.Method, expectedCall.Arguments.String()) } } } if somethingMissing { t.Errorf("FAIL: %d out of %d expectation(s) were met.\n\tThe code you are testing needs to make %d more call(s).\n\tat: %s", len(expectedCalls)-failedExpectations, len(expectedCalls), failedExpectations, assert.CallerInfo()) } return !somethingMissing } // AssertNumberOfCalls asserts that the method was called expectedCalls times. func (m *Mock) AssertNumberOfCalls(t TestingT, methodName string, expectedCalls int) bool { if h, ok := t.(tHelper); ok { h.Helper() } m.mutex.Lock() defer m.mutex.Unlock() var actualCalls int for _, call := range m.calls() { if call.Method == methodName { actualCalls++ } } return assert.Equal(t, expectedCalls, actualCalls, fmt.Sprintf("Expected number of calls (%d) does not match the actual number of calls (%d).", expectedCalls, actualCalls)) } // AssertCalled asserts that the method was called. // It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. func (m *Mock) AssertCalled(t TestingT, methodName string, arguments ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } m.mutex.Lock() defer m.mutex.Unlock() if !m.methodWasCalled(methodName, arguments) { var calledWithArgs []string for _, call := range m.calls() { calledWithArgs = append(calledWithArgs, fmt.Sprintf("%v", call.Arguments)) } if len(calledWithArgs) == 0 { return assert.Fail(t, "Should have called with given arguments", fmt.Sprintf("Expected %q to have been called with:\n%v\nbut no actual calls happened", methodName, arguments)) } return assert.Fail(t, "Should have called with given arguments", fmt.Sprintf("Expected %q to have been called with:\n%v\nbut actual calls were:\n %v", methodName, arguments, strings.Join(calledWithArgs, "\n"))) } return true } // AssertNotCalled asserts that the method was not called. // It can produce a false result when an argument is a pointer type and the underlying value changed after calling the mocked method. func (m *Mock) AssertNotCalled(t TestingT, methodName string, arguments ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } m.mutex.Lock() defer m.mutex.Unlock() if m.methodWasCalled(methodName, arguments) { return assert.Fail(t, "Should not have called with given arguments", fmt.Sprintf("Expected %q to not have been called with:\n%v\nbut actually it was.", methodName, arguments)) } return true } func (m *Mock) methodWasCalled(methodName string, expected []interface{}) bool { for _, call := range m.calls() { if call.Method == methodName { _, differences := Arguments(expected).Diff(call.Arguments) if differences == 0 { // found the expected call return true } } } // we didn't find the expected call return false } func (m *Mock) expectedCalls() []*Call { return append([]*Call{}, m.ExpectedCalls...) } func (m *Mock) calls() []Call { return append([]Call{}, m.Calls...) } /* Arguments */ // Arguments holds an array of method arguments or return values. type Arguments []interface{} const ( // Anything is used in Diff and Assert when the argument being tested // shouldn't be taken into consideration. Anything = "mock.Anything" ) // AnythingOfTypeArgument is a string that contains the type of an argument // for use when type checking. Used in Diff and Assert. type AnythingOfTypeArgument string // AnythingOfType returns an AnythingOfTypeArgument object containing the // name of the type to check for. Used in Diff and Assert. // // For example: // Assert(t, AnythingOfType("string"), AnythingOfType("int")) func AnythingOfType(t string) AnythingOfTypeArgument { return AnythingOfTypeArgument(t) } // argumentMatcher performs custom argument matching, returning whether or // not the argument is matched by the expectation fixture function. type argumentMatcher struct { // fn is a function which accepts one argument, and returns a bool. fn reflect.Value } func (f argumentMatcher) Matches(argument interface{}) bool { expectType := f.fn.Type().In(0) expectTypeNilSupported := false switch expectType.Kind() { case reflect.Interface, reflect.Chan, reflect.Func, reflect.Map, reflect.Slice, reflect.Ptr: expectTypeNilSupported = true } argType := reflect.TypeOf(argument) var arg reflect.Value if argType == nil { arg = reflect.New(expectType).Elem() } else { arg = reflect.ValueOf(argument) } if argType == nil && !expectTypeNilSupported { panic(errors.New("attempting to call matcher with nil for non-nil expected type")) } if argType == nil || argType.AssignableTo(expectType) { result := f.fn.Call([]reflect.Value{arg}) return result[0].Bool() } return false } func (f argumentMatcher) String() string { return fmt.Sprintf("func(%s) bool", f.fn.Type().In(0).Name()) } // MatchedBy can be used to match a mock call based on only certain properties // from a complex struct or some calculation. It takes a function that will be // evaluated with the called argument and will return true when there's a match // and false otherwise. // // Example: // m.On("Do", MatchedBy(func(req *http.Request) bool { return req.Host == "example.com" })) // // |fn|, must be a function accepting a single argument (of the expected type) // which returns a bool. If |fn| doesn't match the required signature, // MatchedBy() panics. func MatchedBy(fn interface{}) argumentMatcher { fnType := reflect.TypeOf(fn) if fnType.Kind() != reflect.Func { panic(fmt.Sprintf("assert: arguments: %s is not a func", fn)) } if fnType.NumIn() != 1 { panic(fmt.Sprintf("assert: arguments: %s does not take exactly one argument", fn)) } if fnType.NumOut() != 1 || fnType.Out(0).Kind() != reflect.Bool { panic(fmt.Sprintf("assert: arguments: %s does not return a bool", fn)) } return argumentMatcher{fn: reflect.ValueOf(fn)} } // Get Returns the argument at the specified index. func (args Arguments) Get(index int) interface{} { if index+1 > len(args) { panic(fmt.Sprintf("assert: arguments: Cannot call Get(%d) because there are %d argument(s).", index, len(args))) } return args[index] } // Is gets whether the objects match the arguments specified. func (args Arguments) Is(objects ...interface{}) bool { for i, obj := range args { if obj != objects[i] { return false } } return true } // Diff gets a string describing the differences between the arguments // and the specified objects. // // Returns the diff string and number of differences found. func (args Arguments) Diff(objects []interface{}) (string, int) { //TODO: could return string as error and nil for No difference var output = "\n" var differences int var maxArgCount = len(args) if len(objects) > maxArgCount { maxArgCount = len(objects) } for i := 0; i < maxArgCount; i++ { var actual, expected interface{} if len(objects) <= i { actual = "(Missing)" } else { actual = objects[i] } if len(args) <= i { expected = "(Missing)" } else { expected = args[i] } if matcher, ok := expected.(argumentMatcher); ok { if matcher.Matches(actual) { output = fmt.Sprintf("%s\t%d: PASS: %s matched by %s\n", output, i, actual, matcher) } else { differences++ output = fmt.Sprintf("%s\t%d: PASS: %s not matched by %s\n", output, i, actual, matcher) } } else if reflect.TypeOf(expected) == reflect.TypeOf((*AnythingOfTypeArgument)(nil)).Elem() { // type checking if reflect.TypeOf(actual).Name() != string(expected.(AnythingOfTypeArgument)) && reflect.TypeOf(actual).String() != string(expected.(AnythingOfTypeArgument)) { // not match differences++ output = fmt.Sprintf("%s\t%d: FAIL: type %s != type %s - %s\n", output, i, expected, reflect.TypeOf(actual).Name(), actual) } } else { // normal checking if assert.ObjectsAreEqual(expected, Anything) || assert.ObjectsAreEqual(actual, Anything) || assert.ObjectsAreEqual(actual, expected) { // match output = fmt.Sprintf("%s\t%d: PASS: %s == %s\n", output, i, actual, expected) } else { // not match differences++ output = fmt.Sprintf("%s\t%d: FAIL: %s != %s\n", output, i, actual, expected) } } } if differences == 0 { return "No differences.", differences } return output, differences } // Assert compares the arguments with the specified objects and fails if // they do not exactly match. func (args Arguments) Assert(t TestingT, objects ...interface{}) bool { if h, ok := t.(tHelper); ok { h.Helper() } // get the differences diff, diffCount := args.Diff(objects) if diffCount == 0 { return true } // there are differences... report them... t.Logf(diff) t.Errorf("%sArguments do not match.", assert.CallerInfo()) return false } // String gets the argument at the specified index. Panics if there is no argument, or // if the argument is of the wrong type. // // If no index is provided, String() returns a complete string representation // of the arguments. func (args Arguments) String(indexOrNil ...int) string { if len(indexOrNil) == 0 { // normal String() method - return a string representation of the args var argsStr []string for _, arg := range args { argsStr = append(argsStr, fmt.Sprintf("%s", reflect.TypeOf(arg))) } return strings.Join(argsStr, ",") } else if len(indexOrNil) == 1 { // Index has been specified - get the argument at that index var index = indexOrNil[0] var s string var ok bool if s, ok = args.Get(index).(string); !ok { panic(fmt.Sprintf("assert: arguments: String(%d) failed because object wasn't correct type: %s", index, args.Get(index))) } return s } panic(fmt.Sprintf("assert: arguments: Wrong number of arguments passed to String. Must be 0 or 1, not %d", len(indexOrNil))) } // Int gets the argument at the specified index. Panics if there is no argument, or // if the argument is of the wrong type. func (args Arguments) Int(index int) int { var s int var ok bool if s, ok = args.Get(index).(int); !ok { panic(fmt.Sprintf("assert: arguments: Int(%d) failed because object wasn't correct type: %v", index, args.Get(index))) } return s } // Error gets the argument at the specified index. Panics if there is no argument, or // if the argument is of the wrong type. func (args Arguments) Error(index int) error { obj := args.Get(index) var s error var ok bool if obj == nil { return nil } if s, ok = obj.(error); !ok { panic(fmt.Sprintf("assert: arguments: Error(%d) failed because object wasn't correct type: %v", index, args.Get(index))) } return s } // Bool gets the argument at the specified index. Panics if there is no argument, or // if the argument is of the wrong type. func (args Arguments) Bool(index int) bool { var s bool var ok bool if s, ok = args.Get(index).(bool); !ok { panic(fmt.Sprintf("assert: arguments: Bool(%d) failed because object wasn't correct type: %v", index, args.Get(index))) } return s } func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { t := reflect.TypeOf(v) k := t.Kind() if k == reflect.Ptr { t = t.Elem() k = t.Kind() } return t, k } func diffArguments(expected Arguments, actual Arguments) string { if len(expected) != len(actual) { return fmt.Sprintf("Provided %v arguments, mocked for %v arguments", len(expected), len(actual)) } for x := range expected { if diffString := diff(expected[x], actual[x]); diffString != "" { return fmt.Sprintf("Difference found in argument %v:\n\n%s", x, diffString) } } return "" } // diff returns a diff of both values as long as both are of the same type and // are a struct, map, slice or array. Otherwise it returns an empty string. func diff(expected interface{}, actual interface{}) string { if expected == nil || actual == nil { return "" } et, ek := typeAndKind(expected) at, _ := typeAndKind(actual) if et != at { return "" } if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { return "" } e := spewConfig.Sdump(expected) a := spewConfig.Sdump(actual) diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ A: difflib.SplitLines(e), B: difflib.SplitLines(a), FromFile: "Expected", FromDate: "", ToFile: "Actual", ToDate: "", Context: 1, }) return diff } var spewConfig = spew.ConfigState{ Indent: " ", DisablePointerAddresses: true, DisableCapacities: true, SortKeys: true, } type tHelper interface { Helper() } ================================================ FILE: src/github.com/stretchr/testify/mock/mock_test.go ================================================ package mock import ( "errors" "fmt" "regexp" "runtime" "sync" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) /* Test objects */ // ExampleInterface represents an example interface. type ExampleInterface interface { TheExampleMethod(a, b, c int) (int, error) } // TestExampleImplementation is a test implementation of ExampleInterface type TestExampleImplementation struct { Mock } func (i *TestExampleImplementation) TheExampleMethod(a, b, c int) (int, error) { args := i.Called(a, b, c) return args.Int(0), errors.New("Whoops") } func (i *TestExampleImplementation) TheExampleMethod2(yesorno bool) { i.Called(yesorno) } type ExampleType struct { ran bool } func (i *TestExampleImplementation) TheExampleMethod3(et *ExampleType) error { args := i.Called(et) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethod4(v ExampleInterface) error { args := i.Called(v) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethod5(ch chan struct{}) error { args := i.Called(ch) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethod6(m map[string]bool) error { args := i.Called(m) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethod7(slice []bool) error { args := i.Called(slice) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethodFunc(fn func(string) error) error { args := i.Called(fn) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethodVariadic(a ...int) error { args := i.Called(a) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethodVariadicInterface(a ...interface{}) error { args := i.Called(a) return args.Error(0) } func (i *TestExampleImplementation) TheExampleMethodMixedVariadic(a int, b ...int) error { args := i.Called(a, b) return args.Error(0) } type ExampleFuncType func(string) error func (i *TestExampleImplementation) TheExampleMethodFuncType(fn ExampleFuncType) error { args := i.Called(fn) return args.Error(0) } // MockTestingT mocks a test struct type MockTestingT struct { logfCount, errorfCount, failNowCount int } const mockTestingTFailNowCalled = "FailNow was called" func (m *MockTestingT) Logf(string, ...interface{}) { m.logfCount++ } func (m *MockTestingT) Errorf(string, ...interface{}) { m.errorfCount++ } // FailNow mocks the FailNow call. // It panics in order to mimic the FailNow behavior in the sense that // the execution stops. // When expecting this method, the call that invokes it should use the following code: // // assert.PanicsWithValue(t, mockTestingTFailNowCalled, func() {...}) func (m *MockTestingT) FailNow() { m.failNowCount++ // this function should panic now to stop the execution as expected panic(mockTestingTFailNowCalled) } /* Mock */ func Test_Mock_TestData(t *testing.T) { var mockedService = new(TestExampleImplementation) if assert.NotNil(t, mockedService.TestData()) { mockedService.TestData().Set("something", 123) assert.Equal(t, 123, mockedService.TestData().Get("something").Data()) } } func Test_Mock_On(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService.On("TheExampleMethod") assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, "TheExampleMethod", c.Method) } func Test_Mock_Chained_On(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) // determine our current line number so we can assert the expected calls callerInfo properly _, _, line, _ := runtime.Caller(0) mockedService. On("TheExampleMethod", 1, 2, 3). Return(0). On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). Return(nil) expectedCalls := []*Call{ { Parent: &mockedService.Mock, Method: "TheExampleMethod", Arguments: []interface{}{1, 2, 3}, ReturnArguments: []interface{}{0}, callerInfo: []string{fmt.Sprintf("mock_test.go:%d", line+2)}, }, { Parent: &mockedService.Mock, Method: "TheExampleMethod3", Arguments: []interface{}{AnythingOfType("*mock.ExampleType")}, ReturnArguments: []interface{}{nil}, callerInfo: []string{fmt.Sprintf("mock_test.go:%d", line+4)}, }, } assert.Equal(t, expectedCalls, mockedService.ExpectedCalls) } func Test_Mock_On_WithArgs(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService.On("TheExampleMethod", 1, 2, 3, 4) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, "TheExampleMethod", c.Method) assert.Equal(t, Arguments{1, 2, 3, 4}, c.Arguments) } func Test_Mock_On_WithFuncArg(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethodFunc", AnythingOfType("func(string) error")). Return(nil) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, "TheExampleMethodFunc", c.Method) assert.Equal(t, 1, len(c.Arguments)) assert.Equal(t, AnythingOfType("func(string) error"), c.Arguments[0]) fn := func(string) error { return nil } assert.NotPanics(t, func() { mockedService.TheExampleMethodFunc(fn) }) } func Test_Mock_On_WithIntArgMatcher(t *testing.T) { var mockedService TestExampleImplementation mockedService.On("TheExampleMethod", MatchedBy(func(a int) bool { return a == 1 }), MatchedBy(func(b int) bool { return b == 2 }), MatchedBy(func(c int) bool { return c == 3 })).Return(0, nil) assert.Panics(t, func() { mockedService.TheExampleMethod(1, 2, 4) }) assert.Panics(t, func() { mockedService.TheExampleMethod(2, 2, 3) }) assert.NotPanics(t, func() { mockedService.TheExampleMethod(1, 2, 3) }) } func TestMock_WithTest(t *testing.T) { var ( mockedService TestExampleImplementation mockedTest MockTestingT ) mockedService.Test(&mockedTest) mockedService.On("TheExampleMethod", 1, 2, 3).Return(0, nil) // Test that on an expected call, the test was not failed mockedService.TheExampleMethod(1, 2, 3) // Assert that Errorf and FailNow were not called assert.Equal(t, 0, mockedTest.errorfCount) assert.Equal(t, 0, mockedTest.failNowCount) // Test that on unexpected call, the mocked test was called to fail the test assert.PanicsWithValue(t, mockTestingTFailNowCalled, func() { mockedService.TheExampleMethod(1, 1, 1) }) // Assert that Errorf and FailNow were called once assert.Equal(t, 1, mockedTest.errorfCount) assert.Equal(t, 1, mockedTest.failNowCount) } func Test_Mock_On_WithPtrArgMatcher(t *testing.T) { var mockedService TestExampleImplementation mockedService.On("TheExampleMethod3", MatchedBy(func(a *ExampleType) bool { return a != nil && a.ran == true }), ).Return(nil) mockedService.On("TheExampleMethod3", MatchedBy(func(a *ExampleType) bool { return a != nil && a.ran == false }), ).Return(errors.New("error")) mockedService.On("TheExampleMethod3", MatchedBy(func(a *ExampleType) bool { return a == nil }), ).Return(errors.New("error2")) assert.Equal(t, mockedService.TheExampleMethod3(&ExampleType{true}), nil) assert.EqualError(t, mockedService.TheExampleMethod3(&ExampleType{false}), "error") assert.EqualError(t, mockedService.TheExampleMethod3(nil), "error2") } func Test_Mock_On_WithFuncArgMatcher(t *testing.T) { var mockedService TestExampleImplementation fixture1, fixture2 := errors.New("fixture1"), errors.New("fixture2") mockedService.On("TheExampleMethodFunc", MatchedBy(func(a func(string) error) bool { return a != nil && a("string") == fixture1 }), ).Return(errors.New("fixture1")) mockedService.On("TheExampleMethodFunc", MatchedBy(func(a func(string) error) bool { return a != nil && a("string") == fixture2 }), ).Return(errors.New("fixture2")) mockedService.On("TheExampleMethodFunc", MatchedBy(func(a func(string) error) bool { return a == nil }), ).Return(errors.New("fixture3")) assert.EqualError(t, mockedService.TheExampleMethodFunc( func(string) error { return fixture1 }), "fixture1") assert.EqualError(t, mockedService.TheExampleMethodFunc( func(string) error { return fixture2 }), "fixture2") assert.EqualError(t, mockedService.TheExampleMethodFunc(nil), "fixture3") } func Test_Mock_On_WithInterfaceArgMatcher(t *testing.T) { var mockedService TestExampleImplementation mockedService.On("TheExampleMethod4", MatchedBy(func(a ExampleInterface) bool { return a == nil }), ).Return(errors.New("fixture1")) assert.EqualError(t, mockedService.TheExampleMethod4(nil), "fixture1") } func Test_Mock_On_WithChannelArgMatcher(t *testing.T) { var mockedService TestExampleImplementation mockedService.On("TheExampleMethod5", MatchedBy(func(ch chan struct{}) bool { return ch == nil }), ).Return(errors.New("fixture1")) assert.EqualError(t, mockedService.TheExampleMethod5(nil), "fixture1") } func Test_Mock_On_WithMapArgMatcher(t *testing.T) { var mockedService TestExampleImplementation mockedService.On("TheExampleMethod6", MatchedBy(func(m map[string]bool) bool { return m == nil }), ).Return(errors.New("fixture1")) assert.EqualError(t, mockedService.TheExampleMethod6(nil), "fixture1") } func Test_Mock_On_WithSliceArgMatcher(t *testing.T) { var mockedService TestExampleImplementation mockedService.On("TheExampleMethod7", MatchedBy(func(slice []bool) bool { return slice == nil }), ).Return(errors.New("fixture1")) assert.EqualError(t, mockedService.TheExampleMethod7(nil), "fixture1") } func Test_Mock_On_WithVariadicFunc(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethodVariadic", []int{1, 2, 3}). Return(nil) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, 1, len(c.Arguments)) assert.Equal(t, []int{1, 2, 3}, c.Arguments[0]) assert.NotPanics(t, func() { mockedService.TheExampleMethodVariadic(1, 2, 3) }) assert.Panics(t, func() { mockedService.TheExampleMethodVariadic(1, 2) }) } func Test_Mock_On_WithMixedVariadicFunc(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethodMixedVariadic", 1, []int{2, 3, 4}). Return(nil) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, 2, len(c.Arguments)) assert.Equal(t, 1, c.Arguments[0]) assert.Equal(t, []int{2, 3, 4}, c.Arguments[1]) assert.NotPanics(t, func() { mockedService.TheExampleMethodMixedVariadic(1, 2, 3, 4) }) assert.Panics(t, func() { mockedService.TheExampleMethodMixedVariadic(1, 2, 3, 5) }) } func Test_Mock_On_WithVariadicFuncWithInterface(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService.On("TheExampleMethodVariadicInterface", []interface{}{1, 2, 3}). Return(nil) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, 1, len(c.Arguments)) assert.Equal(t, []interface{}{1, 2, 3}, c.Arguments[0]) assert.NotPanics(t, func() { mockedService.TheExampleMethodVariadicInterface(1, 2, 3) }) assert.Panics(t, func() { mockedService.TheExampleMethodVariadicInterface(1, 2) }) } func Test_Mock_On_WithVariadicFuncWithEmptyInterfaceArray(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) var expected []interface{} c := mockedService. On("TheExampleMethodVariadicInterface", expected). Return(nil) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, 1, len(c.Arguments)) assert.Equal(t, expected, c.Arguments[0]) assert.NotPanics(t, func() { mockedService.TheExampleMethodVariadicInterface() }) assert.Panics(t, func() { mockedService.TheExampleMethodVariadicInterface(1, 2) }) } func Test_Mock_On_WithFuncPanics(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) assert.Panics(t, func() { mockedService.On("TheExampleMethodFunc", func(string) error { return nil }) }) } func Test_Mock_On_WithFuncTypeArg(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethodFuncType", AnythingOfType("mock.ExampleFuncType")). Return(nil) assert.Equal(t, []*Call{c}, mockedService.ExpectedCalls) assert.Equal(t, 1, len(c.Arguments)) assert.Equal(t, AnythingOfType("mock.ExampleFuncType"), c.Arguments[0]) fn := func(string) error { return nil } assert.NotPanics(t, func() { mockedService.TheExampleMethodFuncType(fn) }) } func Test_Mock_Return(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethod", "A", "B", true). Return(1, "two", true) require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 1, call.ReturnArguments[0]) assert.Equal(t, "two", call.ReturnArguments[1]) assert.Equal(t, true, call.ReturnArguments[2]) assert.Equal(t, 0, call.Repeatability) assert.Nil(t, call.WaitFor) } func Test_Mock_Return_WaitUntil(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) ch := time.After(time.Second) c := mockedService.Mock. On("TheExampleMethod", "A", "B", true). WaitUntil(ch). Return(1, "two", true) // assert that the call was created require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 1, call.ReturnArguments[0]) assert.Equal(t, "two", call.ReturnArguments[1]) assert.Equal(t, true, call.ReturnArguments[2]) assert.Equal(t, 0, call.Repeatability) assert.Equal(t, ch, call.WaitFor) } func Test_Mock_Return_After(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService.Mock. On("TheExampleMethod", "A", "B", true). Return(1, "two", true). After(time.Second) require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.Mock.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 1, call.ReturnArguments[0]) assert.Equal(t, "two", call.ReturnArguments[1]) assert.Equal(t, true, call.ReturnArguments[2]) assert.Equal(t, 0, call.Repeatability) assert.NotEqual(t, nil, call.WaitFor) } func Test_Mock_Return_Run(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) fn := func(args Arguments) { arg := args.Get(0).(*ExampleType) arg.ran = true } c := mockedService.Mock. On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). Return(nil). Run(fn) require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.Mock.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod3", call.Method) assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0]) assert.Equal(t, nil, call.ReturnArguments[0]) assert.Equal(t, 0, call.Repeatability) assert.NotEqual(t, nil, call.WaitFor) assert.NotNil(t, call.Run) et := ExampleType{} assert.Equal(t, false, et.ran) mockedService.TheExampleMethod3(&et) assert.Equal(t, true, et.ran) } func Test_Mock_Return_Run_Out_Of_Order(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) f := func(args Arguments) { arg := args.Get(0).(*ExampleType) arg.ran = true } c := mockedService.Mock. On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")). Run(f). Return(nil) require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.Mock.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod3", call.Method) assert.Equal(t, AnythingOfType("*mock.ExampleType"), call.Arguments[0]) assert.Equal(t, nil, call.ReturnArguments[0]) assert.Equal(t, 0, call.Repeatability) assert.NotEqual(t, nil, call.WaitFor) assert.NotNil(t, call.Run) } func Test_Mock_Return_Once(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService.On("TheExampleMethod", "A", "B", true). Return(1, "two", true). Once() require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 1, call.ReturnArguments[0]) assert.Equal(t, "two", call.ReturnArguments[1]) assert.Equal(t, true, call.ReturnArguments[2]) assert.Equal(t, 1, call.Repeatability) assert.Nil(t, call.WaitFor) } func Test_Mock_Return_Twice(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethod", "A", "B", true). Return(1, "two", true). Twice() require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 1, call.ReturnArguments[0]) assert.Equal(t, "two", call.ReturnArguments[1]) assert.Equal(t, true, call.ReturnArguments[2]) assert.Equal(t, 2, call.Repeatability) assert.Nil(t, call.WaitFor) } func Test_Mock_Return_Times(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethod", "A", "B", true). Return(1, "two", true). Times(5) require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 1, call.ReturnArguments[0]) assert.Equal(t, "two", call.ReturnArguments[1]) assert.Equal(t, true, call.ReturnArguments[2]) assert.Equal(t, 5, call.Repeatability) assert.Nil(t, call.WaitFor) } func Test_Mock_Return_Nothing(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) c := mockedService. On("TheExampleMethod", "A", "B", true). Return() require.Equal(t, []*Call{c}, mockedService.ExpectedCalls) call := mockedService.ExpectedCalls[0] assert.Equal(t, "TheExampleMethod", call.Method) assert.Equal(t, "A", call.Arguments[0]) assert.Equal(t, "B", call.Arguments[1]) assert.Equal(t, true, call.Arguments[2]) assert.Equal(t, 0, len(call.ReturnArguments)) } func Test_Mock_findExpectedCall(t *testing.T) { m := new(Mock) m.On("One", 1).Return("one") m.On("Two", 2).Return("two") m.On("Two", 3).Return("three") f, c := m.findExpectedCall("Two", 3) if assert.Equal(t, 2, f) { if assert.NotNil(t, c) { assert.Equal(t, "Two", c.Method) assert.Equal(t, 3, c.Arguments[0]) assert.Equal(t, "three", c.ReturnArguments[0]) } } } func Test_Mock_findExpectedCall_For_Unknown_Method(t *testing.T) { m := new(Mock) m.On("One", 1).Return("one") m.On("Two", 2).Return("two") m.On("Two", 3).Return("three") f, _ := m.findExpectedCall("Two") assert.Equal(t, -1, f) } func Test_Mock_findExpectedCall_Respects_Repeatability(t *testing.T) { m := new(Mock) m.On("One", 1).Return("one") m.On("Two", 2).Return("two").Once() m.On("Two", 3).Return("three").Twice() m.On("Two", 3).Return("three").Times(8) f, c := m.findExpectedCall("Two", 3) if assert.Equal(t, 2, f) { if assert.NotNil(t, c) { assert.Equal(t, "Two", c.Method) assert.Equal(t, 3, c.Arguments[0]) assert.Equal(t, "three", c.ReturnArguments[0]) } } } func Test_callString(t *testing.T) { assert.Equal(t, `Method(int,bool,string)`, callString("Method", []interface{}{1, true, "something"}, false)) } func Test_Mock_Called(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_Called", 1, 2, 3).Return(5, "6", true) returnArguments := mockedService.Called(1, 2, 3) if assert.Equal(t, 1, len(mockedService.Calls)) { assert.Equal(t, "Test_Mock_Called", mockedService.Calls[0].Method) assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) } if assert.Equal(t, 3, len(returnArguments)) { assert.Equal(t, 5, returnArguments[0]) assert.Equal(t, "6", returnArguments[1]) assert.Equal(t, true, returnArguments[2]) } } func asyncCall(m *Mock, ch chan Arguments) { ch <- m.Called(1, 2, 3) } func Test_Mock_Called_blocks(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.Mock.On("asyncCall", 1, 2, 3).Return(5, "6", true).After(2 * time.Millisecond) ch := make(chan Arguments) go asyncCall(&mockedService.Mock, ch) select { case <-ch: t.Fatal("should have waited") case <-time.After(1 * time.Millisecond): } returnArguments := <-ch if assert.Equal(t, 1, len(mockedService.Mock.Calls)) { assert.Equal(t, "asyncCall", mockedService.Mock.Calls[0].Method) assert.Equal(t, 1, mockedService.Mock.Calls[0].Arguments[0]) assert.Equal(t, 2, mockedService.Mock.Calls[0].Arguments[1]) assert.Equal(t, 3, mockedService.Mock.Calls[0].Arguments[2]) } if assert.Equal(t, 3, len(returnArguments)) { assert.Equal(t, 5, returnArguments[0]) assert.Equal(t, "6", returnArguments[1]) assert.Equal(t, true, returnArguments[2]) } } func Test_Mock_Called_For_Bounded_Repeatability(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService. On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3). Return(5, "6", true). Once() mockedService. On("Test_Mock_Called_For_Bounded_Repeatability", 1, 2, 3). Return(-1, "hi", false) returnArguments1 := mockedService.Called(1, 2, 3) returnArguments2 := mockedService.Called(1, 2, 3) if assert.Equal(t, 2, len(mockedService.Calls)) { assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[0].Method) assert.Equal(t, 1, mockedService.Calls[0].Arguments[0]) assert.Equal(t, 2, mockedService.Calls[0].Arguments[1]) assert.Equal(t, 3, mockedService.Calls[0].Arguments[2]) assert.Equal(t, "Test_Mock_Called_For_Bounded_Repeatability", mockedService.Calls[1].Method) assert.Equal(t, 1, mockedService.Calls[1].Arguments[0]) assert.Equal(t, 2, mockedService.Calls[1].Arguments[1]) assert.Equal(t, 3, mockedService.Calls[1].Arguments[2]) } if assert.Equal(t, 3, len(returnArguments1)) { assert.Equal(t, 5, returnArguments1[0]) assert.Equal(t, "6", returnArguments1[1]) assert.Equal(t, true, returnArguments1[2]) } if assert.Equal(t, 3, len(returnArguments2)) { assert.Equal(t, -1, returnArguments2[0]) assert.Equal(t, "hi", returnArguments2[1]) assert.Equal(t, false, returnArguments2[2]) } } func Test_Mock_Called_For_SetTime_Expectation(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("TheExampleMethod", 1, 2, 3).Return(5, "6", true).Times(4) mockedService.TheExampleMethod(1, 2, 3) mockedService.TheExampleMethod(1, 2, 3) mockedService.TheExampleMethod(1, 2, 3) mockedService.TheExampleMethod(1, 2, 3) assert.Panics(t, func() { mockedService.TheExampleMethod(1, 2, 3) }) } func Test_Mock_Called_Unexpected(t *testing.T) { var mockedService = new(TestExampleImplementation) // make sure it panics if no expectation was made assert.Panics(t, func() { mockedService.Called(1, 2, 3) }, "Calling unexpected method should panic") } func Test_AssertExpectationsForObjects_Helper(t *testing.T) { var mockedService1 = new(TestExampleImplementation) var mockedService2 = new(TestExampleImplementation) var mockedService3 = new(TestExampleImplementation) mockedService1.On("Test_AssertExpectationsForObjects_Helper", 1).Return() mockedService2.On("Test_AssertExpectationsForObjects_Helper", 2).Return() mockedService3.On("Test_AssertExpectationsForObjects_Helper", 3).Return() mockedService1.Called(1) mockedService2.Called(2) mockedService3.Called(3) assert.True(t, AssertExpectationsForObjects(t, &mockedService1.Mock, &mockedService2.Mock, &mockedService3.Mock)) assert.True(t, AssertExpectationsForObjects(t, mockedService1, mockedService2, mockedService3)) } func Test_AssertExpectationsForObjects_Helper_Failed(t *testing.T) { var mockedService1 = new(TestExampleImplementation) var mockedService2 = new(TestExampleImplementation) var mockedService3 = new(TestExampleImplementation) mockedService1.On("Test_AssertExpectationsForObjects_Helper_Failed", 1).Return() mockedService2.On("Test_AssertExpectationsForObjects_Helper_Failed", 2).Return() mockedService3.On("Test_AssertExpectationsForObjects_Helper_Failed", 3).Return() mockedService1.Called(1) mockedService3.Called(3) tt := new(testing.T) assert.False(t, AssertExpectationsForObjects(tt, &mockedService1.Mock, &mockedService2.Mock, &mockedService3.Mock)) assert.False(t, AssertExpectationsForObjects(tt, mockedService1, mockedService2, mockedService3)) } func Test_Mock_AssertExpectations(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertExpectations", 1, 2, 3).Return(5, 6, 7) tt := new(testing.T) assert.False(t, mockedService.AssertExpectations(tt)) // make the call now mockedService.Called(1, 2, 3) // now assert expectations assert.True(t, mockedService.AssertExpectations(tt)) } func Test_Mock_AssertExpectations_Placeholder_NoArgs(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(5, 6, 7).Once() mockedService.On("Test_Mock_AssertExpectations_Placeholder_NoArgs").Return(7, 6, 5) tt := new(testing.T) assert.False(t, mockedService.AssertExpectations(tt)) // make the call now mockedService.Called() // now assert expectations assert.True(t, mockedService.AssertExpectations(tt)) } func Test_Mock_AssertExpectations_Placeholder(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertExpectations_Placeholder", 1, 2, 3).Return(5, 6, 7).Once() mockedService.On("Test_Mock_AssertExpectations_Placeholder", 3, 2, 1).Return(7, 6, 5) tt := new(testing.T) assert.False(t, mockedService.AssertExpectations(tt)) // make the call now mockedService.Called(1, 2, 3) // now assert expectations assert.False(t, mockedService.AssertExpectations(tt)) // make call to the second expectation mockedService.Called(3, 2, 1) // now assert expectations again assert.True(t, mockedService.AssertExpectations(tt)) } func Test_Mock_AssertExpectations_With_Pointers(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{1}).Return(1) mockedService.On("Test_Mock_AssertExpectations_With_Pointers", &struct{ Foo int }{2}).Return(2) tt := new(testing.T) assert.False(t, mockedService.AssertExpectations(tt)) s := struct{ Foo int }{1} // make the calls now mockedService.Called(&s) s.Foo = 2 mockedService.Called(&s) // now assert expectations assert.True(t, mockedService.AssertExpectations(tt)) } func Test_Mock_AssertExpectationsCustomType(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("TheExampleMethod3", AnythingOfType("*mock.ExampleType")).Return(nil).Once() tt := new(testing.T) assert.False(t, mockedService.AssertExpectations(tt)) // make the call now mockedService.TheExampleMethod3(&ExampleType{}) // now assert expectations assert.True(t, mockedService.AssertExpectations(tt)) } func Test_Mock_AssertExpectations_With_Repeatability(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertExpectations_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Twice() tt := new(testing.T) assert.False(t, mockedService.AssertExpectations(tt)) // make the call now mockedService.Called(1, 2, 3) assert.False(t, mockedService.AssertExpectations(tt)) mockedService.Called(1, 2, 3) // now assert expectations assert.True(t, mockedService.AssertExpectations(tt)) } func Test_Mock_TwoCallsWithDifferentArguments(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 1, 2, 3).Return(5, 6, 7) mockedService.On("Test_Mock_TwoCallsWithDifferentArguments", 4, 5, 6).Return(5, 6, 7) args1 := mockedService.Called(1, 2, 3) assert.Equal(t, 5, args1.Int(0)) assert.Equal(t, 6, args1.Int(1)) assert.Equal(t, 7, args1.Int(2)) args2 := mockedService.Called(4, 5, 6) assert.Equal(t, 5, args2.Int(0)) assert.Equal(t, 6, args2.Int(1)) assert.Equal(t, 7, args2.Int(2)) } func Test_Mock_AssertNumberOfCalls(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertNumberOfCalls", 1, 2, 3).Return(5, 6, 7) mockedService.Called(1, 2, 3) assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 1)) mockedService.Called(1, 2, 3) assert.True(t, mockedService.AssertNumberOfCalls(t, "Test_Mock_AssertNumberOfCalls", 2)) } func Test_Mock_AssertCalled(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertCalled", 1, 2, 3).Return(5, 6, 7) mockedService.Called(1, 2, 3) assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled", 1, 2, 3)) } func Test_Mock_AssertCalled_WithAnythingOfTypeArgument(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService. On("Test_Mock_AssertCalled_WithAnythingOfTypeArgument", Anything, Anything, Anything). Return() mockedService.Called(1, "two", []uint8("three")) assert.True(t, mockedService.AssertCalled(t, "Test_Mock_AssertCalled_WithAnythingOfTypeArgument", AnythingOfType("int"), AnythingOfType("string"), AnythingOfType("[]uint8"))) } func Test_Mock_AssertCalled_WithArguments(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertCalled_WithArguments", 1, 2, 3).Return(5, 6, 7) mockedService.Called(1, 2, 3) tt := new(testing.T) assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 1, 2, 3)) assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments", 2, 3, 4)) } func Test_Mock_AssertCalled_WithArguments_With_Repeatability(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3).Return(5, 6, 7).Once() mockedService.On("Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4).Return(5, 6, 7).Once() mockedService.Called(1, 2, 3) mockedService.Called(2, 3, 4) tt := new(testing.T) assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 1, 2, 3)) assert.True(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 2, 3, 4)) assert.False(t, mockedService.AssertCalled(tt, "Test_Mock_AssertCalled_WithArguments_With_Repeatability", 3, 4, 5)) } func Test_Mock_AssertNotCalled(t *testing.T) { var mockedService = new(TestExampleImplementation) mockedService.On("Test_Mock_AssertNotCalled", 1, 2, 3).Return(5, 6, 7) mockedService.Called(1, 2, 3) assert.True(t, mockedService.AssertNotCalled(t, "Test_Mock_NotCalled")) } func Test_Mock_AssertOptional(t *testing.T) { // Optional called var ms1 = new(TestExampleImplementation) ms1.On("TheExampleMethod", 1, 2, 3).Maybe().Return(4, nil) ms1.TheExampleMethod(1, 2, 3) tt1 := new(testing.T) assert.Equal(t, true, ms1.AssertExpectations(tt1)) // Optional not called var ms2 = new(TestExampleImplementation) ms2.On("TheExampleMethod", 1, 2, 3).Maybe().Return(4, nil) tt2 := new(testing.T) assert.Equal(t, true, ms2.AssertExpectations(tt2)) // Non-optional called var ms3 = new(TestExampleImplementation) ms3.On("TheExampleMethod", 1, 2, 3).Return(4, nil) ms3.TheExampleMethod(1, 2, 3) tt3 := new(testing.T) assert.Equal(t, true, ms3.AssertExpectations(tt3)) } /* Arguments helper methods */ func Test_Arguments_Get(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.Equal(t, "string", args.Get(0).(string)) assert.Equal(t, 123, args.Get(1).(int)) assert.Equal(t, true, args.Get(2).(bool)) } func Test_Arguments_Is(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.True(t, args.Is("string", 123, true)) assert.False(t, args.Is("wrong", 456, false)) } func Test_Arguments_Diff(t *testing.T) { var args = Arguments([]interface{}{"Hello World", 123, true}) var diff string var count int diff, count = args.Diff([]interface{}{"Hello World", 456, "false"}) assert.Equal(t, 2, count) assert.Contains(t, diff, `%!s(int=456) != %!s(int=123)`) assert.Contains(t, diff, `false != %!s(bool=true)`) } func Test_Arguments_Diff_DifferentNumberOfArgs(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) var diff string var count int diff, count = args.Diff([]interface{}{"string", 456, "false", "extra"}) assert.Equal(t, 3, count) assert.Contains(t, diff, `extra != (Missing)`) } func Test_Arguments_Diff_WithAnythingArgument(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) var count int _, count = args.Diff([]interface{}{"string", Anything, true}) assert.Equal(t, 0, count) } func Test_Arguments_Diff_WithAnythingArgument_InActualToo(t *testing.T) { var args = Arguments([]interface{}{"string", Anything, true}) var count int _, count = args.Diff([]interface{}{"string", 123, true}) assert.Equal(t, 0, count) } func Test_Arguments_Diff_WithAnythingOfTypeArgument(t *testing.T) { var args = Arguments([]interface{}{"string", AnythingOfType("int"), true}) var count int _, count = args.Diff([]interface{}{"string", 123, true}) assert.Equal(t, 0, count) } func Test_Arguments_Diff_WithAnythingOfTypeArgument_Failing(t *testing.T) { var args = Arguments([]interface{}{"string", AnythingOfType("string"), true}) var count int var diff string diff, count = args.Diff([]interface{}{"string", 123, true}) assert.Equal(t, 1, count) assert.Contains(t, diff, `string != type int - %!s(int=123)`) } func Test_Arguments_Diff_WithArgMatcher(t *testing.T) { matchFn := func(a int) bool { return a == 123 } var args = Arguments([]interface{}{"string", MatchedBy(matchFn), true}) diff, count := args.Diff([]interface{}{"string", 124, true}) assert.Equal(t, 1, count) assert.Contains(t, diff, `%!s(int=124) not matched by func(int) bool`) diff, count = args.Diff([]interface{}{"string", false, true}) assert.Equal(t, 1, count) assert.Contains(t, diff, `%!s(bool=false) not matched by func(int) bool`) diff, count = args.Diff([]interface{}{"string", 123, false}) assert.Contains(t, diff, `%!s(int=123) matched by func(int) bool`) diff, count = args.Diff([]interface{}{"string", 123, true}) assert.Equal(t, 0, count) assert.Contains(t, diff, `No differences.`) } func Test_Arguments_Assert(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.True(t, args.Assert(t, "string", 123, true)) } func Test_Arguments_String_Representation(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.Equal(t, `string,int,bool`, args.String()) } func Test_Arguments_String(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.Equal(t, "string", args.String(0)) } func Test_Arguments_Error(t *testing.T) { var err = errors.New("An Error") var args = Arguments([]interface{}{"string", 123, true, err}) assert.Equal(t, err, args.Error(3)) } func Test_Arguments_Error_Nil(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true, nil}) assert.Equal(t, nil, args.Error(3)) } func Test_Arguments_Int(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.Equal(t, 123, args.Int(1)) } func Test_Arguments_Bool(t *testing.T) { var args = Arguments([]interface{}{"string", 123, true}) assert.Equal(t, true, args.Bool(2)) } func Test_WaitUntil_Parallel(t *testing.T) { // make a test impl object var mockedService = new(TestExampleImplementation) ch1 := make(chan time.Time) ch2 := make(chan time.Time) mockedService.Mock.On("TheExampleMethod2", true).Return().WaitUntil(ch2).Run(func(args Arguments) { ch1 <- time.Now() }) mockedService.Mock.On("TheExampleMethod2", false).Return().WaitUntil(ch1) // Lock both goroutines on the .WaitUntil method go func() { mockedService.TheExampleMethod2(false) }() go func() { mockedService.TheExampleMethod2(true) }() // Allow the first call to execute, so the second one executes afterwards ch2 <- time.Now() } func Test_MockMethodCalled(t *testing.T) { m := new(Mock) m.On("foo", "hello").Return("world") retArgs := m.MethodCalled("foo", "hello") require.True(t, len(retArgs) == 1) require.Equal(t, "world", retArgs[0]) m.AssertExpectations(t) } // Test to validate fix for racy concurrent call access in MethodCalled() func Test_MockReturnAndCalledConcurrent(t *testing.T) { iterations := 1000 m := &Mock{} call := m.On("ConcurrencyTestMethod") wg := sync.WaitGroup{} wg.Add(2) go func() { for i := 0; i < iterations; i++ { call.Return(10) } wg.Done() }() go func() { for i := 0; i < iterations; i++ { ConcurrencyTestMethod(m) } wg.Done() }() wg.Wait() } type timer struct{ Mock } func (s *timer) GetTime(i int) string { return s.Called(i).Get(0).(string) } type tCustomLogger struct { *testing.T logs []string errs []string } func (tc *tCustomLogger) Logf(format string, args ...interface{}) { tc.T.Logf(format, args...) tc.logs = append(tc.logs, fmt.Sprintf(format, args...)) } func (tc *tCustomLogger) Errorf(format string, args ...interface{}) { tc.errs = append(tc.errs, fmt.Sprintf(format, args...)) } func (tc *tCustomLogger) FailNow() {} func TestLoggingAssertExpectations(t *testing.T) { m := new(timer) m.On("GetTime", 0).Return("") tcl := &tCustomLogger{t, []string{}, []string{}} AssertExpectationsForObjects(tcl, m, new(TestExampleImplementation)) require.Equal(t, 1, len(tcl.errs)) assert.Regexp(t, regexp.MustCompile("(?s)FAIL: 0 out of 1 expectation\\(s\\) were met.*The code you are testing needs to make 1 more call\\(s\\).*"), tcl.errs[0]) require.Equal(t, 2, len(tcl.logs)) assert.Regexp(t, regexp.MustCompile("(?s)FAIL:\tGetTime\\(int\\).*"), tcl.logs[0]) require.Equal(t, "Expectations didn't match for Mock: *mock.timer", tcl.logs[1]) } func TestAfterTotalWaitTimeWhileExecution(t *testing.T) { waitDuration := 1 total, waitMs := 5, time.Millisecond*time.Duration(waitDuration) aTimer := new(timer) for i := 0; i < total; i++ { aTimer.On("GetTime", i).After(waitMs).Return(fmt.Sprintf("Time%d", i)).Once() } time.Sleep(waitMs) start := time.Now() var results []string for i := 0; i < total; i++ { results = append(results, aTimer.GetTime(i)) } end := time.Now() elapsedTime := end.Sub(start) assert.True(t, elapsedTime > waitMs, fmt.Sprintf("Total elapsed time:%v should be atleast greater than %v", elapsedTime, waitMs)) assert.Equal(t, total, len(results)) for i := range results { assert.Equal(t, fmt.Sprintf("Time%d", i), results[i], "Return value of method should be same") } } func TestArgumentMatcherToPrintMismatch(t *testing.T) { defer func() { if r := recover(); r != nil { matchingExp := regexp.MustCompile( `\s+mock: Unexpected Method Call\s+-*\s+GetTime\(int\)\s+0: 1\s+The closest call I have is:\s+GetTime\(mock.argumentMatcher\)\s+0: mock.argumentMatcher\{.*?\}\s+Diff:.*\(int=1\) not matched by func\(int\) bool`) assert.Regexp(t, matchingExp, r) } }() m := new(timer) m.On("GetTime", MatchedBy(func(i int) bool { return false })).Return("SomeTime").Once() res := m.GetTime(1) require.Equal(t, "SomeTime", res) m.AssertExpectations(t) } func TestClosestCallMismatchedArgumentInformationShowsTheClosest(t *testing.T) { defer func() { if r := recover(); r != nil { matchingExp := regexp.MustCompile(unexpectedCallRegex(`TheExampleMethod(int,int,int)`, `0: 1\s+1: 1\s+2: 2`, `0: 1\s+1: 1\s+2: 1`, `0: PASS: %!s\(int=1\) == %!s\(int=1\)\s+1: PASS: %!s\(int=1\) == %!s\(int=1\)\s+2: FAIL: %!s\(int=2\) != %!s\(int=1\)`)) assert.Regexp(t, matchingExp, r) } }() m := new(TestExampleImplementation) m.On("TheExampleMethod", 1, 1, 1).Return(1, nil).Once() m.On("TheExampleMethod", 2, 2, 2).Return(2, nil).Once() m.TheExampleMethod(1, 1, 2) } func TestClosestCallMismatchedArgumentValueInformation(t *testing.T) { defer func() { if r := recover(); r != nil { matchingExp := regexp.MustCompile(unexpectedCallRegex(`GetTime(int)`, "0: 1", "0: 999", `0: FAIL: %!s\(int=1\) != %!s\(int=999\)`)) assert.Regexp(t, matchingExp, r) } }() m := new(timer) m.On("GetTime", 999).Return("SomeTime").Once() _ = m.GetTime(1) } func unexpectedCallRegex(method, calledArg, expectedArg, diff string) string { rMethod := regexp.QuoteMeta(method) return fmt.Sprintf(`\s+mock: Unexpected Method Call\s+-*\s+%s\s+%s\s+The closest call I have is:\s+%s\s+%s\s+Diff: %s`, rMethod, calledArg, rMethod, expectedArg, diff) } func ConcurrencyTestMethod(m *Mock) { m.Called() } ================================================ FILE: src/github.com/stretchr/testify/package_test.go ================================================ package testify import ( "github.com/stretchr/testify/assert" "testing" ) func TestImports(t *testing.T) { if assert.Equal(t, 1, 1) != true { t.Error("Something is wrong.") } } ================================================ FILE: src/github.com/stretchr/testify/require/doc.go ================================================ // Package require implements the same assertions as the `assert` package but // stops test execution when a test fails. // // Example Usage // // The following is a complete example using require in a standard test function: // import ( // "testing" // "github.com/stretchr/testify/require" // ) // // func TestSomething(t *testing.T) { // // var a string = "Hello" // var b string = "Hello" // // require.Equal(t, a, b, "The two words should be the same.") // // } // // Assertions // // The `require` package have same global functions as in the `assert` package, // but instead of returning a boolean result they call `t.FailNow()`. // // Every assertion function also takes an optional string message as the final argument, // allowing custom error messages to be appended to the message the assertion method outputs. package require ================================================ FILE: src/github.com/stretchr/testify/require/forward_requirements.go ================================================ package require // Assertions provides assertion methods around the // TestingT interface. type Assertions struct { t TestingT } // New makes a new Assertions object for the specified TestingT. func New(t TestingT) *Assertions { return &Assertions{ t: t, } } //go:generate go run ../_codegen/main.go -output-package=require -template=require_forward.go.tmpl -include-format-funcs ================================================ FILE: src/github.com/stretchr/testify/require/forward_requirements_test.go ================================================ package require import ( "errors" "testing" "time" ) func TestImplementsWrapper(t *testing.T) { require := New(t) require.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Implements((*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestIsTypeWrapper(t *testing.T) { require := New(t) require.IsType(new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) mockT := new(MockT) mockRequire := New(mockT) mockRequire.IsType(new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestEqualWrapper(t *testing.T) { require := New(t) require.Equal(1, 1) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Equal(1, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestNotEqualWrapper(t *testing.T) { require := New(t) require.NotEqual(1, 2) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotEqual(2, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestExactlyWrapper(t *testing.T) { require := New(t) a := float32(1) b := float32(1) c := float64(1) require.Exactly(a, b) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Exactly(a, c) if !mockT.Failed { t.Error("Check should fail") } } func TestNotNilWrapper(t *testing.T) { require := New(t) require.NotNil(t, new(AssertionTesterConformingObject)) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotNil(nil) if !mockT.Failed { t.Error("Check should fail") } } func TestNilWrapper(t *testing.T) { require := New(t) require.Nil(nil) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Nil(new(AssertionTesterConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestTrueWrapper(t *testing.T) { require := New(t) require.True(true) mockT := new(MockT) mockRequire := New(mockT) mockRequire.True(false) if !mockT.Failed { t.Error("Check should fail") } } func TestFalseWrapper(t *testing.T) { require := New(t) require.False(false) mockT := new(MockT) mockRequire := New(mockT) mockRequire.False(true) if !mockT.Failed { t.Error("Check should fail") } } func TestContainsWrapper(t *testing.T) { require := New(t) require.Contains("Hello World", "Hello") mockT := new(MockT) mockRequire := New(mockT) mockRequire.Contains("Hello World", "Salut") if !mockT.Failed { t.Error("Check should fail") } } func TestNotContainsWrapper(t *testing.T) { require := New(t) require.NotContains("Hello World", "Hello!") mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotContains("Hello World", "Hello") if !mockT.Failed { t.Error("Check should fail") } } func TestPanicsWrapper(t *testing.T) { require := New(t) require.Panics(func() { panic("Panic!") }) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Panics(func() {}) if !mockT.Failed { t.Error("Check should fail") } } func TestNotPanicsWrapper(t *testing.T) { require := New(t) require.NotPanics(func() {}) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotPanics(func() { panic("Panic!") }) if !mockT.Failed { t.Error("Check should fail") } } func TestNoErrorWrapper(t *testing.T) { require := New(t) require.NoError(nil) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NoError(errors.New("some error")) if !mockT.Failed { t.Error("Check should fail") } } func TestErrorWrapper(t *testing.T) { require := New(t) require.Error(errors.New("some error")) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Error(nil) if !mockT.Failed { t.Error("Check should fail") } } func TestEqualErrorWrapper(t *testing.T) { require := New(t) require.EqualError(errors.New("some error"), "some error") mockT := new(MockT) mockRequire := New(mockT) mockRequire.EqualError(errors.New("some error"), "Not some error") if !mockT.Failed { t.Error("Check should fail") } } func TestEmptyWrapper(t *testing.T) { require := New(t) require.Empty("") mockT := new(MockT) mockRequire := New(mockT) mockRequire.Empty("x") if !mockT.Failed { t.Error("Check should fail") } } func TestNotEmptyWrapper(t *testing.T) { require := New(t) require.NotEmpty("x") mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotEmpty("") if !mockT.Failed { t.Error("Check should fail") } } func TestWithinDurationWrapper(t *testing.T) { require := New(t) a := time.Now() b := a.Add(10 * time.Second) require.WithinDuration(a, b, 15*time.Second) mockT := new(MockT) mockRequire := New(mockT) mockRequire.WithinDuration(a, b, 5*time.Second) if !mockT.Failed { t.Error("Check should fail") } } func TestInDeltaWrapper(t *testing.T) { require := New(t) require.InDelta(1.001, 1, 0.01) mockT := new(MockT) mockRequire := New(mockT) mockRequire.InDelta(1, 2, 0.5) if !mockT.Failed { t.Error("Check should fail") } } func TestZeroWrapper(t *testing.T) { require := New(t) require.Zero(0) mockT := new(MockT) mockRequire := New(mockT) mockRequire.Zero(1) if !mockT.Failed { t.Error("Check should fail") } } func TestNotZeroWrapper(t *testing.T) { require := New(t) require.NotZero(1) mockT := new(MockT) mockRequire := New(mockT) mockRequire.NotZero(0) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEqWrapper_EqualSONString(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) if mockT.Failed { t.Error("Check should pass") } } func TestJSONEqWrapper_EquivalentButNotEqual(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) if mockT.Failed { t.Error("Check should pass") } } func TestJSONEqWrapper_HashOfArraysAndHashes(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq("{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") if mockT.Failed { t.Error("Check should pass") } } func TestJSONEqWrapper_Array(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) if mockT.Failed { t.Error("Check should pass") } } func TestJSONEqWrapper_HashAndArrayNotEquivalent(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEqWrapper_HashesNotEquivalent(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEqWrapper_ActualIsNotJSON(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`{"foo": "bar"}`, "Not JSON") if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEqWrapper_ExpectedIsNotJSON(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq("Not JSON", `{"foo": "bar", "hello": "world"}`) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEqWrapper_ExpectedAndActualNotJSON(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq("Not JSON", "Not JSON") if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEqWrapper_ArraysOfDifferentOrder(t *testing.T) { mockT := new(MockT) mockRequire := New(mockT) mockRequire.JSONEq(`["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) if !mockT.Failed { t.Error("Check should fail") } } ================================================ FILE: src/github.com/stretchr/testify/require/require.go ================================================ /* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package require import ( assert "github.com/stretchr/testify/assert" http "net/http" url "net/url" time "time" ) // Condition uses a Comparison to assert a complex condition. func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Condition(t, comp, msgAndArgs...) { t.FailNow() } } // Conditionf uses a Comparison to assert a complex condition. func Conditionf(t TestingT, comp assert.Comparison, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Conditionf(t, comp, msg, args...) { t.FailNow() } } // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Contains(t, "Hello World", "World") // assert.Contains(t, ["Hello", "World"], "World") // assert.Contains(t, {"Hello": "World"}, "Hello") func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Contains(t, s, contains, msgAndArgs...) { t.FailNow() } } // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") // assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") // assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Containsf(t, s, contains, msg, args...) { t.FailNow() } } // DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. func DirExists(t TestingT, path string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.DirExists(t, path, msgAndArgs...) { t.FailNow() } } // DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. func DirExistsf(t TestingT, path string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.DirExistsf(t, path, msg, args...) { t.FailNow() } } // ElementsMatch asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) func ElementsMatch(t TestingT, listA interface{}, listB interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.ElementsMatch(t, listA, listB, msgAndArgs...) { t.FailNow() } } // ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.ElementsMatchf(t, listA, listB, msg, args...) { t.FailNow() } } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Empty(t, obj) func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Empty(t, object, msgAndArgs...) { t.FailNow() } } // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // assert.Emptyf(t, obj, "error message %s", "formatted") func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Emptyf(t, object, msg, args...) { t.FailNow() } } // Equal asserts that two objects are equal. // // assert.Equal(t, 123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Equal(t, expected, actual, msgAndArgs...) { t.FailNow() } } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // assert.EqualError(t, err, expectedErrorString) func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.EqualError(t, theError, errString, msgAndArgs...) { t.FailNow() } } // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.EqualErrorf(t, theError, errString, msg, args...) { t.FailNow() } } // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValues(t, uint32(123), int32(123)) func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.EqualValues(t, expected, actual, msgAndArgs...) { t.FailNow() } } // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // // assert.EqualValuesf(t, uint32(123, "error message %s", "formatted"), int32(123)) func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.EqualValuesf(t, expected, actual, msg, args...) { t.FailNow() } } // Equalf asserts that two objects are equal. // // assert.Equalf(t, 123, 123, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Equalf(t, expected, actual, msg, args...) { t.FailNow() } } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Error(t, err) { // assert.Equal(t, expectedError, err) // } func Error(t TestingT, err error, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Error(t, err, msgAndArgs...) { t.FailNow() } } // Errorf asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if assert.Errorf(t, err, "error message %s", "formatted") { // assert.Equal(t, expectedErrorf, err) // } func Errorf(t TestingT, err error, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Errorf(t, err, msg, args...) { t.FailNow() } } // Exactly asserts that two objects are equal in value and type. // // assert.Exactly(t, int32(123), int64(123)) func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Exactly(t, expected, actual, msgAndArgs...) { t.FailNow() } } // Exactlyf asserts that two objects are equal in value and type. // // assert.Exactlyf(t, int32(123, "error message %s", "formatted"), int64(123)) func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Exactlyf(t, expected, actual, msg, args...) { t.FailNow() } } // Fail reports a failure through func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Fail(t, failureMessage, msgAndArgs...) { t.FailNow() } } // FailNow fails test func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.FailNow(t, failureMessage, msgAndArgs...) { t.FailNow() } } // FailNowf fails test func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.FailNowf(t, failureMessage, msg, args...) { t.FailNow() } } // Failf reports a failure through func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Failf(t, failureMessage, msg, args...) { t.FailNow() } } // False asserts that the specified value is false. // // assert.False(t, myBool) func False(t TestingT, value bool, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.False(t, value, msgAndArgs...) { t.FailNow() } } // Falsef asserts that the specified value is false. // // assert.Falsef(t, myBool, "error message %s", "formatted") func Falsef(t TestingT, value bool, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Falsef(t, value, msg, args...) { t.FailNow() } } // FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. func FileExists(t TestingT, path string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.FileExists(t, path, msgAndArgs...) { t.FailNow() } } // FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. func FileExistsf(t TestingT, path string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.FileExistsf(t, path, msg, args...) { t.FailNow() } } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.HTTPBodyContains(t, handler, method, url, values, str, msgAndArgs...) { t.FailNow() } } // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // // assert.HTTPBodyContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.HTTPBodyContainsf(t, handler, method, url, values, str, msg, args...) { t.FailNow() } } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.HTTPBodyNotContains(t, handler, method, url, values, str, msgAndArgs...) { t.FailNow() } } // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // // assert.HTTPBodyNotContainsf(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.HTTPBodyNotContainsf(t, handler, method, url, values, str, msg, args...) { t.FailNow() } } // HTTPError asserts that a specified handler returns an error status code. // // assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.HTTPError(t, handler, method, url, values, msgAndArgs...) { t.FailNow() } } // HTTPErrorf asserts that a specified handler returns an error status code. // // assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.HTTPErrorf(t, handler, method, url, values, msg, args...) { t.FailNow() } } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.HTTPRedirect(t, handler, method, url, values, msgAndArgs...) { t.FailNow() } } // HTTPRedirectf asserts that a specified handler returns a redirect status code. // // assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.HTTPRedirectf(t, handler, method, url, values, msg, args...) { t.FailNow() } } // HTTPSuccess asserts that a specified handler returns a success status code. // // assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.HTTPSuccess(t, handler, method, url, values, msgAndArgs...) { t.FailNow() } } // HTTPSuccessf asserts that a specified handler returns a success status code. // // assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.HTTPSuccessf(t, handler, method, url, values, msg, args...) { t.FailNow() } } // Implements asserts that an object is implemented by the specified interface. // // assert.Implements(t, (*MyInterface)(nil), new(MyObject)) func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Implements(t, interfaceObject, object, msgAndArgs...) { t.FailNow() } } // Implementsf asserts that an object is implemented by the specified interface. // // assert.Implementsf(t, (*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Implementsf(t, interfaceObject, object, msg, args...) { t.FailNow() } } // InDelta asserts that the two numerals are within delta of each other. // // assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.InDelta(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func InDeltaMapValues(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.InDeltaMapValues(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.InDeltaMapValuesf(t, expected, actual, delta, msg, args...) { t.FailNow() } } // InDeltaSlice is the same as InDelta, except it compares two slices. func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.InDeltaSlice(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // InDeltaSlicef is the same as InDelta, except it compares two slices. func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.InDeltaSlicef(t, expected, actual, delta, msg, args...) { t.FailNow() } } // InDeltaf asserts that the two numerals are within delta of each other. // // assert.InDeltaf(t, math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.InDeltaf(t, expected, actual, delta, msg, args...) { t.FailNow() } } // InEpsilon asserts that expected and actual have a relative error less than epsilon func InEpsilon(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { t.FailNow() } } // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.InEpsilonSlice(t, expected, actual, epsilon, msgAndArgs...) { t.FailNow() } } // InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.InEpsilonSlicef(t, expected, actual, epsilon, msg, args...) { t.FailNow() } } // InEpsilonf asserts that expected and actual have a relative error less than epsilon func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.InEpsilonf(t, expected, actual, epsilon, msg, args...) { t.FailNow() } } // IsType asserts that the specified objects are of the same type. func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.IsType(t, expectedType, object, msgAndArgs...) { t.FailNow() } } // IsTypef asserts that the specified objects are of the same type. func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.IsTypef(t, expectedType, object, msg, args...) { t.FailNow() } } // JSONEq asserts that two JSON strings are equivalent. // // assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.JSONEq(t, expected, actual, msgAndArgs...) { t.FailNow() } } // JSONEqf asserts that two JSON strings are equivalent. // // assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.JSONEqf(t, expected, actual, msg, args...) { t.FailNow() } } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // assert.Len(t, mySlice, 3) func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Len(t, object, length, msgAndArgs...) { t.FailNow() } } // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // // assert.Lenf(t, mySlice, 3, "error message %s", "formatted") func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Lenf(t, object, length, msg, args...) { t.FailNow() } } // Nil asserts that the specified object is nil. // // assert.Nil(t, err) func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Nil(t, object, msgAndArgs...) { t.FailNow() } } // Nilf asserts that the specified object is nil. // // assert.Nilf(t, err, "error message %s", "formatted") func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Nilf(t, object, msg, args...) { t.FailNow() } } // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoError(t, err) { // assert.Equal(t, expectedObj, actualObj) // } func NoError(t TestingT, err error, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NoError(t, err, msgAndArgs...) { t.FailNow() } } // NoErrorf asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if assert.NoErrorf(t, err, "error message %s", "formatted") { // assert.Equal(t, expectedObj, actualObj) // } func NoErrorf(t TestingT, err error, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NoErrorf(t, err, msg, args...) { t.FailNow() } } // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // assert.NotContains(t, "Hello World", "Earth") // assert.NotContains(t, ["Hello", "World"], "Earth") // assert.NotContains(t, {"Hello": "World"}, "Earth") func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotContains(t, s, contains, msgAndArgs...) { t.FailNow() } } // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") // assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") // assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotContainsf(t, s, contains, msg, args...) { t.FailNow() } } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if assert.NotEmpty(t, obj) { // assert.Equal(t, "two", obj[1]) // } func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotEmpty(t, object, msgAndArgs...) { t.FailNow() } } // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if assert.NotEmptyf(t, obj, "error message %s", "formatted") { // assert.Equal(t, "two", obj[1]) // } func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotEmptyf(t, object, msg, args...) { t.FailNow() } } // NotEqual asserts that the specified values are NOT equal. // // assert.NotEqual(t, obj1, obj2) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotEqual(t, expected, actual, msgAndArgs...) { t.FailNow() } } // NotEqualf asserts that the specified values are NOT equal. // // assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotEqualf(t, expected, actual, msg, args...) { t.FailNow() } } // NotNil asserts that the specified object is not nil. // // assert.NotNil(t, err) func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotNil(t, object, msgAndArgs...) { t.FailNow() } } // NotNilf asserts that the specified object is not nil. // // assert.NotNilf(t, err, "error message %s", "formatted") func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotNilf(t, object, msg, args...) { t.FailNow() } } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // assert.NotPanics(t, func(){ RemainCalm() }) func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotPanics(t, f, msgAndArgs...) { t.FailNow() } } // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // // assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotPanicsf(t, f, msg, args...) { t.FailNow() } } // NotRegexp asserts that a specified regexp does not match a string. // // assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") // assert.NotRegexp(t, "^start", "it's not starting") func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotRegexp(t, rx, str, msgAndArgs...) { t.FailNow() } } // NotRegexpf asserts that a specified regexp does not match a string. // // assert.NotRegexpf(t, regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") // assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotRegexpf(t, rx, str, msg, args...) { t.FailNow() } } // NotSubset asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotSubset(t, list, subset, msgAndArgs...) { t.FailNow() } } // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotSubsetf(t, list, subset, msg, args...) { t.FailNow() } } // NotZero asserts that i is not the zero value for its type. func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotZero(t, i, msgAndArgs...) { t.FailNow() } } // NotZerof asserts that i is not the zero value for its type. func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.NotZerof(t, i, msg, args...) { t.FailNow() } } // Panics asserts that the code inside the specified PanicTestFunc panics. // // assert.Panics(t, func(){ GoCrazy() }) func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Panics(t, f, msgAndArgs...) { t.FailNow() } } // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.PanicsWithValue(t, expected, f, msgAndArgs...) { t.FailNow() } } // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.PanicsWithValuef(t, expected, f, msg, args...) { t.FailNow() } } // Panicsf asserts that the code inside the specified PanicTestFunc panics. // // assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Panicsf(t, f, msg, args...) { t.FailNow() } } // Regexp asserts that a specified regexp matches a string. // // assert.Regexp(t, regexp.MustCompile("start"), "it's starting") // assert.Regexp(t, "start...$", "it's not starting") func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Regexp(t, rx, str, msgAndArgs...) { t.FailNow() } } // Regexpf asserts that a specified regexp matches a string. // // assert.Regexpf(t, regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") // assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Regexpf(t, rx, str, msg, args...) { t.FailNow() } } // Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Subset(t, list, subset, msgAndArgs...) { t.FailNow() } } // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Subsetf(t, list, subset, msg, args...) { t.FailNow() } } // True asserts that the specified value is true. // // assert.True(t, myBool) func True(t TestingT, value bool, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.True(t, value, msgAndArgs...) { t.FailNow() } } // Truef asserts that the specified value is true. // // assert.Truef(t, myBool, "error message %s", "formatted") func Truef(t TestingT, value bool, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Truef(t, value, msg, args...) { t.FailNow() } } // WithinDuration asserts that the two times are within duration delta of each other. // // assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { t.FailNow() } } // WithinDurationf asserts that the two times are within duration delta of each other. // // assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.WithinDurationf(t, expected, actual, delta, msg, args...) { t.FailNow() } } // Zero asserts that i is the zero value for its type. func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Zero(t, i, msgAndArgs...) { t.FailNow() } } // Zerof asserts that i is the zero value for its type. func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.Zerof(t, i, msg, args...) { t.FailNow() } } ================================================ FILE: src/github.com/stretchr/testify/require/require.go.tmpl ================================================ {{.Comment}} func {{.DocInfo.Name}}(t TestingT, {{.Params}}) { if h, ok := t.(tHelper); ok { h.Helper() } if !assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { t.FailNow() } } ================================================ FILE: src/github.com/stretchr/testify/require/require_forward.go ================================================ /* * CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen * THIS FILE MUST NOT BE EDITED BY HAND */ package require import ( assert "github.com/stretchr/testify/assert" http "net/http" url "net/url" time "time" ) // Condition uses a Comparison to assert a complex condition. func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Condition(a.t, comp, msgAndArgs...) } // Conditionf uses a Comparison to assert a complex condition. func (a *Assertions) Conditionf(comp assert.Comparison, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Conditionf(a.t, comp, msg, args...) } // Contains asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // a.Contains("Hello World", "World") // a.Contains(["Hello", "World"], "World") // a.Contains({"Hello": "World"}, "Hello") func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Contains(a.t, s, contains, msgAndArgs...) } // Containsf asserts that the specified string, list(array, slice...) or map contains the // specified substring or element. // // a.Containsf("Hello World", "World", "error message %s", "formatted") // a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") // a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Containsf(a.t, s, contains, msg, args...) } // DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } DirExists(a.t, path, msgAndArgs...) } // DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } DirExistsf(a.t, path, msg, args...) } // ElementsMatch asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2]) func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } ElementsMatch(a.t, listA, listB, msgAndArgs...) } // ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified // listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, // the number of appearances of each of them in both lists should match. // // a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } ElementsMatchf(a.t, listA, listB, msg, args...) } // Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // a.Empty(obj) func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Empty(a.t, object, msgAndArgs...) } // Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either // a slice or a channel with len == 0. // // a.Emptyf(obj, "error message %s", "formatted") func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Emptyf(a.t, object, msg, args...) } // Equal asserts that two objects are equal. // // a.Equal(123, 123) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Equal(a.t, expected, actual, msgAndArgs...) } // EqualError asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // a.EqualError(err, expectedErrorString) func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } EqualError(a.t, theError, errString, msgAndArgs...) } // EqualErrorf asserts that a function returned an error (i.e. not `nil`) // and that it is equal to the provided error. // // actualObj, err := SomeFunction() // a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } EqualErrorf(a.t, theError, errString, msg, args...) } // EqualValues asserts that two objects are equal or convertable to the same types // and equal. // // a.EqualValues(uint32(123), int32(123)) func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } EqualValues(a.t, expected, actual, msgAndArgs...) } // EqualValuesf asserts that two objects are equal or convertable to the same types // and equal. // // a.EqualValuesf(uint32(123, "error message %s", "formatted"), int32(123)) func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } EqualValuesf(a.t, expected, actual, msg, args...) } // Equalf asserts that two objects are equal. // // a.Equalf(123, 123, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). Function equality // cannot be determined and will always fail. func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Equalf(a.t, expected, actual, msg, args...) } // Error asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if a.Error(err) { // assert.Equal(t, expectedError, err) // } func (a *Assertions) Error(err error, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Error(a.t, err, msgAndArgs...) } // Errorf asserts that a function returned an error (i.e. not `nil`). // // actualObj, err := SomeFunction() // if a.Errorf(err, "error message %s", "formatted") { // assert.Equal(t, expectedErrorf, err) // } func (a *Assertions) Errorf(err error, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Errorf(a.t, err, msg, args...) } // Exactly asserts that two objects are equal in value and type. // // a.Exactly(int32(123), int64(123)) func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Exactly(a.t, expected, actual, msgAndArgs...) } // Exactlyf asserts that two objects are equal in value and type. // // a.Exactlyf(int32(123, "error message %s", "formatted"), int64(123)) func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Exactlyf(a.t, expected, actual, msg, args...) } // Fail reports a failure through func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Fail(a.t, failureMessage, msgAndArgs...) } // FailNow fails test func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } FailNow(a.t, failureMessage, msgAndArgs...) } // FailNowf fails test func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } FailNowf(a.t, failureMessage, msg, args...) } // Failf reports a failure through func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Failf(a.t, failureMessage, msg, args...) } // False asserts that the specified value is false. // // a.False(myBool) func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } False(a.t, value, msgAndArgs...) } // Falsef asserts that the specified value is false. // // a.Falsef(myBool, "error message %s", "formatted") func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Falsef(a.t, value, msg, args...) } // FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } FileExists(a.t, path, msgAndArgs...) } // FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file. func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } FileExistsf(a.t, path, msg, args...) } // HTTPBodyContains asserts that a specified handler returns a // body that contains a string. // // a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...) } // HTTPBodyContainsf asserts that a specified handler returns a // body that contains a string. // // a.HTTPBodyContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...) } // HTTPBodyNotContains asserts that a specified handler returns a // body that does not contain a string. // // a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...) } // HTTPBodyNotContainsf asserts that a specified handler returns a // body that does not contain a string. // // a.HTTPBodyNotContainsf(myHandler, "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...) } // HTTPError asserts that a specified handler returns an error status code. // // a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } HTTPError(a.t, handler, method, url, values, msgAndArgs...) } // HTTPErrorf asserts that a specified handler returns an error status code. // // a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } HTTPErrorf(a.t, handler, method, url, values, msg, args...) } // HTTPRedirect asserts that a specified handler returns a redirect status code. // // a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...) } // HTTPRedirectf asserts that a specified handler returns a redirect status code. // // a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} // // Returns whether the assertion was successful (true, "error message %s", "formatted") or not (false). func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } HTTPRedirectf(a.t, handler, method, url, values, msg, args...) } // HTTPSuccess asserts that a specified handler returns a success status code. // // a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...) } // HTTPSuccessf asserts that a specified handler returns a success status code. // // a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") // // Returns whether the assertion was successful (true) or not (false). func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } HTTPSuccessf(a.t, handler, method, url, values, msg, args...) } // Implements asserts that an object is implemented by the specified interface. // // a.Implements((*MyInterface)(nil), new(MyObject)) func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Implements(a.t, interfaceObject, object, msgAndArgs...) } // Implementsf asserts that an object is implemented by the specified interface. // // a.Implementsf((*MyInterface, "error message %s", "formatted")(nil), new(MyObject)) func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Implementsf(a.t, interfaceObject, object, msg, args...) } // InDelta asserts that the two numerals are within delta of each other. // // a.InDelta(math.Pi, (22 / 7.0), 0.01) func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } InDelta(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...) } // InDeltaSlice is the same as InDelta, except it compares two slices. func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) } // InDeltaSlicef is the same as InDelta, except it compares two slices. func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } InDeltaSlicef(a.t, expected, actual, delta, msg, args...) } // InDeltaf asserts that the two numerals are within delta of each other. // // a.InDeltaf(math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01) func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } InDeltaf(a.t, expected, actual, delta, msg, args...) } // InEpsilon asserts that expected and actual have a relative error less than epsilon func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) } // InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) } // InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) } // InEpsilonf asserts that expected and actual have a relative error less than epsilon func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } InEpsilonf(a.t, expected, actual, epsilon, msg, args...) } // IsType asserts that the specified objects are of the same type. func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } IsType(a.t, expectedType, object, msgAndArgs...) } // IsTypef asserts that the specified objects are of the same type. func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } IsTypef(a.t, expectedType, object, msg, args...) } // JSONEq asserts that two JSON strings are equivalent. // // a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } JSONEq(a.t, expected, actual, msgAndArgs...) } // JSONEqf asserts that two JSON strings are equivalent. // // a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } JSONEqf(a.t, expected, actual, msg, args...) } // Len asserts that the specified object has specific length. // Len also fails if the object has a type that len() not accept. // // a.Len(mySlice, 3) func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Len(a.t, object, length, msgAndArgs...) } // Lenf asserts that the specified object has specific length. // Lenf also fails if the object has a type that len() not accept. // // a.Lenf(mySlice, 3, "error message %s", "formatted") func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Lenf(a.t, object, length, msg, args...) } // Nil asserts that the specified object is nil. // // a.Nil(err) func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Nil(a.t, object, msgAndArgs...) } // Nilf asserts that the specified object is nil. // // a.Nilf(err, "error message %s", "formatted") func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Nilf(a.t, object, msg, args...) } // NoError asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if a.NoError(err) { // assert.Equal(t, expectedObj, actualObj) // } func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NoError(a.t, err, msgAndArgs...) } // NoErrorf asserts that a function returned no error (i.e. `nil`). // // actualObj, err := SomeFunction() // if a.NoErrorf(err, "error message %s", "formatted") { // assert.Equal(t, expectedObj, actualObj) // } func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NoErrorf(a.t, err, msg, args...) } // NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // a.NotContains("Hello World", "Earth") // a.NotContains(["Hello", "World"], "Earth") // a.NotContains({"Hello": "World"}, "Earth") func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotContains(a.t, s, contains, msgAndArgs...) } // NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the // specified substring or element. // // a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") // a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") // a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotContainsf(a.t, s, contains, msg, args...) } // NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if a.NotEmpty(obj) { // assert.Equal(t, "two", obj[1]) // } func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotEmpty(a.t, object, msgAndArgs...) } // NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either // a slice or a channel with len == 0. // // if a.NotEmptyf(obj, "error message %s", "formatted") { // assert.Equal(t, "two", obj[1]) // } func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotEmptyf(a.t, object, msg, args...) } // NotEqual asserts that the specified values are NOT equal. // // a.NotEqual(obj1, obj2) // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotEqual(a.t, expected, actual, msgAndArgs...) } // NotEqualf asserts that the specified values are NOT equal. // // a.NotEqualf(obj1, obj2, "error message %s", "formatted") // // Pointer variable equality is determined based on the equality of the // referenced values (as opposed to the memory addresses). func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotEqualf(a.t, expected, actual, msg, args...) } // NotNil asserts that the specified object is not nil. // // a.NotNil(err) func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotNil(a.t, object, msgAndArgs...) } // NotNilf asserts that the specified object is not nil. // // a.NotNilf(err, "error message %s", "formatted") func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotNilf(a.t, object, msg, args...) } // NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. // // a.NotPanics(func(){ RemainCalm() }) func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotPanics(a.t, f, msgAndArgs...) } // NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. // // a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") func (a *Assertions) NotPanicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotPanicsf(a.t, f, msg, args...) } // NotRegexp asserts that a specified regexp does not match a string. // // a.NotRegexp(regexp.MustCompile("starts"), "it's starting") // a.NotRegexp("^start", "it's not starting") func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotRegexp(a.t, rx, str, msgAndArgs...) } // NotRegexpf asserts that a specified regexp does not match a string. // // a.NotRegexpf(regexp.MustCompile("starts", "error message %s", "formatted"), "it's starting") // a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotRegexpf(a.t, rx, str, msg, args...) } // NotSubset asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotSubset(a.t, list, subset, msgAndArgs...) } // NotSubsetf asserts that the specified list(array, slice...) contains not all // elements given in the specified subset(array, slice...). // // a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotSubsetf(a.t, list, subset, msg, args...) } // NotZero asserts that i is not the zero value for its type. func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotZero(a.t, i, msgAndArgs...) } // NotZerof asserts that i is not the zero value for its type. func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } NotZerof(a.t, i, msg, args...) } // Panics asserts that the code inside the specified PanicTestFunc panics. // // a.Panics(func(){ GoCrazy() }) func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Panics(a.t, f, msgAndArgs...) } // PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // a.PanicsWithValue("crazy error", func(){ GoCrazy() }) func (a *Assertions) PanicsWithValue(expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } PanicsWithValue(a.t, expected, f, msgAndArgs...) } // PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that // the recovered panic value equals the expected panic value. // // a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") func (a *Assertions) PanicsWithValuef(expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } PanicsWithValuef(a.t, expected, f, msg, args...) } // Panicsf asserts that the code inside the specified PanicTestFunc panics. // // a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") func (a *Assertions) Panicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Panicsf(a.t, f, msg, args...) } // Regexp asserts that a specified regexp matches a string. // // a.Regexp(regexp.MustCompile("start"), "it's starting") // a.Regexp("start...$", "it's not starting") func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Regexp(a.t, rx, str, msgAndArgs...) } // Regexpf asserts that a specified regexp matches a string. // // a.Regexpf(regexp.MustCompile("start", "error message %s", "formatted"), "it's starting") // a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Regexpf(a.t, rx, str, msg, args...) } // Subset asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Subset(a.t, list, subset, msgAndArgs...) } // Subsetf asserts that the specified list(array, slice...) contains all // elements given in the specified subset(array, slice...). // // a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Subsetf(a.t, list, subset, msg, args...) } // True asserts that the specified value is true. // // a.True(myBool) func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } True(a.t, value, msgAndArgs...) } // Truef asserts that the specified value is true. // // a.Truef(myBool, "error message %s", "formatted") func (a *Assertions) Truef(value bool, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Truef(a.t, value, msg, args...) } // WithinDuration asserts that the two times are within duration delta of each other. // // a.WithinDuration(time.Now(), time.Now(), 10*time.Second) func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } WithinDuration(a.t, expected, actual, delta, msgAndArgs...) } // WithinDurationf asserts that the two times are within duration delta of each other. // // a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } WithinDurationf(a.t, expected, actual, delta, msg, args...) } // Zero asserts that i is the zero value for its type. func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Zero(a.t, i, msgAndArgs...) } // Zerof asserts that i is the zero value for its type. func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) { if h, ok := a.t.(tHelper); ok { h.Helper() } Zerof(a.t, i, msg, args...) } ================================================ FILE: src/github.com/stretchr/testify/require/require_forward.go.tmpl ================================================ {{.CommentWithoutT "a"}} func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) { if h, ok := a.t.(tHelper); ok { h.Helper() } {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) } ================================================ FILE: src/github.com/stretchr/testify/require/requirements.go ================================================ package require // TestingT is an interface wrapper around *testing.T type TestingT interface { Errorf(format string, args ...interface{}) FailNow() } type tHelper interface { Helper() } // ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful // for table driven tests. type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) // ValueAssertionFunc is a common function prototype when validating a single value. Can be useful // for table driven tests. type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) // BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful // for table driven tests. type BoolAssertionFunc func(TestingT, bool, ...interface{}) // ValuesAssertionFunc is a common function prototype when validating an error value. Can be useful // for table driven tests. type ErrorAssertionFunc func(TestingT, error, ...interface{}) //go:generate go run ../_codegen/main.go -output-package=require -template=require.go.tmpl -include-format-funcs ================================================ FILE: src/github.com/stretchr/testify/require/requirements_test.go ================================================ package require import ( "encoding/json" "errors" "testing" "time" ) // AssertionTesterInterface defines an interface to be used for testing assertion methods type AssertionTesterInterface interface { TestMethod() } // AssertionTesterConformingObject is an object that conforms to the AssertionTesterInterface interface type AssertionTesterConformingObject struct { } func (a *AssertionTesterConformingObject) TestMethod() { } // AssertionTesterNonConformingObject is an object that does not conform to the AssertionTesterInterface interface type AssertionTesterNonConformingObject struct { } type MockT struct { Failed bool } func (t *MockT) FailNow() { t.Failed = true } func (t *MockT) Errorf(format string, args ...interface{}) { _, _ = format, args } func TestImplements(t *testing.T) { Implements(t, (*AssertionTesterInterface)(nil), new(AssertionTesterConformingObject)) mockT := new(MockT) Implements(mockT, (*AssertionTesterInterface)(nil), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestIsType(t *testing.T) { IsType(t, new(AssertionTesterConformingObject), new(AssertionTesterConformingObject)) mockT := new(MockT) IsType(mockT, new(AssertionTesterConformingObject), new(AssertionTesterNonConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestEqual(t *testing.T) { Equal(t, 1, 1) mockT := new(MockT) Equal(mockT, 1, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestNotEqual(t *testing.T) { NotEqual(t, 1, 2) mockT := new(MockT) NotEqual(mockT, 2, 2) if !mockT.Failed { t.Error("Check should fail") } } func TestExactly(t *testing.T) { a := float32(1) b := float32(1) c := float64(1) Exactly(t, a, b) mockT := new(MockT) Exactly(mockT, a, c) if !mockT.Failed { t.Error("Check should fail") } } func TestNotNil(t *testing.T) { NotNil(t, new(AssertionTesterConformingObject)) mockT := new(MockT) NotNil(mockT, nil) if !mockT.Failed { t.Error("Check should fail") } } func TestNil(t *testing.T) { Nil(t, nil) mockT := new(MockT) Nil(mockT, new(AssertionTesterConformingObject)) if !mockT.Failed { t.Error("Check should fail") } } func TestTrue(t *testing.T) { True(t, true) mockT := new(MockT) True(mockT, false) if !mockT.Failed { t.Error("Check should fail") } } func TestFalse(t *testing.T) { False(t, false) mockT := new(MockT) False(mockT, true) if !mockT.Failed { t.Error("Check should fail") } } func TestContains(t *testing.T) { Contains(t, "Hello World", "Hello") mockT := new(MockT) Contains(mockT, "Hello World", "Salut") if !mockT.Failed { t.Error("Check should fail") } } func TestNotContains(t *testing.T) { NotContains(t, "Hello World", "Hello!") mockT := new(MockT) NotContains(mockT, "Hello World", "Hello") if !mockT.Failed { t.Error("Check should fail") } } func TestPanics(t *testing.T) { Panics(t, func() { panic("Panic!") }) mockT := new(MockT) Panics(mockT, func() {}) if !mockT.Failed { t.Error("Check should fail") } } func TestNotPanics(t *testing.T) { NotPanics(t, func() {}) mockT := new(MockT) NotPanics(mockT, func() { panic("Panic!") }) if !mockT.Failed { t.Error("Check should fail") } } func TestNoError(t *testing.T) { NoError(t, nil) mockT := new(MockT) NoError(mockT, errors.New("some error")) if !mockT.Failed { t.Error("Check should fail") } } func TestError(t *testing.T) { Error(t, errors.New("some error")) mockT := new(MockT) Error(mockT, nil) if !mockT.Failed { t.Error("Check should fail") } } func TestEqualError(t *testing.T) { EqualError(t, errors.New("some error"), "some error") mockT := new(MockT) EqualError(mockT, errors.New("some error"), "Not some error") if !mockT.Failed { t.Error("Check should fail") } } func TestEmpty(t *testing.T) { Empty(t, "") mockT := new(MockT) Empty(mockT, "x") if !mockT.Failed { t.Error("Check should fail") } } func TestNotEmpty(t *testing.T) { NotEmpty(t, "x") mockT := new(MockT) NotEmpty(mockT, "") if !mockT.Failed { t.Error("Check should fail") } } func TestWithinDuration(t *testing.T) { a := time.Now() b := a.Add(10 * time.Second) WithinDuration(t, a, b, 15*time.Second) mockT := new(MockT) WithinDuration(mockT, a, b, 5*time.Second) if !mockT.Failed { t.Error("Check should fail") } } func TestInDelta(t *testing.T) { InDelta(t, 1.001, 1, 0.01) mockT := new(MockT) InDelta(mockT, 1, 2, 0.5) if !mockT.Failed { t.Error("Check should fail") } } func TestZero(t *testing.T) { Zero(t, "") mockT := new(MockT) Zero(mockT, "x") if !mockT.Failed { t.Error("Check should fail") } } func TestNotZero(t *testing.T) { NotZero(t, "x") mockT := new(MockT) NotZero(mockT, "") if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEq_EqualSONString(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"hello": "world", "foo": "bar"}`) if mockT.Failed { t.Error("Check should pass") } } func TestJSONEq_EquivalentButNotEqual(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) if mockT.Failed { t.Error("Check should pass") } } func TestJSONEq_HashOfArraysAndHashes(t *testing.T) { mockT := new(MockT) JSONEq(mockT, "{\r\n\t\"numeric\": 1.5,\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]],\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\"\r\n}", "{\r\n\t\"numeric\": 1.5,\r\n\t\"hash\": {\"nested\": \"hash\", \"nested_slice\": [\"this\", \"is\", \"nested\"]},\r\n\t\"string\": \"foo\",\r\n\t\"array\": [{\"foo\": \"bar\"}, 1, \"string\", [\"nested\", \"array\", 5.5]]\r\n}") if mockT.Failed { t.Error("Check should pass") } } func TestJSONEq_Array(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `["foo", {"nested": "hash", "hello": "world"}]`) if mockT.Failed { t.Error("Check should pass") } } func TestJSONEq_HashAndArrayNotEquivalent(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `{"foo": "bar", {"nested": "hash", "hello": "world"}}`) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEq_HashesNotEquivalent(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `{"foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEq_ActualIsNotJSON(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `{"foo": "bar"}`, "Not JSON") if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEq_ExpectedIsNotJSON(t *testing.T) { mockT := new(MockT) JSONEq(mockT, "Not JSON", `{"foo": "bar", "hello": "world"}`) if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEq_ExpectedAndActualNotJSON(t *testing.T) { mockT := new(MockT) JSONEq(mockT, "Not JSON", "Not JSON") if !mockT.Failed { t.Error("Check should fail") } } func TestJSONEq_ArraysOfDifferentOrder(t *testing.T) { mockT := new(MockT) JSONEq(mockT, `["foo", {"hello": "world", "nested": "hash"}]`, `[{ "hello": "world", "nested": "hash"}, "foo"]`) if !mockT.Failed { t.Error("Check should fail") } } func ExampleComparisonAssertionFunc() { t := &testing.T{} // provided by test adder := func(x, y int) int { return x + y } type args struct { x int y int } tests := []struct { name string args args expect int assertion ComparisonAssertionFunc }{ {"2+2=4", args{2, 2}, 4, Equal}, {"2+2!=5", args{2, 2}, 5, NotEqual}, {"2+3==5", args{2, 3}, 5, Exactly}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, tt.expect, adder(tt.args.x, tt.args.y)) }) } } func TestComparisonAssertionFunc(t *testing.T) { type iface interface { Name() string } tests := []struct { name string expect interface{} got interface{} assertion ComparisonAssertionFunc }{ {"implements", (*iface)(nil), t, Implements}, {"isType", (*testing.T)(nil), t, IsType}, {"equal", t, t, Equal}, {"equalValues", t, t, EqualValues}, {"exactly", t, t, Exactly}, {"notEqual", t, nil, NotEqual}, {"notContains", []int{1, 2, 3}, 4, NotContains}, {"subset", []int{1, 2, 3, 4}, []int{2, 3}, Subset}, {"notSubset", []int{1, 2, 3, 4}, []int{0, 3}, NotSubset}, {"elementsMatch", []byte("abc"), []byte("bac"), ElementsMatch}, {"regexp", "^t.*y$", "testify", Regexp}, {"notRegexp", "^t.*y$", "Testify", NotRegexp}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, tt.expect, tt.got) }) } } func ExampleValueAssertionFunc() { t := &testing.T{} // provided by test dumbParse := func(input string) interface{} { var x interface{} json.Unmarshal([]byte(input), &x) return x } tests := []struct { name string arg string assertion ValueAssertionFunc }{ {"true is not nil", "true", NotNil}, {"empty string is nil", "", Nil}, {"zero is not nil", "0", NotNil}, {"zero is zero", "0", Zero}, {"false is zero", "false", Zero}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, dumbParse(tt.arg)) }) } } func TestValueAssertionFunc(t *testing.T) { tests := []struct { name string value interface{} assertion ValueAssertionFunc }{ {"notNil", true, NotNil}, {"nil", nil, Nil}, {"empty", []int{}, Empty}, {"notEmpty", []int{1}, NotEmpty}, {"zero", false, Zero}, {"notZero", 42, NotZero}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, tt.value) }) } } func ExampleBoolAssertionFunc() { t := &testing.T{} // provided by test isOkay := func(x int) bool { return x >= 42 } tests := []struct { name string arg int assertion BoolAssertionFunc }{ {"-1 is bad", -1, False}, {"42 is good", 42, True}, {"41 is bad", 41, False}, {"45 is cool", 45, True}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, isOkay(tt.arg)) }) } } func TestBoolAssertionFunc(t *testing.T) { tests := []struct { name string value bool assertion BoolAssertionFunc }{ {"true", true, True}, {"false", false, False}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, tt.value) }) } } func ExampleErrorAssertionFunc() { t := &testing.T{} // provided by test dumbParseNum := func(input string, v interface{}) error { return json.Unmarshal([]byte(input), v) } tests := []struct { name string arg string assertion ErrorAssertionFunc }{ {"1.2 is number", "1.2", NoError}, {"1.2.3 not number", "1.2.3", Error}, {"true is not number", "true", Error}, {"3 is number", "3", NoError}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var x float64 tt.assertion(t, dumbParseNum(tt.arg, &x)) }) } } func TestErrorAssertionFunc(t *testing.T) { tests := []struct { name string err error assertion ErrorAssertionFunc }{ {"noError", nil, NoError}, {"error", errors.New("whoops"), Error}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.assertion(t, tt.err) }) } } ================================================ FILE: src/github.com/stretchr/testify/suite/doc.go ================================================ // Package suite contains logic for creating testing suite structs // and running the methods on those structs as tests. The most useful // piece of this package is that you can create setup/teardown methods // on your testing suites, which will run before/after the whole suite // or individual tests (depending on which interface(s) you // implement). // // A testing suite is usually built by first extending the built-in // suite functionality from suite.Suite in testify. Alternatively, // you could reproduce that logic on your own if you wanted (you // just need to implement the TestingSuite interface from // suite/interfaces.go). // // After that, you can implement any of the interfaces in // suite/interfaces.go to add setup/teardown functionality to your // suite, and add any methods that start with "Test" to add tests. // Methods that do not match any suite interfaces and do not begin // with "Test" will not be run by testify, and can safely be used as // helper methods. // // Once you've built your testing suite, you need to run the suite // (using suite.Run from testify) inside any function that matches the // identity that "go test" is already looking for (i.e. // func(*testing.T)). // // Regular expression to select test suites specified command-line // argument "-run". Regular expression to select the methods // of test suites specified command-line argument "-m". // Suite object has assertion methods. // // A crude example: // // Basic imports // import ( // "testing" // "github.com/stretchr/testify/assert" // "github.com/stretchr/testify/suite" // ) // // // Define the suite, and absorb the built-in basic suite // // functionality from testify - including a T() method which // // returns the current testing context // type ExampleTestSuite struct { // suite.Suite // VariableThatShouldStartAtFive int // } // // // Make sure that VariableThatShouldStartAtFive is set to five // // before each test // func (suite *ExampleTestSuite) SetupTest() { // suite.VariableThatShouldStartAtFive = 5 // } // // // All methods that begin with "Test" are run as tests within a // // suite. // func (suite *ExampleTestSuite) TestExample() { // assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) // suite.Equal(5, suite.VariableThatShouldStartAtFive) // } // // // In order for 'go test' to run this suite, we need to create // // a normal test function and pass our suite to suite.Run // func TestExampleTestSuite(t *testing.T) { // suite.Run(t, new(ExampleTestSuite)) // } package suite ================================================ FILE: src/github.com/stretchr/testify/suite/interfaces.go ================================================ package suite import "testing" // TestingSuite can store and return the current *testing.T context // generated by 'go test'. type TestingSuite interface { T() *testing.T SetT(*testing.T) } // SetupAllSuite has a SetupSuite method, which will run before the // tests in the suite are run. type SetupAllSuite interface { SetupSuite() } // SetupTestSuite has a SetupTest method, which will run before each // test in the suite. type SetupTestSuite interface { SetupTest() } // TearDownAllSuite has a TearDownSuite method, which will run after // all the tests in the suite have been run. type TearDownAllSuite interface { TearDownSuite() } // TearDownTestSuite has a TearDownTest method, which will run after // each test in the suite. type TearDownTestSuite interface { TearDownTest() } // BeforeTest has a function to be executed right before the test // starts and receives the suite and test names as input type BeforeTest interface { BeforeTest(suiteName, testName string) } // AfterTest has a function to be executed right after the test // finishes and receives the suite and test names as input type AfterTest interface { AfterTest(suiteName, testName string) } ================================================ FILE: src/github.com/stretchr/testify/suite/suite.go ================================================ package suite import ( "flag" "fmt" "os" "reflect" "regexp" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) var allTestsFilter = func(_, _ string) (bool, error) { return true, nil } var matchMethod = flag.String("testify.m", "", "regular expression to select tests of the testify suite to run") // Suite is a basic testing suite with methods for storing and // retrieving the current *testing.T context. type Suite struct { *assert.Assertions require *require.Assertions t *testing.T } // T retrieves the current *testing.T context. func (suite *Suite) T() *testing.T { return suite.t } // SetT sets the current *testing.T context. func (suite *Suite) SetT(t *testing.T) { suite.t = t suite.Assertions = assert.New(t) suite.require = require.New(t) } // Require returns a require context for suite. func (suite *Suite) Require() *require.Assertions { if suite.require == nil { suite.require = require.New(suite.T()) } return suite.require } // Assert returns an assert context for suite. Normally, you can call // `suite.NoError(expected, actual)`, but for situations where the embedded // methods are overridden (for example, you might want to override // assert.Assertions with require.Assertions), this method is provided so you // can call `suite.Assert().NoError()`. func (suite *Suite) Assert() *assert.Assertions { if suite.Assertions == nil { suite.Assertions = assert.New(suite.T()) } return suite.Assertions } // Run takes a testing suite and runs all of the tests attached // to it. func Run(t *testing.T, suite TestingSuite) { suite.SetT(t) if setupAllSuite, ok := suite.(SetupAllSuite); ok { setupAllSuite.SetupSuite() } defer func() { if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok { tearDownAllSuite.TearDownSuite() } }() methodFinder := reflect.TypeOf(suite) tests := []testing.InternalTest{} for index := 0; index < methodFinder.NumMethod(); index++ { method := methodFinder.Method(index) ok, err := methodFilter(method.Name) if err != nil { fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err) os.Exit(1) } if ok { test := testing.InternalTest{ Name: method.Name, F: func(t *testing.T) { parentT := suite.T() suite.SetT(t) if setupTestSuite, ok := suite.(SetupTestSuite); ok { setupTestSuite.SetupTest() } if beforeTestSuite, ok := suite.(BeforeTest); ok { beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name) } defer func() { if afterTestSuite, ok := suite.(AfterTest); ok { afterTestSuite.AfterTest(methodFinder.Elem().Name(), method.Name) } if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok { tearDownTestSuite.TearDownTest() } suite.SetT(parentT) }() method.Func.Call([]reflect.Value{reflect.ValueOf(suite)}) }, } tests = append(tests, test) } } runTests(t, tests) } func runTests(t testing.TB, tests []testing.InternalTest) { r, ok := t.(runner) if !ok { // backwards compatibility with Go 1.6 and below if !testing.RunTests(allTestsFilter, tests) { t.Fail() } return } for _, test := range tests { r.Run(test.Name, test.F) } } // Filtering method according to set regular expression // specified command-line argument -m func methodFilter(name string) (bool, error) { if ok, _ := regexp.MatchString("^Test", name); !ok { return false, nil } return regexp.MatchString(*matchMethod, name) } type runner interface { Run(name string, f func(t *testing.T)) bool } ================================================ FILE: src/github.com/stretchr/testify/suite/suite_test.go ================================================ package suite import ( "errors" "io/ioutil" "os" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // SuiteRequireTwice is intended to test the usage of suite.Require in two // different tests type SuiteRequireTwice struct{ Suite } // TestSuiteRequireTwice checks for regressions of issue #149 where // suite.requirements was not initialised in suite.SetT() // A regression would result on these tests panicking rather than failing. func TestSuiteRequireTwice(t *testing.T) { ok := testing.RunTests( allTestsFilter, []testing.InternalTest{{ Name: "TestSuiteRequireTwice", F: func(t *testing.T) { suite := new(SuiteRequireTwice) Run(t, suite) }, }}, ) assert.Equal(t, false, ok) } func (s *SuiteRequireTwice) TestRequireOne() { r := s.Require() r.Equal(1, 2) } func (s *SuiteRequireTwice) TestRequireTwo() { r := s.Require() r.Equal(1, 2) } // This suite is intended to store values to make sure that only // testing-suite-related methods are run. It's also a fully // functional example of a testing suite, using setup/teardown methods // and a helper method that is ignored by testify. To make this look // more like a real world example, all tests in the suite perform some // type of assertion. type SuiteTester struct { // Include our basic suite logic. Suite // Keep counts of how many times each method is run. SetupSuiteRunCount int TearDownSuiteRunCount int SetupTestRunCount int TearDownTestRunCount int TestOneRunCount int TestTwoRunCount int NonTestMethodRunCount int SuiteNameBefore []string TestNameBefore []string SuiteNameAfter []string TestNameAfter []string TimeBefore []time.Time TimeAfter []time.Time } type SuiteSkipTester struct { // Include our basic suite logic. Suite // Keep counts of how many times each method is run. SetupSuiteRunCount int TearDownSuiteRunCount int } // The SetupSuite method will be run by testify once, at the very // start of the testing suite, before any tests are run. func (suite *SuiteTester) SetupSuite() { suite.SetupSuiteRunCount++ } func (suite *SuiteTester) BeforeTest(suiteName, testName string) { suite.SuiteNameBefore = append(suite.SuiteNameBefore, suiteName) suite.TestNameBefore = append(suite.TestNameBefore, testName) suite.TimeBefore = append(suite.TimeBefore, time.Now()) } func (suite *SuiteTester) AfterTest(suiteName, testName string) { suite.SuiteNameAfter = append(suite.SuiteNameAfter, suiteName) suite.TestNameAfter = append(suite.TestNameAfter, testName) suite.TimeAfter = append(suite.TimeAfter, time.Now()) } func (suite *SuiteSkipTester) SetupSuite() { suite.SetupSuiteRunCount++ suite.T().Skip() } // The TearDownSuite method will be run by testify once, at the very // end of the testing suite, after all tests have been run. func (suite *SuiteTester) TearDownSuite() { suite.TearDownSuiteRunCount++ } func (suite *SuiteSkipTester) TearDownSuite() { suite.TearDownSuiteRunCount++ } // The SetupTest method will be run before every test in the suite. func (suite *SuiteTester) SetupTest() { suite.SetupTestRunCount++ } // The TearDownTest method will be run after every test in the suite. func (suite *SuiteTester) TearDownTest() { suite.TearDownTestRunCount++ } // Every method in a testing suite that begins with "Test" will be run // as a test. TestOne is an example of a test. For the purposes of // this example, we've included assertions in the tests, since most // tests will issue assertions. func (suite *SuiteTester) TestOne() { beforeCount := suite.TestOneRunCount suite.TestOneRunCount++ assert.Equal(suite.T(), suite.TestOneRunCount, beforeCount+1) suite.Equal(suite.TestOneRunCount, beforeCount+1) } // TestTwo is another example of a test. func (suite *SuiteTester) TestTwo() { beforeCount := suite.TestTwoRunCount suite.TestTwoRunCount++ assert.NotEqual(suite.T(), suite.TestTwoRunCount, beforeCount) suite.NotEqual(suite.TestTwoRunCount, beforeCount) } func (suite *SuiteTester) TestSkip() { suite.T().Skip() } // NonTestMethod does not begin with "Test", so it will not be run by // testify as a test in the suite. This is useful for creating helper // methods for your tests. func (suite *SuiteTester) NonTestMethod() { suite.NonTestMethodRunCount++ } // TestRunSuite will be run by the 'go test' command, so within it, we // can run our suite using the Run(*testing.T, TestingSuite) function. func TestRunSuite(t *testing.T) { suiteTester := new(SuiteTester) Run(t, suiteTester) // Normally, the test would end here. The following are simply // some assertions to ensure that the Run function is working as // intended - they are not part of the example. // The suite was only run once, so the SetupSuite and TearDownSuite // methods should have each been run only once. assert.Equal(t, suiteTester.SetupSuiteRunCount, 1) assert.Equal(t, suiteTester.TearDownSuiteRunCount, 1) assert.Equal(t, len(suiteTester.SuiteNameAfter), 3) assert.Equal(t, len(suiteTester.SuiteNameBefore), 3) assert.Equal(t, len(suiteTester.TestNameAfter), 3) assert.Equal(t, len(suiteTester.TestNameBefore), 3) assert.Contains(t, suiteTester.TestNameAfter, "TestOne") assert.Contains(t, suiteTester.TestNameAfter, "TestTwo") assert.Contains(t, suiteTester.TestNameAfter, "TestSkip") assert.Contains(t, suiteTester.TestNameBefore, "TestOne") assert.Contains(t, suiteTester.TestNameBefore, "TestTwo") assert.Contains(t, suiteTester.TestNameBefore, "TestSkip") for _, suiteName := range suiteTester.SuiteNameAfter { assert.Equal(t, "SuiteTester", suiteName) } for _, suiteName := range suiteTester.SuiteNameBefore { assert.Equal(t, "SuiteTester", suiteName) } for _, when := range suiteTester.TimeAfter { assert.False(t, when.IsZero()) } for _, when := range suiteTester.TimeBefore { assert.False(t, when.IsZero()) } // There are three test methods (TestOne, TestTwo, and TestSkip), so // the SetupTest and TearDownTest methods (which should be run once for // each test) should have been run three times. assert.Equal(t, suiteTester.SetupTestRunCount, 3) assert.Equal(t, suiteTester.TearDownTestRunCount, 3) // Each test should have been run once. assert.Equal(t, suiteTester.TestOneRunCount, 1) assert.Equal(t, suiteTester.TestTwoRunCount, 1) // Methods that don't match the test method identifier shouldn't // have been run at all. assert.Equal(t, suiteTester.NonTestMethodRunCount, 0) suiteSkipTester := new(SuiteSkipTester) Run(t, suiteSkipTester) // The suite was only run once, so the SetupSuite and TearDownSuite // methods should have each been run only once, even though SetupSuite // called Skip() assert.Equal(t, suiteSkipTester.SetupSuiteRunCount, 1) assert.Equal(t, suiteSkipTester.TearDownSuiteRunCount, 1) } func TestSuiteGetters(t *testing.T) { suite := new(SuiteTester) suite.SetT(t) assert.NotNil(t, suite.Assert()) assert.Equal(t, suite.Assertions, suite.Assert()) assert.NotNil(t, suite.Require()) assert.Equal(t, suite.require, suite.Require()) } type SuiteLoggingTester struct { Suite } func (s *SuiteLoggingTester) TestLoggingPass() { s.T().Log("TESTLOGPASS") } func (s *SuiteLoggingTester) TestLoggingFail() { s.T().Log("TESTLOGFAIL") assert.NotNil(s.T(), nil) // expected to fail } type StdoutCapture struct { oldStdout *os.File readPipe *os.File } func (sc *StdoutCapture) StartCapture() { sc.oldStdout = os.Stdout sc.readPipe, os.Stdout, _ = os.Pipe() } func (sc *StdoutCapture) StopCapture() (string, error) { if sc.oldStdout == nil || sc.readPipe == nil { return "", errors.New("StartCapture not called before StopCapture") } os.Stdout.Close() os.Stdout = sc.oldStdout bytes, err := ioutil.ReadAll(sc.readPipe) if err != nil { return "", err } return string(bytes), nil } func TestSuiteLogging(t *testing.T) { suiteLoggingTester := new(SuiteLoggingTester) capture := StdoutCapture{} internalTest := testing.InternalTest{ Name: "SomeTest", F: func(subT *testing.T) { Run(subT, suiteLoggingTester) }, } capture.StartCapture() testing.RunTests(allTestsFilter, []testing.InternalTest{internalTest}) output, err := capture.StopCapture() require.NoError(t, err, "Got an error trying to capture stdout and stderr!") require.NotEmpty(t, output, "output content must not be empty") // Failed tests' output is always printed assert.Contains(t, output, "TESTLOGFAIL") if testing.Verbose() { // In verbose mode, output from successful tests is also printed assert.Contains(t, output, "TESTLOGPASS") } else { assert.NotContains(t, output, "TESTLOGPASS") } } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/LICENSE ================================================ ISC License Copyright (c) 2012-2016 Dave Collins Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/bypass.go ================================================ // Copyright (c) 2015-2016 Dave Collins // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // NOTE: Due to the following build constraints, this file will only be compiled // when the code is not running on Google App Engine, compiled by GopherJS, and // "-tags safe" is not added to the go build command line. The "disableunsafe" // tag is deprecated and thus should not be used. // +build !js,!appengine,!safe,!disableunsafe package spew import ( "reflect" "unsafe" ) const ( // UnsafeDisabled is a build-time constant which specifies whether or // not access to the unsafe package is available. UnsafeDisabled = false // ptrSize is the size of a pointer on the current arch. ptrSize = unsafe.Sizeof((*byte)(nil)) ) var ( // offsetPtr, offsetScalar, and offsetFlag are the offsets for the // internal reflect.Value fields. These values are valid before golang // commit ecccf07e7f9d which changed the format. The are also valid // after commit 82f48826c6c7 which changed the format again to mirror // the original format. Code in the init function updates these offsets // as necessary. offsetPtr = uintptr(ptrSize) offsetScalar = uintptr(0) offsetFlag = uintptr(ptrSize * 2) // flagKindWidth and flagKindShift indicate various bits that the // reflect package uses internally to track kind information. // // flagRO indicates whether or not the value field of a reflect.Value is // read-only. // // flagIndir indicates whether the value field of a reflect.Value is // the actual data or a pointer to the data. // // These values are valid before golang commit 90a7c3c86944 which // changed their positions. Code in the init function updates these // flags as necessary. flagKindWidth = uintptr(5) flagKindShift = uintptr(flagKindWidth - 1) flagRO = uintptr(1 << 0) flagIndir = uintptr(1 << 1) ) func init() { // Older versions of reflect.Value stored small integers directly in the // ptr field (which is named val in the older versions). Versions // between commits ecccf07e7f9d and 82f48826c6c7 added a new field named // scalar for this purpose which unfortunately came before the flag // field, so the offset of the flag field is different for those // versions. // // This code constructs a new reflect.Value from a known small integer // and checks if the size of the reflect.Value struct indicates it has // the scalar field. When it does, the offsets are updated accordingly. vv := reflect.ValueOf(0xf00) if unsafe.Sizeof(vv) == (ptrSize * 4) { offsetScalar = ptrSize * 2 offsetFlag = ptrSize * 3 } // Commit 90a7c3c86944 changed the flag positions such that the low // order bits are the kind. This code extracts the kind from the flags // field and ensures it's the correct type. When it's not, the flag // order has been changed to the newer format, so the flags are updated // accordingly. upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag) upfv := *(*uintptr)(upf) flagKindMask := uintptr((1<>flagKindShift != uintptr(reflect.Int) { flagKindShift = 0 flagRO = 1 << 5 flagIndir = 1 << 6 // Commit adf9b30e5594 modified the flags to separate the // flagRO flag into two bits which specifies whether or not the // field is embedded. This causes flagIndir to move over a bit // and means that flagRO is the combination of either of the // original flagRO bit and the new bit. // // This code detects the change by extracting what used to be // the indirect bit to ensure it's set. When it's not, the flag // order has been changed to the newer format, so the flags are // updated accordingly. if upfv&flagIndir == 0 { flagRO = 3 << 5 flagIndir = 1 << 7 } } } // unsafeReflectValue converts the passed reflect.Value into a one that bypasses // the typical safety restrictions preventing access to unaddressable and // unexported data. It works by digging the raw pointer to the underlying // value out of the protected value and generating a new unprotected (unsafe) // reflect.Value to it. // // This allows us to check for implementations of the Stringer and error // interfaces to be used for pretty printing ordinarily unaddressable and // inaccessible values such as unexported struct fields. func unsafeReflectValue(v reflect.Value) (rv reflect.Value) { indirects := 1 vt := v.Type() upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr) rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag)) if rvf&flagIndir != 0 { vt = reflect.PtrTo(v.Type()) indirects++ } else if offsetScalar != 0 { // The value is in the scalar field when it's not one of the // reference types. switch vt.Kind() { case reflect.Uintptr: case reflect.Chan: case reflect.Func: case reflect.Map: case reflect.Ptr: case reflect.UnsafePointer: default: upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetScalar) } } pv := reflect.NewAt(vt, upv) rv = pv for i := 0; i < indirects; i++ { rv = rv.Elem() } return rv } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go ================================================ // Copyright (c) 2015-2016 Dave Collins // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // NOTE: Due to the following build constraints, this file will only be compiled // when the code is running on Google App Engine, compiled by GopherJS, or // "-tags safe" is added to the go build command line. The "disableunsafe" // tag is deprecated and thus should not be used. // +build js appengine safe disableunsafe package spew import "reflect" const ( // UnsafeDisabled is a build-time constant which specifies whether or // not access to the unsafe package is available. UnsafeDisabled = true ) // unsafeReflectValue typically converts the passed reflect.Value into a one // that bypasses the typical safety restrictions preventing access to // unaddressable and unexported data. However, doing this relies on access to // the unsafe package. This is a stub version which simply returns the passed // reflect.Value when the unsafe package is not available. func unsafeReflectValue(v reflect.Value) reflect.Value { return v } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/common.go ================================================ /* * Copyright (c) 2013-2016 Dave Collins * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "io" "reflect" "sort" "strconv" ) // Some constants in the form of bytes to avoid string overhead. This mirrors // the technique used in the fmt package. var ( panicBytes = []byte("(PANIC=") plusBytes = []byte("+") iBytes = []byte("i") trueBytes = []byte("true") falseBytes = []byte("false") interfaceBytes = []byte("(interface {})") commaNewlineBytes = []byte(",\n") newlineBytes = []byte("\n") openBraceBytes = []byte("{") openBraceNewlineBytes = []byte("{\n") closeBraceBytes = []byte("}") asteriskBytes = []byte("*") colonBytes = []byte(":") colonSpaceBytes = []byte(": ") openParenBytes = []byte("(") closeParenBytes = []byte(")") spaceBytes = []byte(" ") pointerChainBytes = []byte("->") nilAngleBytes = []byte("") maxNewlineBytes = []byte("\n") maxShortBytes = []byte("") circularBytes = []byte("") circularShortBytes = []byte("") invalidAngleBytes = []byte("") openBracketBytes = []byte("[") closeBracketBytes = []byte("]") percentBytes = []byte("%") precisionBytes = []byte(".") openAngleBytes = []byte("<") closeAngleBytes = []byte(">") openMapBytes = []byte("map[") closeMapBytes = []byte("]") lenEqualsBytes = []byte("len=") capEqualsBytes = []byte("cap=") ) // hexDigits is used to map a decimal value to a hex digit. var hexDigits = "0123456789abcdef" // catchPanic handles any panics that might occur during the handleMethods // calls. func catchPanic(w io.Writer, v reflect.Value) { if err := recover(); err != nil { w.Write(panicBytes) fmt.Fprintf(w, "%v", err) w.Write(closeParenBytes) } } // handleMethods attempts to call the Error and String methods on the underlying // type the passed reflect.Value represents and outputes the result to Writer w. // // It handles panics in any called methods by catching and displaying the error // as the formatted value. func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { // We need an interface to check if the type implements the error or // Stringer interface. However, the reflect package won't give us an // interface on certain things like unexported struct fields in order // to enforce visibility rules. We use unsafe, when it's available, // to bypass these restrictions since this package does not mutate the // values. if !v.CanInterface() { if UnsafeDisabled { return false } v = unsafeReflectValue(v) } // Choose whether or not to do error and Stringer interface lookups against // the base type or a pointer to the base type depending on settings. // Technically calling one of these methods with a pointer receiver can // mutate the value, however, types which choose to satisify an error or // Stringer interface with a pointer receiver should not be mutating their // state inside these interface methods. if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { v = unsafeReflectValue(v) } if v.CanAddr() { v = v.Addr() } // Is it an error or Stringer? switch iface := v.Interface().(type) { case error: defer catchPanic(w, v) if cs.ContinueOnMethod { w.Write(openParenBytes) w.Write([]byte(iface.Error())) w.Write(closeParenBytes) w.Write(spaceBytes) return false } w.Write([]byte(iface.Error())) return true case fmt.Stringer: defer catchPanic(w, v) if cs.ContinueOnMethod { w.Write(openParenBytes) w.Write([]byte(iface.String())) w.Write(closeParenBytes) w.Write(spaceBytes) return false } w.Write([]byte(iface.String())) return true } return false } // printBool outputs a boolean value as true or false to Writer w. func printBool(w io.Writer, val bool) { if val { w.Write(trueBytes) } else { w.Write(falseBytes) } } // printInt outputs a signed integer value to Writer w. func printInt(w io.Writer, val int64, base int) { w.Write([]byte(strconv.FormatInt(val, base))) } // printUint outputs an unsigned integer value to Writer w. func printUint(w io.Writer, val uint64, base int) { w.Write([]byte(strconv.FormatUint(val, base))) } // printFloat outputs a floating point value using the specified precision, // which is expected to be 32 or 64bit, to Writer w. func printFloat(w io.Writer, val float64, precision int) { w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) } // printComplex outputs a complex value using the specified float precision // for the real and imaginary parts to Writer w. func printComplex(w io.Writer, c complex128, floatPrecision int) { r := real(c) w.Write(openParenBytes) w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) i := imag(c) if i >= 0 { w.Write(plusBytes) } w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) w.Write(iBytes) w.Write(closeParenBytes) } // printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x' // prefix to Writer w. func printHexPtr(w io.Writer, p uintptr) { // Null pointer. num := uint64(p) if num == 0 { w.Write(nilAngleBytes) return } // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix buf := make([]byte, 18) // It's simpler to construct the hex string right to left. base := uint64(16) i := len(buf) - 1 for num >= base { buf[i] = hexDigits[num%base] num /= base i-- } buf[i] = hexDigits[num] // Add '0x' prefix. i-- buf[i] = 'x' i-- buf[i] = '0' // Strip unused leading bytes. buf = buf[i:] w.Write(buf) } // valuesSorter implements sort.Interface to allow a slice of reflect.Value // elements to be sorted. type valuesSorter struct { values []reflect.Value strings []string // either nil or same len and values cs *ConfigState } // newValuesSorter initializes a valuesSorter instance, which holds a set of // surrogate keys on which the data should be sorted. It uses flags in // ConfigState to decide if and how to populate those surrogate keys. func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { vs := &valuesSorter{values: values, cs: cs} if canSortSimply(vs.values[0].Kind()) { return vs } if !cs.DisableMethods { vs.strings = make([]string, len(values)) for i := range vs.values { b := bytes.Buffer{} if !handleMethods(cs, &b, vs.values[i]) { vs.strings = nil break } vs.strings[i] = b.String() } } if vs.strings == nil && cs.SpewKeys { vs.strings = make([]string, len(values)) for i := range vs.values { vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) } } return vs } // canSortSimply tests whether a reflect.Kind is a primitive that can be sorted // directly, or whether it should be considered for sorting by surrogate keys // (if the ConfigState allows it). func canSortSimply(kind reflect.Kind) bool { // This switch parallels valueSortLess, except for the default case. switch kind { case reflect.Bool: return true case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return true case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: return true case reflect.Float32, reflect.Float64: return true case reflect.String: return true case reflect.Uintptr: return true case reflect.Array: return true } return false } // Len returns the number of values in the slice. It is part of the // sort.Interface implementation. func (s *valuesSorter) Len() int { return len(s.values) } // Swap swaps the values at the passed indices. It is part of the // sort.Interface implementation. func (s *valuesSorter) Swap(i, j int) { s.values[i], s.values[j] = s.values[j], s.values[i] if s.strings != nil { s.strings[i], s.strings[j] = s.strings[j], s.strings[i] } } // valueSortLess returns whether the first value should sort before the second // value. It is used by valueSorter.Less as part of the sort.Interface // implementation. func valueSortLess(a, b reflect.Value) bool { switch a.Kind() { case reflect.Bool: return !a.Bool() && b.Bool() case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: return a.Int() < b.Int() case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: return a.Uint() < b.Uint() case reflect.Float32, reflect.Float64: return a.Float() < b.Float() case reflect.String: return a.String() < b.String() case reflect.Uintptr: return a.Uint() < b.Uint() case reflect.Array: // Compare the contents of both arrays. l := a.Len() for i := 0; i < l; i++ { av := a.Index(i) bv := b.Index(i) if av.Interface() == bv.Interface() { continue } return valueSortLess(av, bv) } } return a.String() < b.String() } // Less returns whether the value at index i should sort before the // value at index j. It is part of the sort.Interface implementation. func (s *valuesSorter) Less(i, j int) bool { if s.strings == nil { return valueSortLess(s.values[i], s.values[j]) } return s.strings[i] < s.strings[j] } // sortValues is a sort function that handles both native types and any type that // can be converted to error or Stringer. Other inputs are sorted according to // their Value.String() value to ensure display stability. func sortValues(values []reflect.Value, cs *ConfigState) { if len(values) == 0 { return } sort.Sort(newValuesSorter(values, cs)) } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/config.go ================================================ /* * Copyright (c) 2013-2016 Dave Collins * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "io" "os" ) // ConfigState houses the configuration options used by spew to format and // display values. There is a global instance, Config, that is used to control // all top-level Formatter and Dump functionality. Each ConfigState instance // provides methods equivalent to the top-level functions. // // The zero value for ConfigState provides no indentation. You would typically // want to set it to a space or a tab. // // Alternatively, you can use NewDefaultConfig to get a ConfigState instance // with default settings. See the documentation of NewDefaultConfig for default // values. type ConfigState struct { // Indent specifies the string to use for each indentation level. The // global config instance that all top-level functions use set this to a // single space by default. If you would like more indentation, you might // set this to a tab with "\t" or perhaps two spaces with " ". Indent string // MaxDepth controls the maximum number of levels to descend into nested // data structures. The default, 0, means there is no limit. // // NOTE: Circular data structures are properly detected, so it is not // necessary to set this value unless you specifically want to limit deeply // nested data structures. MaxDepth int // DisableMethods specifies whether or not error and Stringer interfaces are // invoked for types that implement them. DisableMethods bool // DisablePointerMethods specifies whether or not to check for and invoke // error and Stringer interfaces on types which only accept a pointer // receiver when the current type is not a pointer. // // NOTE: This might be an unsafe action since calling one of these methods // with a pointer receiver could technically mutate the value, however, // in practice, types which choose to satisify an error or Stringer // interface with a pointer receiver should not be mutating their state // inside these interface methods. As a result, this option relies on // access to the unsafe package, so it will not have any effect when // running in environments without access to the unsafe package such as // Google App Engine or with the "safe" build tag specified. DisablePointerMethods bool // DisablePointerAddresses specifies whether to disable the printing of // pointer addresses. This is useful when diffing data structures in tests. DisablePointerAddresses bool // DisableCapacities specifies whether to disable the printing of capacities // for arrays, slices, maps and channels. This is useful when diffing // data structures in tests. DisableCapacities bool // ContinueOnMethod specifies whether or not recursion should continue once // a custom error or Stringer interface is invoked. The default, false, // means it will print the results of invoking the custom error or Stringer // interface and return immediately instead of continuing to recurse into // the internals of the data type. // // NOTE: This flag does not have any effect if method invocation is disabled // via the DisableMethods or DisablePointerMethods options. ContinueOnMethod bool // SortKeys specifies map keys should be sorted before being printed. Use // this to have a more deterministic, diffable output. Note that only // native types (bool, int, uint, floats, uintptr and string) and types // that support the error or Stringer interfaces (if methods are // enabled) are supported, with other types sorted according to the // reflect.Value.String() output which guarantees display stability. SortKeys bool // SpewKeys specifies that, as a last resort attempt, map keys should // be spewed to strings and sorted by those strings. This is only // considered if SortKeys is true. SpewKeys bool } // Config is the active configuration of the top-level functions. // The configuration can be changed by modifying the contents of spew.Config. var Config = ConfigState{Indent: " "} // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the formatted string as a value that satisfies error. See NewFormatter // for formatting details. // // This function is shorthand for the following syntax: // // fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { return fmt.Errorf(format, c.convertArgs(a)...) } // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprint(w, c.convertArgs(a)...) } // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { return fmt.Fprintf(w, format, c.convertArgs(a)...) } // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it // passed with a Formatter interface returned by c.NewFormatter. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprintln(w, c.convertArgs(a)...) } // Print is a wrapper for fmt.Print that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Print(a ...interface{}) (n int, err error) { return fmt.Print(c.convertArgs(a)...) } // Printf is a wrapper for fmt.Printf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format, c.convertArgs(a)...) } // Println is a wrapper for fmt.Println that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Println(a ...interface{}) (n int, err error) { return fmt.Println(c.convertArgs(a)...) } // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Sprint(a ...interface{}) string { return fmt.Sprint(c.convertArgs(a)...) } // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were // passed with a Formatter interface returned by c.NewFormatter. It returns // the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Sprintf(format string, a ...interface{}) string { return fmt.Sprintf(format, c.convertArgs(a)...) } // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it // were passed with a Formatter interface returned by c.NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) func (c *ConfigState) Sprintln(a ...interface{}) string { return fmt.Sprintln(c.convertArgs(a)...) } /* NewFormatter returns a custom formatter that satisfies the fmt.Formatter interface. As a result, it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Typically this function shouldn't be called directly. It is much easier to make use of the custom formatter by calling one of the convenience functions such as c.Printf, c.Println, or c.Printf. */ func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { return newFormatter(c, v) } // Fdump formats and displays the passed arguments to io.Writer w. It formats // exactly the same as Dump. func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { fdump(c, w, a...) } /* Dump displays the passed parameters to standard out with newlines, customizable indentation, and additional debug information such as complete types and all pointer addresses used to indirect to the final value. It provides the following features over the built-in printing facilities provided by the fmt package: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output The configuration options are controlled by modifying the public members of c. See ConfigState for options documentation. See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to get the formatted result as a string. */ func (c *ConfigState) Dump(a ...interface{}) { fdump(c, os.Stdout, a...) } // Sdump returns a string with the passed arguments formatted exactly the same // as Dump. func (c *ConfigState) Sdump(a ...interface{}) string { var buf bytes.Buffer fdump(c, &buf, a...) return buf.String() } // convertArgs accepts a slice of arguments and returns a slice of the same // length with each argument converted to a spew Formatter interface using // the ConfigState associated with s. func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { formatters = make([]interface{}, len(args)) for index, arg := range args { formatters[index] = newFormatter(c, arg) } return formatters } // NewDefaultConfig returns a ConfigState with the following default settings. // // Indent: " " // MaxDepth: 0 // DisableMethods: false // DisablePointerMethods: false // ContinueOnMethod: false // SortKeys: false func NewDefaultConfig() *ConfigState { return &ConfigState{Indent: " "} } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/doc.go ================================================ /* * Copyright (c) 2013-2016 Dave Collins * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* Package spew implements a deep pretty printer for Go data structures to aid in debugging. A quick overview of the additional features spew provides over the built-in printing facilities for Go data types are as follows: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output (only when using Dump style) There are two different approaches spew allows for dumping Go data structures: * Dump style which prints with newlines, customizable indentation, and additional debug information such as types and all pointer addresses used to indirect to the final value * A custom Formatter interface that integrates cleanly with the standard fmt package and replaces %v, %+v, %#v, and %#+v to provide inline printing similar to the default %v while providing the additional functionality outlined above and passing unsupported format verbs such as %x and %q along to fmt Quick Start This section demonstrates how to quickly get started with spew. See the sections below for further details on formatting and configuration options. To dump a variable with full newlines, indentation, type, and pointer information use Dump, Fdump, or Sdump: spew.Dump(myVar1, myVar2, ...) spew.Fdump(someWriter, myVar1, myVar2, ...) str := spew.Sdump(myVar1, myVar2, ...) Alternatively, if you would prefer to use format strings with a compacted inline printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses): spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) Configuration Options Configuration of spew is handled by fields in the ConfigState type. For convenience, all of the top-level functions use a global state available via the spew.Config global. It is also possible to create a ConfigState instance that provides methods equivalent to the top-level functions. This allows concurrent configuration options. See the ConfigState documentation for more details. The following configuration options are available: * Indent String to use for each indentation level for Dump functions. It is a single space by default. A popular alternative is "\t". * MaxDepth Maximum number of levels to descend into nested data structures. There is no limit by default. * DisableMethods Disables invocation of error and Stringer interface methods. Method invocation is enabled by default. * DisablePointerMethods Disables invocation of error and Stringer interface methods on types which only accept pointer receivers from non-pointer variables. Pointer method invocation is enabled by default. * DisablePointerAddresses DisablePointerAddresses specifies whether to disable the printing of pointer addresses. This is useful when diffing data structures in tests. * DisableCapacities DisableCapacities specifies whether to disable the printing of capacities for arrays, slices, maps and channels. This is useful when diffing data structures in tests. * ContinueOnMethod Enables recursion into types after invoking error and Stringer interface methods. Recursion after method invocation is disabled by default. * SortKeys Specifies map keys should be sorted before being printed. Use this to have a more deterministic, diffable output. Note that only native types (bool, int, uint, floats, uintptr and string) and types which implement error or Stringer interfaces are supported with other types sorted according to the reflect.Value.String() output which guarantees display stability. Natural map order is used by default. * SpewKeys Specifies that, as a last resort attempt, map keys should be spewed to strings and sorted by those strings. This is only considered if SortKeys is true. Dump Usage Simply call spew.Dump with a list of variables you want to dump: spew.Dump(myVar1, myVar2, ...) You may also call spew.Fdump if you would prefer to output to an arbitrary io.Writer. For example, to dump to standard error: spew.Fdump(os.Stderr, myVar1, myVar2, ...) A third option is to call spew.Sdump to get the formatted output as a string: str := spew.Sdump(myVar1, myVar2, ...) Sample Dump Output See the Dump example for details on the setup of the types and variables being shown here. (main.Foo) { unexportedField: (*main.Bar)(0xf84002e210)({ flag: (main.Flag) flagTwo, data: (uintptr) }), ExportedField: (map[interface {}]interface {}) (len=1) { (string) (len=3) "one": (bool) true } } Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C command as shown. ([]uint8) (len=32 cap=32) { 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| 00000020 31 32 |12| } Custom Formatter Spew provides a custom formatter that implements the fmt.Formatter interface so that it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Custom Formatter Usage The simplest way to make use of the spew custom formatter is to call one of the convenience functions such as spew.Printf, spew.Println, or spew.Printf. The functions have syntax you are most likely already familiar with: spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) spew.Println(myVar, myVar2) spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) See the Index for the full list convenience functions. Sample Formatter Output Double pointer to a uint8: %v: <**>5 %+v: <**>(0xf8400420d0->0xf8400420c8)5 %#v: (**uint8)5 %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 Pointer to circular struct with a uint8 field and a pointer to itself: %v: <*>{1 <*>} %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} See the Printf example for details on the setup of variables being shown here. Errors Since it is possible for custom Stringer/error interfaces to panic, spew detects them and handles them internally by printing the panic information inline with the output. Since spew is intended to provide deep pretty printing capabilities on structures, it intentionally does not return any errors. */ package spew ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/dump.go ================================================ /* * Copyright (c) 2013-2016 Dave Collins * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "encoding/hex" "fmt" "io" "os" "reflect" "regexp" "strconv" "strings" ) var ( // uint8Type is a reflect.Type representing a uint8. It is used to // convert cgo types to uint8 slices for hexdumping. uint8Type = reflect.TypeOf(uint8(0)) // cCharRE is a regular expression that matches a cgo char. // It is used to detect character arrays to hexdump them. cCharRE = regexp.MustCompile("^.*\\._Ctype_char$") // cUnsignedCharRE is a regular expression that matches a cgo unsigned // char. It is used to detect unsigned character arrays to hexdump // them. cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$") // cUint8tCharRE is a regular expression that matches a cgo uint8_t. // It is used to detect uint8_t arrays to hexdump them. cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$") ) // dumpState contains information about the state of a dump operation. type dumpState struct { w io.Writer depth int pointers map[uintptr]int ignoreNextType bool ignoreNextIndent bool cs *ConfigState } // indent performs indentation according to the depth level and cs.Indent // option. func (d *dumpState) indent() { if d.ignoreNextIndent { d.ignoreNextIndent = false return } d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) } // unpackValue returns values inside of non-nil interfaces when possible. // This is useful for data types like structs, arrays, slices, and maps which // can contain varying types packed inside an interface. func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface && !v.IsNil() { v = v.Elem() } return v } // dumpPtr handles formatting of pointers by indirecting them as necessary. func (d *dumpState) dumpPtr(v reflect.Value) { // Remove pointers at or below the current depth from map used to detect // circular refs. for k, depth := range d.pointers { if depth >= d.depth { delete(d.pointers, k) } } // Keep list of all dereferenced pointers to show later. pointerChain := make([]uintptr, 0) // Figure out how many levels of indirection there are by dereferencing // pointers and unpacking interfaces down the chain while detecting circular // references. nilFound := false cycleFound := false indirects := 0 ve := v for ve.Kind() == reflect.Ptr { if ve.IsNil() { nilFound = true break } indirects++ addr := ve.Pointer() pointerChain = append(pointerChain, addr) if pd, ok := d.pointers[addr]; ok && pd < d.depth { cycleFound = true indirects-- break } d.pointers[addr] = d.depth ve = ve.Elem() if ve.Kind() == reflect.Interface { if ve.IsNil() { nilFound = true break } ve = ve.Elem() } } // Display type information. d.w.Write(openParenBytes) d.w.Write(bytes.Repeat(asteriskBytes, indirects)) d.w.Write([]byte(ve.Type().String())) d.w.Write(closeParenBytes) // Display pointer information. if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { d.w.Write(openParenBytes) for i, addr := range pointerChain { if i > 0 { d.w.Write(pointerChainBytes) } printHexPtr(d.w, addr) } d.w.Write(closeParenBytes) } // Display dereferenced value. d.w.Write(openParenBytes) switch { case nilFound == true: d.w.Write(nilAngleBytes) case cycleFound == true: d.w.Write(circularBytes) default: d.ignoreNextType = true d.dump(ve) } d.w.Write(closeParenBytes) } // dumpSlice handles formatting of arrays and slices. Byte (uint8 under // reflection) arrays and slices are dumped in hexdump -C fashion. func (d *dumpState) dumpSlice(v reflect.Value) { // Determine whether this type should be hex dumped or not. Also, // for types which should be hexdumped, try to use the underlying data // first, then fall back to trying to convert them to a uint8 slice. var buf []uint8 doConvert := false doHexDump := false numEntries := v.Len() if numEntries > 0 { vt := v.Index(0).Type() vts := vt.String() switch { // C types that need to be converted. case cCharRE.MatchString(vts): fallthrough case cUnsignedCharRE.MatchString(vts): fallthrough case cUint8tCharRE.MatchString(vts): doConvert = true // Try to use existing uint8 slices and fall back to converting // and copying if that fails. case vt.Kind() == reflect.Uint8: // We need an addressable interface to convert the type // to a byte slice. However, the reflect package won't // give us an interface on certain things like // unexported struct fields in order to enforce // visibility rules. We use unsafe, when available, to // bypass these restrictions since this package does not // mutate the values. vs := v if !vs.CanInterface() || !vs.CanAddr() { vs = unsafeReflectValue(vs) } if !UnsafeDisabled { vs = vs.Slice(0, numEntries) // Use the existing uint8 slice if it can be // type asserted. iface := vs.Interface() if slice, ok := iface.([]uint8); ok { buf = slice doHexDump = true break } } // The underlying data needs to be converted if it can't // be type asserted to a uint8 slice. doConvert = true } // Copy and convert the underlying type if needed. if doConvert && vt.ConvertibleTo(uint8Type) { // Convert and copy each element into a uint8 byte // slice. buf = make([]uint8, numEntries) for i := 0; i < numEntries; i++ { vv := v.Index(i) buf[i] = uint8(vv.Convert(uint8Type).Uint()) } doHexDump = true } } // Hexdump the entire slice as needed. if doHexDump { indent := strings.Repeat(d.cs.Indent, d.depth) str := indent + hex.Dump(buf) str = strings.Replace(str, "\n", "\n"+indent, -1) str = strings.TrimRight(str, d.cs.Indent) d.w.Write([]byte(str)) return } // Recursively call dump for each item. for i := 0; i < numEntries; i++ { d.dump(d.unpackValue(v.Index(i))) if i < (numEntries - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } // dump is the main workhorse for dumping a value. It uses the passed reflect // value to figure out what kind of object we are dealing with and formats it // appropriately. It is a recursive function, however circular data structures // are detected and handled properly. func (d *dumpState) dump(v reflect.Value) { // Handle invalid reflect values immediately. kind := v.Kind() if kind == reflect.Invalid { d.w.Write(invalidAngleBytes) return } // Handle pointers specially. if kind == reflect.Ptr { d.indent() d.dumpPtr(v) return } // Print type information unless already handled elsewhere. if !d.ignoreNextType { d.indent() d.w.Write(openParenBytes) d.w.Write([]byte(v.Type().String())) d.w.Write(closeParenBytes) d.w.Write(spaceBytes) } d.ignoreNextType = false // Display length and capacity if the built-in len and cap functions // work with the value's kind and the len/cap itself is non-zero. valueLen, valueCap := 0, 0 switch v.Kind() { case reflect.Array, reflect.Slice, reflect.Chan: valueLen, valueCap = v.Len(), v.Cap() case reflect.Map, reflect.String: valueLen = v.Len() } if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { d.w.Write(openParenBytes) if valueLen != 0 { d.w.Write(lenEqualsBytes) printInt(d.w, int64(valueLen), 10) } if !d.cs.DisableCapacities && valueCap != 0 { if valueLen != 0 { d.w.Write(spaceBytes) } d.w.Write(capEqualsBytes) printInt(d.w, int64(valueCap), 10) } d.w.Write(closeParenBytes) d.w.Write(spaceBytes) } // Call Stringer/error interfaces if they exist and the handle methods flag // is enabled if !d.cs.DisableMethods { if (kind != reflect.Invalid) && (kind != reflect.Interface) { if handled := handleMethods(d.cs, d.w, v); handled { return } } } switch kind { case reflect.Invalid: // Do nothing. We should never get here since invalid has already // been handled above. case reflect.Bool: printBool(d.w, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: printInt(d.w, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: printUint(d.w, v.Uint(), 10) case reflect.Float32: printFloat(d.w, v.Float(), 32) case reflect.Float64: printFloat(d.w, v.Float(), 64) case reflect.Complex64: printComplex(d.w, v.Complex(), 32) case reflect.Complex128: printComplex(d.w, v.Complex(), 64) case reflect.Slice: if v.IsNil() { d.w.Write(nilAngleBytes) break } fallthrough case reflect.Array: d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { d.dumpSlice(v) } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.String: d.w.Write([]byte(strconv.Quote(v.String()))) case reflect.Interface: // The only time we should get here is for nil interfaces due to // unpackValue calls. if v.IsNil() { d.w.Write(nilAngleBytes) } case reflect.Ptr: // Do nothing. We should never get here since pointers have already // been handled above. case reflect.Map: // nil maps should be indicated as different than empty maps if v.IsNil() { d.w.Write(nilAngleBytes) break } d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { numEntries := v.Len() keys := v.MapKeys() if d.cs.SortKeys { sortValues(keys, d.cs) } for i, key := range keys { d.dump(d.unpackValue(key)) d.w.Write(colonSpaceBytes) d.ignoreNextIndent = true d.dump(d.unpackValue(v.MapIndex(key))) if i < (numEntries - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.Struct: d.w.Write(openBraceNewlineBytes) d.depth++ if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { d.indent() d.w.Write(maxNewlineBytes) } else { vt := v.Type() numFields := v.NumField() for i := 0; i < numFields; i++ { d.indent() vtf := vt.Field(i) d.w.Write([]byte(vtf.Name)) d.w.Write(colonSpaceBytes) d.ignoreNextIndent = true d.dump(d.unpackValue(v.Field(i))) if i < (numFields - 1) { d.w.Write(commaNewlineBytes) } else { d.w.Write(newlineBytes) } } } d.depth-- d.indent() d.w.Write(closeBraceBytes) case reflect.Uintptr: printHexPtr(d.w, uintptr(v.Uint())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: printHexPtr(d.w, v.Pointer()) // There were not any other types at the time this code was written, but // fall back to letting the default fmt package handle it in case any new // types are added. default: if v.CanInterface() { fmt.Fprintf(d.w, "%v", v.Interface()) } else { fmt.Fprintf(d.w, "%v", v.String()) } } } // fdump is a helper function to consolidate the logic from the various public // methods which take varying writers and config states. func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { for _, arg := range a { if arg == nil { w.Write(interfaceBytes) w.Write(spaceBytes) w.Write(nilAngleBytes) w.Write(newlineBytes) continue } d := dumpState{w: w, cs: cs} d.pointers = make(map[uintptr]int) d.dump(reflect.ValueOf(arg)) d.w.Write(newlineBytes) } } // Fdump formats and displays the passed arguments to io.Writer w. It formats // exactly the same as Dump. func Fdump(w io.Writer, a ...interface{}) { fdump(&Config, w, a...) } // Sdump returns a string with the passed arguments formatted exactly the same // as Dump. func Sdump(a ...interface{}) string { var buf bytes.Buffer fdump(&Config, &buf, a...) return buf.String() } /* Dump displays the passed parameters to standard out with newlines, customizable indentation, and additional debug information such as complete types and all pointer addresses used to indirect to the final value. It provides the following features over the built-in printing facilities provided by the fmt package: * Pointers are dereferenced and followed * Circular data structures are detected and handled properly * Custom Stringer/error interfaces are optionally invoked, including on unexported types * Custom types which only implement the Stringer/error interfaces via a pointer receiver are optionally invoked when passing non-pointer variables * Byte arrays and slices are dumped like the hexdump -C command which includes offsets, byte values in hex, and ASCII output The configuration options are controlled by an exported package global, spew.Config. See ConfigState for options documentation. See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to get the formatted result as a string. */ func Dump(a ...interface{}) { fdump(&Config, os.Stdout, a...) } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/format.go ================================================ /* * Copyright (c) 2013-2016 Dave Collins * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "bytes" "fmt" "reflect" "strconv" "strings" ) // supportedFlags is a list of all the character flags supported by fmt package. const supportedFlags = "0-+# " // formatState implements the fmt.Formatter interface and contains information // about the state of a formatting operation. The NewFormatter function can // be used to get a new Formatter which can be used directly as arguments // in standard fmt package printing calls. type formatState struct { value interface{} fs fmt.State depth int pointers map[uintptr]int ignoreNextType bool cs *ConfigState } // buildDefaultFormat recreates the original format string without precision // and width information to pass in to fmt.Sprintf in the case of an // unrecognized type. Unless new types are added to the language, this // function won't ever be called. func (f *formatState) buildDefaultFormat() (format string) { buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { if f.fs.Flag(int(flag)) { buf.WriteRune(flag) } } buf.WriteRune('v') format = buf.String() return format } // constructOrigFormat recreates the original format string including precision // and width information to pass along to the standard fmt package. This allows // automatic deferral of all format strings this package doesn't support. func (f *formatState) constructOrigFormat(verb rune) (format string) { buf := bytes.NewBuffer(percentBytes) for _, flag := range supportedFlags { if f.fs.Flag(int(flag)) { buf.WriteRune(flag) } } if width, ok := f.fs.Width(); ok { buf.WriteString(strconv.Itoa(width)) } if precision, ok := f.fs.Precision(); ok { buf.Write(precisionBytes) buf.WriteString(strconv.Itoa(precision)) } buf.WriteRune(verb) format = buf.String() return format } // unpackValue returns values inside of non-nil interfaces when possible and // ensures that types for values which have been unpacked from an interface // are displayed when the show types flag is also set. // This is useful for data types like structs, arrays, slices, and maps which // can contain varying types packed inside an interface. func (f *formatState) unpackValue(v reflect.Value) reflect.Value { if v.Kind() == reflect.Interface { f.ignoreNextType = false if !v.IsNil() { v = v.Elem() } } return v } // formatPtr handles formatting of pointers by indirecting them as necessary. func (f *formatState) formatPtr(v reflect.Value) { // Display nil if top level pointer is nil. showTypes := f.fs.Flag('#') if v.IsNil() && (!showTypes || f.ignoreNextType) { f.fs.Write(nilAngleBytes) return } // Remove pointers at or below the current depth from map used to detect // circular refs. for k, depth := range f.pointers { if depth >= f.depth { delete(f.pointers, k) } } // Keep list of all dereferenced pointers to possibly show later. pointerChain := make([]uintptr, 0) // Figure out how many levels of indirection there are by derferencing // pointers and unpacking interfaces down the chain while detecting circular // references. nilFound := false cycleFound := false indirects := 0 ve := v for ve.Kind() == reflect.Ptr { if ve.IsNil() { nilFound = true break } indirects++ addr := ve.Pointer() pointerChain = append(pointerChain, addr) if pd, ok := f.pointers[addr]; ok && pd < f.depth { cycleFound = true indirects-- break } f.pointers[addr] = f.depth ve = ve.Elem() if ve.Kind() == reflect.Interface { if ve.IsNil() { nilFound = true break } ve = ve.Elem() } } // Display type or indirection level depending on flags. if showTypes && !f.ignoreNextType { f.fs.Write(openParenBytes) f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) f.fs.Write([]byte(ve.Type().String())) f.fs.Write(closeParenBytes) } else { if nilFound || cycleFound { indirects += strings.Count(ve.Type().String(), "*") } f.fs.Write(openAngleBytes) f.fs.Write([]byte(strings.Repeat("*", indirects))) f.fs.Write(closeAngleBytes) } // Display pointer information depending on flags. if f.fs.Flag('+') && (len(pointerChain) > 0) { f.fs.Write(openParenBytes) for i, addr := range pointerChain { if i > 0 { f.fs.Write(pointerChainBytes) } printHexPtr(f.fs, addr) } f.fs.Write(closeParenBytes) } // Display dereferenced value. switch { case nilFound == true: f.fs.Write(nilAngleBytes) case cycleFound == true: f.fs.Write(circularShortBytes) default: f.ignoreNextType = true f.format(ve) } } // format is the main workhorse for providing the Formatter interface. It // uses the passed reflect value to figure out what kind of object we are // dealing with and formats it appropriately. It is a recursive function, // however circular data structures are detected and handled properly. func (f *formatState) format(v reflect.Value) { // Handle invalid reflect values immediately. kind := v.Kind() if kind == reflect.Invalid { f.fs.Write(invalidAngleBytes) return } // Handle pointers specially. if kind == reflect.Ptr { f.formatPtr(v) return } // Print type information unless already handled elsewhere. if !f.ignoreNextType && f.fs.Flag('#') { f.fs.Write(openParenBytes) f.fs.Write([]byte(v.Type().String())) f.fs.Write(closeParenBytes) } f.ignoreNextType = false // Call Stringer/error interfaces if they exist and the handle methods // flag is enabled. if !f.cs.DisableMethods { if (kind != reflect.Invalid) && (kind != reflect.Interface) { if handled := handleMethods(f.cs, f.fs, v); handled { return } } } switch kind { case reflect.Invalid: // Do nothing. We should never get here since invalid has already // been handled above. case reflect.Bool: printBool(f.fs, v.Bool()) case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: printInt(f.fs, v.Int(), 10) case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: printUint(f.fs, v.Uint(), 10) case reflect.Float32: printFloat(f.fs, v.Float(), 32) case reflect.Float64: printFloat(f.fs, v.Float(), 64) case reflect.Complex64: printComplex(f.fs, v.Complex(), 32) case reflect.Complex128: printComplex(f.fs, v.Complex(), 64) case reflect.Slice: if v.IsNil() { f.fs.Write(nilAngleBytes) break } fallthrough case reflect.Array: f.fs.Write(openBracketBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { numEntries := v.Len() for i := 0; i < numEntries; i++ { if i > 0 { f.fs.Write(spaceBytes) } f.ignoreNextType = true f.format(f.unpackValue(v.Index(i))) } } f.depth-- f.fs.Write(closeBracketBytes) case reflect.String: f.fs.Write([]byte(v.String())) case reflect.Interface: // The only time we should get here is for nil interfaces due to // unpackValue calls. if v.IsNil() { f.fs.Write(nilAngleBytes) } case reflect.Ptr: // Do nothing. We should never get here since pointers have already // been handled above. case reflect.Map: // nil maps should be indicated as different than empty maps if v.IsNil() { f.fs.Write(nilAngleBytes) break } f.fs.Write(openMapBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { keys := v.MapKeys() if f.cs.SortKeys { sortValues(keys, f.cs) } for i, key := range keys { if i > 0 { f.fs.Write(spaceBytes) } f.ignoreNextType = true f.format(f.unpackValue(key)) f.fs.Write(colonBytes) f.ignoreNextType = true f.format(f.unpackValue(v.MapIndex(key))) } } f.depth-- f.fs.Write(closeMapBytes) case reflect.Struct: numFields := v.NumField() f.fs.Write(openBraceBytes) f.depth++ if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { f.fs.Write(maxShortBytes) } else { vt := v.Type() for i := 0; i < numFields; i++ { if i > 0 { f.fs.Write(spaceBytes) } vtf := vt.Field(i) if f.fs.Flag('+') || f.fs.Flag('#') { f.fs.Write([]byte(vtf.Name)) f.fs.Write(colonBytes) } f.format(f.unpackValue(v.Field(i))) } } f.depth-- f.fs.Write(closeBraceBytes) case reflect.Uintptr: printHexPtr(f.fs, uintptr(v.Uint())) case reflect.UnsafePointer, reflect.Chan, reflect.Func: printHexPtr(f.fs, v.Pointer()) // There were not any other types at the time this code was written, but // fall back to letting the default fmt package handle it if any get added. default: format := f.buildDefaultFormat() if v.CanInterface() { fmt.Fprintf(f.fs, format, v.Interface()) } else { fmt.Fprintf(f.fs, format, v.String()) } } } // Format satisfies the fmt.Formatter interface. See NewFormatter for usage // details. func (f *formatState) Format(fs fmt.State, verb rune) { f.fs = fs // Use standard formatting for verbs that are not v. if verb != 'v' { format := f.constructOrigFormat(verb) fmt.Fprintf(fs, format, f.value) return } if f.value == nil { if fs.Flag('#') { fs.Write(interfaceBytes) } fs.Write(nilAngleBytes) return } f.format(reflect.ValueOf(f.value)) } // newFormatter is a helper function to consolidate the logic from the various // public methods which take varying config states. func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { fs := &formatState{value: v, cs: cs} fs.pointers = make(map[uintptr]int) return fs } /* NewFormatter returns a custom formatter that satisfies the fmt.Formatter interface. As a result, it integrates cleanly with standard fmt package printing functions. The formatter is useful for inline printing of smaller data types similar to the standard %v format specifier. The custom formatter only responds to the %v (most compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb combinations. Any other verbs such as %x and %q will be sent to the the standard fmt package for formatting. In addition, the custom formatter ignores the width and precision arguments (however they will still work on the format specifiers not handled by the custom formatter). Typically this function shouldn't be called directly. It is much easier to make use of the custom formatter by calling one of the convenience functions such as Printf, Println, or Fprintf. */ func NewFormatter(v interface{}) fmt.Formatter { return newFormatter(&Config, v) } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/davecgh/go-spew/spew/spew.go ================================================ /* * Copyright (c) 2013-2016 Dave Collins * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package spew import ( "fmt" "io" ) // Errorf is a wrapper for fmt.Errorf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the formatted string as a value that satisfies error. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) func Errorf(format string, a ...interface{}) (err error) { return fmt.Errorf(format, convertArgs(a)...) } // Fprint is a wrapper for fmt.Fprint that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) func Fprint(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprint(w, convertArgs(a)...) } // Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { return fmt.Fprintf(w, format, convertArgs(a)...) } // Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it // passed with a default Formatter interface returned by NewFormatter. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { return fmt.Fprintln(w, convertArgs(a)...) } // Print is a wrapper for fmt.Print that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) func Print(a ...interface{}) (n int, err error) { return fmt.Print(convertArgs(a)...) } // Printf is a wrapper for fmt.Printf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) func Printf(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format, convertArgs(a)...) } // Println is a wrapper for fmt.Println that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the number of bytes written and any write error encountered. See // NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) func Println(a ...interface{}) (n int, err error) { return fmt.Println(convertArgs(a)...) } // Sprint is a wrapper for fmt.Sprint that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) func Sprint(a ...interface{}) string { return fmt.Sprint(convertArgs(a)...) } // Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were // passed with a default Formatter interface returned by NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) func Sprintf(format string, a ...interface{}) string { return fmt.Sprintf(format, convertArgs(a)...) } // Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it // were passed with a default Formatter interface returned by NewFormatter. It // returns the resulting string. See NewFormatter for formatting details. // // This function is shorthand for the following syntax: // // fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) func Sprintln(a ...interface{}) string { return fmt.Sprintln(convertArgs(a)...) } // convertArgs accepts a slice of arguments and returns a slice of the same // length with each argument converted to a default spew Formatter interface. func convertArgs(args []interface{}) (formatters []interface{}) { formatters = make([]interface{}, len(args)) for index, arg := range args { formatters[index] = NewFormatter(arg) } return formatters } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/LICENSE ================================================ Copyright (c) 2013, Patrick Mezard All rights reserved. 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. The names of its contributors may not 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 HOLDER 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. ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/pmezard/go-difflib/difflib/difflib.go ================================================ // Package difflib is a partial port of Python difflib module. // // It provides tools to compare sequences of strings and generate textual diffs. // // The following class and functions have been ported: // // - SequenceMatcher // // - unified_diff // // - context_diff // // Getting unified diffs was the main goal of the port. Keep in mind this code // is mostly suitable to output text differences in a human friendly way, there // are no guarantees generated diffs are consumable by patch(1). package difflib import ( "bufio" "bytes" "fmt" "io" "strings" ) func min(a, b int) int { if a < b { return a } return b } func max(a, b int) int { if a > b { return a } return b } func calculateRatio(matches, length int) float64 { if length > 0 { return 2.0 * float64(matches) / float64(length) } return 1.0 } type Match struct { A int B int Size int } type OpCode struct { Tag byte I1 int I2 int J1 int J2 int } // SequenceMatcher compares sequence of strings. The basic // algorithm predates, and is a little fancier than, an algorithm // published in the late 1980's by Ratcliff and Obershelp under the // hyperbolic name "gestalt pattern matching". The basic idea is to find // the longest contiguous matching subsequence that contains no "junk" // elements (R-O doesn't address junk). The same idea is then applied // recursively to the pieces of the sequences to the left and to the right // of the matching subsequence. This does not yield minimal edit // sequences, but does tend to yield matches that "look right" to people. // // SequenceMatcher tries to compute a "human-friendly diff" between two // sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the // longest *contiguous* & junk-free matching subsequence. That's what // catches peoples' eyes. The Windows(tm) windiff has another interesting // notion, pairing up elements that appear uniquely in each sequence. // That, and the method here, appear to yield more intuitive difference // reports than does diff. This method appears to be the least vulnerable // to synching up on blocks of "junk lines", though (like blank lines in // ordinary text files, or maybe "

" lines in HTML files). That may be // because this is the only method of the 3 that has a *concept* of // "junk" . // // Timing: Basic R-O is cubic time worst case and quadratic time expected // case. SequenceMatcher is quadratic time for the worst case and has // expected-case behavior dependent in a complicated way on how many // elements the sequences have in common; best case time is linear. type SequenceMatcher struct { a []string b []string b2j map[string][]int IsJunk func(string) bool autoJunk bool bJunk map[string]struct{} matchingBlocks []Match fullBCount map[string]int bPopular map[string]struct{} opCodes []OpCode } func NewMatcher(a, b []string) *SequenceMatcher { m := SequenceMatcher{autoJunk: true} m.SetSeqs(a, b) return &m } func NewMatcherWithJunk(a, b []string, autoJunk bool, isJunk func(string) bool) *SequenceMatcher { m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk} m.SetSeqs(a, b) return &m } // Set two sequences to be compared. func (m *SequenceMatcher) SetSeqs(a, b []string) { m.SetSeq1(a) m.SetSeq2(b) } // Set the first sequence to be compared. The second sequence to be compared is // not changed. // // SequenceMatcher computes and caches detailed information about the second // sequence, so if you want to compare one sequence S against many sequences, // use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other // sequences. // // See also SetSeqs() and SetSeq2(). func (m *SequenceMatcher) SetSeq1(a []string) { if &a == &m.a { return } m.a = a m.matchingBlocks = nil m.opCodes = nil } // Set the second sequence to be compared. The first sequence to be compared is // not changed. func (m *SequenceMatcher) SetSeq2(b []string) { if &b == &m.b { return } m.b = b m.matchingBlocks = nil m.opCodes = nil m.fullBCount = nil m.chainB() } func (m *SequenceMatcher) chainB() { // Populate line -> index mapping b2j := map[string][]int{} for i, s := range m.b { indices := b2j[s] indices = append(indices, i) b2j[s] = indices } // Purge junk elements m.bJunk = map[string]struct{}{} if m.IsJunk != nil { junk := m.bJunk for s, _ := range b2j { if m.IsJunk(s) { junk[s] = struct{}{} } } for s, _ := range junk { delete(b2j, s) } } // Purge remaining popular elements popular := map[string]struct{}{} n := len(m.b) if m.autoJunk && n >= 200 { ntest := n/100 + 1 for s, indices := range b2j { if len(indices) > ntest { popular[s] = struct{}{} } } for s, _ := range popular { delete(b2j, s) } } m.bPopular = popular m.b2j = b2j } func (m *SequenceMatcher) isBJunk(s string) bool { _, ok := m.bJunk[s] return ok } // Find longest matching block in a[alo:ahi] and b[blo:bhi]. // // If IsJunk is not defined: // // Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where // alo <= i <= i+k <= ahi // blo <= j <= j+k <= bhi // and for all (i',j',k') meeting those conditions, // k >= k' // i <= i' // and if i == i', j <= j' // // In other words, of all maximal matching blocks, return one that // starts earliest in a, and of all those maximal matching blocks that // start earliest in a, return the one that starts earliest in b. // // If IsJunk is defined, first the longest matching block is // determined as above, but with the additional restriction that no // junk element appears in the block. Then that block is extended as // far as possible by matching (only) junk elements on both sides. So // the resulting block never matches on junk except as identical junk // happens to be adjacent to an "interesting" match. // // If no blocks match, return (alo, blo, 0). func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { // CAUTION: stripping common prefix or suffix would be incorrect. // E.g., // ab // acab // Longest matching block is "ab", but if common prefix is // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so // strip, so ends up claiming that ab is changed to acab by // inserting "ca" in the middle. That's minimal but unintuitive: // "it's obvious" that someone inserted "ac" at the front. // Windiff ends up at the same place as diff, but by pairing up // the unique 'b's and then matching the first two 'a's. besti, bestj, bestsize := alo, blo, 0 // find longest junk-free match // during an iteration of the loop, j2len[j] = length of longest // junk-free match ending with a[i-1] and b[j] j2len := map[int]int{} for i := alo; i != ahi; i++ { // look at all instances of a[i] in b; note that because // b2j has no junk keys, the loop is skipped if a[i] is junk newj2len := map[int]int{} for _, j := range m.b2j[m.a[i]] { // a[i] matches b[j] if j < blo { continue } if j >= bhi { break } k := j2len[j-1] + 1 newj2len[j] = k if k > bestsize { besti, bestj, bestsize = i-k+1, j-k+1, k } } j2len = newj2len } // Extend the best by non-junk elements on each end. In particular, // "popular" non-junk elements aren't in b2j, which greatly speeds // the inner loop above, but also means "the best" match so far // doesn't contain any junk *or* popular non-junk elements. for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) && m.a[besti-1] == m.b[bestj-1] { besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 } for besti+bestsize < ahi && bestj+bestsize < bhi && !m.isBJunk(m.b[bestj+bestsize]) && m.a[besti+bestsize] == m.b[bestj+bestsize] { bestsize += 1 } // Now that we have a wholly interesting match (albeit possibly // empty!), we may as well suck up the matching junk on each // side of it too. Can't think of a good reason not to, and it // saves post-processing the (possibly considerable) expense of // figuring out what to do with it. In the case of an empty // interesting match, this is clearly the right thing to do, // because no other kind of match is possible in the regions. for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) && m.a[besti-1] == m.b[bestj-1] { besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 } for besti+bestsize < ahi && bestj+bestsize < bhi && m.isBJunk(m.b[bestj+bestsize]) && m.a[besti+bestsize] == m.b[bestj+bestsize] { bestsize += 1 } return Match{A: besti, B: bestj, Size: bestsize} } // Return list of triples describing matching subsequences. // // Each triple is of the form (i, j, n), and means that // a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in // i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are // adjacent triples in the list, and the second is not the last triple in the // list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe // adjacent equal blocks. // // The last triple is a dummy, (len(a), len(b), 0), and is the only // triple with n==0. func (m *SequenceMatcher) GetMatchingBlocks() []Match { if m.matchingBlocks != nil { return m.matchingBlocks } var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match { match := m.findLongestMatch(alo, ahi, blo, bhi) i, j, k := match.A, match.B, match.Size if match.Size > 0 { if alo < i && blo < j { matched = matchBlocks(alo, i, blo, j, matched) } matched = append(matched, match) if i+k < ahi && j+k < bhi { matched = matchBlocks(i+k, ahi, j+k, bhi, matched) } } return matched } matched := matchBlocks(0, len(m.a), 0, len(m.b), nil) // It's possible that we have adjacent equal blocks in the // matching_blocks list now. nonAdjacent := []Match{} i1, j1, k1 := 0, 0, 0 for _, b := range matched { // Is this block adjacent to i1, j1, k1? i2, j2, k2 := b.A, b.B, b.Size if i1+k1 == i2 && j1+k1 == j2 { // Yes, so collapse them -- this just increases the length of // the first block by the length of the second, and the first // block so lengthened remains the block to compare against. k1 += k2 } else { // Not adjacent. Remember the first block (k1==0 means it's // the dummy we started with), and make the second block the // new block to compare against. if k1 > 0 { nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) } i1, j1, k1 = i2, j2, k2 } } if k1 > 0 { nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) } nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0}) m.matchingBlocks = nonAdjacent return m.matchingBlocks } // Return list of 5-tuples describing how to turn a into b. // // Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple // has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the // tuple preceding it, and likewise for j1 == the previous j2. // // The tags are characters, with these meanings: // // 'r' (replace): a[i1:i2] should be replaced by b[j1:j2] // // 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case. // // 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case. // // 'e' (equal): a[i1:i2] == b[j1:j2] func (m *SequenceMatcher) GetOpCodes() []OpCode { if m.opCodes != nil { return m.opCodes } i, j := 0, 0 matching := m.GetMatchingBlocks() opCodes := make([]OpCode, 0, len(matching)) for _, m := range matching { // invariant: we've pumped out correct diffs to change // a[:i] into b[:j], and the next matching block is // a[ai:ai+size] == b[bj:bj+size]. So we need to pump // out a diff to change a[i:ai] into b[j:bj], pump out // the matching block, and move (i,j) beyond the match ai, bj, size := m.A, m.B, m.Size tag := byte(0) if i < ai && j < bj { tag = 'r' } else if i < ai { tag = 'd' } else if j < bj { tag = 'i' } if tag > 0 { opCodes = append(opCodes, OpCode{tag, i, ai, j, bj}) } i, j = ai+size, bj+size // the list of matching blocks is terminated by a // sentinel with size 0 if size > 0 { opCodes = append(opCodes, OpCode{'e', ai, i, bj, j}) } } m.opCodes = opCodes return m.opCodes } // Isolate change clusters by eliminating ranges with no changes. // // Return a generator of groups with up to n lines of context. // Each group is in the same format as returned by GetOpCodes(). func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { if n < 0 { n = 3 } codes := m.GetOpCodes() if len(codes) == 0 { codes = []OpCode{OpCode{'e', 0, 1, 0, 1}} } // Fixup leading and trailing groups if they show no changes. if codes[0].Tag == 'e' { c := codes[0] i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2} } if codes[len(codes)-1].Tag == 'e' { c := codes[len(codes)-1] i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)} } nn := n + n groups := [][]OpCode{} group := []OpCode{} for _, c := range codes { i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 // End the current group and start a new one whenever // there is a large range with no changes. if c.Tag == 'e' && i2-i1 > nn { group = append(group, OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)}) groups = append(groups, group) group = []OpCode{} i1, j1 = max(i1, i2-n), max(j1, j2-n) } group = append(group, OpCode{c.Tag, i1, i2, j1, j2}) } if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') { groups = append(groups, group) } return groups } // Return a measure of the sequences' similarity (float in [0,1]). // // Where T is the total number of elements in both sequences, and // M is the number of matches, this is 2.0*M / T. // Note that this is 1 if the sequences are identical, and 0 if // they have nothing in common. // // .Ratio() is expensive to compute if you haven't already computed // .GetMatchingBlocks() or .GetOpCodes(), in which case you may // want to try .QuickRatio() or .RealQuickRation() first to get an // upper bound. func (m *SequenceMatcher) Ratio() float64 { matches := 0 for _, m := range m.GetMatchingBlocks() { matches += m.Size } return calculateRatio(matches, len(m.a)+len(m.b)) } // Return an upper bound on ratio() relatively quickly. // // This isn't defined beyond that it is an upper bound on .Ratio(), and // is faster to compute. func (m *SequenceMatcher) QuickRatio() float64 { // viewing a and b as multisets, set matches to the cardinality // of their intersection; this counts the number of matches // without regard to order, so is clearly an upper bound if m.fullBCount == nil { m.fullBCount = map[string]int{} for _, s := range m.b { m.fullBCount[s] = m.fullBCount[s] + 1 } } // avail[x] is the number of times x appears in 'b' less the // number of times we've seen it in 'a' so far ... kinda avail := map[string]int{} matches := 0 for _, s := range m.a { n, ok := avail[s] if !ok { n = m.fullBCount[s] } avail[s] = n - 1 if n > 0 { matches += 1 } } return calculateRatio(matches, len(m.a)+len(m.b)) } // Return an upper bound on ratio() very quickly. // // This isn't defined beyond that it is an upper bound on .Ratio(), and // is faster to compute than either .Ratio() or .QuickRatio(). func (m *SequenceMatcher) RealQuickRatio() float64 { la, lb := len(m.a), len(m.b) return calculateRatio(min(la, lb), la+lb) } // Convert range to the "ed" format func formatRangeUnified(start, stop int) string { // Per the diff spec at http://www.unix.org/single_unix_specification/ beginning := start + 1 // lines start numbering with one length := stop - start if length == 1 { return fmt.Sprintf("%d", beginning) } if length == 0 { beginning -= 1 // empty ranges begin at line just before the range } return fmt.Sprintf("%d,%d", beginning, length) } // Unified diff parameters type UnifiedDiff struct { A []string // First sequence lines FromFile string // First file name FromDate string // First file time B []string // Second sequence lines ToFile string // Second file name ToDate string // Second file time Eol string // Headers end of line, defaults to LF Context int // Number of context lines } // Compare two sequences of lines; generate the delta as a unified diff. // // Unified diffs are a compact way of showing line changes and a few // lines of context. The number of context lines is set by 'n' which // defaults to three. // // By default, the diff control lines (those with ---, +++, or @@) are // created with a trailing newline. This is helpful so that inputs // created from file.readlines() result in diffs that are suitable for // file.writelines() since both the inputs and outputs have trailing // newlines. // // For inputs that do not have trailing newlines, set the lineterm // argument to "" so that the output will be uniformly newline free. // // The unidiff format normally has a header for filenames and modification // times. Any or all of these may be specified using strings for // 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. // The modification times are normally expressed in the ISO 8601 format. func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { buf := bufio.NewWriter(writer) defer buf.Flush() wf := func(format string, args ...interface{}) error { _, err := buf.WriteString(fmt.Sprintf(format, args...)) return err } ws := func(s string) error { _, err := buf.WriteString(s) return err } if len(diff.Eol) == 0 { diff.Eol = "\n" } started := false m := NewMatcher(diff.A, diff.B) for _, g := range m.GetGroupedOpCodes(diff.Context) { if !started { started = true fromDate := "" if len(diff.FromDate) > 0 { fromDate = "\t" + diff.FromDate } toDate := "" if len(diff.ToDate) > 0 { toDate = "\t" + diff.ToDate } if diff.FromFile != "" || diff.ToFile != "" { err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol) if err != nil { return err } err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol) if err != nil { return err } } } first, last := g[0], g[len(g)-1] range1 := formatRangeUnified(first.I1, last.I2) range2 := formatRangeUnified(first.J1, last.J2) if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil { return err } for _, c := range g { i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 if c.Tag == 'e' { for _, line := range diff.A[i1:i2] { if err := ws(" " + line); err != nil { return err } } continue } if c.Tag == 'r' || c.Tag == 'd' { for _, line := range diff.A[i1:i2] { if err := ws("-" + line); err != nil { return err } } } if c.Tag == 'r' || c.Tag == 'i' { for _, line := range diff.B[j1:j2] { if err := ws("+" + line); err != nil { return err } } } } } return nil } // Like WriteUnifiedDiff but returns the diff a string. func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { w := &bytes.Buffer{} err := WriteUnifiedDiff(w, diff) return string(w.Bytes()), err } // Convert range to the "ed" format. func formatRangeContext(start, stop int) string { // Per the diff spec at http://www.unix.org/single_unix_specification/ beginning := start + 1 // lines start numbering with one length := stop - start if length == 0 { beginning -= 1 // empty ranges begin at line just before the range } if length <= 1 { return fmt.Sprintf("%d", beginning) } return fmt.Sprintf("%d,%d", beginning, beginning+length-1) } type ContextDiff UnifiedDiff // Compare two sequences of lines; generate the delta as a context diff. // // Context diffs are a compact way of showing line changes and a few // lines of context. The number of context lines is set by diff.Context // which defaults to three. // // By default, the diff control lines (those with *** or ---) are // created with a trailing newline. // // For inputs that do not have trailing newlines, set the diff.Eol // argument to "" so that the output will be uniformly newline free. // // The context diff format normally has a header for filenames and // modification times. Any or all of these may be specified using // strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate. // The modification times are normally expressed in the ISO 8601 format. // If not specified, the strings default to blanks. func WriteContextDiff(writer io.Writer, diff ContextDiff) error { buf := bufio.NewWriter(writer) defer buf.Flush() var diffErr error wf := func(format string, args ...interface{}) { _, err := buf.WriteString(fmt.Sprintf(format, args...)) if diffErr == nil && err != nil { diffErr = err } } ws := func(s string) { _, err := buf.WriteString(s) if diffErr == nil && err != nil { diffErr = err } } if len(diff.Eol) == 0 { diff.Eol = "\n" } prefix := map[byte]string{ 'i': "+ ", 'd': "- ", 'r': "! ", 'e': " ", } started := false m := NewMatcher(diff.A, diff.B) for _, g := range m.GetGroupedOpCodes(diff.Context) { if !started { started = true fromDate := "" if len(diff.FromDate) > 0 { fromDate = "\t" + diff.FromDate } toDate := "" if len(diff.ToDate) > 0 { toDate = "\t" + diff.ToDate } if diff.FromFile != "" || diff.ToFile != "" { wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol) wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol) } } first, last := g[0], g[len(g)-1] ws("***************" + diff.Eol) range1 := formatRangeContext(first.I1, last.I2) wf("*** %s ****%s", range1, diff.Eol) for _, c := range g { if c.Tag == 'r' || c.Tag == 'd' { for _, cc := range g { if cc.Tag == 'i' { continue } for _, line := range diff.A[cc.I1:cc.I2] { ws(prefix[cc.Tag] + line) } } break } } range2 := formatRangeContext(first.J1, last.J2) wf("--- %s ----%s", range2, diff.Eol) for _, c := range g { if c.Tag == 'r' || c.Tag == 'i' { for _, cc := range g { if cc.Tag == 'd' { continue } for _, line := range diff.B[cc.J1:cc.J2] { ws(prefix[cc.Tag] + line) } } break } } } return diffErr } // Like WriteContextDiff but returns the diff a string. func GetContextDiffString(diff ContextDiff) (string, error) { w := &bytes.Buffer{} err := WriteContextDiff(w, diff) return string(w.Bytes()), err } // Split a string on "\n" while preserving them. The output can be used // as input for UnifiedDiff and ContextDiff structures. func SplitLines(s string) []string { lines := strings.SplitAfter(s, "\n") lines[len(lines)-1] += "\n" return lines } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/LICENSE ================================================ The MIT License Copyright (c) 2014 Stretchr, Inc. Copyright (c) 2017-2018 objx contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/accessors.go ================================================ package objx import ( "fmt" "regexp" "strconv" "strings" ) // arrayAccesRegexString is the regex used to extract the array number // from the access path const arrayAccesRegexString = `^(.+)\[([0-9]+)\]$` // arrayAccesRegex is the compiled arrayAccesRegexString var arrayAccesRegex = regexp.MustCompile(arrayAccesRegexString) // Get gets the value using the specified selector and // returns it inside a new Obj object. // // If it cannot find the value, Get will return a nil // value inside an instance of Obj. // // Get can only operate directly on map[string]interface{} and []interface. // // Example // // To access the title of the third chapter of the second book, do: // // o.Get("books[1].chapters[2].title") func (m Map) Get(selector string) *Value { rawObj := access(m, selector, nil, false, false) return &Value{data: rawObj} } // Set sets the value using the specified selector and // returns the object on which Set was called. // // Set can only operate directly on map[string]interface{} and []interface // // Example // // To set the title of the third chapter of the second book, do: // // o.Set("books[1].chapters[2].title","Time to Go") func (m Map) Set(selector string, value interface{}) Map { access(m, selector, value, true, false) return m } // access accesses the object using the selector and performs the // appropriate action. func access(current, selector, value interface{}, isSet, panics bool) interface{} { switch selector.(type) { case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: if array, ok := current.([]interface{}); ok { index := intFromInterface(selector) if index >= len(array) { if panics { panic(fmt.Sprintf("objx: Index %d is out of range. Slice only contains %d items.", index, len(array))) } return nil } return array[index] } return nil case string: selStr := selector.(string) selSegs := strings.SplitN(selStr, PathSeparator, 2) thisSel := selSegs[0] index := -1 var err error if strings.Contains(thisSel, "[") { arrayMatches := arrayAccesRegex.FindStringSubmatch(thisSel) if len(arrayMatches) > 0 { // Get the key into the map thisSel = arrayMatches[1] // Get the index into the array at the key index, err = strconv.Atoi(arrayMatches[2]) if err != nil { // This should never happen. If it does, something has gone // seriously wrong. Panic. panic("objx: Array index is not an integer. Must use array[int].") } } } if curMap, ok := current.(Map); ok { current = map[string]interface{}(curMap) } // get the object in question switch current.(type) { case map[string]interface{}: curMSI := current.(map[string]interface{}) if len(selSegs) <= 1 && isSet { curMSI[thisSel] = value return nil } current = curMSI[thisSel] default: current = nil } if current == nil && panics { panic(fmt.Sprintf("objx: '%v' invalid on object.", selector)) } // do we need to access the item of an array? if index > -1 { if array, ok := current.([]interface{}); ok { if index < len(array) { current = array[index] } else { if panics { panic(fmt.Sprintf("objx: Index %d is out of range. Slice only contains %d items.", index, len(array))) } current = nil } } } if len(selSegs) > 1 { current = access(current, selSegs[1], value, isSet, panics) } } return current } // intFromInterface converts an interface object to the largest // representation of an unsigned integer using a type switch and // assertions func intFromInterface(selector interface{}) int { var value int switch selector.(type) { case int: value = selector.(int) case int8: value = int(selector.(int8)) case int16: value = int(selector.(int16)) case int32: value = int(selector.(int32)) case int64: value = int(selector.(int64)) case uint: value = int(selector.(uint)) case uint8: value = int(selector.(uint8)) case uint16: value = int(selector.(uint16)) case uint32: value = int(selector.(uint32)) case uint64: value = int(selector.(uint64)) default: panic("objx: array access argument is not an integer type (this should never happen)") } return value } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/constants.go ================================================ package objx const ( // PathSeparator is the character used to separate the elements // of the keypath. // // For example, `location.address.city` PathSeparator string = "." // SignatureSeparator is the character that is used to // separate the Base64 string from the security signature. SignatureSeparator = "_" ) ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/conversions.go ================================================ package objx import ( "bytes" "encoding/base64" "encoding/json" "errors" "fmt" "net/url" ) // JSON converts the contained object to a JSON string // representation func (m Map) JSON() (string, error) { result, err := json.Marshal(m) if err != nil { err = errors.New("objx: JSON encode failed with: " + err.Error()) } return string(result), err } // MustJSON converts the contained object to a JSON string // representation and panics if there is an error func (m Map) MustJSON() string { result, err := m.JSON() if err != nil { panic(err.Error()) } return result } // Base64 converts the contained object to a Base64 string // representation of the JSON string representation func (m Map) Base64() (string, error) { var buf bytes.Buffer jsonData, err := m.JSON() if err != nil { return "", err } encoder := base64.NewEncoder(base64.StdEncoding, &buf) _, err = encoder.Write([]byte(jsonData)) if err != nil { return "", err } _ = encoder.Close() return buf.String(), nil } // MustBase64 converts the contained object to a Base64 string // representation of the JSON string representation and panics // if there is an error func (m Map) MustBase64() string { result, err := m.Base64() if err != nil { panic(err.Error()) } return result } // SignedBase64 converts the contained object to a Base64 string // representation of the JSON string representation and signs it // using the provided key. func (m Map) SignedBase64(key string) (string, error) { base64, err := m.Base64() if err != nil { return "", err } sig := HashWithKey(base64, key) return base64 + SignatureSeparator + sig, nil } // MustSignedBase64 converts the contained object to a Base64 string // representation of the JSON string representation and signs it // using the provided key and panics if there is an error func (m Map) MustSignedBase64(key string) string { result, err := m.SignedBase64(key) if err != nil { panic(err.Error()) } return result } /* URL Query ------------------------------------------------ */ // URLValues creates a url.Values object from an Obj. This // function requires that the wrapped object be a map[string]interface{} func (m Map) URLValues() url.Values { vals := make(url.Values) for k, v := range m { //TODO: can this be done without sprintf? vals.Set(k, fmt.Sprintf("%v", v)) } return vals } // URLQuery gets an encoded URL query representing the given // Obj. This function requires that the wrapped object be a // map[string]interface{} func (m Map) URLQuery() (string, error) { return m.URLValues().Encode(), nil } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/doc.go ================================================ /* Objx - Go package for dealing with maps, slices, JSON and other data. Overview Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes a powerful `Get` method (among others) that allows you to easily and quickly get access to data within the map, without having to worry too much about type assertions, missing data, default values etc. Pattern Objx uses a preditable pattern to make access data from within `map[string]interface{}` easy. Call one of the `objx.` functions to create your `objx.Map` to get going: m, err := objx.FromJSON(json) NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, the rest will be optimistic and try to figure things out without panicking. Use `Get` to access the value you're interested in. You can use dot and array notation too: m.Get("places[0].latlng") Once you have sought the `Value` you're interested in, you can use the `Is*` methods to determine its type. if m.Get("code").IsStr() { // Your code... } Or you can just assume the type, and use one of the strong type methods to extract the real value: m.Get("code").Int() If there's no value there (or if it's the wrong type) then a default value will be returned, or you can be explicit about the default value. Get("code").Int(-1) If you're dealing with a slice of data as a value, Objx provides many useful methods for iterating, manipulating and selecting that data. You can find out more by exploring the index below. Reading data A simple example of how to use Objx: // Use MustFromJSON to make an objx.Map from some JSON m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`) // Get the details name := m.Get("name").Str() age := m.Get("age").Int() // Get their nickname (or use their name if they don't have one) nickname := m.Get("nickname").Str(name) Ranging Since `objx.Map` is a `map[string]interface{}` you can treat it as such. For example, to `range` the data, do what you would expect: m := objx.MustFromJSON(json) for key, value := range m { // Your code... } */ package objx ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/map.go ================================================ package objx import ( "encoding/base64" "encoding/json" "errors" "io/ioutil" "net/url" "strings" ) // MSIConvertable is an interface that defines methods for converting your // custom types to a map[string]interface{} representation. type MSIConvertable interface { // MSI gets a map[string]interface{} (msi) representing the // object. MSI() map[string]interface{} } // Map provides extended functionality for working with // untyped data, in particular map[string]interface (msi). type Map map[string]interface{} // Value returns the internal value instance func (m Map) Value() *Value { return &Value{data: m} } // Nil represents a nil Map. var Nil = New(nil) // New creates a new Map containing the map[string]interface{} in the data argument. // If the data argument is not a map[string]interface, New attempts to call the // MSI() method on the MSIConvertable interface to create one. func New(data interface{}) Map { if _, ok := data.(map[string]interface{}); !ok { if converter, ok := data.(MSIConvertable); ok { data = converter.MSI() } else { return nil } } return Map(data.(map[string]interface{})) } // MSI creates a map[string]interface{} and puts it inside a new Map. // // The arguments follow a key, value pattern. // // Panics // // Panics if any key argument is non-string or if there are an odd number of arguments. // // Example // // To easily create Maps: // // m := objx.MSI("name", "Mat", "age", 29, "subobj", objx.MSI("active", true)) // // // creates an Map equivalent to // m := objx.New(map[string]interface{}{"name": "Mat", "age": 29, "subobj": map[string]interface{}{"active": true}}) func MSI(keyAndValuePairs ...interface{}) Map { newMap := make(map[string]interface{}) keyAndValuePairsLen := len(keyAndValuePairs) if keyAndValuePairsLen%2 != 0 { panic("objx: MSI must have an even number of arguments following the 'key, value' pattern.") } for i := 0; i < keyAndValuePairsLen; i = i + 2 { key := keyAndValuePairs[i] value := keyAndValuePairs[i+1] // make sure the key is a string keyString, keyStringOK := key.(string) if !keyStringOK { panic("objx: MSI must follow 'string, interface{}' pattern. " + keyString + " is not a valid key.") } newMap[keyString] = value } return New(newMap) } // ****** Conversion Constructors // MustFromJSON creates a new Map containing the data specified in the // jsonString. // // Panics if the JSON is invalid. func MustFromJSON(jsonString string) Map { o, err := FromJSON(jsonString) if err != nil { panic("objx: MustFromJSON failed with error: " + err.Error()) } return o } // FromJSON creates a new Map containing the data specified in the // jsonString. // // Returns an error if the JSON is invalid. func FromJSON(jsonString string) (Map, error) { var data interface{} err := json.Unmarshal([]byte(jsonString), &data) if err != nil { return Nil, err } return New(data), nil } // FromBase64 creates a new Obj containing the data specified // in the Base64 string. // // The string is an encoded JSON string returned by Base64 func FromBase64(base64String string) (Map, error) { decoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(base64String)) decoded, err := ioutil.ReadAll(decoder) if err != nil { return nil, err } return FromJSON(string(decoded)) } // MustFromBase64 creates a new Obj containing the data specified // in the Base64 string and panics if there is an error. // // The string is an encoded JSON string returned by Base64 func MustFromBase64(base64String string) Map { result, err := FromBase64(base64String) if err != nil { panic("objx: MustFromBase64 failed with error: " + err.Error()) } return result } // FromSignedBase64 creates a new Obj containing the data specified // in the Base64 string. // // The string is an encoded JSON string returned by SignedBase64 func FromSignedBase64(base64String, key string) (Map, error) { parts := strings.Split(base64String, SignatureSeparator) if len(parts) != 2 { return nil, errors.New("objx: Signed base64 string is malformed") } sig := HashWithKey(parts[0], key) if parts[1] != sig { return nil, errors.New("objx: Signature for base64 data does not match") } return FromBase64(parts[0]) } // MustFromSignedBase64 creates a new Obj containing the data specified // in the Base64 string and panics if there is an error. // // The string is an encoded JSON string returned by Base64 func MustFromSignedBase64(base64String, key string) Map { result, err := FromSignedBase64(base64String, key) if err != nil { panic("objx: MustFromSignedBase64 failed with error: " + err.Error()) } return result } // FromURLQuery generates a new Obj by parsing the specified // query. // // For queries with multiple values, the first value is selected. func FromURLQuery(query string) (Map, error) { vals, err := url.ParseQuery(query) if err != nil { return nil, err } m := make(map[string]interface{}) for k, vals := range vals { m[k] = vals[0] } return New(m), nil } // MustFromURLQuery generates a new Obj by parsing the specified // query. // // For queries with multiple values, the first value is selected. // // Panics if it encounters an error func MustFromURLQuery(query string) Map { o, err := FromURLQuery(query) if err != nil { panic("objx: MustFromURLQuery failed with error: " + err.Error()) } return o } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/mutations.go ================================================ package objx // Exclude returns a new Map with the keys in the specified []string // excluded. func (m Map) Exclude(exclude []string) Map { excluded := make(Map) for k, v := range m { var shouldInclude = true for _, toExclude := range exclude { if k == toExclude { shouldInclude = false break } } if shouldInclude { excluded[k] = v } } return excluded } // Copy creates a shallow copy of the Obj. func (m Map) Copy() Map { copied := make(map[string]interface{}) for k, v := range m { copied[k] = v } return New(copied) } // Merge blends the specified map with a copy of this map and returns the result. // // Keys that appear in both will be selected from the specified map. // This method requires that the wrapped object be a map[string]interface{} func (m Map) Merge(merge Map) Map { return m.Copy().MergeHere(merge) } // MergeHere blends the specified map with this map and returns the current map. // // Keys that appear in both will be selected from the specified map. The original map // will be modified. This method requires that // the wrapped object be a map[string]interface{} func (m Map) MergeHere(merge Map) Map { for k, v := range merge { m[k] = v } return m } // Transform builds a new Obj giving the transformer a chance // to change the keys and values as it goes. This method requires that // the wrapped object be a map[string]interface{} func (m Map) Transform(transformer func(key string, value interface{}) (string, interface{})) Map { newMap := make(map[string]interface{}) for k, v := range m { modifiedKey, modifiedVal := transformer(k, v) newMap[modifiedKey] = modifiedVal } return New(newMap) } // TransformKeys builds a new map using the specified key mapping. // // Unspecified keys will be unaltered. // This method requires that the wrapped object be a map[string]interface{} func (m Map) TransformKeys(mapping map[string]string) Map { return m.Transform(func(key string, value interface{}) (string, interface{}) { if newKey, ok := mapping[key]; ok { return newKey, value } return key, value }) } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/security.go ================================================ package objx import ( "crypto/sha1" "encoding/hex" ) // HashWithKey hashes the specified string using the security // key. func HashWithKey(data, key string) string { hash := sha1.New() _, err := hash.Write([]byte(data + ":" + key)) if err != nil { return "" } return hex.EncodeToString(hash.Sum(nil)) } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/tests.go ================================================ package objx // Has gets whether there is something at the specified selector // or not. // // If m is nil, Has will always return false. func (m Map) Has(selector string) bool { if m == nil { return false } return !m.Get(selector).IsNil() } // IsNil gets whether the data is nil or not. func (v *Value) IsNil() bool { return v == nil || v.data == nil } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/type_specific_codegen.go ================================================ package objx /* Inter (interface{} and []interface{}) */ // Inter gets the value as a interface{}, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Inter(optionalDefault ...interface{}) interface{} { if s, ok := v.data.(interface{}); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustInter gets the value as a interface{}. // // Panics if the object is not a interface{}. func (v *Value) MustInter() interface{} { return v.data.(interface{}) } // InterSlice gets the value as a []interface{}, returns the optionalDefault // value or nil if the value is not a []interface{}. func (v *Value) InterSlice(optionalDefault ...[]interface{}) []interface{} { if s, ok := v.data.([]interface{}); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustInterSlice gets the value as a []interface{}. // // Panics if the object is not a []interface{}. func (v *Value) MustInterSlice() []interface{} { return v.data.([]interface{}) } // IsInter gets whether the object contained is a interface{} or not. func (v *Value) IsInter() bool { _, ok := v.data.(interface{}) return ok } // IsInterSlice gets whether the object contained is a []interface{} or not. func (v *Value) IsInterSlice() bool { _, ok := v.data.([]interface{}) return ok } // EachInter calls the specified callback for each object // in the []interface{}. // // Panics if the object is the wrong type. func (v *Value) EachInter(callback func(int, interface{}) bool) *Value { for index, val := range v.MustInterSlice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereInter uses the specified decider function to select items // from the []interface{}. The object contained in the result will contain // only the selected items. func (v *Value) WhereInter(decider func(int, interface{}) bool) *Value { var selected []interface{} v.EachInter(func(index int, val interface{}) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupInter uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]interface{}. func (v *Value) GroupInter(grouper func(int, interface{}) string) *Value { groups := make(map[string][]interface{}) v.EachInter(func(index int, val interface{}) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]interface{}, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceInter uses the specified function to replace each interface{}s // by iterating each item. The data in the returned result will be a // []interface{} containing the replaced items. func (v *Value) ReplaceInter(replacer func(int, interface{}) interface{}) *Value { arr := v.MustInterSlice() replaced := make([]interface{}, len(arr)) v.EachInter(func(index int, val interface{}) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectInter uses the specified collector function to collect a value // for each of the interface{}s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectInter(collector func(int, interface{}) interface{}) *Value { arr := v.MustInterSlice() collected := make([]interface{}, len(arr)) v.EachInter(func(index int, val interface{}) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* MSI (map[string]interface{} and []map[string]interface{}) */ // MSI gets the value as a map[string]interface{}, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) MSI(optionalDefault ...map[string]interface{}) map[string]interface{} { if s, ok := v.data.(map[string]interface{}); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustMSI gets the value as a map[string]interface{}. // // Panics if the object is not a map[string]interface{}. func (v *Value) MustMSI() map[string]interface{} { return v.data.(map[string]interface{}) } // MSISlice gets the value as a []map[string]interface{}, returns the optionalDefault // value or nil if the value is not a []map[string]interface{}. func (v *Value) MSISlice(optionalDefault ...[]map[string]interface{}) []map[string]interface{} { if s, ok := v.data.([]map[string]interface{}); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustMSISlice gets the value as a []map[string]interface{}. // // Panics if the object is not a []map[string]interface{}. func (v *Value) MustMSISlice() []map[string]interface{} { return v.data.([]map[string]interface{}) } // IsMSI gets whether the object contained is a map[string]interface{} or not. func (v *Value) IsMSI() bool { _, ok := v.data.(map[string]interface{}) return ok } // IsMSISlice gets whether the object contained is a []map[string]interface{} or not. func (v *Value) IsMSISlice() bool { _, ok := v.data.([]map[string]interface{}) return ok } // EachMSI calls the specified callback for each object // in the []map[string]interface{}. // // Panics if the object is the wrong type. func (v *Value) EachMSI(callback func(int, map[string]interface{}) bool) *Value { for index, val := range v.MustMSISlice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereMSI uses the specified decider function to select items // from the []map[string]interface{}. The object contained in the result will contain // only the selected items. func (v *Value) WhereMSI(decider func(int, map[string]interface{}) bool) *Value { var selected []map[string]interface{} v.EachMSI(func(index int, val map[string]interface{}) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupMSI uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]map[string]interface{}. func (v *Value) GroupMSI(grouper func(int, map[string]interface{}) string) *Value { groups := make(map[string][]map[string]interface{}) v.EachMSI(func(index int, val map[string]interface{}) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]map[string]interface{}, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceMSI uses the specified function to replace each map[string]interface{}s // by iterating each item. The data in the returned result will be a // []map[string]interface{} containing the replaced items. func (v *Value) ReplaceMSI(replacer func(int, map[string]interface{}) map[string]interface{}) *Value { arr := v.MustMSISlice() replaced := make([]map[string]interface{}, len(arr)) v.EachMSI(func(index int, val map[string]interface{}) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectMSI uses the specified collector function to collect a value // for each of the map[string]interface{}s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectMSI(collector func(int, map[string]interface{}) interface{}) *Value { arr := v.MustMSISlice() collected := make([]interface{}, len(arr)) v.EachMSI(func(index int, val map[string]interface{}) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* ObjxMap ((Map) and [](Map)) */ // ObjxMap gets the value as a (Map), returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) ObjxMap(optionalDefault ...(Map)) Map { if s, ok := v.data.((Map)); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return New(nil) } // MustObjxMap gets the value as a (Map). // // Panics if the object is not a (Map). func (v *Value) MustObjxMap() Map { return v.data.((Map)) } // ObjxMapSlice gets the value as a [](Map), returns the optionalDefault // value or nil if the value is not a [](Map). func (v *Value) ObjxMapSlice(optionalDefault ...[](Map)) [](Map) { if s, ok := v.data.([](Map)); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustObjxMapSlice gets the value as a [](Map). // // Panics if the object is not a [](Map). func (v *Value) MustObjxMapSlice() [](Map) { return v.data.([](Map)) } // IsObjxMap gets whether the object contained is a (Map) or not. func (v *Value) IsObjxMap() bool { _, ok := v.data.((Map)) return ok } // IsObjxMapSlice gets whether the object contained is a [](Map) or not. func (v *Value) IsObjxMapSlice() bool { _, ok := v.data.([](Map)) return ok } // EachObjxMap calls the specified callback for each object // in the [](Map). // // Panics if the object is the wrong type. func (v *Value) EachObjxMap(callback func(int, Map) bool) *Value { for index, val := range v.MustObjxMapSlice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereObjxMap uses the specified decider function to select items // from the [](Map). The object contained in the result will contain // only the selected items. func (v *Value) WhereObjxMap(decider func(int, Map) bool) *Value { var selected [](Map) v.EachObjxMap(func(index int, val Map) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupObjxMap uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][](Map). func (v *Value) GroupObjxMap(grouper func(int, Map) string) *Value { groups := make(map[string][](Map)) v.EachObjxMap(func(index int, val Map) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([](Map), 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceObjxMap uses the specified function to replace each (Map)s // by iterating each item. The data in the returned result will be a // [](Map) containing the replaced items. func (v *Value) ReplaceObjxMap(replacer func(int, Map) Map) *Value { arr := v.MustObjxMapSlice() replaced := make([](Map), len(arr)) v.EachObjxMap(func(index int, val Map) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectObjxMap uses the specified collector function to collect a value // for each of the (Map)s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectObjxMap(collector func(int, Map) interface{}) *Value { arr := v.MustObjxMapSlice() collected := make([]interface{}, len(arr)) v.EachObjxMap(func(index int, val Map) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Bool (bool and []bool) */ // Bool gets the value as a bool, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Bool(optionalDefault ...bool) bool { if s, ok := v.data.(bool); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return false } // MustBool gets the value as a bool. // // Panics if the object is not a bool. func (v *Value) MustBool() bool { return v.data.(bool) } // BoolSlice gets the value as a []bool, returns the optionalDefault // value or nil if the value is not a []bool. func (v *Value) BoolSlice(optionalDefault ...[]bool) []bool { if s, ok := v.data.([]bool); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustBoolSlice gets the value as a []bool. // // Panics if the object is not a []bool. func (v *Value) MustBoolSlice() []bool { return v.data.([]bool) } // IsBool gets whether the object contained is a bool or not. func (v *Value) IsBool() bool { _, ok := v.data.(bool) return ok } // IsBoolSlice gets whether the object contained is a []bool or not. func (v *Value) IsBoolSlice() bool { _, ok := v.data.([]bool) return ok } // EachBool calls the specified callback for each object // in the []bool. // // Panics if the object is the wrong type. func (v *Value) EachBool(callback func(int, bool) bool) *Value { for index, val := range v.MustBoolSlice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereBool uses the specified decider function to select items // from the []bool. The object contained in the result will contain // only the selected items. func (v *Value) WhereBool(decider func(int, bool) bool) *Value { var selected []bool v.EachBool(func(index int, val bool) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupBool uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]bool. func (v *Value) GroupBool(grouper func(int, bool) string) *Value { groups := make(map[string][]bool) v.EachBool(func(index int, val bool) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]bool, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceBool uses the specified function to replace each bools // by iterating each item. The data in the returned result will be a // []bool containing the replaced items. func (v *Value) ReplaceBool(replacer func(int, bool) bool) *Value { arr := v.MustBoolSlice() replaced := make([]bool, len(arr)) v.EachBool(func(index int, val bool) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectBool uses the specified collector function to collect a value // for each of the bools in the slice. The data returned will be a // []interface{}. func (v *Value) CollectBool(collector func(int, bool) interface{}) *Value { arr := v.MustBoolSlice() collected := make([]interface{}, len(arr)) v.EachBool(func(index int, val bool) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Str (string and []string) */ // Str gets the value as a string, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Str(optionalDefault ...string) string { if s, ok := v.data.(string); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return "" } // MustStr gets the value as a string. // // Panics if the object is not a string. func (v *Value) MustStr() string { return v.data.(string) } // StrSlice gets the value as a []string, returns the optionalDefault // value or nil if the value is not a []string. func (v *Value) StrSlice(optionalDefault ...[]string) []string { if s, ok := v.data.([]string); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustStrSlice gets the value as a []string. // // Panics if the object is not a []string. func (v *Value) MustStrSlice() []string { return v.data.([]string) } // IsStr gets whether the object contained is a string or not. func (v *Value) IsStr() bool { _, ok := v.data.(string) return ok } // IsStrSlice gets whether the object contained is a []string or not. func (v *Value) IsStrSlice() bool { _, ok := v.data.([]string) return ok } // EachStr calls the specified callback for each object // in the []string. // // Panics if the object is the wrong type. func (v *Value) EachStr(callback func(int, string) bool) *Value { for index, val := range v.MustStrSlice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereStr uses the specified decider function to select items // from the []string. The object contained in the result will contain // only the selected items. func (v *Value) WhereStr(decider func(int, string) bool) *Value { var selected []string v.EachStr(func(index int, val string) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupStr uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]string. func (v *Value) GroupStr(grouper func(int, string) string) *Value { groups := make(map[string][]string) v.EachStr(func(index int, val string) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]string, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceStr uses the specified function to replace each strings // by iterating each item. The data in the returned result will be a // []string containing the replaced items. func (v *Value) ReplaceStr(replacer func(int, string) string) *Value { arr := v.MustStrSlice() replaced := make([]string, len(arr)) v.EachStr(func(index int, val string) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectStr uses the specified collector function to collect a value // for each of the strings in the slice. The data returned will be a // []interface{}. func (v *Value) CollectStr(collector func(int, string) interface{}) *Value { arr := v.MustStrSlice() collected := make([]interface{}, len(arr)) v.EachStr(func(index int, val string) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Int (int and []int) */ // Int gets the value as a int, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Int(optionalDefault ...int) int { if s, ok := v.data.(int); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustInt gets the value as a int. // // Panics if the object is not a int. func (v *Value) MustInt() int { return v.data.(int) } // IntSlice gets the value as a []int, returns the optionalDefault // value or nil if the value is not a []int. func (v *Value) IntSlice(optionalDefault ...[]int) []int { if s, ok := v.data.([]int); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustIntSlice gets the value as a []int. // // Panics if the object is not a []int. func (v *Value) MustIntSlice() []int { return v.data.([]int) } // IsInt gets whether the object contained is a int or not. func (v *Value) IsInt() bool { _, ok := v.data.(int) return ok } // IsIntSlice gets whether the object contained is a []int or not. func (v *Value) IsIntSlice() bool { _, ok := v.data.([]int) return ok } // EachInt calls the specified callback for each object // in the []int. // // Panics if the object is the wrong type. func (v *Value) EachInt(callback func(int, int) bool) *Value { for index, val := range v.MustIntSlice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereInt uses the specified decider function to select items // from the []int. The object contained in the result will contain // only the selected items. func (v *Value) WhereInt(decider func(int, int) bool) *Value { var selected []int v.EachInt(func(index int, val int) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupInt uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]int. func (v *Value) GroupInt(grouper func(int, int) string) *Value { groups := make(map[string][]int) v.EachInt(func(index int, val int) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]int, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceInt uses the specified function to replace each ints // by iterating each item. The data in the returned result will be a // []int containing the replaced items. func (v *Value) ReplaceInt(replacer func(int, int) int) *Value { arr := v.MustIntSlice() replaced := make([]int, len(arr)) v.EachInt(func(index int, val int) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectInt uses the specified collector function to collect a value // for each of the ints in the slice. The data returned will be a // []interface{}. func (v *Value) CollectInt(collector func(int, int) interface{}) *Value { arr := v.MustIntSlice() collected := make([]interface{}, len(arr)) v.EachInt(func(index int, val int) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Int8 (int8 and []int8) */ // Int8 gets the value as a int8, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Int8(optionalDefault ...int8) int8 { if s, ok := v.data.(int8); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustInt8 gets the value as a int8. // // Panics if the object is not a int8. func (v *Value) MustInt8() int8 { return v.data.(int8) } // Int8Slice gets the value as a []int8, returns the optionalDefault // value or nil if the value is not a []int8. func (v *Value) Int8Slice(optionalDefault ...[]int8) []int8 { if s, ok := v.data.([]int8); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustInt8Slice gets the value as a []int8. // // Panics if the object is not a []int8. func (v *Value) MustInt8Slice() []int8 { return v.data.([]int8) } // IsInt8 gets whether the object contained is a int8 or not. func (v *Value) IsInt8() bool { _, ok := v.data.(int8) return ok } // IsInt8Slice gets whether the object contained is a []int8 or not. func (v *Value) IsInt8Slice() bool { _, ok := v.data.([]int8) return ok } // EachInt8 calls the specified callback for each object // in the []int8. // // Panics if the object is the wrong type. func (v *Value) EachInt8(callback func(int, int8) bool) *Value { for index, val := range v.MustInt8Slice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereInt8 uses the specified decider function to select items // from the []int8. The object contained in the result will contain // only the selected items. func (v *Value) WhereInt8(decider func(int, int8) bool) *Value { var selected []int8 v.EachInt8(func(index int, val int8) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupInt8 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]int8. func (v *Value) GroupInt8(grouper func(int, int8) string) *Value { groups := make(map[string][]int8) v.EachInt8(func(index int, val int8) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]int8, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceInt8 uses the specified function to replace each int8s // by iterating each item. The data in the returned result will be a // []int8 containing the replaced items. func (v *Value) ReplaceInt8(replacer func(int, int8) int8) *Value { arr := v.MustInt8Slice() replaced := make([]int8, len(arr)) v.EachInt8(func(index int, val int8) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectInt8 uses the specified collector function to collect a value // for each of the int8s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectInt8(collector func(int, int8) interface{}) *Value { arr := v.MustInt8Slice() collected := make([]interface{}, len(arr)) v.EachInt8(func(index int, val int8) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Int16 (int16 and []int16) */ // Int16 gets the value as a int16, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Int16(optionalDefault ...int16) int16 { if s, ok := v.data.(int16); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustInt16 gets the value as a int16. // // Panics if the object is not a int16. func (v *Value) MustInt16() int16 { return v.data.(int16) } // Int16Slice gets the value as a []int16, returns the optionalDefault // value or nil if the value is not a []int16. func (v *Value) Int16Slice(optionalDefault ...[]int16) []int16 { if s, ok := v.data.([]int16); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustInt16Slice gets the value as a []int16. // // Panics if the object is not a []int16. func (v *Value) MustInt16Slice() []int16 { return v.data.([]int16) } // IsInt16 gets whether the object contained is a int16 or not. func (v *Value) IsInt16() bool { _, ok := v.data.(int16) return ok } // IsInt16Slice gets whether the object contained is a []int16 or not. func (v *Value) IsInt16Slice() bool { _, ok := v.data.([]int16) return ok } // EachInt16 calls the specified callback for each object // in the []int16. // // Panics if the object is the wrong type. func (v *Value) EachInt16(callback func(int, int16) bool) *Value { for index, val := range v.MustInt16Slice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereInt16 uses the specified decider function to select items // from the []int16. The object contained in the result will contain // only the selected items. func (v *Value) WhereInt16(decider func(int, int16) bool) *Value { var selected []int16 v.EachInt16(func(index int, val int16) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupInt16 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]int16. func (v *Value) GroupInt16(grouper func(int, int16) string) *Value { groups := make(map[string][]int16) v.EachInt16(func(index int, val int16) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]int16, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceInt16 uses the specified function to replace each int16s // by iterating each item. The data in the returned result will be a // []int16 containing the replaced items. func (v *Value) ReplaceInt16(replacer func(int, int16) int16) *Value { arr := v.MustInt16Slice() replaced := make([]int16, len(arr)) v.EachInt16(func(index int, val int16) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectInt16 uses the specified collector function to collect a value // for each of the int16s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectInt16(collector func(int, int16) interface{}) *Value { arr := v.MustInt16Slice() collected := make([]interface{}, len(arr)) v.EachInt16(func(index int, val int16) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Int32 (int32 and []int32) */ // Int32 gets the value as a int32, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Int32(optionalDefault ...int32) int32 { if s, ok := v.data.(int32); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustInt32 gets the value as a int32. // // Panics if the object is not a int32. func (v *Value) MustInt32() int32 { return v.data.(int32) } // Int32Slice gets the value as a []int32, returns the optionalDefault // value or nil if the value is not a []int32. func (v *Value) Int32Slice(optionalDefault ...[]int32) []int32 { if s, ok := v.data.([]int32); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustInt32Slice gets the value as a []int32. // // Panics if the object is not a []int32. func (v *Value) MustInt32Slice() []int32 { return v.data.([]int32) } // IsInt32 gets whether the object contained is a int32 or not. func (v *Value) IsInt32() bool { _, ok := v.data.(int32) return ok } // IsInt32Slice gets whether the object contained is a []int32 or not. func (v *Value) IsInt32Slice() bool { _, ok := v.data.([]int32) return ok } // EachInt32 calls the specified callback for each object // in the []int32. // // Panics if the object is the wrong type. func (v *Value) EachInt32(callback func(int, int32) bool) *Value { for index, val := range v.MustInt32Slice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereInt32 uses the specified decider function to select items // from the []int32. The object contained in the result will contain // only the selected items. func (v *Value) WhereInt32(decider func(int, int32) bool) *Value { var selected []int32 v.EachInt32(func(index int, val int32) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupInt32 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]int32. func (v *Value) GroupInt32(grouper func(int, int32) string) *Value { groups := make(map[string][]int32) v.EachInt32(func(index int, val int32) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]int32, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceInt32 uses the specified function to replace each int32s // by iterating each item. The data in the returned result will be a // []int32 containing the replaced items. func (v *Value) ReplaceInt32(replacer func(int, int32) int32) *Value { arr := v.MustInt32Slice() replaced := make([]int32, len(arr)) v.EachInt32(func(index int, val int32) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectInt32 uses the specified collector function to collect a value // for each of the int32s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectInt32(collector func(int, int32) interface{}) *Value { arr := v.MustInt32Slice() collected := make([]interface{}, len(arr)) v.EachInt32(func(index int, val int32) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Int64 (int64 and []int64) */ // Int64 gets the value as a int64, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Int64(optionalDefault ...int64) int64 { if s, ok := v.data.(int64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustInt64 gets the value as a int64. // // Panics if the object is not a int64. func (v *Value) MustInt64() int64 { return v.data.(int64) } // Int64Slice gets the value as a []int64, returns the optionalDefault // value or nil if the value is not a []int64. func (v *Value) Int64Slice(optionalDefault ...[]int64) []int64 { if s, ok := v.data.([]int64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustInt64Slice gets the value as a []int64. // // Panics if the object is not a []int64. func (v *Value) MustInt64Slice() []int64 { return v.data.([]int64) } // IsInt64 gets whether the object contained is a int64 or not. func (v *Value) IsInt64() bool { _, ok := v.data.(int64) return ok } // IsInt64Slice gets whether the object contained is a []int64 or not. func (v *Value) IsInt64Slice() bool { _, ok := v.data.([]int64) return ok } // EachInt64 calls the specified callback for each object // in the []int64. // // Panics if the object is the wrong type. func (v *Value) EachInt64(callback func(int, int64) bool) *Value { for index, val := range v.MustInt64Slice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereInt64 uses the specified decider function to select items // from the []int64. The object contained in the result will contain // only the selected items. func (v *Value) WhereInt64(decider func(int, int64) bool) *Value { var selected []int64 v.EachInt64(func(index int, val int64) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupInt64 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]int64. func (v *Value) GroupInt64(grouper func(int, int64) string) *Value { groups := make(map[string][]int64) v.EachInt64(func(index int, val int64) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]int64, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceInt64 uses the specified function to replace each int64s // by iterating each item. The data in the returned result will be a // []int64 containing the replaced items. func (v *Value) ReplaceInt64(replacer func(int, int64) int64) *Value { arr := v.MustInt64Slice() replaced := make([]int64, len(arr)) v.EachInt64(func(index int, val int64) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectInt64 uses the specified collector function to collect a value // for each of the int64s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectInt64(collector func(int, int64) interface{}) *Value { arr := v.MustInt64Slice() collected := make([]interface{}, len(arr)) v.EachInt64(func(index int, val int64) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Uint (uint and []uint) */ // Uint gets the value as a uint, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Uint(optionalDefault ...uint) uint { if s, ok := v.data.(uint); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustUint gets the value as a uint. // // Panics if the object is not a uint. func (v *Value) MustUint() uint { return v.data.(uint) } // UintSlice gets the value as a []uint, returns the optionalDefault // value or nil if the value is not a []uint. func (v *Value) UintSlice(optionalDefault ...[]uint) []uint { if s, ok := v.data.([]uint); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustUintSlice gets the value as a []uint. // // Panics if the object is not a []uint. func (v *Value) MustUintSlice() []uint { return v.data.([]uint) } // IsUint gets whether the object contained is a uint or not. func (v *Value) IsUint() bool { _, ok := v.data.(uint) return ok } // IsUintSlice gets whether the object contained is a []uint or not. func (v *Value) IsUintSlice() bool { _, ok := v.data.([]uint) return ok } // EachUint calls the specified callback for each object // in the []uint. // // Panics if the object is the wrong type. func (v *Value) EachUint(callback func(int, uint) bool) *Value { for index, val := range v.MustUintSlice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereUint uses the specified decider function to select items // from the []uint. The object contained in the result will contain // only the selected items. func (v *Value) WhereUint(decider func(int, uint) bool) *Value { var selected []uint v.EachUint(func(index int, val uint) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupUint uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]uint. func (v *Value) GroupUint(grouper func(int, uint) string) *Value { groups := make(map[string][]uint) v.EachUint(func(index int, val uint) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]uint, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceUint uses the specified function to replace each uints // by iterating each item. The data in the returned result will be a // []uint containing the replaced items. func (v *Value) ReplaceUint(replacer func(int, uint) uint) *Value { arr := v.MustUintSlice() replaced := make([]uint, len(arr)) v.EachUint(func(index int, val uint) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectUint uses the specified collector function to collect a value // for each of the uints in the slice. The data returned will be a // []interface{}. func (v *Value) CollectUint(collector func(int, uint) interface{}) *Value { arr := v.MustUintSlice() collected := make([]interface{}, len(arr)) v.EachUint(func(index int, val uint) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Uint8 (uint8 and []uint8) */ // Uint8 gets the value as a uint8, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Uint8(optionalDefault ...uint8) uint8 { if s, ok := v.data.(uint8); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustUint8 gets the value as a uint8. // // Panics if the object is not a uint8. func (v *Value) MustUint8() uint8 { return v.data.(uint8) } // Uint8Slice gets the value as a []uint8, returns the optionalDefault // value or nil if the value is not a []uint8. func (v *Value) Uint8Slice(optionalDefault ...[]uint8) []uint8 { if s, ok := v.data.([]uint8); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustUint8Slice gets the value as a []uint8. // // Panics if the object is not a []uint8. func (v *Value) MustUint8Slice() []uint8 { return v.data.([]uint8) } // IsUint8 gets whether the object contained is a uint8 or not. func (v *Value) IsUint8() bool { _, ok := v.data.(uint8) return ok } // IsUint8Slice gets whether the object contained is a []uint8 or not. func (v *Value) IsUint8Slice() bool { _, ok := v.data.([]uint8) return ok } // EachUint8 calls the specified callback for each object // in the []uint8. // // Panics if the object is the wrong type. func (v *Value) EachUint8(callback func(int, uint8) bool) *Value { for index, val := range v.MustUint8Slice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereUint8 uses the specified decider function to select items // from the []uint8. The object contained in the result will contain // only the selected items. func (v *Value) WhereUint8(decider func(int, uint8) bool) *Value { var selected []uint8 v.EachUint8(func(index int, val uint8) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupUint8 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]uint8. func (v *Value) GroupUint8(grouper func(int, uint8) string) *Value { groups := make(map[string][]uint8) v.EachUint8(func(index int, val uint8) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]uint8, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceUint8 uses the specified function to replace each uint8s // by iterating each item. The data in the returned result will be a // []uint8 containing the replaced items. func (v *Value) ReplaceUint8(replacer func(int, uint8) uint8) *Value { arr := v.MustUint8Slice() replaced := make([]uint8, len(arr)) v.EachUint8(func(index int, val uint8) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectUint8 uses the specified collector function to collect a value // for each of the uint8s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectUint8(collector func(int, uint8) interface{}) *Value { arr := v.MustUint8Slice() collected := make([]interface{}, len(arr)) v.EachUint8(func(index int, val uint8) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Uint16 (uint16 and []uint16) */ // Uint16 gets the value as a uint16, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Uint16(optionalDefault ...uint16) uint16 { if s, ok := v.data.(uint16); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustUint16 gets the value as a uint16. // // Panics if the object is not a uint16. func (v *Value) MustUint16() uint16 { return v.data.(uint16) } // Uint16Slice gets the value as a []uint16, returns the optionalDefault // value or nil if the value is not a []uint16. func (v *Value) Uint16Slice(optionalDefault ...[]uint16) []uint16 { if s, ok := v.data.([]uint16); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustUint16Slice gets the value as a []uint16. // // Panics if the object is not a []uint16. func (v *Value) MustUint16Slice() []uint16 { return v.data.([]uint16) } // IsUint16 gets whether the object contained is a uint16 or not. func (v *Value) IsUint16() bool { _, ok := v.data.(uint16) return ok } // IsUint16Slice gets whether the object contained is a []uint16 or not. func (v *Value) IsUint16Slice() bool { _, ok := v.data.([]uint16) return ok } // EachUint16 calls the specified callback for each object // in the []uint16. // // Panics if the object is the wrong type. func (v *Value) EachUint16(callback func(int, uint16) bool) *Value { for index, val := range v.MustUint16Slice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereUint16 uses the specified decider function to select items // from the []uint16. The object contained in the result will contain // only the selected items. func (v *Value) WhereUint16(decider func(int, uint16) bool) *Value { var selected []uint16 v.EachUint16(func(index int, val uint16) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupUint16 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]uint16. func (v *Value) GroupUint16(grouper func(int, uint16) string) *Value { groups := make(map[string][]uint16) v.EachUint16(func(index int, val uint16) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]uint16, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceUint16 uses the specified function to replace each uint16s // by iterating each item. The data in the returned result will be a // []uint16 containing the replaced items. func (v *Value) ReplaceUint16(replacer func(int, uint16) uint16) *Value { arr := v.MustUint16Slice() replaced := make([]uint16, len(arr)) v.EachUint16(func(index int, val uint16) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectUint16 uses the specified collector function to collect a value // for each of the uint16s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectUint16(collector func(int, uint16) interface{}) *Value { arr := v.MustUint16Slice() collected := make([]interface{}, len(arr)) v.EachUint16(func(index int, val uint16) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Uint32 (uint32 and []uint32) */ // Uint32 gets the value as a uint32, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Uint32(optionalDefault ...uint32) uint32 { if s, ok := v.data.(uint32); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustUint32 gets the value as a uint32. // // Panics if the object is not a uint32. func (v *Value) MustUint32() uint32 { return v.data.(uint32) } // Uint32Slice gets the value as a []uint32, returns the optionalDefault // value or nil if the value is not a []uint32. func (v *Value) Uint32Slice(optionalDefault ...[]uint32) []uint32 { if s, ok := v.data.([]uint32); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustUint32Slice gets the value as a []uint32. // // Panics if the object is not a []uint32. func (v *Value) MustUint32Slice() []uint32 { return v.data.([]uint32) } // IsUint32 gets whether the object contained is a uint32 or not. func (v *Value) IsUint32() bool { _, ok := v.data.(uint32) return ok } // IsUint32Slice gets whether the object contained is a []uint32 or not. func (v *Value) IsUint32Slice() bool { _, ok := v.data.([]uint32) return ok } // EachUint32 calls the specified callback for each object // in the []uint32. // // Panics if the object is the wrong type. func (v *Value) EachUint32(callback func(int, uint32) bool) *Value { for index, val := range v.MustUint32Slice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereUint32 uses the specified decider function to select items // from the []uint32. The object contained in the result will contain // only the selected items. func (v *Value) WhereUint32(decider func(int, uint32) bool) *Value { var selected []uint32 v.EachUint32(func(index int, val uint32) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupUint32 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]uint32. func (v *Value) GroupUint32(grouper func(int, uint32) string) *Value { groups := make(map[string][]uint32) v.EachUint32(func(index int, val uint32) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]uint32, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceUint32 uses the specified function to replace each uint32s // by iterating each item. The data in the returned result will be a // []uint32 containing the replaced items. func (v *Value) ReplaceUint32(replacer func(int, uint32) uint32) *Value { arr := v.MustUint32Slice() replaced := make([]uint32, len(arr)) v.EachUint32(func(index int, val uint32) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectUint32 uses the specified collector function to collect a value // for each of the uint32s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectUint32(collector func(int, uint32) interface{}) *Value { arr := v.MustUint32Slice() collected := make([]interface{}, len(arr)) v.EachUint32(func(index int, val uint32) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Uint64 (uint64 and []uint64) */ // Uint64 gets the value as a uint64, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Uint64(optionalDefault ...uint64) uint64 { if s, ok := v.data.(uint64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustUint64 gets the value as a uint64. // // Panics if the object is not a uint64. func (v *Value) MustUint64() uint64 { return v.data.(uint64) } // Uint64Slice gets the value as a []uint64, returns the optionalDefault // value or nil if the value is not a []uint64. func (v *Value) Uint64Slice(optionalDefault ...[]uint64) []uint64 { if s, ok := v.data.([]uint64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustUint64Slice gets the value as a []uint64. // // Panics if the object is not a []uint64. func (v *Value) MustUint64Slice() []uint64 { return v.data.([]uint64) } // IsUint64 gets whether the object contained is a uint64 or not. func (v *Value) IsUint64() bool { _, ok := v.data.(uint64) return ok } // IsUint64Slice gets whether the object contained is a []uint64 or not. func (v *Value) IsUint64Slice() bool { _, ok := v.data.([]uint64) return ok } // EachUint64 calls the specified callback for each object // in the []uint64. // // Panics if the object is the wrong type. func (v *Value) EachUint64(callback func(int, uint64) bool) *Value { for index, val := range v.MustUint64Slice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereUint64 uses the specified decider function to select items // from the []uint64. The object contained in the result will contain // only the selected items. func (v *Value) WhereUint64(decider func(int, uint64) bool) *Value { var selected []uint64 v.EachUint64(func(index int, val uint64) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupUint64 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]uint64. func (v *Value) GroupUint64(grouper func(int, uint64) string) *Value { groups := make(map[string][]uint64) v.EachUint64(func(index int, val uint64) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]uint64, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceUint64 uses the specified function to replace each uint64s // by iterating each item. The data in the returned result will be a // []uint64 containing the replaced items. func (v *Value) ReplaceUint64(replacer func(int, uint64) uint64) *Value { arr := v.MustUint64Slice() replaced := make([]uint64, len(arr)) v.EachUint64(func(index int, val uint64) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectUint64 uses the specified collector function to collect a value // for each of the uint64s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectUint64(collector func(int, uint64) interface{}) *Value { arr := v.MustUint64Slice() collected := make([]interface{}, len(arr)) v.EachUint64(func(index int, val uint64) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Uintptr (uintptr and []uintptr) */ // Uintptr gets the value as a uintptr, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Uintptr(optionalDefault ...uintptr) uintptr { if s, ok := v.data.(uintptr); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustUintptr gets the value as a uintptr. // // Panics if the object is not a uintptr. func (v *Value) MustUintptr() uintptr { return v.data.(uintptr) } // UintptrSlice gets the value as a []uintptr, returns the optionalDefault // value or nil if the value is not a []uintptr. func (v *Value) UintptrSlice(optionalDefault ...[]uintptr) []uintptr { if s, ok := v.data.([]uintptr); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustUintptrSlice gets the value as a []uintptr. // // Panics if the object is not a []uintptr. func (v *Value) MustUintptrSlice() []uintptr { return v.data.([]uintptr) } // IsUintptr gets whether the object contained is a uintptr or not. func (v *Value) IsUintptr() bool { _, ok := v.data.(uintptr) return ok } // IsUintptrSlice gets whether the object contained is a []uintptr or not. func (v *Value) IsUintptrSlice() bool { _, ok := v.data.([]uintptr) return ok } // EachUintptr calls the specified callback for each object // in the []uintptr. // // Panics if the object is the wrong type. func (v *Value) EachUintptr(callback func(int, uintptr) bool) *Value { for index, val := range v.MustUintptrSlice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereUintptr uses the specified decider function to select items // from the []uintptr. The object contained in the result will contain // only the selected items. func (v *Value) WhereUintptr(decider func(int, uintptr) bool) *Value { var selected []uintptr v.EachUintptr(func(index int, val uintptr) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupUintptr uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]uintptr. func (v *Value) GroupUintptr(grouper func(int, uintptr) string) *Value { groups := make(map[string][]uintptr) v.EachUintptr(func(index int, val uintptr) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]uintptr, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceUintptr uses the specified function to replace each uintptrs // by iterating each item. The data in the returned result will be a // []uintptr containing the replaced items. func (v *Value) ReplaceUintptr(replacer func(int, uintptr) uintptr) *Value { arr := v.MustUintptrSlice() replaced := make([]uintptr, len(arr)) v.EachUintptr(func(index int, val uintptr) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectUintptr uses the specified collector function to collect a value // for each of the uintptrs in the slice. The data returned will be a // []interface{}. func (v *Value) CollectUintptr(collector func(int, uintptr) interface{}) *Value { arr := v.MustUintptrSlice() collected := make([]interface{}, len(arr)) v.EachUintptr(func(index int, val uintptr) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Float32 (float32 and []float32) */ // Float32 gets the value as a float32, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Float32(optionalDefault ...float32) float32 { if s, ok := v.data.(float32); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustFloat32 gets the value as a float32. // // Panics if the object is not a float32. func (v *Value) MustFloat32() float32 { return v.data.(float32) } // Float32Slice gets the value as a []float32, returns the optionalDefault // value or nil if the value is not a []float32. func (v *Value) Float32Slice(optionalDefault ...[]float32) []float32 { if s, ok := v.data.([]float32); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustFloat32Slice gets the value as a []float32. // // Panics if the object is not a []float32. func (v *Value) MustFloat32Slice() []float32 { return v.data.([]float32) } // IsFloat32 gets whether the object contained is a float32 or not. func (v *Value) IsFloat32() bool { _, ok := v.data.(float32) return ok } // IsFloat32Slice gets whether the object contained is a []float32 or not. func (v *Value) IsFloat32Slice() bool { _, ok := v.data.([]float32) return ok } // EachFloat32 calls the specified callback for each object // in the []float32. // // Panics if the object is the wrong type. func (v *Value) EachFloat32(callback func(int, float32) bool) *Value { for index, val := range v.MustFloat32Slice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereFloat32 uses the specified decider function to select items // from the []float32. The object contained in the result will contain // only the selected items. func (v *Value) WhereFloat32(decider func(int, float32) bool) *Value { var selected []float32 v.EachFloat32(func(index int, val float32) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupFloat32 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]float32. func (v *Value) GroupFloat32(grouper func(int, float32) string) *Value { groups := make(map[string][]float32) v.EachFloat32(func(index int, val float32) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]float32, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceFloat32 uses the specified function to replace each float32s // by iterating each item. The data in the returned result will be a // []float32 containing the replaced items. func (v *Value) ReplaceFloat32(replacer func(int, float32) float32) *Value { arr := v.MustFloat32Slice() replaced := make([]float32, len(arr)) v.EachFloat32(func(index int, val float32) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectFloat32 uses the specified collector function to collect a value // for each of the float32s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectFloat32(collector func(int, float32) interface{}) *Value { arr := v.MustFloat32Slice() collected := make([]interface{}, len(arr)) v.EachFloat32(func(index int, val float32) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Float64 (float64 and []float64) */ // Float64 gets the value as a float64, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Float64(optionalDefault ...float64) float64 { if s, ok := v.data.(float64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustFloat64 gets the value as a float64. // // Panics if the object is not a float64. func (v *Value) MustFloat64() float64 { return v.data.(float64) } // Float64Slice gets the value as a []float64, returns the optionalDefault // value or nil if the value is not a []float64. func (v *Value) Float64Slice(optionalDefault ...[]float64) []float64 { if s, ok := v.data.([]float64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustFloat64Slice gets the value as a []float64. // // Panics if the object is not a []float64. func (v *Value) MustFloat64Slice() []float64 { return v.data.([]float64) } // IsFloat64 gets whether the object contained is a float64 or not. func (v *Value) IsFloat64() bool { _, ok := v.data.(float64) return ok } // IsFloat64Slice gets whether the object contained is a []float64 or not. func (v *Value) IsFloat64Slice() bool { _, ok := v.data.([]float64) return ok } // EachFloat64 calls the specified callback for each object // in the []float64. // // Panics if the object is the wrong type. func (v *Value) EachFloat64(callback func(int, float64) bool) *Value { for index, val := range v.MustFloat64Slice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereFloat64 uses the specified decider function to select items // from the []float64. The object contained in the result will contain // only the selected items. func (v *Value) WhereFloat64(decider func(int, float64) bool) *Value { var selected []float64 v.EachFloat64(func(index int, val float64) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupFloat64 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]float64. func (v *Value) GroupFloat64(grouper func(int, float64) string) *Value { groups := make(map[string][]float64) v.EachFloat64(func(index int, val float64) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]float64, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceFloat64 uses the specified function to replace each float64s // by iterating each item. The data in the returned result will be a // []float64 containing the replaced items. func (v *Value) ReplaceFloat64(replacer func(int, float64) float64) *Value { arr := v.MustFloat64Slice() replaced := make([]float64, len(arr)) v.EachFloat64(func(index int, val float64) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectFloat64 uses the specified collector function to collect a value // for each of the float64s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectFloat64(collector func(int, float64) interface{}) *Value { arr := v.MustFloat64Slice() collected := make([]interface{}, len(arr)) v.EachFloat64(func(index int, val float64) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Complex64 (complex64 and []complex64) */ // Complex64 gets the value as a complex64, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Complex64(optionalDefault ...complex64) complex64 { if s, ok := v.data.(complex64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustComplex64 gets the value as a complex64. // // Panics if the object is not a complex64. func (v *Value) MustComplex64() complex64 { return v.data.(complex64) } // Complex64Slice gets the value as a []complex64, returns the optionalDefault // value or nil if the value is not a []complex64. func (v *Value) Complex64Slice(optionalDefault ...[]complex64) []complex64 { if s, ok := v.data.([]complex64); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustComplex64Slice gets the value as a []complex64. // // Panics if the object is not a []complex64. func (v *Value) MustComplex64Slice() []complex64 { return v.data.([]complex64) } // IsComplex64 gets whether the object contained is a complex64 or not. func (v *Value) IsComplex64() bool { _, ok := v.data.(complex64) return ok } // IsComplex64Slice gets whether the object contained is a []complex64 or not. func (v *Value) IsComplex64Slice() bool { _, ok := v.data.([]complex64) return ok } // EachComplex64 calls the specified callback for each object // in the []complex64. // // Panics if the object is the wrong type. func (v *Value) EachComplex64(callback func(int, complex64) bool) *Value { for index, val := range v.MustComplex64Slice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereComplex64 uses the specified decider function to select items // from the []complex64. The object contained in the result will contain // only the selected items. func (v *Value) WhereComplex64(decider func(int, complex64) bool) *Value { var selected []complex64 v.EachComplex64(func(index int, val complex64) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupComplex64 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]complex64. func (v *Value) GroupComplex64(grouper func(int, complex64) string) *Value { groups := make(map[string][]complex64) v.EachComplex64(func(index int, val complex64) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]complex64, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceComplex64 uses the specified function to replace each complex64s // by iterating each item. The data in the returned result will be a // []complex64 containing the replaced items. func (v *Value) ReplaceComplex64(replacer func(int, complex64) complex64) *Value { arr := v.MustComplex64Slice() replaced := make([]complex64, len(arr)) v.EachComplex64(func(index int, val complex64) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectComplex64 uses the specified collector function to collect a value // for each of the complex64s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectComplex64(collector func(int, complex64) interface{}) *Value { arr := v.MustComplex64Slice() collected := make([]interface{}, len(arr)) v.EachComplex64(func(index int, val complex64) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } /* Complex128 (complex128 and []complex128) */ // Complex128 gets the value as a complex128, returns the optionalDefault // value or a system default object if the value is the wrong type. func (v *Value) Complex128(optionalDefault ...complex128) complex128 { if s, ok := v.data.(complex128); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return 0 } // MustComplex128 gets the value as a complex128. // // Panics if the object is not a complex128. func (v *Value) MustComplex128() complex128 { return v.data.(complex128) } // Complex128Slice gets the value as a []complex128, returns the optionalDefault // value or nil if the value is not a []complex128. func (v *Value) Complex128Slice(optionalDefault ...[]complex128) []complex128 { if s, ok := v.data.([]complex128); ok { return s } if len(optionalDefault) == 1 { return optionalDefault[0] } return nil } // MustComplex128Slice gets the value as a []complex128. // // Panics if the object is not a []complex128. func (v *Value) MustComplex128Slice() []complex128 { return v.data.([]complex128) } // IsComplex128 gets whether the object contained is a complex128 or not. func (v *Value) IsComplex128() bool { _, ok := v.data.(complex128) return ok } // IsComplex128Slice gets whether the object contained is a []complex128 or not. func (v *Value) IsComplex128Slice() bool { _, ok := v.data.([]complex128) return ok } // EachComplex128 calls the specified callback for each object // in the []complex128. // // Panics if the object is the wrong type. func (v *Value) EachComplex128(callback func(int, complex128) bool) *Value { for index, val := range v.MustComplex128Slice() { carryon := callback(index, val) if !carryon { break } } return v } // WhereComplex128 uses the specified decider function to select items // from the []complex128. The object contained in the result will contain // only the selected items. func (v *Value) WhereComplex128(decider func(int, complex128) bool) *Value { var selected []complex128 v.EachComplex128(func(index int, val complex128) bool { shouldSelect := decider(index, val) if !shouldSelect { selected = append(selected, val) } return true }) return &Value{data: selected} } // GroupComplex128 uses the specified grouper function to group the items // keyed by the return of the grouper. The object contained in the // result will contain a map[string][]complex128. func (v *Value) GroupComplex128(grouper func(int, complex128) string) *Value { groups := make(map[string][]complex128) v.EachComplex128(func(index int, val complex128) bool { group := grouper(index, val) if _, ok := groups[group]; !ok { groups[group] = make([]complex128, 0) } groups[group] = append(groups[group], val) return true }) return &Value{data: groups} } // ReplaceComplex128 uses the specified function to replace each complex128s // by iterating each item. The data in the returned result will be a // []complex128 containing the replaced items. func (v *Value) ReplaceComplex128(replacer func(int, complex128) complex128) *Value { arr := v.MustComplex128Slice() replaced := make([]complex128, len(arr)) v.EachComplex128(func(index int, val complex128) bool { replaced[index] = replacer(index, val) return true }) return &Value{data: replaced} } // CollectComplex128 uses the specified collector function to collect a value // for each of the complex128s in the slice. The data returned will be a // []interface{}. func (v *Value) CollectComplex128(collector func(int, complex128) interface{}) *Value { arr := v.MustComplex128Slice() collected := make([]interface{}, len(arr)) v.EachComplex128(func(index int, val complex128) bool { collected[index] = collector(index, val) return true }) return &Value{data: collected} } ================================================ FILE: src/github.com/stretchr/testify/vendor/github.com/stretchr/objx/value.go ================================================ package objx import ( "fmt" "strconv" ) // Value provides methods for extracting interface{} data in various // types. type Value struct { // data contains the raw data being managed by this Value data interface{} } // Data returns the raw data contained by this Value func (v *Value) Data() interface{} { return v.data } // String returns the value always as a string func (v *Value) String() string { switch { case v.IsStr(): return v.Str() case v.IsBool(): return strconv.FormatBool(v.Bool()) case v.IsFloat32(): return strconv.FormatFloat(float64(v.Float32()), 'f', -1, 32) case v.IsFloat64(): return strconv.FormatFloat(v.Float64(), 'f', -1, 64) case v.IsInt(): return strconv.FormatInt(int64(v.Int()), 10) case v.IsInt(): return strconv.FormatInt(int64(v.Int()), 10) case v.IsInt8(): return strconv.FormatInt(int64(v.Int8()), 10) case v.IsInt16(): return strconv.FormatInt(int64(v.Int16()), 10) case v.IsInt32(): return strconv.FormatInt(int64(v.Int32()), 10) case v.IsInt64(): return strconv.FormatInt(v.Int64(), 10) case v.IsUint(): return strconv.FormatUint(uint64(v.Uint()), 10) case v.IsUint8(): return strconv.FormatUint(uint64(v.Uint8()), 10) case v.IsUint16(): return strconv.FormatUint(uint64(v.Uint16()), 10) case v.IsUint32(): return strconv.FormatUint(uint64(v.Uint32()), 10) case v.IsUint64(): return strconv.FormatUint(v.Uint64(), 10) } return fmt.Sprintf("%#v", v.Data()) } ================================================ FILE: src/main.go ================================================ package main import ( "github.com/dolotech/leaf" "server/conf" "server/gate" "server/login" "net/http" "flag" "github.com/golang/glog" "github.com/dolotech/lib/db" "server/model" "server/game" ) var Commit = "" var BUILD_TIME = "" var VERSION = "" var createdb bool func init() { flag.StringVar(&conf.Server.WSAddr, "addr", ":8989", "websocket port") flag.IntVar(&conf.Server.MaxConnNum, "maxconn", 20000, "Max Conn Num") flag.StringVar(&conf.Server.DBUrl, "pg", "postgres://postgres:haosql@127.0.0.1:5432/postgres?sslmode=disable", "pg addr") flag.BoolVar(&createdb, "createdb", false, "initial database") flag.Parse() db.Init(conf.Server.DBUrl) if createdb { createDb() } } func main() { go leaf.Run( game.Module, gate.Module, login.Module, ) // for test client http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("./")))) err := http.ListenAndServe(":12345", nil) if err != nil { glog.Fatalf("ListenAndServe: %v ", err) } } func createDb() { // 建表,只维护和服务器game里面有关的表 err := db.C().Sync(model.User{}, model.Room{}) if err != nil { glog.Errorln(err) } } ================================================ FILE: src/server/algorithm/7462.txt ================================================ TOTAL FIVE CARDS HAND VALUE POKER HAND ===================================================================== 4 T J Q K A Royal Flush ROYAL FLUSH 4 9 T J Q K King High Straight Flush STRAIGHT FLUSH 4 8 9 T J Q Queen High Straight Flush 4 7 8 9 T J Jack High Straight Flush 4 6 7 8 9 T Ten High Straight Flush 4 5 6 7 8 9 Nine High Straight Flush 4 4 5 6 7 8 Eight High Straight Flush 4 3 4 5 6 7 Seven High Straight Flush 4 2 3 4 5 6 Six High Straight Flush 4 A 2 3 4 5 Five High Straight Flush 4 A A A A K Four Aces FOUR OF A KIND 4 A A A A Q 4 A A A A J 4 A A A A T 4 A A A A 9 4 A A A A 8 4 A A A A 7 4 A A A A 6 4 A A A A 5 4 A A A A 4 4 A A A A 3 4 A A A A 2 4 K K K K A Four Kings 4 K K K K Q 4 K K K K J 4 K K K K T 4 K K K K 9 4 K K K K 8 4 K K K K 7 4 K K K K 6 4 K K K K 5 4 K K K K 4 4 K K K K 3 4 K K K K 2 4 Q Q Q Q A Four Queens 4 Q Q Q Q K 4 Q Q Q Q J 4 Q Q Q Q T 4 Q Q Q Q 9 4 Q Q Q Q 8 4 Q Q Q Q 7 4 Q Q Q Q 6 4 Q Q Q Q 5 4 Q Q Q Q 4 4 Q Q Q Q 3 4 Q Q Q Q 2 4 J J J J A Four Jacks 4 J J J J K 4 J J J J Q 4 J J J J T 4 J J J J 9 4 J J J J 8 4 J J J J 7 4 J J J J 6 4 J J J J 5 4 J J J J 4 4 J J J J 3 4 J J J J 2 4 T T T T A Four Tens 4 T T T T K 4 T T T T Q 4 T T T T J 4 T T T T 9 4 T T T T 8 4 T T T T 7 4 T T T T 6 4 T T T T 5 4 T T T T 4 4 T T T T 3 4 T T T T 2 4 9 9 9 9 A Four Nines 4 9 9 9 9 K 4 9 9 9 9 Q 4 9 9 9 9 J 4 9 9 9 9 T 4 9 9 9 9 8 4 9 9 9 9 7 4 9 9 9 9 6 4 9 9 9 9 5 4 9 9 9 9 4 4 9 9 9 9 3 4 9 9 9 9 2 4 8 8 8 8 A Four Eights 4 8 8 8 8 K 4 8 8 8 8 Q 4 8 8 8 8 J 4 8 8 8 8 T 4 8 8 8 8 9 4 8 8 8 8 7 4 8 8 8 8 6 4 8 8 8 8 5 4 8 8 8 8 4 4 8 8 8 8 3 4 8 8 8 8 2 4 7 7 7 7 A Four Sevens 4 7 7 7 7 K 4 7 7 7 7 Q 4 7 7 7 7 J 4 7 7 7 7 T 4 7 7 7 7 9 4 7 7 7 7 8 4 7 7 7 7 6 4 7 7 7 7 5 4 7 7 7 7 4 4 7 7 7 7 3 4 7 7 7 7 2 4 6 6 6 6 A Four Sixes 4 6 6 6 6 K 4 6 6 6 6 Q 4 6 6 6 6 J 4 6 6 6 6 T 4 6 6 6 6 9 4 6 6 6 6 8 4 6 6 6 6 7 4 6 6 6 6 5 4 6 6 6 6 4 4 6 6 6 6 3 4 6 6 6 6 2 4 5 5 5 5 A Four Fives 4 5 5 5 5 K 4 5 5 5 5 Q 4 5 5 5 5 J 4 5 5 5 5 T 4 5 5 5 5 9 4 5 5 5 5 8 4 5 5 5 5 7 4 5 5 5 5 6 4 5 5 5 5 4 4 5 5 5 5 3 4 5 5 5 5 2 4 4 4 4 4 A Four Fours 4 4 4 4 4 K 4 4 4 4 4 Q 4 4 4 4 4 J 4 4 4 4 4 T 4 4 4 4 4 9 4 4 4 4 4 8 4 4 4 4 4 7 4 4 4 4 4 6 4 4 4 4 4 5 4 4 4 4 4 3 4 4 4 4 4 2 4 3 3 3 3 A Four Treys 4 3 3 3 3 K 4 3 3 3 3 Q 4 3 3 3 3 J 4 3 3 3 3 T 4 3 3 3 3 9 4 3 3 3 3 8 4 3 3 3 3 7 4 3 3 3 3 6 4 3 3 3 3 5 4 3 3 3 3 4 4 3 3 3 3 2 4 2 2 2 2 A Four Deuces 4 2 2 2 2 K 4 2 2 2 2 Q 4 2 2 2 2 J 4 2 2 2 2 T 4 2 2 2 2 9 4 2 2 2 2 8 4 2 2 2 2 7 4 2 2 2 2 6 4 2 2 2 2 5 4 2 2 2 2 4 4 2 2 2 2 3 24 A A A K K Aces Full FULL HOUSE 24 A A A Q Q 24 A A A J J 24 A A A T T 24 A A A 9 9 24 A A A 8 8 24 A A A 7 7 24 A A A 6 6 24 A A A 5 5 24 A A A 4 4 24 A A A 3 3 24 A A A 2 2 24 K K K A A Kings Full 24 K K K Q Q 24 K K K J J 24 K K K T T 24 K K K 9 9 24 K K K 8 8 24 K K K 7 7 24 K K K 6 6 24 K K K 5 5 24 K K K 4 4 24 K K K 3 3 24 K K K 2 2 24 Q Q Q A A Queens Full 24 Q Q Q K K 24 Q Q Q J J 24 Q Q Q T T 24 Q Q Q 9 9 24 Q Q Q 8 8 24 Q Q Q 7 7 24 Q Q Q 6 6 24 Q Q Q 5 5 24 Q Q Q 4 4 24 Q Q Q 3 3 24 Q Q Q 2 2 24 J J J A A Jacks Full 24 J J J K K 24 J J J Q Q 24 J J J T T 24 J J J 9 9 24 J J J 8 8 24 J J J 7 7 24 J J J 6 6 24 J J J 5 5 24 J J J 4 4 24 J J J 3 3 24 J J J 2 2 24 T T T A A Tens Full 24 T T T K K 24 T T T Q Q 24 T T T J J 24 T T T 9 9 24 T T T 8 8 24 T T T 7 7 24 T T T 6 6 24 T T T 5 5 24 T T T 4 4 24 T T T 3 3 24 T T T 2 2 24 9 9 9 A A Nines Full 24 9 9 9 K K 24 9 9 9 Q Q 24 9 9 9 J J 24 9 9 9 T T 24 9 9 9 8 8 24 9 9 9 7 7 24 9 9 9 6 6 24 9 9 9 5 5 24 9 9 9 4 4 24 9 9 9 3 3 24 9 9 9 2 2 24 8 8 8 A A Eights Full 24 8 8 8 K K 24 8 8 8 Q Q 24 8 8 8 J J 24 8 8 8 T T 24 8 8 8 9 9 24 8 8 8 7 7 24 8 8 8 6 6 24 8 8 8 5 5 24 8 8 8 4 4 24 8 8 8 3 3 24 8 8 8 2 2 24 7 7 7 A A Sevens Full 24 7 7 7 K K 24 7 7 7 Q Q 24 7 7 7 J J 24 7 7 7 T T 24 7 7 7 9 9 24 7 7 7 8 8 24 7 7 7 6 6 24 7 7 7 5 5 24 7 7 7 4 4 24 7 7 7 3 3 24 7 7 7 2 2 24 6 6 6 A A Sixes Full 24 6 6 6 K K 24 6 6 6 Q Q 24 6 6 6 J J 24 6 6 6 T T 24 6 6 6 9 9 24 6 6 6 8 8 24 6 6 6 7 7 24 6 6 6 5 5 24 6 6 6 4 4 24 6 6 6 3 3 24 6 6 6 2 2 24 5 5 5 A A Fives Full 24 5 5 5 K K 24 5 5 5 Q Q 24 5 5 5 J J 24 5 5 5 T T 24 5 5 5 9 9 24 5 5 5 8 8 24 5 5 5 7 7 24 5 5 5 6 6 24 5 5 5 4 4 24 5 5 5 3 3 24 5 5 5 2 2 24 4 4 4 A A Fours Full 24 4 4 4 K K 24 4 4 4 Q Q 24 4 4 4 J J 24 4 4 4 T T 24 4 4 4 9 9 24 4 4 4 8 8 24 4 4 4 7 7 24 4 4 4 6 6 24 4 4 4 5 5 24 4 4 4 3 3 24 4 4 4 2 2 24 3 3 3 A A Threes Full 24 3 3 3 K K 24 3 3 3 Q Q 24 3 3 3 J J 24 3 3 3 T T 24 3 3 3 9 9 24 3 3 3 8 8 24 3 3 3 7 7 24 3 3 3 6 6 24 3 3 3 5 5 24 3 3 3 4 4 24 3 3 3 2 2 24 2 2 2 A A Deuces Full 24 2 2 2 K K 24 2 2 2 Q Q 24 2 2 2 J J 24 2 2 2 T T 24 2 2 2 9 9 24 2 2 2 8 8 24 2 2 2 7 7 24 2 2 2 6 6 24 2 2 2 5 5 24 2 2 2 4 4 24 2 2 2 3 3 4 9 J Q K A Ace High Flush FLUSH 4 8 J Q K A 4 7 J Q K A 4 6 J Q K A 4 5 J Q K A 4 4 J Q K A 4 3 J Q K A 4 2 J Q K A 4 9 T Q K A 4 8 T Q K A 4 7 T Q K A 4 6 T Q K A 4 5 T Q K A 4 4 T Q K A 4 3 T Q K A 4 2 T Q K A 4 8 9 Q K A 4 7 9 Q K A 4 6 9 Q K A 4 5 9 Q K A 4 4 9 Q K A 4 3 9 Q K A 4 2 9 Q K A 4 7 8 Q K A 4 6 8 Q K A 4 5 8 Q K A 4 4 8 Q K A 4 3 8 Q K A 4 2 8 Q K A 4 6 7 Q K A 4 5 7 Q K A 4 4 7 Q K A 4 3 7 Q K A 4 2 7 Q K A 4 5 6 Q K A 4 4 6 Q K A 4 3 6 Q K A 4 2 6 Q K A 4 4 5 Q K A 4 3 5 Q K A 4 2 5 Q K A 4 3 4 Q K A 4 2 4 Q K A 4 2 3 Q K A 4 9 T J K A 4 8 T J K A 4 7 T J K A 4 6 T J K A 4 5 T J K A 4 4 T J K A 4 3 T J K A 4 2 T J K A 4 8 9 J K A 4 7 9 J K A 4 6 9 J K A 4 5 9 J K A 4 4 9 J K A 4 3 9 J K A 4 2 9 J K A 4 7 8 J K A 4 6 8 J K A 4 5 8 J K A 4 4 8 J K A 4 3 8 J K A 4 2 8 J K A 4 6 7 J K A 4 5 7 J K A 4 4 7 J K A 4 3 7 J K A 4 2 7 J K A 4 5 6 J K A 4 4 6 J K A 4 3 6 J K A 4 2 6 J K A 4 4 5 J K A 4 3 5 J K A 4 2 5 J K A 4 3 4 J K A 4 2 4 J K A 4 2 3 J K A 4 8 9 T K A 4 7 9 T K A 4 6 9 T K A 4 5 9 T K A 4 4 9 T K A 4 3 9 T K A 4 2 9 T K A 4 7 8 T K A 4 6 8 T K A 4 5 8 T K A 4 4 8 T K A 4 3 8 T K A 4 2 8 T K A 4 6 7 T K A 4 5 7 T K A 4 4 7 T K A 4 3 7 T K A 4 2 7 T K A 4 5 6 T K A 4 4 6 T K A 4 3 6 T K A 4 2 6 T K A 4 4 5 T K A 4 3 5 T K A 4 2 5 T K A 4 3 4 T K A 4 2 4 T K A 4 2 3 T K A 4 7 8 9 K A 4 6 8 9 K A 4 5 8 9 K A 4 4 8 9 K A 4 3 8 9 K A 4 2 8 9 K A 4 6 7 9 K A 4 5 7 9 K A 4 4 7 9 K A 4 3 7 9 K A 4 2 7 9 K A 4 5 6 9 K A 4 4 6 9 K A 4 3 6 9 K A 4 2 6 9 K A 4 4 5 9 K A 4 3 5 9 K A 4 2 5 9 K A 4 3 4 9 K A 4 2 4 9 K A 4 2 3 9 K A 4 6 7 8 K A 4 5 7 8 K A 4 4 7 8 K A 4 3 7 8 K A 4 2 7 8 K A 4 5 6 8 K A 4 4 6 8 K A 4 3 6 8 K A 4 2 6 8 K A 4 4 5 8 K A 4 3 5 8 K A 4 2 5 8 K A 4 3 4 8 K A 4 2 4 8 K A 4 2 3 8 K A 4 5 6 7 K A 4 4 6 7 K A 4 3 6 7 K A 4 2 6 7 K A 4 4 5 7 K A 4 3 5 7 K A 4 2 5 7 K A 4 3 4 7 K A 4 2 4 7 K A 4 2 3 7 K A 4 4 5 6 K A 4 3 5 6 K A 4 2 5 6 K A 4 3 4 6 K A 4 2 4 6 K A 4 2 3 6 K A 4 3 4 5 K A 4 2 4 5 K A 4 2 3 5 K A 4 2 3 4 K A 4 9 T J Q A 4 8 T J Q A 4 7 T J Q A 4 6 T J Q A 4 5 T J Q A 4 4 T J Q A 4 3 T J Q A 4 2 T J Q A 4 8 9 J Q A 4 7 9 J Q A 4 6 9 J Q A 4 5 9 J Q A 4 4 9 J Q A 4 3 9 J Q A 4 2 9 J Q A 4 7 8 J Q A 4 6 8 J Q A 4 5 8 J Q A 4 4 8 J Q A 4 3 8 J Q A 4 2 8 J Q A 4 6 7 J Q A 4 5 7 J Q A 4 4 7 J Q A 4 3 7 J Q A 4 2 7 J Q A 4 5 6 J Q A 4 4 6 J Q A 4 3 6 J Q A 4 2 6 J Q A 4 4 5 J Q A 4 3 5 J Q A 4 2 5 J Q A 4 3 4 J Q A 4 2 4 J Q A 4 2 3 J Q A 4 8 9 T Q A 4 7 9 T Q A 4 6 9 T Q A 4 5 9 T Q A 4 4 9 T Q A 4 3 9 T Q A 4 2 9 T Q A 4 7 8 T Q A 4 6 8 T Q A 4 5 8 T Q A 4 4 8 T Q A 4 3 8 T Q A 4 2 8 T Q A 4 6 7 T Q A 4 5 7 T Q A 4 4 7 T Q A 4 3 7 T Q A 4 2 7 T Q A 4 5 6 T Q A 4 4 6 T Q A 4 3 6 T Q A 4 2 6 T Q A 4 4 5 T Q A 4 3 5 T Q A 4 2 5 T Q A 4 3 4 T Q A 4 2 4 T Q A 4 2 3 T Q A 4 7 8 9 Q A 4 6 8 9 Q A 4 5 8 9 Q A 4 4 8 9 Q A 4 3 8 9 Q A 4 2 8 9 Q A 4 6 7 9 Q A 4 5 7 9 Q A 4 4 7 9 Q A 4 3 7 9 Q A 4 2 7 9 Q A 4 5 6 9 Q A 4 4 6 9 Q A 4 3 6 9 Q A 4 2 6 9 Q A 4 4 5 9 Q A 4 3 5 9 Q A 4 2 5 9 Q A 4 3 4 9 Q A 4 2 4 9 Q A 4 2 3 9 Q A 4 6 7 8 Q A 4 5 7 8 Q A 4 4 7 8 Q A 4 3 7 8 Q A 4 2 7 8 Q A 4 5 6 8 Q A 4 4 6 8 Q A 4 3 6 8 Q A 4 2 6 8 Q A 4 4 5 8 Q A 4 3 5 8 Q A 4 2 5 8 Q A 4 3 4 8 Q A 4 2 4 8 Q A 4 2 3 8 Q A 4 5 6 7 Q A 4 4 6 7 Q A 4 3 6 7 Q A 4 2 6 7 Q A 4 4 5 7 Q A 4 3 5 7 Q A 4 2 5 7 Q A 4 3 4 7 Q A 4 2 4 7 Q A 4 2 3 7 Q A 4 4 5 6 Q A 4 3 5 6 Q A 4 2 5 6 Q A 4 3 4 6 Q A 4 2 4 6 Q A 4 2 3 6 Q A 4 3 4 5 Q A 4 2 4 5 Q A 4 2 3 5 Q A 4 2 3 4 Q A 4 8 9 T J A 4 7 9 T J A 4 6 9 T J A 4 5 9 T J A 4 4 9 T J A 4 3 9 T J A 4 2 9 T J A 4 7 8 T J A 4 6 8 T J A 4 5 8 T J A 4 4 8 T J A 4 3 8 T J A 4 2 8 T J A 4 6 7 T J A 4 5 7 T J A 4 4 7 T J A 4 3 7 T J A 4 2 7 T J A 4 5 6 T J A 4 4 6 T J A 4 3 6 T J A 4 2 6 T J A 4 4 5 T J A 4 3 5 T J A 4 2 5 T J A 4 3 4 T J A 4 2 4 T J A 4 2 3 T J A 4 7 8 9 J A 4 6 8 9 J A 4 5 8 9 J A 4 4 8 9 J A 4 3 8 9 J A 4 2 8 9 J A 4 6 7 9 J A 4 5 7 9 J A 4 4 7 9 J A 4 3 7 9 J A 4 2 7 9 J A 4 5 6 9 J A 4 4 6 9 J A 4 3 6 9 J A 4 2 6 9 J A 4 4 5 9 J A 4 3 5 9 J A 4 2 5 9 J A 4 3 4 9 J A 4 2 4 9 J A 4 2 3 9 J A 4 6 7 8 J A 4 5 7 8 J A 4 4 7 8 J A 4 3 7 8 J A 4 2 7 8 J A 4 5 6 8 J A 4 4 6 8 J A 4 3 6 8 J A 4 2 6 8 J A 4 4 5 8 J A 4 3 5 8 J A 4 2 5 8 J A 4 3 4 8 J A 4 2 4 8 J A 4 2 3 8 J A 4 5 6 7 J A 4 4 6 7 J A 4 3 6 7 J A 4 2 6 7 J A 4 4 5 7 J A 4 3 5 7 J A 4 2 5 7 J A 4 3 4 7 J A 4 2 4 7 J A 4 2 3 7 J A 4 4 5 6 J A 4 3 5 6 J A 4 2 5 6 J A 4 3 4 6 J A 4 2 4 6 J A 4 2 3 6 J A 4 3 4 5 J A 4 2 4 5 J A 4 2 3 5 J A 4 2 3 4 J A 4 7 8 9 T A 4 6 8 9 T A 4 5 8 9 T A 4 4 8 9 T A 4 3 8 9 T A 4 2 8 9 T A 4 6 7 9 T A 4 5 7 9 T A 4 4 7 9 T A 4 3 7 9 T A 4 2 7 9 T A 4 5 6 9 T A 4 4 6 9 T A 4 3 6 9 T A 4 2 6 9 T A 4 4 5 9 T A 4 3 5 9 T A 4 2 5 9 T A 4 3 4 9 T A 4 2 4 9 T A 4 2 3 9 T A 4 6 7 8 T A 4 5 7 8 T A 4 4 7 8 T A 4 3 7 8 T A 4 2 7 8 T A 4 5 6 8 T A 4 4 6 8 T A 4 3 6 8 T A 4 2 6 8 T A 4 4 5 8 T A 4 3 5 8 T A 4 2 5 8 T A 4 3 4 8 T A 4 2 4 8 T A 4 2 3 8 T A 4 5 6 7 T A 4 4 6 7 T A 4 3 6 7 T A 4 2 6 7 T A 4 4 5 7 T A 4 3 5 7 T A 4 2 5 7 T A 4 3 4 7 T A 4 2 4 7 T A 4 2 3 7 T A 4 4 5 6 T A 4 3 5 6 T A 4 2 5 6 T A 4 3 4 6 T A 4 2 4 6 T A 4 2 3 6 T A 4 3 4 5 T A 4 2 4 5 T A 4 2 3 5 T A 4 2 3 4 T A 4 6 7 8 9 A 4 5 7 8 9 A 4 4 7 8 9 A 4 3 7 8 9 A 4 2 7 8 9 A 4 5 6 8 9 A 4 4 6 8 9 A 4 3 6 8 9 A 4 2 6 8 9 A 4 4 5 8 9 A 4 3 5 8 9 A 4 2 5 8 9 A 4 3 4 8 9 A 4 2 4 8 9 A 4 2 3 8 9 A 4 5 6 7 9 A 4 4 6 7 9 A 4 3 6 7 9 A 4 2 6 7 9 A 4 4 5 7 9 A 4 3 5 7 9 A 4 2 5 7 9 A 4 3 4 7 9 A 4 2 4 7 9 A 4 2 3 7 9 A 4 4 5 6 9 A 4 3 5 6 9 A 4 2 5 6 9 A 4 3 4 6 9 A 4 2 4 6 9 A 4 2 3 6 9 A 4 3 4 5 9 A 4 2 4 5 9 A 4 2 3 5 9 A 4 2 3 4 9 A 4 5 6 7 8 A 4 4 6 7 8 A 4 3 6 7 8 A 4 2 6 7 8 A 4 4 5 7 8 A 4 3 5 7 8 A 4 2 5 7 8 A 4 3 4 7 8 A 4 2 4 7 8 A 4 2 3 7 8 A 4 4 5 6 8 A 4 3 5 6 8 A 4 2 5 6 8 A 4 3 4 6 8 A 4 2 4 6 8 A 4 2 3 6 8 A 4 3 4 5 8 A 4 2 4 5 8 A 4 2 3 5 8 A 4 2 3 4 8 A 4 4 5 6 7 A 4 3 5 6 7 A 4 2 5 6 7 A 4 3 4 6 7 A 4 2 4 6 7 A 4 2 3 6 7 A 4 3 4 5 7 A 4 2 4 5 7 A 4 2 3 5 7 A 4 2 3 4 7 A 4 3 4 5 6 A 4 2 4 5 6 A 4 2 3 5 6 A 4 2 3 4 6 A 4 8 T J Q K King High Flush 4 7 T J Q K 4 6 T J Q K 4 5 T J Q K 4 4 T J Q K 4 3 T J Q K 4 2 T J Q K 4 8 9 J Q K 4 7 9 J Q K 4 6 9 J Q K 4 5 9 J Q K 4 4 9 J Q K 4 3 9 J Q K 4 2 9 J Q K 4 7 8 J Q K 4 6 8 J Q K 4 5 8 J Q K 4 4 8 J Q K 4 3 8 J Q K 4 2 8 J Q K 4 6 7 J Q K 4 5 7 J Q K 4 4 7 J Q K 4 3 7 J Q K 4 2 7 J Q K 4 5 6 J Q K 4 4 6 J Q K 4 3 6 J Q K 4 2 6 J Q K 4 4 5 J Q K 4 3 5 J Q K 4 2 5 J Q K 4 3 4 J Q K 4 2 4 J Q K 4 2 3 J Q K 4 8 9 T Q K 4 7 9 T Q K 4 6 9 T Q K 4 5 9 T Q K 4 4 9 T Q K 4 3 9 T Q K 4 2 9 T Q K 4 7 8 T Q K 4 6 8 T Q K 4 5 8 T Q K 4 4 8 T Q K 4 3 8 T Q K 4 2 8 T Q K 4 6 7 T Q K 4 5 7 T Q K 4 4 7 T Q K 4 3 7 T Q K 4 2 7 T Q K 4 5 6 T Q K 4 4 6 T Q K 4 3 6 T Q K 4 2 6 T Q K 4 4 5 T Q K 4 3 5 T Q K 4 2 5 T Q K 4 3 4 T Q K 4 2 4 T Q K 4 2 3 T Q K 4 7 8 9 Q K 4 6 8 9 Q K 4 5 8 9 Q K 4 4 8 9 Q K 4 3 8 9 Q K 4 2 8 9 Q K 4 6 7 9 Q K 4 5 7 9 Q K 4 4 7 9 Q K 4 3 7 9 Q K 4 2 7 9 Q K 4 5 6 9 Q K 4 4 6 9 Q K 4 3 6 9 Q K 4 2 6 9 Q K 4 4 5 9 Q K 4 3 5 9 Q K 4 2 5 9 Q K 4 3 4 9 Q K 4 2 4 9 Q K 4 2 3 9 Q K 4 6 7 8 Q K 4 5 7 8 Q K 4 4 7 8 Q K 4 3 7 8 Q K 4 2 7 8 Q K 4 5 6 8 Q K 4 4 6 8 Q K 4 3 6 8 Q K 4 2 6 8 Q K 4 4 5 8 Q K 4 3 5 8 Q K 4 2 5 8 Q K 4 3 4 8 Q K 4 2 4 8 Q K 4 2 3 8 Q K 4 5 6 7 Q K 4 4 6 7 Q K 4 3 6 7 Q K 4 2 6 7 Q K 4 4 5 7 Q K 4 3 5 7 Q K 4 2 5 7 Q K 4 3 4 7 Q K 4 2 4 7 Q K 4 2 3 7 Q K 4 4 5 6 Q K 4 3 5 6 Q K 4 2 5 6 Q K 4 3 4 6 Q K 4 2 4 6 Q K 4 2 3 6 Q K 4 3 4 5 Q K 4 2 4 5 Q K 4 2 3 5 Q K 4 2 3 4 Q K 4 8 9 T J K 4 7 9 T J K 4 6 9 T J K 4 5 9 T J K 4 4 9 T J K 4 3 9 T J K 4 2 9 T J K 4 7 8 T J K 4 6 8 T J K 4 5 8 T J K 4 4 8 T J K 4 3 8 T J K 4 2 8 T J K 4 6 7 T J K 4 5 7 T J K 4 4 7 T J K 4 3 7 T J K 4 2 7 T J K 4 5 6 T J K 4 4 6 T J K 4 3 6 T J K 4 2 6 T J K 4 4 5 T J K 4 3 5 T J K 4 2 5 T J K 4 3 4 T J K 4 2 4 T J K 4 2 3 T J K 4 7 8 9 J K 4 6 8 9 J K 4 5 8 9 J K 4 4 8 9 J K 4 3 8 9 J K 4 2 8 9 J K 4 6 7 9 J K 4 5 7 9 J K 4 4 7 9 J K 4 3 7 9 J K 4 2 7 9 J K 4 5 6 9 J K 4 4 6 9 J K 4 3 6 9 J K 4 2 6 9 J K 4 4 5 9 J K 4 3 5 9 J K 4 2 5 9 J K 4 3 4 9 J K 4 2 4 9 J K 4 2 3 9 J K 4 6 7 8 J K 4 5 7 8 J K 4 4 7 8 J K 4 3 7 8 J K 4 2 7 8 J K 4 5 6 8 J K 4 4 6 8 J K 4 3 6 8 J K 4 2 6 8 J K 4 4 5 8 J K 4 3 5 8 J K 4 2 5 8 J K 4 3 4 8 J K 4 2 4 8 J K 4 2 3 8 J K 4 5 6 7 J K 4 4 6 7 J K 4 3 6 7 J K 4 2 6 7 J K 4 4 5 7 J K 4 3 5 7 J K 4 2 5 7 J K 4 3 4 7 J K 4 2 4 7 J K 4 2 3 7 J K 4 4 5 6 J K 4 3 5 6 J K 4 2 5 6 J K 4 3 4 6 J K 4 2 4 6 J K 4 2 3 6 J K 4 3 4 5 J K 4 2 4 5 J K 4 2 3 5 J K 4 2 3 4 J K 4 7 8 9 T K 4 6 8 9 T K 4 5 8 9 T K 4 4 8 9 T K 4 3 8 9 T K 4 2 8 9 T K 4 6 7 9 T K 4 5 7 9 T K 4 4 7 9 T K 4 3 7 9 T K 4 2 7 9 T K 4 5 6 9 T K 4 4 6 9 T K 4 3 6 9 T K 4 2 6 9 T K 4 4 5 9 T K 4 3 5 9 T K 4 2 5 9 T K 4 3 4 9 T K 4 2 4 9 T K 4 2 3 9 T K 4 6 7 8 T K 4 5 7 8 T K 4 4 7 8 T K 4 3 7 8 T K 4 2 7 8 T K 4 5 6 8 T K 4 4 6 8 T K 4 3 6 8 T K 4 2 6 8 T K 4 4 5 8 T K 4 3 5 8 T K 4 2 5 8 T K 4 3 4 8 T K 4 2 4 8 T K 4 2 3 8 T K 4 5 6 7 T K 4 4 6 7 T K 4 3 6 7 T K 4 2 6 7 T K 4 4 5 7 T K 4 3 5 7 T K 4 2 5 7 T K 4 3 4 7 T K 4 2 4 7 T K 4 2 3 7 T K 4 4 5 6 T K 4 3 5 6 T K 4 2 5 6 T K 4 3 4 6 T K 4 2 4 6 T K 4 2 3 6 T K 4 3 4 5 T K 4 2 4 5 T K 4 2 3 5 T K 4 2 3 4 T K 4 6 7 8 9 K 4 5 7 8 9 K 4 4 7 8 9 K 4 3 7 8 9 K 4 2 7 8 9 K 4 5 6 8 9 K 4 4 6 8 9 K 4 3 6 8 9 K 4 2 6 8 9 K 4 4 5 8 9 K 4 3 5 8 9 K 4 2 5 8 9 K 4 3 4 8 9 K 4 2 4 8 9 K 4 2 3 8 9 K 4 5 6 7 9 K 4 4 6 7 9 K 4 3 6 7 9 K 4 2 6 7 9 K 4 4 5 7 9 K 4 3 5 7 9 K 4 2 5 7 9 K 4 3 4 7 9 K 4 2 4 7 9 K 4 2 3 7 9 K 4 4 5 6 9 K 4 3 5 6 9 K 4 2 5 6 9 K 4 3 4 6 9 K 4 2 4 6 9 K 4 2 3 6 9 K 4 3 4 5 9 K 4 2 4 5 9 K 4 2 3 5 9 K 4 2 3 4 9 K 4 5 6 7 8 K 4 4 6 7 8 K 4 3 6 7 8 K 4 2 6 7 8 K 4 4 5 7 8 K 4 3 5 7 8 K 4 2 5 7 8 K 4 3 4 7 8 K 4 2 4 7 8 K 4 2 3 7 8 K 4 4 5 6 8 K 4 3 5 6 8 K 4 2 5 6 8 K 4 3 4 6 8 K 4 2 4 6 8 K 4 2 3 6 8 K 4 3 4 5 8 K 4 2 4 5 8 K 4 2 3 5 8 K 4 2 3 4 8 K 4 4 5 6 7 K 4 3 5 6 7 K 4 2 5 6 7 K 4 3 4 6 7 K 4 2 4 6 7 K 4 2 3 6 7 K 4 3 4 5 7 K 4 2 4 5 7 K 4 2 3 5 7 K 4 2 3 4 7 K 4 3 4 5 6 K 4 2 4 5 6 K 4 2 3 5 6 K 4 2 3 4 6 K 4 2 3 4 5 K 4 7 9 T J Q Queen High Flush 4 6 9 T J Q 4 5 9 T J Q 4 4 9 T J Q 4 3 9 T J Q 4 2 9 T J Q 4 7 8 T J Q 4 6 8 T J Q 4 5 8 T J Q 4 4 8 T J Q 4 3 8 T J Q 4 2 8 T J Q 4 6 7 T J Q 4 5 7 T J Q 4 4 7 T J Q 4 3 7 T J Q 4 2 7 T J Q 4 5 6 T J Q 4 4 6 T J Q 4 3 6 T J Q 4 2 6 T J Q 4 4 5 T J Q 4 3 5 T J Q 4 2 5 T J Q 4 3 4 T J Q 4 2 4 T J Q 4 2 3 T J Q 4 7 8 9 J Q 4 6 8 9 J Q 4 5 8 9 J Q 4 4 8 9 J Q 4 3 8 9 J Q 4 2 8 9 J Q 4 6 7 9 J Q 4 5 7 9 J Q 4 4 7 9 J Q 4 3 7 9 J Q 4 2 7 9 J Q 4 5 6 9 J Q 4 4 6 9 J Q 4 3 6 9 J Q 4 2 6 9 J Q 4 4 5 9 J Q 4 3 5 9 J Q 4 2 5 9 J Q 4 3 4 9 J Q 4 2 4 9 J Q 4 2 3 9 J Q 4 6 7 8 J Q 4 5 7 8 J Q 4 4 7 8 J Q 4 3 7 8 J Q 4 2 7 8 J Q 4 5 6 8 J Q 4 4 6 8 J Q 4 3 6 8 J Q 4 2 6 8 J Q 4 4 5 8 J Q 4 3 5 8 J Q 4 2 5 8 J Q 4 3 4 8 J Q 4 2 4 8 J Q 4 2 3 8 J Q 4 5 6 7 J Q 4 4 6 7 J Q 4 3 6 7 J Q 4 2 6 7 J Q 4 4 5 7 J Q 4 3 5 7 J Q 4 2 5 7 J Q 4 3 4 7 J Q 4 2 4 7 J Q 4 2 3 7 J Q 4 4 5 6 J Q 4 3 5 6 J Q 4 2 5 6 J Q 4 3 4 6 J Q 4 2 4 6 J Q 4 2 3 6 J Q 4 3 4 5 J Q 4 2 4 5 J Q 4 2 3 5 J Q 4 2 3 4 J Q 4 7 8 9 T Q 4 6 8 9 T Q 4 5 8 9 T Q 4 4 8 9 T Q 4 3 8 9 T Q 4 2 8 9 T Q 4 6 7 9 T Q 4 5 7 9 T Q 4 4 7 9 T Q 4 3 7 9 T Q 4 2 7 9 T Q 4 5 6 9 T Q 4 4 6 9 T Q 4 3 6 9 T Q 4 2 6 9 T Q 4 4 5 9 T Q 4 3 5 9 T Q 4 2 5 9 T Q 4 3 4 9 T Q 4 2 4 9 T Q 4 2 3 9 T Q 4 6 7 8 T Q 4 5 7 8 T Q 4 4 7 8 T Q 4 3 7 8 T Q 4 2 7 8 T Q 4 5 6 8 T Q 4 4 6 8 T Q 4 3 6 8 T Q 4 2 6 8 T Q 4 4 5 8 T Q 4 3 5 8 T Q 4 2 5 8 T Q 4 3 4 8 T Q 4 2 4 8 T Q 4 2 3 8 T Q 4 5 6 7 T Q 4 4 6 7 T Q 4 3 6 7 T Q 4 2 6 7 T Q 4 4 5 7 T Q 4 3 5 7 T Q 4 2 5 7 T Q 4 3 4 7 T Q 4 2 4 7 T Q 4 2 3 7 T Q 4 4 5 6 T Q 4 3 5 6 T Q 4 2 5 6 T Q 4 3 4 6 T Q 4 2 4 6 T Q 4 2 3 6 T Q 4 3 4 5 T Q 4 2 4 5 T Q 4 2 3 5 T Q 4 2 3 4 T Q 4 6 7 8 9 Q 4 5 7 8 9 Q 4 4 7 8 9 Q 4 3 7 8 9 Q 4 2 7 8 9 Q 4 5 6 8 9 Q 4 4 6 8 9 Q 4 3 6 8 9 Q 4 2 6 8 9 Q 4 4 5 8 9 Q 4 3 5 8 9 Q 4 2 5 8 9 Q 4 3 4 8 9 Q 4 2 4 8 9 Q 4 2 3 8 9 Q 4 5 6 7 9 Q 4 4 6 7 9 Q 4 3 6 7 9 Q 4 2 6 7 9 Q 4 4 5 7 9 Q 4 3 5 7 9 Q 4 2 5 7 9 Q 4 3 4 7 9 Q 4 2 4 7 9 Q 4 2 3 7 9 Q 4 4 5 6 9 Q 4 3 5 6 9 Q 4 2 5 6 9 Q 4 3 4 6 9 Q 4 2 4 6 9 Q 4 2 3 6 9 Q 4 3 4 5 9 Q 4 2 4 5 9 Q 4 2 3 5 9 Q 4 2 3 4 9 Q 4 5 6 7 8 Q 4 4 6 7 8 Q 4 3 6 7 8 Q 4 2 6 7 8 Q 4 4 5 7 8 Q 4 3 5 7 8 Q 4 2 5 7 8 Q 4 3 4 7 8 Q 4 2 4 7 8 Q 4 2 3 7 8 Q 4 4 5 6 8 Q 4 3 5 6 8 Q 4 2 5 6 8 Q 4 3 4 6 8 Q 4 2 4 6 8 Q 4 2 3 6 8 Q 4 3 4 5 8 Q 4 2 4 5 8 Q 4 2 3 5 8 Q 4 2 3 4 8 Q 4 4 5 6 7 Q 4 3 5 6 7 Q 4 2 5 6 7 Q 4 3 4 6 7 Q 4 2 4 6 7 Q 4 2 3 6 7 Q 4 3 4 5 7 Q 4 2 4 5 7 Q 4 2 3 5 7 Q 4 2 3 4 7 Q 4 3 4 5 6 Q 4 2 4 5 6 Q 4 2 3 5 6 Q 4 2 3 4 6 Q 4 2 3 4 5 Q 4 6 8 9 T J Jack High Flush 4 5 8 9 T J 4 4 8 9 T J 4 3 8 9 T J 4 2 8 9 T J 4 6 7 9 T J 4 5 7 9 T J 4 4 7 9 T J 4 3 7 9 T J 4 2 7 9 T J 4 5 6 9 T J 4 4 6 9 T J 4 3 6 9 T J 4 2 6 9 T J 4 4 5 9 T J 4 3 5 9 T J 4 2 5 9 T J 4 3 4 9 T J 4 2 4 9 T J 4 2 3 9 T J 4 6 7 8 T J 4 5 7 8 T J 4 4 7 8 T J 4 3 7 8 T J 4 2 7 8 T J 4 5 6 8 T J 4 4 6 8 T J 4 3 6 8 T J 4 2 6 8 T J 4 4 5 8 T J 4 3 5 8 T J 4 2 5 8 T J 4 3 4 8 T J 4 2 4 8 T J 4 2 3 8 T J 4 5 6 7 T J 4 4 6 7 T J 4 3 6 7 T J 4 2 6 7 T J 4 4 5 7 T J 4 3 5 7 T J 4 2 5 7 T J 4 3 4 7 T J 4 2 4 7 T J 4 2 3 7 T J 4 4 5 6 T J 4 3 5 6 T J 4 2 5 6 T J 4 3 4 6 T J 4 2 4 6 T J 4 2 3 6 T J 4 3 4 5 T J 4 2 4 5 T J 4 2 3 5 T J 4 2 3 4 T J 4 6 7 8 9 J 4 5 7 8 9 J 4 4 7 8 9 J 4 3 7 8 9 J 4 2 7 8 9 J 4 5 6 8 9 J 4 4 6 8 9 J 4 3 6 8 9 J 4 2 6 8 9 J 4 4 5 8 9 J 4 3 5 8 9 J 4 2 5 8 9 J 4 3 4 8 9 J 4 2 4 8 9 J 4 2 3 8 9 J 4 5 6 7 9 J 4 4 6 7 9 J 4 3 6 7 9 J 4 2 6 7 9 J 4 4 5 7 9 J 4 3 5 7 9 J 4 2 5 7 9 J 4 3 4 7 9 J 4 2 4 7 9 J 4 2 3 7 9 J 4 4 5 6 9 J 4 3 5 6 9 J 4 2 5 6 9 J 4 3 4 6 9 J 4 2 4 6 9 J 4 2 3 6 9 J 4 3 4 5 9 J 4 2 4 5 9 J 4 2 3 5 9 J 4 2 3 4 9 J 4 5 6 7 8 J 4 4 6 7 8 J 4 3 6 7 8 J 4 2 6 7 8 J 4 4 5 7 8 J 4 3 5 7 8 J 4 2 5 7 8 J 4 3 4 7 8 J 4 2 4 7 8 J 4 2 3 7 8 J 4 4 5 6 8 J 4 3 5 6 8 J 4 2 5 6 8 J 4 3 4 6 8 J 4 2 4 6 8 J 4 2 3 6 8 J 4 3 4 5 8 J 4 2 4 5 8 J 4 2 3 5 8 J 4 2 3 4 8 J 4 4 5 6 7 J 4 3 5 6 7 J 4 2 5 6 7 J 4 3 4 6 7 J 4 2 4 6 7 J 4 2 3 6 7 J 4 3 4 5 7 J 4 2 4 5 7 J 4 2 3 5 7 J 4 2 3 4 7 J 4 3 4 5 6 J 4 2 4 5 6 J 4 2 3 5 6 J 4 2 3 4 6 J 4 2 3 4 5 J 4 5 7 8 9 T Ten High Flush 4 4 7 8 9 T 4 3 7 8 9 T 4 2 7 8 9 T 4 5 6 8 9 T 4 4 6 8 9 T 4 3 6 8 9 T 4 2 6 8 9 T 4 4 5 8 9 T 4 3 5 8 9 T 4 2 5 8 9 T 4 3 4 8 9 T 4 2 4 8 9 T 4 2 3 8 9 T 4 5 6 7 9 T 4 4 6 7 9 T 4 3 6 7 9 T 4 2 6 7 9 T 4 4 5 7 9 T 4 3 5 7 9 T 4 2 5 7 9 T 4 3 4 7 9 T 4 2 4 7 9 T 4 2 3 7 9 T 4 4 5 6 9 T 4 3 5 6 9 T 4 2 5 6 9 T 4 3 4 6 9 T 4 2 4 6 9 T 4 2 3 6 9 T 4 3 4 5 9 T 4 2 4 5 9 T 4 2 3 5 9 T 4 2 3 4 9 T 4 5 6 7 8 T 4 4 6 7 8 T 4 3 6 7 8 T 4 2 6 7 8 T 4 4 5 7 8 T 4 3 5 7 8 T 4 2 5 7 8 T 4 3 4 7 8 T 4 2 4 7 8 T 4 2 3 7 8 T 4 4 5 6 8 T 4 3 5 6 8 T 4 2 5 6 8 T 4 3 4 6 8 T 4 2 4 6 8 T 4 2 3 6 8 T 4 3 4 5 8 T 4 2 4 5 8 T 4 2 3 5 8 T 4 2 3 4 8 T 4 4 5 6 7 T 4 3 5 6 7 T 4 2 5 6 7 T 4 3 4 6 7 T 4 2 4 6 7 T 4 2 3 6 7 T 4 3 4 5 7 T 4 2 4 5 7 T 4 2 3 5 7 T 4 2 3 4 7 T 4 3 4 5 6 T 4 2 4 5 6 T 4 2 3 5 6 T 4 2 3 4 6 T 4 2 3 4 5 T 4 4 6 7 8 9 Nine High Flush 4 3 6 7 8 9 4 2 6 7 8 9 4 4 5 7 8 9 4 3 5 7 8 9 4 2 5 7 8 9 4 3 4 7 8 9 4 2 4 7 8 9 4 2 3 7 8 9 4 4 5 6 8 9 4 3 5 6 8 9 4 2 5 6 8 9 4 3 4 6 8 9 4 2 4 6 8 9 4 2 3 6 8 9 4 3 4 5 8 9 4 2 4 5 8 9 4 2 3 5 8 9 4 2 3 4 8 9 4 4 5 6 7 9 4 3 5 6 7 9 4 2 5 6 7 9 4 3 4 6 7 9 4 2 4 6 7 9 4 2 3 6 7 9 4 3 4 5 7 9 4 2 4 5 7 9 4 2 3 5 7 9 4 2 3 4 7 9 4 3 4 5 6 9 4 2 4 5 6 9 4 2 3 5 6 9 4 2 3 4 6 9 4 2 3 4 5 9 4 3 5 6 7 8 Eight High Flush 4 2 5 6 7 8 4 3 4 6 7 8 4 2 4 6 7 8 4 2 3 6 7 8 4 3 4 5 7 8 4 2 4 5 7 8 4 2 3 5 7 8 4 2 3 4 7 8 4 3 4 5 6 8 4 2 4 5 6 8 4 2 3 5 6 8 4 2 3 4 6 8 4 2 3 4 5 8 4 2 4 5 6 7 Seven High Flush 4 2 3 5 6 7 4 2 3 4 6 7 4 2 3 4 5 7 1024 T J Q K A Ace High Straight STRAIGHT 1024 9 T J Q K King High Straight 1024 8 9 T J Q Queen High Straight 1024 7 8 9 T J Jack High Straight 1024 6 7 8 9 T Ten High Straight 1024 5 6 7 8 9 Nine High Straight 1024 4 5 6 7 8 Eight High Straight 1024 3 4 5 6 7 Seven High Straight 1024 2 3 4 5 6 Six High Straight 1024 A 2 3 4 5 Five High Straight 64 Q K A A A Three Aces THREE OF A KIND 64 J K A A A 64 T K A A A 64 9 K A A A 64 8 K A A A 64 7 K A A A 64 6 K A A A 64 5 K A A A 64 4 K A A A 64 3 K A A A 64 2 K A A A 64 J Q A A A 64 T Q A A A 64 9 Q A A A 64 8 Q A A A 64 7 Q A A A 64 6 Q A A A 64 5 Q A A A 64 4 Q A A A 64 3 Q A A A 64 2 Q A A A 64 T J A A A 64 9 J A A A 64 8 J A A A 64 7 J A A A 64 6 J A A A 64 5 J A A A 64 4 J A A A 64 3 J A A A 64 2 J A A A 64 9 T A A A 64 8 T A A A 64 7 T A A A 64 6 T A A A 64 5 T A A A 64 4 T A A A 64 3 T A A A 64 2 T A A A 64 8 9 A A A 64 7 9 A A A 64 6 9 A A A 64 5 9 A A A 64 4 9 A A A 64 3 9 A A A 64 2 9 A A A 64 7 8 A A A 64 6 8 A A A 64 5 8 A A A 64 4 8 A A A 64 3 8 A A A 64 2 8 A A A 64 6 7 A A A 64 5 7 A A A 64 4 7 A A A 64 3 7 A A A 64 2 7 A A A 64 5 6 A A A 64 4 6 A A A 64 3 6 A A A 64 2 6 A A A 64 4 5 A A A 64 3 5 A A A 64 2 5 A A A 64 3 4 A A A 64 2 4 A A A 64 2 3 A A A 64 Q K K K A Three Kings 64 J K K K A 64 T K K K A 64 9 K K K A 64 8 K K K A 64 7 K K K A 64 6 K K K A 64 5 K K K A 64 4 K K K A 64 3 K K K A 64 2 K K K A 64 J Q K K K 64 T Q K K K 64 9 Q K K K 64 8 Q K K K 64 7 Q K K K 64 6 Q K K K 64 5 Q K K K 64 4 Q K K K 64 3 Q K K K 64 2 Q K K K 64 T J K K K 64 9 J K K K 64 8 J K K K 64 7 J K K K 64 6 J K K K 64 5 J K K K 64 4 J K K K 64 3 J K K K 64 2 J K K K 64 9 T K K K 64 8 T K K K 64 7 T K K K 64 6 T K K K 64 5 T K K K 64 4 T K K K 64 3 T K K K 64 2 T K K K 64 8 9 K K K 64 7 9 K K K 64 6 9 K K K 64 5 9 K K K 64 4 9 K K K 64 3 9 K K K 64 2 9 K K K 64 7 8 K K K 64 6 8 K K K 64 5 8 K K K 64 4 8 K K K 64 3 8 K K K 64 2 8 K K K 64 6 7 K K K 64 5 7 K K K 64 4 7 K K K 64 3 7 K K K 64 2 7 K K K 64 5 6 K K K 64 4 6 K K K 64 3 6 K K K 64 2 6 K K K 64 4 5 K K K 64 3 5 K K K 64 2 5 K K K 64 3 4 K K K 64 2 4 K K K 64 2 3 K K K 64 Q Q Q K A Three Queens 64 J Q Q Q A 64 T Q Q Q A 64 9 Q Q Q A 64 8 Q Q Q A 64 7 Q Q Q A 64 6 Q Q Q A 64 5 Q Q Q A 64 4 Q Q Q A 64 3 Q Q Q A 64 2 Q Q Q A 64 J Q Q Q K 64 T Q Q Q K 64 9 Q Q Q K 64 8 Q Q Q K 64 7 Q Q Q K 64 6 Q Q Q K 64 5 Q Q Q K 64 4 Q Q Q K 64 3 Q Q Q K 64 2 Q Q Q K 64 T J Q Q Q 64 9 J Q Q Q 64 8 J Q Q Q 64 7 J Q Q Q 64 6 J Q Q Q 64 5 J Q Q Q 64 4 J Q Q Q 64 3 J Q Q Q 64 2 J Q Q Q 64 9 T Q Q Q 64 8 T Q Q Q 64 7 T Q Q Q 64 6 T Q Q Q 64 5 T Q Q Q 64 4 T Q Q Q 64 3 T Q Q Q 64 2 T Q Q Q 64 8 9 Q Q Q 64 7 9 Q Q Q 64 6 9 Q Q Q 64 5 9 Q Q Q 64 4 9 Q Q Q 64 3 9 Q Q Q 64 2 9 Q Q Q 64 7 8 Q Q Q 64 6 8 Q Q Q 64 5 8 Q Q Q 64 4 8 Q Q Q 64 3 8 Q Q Q 64 2 8 Q Q Q 64 6 7 Q Q Q 64 5 7 Q Q Q 64 4 7 Q Q Q 64 3 7 Q Q Q 64 2 7 Q Q Q 64 5 6 Q Q Q 64 4 6 Q Q Q 64 3 6 Q Q Q 64 2 6 Q Q Q 64 4 5 Q Q Q 64 3 5 Q Q Q 64 2 5 Q Q Q 64 3 4 Q Q Q 64 2 4 Q Q Q 64 2 3 Q Q Q 64 J J J K A Three Jacks 64 J J J Q A 64 T J J J A 64 9 J J J A 64 8 J J J A 64 7 J J J A 64 6 J J J A 64 5 J J J A 64 4 J J J A 64 3 J J J A 64 2 J J J A 64 J J J Q K 64 T J J J K 64 9 J J J K 64 8 J J J K 64 7 J J J K 64 6 J J J K 64 5 J J J K 64 4 J J J K 64 3 J J J K 64 2 J J J K 64 T J J J Q 64 9 J J J Q 64 8 J J J Q 64 7 J J J Q 64 6 J J J Q 64 5 J J J Q 64 4 J J J Q 64 3 J J J Q 64 2 J J J Q 64 9 T J J J 64 8 T J J J 64 7 T J J J 64 6 T J J J 64 5 T J J J 64 4 T J J J 64 3 T J J J 64 2 T J J J 64 8 9 J J J 64 7 9 J J J 64 6 9 J J J 64 5 9 J J J 64 4 9 J J J 64 3 9 J J J 64 2 9 J J J 64 7 8 J J J 64 6 8 J J J 64 5 8 J J J 64 4 8 J J J 64 3 8 J J J 64 2 8 J J J 64 6 7 J J J 64 5 7 J J J 64 4 7 J J J 64 3 7 J J J 64 2 7 J J J 64 5 6 J J J 64 4 6 J J J 64 3 6 J J J 64 2 6 J J J 64 4 5 J J J 64 3 5 J J J 64 2 5 J J J 64 3 4 J J J 64 2 4 J J J 64 2 3 J J J 64 T T T K A Three Tens 64 T T T Q A 64 T T T J A 64 9 T T T A 64 8 T T T A 64 7 T T T A 64 6 T T T A 64 5 T T T A 64 4 T T T A 64 3 T T T A 64 2 T T T A 64 T T T Q K 64 T T T J K 64 9 T T T K 64 8 T T T K 64 7 T T T K 64 6 T T T K 64 5 T T T K 64 4 T T T K 64 3 T T T K 64 2 T T T K 64 T T T J Q 64 9 T T T Q 64 8 T T T Q 64 7 T T T Q 64 6 T T T Q 64 5 T T T Q 64 4 T T T Q 64 3 T T T Q 64 2 T T T Q 64 9 T T T J 64 8 T T T J 64 7 T T T J 64 6 T T T J 64 5 T T T J 64 4 T T T J 64 3 T T T J 64 2 T T T J 64 8 9 T T T 64 7 9 T T T 64 6 9 T T T 64 5 9 T T T 64 4 9 T T T 64 3 9 T T T 64 2 9 T T T 64 7 8 T T T 64 6 8 T T T 64 5 8 T T T 64 4 8 T T T 64 3 8 T T T 64 2 8 T T T 64 6 7 T T T 64 5 7 T T T 64 4 7 T T T 64 3 7 T T T 64 2 7 T T T 64 5 6 T T T 64 4 6 T T T 64 3 6 T T T 64 2 6 T T T 64 4 5 T T T 64 3 5 T T T 64 2 5 T T T 64 3 4 T T T 64 2 4 T T T 64 2 3 T T T 64 9 9 9 K A Three Nines 64 9 9 9 Q A 64 9 9 9 J A 64 9 9 9 T A 64 8 9 9 9 A 64 7 9 9 9 A 64 6 9 9 9 A 64 5 9 9 9 A 64 4 9 9 9 A 64 3 9 9 9 A 64 2 9 9 9 A 64 9 9 9 Q K 64 9 9 9 J K 64 9 9 9 T K 64 8 9 9 9 K 64 7 9 9 9 K 64 6 9 9 9 K 64 5 9 9 9 K 64 4 9 9 9 K 64 3 9 9 9 K 64 2 9 9 9 K 64 9 9 9 J Q 64 9 9 9 T Q 64 8 9 9 9 Q 64 7 9 9 9 Q 64 6 9 9 9 Q 64 5 9 9 9 Q 64 4 9 9 9 Q 64 3 9 9 9 Q 64 2 9 9 9 Q 64 9 9 9 T J 64 8 9 9 9 J 64 7 9 9 9 J 64 6 9 9 9 J 64 5 9 9 9 J 64 4 9 9 9 J 64 3 9 9 9 J 64 2 9 9 9 J 64 8 9 9 9 T 64 7 9 9 9 T 64 6 9 9 9 T 64 5 9 9 9 T 64 4 9 9 9 T 64 3 9 9 9 T 64 2 9 9 9 T 64 7 8 9 9 9 64 6 8 9 9 9 64 5 8 9 9 9 64 4 8 9 9 9 64 3 8 9 9 9 64 2 8 9 9 9 64 6 7 9 9 9 64 5 7 9 9 9 64 4 7 9 9 9 64 3 7 9 9 9 64 2 7 9 9 9 64 5 6 9 9 9 64 4 6 9 9 9 64 3 6 9 9 9 64 2 6 9 9 9 64 4 5 9 9 9 64 3 5 9 9 9 64 2 5 9 9 9 64 3 4 9 9 9 64 2 4 9 9 9 64 2 3 9 9 9 64 8 8 8 K A Three Eights 64 8 8 8 Q A 64 8 8 8 J A 64 8 8 8 T A 64 8 8 8 9 A 64 7 8 8 8 A 64 6 8 8 8 A 64 5 8 8 8 A 64 4 8 8 8 A 64 3 8 8 8 A 64 2 8 8 8 A 64 8 8 8 Q K 64 8 8 8 J K 64 8 8 8 T K 64 8 8 8 9 K 64 7 8 8 8 K 64 6 8 8 8 K 64 5 8 8 8 K 64 4 8 8 8 K 64 3 8 8 8 K 64 2 8 8 8 K 64 8 8 8 J Q 64 8 8 8 T Q 64 8 8 8 9 Q 64 7 8 8 8 Q 64 6 8 8 8 Q 64 5 8 8 8 Q 64 4 8 8 8 Q 64 3 8 8 8 Q 64 2 8 8 8 Q 64 8 8 8 T J 64 8 8 8 9 J 64 7 8 8 8 J 64 6 8 8 8 J 64 5 8 8 8 J 64 4 8 8 8 J 64 3 8 8 8 J 64 2 8 8 8 J 64 8 8 8 9 T 64 7 8 8 8 T 64 6 8 8 8 T 64 5 8 8 8 T 64 4 8 8 8 T 64 3 8 8 8 T 64 2 8 8 8 T 64 7 8 8 8 9 64 6 8 8 8 9 64 5 8 8 8 9 64 4 8 8 8 9 64 3 8 8 8 9 64 2 8 8 8 9 64 6 7 8 8 8 64 5 7 8 8 8 64 4 7 8 8 8 64 3 7 8 8 8 64 2 7 8 8 8 64 5 6 8 8 8 64 4 6 8 8 8 64 3 6 8 8 8 64 2 6 8 8 8 64 4 5 8 8 8 64 3 5 8 8 8 64 2 5 8 8 8 64 3 4 8 8 8 64 2 4 8 8 8 64 2 3 8 8 8 64 7 7 7 K A Three Sevens 64 7 7 7 Q A 64 7 7 7 J A 64 7 7 7 T A 64 7 7 7 9 A 64 7 7 7 8 A 64 6 7 7 7 A 64 5 7 7 7 A 64 4 7 7 7 A 64 3 7 7 7 A 64 2 7 7 7 A 64 7 7 7 Q K 64 7 7 7 J K 64 7 7 7 T K 64 7 7 7 9 K 64 7 7 7 8 K 64 6 7 7 7 K 64 5 7 7 7 K 64 4 7 7 7 K 64 3 7 7 7 K 64 2 7 7 7 K 64 7 7 7 J Q 64 7 7 7 T Q 64 7 7 7 9 Q 64 7 7 7 8 Q 64 6 7 7 7 Q 64 5 7 7 7 Q 64 4 7 7 7 Q 64 3 7 7 7 Q 64 2 7 7 7 Q 64 7 7 7 T J 64 7 7 7 9 J 64 7 7 7 8 J 64 6 7 7 7 J 64 5 7 7 7 J 64 4 7 7 7 J 64 3 7 7 7 J 64 2 7 7 7 J 64 7 7 7 9 T 64 7 7 7 8 T 64 6 7 7 7 T 64 5 7 7 7 T 64 4 7 7 7 T 64 3 7 7 7 T 64 2 7 7 7 T 64 7 7 7 8 9 64 6 7 7 7 9 64 5 7 7 7 9 64 4 7 7 7 9 64 3 7 7 7 9 64 2 7 7 7 9 64 6 7 7 7 8 64 5 7 7 7 8 64 4 7 7 7 8 64 3 7 7 7 8 64 2 7 7 7 8 64 5 6 7 7 7 64 4 6 7 7 7 64 3 6 7 7 7 64 2 6 7 7 7 64 4 5 7 7 7 64 3 5 7 7 7 64 2 5 7 7 7 64 3 4 7 7 7 64 2 4 7 7 7 64 2 3 7 7 7 64 6 6 6 K A Three Sixes 64 6 6 6 Q A 64 6 6 6 J A 64 6 6 6 T A 64 6 6 6 9 A 64 6 6 6 8 A 64 6 6 6 7 A 64 5 6 6 6 A 64 4 6 6 6 A 64 3 6 6 6 A 64 2 6 6 6 A 64 6 6 6 Q K 64 6 6 6 J K 64 6 6 6 T K 64 6 6 6 9 K 64 6 6 6 8 K 64 6 6 6 7 K 64 5 6 6 6 K 64 4 6 6 6 K 64 3 6 6 6 K 64 2 6 6 6 K 64 6 6 6 J Q 64 6 6 6 T Q 64 6 6 6 9 Q 64 6 6 6 8 Q 64 6 6 6 7 Q 64 5 6 6 6 Q 64 4 6 6 6 Q 64 3 6 6 6 Q 64 2 6 6 6 Q 64 6 6 6 T J 64 6 6 6 9 J 64 6 6 6 8 J 64 6 6 6 7 J 64 5 6 6 6 J 64 4 6 6 6 J 64 3 6 6 6 J 64 2 6 6 6 J 64 6 6 6 9 T 64 6 6 6 8 T 64 6 6 6 7 T 64 5 6 6 6 T 64 4 6 6 6 T 64 3 6 6 6 T 64 2 6 6 6 T 64 6 6 6 8 9 64 6 6 6 7 9 64 5 6 6 6 9 64 4 6 6 6 9 64 3 6 6 6 9 64 2 6 6 6 9 64 6 6 6 7 8 64 5 6 6 6 8 64 4 6 6 6 8 64 3 6 6 6 8 64 2 6 6 6 8 64 5 6 6 6 7 64 4 6 6 6 7 64 3 6 6 6 7 64 2 6 6 6 7 64 4 5 6 6 6 64 3 5 6 6 6 64 2 5 6 6 6 64 3 4 6 6 6 64 2 4 6 6 6 64 2 3 6 6 6 64 5 5 5 K A Three Fives 64 5 5 5 Q A 64 5 5 5 J A 64 5 5 5 T A 64 5 5 5 9 A 64 5 5 5 8 A 64 5 5 5 7 A 64 5 5 5 6 A 64 4 5 5 5 A 64 3 5 5 5 A 64 2 5 5 5 A 64 5 5 5 Q K 64 5 5 5 J K 64 5 5 5 T K 64 5 5 5 9 K 64 5 5 5 8 K 64 5 5 5 7 K 64 5 5 5 6 K 64 4 5 5 5 K 64 3 5 5 5 K 64 2 5 5 5 K 64 5 5 5 J Q 64 5 5 5 T Q 64 5 5 5 9 Q 64 5 5 5 8 Q 64 5 5 5 7 Q 64 5 5 5 6 Q 64 4 5 5 5 Q 64 3 5 5 5 Q 64 2 5 5 5 Q 64 5 5 5 T J 64 5 5 5 9 J 64 5 5 5 8 J 64 5 5 5 7 J 64 5 5 5 6 J 64 4 5 5 5 J 64 3 5 5 5 J 64 2 5 5 5 J 64 5 5 5 9 T 64 5 5 5 8 T 64 5 5 5 7 T 64 5 5 5 6 T 64 4 5 5 5 T 64 3 5 5 5 T 64 2 5 5 5 T 64 5 5 5 8 9 64 5 5 5 7 9 64 5 5 5 6 9 64 4 5 5 5 9 64 3 5 5 5 9 64 2 5 5 5 9 64 5 5 5 7 8 64 5 5 5 6 8 64 4 5 5 5 8 64 3 5 5 5 8 64 2 5 5 5 8 64 5 5 5 6 7 64 4 5 5 5 7 64 3 5 5 5 7 64 2 5 5 5 7 64 4 5 5 5 6 64 3 5 5 5 6 64 2 5 5 5 6 64 3 4 5 5 5 64 2 4 5 5 5 64 2 3 5 5 5 64 4 4 4 K A Three Fours 64 4 4 4 Q A 64 4 4 4 J A 64 4 4 4 T A 64 4 4 4 9 A 64 4 4 4 8 A 64 4 4 4 7 A 64 4 4 4 6 A 64 4 4 4 5 A 64 3 4 4 4 A 64 2 4 4 4 A 64 4 4 4 Q K 64 4 4 4 J K 64 4 4 4 T K 64 4 4 4 9 K 64 4 4 4 8 K 64 4 4 4 7 K 64 4 4 4 6 K 64 4 4 4 5 K 64 3 4 4 4 K 64 2 4 4 4 K 64 4 4 4 J Q 64 4 4 4 T Q 64 4 4 4 9 Q 64 4 4 4 8 Q 64 4 4 4 7 Q 64 4 4 4 6 Q 64 4 4 4 5 Q 64 3 4 4 4 Q 64 2 4 4 4 Q 64 4 4 4 T J 64 4 4 4 9 J 64 4 4 4 8 J 64 4 4 4 7 J 64 4 4 4 6 J 64 4 4 4 5 J 64 3 4 4 4 J 64 2 4 4 4 J 64 4 4 4 9 T 64 4 4 4 8 T 64 4 4 4 7 T 64 4 4 4 6 T 64 4 4 4 5 T 64 3 4 4 4 T 64 2 4 4 4 T 64 4 4 4 8 9 64 4 4 4 7 9 64 4 4 4 6 9 64 4 4 4 5 9 64 3 4 4 4 9 64 2 4 4 4 9 64 4 4 4 7 8 64 4 4 4 6 8 64 4 4 4 5 8 64 3 4 4 4 8 64 2 4 4 4 8 64 4 4 4 6 7 64 4 4 4 5 7 64 3 4 4 4 7 64 2 4 4 4 7 64 4 4 4 5 6 64 3 4 4 4 6 64 2 4 4 4 6 64 3 4 4 4 5 64 2 4 4 4 5 64 2 3 4 4 4 64 3 3 3 K A Three Treys 64 3 3 3 Q A 64 3 3 3 J A 64 3 3 3 T A 64 3 3 3 9 A 64 3 3 3 8 A 64 3 3 3 7 A 64 3 3 3 6 A 64 3 3 3 5 A 64 3 3 3 4 A 64 2 3 3 3 A 64 3 3 3 Q K 64 3 3 3 J K 64 3 3 3 T K 64 3 3 3 9 K 64 3 3 3 8 K 64 3 3 3 7 K 64 3 3 3 6 K 64 3 3 3 5 K 64 3 3 3 4 K 64 2 3 3 3 K 64 3 3 3 J Q 64 3 3 3 T Q 64 3 3 3 9 Q 64 3 3 3 8 Q 64 3 3 3 7 Q 64 3 3 3 6 Q 64 3 3 3 5 Q 64 3 3 3 4 Q 64 2 3 3 3 Q 64 3 3 3 T J 64 3 3 3 9 J 64 3 3 3 8 J 64 3 3 3 7 J 64 3 3 3 6 J 64 3 3 3 5 J 64 3 3 3 4 J 64 2 3 3 3 J 64 3 3 3 9 T 64 3 3 3 8 T 64 3 3 3 7 T 64 3 3 3 6 T 64 3 3 3 5 T 64 3 3 3 4 T 64 2 3 3 3 T 64 3 3 3 8 9 64 3 3 3 7 9 64 3 3 3 6 9 64 3 3 3 5 9 64 3 3 3 4 9 64 2 3 3 3 9 64 3 3 3 7 8 64 3 3 3 6 8 64 3 3 3 5 8 64 3 3 3 4 8 64 2 3 3 3 8 64 3 3 3 6 7 64 3 3 3 5 7 64 3 3 3 4 7 64 2 3 3 3 7 64 3 3 3 5 6 64 3 3 3 4 6 64 2 3 3 3 6 64 3 3 3 4 5 64 2 3 3 3 5 64 2 3 3 3 4 64 2 2 2 K A Three Deuces 64 2 2 2 Q A 64 2 2 2 J A 64 2 2 2 T A 64 2 2 2 9 A 64 2 2 2 8 A 64 2 2 2 7 A 64 2 2 2 6 A 64 2 2 2 5 A 64 2 2 2 4 A 64 2 2 2 3 A 64 2 2 2 Q K 64 2 2 2 J K 64 2 2 2 T K 64 2 2 2 9 K 64 2 2 2 8 K 64 2 2 2 7 K 64 2 2 2 6 K 64 2 2 2 5 K 64 2 2 2 4 K 64 2 2 2 3 K 64 2 2 2 J Q 64 2 2 2 T Q 64 2 2 2 9 Q 64 2 2 2 8 Q 64 2 2 2 7 Q 64 2 2 2 6 Q 64 2 2 2 5 Q 64 2 2 2 4 Q 64 2 2 2 3 Q 64 2 2 2 T J 64 2 2 2 9 J 64 2 2 2 8 J 64 2 2 2 7 J 64 2 2 2 6 J 64 2 2 2 5 J 64 2 2 2 4 J 64 2 2 2 3 J 64 2 2 2 9 T 64 2 2 2 8 T 64 2 2 2 7 T 64 2 2 2 6 T 64 2 2 2 5 T 64 2 2 2 4 T 64 2 2 2 3 T 64 2 2 2 8 9 64 2 2 2 7 9 64 2 2 2 6 9 64 2 2 2 5 9 64 2 2 2 4 9 64 2 2 2 3 9 64 2 2 2 7 8 64 2 2 2 6 8 64 2 2 2 5 8 64 2 2 2 4 8 64 2 2 2 3 8 64 2 2 2 6 7 64 2 2 2 5 7 64 2 2 2 4 7 64 2 2 2 3 7 64 2 2 2 5 6 64 2 2 2 4 6 64 2 2 2 3 6 64 2 2 2 4 5 64 2 2 2 3 5 64 2 2 2 3 4 144 Q K K A A Aces over Kings TWO PAIR 144 J K K A A 144 T K K A A 144 9 K K A A 144 8 K K A A 144 7 K K A A 144 6 K K A A 144 5 K K A A 144 4 K K A A 144 3 K K A A 144 2 K K A A 144 Q Q K A A Aces over Queens 144 J Q Q A A 144 T Q Q A A 144 9 Q Q A A 144 8 Q Q A A 144 7 Q Q A A 144 6 Q Q A A 144 5 Q Q A A 144 4 Q Q A A 144 3 Q Q A A 144 2 Q Q A A 144 J J K A A Aces over Jacks 144 J J Q A A 144 T J J A A 144 9 J J A A 144 8 J J A A 144 7 J J A A 144 6 J J A A 144 5 J J A A 144 4 J J A A 144 3 J J A A 144 2 J J A A 144 T T K A A Aces over Tens 144 T T Q A A 144 T T J A A 144 9 T T A A 144 8 T T A A 144 7 T T A A 144 6 T T A A 144 5 T T A A 144 4 T T A A 144 3 T T A A 144 2 T T A A 144 9 9 K A A Aces over Nines 144 9 9 Q A A 144 9 9 J A A 144 9 9 T A A 144 8 9 9 A A 144 7 9 9 A A 144 6 9 9 A A 144 5 9 9 A A 144 4 9 9 A A 144 3 9 9 A A 144 2 9 9 A A 144 8 8 K A A Aces over Eights 144 8 8 Q A A 144 8 8 J A A 144 8 8 T A A 144 8 8 9 A A 144 7 8 8 A A 144 6 8 8 A A 144 5 8 8 A A 144 4 8 8 A A 144 3 8 8 A A 144 2 8 8 A A 144 7 7 K A A Aces over Sevens 144 7 7 Q A A 144 7 7 J A A 144 7 7 T A A 144 7 7 9 A A 144 7 7 8 A A 144 6 7 7 A A 144 5 7 7 A A 144 4 7 7 A A 144 3 7 7 A A 144 2 7 7 A A 144 6 6 K A A Aces over Sixes 144 6 6 Q A A 144 6 6 J A A 144 6 6 T A A 144 6 6 9 A A 144 6 6 8 A A 144 6 6 7 A A 144 5 6 6 A A 144 4 6 6 A A 144 3 6 6 A A 144 2 6 6 A A 144 5 5 K A A Aces over Fives 144 5 5 Q A A 144 5 5 J A A 144 5 5 T A A 144 5 5 9 A A 144 5 5 8 A A 144 5 5 7 A A 144 5 5 6 A A 144 4 5 5 A A 144 3 5 5 A A 144 2 5 5 A A 144 4 4 K A A Aces over Fours 144 4 4 Q A A 144 4 4 J A A 144 4 4 T A A 144 4 4 9 A A 144 4 4 8 A A 144 4 4 7 A A 144 4 4 6 A A 144 4 4 5 A A 144 3 4 4 A A 144 2 4 4 A A 144 3 3 K A A Aces over Treys 144 3 3 Q A A 144 3 3 J A A 144 3 3 T A A 144 3 3 9 A A 144 3 3 8 A A 144 3 3 7 A A 144 3 3 6 A A 144 3 3 5 A A 144 3 3 4 A A 144 2 3 3 A A 144 2 2 K A A Aces over Deuces 144 2 2 Q A A 144 2 2 J A A 144 2 2 T A A 144 2 2 9 A A 144 2 2 8 A A 144 2 2 7 A A 144 2 2 6 A A 144 2 2 5 A A 144 2 2 4 A A 144 2 2 3 A A 144 Q Q K K A Kings over Queens 144 J Q Q K K 144 T Q Q K K 144 9 Q Q K K 144 8 Q Q K K 144 7 Q Q K K 144 6 Q Q K K 144 5 Q Q K K 144 4 Q Q K K 144 3 Q Q K K 144 2 Q Q K K 144 J J K K A Kings over Jacks 144 J J Q K K 144 T J J K K 144 9 J J K K 144 8 J J K K 144 7 J J K K 144 6 J J K K 144 5 J J K K 144 4 J J K K 144 3 J J K K 144 2 J J K K 144 T T K K A Kings over Tens 144 T T Q K K 144 T T J K K 144 9 T T K K 144 8 T T K K 144 7 T T K K 144 6 T T K K 144 5 T T K K 144 4 T T K K 144 3 T T K K 144 2 T T K K 144 9 9 K K A Kings over Nines 144 9 9 Q K K 144 9 9 J K K 144 9 9 T K K 144 8 9 9 K K 144 7 9 9 K K 144 6 9 9 K K 144 5 9 9 K K 144 4 9 9 K K 144 3 9 9 K K 144 2 9 9 K K 144 8 8 K K A Kings over Eights 144 8 8 Q K K 144 8 8 J K K 144 8 8 T K K 144 8 8 9 K K 144 7 8 8 K K 144 6 8 8 K K 144 5 8 8 K K 144 4 8 8 K K 144 3 8 8 K K 144 2 8 8 K K 144 7 7 K K A Kings over Sevens 144 7 7 Q K K 144 7 7 J K K 144 7 7 T K K 144 7 7 9 K K 144 7 7 8 K K 144 6 7 7 K K 144 5 7 7 K K 144 4 7 7 K K 144 3 7 7 K K 144 2 7 7 K K 144 6 6 K K A Kings over Sixes 144 6 6 Q K K 144 6 6 J K K 144 6 6 T K K 144 6 6 9 K K 144 6 6 8 K K 144 6 6 7 K K 144 5 6 6 K K 144 4 6 6 K K 144 3 6 6 K K 144 2 6 6 K K 144 5 5 K K A Kings over Fives 144 5 5 Q K K 144 5 5 J K K 144 5 5 T K K 144 5 5 9 K K 144 5 5 8 K K 144 5 5 7 K K 144 5 5 6 K K 144 4 5 5 K K 144 3 5 5 K K 144 2 5 5 K K 144 4 4 K K A Kings over Fours 144 4 4 Q K K 144 4 4 J K K 144 4 4 T K K 144 4 4 9 K K 144 4 4 8 K K 144 4 4 7 K K 144 4 4 6 K K 144 4 4 5 K K 144 3 4 4 K K 144 2 4 4 K K 144 3 3 K K A Kings over Treys 144 3 3 Q K K 144 3 3 J K K 144 3 3 T K K 144 3 3 9 K K 144 3 3 8 K K 144 3 3 7 K K 144 3 3 6 K K 144 3 3 5 K K 144 3 3 4 K K 144 2 3 3 K K 144 2 2 K K A Kings over Deuces 144 2 2 Q K K 144 2 2 J K K 144 2 2 T K K 144 2 2 9 K K 144 2 2 8 K K 144 2 2 7 K K 144 2 2 6 K K 144 2 2 5 K K 144 2 2 4 K K 144 2 2 3 K K 144 J J Q Q A Queens over Jacks 144 J J Q Q K 144 T J J Q Q 144 9 J J Q Q 144 8 J J Q Q 144 7 J J Q Q 144 6 J J Q Q 144 5 J J Q Q 144 4 J J Q Q 144 3 J J Q Q 144 2 J J Q Q 144 T T Q Q A Queens over Tens 144 T T Q Q K 144 T T J Q Q 144 9 T T Q Q 144 8 T T Q Q 144 7 T T Q Q 144 6 T T Q Q 144 5 T T Q Q 144 4 T T Q Q 144 3 T T Q Q 144 2 T T Q Q 144 9 9 Q Q A Queens over Nines 144 9 9 Q Q K 144 9 9 J Q Q 144 9 9 T Q Q 144 8 9 9 Q Q 144 7 9 9 Q Q 144 6 9 9 Q Q 144 5 9 9 Q Q 144 4 9 9 Q Q 144 3 9 9 Q Q 144 2 9 9 Q Q 144 8 8 Q Q A Queens over Eights 144 8 8 Q Q K 144 8 8 J Q Q 144 8 8 T Q Q 144 8 8 9 Q Q 144 7 8 8 Q Q 144 6 8 8 Q Q 144 5 8 8 Q Q 144 4 8 8 Q Q 144 3 8 8 Q Q 144 2 8 8 Q Q 144 7 7 Q Q A Queens over Sevens 144 7 7 Q Q K 144 7 7 J Q Q 144 7 7 T Q Q 144 7 7 9 Q Q 144 7 7 8 Q Q 144 6 7 7 Q Q 144 5 7 7 Q Q 144 4 7 7 Q Q 144 3 7 7 Q Q 144 2 7 7 Q Q 144 6 6 Q Q A Queens over Sixes 144 6 6 Q Q K 144 6 6 J Q Q 144 6 6 T Q Q 144 6 6 9 Q Q 144 6 6 8 Q Q 144 6 6 7 Q Q 144 5 6 6 Q Q 144 4 6 6 Q Q 144 3 6 6 Q Q 144 2 6 6 Q Q 144 5 5 Q Q A Queens over Fives 144 5 5 Q Q K 144 5 5 J Q Q 144 5 5 T Q Q 144 5 5 9 Q Q 144 5 5 8 Q Q 144 5 5 7 Q Q 144 5 5 6 Q Q 144 4 5 5 Q Q 144 3 5 5 Q Q 144 2 5 5 Q Q 144 4 4 Q Q A Queens over Fours 144 4 4 Q Q K 144 4 4 J Q Q 144 4 4 T Q Q 144 4 4 9 Q Q 144 4 4 8 Q Q 144 4 4 7 Q Q 144 4 4 6 Q Q 144 4 4 5 Q Q 144 3 4 4 Q Q 144 2 4 4 Q Q 144 3 3 Q Q A Queens over Treys 144 3 3 Q Q K 144 3 3 J Q Q 144 3 3 T Q Q 144 3 3 9 Q Q 144 3 3 8 Q Q 144 3 3 7 Q Q 144 3 3 6 Q Q 144 3 3 5 Q Q 144 3 3 4 Q Q 144 2 3 3 Q Q 144 2 2 Q Q A Queens over Deuces 144 2 2 Q Q K 144 2 2 J Q Q 144 2 2 T Q Q 144 2 2 9 Q Q 144 2 2 8 Q Q 144 2 2 7 Q Q 144 2 2 6 Q Q 144 2 2 5 Q Q 144 2 2 4 Q Q 144 2 2 3 Q Q 144 T T J J A Jacks over Tens 144 T T J J K 144 T T J J Q 144 9 T T J J 144 8 T T J J 144 7 T T J J 144 6 T T J J 144 5 T T J J 144 4 T T J J 144 3 T T J J 144 2 T T J J 144 9 9 J J A Jacks over Nines 144 9 9 J J K 144 9 9 J J Q 144 9 9 T J J 144 8 9 9 J J 144 7 9 9 J J 144 6 9 9 J J 144 5 9 9 J J 144 4 9 9 J J 144 3 9 9 J J 144 2 9 9 J J 144 8 8 J J A Jacks over Eights 144 8 8 J J K 144 8 8 J J Q 144 8 8 T J J 144 8 8 9 J J 144 7 8 8 J J 144 6 8 8 J J 144 5 8 8 J J 144 4 8 8 J J 144 3 8 8 J J 144 2 8 8 J J 144 7 7 J J A Jacks over Sevens 144 7 7 J J K 144 7 7 J J Q 144 7 7 T J J 144 7 7 9 J J 144 7 7 8 J J 144 6 7 7 J J 144 5 7 7 J J 144 4 7 7 J J 144 3 7 7 J J 144 2 7 7 J J 144 6 6 J J A Jacks over Sixes 144 6 6 J J K 144 6 6 J J Q 144 6 6 T J J 144 6 6 9 J J 144 6 6 8 J J 144 6 6 7 J J 144 5 6 6 J J 144 4 6 6 J J 144 3 6 6 J J 144 2 6 6 J J 144 5 5 J J A Jacks over Fives 144 5 5 J J K 144 5 5 J J Q 144 5 5 T J J 144 5 5 9 J J 144 5 5 8 J J 144 5 5 7 J J 144 5 5 6 J J 144 4 5 5 J J 144 3 5 5 J J 144 2 5 5 J J 144 4 4 J J A Jacks over Fours 144 4 4 J J K 144 4 4 J J Q 144 4 4 T J J 144 4 4 9 J J 144 4 4 8 J J 144 4 4 7 J J 144 4 4 6 J J 144 4 4 5 J J 144 3 4 4 J J 144 2 4 4 J J 144 3 3 J J A Jacks over Treys 144 3 3 J J K 144 3 3 J J Q 144 3 3 T J J 144 3 3 9 J J 144 3 3 8 J J 144 3 3 7 J J 144 3 3 6 J J 144 3 3 5 J J 144 3 3 4 J J 144 2 3 3 J J 144 2 2 J J A Jacks over Deuces 144 2 2 J J K 144 2 2 J J Q 144 2 2 T J J 144 2 2 9 J J 144 2 2 8 J J 144 2 2 7 J J 144 2 2 6 J J 144 2 2 5 J J 144 2 2 4 J J 144 2 2 3 J J 144 9 9 T T A Tens over Nines 144 9 9 T T K 144 9 9 T T Q 144 9 9 T T J 144 8 9 9 T T 144 7 9 9 T T 144 6 9 9 T T 144 5 9 9 T T 144 4 9 9 T T 144 3 9 9 T T 144 2 9 9 T T 144 8 8 T T A Tens over Eights 144 8 8 T T K 144 8 8 T T Q 144 8 8 T T J 144 8 8 9 T T 144 7 8 8 T T 144 6 8 8 T T 144 5 8 8 T T 144 4 8 8 T T 144 3 8 8 T T 144 2 8 8 T T 144 7 7 T T A Tens over Sevens 144 7 7 T T K 144 7 7 T T Q 144 7 7 T T J 144 7 7 9 T T 144 7 7 8 T T 144 6 7 7 T T 144 5 7 7 T T 144 4 7 7 T T 144 3 7 7 T T 144 2 7 7 T T 144 6 6 T T A Tens over Sixes 144 6 6 T T K 144 6 6 T T Q 144 6 6 T T J 144 6 6 9 T T 144 6 6 8 T T 144 6 6 7 T T 144 5 6 6 T T 144 4 6 6 T T 144 3 6 6 T T 144 2 6 6 T T 144 5 5 T T A Tens over Fives 144 5 5 T T K 144 5 5 T T Q 144 5 5 T T J 144 5 5 9 T T 144 5 5 8 T T 144 5 5 7 T T 144 5 5 6 T T 144 4 5 5 T T 144 3 5 5 T T 144 2 5 5 T T 144 4 4 T T A Tens over Fours 144 4 4 T T K 144 4 4 T T Q 144 4 4 T T J 144 4 4 9 T T 144 4 4 8 T T 144 4 4 7 T T 144 4 4 6 T T 144 4 4 5 T T 144 3 4 4 T T 144 2 4 4 T T 144 3 3 T T A Tens over Treys 144 3 3 T T K 144 3 3 T T Q 144 3 3 T T J 144 3 3 9 T T 144 3 3 8 T T 144 3 3 7 T T 144 3 3 6 T T 144 3 3 5 T T 144 3 3 4 T T 144 2 3 3 T T 144 2 2 T T A Tens over Deuces 144 2 2 T T K 144 2 2 T T Q 144 2 2 T T J 144 2 2 9 T T 144 2 2 8 T T 144 2 2 7 T T 144 2 2 6 T T 144 2 2 5 T T 144 2 2 4 T T 144 2 2 3 T T 144 8 8 9 9 A Nines over Eights 144 8 8 9 9 K 144 8 8 9 9 Q 144 8 8 9 9 J 144 8 8 9 9 T 144 7 8 8 9 9 144 6 8 8 9 9 144 5 8 8 9 9 144 4 8 8 9 9 144 3 8 8 9 9 144 2 8 8 9 9 144 7 7 9 9 A Nines over Sevens 144 7 7 9 9 K 144 7 7 9 9 Q 144 7 7 9 9 J 144 7 7 9 9 T 144 7 7 8 9 9 144 6 7 7 9 9 144 5 7 7 9 9 144 4 7 7 9 9 144 3 7 7 9 9 144 2 7 7 9 9 144 6 6 9 9 A Nines over Sixes 144 6 6 9 9 K 144 6 6 9 9 Q 144 6 6 9 9 J 144 6 6 9 9 T 144 6 6 8 9 9 144 6 6 7 9 9 144 5 6 6 9 9 144 4 6 6 9 9 144 3 6 6 9 9 144 2 6 6 9 9 144 5 5 9 9 A Nines over Fives 144 5 5 9 9 K 144 5 5 9 9 Q 144 5 5 9 9 J 144 5 5 9 9 T 144 5 5 8 9 9 144 5 5 7 9 9 144 5 5 6 9 9 144 4 5 5 9 9 144 3 5 5 9 9 144 2 5 5 9 9 144 4 4 9 9 A Nines over Fours 144 4 4 9 9 K 144 4 4 9 9 Q 144 4 4 9 9 J 144 4 4 9 9 T 144 4 4 8 9 9 144 4 4 7 9 9 144 4 4 6 9 9 144 4 4 5 9 9 144 3 4 4 9 9 144 2 4 4 9 9 144 3 3 9 9 A Nines over Treys 144 3 3 9 9 K 144 3 3 9 9 Q 144 3 3 9 9 J 144 3 3 9 9 T 144 3 3 8 9 9 144 3 3 7 9 9 144 3 3 6 9 9 144 3 3 5 9 9 144 3 3 4 9 9 144 2 3 3 9 9 144 2 2 9 9 A Nines over Deuces 144 2 2 9 9 K 144 2 2 9 9 Q 144 2 2 9 9 J 144 2 2 9 9 T 144 2 2 8 9 9 144 2 2 7 9 9 144 2 2 6 9 9 144 2 2 5 9 9 144 2 2 4 9 9 144 2 2 3 9 9 144 7 7 8 8 A Eights over Sevens 144 7 7 8 8 K 144 7 7 8 8 Q 144 7 7 8 8 J 144 7 7 8 8 T 144 7 7 8 8 9 144 6 7 7 8 8 144 5 7 7 8 8 144 4 7 7 8 8 144 3 7 7 8 8 144 2 7 7 8 8 144 6 6 8 8 A Eights over Sixes 144 6 6 8 8 K 144 6 6 8 8 Q 144 6 6 8 8 J 144 6 6 8 8 T 144 6 6 8 8 9 144 6 6 7 8 8 144 5 6 6 8 8 144 4 6 6 8 8 144 3 6 6 8 8 144 2 6 6 8 8 144 5 5 8 8 A Eights over Fives 144 5 5 8 8 K 144 5 5 8 8 Q 144 5 5 8 8 J 144 5 5 8 8 T 144 5 5 8 8 9 144 5 5 7 8 8 144 5 5 6 8 8 144 4 5 5 8 8 144 3 5 5 8 8 144 2 5 5 8 8 144 4 4 8 8 A Eights over Fours 144 4 4 8 8 K 144 4 4 8 8 Q 144 4 4 8 8 J 144 4 4 8 8 T 144 4 4 8 8 9 144 4 4 7 8 8 144 4 4 6 8 8 144 4 4 5 8 8 144 3 4 4 8 8 144 2 4 4 8 8 144 3 3 8 8 A Eights over Treys 144 3 3 8 8 K 144 3 3 8 8 Q 144 3 3 8 8 J 144 3 3 8 8 T 144 3 3 8 8 9 144 3 3 7 8 8 144 3 3 6 8 8 144 3 3 5 8 8 144 3 3 4 8 8 144 2 3 3 8 8 144 2 2 8 8 A Eights over Deuces 144 2 2 8 8 K 144 2 2 8 8 Q 144 2 2 8 8 J 144 2 2 8 8 T 144 2 2 8 8 9 144 2 2 7 8 8 144 2 2 6 8 8 144 2 2 5 8 8 144 2 2 4 8 8 144 2 2 3 8 8 144 6 6 7 7 A Sevens over Sixes 144 6 6 7 7 K 144 6 6 7 7 Q 144 6 6 7 7 J 144 6 6 7 7 T 144 6 6 7 7 9 144 6 6 7 7 8 144 5 6 6 7 7 144 4 6 6 7 7 144 3 6 6 7 7 144 2 6 6 7 7 144 5 5 7 7 A Sevens over Fives 144 5 5 7 7 K 144 5 5 7 7 Q 144 5 5 7 7 J 144 5 5 7 7 T 144 5 5 7 7 9 144 5 5 7 7 8 144 5 5 6 7 7 144 4 5 5 7 7 144 3 5 5 7 7 144 2 5 5 7 7 144 4 4 7 7 A Sevens over Fours 144 4 4 7 7 K 144 4 4 7 7 Q 144 4 4 7 7 J 144 4 4 7 7 T 144 4 4 7 7 9 144 4 4 7 7 8 144 4 4 6 7 7 144 4 4 5 7 7 144 3 4 4 7 7 144 2 4 4 7 7 144 3 3 7 7 A Sevens over Treys 144 3 3 7 7 K 144 3 3 7 7 Q 144 3 3 7 7 J 144 3 3 7 7 T 144 3 3 7 7 9 144 3 3 7 7 8 144 3 3 6 7 7 144 3 3 5 7 7 144 3 3 4 7 7 144 2 3 3 7 7 144 2 2 7 7 A Sevens over Deuces 144 2 2 7 7 K 144 2 2 7 7 Q 144 2 2 7 7 J 144 2 2 7 7 T 144 2 2 7 7 9 144 2 2 7 7 8 144 2 2 6 7 7 144 2 2 5 7 7 144 2 2 4 7 7 144 2 2 3 7 7 144 5 5 6 6 A Sixes over Fives 144 5 5 6 6 K 144 5 5 6 6 Q 144 5 5 6 6 J 144 5 5 6 6 T 144 5 5 6 6 9 144 5 5 6 6 8 144 5 5 6 6 7 144 4 5 5 6 6 144 3 5 5 6 6 144 2 5 5 6 6 144 4 4 6 6 A Sixes over Fours 144 4 4 6 6 K 144 4 4 6 6 Q 144 4 4 6 6 J 144 4 4 6 6 T 144 4 4 6 6 9 144 4 4 6 6 8 144 4 4 6 6 7 144 4 4 5 6 6 144 3 4 4 6 6 144 2 4 4 6 6 144 3 3 6 6 A Sixes over Treys 144 3 3 6 6 K 144 3 3 6 6 Q 144 3 3 6 6 J 144 3 3 6 6 T 144 3 3 6 6 9 144 3 3 6 6 8 144 3 3 6 6 7 144 3 3 5 6 6 144 3 3 4 6 6 144 2 3 3 6 6 144 2 2 6 6 A Sixes over Deuces 144 2 2 6 6 K 144 2 2 6 6 Q 144 2 2 6 6 J 144 2 2 6 6 T 144 2 2 6 6 9 144 2 2 6 6 8 144 2 2 6 6 7 144 2 2 5 6 6 144 2 2 4 6 6 144 2 2 3 6 6 144 4 4 5 5 A Fives over Fours 144 4 4 5 5 K 144 4 4 5 5 Q 144 4 4 5 5 J 144 4 4 5 5 T 144 4 4 5 5 9 144 4 4 5 5 8 144 4 4 5 5 7 144 4 4 5 5 6 144 3 4 4 5 5 144 2 4 4 5 5 144 3 3 5 5 A Fives over Treys 144 3 3 5 5 K 144 3 3 5 5 Q 144 3 3 5 5 J 144 3 3 5 5 T 144 3 3 5 5 9 144 3 3 5 5 8 144 3 3 5 5 7 144 3 3 5 5 6 144 3 3 4 5 5 144 2 3 3 5 5 144 2 2 5 5 A Fives over Deuces 144 2 2 5 5 K 144 2 2 5 5 Q 144 2 2 5 5 J 144 2 2 5 5 T 144 2 2 5 5 9 144 2 2 5 5 8 144 2 2 5 5 7 144 2 2 5 5 6 144 2 2 4 5 5 144 2 2 3 5 5 144 3 3 4 4 A Fours over Treys 144 3 3 4 4 K 144 3 3 4 4 Q 144 3 3 4 4 J 144 3 3 4 4 T 144 3 3 4 4 9 144 3 3 4 4 8 144 3 3 4 4 7 144 3 3 4 4 6 144 3 3 4 4 5 144 3 3 4 4 2 144 2 2 4 4 A Fours over Deuces 144 2 2 4 4 K 144 2 2 4 4 Q 144 2 2 4 4 J 144 2 2 4 4 T 144 2 2 4 4 9 144 2 2 4 4 8 144 2 2 4 4 7 144 2 2 4 4 6 144 2 2 4 4 5 144 2 2 4 4 3 144 2 2 3 3 A Treys over Deuces 144 2 2 3 3 K 144 2 2 3 3 Q 144 2 2 3 3 J 144 2 2 3 3 T 144 2 2 3 3 9 144 2 2 3 3 8 144 2 2 3 3 7 144 2 2 3 3 6 144 2 2 3 3 5 144 2 2 3 3 4 384 J Q K A A Pair of Aces ONE PAIR 384 T Q K A A 384 9 Q K A A 384 8 Q K A A 384 7 Q K A A 384 6 Q K A A 384 5 Q K A A 384 4 Q K A A 384 3 Q K A A 384 2 Q K A A 384 T J K A A 384 9 J K A A 384 8 J K A A 384 7 J K A A 384 6 J K A A 384 5 J K A A 384 4 J K A A 384 3 J K A A 384 2 J K A A 384 9 T K A A 384 8 T K A A 384 7 T K A A 384 6 T K A A 384 5 T K A A 384 4 T K A A 384 3 T K A A 384 2 T K A A 384 8 9 K A A 384 7 9 K A A 384 6 9 K A A 384 5 9 K A A 384 4 9 K A A 384 3 9 K A A 384 2 9 K A A 384 7 8 K A A 384 6 8 K A A 384 5 8 K A A 384 4 8 K A A 384 3 8 K A A 384 2 8 K A A 384 6 7 K A A 384 5 7 K A A 384 4 7 K A A 384 3 7 K A A 384 2 7 K A A 384 5 6 K A A 384 4 6 K A A 384 3 6 K A A 384 2 6 K A A 384 4 5 K A A 384 3 5 K A A 384 2 5 K A A 384 3 4 K A A 384 2 4 K A A 384 2 3 K A A 384 T J Q A A 384 9 J Q A A 384 8 J Q A A 384 7 J Q A A 384 6 J Q A A 384 5 J Q A A 384 4 J Q A A 384 3 J Q A A 384 2 J Q A A 384 9 T Q A A 384 8 T Q A A 384 7 T Q A A 384 6 T Q A A 384 5 T Q A A 384 4 T Q A A 384 3 T Q A A 384 2 T Q A A 384 8 9 Q A A 384 7 9 Q A A 384 6 9 Q A A 384 5 9 Q A A 384 4 9 Q A A 384 3 9 Q A A 384 2 9 Q A A 384 7 8 Q A A 384 6 8 Q A A 384 5 8 Q A A 384 4 8 Q A A 384 3 8 Q A A 384 2 8 Q A A 384 6 7 Q A A 384 5 7 Q A A 384 4 7 Q A A 384 3 7 Q A A 384 2 7 Q A A 384 5 6 Q A A 384 4 6 Q A A 384 3 6 Q A A 384 2 6 Q A A 384 4 5 Q A A 384 3 5 Q A A 384 2 5 Q A A 384 3 4 Q A A 384 2 4 Q A A 384 2 3 Q A A 384 9 T J A A 384 8 T J A A 384 7 T J A A 384 6 T J A A 384 5 T J A A 384 4 T J A A 384 3 T J A A 384 2 T J A A 384 8 9 J A A 384 7 9 J A A 384 6 9 J A A 384 5 9 J A A 384 4 9 J A A 384 3 9 J A A 384 2 9 J A A 384 7 8 J A A 384 6 8 J A A 384 5 8 J A A 384 4 8 J A A 384 3 8 J A A 384 2 8 J A A 384 6 7 J A A 384 5 7 J A A 384 4 7 J A A 384 3 7 J A A 384 2 7 J A A 384 5 6 J A A 384 4 6 J A A 384 3 6 J A A 384 2 6 J A A 384 4 5 J A A 384 3 5 J A A 384 2 5 J A A 384 3 4 J A A 384 2 4 J A A 384 2 3 J A A 384 8 9 T A A 384 7 9 T A A 384 6 9 T A A 384 5 9 T A A 384 4 9 T A A 384 3 9 T A A 384 2 9 T A A 384 7 8 T A A 384 6 8 T A A 384 5 8 T A A 384 4 8 T A A 384 3 8 T A A 384 2 8 T A A 384 6 7 T A A 384 5 7 T A A 384 4 7 T A A 384 3 7 T A A 384 2 7 T A A 384 5 6 T A A 384 4 6 T A A 384 3 6 T A A 384 2 6 T A A 384 4 5 T A A 384 3 5 T A A 384 2 5 T A A 384 3 4 T A A 384 2 4 T A A 384 2 3 T A A 384 7 8 9 A A 384 6 8 9 A A 384 5 8 9 A A 384 4 8 9 A A 384 3 8 9 A A 384 2 8 9 A A 384 6 7 9 A A 384 5 7 9 A A 384 4 7 9 A A 384 3 7 9 A A 384 2 7 9 A A 384 5 6 9 A A 384 4 6 9 A A 384 3 6 9 A A 384 2 6 9 A A 384 4 5 9 A A 384 3 5 9 A A 384 2 5 9 A A 384 3 4 9 A A 384 2 4 9 A A 384 2 3 9 A A 384 6 7 8 A A 384 5 7 8 A A 384 4 7 8 A A 384 3 7 8 A A 384 2 7 8 A A 384 5 6 8 A A 384 4 6 8 A A 384 3 6 8 A A 384 2 6 8 A A 384 4 5 8 A A 384 3 5 8 A A 384 2 5 8 A A 384 3 4 8 A A 384 2 4 8 A A 384 2 3 8 A A 384 5 6 7 A A 384 4 6 7 A A 384 3 6 7 A A 384 2 6 7 A A 384 4 5 7 A A 384 3 5 7 A A 384 2 5 7 A A 384 3 4 7 A A 384 2 4 7 A A 384 2 3 7 A A 384 4 5 6 A A 384 3 5 6 A A 384 2 5 6 A A 384 3 4 6 A A 384 2 4 6 A A 384 2 3 6 A A 384 3 4 5 A A 384 2 4 5 A A 384 2 3 5 A A 384 2 3 4 A A 384 J Q K K A Pair of Kings 384 T Q K K A 384 9 Q K K A 384 8 Q K K A 384 7 Q K K A 384 6 Q K K A 384 5 Q K K A 384 4 Q K K A 384 3 Q K K A 384 2 Q K K A 384 T J K K A 384 9 J K K A 384 8 J K K A 384 7 J K K A 384 6 J K K A 384 5 J K K A 384 4 J K K A 384 3 J K K A 384 2 J K K A 384 9 T K K A 384 8 T K K A 384 7 T K K A 384 6 T K K A 384 5 T K K A 384 4 T K K A 384 3 T K K A 384 2 T K K A 384 8 9 K K A 384 7 9 K K A 384 6 9 K K A 384 5 9 K K A 384 4 9 K K A 384 3 9 K K A 384 2 9 K K A 384 7 8 K K A 384 6 8 K K A 384 5 8 K K A 384 4 8 K K A 384 3 8 K K A 384 2 8 K K A 384 6 7 K K A 384 5 7 K K A 384 4 7 K K A 384 3 7 K K A 384 2 7 K K A 384 5 6 K K A 384 4 6 K K A 384 3 6 K K A 384 2 6 K K A 384 4 5 K K A 384 3 5 K K A 384 2 5 K K A 384 3 4 K K A 384 2 4 K K A 384 2 3 K K A 384 T J Q K K 384 9 J Q K K 384 8 J Q K K 384 7 J Q K K 384 6 J Q K K 384 5 J Q K K 384 4 J Q K K 384 3 J Q K K 384 2 J Q K K 384 9 T Q K K 384 8 T Q K K 384 7 T Q K K 384 6 T Q K K 384 5 T Q K K 384 4 T Q K K 384 3 T Q K K 384 2 T Q K K 384 8 9 Q K K 384 7 9 Q K K 384 6 9 Q K K 384 5 9 Q K K 384 4 9 Q K K 384 3 9 Q K K 384 2 9 Q K K 384 7 8 Q K K 384 6 8 Q K K 384 5 8 Q K K 384 4 8 Q K K 384 3 8 Q K K 384 2 8 Q K K 384 6 7 Q K K 384 5 7 Q K K 384 4 7 Q K K 384 3 7 Q K K 384 2 7 Q K K 384 5 6 Q K K 384 4 6 Q K K 384 3 6 Q K K 384 2 6 Q K K 384 4 5 Q K K 384 3 5 Q K K 384 2 5 Q K K 384 3 4 Q K K 384 2 4 Q K K 384 2 3 Q K K 384 9 T J K K 384 8 T J K K 384 7 T J K K 384 6 T J K K 384 5 T J K K 384 4 T J K K 384 3 T J K K 384 2 T J K K 384 8 9 J K K 384 7 9 J K K 384 6 9 J K K 384 5 9 J K K 384 4 9 J K K 384 3 9 J K K 384 2 9 J K K 384 7 8 J K K 384 6 8 J K K 384 5 8 J K K 384 4 8 J K K 384 3 8 J K K 384 2 8 J K K 384 6 7 J K K 384 5 7 J K K 384 4 7 J K K 384 3 7 J K K 384 2 7 J K K 384 5 6 J K K 384 4 6 J K K 384 3 6 J K K 384 2 6 J K K 384 4 5 J K K 384 3 5 J K K 384 2 5 J K K 384 3 4 J K K 384 2 4 J K K 384 2 3 J K K 384 8 9 T K K 384 7 9 T K K 384 6 9 T K K 384 5 9 T K K 384 4 9 T K K 384 3 9 T K K 384 2 9 T K K 384 7 8 T K K 384 6 8 T K K 384 5 8 T K K 384 4 8 T K K 384 3 8 T K K 384 2 8 T K K 384 6 7 T K K 384 5 7 T K K 384 4 7 T K K 384 3 7 T K K 384 2 7 T K K 384 5 6 T K K 384 4 6 T K K 384 3 6 T K K 384 2 6 T K K 384 4 5 T K K 384 3 5 T K K 384 2 5 T K K 384 3 4 T K K 384 2 4 T K K 384 2 3 T K K 384 7 8 9 K K 384 6 8 9 K K 384 5 8 9 K K 384 4 8 9 K K 384 3 8 9 K K 384 2 8 9 K K 384 6 7 9 K K 384 5 7 9 K K 384 4 7 9 K K 384 3 7 9 K K 384 2 7 9 K K 384 5 6 9 K K 384 4 6 9 K K 384 3 6 9 K K 384 2 6 9 K K 384 4 5 9 K K 384 3 5 9 K K 384 2 5 9 K K 384 3 4 9 K K 384 2 4 9 K K 384 2 3 9 K K 384 6 7 8 K K 384 5 7 8 K K 384 4 7 8 K K 384 3 7 8 K K 384 2 7 8 K K 384 5 6 8 K K 384 4 6 8 K K 384 3 6 8 K K 384 2 6 8 K K 384 4 5 8 K K 384 3 5 8 K K 384 2 5 8 K K 384 3 4 8 K K 384 2 4 8 K K 384 2 3 8 K K 384 5 6 7 K K 384 4 6 7 K K 384 3 6 7 K K 384 2 6 7 K K 384 4 5 7 K K 384 3 5 7 K K 384 2 5 7 K K 384 3 4 7 K K 384 2 4 7 K K 384 2 3 7 K K 384 4 5 6 K K 384 3 5 6 K K 384 2 5 6 K K 384 3 4 6 K K 384 2 4 6 K K 384 2 3 6 K K 384 3 4 5 K K 384 2 4 5 K K 384 2 3 5 K K 384 2 3 4 K K 384 J Q Q K A Pair of Queens 384 T Q Q K A 384 9 Q Q K A 384 8 Q Q K A 384 7 Q Q K A 384 6 Q Q K A 384 5 Q Q K A 384 4 Q Q K A 384 3 Q Q K A 384 2 Q Q K A 384 T J Q Q A 384 9 J Q Q A 384 8 J Q Q A 384 7 J Q Q A 384 6 J Q Q A 384 5 J Q Q A 384 4 J Q Q A 384 3 J Q Q A 384 2 J Q Q A 384 9 T Q Q A 384 8 T Q Q A 384 7 T Q Q A 384 6 T Q Q A 384 5 T Q Q A 384 4 T Q Q A 384 3 T Q Q A 384 2 T Q Q A 384 8 9 Q Q A 384 7 9 Q Q A 384 6 9 Q Q A 384 5 9 Q Q A 384 4 9 Q Q A 384 3 9 Q Q A 384 2 9 Q Q A 384 7 8 Q Q A 384 6 8 Q Q A 384 5 8 Q Q A 384 4 8 Q Q A 384 3 8 Q Q A 384 2 8 Q Q A 384 6 7 Q Q A 384 5 7 Q Q A 384 4 7 Q Q A 384 3 7 Q Q A 384 2 7 Q Q A 384 5 6 Q Q A 384 4 6 Q Q A 384 3 6 Q Q A 384 2 6 Q Q A 384 4 5 Q Q A 384 3 5 Q Q A 384 2 5 Q Q A 384 3 4 Q Q A 384 2 4 Q Q A 384 2 3 Q Q A 384 T J Q Q K 384 9 J Q Q K 384 8 J Q Q K 384 7 J Q Q K 384 6 J Q Q K 384 5 J Q Q K 384 4 J Q Q K 384 3 J Q Q K 384 2 J Q Q K 384 9 T Q Q K 384 8 T Q Q K 384 7 T Q Q K 384 6 T Q Q K 384 5 T Q Q K 384 4 T Q Q K 384 3 T Q Q K 384 2 T Q Q K 384 8 9 Q Q K 384 7 9 Q Q K 384 6 9 Q Q K 384 5 9 Q Q K 384 4 9 Q Q K 384 3 9 Q Q K 384 2 9 Q Q K 384 7 8 Q Q K 384 6 8 Q Q K 384 5 8 Q Q K 384 4 8 Q Q K 384 3 8 Q Q K 384 2 8 Q Q K 384 6 7 Q Q K 384 5 7 Q Q K 384 4 7 Q Q K 384 3 7 Q Q K 384 2 7 Q Q K 384 5 6 Q Q K 384 4 6 Q Q K 384 3 6 Q Q K 384 2 6 Q Q K 384 4 5 Q Q K 384 3 5 Q Q K 384 2 5 Q Q K 384 3 4 Q Q K 384 2 4 Q Q K 384 2 3 Q Q K 384 9 T J Q Q 384 8 T J Q Q 384 7 T J Q Q 384 6 T J Q Q 384 5 T J Q Q 384 4 T J Q Q 384 3 T J Q Q 384 2 T J Q Q 384 8 9 J Q Q 384 7 9 J Q Q 384 6 9 J Q Q 384 5 9 J Q Q 384 4 9 J Q Q 384 3 9 J Q Q 384 2 9 J Q Q 384 7 8 J Q Q 384 6 8 J Q Q 384 5 8 J Q Q 384 4 8 J Q Q 384 3 8 J Q Q 384 2 8 J Q Q 384 6 7 J Q Q 384 5 7 J Q Q 384 4 7 J Q Q 384 3 7 J Q Q 384 2 7 J Q Q 384 5 6 J Q Q 384 4 6 J Q Q 384 3 6 J Q Q 384 2 6 J Q Q 384 4 5 J Q Q 384 3 5 J Q Q 384 2 5 J Q Q 384 3 4 J Q Q 384 2 4 J Q Q 384 2 3 J Q Q 384 8 9 T Q Q 384 7 9 T Q Q 384 6 9 T Q Q 384 5 9 T Q Q 384 4 9 T Q Q 384 3 9 T Q Q 384 2 9 T Q Q 384 7 8 T Q Q 384 6 8 T Q Q 384 5 8 T Q Q 384 4 8 T Q Q 384 3 8 T Q Q 384 2 8 T Q Q 384 6 7 T Q Q 384 5 7 T Q Q 384 4 7 T Q Q 384 3 7 T Q Q 384 2 7 T Q Q 384 5 6 T Q Q 384 4 6 T Q Q 384 3 6 T Q Q 384 2 6 T Q Q 384 4 5 T Q Q 384 3 5 T Q Q 384 2 5 T Q Q 384 3 4 T Q Q 384 2 4 T Q Q 384 2 3 T Q Q 384 7 8 9 Q Q 384 6 8 9 Q Q 384 5 8 9 Q Q 384 4 8 9 Q Q 384 3 8 9 Q Q 384 2 8 9 Q Q 384 6 7 9 Q Q 384 5 7 9 Q Q 384 4 7 9 Q Q 384 3 7 9 Q Q 384 2 7 9 Q Q 384 5 6 9 Q Q 384 4 6 9 Q Q 384 3 6 9 Q Q 384 2 6 9 Q Q 384 4 5 9 Q Q 384 3 5 9 Q Q 384 2 5 9 Q Q 384 3 4 9 Q Q 384 2 4 9 Q Q 384 2 3 9 Q Q 384 6 7 8 Q Q 384 5 7 8 Q Q 384 4 7 8 Q Q 384 3 7 8 Q Q 384 2 7 8 Q Q 384 5 6 8 Q Q 384 4 6 8 Q Q 384 3 6 8 Q Q 384 2 6 8 Q Q 384 4 5 8 Q Q 384 3 5 8 Q Q 384 2 5 8 Q Q 384 3 4 8 Q Q 384 2 4 8 Q Q 384 2 3 8 Q Q 384 5 6 7 Q Q 384 4 6 7 Q Q 384 3 6 7 Q Q 384 2 6 7 Q Q 384 4 5 7 Q Q 384 3 5 7 Q Q 384 2 5 7 Q Q 384 3 4 7 Q Q 384 2 4 7 Q Q 384 2 3 7 Q Q 384 4 5 6 Q Q 384 3 5 6 Q Q 384 2 5 6 Q Q 384 3 4 6 Q Q 384 2 4 6 Q Q 384 2 3 6 Q Q 384 3 4 5 Q Q 384 2 4 5 Q Q 384 2 3 5 Q Q 384 2 3 4 Q Q 384 J J Q K A Pair of Jacks 384 T J J K A 384 9 J J K A 384 8 J J K A 384 7 J J K A 384 6 J J K A 384 5 J J K A 384 4 J J K A 384 3 J J K A 384 2 J J K A 384 T J J Q A 384 9 J J Q A 384 8 J J Q A 384 7 J J Q A 384 6 J J Q A 384 5 J J Q A 384 4 J J Q A 384 3 J J Q A 384 2 J J Q A 384 9 T J J A 384 8 T J J A 384 7 T J J A 384 6 T J J A 384 5 T J J A 384 4 T J J A 384 3 T J J A 384 2 T J J A 384 8 9 J J A 384 7 9 J J A 384 6 9 J J A 384 5 9 J J A 384 4 9 J J A 384 3 9 J J A 384 2 9 J J A 384 7 8 J J A 384 6 8 J J A 384 5 8 J J A 384 4 8 J J A 384 3 8 J J A 384 2 8 J J A 384 6 7 J J A 384 5 7 J J A 384 4 7 J J A 384 3 7 J J A 384 2 7 J J A 384 5 6 J J A 384 4 6 J J A 384 3 6 J J A 384 2 6 J J A 384 4 5 J J A 384 3 5 J J A 384 2 5 J J A 384 3 4 J J A 384 2 4 J J A 384 2 3 J J A 384 T J J Q K 384 9 J J Q K 384 8 J J Q K 384 7 J J Q K 384 6 J J Q K 384 5 J J Q K 384 4 J J Q K 384 3 J J Q K 384 2 J J Q K 384 9 T J J K 384 8 T J J K 384 7 T J J K 384 6 T J J K 384 5 T J J K 384 4 T J J K 384 3 T J J K 384 2 T J J K 384 8 9 J J K 384 7 9 J J K 384 6 9 J J K 384 5 9 J J K 384 4 9 J J K 384 3 9 J J K 384 2 9 J J K 384 7 8 J J K 384 6 8 J J K 384 5 8 J J K 384 4 8 J J K 384 3 8 J J K 384 2 8 J J K 384 6 7 J J K 384 5 7 J J K 384 4 7 J J K 384 3 7 J J K 384 2 7 J J K 384 5 6 J J K 384 4 6 J J K 384 3 6 J J K 384 2 6 J J K 384 4 5 J J K 384 3 5 J J K 384 2 5 J J K 384 3 4 J J K 384 2 4 J J K 384 2 3 J J K 384 9 T J J Q 384 8 T J J Q 384 7 T J J Q 384 6 T J J Q 384 5 T J J Q 384 4 T J J Q 384 3 T J J Q 384 2 T J J Q 384 8 9 J J Q 384 7 9 J J Q 384 6 9 J J Q 384 5 9 J J Q 384 4 9 J J Q 384 3 9 J J Q 384 2 9 J J Q 384 7 8 J J Q 384 6 8 J J Q 384 5 8 J J Q 384 4 8 J J Q 384 3 8 J J Q 384 2 8 J J Q 384 6 7 J J Q 384 5 7 J J Q 384 4 7 J J Q 384 3 7 J J Q 384 2 7 J J Q 384 5 6 J J Q 384 4 6 J J Q 384 3 6 J J Q 384 2 6 J J Q 384 4 5 J J Q 384 3 5 J J Q 384 2 5 J J Q 384 3 4 J J Q 384 2 4 J J Q 384 2 3 J J Q 384 8 9 T J J 384 7 9 T J J 384 6 9 T J J 384 5 9 T J J 384 4 9 T J J 384 3 9 T J J 384 2 9 T J J 384 7 8 T J J 384 6 8 T J J 384 5 8 T J J 384 4 8 T J J 384 3 8 T J J 384 2 8 T J J 384 6 7 T J J 384 5 7 T J J 384 4 7 T J J 384 3 7 T J J 384 2 7 T J J 384 5 6 T J J 384 4 6 T J J 384 3 6 T J J 384 2 6 T J J 384 4 5 T J J 384 3 5 T J J 384 2 5 T J J 384 3 4 T J J 384 2 4 T J J 384 2 3 T J J 384 7 8 9 J J 384 6 8 9 J J 384 5 8 9 J J 384 4 8 9 J J 384 3 8 9 J J 384 2 8 9 J J 384 6 7 9 J J 384 5 7 9 J J 384 4 7 9 J J 384 3 7 9 J J 384 2 7 9 J J 384 5 6 9 J J 384 4 6 9 J J 384 3 6 9 J J 384 2 6 9 J J 384 4 5 9 J J 384 3 5 9 J J 384 2 5 9 J J 384 3 4 9 J J 384 2 4 9 J J 384 2 3 9 J J 384 6 7 8 J J 384 5 7 8 J J 384 4 7 8 J J 384 3 7 8 J J 384 2 7 8 J J 384 5 6 8 J J 384 4 6 8 J J 384 3 6 8 J J 384 2 6 8 J J 384 4 5 8 J J 384 3 5 8 J J 384 2 5 8 J J 384 3 4 8 J J 384 2 4 8 J J 384 2 3 8 J J 384 5 6 7 J J 384 4 6 7 J J 384 3 6 7 J J 384 2 6 7 J J 384 4 5 7 J J 384 3 5 7 J J 384 2 5 7 J J 384 3 4 7 J J 384 2 4 7 J J 384 2 3 7 J J 384 4 5 6 J J 384 3 5 6 J J 384 2 5 6 J J 384 3 4 6 J J 384 2 4 6 J J 384 2 3 6 J J 384 3 4 5 J J 384 2 4 5 J J 384 2 3 5 J J 384 2 3 4 J J 384 T T Q K A Pair of Tens 384 T T J K A 384 9 T T K A 384 8 T T K A 384 7 T T K A 384 6 T T K A 384 5 T T K A 384 4 T T K A 384 3 T T K A 384 2 T T K A 384 T T J Q A 384 9 T T Q A 384 8 T T Q A 384 7 T T Q A 384 6 T T Q A 384 5 T T Q A 384 4 T T Q A 384 3 T T Q A 384 2 T T Q A 384 9 T T J A 384 8 T T J A 384 7 T T J A 384 6 T T J A 384 5 T T J A 384 4 T T J A 384 3 T T J A 384 2 T T J A 384 8 9 T T A 384 7 9 T T A 384 6 9 T T A 384 5 9 T T A 384 4 9 T T A 384 3 9 T T A 384 2 9 T T A 384 7 8 T T A 384 6 8 T T A 384 5 8 T T A 384 4 8 T T A 384 3 8 T T A 384 2 8 T T A 384 6 7 T T A 384 5 7 T T A 384 4 7 T T A 384 3 7 T T A 384 2 7 T T A 384 5 6 T T A 384 4 6 T T A 384 3 6 T T A 384 2 6 T T A 384 4 5 T T A 384 3 5 T T A 384 2 5 T T A 384 3 4 T T A 384 2 4 T T A 384 2 3 T T A 384 T T J Q K 384 9 T T Q K 384 8 T T Q K 384 7 T T Q K 384 6 T T Q K 384 5 T T Q K 384 4 T T Q K 384 3 T T Q K 384 2 T T Q K 384 9 T T J K 384 8 T T J K 384 7 T T J K 384 6 T T J K 384 5 T T J K 384 4 T T J K 384 3 T T J K 384 2 T T J K 384 8 9 T T K 384 7 9 T T K 384 6 9 T T K 384 5 9 T T K 384 4 9 T T K 384 3 9 T T K 384 2 9 T T K 384 7 8 T T K 384 6 8 T T K 384 5 8 T T K 384 4 8 T T K 384 3 8 T T K 384 2 8 T T K 384 6 7 T T K 384 5 7 T T K 384 4 7 T T K 384 3 7 T T K 384 2 7 T T K 384 5 6 T T K 384 4 6 T T K 384 3 6 T T K 384 2 6 T T K 384 4 5 T T K 384 3 5 T T K 384 2 5 T T K 384 3 4 T T K 384 2 4 T T K 384 2 3 T T K 384 9 T T J Q 384 8 T T J Q 384 7 T T J Q 384 6 T T J Q 384 5 T T J Q 384 4 T T J Q 384 3 T T J Q 384 2 T T J Q 384 8 9 T T Q 384 7 9 T T Q 384 6 9 T T Q 384 5 9 T T Q 384 4 9 T T Q 384 3 9 T T Q 384 2 9 T T Q 384 7 8 T T Q 384 6 8 T T Q 384 5 8 T T Q 384 4 8 T T Q 384 3 8 T T Q 384 2 8 T T Q 384 6 7 T T Q 384 5 7 T T Q 384 4 7 T T Q 384 3 7 T T Q 384 2 7 T T Q 384 5 6 T T Q 384 4 6 T T Q 384 3 6 T T Q 384 2 6 T T Q 384 4 5 T T Q 384 3 5 T T Q 384 2 5 T T Q 384 3 4 T T Q 384 2 4 T T Q 384 2 3 T T Q 384 8 9 T T J 384 7 9 T T J 384 6 9 T T J 384 5 9 T T J 384 4 9 T T J 384 3 9 T T J 384 2 9 T T J 384 7 8 T T J 384 6 8 T T J 384 5 8 T T J 384 4 8 T T J 384 3 8 T T J 384 2 8 T T J 384 6 7 T T J 384 5 7 T T J 384 4 7 T T J 384 3 7 T T J 384 2 7 T T J 384 5 6 T T J 384 4 6 T T J 384 3 6 T T J 384 2 6 T T J 384 4 5 T T J 384 3 5 T T J 384 2 5 T T J 384 3 4 T T J 384 2 4 T T J 384 2 3 T T J 384 7 8 9 T T 384 6 8 9 T T 384 5 8 9 T T 384 4 8 9 T T 384 3 8 9 T T 384 2 8 9 T T 384 6 7 9 T T 384 5 7 9 T T 384 4 7 9 T T 384 3 7 9 T T 384 2 7 9 T T 384 5 6 9 T T 384 4 6 9 T T 384 3 6 9 T T 384 2 6 9 T T 384 4 5 9 T T 384 3 5 9 T T 384 2 5 9 T T 384 3 4 9 T T 384 2 4 9 T T 384 2 3 9 T T 384 6 7 8 T T 384 5 7 8 T T 384 4 7 8 T T 384 3 7 8 T T 384 2 7 8 T T 384 5 6 8 T T 384 4 6 8 T T 384 3 6 8 T T 384 2 6 8 T T 384 4 5 8 T T 384 3 5 8 T T 384 2 5 8 T T 384 3 4 8 T T 384 2 4 8 T T 384 2 3 8 T T 384 5 6 7 T T 384 4 6 7 T T 384 3 6 7 T T 384 2 6 7 T T 384 4 5 7 T T 384 3 5 7 T T 384 2 5 7 T T 384 3 4 7 T T 384 2 4 7 T T 384 2 3 7 T T 384 4 5 6 T T 384 3 5 6 T T 384 2 5 6 T T 384 3 4 6 T T 384 2 4 6 T T 384 2 3 6 T T 384 3 4 5 T T 384 2 4 5 T T 384 2 3 5 T T 384 2 3 4 T T 384 9 9 Q K A Pair of Nines 384 9 9 J K A 384 9 9 T K A 384 8 9 9 K A 384 7 9 9 K A 384 6 9 9 K A 384 5 9 9 K A 384 4 9 9 K A 384 3 9 9 K A 384 2 9 9 K A 384 9 9 J Q A 384 9 9 T Q A 384 8 9 9 Q A 384 7 9 9 Q A 384 6 9 9 Q A 384 5 9 9 Q A 384 4 9 9 Q A 384 3 9 9 Q A 384 2 9 9 Q A 384 9 9 T J A 384 8 9 9 J A 384 7 9 9 J A 384 6 9 9 J A 384 5 9 9 J A 384 4 9 9 J A 384 3 9 9 J A 384 2 9 9 J A 384 8 9 9 T A 384 7 9 9 T A 384 6 9 9 T A 384 5 9 9 T A 384 4 9 9 T A 384 3 9 9 T A 384 2 9 9 T A 384 7 8 9 9 A 384 6 8 9 9 A 384 5 8 9 9 A 384 4 8 9 9 A 384 3 8 9 9 A 384 2 8 9 9 A 384 6 7 9 9 A 384 5 7 9 9 A 384 4 7 9 9 A 384 3 7 9 9 A 384 2 7 9 9 A 384 5 6 9 9 A 384 4 6 9 9 A 384 3 6 9 9 A 384 2 6 9 9 A 384 4 5 9 9 A 384 3 5 9 9 A 384 2 5 9 9 A 384 3 4 9 9 A 384 2 4 9 9 A 384 2 3 9 9 A 384 9 9 J Q K 384 9 9 T Q K 384 8 9 9 Q K 384 7 9 9 Q K 384 6 9 9 Q K 384 5 9 9 Q K 384 4 9 9 Q K 384 3 9 9 Q K 384 2 9 9 Q K 384 9 9 T J K 384 8 9 9 J K 384 7 9 9 J K 384 6 9 9 J K 384 5 9 9 J K 384 4 9 9 J K 384 3 9 9 J K 384 2 9 9 J K 384 8 9 9 T K 384 7 9 9 T K 384 6 9 9 T K 384 5 9 9 T K 384 4 9 9 T K 384 3 9 9 T K 384 2 9 9 T K 384 7 8 9 9 K 384 6 8 9 9 K 384 5 8 9 9 K 384 4 8 9 9 K 384 3 8 9 9 K 384 2 8 9 9 K 384 6 7 9 9 K 384 5 7 9 9 K 384 4 7 9 9 K 384 3 7 9 9 K 384 2 7 9 9 K 384 5 6 9 9 K 384 4 6 9 9 K 384 3 6 9 9 K 384 2 6 9 9 K 384 4 5 9 9 K 384 3 5 9 9 K 384 2 5 9 9 K 384 3 4 9 9 K 384 2 4 9 9 K 384 2 3 9 9 K 384 9 9 T J Q 384 8 9 9 J Q 384 7 9 9 J Q 384 6 9 9 J Q 384 5 9 9 J Q 384 4 9 9 J Q 384 3 9 9 J Q 384 2 9 9 J Q 384 8 9 9 T Q 384 7 9 9 T Q 384 6 9 9 T Q 384 5 9 9 T Q 384 4 9 9 T Q 384 3 9 9 T Q 384 2 9 9 T Q 384 7 8 9 9 Q 384 6 8 9 9 Q 384 5 8 9 9 Q 384 4 8 9 9 Q 384 3 8 9 9 Q 384 2 8 9 9 Q 384 6 7 9 9 Q 384 5 7 9 9 Q 384 4 7 9 9 Q 384 3 7 9 9 Q 384 2 7 9 9 Q 384 5 6 9 9 Q 384 4 6 9 9 Q 384 3 6 9 9 Q 384 2 6 9 9 Q 384 4 5 9 9 Q 384 3 5 9 9 Q 384 2 5 9 9 Q 384 3 4 9 9 Q 384 2 4 9 9 Q 384 2 3 9 9 Q 384 8 9 9 T J 384 7 9 9 T J 384 6 9 9 T J 384 5 9 9 T J 384 4 9 9 T J 384 3 9 9 T J 384 2 9 9 T J 384 7 8 9 9 J 384 6 8 9 9 J 384 5 8 9 9 J 384 4 8 9 9 J 384 3 8 9 9 J 384 2 8 9 9 J 384 6 7 9 9 J 384 5 7 9 9 J 384 4 7 9 9 J 384 3 7 9 9 J 384 2 7 9 9 J 384 5 6 9 9 J 384 4 6 9 9 J 384 3 6 9 9 J 384 2 6 9 9 J 384 4 5 9 9 J 384 3 5 9 9 J 384 2 5 9 9 J 384 3 4 9 9 J 384 2 4 9 9 J 384 2 3 9 9 J 384 7 8 9 9 T 384 6 8 9 9 T 384 5 8 9 9 T 384 4 8 9 9 T 384 3 8 9 9 T 384 2 8 9 9 T 384 6 7 9 9 T 384 5 7 9 9 T 384 4 7 9 9 T 384 3 7 9 9 T 384 2 7 9 9 T 384 5 6 9 9 T 384 4 6 9 9 T 384 3 6 9 9 T 384 2 6 9 9 T 384 4 5 9 9 T 384 3 5 9 9 T 384 2 5 9 9 T 384 3 4 9 9 T 384 2 4 9 9 T 384 2 3 9 9 T 384 6 7 8 9 9 384 5 7 8 9 9 384 4 7 8 9 9 384 3 7 8 9 9 384 2 7 8 9 9 384 5 6 8 9 9 384 4 6 8 9 9 384 3 6 8 9 9 384 2 6 8 9 9 384 4 5 8 9 9 384 3 5 8 9 9 384 2 5 8 9 9 384 3 4 8 9 9 384 2 4 8 9 9 384 2 3 8 9 9 384 5 6 7 9 9 384 4 6 7 9 9 384 3 6 7 9 9 384 2 6 7 9 9 384 4 5 7 9 9 384 3 5 7 9 9 384 2 5 7 9 9 384 3 4 7 9 9 384 2 4 7 9 9 384 2 3 7 9 9 384 4 5 6 9 9 384 3 5 6 9 9 384 2 5 6 9 9 384 3 4 6 9 9 384 2 4 6 9 9 384 2 3 6 9 9 384 3 4 5 9 9 384 2 4 5 9 9 384 2 3 5 9 9 384 2 3 4 9 9 384 8 8 Q K A Pair of Eights 384 8 8 J K A 384 8 8 T K A 384 8 8 9 K A 384 7 8 8 K A 384 6 8 8 K A 384 5 8 8 K A 384 4 8 8 K A 384 3 8 8 K A 384 2 8 8 K A 384 8 8 J Q A 384 8 8 T Q A 384 8 8 9 Q A 384 7 8 8 Q A 384 6 8 8 Q A 384 5 8 8 Q A 384 4 8 8 Q A 384 3 8 8 Q A 384 2 8 8 Q A 384 8 8 T J A 384 8 8 9 J A 384 7 8 8 J A 384 6 8 8 J A 384 5 8 8 J A 384 4 8 8 J A 384 3 8 8 J A 384 2 8 8 J A 384 8 8 9 T A 384 7 8 8 T A 384 6 8 8 T A 384 5 8 8 T A 384 4 8 8 T A 384 3 8 8 T A 384 2 8 8 T A 384 7 8 8 9 A 384 6 8 8 9 A 384 5 8 8 9 A 384 4 8 8 9 A 384 3 8 8 9 A 384 2 8 8 9 A 384 6 7 8 8 A 384 5 7 8 8 A 384 4 7 8 8 A 384 3 7 8 8 A 384 2 7 8 8 A 384 5 6 8 8 A 384 4 6 8 8 A 384 3 6 8 8 A 384 2 6 8 8 A 384 4 5 8 8 A 384 3 5 8 8 A 384 2 5 8 8 A 384 3 4 8 8 A 384 2 4 8 8 A 384 2 3 8 8 A 384 8 8 J Q K 384 8 8 T Q K 384 8 8 9 Q K 384 7 8 8 Q K 384 6 8 8 Q K 384 5 8 8 Q K 384 4 8 8 Q K 384 3 8 8 Q K 384 2 8 8 Q K 384 8 8 T J K 384 8 8 9 J K 384 7 8 8 J K 384 6 8 8 J K 384 5 8 8 J K 384 4 8 8 J K 384 3 8 8 J K 384 2 8 8 J K 384 8 8 9 T K 384 7 8 8 T K 384 6 8 8 T K 384 5 8 8 T K 384 4 8 8 T K 384 3 8 8 T K 384 2 8 8 T K 384 7 8 8 9 K 384 6 8 8 9 K 384 5 8 8 9 K 384 4 8 8 9 K 384 3 8 8 9 K 384 2 8 8 9 K 384 6 7 8 8 K 384 5 7 8 8 K 384 4 7 8 8 K 384 3 7 8 8 K 384 2 7 8 8 K 384 5 6 8 8 K 384 4 6 8 8 K 384 3 6 8 8 K 384 2 6 8 8 K 384 4 5 8 8 K 384 3 5 8 8 K 384 2 5 8 8 K 384 3 4 8 8 K 384 2 4 8 8 K 384 2 3 8 8 K 384 8 8 T J Q 384 8 8 9 J Q 384 7 8 8 J Q 384 6 8 8 J Q 384 5 8 8 J Q 384 4 8 8 J Q 384 3 8 8 J Q 384 2 8 8 J Q 384 8 8 9 T Q 384 7 8 8 T Q 384 6 8 8 T Q 384 5 8 8 T Q 384 4 8 8 T Q 384 3 8 8 T Q 384 2 8 8 T Q 384 7 8 8 9 Q 384 6 8 8 9 Q 384 5 8 8 9 Q 384 4 8 8 9 Q 384 3 8 8 9 Q 384 2 8 8 9 Q 384 6 7 8 8 Q 384 5 7 8 8 Q 384 4 7 8 8 Q 384 3 7 8 8 Q 384 2 7 8 8 Q 384 5 6 8 8 Q 384 4 6 8 8 Q 384 3 6 8 8 Q 384 2 6 8 8 Q 384 4 5 8 8 Q 384 3 5 8 8 Q 384 2 5 8 8 Q 384 3 4 8 8 Q 384 2 4 8 8 Q 384 2 3 8 8 Q 384 8 8 9 T J 384 7 8 8 T J 384 6 8 8 T J 384 5 8 8 T J 384 4 8 8 T J 384 3 8 8 T J 384 2 8 8 T J 384 7 8 8 9 J 384 6 8 8 9 J 384 5 8 8 9 J 384 4 8 8 9 J 384 3 8 8 9 J 384 2 8 8 9 J 384 6 7 8 8 J 384 5 7 8 8 J 384 4 7 8 8 J 384 3 7 8 8 J 384 2 7 8 8 J 384 5 6 8 8 J 384 4 6 8 8 J 384 3 6 8 8 J 384 2 6 8 8 J 384 4 5 8 8 J 384 3 5 8 8 J 384 2 5 8 8 J 384 3 4 8 8 J 384 2 4 8 8 J 384 2 3 8 8 J 384 7 8 8 9 T 384 6 8 8 9 T 384 5 8 8 9 T 384 4 8 8 9 T 384 3 8 8 9 T 384 2 8 8 9 T 384 6 7 8 8 T 384 5 7 8 8 T 384 4 7 8 8 T 384 3 7 8 8 T 384 2 7 8 8 T 384 5 6 8 8 T 384 4 6 8 8 T 384 3 6 8 8 T 384 2 6 8 8 T 384 4 5 8 8 T 384 3 5 8 8 T 384 2 5 8 8 T 384 3 4 8 8 T 384 2 4 8 8 T 384 2 3 8 8 T 384 6 7 8 8 9 384 5 7 8 8 9 384 4 7 8 8 9 384 3 7 8 8 9 384 2 7 8 8 9 384 5 6 8 8 9 384 4 6 8 8 9 384 3 6 8 8 9 384 2 6 8 8 9 384 4 5 8 8 9 384 3 5 8 8 9 384 2 5 8 8 9 384 3 4 8 8 9 384 2 4 8 8 9 384 2 3 8 8 9 384 5 6 7 8 8 384 4 6 7 8 8 384 3 6 7 8 8 384 2 6 7 8 8 384 4 5 7 8 8 384 3 5 7 8 8 384 2 5 7 8 8 384 3 4 7 8 8 384 2 4 7 8 8 384 2 3 7 8 8 384 4 5 6 8 8 384 3 5 6 8 8 384 2 5 6 8 8 384 3 4 6 8 8 384 2 4 6 8 8 384 2 3 6 8 8 384 3 4 5 8 8 384 2 4 5 8 8 384 2 3 5 8 8 384 2 3 4 8 8 384 7 7 Q K A Pair of Sevens 384 7 7 J K A 384 7 7 T K A 384 7 7 9 K A 384 7 7 8 K A 384 6 7 7 K A 384 5 7 7 K A 384 4 7 7 K A 384 3 7 7 K A 384 2 7 7 K A 384 7 7 J Q A 384 7 7 T Q A 384 7 7 9 Q A 384 7 7 8 Q A 384 6 7 7 Q A 384 5 7 7 Q A 384 4 7 7 Q A 384 3 7 7 Q A 384 2 7 7 Q A 384 7 7 T J A 384 7 7 9 J A 384 7 7 8 J A 384 6 7 7 J A 384 5 7 7 J A 384 4 7 7 J A 384 3 7 7 J A 384 2 7 7 J A 384 7 7 9 T A 384 7 7 8 T A 384 6 7 7 T A 384 5 7 7 T A 384 4 7 7 T A 384 3 7 7 T A 384 2 7 7 T A 384 7 7 8 9 A 384 6 7 7 9 A 384 5 7 7 9 A 384 4 7 7 9 A 384 3 7 7 9 A 384 2 7 7 9 A 384 6 7 7 8 A 384 5 7 7 8 A 384 4 7 7 8 A 384 3 7 7 8 A 384 2 7 7 8 A 384 5 6 7 7 A 384 4 6 7 7 A 384 3 6 7 7 A 384 2 6 7 7 A 384 4 5 7 7 A 384 3 5 7 7 A 384 2 5 7 7 A 384 3 4 7 7 A 384 2 4 7 7 A 384 2 3 7 7 A 384 7 7 J Q K 384 7 7 T Q K 384 7 7 9 Q K 384 7 7 8 Q K 384 6 7 7 Q K 384 5 7 7 Q K 384 4 7 7 Q K 384 3 7 7 Q K 384 2 7 7 Q K 384 7 7 T J K 384 7 7 9 J K 384 7 7 8 J K 384 6 7 7 J K 384 5 7 7 J K 384 4 7 7 J K 384 3 7 7 J K 384 2 7 7 J K 384 7 7 9 T K 384 7 7 8 T K 384 6 7 7 T K 384 5 7 7 T K 384 4 7 7 T K 384 3 7 7 T K 384 2 7 7 T K 384 7 7 8 9 K 384 6 7 7 9 K 384 5 7 7 9 K 384 4 7 7 9 K 384 3 7 7 9 K 384 2 7 7 9 K 384 6 7 7 8 K 384 5 7 7 8 K 384 4 7 7 8 K 384 3 7 7 8 K 384 2 7 7 8 K 384 5 6 7 7 K 384 4 6 7 7 K 384 3 6 7 7 K 384 2 6 7 7 K 384 4 5 7 7 K 384 3 5 7 7 K 384 2 5 7 7 K 384 3 4 7 7 K 384 2 4 7 7 K 384 2 3 7 7 K 384 7 7 T J Q 384 7 7 9 J Q 384 7 7 8 J Q 384 6 7 7 J Q 384 5 7 7 J Q 384 4 7 7 J Q 384 3 7 7 J Q 384 2 7 7 J Q 384 7 7 9 T Q 384 7 7 8 T Q 384 6 7 7 T Q 384 5 7 7 T Q 384 4 7 7 T Q 384 3 7 7 T Q 384 2 7 7 T Q 384 7 7 8 9 Q 384 6 7 7 9 Q 384 5 7 7 9 Q 384 4 7 7 9 Q 384 3 7 7 9 Q 384 2 7 7 9 Q 384 6 7 7 8 Q 384 5 7 7 8 Q 384 4 7 7 8 Q 384 3 7 7 8 Q 384 2 7 7 8 Q 384 5 6 7 7 Q 384 4 6 7 7 Q 384 3 6 7 7 Q 384 2 6 7 7 Q 384 4 5 7 7 Q 384 3 5 7 7 Q 384 2 5 7 7 Q 384 3 4 7 7 Q 384 2 4 7 7 Q 384 2 3 7 7 Q 384 7 7 9 T J 384 7 7 8 T J 384 6 7 7 T J 384 5 7 7 T J 384 4 7 7 T J 384 3 7 7 T J 384 2 7 7 T J 384 7 7 8 9 J 384 6 7 7 9 J 384 5 7 7 9 J 384 4 7 7 9 J 384 3 7 7 9 J 384 2 7 7 9 J 384 6 7 7 8 J 384 5 7 7 8 J 384 4 7 7 8 J 384 3 7 7 8 J 384 2 7 7 8 J 384 5 6 7 7 J 384 4 6 7 7 J 384 3 6 7 7 J 384 2 6 7 7 J 384 4 5 7 7 J 384 3 5 7 7 J 384 2 5 7 7 J 384 3 4 7 7 J 384 2 4 7 7 J 384 2 3 7 7 J 384 7 7 8 9 T 384 6 7 7 9 T 384 5 7 7 9 T 384 4 7 7 9 T 384 3 7 7 9 T 384 2 7 7 9 T 384 6 7 7 8 T 384 5 7 7 8 T 384 4 7 7 8 T 384 3 7 7 8 T 384 2 7 7 8 T 384 5 6 7 7 T 384 4 6 7 7 T 384 3 6 7 7 T 384 2 6 7 7 T 384 4 5 7 7 T 384 3 5 7 7 T 384 2 5 7 7 T 384 3 4 7 7 T 384 2 4 7 7 T 384 2 3 7 7 T 384 6 7 7 8 9 384 5 7 7 8 9 384 4 7 7 8 9 384 3 7 7 8 9 384 2 7 7 8 9 384 5 6 7 7 9 384 4 6 7 7 9 384 3 6 7 7 9 384 2 6 7 7 9 384 4 5 7 7 9 384 3 5 7 7 9 384 2 5 7 7 9 384 3 4 7 7 9 384 2 4 7 7 9 384 2 3 7 7 9 384 5 6 7 7 8 384 4 6 7 7 8 384 3 6 7 7 8 384 2 6 7 7 8 384 4 5 7 7 8 384 3 5 7 7 8 384 2 5 7 7 8 384 3 4 7 7 8 384 2 4 7 7 8 384 2 3 7 7 8 384 4 5 6 7 7 384 3 5 6 7 7 384 2 5 6 7 7 384 3 4 6 7 7 384 2 4 6 7 7 384 2 3 6 7 7 384 3 4 5 7 7 384 2 4 5 7 7 384 2 3 5 7 7 384 2 3 4 7 7 384 6 6 Q K A Pair of Sixes 384 6 6 J K A 384 6 6 T K A 384 6 6 9 K A 384 6 6 8 K A 384 6 6 7 K A 384 5 6 6 K A 384 4 6 6 K A 384 3 6 6 K A 384 2 6 6 K A 384 6 6 J Q A 384 6 6 T Q A 384 6 6 9 Q A 384 6 6 8 Q A 384 6 6 7 Q A 384 5 6 6 Q A 384 4 6 6 Q A 384 3 6 6 Q A 384 2 6 6 Q A 384 6 6 T J A 384 6 6 9 J A 384 6 6 8 J A 384 6 6 7 J A 384 5 6 6 J A 384 4 6 6 J A 384 3 6 6 J A 384 2 6 6 J A 384 6 6 9 T A 384 6 6 8 T A 384 6 6 7 T A 384 5 6 6 T A 384 4 6 6 T A 384 3 6 6 T A 384 2 6 6 T A 384 6 6 8 9 A 384 6 6 7 9 A 384 5 6 6 9 A 384 4 6 6 9 A 384 3 6 6 9 A 384 2 6 6 9 A 384 6 6 7 8 A 384 5 6 6 8 A 384 4 6 6 8 A 384 3 6 6 8 A 384 2 6 6 8 A 384 5 6 6 7 A 384 4 6 6 7 A 384 3 6 6 7 A 384 2 6 6 7 A 384 4 5 6 6 A 384 3 5 6 6 A 384 2 5 6 6 A 384 3 4 6 6 A 384 2 4 6 6 A 384 2 3 6 6 A 384 6 6 J Q K 384 6 6 T Q K 384 6 6 9 Q K 384 6 6 8 Q K 384 6 6 7 Q K 384 5 6 6 Q K 384 4 6 6 Q K 384 3 6 6 Q K 384 2 6 6 Q K 384 6 6 T J K 384 6 6 9 J K 384 6 6 8 J K 384 6 6 7 J K 384 5 6 6 J K 384 4 6 6 J K 384 3 6 6 J K 384 2 6 6 J K 384 6 6 9 T K 384 6 6 8 T K 384 6 6 7 T K 384 5 6 6 T K 384 4 6 6 T K 384 3 6 6 T K 384 2 6 6 T K 384 6 6 8 9 K 384 6 6 7 9 K 384 5 6 6 9 K 384 4 6 6 9 K 384 3 6 6 9 K 384 2 6 6 9 K 384 6 6 7 8 K 384 5 6 6 8 K 384 4 6 6 8 K 384 3 6 6 8 K 384 2 6 6 8 K 384 5 6 6 7 K 384 4 6 6 7 K 384 3 6 6 7 K 384 2 6 6 7 K 384 4 5 6 6 K 384 3 5 6 6 K 384 2 5 6 6 K 384 3 4 6 6 K 384 2 4 6 6 K 384 2 3 6 6 K 384 6 6 T J Q 384 6 6 9 J Q 384 6 6 8 J Q 384 6 6 7 J Q 384 5 6 6 J Q 384 4 6 6 J Q 384 3 6 6 J Q 384 2 6 6 J Q 384 6 6 9 T Q 384 6 6 8 T Q 384 6 6 7 T Q 384 5 6 6 T Q 384 4 6 6 T Q 384 3 6 6 T Q 384 2 6 6 T Q 384 6 6 8 9 Q 384 6 6 7 9 Q 384 5 6 6 9 Q 384 4 6 6 9 Q 384 3 6 6 9 Q 384 2 6 6 9 Q 384 6 6 7 8 Q 384 5 6 6 8 Q 384 4 6 6 8 Q 384 3 6 6 8 Q 384 2 6 6 8 Q 384 5 6 6 7 Q 384 4 6 6 7 Q 384 3 6 6 7 Q 384 2 6 6 7 Q 384 4 5 6 6 Q 384 3 5 6 6 Q 384 2 5 6 6 Q 384 3 4 6 6 Q 384 2 4 6 6 Q 384 2 3 6 6 Q 384 6 6 9 T J 384 6 6 8 T J 384 6 6 7 T J 384 5 6 6 T J 384 4 6 6 T J 384 3 6 6 T J 384 2 6 6 T J 384 6 6 8 9 J 384 6 6 7 9 J 384 5 6 6 9 J 384 4 6 6 9 J 384 3 6 6 9 J 384 2 6 6 9 J 384 6 6 7 8 J 384 5 6 6 8 J 384 4 6 6 8 J 384 3 6 6 8 J 384 2 6 6 8 J 384 5 6 6 7 J 384 4 6 6 7 J 384 3 6 6 7 J 384 2 6 6 7 J 384 4 5 6 6 J 384 3 5 6 6 J 384 2 5 6 6 J 384 3 4 6 6 J 384 2 4 6 6 J 384 2 3 6 6 J 384 6 6 8 9 T 384 6 6 7 9 T 384 5 6 6 9 T 384 4 6 6 9 T 384 3 6 6 9 T 384 2 6 6 9 T 384 6 6 7 8 T 384 5 6 6 8 T 384 4 6 6 8 T 384 3 6 6 8 T 384 2 6 6 8 T 384 5 6 6 7 T 384 4 6 6 7 T 384 3 6 6 7 T 384 2 6 6 7 T 384 4 5 6 6 T 384 3 5 6 6 T 384 2 5 6 6 T 384 3 4 6 6 T 384 2 4 6 6 T 384 2 3 6 6 T 384 6 6 7 8 9 384 5 6 6 8 9 384 4 6 6 8 9 384 3 6 6 8 9 384 2 6 6 8 9 384 5 6 6 7 9 384 4 6 6 7 9 384 3 6 6 7 9 384 2 6 6 7 9 384 4 5 6 6 9 384 3 5 6 6 9 384 2 5 6 6 9 384 3 4 6 6 9 384 2 4 6 6 9 384 2 3 6 6 9 384 5 6 6 7 8 384 4 6 6 7 8 384 3 6 6 7 8 384 2 6 6 7 8 384 4 5 6 6 8 384 3 5 6 6 8 384 2 5 6 6 8 384 3 4 6 6 8 384 2 4 6 6 8 384 2 3 6 6 8 384 4 5 6 6 7 384 3 5 6 6 7 384 2 5 6 6 7 384 3 4 6 6 7 384 2 4 6 6 7 384 2 3 6 6 7 384 3 4 5 6 6 384 2 4 5 6 6 384 2 3 5 6 6 384 2 3 4 6 6 384 5 5 Q K A Pair of Fives 384 5 5 J K A 384 5 5 T K A 384 5 5 9 K A 384 5 5 8 K A 384 5 5 7 K A 384 5 5 6 K A 384 4 5 5 K A 384 3 5 5 K A 384 2 5 5 K A 384 5 5 J Q A 384 5 5 T Q A 384 5 5 9 Q A 384 5 5 8 Q A 384 5 5 7 Q A 384 5 5 6 Q A 384 4 5 5 Q A 384 3 5 5 Q A 384 2 5 5 Q A 384 5 5 T J A 384 5 5 9 J A 384 5 5 8 J A 384 5 5 7 J A 384 5 5 6 J A 384 4 5 5 J A 384 3 5 5 J A 384 2 5 5 J A 384 5 5 9 T A 384 5 5 8 T A 384 5 5 7 T A 384 5 5 6 T A 384 4 5 5 T A 384 3 5 5 T A 384 2 5 5 T A 384 5 5 8 9 A 384 5 5 7 9 A 384 5 5 6 9 A 384 4 5 5 9 A 384 3 5 5 9 A 384 2 5 5 9 A 384 5 5 7 8 A 384 5 5 6 8 A 384 4 5 5 8 A 384 3 5 5 8 A 384 2 5 5 8 A 384 5 5 6 7 A 384 4 5 5 7 A 384 3 5 5 7 A 384 2 5 5 7 A 384 4 5 5 6 A 384 3 5 5 6 A 384 2 5 5 6 A 384 3 4 5 5 A 384 2 4 5 5 A 384 2 3 5 5 A 384 5 5 J Q K 384 5 5 T Q K 384 5 5 9 Q K 384 5 5 8 Q K 384 5 5 7 Q K 384 5 5 6 Q K 384 4 5 5 Q K 384 3 5 5 Q K 384 2 5 5 Q K 384 5 5 T J K 384 5 5 9 J K 384 5 5 8 J K 384 5 5 7 J K 384 5 5 6 J K 384 4 5 5 J K 384 3 5 5 J K 384 2 5 5 J K 384 5 5 9 T K 384 5 5 8 T K 384 5 5 7 T K 384 5 5 6 T K 384 4 5 5 T K 384 3 5 5 T K 384 2 5 5 T K 384 5 5 8 9 K 384 5 5 7 9 K 384 5 5 6 9 K 384 4 5 5 9 K 384 3 5 5 9 K 384 2 5 5 9 K 384 5 5 7 8 K 384 5 5 6 8 K 384 4 5 5 8 K 384 3 5 5 8 K 384 2 5 5 8 K 384 5 5 6 7 K 384 4 5 5 7 K 384 3 5 5 7 K 384 2 5 5 7 K 384 4 5 5 6 K 384 3 5 5 6 K 384 2 5 5 6 K 384 3 4 5 5 K 384 2 4 5 5 K 384 2 3 5 5 K 384 5 5 T J Q 384 5 5 9 J Q 384 5 5 8 J Q 384 5 5 7 J Q 384 5 5 6 J Q 384 4 5 5 J Q 384 3 5 5 J Q 384 2 5 5 J Q 384 5 5 9 T Q 384 5 5 8 T Q 384 5 5 7 T Q 384 5 5 6 T Q 384 4 5 5 T Q 384 3 5 5 T Q 384 2 5 5 T Q 384 5 5 8 9 Q 384 5 5 7 9 Q 384 5 5 6 9 Q 384 4 5 5 9 Q 384 3 5 5 9 Q 384 2 5 5 9 Q 384 5 5 7 8 Q 384 5 5 6 8 Q 384 4 5 5 8 Q 384 3 5 5 8 Q 384 2 5 5 8 Q 384 5 5 6 7 Q 384 4 5 5 7 Q 384 3 5 5 7 Q 384 2 5 5 7 Q 384 4 5 5 6 Q 384 3 5 5 6 Q 384 2 5 5 6 Q 384 3 4 5 5 Q 384 2 4 5 5 Q 384 2 3 5 5 Q 384 5 5 9 T J 384 5 5 8 T J 384 5 5 7 T J 384 5 5 6 T J 384 4 5 5 T J 384 3 5 5 T J 384 2 5 5 T J 384 5 5 8 9 J 384 5 5 7 9 J 384 5 5 6 9 J 384 4 5 5 9 J 384 3 5 5 9 J 384 2 5 5 9 J 384 5 5 7 8 J 384 5 5 6 8 J 384 4 5 5 8 J 384 3 5 5 8 J 384 2 5 5 8 J 384 5 5 6 7 J 384 4 5 5 7 J 384 3 5 5 7 J 384 2 5 5 7 J 384 4 5 5 6 J 384 3 5 5 6 J 384 2 5 5 6 J 384 3 4 5 5 J 384 2 4 5 5 J 384 2 3 5 5 J 384 5 5 8 9 T 384 5 5 7 9 T 384 5 5 6 9 T 384 4 5 5 9 T 384 3 5 5 9 T 384 2 5 5 9 T 384 5 5 7 8 T 384 5 5 6 8 T 384 4 5 5 8 T 384 3 5 5 8 T 384 2 5 5 8 T 384 5 5 6 7 T 384 4 5 5 7 T 384 3 5 5 7 T 384 2 5 5 7 T 384 4 5 5 6 T 384 3 5 5 6 T 384 2 5 5 6 T 384 3 4 5 5 T 384 2 4 5 5 T 384 2 3 5 5 T 384 5 5 7 8 9 384 5 5 6 8 9 384 4 5 5 8 9 384 3 5 5 8 9 384 2 5 5 8 9 384 5 5 6 7 9 384 4 5 5 7 9 384 3 5 5 7 9 384 2 5 5 7 9 384 4 5 5 6 9 384 3 5 5 6 9 384 2 5 5 6 9 384 3 4 5 5 9 384 2 4 5 5 9 384 2 3 5 5 9 384 5 5 6 7 8 384 4 5 5 7 8 384 3 5 5 7 8 384 2 5 5 7 8 384 4 5 5 6 8 384 3 5 5 6 8 384 2 5 5 6 8 384 3 4 5 5 8 384 2 4 5 5 8 384 2 3 5 5 8 384 4 5 5 6 7 384 3 5 5 6 7 384 2 5 5 6 7 384 3 4 5 5 7 384 2 4 5 5 7 384 2 3 5 5 7 384 3 4 5 5 6 384 2 4 5 5 6 384 2 3 5 5 6 384 2 3 4 5 5 384 4 4 Q K A Pair of Fours 384 4 4 J K A 384 4 4 T K A 384 4 4 9 K A 384 4 4 8 K A 384 4 4 7 K A 384 4 4 6 K A 384 4 4 5 K A 384 3 4 4 K A 384 2 4 4 K A 384 4 4 J Q A 384 4 4 T Q A 384 4 4 9 Q A 384 4 4 8 Q A 384 4 4 7 Q A 384 4 4 6 Q A 384 4 4 5 Q A 384 3 4 4 Q A 384 2 4 4 Q A 384 4 4 T J A 384 4 4 9 J A 384 4 4 8 J A 384 4 4 7 J A 384 4 4 6 J A 384 4 4 5 J A 384 3 4 4 J A 384 2 4 4 J A 384 4 4 9 T A 384 4 4 8 T A 384 4 4 7 T A 384 4 4 6 T A 384 4 4 5 T A 384 3 4 4 T A 384 2 4 4 T A 384 4 4 8 9 A 384 4 4 7 9 A 384 4 4 6 9 A 384 4 4 5 9 A 384 3 4 4 9 A 384 2 4 4 9 A 384 4 4 7 8 A 384 4 4 6 8 A 384 4 4 5 8 A 384 3 4 4 8 A 384 2 4 4 8 A 384 4 4 6 7 A 384 4 4 5 7 A 384 3 4 4 7 A 384 2 4 4 7 A 384 4 4 5 6 A 384 3 4 4 6 A 384 2 4 4 6 A 384 3 4 4 5 A 384 2 4 4 5 A 384 2 3 4 4 A 384 4 4 J Q K 384 4 4 T Q K 384 4 4 9 Q K 384 4 4 8 Q K 384 4 4 7 Q K 384 4 4 6 Q K 384 4 4 5 Q K 384 3 4 4 Q K 384 2 4 4 Q K 384 4 4 T J K 384 4 4 9 J K 384 4 4 8 J K 384 4 4 7 J K 384 4 4 6 J K 384 4 4 5 J K 384 3 4 4 J K 384 2 4 4 J K 384 4 4 9 T K 384 4 4 8 T K 384 4 4 7 T K 384 4 4 6 T K 384 4 4 5 T K 384 3 4 4 T K 384 2 4 4 T K 384 4 4 8 9 K 384 4 4 7 9 K 384 4 4 6 9 K 384 4 4 5 9 K 384 3 4 4 9 K 384 2 4 4 9 K 384 4 4 7 8 K 384 4 4 6 8 K 384 4 4 5 8 K 384 3 4 4 8 K 384 2 4 4 8 K 384 4 4 6 7 K 384 4 4 5 7 K 384 3 4 4 7 K 384 2 4 4 7 K 384 4 4 5 6 K 384 3 4 4 6 K 384 2 4 4 6 K 384 3 4 4 5 K 384 2 4 4 5 K 384 2 3 4 4 K 384 4 4 T J Q 384 4 4 9 J Q 384 4 4 8 J Q 384 4 4 7 J Q 384 4 4 6 J Q 384 4 4 5 J Q 384 3 4 4 J Q 384 2 4 4 J Q 384 4 4 9 T Q 384 4 4 8 T Q 384 4 4 7 T Q 384 4 4 6 T Q 384 4 4 5 T Q 384 3 4 4 T Q 384 2 4 4 T Q 384 4 4 8 9 Q 384 4 4 7 9 Q 384 4 4 6 9 Q 384 4 4 5 9 Q 384 3 4 4 9 Q 384 2 4 4 9 Q 384 4 4 7 8 Q 384 4 4 6 8 Q 384 4 4 5 8 Q 384 3 4 4 8 Q 384 2 4 4 8 Q 384 4 4 6 7 Q 384 4 4 5 7 Q 384 3 4 4 7 Q 384 2 4 4 7 Q 384 4 4 5 6 Q 384 3 4 4 6 Q 384 2 4 4 6 Q 384 3 4 4 5 Q 384 2 4 4 5 Q 384 2 3 4 4 Q 384 4 4 9 T J 384 4 4 8 T J 384 4 4 7 T J 384 4 4 6 T J 384 4 4 5 T J 384 3 4 4 T J 384 2 4 4 T J 384 4 4 8 9 J 384 4 4 7 9 J 384 4 4 6 9 J 384 4 4 5 9 J 384 3 4 4 9 J 384 2 4 4 9 J 384 4 4 7 8 J 384 4 4 6 8 J 384 4 4 5 8 J 384 3 4 4 8 J 384 2 4 4 8 J 384 4 4 6 7 J 384 4 4 5 7 J 384 3 4 4 7 J 384 2 4 4 7 J 384 4 4 5 6 J 384 3 4 4 6 J 384 2 4 4 6 J 384 3 4 4 5 J 384 2 4 4 5 J 384 2 3 4 4 J 384 4 4 8 9 T 384 4 4 7 9 T 384 4 4 6 9 T 384 4 4 5 9 T 384 3 4 4 9 T 384 2 4 4 9 T 384 4 4 7 8 T 384 4 4 6 8 T 384 4 4 5 8 T 384 3 4 4 8 T 384 2 4 4 8 T 384 4 4 6 7 T 384 4 4 5 7 T 384 3 4 4 7 T 384 2 4 4 7 T 384 4 4 5 6 T 384 3 4 4 6 T 384 2 4 4 6 T 384 3 4 4 5 T 384 2 4 4 5 T 384 2 3 4 4 T 384 4 4 7 8 9 384 4 4 6 8 9 384 4 4 5 8 9 384 3 4 4 8 9 384 2 4 4 8 9 384 4 4 6 7 9 384 4 4 5 7 9 384 3 4 4 7 9 384 2 4 4 7 9 384 4 4 5 6 9 384 3 4 4 6 9 384 2 4 4 6 9 384 3 4 4 5 9 384 2 4 4 5 9 384 2 3 4 4 9 384 4 4 6 7 8 384 4 4 5 7 8 384 3 4 4 7 8 384 2 4 4 7 8 384 4 4 5 6 8 384 3 4 4 6 8 384 2 4 4 6 8 384 3 4 4 5 8 384 2 4 4 5 8 384 2 3 4 4 8 384 4 4 5 6 7 384 3 4 4 6 7 384 2 4 4 6 7 384 3 4 4 5 7 384 2 4 4 5 7 384 2 3 4 4 7 384 3 4 4 5 6 384 2 4 4 5 6 384 2 3 4 4 6 384 2 3 4 4 5 384 3 3 Q K A Pair of Treys 384 3 3 J K A 384 3 3 T K A 384 3 3 9 K A 384 3 3 8 K A 384 3 3 7 K A 384 3 3 6 K A 384 3 3 5 K A 384 3 3 4 K A 384 2 3 3 K A 384 3 3 J Q A 384 3 3 T Q A 384 3 3 9 Q A 384 3 3 8 Q A 384 3 3 7 Q A 384 3 3 6 Q A 384 3 3 5 Q A 384 3 3 4 Q A 384 2 3 3 Q A 384 3 3 T J A 384 3 3 9 J A 384 3 3 8 J A 384 3 3 7 J A 384 3 3 6 J A 384 3 3 5 J A 384 3 3 4 J A 384 2 3 3 J A 384 3 3 9 T A 384 3 3 8 T A 384 3 3 7 T A 384 3 3 6 T A 384 3 3 5 T A 384 3 3 4 T A 384 2 3 3 T A 384 3 3 8 9 A 384 3 3 7 9 A 384 3 3 6 9 A 384 3 3 5 9 A 384 3 3 4 9 A 384 2 3 3 9 A 384 3 3 7 8 A 384 3 3 6 8 A 384 3 3 5 8 A 384 3 3 4 8 A 384 2 3 3 8 A 384 3 3 6 7 A 384 3 3 5 7 A 384 3 3 4 7 A 384 2 3 3 7 A 384 3 3 5 6 A 384 3 3 4 6 A 384 2 3 3 6 A 384 3 3 4 5 A 384 2 3 3 5 A 384 2 3 3 4 A 384 3 3 J Q K 384 3 3 T Q K 384 3 3 9 Q K 384 3 3 8 Q K 384 3 3 7 Q K 384 3 3 6 Q K 384 3 3 5 Q K 384 3 3 4 Q K 384 2 3 3 Q K 384 3 3 T J K 384 3 3 9 J K 384 3 3 8 J K 384 3 3 7 J K 384 3 3 6 J K 384 3 3 5 J K 384 3 3 4 J K 384 2 3 3 J K 384 3 3 9 T K 384 3 3 8 T K 384 3 3 7 T K 384 3 3 6 T K 384 3 3 5 T K 384 3 3 4 T K 384 2 3 3 T K 384 3 3 8 9 K 384 3 3 7 9 K 384 3 3 6 9 K 384 3 3 5 9 K 384 3 3 4 9 K 384 2 3 3 9 K 384 3 3 7 8 K 384 3 3 6 8 K 384 3 3 5 8 K 384 3 3 4 8 K 384 2 3 3 8 K 384 3 3 6 7 K 384 3 3 5 7 K 384 3 3 4 7 K 384 2 3 3 7 K 384 3 3 5 6 K 384 3 3 4 6 K 384 2 3 3 6 K 384 3 3 4 5 K 384 2 3 3 5 K 384 2 3 3 4 K 384 3 3 T J Q 384 3 3 9 J Q 384 3 3 8 J Q 384 3 3 7 J Q 384 3 3 6 J Q 384 3 3 5 J Q 384 3 3 4 J Q 384 2 3 3 J Q 384 3 3 9 T Q 384 3 3 8 T Q 384 3 3 7 T Q 384 3 3 6 T Q 384 3 3 5 T Q 384 3 3 4 T Q 384 2 3 3 T Q 384 3 3 8 9 Q 384 3 3 7 9 Q 384 3 3 6 9 Q 384 3 3 5 9 Q 384 3 3 4 9 Q 384 2 3 3 9 Q 384 3 3 7 8 Q 384 3 3 6 8 Q 384 3 3 5 8 Q 384 3 3 4 8 Q 384 2 3 3 8 Q 384 3 3 6 7 Q 384 3 3 5 7 Q 384 3 3 4 7 Q 384 2 3 3 7 Q 384 3 3 5 6 Q 384 3 3 4 6 Q 384 2 3 3 6 Q 384 3 3 4 5 Q 384 2 3 3 5 Q 384 2 3 3 4 Q 384 3 3 9 T J 384 3 3 8 T J 384 3 3 7 T J 384 3 3 6 T J 384 3 3 5 T J 384 3 3 4 T J 384 2 3 3 T J 384 3 3 8 9 J 384 3 3 7 9 J 384 3 3 6 9 J 384 3 3 5 9 J 384 3 3 4 9 J 384 2 3 3 9 J 384 3 3 7 8 J 384 3 3 6 8 J 384 3 3 5 8 J 384 3 3 4 8 J 384 2 3 3 8 J 384 3 3 6 7 J 384 3 3 5 7 J 384 3 3 4 7 J 384 2 3 3 7 J 384 3 3 5 6 J 384 3 3 4 6 J 384 2 3 3 6 J 384 3 3 4 5 J 384 2 3 3 5 J 384 2 3 3 4 J 384 3 3 8 9 T 384 3 3 7 9 T 384 3 3 6 9 T 384 3 3 5 9 T 384 3 3 4 9 T 384 2 3 3 9 T 384 3 3 7 8 T 384 3 3 6 8 T 384 3 3 5 8 T 384 3 3 4 8 T 384 2 3 3 8 T 384 3 3 6 7 T 384 3 3 5 7 T 384 3 3 4 7 T 384 2 3 3 7 T 384 3 3 5 6 T 384 3 3 4 6 T 384 2 3 3 6 T 384 3 3 4 5 T 384 2 3 3 5 T 384 2 3 3 4 T 384 3 3 7 8 9 384 3 3 6 8 9 384 3 3 5 8 9 384 3 3 4 8 9 384 2 3 3 8 9 384 3 3 6 7 9 384 3 3 5 7 9 384 3 3 4 7 9 384 2 3 3 7 9 384 3 3 5 6 9 384 3 3 4 6 9 384 2 3 3 6 9 384 3 3 4 5 9 384 2 3 3 5 9 384 2 3 3 4 9 384 3 3 6 7 8 384 3 3 5 7 8 384 3 3 4 7 8 384 2 3 3 7 8 384 3 3 5 6 8 384 3 3 4 6 8 384 2 3 3 6 8 384 3 3 4 5 8 384 2 3 3 5 8 384 2 3 3 4 8 384 3 3 5 6 7 384 3 3 4 6 7 384 2 3 3 6 7 384 3 3 4 5 7 384 2 3 3 5 7 384 2 3 3 4 7 384 3 3 4 5 6 384 2 3 3 5 6 384 2 3 3 4 6 384 2 3 3 4 5 384 2 2 Q K A Pair of Deuces 384 2 2 J K A 384 2 2 T K A 384 2 2 9 K A 384 2 2 8 K A 384 2 2 7 K A 384 2 2 6 K A 384 2 2 5 K A 384 2 2 4 K A 384 2 2 3 K A 384 2 2 J Q A 384 2 2 T Q A 384 2 2 9 Q A 384 2 2 8 Q A 384 2 2 7 Q A 384 2 2 6 Q A 384 2 2 5 Q A 384 2 2 4 Q A 384 2 2 3 Q A 384 2 2 T J A 384 2 2 9 J A 384 2 2 8 J A 384 2 2 7 J A 384 2 2 6 J A 384 2 2 5 J A 384 2 2 4 J A 384 2 2 3 J A 384 2 2 9 T A 384 2 2 8 T A 384 2 2 7 T A 384 2 2 6 T A 384 2 2 5 T A 384 2 2 4 T A 384 2 2 3 T A 384 2 2 8 9 A 384 2 2 7 9 A 384 2 2 6 9 A 384 2 2 5 9 A 384 2 2 4 9 A 384 2 2 3 9 A 384 2 2 7 8 A 384 2 2 6 8 A 384 2 2 5 8 A 384 2 2 4 8 A 384 2 2 3 8 A 384 2 2 6 7 A 384 2 2 5 7 A 384 2 2 4 7 A 384 2 2 3 7 A 384 2 2 5 6 A 384 2 2 4 6 A 384 2 2 3 6 A 384 2 2 4 5 A 384 2 2 3 5 A 384 2 2 3 4 A 384 2 2 J Q K 384 2 2 T Q K 384 2 2 9 Q K 384 2 2 8 Q K 384 2 2 7 Q K 384 2 2 6 Q K 384 2 2 5 Q K 384 2 2 4 Q K 384 2 2 3 Q K 384 2 2 T J K 384 2 2 9 J K 384 2 2 8 J K 384 2 2 7 J K 384 2 2 6 J K 384 2 2 5 J K 384 2 2 4 J K 384 2 2 3 J K 384 2 2 9 T K 384 2 2 8 T K 384 2 2 7 T K 384 2 2 6 T K 384 2 2 5 T K 384 2 2 4 T K 384 2 2 3 T K 384 2 2 8 9 K 384 2 2 7 9 K 384 2 2 6 9 K 384 2 2 5 9 K 384 2 2 4 9 K 384 2 2 3 9 K 384 2 2 7 8 K 384 2 2 6 8 K 384 2 2 5 8 K 384 2 2 4 8 K 384 2 2 3 8 K 384 2 2 6 7 K 384 2 2 5 7 K 384 2 2 4 7 K 384 2 2 3 7 K 384 2 2 5 6 K 384 2 2 4 6 K 384 2 2 3 6 K 384 2 2 4 5 K 384 2 2 3 5 K 384 2 2 3 4 K 384 2 2 T J Q 384 2 2 9 J Q 384 2 2 8 J Q 384 2 2 7 J Q 384 2 2 6 J Q 384 2 2 5 J Q 384 2 2 4 J Q 384 2 2 3 J Q 384 2 2 9 T Q 384 2 2 8 T Q 384 2 2 7 T Q 384 2 2 6 T Q 384 2 2 5 T Q 384 2 2 4 T Q 384 2 2 3 T Q 384 2 2 8 9 Q 384 2 2 7 9 Q 384 2 2 6 9 Q 384 2 2 5 9 Q 384 2 2 4 9 Q 384 2 2 3 9 Q 384 2 2 7 8 Q 384 2 2 6 8 Q 384 2 2 5 8 Q 384 2 2 4 8 Q 384 2 2 3 8 Q 384 2 2 6 7 Q 384 2 2 5 7 Q 384 2 2 4 7 Q 384 2 2 3 7 Q 384 2 2 5 6 Q 384 2 2 4 6 Q 384 2 2 3 6 Q 384 2 2 4 5 Q 384 2 2 3 5 Q 384 2 2 3 4 Q 384 2 2 9 T J 384 2 2 8 T J 384 2 2 7 T J 384 2 2 6 T J 384 2 2 5 T J 384 2 2 4 T J 384 2 2 3 T J 384 2 2 8 9 J 384 2 2 7 9 J 384 2 2 6 9 J 384 2 2 5 9 J 384 2 2 4 9 J 384 2 2 3 9 J 384 2 2 7 8 J 384 2 2 6 8 J 384 2 2 5 8 J 384 2 2 4 8 J 384 2 2 3 8 J 384 2 2 6 7 J 384 2 2 5 7 J 384 2 2 4 7 J 384 2 2 3 7 J 384 2 2 5 6 J 384 2 2 4 6 J 384 2 2 3 6 J 384 2 2 4 5 J 384 2 2 3 5 J 384 2 2 3 4 J 384 2 2 8 9 T 384 2 2 7 9 T 384 2 2 6 9 T 384 2 2 5 9 T 384 2 2 4 9 T 384 2 2 3 9 T 384 2 2 7 8 T 384 2 2 6 8 T 384 2 2 5 8 T 384 2 2 4 8 T 384 2 2 3 8 T 384 2 2 6 7 T 384 2 2 5 7 T 384 2 2 4 7 T 384 2 2 3 7 T 384 2 2 5 6 T 384 2 2 4 6 T 384 2 2 3 6 T 384 2 2 4 5 T 384 2 2 3 5 T 384 2 2 3 4 T 384 2 2 7 8 9 384 2 2 6 8 9 384 2 2 5 8 9 384 2 2 4 8 9 384 2 2 3 8 9 384 2 2 6 7 9 384 2 2 5 7 9 384 2 2 4 7 9 384 2 2 3 7 9 384 2 2 5 6 9 384 2 2 4 6 9 384 2 2 3 6 9 384 2 2 4 5 9 384 2 2 3 5 9 384 2 2 3 4 9 384 2 2 6 7 8 384 2 2 5 7 8 384 2 2 4 7 8 384 2 2 3 7 8 384 2 2 5 6 8 384 2 2 4 6 8 384 2 2 3 6 8 384 2 2 4 5 8 384 2 2 3 5 8 384 2 2 3 4 8 384 2 2 5 6 7 384 2 2 4 6 7 384 2 2 3 6 7 384 2 2 4 5 7 384 2 2 3 5 7 384 2 2 3 4 7 384 2 2 4 5 6 384 2 2 3 5 6 384 2 2 3 4 6 384 2 2 3 4 5 1024 9 J Q K A Ace High HIGH CARD 1024 8 J Q K A 1024 7 J Q K A 1024 6 J Q K A 1024 5 J Q K A 1024 4 J Q K A 1024 3 J Q K A 1024 2 J Q K A 1024 9 T Q K A 1024 8 T Q K A 1024 7 T Q K A 1024 6 T Q K A 1024 5 T Q K A 1024 4 T Q K A 1024 3 T Q K A 1024 2 T Q K A 1024 8 9 Q K A 1024 7 9 Q K A 1024 6 9 Q K A 1024 5 9 Q K A 1024 4 9 Q K A 1024 3 9 Q K A 1024 2 9 Q K A 1024 7 8 Q K A 1024 6 8 Q K A 1024 5 8 Q K A 1024 4 8 Q K A 1024 3 8 Q K A 1024 2 8 Q K A 1024 6 7 Q K A 1024 5 7 Q K A 1024 4 7 Q K A 1024 3 7 Q K A 1024 2 7 Q K A 1024 5 6 Q K A 1024 4 6 Q K A 1024 3 6 Q K A 1024 2 6 Q K A 1024 4 5 Q K A 1024 3 5 Q K A 1024 2 5 Q K A 1024 3 4 Q K A 1024 2 4 Q K A 1024 2 3 Q K A 1024 9 T J K A 1024 8 T J K A 1024 7 T J K A 1024 6 T J K A 1024 5 T J K A 1024 4 T J K A 1024 3 T J K A 1024 2 T J K A 1024 8 9 J K A 1024 7 9 J K A 1024 6 9 J K A 1024 5 9 J K A 1024 4 9 J K A 1024 3 9 J K A 1024 2 9 J K A 1024 7 8 J K A 1024 6 8 J K A 1024 5 8 J K A 1024 4 8 J K A 1024 3 8 J K A 1024 2 8 J K A 1024 6 7 J K A 1024 5 7 J K A 1024 4 7 J K A 1024 3 7 J K A 1024 2 7 J K A 1024 5 6 J K A 1024 4 6 J K A 1024 3 6 J K A 1024 2 6 J K A 1024 4 5 J K A 1024 3 5 J K A 1024 2 5 J K A 1024 3 4 J K A 1024 2 4 J K A 1024 2 3 J K A 1024 8 9 T K A 1024 7 9 T K A 1024 6 9 T K A 1024 5 9 T K A 1024 4 9 T K A 1024 3 9 T K A 1024 2 9 T K A 1024 7 8 T K A 1024 6 8 T K A 1024 5 8 T K A 1024 4 8 T K A 1024 3 8 T K A 1024 2 8 T K A 1024 6 7 T K A 1024 5 7 T K A 1024 4 7 T K A 1024 3 7 T K A 1024 2 7 T K A 1024 5 6 T K A 1024 4 6 T K A 1024 3 6 T K A 1024 2 6 T K A 1024 4 5 T K A 1024 3 5 T K A 1024 2 5 T K A 1024 3 4 T K A 1024 2 4 T K A 1024 2 3 T K A 1024 7 8 9 K A 1024 6 8 9 K A 1024 5 8 9 K A 1024 4 8 9 K A 1024 3 8 9 K A 1024 2 8 9 K A 1024 6 7 9 K A 1024 5 7 9 K A 1024 4 7 9 K A 1024 3 7 9 K A 1024 2 7 9 K A 1024 5 6 9 K A 1024 4 6 9 K A 1024 3 6 9 K A 1024 2 6 9 K A 1024 4 5 9 K A 1024 3 5 9 K A 1024 2 5 9 K A 1024 3 4 9 K A 1024 2 4 9 K A 1024 2 3 9 K A 1024 6 7 8 K A 1024 5 7 8 K A 1024 4 7 8 K A 1024 3 7 8 K A 1024 2 7 8 K A 1024 5 6 8 K A 1024 4 6 8 K A 1024 3 6 8 K A 1024 2 6 8 K A 1024 4 5 8 K A 1024 3 5 8 K A 1024 2 5 8 K A 1024 3 4 8 K A 1024 2 4 8 K A 1024 2 3 8 K A 1024 5 6 7 K A 1024 4 6 7 K A 1024 3 6 7 K A 1024 2 6 7 K A 1024 4 5 7 K A 1024 3 5 7 K A 1024 2 5 7 K A 1024 3 4 7 K A 1024 2 4 7 K A 1024 2 3 7 K A 1024 4 5 6 K A 1024 3 5 6 K A 1024 2 5 6 K A 1024 3 4 6 K A 1024 2 4 6 K A 1024 2 3 6 K A 1024 3 4 5 K A 1024 2 4 5 K A 1024 2 3 5 K A 1024 2 3 4 K A 1024 9 T J Q A 1024 8 T J Q A 1024 7 T J Q A 1024 6 T J Q A 1024 5 T J Q A 1024 4 T J Q A 1024 3 T J Q A 1024 2 T J Q A 1024 8 9 J Q A 1024 7 9 J Q A 1024 6 9 J Q A 1024 5 9 J Q A 1024 4 9 J Q A 1024 3 9 J Q A 1024 2 9 J Q A 1024 7 8 J Q A 1024 6 8 J Q A 1024 5 8 J Q A 1024 4 8 J Q A 1024 3 8 J Q A 1024 2 8 J Q A 1024 6 7 J Q A 1024 5 7 J Q A 1024 4 7 J Q A 1024 3 7 J Q A 1024 2 7 J Q A 1024 5 6 J Q A 1024 4 6 J Q A 1024 3 6 J Q A 1024 2 6 J Q A 1024 4 5 J Q A 1024 3 5 J Q A 1024 2 5 J Q A 1024 3 4 J Q A 1024 2 4 J Q A 1024 2 3 J Q A 1024 8 9 T Q A 1024 7 9 T Q A 1024 6 9 T Q A 1024 5 9 T Q A 1024 4 9 T Q A 1024 3 9 T Q A 1024 2 9 T Q A 1024 7 8 T Q A 1024 6 8 T Q A 1024 5 8 T Q A 1024 4 8 T Q A 1024 3 8 T Q A 1024 2 8 T Q A 1024 6 7 T Q A 1024 5 7 T Q A 1024 4 7 T Q A 1024 3 7 T Q A 1024 2 7 T Q A 1024 5 6 T Q A 1024 4 6 T Q A 1024 3 6 T Q A 1024 2 6 T Q A 1024 4 5 T Q A 1024 3 5 T Q A 1024 2 5 T Q A 1024 3 4 T Q A 1024 2 4 T Q A 1024 2 3 T Q A 1024 7 8 9 Q A 1024 6 8 9 Q A 1024 5 8 9 Q A 1024 4 8 9 Q A 1024 3 8 9 Q A 1024 2 8 9 Q A 1024 6 7 9 Q A 1024 5 7 9 Q A 1024 4 7 9 Q A 1024 3 7 9 Q A 1024 2 7 9 Q A 1024 5 6 9 Q A 1024 4 6 9 Q A 1024 3 6 9 Q A 1024 2 6 9 Q A 1024 4 5 9 Q A 1024 3 5 9 Q A 1024 2 5 9 Q A 1024 3 4 9 Q A 1024 2 4 9 Q A 1024 2 3 9 Q A 1024 6 7 8 Q A 1024 5 7 8 Q A 1024 4 7 8 Q A 1024 3 7 8 Q A 1024 2 7 8 Q A 1024 5 6 8 Q A 1024 4 6 8 Q A 1024 3 6 8 Q A 1024 2 6 8 Q A 1024 4 5 8 Q A 1024 3 5 8 Q A 1024 2 5 8 Q A 1024 3 4 8 Q A 1024 2 4 8 Q A 1024 2 3 8 Q A 1024 5 6 7 Q A 1024 4 6 7 Q A 1024 3 6 7 Q A 1024 2 6 7 Q A 1024 4 5 7 Q A 1024 3 5 7 Q A 1024 2 5 7 Q A 1024 3 4 7 Q A 1024 2 4 7 Q A 1024 2 3 7 Q A 1024 4 5 6 Q A 1024 3 5 6 Q A 1024 2 5 6 Q A 1024 3 4 6 Q A 1024 2 4 6 Q A 1024 2 3 6 Q A 1024 3 4 5 Q A 1024 2 4 5 Q A 1024 2 3 5 Q A 1024 2 3 4 Q A 1024 8 9 T J A 1024 7 9 T J A 1024 6 9 T J A 1024 5 9 T J A 1024 4 9 T J A 1024 3 9 T J A 1024 2 9 T J A 1024 7 8 T J A 1024 6 8 T J A 1024 5 8 T J A 1024 4 8 T J A 1024 3 8 T J A 1024 2 8 T J A 1024 6 7 T J A 1024 5 7 T J A 1024 4 7 T J A 1024 3 7 T J A 1024 2 7 T J A 1024 5 6 T J A 1024 4 6 T J A 1024 3 6 T J A 1024 2 6 T J A 1024 4 5 T J A 1024 3 5 T J A 1024 2 5 T J A 1024 3 4 T J A 1024 2 4 T J A 1024 2 3 T J A 1024 7 8 9 J A 1024 6 8 9 J A 1024 5 8 9 J A 1024 4 8 9 J A 1024 3 8 9 J A 1024 2 8 9 J A 1024 6 7 9 J A 1024 5 7 9 J A 1024 4 7 9 J A 1024 3 7 9 J A 1024 2 7 9 J A 1024 5 6 9 J A 1024 4 6 9 J A 1024 3 6 9 J A 1024 2 6 9 J A 1024 4 5 9 J A 1024 3 5 9 J A 1024 2 5 9 J A 1024 3 4 9 J A 1024 2 4 9 J A 1024 2 3 9 J A 1024 6 7 8 J A 1024 5 7 8 J A 1024 4 7 8 J A 1024 3 7 8 J A 1024 2 7 8 J A 1024 5 6 8 J A 1024 4 6 8 J A 1024 3 6 8 J A 1024 2 6 8 J A 1024 4 5 8 J A 1024 3 5 8 J A 1024 2 5 8 J A 1024 3 4 8 J A 1024 2 4 8 J A 1024 2 3 8 J A 1024 5 6 7 J A 1024 4 6 7 J A 1024 3 6 7 J A 1024 2 6 7 J A 1024 4 5 7 J A 1024 3 5 7 J A 1024 2 5 7 J A 1024 3 4 7 J A 1024 2 4 7 J A 1024 2 3 7 J A 1024 4 5 6 J A 1024 3 5 6 J A 1024 2 5 6 J A 1024 3 4 6 J A 1024 2 4 6 J A 1024 2 3 6 J A 1024 3 4 5 J A 1024 2 4 5 J A 1024 2 3 5 J A 1024 2 3 4 J A 1024 7 8 9 T A 1024 6 8 9 T A 1024 5 8 9 T A 1024 4 8 9 T A 1024 3 8 9 T A 1024 2 8 9 T A 1024 6 7 9 T A 1024 5 7 9 T A 1024 4 7 9 T A 1024 3 7 9 T A 1024 2 7 9 T A 1024 5 6 9 T A 1024 4 6 9 T A 1024 3 6 9 T A 1024 2 6 9 T A 1024 4 5 9 T A 1024 3 5 9 T A 1024 2 5 9 T A 1024 3 4 9 T A 1024 2 4 9 T A 1024 2 3 9 T A 1024 6 7 8 T A 1024 5 7 8 T A 1024 4 7 8 T A 1024 3 7 8 T A 1024 2 7 8 T A 1024 5 6 8 T A 1024 4 6 8 T A 1024 3 6 8 T A 1024 2 6 8 T A 1024 4 5 8 T A 1024 3 5 8 T A 1024 2 5 8 T A 1024 3 4 8 T A 1024 2 4 8 T A 1024 2 3 8 T A 1024 5 6 7 T A 1024 4 6 7 T A 1024 3 6 7 T A 1024 2 6 7 T A 1024 4 5 7 T A 1024 3 5 7 T A 1024 2 5 7 T A 1024 3 4 7 T A 1024 2 4 7 T A 1024 2 3 7 T A 1024 4 5 6 T A 1024 3 5 6 T A 1024 2 5 6 T A 1024 3 4 6 T A 1024 2 4 6 T A 1024 2 3 6 T A 1024 3 4 5 T A 1024 2 4 5 T A 1024 2 3 5 T A 1024 2 3 4 T A 1024 6 7 8 9 A 1024 5 7 8 9 A 1024 4 7 8 9 A 1024 3 7 8 9 A 1024 2 7 8 9 A 1024 5 6 8 9 A 1024 4 6 8 9 A 1024 3 6 8 9 A 1024 2 6 8 9 A 1024 4 5 8 9 A 1024 3 5 8 9 A 1024 2 5 8 9 A 1024 3 4 8 9 A 1024 2 4 8 9 A 1024 2 3 8 9 A 1024 5 6 7 9 A 1024 4 6 7 9 A 1024 3 6 7 9 A 1024 2 6 7 9 A 1024 4 5 7 9 A 1024 3 5 7 9 A 1024 2 5 7 9 A 1024 3 4 7 9 A 1024 2 4 7 9 A 1024 2 3 7 9 A 1024 4 5 6 9 A 1024 3 5 6 9 A 1024 2 5 6 9 A 1024 3 4 6 9 A 1024 2 4 6 9 A 1024 2 3 6 9 A 1024 3 4 5 9 A 1024 2 4 5 9 A 1024 2 3 5 9 A 1024 2 3 4 9 A 1024 5 6 7 8 A 1024 4 6 7 8 A 1024 3 6 7 8 A 1024 2 6 7 8 A 1024 4 5 7 8 A 1024 3 5 7 8 A 1024 2 5 7 8 A 1024 3 4 7 8 A 1024 2 4 7 8 A 1024 2 3 7 8 A 1024 4 5 6 8 A 1024 3 5 6 8 A 1024 2 5 6 8 A 1024 3 4 6 8 A 1024 2 4 6 8 A 1024 2 3 6 8 A 1024 3 4 5 8 A 1024 2 4 5 8 A 1024 2 3 5 8 A 1024 2 3 4 8 A 1024 4 5 6 7 A 1024 3 5 6 7 A 1024 2 5 6 7 A 1024 3 4 6 7 A 1024 2 4 6 7 A 1024 2 3 6 7 A 1024 3 4 5 7 A 1024 2 4 5 7 A 1024 2 3 5 7 A 1024 2 3 4 7 A 1024 3 4 5 6 A 1024 2 4 5 6 A 1024 2 3 5 6 A 1024 2 3 4 6 A 1024 8 T J Q K King High 1024 7 T J Q K 1024 6 T J Q K 1024 5 T J Q K 1024 4 T J Q K 1024 3 T J Q K 1024 2 T J Q K 1024 8 9 J Q K 1024 7 9 J Q K 1024 6 9 J Q K 1024 5 9 J Q K 1024 4 9 J Q K 1024 3 9 J Q K 1024 2 9 J Q K 1024 7 8 J Q K 1024 6 8 J Q K 1024 5 8 J Q K 1024 4 8 J Q K 1024 3 8 J Q K 1024 2 8 J Q K 1024 6 7 J Q K 1024 5 7 J Q K 1024 4 7 J Q K 1024 3 7 J Q K 1024 2 7 J Q K 1024 5 6 J Q K 1024 4 6 J Q K 1024 3 6 J Q K 1024 2 6 J Q K 1024 4 5 J Q K 1024 3 5 J Q K 1024 2 5 J Q K 1024 3 4 J Q K 1024 2 4 J Q K 1024 2 3 J Q K 1024 8 9 T Q K 1024 7 9 T Q K 1024 6 9 T Q K 1024 5 9 T Q K 1024 4 9 T Q K 1024 3 9 T Q K 1024 2 9 T Q K 1024 7 8 T Q K 1024 6 8 T Q K 1024 5 8 T Q K 1024 4 8 T Q K 1024 3 8 T Q K 1024 2 8 T Q K 1024 6 7 T Q K 1024 5 7 T Q K 1024 4 7 T Q K 1024 3 7 T Q K 1024 2 7 T Q K 1024 5 6 T Q K 1024 4 6 T Q K 1024 3 6 T Q K 1024 2 6 T Q K 1024 4 5 T Q K 1024 3 5 T Q K 1024 2 5 T Q K 1024 3 4 T Q K 1024 2 4 T Q K 1024 2 3 T Q K 1024 7 8 9 Q K 1024 6 8 9 Q K 1024 5 8 9 Q K 1024 4 8 9 Q K 1024 3 8 9 Q K 1024 2 8 9 Q K 1024 6 7 9 Q K 1024 5 7 9 Q K 1024 4 7 9 Q K 1024 3 7 9 Q K 1024 2 7 9 Q K 1024 5 6 9 Q K 1024 4 6 9 Q K 1024 3 6 9 Q K 1024 2 6 9 Q K 1024 4 5 9 Q K 1024 3 5 9 Q K 1024 2 5 9 Q K 1024 3 4 9 Q K 1024 2 4 9 Q K 1024 2 3 9 Q K 1024 6 7 8 Q K 1024 5 7 8 Q K 1024 4 7 8 Q K 1024 3 7 8 Q K 1024 2 7 8 Q K 1024 5 6 8 Q K 1024 4 6 8 Q K 1024 3 6 8 Q K 1024 2 6 8 Q K 1024 4 5 8 Q K 1024 3 5 8 Q K 1024 2 5 8 Q K 1024 3 4 8 Q K 1024 2 4 8 Q K 1024 2 3 8 Q K 1024 5 6 7 Q K 1024 4 6 7 Q K 1024 3 6 7 Q K 1024 2 6 7 Q K 1024 4 5 7 Q K 1024 3 5 7 Q K 1024 2 5 7 Q K 1024 3 4 7 Q K 1024 2 4 7 Q K 1024 2 3 7 Q K 1024 4 5 6 Q K 1024 3 5 6 Q K 1024 2 5 6 Q K 1024 3 4 6 Q K 1024 2 4 6 Q K 1024 2 3 6 Q K 1024 3 4 5 Q K 1024 2 4 5 Q K 1024 2 3 5 Q K 1024 2 3 4 Q K 1024 8 9 T J K 1024 7 9 T J K 1024 6 9 T J K 1024 5 9 T J K 1024 4 9 T J K 1024 3 9 T J K 1024 2 9 T J K 1024 7 8 T J K 1024 6 8 T J K 1024 5 8 T J K 1024 4 8 T J K 1024 3 8 T J K 1024 2 8 T J K 1024 6 7 T J K 1024 5 7 T J K 1024 4 7 T J K 1024 3 7 T J K 1024 2 7 T J K 1024 5 6 T J K 1024 4 6 T J K 1024 3 6 T J K 1024 2 6 T J K 1024 4 5 T J K 1024 3 5 T J K 1024 2 5 T J K 1024 3 4 T J K 1024 2 4 T J K 1024 2 3 T J K 1024 7 8 9 J K 1024 6 8 9 J K 1024 5 8 9 J K 1024 4 8 9 J K 1024 3 8 9 J K 1024 2 8 9 J K 1024 6 7 9 J K 1024 5 7 9 J K 1024 4 7 9 J K 1024 3 7 9 J K 1024 2 7 9 J K 1024 5 6 9 J K 1024 4 6 9 J K 1024 3 6 9 J K 1024 2 6 9 J K 1024 4 5 9 J K 1024 3 5 9 J K 1024 2 5 9 J K 1024 3 4 9 J K 1024 2 4 9 J K 1024 2 3 9 J K 1024 6 7 8 J K 1024 5 7 8 J K 1024 4 7 8 J K 1024 3 7 8 J K 1024 2 7 8 J K 1024 5 6 8 J K 1024 4 6 8 J K 1024 3 6 8 J K 1024 2 6 8 J K 1024 4 5 8 J K 1024 3 5 8 J K 1024 2 5 8 J K 1024 3 4 8 J K 1024 2 4 8 J K 1024 2 3 8 J K 1024 5 6 7 J K 1024 4 6 7 J K 1024 3 6 7 J K 1024 2 6 7 J K 1024 4 5 7 J K 1024 3 5 7 J K 1024 2 5 7 J K 1024 3 4 7 J K 1024 2 4 7 J K 1024 2 3 7 J K 1024 4 5 6 J K 1024 3 5 6 J K 1024 2 5 6 J K 1024 3 4 6 J K 1024 2 4 6 J K 1024 2 3 6 J K 1024 3 4 5 J K 1024 2 4 5 J K 1024 2 3 5 J K 1024 2 3 4 J K 1024 7 8 9 T K 1024 6 8 9 T K 1024 5 8 9 T K 1024 4 8 9 T K 1024 3 8 9 T K 1024 2 8 9 T K 1024 6 7 9 T K 1024 5 7 9 T K 1024 4 7 9 T K 1024 3 7 9 T K 1024 2 7 9 T K 1024 5 6 9 T K 1024 4 6 9 T K 1024 3 6 9 T K 1024 2 6 9 T K 1024 4 5 9 T K 1024 3 5 9 T K 1024 2 5 9 T K 1024 3 4 9 T K 1024 2 4 9 T K 1024 2 3 9 T K 1024 6 7 8 T K 1024 5 7 8 T K 1024 4 7 8 T K 1024 3 7 8 T K 1024 2 7 8 T K 1024 5 6 8 T K 1024 4 6 8 T K 1024 3 6 8 T K 1024 2 6 8 T K 1024 4 5 8 T K 1024 3 5 8 T K 1024 2 5 8 T K 1024 3 4 8 T K 1024 2 4 8 T K 1024 2 3 8 T K 1024 5 6 7 T K 1024 4 6 7 T K 1024 3 6 7 T K 1024 2 6 7 T K 1024 4 5 7 T K 1024 3 5 7 T K 1024 2 5 7 T K 1024 3 4 7 T K 1024 2 4 7 T K 1024 2 3 7 T K 1024 4 5 6 T K 1024 3 5 6 T K 1024 2 5 6 T K 1024 3 4 6 T K 1024 2 4 6 T K 1024 2 3 6 T K 1024 3 4 5 T K 1024 2 4 5 T K 1024 2 3 5 T K 1024 2 3 4 T K 1024 6 7 8 9 K 1024 5 7 8 9 K 1024 4 7 8 9 K 1024 3 7 8 9 K 1024 2 7 8 9 K 1024 5 6 8 9 K 1024 4 6 8 9 K 1024 3 6 8 9 K 1024 2 6 8 9 K 1024 4 5 8 9 K 1024 3 5 8 9 K 1024 2 5 8 9 K 1024 3 4 8 9 K 1024 2 4 8 9 K 1024 2 3 8 9 K 1024 5 6 7 9 K 1024 4 6 7 9 K 1024 3 6 7 9 K 1024 2 6 7 9 K 1024 4 5 7 9 K 1024 3 5 7 9 K 1024 2 5 7 9 K 1024 3 4 7 9 K 1024 2 4 7 9 K 1024 2 3 7 9 K 1024 4 5 6 9 K 1024 3 5 6 9 K 1024 2 5 6 9 K 1024 3 4 6 9 K 1024 2 4 6 9 K 1024 2 3 6 9 K 1024 3 4 5 9 K 1024 2 4 5 9 K 1024 2 3 5 9 K 1024 2 3 4 9 K 1024 5 6 7 8 K 1024 4 6 7 8 K 1024 3 6 7 8 K 1024 2 6 7 8 K 1024 4 5 7 8 K 1024 3 5 7 8 K 1024 2 5 7 8 K 1024 3 4 7 8 K 1024 2 4 7 8 K 1024 2 3 7 8 K 1024 4 5 6 8 K 1024 3 5 6 8 K 1024 2 5 6 8 K 1024 3 4 6 8 K 1024 2 4 6 8 K 1024 2 3 6 8 K 1024 3 4 5 8 K 1024 2 4 5 8 K 1024 2 3 5 8 K 1024 2 3 4 8 K 1024 4 5 6 7 K 1024 3 5 6 7 K 1024 2 5 6 7 K 1024 3 4 6 7 K 1024 2 4 6 7 K 1024 2 3 6 7 K 1024 3 4 5 7 K 1024 2 4 5 7 K 1024 2 3 5 7 K 1024 2 3 4 7 K 1024 3 4 5 6 K 1024 2 4 5 6 K 1024 2 3 5 6 K 1024 2 3 4 6 K 1024 2 3 4 5 K 1024 7 9 T J Q Queen High 1024 6 9 T J Q 1024 5 9 T J Q 1024 4 9 T J Q 1024 3 9 T J Q 1024 2 9 T J Q 1024 7 8 T J Q 1024 6 8 T J Q 1024 5 8 T J Q 1024 4 8 T J Q 1024 3 8 T J Q 1024 2 8 T J Q 1024 6 7 T J Q 1024 5 7 T J Q 1024 4 7 T J Q 1024 3 7 T J Q 1024 2 7 T J Q 1024 5 6 T J Q 1024 4 6 T J Q 1024 3 6 T J Q 1024 2 6 T J Q 1024 4 5 T J Q 1024 3 5 T J Q 1024 2 5 T J Q 1024 3 4 T J Q 1024 2 4 T J Q 1024 2 3 T J Q 1024 7 8 9 J Q 1024 6 8 9 J Q 1024 5 8 9 J Q 1024 4 8 9 J Q 1024 3 8 9 J Q 1024 2 8 9 J Q 1024 6 7 9 J Q 1024 5 7 9 J Q 1024 4 7 9 J Q 1024 3 7 9 J Q 1024 2 7 9 J Q 1024 5 6 9 J Q 1024 4 6 9 J Q 1024 3 6 9 J Q 1024 2 6 9 J Q 1024 4 5 9 J Q 1024 3 5 9 J Q 1024 2 5 9 J Q 1024 3 4 9 J Q 1024 2 4 9 J Q 1024 2 3 9 J Q 1024 6 7 8 J Q 1024 5 7 8 J Q 1024 4 7 8 J Q 1024 3 7 8 J Q 1024 2 7 8 J Q 1024 5 6 8 J Q 1024 4 6 8 J Q 1024 3 6 8 J Q 1024 2 6 8 J Q 1024 4 5 8 J Q 1024 3 5 8 J Q 1024 2 5 8 J Q 1024 3 4 8 J Q 1024 2 4 8 J Q 1024 2 3 8 J Q 1024 5 6 7 J Q 1024 4 6 7 J Q 1024 3 6 7 J Q 1024 2 6 7 J Q 1024 4 5 7 J Q 1024 3 5 7 J Q 1024 2 5 7 J Q 1024 3 4 7 J Q 1024 2 4 7 J Q 1024 2 3 7 J Q 1024 4 5 6 J Q 1024 3 5 6 J Q 1024 2 5 6 J Q 1024 3 4 6 J Q 1024 2 4 6 J Q 1024 2 3 6 J Q 1024 3 4 5 J Q 1024 2 4 5 J Q 1024 2 3 5 J Q 1024 2 3 4 J Q 1024 7 8 9 T Q 1024 6 8 9 T Q 1024 5 8 9 T Q 1024 4 8 9 T Q 1024 3 8 9 T Q 1024 2 8 9 T Q 1024 6 7 9 T Q 1024 5 7 9 T Q 1024 4 7 9 T Q 1024 3 7 9 T Q 1024 2 7 9 T Q 1024 5 6 9 T Q 1024 4 6 9 T Q 1024 3 6 9 T Q 1024 2 6 9 T Q 1024 4 5 9 T Q 1024 3 5 9 T Q 1024 2 5 9 T Q 1024 3 4 9 T Q 1024 2 4 9 T Q 1024 2 3 9 T Q 1024 6 7 8 T Q 1024 5 7 8 T Q 1024 4 7 8 T Q 1024 3 7 8 T Q 1024 2 7 8 T Q 1024 5 6 8 T Q 1024 4 6 8 T Q 1024 3 6 8 T Q 1024 2 6 8 T Q 1024 4 5 8 T Q 1024 3 5 8 T Q 1024 2 5 8 T Q 1024 3 4 8 T Q 1024 2 4 8 T Q 1024 2 3 8 T Q 1024 5 6 7 T Q 1024 4 6 7 T Q 1024 3 6 7 T Q 1024 2 6 7 T Q 1024 4 5 7 T Q 1024 3 5 7 T Q 1024 2 5 7 T Q 1024 3 4 7 T Q 1024 2 4 7 T Q 1024 2 3 7 T Q 1024 4 5 6 T Q 1024 3 5 6 T Q 1024 2 5 6 T Q 1024 3 4 6 T Q 1024 2 4 6 T Q 1024 2 3 6 T Q 1024 3 4 5 T Q 1024 2 4 5 T Q 1024 2 3 5 T Q 1024 2 3 4 T Q 1024 6 7 8 9 Q 1024 5 7 8 9 Q 1024 4 7 8 9 Q 1024 3 7 8 9 Q 1024 2 7 8 9 Q 1024 5 6 8 9 Q 1024 4 6 8 9 Q 1024 3 6 8 9 Q 1024 2 6 8 9 Q 1024 4 5 8 9 Q 1024 3 5 8 9 Q 1024 2 5 8 9 Q 1024 3 4 8 9 Q 1024 2 4 8 9 Q 1024 2 3 8 9 Q 1024 5 6 7 9 Q 1024 4 6 7 9 Q 1024 3 6 7 9 Q 1024 2 6 7 9 Q 1024 4 5 7 9 Q 1024 3 5 7 9 Q 1024 2 5 7 9 Q 1024 3 4 7 9 Q 1024 2 4 7 9 Q 1024 2 3 7 9 Q 1024 4 5 6 9 Q 1024 3 5 6 9 Q 1024 2 5 6 9 Q 1024 3 4 6 9 Q 1024 2 4 6 9 Q 1024 2 3 6 9 Q 1024 3 4 5 9 Q 1024 2 4 5 9 Q 1024 2 3 5 9 Q 1024 2 3 4 9 Q 1024 5 6 7 8 Q 1024 4 6 7 8 Q 1024 3 6 7 8 Q 1024 2 6 7 8 Q 1024 4 5 7 8 Q 1024 3 5 7 8 Q 1024 2 5 7 8 Q 1024 3 4 7 8 Q 1024 2 4 7 8 Q 1024 2 3 7 8 Q 1024 4 5 6 8 Q 1024 3 5 6 8 Q 1024 2 5 6 8 Q 1024 3 4 6 8 Q 1024 2 4 6 8 Q 1024 2 3 6 8 Q 1024 3 4 5 8 Q 1024 2 4 5 8 Q 1024 2 3 5 8 Q 1024 2 3 4 8 Q 1024 4 5 6 7 Q 1024 3 5 6 7 Q 1024 2 5 6 7 Q 1024 3 4 6 7 Q 1024 2 4 6 7 Q 1024 2 3 6 7 Q 1024 3 4 5 7 Q 1024 2 4 5 7 Q 1024 2 3 5 7 Q 1024 2 3 4 7 Q 1024 3 4 5 6 Q 1024 2 4 5 6 Q 1024 2 3 5 6 Q 1024 2 3 4 6 Q 1024 2 3 4 5 Q 1024 6 8 9 T J Jack High 1024 5 8 9 T J 1024 4 8 9 T J 1024 3 8 9 T J 1024 2 8 9 T J 1024 6 7 9 T J 1024 5 7 9 T J 1024 4 7 9 T J 1024 3 7 9 T J 1024 2 7 9 T J 1024 5 6 9 T J 1024 4 6 9 T J 1024 3 6 9 T J 1024 2 6 9 T J 1024 4 5 9 T J 1024 3 5 9 T J 1024 2 5 9 T J 1024 3 4 9 T J 1024 2 4 9 T J 1024 2 3 9 T J 1024 6 7 8 T J 1024 5 7 8 T J 1024 4 7 8 T J 1024 3 7 8 T J 1024 2 7 8 T J 1024 5 6 8 T J 1024 4 6 8 T J 1024 3 6 8 T J 1024 2 6 8 T J 1024 4 5 8 T J 1024 3 5 8 T J 1024 2 5 8 T J 1024 3 4 8 T J 1024 2 4 8 T J 1024 2 3 8 T J 1024 5 6 7 T J 1024 4 6 7 T J 1024 3 6 7 T J 1024 2 6 7 T J 1024 4 5 7 T J 1024 3 5 7 T J 1024 2 5 7 T J 1024 3 4 7 T J 1024 2 4 7 T J 1024 2 3 7 T J 1024 4 5 6 T J 1024 3 5 6 T J 1024 2 5 6 T J 1024 3 4 6 T J 1024 2 4 6 T J 1024 2 3 6 T J 1024 3 4 5 T J 1024 2 4 5 T J 1024 2 3 5 T J 1024 2 3 4 T J 1024 6 7 8 9 J 1024 5 7 8 9 J 1024 4 7 8 9 J 1024 3 7 8 9 J 1024 2 7 8 9 J 1024 5 6 8 9 J 1024 4 6 8 9 J 1024 3 6 8 9 J 1024 2 6 8 9 J 1024 4 5 8 9 J 1024 3 5 8 9 J 1024 2 5 8 9 J 1024 3 4 8 9 J 1024 2 4 8 9 J 1024 2 3 8 9 J 1024 5 6 7 9 J 1024 4 6 7 9 J 1024 3 6 7 9 J 1024 2 6 7 9 J 1024 4 5 7 9 J 1024 3 5 7 9 J 1024 2 5 7 9 J 1024 3 4 7 9 J 1024 2 4 7 9 J 1024 2 3 7 9 J 1024 4 5 6 9 J 1024 3 5 6 9 J 1024 2 5 6 9 J 1024 3 4 6 9 J 1024 2 4 6 9 J 1024 2 3 6 9 J 1024 3 4 5 9 J 1024 2 4 5 9 J 1024 2 3 5 9 J 1024 2 3 4 9 J 1024 5 6 7 8 J 1024 4 6 7 8 J 1024 3 6 7 8 J 1024 2 6 7 8 J 1024 4 5 7 8 J 1024 3 5 7 8 J 1024 2 5 7 8 J 1024 3 4 7 8 J 1024 2 4 7 8 J 1024 2 3 7 8 J 1024 4 5 6 8 J 1024 3 5 6 8 J 1024 2 5 6 8 J 1024 3 4 6 8 J 1024 2 4 6 8 J 1024 2 3 6 8 J 1024 3 4 5 8 J 1024 2 4 5 8 J 1024 2 3 5 8 J 1024 2 3 4 8 J 1024 4 5 6 7 J 1024 3 5 6 7 J 1024 2 5 6 7 J 1024 3 4 6 7 J 1024 2 4 6 7 J 1024 2 3 6 7 J 1024 3 4 5 7 J 1024 2 4 5 7 J 1024 2 3 5 7 J 1024 2 3 4 7 J 1024 3 4 5 6 J 1024 2 4 5 6 J 1024 2 3 5 6 J 1024 2 3 4 6 J 1024 2 3 4 5 J 1024 5 7 8 9 T Ten High 1024 4 7 8 9 T 1024 3 7 8 9 T 1024 2 7 8 9 T 1024 5 6 8 9 T 1024 4 6 8 9 T 1024 3 6 8 9 T 1024 2 6 8 9 T 1024 4 5 8 9 T 1024 3 5 8 9 T 1024 2 5 8 9 T 1024 3 4 8 9 T 1024 2 4 8 9 T 1024 2 3 8 9 T 1024 5 6 7 9 T 1024 4 6 7 9 T 1024 3 6 7 9 T 1024 2 6 7 9 T 1024 4 5 7 9 T 1024 3 5 7 9 T 1024 2 5 7 9 T 1024 3 4 7 9 T 1024 2 4 7 9 T 1024 2 3 7 9 T 1024 4 5 6 9 T 1024 3 5 6 9 T 1024 2 5 6 9 T 1024 3 4 6 9 T 1024 2 4 6 9 T 1024 2 3 6 9 T 1024 3 4 5 9 T 1024 2 4 5 9 T 1024 2 3 5 9 T 1024 2 3 4 9 T 1024 5 6 7 8 T 1024 4 6 7 8 T 1024 3 6 7 8 T 1024 2 6 7 8 T 1024 4 5 7 8 T 1024 3 5 7 8 T 1024 2 5 7 8 T 1024 3 4 7 8 T 1024 2 4 7 8 T 1024 2 3 7 8 T 1024 4 5 6 8 T 1024 3 5 6 8 T 1024 2 5 6 8 T 1024 3 4 6 8 T 1024 2 4 6 8 T 1024 2 3 6 8 T 1024 3 4 5 8 T 1024 2 4 5 8 T 1024 2 3 5 8 T 1024 2 3 4 8 T 1024 4 5 6 7 T 1024 3 5 6 7 T 1024 2 5 6 7 T 1024 3 4 6 7 T 1024 2 4 6 7 T 1024 2 3 6 7 T 1024 3 4 5 7 T 1024 2 4 5 7 T 1024 2 3 5 7 T 1024 2 3 4 7 T 1024 3 4 5 6 T 1024 2 4 5 6 T 1024 2 3 5 6 T 1024 2 3 4 6 T 1024 2 3 4 5 T 1024 4 6 7 8 9 Nine High 1024 3 6 7 8 9 1024 2 6 7 8 9 1024 4 5 7 8 9 1024 3 5 7 8 9 1024 2 5 7 8 9 1024 3 4 7 8 9 1024 2 4 7 8 9 1024 2 3 7 8 9 1024 4 5 6 8 9 1024 3 5 6 8 9 1024 2 5 6 8 9 1024 3 4 6 8 9 1024 2 4 6 8 9 1024 2 3 6 8 9 1024 3 4 5 8 9 1024 2 4 5 8 9 1024 2 3 5 8 9 1024 2 3 4 8 9 1024 4 5 6 7 9 1024 3 5 6 7 9 1024 2 5 6 7 9 1024 3 4 6 7 9 1024 2 4 6 7 9 1024 2 3 6 7 9 1024 3 4 5 7 9 1024 2 4 5 7 9 1024 2 3 5 7 9 1024 2 3 4 7 9 1024 3 4 5 6 9 1024 2 4 5 6 9 1024 2 3 5 6 9 1024 2 3 4 6 9 1024 2 3 4 5 9 1024 3 5 6 7 8 Eight High 1024 2 5 6 7 8 1024 3 4 6 7 8 1024 2 4 6 7 8 1024 2 3 6 7 8 1024 3 4 5 7 8 1024 2 4 5 7 8 1024 2 3 5 7 8 1024 2 3 4 7 8 1024 3 4 5 6 8 1024 2 4 5 6 8 1024 2 3 5 6 8 1024 2 3 4 6 8 1024 2 3 4 5 8 1024 2 4 5 6 7 Seven High 1024 2 3 5 6 7 1024 2 3 4 6 7 1024 2 3 4 5 7 ================================================ FILE: src/server/algorithm/Pocker Rule.html ================================================ 德州扑克流程与规则

德州扑克玩法与规则

游戏规则

使用道具

游戏人数

发牌下注

Pre-flop

Flop

Turn

River

比牌

比牌方法

玩法介绍

庄家(Dealer)

盲注(Blinds)

底牌(Hole cards)

第一轮下注(Pre-flop)

翻牌及第二轮下注(Flop)

转牌及第三轮下注(Turn)

河牌及第四轮下注(River)

摊牌和比牌(Showdown)

新手盲注

全押(All-in)

底池(Pot)

主池(Main pot)与边池(Side pot)

参考文档

游戏规则

使用道具

一副标准扑克牌去掉大小王后的52张牌进行游戏

游戏人数

理论上一桌同时最多可容纳22位玩家,一般2-10个玩家

发牌下注

发牌一般分为5个步骤,分别为:

Pre-flop

先下大小盲注,然后给每个玩家发2张底牌,大盲注后面第一个玩家选择跟注、加注或者盖牌放弃,按照顺时针方向,其他玩家依次表态,大盲注玩家最后表态,如果玩家有加注情况,前面已经跟注的玩家需要再次表态甚至多次表态。

Flop

同时发三张公牌,由小盲注开始(如果小盲注已盖牌,由后面最近的玩家开始,以此类推),按照顺时针方向依次表态,玩家可以选择下注、加注、或者盖牌放弃。

Turn

发第4张牌,由小盲注开始,按照顺时针方向依次表态。

River

发第五张牌,由小盲注开始,按照顺时针方向依次表态,玩家可以选择下注、加注、或者盖牌放弃。

比牌

经过前面4轮发牌和下注,剩余的玩家开始亮牌比大小,成牌最大的玩家赢取池底。

比牌方法

用自己的2张底牌和5张公共牌结合在一起,选出5张牌,不论手中的牌使用几张(甚至可以不用手中的底牌),凑成最大的成牌,跟其他玩家比大小。

比牌先比牌型,大的牌型大于小的牌型,牌型一般分为10种,从大到小为:

皇家同花顺(Royal Flush)

同花色的A, K, Q, J和10。

平手牌:在摊牌的时候有两副多副皇家同花顺时,平分筹码。

同花顺(Straight Flush)

五张同花色的连续牌。

平手牌:如果摊牌时有两副或多副同花顺,连续牌的头张牌大的获得筹码。如果是两副或多副相同的连续牌,平分筹码。

四条(Four of a Kind,亦称“铁支”、“四张”或“炸弹”)

其中四张是相同点数但不同花的扑克牌,第五张是随意的一张牌。

平手牌:如果两组或者更多组摊牌,则四张牌中的最大者赢局,如果一组人持有的四张牌是一样的,那么第五张牌最大者赢局(起脚牌)。如果起脚牌也一样,平分彩池。

满堂彩(Fullhouse,葫芦,三带二

由三张相同点数及任何两张其他相同点数的扑克牌组成。

平手牌:如果两组或者更多组摊牌,那么三张相同点数中较大者赢局。如果三张牌都一样,则两张牌中点数较大者赢局,如果所有的牌都一样,则平分彩池。

同花(Flush,简称“花”)

此牌由五张不按顺序但相同花的扑克牌组成。

平手牌:如果不止一人抓到此牌相,则牌点最高的人赢得该局,如果最大点相同,则由第二、第三、第四或者第五张牌来决定胜负,如果所有的牌都相同,平分彩池。

顺子(Straight,亦称“蛇”)

此牌由五张顺序扑克牌组成。

平手牌:如果不止一人抓到此牌,则五张牌中点数最大的赢得此局,如果所有牌点数都相同,平分彩池。

三条(Three of a kind,亦称“三张”)

由三张相同点数和两张不同点数的扑克组成。

平手牌:如果不止一人抓到此牌,则三张牌中最大点数者赢局,如果三张牌都相同,比较第四张牌,必要时比较第五张,点数大的人赢局。如果所有牌都相同,则平分彩池。

两对(Two Pairs)

两对点数相同但两两不同的扑克和随意的一张牌组成。

平手牌:如果不止一人抓大此牌相,牌点比较大的人赢,如果比较大的牌点相同,那么较小牌点中的较大者赢,如果两对牌点相同,那么第五张牌点较大者赢(起脚牌)。如果起脚牌也相同,则平分彩池。

一对(One Pair)

由两张相同点数的扑克牌和另三张随意的牌组成。

平手牌:如果不止一人抓到此牌,则两张牌中点数大的赢,如果对牌都一样,则比较另外三张牌中大的赢,如果另外三张牌中较大的也一样则比较第二大的和第三大的,如果所有的牌都一样,则平分彩池。

高牌(high card)

既不是同一花色也不是同一点数的五张牌组成。

平手牌:如果不止一人抓到此牌,则比较点数最大者,如果点数最大的相同,则比较第二、第三、第四和第五大的,如果所有牌都相同,则平分彩池。

玩法介绍

庄家(Dealer)

首先确定庄家(英文为Button,固也称按钮)位置。第一局庄家位置系统随机指定,以后每局庄家位置按照顺时针方向下移一位。

盲注(Blinds)

为了使得游戏能够进行,强制庄家左边第一个人下一注(称小盲注 Small Blind),按钮左边第二个人下两注(称大盲注 Big Blind)。

底牌(Hole cards)

下盲注后从下大盲注玩家开始按顺时针方向每人发两张牌,皆为暗牌,称底牌或起手牌。

第一轮下注(Pre-flop)

发底牌后,从大盲注左边的玩家开始行动/叫注/说话(Action),行动指从以下几项选择其一:

  • 弃牌(Fold):放弃本副牌,不参与竞争。
  • 让牌(Check):观望态度,或者是挖陷阱。
  • 跟注(Call):跟到和上家相同的注额。
  • 加注(Raise):增加下注额,直到全部筹码即全押(All-in)。

一人结束行动后按顺时针方向下一玩家获得行动权,直到不再有人弃牌,且每人已向奖池投入相同注额。已弃牌玩家不再有行动权。

如无盲注,则为发牌人左方的玩家,如为一对一时,则由大盲注先行叫注。

翻牌及第二轮下注(Flop)

发三张牌到牌桌中央,称为“翻牌”,为公共牌,所有人可见。

从小盲注玩家按顺时针方向做同于第一轮的行动,直到不再有人弃牌,且每人已向奖池投入相同注额。已弃牌玩家不再参与游戏。

转牌及第三轮下注(Turn)

发第四张牌,称为“转牌”,为公共牌,所有人可见。

从小盲注玩家按顺时针方向做同于第一轮的行动,直到不再有人弃牌,且每人已向奖池投入相同注额。已弃牌玩家不再参与游戏。

河牌及第四轮下注(River)

发第五张牌,称为“河牌”,为公共牌,所有人可见。

从小盲注玩家按顺时针方向做同于第一轮的行动,直到不再有人弃牌,且每人已向奖池投入相同注额。已弃牌玩家不再参与游戏。

摊牌和比牌(Showdown)

四轮下注都完成后,若仍剩余两名或两名以上玩家,则进行比牌。

比牌时,每位玩家用手中2张底牌与5张公共牌中任选5张组成最大牌者进行比较大小。胜者赢得底池所有注码。若有多人获胜,则平分底池注码。

當彩池由兩個以上玩家平分時,若有無法平分之小額籌碼,由順時鐘方向算過去,最靠近發牌者的贏家取得,舉例來說有ABCDE依順時鐘方向入座,A為本局發牌者,最小面額籌碼為$10,所有玩家皆未蓋牌至攤牌,最終由CDE勝出平分本局彩池$1000時,則DE各分到$330,而多出的$10將分配給最靠近A的贏家C,C於本局可分到$340。

新手盲注

在牌局已经形成的情况下,新加入牌局的人,需要下新手盲注,新手盲注等于大盲注。

全押(All-in)

当一个玩家加注或企图跟注却筹码不足时,他可以选择全押。当有玩家全押时,他会跟进他所有的筹码,底池被分为主池和边池。其他玩家多出全押玩家筹码的注额将都会被加入边池,此全押玩家将不可能获得边池而只可能赢得主池。同理,当多个玩家全押时可能出现多个边池。

底池(Pot)

每一个牌局里众人已押上的筹码总额,也即该局的奖金数目。

主池(Main pot)边池(Side pot)

当没有玩家全押(All-in)时,底池由未弃牌的玩家中牌型最大者独得。

当有一个或多个玩家全押时,超过玩家压注金额的部分将会形成一个或多个边池。玩家参与投注该边池才有机会赢取改边池。

当一局结束而且所有已全押的玩家未持有最大牌型时,边池和主池都由牌面最佳获胜者赢取。

当一局结束而且有全押的玩家赢牌时,该玩家有参与投注的主池和边池均归该玩家,而其他边池由参与改池投注里,持有最大牌面的玩家赢得。

在几个玩家全押形成多个边池时,依全押的顺序分配给各边池中最佳牌面的玩家,有最大牌面的玩家赢得该玩家全押前所累积的边池。已全押的玩家无法赢取全押后产生的边池,即最多只能从其他每个跟牌玩家处取得相当于本身全押的总筹码数。全押后的下注可视为只在之后参与的玩家之间的独立输赢分配。

无人跟注的边池(仅有一位玩家下注,剩下其他玩家都弃牌)将会直接赢得该边池,相当于退换下注于该边池的筹码。

底池分配范例

例如ABCDEF六名玩家參與牌局,F於中途蓋牌退出,最終A全押投入$50,B全押投入$250,C全押投入$350,DE各投入$800,F投入$500,此時總彩池大小為$2750,形成了一個主池為50*6=$300,邊池各為(250-50)*5=$1000,(350-250)*4=$400,(500-350)*3=$450,(800-500)*2=$600,若最終組成牌面大小為F>A>B>D>E>C,但F已蓋牌不能分配任何彩池,則此局主池即為A於此局贏得的籌碼($300),B可贏得第一個邊池($1000),D參與至最後一個邊池,且牌面勝過參與第二、第三及第四邊池的所有玩家,因此可贏得剩下所有的邊池(400+450+600=$1450)

因为每个人手中的筹码量会不时的产生变化,当出现多个筹码量不等的玩家“全下(ALL-IN)”争夺底池的时候就会出现多个奖池,这时候底池将分出主池和边池,主池里的筹码可由任何一位争夺者胜利后将其拿走,其后每个边池将分别由参与者按牌型大小分别拿走。

举个例子,假如发到河牌后共有三个人争夺底池,三人分别用ABC代替,假设A玩家手中有60,B手中有80,C手中有100。三人ALL-IN后则先把每人的筹码划分成:

A玩家60;B玩家60+20;C玩家60+20+20,然后分出底池:

主池         由60乘以三个人(A+B+C)形成一个堆,总额为180;

边池一 由20乘以剩下的两个人(B+C)多出的部分为一个堆,总额为40;

边池二 由筹码最多者C的多出的部分20单独组成一个堆,总额为20。

现在三个底池形成了,然后分别按照牌型的大小来决定谁拿走哪个底池……

首先,主池可以由三人中的任何一人得到胜利都可以拿走;但是边池一的争夺就只能在B与C之间产生,两人谁赢谁拿走,与A无关(就算A玩家的牌最大也只能拿走他参与的主池)。而最后剩下的边池二不论三人谁输谁赢都只能由C拿走,因为边池二里的筹码只有C自己参与了,与其他人无关。

参考文档

  • 德州扑克规则

http://jingyan.baidu.com/article/0aa223758306b688cd0d6462.html

        http://zhidao.baidu.com/question/1446347228032870540.html

================================================ FILE: src/server/algorithm/cards.go ================================================ package algorithm type Cards []byte // todo 两对和四张起脚牌的判定 var StraightMask = []uint16{15872, 7936, 3968, 1984, 992, 496, 248, 124, 62, 31} //顺子(Straight,亦称“蛇”) //此牌由五张顺序扑克牌组成。 //平手牌:如果不止一人抓到此牌,则五张牌中点数最大的赢得此局, // 如果所有牌点数都相同,平分彩池。 func (this *Cards) straight() uint32 { var handvalue uint16 for _, v := range (*this) { value := v & 0xF if value == 0xE { handvalue |= 1 } handvalue |= (1 << (value - 1 ) ) } for i := uint8(0); i < 10; i++ { if handvalue&StraightMask[i] == StraightMask[i] { return En(STRAIGHT, uint32(10-i+4)) } } return 0 } //同花顺(Straight Flush) //五张同花色的连续牌。 //平手牌:如果摊牌时有两副或多副同花顺,连续牌的头张牌大的获得筹码。 //如果是两副或多副相同的连续牌,平分筹码。 func (this *Cards) straightFlush() uint32 { cards := *this for i := byte(0); i < SUITSIZE; i++ { var handvalue uint16 for _, v := range cards { if (v >> 4) == i { value := v & 0xF if value == 0xE { handvalue |= 1 } handvalue |= (1 << (value - 1 ) ) } } for i := uint8(0); i < 10; i++ { if handvalue&StraightMask[i] == StraightMask[i] { return En(STRAIGHT_FLUSH, uint32(10-i+4)) } } } return 0 } //皇家同花顺(Royal Flush) //同花色的A, K, Q, J和10。 //平手牌:在摊牌的时候有两副多副皇家同花顺时,平分筹码。 func (this *Cards) royalFlush() uint32 { cards := *this for i := byte(0); i < SUITSIZE; i++ { var handvalue uint16 for _, v := range cards { if (v >> 4) == i { value := v & 0xF if value == 0xE { handvalue |= 1 } handvalue |= (1 << (value - 1 ) ) } } if handvalue&StraightMask[0] == StraightMask[0] { return En(ROYAL_FLUSH, 0) } } return 0 } //四条(Four of a Kind,亦称“铁支”、“四张”或“炸弹”) //其中四张是相同点数但不同花的扑克牌,第五张是随意的一张牌。 //平手牌:如果两组或者更多组摊牌,则四张牌中的最大者赢局,如果一组人持有的四张牌是一样的, //那么第五张牌最大者赢局(起脚牌,2张起手牌中小的那张就叫做起脚牌)。如果起脚牌也一样,平分彩池。 func (this *Cards) four(counter *ValueCounter) uint32 { cards := *this if counter.Get(cards[len(cards)-1]) == 4 { return En(FOUR, ToValue(cards)) } return 0 } //满堂彩(Fullhouse,葫芦,三带二) //由三张相同点数及任何两张其他相同点数的扑克牌组成。 //平手牌:如果两组或者更多组摊牌,那么三张相同点数中较大者赢局。 //如果三张牌都一样,则两张牌中点数较大者赢局,如果所有的牌都一样,则平分彩池。 func (this *Cards) fullFouse(counter *ValueCounter) uint32 { cards := *this length := len(cards) if length >= 5 { if cards[length-1]&0xF == cards[length-2]&0xF && cards[length-3]&0xF == cards[length-1]&0xF && cards[length-4]&0xF == cards[length-5]&0xF { return En(FULL_HOUSE, ToValue(cards)) } } return 0 } //同花(Flush,简称“花”) //此牌由五张不按顺序但相同花的扑克牌组成。 //平手牌:如果不止一人抓到此牌相,则牌点最高的人赢得该局, //如果最大点相同,则由第二、第三、第四或者第五张牌来决定胜负,如果所有的牌都相同,平分彩池。 func (this *Cards) flush() uint32 { cards := *this for i := byte(0); i < SUITSIZE; i++ { var count uint8 for _, v := range cards { if (v >> 4) == i { count ++ if count == 5 { var handvalue uint16 for _, v1 := range cards { if (v1 >> 4) == i { value := v1 & 0xF if value == 0xE { handvalue |= 1 } handvalue |= (1 << (value - 1 ) ) } } return En(FLUSH, uint32(handvalue)) } } } } return 0 } //三条(Three of a kind,亦称“三张”) //由三张相同点数和两张不同点数的扑克组成。 //平手牌:如果不止一人抓到此牌,则三张牌中最大点数者赢局, //如果三张牌都相同,比较第四张牌,必要时比较第五张,点数大的人赢局。如果所有牌都相同,则平分彩池。 func (this *Cards) three(counter *ValueCounter) uint32 { cards := *this if counter.Get(cards[len(cards)-1]) == 3 { return En(THREE, ToValue(cards)) } return 0 } //两对(Two Pairs) //两对点数相同但两两不同的扑克和随意的一张牌组成。 //平手牌:如果不止一人抓大此牌相,牌点比较大的人赢,如果比较大的牌点相同,那么较小牌点中的较大者赢, //如果两对牌点相同,那么第五张牌点较大者赢(起脚牌,2张起手牌中小的那张就叫做起脚牌)。如果起脚牌也相同,则平分彩池。 func (this *Cards) twoPair() uint32 { cards := *this length := len(cards) if length >= 4 { if cards[length-1]&0xF == cards[length-2]&0xF && cards[length-3]&0xF == cards[length-4]&0xF { return En(TWO_PAIR, ToValue(cards)) } } return 0 } //一对(One Pair) //由两张相同点数的扑克牌和另三张随意的牌组成。 //平手牌:如果不止一人抓到此牌,则两张牌中点数大的赢,如果对牌都一样,则比较另外三张牌中大的赢, //如果另外三张牌中较大的也一样则比较第二大的和第三大的,如果所有的牌都一样,则平分彩池。 func (this *Cards) onePair() uint32 { cards := *this length := len(cards) if length >= 2 { if cards[length-1]&0xF == cards[length-2]&0xF { return En(ONE_PAIR, ToValue(cards)) } } return 0 } func ToValue(cards []byte) uint32 { var res uint32 for i := len(cards) - 1; i >= 0; i-- { res *= 10 res += uint32(cards[i] & 0xF) } return res } func De(v uint32) (uint8, uint32) { return uint8(v >> 24), v & 0xFFFFFF } func En(t uint8, v uint32) uint32 { v1 := v | ( uint32(t) << 24) return v1 } ================================================ FILE: src/server/algorithm/cards_test.go ================================================ package algorithm import ( "testing" "strings" "github.com/stretchr/testify/assert" ) func TestFour(t *testing.T) { cards := Cards{0x12, 0x02, 0x22, 0xb, 0x1b, 0x7, 0x32} k,_:=De(cards.GetType()) assert.Equal(t, k, FOUR) cards = Cards{0x12, 0x02, 0x22, 0x32} k,_=De(cards.GetType()) assert.Equal(t, k, FOUR) } func TestThree(t *testing.T) { cards := Cards{0x12, 0x02, 0x22, 0x3a, 0x2a, 0x1a, 0x33} k,_:=De(cards.GetType()) assert.Equal(t, k, FULL_HOUSE) } func TestHighCard(t *testing.T) { //var cs Cards cards := Cards{0x1E, 0x02, 0x22, 0x3a, 0x2a, 0x1a, 0x33} k, _ := De(cards.GetType()) assert.Equal(t, k, FULL_HOUSE) //assert.Equal(t, v, uint32(0xE)) } func TestCards_OnePair(t *testing.T) { cards := Cards{0x12, 0x0e, 0x2e, 0x3a, 0x2a, 0x1a, 0x32} k, _ := De(cards.GetType()) assert.Equal(t, k, FULL_HOUSE) } func TestCards_Straight(t *testing.T) { cards := Cards{0x12, 0x03, 0x24, 0x35, 0x26, 0x17, 0x33} k, v := De(cards.GetType()) assert.Equal(t, k, STRAIGHT) assert.Equal(t, v, uint32(7)) cards = Cards{0x12, 0x03, 0x24, 0x34, 0x26, 0x17, 0x37} assert.Equal(t, k, STRAIGHT) assert.Equal(t, v, uint32(7)) cards = Cards{0x12, 0x03, 0x24, 0x34, 0x25, 0x17, 0x3E} k, v = De(cards.GetType()) assert.Equal(t, k, STRAIGHT) assert.Equal(t, v, uint32(0x5)) cards = Cards{0x12, 0x03, 0x2a, 0x3c, 0x2b, 0x1d, 0x3E} k, v = De(cards.GetType()) assert.Equal(t, k, STRAIGHT) assert.Equal(t, v, uint32(0xe)) } func TestCards_Flush(t *testing.T) { cards := Cards{0x32, 0x33, 0x34, 0x35, 0x26, 0x37, 0x28} k, _ := De(cards.GetType()) assert.Equal(t, k,FLUSH) //assert.Equal(t, v, uint32(6)) } func TestCards_TwoPair(t *testing.T) { cards := Cards{0x12, 0x22, 0x34, 0x35, 0x25, 0x38, 0x28} k, _ := De(cards.GetType()) assert.Equal(t, k, TWO_PAIR) } func TestCards_RoyalFlush(t *testing.T) { cards := Cards{0x3A, 0x3B, 0x3C, 0x3E, 0x3D, 0x38, 0x28} k, _ := De(cards.GetType()) assert.Equal(t, k, ROYAL_FLUSH) cards = Cards{0x3A, 0x3B, 0x3C, 0x3E, 0x2D, 0x38, 0x28} k, _ = De(cards.GetType()) assert.Equal(t, k, FLUSH) } func TestCards_FLUSH1(t *testing.T) { cards1 := Cards{0x22, 0x22, 0x22, 0x25, 0x38, 0x28} cards2 := Cards{0x32, 0x32, 0x33, 0x34, 0x25, 0x36} v1:=cards1.GetType() v2:=cards2.GetType() assert.Equal(t,v1 > v2 ,true) cards1 = Cards{0x22, 0x22, 0x2E, 0x25, 0x38, 0x28} cards2 = Cards{0x32, 0x32, 0x33, 0x3a, 0x2a, 0x3E} assert.Equal(t,cards1.GetType() > cards2.GetType() ,false) } func TestCards_FLUSH(t *testing.T) { cards1 := Cards{0x22, 0x22, 0x24, 0x25, 0x38, 0x28} cards2 := Cards{0x32, 0x32, 0x33, 0x34, 0x25, 0x36} v1:=cards1.GetType() v2:=cards2.GetType() assert.Equal(t,v1 > v2 ,true) } func TestCards_PK(t *testing.T) { cards1 := Cards{0x32, 0x32, 0x34, 0x35, 0x25, 0x38, 0x28} cards2 := Cards{0x32, 0x32, 0x33, 0x34, 0x25, 0x36} v1:=cards1.GetType() v2:=cards2.GetType() assert.Equal(t,v1 > v2 ,true) } func TestCards_StraightFlush(t *testing.T) { cards := Cards{0x32, 0x33, 0x34, 0x35, 0x36, 0x27, 0x28} k, v := De(cards.GetType()) assert.Equal(t, k, uint8(9)) assert.Equal(t, v, uint32(6)) cards = Cards{0x32, 0x33, 0x34, 0x35, 0x3E, 0x37, 0x28} k, v = De(cards.GetType()) assert.Equal(t, k, uint8(9)) assert.Equal(t, v, uint32(5)) cards = Cards{0x32, 0x33, 0x34, 0x35, 0x3E, 0x36, 0x28} k, v = De(cards.GetType()) assert.Equal(t, k, uint8(9)) assert.Equal(t, v, uint32(6)) } func TestCards_FullFouse(t *testing.T) { cards := Cards{0x33, 0x33, 0x33, 0x35, 0x25, 0x35, 0x28} k, _ := De(cards.GetType()) //t.Logf("%v %v %#v ",k,v,cards) assert.Equal(t, k, FULL_HOUSE) //assert.Equal(t, v, FULL_HOUSE) //t.Log(cards.String()) //t.Log(cards.Hex()) } func TestString2Num(t *testing.T) { array := Cards{0x33, 0x33, 0x33, 0x35, 0x25, 0x35, 0x3E, 0x1A} //for i := 0; i < N; i++ { go array.Shuffle() t.Log(array.String()) //} } func TestFullFouse(t *testing.T) { var s = "A A A K K|" + "A A A Q Q|" + "A A A J J|" + "A A A T T|" + "A A A 9 9|" + "A A A 8 8|" + "A A A 7 7|" + "A A A 6 6|" + "A A A 5 5|" + "A A A 4 4|" + "A A A 3 3|" + "A A A 2 2|" + "K K K A A|" + "K K K Q Q|" + "K K K J J|" + "K K K T T|" + "K K K 9 9|" + "K K K 8 8|" + "K K K 7 7|" + "K K K 6 6|" + "K K K 5 5|" + "K K K 4 4|" + "K K K 3 3|" + "K K K 2 2|" + "Q Q Q A A|" + "Q Q Q K K|" + "Q Q Q J J|" + "Q Q Q T T|" + "Q Q Q 9 9" array := strings.Split(s, "|") var oldValue uint32 for _, v := range array { cards := &Cards{} cards.SetByString(v) //t.Log(cards.String()) k, value := De(cards.GetType()) if oldValue == 0{ oldValue = value continue } assert.Equal(t, oldValue> value, true) assert.Equal(t, k, FULL_HOUSE) //assert.Equal(t,v,uint32(6)) //t.Log(De(cards.FullFouse(cards.Counter()))) } } func Test_Straight1(t *testing.T) { /* testCards := "T J Q K A|" + "9 T J Q K|" + "8 9 T J Q|" + "7 8 9 T J|" + "6 7 8 9 T|" + "5 6 7 8 9|" + "4 5 6 7 8|" + "3 4 5 6 7|" + "2 3 4 5 6|" + "A 2 3 4 5" //array := strings.Split(testCards, "|") for _, v := range array { cards := &Cards{} cards.SetByString(v) cards.Sort() t.Log(cards.String(), cards.Straight() > 0) } t.Log("--------------------------------------") for _, v := range array { cards := &Cards{} cards.SetByString(v) cards.Sort() t.Log(cards.String(), cards.StraightFlush() > 0) }*/ /* t.Log("--------------------------------------") for _, v := range array { cards := &Cards{} cards.SetByString(v) cards.Sort() t.Log(cards.String(), cards.RoyalFlush()) }*/ } func Test_AnalyseCards(t *testing.T) { var a ColorCounter cards := []byte{0x33, 0x35, 0x25, 0x35, 0x28} a.Set(cards) t.Log(a.Get(0x33), a.Get(0x35), a.Get(0x28)) } func Test_Append(t *testing.T) { cards := Cards{0x33, 0x35, 0x25, 0x35, 0x28} cards = cards.Append(Cards{0x33, 0x33}...) t.Logf("%#v ", cards.GetType()) } func Test_turnToValue1(t *testing.T) { v1 := []byte{0x33, 0x35, 0x25, 0x35, 0x28} v2 := []byte{0x35, 0x35, 0x25, 0x35, 0x27} t.Logf("%#v %#v ", v1, v2) b1 := ToValue(v1) b2 := ToValue(v2) t.Log(b1, b2) } func Test_ColorCounter(t *testing.T) { v2 := []byte{0x35, 0x35, 0x25, 0x35, 0x27} var colorCounter ColorCounter colorCounter.Set(v2) t.Log(v2) } func Test_turnToValue(t *testing.T) { v := ToValue([]byte{0x3E, 0x3E, 0x3E, 0x3E, 0x3E, 0x3E, 0x3E}) //var v3 uint16 = v v1 := v | ( 10 << 24) //t.Log(v3) t.Logf("%v %v %v", v, v1>>24, v1&0xFFFFFF) t.Logf("%v ", ToValue([]byte{0x33, 0x35, 0x25, 0x35, 0x28})) } ================================================ FILE: src/server/algorithm/constan.go ================================================ package algorithm // 扑克牌52张,分别包含普通牌52张 2-10、J、Q、K、A (以上每种牌4个花色 黑桃、梅花、红心、方块) var CARDS = []byte{ //方块 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, //梅花 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, //红桃 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, //黑桃 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, } const ( CARDRANK = 13 SUITSIZE = 4 TOTAL = 13 * 4 TYPE_LEN = 5 // 牌型长度 CARDS_LEN = 7 // 河牌+底牌长度 ) //牌型大小: //1、皇家同花顺>同花顺>四条>葫芦>同花>顺子>三条>两队>一对>单牌 //2、牌点从大到小为:A、K、Q、J、10、9、8、7、6、5、4、3、2,各花色不分大小。 //3、同种牌型,对子时比对子的大小,其它牌型比最大的牌张,如最大牌张相同则比第二大的牌张,以此类推,都相同时为相同。 //4、A 可以组顺子 A、1、2、3、4、5 也可以组顺子 10、J、Q、K、A 同花顺同理 //所有牌型如下: const ( ROYAL_FLUSH uint8= 10 // 皇家同花顺:同一花色的最大顺子。(最大牌:A-K-Q-J-10) STRAIGHT_FLUSH uint8= 9 // 同花顺:同一花色的顺子。(最大牌:K-Q-J-10-9 最小牌:A-2-3-4-5) FOUR uint8= 8 // 四条:四同张加单张。(最大牌:A-A-A-A-K 最小牌:2-2-2-2-3) FULL_HOUSE uint8= 7 // 葫芦(豪斯):三同张加对子。(最大牌:A-A-A-K-K 最小牌:2-2-2-3-3) FLUSH uint8= 6 // 同花:同一花色。(最大牌:A-K-Q-J-9 最小牌:2-3-4-5-7) STRAIGHT uint8= 5 // 顺子:花色不一样的顺子。(最大牌:A-K-Q-J-10 最小牌:A-2-3-4-5) THREE uint8= 4 // 三条:三同张加两单张。(最大牌:A-A-A-K-Q 最小牌:2-2-2-3-4) TWO_PAIR uint8= 3 // 两对:(最大牌:A-A-K-K-Q 最小牌:2-2-3-3-4) ONE_PAIR uint8= 2 // 一对:(最大牌:A-A-K-Q-J 最小牌:2-2-3-4-5) HIGH_CARD uint8= 1 // 高牌:(最大牌:A-K-Q-J-9 最小牌:2-3-4-5-7) ) ================================================ FILE: src/server/algorithm/dealer.go ================================================ package algorithm import ( "time" "math/rand" ) //var n int64 //var a int64= 1<<62 // 洗牌 func (this *Cards) Shuffle() { *this = make([]byte, TOTAL) copy(*this, CARDS) source := rand.NewSource(time.Now().UnixNano() ) //n ++ //n %=a r := rand.New(source) for i := TOTAL - 1; i > 0; i-- { index := r.Int() % i (*this)[i], (*this)[index] = (*this)[index], (*this)[i] } } ================================================ FILE: src/server/algorithm/dealer_test.go ================================================ package algorithm import "testing" func Test_Dealer(t *testing.T) { d:= &Cards{} d.Shuffle() d.Shuffle() t.Logf("%#v ",d) } ================================================ FILE: src/server/algorithm/flush_test.go ================================================ package algorithm import ( "testing" "strings" "github.com/stretchr/testify/assert" ) func TestFlush1(t *testing.T) { var s = "9 J Q K A |" + "8 J Q K A |" + "7 J Q K A |" + "6 J Q K A |" + "5 J Q K A |" + "4 J Q K A |" + "3 J Q K A |" + "2 J Q K A |" + "9 T Q K A |" + "8 T Q K A |" + "7 T Q K A |" + "6 T Q K A |" + "5 T Q K A |" + "4 T Q K A |" + "3 T Q K A |" + "2 T Q K A |" + "8 9 Q K A |" + "7 9 Q K A |" + "6 9 Q K A |" + "5 9 Q K A |" + "4 9 Q K A |" + "3 9 Q K A |" + "2 9 Q K A |" + "7 8 Q K A |" + "6 8 Q K A |" + "5 8 Q K A |" + "4 8 Q K A |" + "3 8 Q K A |" + "2 8 Q K A |" + "6 7 Q K A |" + "5 7 Q K A |" + "4 7 Q K A |" + "3 7 Q K A |" + "2 7 Q K A |" + "5 6 Q K A |" + "4 6 Q K A |" + "3 6 Q K A |" + "2 6 Q K A |" + "4 5 Q K A |" + "3 5 Q K A |" + "2 5 Q K A |" + "3 4 Q K A |" + "2 4 Q K A |" + "2 3 Q K A |" + "9 T J K A |" + "8 T J K A |" + "7 T J K A |" + "6 T J K A |" + "5 T J K A |" + "4 T J K A |" + "3 T J K A |" + "2 T J K A |" + "8 9 J K A |" + "7 9 J K A |" + "6 9 J K A |" + "5 9 J K A |" + "4 9 J K A |" + "3 9 J K A |" + "2 9 J K A |" + "7 8 J K A |" + "6 8 J K A |" + "5 8 J K A |" + "4 8 J K A |" + "3 8 J K A |" + "2 8 J K A |" + "6 7 J K A |" + "5 7 J K A |" + "4 7 J K A |" + "3 7 J K A |" + "2 7 J K A |" + "5 6 J K A |" + "4 6 J K A |" + "3 6 J K A |" + "2 6 J K A |" + "4 5 J K A |" + "3 5 J K A |" + "2 5 J K A |" + "3 4 J K A |" + "2 4 J K A |" + "2 3 J K A |" + "8 9 T K A |" + "7 9 T K A |" + "6 9 T K A |" + "5 9 T K A |" + "4 9 T K A |" + "3 9 T K A |" + "2 9 T K A |" + "7 8 T K A |" + "6 8 T K A |" + "5 8 T K A |" + "4 8 T K A |" + "3 8 T K A |" + "2 8 T K A |" + "6 7 T K A |" + "5 7 T K A |" + "4 7 T K A |" + "3 7 T K A |" + "2 7 T K A |" + "5 6 T K A |" + "4 6 T K A |" + "3 6 T K A |" + "2 6 T K A |" + "4 5 T K A |" + "3 5 T K A |" + "2 5 T K A |" + "3 4 T K A |" + "2 4 T K A |" + "2 3 T K A |" + "7 8 9 K A |" + "6 8 9 K A |" + "5 8 9 K A |" + "4 8 9 K A |" + "3 8 9 K A |" + "2 8 9 K A |" + "6 7 9 K A |" + "5 7 9 K A |" + "4 7 9 K A |" + "3 7 9 K A |" + "2 7 9 K A |" + "5 6 9 K A |" + "4 6 9 K A |" + "3 6 9 K A |" + "2 6 9 K A |" + "4 5 9 K A |" + "3 5 9 K A |" + "2 5 9 K A |" + "3 4 9 K A |" + "2 4 9 K A |" + "2 3 9 K A |" + "6 7 8 K A |" + "5 7 8 K A |" + "4 7 8 K A |" + "3 7 8 K A |" + "2 7 8 K A |" + "5 6 8 K A |" + "4 6 8 K A |" + "3 6 8 K A |" + "2 6 8 K A |" + "4 5 8 K A |" + "3 5 8 K A |" + "2 5 8 K A |" + "3 4 8 K A |" + "2 4 8 K A |" + "2 3 8 K A |" + "5 6 7 K A |" + "4 6 7 K A |" + "3 6 7 K A |" + "2 6 7 K A |" + "4 5 7 K A |" + "3 5 7 K A |" + "2 5 7 K A |" + "3 4 7 K A |" + "2 4 7 K A |" + "2 3 7 K A |" + "4 5 6 K A |" + "3 5 6 K A |" + "2 5 6 K A |" + "3 4 6 K A |" + "2 4 6 K A |" + "2 3 6 K A |" + "3 4 5 K A |" + "2 4 5 K A |" + "2 3 5 K A |" + "2 3 4 K A |" + "9 T J Q A |" + "8 T J Q A |" + "7 T J Q A |" + "6 T J Q A |" + "5 T J Q A |" + "4 T J Q A |" + "3 T J Q A |" + "2 T J Q A |" + "8 9 J Q A |" + "7 9 J Q A |" + "6 9 J Q A |" + "5 9 J Q A |" + "4 9 J Q A |" + "3 9 J Q A |" + "2 9 J Q A |" + "7 8 J Q A |" + "6 8 J Q A |" + "5 8 J Q A |" + "4 8 J Q A |" + "3 8 J Q A |" + "2 8 J Q A |" + "6 7 J Q A |" + "5 7 J Q A |" + "4 7 J Q A |" + "3 7 J Q A |" + "2 7 J Q A |" + "5 6 J Q A |" + "4 6 J Q A |" + "3 6 J Q A |" + "2 6 J Q A |" + "4 5 J Q A |" + "3 5 J Q A |" + "2 5 J Q A |" + "3 4 J Q A |" + "2 4 J Q A |" + "2 3 J Q A |" + "8 9 T Q A |" + "7 9 T Q A |" + "6 9 T Q A |" + "5 9 T Q A |" + "4 9 T Q A |" + "3 9 T Q A |" + "2 9 T Q A |" + "7 8 T Q A |" + "6 8 T Q A |" + "5 8 T Q A |" + "4 8 T Q A |" + "3 8 T Q A |" + "2 8 T Q A |" + "6 7 T Q A |" + "5 7 T Q A |" + "4 7 T Q A |" + "3 7 T Q A |" + "2 7 T Q A |" + "5 6 T Q A |" + "4 6 T Q A |" + "3 6 T Q A |" + "2 6 T Q A |" + "4 5 T Q A |" + "3 5 T Q A |" + "2 5 T Q A |" + "3 4 T Q A |" + "2 4 T Q A |" + "2 3 T Q A |" + "7 8 9 Q A |" + "6 8 9 Q A |" + "5 8 9 Q A |" + "4 8 9 Q A |" + "3 8 9 Q A |" + "2 8 9 Q A |" + "6 7 9 Q A |" + "5 7 9 Q A |" + "4 7 9 Q A |" + "3 7 9 Q A |" + "2 7 9 Q A |" + "5 6 9 Q A |" + "4 6 9 Q A |" + "3 6 9 Q A |" + "2 6 9 Q A |" + "4 5 9 Q A |" + "3 5 9 Q A |" + "2 5 9 Q A |" + "3 4 9 Q A |" + "2 4 9 Q A |" + "2 3 9 Q A |" + "6 7 8 Q A |" + "5 7 8 Q A |" + "4 7 8 Q A |" + "3 7 8 Q A |" + "2 7 8 Q A |" + "5 6 8 Q A |" + "4 6 8 Q A |" + "3 6 8 Q A |" + "2 6 8 Q A |" + "4 5 8 Q A |" + "3 5 8 Q A |" + "2 5 8 Q A |" + "3 4 8 Q A |" + "2 4 8 Q A |" + "2 3 8 Q A |" + "5 6 7 Q A |" + "4 6 7 Q A |" + "3 6 7 Q A |" + "2 6 7 Q A |" + "4 5 7 Q A |" + "3 5 7 Q A |" + "2 5 7 Q A |" + "3 4 7 Q A |" + "2 4 7 Q A |" + "2 3 7 Q A |" + "4 5 6 Q A |" + "3 5 6 Q A |" + "2 5 6 Q A |" + "3 4 6 Q A |" + "2 4 6 Q A |" + "2 3 6 Q A |" + "3 4 5 Q A |" + "2 4 5 Q A |" + "2 3 5 Q A |" + "2 3 4 Q A |" + "8 9 T J A |" + "7 9 T J A |" + "6 9 T J A |" + "5 9 T J A |" + "4 9 T J A |" + "3 9 T J A |" + "2 9 T J A |" + "7 8 T J A |" + "6 8 T J A |" + "5 8 T J A |" + "4 8 T J A |" + "3 8 T J A |" + "2 8 T J A |" + "6 7 T J A |" + "5 7 T J A |" + "4 7 T J A |" + "3 7 T J A |" + "2 7 T J A |" + "5 6 T J A |" + "4 6 T J A |" + "3 6 T J A |" + "2 6 T J A |" + "4 5 T J A |" + "3 5 T J A |" + "2 5 T J A |" + "3 4 T J A |" + "2 4 T J A |" + "2 3 T J A |" + "7 8 9 J A |" + "6 8 9 J A |" + "5 8 9 J A |" + "4 8 9 J A |" + "3 8 9 J A |" + "2 8 9 J A |" + "6 7 9 J A |" + "5 7 9 J A |" + "4 7 9 J A |" + "3 7 9 J A |" + "2 7 9 J A |" + "5 6 9 J A |" + "4 6 9 J A |" + "3 6 9 J A |" + "2 6 9 J A |" + "4 5 9 J A |" + "3 5 9 J A |" + "2 5 9 J A |" + "3 4 9 J A |" + "2 4 9 J A |" + "2 3 9 J A |" + "6 7 8 J A |" + "5 7 8 J A |" + "4 7 8 J A |" + "3 7 8 J A |" + "2 7 8 J A |" + "5 6 8 J A |" + "4 6 8 J A |" + "3 6 8 J A |" + "2 6 8 J A |" + "4 5 8 J A |" + "3 5 8 J A |" + "2 5 8 J A |" + "3 4 8 J A |" + "2 4 8 J A |" + "2 3 8 J A |" + "5 6 7 J A |" + "4 6 7 J A |" + "3 6 7 J A |" + "2 6 7 J A |" + "4 5 7 J A |" + "3 5 7 J A |" + "2 5 7 J A |" + "3 4 7 J A |" + "2 4 7 J A |" + "2 3 7 J A |" + "4 5 6 J A |" + "3 5 6 J A |" + "2 5 6 J A |" + "3 4 6 J A |" + "2 4 6 J A |" + "2 3 6 J A |" + "3 4 5 J A |" + "2 4 5 J A |" + "2 3 5 J A |" + "2 3 4 J A |" + "7 8 9 T A |" + "6 8 9 T A |" + "5 8 9 T A |" + "4 8 9 T A |" + "3 8 9 T A |" + "2 8 9 T A |" + "6 7 9 T A |" + "5 7 9 T A |" + "4 7 9 T A |" + "3 7 9 T A |" + "2 7 9 T A |" + "5 6 9 T A |" + "4 6 9 T A |" + "3 6 9 T A |" + "2 6 9 T A |" + "4 5 9 T A |" + "3 5 9 T A |" + "2 5 9 T A |" + "3 4 9 T A |" + "2 4 9 T A |" + "2 3 9 T A |" + "6 7 8 T A |" + "5 7 8 T A |" + "4 7 8 T A |" + "3 7 8 T A |" + "2 7 8 T A |" + "5 6 8 T A |" + "4 6 8 T A |" + "3 6 8 T A |" + "2 6 8 T A |" + "4 5 8 T A |" + "3 5 8 T A |" + "2 5 8 T A |" + "3 4 8 T A |" + "2 4 8 T A |" + "2 3 8 T A |" + "5 6 7 T A |" + "4 6 7 T A |" + "3 6 7 T A |" + "2 6 7 T A |" + "4 5 7 T A |" + "3 5 7 T A |" + "2 5 7 T A |" + "3 4 7 T A |" + "2 4 7 T A |" + "2 3 7 T A |" + "4 5 6 T A |" + "3 5 6 T A |" + "2 5 6 T A |" + "3 4 6 T A |" + "2 4 6 T A |" + "2 3 6 T A |" + "3 4 5 T A |" + "2 4 5 T A |" + "2 3 5 T A |" + "2 3 4 T A |" + "6 7 8 9 A |" + "5 7 8 9 A |" + "4 7 8 9 A |" + "3 7 8 9 A |" + "2 7 8 9 A |" + "5 6 8 9 A |" + "4 6 8 9 A |" + "3 6 8 9 A |" + "2 6 8 9 A |" + "4 5 8 9 A |" + "3 5 8 9 A |" + "2 5 8 9 A |" + "3 4 8 9 A |" + "2 4 8 9 A |" + "2 3 8 9 A |" + "5 6 7 9 A |" + "4 6 7 9 A |" + "3 6 7 9 A |" + "2 6 7 9 A |" + "4 5 7 9 A |" + "3 5 7 9 A |" + "2 5 7 9 A |" + "3 4 7 9 A |" + "2 4 7 9 A |" + "2 3 7 9 A |" + "4 5 6 9 A |" + "3 5 6 9 A |" + "2 5 6 9 A |" + "3 4 6 9 A |" + "2 4 6 9 A |" + "2 3 6 9 A |" + "3 4 5 9 A |" + "2 4 5 9 A |" + "2 3 5 9 A |" + "2 3 4 9 A |" + "5 6 7 8 A |" + "4 6 7 8 A |" + "3 6 7 8 A |" + "2 6 7 8 A |" + "4 5 7 8 A |" + "3 5 7 8 A |" + "2 5 7 8 A |" + "3 4 7 8 A |" + "2 4 7 8 A |" + "2 3 7 8 A |" + "4 5 6 8 A |" + "3 5 6 8 A |" + "2 5 6 8 A |" + "3 4 6 8 A |" + "2 4 6 8 A |" + "2 3 6 8 A |" + "3 4 5 8 A |" + "2 4 5 8 A |" + "2 3 5 8 A |" + "2 3 4 8 A |" + "4 5 6 7 A |" + "3 5 6 7 A |" + "2 5 6 7 A |" + "3 4 6 7 A |" + "2 4 6 7 A |" + "2 3 6 7 A |" + "3 4 5 7 A |" + "2 4 5 7 A |" + "2 3 5 7 A |" + "2 3 4 7 A |" + "3 4 5 6 A |" + "2 4 5 6 A |" + "2 3 5 6 A |" + "2 3 4 6 A |" + "8 T J Q K |" + "7 T J Q K |" + "6 T J Q K |" + "5 T J Q K |" + "4 T J Q K |" + "3 T J Q K |" + "2 T J Q K |" + "8 9 J Q K |" + "7 9 J Q K |" + "6 9 J Q K |" + "5 9 J Q K |" + "4 9 J Q K |" + "3 9 J Q K |" + "2 9 J Q K |" + "7 8 J Q K |" + "6 8 J Q K |" + "5 8 J Q K |" + "4 8 J Q K |" + "3 8 J Q K |" + "2 8 J Q K |" + "6 7 J Q K |" + "5 7 J Q K |" + "4 7 J Q K |" + "3 7 J Q K |" + "2 7 J Q K |" + "5 6 J Q K |" + "4 6 J Q K |" + "3 6 J Q K |" + "2 6 J Q K |" + "4 5 J Q K |" + "3 5 J Q K |" + "2 5 J Q K |" + "3 4 J Q K |" + "2 4 J Q K |" + "2 3 J Q K |" + "8 9 T Q K |" + "7 9 T Q K |" + "6 9 T Q K |" + "5 9 T Q K |" + "4 9 T Q K |" + "3 9 T Q K |" + "2 9 T Q K |" + "7 8 T Q K |" + "6 8 T Q K |" + "5 8 T Q K |" + "4 8 T Q K |" + "3 8 T Q K |" + "2 8 T Q K |" + "6 7 T Q K |" + "5 7 T Q K |" + "4 7 T Q K |" + "3 7 T Q K |" + "2 7 T Q K |" + "5 6 T Q K |" + "4 6 T Q K |" + "3 6 T Q K |" + "2 6 T Q K |" + "4 5 T Q K |" + "3 5 T Q K |" + "2 5 T Q K |" + "3 4 T Q K |" + "2 4 T Q K |" + "2 3 T Q K |" + "7 8 9 Q K |" + "6 8 9 Q K |" + "5 8 9 Q K |" + "4 8 9 Q K |" + "3 8 9 Q K |" + "2 8 9 Q K |" + "6 7 9 Q K |" + "5 7 9 Q K |" + "4 7 9 Q K |" + "3 7 9 Q K |" + "2 7 9 Q K |" + "5 6 9 Q K |" + "4 6 9 Q K |" + "3 6 9 Q K |" + "2 6 9 Q K |" + "4 5 9 Q K |" + "3 5 9 Q K |" + "2 5 9 Q K |" + "3 4 9 Q K |" + "2 4 9 Q K |" + "2 3 9 Q K |" + "6 7 8 Q K |" + "5 7 8 Q K |" + "4 7 8 Q K |" + "3 7 8 Q K |" + "2 7 8 Q K |" + "5 6 8 Q K |" + "4 6 8 Q K |" + "3 6 8 Q K |" + "2 6 8 Q K |" + "4 5 8 Q K |" + "3 5 8 Q K |" + "2 5 8 Q K |" + "3 4 8 Q K |" + "2 4 8 Q K |" + "2 3 8 Q K |" + "5 6 7 Q K |" + "4 6 7 Q K |" + "3 6 7 Q K |" + "2 6 7 Q K |" + "4 5 7 Q K |" + "3 5 7 Q K |" + "2 5 7 Q K |" + "3 4 7 Q K |" + "2 4 7 Q K |" + "2 3 7 Q K |" + "4 5 6 Q K |" + "3 5 6 Q K |" + "2 5 6 Q K |" + "3 4 6 Q K |" + "2 4 6 Q K |" + "2 3 6 Q K |" + "3 4 5 Q K |" + "2 4 5 Q K |" + "2 3 5 Q K |" + "2 3 4 Q K |" + "8 9 T J K |" + "7 9 T J K |" + "6 9 T J K |" + "5 9 T J K |" + "4 9 T J K |" + "3 9 T J K |" + "2 9 T J K |" + "7 8 T J K |" + "6 8 T J K |" + "5 8 T J K |" + "4 8 T J K |" + "3 8 T J K |" + "2 8 T J K |" + "6 7 T J K |" + "5 7 T J K |" + "4 7 T J K |" + "3 7 T J K |" + "2 7 T J K |" + "5 6 T J K |" + "4 6 T J K |" + "3 6 T J K |" + "2 6 T J K |" + "4 5 T J K |" + "3 5 T J K |" + "2 5 T J K |" + "3 4 T J K |" + "2 4 T J K |" + "2 3 T J K |" + "7 8 9 J K |" + "6 8 9 J K |" + "5 8 9 J K |" + "4 8 9 J K |" + "3 8 9 J K |" + "2 8 9 J K |" + "6 7 9 J K |" + "5 7 9 J K |" + "4 7 9 J K |" + "3 7 9 J K |" + "2 7 9 J K |" + "5 6 9 J K |" + "4 6 9 J K |" + "3 6 9 J K |" + "2 6 9 J K |" + "4 5 9 J K |" + "3 5 9 J K |" + "2 5 9 J K |" + "3 4 9 J K |" + "2 4 9 J K |" + "2 3 9 J K |" + "6 7 8 J K |" + "5 7 8 J K |" + "4 7 8 J K |" + "3 7 8 J K |" + "2 7 8 J K |" + "5 6 8 J K |" + "4 6 8 J K |" + "3 6 8 J K |" + "2 6 8 J K |" + "4 5 8 J K |" + "3 5 8 J K |" + "2 5 8 J K |" + "3 4 8 J K |" + "2 4 8 J K |" + "2 3 8 J K |" + "5 6 7 J K |" + "4 6 7 J K |" + "3 6 7 J K |" + "2 6 7 J K |" + "4 5 7 J K |" + "3 5 7 J K |" + "2 5 7 J K |" + "3 4 7 J K |" + "2 4 7 J K |" + "2 3 7 J K |" + "4 5 6 J K |" + "3 5 6 J K |" + "2 5 6 J K |" + "3 4 6 J K |" + "2 4 6 J K |" + "2 3 6 J K |" + "3 4 5 J K |" + "2 4 5 J K |" + "2 3 5 J K |" + "2 3 4 J K |" + "7 8 9 T K |" + "6 8 9 T K |" + "5 8 9 T K |" + "4 8 9 T K |" + "3 8 9 T K |" + "2 8 9 T K |" + "6 7 9 T K |" + "5 7 9 T K |" + "4 7 9 T K |" + "3 7 9 T K |" + "2 7 9 T K |" + "5 6 9 T K |" + "4 6 9 T K |" + "3 6 9 T K |" + "2 6 9 T K |" + "4 5 9 T K |" + "3 5 9 T K |" + "2 5 9 T K |" + "3 4 9 T K |" + "2 4 9 T K |" + "2 3 9 T K |" + "6 7 8 T K |" + "5 7 8 T K |" + "4 7 8 T K |" + "3 7 8 T K |" + "2 7 8 T K |" + "5 6 8 T K |" + "4 6 8 T K |" + "3 6 8 T K |" + "2 6 8 T K |" + "4 5 8 T K |" + "3 5 8 T K |" + "2 5 8 T K |" + "3 4 8 T K |" + "2 4 8 T K |" + "2 3 8 T K |" + "5 6 7 T K |" + "4 6 7 T K |" + "3 6 7 T K |" + "2 6 7 T K |" + "4 5 7 T K |" + "3 5 7 T K |" + "2 5 7 T K |" + "3 4 7 T K |" + "2 4 7 T K |" + "2 3 7 T K |" + "4 5 6 T K |" + "3 5 6 T K |" + "2 5 6 T K |" + "3 4 6 T K |" + "2 4 6 T K |" + "2 3 6 T K |" + "3 4 5 T K |" + "2 4 5 T K |" + "2 3 5 T K |" + "2 3 4 T K |" + "6 7 8 9 K |" + "5 7 8 9 K |" + "4 7 8 9 K |" + "3 7 8 9 K |" + "2 7 8 9 K |" + "5 6 8 9 K |" + "4 6 8 9 K |" + "3 6 8 9 K |" + "2 6 8 9 K |" + "4 5 8 9 K |" + "3 5 8 9 K |" + "2 5 8 9 K |" + "3 4 8 9 K |" + "2 4 8 9 K |" + "2 3 8 9 K |" + "5 6 7 9 K |" + "4 6 7 9 K |" + "3 6 7 9 K |" + "2 6 7 9 K |" + "4 5 7 9 K |" + "3 5 7 9 K |" + "2 5 7 9 K |" + "3 4 7 9 K |" + "2 4 7 9 K |" + "2 3 7 9 K |" + "4 5 6 9 K |" + "3 5 6 9 K |" + "2 5 6 9 K |" + "3 4 6 9 K |" + "2 4 6 9 K |" + "2 3 6 9 K |" + "3 4 5 9 K |" + "2 4 5 9 K |" + "2 3 5 9 K |" + "2 3 4 9 K |" + "5 6 7 8 K |" + "4 6 7 8 K |" + "3 6 7 8 K |" + "2 6 7 8 K |" + "4 5 7 8 K |" + "3 5 7 8 K |" + "2 5 7 8 K |" + "3 4 7 8 K |" + "2 4 7 8 K |" + "2 3 7 8 K |" + "4 5 6 8 K |" + "3 5 6 8 K |" + "2 5 6 8 K |" + "3 4 6 8 K |" + "2 4 6 8 K |" + "2 3 6 8 K |" + "3 4 5 8 K |" + "2 4 5 8 K |" + "2 3 5 8 K |" + "2 3 4 8 K |" + "4 5 6 7 K |" + "3 5 6 7 K |" + "2 5 6 7 K |" + "3 4 6 7 K |" + "2 4 6 7 K |" + "2 3 6 7 K |" + "3 4 5 7 K |" + "2 4 5 7 K |" + "2 3 5 7 K |" + "2 3 4 7 K |" + "3 4 5 6 K |" + "2 4 5 6 K |" + "2 3 5 6 K |" + "2 3 4 6 K |" + "2 3 4 5 K |" + "7 9 T J Q |" + "6 9 T J Q |" + "5 9 T J Q |" + "4 9 T J Q |" + "3 9 T J Q |" + "2 9 T J Q |" + "7 8 T J Q |" + "6 8 T J Q |" + "5 8 T J Q |" + "4 8 T J Q |" + "3 8 T J Q |" + "2 8 T J Q |" + "6 7 T J Q |" + "5 7 T J Q |" + "4 7 T J Q |" + "3 7 T J Q |" + "2 7 T J Q |" + "5 6 T J Q |" + "4 6 T J Q |" + "3 6 T J Q |" + "2 6 T J Q |" + "4 5 T J Q |" + "3 5 T J Q |" + "2 5 T J Q |" + "3 4 T J Q |" + "2 4 T J Q |" + "2 3 T J Q |" + "7 8 9 J Q |" + "6 8 9 J Q |" + "5 8 9 J Q |" + "4 8 9 J Q |" + "3 8 9 J Q |" + "2 8 9 J Q |" + "6 7 9 J Q |" + "5 7 9 J Q |" + "4 7 9 J Q |" + "3 7 9 J Q |" + "2 7 9 J Q |" + "5 6 9 J Q |" + "4 6 9 J Q |" + "3 6 9 J Q |" + "2 6 9 J Q |" + "4 5 9 J Q |" + "3 5 9 J Q |" + "2 5 9 J Q |" + "3 4 9 J Q |" + "2 4 9 J Q |" + "2 3 9 J Q |" + "6 7 8 J Q |" + "5 7 8 J Q |" + "4 7 8 J Q |" + "3 7 8 J Q |" + "2 7 8 J Q |" + "5 6 8 J Q |" + "4 6 8 J Q |" + "3 6 8 J Q |" + "2 6 8 J Q |" + "4 5 8 J Q |" + "3 5 8 J Q |" + "2 5 8 J Q |" + "3 4 8 J Q |" + "2 4 8 J Q |" + "2 3 8 J Q |" + "5 6 7 J Q |" + "4 6 7 J Q |" + "3 6 7 J Q |" + "2 6 7 J Q |" + "4 5 7 J Q |" + "3 5 7 J Q |" + "2 5 7 J Q |" + "3 4 7 J Q |" + "2 4 7 J Q |" + "2 3 7 J Q |" + "4 5 6 J Q |" + "3 5 6 J Q |" + "2 5 6 J Q |" + "3 4 6 J Q |" + "2 4 6 J Q |" + "2 3 6 J Q |" + "3 4 5 J Q |" + "2 4 5 J Q |" + "2 3 5 J Q |" + "2 3 4 J Q |" + "7 8 9 T Q |" + "6 8 9 T Q |" + "5 8 9 T Q |" + "4 8 9 T Q |" + "3 8 9 T Q |" + "2 8 9 T Q |" + "6 7 9 T Q |" + "5 7 9 T Q" array := strings.Split(s, " |") var oldValue uint32 for _, v := range array { cards := &Cards{} cards.SetByString(v) //t.Log(cards.String()) k, value := De(cards.GetType()) if oldValue == 0 { oldValue = value continue } assert.Equal(t, oldValue > value, true) assert.Equal(t, k, FLUSH) //assert.Equal(t,v,uint32(6)) //t.Log(De(cards.FullFouse(cards.Counter()))) } } ================================================ FILE: src/server/algorithm/pk.go ================================================ package algorithm func (this *Cards) Counter() *ValueCounter { var counter ValueCounter counter.Set(*this) return &counter } func (this *Cards) GetType() uint32 { if len(*this) == 0 { return 0 } counter := this.Counter() ASort(*this, 0, int8(len(*this))-1, counter) if res := this.royalFlush(); res > 0 { return res } if res := this.straightFlush(); res > 0 { return res } if res := this.four(counter); res > 0 { return res } if res := this.fullFouse(counter); res > 0 { return res } if res := this.flush(); res > 0 { return res } if res := this.straight(); res > 0 { return res } if res := this.three(counter); res > 0 { return res } if res := this.twoPair(); res > 0 { return res } if res := this.onePair(); res > 0 { return res } //高牌(high card) //既不是同一花色也不是同一点数的五张牌组成。 //平手牌:如果不止一人抓到此牌,则比较点数最大者, //如果点数最大的相同,则比较第二、第三、第四和第五大的,如果所有牌都相同,则平分彩池。 return En(HIGH_CARD, ToValue(*this)) } ================================================ FILE: src/server/algorithm/sort.go ================================================ package algorithm // 对牌值从小到大排序,采用快速排序算法 func SortCards(arr []byte, start, end int8) { if start < end { i, j := start, end card := arr[(start+end)/2] key := card & 0xF suit := card >> 4 for i <= j { for (arr[i])&0xF < key || ((arr[i])&0xF == key && arr[i]>>4 < suit) { i++ } for (arr[j])&0xF > key || ((arr[j])&0xF == key && arr[j]>>4 > suit) { j-- } if i <= j { arr[i], arr[j] = arr[j], arr[i] i++ j-- } } if start < j { SortCards(arr, start, j) } if end > i { SortCards(arr, i, end) } } } func Sort(cards []byte, start, end int8) { if start < end { i, j := start, end card := cards[(start+end)/2] for i <= j { for cards[i] < card { i++ } for cards[j] > card { j-- } if i <= j { cards[i], cards[j] = cards[j], cards[i] i++ j-- } } if start < j { Sort(cards, start, j) } if end > i { Sort(cards, i, end) } } } type ColorCounter uint16 func (this *ColorCounter) Set(cards []byte) { //*this = 0 l := uint8(len(cards)) for i := uint8(0); i < l; i++ { card := (cards[i] >> 4) * 3 count := ((*this >> card) & 0x07) + 1 *this &= (^(0x07 << card)) *this |= (count << card) } } func (this *ColorCounter) Get(card byte) uint8 { return uint8((*this >> (card >> 4) * 3 ) & 0x07) } type ValueCounter uint64 func (this *ValueCounter) Set(cards []byte) { //*this = 0 l := uint8(len(cards)) for i := uint8(0); i < l; i++ { card := (cards[i] & 0xF) * 3 count := ((*this >> card) & 0x07) + 1 *this &= (^(0x07 << card)) *this |= (count << card) } } func (this *ValueCounter) Get(card byte) uint8 { return uint8((*this >> (card & 0xF * 3 )) & 0x07) } func ASort(arr []byte, start, end int8, counter *ValueCounter) { if start < end { i, j := start, end card := arr[(start+end)/2] key := card & 0xF count := counter.Get(key) for i <= j { for (counter.Get(arr[i]&0xF) < count) || ((counter.Get(arr[i]&0xF) == count) && (arr[i])&0xF < key ) { i++ } for (counter.Get(arr[j]&0xF) > count) || ((counter.Get(arr[j]&0xF) == count) && (arr[j])&0xF > key ) { j-- } if i <= j { arr[i], arr[j] = arr[j], arr[i] i++ j-- } } if start < j { ASort(arr, start, j, counter) } if end > i { ASort(arr, i, end, counter) } } } ================================================ FILE: src/server/algorithm/sort_test.go ================================================ package algorithm import "testing" func Test11Base(t *testing.T) { cards := Cards{0x12, 0x03, 0x24, 0x35, 0x26, 0x17, 0x33} var a ValueCounter a.Set(cards) ASort(cards, 0, int8(len(cards) -1), &a) t.Logf("%#v ",cards) } func Test10Base(t *testing.T) { arr := Cards([]byte{1, 2, 3, 4, 4, 5, 6}) arr.Shuffle() t.Logf("%#v ", arr) t.Logf("%#v ", arr) } ================================================ FILE: src/server/algorithm/tostring.go ================================================ package algorithm import ( "strings" "fmt" ) func (this *Cards) Bytes() []byte { b := make([]byte, len(*this)) for k, v := range *this { b[k] = byte(v) } return b } func (this *Cards) Len() int { return len(*this) } func (this *Cards) Take() byte { card := (*this)[0] (*this) = (*this)[1:] return card } func (this *Cards) Append(cards ...byte) Cards { cs := make([]byte, 0, len(cards)+len(*this)) cs = append(cs, (*this)...) cs = append(cs, cards...) return cs } func (this *Cards) Equal(cards []byte) bool { if len(*this) != len(cards) { return false } for k, v := range *this { if cards[k] != v { return false } } return true } func Color(color byte) (char string) { switch color { case 0: char = "♦" case 1: char = "♣" case 2: char = "♥" case 3: char = "♠" } return } func String2Num(c byte) (n byte) { switch c { case '2': n = 2 case '3': n = 3 case '4': n = 4 case '5': n = 5 case '6': n = 6 case '7': n = 7 case '8': n = 8 case '9': n = 9 case 'T': n = 0xA case 'J': n = 0xB case 'Q': n = 0xC case 'K': n = 0xD case 'A': n = 0xE } return } func Num2String(n byte) (c byte) { switch n { case 2: c = '2' case 3: c = '3' case 4: c = '4' case 5: c = '5' case 6: c = '6' case 7: c = '7' case 8: c = '8' case 9: c = '9' case 0xA: c = 'T' case 0xB: c = 'J' case 0xC: c = 'Q' case 0xD: c = 'K' case 0xE: c = 'A' } return } func (this *Cards) SetByString(str string) { array := strings.Split(str, " ") *this = make([]byte, len(array)) for k, v := range array { (*this)[k] = String2Num(byte(v[0])) } } func (this *Cards) String() (str string) { for k, v := range *this { color := Color(v) value := Num2String(v) str += string(color) + string(value) if k < len(*this)-1 { str += " " } } return } func (this *Cards) Hex() string { return fmt.Sprintf("%#v", *this) } ================================================ FILE: src/server/base/skeleton.go ================================================ package base import ( "github.com/dolotech/leaf/chanrpc" "github.com/dolotech/leaf/module" "server/conf" ) func NewSkeleton() *module.Skeleton { skeleton := &module.Skeleton{ GoLen: conf.GoLen, TimerDispatcherLen: conf.TimerDispatcherLen, AsynCallLen: conf.AsynCallLen, ChanRPCServer: chanrpc.NewServer(conf.ChanRPCLen), } skeleton.Init() return skeleton } ================================================ FILE: src/server/conf/conf.go ================================================ package conf import ( "log" "time" ) var ( // glog conf LogFlag = log.LstdFlags // gate conf PendingWriteNum = 2000 MaxMsgLen uint32 = 4096 HTTPTimeout = 10 * time.Second LenMsgLen = 2 LittleEndian = false // skeleton conf GoLen = 10000 TimerDispatcherLen = 10000 AsynCallLen = 10000 ChanRPCLen = 10000 ) var Server struct { WSAddr string CertFile string KeyFile string TCPAddr string MaxConnNum int DBMaxConnNum int DBUrl string } ================================================ FILE: src/server/game/external.go ================================================ package game import ( "server/game/internal" ) var ( Module = new(internal.Module)//建立模块新的 ChanRPC = internal.ChanRPC ) ================================================ FILE: src/server/game/internal/chanrpc.go ================================================ package internal import ( "github.com/dolotech/leaf/gate" "github.com/golang/glog" "server/model" "github.com/dolotech/leaf/room" ) func init() { skeleton.RegisterChanRPC(model.Agent_New, rpcNewAgent) skeleton.RegisterChanRPC(model.Agent_Close, rpcCloseAgent) skeleton.RegisterChanRPC(model.Agent_Login, rpcLoginAgent) } func rpcNewAgent(a gate.Agent) { glog.Errorln("新建链接 ", a) } func rpcCloseAgent(a gate.Agent) { glog.Errorln("链接关闭 ", a) } func rpcLoginAgent(u *model.User, a gate.Agent) { o := NewOccupant(u, a) a.SetUserData(o) if len(u.RoomID) > 0 { o.room = room.GetRoom(u.RoomID) } glog.Errorln("rpcLoginAgent", u) } ================================================ FILE: src/server/game/internal/game_rule.go ================================================ package internal import ( "github.com/golang/glog" "server/protocol" "server/model" "server/algorithm" "time" "github.com/dolotech/lib/utils" ) func (r *Room) startDelay(startDelay *startDelay, o *Occupant) { if startDelay.kind == 0 { r.Info() r.start() } } func (r *Room) start() { if r.status == RUNNING { return } // 产生庄 var dealer *Occupant button := r.Button - 1 r.Each((button+1)%r.Cap(), func(o *Occupant) bool { r.Button = o.Pos dealer = o return false }) if dealer == nil { return } r.remain = 0 r.allin = 0 // 剔除筹码小于大盲和离线的玩家 n := 0 r.Each(0, func(o *Occupant) bool { if o.chips < r.BB || o.IsOffline() { o.SetSitdown() return true } o.SetGameing() n ++ return true }) // 2人及以上才开始游戏 if n < 2 { return } r.status = RUNNING // 洗牌 r.Cards.Shuffle() // 产生小盲 sb := r.next(dealer.Pos) if n == 2 { // one-to-one sb = dealer } // 产生大盲 bb := r.next(sb.Pos) bbPos := bb.Pos // 通报本局庄家 r.WriteMsg(&protocol.Button{Uid: dealer.Uid}) // 小大盲下注 r.betting(sb, int32(r.SB)) r.betting(bb, int32(r.BB)) // Round 1 : preflop r.ready() r.Each(0, func(o *Occupant) bool { o.cards = algorithm.Cards{r.Cards.Take(), r.Cards.Take()} kind, _ := algorithm.De(o.cards.GetType()) m := &protocol.PreFlop{ Cards: o.cards.Bytes(), Kind: kind, } o.WriteMsg(m) return true }) r.Broadcast(&protocol.PreFlop{}, false) r.action(0) if r.remain <= 1 { goto showdown } r.calc() // Round 2 : Flop r.ready() r.Cards = algorithm.Cards{r.Cards.Take(), r.Cards.Take(), r.Cards.Take()} r.Each(0, func(o *Occupant) bool { cs := r.Cards.Append(o.cards...) kind, _ := algorithm.De(cs.GetType()) m := &protocol.Flop{ Cards: cs.Bytes(), Kind: kind, } o.WriteMsg(m) return true }) r.Broadcast(&protocol.Flop{Cards: r.Cards.Bytes()}, false) r.action(0) if r.remain <= 1 { goto showdown } r.calc() // Round 3 : Turn r.ready() r.Cards = r.Cards.Append(r.Cards.Take()) r.Each(0, func(o *Occupant) bool { cs := r.Cards.Append(o.cards...) kind, _ := algorithm.De(cs.GetType()) m := &protocol.Turn{ Card: r.Cards[3], Kind: kind, } o.WriteMsg(m) return true }) r.Broadcast(&protocol.Turn{Card: r.Cards[3]}, false) r.action(0) if r.remain <= 1 { goto showdown } r.calc() // Round 4 : River r.ready() r.Cards = r.Cards.Append(r.Cards.Take()) r.Each(0, func(o *Occupant) bool { cs := r.Cards.Append(o.cards...) value := cs.GetType() kind, _ := algorithm.De(value) m := &protocol.River{ Card: r.Cards[4], Kind: kind, } o.WriteMsg(m) o.HandValue = value return true }) r.Broadcast(&protocol.River{Card: r.Cards[4]}, false) r.action(0) showdown: r.showdown() showdown := &protocol.Showdown{} for _, o := range r.Occupants { if o != nil && o.IsGameing() { o.SetSitdown() item := &protocol.ShowdownItem{ Uid: o.Uid, ChipsWin: r.Chips[o.Pos-1], Chips: o.chips, } showdown.Showdown = append(showdown.Showdown, item) } } r.Broadcast(showdown, true) r.Info(sb.Pos, bbPos) r.status = GAMEOVER time.AfterFunc(time.Second*2, func() { defer utils.PrintPanicStack() r.Send(nil, &startDelay{}) }) } func (r *Room) calc() (pots []handPot) { pots = calcPot(r.Chips) r.Pot = r.Pot[:] var ps []uint32 for _, pot := range pots { r.Pot = append(r.Pot, pot.Pot) ps = append(ps, pot.Pot) } r.Broadcast(&protocol.Pot{Pot: ps}, true) return } func (r *Room) action(pos uint8) { if r.allin+1 >= r.remain { return } var skip uint8 if pos == 0 { // start from left hand of button pos = (r.Button)%r.Cap() + 1 } for { var raised uint8 r.Each(pos-1, func(o *Occupant) bool { if r.remain <= 1 { return false } if o.Pos == skip || o.chips == 0 { return true } r.WriteMsg(&protocol.BetPrompt{}) n := o.GetAction(r.Timeout) if r.remain <= 1 { return false } if r.betting(o, n) { raised = o.Pos return false } return true }) if raised == 0 { break } pos = raised skip = pos } } func (r *Room) ready() { r.Bet = 0 r.Each(0, func(o *Occupant) bool { o.Bet = 0 o.waitAction = false r.remain++ o.HandValue = 0 return true }) } // 比牌 func (r *Room) showdown() { pots := r.calc() for i, _ := range r.Chips { r.Chips[i] = 0 } for _, pot := range pots { var maxO *Occupant for _, pos := range pot.OPos { o := r.Occupants[pos-1] if o != nil && len(o.cards) > 0 { if maxO == nil { maxO = o continue } if o.HandValue > maxO.HandValue { maxO = o } } } var winners []uint8 for _, pos := range pot.OPos { o := r.Occupants[pos-1] if o != nil && o.HandValue == maxO.HandValue && o.IsGameing() { winners = append(winners, o.Pos) } } if len(winners) == 0 { glog.Errorln("!!!no winners!!!") return } for _, winner := range winners { r.Chips[winner-1] += pot.Pot / uint32(len(winners)) } r.Chips[winners[0]-1] += pot.Pot % uint32(len(winners)) // odd chips } for i, _ := range r.Chips { if r.Occupants[i] != nil { r.Occupants[i].chips += r.Chips[i] } } } func (r *Room) betting(o *Occupant, n int32) (raised bool) { if n > int32(o.chips) || // 手上筹码不足 (n == 0 && o.Bet != r.Bet) || // 让牌 (n > 0 && n != int32(o.chips) && ((n + int32(o.Bet)) < int32(r.Bet))) { glog.Errorf("下注筹码不合法!!! n:%d p.Bet:%d p.Chips:%d t.Bet:%d", n, o.Bet, o.chips, r.Bet) return } value := n actionName := "" if n < 0 { actionName = model.BET_FOLD n = 0 r.remain-- o.SetSitdown() } else if n == 0 { actionName = model.BET_CHECK } else if uint32(n)+o.Bet <= r.Bet { actionName = model.BET_CALL o.chips -= uint32(n) o.Bet += uint32(n) } else { actionName = model.BET_RAISE o.chips -= uint32(n) o.Bet += uint32(n) r.Bet = o.Bet raised = true } if o.chips == 0 { r.allin++ actionName = model.BET_ALLIN } r.Chips[o.Pos-1] += uint32(n) r.Broadcast(&protocol.BetBroadcast{ Uid: o.Uid, Kind: actionName, Value: value, }, true) return } func (r *Room) next(pos uint8) *Occupant { volume := r.Cap() for i := (pos) % volume; i != pos-1; i = (i + 1) % volume { if r.Occupants[i] != nil && r.Occupants[i].IsGameing() { return r.Occupants[i] } } return nil } ================================================ FILE: src/server/game/internal/module.go ================================================ package internal import ( "github.com/dolotech/leaf/module" "server/base" "github.com/golang/glog" "server/protocol" "github.com/dolotech/leaf/room" "reflect" "server/model" ) var ( skeleton = base.NewSkeleton() ChanRPC = skeleton.ChanRPCServer ) func handler(m interface{}, h interface{}) { skeleton.RegisterChanRPC(reflect.TypeOf(m), h) } func init() { handler(&protocol.JoinRoom{}, room.OnMessage) handler(&protocol.LeaveRoom{}, room.OnMessage) handler(&protocol.Bet{}, room.OnMessage) handler(&protocol.SitDown{}, room.OnMessage) // handler(&protocol.StandUp{}, room.OnMessage) // handler(&protocol.Chat{}, room.OnMessage) // } type Module struct { *module.Skeleton } func (m *Module) OnInit() { m.Skeleton = skeleton room.Init(&Creator{}) } func (m *Module) OnDestroy() { glog.Errorln("OnDestroy") } type Creator struct{} // 对玩家未进入房间,或者没房间数据的处理 func (this *Creator) Create(m interface{}) room.IRoom { if msg, ok := m.(*protocol.JoinRoom); ok { if len(msg.RoomNumber) == 0 { r := room.FindRoom() return r } r := room.GetRoom(msg.RoomNumber) if r != nil { return r } room := NewRoom(9, 5, 10, 1000, model.Timeout) room.Insert() return room } return nil } ================================================ FILE: src/server/game/internal/occupant.go ================================================ package internal import ( "server/model" "github.com/dolotech/leaf/gate" "server/algorithm" "time" "errors" "github.com/dolotech/leaf/room" ) type Occupant struct { *model.User gate.Agent room room.IRoom cards algorithm.Cards Pos uint8 // 玩家座位号,从1开始 status int32 // 1为离线状态 Bet uint32 // 当前下注 actions chan int32 waitAction bool chips uint32 // 带入的筹码 HandValue uint32 } const ( Occupant_status_InGame int32 = 3 Occupant_status_Offline int32 = 1 Occupant_status_Observe int32 = 2 Occupant_status_Sitdown int32 = 0 ) func (o *Occupant) GetRoom() room.IRoom { return o.room } func (o *Occupant) SetRoom(m room.IRoom) { o.room = m } func (o *Occupant) SetAction(n int32)error { if o.waitAction { o.actions <- n return nil } return errors.New("not your action") } func (o *Occupant) GetAction(timeout time.Duration) int32 { timer := time.NewTimer(timeout) o.waitAction = true select { case n := <-o.actions: timer.Stop() o.waitAction = false return n case <-o.room.Closed(): timer.Stop() o.waitAction = false return -1 case <-timer.C: o.waitAction = false timer.Stop() return -1 // 超时弃牌 } } func (o *Occupant)SetPos(pos uint8) { o.Pos = pos } func (o *Occupant) GetPos() uint8 { return o.Pos } func (o *Occupant) GetUid() uint32 { return o.Uid } func (o *Occupant) WriteMsg(msg interface{}) { if o.status != Occupant_status_Offline { o.Agent.WriteMsg(msg) } } func (o *Occupant) SetData(d interface{}) { o.User = d.(*model.User) } func (o *Occupant) GetId() uint32 { return o.Uid } func (o *Occupant) SetObserve() { o.status = Occupant_status_Observe } func (o *Occupant) IsObserve() bool { return o.status == Occupant_status_Observe } func (o *Occupant) SetOffline() { o.status = Occupant_status_Offline } func (o *Occupant) IsOffline() bool { return o.status == Occupant_status_Offline } func (o *Occupant) SetSitdown() { o.status = Occupant_status_Sitdown } func (o *Occupant) IsSitdown() bool { return o.status == Occupant_status_Sitdown } func (o *Occupant) SetGameing() { o.status = Occupant_status_InGame } func (o *Occupant) IsGameing() bool { return o.status == Occupant_status_InGame } func (o *Occupant) Replace(value *Occupant) { o.Pos = value.Pos o.cards = value.cards o.room = value.room } func NewOccupant(data *model.User, conn gate.Agent) *Occupant { o := &Occupant{ User: data, Agent: conn, actions: make(chan int32), } return o } ================================================ FILE: src/server/game/internal/pot.go ================================================ package internal import ( "sort" ) type handBet struct { Pos uint8 Bet uint32 } type handBets []handBet func (p handBets) Len() int { return len(p) } func (p handBets) Less(i, j int) bool { return p[i].Bet < p[j].Bet } func (p handBets) Swap(i, j int) { p[i], p[j] = p[j], p[i] } type handPot struct { Pot uint32 OPos []uint32 } //因为每个人手中的筹码量会不时的产生变化,当出现多个筹码量不等的玩家“全下(ALL-IN)”争夺底池的时候就会出现多个奖池, //这时候底池将分出主池和边池,主池里的筹码可 由任何一位争夺者胜利后将其拿走,其后每个边池将分别由参与者按牌型大小分别拿走。 //举个例子,假如发到河牌后共有三个人争夺底池,三人分别用ABC代替, //假设A玩家手中有60,B手中有80,C手中有100。三人ALL-IN后则先把每人的筹码划分成: //A玩家60;B玩家60+20;C玩家60+20+20,然后分出底池: //主池 由60乘以三个人(A+B+C)形成一个堆,总额为180; //边池一 由20乘以剩下的两个人(B+C)多出的部分为一个堆,总额为40; //边池二 由筹码最多者C的多出的部分20单独组成一个堆,总额为20。 //现在三个底池形成了,然后分别按照牌型的大小来决定谁拿走哪个底池…… //首先,主池可以由三人中的任何一人得到胜利都可以拿走; // 但是边池一的争夺就只能在B与C之间产生,两人谁赢谁拿走,与A无关(就算A玩家的牌最大也只能拿走他参与的主池)。 //而最后剩下的边池二不论三人谁输谁赢都只能由C拿走,因为边池二里的筹码只有C自己参与了,与其他人无关。 func calcPot(bets []uint32) (pots []handPot) { var obs handBets for i, bet := range bets { if bet > 0 { obs = append(obs, handBet{Pos: uint8(i) + 1, Bet: bet}) } } sort.Sort(obs) for i, ob := range obs { if ob.Bet > 0 { s := obs[i:] hpot := handPot{Pot: ob.Bet * uint32(len(s))} for j, _ := range s { s[j].Bet -= ob.Bet hpot.OPos = append(hpot.OPos, uint32(s[j].Pos)) } pots = append(pots, hpot) } } return } ================================================ FILE: src/server/game/internal/pot_test.go ================================================ package internal import "testing" func Test_Pot(t *testing.T) { bets := []uint32{60,80,90,0,0,0,0,0,0} res:=calcPot(bets) //[{180 [1 2 3]} {40 [2 3]} {10 [3]}] t.Log(res) bets = []uint32{60,60,60,0,0,0,0,0,0} res=calcPot(bets) //[{180 [1 2 3]}] t.Log(res) a:= []byte{} a = nil t.Log(len(a)) } ================================================ FILE: src/server/game/internal/room.go ================================================ package internal import ( "server/model" "server/protocol" "server/algorithm" "time" "github.com/dolotech/leaf/room" "github.com/golang/glog" ) const ( RUNNING uint8= 1 GAMEOVER uint8= 0 ) type Room struct { *model.Room *room.MsgLoop *room.Log Occupants []*Occupant observes []*Occupant // 站起的玩家 AutoSitdown []*Occupant // 自动坐下队列 remain int allin int n uint8 status uint8 SB uint32 // 小盲注 BB uint32 // 大盲注 Cards algorithm.Cards // 公共牌 Pot []uint32 // 奖池筹码数, 第一项为主池,其他项(若存在)为边池 Timeout time.Duration // 倒计时超时时间(秒) Button uint8 // 当前庄家座位号,从1开始 Chips []uint32 // 玩家本局下注的总筹码数,与occupants一一对应 Bet uint32 // 当前回合 上一玩家下注额 Max uint8 // 房间最大玩家人数 MaxChips uint32 MinChips uint32 } func NewRoom(max uint8, sb, bb uint32, chips uint32, timeout uint8) *Room { if max <= 0 || max > 9 { max = 9 // default 9 Occupants } r := &Room{ Room: &model.Room{DraginChips: chips,}, MsgLoop: room.NewMsgLoop(), Chips: make([]uint32, max), Occupants: make([]*Occupant, max), Pot: make([]uint32, 0, max), Timeout: time.Second * time.Duration(timeout), SB: sb, BB: bb, Max: max, } r.Log = room.NewLog(r) r.Regist(&protocol.JoinRoom{}, r.joinRoom) r.Regist(&protocol.LeaveRoom{}, r.leaveRoom) r.Regist(&protocol.Bet{}, r.bet) r.Regist(&protocol.SitDown{}, r.sitDown) // r.Regist(&protocol.StandUp{}, r.standUp) // r.Regist(&protocol.Chat{}, r.chat) // r.Regist(&protocol.Chat{}, r.chat) // r.Regist(&startDelay{}, r.startDelay) // return r } type startDelay struct { kind uint8 } func (r *Room) New(m interface{}) room.IRoom { glog.Errorln(r, m) if msg, ok := m.(*protocol.JoinRoom); ok { if len(msg.RoomNumber) == 0 { r := room.FindRoom() return r } r := room.GetRoom(msg.RoomNumber) if r != nil { return r } room := NewRoom(9, 5, 10, 1000, model.Timeout) room.Insert() return room } return nil } func (r *Room) WriteMsg(msg interface{}, exc ...uint32) { for _, v := range r.Occupants { if v != nil { for _, uid := range exc { if uid == v.GetUid() { goto End } } v.WriteMsg(msg) } End: } } func (r *Room) Broadcast(msg interface{}, all bool, exc ...uint32) { for _, v := range r.Occupants { if v != nil && (all || !v.IsGameing()) { for _, uid := range exc { if uid == v.GetUid() { goto End1 } } v.WriteMsg(msg) } End1: } for _, v := range r.observes { if v != nil { for _, uid := range exc { if uid == v.Uid { goto End } } v.WriteMsg(msg) } End: } } func (r *Room) addOccupant(o *Occupant) uint8 { for _, v := range r.Occupants { if v != nil && v.GetUid() == o.Uid { return 0 } } for k, v := range r.Occupants { if v == nil { r.Occupants[k] = o o.SetRoom(r) o.Pos = uint8(k + 1) o.SetSitdown() return o.Pos } } return 0 } func (r *Room) removeOccupant(o *Occupant) uint8 { for k, v := range r.Occupants { if v != nil && v.GetUid() == o.Uid { v.SetPos(0) r.Occupants[k] = nil return uint8(k + 1) } } return 0 } func (r *Room) addObserve(o *Occupant) uint8 { for _, v := range r.observes { if v != nil && v.Uid == o.Uid { return 0 } } o.SetObserve() r.observes = append(r.observes, o) return 0 } func (r *Room) removeObserve(o *Occupant) { for k, v := range r.observes { if v != nil && v.Uid == o.Uid { r.observes = append(r.observes[:k], r.observes[k+1:]...) return } } } // start starts from 0 func (r *Room) Each(start uint8, f func(o *Occupant) bool) { volume := r.Cap() end := (volume + start - 1) % volume i := start for ; i != end; i = (i + 1) % volume { if r.Occupants[i] != nil && r.Occupants[i].IsGameing() && !f(r.Occupants[i]) { return } } // end if r.Occupants[i] != nil && r.Occupants[i].IsGameing() { f(r.Occupants[i]) } } func (r *Room) Cap() uint8 { return r.Max } func (r *Room) Len() uint8 { var num uint8 for _, v := range r.Occupants { if v != nil { num ++ } } return num } func (r *Room) GetNumber() string { return r.Number } func (r *Room) SetNumber(value string) { r.Number = value } func (r *Room) Data() interface{} { return r.Room } func (r *Room) SetData(d interface{}) { r.Room = d.(*model.Room) } ================================================ FILE: src/server/game/internal/room_internal_handler.go ================================================ package internal import ( "server/protocol" "github.com/golang/glog" "github.com/davecgh/go-spew/spew" "time" "github.com/dolotech/lib/utils" ) func (r *Room) joinRoom(m *protocol.JoinRoom, o *Occupant) { if o.room != nil { for k, v := range r.Occupants { glog.Infoln(v, o) if v.Uid == o.Uid { // todo 掉线重连现场数据替换处理 o.Replace(r.Occupants[k]) r.Occupants[k] = o if o != v { v.Close() glog.Infoln("掉线重连处理") } else { glog.Infoln("同一个链接重复请求加入房间") } r.WriteMsg(&protocol.UserInfo{Uid: o.Uid}, o.Uid) return } } } rinfo := &protocol.RoomInfo{ Number: r.Number, } userinfos := make([]*protocol.UserInfo, 0, r.Cap()) r.Each(0, func(o *Occupant) bool { userinfo := &protocol.UserInfo{ Nickname: o.Nickname, Uid: o.Uid, Account: o.Account, Sex: o.Sex, Profile: o.Profile, Chips: o.chips, } userinfos = append(userinfos, userinfo) return true }) pos := r.addOccupant(o) // 坐下失败转为旁观 if pos == 0 { r.addObserve(o) } else { userInfo := &protocol.UserInfo{ Nickname: o.Nickname, Uid: o.Uid, Account: o.Account, Sex: o.Sex, Profile: o.Profile, Chips: o.chips, } r.Broadcast(&protocol.JoinRoomBroadcast{UserInfo: userInfo}, true, o.Uid) } o.RoomID = r.Number o.UpdateRoomId() o.WriteMsg(&protocol.JoinRoomResp{UserInfos: userinfos, RoomInfo: rinfo}) time.AfterFunc(time.Second*2, func() { defer utils.PrintPanicStack() r.Send(o,&startDelay{}) }) r.Debug("joinRoom", spew.Sdump(m)) } func (r *Room) leaveAndRecycleChips(o *Occupant) { if r.removeOccupant(o) > 0 { // 玩家站起回收带入筹码 gap := int32(o.chips) - int32(r.DraginChips) if gap == 0 { o.UpdateChips(gap) } } } func (r *Room) leaveRoom(m *protocol.LeaveRoom, o *Occupant) { r.removeObserve(o) r.removeOccupant(o) r.leaveAndRecycleChips(o) o.RoomID = "" o.room = nil o.UpdateRoomId() leave := &protocol.LeaveRoom{ RoomNumber: r.Number, Uid: o.Uid, } r.Broadcast(leave, true) r.Debug() // 房间里没有玩家时关闭并从列表中删除 if r.Len() == 0 { r.Close(r) } glog.Errorln("leaveRoom", m) } func (r *Room) bet(m *protocol.Bet, o *Occupant) { if !o.IsGameing() { o.WriteMsg(protocol.MSG_NOT_NOT_START) return } if m.Value < 0 { err := o.SetAction(-1) if err != nil { o.WriteMsg(protocol.MSG_NOT_TURN) } } else { err := o.SetAction(m.Value) if err != nil { o.WriteMsg(protocol.MSG_NOT_TURN) } } glog.Errorln("bet", m) } func (r *Room) sitDown(m *protocol.SitDown, o *Occupant) { pos := r.addOccupant(o) if pos == 0 { // 给进入房间的玩家带入筹码 o.chips = r.DraginChips r.addObserve(o) } else { } r.Broadcast(&protocol.SitDown{Uid: o.Uid, Pos: o.Pos}, true) glog.Errorln("sitDown", m) } func (r *Room) standUp(m *protocol.StandUp, o *Occupant) { o.SetAction(-1) r.leaveAndRecycleChips(o) r.addObserve(o) r.Broadcast(&protocol.StandUp{Uid: o.Uid}, true) glog.Errorln("standUp", m) } func (r *Room) chat(m *protocol.Chat, o *Occupant) { r.Broadcast(m, true) } ================================================ FILE: src/server/game/internal/room_test.go ================================================ package internal import ( "testing" "time" "reflect" ) func TestRoom_Value(t *testing.T) { t.Log(reflect.ValueOf(12)) } func TestRoom_RecvMsg(t *testing.T) { /*room:= NewRoom(&model.Room{}) protocol:= &msg2.JoinRoom{RoomNumber:"9999"} room.Send(12,protocol) */ //msg1:= &msg2.LeaveRoom{RoomNumber:"9999"} //room.RecvMsg(12,msg1) time.Sleep(time.Second * 2) } func TestClose(t *testing.T) { c:= make(chan struct{},1) go func() { select { case <-c: default: t.Log("default") } }() <- time.After(time.Second) close(c) select { case c<- struct{}{}: default: t.Log("default") } <- time.After(time.Second) } func BenchmarkCloseRoom(t *testing.B) { /* for i:=0;i