Advertisement
Guest User

Untitled

a guest
Oct 24th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "os"
  6. "io/ioutil"
  7. "strings"
  8. "regexp"
  9. )
  10.  
  11. var functionPrefix = "Complexity"
  12.  
  13. var testingFunc = `
  14. func main(){
  15. nVals := []int{1, 10, 100, 1000, 10000, 100000}
  16. for _, n := range nVals {
  17. dataSet := getDataSet(n)
  18. start := time.Now().UnixNano()
  19. <complexityFunc>(dataSet)
  20. fmt.Printf("\n(%d, %d)\n", n, time.Now().UnixNano() - start)
  21. }
  22. }`
  23.  
  24. func main() {
  25. data, err := ioutil.ReadAll(os.Stdin)
  26. if err != nil {
  27. fmt.Println(err)
  28. }
  29. code := string(data)
  30.  
  31. // Split the code at each function declaration and exclude the first element
  32. funcBodys := strings.Split(code, "\nfunc ")[1:]
  33.  
  34. // Parse the funtionBodys to retrieve a list of all functions in code
  35. funcNames := getFuncs(funcBodys)
  36.  
  37. // Rename original main function so that it doesn't conflict with our new main()
  38. code = renameMainFunc(code, "main2")
  39.  
  40. // Add in our new main method and swap out the placeholder for the function call
  41. code = code + strings.Replace(testingFunc, "<complexityFunc>", getTestFunc(funcNames), -1)
  42.  
  43. // Print to stdout
  44. fmt.Println(code)
  45. }
  46.  
  47. // Parses slice of function bodys and returns a slice with all function names
  48. func getFuncs(funcBodys []string) []string {
  49. funcNames := make([]string, len(funcBodys))
  50. for i := 0; i < len(funcBodys); i++ {
  51. funcName := strings.Split(funcBodys[i], "(")[0]
  52. funcNames[i] = funcName
  53. }
  54. return funcNames
  55. }
  56.  
  57. // Selects the first function in the list of functions that starts with a predefined function prefix
  58. // Returns an empty string if fitting function is not found
  59. func getTestFunc(funcNames []string) string {
  60. for _, funcName := range funcNames {
  61. if funcName[0:len(functionPrefix)] == functionPrefix {
  62. return funcName
  63. }
  64. }
  65. return ""
  66. }
  67.  
  68. // Uses regex to find and replace the main method declaration with newFuncName
  69. func renameMainFunc(code, newFuncName string) string {
  70. funcRegex, _ := regexp.Compile("func main ?\\( ?\\) ?{")
  71. return funcRegex.ReplaceAllString(code, fmt.Sprintf("func %s() {", newFuncName))
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement