buildTree build the prefix tree from the previously registered routes
()
| 827 | |
| 828 | // buildTree build the prefix tree from the previously registered routes |
| 829 | func (app *App) buildTree() *App { |
| 830 | // If routes haven't been refreshed, nothing to do |
| 831 | if !app.hasRoutesRefreshed { |
| 832 | return app |
| 833 | } |
| 834 | |
| 835 | // 1) First loop: determine all possible 3-char prefixes ("treePaths") for each method |
| 836 | for method := range app.config.RequestMethods { |
| 837 | routes := app.stack[method] |
| 838 | treePaths := make([]int, len(routes)) |
| 839 | |
| 840 | globalCount := 0 |
| 841 | prefixCounts := make(map[int]int, len(routes)) |
| 842 | |
| 843 | for i, route := range routes { |
| 844 | if len(route.routeParser.segs) > 0 && len(route.routeParser.segs[0].Const) >= maxDetectionPaths { |
| 845 | treePaths[i] = int(route.routeParser.segs[0].Const[0])<<16 | |
| 846 | int(route.routeParser.segs[0].Const[1])<<8 | |
| 847 | int(route.routeParser.segs[0].Const[2]) |
| 848 | } |
| 849 | |
| 850 | if treePaths[i] == 0 { |
| 851 | globalCount++ |
| 852 | continue |
| 853 | } |
| 854 | |
| 855 | prefixCounts[treePaths[i]]++ |
| 856 | } |
| 857 | |
| 858 | prevBuckets := app.treeStack[method] |
| 859 | tsMap := make(map[int][]*Route, len(prefixCounts)+1) |
| 860 | tsMap[0] = reuseRouteBucket(prevBuckets, 0, globalCount) |
| 861 | for treePath, count := range prefixCounts { |
| 862 | tsMap[treePath] = reuseRouteBucket(prevBuckets, treePath, count+globalCount) |
| 863 | } |
| 864 | |
| 865 | for i, route := range routes { |
| 866 | treePath := treePaths[i] |
| 867 | |
| 868 | if treePath == 0 { |
| 869 | for bucket := range tsMap { |
| 870 | tsMap[bucket] = append(tsMap[bucket], route) |
| 871 | } |
| 872 | continue |
| 873 | } |
| 874 | |
| 875 | tsMap[treePath] = append(tsMap[treePath], route) |
| 876 | } |
| 877 | |
| 878 | app.treeStack[method] = tsMap |
| 879 | } |
| 880 | |
| 881 | // reset the flag and return |
| 882 | app.hasRoutesRefreshed = false |
| 883 | return app |
| 884 | } |
| 885 | |
| 886 | func reuseRouteBucket(prev map[int][]*Route, key, capHint int) []*Route { |
no test coverage detected