diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 2568ecf0..c39bf83c 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -1,458 +1,329 @@ go test -bench=. -benchmem -goos: linux +goos: darwin goarch: amd64 -pkg: github.com/brianvoe/gofakeit/v6 -cpu: 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz -Table generated with tablesgenerator.com/markdown_tables +pkg: github.com/brianvoe/gofakeit/v7 +cpu: Apple M1 Max +Table generated with tablesgenerator.com/markdown_tables File->Paste table data -| Benchmark | Ops | CPU | MEM | MEM alloc | -|--------------------------------------------------|------------|------------------|----------------|-------------------| -| BenchmarkAddress/package-8 | 1270872 | 940.1 ns/op | 197 B/op | 5 allocs/op | -| BenchmarkAddress/Faker_math-8 | 1238563 | 1042 ns/op | 197 B/op | 5 allocs/op | -| BenchmarkAddress/Faker_crypto-8 | 139857 | 7862 ns/op | 197 B/op | 5 allocs/op | -| BenchmarkStreet/package-8 | 2955518 | 422.6 ns/op | 26 B/op | 2 allocs/op | -| BenchmarkStreet/Faker_math-8 | 3027224 | 427.3 ns/op | 26 B/op | 2 allocs/op | -| BenchmarkStreet/Faker_crypto-8 | 352165 | 3559 ns/op | 26 B/op | 2 allocs/op | -| BenchmarkStreetNumber/package-8 | 6842211 | 149.2 ns/op | 4 B/op | 1 allocs/op | -| BenchmarkStreetNumber/Faker_math-8 | 6924288 | 158.8 ns/op | 4 B/op | 1 allocs/op | -| BenchmarkStreetNumber/Faker_crypto-8 | 549988 | 1900 ns/op | 4 B/op | 1 allocs/op | -| BenchmarkStreetPrefix/package-8 | 18441643 | 74.12 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkStreetPrefix/Faker_math-8 | 17888110 | 67.51 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkStreetPrefix/Faker_crypto-8 | 2650390 | 458.9 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkStreetName/package-8 | 18799832 | 62.90 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkStreetName/Faker_math-8 | 16124620 | 63.57 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkStreetName/Faker_crypto-8 | 2873138 | 428.2 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkStreetSuffix/package-8 | 17192164 | 72.19 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkStreetSuffix/Faker_math-8 | 16545355 | 65.44 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkStreetSuffix/Faker_crypto-8 | 2986934 | 450.9 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCity/package-8 | 18553683 | 64.93 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCity/Faker_math-8 | 17648109 | 63.77 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCity/Faker_crypto-8 | 2567427 | 470.8 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkState/package-8 | 18262387 | 66.25 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkState/Faker_math-8 | 16690209 | 73.21 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkState/Faker_crypto-8 | 2599795 | 401.3 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkStateAbr/package-8 | 17492332 | 63.87 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkStateAbr/Faker_math-8 | 18612169 | 64.82 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkStateAbr/Faker_crypto-8 | 2821579 | 460.0 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkZip/package-8 | 7573238 | 157.1 ns/op | 5 B/op | 1 allocs/op | -| BenchmarkZip/Faker_math-8 | 6644562 | 163.4 ns/op | 5 B/op | 1 allocs/op | -| BenchmarkZip/Faker_crypto-8 | 484525 | 2470 ns/op | 5 B/op | 1 allocs/op | -| BenchmarkCountry/package-8 | 15623450 | 65.65 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCountry/Faker_math-8 | 17786485 | 76.22 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCountry/Faker_crypto-8 | 3002818 | 400.3 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCountryAbr/package-8 | 17296935 | 66.75 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCountryAbr/Faker_math-8 | 17862819 | 67.41 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCountryAbr/Faker_crypto-8 | 2931120 | 426.0 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLatitude/package-8 | 46248466 | 26.11 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLatitude/Faker_math-8 | 46120956 | 26.00 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLatitude/Faker_crypto-8 | 3512108 | 366.7 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLongitude/package-8 | 47443129 | 24.03 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLongitude/Faker_math-8 | 46691144 | 24.64 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLongitude/Faker_crypto-8 | 3501789 | 365.8 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLatitudeInRange/package-8 | 44125588 | 26.96 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLatitudeInRange/Faker_math-8 | 40113348 | 27.36 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLatitudeInRange/Faker_crypto-8 | 3227358 | 378.4 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLongitudeInRange/package-8 | 38948743 | 32.36 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLongitudeInRange/Faker_math-8 | 36491187 | 27.86 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLongitudeInRange/Faker_crypto-8 | 3004773 | 350.4 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkPetName/package-8 | 23445927 | 60.81 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkPetName/Faker_math-8 | 23982228 | 53.68 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkPetName/Faker_crypto-8 | 2681886 | 458.0 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkAnimal/package-8 | 23230071 | 55.13 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkAnimal/Faker_math-8 | 21923606 | 53.10 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkAnimal/Faker_crypto-8 | 2680177 | 411.6 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkAnimalType/package-8 | 18826995 | 53.45 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkAnimalType/Faker_math-8 | 22170756 | 63.39 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkAnimalType/Faker_crypto-8 | 2780270 | 399.6 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkFarmAnimal/package-8 | 18548028 | 64.87 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkFarmAnimal/Faker_math-8 | 17291526 | 62.47 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkFarmAnimal/Faker_crypto-8 | 2543520 | 409.9 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCat/package-8 | 21213028 | 68.91 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCat/Faker_math-8 | 19973062 | 58.74 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCat/Faker_crypto-8 | 2985601 | 405.2 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkDog/package-8 | 16995627 | 68.15 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkDog/Faker_math-8 | 17296502 | 81.35 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkDog/Faker_crypto-8 | 2530860 | 433.1 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBird/package-8 | 14445968 | 81.31 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBird/Faker_math-8 | 14545851 | 82.69 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBird/Faker_crypto-8 | 2892721 | 420.4 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkAppName/package-8 | 2799828 | 438.6 ns/op | 25 B/op | 1 allocs/op | -| BenchmarkAppName/Faker_math-8 | 2784135 | 431.1 ns/op | 25 B/op | 1 allocs/op | -| BenchmarkAppName/Faker_crypto-8 | 611072 | 1923 ns/op | 25 B/op | 1 allocs/op | -| BenchmarkAppVersion/package-8 | 7552165 | 154.1 ns/op | 7 B/op | 1 allocs/op | -| BenchmarkAppVersion/Faker_math-8 | 8020767 | 156.6 ns/op | 7 B/op | 1 allocs/op | -| BenchmarkAppVersion/Faker_crypto-8 | 875899 | 1209 ns/op | 7 B/op | 1 allocs/op | -| BenchmarkAppAuthor/package-8 | 9596493 | 119.7 ns/op | 8 B/op | 0 allocs/op | -| BenchmarkAppAuthor/Faker_math-8 | 10068729 | 121.0 ns/op | 8 B/op | 0 allocs/op | -| BenchmarkAppAuthor/Faker_crypto-8 | 1212542 | 983.7 ns/op | 8 B/op | 0 allocs/op | -| BenchmarkUsername/package-8 | 6687600 | 174.6 ns/op | 16 B/op | 2 allocs/op | -| BenchmarkUsername/Faker_math-8 | 7233685 | 173.3 ns/op | 16 B/op | 2 allocs/op | -| BenchmarkUsername/Faker_crypto-8 | 616884 | 2166 ns/op | 16 B/op | 2 allocs/op | -| BenchmarkPassword/package-8 | 2966407 | 401.0 ns/op | 336 B/op | 6 allocs/op | -| BenchmarkPassword/Faker_math-8 | 3080845 | 399.8 ns/op | 336 B/op | 6 allocs/op | -| BenchmarkPassword/Faker_crypto-8 | 182074 | 5963 ns/op | 336 B/op | 6 allocs/op | -| BenchmarkBeerName/package-8 | 23768442 | 53.26 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerName/Faker_math-8 | 22010898 | 63.87 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerName/Faker_crypto-8 | 2569424 | 392.6 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerStyle/package-8 | 17567354 | 69.64 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerStyle/Faker_math-8 | 16695721 | 80.73 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerStyle/Faker_crypto-8 | 2710214 | 407.6 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerHop/package-8 | 20877854 | 56.43 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerHop/Faker_math-8 | 22603234 | 65.04 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerHop/Faker_crypto-8 | 2618493 | 419.3 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerYeast/package-8 | 20738073 | 67.89 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerYeast/Faker_math-8 | 21325231 | 67.34 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerYeast/Faker_crypto-8 | 3042529 | 399.8 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerMalt/package-8 | 15756969 | 65.67 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerMalt/Faker_math-8 | 18026910 | 71.42 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerMalt/Faker_crypto-8 | 2949741 | 429.4 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBeerIbu/package-8 | 32683443 | 35.57 ns/op | 8 B/op | 1 allocs/op | -| BenchmarkBeerIbu/Faker_math-8 | 29983339 | 36.03 ns/op | 8 B/op | 1 allocs/op | -| BenchmarkBeerIbu/Faker_crypto-8 | 3094896 | 386.6 ns/op | 8 B/op | 1 allocs/op | -| BenchmarkBeerAlcohol/package-8 | 4744302 | 243.6 ns/op | 32 B/op | 3 allocs/op | -| BenchmarkBeerAlcohol/Faker_math-8 | 4718923 | 252.0 ns/op | 32 B/op | 3 allocs/op | -| BenchmarkBeerAlcohol/Faker_crypto-8 | 1952740 | 656.0 ns/op | 32 B/op | 3 allocs/op | -| BenchmarkBeerBlg/package-8 | 4086861 | 270.6 ns/op | 40 B/op | 3 allocs/op | -| BenchmarkBeerBlg/Faker_math-8 | 4488897 | 259.5 ns/op | 40 B/op | 3 allocs/op | -| BenchmarkBeerBlg/Faker_crypto-8 | 1865367 | 646.7 ns/op | 40 B/op | 3 allocs/op | -| BenchmarkCar/package-8 | 2800782 | 400.5 ns/op | 96 B/op | 1 allocs/op | -| BenchmarkCar/Faker_math-8 | 2938509 | 396.5 ns/op | 96 B/op | 1 allocs/op | -| BenchmarkCar/Faker_crypto-8 | 461906 | 2590 ns/op | 96 B/op | 1 allocs/op | -| BenchmarkCarType/package-8 | 23655384 | 51.72 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarType/Faker_math-8 | 25902462 | 50.55 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarType/Faker_crypto-8 | 3035287 | 455.8 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarFuelType/package-8 | 18750069 | 63.80 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarFuelType/Faker_math-8 | 18858705 | 63.15 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarFuelType/Faker_crypto-8 | 3028026 | 387.0 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarTransmissionType/package-8 | 22570701 | 54.01 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarTransmissionType/Faker_math-8 | 21484246 | 64.27 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarTransmissionType/Faker_crypto-8 | 3061364 | 387.6 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarMaker/package-8 | 17628445 | 68.23 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarMaker/Faker_math-8 | 21573310 | 64.19 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarMaker/Faker_crypto-8 | 2688284 | 475.5 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarModel/package-8 | 18500498 | 73.43 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarModel/Faker_math-8 | 16116993 | 66.91 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCarModel/Faker_crypto-8 | 2487638 | 440.0 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCelebrityActor/package-8 | 18712833 | 74.12 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCelebrityActor/Faker_math-8 | 18564168 | 68.96 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCelebrityActor/Faker_crypto-8 | 2593150 | 415.5 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCelebrityBusiness/package-8 | 18721152 | 68.98 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCelebrityBusiness/Faker_math-8 | 16916186 | 70.66 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCelebrityBusiness/Faker_crypto-8 | 2578786 | 407.7 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCelebritySport/package-8 | 16716724 | 87.51 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCelebritySport/Faker_math-8 | 16602294 | 86.41 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCelebritySport/Faker_crypto-8 | 2919696 | 419.0 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkColor/package-8 | 17871778 | 62.28 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkColor/Faker_math-8 | 21601353 | 62.63 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkColor/Faker_crypto-8 | 3040459 | 463.1 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkNiceColors/package-8 | 81438092 | 14.86 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkNiceColors/Faker_math-8 | 75775309 | 18.52 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkNiceColors/Faker_crypto-8 | 3450939 | 353.9 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkSafeColor/package-8 | 22775230 | 53.52 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkSafeColor/Faker_math-8 | 24526308 | 59.40 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkSafeColor/Faker_crypto-8 | 3103851 | 413.3 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHexColor/package-8 | 4640522 | 255.2 ns/op | 24 B/op | 3 allocs/op | -| BenchmarkHexColor/Faker_math-8 | 4723542 | 257.2 ns/op | 24 B/op | 3 allocs/op | -| BenchmarkHexColor/Faker_crypto-8 | 283828 | 4447 ns/op | 24 B/op | 3 allocs/op | -| BenchmarkRGBColor/package-8 | 19721971 | 59.64 ns/op | 24 B/op | 1 allocs/op | -| BenchmarkRGBColor/Faker_math-8 | 18808492 | 67.35 ns/op | 24 B/op | 1 allocs/op | -| BenchmarkRGBColor/Faker_crypto-8 | 1000000 | 1066 ns/op | 24 B/op | 1 allocs/op | -| BenchmarkCompany/package-8 | 22072651 | 48.06 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCompany/Faker_math-8 | 22528284 | 53.94 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCompany/Faker_crypto-8 | 2690668 | 402.4 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCompanySuffix/package-8 | 28169413 | 48.00 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCompanySuffix/Faker_math-8 | 20685153 | 52.20 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCompanySuffix/Faker_crypto-8 | 3018765 | 418.0 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBuzzWord/package-8 | 24238677 | 54.55 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBuzzWord/Faker_math-8 | 22195419 | 52.30 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBuzzWord/Faker_crypto-8 | 2840428 | 392.1 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBS/package-8 | 23481436 | 56.33 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBS/Faker_math-8 | 23195737 | 65.66 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBS/Faker_crypto-8 | 3027972 | 419.8 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkJob/package-8 | 4432520 | 253.5 ns/op | 64 B/op | 1 allocs/op | -| BenchmarkJob/Faker_math-8 | 4513154 | 253.7 ns/op | 64 B/op | 1 allocs/op | -| BenchmarkJob/Faker_crypto-8 | 686028 | 1716 ns/op | 64 B/op | 1 allocs/op | -| BenchmarkJobTitle/package-8 | 20079558 | 54.21 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkJobTitle/Faker_math-8 | 21871627 | 54.86 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkJobTitle/Faker_crypto-8 | 3017896 | 413.3 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkJobDescriptor/package-8 | 21579855 | 53.36 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkJobDescriptor/Faker_math-8 | 24638751 | 55.91 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkJobDescriptor/Faker_crypto-8 | 2984810 | 415.9 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkJobLevel/package-8 | 18311070 | 59.35 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkJobLevel/Faker_math-8 | 17051210 | 59.53 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkJobLevel/Faker_crypto-8 | 2991106 | 426.8 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCSVLookup100-8 | 1468 | 780852 ns/op | 437416 B/op | 5933 allocs/op | -| BenchmarkCSVLookup1000-8 | 151 | 7853471 ns/op | 4224820 B/op | 59612 allocs/op | -| BenchmarkCSVLookup10000-8 | 14 | 78165009 ns/op | 41208010 B/op | 597842 allocs/op | -| BenchmarkCSVLookup100000-8 | 2 | 768800840 ns/op | 437275164 B/op | 5980461 allocs/op | -| BenchmarkEmoji/package-8 | 22212386 | 54.40 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmoji/Faker_math-8 | 21471013 | 51.55 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmoji/Faker_crypto-8 | 3036081 | 458.1 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmojiDescription/package-8 | 18250413 | 57.08 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmojiDescription/Faker_math-8 | 21924381 | 57.58 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmojiDescription/Faker_crypto-8 | 2837050 | 387.5 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmojiCategory/package-8 | 21270252 | 55.87 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmojiCategory/Faker_math-8 | 21421813 | 59.59 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmojiCategory/Faker_crypto-8 | 2635878 | 491.0 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmojiAlias/package-8 | 18760875 | 68.20 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmojiAlias/Faker_math-8 | 16918242 | 67.60 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmojiAlias/Faker_crypto-8 | 2854717 | 488.9 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmojiTag/package-8 | 19953885 | 65.43 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmojiTag/Faker_math-8 | 18220396 | 72.91 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkEmojiTag/Faker_crypto-8 | 2802847 | 426.2 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkError/package-8 | 1547610 | 786.6 ns/op | 279 B/op | 8 allocs/op | -| BenchmarkError/Faker_math-8 | 1504578 | 794.1 ns/op | 279 B/op | 8 allocs/op | -| BenchmarkError/Faker_crypto-8 | 800712 | 1476 ns/op | 279 B/op | 8 allocs/op | -| BenchmarkErrorObject/package-8 | 6054552 | 190.3 ns/op | 32 B/op | 3 allocs/op | -| BenchmarkErrorObject/Faker_math-8 | 5968180 | 190.3 ns/op | 32 B/op | 3 allocs/op | -| BenchmarkErrorObject/Faker_crypto-8 | 2088008 | 618.0 ns/op | 32 B/op | 3 allocs/op | -| BenchmarkErrorDatabase/package-8 | 5275713 | 212.8 ns/op | 64 B/op | 3 allocs/op | -| BenchmarkErrorDatabase/Faker_math-8 | 5407803 | 217.3 ns/op | 64 B/op | 3 allocs/op | -| BenchmarkErrorDatabase/Faker_crypto-8 | 2005333 | 628.7 ns/op | 63 B/op | 3 allocs/op | -| BenchmarkErrorGRPC/package-8 | 5700810 | 202.9 ns/op | 64 B/op | 3 allocs/op | -| BenchmarkErrorGRPC/Faker_math-8 | 5907589 | 202.5 ns/op | 64 B/op | 3 allocs/op | -| BenchmarkErrorGRPC/Faker_crypto-8 | 2027650 | 643.3 ns/op | 64 B/op | 3 allocs/op | -| BenchmarkErrorHTTP/package-8 | 3182026 | 321.6 ns/op | 157 B/op | 4 allocs/op | -| BenchmarkErrorHTTP/Faker_math-8 | 3667356 | 314.9 ns/op | 157 B/op | 4 allocs/op | -| BenchmarkErrorHTTP/Faker_crypto-8 | 1590696 | 720.2 ns/op | 157 B/op | 4 allocs/op | -| BenchmarkErrorHTTPClient/package-8 | 5745494 | 204.0 ns/op | 52 B/op | 3 allocs/op | -| BenchmarkErrorHTTPClient/Faker_math-8 | 5549187 | 212.8 ns/op | 52 B/op | 3 allocs/op | -| BenchmarkErrorHTTPClient/Faker_crypto-8 | 2011905 | 596.7 ns/op | 52 B/op | 3 allocs/op | -| BenchmarkErrorHTTPServer/package-8 | 5466012 | 214.7 ns/op | 59 B/op | 3 allocs/op | -| BenchmarkErrorHTTPServer/Faker_math-8 | 5542838 | 207.3 ns/op | 59 B/op | 3 allocs/op | -| BenchmarkErrorHTTPServer/Faker_crypto-8 | 1939080 | 633.9 ns/op | 59 B/op | 3 allocs/op | -| BenchmarkErrorRuntime/package-8 | 4245986 | 263.4 ns/op | 150 B/op | 3 allocs/op | -| BenchmarkErrorRuntime/Faker_math-8 | 4355534 | 263.1 ns/op | 150 B/op | 3 allocs/op | -| BenchmarkErrorRuntime/Faker_crypto-8 | 1782044 | 651.4 ns/op | 150 B/op | 3 allocs/op | -| BenchmarkErrorValidation/package-8 | 1659858 | 715.7 ns/op | 268 B/op | 7 allocs/op | -| BenchmarkErrorValidation/Faker_math-8 | 1690849 | 716.4 ns/op | 268 B/op | 7 allocs/op | -| BenchmarkErrorValidation/Faker_crypto-8 | 883600 | 1348 ns/op | 268 B/op | 7 allocs/op | -| BenchmarkFileMimeType/package-8 | 18005230 | 56.88 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkFileMimeType/Faker_math-8 | 21229381 | 54.62 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkFileMimeType/Faker_crypto-8 | 2605701 | 462.5 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkFileExtension/package-8 | 19272264 | 73.07 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkFileExtension/Faker_math-8 | 20149288 | 60.79 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkFileExtension/Faker_crypto-8 | 2627210 | 423.1 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkCusip/package-8 | 5402995 | 224.9 ns/op | 24 B/op | 2 allocs/op | -| BenchmarkCusip/Faker_math-8 | 5367218 | 221.1 ns/op | 24 B/op | 2 allocs/op | -| BenchmarkCusip/Faker_crypto-8 | 363460 | 2967 ns/op | 24 B/op | 2 allocs/op | -| BenchmarkIsin/package-8 | 1742368 | 701.4 ns/op | 533 B/op | 8 allocs/op | -| BenchmarkIsin/Faker_math-8 | 1653408 | 715.5 ns/op | 533 B/op | 8 allocs/op | -| BenchmarkIsin/Faker_crypto-8 | 330396 | 3583 ns/op | 533 B/op | 8 allocs/op | -| BenchmarkFruit/package-8 | 21421066 | 55.23 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkFruit/Faker_math-8 | 22680361 | 55.68 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkFruit/Faker_crypto-8 | 2914611 | 486.7 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkVegetable/package-8 | 21113413 | 56.44 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkVegetable/Faker_math-8 | 21101716 | 60.98 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkVegetable/Faker_crypto-8 | 2811384 | 467.1 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBreakfast/package-8 | 8954784 | 127.7 ns/op | 32 B/op | 1 allocs/op | -| BenchmarkBreakfast/Faker_math-8 | 9430814 | 128.8 ns/op | 32 B/op | 1 allocs/op | -| BenchmarkBreakfast/Faker_crypto-8 | 2132481 | 496.5 ns/op | 32 B/op | 1 allocs/op | -| BenchmarkLunch/package-8 | 8934501 | 125.9 ns/op | 34 B/op | 1 allocs/op | -| BenchmarkLunch/Faker_math-8 | 8668546 | 128.9 ns/op | 34 B/op | 1 allocs/op | -| BenchmarkLunch/Faker_crypto-8 | 2216348 | 518.3 ns/op | 34 B/op | 1 allocs/op | -| BenchmarkDinner/package-8 | 9317936 | 125.2 ns/op | 36 B/op | 1 allocs/op | -| BenchmarkDinner/Faker_math-8 | 9023473 | 126.3 ns/op | 36 B/op | 1 allocs/op | -| BenchmarkDinner/Faker_crypto-8 | 2435984 | 518.9 ns/op | 36 B/op | 1 allocs/op | -| BenchmarkDrink/package-8 | 7698025 | 143.4 ns/op | 7 B/op | 2 allocs/op | -| BenchmarkDrink/Faker_math-8 | 8096294 | 139.8 ns/op | 7 B/op | 2 allocs/op | -| BenchmarkDrink/Faker_crypto-8 | 2247427 | 536.2 ns/op | 7 B/op | 2 allocs/op | -| BenchmarkSnack/package-8 | 8109601 | 149.2 ns/op | 32 B/op | 1 allocs/op | -| BenchmarkSnack/Faker_math-8 | 7993006 | 150.5 ns/op | 32 B/op | 1 allocs/op | -| BenchmarkSnack/Faker_crypto-8 | 2214736 | 535.7 ns/op | 32 B/op | 1 allocs/op | -| BenchmarkDessert/package-8 | 8295364 | 133.9 ns/op | 31 B/op | 2 allocs/op | -| BenchmarkDessert/Faker_math-8 | 8610325 | 134.1 ns/op | 31 B/op | 2 allocs/op | -| BenchmarkDessert/Faker_crypto-8 | 2205777 | 507.4 ns/op | 31 B/op | 2 allocs/op | -| BenchmarkGamertag/package-8 | 2111506 | 544.8 ns/op | 83 B/op | 5 allocs/op | -| BenchmarkGamertag/Faker_math-8 | 2203573 | 551.4 ns/op | 83 B/op | 5 allocs/op | -| BenchmarkGamertag/Faker_crypto-8 | 487366 | 2428 ns/op | 83 B/op | 5 allocs/op | -| BenchmarkDice/package-8 | 43259642 | 26.58 ns/op | 8 B/op | 1 allocs/op | -| BenchmarkDice/Faker_math-8 | 42908084 | 26.84 ns/op | 8 B/op | 1 allocs/op | -| BenchmarkDice/Faker_crypto-8 | 2953483 | 395.5 ns/op | 8 B/op | 1 allocs/op | -| BenchmarkGenerate/package-8 | 383122 | 2767 ns/op | 1139 B/op | 29 allocs/op | -| BenchmarkGenerate/Complex-8 | 135508 | 8555 ns/op | 4440 B/op | 80 allocs/op | -| BenchmarkGenerate/Faker_math-8 | 377151 | 2817 ns/op | 1139 B/op | 29 allocs/op | -| BenchmarkGenerate/Faker_crypto-8 | 152226 | 7234 ns/op | 1139 B/op | 29 allocs/op | -| BenchmarkRegex/package-8 | 628683 | 1922 ns/op | 1632 B/op | 27 allocs/op | -| BenchmarkRegex/Faker_math-8 | 591548 | 1940 ns/op | 1632 B/op | 27 allocs/op | -| BenchmarkRegex/Faker_crypto-8 | 616701 | 1934 ns/op | 1632 B/op | 27 allocs/op | -| BenchmarkRegexEmail/package-8 | 174812 | 6607 ns/op | 4084 B/op | 90 allocs/op | -| BenchmarkRegexEmail/Faker_math-8 | 174512 | 6619 ns/op | 4084 B/op | 90 allocs/op | -| BenchmarkRegexEmail/Faker_crypto-8 | 62312 | 18793 ns/op | 4083 B/op | 90 allocs/op | -| BenchmarkMap/package-8 | 318559 | 3275 ns/op | 1113 B/op | 16 allocs/op | -| BenchmarkMap/Faker_math-8 | 315990 | 3319 ns/op | 1113 B/op | 16 allocs/op | -| BenchmarkMap/Faker_crypto-8 | 46202 | 23997 ns/op | 1115 B/op | 16 allocs/op | -| BenchmarkHackerPhrase/package-8 | 155998 | 7191 ns/op | 3004 B/op | 50 allocs/op | -| BenchmarkHackerPhrase/Faker_math-8 | 154675 | 7305 ns/op | 3008 B/op | 50 allocs/op | -| BenchmarkHackerPhrase/Faker_crypto-8 | 109282 | 10268 ns/op | 3007 B/op | 50 allocs/op | -| BenchmarkHackerAbbreviation/package-8 | 21881574 | 57.57 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackerAbbreviation/Faker_math-8 | 18534495 | 59.55 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackerAbbreviation/Faker_crypto-8 | 2607735 | 401.6 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackerAdjective/package-8 | 24286845 | 55.74 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackerAdjective/Faker_math-8 | 22684101 | 55.22 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackerAdjective/Faker_crypto-8 | 2953530 | 490.5 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackerNoun/package-8 | 22554241 | 55.35 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackerNoun/Faker_math-8 | 18360708 | 56.78 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackerNoun/Faker_crypto-8 | 2823256 | 464.8 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackerVerb/package-8 | 19236123 | 65.49 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackerVerb/Faker_math-8 | 18090754 | 68.18 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackerVerb/Faker_crypto-8 | 2880181 | 439.2 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackeringVerb/package-8 | 19090326 | 71.74 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackeringVerb/Faker_math-8 | 19048659 | 63.31 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHackeringVerb/Faker_crypto-8 | 3020748 | 404.5 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkReplaceWithNumbers-8 | 162931 | 7098 ns/op | 32 B/op | 2 allocs/op | -| BenchmarkHipsterWord/package-8 | 24059244 | 54.69 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHipsterWord/Faker_math-8 | 21708511 | 52.98 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHipsterWord/Faker_crypto-8 | 2870858 | 396.1 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHipsterSentence/package-8 | 1278764 | 927.7 ns/op | 288 B/op | 3 allocs/op | -| BenchmarkHipsterSentence/Faker_math-8 | 1287939 | 955.0 ns/op | 288 B/op | 3 allocs/op | -| BenchmarkHipsterSentence/Faker_crypto-8 | 237703 | 4595 ns/op | 288 B/op | 3 allocs/op | -| BenchmarkHipsterParagraph/package-8 | 57895 | 18466 ns/op | 10521 B/op | 48 allocs/op | -| BenchmarkHipsterParagraph/Faker_math-8 | 61772 | 19188 ns/op | 10520 B/op | 48 allocs/op | -| BenchmarkHipsterParagraph/Faker_crypto-8 | 12978 | 91733 ns/op | 10522 B/op | 48 allocs/op | -| BenchmarkInputName/package-8 | 15728428 | 74.49 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkInputName/Faker_math-8 | 13243030 | 89.75 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkInputName/Faker_crypto-8 | 2736225 | 478.4 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkSvg/package-8 | 172828 | 7906 ns/op | 8871 B/op | 52 allocs/op | -| BenchmarkSvg/Faker_math-8 | 161821 | 6754 ns/op | 8875 B/op | 52 allocs/op | -| BenchmarkSvg/Faker_crypto-8 | 29023 | 40910 ns/op | 8862 B/op | 52 allocs/op | -| BenchmarkImageURL/package-8 | 11692422 | 94.34 ns/op | 38 B/op | 3 allocs/op | -| BenchmarkImageURL/Faker_math-8 | 11451087 | 91.39 ns/op | 38 B/op | 3 allocs/op | -| BenchmarkImageURL/Faker_crypto-8 | 12107578 | 92.30 ns/op | 38 B/op | 3 allocs/op | -| BenchmarkImage/package-8 | 50 | 20495942 ns/op | 2457673 B/op | 307202 allocs/op | -| BenchmarkImage/Faker_math-8 | 51 | 20349126 ns/op | 2457780 B/op | 307202 allocs/op | -| BenchmarkImage/Faker_crypto-8 | 3 | 393591549 ns/op | 2457685 B/op | 307202 allocs/op | -| BenchmarkImageJpeg/package-8 | 31 | 32857846 ns/op | 2982318 B/op | 307214 allocs/op | -| BenchmarkImageJpeg/Faker_math-8 | 34 | 31873165 ns/op | 2982479 B/op | 307214 allocs/op | -| BenchmarkImageJpeg/Faker_crypto-8 | 3 | 387670345 ns/op | 2982357 B/op | 307215 allocs/op | -| BenchmarkImagePng/package-8 | 16 | 65425256 ns/op | 5899024 B/op | 307270 allocs/op | -| BenchmarkImagePng/Faker_math-8 | 18 | 67804235 ns/op | 5899314 B/op | 307270 allocs/op | -| BenchmarkImagePng/Faker_crypto-8 | 3 | 396378778 ns/op | 5899005 B/op | 307270 allocs/op | -| BenchmarkDomainName/package-8 | 2344912 | 505.6 ns/op | 95 B/op | 5 allocs/op | -| BenchmarkDomainName/Faker_math-8 | 2265744 | 512.5 ns/op | 95 B/op | 5 allocs/op | -| BenchmarkDomainName/Faker_crypto-8 | 639775 | 1788 ns/op | 95 B/op | 5 allocs/op | -| BenchmarkDomainSuffix/package-8 | 19431498 | 59.95 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkDomainSuffix/Faker_math-8 | 20097267 | 59.04 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkDomainSuffix/Faker_crypto-8 | 2498906 | 437.0 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkURL/package-8 | 1000000 | 1155 ns/op | 277 B/op | 10 allocs/op | -| BenchmarkURL/Faker_math-8 | 1000000 | 1165 ns/op | 277 B/op | 10 allocs/op | -| BenchmarkURL/Faker_crypto-8 | 275793 | 4371 ns/op | 276 B/op | 10 allocs/op | -| BenchmarkHTTPMethod/package-8 | 17651594 | 59.20 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHTTPMethod/Faker_math-8 | 20081227 | 61.28 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHTTPMethod/Faker_crypto-8 | 2844322 | 460.1 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkIPv4Address/package-8 | 5215255 | 229.2 ns/op | 16 B/op | 1 allocs/op | -| BenchmarkIPv4Address/Faker_math-8 | 4852905 | 224.9 ns/op | 16 B/op | 1 allocs/op | -| BenchmarkIPv4Address/Faker_crypto-8 | 670951 | 1827 ns/op | 16 B/op | 1 allocs/op | -| BenchmarkIPv6Address/package-8 | 2312482 | 510.0 ns/op | 111 B/op | 8 allocs/op | -| BenchmarkIPv6Address/Faker_math-8 | 2261472 | 521.2 ns/op | 111 B/op | 8 allocs/op | -| BenchmarkIPv6Address/Faker_crypto-8 | 338601 | 3623 ns/op | 111 B/op | 8 allocs/op | -| BenchmarkMacAddress/package-8 | 2809762 | 426.2 ns/op | 24 B/op | 1 allocs/op | -| BenchmarkMacAddress/Faker_math-8 | 2863842 | 425.5 ns/op | 24 B/op | 1 allocs/op | -| BenchmarkMacAddress/Faker_crypto-8 | 376604 | 2688 ns/op | 24 B/op | 1 allocs/op | -| BenchmarkHTTPStatusCode/package-8 | 13488582 | 88.27 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHTTPStatusCode/Faker_math-8 | 14188726 | 73.23 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHTTPStatusCode/Faker_crypto-8 | 2497014 | 463.7 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHTTPStatusCodeSimple/package-8 | 17822486 | 81.54 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHTTPStatusCodeSimple/Faker_math-8 | 16282341 | 70.72 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkHTTPStatusCodeSimple/Faker_crypto-8 | 2360576 | 451.7 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLogLevel/package-8 | 19343472 | 67.40 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLogLevel/Faker_math-8 | 19445798 | 61.84 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLogLevel/Faker_crypto-8 | 2296162 | 468.5 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkUserAgent/package-8 | 1503814 | 813.9 ns/op | 297 B/op | 5 allocs/op | -| BenchmarkUserAgent/Faker_math-8 | 1462177 | 803.6 ns/op | 298 B/op | 5 allocs/op | -| BenchmarkUserAgent/Faker_crypto-8 | 181178 | 6157 ns/op | 298 B/op | 5 allocs/op | -| BenchmarkChromeUserAgent/package-8 | 1911201 | 596.8 ns/op | 184 B/op | 5 allocs/op | -| BenchmarkChromeUserAgent/Faker_math-8 | 1969712 | 598.1 ns/op | 184 B/op | 5 allocs/op | -| BenchmarkChromeUserAgent/Faker_crypto-8 | 264816 | 4433 ns/op | 184 B/op | 5 allocs/op | -| BenchmarkFirefoxUserAgent/package-8 | 1000000 | 1043 ns/op | 362 B/op | 6 allocs/op | -| BenchmarkFirefoxUserAgent/Faker_math-8 | 1000000 | 1054 ns/op | 362 B/op | 6 allocs/op | -| BenchmarkFirefoxUserAgent/Faker_crypto-8 | 166128 | 7646 ns/op | 362 B/op | 6 allocs/op | -| BenchmarkSafariUserAgent/package-8 | 1000000 | 1022 ns/op | 551 B/op | 7 allocs/op | -| BenchmarkSafariUserAgent/Faker_math-8 | 1000000 | 1017 ns/op | 551 B/op | 7 allocs/op | -| BenchmarkSafariUserAgent/Faker_crypto-8 | 146463 | 7525 ns/op | 551 B/op | 7 allocs/op | -| BenchmarkOperaUserAgent/package-8 | 1844185 | 643.8 ns/op | 212 B/op | 5 allocs/op | -| BenchmarkOperaUserAgent/Faker_math-8 | 1805168 | 654.3 ns/op | 212 B/op | 5 allocs/op | -| BenchmarkOperaUserAgent/Faker_crypto-8 | 219927 | 5257 ns/op | 212 B/op | 5 allocs/op | -| BenchmarkJSONLookup100-8 | 894 | 1194698 ns/op | 537673 B/op | 8141 allocs/op | -| BenchmarkJSONLookup1000-8 | 91 | 12099728 ns/op | 5616708 B/op | 81606 allocs/op | -| BenchmarkJSONLookup10000-8 | 8 | 128144166 ns/op | 62638763 B/op | 817708 allocs/op | -| BenchmarkJSONLookup100000-8 | 1 | 1324756016 ns/op | 616116744 B/op | 8179136 allocs/op | -| BenchmarkLanguage/package-8 | 20946056 | 68.53 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLanguage/Faker_math-8 | 16884613 | 61.06 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLanguage/Faker_crypto-8 | 2889944 | 442.0 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLanguageAbbreviation/package-8 | 20782443 | 53.79 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLanguageAbbreviation/Faker_math-8 | 17936367 | 56.26 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLanguageAbbreviation/Faker_crypto-8 | 2630406 | 423.8 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLanguageBCP/package-8 | 19858063 | 59.00 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLanguageBCP/Faker_math-8 | 20712447 | 60.02 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLanguageBCP/Faker_crypto-8 | 2654044 | 469.2 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkProgrammingLanguage/package-8 | 17849598 | 58.34 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkProgrammingLanguage/Faker_math-8 | 20090289 | 70.59 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkProgrammingLanguage/Faker_crypto-8 | 2628798 | 424.4 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkProgrammingLanguageBest/package-8 | 1000000000 | 0.4044 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkProgrammingLanguageBest/Faker_math-8 | 1000000000 | 0.2975 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkProgrammingLanguageBest/Faker_crypto-8 | 1000000000 | 0.2543 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLoremIpsumWord-8 | 22434632 | 54.96 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkLoremIpsumSentence-8 | 1000000 | 1038 ns/op | 219 B/op | 2 allocs/op | -| BenchmarkLoremIpsumParagraph-8 | 59320 | 19442 ns/op | 8479 B/op | 40 allocs/op | -| BenchmarkMinecraftOre/package-8 | 14624242 | 90.01 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftOre/Faker_math-8 | 16379578 | 86.91 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftOre/Faker_crypto-8 | 2757652 | 477.0 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftWood/package-8 | 15815132 | 83.23 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftWood/Faker_math-8 | 14872902 | 75.36 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftWood/Faker_crypto-8 | 2524514 | 514.4 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftArmorTier/package-8 | 15296107 | 78.58 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftArmorTier/Faker_math-8 | 14341870 | 86.33 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftArmorTier/Faker_crypto-8 | 2344278 | 473.1 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftArmorPart/package-8 | 16863422 | 82.04 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftArmorPart/Faker_math-8 | 14052031 | 76.92 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftArmorPart/Faker_crypto-8 | 2770314 | 474.5 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftWeapon/package-8 | 15759004 | 77.42 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftWeapon/Faker_math-8 | 15945940 | 81.48 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftWeapon/Faker_crypto-8 | 2254436 | 464.5 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftTool/package-8 | 15887787 | 76.39 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftTool/Faker_math-8 | 14269508 | 91.01 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftTool/Faker_crypto-8 | 2718507 | 525.7 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftDye/package-8 | 16131942 | 71.06 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftDye/Faker_math-8 | 16802478 | 73.40 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftDye/Faker_crypto-8 | 2584966 | 476.4 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftFood/package-8 | 14680048 | 87.15 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftFood/Faker_math-8 | 13558227 | 86.71 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftFood/Faker_crypto-8 | 2329946 | 435.6 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftAnimal/package-8 | 15871832 | 85.92 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftAnimal/Faker_math-8 | 12411510 | 83.88 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftAnimal/Faker_crypto-8 | 2528960 | 441.9 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftVillagerJob/package-8 | 13549438 | 80.41 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftVillagerJob/Faker_math-8 | 13769702 | 104.5 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftVillagerJob/Faker_crypto-8 | 2397300 | 452.2 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftVillagerStation/package-8 | 15069139 | 93.65 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftVillagerStation/Faker_math-8 | 15468883 | 82.27 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftVillagerStation/Faker_crypto-8 | 2469778 | 453.9 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftVillagerLevel/package-8 | 13468396 | 102.1 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftVillagerLevel/Faker_math-8 | 14354506 | 92.55 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftVillagerLevel/Faker_crypto-8 | 2416441 | 544.5 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftMobPassive/package-8 | 13299806 | 84.84 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftMobPassive/Faker_math-8 | 14181126 | 87.18 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftMobPassive/Faker_crypto-8 | 2539264 | 510.0 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftMobNeutral/package-8 | 11043175 | 110.7 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftMobNeutral/Faker_math-8 | 13059249 | 99.36 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftMobNeutral/Faker_crypto-8 | 2394342 | 544.6 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftMobHostile/package-8 | 13963809 | 95.66 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftMobHostile/Faker_math-8 | 15182318 | 96.90 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftMobHostile/Faker_crypto-8 | 2204600 | 538.3 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftMobBoss/package-8 | 12737437 | 89.68 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftMobBoss/Faker_math-8 | 13494093 | 90.65 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftMobBoss/Faker_crypto-8 | 2671172 | 461.3 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftBiome/package-8 | 13233918 | 81.47 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftBiome/Faker_math-8 | 16109408 | 85.68 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftBiome/Faker_crypto-8 | 2205704 | 499.4 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftWeather/package-8 | 13371518 | 79.93 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftWeather/Faker_math-8 | 14987182 | 80.69 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkMinecraftWeather/Faker_crypto-8 | 2373735 | 473.6 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBool/package-8 | 75772935 | 15.03 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBool/Faker_math-8 | 76893664 | 19.04 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkBool/Faker_crypto-8 | 3141634 | 376.4 ns/op | 0 B/op | 0 allocs/op | -| BenchmarkUUID/package-8 | 9382911 | 115.3 ns/op | 64 B/op | 2 allocs/op | -| BenchmarkUUID/Faker_math-8 | 9492183 | 114.1 ns/op | 64 B/op | 2 allocs/op | -| BenchmarkUUID/Faker_crypto-8 | 1000000 | 1039 ns/op | 64 B/op | 2 allocs/op | -| BenchmarkShuffleAnySlice/package-8 | 2234314 | 511.5 ns/op | 24 B/op | 1 allocs/op | \ No newline at end of file +| Benchmark | Ops | CPU | MEM | MEM alloc | +|---------------------------------------|----------|----------------|--------------|------------------| +| BenchmarkAddress-10 | 1375822 | 869.4 ns/op | 195 B/op | 5 allocs/op | +|---------------------------------------|----------|----------------|--------------|------------------| +| BenchmarkStreet-10 | 3450486 | 347.3 ns/op | 25 B/op | 2 allocs/op | +| BenchmarkStreetNumber-10 | 8865484 | 134.7 ns/op | 4 B/op | 1 allocs/op | +| BenchmarkStreetPrefix-10 | 19342502 | 60.21 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkStreetName-10 | 19748833 | 60.37 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkStreetSuffix-10 | 19729594 | 60.34 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCity-10 | 20015956 | 59.27 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkState-10 | 19448972 | 61.07 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkStateAbr-10 | 19488494 | 61.04 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkZip-10 | 7568804 | 160.8 ns/op | 5 B/op | 1 allocs/op | +| BenchmarkCountry-10 | 18972093 | 62.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCountryAbr-10 | 19571958 | 69.59 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkLatitude-10 | 61390362 | 19.55 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkLongitude-10 | 61311031 | 19.55 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkLatitudeInRange-10 | 55916792 | 21.42 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkLongitudeInRange-10 | 55720761 | 21.42 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPetName-10 | 20981083 | 55.91 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAnimal-10 | 20565596 | 58.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAnimalType-10 | 19437697 | 63.35 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkFarmAnimal-10 | 16147407 | 73.52 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCat-10 | 17844429 | 67.84 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkDog-10 | 14622160 | 81.74 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBird-10 | 12817699 | 93.56 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAppName-10 | 3149502 | 379.8 ns/op | 25 B/op | 1 allocs/op | +| BenchmarkAppVersion-10 | 8479448 | 141.4 ns/op | 7 B/op | 1 allocs/op | +| BenchmarkAppAuthor-10 | 10185164 | 118.4 ns/op | 8 B/op | 0 allocs/op | +| BenchmarkUsername-10 | 7506927 | 159.2 ns/op | 16 B/op | 2 allocs/op | +| BenchmarkPassword-10 | 277974 | 4278 ns/op | 1657 B/op | 60 allocs/op | +| BenchmarkBeerName-10 | 26747800 | 44.92 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBeerStyle-10 | 18350890 | 65.26 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBeerHop-10 | 25144998 | 47.69 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBeerYeast-10 | 23666304 | 50.52 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBeerMalt-10 | 19719030 | 60.68 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBeerIbu-10 | 34583502 | 34.44 ns/op | 8 B/op | 1 allocs/op | +| BenchmarkBeerAlcohol-10 | 5074156 | 238.5 ns/op | 28 B/op | 2 allocs/op | +| BenchmarkBeerBlg-10 | 4895299 | 244.9 ns/op | 37 B/op | 2 allocs/op | +| BenchmarkBook-10 | 5470438 | 219.3 ns/op | 48 B/op | 1 allocs/op | +| BenchmarkBookTitle-10 | 21608480 | 55.42 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBookAuthor-10 | 20776431 | 57.66 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBookGenre-10 | 16837358 | 71.15 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCar-10 | 3381850 | 354.1 ns/op | 96 B/op | 1 allocs/op | +| BenchmarkCarType-10 | 24185968 | 49.45 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCarFuelType-10 | 23069048 | 51.91 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCarTransmissionType-10 | 21307764 | 56.23 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCarMaker-10 | 20469315 | 58.53 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCarModel-10 | 16555663 | 72.45 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCelebrityActor-10 | 22965316 | 52.18 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCelebrityBusiness-10 | 21951553 | 54.59 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCelebritySport-10 | 17658906 | 67.81 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkColor-10 | 19688874 | 60.67 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNiceColors-10 | 73932027 | 16.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkSafeColor-10 | 24165553 | 49.60 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkHexColor-10 | 4798290 | 249.1 ns/op | 24 B/op | 3 allocs/op | +| BenchmarkRGBColor-10 | 19693560 | 61.06 ns/op | 24 B/op | 1 allocs/op | +| BenchmarkCompany-10 | 25783947 | 46.14 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCompanySuffix-10 | 24720987 | 48.45 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBlurb-10 | 20877235 | 57.81 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBuzzWord-10 | 23336427 | 51.29 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBS-10 | 22074699 | 54.26 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkJob-10 | 4047650 | 295.9 ns/op | 64 B/op | 1 allocs/op | +| BenchmarkJobTitle-10 | 26408619 | 45.52 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkJobDescriptor-10 | 24977818 | 48.01 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkJobLevel-10 | 20871273 | 57.37 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkSlogan-10 | 4598202 | 260.3 ns/op | 41 B/op | 1 allocs/op | +| BenchmarkCSVLookup100-10 | 1118 | 1083290 ns/op | 713669 B/op | 9924 allocs/op | +| BenchmarkEmoji-10 | 22190750 | 53.94 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkEmojiDescription-10 | 21292152 | 56.20 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkEmojiCategory-10 | 19740643 | 60.80 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkEmojiAlias-10 | 16636665 | 71.98 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkEmojiTag-10 | 18367076 | 65.27 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkError-10 | 1585123 | 758.6 ns/op | 288 B/op | 8 allocs/op | +| BenchmarkErrorObject-10 | 6719510 | 176.0 ns/op | 32 B/op | 3 allocs/op | +| BenchmarkErrorDatabase-10 | 5866993 | 205.0 ns/op | 64 B/op | 3 allocs/op | +| BenchmarkErrorGRPC-10 | 5956057 | 201.8 ns/op | 64 B/op | 3 allocs/op | +| BenchmarkErrorHTTP-10 | 3914607 | 311.2 ns/op | 158 B/op | 4 allocs/op | +| BenchmarkErrorHTTPClient-10 | 6034057 | 199.7 ns/op | 52 B/op | 3 allocs/op | +| BenchmarkErrorHTTPServer-10 | 5825484 | 205.8 ns/op | 59 B/op | 3 allocs/op | +| BenchmarkErrorRuntime-10 | 4678354 | 253.6 ns/op | 150 B/op | 3 allocs/op | +| BenchmarkErrorValidation-10 | 1745886 | 685.5 ns/op | 277 B/op | 7 allocs/op | +| BenchmarkFileMimeType-10 | 25133455 | 47.62 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkFileExtension-10 | 20728759 | 57.74 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCusip-10 | 6810276 | 175.2 ns/op | 16 B/op | 1 allocs/op | +| BenchmarkIsin-10 | 1758177 | 684.4 ns/op | 525 B/op | 7 allocs/op | +| BenchmarkFruit-10 | 25126088 | 47.61 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkVegetable-10 | 23948730 | 50.03 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBreakfast-10 | 10403901 | 115.6 ns/op | 32 B/op | 1 allocs/op | +| BenchmarkLunch-10 | 9939966 | 121.6 ns/op | 34 B/op | 1 allocs/op | +| BenchmarkDinner-10 | 10409384 | 115.7 ns/op | 36 B/op | 1 allocs/op | +| BenchmarkDrink-10 | 9209277 | 130.0 ns/op | 7 B/op | 2 allocs/op | +| BenchmarkSnack-10 | 8251453 | 144.8 ns/op | 32 B/op | 1 allocs/op | +| BenchmarkDessert-10 | 9630193 | 124.5 ns/op | 31 B/op | 2 allocs/op | +| BenchmarkGamertag-10 | 2490394 | 479.5 ns/op | 83 B/op | 5 allocs/op | +| BenchmarkDice-10 | 48060315 | 25.16 ns/op | 8 B/op | 1 allocs/op | +| BenchmarkGenerate/package-10 | 435873 | 2836 ns/op | 1187 B/op | 29 allocs/op | +| BenchmarkGenerate/Complex-10 | 140688 | 8538 ns/op | 4552 B/op | 80 allocs/op | +| BenchmarkFixedWidthLookup100-10 | 2074 | 577861 ns/op | 489980 B/op | 8701 allocs/op | +| BenchmarkRegex-10 | 637093 | 1908 ns/op | 1632 B/op | 27 allocs/op | +| BenchmarkRegexEmail-10 | 206439 | 5858 ns/op | 4083 B/op | 90 allocs/op | +| BenchmarkMap-10 | 335659 | 3588 ns/op | 1109 B/op | 16 allocs/op | +| BenchmarkHackerPhrase-10 | 167949 | 7200 ns/op | 3106 B/op | 50 allocs/op | +| BenchmarkHackerAbbreviation-10 | 26049344 | 45.87 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkHackerAdjective-10 | 25004623 | 47.90 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkHackerNoun-10 | 23641378 | 50.72 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkHackerVerb-10 | 19799652 | 60.58 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkHackeringVerb-10 | 20966176 | 57.04 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkReplaceWithNumbers-10 | 1393796 | 859.9 ns/op | 296 B/op | 10 allocs/op | +| BenchmarkHipsterWord-10 | 24402415 | 48.90 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkHipsterSentence-10 | 1306906 | 918.2 ns/op | 288 B/op | 3 allocs/op | +| BenchmarkHipsterParagraph-10 | 66908 | 18036 ns/op | 10521 B/op | 48 allocs/op | +| BenchmarkInputName-10 | 20470465 | 58.45 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkSvg-10 | 235867 | 5062 ns/op | 8875 B/op | 52 allocs/op | +| BenchmarkImageURL-10 | 15412327 | 77.79 ns/op | 38 B/op | 3 allocs/op | +| BenchmarkImage-10 | 63 | 18696842 ns/op | 2457675 B/op | 307202 allocs/op | +| BenchmarkImageJpeg-10 | 38 | 29468572 ns/op | 2982467 B/op | 307217 allocs/op | +| BenchmarkImagePng-10 | 16 | 68482049 ns/op | 5899021 B/op | 307270 allocs/op | +| BenchmarkDomainName-10 | 3059372 | 392.7 ns/op | 95 B/op | 5 allocs/op | +| BenchmarkDomainSuffix-10 | 23718696 | 50.49 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkURL-10 | 1288100 | 944.0 ns/op | 277 B/op | 10 allocs/op | +| BenchmarkHTTPMethod-10 | 21987484 | 54.48 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkIPv4Address-10 | 6136962 | 195.2 ns/op | 16 B/op | 1 allocs/op | +| BenchmarkIPv6Address-10 | 2601337 | 461.5 ns/op | 111 B/op | 8 allocs/op | +| BenchmarkMacAddress-10 | 3300115 | 363.0 ns/op | 24 B/op | 1 allocs/op | +| BenchmarkHTTPStatusCode-10 | 17352846 | 69.17 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkHTTPStatusCodeSimple-10 | 18258100 | 65.57 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkLogLevel-10 | 23441868 | 51.08 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkUserAgent-10 | 1902708 | 630.4 ns/op | 298 B/op | 5 allocs/op | +| BenchmarkChromeUserAgent-10 | 2524466 | 473.4 ns/op | 184 B/op | 5 allocs/op | +| BenchmarkFirefoxUserAgent-10 | 1556302 | 771.4 ns/op | 362 B/op | 6 allocs/op | +| BenchmarkSafariUserAgent-10 | 1543339 | 777.2 ns/op | 551 B/op | 7 allocs/op | +| BenchmarkOperaUserAgent-10 | 2315252 | 517.9 ns/op | 212 B/op | 5 allocs/op | +| BenchmarkJSONLookup100-10 | 938 | 1287307 ns/op | 816308 B/op | 12135 allocs/op | +| BenchmarkLanguage-10 | 25106659 | 47.70 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkLanguageAbbreviation-10 | 26723254 | 44.88 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkLanguageBCP-10 | 23676246 | 50.56 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkProgrammingLanguage-10 | 22303432 | 53.67 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkLoremIpsumWord-10 | 25471666 | 47.06 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkLoremIpsumSentence-10 | 1400270 | 857.5 ns/op | 219 B/op | 2 allocs/op | +| BenchmarkLoremIpsumParagraph-10 | 70117 | 17029 ns/op | 8479 B/op | 40 allocs/op | +| BenchmarkMinecraftOre-10 | 16607262 | 72.11 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftWood-10 | 16687941 | 71.81 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftArmorTier-10 | 16707594 | 71.67 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftArmorPart-10 | 16674888 | 71.96 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftWeapon-10 | 16790241 | 71.49 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftTool-10 | 16686007 | 71.83 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftDye-10 | 16578057 | 72.21 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftFood-10 | 15760260 | 76.06 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftAnimal-10 | 16580454 | 72.37 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftVillagerJob-10 | 16582592 | 72.21 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftVillagerStation-10 | 16320229 | 73.41 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftVillagerLevel-10 | 16137780 | 74.37 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftMobPassive-10 | 16823058 | 71.14 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftMobNeutral-10 | 16455928 | 72.87 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftMobHostile-10 | 15813878 | 75.74 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftMobBoss-10 | 15630010 | 76.57 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftBiome-10 | 16159348 | 74.21 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinecraftWeather-10 | 15548354 | 77.18 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkBool-10 | 74414372 | 16.16 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkUUID-10 | 4171688 | 287.7 ns/op | 48 B/op | 1 allocs/op | +| BenchmarkShuffleAnySlice-10 | 3161480 | 379.2 ns/op | 24 B/op | 1 allocs/op | +| BenchmarkFlipACoin-10 | 74035035 | 16.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMovie-10 | 8781188 | 135.8 ns/op | 32 B/op | 1 allocs/op | +| BenchmarkMovieName-10 | 24128484 | 49.60 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMovieGenre-10 | 23041234 | 52.07 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNumber-10 | 73899970 | 16.14 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkUint8-10 | 72125496 | 16.55 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkUint16-10 | 72266845 | 16.56 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkUint32-10 | 72048993 | 16.55 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkUint64-10 | 72268842 | 16.55 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkUintRange-10 | 74468632 | 16.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkInt8-10 | 73880443 | 16.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkInt16-10 | 74023618 | 16.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkInt32-10 | 72283168 | 16.55 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkInt64-10 | 72318379 | 16.55 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkIntRange-10 | 74263170 | 16.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkFloat32-10 | 73899206 | 16.16 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkFloat32Range-10 | 73803760 | 16.16 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkFloat64-10 | 72352354 | 16.58 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkFloat64Range-10 | 72968102 | 16.41 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkShuffleInts-10 | 9118050 | 131.5 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkRandomInt-10 | 72387454 | 16.57 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkRandomUint-10 | 72164350 | 16.55 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkHexUint8-10 | 27118056 | 44.24 ns/op | 8 B/op | 2 allocs/op | +| BenchmarkHexUint16-10 | 14899891 | 80.26 ns/op | 16 B/op | 2 allocs/op | +| BenchmarkHexUint32-10 | 7935871 | 151.7 ns/op | 32 B/op | 2 allocs/op | +| BenchmarkHexUint64-10 | 4170579 | 287.5 ns/op | 48 B/op | 2 allocs/op | +| BenchmarkHexUint128-10 | 2147535 | 558.7 ns/op | 96 B/op | 2 allocs/op | +| BenchmarkHexUint256-10 | 1000000 | 1104 ns/op | 160 B/op | 2 allocs/op | +| BenchmarkCurrency-10 | 15053848 | 79.94 ns/op | 32 B/op | 1 allocs/op | +| BenchmarkCurrencyShort-10 | 26722684 | 44.80 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCurrencyLong-10 | 25114737 | 47.62 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPrice-10 | 73138586 | 16.33 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCreditCard-10 | 1000000 | 1138 ns/op | 264 B/op | 15 allocs/op | +| BenchmarkCreditCardType-10 | 31956361 | 37.34 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkCreditCardNumber-10 | 1535527 | 781.5 ns/op | 183 B/op | 10 allocs/op | +| BenchmarkCreditCardExp-10 | 11157142 | 106.8 ns/op | 5 B/op | 1 allocs/op | +| BenchmarkCreditCardCvv-10 | 20467788 | 58.54 ns/op | 3 B/op | 1 allocs/op | +| BenchmarkAchRouting-10 | 7131913 | 159.7 ns/op | 16 B/op | 1 allocs/op | +| BenchmarkAchAccount-10 | 5750278 | 208.4 ns/op | 16 B/op | 1 allocs/op | +| BenchmarkBitcoinAddress-10 | 527527 | 2256 ns/op | 715 B/op | 37 allocs/op | +| BenchmarkBitcoinPrivateKey-10 | 1312020 | 915.3 ns/op | 184 B/op | 5 allocs/op | +| BenchmarkName-10 | 7987867 | 149.9 ns/op | 16 B/op | 1 allocs/op | +| BenchmarkFirstName-10 | 23559168 | 50.87 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMiddleName-10 | 17695417 | 67.89 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkLastName-10 | 20915487 | 57.27 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNamePrefix-10 | 26101070 | 46.02 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNameSuffix-10 | 22054024 | 54.36 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkSSN-10 | 32379632 | 36.71 ns/op | 16 B/op | 1 allocs/op | +| BenchmarkGender-10 | 74214370 | 16.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkHobby-10 | 17543538 | 68.35 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPerson-10 | 328150 | 3576 ns/op | 836 B/op | 32 allocs/op | +| BenchmarkContact-10 | 1857553 | 643.7 ns/op | 136 B/op | 6 allocs/op | +| BenchmarkPhone-10 | 6788635 | 176.7 ns/op | 16 B/op | 1 allocs/op | +| BenchmarkPhoneFormatted-10 | 4711425 | 253.7 ns/op | 16 B/op | 1 allocs/op | +| BenchmarkEmail-10 | 2846696 | 420.6 ns/op | 88 B/op | 4 allocs/op | +| BenchmarkTeams-10 | 1547748 | 774.7 ns/op | 672 B/op | 10 allocs/op | +| BenchmarkProduct-10 | 207730 | 5835 ns/op | 1068 B/op | 31 allocs/op | +| BenchmarkProductName-10 | 2246737 | 534.4 ns/op | 103 B/op | 5 allocs/op | +| BenchmarkProductDescription-10 | 356503 | 3328 ns/op | 549 B/op | 8 allocs/op | +| BenchmarkProductCategory-10 | 23509492 | 50.94 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkProductFeature-10 | 19975862 | 60.10 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkProductMaterial-10 | 16895538 | 71.03 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkProductUPC-10 | 1367638 | 875.6 ns/op | 96 B/op | 11 allocs/op | +| BenchmarkSchool-10 | 5458804 | 219.7 ns/op | 34 B/op | 1 allocs/op | +| BenchmarkLetter-10 | 71643219 | 16.66 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkLetterN-10 | 5059563 | 236.5 ns/op | 64 B/op | 2 allocs/op | +| BenchmarkVowel-10 | 58373920 | 20.67 ns/op | 4 B/op | 1 allocs/op | +| BenchmarkDigit-10 | 71860232 | 16.71 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkDigitN-10 | 5075998 | 236.8 ns/op | 64 B/op | 2 allocs/op | +| BenchmarkNumerify-10 | 6797595 | 176.1 ns/op | 16 B/op | 1 allocs/op | +| BenchmarkLexify-10 | 11170232 | 107.4 ns/op | 8 B/op | 1 allocs/op | +| BenchmarkShuffleStrings-10 | 9975268 | 120.1 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkRandomString-10 | 73696868 | 16.30 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkTemplate-10 | 2539 | 480370 ns/op | 283084 B/op | 4681 allocs/op | +| BenchmarkDate-10 | 10351170 | 115.7 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPastDate-10 | 18027559 | 66.44 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkFutureDate-10 | 18718327 | 64.05 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkDateRange-10 | 8422170 | 142.5 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMonth-10 | 74189328 | 16.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMonthString-10 | 73959368 | 16.16 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkWeekDay-10 | 72201440 | 16.27 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkDay-10 | 74319124 | 16.14 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkYear-10 | 74319318 | 16.14 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkHour-10 | 74070644 | 16.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkMinute-10 | 73946456 | 16.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkSecond-10 | 74276002 | 16.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNanoSecond-10 | 73999466 | 16.13 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkTimeZone-10 | 19861794 | 60.31 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkTimeZoneFull-10 | 16748313 | 71.57 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkTimeZoneAbv-10 | 21469321 | 55.82 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkTimeZoneOffset-10 | 15023388 | 79.76 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkTimeZoneRegion-10 | 16213138 | 73.94 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkWeighted-10 | 29409751 | 40.55 ns/op | 16 B/op | 1 allocs/op | +| BenchmarkAdjective-10 | 7012708 | 171.0 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdjectiveDescriptive-10 | 16624210 | 72.11 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdjectiveQuantitative-10 | 16431452 | 72.88 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdjectiveProper-10 | 17418051 | 68.84 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdjectiveDemonstrative-10 | 16586106 | 72.33 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdjectivePossessive-10 | 16352059 | 73.30 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdjectiveInterrogative-10 | 16728264 | 71.58 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdjectiveIndefinite-10 | 16374865 | 73.25 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdverb-10 | 7213459 | 166.2 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdverbManner-10 | 16105462 | 74.82 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdverbDegree-10 | 17215963 | 69.67 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdverbPlace-10 | 17027968 | 70.44 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdverbTimeDefinite-10 | 16807536 | 71.33 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdverbTimeIndefinite-10 | 16834258 | 71.29 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdverbFrequencyDefinite-10 | 16643116 | 72.10 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkAdverbFrequencyIndefinite-10 | 16712266 | 71.80 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkComment-10 | 1000000 | 1124 ns/op | 258 B/op | 6 allocs/op | +| BenchmarkConnective-10 | 7623532 | 157.5 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkConnectiveTime-10 | 14703411 | 81.57 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkConnectiveComparative-10 | 16663310 | 72.02 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkConnectiveComplaint-10 | 16605826 | 72.29 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkConnectiveListing-10 | 16070548 | 74.58 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkConnectiveCasual-10 | 16650988 | 72.01 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkConnectiveExamplify-10 | 16406899 | 73.16 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkWord-10 | 8424476 | 142.2 ns/op | 3 B/op | 0 allocs/op | +| BenchmarkSentenceSimple-10 | 707913 | 1715 ns/op | 590 B/op | 11 allocs/op | +| BenchmarkInterjection-10 | 16653078 | 71.87 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNoun-10 | 6856959 | 175.0 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNounCommon-10 | 17568795 | 67.45 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNounConcrete-10 | 17735508 | 67.63 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNounAbstract-10 | 17774474 | 67.42 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNounCollectivePeople-10 | 16644973 | 72.10 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNounCollectiveAnimal-10 | 16826046 | 71.30 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNounCollectiveThing-10 | 16829851 | 71.31 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNounCountable-10 | 17706612 | 69.16 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNounUncountable-10 | 17657629 | 67.97 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkNounProper-10 | 11185551 | 106.9 ns/op | 7 B/op | 0 allocs/op | +| BenchmarkNounDeterminer-10 | 17901252 | 67.10 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPhrase-10 | 20295181 | 59.11 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPhraseNoun-10 | 2975310 | 402.1 ns/op | 104 B/op | 2 allocs/op | +| BenchmarkPhraseVerb-10 | 1414914 | 848.5 ns/op | 232 B/op | 6 allocs/op | +| BenchmarkPhraseAdverb-10 | 7854709 | 151.7 ns/op | 9 B/op | 0 allocs/op | +| BenchmarkPhrasePreposition-10 | 2333119 | 516.6 ns/op | 123 B/op | 3 allocs/op | +| BenchmarkPreposition-10 | 9345999 | 128.3 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPrepositionSimple-10 | 16774008 | 71.50 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPrepositionDouble-10 | 16645617 | 72.09 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPrepositionCompound-10 | 16644290 | 72.30 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPronoun-10 | 6586246 | 182.0 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPronounPersonal-10 | 17675358 | 67.87 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPronounObject-10 | 16869451 | 71.12 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPronounPossessive-10 | 16814512 | 71.37 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPronounReflective-10 | 16223980 | 74.03 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPronounIndefinite-10 | 16787139 | 71.50 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPronounDemonstrative-10 | 16522154 | 72.55 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPronounInterrogative-10 | 16784683 | 71.50 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPronounRelative-10 | 17615938 | 68.12 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkSentence-10 | 755766 | 1599 ns/op | 219 B/op | 3 allocs/op | +| BenchmarkParagraph-10 | 40198 | 29978 ns/op | 6686 B/op | 53 allocs/op | +| BenchmarkQuestion-10 | 1714515 | 700.9 ns/op | 242 B/op | 3 allocs/op | +| BenchmarkQuote-10 | 1477675 | 810.9 ns/op | 261 B/op | 3 allocs/op | +| BenchmarkVerb-10 | 9484125 | 126.5 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkVerbAction-10 | 17250270 | 69.67 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkVerbTransitive-10 | 17820943 | 67.54 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkVerbIntransitive-10 | 16775746 | 71.37 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkVerbLinking-10 | 17926422 | 66.91 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkVerbHelping-10 | 17875374 | 66.91 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkXMLLookup100-10 | 908 | 1314152 ns/op | 862571 B/op | 11370 allocs/op | \ No newline at end of file diff --git a/README.md b/README.md index b42992d1..1f27284d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ ![alt text](https://raw.githubusercontent.com/brianvoe/gofakeit/master/logo.png) -# Gofakeit [![Go Report Card](https://goreportcard.com/badge/github.com/brianvoe/gofakeit)](https://goreportcard.com/report/github.com/brianvoe/gofakeit) ![Test](https://github.com/brianvoe/gofakeit/workflows/Test/badge.svg?branch=master) [![GoDoc](https://godoc.org/github.com/brianvoe/gofakeit/v6?status.svg)](https://godoc.org/github.com/brianvoe/gofakeit/v6) [![license](http://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/brianvoe/gofakeit/master/LICENSE.txt) +# Gofakeit [![Go Report Card](https://goreportcard.com/badge/github.com/brianvoe/gofakeit)](https://goreportcard.com/report/github.com/brianvoe/gofakeit) ![Test](https://github.com/brianvoe/gofakeit/workflows/Test/badge.svg?branch=master) [![GoDoc](https://godoc.org/github.com/brianvoe/gofakeit/v7?status.svg)](https://godoc.org/github.com/brianvoe/gofakeit/v7) [![license](http://img.shields.io/badge/license-MIT-green.svg?style=flat)](https://raw.githubusercontent.com/brianvoe/gofakeit/master/LICENSE.txt) Random data generator written in go @@ -33,13 +33,13 @@ Thank you to all our Gofakeit contributors! ## Installation ```go -go get github.com/brianvoe/gofakeit/v6 +go get github.com/brianvoe/gofakeit/v7 ``` ## Simple Usage ```go -import "github.com/brianvoe/gofakeit/v6" +import "github.com/brianvoe/gofakeit/v7" gofakeit.Name() // Markus Moen gofakeit.Email() // alaynawuckert@kozey.biz @@ -65,7 +65,7 @@ If you need a reproducible outcome you can set it via the Seed function call. Ev this repo sets it for testing purposes. ```go -import "github.com/brianvoe/gofakeit/v6" +import "github.com/brianvoe/gofakeit/v7" gofakeit.Seed(0) // If 0 will use crypto/rand to generate a number @@ -76,25 +76,43 @@ gofakeit.Seed(8675309) // Set it to whatever number you want ## Random Sources -Gofakeit has a few rand sources, by default it uses math.Rand and uses mutex locking to allow for safe goroutines. +Gofakeit has a few rand sources, by default it uses math/rand/v2 PCG which is a pseudo random number generator and is thread locked. -If you want to use a more performant source please use NewUnlocked. Be aware that it is not goroutine safe. +If you want to see other potential sources you can see the sub package [Source](https://pkg.go.dev/github.com/brianvoe/gofakeit/v7/source) for more information. ```go -import "github.com/brianvoe/gofakeit/v6" +import ( + "github.com/brianvoe/gofakeit/v7" + "github.com/brianvoe/gofakeit/v7/source" + "math/rand/v2" +) -// Uses math/rand(Pseudo) with mutex locking +// Uses math/rand/v2(PCG Pseudo) with mutex locking faker := gofakeit.New(0) -// Uses math/rand(Pseudo) with NO mutext locking -// More performant but not goroutine safe. -faker := gofakeit.NewUnlocked(0) +// NewFaker takes in a source and whether or not it should be thread safe +faker := gofakeit.NewFaker(source rand.Source, threadSafe bool) -// Uses crypto/rand(cryptographically secure) with mutext locking -faker := gofakeit.NewCrypto() +// PCG Pseudo +faker := gofakeit.NewFaker(rand.NewPCG(11, 11), true) -// Pass in your own random source -faker := gofakeit.NewCustom() +// ChaCha8 +faker := gofakeit.NewFaker(rand.NewChaCha8([32]byte{0, 1, 2, 3, 4, 5}), true) + + +// Additional from Gofakeit sub package source + +// JSF(Jenkins Small Fast) +faker := gofakeit.NewFaker(source.NewJSF(11), true) + +// SFC(Simple Fast Counter) +faker := gofakeit.NewFaker(source.NewSFC(11), true) + +// Crypto - Uses crypto/rand +faker := gofakeit.NewFaker(source.NewCrypto(), true) + +// Dumb - simple incrementing number +faker := gofakeit.NewFaker(source.NewDumb(11), true) ``` ## Global Rand Set @@ -103,10 +121,13 @@ If you would like to use the simple function calls but need to use something lik crypto/rand you can override the default global with the random source that you want. ```go -import "github.com/brianvoe/gofakeit/v6" +import ( + "github.com/brianvoe/gofakeit/v7" + "math/rand/v2" +) -faker := gofakeit.NewCrypto() -gofakeit.SetGlobalFaker(faker) +faker := gofakeit.New(0) +gofakeit.GlobalFaker = faker ``` ## Struct @@ -117,7 +138,7 @@ as well as some non-basic like time.Time. Struct fields can also use tags to more specifically generate data for that field type. ```go -import "github.com/brianvoe/gofakeit/v6" +import "github.com/brianvoe/gofakeit/v7" // Create structs with random injected data type Foo struct { @@ -147,14 +168,14 @@ type Bar struct { // Pass your struct as a pointer var f Foo -gofakeit.Struct(&f) +err := gofakeit.Struct(&f) fmt.Println(f.Str) // hrukpttuezptneuvunh fmt.Println(f.Int) // -7825289004089916589 fmt.Println(*f.Pointer) // -343806609094473732 fmt.Println(f.Name) // fred fmt.Println(f.Sentence) // Record river mind. -fmt.Println(f.RandStr) // world +fmt.Println(fStr) // world fmt.Println(f.Number) // 4 fmt.Println(f.Regex) // cbdfc fmt.Println(f.Map) // map[PxLIo:52 lxwnqhqc:846] @@ -229,8 +250,8 @@ gofakeit.AddFuncLookup("friendname", gofakeit.Info{ Description: "Random friend name", Example: "bill", Output: "string", - Generate: func(r *rand.Rand, m *gofakeit.MapParams, info *gofakeit.Info) (any, error) { - return gofakeit.RandomString([]string{"bill", "bob", "sally"}), nil + Generate: func(f *Faker, m *gofakeit.MapParams, info *gofakeit.Info) (any, error) { + return f.RandomString([]string{"bill", "bob", "sally"}), nil }, }) @@ -243,14 +264,14 @@ gofakeit.AddFuncLookup("jumbleword", gofakeit.Info{ Params: []gofakeit.Param{ {Field: "word", Type: "string", Description: "Word you want to jumble"}, }, - Generate: func(r *rand.Rand, m *gofakeit.MapParams, info *gofakeit.Info) (any, error) { + Generate: func(f *Faker, m *gofakeit.MapParams, info *gofakeit.Info) (any, error) { word, err := info.GetString(m, "word") if err != nil { return nil, err } split := strings.Split(word, "") - gofakeit.ShuffleStrings(split) + f.ShuffleStrings(split) return strings.Join(split, ""), nil }, }) @@ -301,7 +322,7 @@ Additional Available Functions ### Example Usages ```go -import "github.com/brianvoe/gofakeit/v6" +import "github.com/brianvoe/gofakeit/v7" func main() { // Accessing the Lines variable from within the template. @@ -748,10 +769,14 @@ ProgrammingLanguageBest() string ```go Number(min int, max int) int +Int() int +IntN(n int) int Int8() int8 Int16() int16 Int32() int32 Int64() int64 +Uint() uint +UintN(n uint) uint Uint8() uint8 Uint16() uint16 Uint32() uint32 @@ -762,12 +787,7 @@ Float64() float64 Float64Range(min, max float64) float64 ShuffleInts(a []int) RandomInt(i []int) int -HexUint8() string -HexUint16() string -HexUint32() string -HexUint64() string -HexUint128() string -HexUint256() string +HexUint(bitsize int) string ``` ### String diff --git a/address.go b/address.go index 3c8bc96f..f8e4e7b8 100644 --- a/address.go +++ b/address.go @@ -2,7 +2,6 @@ package gofakeit import ( "errors" - "math/rand" "strings" ) @@ -19,16 +18,16 @@ type AddressInfo struct { } // Address will generate a struct of address information -func Address() *AddressInfo { return address(globalFaker.Rand) } +func Address() *AddressInfo { return address(GlobalFaker) } // Address will generate a struct of address information -func (f *Faker) Address() *AddressInfo { return address(f.Rand) } +func (f *Faker) Address() *AddressInfo { return address(f) } -func address(r *rand.Rand) *AddressInfo { - street := street(r) - city := city(r) - state := state(r) - zip := zip(r) +func address(f *Faker) *AddressInfo { + street := street(f) + city := city(f) + state := state(f) + zip := zip(f) return &AddressInfo{ Address: street + ", " + city + ", " + state + " " + zip, @@ -36,162 +35,162 @@ func address(r *rand.Rand) *AddressInfo { City: city, State: state, Zip: zip, - Country: country(r), - Latitude: latitude(r), - Longitude: longitude(r), + Country: country(f), + Latitude: latitude(f), + Longitude: longitude(f), } } // Street will generate a random address street string -func Street() string { return street(globalFaker.Rand) } +func Street() string { return street(GlobalFaker) } // Street will generate a random address street string -func (f *Faker) Street() string { return street(f.Rand) } +func (f *Faker) Street() string { return street(f) } -func street(r *rand.Rand) string { +func street(f *Faker) string { var street = "" - switch randInt := randIntRange(r, 1, 2); randInt { + switch randInt := randIntRange(f, 1, 2); randInt { case 1: - street = streetNumber(r) + " " + streetPrefix(r) + " " + streetName(r) + streetSuffix(r) + street = streetNumber(f) + " " + streetPrefix(f) + " " + streetName(f) + streetSuffix(f) case 2: - street = streetNumber(r) + " " + streetName(r) + streetSuffix(r) + street = streetNumber(f) + " " + streetName(f) + streetSuffix(f) } return street } // StreetNumber will generate a random address street number string -func StreetNumber() string { return streetNumber(globalFaker.Rand) } +func StreetNumber() string { return streetNumber(GlobalFaker) } // StreetNumber will generate a random address street number string -func (f *Faker) StreetNumber() string { return streetNumber(f.Rand) } +func (f *Faker) StreetNumber() string { return streetNumber(f) } -func streetNumber(r *rand.Rand) string { - return strings.TrimLeft(replaceWithNumbers(r, getRandValue(r, []string{"address", "number"})), "0") +func streetNumber(f *Faker) string { + return strings.TrimLeft(replaceWithNumbers(f, getRandValue(f, []string{"address", "number"})), "0") } // StreetPrefix will generate a random address street prefix string -func StreetPrefix() string { return streetPrefix(globalFaker.Rand) } +func StreetPrefix() string { return streetPrefix(GlobalFaker) } // StreetPrefix will generate a random address street prefix string -func (f *Faker) StreetPrefix() string { return streetPrefix(f.Rand) } +func (f *Faker) StreetPrefix() string { return streetPrefix(f) } -func streetPrefix(r *rand.Rand) string { return getRandValue(r, []string{"address", "street_prefix"}) } +func streetPrefix(f *Faker) string { return getRandValue(f, []string{"address", "street_prefix"}) } // StreetName will generate a random address street name string -func StreetName() string { return streetName(globalFaker.Rand) } +func StreetName() string { return streetName(GlobalFaker) } // StreetName will generate a random address street name string -func (f *Faker) StreetName() string { return streetName(f.Rand) } +func (f *Faker) StreetName() string { return streetName(f) } -func streetName(r *rand.Rand) string { return getRandValue(r, []string{"address", "street_name"}) } +func streetName(f *Faker) string { return getRandValue(f, []string{"address", "street_name"}) } // StreetSuffix will generate a random address street suffix string -func StreetSuffix() string { return streetSuffix(globalFaker.Rand) } +func StreetSuffix() string { return streetSuffix(GlobalFaker) } // StreetSuffix will generate a random address street suffix string -func (f *Faker) StreetSuffix() string { return streetSuffix(f.Rand) } +func (f *Faker) StreetSuffix() string { return streetSuffix(f) } -func streetSuffix(r *rand.Rand) string { return getRandValue(r, []string{"address", "street_suffix"}) } +func streetSuffix(f *Faker) string { return getRandValue(f, []string{"address", "street_suffix"}) } // City will generate a random city string -func City() string { return city(globalFaker.Rand) } +func City() string { return city(GlobalFaker) } // City will generate a random city string -func (f *Faker) City() string { return city(f.Rand) } +func (f *Faker) City() string { return city(f) } -func city(r *rand.Rand) string { return getRandValue(r, []string{"address", "city"}) } +func city(f *Faker) string { return getRandValue(f, []string{"address", "city"}) } // State will generate a random state string -func State() string { return state(globalFaker.Rand) } +func State() string { return state(GlobalFaker) } // State will generate a random state string -func (f *Faker) State() string { return state(f.Rand) } +func (f *Faker) State() string { return state(f) } -func state(r *rand.Rand) string { return getRandValue(r, []string{"address", "state"}) } +func state(f *Faker) string { return getRandValue(f, []string{"address", "state"}) } // StateAbr will generate a random abbreviated state string -func StateAbr() string { return stateAbr(globalFaker.Rand) } +func StateAbr() string { return stateAbr(GlobalFaker) } // StateAbr will generate a random abbreviated state string -func (f *Faker) StateAbr() string { return stateAbr(f.Rand) } +func (f *Faker) StateAbr() string { return stateAbr(f) } -func stateAbr(r *rand.Rand) string { return getRandValue(r, []string{"address", "state_abr"}) } +func stateAbr(f *Faker) string { return getRandValue(f, []string{"address", "state_abr"}) } // Zip will generate a random Zip code string -func Zip() string { return zip(globalFaker.Rand) } +func Zip() string { return zip(GlobalFaker) } // Zip will generate a random Zip code string -func (f *Faker) Zip() string { return zip(f.Rand) } +func (f *Faker) Zip() string { return zip(f) } -func zip(r *rand.Rand) string { - return replaceWithNumbers(r, getRandValue(r, []string{"address", "zip"})) +func zip(f *Faker) string { + return replaceWithNumbers(f, getRandValue(f, []string{"address", "zip"})) } // Country will generate a random country string -func Country() string { return country(globalFaker.Rand) } +func Country() string { return country(GlobalFaker) } // Country will generate a random country string -func (f *Faker) Country() string { return country(f.Rand) } +func (f *Faker) Country() string { return country(f) } -func country(r *rand.Rand) string { return getRandValue(r, []string{"address", "country"}) } +func country(f *Faker) string { return getRandValue(f, []string{"address", "country"}) } // CountryAbr will generate a random abbreviated country string -func CountryAbr() string { return countryAbr(globalFaker.Rand) } +func CountryAbr() string { return countryAbr(GlobalFaker) } // CountryAbr will generate a random abbreviated country string -func (f *Faker) CountryAbr() string { return countryAbr(f.Rand) } +func (f *Faker) CountryAbr() string { return countryAbr(f) } -func countryAbr(r *rand.Rand) string { return getRandValue(r, []string{"address", "country_abr"}) } +func countryAbr(f *Faker) string { return getRandValue(f, []string{"address", "country_abr"}) } // Latitude will generate a random latitude float64 -func Latitude() float64 { return latitude(globalFaker.Rand) } +func Latitude() float64 { return latitude(GlobalFaker) } // Latitude will generate a random latitude float64 -func (f *Faker) Latitude() float64 { return latitude(f.Rand) } +func (f *Faker) Latitude() float64 { return latitude(f) } -func latitude(r *rand.Rand) float64 { return toFixed((r.Float64()*180)-90, 6) } +func latitude(f *Faker) float64 { return toFixed((f.Float64()*180)-90, 6) } // LatitudeInRange will generate a random latitude within the input range func LatitudeInRange(min, max float64) (float64, error) { - return latitudeInRange(globalFaker.Rand, min, max) + return latitudeInRange(GlobalFaker, min, max) } // LatitudeInRange will generate a random latitude within the input range func (f *Faker) LatitudeInRange(min, max float64) (float64, error) { - return latitudeInRange(f.Rand, min, max) + return latitudeInRange(f, min, max) } -func latitudeInRange(r *rand.Rand, min, max float64) (float64, error) { +func latitudeInRange(f *Faker, min, max float64) (float64, error) { if min > max || min < -90 || min > 90 || max < -90 || max > 90 { return 0, errors.New("invalid min or max range, must be valid floats and between -90 and 90") } - return toFixed(float64Range(r, min, max), 6), nil + return toFixed(float64Range(f, min, max), 6), nil } // Longitude will generate a random longitude float64 -func Longitude() float64 { return longitude(globalFaker.Rand) } +func Longitude() float64 { return longitude(GlobalFaker) } // Longitude will generate a random longitude float64 -func (f *Faker) Longitude() float64 { return longitude(f.Rand) } +func (f *Faker) Longitude() float64 { return longitude(f) } -func longitude(r *rand.Rand) float64 { return toFixed((r.Float64()*360)-180, 6) } +func longitude(f *Faker) float64 { return toFixed((f.Float64()*360)-180, 6) } // LongitudeInRange will generate a random longitude within the input range func LongitudeInRange(min, max float64) (float64, error) { - return longitudeInRange(globalFaker.Rand, min, max) + return longitudeInRange(GlobalFaker, min, max) } // LongitudeInRange will generate a random longitude within the input range func (f *Faker) LongitudeInRange(min, max float64) (float64, error) { - return longitudeInRange(f.Rand, min, max) + return longitudeInRange(f, min, max) } -func longitudeInRange(r *rand.Rand, min, max float64) (float64, error) { +func longitudeInRange(f *Faker, min, max float64) (float64, error) { if min > max || min < -180 || min > 180 || max < -180 || max > 180 { return 0, errors.New("invalid min or max range, must be valid floats and between -180 and 180") } - return toFixed(float64Range(r, min, max), 6), nil + return toFixed(float64Range(f, min, max), 6), nil } func addAddressLookup() { @@ -211,8 +210,8 @@ func addAddressLookup() { }`, Output: "map[string]any", ContentType: "application/json", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return address(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return address(f), nil }, }) @@ -222,8 +221,8 @@ func addAddressLookup() { Description: "Part of a country with significant population, often a central hub for culture and commerce", Example: "Marcelside", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return city(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return city(f), nil }, }) @@ -233,8 +232,8 @@ func addAddressLookup() { Description: "Nation with its own government and defined territory", Example: "United States of America", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return country(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return country(f), nil }, }) @@ -244,8 +243,8 @@ func addAddressLookup() { Description: "Shortened 2-letter form of a country's name", Example: "US", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return countryAbr(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return countryAbr(f), nil }, }) @@ -255,8 +254,8 @@ func addAddressLookup() { Description: "Governmental division within a country, often having its own laws and government", Example: "Illinois", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return state(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return state(f), nil }, }) @@ -266,8 +265,8 @@ func addAddressLookup() { Description: "Shortened 2-letter form of a country's state", Example: "IL", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return stateAbr(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return stateAbr(f), nil }, }) @@ -277,8 +276,8 @@ func addAddressLookup() { Description: "Public road in a city or town, typically with houses and buildings on each side", Example: "364 East Rapidsborough", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return street(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return street(f), nil }, }) @@ -288,8 +287,8 @@ func addAddressLookup() { Description: "Name given to a specific road or street", Example: "View", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return streetName(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return streetName(f), nil }, }) @@ -299,8 +298,8 @@ func addAddressLookup() { Description: "Numerical identifier assigned to a street", Example: "13645", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return streetNumber(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return streetNumber(f), nil }, }) @@ -310,8 +309,8 @@ func addAddressLookup() { Description: "Directional or descriptive term preceding a street name, like 'East' or 'Main'", Example: "Lake", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return streetPrefix(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return streetPrefix(f), nil }, }) @@ -321,8 +320,8 @@ func addAddressLookup() { Description: "Designation at the end of a street name indicating type, like 'Avenue' or 'Street'", Example: "land", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return streetSuffix(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return streetSuffix(f), nil }, }) @@ -332,8 +331,8 @@ func addAddressLookup() { Description: "Numerical code for postal address sorting, specific to a geographic area", Example: "13645", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return zip(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return zip(f), nil }, }) @@ -343,8 +342,8 @@ func addAddressLookup() { Description: "Geographic coordinate specifying north-south position on Earth's surface", Example: "-73.534056", Output: "float", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return latitude(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return latitude(f), nil }, }) @@ -358,7 +357,7 @@ func addAddressLookup() { {Field: "min", Display: "Min", Type: "float", Default: "0", Description: "Minimum range"}, {Field: "max", Display: "Max", Type: "float", Default: "90", Description: "Maximum range"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { min, err := info.GetFloat64(m, "min") if err != nil { return nil, err @@ -369,7 +368,7 @@ func addAddressLookup() { return nil, err } - rangeOut, err := latitudeInRange(r, min, max) + rangeOut, err := latitudeInRange(f, min, max) if err != nil { return nil, err } @@ -384,8 +383,8 @@ func addAddressLookup() { Description: "Geographic coordinate indicating east-west position on Earth's surface", Example: "-147.068112", Output: "float", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return longitude(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return longitude(f), nil }, }) @@ -399,7 +398,7 @@ func addAddressLookup() { {Field: "min", Display: "Min", Type: "float", Default: "0", Description: "Minimum range"}, {Field: "max", Display: "Max", Type: "float", Default: "180", Description: "Maximum range"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { min, err := info.GetFloat64(m, "min") if err != nil { return nil, err @@ -410,7 +409,7 @@ func addAddressLookup() { return nil, err } - rangeOut, err := longitudeInRange(r, min, max) + rangeOut, err := longitudeInRange(f, min, max) if err != nil { return nil, err } diff --git a/address_test.go b/address_test.go index ad5385d7..86f0a4c4 100644 --- a/address_test.go +++ b/address_test.go @@ -17,14 +17,14 @@ func ExampleAddress() { fmt.Println(address.Latitude) fmt.Println(address.Longitude) - // Output: 364 Unionsville, Norfolk, Ohio 99536 - // 364 Unionsville - // Norfolk - // Ohio - // 99536 - // Lesotho - // 88.792592 - // 174.504681 + // Output: 125 East Routemouth, North Las Vegas, South Dakota 17999 + // 125 East Routemouth + // North Las Vegas + // South Dakota + // 17999 + // Iran (Islamic Republic of) + // 83.558542 + // -159.896615 } func ExampleFaker_Address() { @@ -39,242 +39,134 @@ func ExampleFaker_Address() { fmt.Println(address.Latitude) fmt.Println(address.Longitude) - // Output: 364 Unionsville, Norfolk, Ohio 99536 - // 364 Unionsville - // Norfolk - // Ohio - // 99536 - // Lesotho - // 88.792592 - // 174.504681 + // Output: 125 East Routemouth, North Las Vegas, South Dakota 17999 + // 125 East Routemouth + // North Las Vegas + // South Dakota + // 17999 + // Iran (Islamic Republic of) + // 83.558542 + // -159.896615 } func BenchmarkAddress(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Address() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Address() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Address() - } - }) + for i := 0; i < b.N; i++ { + Address() + } } func ExampleStreet() { Seed(11) fmt.Println(Street()) - // Output: 364 Unionsville + // Output: 125 East Routemouth } func ExampleFaker_Street() { f := New(11) fmt.Println(f.Street()) - // Output: 364 Unionsville + // Output: 125 East Routemouth } func BenchmarkStreet(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Street() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Street() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Street() - } - }) + for i := 0; i < b.N; i++ { + Street() + } } func ExampleStreetNumber() { Seed(11) fmt.Println(StreetNumber()) - // Output: 13645 + // Output: 812 } func ExampleFaker_StreetNumber() { f := New(11) fmt.Println(f.StreetNumber()) - // Output: 13645 + // Output: 812 } func BenchmarkStreetNumber(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - StreetNumber() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.StreetNumber() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.StreetNumber() - } - }) + for i := 0; i < b.N; i++ { + StreetNumber() + } } func ExampleStreetPrefix() { Seed(11) fmt.Println(StreetPrefix()) - // Output: Lake + // Output: Port } func ExampleFaker_StreetPrefix() { f := New(11) fmt.Println(f.StreetPrefix()) - // Output: Lake + // Output: Port } func BenchmarkStreetPrefix(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - StreetPrefix() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.StreetPrefix() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.StreetPrefix() - } - }) + for i := 0; i < b.N; i++ { + StreetPrefix() + } } func ExampleStreetName() { Seed(11) fmt.Println(StreetName()) - // Output: View + // Output: Turnpike } func ExampleFaker_StreetName() { f := New(11) fmt.Println(f.StreetName()) - // Output: View + // Output: Turnpike } func BenchmarkStreetName(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - StreetName() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.StreetName() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.StreetName() - } - }) + for i := 0; i < b.N; i++ { + StreetName() + } } func ExampleStreetSuffix() { Seed(11) fmt.Println(StreetSuffix()) - // Output: land + // Output: side } func ExampleFaker_StreetSuffix() { f := New(11) fmt.Println(f.StreetSuffix()) - // Output: land + // Output: side } func BenchmarkStreetSuffix(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - StreetSuffix() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.StreetSuffix() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.StreetSuffix() - } - }) + for i := 0; i < b.N; i++ { + StreetSuffix() + } } func ExampleCity() { Seed(11) fmt.Println(City()) - // Output: Plano + // Output: Reno } func ExampleFaker_City() { f := New(11) fmt.Println(f.City()) - // Output: Plano + // Output: Reno } func TestCity(t *testing.T) { @@ -284,293 +176,149 @@ func TestCity(t *testing.T) { } func BenchmarkCity(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - City() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.City() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.City() - } - }) + for i := 0; i < b.N; i++ { + City() + } } func ExampleState() { Seed(11) fmt.Println(State()) - // Output: Hawaii + // Output: Vermont } func ExampleFaker_State() { f := New(11) fmt.Println(f.State()) - // Output: Hawaii + // Output: Vermont } func BenchmarkState(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - State() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.State() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.State() - } - }) + for i := 0; i < b.N; i++ { + State() + } } func ExampleStateAbr() { Seed(11) fmt.Println(StateAbr()) - // Output: CO + // Output: WV } func ExampleFaker_StateAbr() { f := New(11) fmt.Println(f.StateAbr()) - // Output: CO + // Output: WV } func BenchmarkStateAbr(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - StateAbr() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.StateAbr() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.StateAbr() - } - }) + for i := 0; i < b.N; i++ { + StateAbr() + } } func ExampleZip() { Seed(11) fmt.Println(Zip()) - // Output: 13645 + // Output: 81252 } func ExampleFaker_Zip() { f := New(11) fmt.Println(f.Zip()) - // Output: 13645 + // Output: 81252 } func BenchmarkZip(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Zip() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Zip() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Zip() - } - }) + for i := 0; i < b.N; i++ { + Zip() + } } func ExampleCountry() { Seed(11) fmt.Println(Country()) - // Output: Cabo Verde + // Output: Tonga } func ExampleFaker_Country() { f := New(11) fmt.Println(f.Country()) - // Output: Cabo Verde + // Output: Tonga } func BenchmarkCountry(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Country() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Country() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Country() - } - }) + for i := 0; i < b.N; i++ { + Country() + } } func ExampleCountryAbr() { Seed(11) fmt.Println(CountryAbr()) - // Output: CV + // Output: TO } func ExampleFaker_CountryAbr() { f := New(11) fmt.Println(f.CountryAbr()) - // Output: CV + // Output: TO } func BenchmarkCountryAbr(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - CountryAbr() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.CountryAbr() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.CountryAbr() - } - }) + for i := 0; i < b.N; i++ { + CountryAbr() + } } func ExampleLatitude() { Seed(11) fmt.Println(Latitude()) - // Output: -73.534057 + // Output: 48.654167 } func ExampleFaker_Latitude() { f := New(11) fmt.Println(f.Latitude()) - // Output: -73.534057 + // Output: 48.654167 } func BenchmarkLatitude(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Latitude() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Latitude() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Latitude() - } - }) + for i := 0; i < b.N; i++ { + Latitude() + } } func ExampleLongitude() { Seed(11) fmt.Println(Longitude()) - // Output: -147.068113 + // Output: 97.308335 } func ExampleFaker_Longitude() { f := New(11) fmt.Println(f.Longitude()) - // Output: -147.068113 + // Output: 97.308335 } func BenchmarkLongitude(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Longitude() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Longitude() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Longitude() - } - }) + for i := 0; i < b.N; i++ { + Longitude() + } } func TestLatitudeInRange(t *testing.T) { @@ -600,7 +348,7 @@ func ExampleLatitudeInRange() { lat, _ := LatitudeInRange(21, 42) fmt.Println(lat) - // Output: 22.921026 + // Output: 37.176319 } func ExampleFaker_LatitudeInRange() { @@ -608,31 +356,13 @@ func ExampleFaker_LatitudeInRange() { lat, _ := f.LatitudeInRange(21, 42) fmt.Println(lat) - // Output: 22.921026 + // Output: 37.176319 } func BenchmarkLatitudeInRange(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - LatitudeInRange(-90, 90) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.LatitudeInRange(-90, 90) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.LatitudeInRange(-90, 90) - } - }) + for i := 0; i < b.N; i++ { + LatitudeInRange(-90, 90) + } } func TestLongitudeInRange(t *testing.T) { @@ -662,7 +392,7 @@ func ExampleLongitudeInRange() { long, _ := LongitudeInRange(-10, 10) fmt.Println(long) - // Output: -8.170451 + // Output: 5.406018 } func ExampleFaker_LongitudeInRange() { @@ -670,29 +400,11 @@ func ExampleFaker_LongitudeInRange() { long, _ := f.LongitudeInRange(-10, 10) fmt.Println(long) - // Output: -8.170451 + // Output: 5.406018 } func BenchmarkLongitudeInRange(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - LongitudeInRange(-180, 180) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.LongitudeInRange(-180, 180) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.LongitudeInRange(-180, 180) - } - }) + for i := 0; i < b.N; i++ { + LongitudeInRange(-180, 180) + } } diff --git a/animal.go b/animal.go index 56772ea9..b70438b6 100644 --- a/animal.go +++ b/animal.go @@ -1,103 +1,101 @@ package gofakeit -import "math/rand" - // PetName will return a random fun pet name func PetName() string { - return petName(globalFaker.Rand) + return petName(GlobalFaker) } // PetName will return a random fun pet name func (f *Faker) PetName() string { - return petName(f.Rand) + return petName(f) } -func petName(r *rand.Rand) string { - return getRandValue(r, []string{"animal", "petname"}) +func petName(f *Faker) string { + return getRandValue(f, []string{"animal", "petname"}) } // Animal will return a random animal func Animal() string { - return animal(globalFaker.Rand) + return animal(GlobalFaker) } // Animal will return a random animal func (f *Faker) Animal() string { - return animal(f.Rand) + return animal(f) } -func animal(r *rand.Rand) string { - return getRandValue(r, []string{"animal", "animal"}) +func animal(f *Faker) string { + return getRandValue(f, []string{"animal", "animal"}) } // AnimalType will return a random animal type func AnimalType() string { - return animalType(globalFaker.Rand) + return animalType(GlobalFaker) } // AnimalType will return a random animal type func (f *Faker) AnimalType() string { - return animalType(f.Rand) + return animalType(f) } -func animalType(r *rand.Rand) string { - return getRandValue(r, []string{"animal", "type"}) +func animalType(f *Faker) string { + return getRandValue(f, []string{"animal", "type"}) } // FarmAnimal will return a random animal that usually lives on a farm func FarmAnimal() string { - return farmAnimal(globalFaker.Rand) + return farmAnimal(GlobalFaker) } // FarmAnimal will return a random animal that usually lives on a farm func (f *Faker) FarmAnimal() string { - return farmAnimal(f.Rand) + return farmAnimal(f) } -func farmAnimal(r *rand.Rand) string { - return getRandValue(r, []string{"animal", "farm"}) +func farmAnimal(f *Faker) string { + return getRandValue(f, []string{"animal", "farm"}) } // Cat will return a random cat breed func Cat() string { - return cat(globalFaker.Rand) + return cat(GlobalFaker) } // Cat will return a random cat breed func (f *Faker) Cat() string { - return cat(f.Rand) + return cat(f) } -func cat(r *rand.Rand) string { - return getRandValue(r, []string{"animal", "cat"}) +func cat(f *Faker) string { + return getRandValue(f, []string{"animal", "cat"}) } // Dog will return a random dog breed func Dog() string { - return dog(globalFaker.Rand) + return dog(GlobalFaker) } // Dog will return a random dog breed func (f *Faker) Dog() string { - return dog(f.Rand) + return dog(f) } -func dog(r *rand.Rand) string { - return getRandValue(r, []string{"animal", "dog"}) +func dog(f *Faker) string { + return getRandValue(f, []string{"animal", "dog"}) } // Bird will return a random bird species func Bird() string { - return bird(globalFaker.Rand) + return bird(GlobalFaker) } // Bird will return a random bird species func (f *Faker) Bird() string { - return bird(f.Rand) + return bird(f) } -func bird(r *rand.Rand) string { - return getRandValue(r, []string{"animal", "bird"}) +func bird(f *Faker) string { + return getRandValue(f, []string{"animal", "bird"}) } func addAnimalLookup() { @@ -107,8 +105,8 @@ func addAnimalLookup() { Description: "Affectionate nickname given to a pet", Example: "Ozzy Pawsborne", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return petName(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return petName(f), nil }, }) @@ -118,8 +116,8 @@ func addAnimalLookup() { Description: "Living creature with the ability to move, eat, and interact with its environment", Example: "elk", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return animal(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return animal(f), nil }, }) @@ -129,8 +127,8 @@ func addAnimalLookup() { Description: "Type of animal, such as mammals, birds, reptiles, etc.", Example: "amphibians", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return animalType(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return animalType(f), nil }, }) @@ -140,8 +138,8 @@ func addAnimalLookup() { Description: "Animal name commonly found on a farm", Example: "Chicken", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return farmAnimal(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return farmAnimal(f), nil }, }) @@ -151,8 +149,8 @@ func addAnimalLookup() { Description: "Various breeds that define different cats", Example: "Chausie", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return cat(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return cat(f), nil }, }) @@ -162,8 +160,8 @@ func addAnimalLookup() { Description: "Various breeds that define different dogs", Example: "Norwich Terrier", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return dog(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return dog(f), nil }, }) @@ -173,8 +171,8 @@ func addAnimalLookup() { Description: "Distinct species of birds", Example: "goose", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return bird(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return bird(f), nil }, }) } diff --git a/animal_test.go b/animal_test.go index 580cfff5..26af90dc 100644 --- a/animal_test.go +++ b/animal_test.go @@ -9,152 +9,80 @@ func ExamplePetName() { Seed(11) fmt.Println(PetName()) - // Output: Ozzy Pawsborne + // Output: The Notorious D.O.G. } func ExampleFaker_PetName() { f := New(11) fmt.Println(f.PetName()) - // Output: Ozzy Pawsborne + // Output: The Notorious D.O.G. } func BenchmarkPetName(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - PetName() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.PetName() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.PetName() - } - }) + for i := 0; i < b.N; i++ { + PetName() + } } func ExampleAnimal() { Seed(11) fmt.Println(Animal()) - // Output: elk + // Output: turtle } func ExampleFaker_Animal() { f := New(11) fmt.Println(f.Animal()) - // Output: elk + // Output: turtle } func BenchmarkAnimal(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Animal() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Animal() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Animal() - } - }) + for i := 0; i < b.N; i++ { + Animal() + } } func ExampleAnimalType() { Seed(11) fmt.Println(AnimalType()) - // Output: amphibians + // Output: reptiles } func ExampleFaker_AnimalType() { f := New(11) fmt.Println(f.AnimalType()) - // Output: amphibians + // Output: reptiles } func BenchmarkAnimalType(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - AnimalType() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.AnimalType() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.AnimalType() - } - }) + for i := 0; i < b.N; i++ { + AnimalType() + } } func ExampleFarmAnimal() { Seed(11) fmt.Println(FarmAnimal()) - // Output: Chicken + // Output: Sheep } func ExampleFaker_FarmAnimal() { f := New(11) fmt.Println(f.FarmAnimal()) - // Output: Chicken + // Output: Sheep } func BenchmarkFarmAnimal(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - FarmAnimal() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.FarmAnimal() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.FarmAnimal() - } - }) + for i := 0; i < b.N; i++ { + FarmAnimal() + } } func ExampleCat() { @@ -172,101 +100,47 @@ func ExampleFaker_Cat() { } func BenchmarkCat(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Cat() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Cat() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Cat() - } - }) + for i := 0; i < b.N; i++ { + Cat() + } } func ExampleDog() { Seed(11) fmt.Println(Dog()) - // Output: Norwich Terrier + // Output: Rat Terrier } func ExampleFaker_Dog() { f := New(11) fmt.Println(f.Dog()) - // Output: Norwich Terrier + // Output: Rat Terrier } func BenchmarkDog(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Dog() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Dog() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Dog() - } - }) + for i := 0; i < b.N; i++ { + Dog() + } } func ExampleBird() { Seed(11) fmt.Println(Bird()) - // Output: goose + // Output: toucan } func ExampleFaker_Bird() { f := New(11) fmt.Println(f.Bird()) - // Output: goose + // Output: toucan } func BenchmarkBird(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Bird() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Bird() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Bird() - } - }) + for i := 0; i < b.N; i++ { + Bird() + } } diff --git a/app.go b/app.go index 172c8179..9c66cd5c 100644 --- a/app.go +++ b/app.go @@ -2,28 +2,27 @@ package gofakeit import ( "fmt" - "math/rand" ) // AppName will generate a random app name func AppName() string { - return appName(globalFaker.Rand) + return appName(GlobalFaker) } // AppName will generate a random app name func (f *Faker) AppName() string { - return appName(f.Rand) + return appName(f) } -func appName(r *rand.Rand) string { +func appName(f *Faker) string { name := "" - switch number(r, 1, 3) { + switch number(f, 1, 3) { case 1: - name = noun(r) + verb(r) + name = noun(f) + verb(f) case 2: - name = color(r) + noun(r) + name = color(f) + noun(f) case 3: - name = animal(r) + verb(r) + name = animal(f) + verb(f) } return title(name) @@ -31,34 +30,34 @@ func appName(r *rand.Rand) string { // AppVersion will generate a random app version func AppVersion() string { - return appVersion(globalFaker.Rand) + return appVersion(GlobalFaker) } // AppVersion will generate a random app version func (f *Faker) AppVersion() string { - return appVersion(f.Rand) + return appVersion(f) } -func appVersion(r *rand.Rand) string { - return fmt.Sprintf("%d.%d.%d", number(r, 1, 5), number(r, 1, 20), number(r, 1, 20)) +func appVersion(f *Faker) string { + return fmt.Sprintf("%d.%d.%d", number(f, 1, 5), number(f, 1, 20), number(f, 1, 20)) } // AppAuthor will generate a random company or person name func AppAuthor() string { - return appAuthor(globalFaker.Rand) + return appAuthor(GlobalFaker) } // AppAuthor will generate a random company or person name func (f *Faker) AppAuthor() string { - return appAuthor(f.Rand) + return appAuthor(f) } -func appAuthor(r *rand.Rand) string { - if boolFunc(r) { - return name(r) +func appAuthor(f *Faker) string { + if boolFunc(f) { + return name(f) } - return company(r) + return company(f) } func addAppLookup() { @@ -68,8 +67,8 @@ func addAppLookup() { Description: "Software program designed for a specific purpose or task on a computer or mobile device", Example: "Parkrespond", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return appName(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return appName(f), nil }, }) @@ -79,8 +78,8 @@ func addAppLookup() { Description: "Particular release of an application in Semantic Versioning format", Example: "1.12.14", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return appVersion(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return appVersion(f), nil }, }) @@ -90,8 +89,8 @@ func addAppLookup() { Description: "Person or group creating and developing an application", Example: "Qado Energy, Inc.", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return appAuthor(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return appAuthor(f), nil }, }) } diff --git a/app_test.go b/app_test.go index 990757cf..6bf4296f 100644 --- a/app_test.go +++ b/app_test.go @@ -9,14 +9,14 @@ func ExampleAppName() { Seed(11) fmt.Println(AppName()) - // Output: Oxbeing + // Output: Swanthink } func ExampleFaker_AppName() { f := New(11) fmt.Println(f.AppName()) - // Output: Oxbeing + // Output: Swanthink } func TestAppName(t *testing.T) { @@ -29,79 +29,43 @@ func TestAppName(t *testing.T) { } func BenchmarkAppName(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - AppName() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.AppName() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.AppName() - } - }) + for i := 0; i < b.N; i++ { + AppName() + } } func ExampleAppVersion() { Seed(11) fmt.Println(AppVersion()) - // Output: 1.17.20 + // Output: 5.18.4 } func ExampleFaker_AppVersion() { f := New(11) fmt.Println(f.AppVersion()) - // Output: 1.17.20 + // Output: 5.18.4 } func BenchmarkAppVersion(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - AppVersion() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.AppVersion() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.AppVersion() - } - }) + for i := 0; i < b.N; i++ { + AppVersion() + } } func ExampleAppAuthor() { Seed(11) fmt.Println(AppAuthor()) - // Output: Marcel Pagac + // Output: StreetEasy } func ExampleFaker_AppAuthor() { f := New(11) fmt.Println(f.AppAuthor()) - // Output: Marcel Pagac + // Output: StreetEasy } func TestAuthor(t *testing.T) { @@ -114,25 +78,7 @@ func TestAuthor(t *testing.T) { } func BenchmarkAppAuthor(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - AppAuthor() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.AppAuthor() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.AppAuthor() - } - }) + for i := 0; i < b.N; i++ { + AppAuthor() + } } diff --git a/auth.go b/auth.go index ae86e3d1..516a0187 100644 --- a/auth.go +++ b/auth.go @@ -1,34 +1,32 @@ package gofakeit -import "math/rand" - // Username will generate a random username based upon picking a random lastname and random numbers at the end func Username() string { - return username(globalFaker.Rand) + return username(GlobalFaker) } // Username will generate a random username based upon picking a random lastname and random numbers at the end func (f *Faker) Username() string { - return username(f.Rand) + return username(f) } -func username(r *rand.Rand) string { - return getRandValue(r, []string{"person", "last"}) + replaceWithNumbers(r, "####") +func username(f *Faker) string { + return getRandValue(f, []string{"person", "last"}) + replaceWithNumbers(f, "####") } // Password will generate a random password. // Minimum number length of 5 if less than. func Password(lower bool, upper bool, numeric bool, special bool, space bool, num int) string { - return password(globalFaker.Rand, lower, upper, numeric, special, space, num) + return password(GlobalFaker, lower, upper, numeric, special, space, num) } // Password will generate a random password. // Minimum number length of 5 if less than. func (f *Faker) Password(lower bool, upper bool, numeric bool, special bool, space bool, num int) string { - return password(f.Rand, lower, upper, numeric, special, space, num) + return password(f, lower, upper, numeric, special, space, num) } -func password(r *rand.Rand, lower bool, upper bool, numeric bool, special bool, space bool, num int) string { +func password(f *Faker, lower bool, upper bool, numeric bool, special bool, space bool, num int) string { // Make sure the num minimum is at least 5 if num < 5 { num = 5 @@ -69,34 +67,34 @@ func password(r *rand.Rand, lower bool, upper bool, numeric bool, special bool, for i := 0; i <= num-1; i++ { // Run weighted - weight, _ := weighted(r, items, weights) + weight, _ := weighted(f, items, weights) switch weight.(string) { case "lower": - b[i] = lowerStr[r.Int63()%int64(len(lowerStr))] + b[i] = lowerStr[f.Int64()%int64(len(lowerStr))] case "upper": - b[i] = upperStr[r.Int63()%int64(len(upperStr))] + b[i] = upperStr[f.Int64()%int64(len(upperStr))] case "numeric": - b[i] = numericStr[r.Int63()%int64(len(numericStr))] + b[i] = numericStr[f.Int64()%int64(len(numericStr))] case "special": - b[i] = specialSafeStr[r.Int63()%int64(len(specialSafeStr))] + b[i] = specialSafeStr[f.Int64()%int64(len(specialSafeStr))] case "space": - b[i] = spaceStr[r.Int63()%int64(len(spaceStr))] + b[i] = spaceStr[f.Int64()%int64(len(spaceStr))] } } // Shuffle bytes for i := range b { - j := r.Intn(i + 1) + j := f.IntN(i + 1) b[i], b[j] = b[j], b[i] } // Replace first or last character if it's a space, and other options are available if b[0] == ' ' { - b[0] = password(r, lower, upper, numeric, special, false, 1)[0] + b[0] = password(f, lower, upper, numeric, special, false, 1)[0] } if b[len(b)-1] == ' ' { - b[len(b)-1] = password(r, lower, upper, numeric, special, false, 1)[0] + b[len(b)-1] = password(f, lower, upper, numeric, special, false, 1)[0] } return string(b) @@ -109,8 +107,8 @@ func addAuthLookup() { Description: "Unique identifier assigned to a user for accessing an account or system", Example: "Daniel1364", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return username(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return username(f), nil }, }) @@ -128,7 +126,7 @@ func addAuthLookup() { {Field: "space", Display: "Space", Type: "bool", Default: "false", Description: "Whether or not to add spaces"}, {Field: "length", Display: "Length", Type: "int", Default: "12", Description: "Number of characters in password"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { lower, err := info.GetBool(m, "lower") if err != nil { return nil, err @@ -159,7 +157,7 @@ func addAuthLookup() { return nil, err } - return password(r, lower, upper, numeric, special, space, length), nil + return password(f, lower, upper, numeric, special, space, length), nil }, }) } diff --git a/auth_test.go b/auth_test.go index ff0e144c..c1f91425 100644 --- a/auth_test.go +++ b/auth_test.go @@ -9,38 +9,20 @@ func ExampleUsername() { Seed(11) fmt.Println(Username()) - // Output: Daniel1364 + // Output: Treutel8125 } func ExampleFaker_Username() { f := New(11) fmt.Println(f.Username()) - // Output: Daniel1364 + // Output: Treutel8125 } func BenchmarkUsername(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Username() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Username() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Username() - } - }) + for i := 0; i < b.N; i++ { + Username() + } } func TestPassword(t *testing.T) { @@ -76,12 +58,12 @@ func ExamplePassword() { fmt.Println(Password(true, true, true, true, true, 32)) fmt.Println(Password(true, true, true, true, true, 4)) - // Output: vodnqxzsuptgehrzylximvylxzoywexw - // ZSRQWJFJWCSTVGXKYKWMLIAFGFELFJRG - // 61718615932495608398906260648432 - // !*&#$$??_!&!#.@@-!_!!$$-?_$&.@-& - // d6UzSwXvJ81 7QPvlse@l ln VmvU5jd - // UKTn2 + // Output: cfelntbponnbbzrhswobuwlxajeeclrx + // KYEKNGUUNKUYSFBUFFTGDKUVCVYKPONP + // 43622637275953627791234759581343 + // !?*-_-?#@!*?@?-&@!*!*?_!#$@@@**@ + // .DTHJ&@oF#d.L5F65 N.-#U5xWX F0DI + // foZnB } func ExampleFaker_Password() { @@ -93,34 +75,16 @@ func ExampleFaker_Password() { fmt.Println(f.Password(true, true, true, true, true, 32)) fmt.Println(f.Password(true, true, true, true, true, 4)) - // Output: vodnqxzsuptgehrzylximvylxzoywexw - // ZSRQWJFJWCSTVGXKYKWMLIAFGFELFJRG - // 61718615932495608398906260648432 - // !*&#$$??_!&!#.@@-!_!!$$-?_$&.@-& - // d6UzSwXvJ81 7QPvlse@l ln VmvU5jd - // UKTn2 + // Output: cfelntbponnbbzrhswobuwlxajeeclrx + // KYEKNGUUNKUYSFBUFFTGDKUVCVYKPONP + // 43622637275953627791234759581343 + // !?*-_-?#@!*?@?-&@!*!*?_!#$@@@**@ + // .DTHJ&@oF#d.L5F65 N.-#U5xWX F0DI + // foZnB } func BenchmarkPassword(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Password(true, true, true, true, true, 50) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Password(true, true, true, true, true, 8) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Password(true, true, true, true, true, 8) - } - }) + for i := 0; i < b.N; i++ { + Password(true, true, true, true, true, 50) + } } diff --git a/beer.go b/beer.go index 292ae680..a6bc493e 100644 --- a/beer.go +++ b/beer.go @@ -1,120 +1,119 @@ package gofakeit import ( - "math/rand" "strconv" ) // BeerName will return a random beer name func BeerName() string { - return beerName(globalFaker.Rand) + return beerName(GlobalFaker) } // BeerName will return a random beer name func (f *Faker) BeerName() string { - return beerName(f.Rand) + return beerName(f) } -func beerName(r *rand.Rand) string { - return getRandValue(r, []string{"beer", "name"}) +func beerName(f *Faker) string { + return getRandValue(f, []string{"beer", "name"}) } // BeerStyle will return a random beer style func BeerStyle() string { - return beerStyle(globalFaker.Rand) + return beerStyle(GlobalFaker) } // BeerStyle will return a random beer style func (f *Faker) BeerStyle() string { - return beerStyle(f.Rand) + return beerStyle(f) } -func beerStyle(r *rand.Rand) string { - return getRandValue(r, []string{"beer", "style"}) +func beerStyle(f *Faker) string { + return getRandValue(f, []string{"beer", "style"}) } // BeerHop will return a random beer hop func BeerHop() string { - return beerHop(globalFaker.Rand) + return beerHop(GlobalFaker) } // BeerHop will return a random beer hop func (f *Faker) BeerHop() string { - return beerHop(f.Rand) + return beerHop(f) } -func beerHop(r *rand.Rand) string { - return getRandValue(r, []string{"beer", "hop"}) +func beerHop(f *Faker) string { + return getRandValue(f, []string{"beer", "hop"}) } // BeerYeast will return a random beer yeast func BeerYeast() string { - return beerYeast(globalFaker.Rand) + return beerYeast(GlobalFaker) } // BeerYeast will return a random beer yeast func (f *Faker) BeerYeast() string { - return beerYeast(f.Rand) + return beerYeast(f) } -func beerYeast(r *rand.Rand) string { - return getRandValue(r, []string{"beer", "yeast"}) +func beerYeast(f *Faker) string { + return getRandValue(f, []string{"beer", "yeast"}) } // BeerMalt will return a random beer malt func BeerMalt() string { - return beerMalt(globalFaker.Rand) + return beerMalt(GlobalFaker) } // BeerMalt will return a random beer malt func (f *Faker) BeerMalt() string { - return beerMalt(f.Rand) + return beerMalt(f) } -func beerMalt(r *rand.Rand) string { - return getRandValue(r, []string{"beer", "malt"}) +func beerMalt(f *Faker) string { + return getRandValue(f, []string{"beer", "malt"}) } // BeerAlcohol will return a random beer alcohol level between 2.0 and 10.0 func BeerAlcohol() string { - return beerAlcohol(globalFaker.Rand) + return beerAlcohol(GlobalFaker) } // BeerAlcohol will return a random beer alcohol level between 2.0 and 10.0 func (f *Faker) BeerAlcohol() string { - return beerAlcohol(f.Rand) + return beerAlcohol(f) } -func beerAlcohol(r *rand.Rand) string { - return strconv.FormatFloat(float64Range(r, 2.0, 10.0), 'f', 1, 64) + "%" +func beerAlcohol(f *Faker) string { + return strconv.FormatFloat(float64Range(f, 2.0, 10.0), 'f', 1, 64) + "%" } // BeerIbu will return a random beer ibu value between 10 and 100 func BeerIbu() string { - return beerIbu(globalFaker.Rand) + return beerIbu(GlobalFaker) } // BeerIbu will return a random beer ibu value between 10 and 100 func (f *Faker) BeerIbu() string { - return beerIbu(f.Rand) + return beerIbu(f) } -func beerIbu(r *rand.Rand) string { - return strconv.Itoa(randIntRange(r, 10, 100)) + " IBU" +func beerIbu(f *Faker) string { + return strconv.Itoa(randIntRange(f, 10, 100)) + " IBU" } // BeerBlg will return a random beer blg between 5.0 and 20.0 func BeerBlg() string { - return beerBlg(globalFaker.Rand) + return beerBlg(GlobalFaker) } // BeerBlg will return a random beer blg between 5.0 and 20.0 func (f *Faker) BeerBlg() string { - return beerBlg(f.Rand) + return beerBlg(f) } -func beerBlg(r *rand.Rand) string { - return strconv.FormatFloat(float64Range(r, 5.0, 20.0), 'f', 1, 64) + "°Blg" +func beerBlg(f *Faker) string { + return strconv.FormatFloat(float64Range(f, 5.0, 20.0), 'f', 1, 64) + "°Blg" } func addBeerLookup() { @@ -124,8 +123,8 @@ func addBeerLookup() { Description: "Specific brand or variety of beer", Example: "Duvel", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return beerName(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return beerName(f), nil }, }) @@ -135,8 +134,8 @@ func addBeerLookup() { Description: "Distinct characteristics and flavors of beer", Example: "European Amber Lager", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return beerStyle(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return beerStyle(f), nil }, }) @@ -146,8 +145,8 @@ func addBeerLookup() { Description: "The flower used in brewing to add flavor, aroma, and bitterness to beer", Example: "Glacier", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return beerHop(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return beerHop(f), nil }, }) @@ -157,8 +156,8 @@ func addBeerLookup() { Description: "Microorganism used in brewing to ferment sugars, producing alcohol and carbonation in beer", Example: "1388 - Belgian Strong Ale", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return beerYeast(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return beerYeast(f), nil }, }) @@ -168,8 +167,8 @@ func addBeerLookup() { Description: "Processed barley or other grains, provides sugars for fermentation and flavor to beer", Example: "Munich", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return beerMalt(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return beerMalt(f), nil }, }) @@ -179,8 +178,8 @@ func addBeerLookup() { Description: "Measures the alcohol content in beer", Example: "2.7%", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return beerAlcohol(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return beerAlcohol(f), nil }, }) @@ -190,8 +189,8 @@ func addBeerLookup() { Description: "Scale measuring bitterness of beer from hops", Example: "29 IBU", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return beerIbu(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return beerIbu(f), nil }, }) @@ -201,8 +200,8 @@ func addBeerLookup() { Description: "Scale indicating the concentration of extract in worts", Example: "6.4°Blg", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return beerBlg(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return beerBlg(f), nil }, }) } diff --git a/beer_test.go b/beer_test.go index 6446dee0..e88105d8 100644 --- a/beer_test.go +++ b/beer_test.go @@ -9,152 +9,81 @@ func ExampleBeerName() { Seed(11) fmt.Println(BeerName()) - // Output: Duvel + // Output: Sierra Nevada Bigfoot Barleywine Style Ale } func ExampleFaker_BeerName() { f := New(11) fmt.Println(f.BeerName()) - // Output: Duvel + // Output: Sierra Nevada Bigfoot Barleywine Style Ale } func BenchmarkBeerName(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BeerName() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BeerName() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BeerName() - } - }) + for i := 0; i < b.N; i++ { + BeerName() + } } func ExampleBeerStyle() { Seed(11) fmt.Println(BeerStyle()) - // Output: European Amber Lager + // Output: Vegetable Beer } func ExampleFaker_BeerStyle() { f := New(11) fmt.Println(f.BeerStyle()) - // Output: European Amber Lager + // Output: Vegetable Beer } func BenchmarkBeerStyle(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BeerStyle() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BeerStyle() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BeerStyle() - } - }) + for i := 0; i < b.N; i++ { + BeerStyle() + } } func ExampleBeerHop() { Seed(11) fmt.Println(BeerHop()) - // Output: Glacier + // Output: TriplePearl } func ExampleFaker_BeerHop() { f := New(11) fmt.Println(f.BeerHop()) - // Output: Glacier + // Output: TriplePearl } func BenchmarkBeerHop(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BeerHop() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BeerHop() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BeerHop() - } - }) + for i := 0; i < b.N; i++ { + BeerHop() + } } func ExampleBeerYeast() { Seed(11) fmt.Println(BeerYeast()) - // Output: 1388 - Belgian Strong Ale + // Output: 2308 - Munich Lager } func ExampleFaker_BeerYeast() { f := New(11) fmt.Println(f.BeerYeast()) - // Output: 1388 - Belgian Strong Ale + // Output: 2308 - Munich Lager } func BenchmarkBeerYeast(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BeerYeast() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BeerYeast() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BeerYeast() - } - }) + for i := 0; i < b.N; i++ { + BeerYeast() + } + } func ExampleBeerMalt() { @@ -172,139 +101,67 @@ func ExampleFaker_BeerMalt() { } func BenchmarkBeerMalt(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BeerMalt() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BeerMalt() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BeerMalt() - } - }) + for i := 0; i < b.N; i++ { + BeerMalt() + } } func ExampleBeerIbu() { Seed(11) fmt.Println(BeerIbu()) - // Output: 47 IBU + // Output: 91 IBU } func ExampleFaker_BeerIbu() { f := New(11) fmt.Println(f.BeerIbu()) - // Output: 47 IBU + // Output: 91 IBU } func BenchmarkBeerIbu(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BeerIbu() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BeerIbu() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BeerIbu() - } - }) + for i := 0; i < b.N; i++ { + BeerIbu() + } } func ExampleBeerAlcohol() { Seed(11) fmt.Println(BeerAlcohol()) - // Output: 2.7% + // Output: 8.2% } func ExampleFaker_BeerAlcohol() { f := New(11) fmt.Println(f.BeerAlcohol()) - // Output: 2.7% + // Output: 8.2% } func BenchmarkBeerAlcohol(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BeerAlcohol() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BeerAlcohol() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BeerAlcohol() - } - }) + for i := 0; i < b.N; i++ { + BeerAlcohol() + } } func ExampleBeerBlg() { Seed(11) fmt.Println(BeerBlg()) - // Output: 6.4°Blg + // Output: 16.6°Blg } func ExampleFaker_BeerBlg() { f := New(11) fmt.Println(f.BeerBlg()) - // Output: 6.4°Blg + // Output: 16.6°Blg } func BenchmarkBeerBlg(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BeerBlg() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BeerBlg() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BeerBlg() - } - }) + for i := 0; i < b.N; i++ { + BeerBlg() + } } diff --git a/book.go b/book.go index e2059dcf..fd8e0910 100644 --- a/book.go +++ b/book.go @@ -1,24 +1,22 @@ package gofakeit -import "math/rand" +func BookTitle() string { return bookTitle(GlobalFaker) } -func BookTitle() string { return bookTitle(globalFaker.Rand) } +func (f *Faker) BookTitle() string { return bookTitle(f) } -func (f *Faker) BookTitle() string { return bookTitle(f.Rand) } +func bookTitle(f *Faker) string { return getRandValue(f, []string{"book", "title"}) } -func bookTitle(r *rand.Rand) string { return getRandValue(r, []string{"book", "title"}) } +func BookAuthor() string { return bookAuthor(GlobalFaker) } -func BookAuthor() string { return bookAuthor(globalFaker.Rand) } +func (f *Faker) BookAuthor() string { return bookAuthor(f) } -func (f *Faker) BookAuthor() string { return bookAuthor(f.Rand) } +func bookAuthor(f *Faker) string { return getRandValue(f, []string{"book", "author"}) } -func bookAuthor(r *rand.Rand) string { return getRandValue(r, []string{"book", "author"}) } +func BookGenre() string { return bookGenre(GlobalFaker) } -func BookGenre() string { return bookGenre(globalFaker.Rand) } +func (f *Faker) BookGenre() string { return bookGenre(f) } -func (f *Faker) BookGenre() string { return bookGenre(f.Rand) } - -func bookGenre(r *rand.Rand) string { return getRandValue(r, []string{"book", "genre"}) } +func bookGenre(f *Faker) string { return getRandValue(f, []string{"book", "genre"}) } type BookInfo struct { Title string `json:"title" xml:"name"` @@ -26,15 +24,15 @@ type BookInfo struct { Genre string `json:"genre" xml:"genre"` } -func Book() *BookInfo { return book(globalFaker.Rand) } +func Book() *BookInfo { return book(GlobalFaker) } -func (f *Faker) Book() *BookInfo { return book(f.Rand) } +func (f *Faker) Book() *BookInfo { return book(f) } -func book(r *rand.Rand) *BookInfo { +func book(f *Faker) *BookInfo { return &BookInfo{ - Title: bookTitle(r), - Author: bookAuthor(r), - Genre: bookGenre(r), + Title: bookTitle(f), + Author: bookAuthor(f), + Genre: bookGenre(f), } } @@ -50,8 +48,8 @@ func addBookLookup() { }`, Output: "map[string]string", ContentType: "application/json", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return book(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return book(f), nil }, }) @@ -61,8 +59,8 @@ func addBookLookup() { Description: "The specific name given to a book", Example: "Hamlet", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return bookTitle(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return bookTitle(f), nil }, }) @@ -72,8 +70,8 @@ func addBookLookup() { Description: "The individual who wrote or created the content of a book", Example: "Mark Twain", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return bookAuthor(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return bookAuthor(f), nil }, }) @@ -83,8 +81,8 @@ func addBookLookup() { Description: "Category or type of book defined by its content, style, or form", Example: "Adventure", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return bookGenre(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return bookGenre(f), nil }, }) } diff --git a/book_test.go b/book_test.go index 12b91bb1..2128b930 100644 --- a/book_test.go +++ b/book_test.go @@ -12,9 +12,9 @@ func ExampleBook() { fmt.Println(book.Author) fmt.Println(book.Genre) - // Output: Anna Karenina + // Output: Things Fall Apart // Toni Morrison - // Thriller + // Erotic } func ExampleFaker_Book() { @@ -24,33 +24,15 @@ func ExampleFaker_Book() { fmt.Println(book.Author) fmt.Println(book.Genre) - // Output: Anna Karenina + // Output: Things Fall Apart // Toni Morrison - // Thriller + // Erotic } func BenchmarkBook(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Book() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Book() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Book() - } - }) + for i := 0; i < b.N; i++ { + Book() + } } func TestBook(t *testing.T) { @@ -63,112 +45,58 @@ func ExampleBookTitle() { Seed(11) fmt.Println(BookTitle()) - // Output: Anna Karenina + // Output: Things Fall Apart } func ExampleFaker_BookTitle() { f := New(11) fmt.Println(f.BookTitle()) - // Output: Anna Karenina + // Output: Things Fall Apart } func BenchmarkBookTitle(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BookTitle() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BookTitle() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BookTitle() - } - }) + for i := 0; i < b.N; i++ { + BookTitle() + } } func ExampleBookAuthor() { Seed(11) fmt.Println(BookAuthor()) - // Output: James Joyce + // Output: Vladimir Nabokov } func ExampleFaker_BookAuthor() { f := New(11) fmt.Println(f.BookAuthor()) - // Output: James Joyce + // Output: Vladimir Nabokov } func BenchmarkBookAuthor(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BookAuthor() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BookAuthor() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BookAuthor() - } - }) + for i := 0; i < b.N; i++ { + BookAuthor() + } } func ExampleBookGenre() { Seed(11) fmt.Println(BookGenre()) - // Output: Crime + // Output: Thriller } func ExampleFaker_BookGenre() { f := New(11) fmt.Println(f.BookGenre()) - // Output: Crime + // Output: Thriller } func BenchmarkBookGenre(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BookGenre() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BookGenre() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BookGenre() - } - }) + for i := 0; i < b.N; i++ { + BookGenre() + } } diff --git a/car.go b/car.go index 983e2576..def82dc4 100644 --- a/car.go +++ b/car.go @@ -1,7 +1,5 @@ package gofakeit -import "math/rand" - // CarInfo is a struct dataset of all car information type CarInfo struct { Type string `json:"type" xml:"type"` @@ -13,63 +11,63 @@ type CarInfo struct { } // Car will generate a struct with car information -func Car() *CarInfo { return car(globalFaker.Rand) } +func Car() *CarInfo { return car(GlobalFaker) } // Car will generate a struct with car information -func (f *Faker) Car() *CarInfo { return car(f.Rand) } +func (f *Faker) Car() *CarInfo { return car(f) } -func car(r *rand.Rand) *CarInfo { +func car(f *Faker) *CarInfo { return &CarInfo{ - Type: carType(r), - Fuel: carFuelType(r), - Transmission: carTransmissionType(r), - Brand: carMaker(r), - Model: carModel(r), - Year: year(r), + Type: carType(f), + Fuel: carFuelType(f), + Transmission: carTransmissionType(f), + Brand: carMaker(f), + Model: carModel(f), + Year: year(f), } } // CarType will generate a random car type string -func CarType() string { return carType(globalFaker.Rand) } +func CarType() string { return carType(GlobalFaker) } // CarType will generate a random car type string -func (f *Faker) CarType() string { return carType(f.Rand) } +func (f *Faker) CarType() string { return carType(f) } -func carType(r *rand.Rand) string { return getRandValue(r, []string{"car", "type"}) } +func carType(f *Faker) string { return getRandValue(f, []string{"car", "type"}) } // CarFuelType will return a random fuel type -func CarFuelType() string { return carFuelType(globalFaker.Rand) } +func CarFuelType() string { return carFuelType(GlobalFaker) } // CarFuelType will return a random fuel type -func (f *Faker) CarFuelType() string { return carFuelType(f.Rand) } +func (f *Faker) CarFuelType() string { return carFuelType(f) } -func carFuelType(r *rand.Rand) string { return getRandValue(r, []string{"car", "fuel_type"}) } +func carFuelType(f *Faker) string { return getRandValue(f, []string{"car", "fuel_type"}) } // CarTransmissionType will return a random transmission type -func CarTransmissionType() string { return carTransmissionType(globalFaker.Rand) } +func CarTransmissionType() string { return carTransmissionType(GlobalFaker) } // CarTransmissionType will return a random transmission type -func (f *Faker) CarTransmissionType() string { return carTransmissionType(f.Rand) } +func (f *Faker) CarTransmissionType() string { return carTransmissionType(f) } -func carTransmissionType(r *rand.Rand) string { - return getRandValue(r, []string{"car", "transmission_type"}) +func carTransmissionType(f *Faker) string { + return getRandValue(f, []string{"car", "transmission_type"}) } // CarMaker will return a random car maker -func CarMaker() string { return carMaker(globalFaker.Rand) } +func CarMaker() string { return carMaker(GlobalFaker) } // CarMaker will return a random car maker -func (f *Faker) CarMaker() string { return carMaker(f.Rand) } +func (f *Faker) CarMaker() string { return carMaker(f) } -func carMaker(r *rand.Rand) string { return getRandValue(r, []string{"car", "maker"}) } +func carMaker(f *Faker) string { return getRandValue(f, []string{"car", "maker"}) } // CarModel will return a random car model -func CarModel() string { return carModel(globalFaker.Rand) } +func CarModel() string { return carModel(GlobalFaker) } // CarModel will return a random car model -func (f *Faker) CarModel() string { return carModel(f.Rand) } +func (f *Faker) CarModel() string { return carModel(f) } -func carModel(r *rand.Rand) string { return getRandValue(r, []string{"car", "model"}) } +func carModel(f *Faker) string { return getRandValue(f, []string{"car", "model"}) } func addCarLookup() { AddFuncLookup("car", Info{ @@ -86,8 +84,8 @@ func addCarLookup() { }`, Output: "map[string]any", ContentType: "application/json", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return car(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return car(f), nil }, }) @@ -97,8 +95,8 @@ func addCarLookup() { Description: "Classification of cars based on size, use, or body style", Example: "Passenger car mini", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return carType(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return carType(f), nil }, }) @@ -108,8 +106,8 @@ func addCarLookup() { Description: "Type of energy source a car uses", Example: "CNG", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return carFuelType(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return carFuelType(f), nil }, }) @@ -119,8 +117,8 @@ func addCarLookup() { Description: "Mechanism a car uses to transmit power from the engine to the wheels", Example: "Manual", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return carTransmissionType(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return carTransmissionType(f), nil }, }) @@ -130,8 +128,8 @@ func addCarLookup() { Description: "Company or brand that manufactures and designs cars", Example: "Nissan", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return carMaker(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return carMaker(f), nil }, }) @@ -141,8 +139,8 @@ func addCarLookup() { Description: "Specific design or version of a car produced by a manufacturer", Example: "Aveo", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return carModel(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return carModel(f), nil }, }) } diff --git a/car_test.go b/car_test.go index d93ff6b0..c4160b4d 100644 --- a/car_test.go +++ b/car_test.go @@ -15,12 +15,12 @@ func ExampleCar() { fmt.Println(car.Type) fmt.Println(car.Year) - // Output: Fiat - // Gasoline - // Freestyle Fwd + // Output: Dacia + // CNG + // Santafe 4wd // Automatic - // Passenger car mini - // 1965 + // Passenger car heavy + // 1928 } func ExampleFaker_Car() { @@ -33,112 +33,58 @@ func ExampleFaker_Car() { fmt.Println(car.Type) fmt.Println(car.Year) - // Output: Fiat - // Gasoline - // Freestyle Fwd + // Output: Dacia + // CNG + // Santafe 4wd // Automatic - // Passenger car mini - // 1965 + // Passenger car heavy + // 1928 } func BenchmarkCar(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Car() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Car() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Car() - } - }) + for i := 0; i < b.N; i++ { + Car() + } } func ExampleCarType() { Seed(11) fmt.Println(CarType()) - // Output: Passenger car mini + // Output: Passenger car heavy } func ExampleFaker_CarType() { f := New(11) fmt.Println(f.CarType()) - // Output: Passenger car mini + // Output: Passenger car heavy } func BenchmarkCarType(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - CarType() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.CarType() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.CarType() - } - }) + for i := 0; i < b.N; i++ { + CarType() + } } func ExampleCarFuelType() { Seed(11) fmt.Println(CarFuelType()) - // Output: CNG + // Output: Electric } func ExampleFaker_CarFuelType() { f := New(11) fmt.Println(f.CarFuelType()) - // Output: CNG + // Output: Electric } func BenchmarkCarFuelType(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - CarFuelType() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.CarFuelType() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.CarFuelType() - } - }) + for i := 0; i < b.N; i++ { + CarFuelType() + } } func ExampleCarTransmissionType() { @@ -156,101 +102,47 @@ func ExampleFaker_CarTransmissionType() { } func BenchmarkCarTransmissionType(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - CarTransmissionType() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.CarTransmissionType() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.CarTransmissionType() - } - }) + for i := 0; i < b.N; i++ { + CarTransmissionType() + } } func ExampleCarMaker() { Seed(11) fmt.Println(CarMaker()) - // Output: Nissan + // Output: Spyker } func ExampleFaker_CarMaker() { f := New(11) fmt.Println(f.CarMaker()) - // Output: Nissan + // Output: Spyker } func BenchmarkCarMaker(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - CarMaker() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.CarMaker() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.CarMaker() - } - }) + for i := 0; i < b.N; i++ { + CarMaker() + } } func ExampleCarModel() { Seed(11) fmt.Println(CarModel()) - // Output: Aveo + // Output: Prius } func ExampleFaker_CarModel() { f := New(11) fmt.Println(f.CarModel()) - // Output: Aveo + // Output: Prius } func BenchmarkCarModel(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - CarModel() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.CarModel() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.CarModel() - } - }) + for i := 0; i < b.N; i++ { + CarModel() + } } diff --git a/celebrity.go b/celebrity.go index d7400f80..b00036d8 100644 --- a/celebrity.go +++ b/celebrity.go @@ -1,32 +1,30 @@ package gofakeit -import "math/rand" - // CelebrityActor will generate a random celebrity actor -func CelebrityActor() string { return celebrityActor(globalFaker.Rand) } +func CelebrityActor() string { return celebrityActor(GlobalFaker) } // CelebrityActor will generate a random celebrity actor -func (f *Faker) CelebrityActor() string { return celebrityActor(f.Rand) } +func (f *Faker) CelebrityActor() string { return celebrityActor(f) } -func celebrityActor(r *rand.Rand) string { return getRandValue(r, []string{"celebrity", "actor"}) } +func celebrityActor(f *Faker) string { return getRandValue(f, []string{"celebrity", "actor"}) } // CelebrityBusiness will generate a random celebrity business person -func CelebrityBusiness() string { return celebrityBusiness(globalFaker.Rand) } +func CelebrityBusiness() string { return celebrityBusiness(GlobalFaker) } // CelebrityBusiness will generate a random celebrity business person -func (f *Faker) CelebrityBusiness() string { return celebrityBusiness(f.Rand) } +func (f *Faker) CelebrityBusiness() string { return celebrityBusiness(f) } -func celebrityBusiness(r *rand.Rand) string { - return getRandValue(r, []string{"celebrity", "business"}) +func celebrityBusiness(f *Faker) string { + return getRandValue(f, []string{"celebrity", "business"}) } // CelebritySport will generate a random celebrity sport person -func CelebritySport() string { return celebritySport(globalFaker.Rand) } +func CelebritySport() string { return celebritySport(GlobalFaker) } // CelebritySport will generate a random celebrity sport person -func (f *Faker) CelebritySport() string { return celebritySport(f.Rand) } +func (f *Faker) CelebritySport() string { return celebritySport(f) } -func celebritySport(r *rand.Rand) string { return getRandValue(r, []string{"celebrity", "sport"}) } +func celebritySport(f *Faker) string { return getRandValue(f, []string{"celebrity", "sport"}) } func addCelebrityLookup() { AddFuncLookup("celebrityactor", Info{ @@ -35,8 +33,8 @@ func addCelebrityLookup() { Description: "Famous person known for acting in films, television, or theater", Example: "Brad Pitt", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return celebrityActor(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return celebrityActor(f), nil }, }) @@ -46,8 +44,8 @@ func addCelebrityLookup() { Description: "High-profile individual known for significant achievements in business or entrepreneurship", Example: "Elon Musk", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return celebrityBusiness(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return celebrityBusiness(f), nil }, }) @@ -57,8 +55,8 @@ func addCelebrityLookup() { Description: "Famous athlete known for achievements in a particular sport", Example: "Michael Phelps", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return celebritySport(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return celebritySport(f), nil }, }) } diff --git a/celebrity_test.go b/celebrity_test.go index 2994fd49..b431a4fb 100644 --- a/celebrity_test.go +++ b/celebrity_test.go @@ -9,112 +9,58 @@ func ExampleCelebrityActor() { Seed(11) fmt.Println(CelebrityActor()) - // Output: Owen Wilson + // Output: Shah Rukh Khan } func ExampleFaker_CelebrityActor() { f := New(11) fmt.Println(f.CelebrityActor()) - // Output: Owen Wilson + // Output: Shah Rukh Khan } func BenchmarkCelebrityActor(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - CelebrityActor() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.CelebrityActor() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.CelebrityActor() - } - }) + for i := 0; i < b.N; i++ { + CelebrityActor() + } } func ExampleCelebrityBusiness() { Seed(11) fmt.Println(CelebrityBusiness()) - // Output: Cameron Diaz + // Output: Prescott Bush } func ExampleFaker_CelebrityBusiness() { f := New(11) fmt.Println(f.CelebrityBusiness()) - // Output: Cameron Diaz + // Output: Prescott Bush } func BenchmarkCelebrityBusiness(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - CelebrityBusiness() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.CelebrityBusiness() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.CelebrityBusiness() - } - }) + for i := 0; i < b.N; i++ { + CelebrityBusiness() + } } func ExampleCelebritySport() { Seed(11) fmt.Println(CelebritySport()) - // Output: Hicham El Guerrouj + // Output: Grete Waitz } func ExampleFaker_CelebritySport() { f := New(11) fmt.Println(f.CelebritySport()) - // Output: Hicham El Guerrouj + // Output: Grete Waitz } func BenchmarkCelebritySport(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - CelebritySport() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.CelebritySport() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.CelebritySport() - } - }) + for i := 0; i < b.N; i++ { + CelebritySport() + } } diff --git a/cmd/exampleupdate/main.go b/cmd/exampleupdate/main.go new file mode 100644 index 00000000..fffc7cc2 --- /dev/null +++ b/cmd/exampleupdate/main.go @@ -0,0 +1,252 @@ +package main + +import ( + "errors" + "fmt" + "os" + "os/exec" + "regexp" + "strings" + "sync" +) + +func main() { + entries, err := os.ReadDir(".") + if err != nil { + fmt.Println("Error reading directory:", err) + return + } + + // Add wait group to wait for all examples to finish + var wg sync.WaitGroup + + for _, entry := range entries { + if !entry.IsDir() { + filename := entry.Name() + if isTestFile(filename) { + // Add to wait group + wg.Add(1) + + // go func() { + + // Process the file in a goroutine + fmt.Println("Processing file:", filename) + if err := processTestFile(filename); err != nil { + fmt.Println("Error processing test file:\n", err) + return // Stop processing further if any example fails + } + + fmt.Println() + + // time.Sleep(1 * time.Second) + + // Done with the file + wg.Done() + + // }() + } + } + } + + // Wait for all examples to finish + wg.Wait() +} + +func isTestFile(filename string) bool { + return regexp.MustCompile(`_test\.go$`).MatchString(filename) +} + +func findExampleFunctions(filename string) ([]string, error) { + // ReRead the content after each example + fileContentBytes, err := os.ReadFile(filename) + if err != nil { + return nil, fmt.Errorf("error reading file %s: %w", filename, err) + } + fileContent := string(fileContentBytes) + + var examples []string + r := regexp.MustCompile(`func Example[^(]*\(\)`) + matches := r.FindAllString(fileContent, -1) + + for _, match := range matches { + exampleName := match[5:] // Remove "func " prefix to get the example function name + examples = append(examples, exampleName) + } + + return examples, nil +} + +func processTestFile(filename string) error { + examples, err := findExampleFunctions(filename) + if err != nil { + return fmt.Errorf("error finding example functions in file %s: %w", filename, err) + } + + // Test the filename as a hole first + // go test -run ^(strings.Join(examples, "|"))$ + TestPassCmd := exec.Command("go", "test", "-run", "^("+strings.Join(examples, "|")+")$") + _, err = TestPassCmd.CombinedOutput() + if err == nil { + fmt.Println("Success") + // fmt.Printf("file %s passed successfully on first run\n", filename) + return nil + } + + for _, example := range examples { + // ReRead the content after each example + content, err := os.ReadFile(filename) + if err != nil { + return fmt.Errorf("error reading file %s: %w", filename, err) + } + + if err := runAndUpdateExample(filename, example, string(content)); err != nil { + return err // Return the error to stop further processing + } + + // Give some space in the output + fmt.Println() + } + return nil +} + +func runAndUpdateExample(filename, exampleName, content string) error { + fmt.Println("Testing: ", exampleName) + firstRunCmd := exec.Command("go", "test", "-run", exampleName+"$") + firstOutput, err := firstRunCmd.CombinedOutput() + if err == nil { + fmt.Println("Success") + // fmt.Printf("example %s in file %s passed successfully on first run\n", exampleName, filename) + return nil + } + + // fmt.Printf("firstOutput: %s\n", string(firstOutput)) + + // If the example failed, output the error and continue + fmt.Println("Failed, running update") + // fmt.Printf("example %s in file %s failed on first run: %s\n", exampleName, filename, err) + + // Parse the output to get "got" and "want" + got, want := parseOutputForGotAndWant(string(firstOutput)) + if got == "" || want == "" { + return fmt.Errorf("example %s in file %s failed, but unable to parse got/want: %s", exampleName, filename, err) + } + + // fmt.Printf("Got:\n%s\n\nWant:\n%s\n", got, want) + + // Update the file with "got" as new output + newContent, err := updateExampleOutputInFileContent(content, exampleName, got) + if err != nil { + return fmt.Errorf("error updating example %s in file %s: %s", exampleName, filename, err) + } + if newContent == "" { + return fmt.Errorf("failed to update example %s in file %s with new output", exampleName, filename) + } + + if err := os.WriteFile(filename, []byte(newContent), 0644); err != nil { + return fmt.Errorf("error writing updated file %s: %s", filename, err) + } + + // time.Sleep(1 * time.Second) + + // Rerun the example after updating + secondRunCmd := exec.Command("go", "test", "-run", exampleName+"$") + secondOutput, err := secondRunCmd.CombinedOutput() + if err != nil { + return fmt.Errorf("example %s in file %s failed after update: %s\nOutput:\n%s", exampleName, filename, err, string(secondOutput)) + } + + fmt.Println("Success after update") + // fmt.Printf("example %s in file %s passed successfully after update\n", exampleName, filename) + return nil +} + +func parseOutputForGotAndWant(output string) (got, want string) { + gotRegex := regexp.MustCompile(`(?s)got:\n(.*?)\nwant:`) + wantRegex := regexp.MustCompile(`(?s)want:\n(.*)`) + + gotMatch := gotRegex.FindStringSubmatch(output) + wantMatch := wantRegex.FindStringSubmatch(output) + + if len(gotMatch) > 1 { + got = gotMatch[1] + } + if len(wantMatch) > 1 { + want = wantMatch[1] + } + + return strings.TrimSpace(got), strings.TrimSpace(want) +} + +func updateExampleOutputInFileContent(content, exampleName, newOutput string) (string, error) { + lines := strings.Split(content, "\n") + foundExample := false + foundOutputMarker := false + exampleStart := fmt.Sprintf("func %s", exampleName) // func ExampleCusip() + fmt.Println(exampleStart) + outputMarker := "// Output:" + + // Prepare the new output lines, each prefixed with "// " + outputLines := strings.Split(newOutput, "\n") + for i, line := range outputLines { + // Add // Output: prefix to the first line + if i == 0 { + // Starting with [tab]// Output: + outputLines[i] = " " + outputMarker + " " + line + continue + } + + // Starting with [tab]//[space] + outputLines[i] = " // " + line + } + + startComment := 0 + endComment := 0 + for i, line := range lines { + // If you have started the comment figure out the end + if foundExample && foundOutputMarker { + // Check if current row starts with // if so continue + if strings.HasPrefix(strings.TrimSpace(line), "//") { + continue + } else { + // If we are here we are at the end of the comment + endComment = i + break + } + } + + // Found example function + if strings.Contains(line, exampleStart) { + foundExample = true + } + + // Found output marker + if foundExample && strings.Contains(line, outputMarker) { + // Mark that we found the output marker and start inserting new output lines + foundOutputMarker = true + startComment = i + + continue + } + } + + if !foundExample { + return "", errors.New(exampleName + " not found in example function") + } + + if !foundOutputMarker { + return "", errors.New("output marker not found in example function") + } + + // If startComment and endComment are 0 then error + if startComment == 0 && endComment == 0 { + return "", errors.New("start and end comment not found") + } + + // fmt.Printf("Start: %d, End: %d\n\n", startComment, endComment) + + // Loop through the lines deleting the old output + // and inserting the new output + lines = append(lines[:startComment], append(outputLines, lines[endComment:]...)...) + + return strings.Join(lines, "\n"), nil +} diff --git a/cmd/gofakeit/README.md b/cmd/gofakeit/README.md index d06bee66..1ca0708e 100644 --- a/cmd/gofakeit/README.md +++ b/cmd/gofakeit/README.md @@ -6,7 +6,7 @@ All functions are available to run in lowercase and if they require additional p ### Installation ```go -go install -v github.com/brianvoe/gofakeit/v6/cmd/gofakeit@latest +go install -v github.com/brianvoe/gofakeit/v7/cmd/gofakeit@latest ``` ### Example diff --git a/cmd/gofakeit/gofakeit.go b/cmd/gofakeit/gofakeit.go index 4247ae30..578ae052 100644 --- a/cmd/gofakeit/gofakeit.go +++ b/cmd/gofakeit/gofakeit.go @@ -8,7 +8,7 @@ import ( "strconv" "strings" - "github.com/brianvoe/gofakeit/v6" + "github.com/brianvoe/gofakeit/v7" ) var errNoFuncRunMsg = errors.New("could not find function to run\nrun gofakeit help or gofakeit list for available functions") @@ -50,7 +50,7 @@ func main() { fmt.Printf("%s", out) } -func mainFunc(seed int64, args []string, loop int) (string, error) { +func mainFunc(seed uint64, args []string, loop int) (string, error) { faker := gofakeit.New(seed) argsLen := len(args) @@ -142,7 +142,7 @@ func runFunction(faker *gofakeit.Faker, function string, args []string) (string, } } - value, err := info.Generate(faker.Rand, params, info) + value, err := info.Generate(faker, params, info) if err != nil { return "", err } diff --git a/cmd/gofakeit/gofakeit_test.go b/cmd/gofakeit/gofakeit_test.go index 4609a79b..68cb387a 100644 --- a/cmd/gofakeit/gofakeit_test.go +++ b/cmd/gofakeit/gofakeit_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/brianvoe/gofakeit/v6/data" + "github.com/brianvoe/gofakeit/v7/data" ) func TestMain(t *testing.T) { @@ -69,7 +69,7 @@ func TestFunctionLoop(t *testing.T) { } func TestNotEnoughArgs(t *testing.T) { - seed := int64(11) + seed := uint64(11) args := []string{} _, err := mainFunc(seed, args, 1) @@ -79,7 +79,7 @@ func TestNotEnoughArgs(t *testing.T) { } func TestNoFunction(t *testing.T) { - seed := int64(11) + seed := uint64(11) args := []string{"notafunction"} _, err := mainFunc(seed, args, 1) @@ -89,7 +89,7 @@ func TestNoFunction(t *testing.T) { } func TestFunctionSimple(t *testing.T) { - seed := int64(11) + seed := uint64(11) args := []string{"firstname"} outStr, err := mainFunc(seed, args, 1) @@ -114,7 +114,7 @@ func TestFunctionSimple(t *testing.T) { func TestFunctionWithParams(t *testing.T) { strs := []string{"hello", "world", "whats", "up"} - seed := int64(11) + seed := uint64(11) args := []string{"shufflestrings", strings.Join(strs, ",")} outStr, err := mainFunc(seed, args, 1) @@ -128,7 +128,7 @@ func TestFunctionWithParams(t *testing.T) { } func TestHelp(t *testing.T) { - seed := int64(11) + seed := uint64(11) args := []string{"help"} outStr, err := mainFunc(seed, args, 1) @@ -149,7 +149,7 @@ func TestHelp(t *testing.T) { } func TestList(t *testing.T) { - seed := int64(11) + seed := uint64(11) args := []string{"list"} outStr, err := mainFunc(seed, args, 1) @@ -176,7 +176,7 @@ func TestList(t *testing.T) { } func TestListCategory(t *testing.T) { - seed := int64(11) + seed := uint64(11) args := []string{"list", "person"} outStr, err := mainFunc(seed, args, 1) @@ -200,7 +200,7 @@ func TestListCategory(t *testing.T) { } func TestListCategoryFunction(t *testing.T) { - seed := int64(11) + seed := uint64(11) args := []string{"list", "word", "noun"} outStr, err := mainFunc(seed, args, 1) diff --git a/cmd/gofakeitserver/README.md b/cmd/gofakeitserver/README.md index 849c98fb..4d0ba198 100644 --- a/cmd/gofakeitserver/README.md +++ b/cmd/gofakeitserver/README.md @@ -4,7 +4,7 @@ All functions are available to run in lowercase as first path and if they take i ### Installation ```go -go get -u github.com/brianvoe/gofakeit/v6/cmd/gofakeitserver +go get -u github.com/brianvoe/gofakeit/v7/cmd/gofakeitserver ``` ### Example diff --git a/cmd/gofakeitserver/init_test.go b/cmd/gofakeitserver/init_test.go index 18410c46..6f637e77 100644 --- a/cmd/gofakeitserver/init_test.go +++ b/cmd/gofakeitserver/init_test.go @@ -12,7 +12,7 @@ import ( "strings" "testing" - "github.com/brianvoe/gofakeit/v6" + "github.com/brianvoe/gofakeit/v7" ) var ts *httptest.Server diff --git a/cmd/gofakeitserver/main.go b/cmd/gofakeitserver/main.go index 3d394e47..c1880872 100644 --- a/cmd/gofakeitserver/main.go +++ b/cmd/gofakeitserver/main.go @@ -10,7 +10,7 @@ import ( "reflect" "strings" - "github.com/brianvoe/gofakeit/v6" + "github.com/brianvoe/gofakeit/v7" ) var port string @@ -83,7 +83,7 @@ func lookupGet(w http.ResponseWriter, r *http.Request) { } // Generate requested data - data, err := info.Generate(faker.Rand, m, info) + data, err := info.Generate(faker, m, info) if err != nil { badrequest(w, err.Error()) return @@ -149,7 +149,7 @@ func lookupPost(w http.ResponseWriter, r *http.Request) { } // Generate requested data - data, err := info.Generate(faker.Rand, mapString, info) + data, err := info.Generate(faker, mapString, info) if err != nil { badrequest(w, err.Error()) return diff --git a/cmd/gofakeitserver/main_test.go b/cmd/gofakeitserver/main_test.go index 050397e4..3120b38c 100644 --- a/cmd/gofakeitserver/main_test.go +++ b/cmd/gofakeitserver/main_test.go @@ -2,12 +2,12 @@ package main import ( "fmt" - "math/rand" + "math/rand/v2" "net/url" "strings" "testing" - "github.com/brianvoe/gofakeit/v6" + "github.com/brianvoe/gofakeit/v7" ) func TestList(t *testing.T) { @@ -38,7 +38,7 @@ func TestGetAllRequests(t *testing.T) { for _, p := range info.Params { // If default is empty and has options randomly pick one if p.Default == "" && len(p.Options) != 0 { - mapData.Add(p.Field, p.Options[faker.Rand.Intn(len(p.Options))]) + mapData.Add(p.Field, p.Options[faker.IntN(len(p.Options))]) continue } else if p.Default != "" { // If p.Type is []uint, then we need to convert it to []string @@ -174,7 +174,7 @@ func TestPostAllRequests(t *testing.T) { for _, p := range info.Params { // If default is empty and has options randomly pick one if p.Default == "" && len(p.Options) != 0 { - mapData[p.Field] = []string{p.Options[rand.Intn(len(p.Options))]} + mapData[p.Field] = []string{p.Options[rand.IntN(len(p.Options))]} continue } else if p.Default != "" { // If p.Type is []uint, then we need to convert it to []string diff --git a/color.go b/color.go index dce7db5f..e8feb402 100644 --- a/color.go +++ b/color.go @@ -1,61 +1,59 @@ package gofakeit import ( - "math/rand" - - "github.com/brianvoe/gofakeit/v6/data" + "github.com/brianvoe/gofakeit/v7/data" ) // Color will generate a random color string -func Color() string { return color(globalFaker.Rand) } +func Color() string { return color(GlobalFaker) } // Color will generate a random color string -func (f *Faker) Color() string { return color(f.Rand) } +func (f *Faker) Color() string { return color(f) } -func color(r *rand.Rand) string { return getRandValue(r, []string{"color", "full"}) } +func color(f *Faker) string { return getRandValue(f, []string{"color", "full"}) } // NiceColor will generate a random safe color string -func NiceColors() []string { return niceColors(globalFaker.Rand) } +func NiceColors() []string { return niceColors(GlobalFaker) } // NiceColor will generate a random safe color string -func (f *Faker) NiceColors() []string { return niceColors(f.Rand) } +func (f *Faker) NiceColors() []string { return niceColors(f) } -func niceColors(r *rand.Rand) []string { - return data.ColorsNice[randIntRange(r, 0, len(data.ColorsNice)-1)] +func niceColors(f *Faker) []string { + return data.ColorsNice[randIntRange(f, 0, len(data.ColorsNice)-1)] } // SafeColor will generate a random safe color string -func SafeColor() string { return safeColor(globalFaker.Rand) } +func SafeColor() string { return safeColor(GlobalFaker) } // SafeColor will generate a random safe color string -func (f *Faker) SafeColor() string { return safeColor(f.Rand) } +func (f *Faker) SafeColor() string { return safeColor(f) } -func safeColor(r *rand.Rand) string { return getRandValue(r, []string{"color", "safe"}) } +func safeColor(f *Faker) string { return getRandValue(f, []string{"color", "safe"}) } // HexColor will generate a random hexadecimal color string -func HexColor() string { return hexColor(globalFaker.Rand) } +func HexColor() string { return hexColor(GlobalFaker) } // HexColor will generate a random hexadecimal color string -func (f *Faker) HexColor() string { return hexColor(f.Rand) } +func (f *Faker) HexColor() string { return hexColor(f) } -func hexColor(r *rand.Rand) string { +func hexColor(f *Faker) string { color := make([]byte, 6) hashQuestion := []byte("?#") for i := 0; i < 6; i++ { - color[i] = hashQuestion[r.Intn(2)] + color[i] = hashQuestion[f.IntN(2)] } - return "#" + replaceWithHexLetters(r, replaceWithNumbers(r, string(color))) + return "#" + replaceWithHexLetters(f, replaceWithNumbers(f, string(color))) } // RGBColor will generate a random int slice color -func RGBColor() []int { return rgbColor(globalFaker.Rand) } +func RGBColor() []int { return rgbColor(GlobalFaker) } // RGBColor will generate a random int slice color -func (f *Faker) RGBColor() []int { return rgbColor(f.Rand) } +func (f *Faker) RGBColor() []int { return rgbColor(f) } -func rgbColor(r *rand.Rand) []int { - return []int{randIntRange(r, 0, 255), randIntRange(r, 0, 255), randIntRange(r, 0, 255)} +func rgbColor(f *Faker) []int { + return []int{randIntRange(f, 0, 255), randIntRange(f, 0, 255), randIntRange(f, 0, 255)} } func addColorLookup() { @@ -65,8 +63,8 @@ func addColorLookup() { Description: "Hue seen by the eye, returns the name of the color like red or blue", Example: "MediumOrchid", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return color(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return color(f), nil }, }) @@ -77,8 +75,8 @@ func addColorLookup() { Example: `["#cfffdd","#b4dec1","#5c5863","#a85163","#ff1f4c"]`, Output: "[]string", ContentType: "application/json", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return color(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return color(f), nil }, }) @@ -88,8 +86,8 @@ func addColorLookup() { Description: "Colors displayed consistently on different web browsers and devices", Example: "black", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return safeColor(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return safeColor(f), nil }, }) @@ -99,8 +97,8 @@ func addColorLookup() { Description: "Six-digit code representing a color in the color model", Example: "#a99fb4", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hexColor(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return hexColor(f), nil }, }) @@ -111,8 +109,8 @@ func addColorLookup() { Example: "[85, 224, 195]", Output: "[]int", ContentType: "application/json", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return rgbColor(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return rgbColor(f), nil }, }) } diff --git a/color_test.go b/color_test.go index 5cafa62a..e892c401 100644 --- a/color_test.go +++ b/color_test.go @@ -9,188 +9,98 @@ func ExampleColor() { Seed(11) fmt.Println(Color()) - // Output: MediumOrchid + // Output: SlateGray } func ExampleFaker_Color() { f := New(11) fmt.Println(f.Color()) - // Output: MediumOrchid + // Output: SlateGray } func BenchmarkColor(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Color() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Color() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Color() - } - }) + for i := 0; i < b.N; i++ { + Color() + } } func ExampleNiceColors() { Seed(11) fmt.Println(NiceColors()) - // Output: [#f6f6f6 #e8e8e8 #333333 #990100 #b90504] + // Output: [#fffbb7 #a6f6af #66b6ab #5b7c8d #4f2958] } func ExampleFaker_NiceColors() { f := New(11) fmt.Println(f.NiceColors()) - // Output: [#f6f6f6 #e8e8e8 #333333 #990100 #b90504] + // Output: [#fffbb7 #a6f6af #66b6ab #5b7c8d #4f2958] } func BenchmarkNiceColors(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - NiceColors() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.NiceColors() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.NiceColors() - } - }) + for i := 0; i < b.N; i++ { + NiceColors() + } } func ExampleSafeColor() { Seed(11) fmt.Println(SafeColor()) - // Output: black + // Output: aqua } func ExampleFaker_SafeColor() { f := New(11) fmt.Println(f.SafeColor()) - // Output: black + // Output: aqua } func BenchmarkSafeColor(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - SafeColor() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.SafeColor() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.SafeColor() - } - }) + for i := 0; i < b.N; i++ { + SafeColor() + } } func ExampleHexColor() { Seed(11) fmt.Println(HexColor()) - // Output: #a99fb4 + // Output: #ef759a } func ExampleFaker_HexColor() { f := New(11) fmt.Println(f.HexColor()) - // Output: #a99fb4 + // Output: #ef759a } func BenchmarkHexColor(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HexColor() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HexColor() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HexColor() - } - }) + for i := 0; i < b.N; i++ { + HexColor() + } } func ExampleRGBColor() { Seed(11) fmt.Println(RGBColor()) - // Output: [89 176 195] + // Output: [180 18 181] } func ExampleFaker_RGBColor() { f := New(11) fmt.Println(f.RGBColor()) - // Output: [89 176 195] + // Output: [180 18 181] } func BenchmarkRGBColor(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - RGBColor() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.RGBColor() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.RGBColor() - } - }) + for i := 0; i < b.N; i++ { + RGBColor() + } } diff --git a/company.go b/company.go index ea8af6ca..64167295 100644 --- a/company.go +++ b/company.go @@ -1,45 +1,43 @@ package gofakeit -import "math/rand" - // Company will generate a random company name string -func Company() string { return company(globalFaker.Rand) } +func Company() string { return company(GlobalFaker) } // Company will generate a random company name string -func (f *Faker) Company() string { return company(f.Rand) } +func (f *Faker) Company() string { return company(f) } -func company(r *rand.Rand) string { return getRandValue(r, []string{"company", "name"}) } +func company(f *Faker) string { return getRandValue(f, []string{"company", "name"}) } // CompanySuffix will generate a random company suffix string -func CompanySuffix() string { return companySuffix(globalFaker.Rand) } +func CompanySuffix() string { return companySuffix(GlobalFaker) } // CompanySuffix will generate a random company suffix string -func (f *Faker) CompanySuffix() string { return companySuffix(f.Rand) } +func (f *Faker) CompanySuffix() string { return companySuffix(f) } -func companySuffix(r *rand.Rand) string { return getRandValue(r, []string{"company", "suffix"}) } +func companySuffix(f *Faker) string { return getRandValue(f, []string{"company", "suffix"}) } // Blurb will generate a random company blurb string -func Blurb() string { return blurb(globalFaker.Rand) } +func Blurb() string { return blurb(GlobalFaker) } -func (f *Faker) Blurb() string { return blurb(f.Rand) } +func (f *Faker) Blurb() string { return blurb(f) } -func blurb(r *rand.Rand) string { return getRandValue(r, []string{"company", "blurb"}) } +func blurb(f *Faker) string { return getRandValue(f, []string{"company", "blurb"}) } // BuzzWord will generate a random company buzz word string -func BuzzWord() string { return buzzWord(globalFaker.Rand) } +func BuzzWord() string { return buzzWord(GlobalFaker) } // BuzzWord will generate a random company buzz word string -func (f *Faker) BuzzWord() string { return buzzWord(f.Rand) } +func (f *Faker) BuzzWord() string { return buzzWord(f) } -func buzzWord(r *rand.Rand) string { return getRandValue(r, []string{"company", "buzzwords"}) } +func buzzWord(f *Faker) string { return getRandValue(f, []string{"company", "buzzwords"}) } // BS will generate a random company bs string -func BS() string { return bs(globalFaker.Rand) } +func BS() string { return bs(GlobalFaker) } // BS will generate a random company bs string -func (f *Faker) BS() string { return bs(f.Rand) } +func (f *Faker) BS() string { return bs(f) } -func bs(r *rand.Rand) string { return getRandValue(r, []string{"company", "bs"}) } +func bs(f *Faker) string { return getRandValue(f, []string{"company", "bs"}) } // JobInfo is a struct of job information type JobInfo struct { @@ -50,64 +48,64 @@ type JobInfo struct { } // Job will generate a struct with random job information -func Job() *JobInfo { return job(globalFaker.Rand) } +func Job() *JobInfo { return job(GlobalFaker) } // Job will generate a struct with random job information -func (f *Faker) Job() *JobInfo { return job(f.Rand) } +func (f *Faker) Job() *JobInfo { return job(f) } -func job(r *rand.Rand) *JobInfo { +func job(f *Faker) *JobInfo { return &JobInfo{ - Company: company(r), - Title: jobTitle(r), - Descriptor: jobDescriptor(r), - Level: jobLevel(r), + Company: company(f), + Title: jobTitle(f), + Descriptor: jobDescriptor(f), + Level: jobLevel(f), } } // JobTitle will generate a random job title string -func JobTitle() string { return jobTitle(globalFaker.Rand) } +func JobTitle() string { return jobTitle(GlobalFaker) } // JobTitle will generate a random job title string -func (f *Faker) JobTitle() string { return jobTitle(f.Rand) } +func (f *Faker) JobTitle() string { return jobTitle(f) } -func jobTitle(r *rand.Rand) string { return getRandValue(r, []string{"job", "title"}) } +func jobTitle(f *Faker) string { return getRandValue(f, []string{"job", "title"}) } // JobDescriptor will generate a random job descriptor string -func JobDescriptor() string { return jobDescriptor(globalFaker.Rand) } +func JobDescriptor() string { return jobDescriptor(GlobalFaker) } // JobDescriptor will generate a random job descriptor string -func (f *Faker) JobDescriptor() string { return jobDescriptor(f.Rand) } +func (f *Faker) JobDescriptor() string { return jobDescriptor(f) } -func jobDescriptor(r *rand.Rand) string { return getRandValue(r, []string{"job", "descriptor"}) } +func jobDescriptor(f *Faker) string { return getRandValue(f, []string{"job", "descriptor"}) } // JobLevel will generate a random job level string -func JobLevel() string { return jobLevel(globalFaker.Rand) } +func JobLevel() string { return jobLevel(GlobalFaker) } // JobLevel will generate a random job level string -func (f *Faker) JobLevel() string { return jobLevel(f.Rand) } +func (f *Faker) JobLevel() string { return jobLevel(f) } -func jobLevel(r *rand.Rand) string { return getRandValue(r, []string{"job", "level"}) } +func jobLevel(f *Faker) string { return getRandValue(f, []string{"job", "level"}) } // Slogan will generate a random company slogan -func Slogan() string { return slogan(globalFaker.Rand) } +func Slogan() string { return slogan(GlobalFaker) } // Slogan will generate a random company slogan -func (f *Faker) Slogan() string { return slogan(f.Rand) } +func (f *Faker) Slogan() string { return slogan(f) } // Slogan will generate a random company slogan -func slogan(r *rand.Rand) string { +func slogan(f *Faker) string { slogan := "" - var sloganStyle = number(r, 0, 2) + var sloganStyle = number(f, 0, 2) switch sloganStyle { // Noun. Buzzword! case 0: - slogan = getRandValue(r, []string{"company", "blurb"}) + ". " + getRandValue(r, []string{"company", "buzzwords"}) + "!" + slogan = getRandValue(f, []string{"company", "blurb"}) + ". " + getRandValue(f, []string{"company", "buzzwords"}) + "!" // Buzzword Noun, Buzzword Noun. case 1: - slogan = getRandValue(r, []string{"company", "buzzwords"}) + " " + getRandValue(r, []string{"company", "blurb"}) + ", " + getRandValue(r, []string{"company", "buzzwords"}) + " " + getRandValue(r, []string{"company", "blurb"}) + "." + slogan = getRandValue(f, []string{"company", "buzzwords"}) + " " + getRandValue(f, []string{"company", "blurb"}) + ", " + getRandValue(f, []string{"company", "buzzwords"}) + " " + getRandValue(f, []string{"company", "blurb"}) + "." // Buzzword bs Noun, Buzzword. case 2: - slogan = getRandValue(r, []string{"company", "buzzwords"}) + " " + getRandValue(r, []string{"company", "bs"}) + " " + getRandValue(r, []string{"company", "blurb"}) + ", " + getRandValue(r, []string{"company", "buzzwords"}) + "." + slogan = getRandValue(f, []string{"company", "buzzwords"}) + " " + getRandValue(f, []string{"company", "bs"}) + " " + getRandValue(f, []string{"company", "blurb"}) + ", " + getRandValue(f, []string{"company", "buzzwords"}) + "." } return slogan } @@ -119,8 +117,8 @@ func addCompanyLookup() { Description: "Designated official name of a business or organization", Example: "Moen, Pagac and Wuckert", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return company(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return company(f), nil }, }) @@ -130,8 +128,8 @@ func addCompanyLookup() { Description: "Suffix at the end of a company name, indicating business structure, like 'Inc.' or 'LLC'", Example: "Inc", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return companySuffix(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return companySuffix(f), nil }, }) @@ -141,8 +139,8 @@ func addCompanyLookup() { Description: "Random bs company word", Example: "front-end", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return bs(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return bs(f), nil }, }) @@ -152,8 +150,8 @@ func addCompanyLookup() { Description: "Brief description or summary of a company's purpose, products, or services", Example: "word", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return blurb(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return blurb(f), nil }, }) @@ -163,8 +161,8 @@ func addCompanyLookup() { Description: "Trendy or overused term often used in business to sound impressive", Example: "disintermediate", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return buzzWord(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return buzzWord(f), nil }, }) @@ -180,8 +178,8 @@ func addCompanyLookup() { }`, Output: "map[string]string", ContentType: "application/json", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return job(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return job(f), nil }, }) @@ -191,8 +189,8 @@ func addCompanyLookup() { Description: "Specific title for a position or role within a company or organization", Example: "Director", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return jobTitle(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return jobTitle(f), nil }, }) @@ -202,8 +200,8 @@ func addCompanyLookup() { Description: "Word used to describe the duties, requirements, and nature of a job", Example: "Central", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return jobDescriptor(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return jobDescriptor(f), nil }, }) @@ -213,8 +211,8 @@ func addCompanyLookup() { Description: "Random job level", Example: "Assurance", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return jobLevel(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return jobLevel(f), nil }, }) @@ -224,8 +222,8 @@ func addCompanyLookup() { Description: "Catchphrase or motto used by a company to represent its brand or values", Example: "Universal seamless Focus, interactive.", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return slogan(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return slogan(f), nil }, }) } diff --git a/company_test.go b/company_test.go index fb99cf3c..5a62a066 100644 --- a/company_test.go +++ b/company_test.go @@ -9,38 +9,20 @@ func ExampleCompany() { Seed(11) fmt.Println(Company()) - // Output: ClearHealthCosts + // Output: TransparaGov } func ExampleFaker_Company() { f := New(11) fmt.Println(f.Company()) - // Output: ClearHealthCosts + // Output: TransparaGov } func BenchmarkCompany(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Company() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Company() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Company() - } - }) + for i := 0; i < b.N; i++ { + Company() + } } func TestCompany(t *testing.T) { @@ -64,140 +46,68 @@ func ExampleFaker_CompanySuffix() { } func BenchmarkCompanySuffix(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - CompanySuffix() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.CompanySuffix() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.CompanySuffix() - } - }) + for i := 0; i < b.N; i++ { + CompanySuffix() + } } func ExampleBlurb() { Seed(11) fmt.Println(Blurb()) - // Output: Motivation + // Output: Teamwork } func ExampleFaker_Blurb() { f := New(11) fmt.Println(f.Blurb()) - // Output: Motivation + // Output: Teamwork } func BenchmarkBlurb(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Blurb() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Blurb() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Blurb() - } - }) + for i := 0; i < b.N; i++ { + Blurb() + } } func ExampleBuzzWord() { Seed(11) fmt.Println(BuzzWord()) - // Output: disintermediate + // Output: open system } func ExampleFaker_BuzzWord() { f := New(11) fmt.Println(f.BuzzWord()) - // Output: disintermediate + // Output: open system } func BenchmarkBuzzWord(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BuzzWord() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BuzzWord() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BuzzWord() - } - }) + for i := 0; i < b.N; i++ { + BuzzWord() + } } func ExampleBS() { Seed(11) fmt.Println(BS()) - // Output: front-end + // Output: models } func ExampleFaker_BS() { f := New(11) fmt.Println(f.BS()) - // Output: front-end + // Output: models } func BenchmarkBS(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - BS() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.BS() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.BS() - } - }) + for i := 0; i < b.N; i++ { + BS() + } } func ExampleJob() { @@ -208,10 +118,10 @@ func ExampleJob() { fmt.Println(jobInfo.Descriptor) fmt.Println(jobInfo.Level) - // Output: ClearHealthCosts - // Agent - // Future - // Tactics + // Output: TransparaGov + // Specialist + // Direct + // Configuration } func ExampleFaker_Job() { @@ -222,184 +132,94 @@ func ExampleFaker_Job() { fmt.Println(jobInfo.Descriptor) fmt.Println(jobInfo.Level) - // Output: ClearHealthCosts - // Agent - // Future - // Tactics + // Output: TransparaGov + // Specialist + // Direct + // Configuration } func BenchmarkJob(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Job() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Job() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Job() - } - }) + for i := 0; i < b.N; i++ { + Job() + } } func ExampleJobTitle() { Seed(11) fmt.Println(JobTitle()) - // Output: Director + // Output: Strategist } func ExampleFaker_JobTitle() { f := New(11) fmt.Println(f.JobTitle()) - // Output: Director + // Output: Strategist } func BenchmarkJobTitle(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - JobTitle() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.JobTitle() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.JobTitle() - } - }) + for i := 0; i < b.N; i++ { + JobTitle() + } } func ExampleJobDescriptor() { Seed(11) fmt.Println(JobDescriptor()) - // Output: Central + // Output: Product } func ExampleFaker_JobDescriptor() { f := New(11) fmt.Println(f.JobDescriptor()) - // Output: Central + // Output: Product } func BenchmarkJobDescriptor(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - JobDescriptor() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.JobDescriptor() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.JobDescriptor() - } - }) + for i := 0; i < b.N; i++ { + JobDescriptor() + } } func ExampleJobLevel() { Seed(11) fmt.Println(JobLevel()) - // Output: Assurance + // Output: Solutions } func ExampleFaker_JobLevel() { f := New(11) fmt.Println(f.JobLevel()) - // Output: Assurance + // Output: Solutions } func BenchmarkJobLevel(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - JobLevel() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.JobLevel() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.JobLevel() - } - }) + for i := 0; i < b.N; i++ { + JobLevel() + } } func ExampleSlogan() { Seed(11) fmt.Println(Slogan()) - // Output: Universal seamless Focus, interactive. + // Output: local area network maximize Drive, mission-critical. } func ExampleFaker_Slogan() { f := New(11) fmt.Println(f.Slogan()) - // Output: Universal seamless Focus, interactive. + // Output: local area network maximize Drive, mission-critical. } func BenchmarkSlogan(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Slogan() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Slogan() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Slogan() - } - }) + for i := 0; i < b.N; i++ { + Slogan() + } } diff --git a/csv.go b/csv.go index 6a2310ef..7f31ec2f 100644 --- a/csv.go +++ b/csv.go @@ -6,7 +6,6 @@ import ( "encoding/json" "errors" "fmt" - "math/rand" "reflect" "strings" ) @@ -20,7 +19,7 @@ type CSVOptions struct { // CSV generates an object or an array of objects in json format // A nil CSVOptions returns a randomly structured CSV. -func CSV(co *CSVOptions) ([]byte, error) { return csvFunc(globalFaker, co) } +func CSV(co *CSVOptions) ([]byte, error) { return csvFunc(GlobalFaker, co) } // CSV generates an object or an array of objects in json format // A nil CSVOptions returns a randomly structured CSV. @@ -84,7 +83,7 @@ func csvFunc(f *Faker, co *CSVOptions) ([]byte, error) { return nil, errors.New("invalid function, " + field.Function + " does not exist") } - value, err := funcInfo.Generate(f.Rand, &field.Params, funcInfo) + value, err := funcInfo.Generate(f, &field.Params, funcInfo) if err != nil { return nil, err } @@ -140,7 +139,7 @@ func addFileCSVLookup() { {Field: "rowcount", Display: "Row Count", Type: "int", Default: "100", Description: "Number of rows"}, {Field: "fields", Display: "Fields", Type: "[]Field", Description: "Fields containing key name and function"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { co := CSVOptions{} delimiter, err := info.GetString(m, "delimiter") @@ -173,7 +172,6 @@ func addFileCSVLookup() { } } - f := &Faker{Rand: r} csvOut, err := csvFunc(f, &co) if err != nil { return nil, err diff --git a/csv_test.go b/csv_test.go index cf7a2116..8dda5350 100644 --- a/csv_test.go +++ b/csv_test.go @@ -24,11 +24,10 @@ func ExampleCSV_array() { fmt.Println(string(value)) - // Output: - // id,first_name,last_name,password - // 1,Markus,Moen,856Y5wPZevX9 - // 2,Jalon,Rolfson,64wz4EAS0Hl0 - // 3,Nestor,Harris,14GKq1j7Lx4T + // Output: id,first_name,last_name,password + // 1,Sonny,Stiedemann,8nwf0o3sBXcR + // 2,Verda,Brakus,3beWLpq75Lua + // 3,Jules,Cremin,Uu38J14Y8W82 } func ExampleFaker_CSV_array() { @@ -49,11 +48,10 @@ func ExampleFaker_CSV_array() { fmt.Println(string(value)) - // Output: - // id,first_name,last_name,password - // 1,Markus,Moen,856Y5wPZevX9 - // 2,Jalon,Rolfson,64wz4EAS0Hl0 - // 3,Nestor,Harris,14GKq1j7Lx4T + // Output: id,first_name,last_name,password + // 1,Sonny,Stiedemann,8nwf0o3sBXcR + // 2,Verda,Brakus,3beWLpq75Lua + // 3,Jules,Cremin,Uu38J14Y8W82 } func TestCSVLookup(t *testing.T) { @@ -84,7 +82,7 @@ func TestCSVLookup(t *testing.T) { }, } - output, err := info.Generate(faker.Rand, &m, info) + output, err := info.Generate(faker, &m, info) if err != nil { t.Fatal(err.Error()) } @@ -125,76 +123,7 @@ func BenchmarkCSVLookup100(b *testing.B) { `{"name":"created_at","function":"date"}`, }, } - _, err := info.Generate(faker.Rand, &m, info) - if err != nil { - b.Fatal(err.Error()) - } - } -} - -func BenchmarkCSVLookup1000(b *testing.B) { - faker := New(0) - - for i := 0; i < b.N; i++ { - info := GetFuncLookup("csv") - m := MapParams{ - "rowcount": {"1000"}, - "fields": { - `{"name":"id","function":"autoincrement"}`, - `{"name":"first_name","function":"firstname"}`, - `{"name":"last_name","function":"lastname"}`, - `{"name":"password","function":"password"}`, - `{"name":"description","function":"paragraph"}`, - `{"name":"created_at","function":"date"}`, - }, - } - _, err := info.Generate(faker.Rand, &m, info) - if err != nil { - b.Fatal(err.Error()) - } - } -} - -func BenchmarkCSVLookup10000(b *testing.B) { - faker := New(0) - - for i := 0; i < b.N; i++ { - info := GetFuncLookup("csv") - m := MapParams{ - "rowcount": {"10000"}, - "fields": { - `{"name":"id","function":"autoincrement"}`, - `{"name":"first_name","function":"firstname"}`, - `{"name":"last_name","function":"lastname"}`, - `{"name":"password","function":"password"}`, - `{"name":"description","function":"paragraph"}`, - `{"name":"created_at","function":"date"}`, - }, - } - _, err := info.Generate(faker.Rand, &m, info) - if err != nil { - b.Fatal(err.Error()) - } - } -} - -func BenchmarkCSVLookup100000(b *testing.B) { - faker := New(0) - - for i := 0; i < b.N; i++ { - info := GetFuncLookup("csv") - m := MapParams{ - "rowcount": {"100000"}, - "fields": { - `{"name":"id","function":"autoincrement"}`, - `{"name":"first_name","function":"firstname"}`, - `{"name":"last_name","function":"lastname"}`, - `{"name":"password","function":"password"}`, - `{"name":"description","function":"paragraph"}`, - `{"name":"created_at","function":"date"}`, - }, - } - _, err := info.Generate(faker.Rand, &m, info) + _, err := info.Generate(faker, &m, info) if err != nil { b.Fatal(err.Error()) } diff --git a/data/data_test.go b/data/data_test.go index c28bd110..27d8b0a4 100644 --- a/data/data_test.go +++ b/data/data_test.go @@ -27,7 +27,7 @@ func ExampleGet() { // [Mr. Mrs. Ms. Miss Dr.] } -func ExampleGetSub() { +func ExampleGet_sub() { // Get data data := GetSubData("person", "prefix") diff --git a/data/emoji.go b/data/emoji.go index b48605ea..8f8ce80f 100644 --- a/data/emoji.go +++ b/data/emoji.go @@ -149,7 +149,6 @@ var Emoji = map[string][]string{ "🕳️", "💣", "💬", - "👁️‍🗨️", "🗨️", "🗯️", "💭", @@ -415,8 +414,6 @@ var Emoji = map[string][]string{ "🚣‍♀️", "🏊", "⛹️", - "⛹️‍♂️", - "⛹️‍♀️", "🏋️", "🚴", "🚴‍♂️", @@ -449,13 +446,6 @@ var Emoji = map[string][]string{ "👫", "👬", "💏", - "👩‍❤️‍💋‍👨", - "👨‍❤️‍💋‍👨", - "👩‍❤️‍💋‍👩", - "💑", - "👩‍❤️‍👨", - "👨‍❤️‍👨", - "👩‍❤️‍👩", "👪", "👨‍👩‍👦", "👨‍👩‍👧", @@ -1479,7 +1469,6 @@ var Emoji = map[string][]string{ "🎌", "🏴", "🏳️", - "🏳️‍⚧️", "🏴‍☠️", "🇦🇨", "🇦🇩", @@ -1739,9 +1728,6 @@ var Emoji = map[string][]string{ "🇿🇦", "🇿🇲", "🇿🇼", - "🏴󠁧󠁢󠁥󠁮󠁧󠁿", - "🏴󠁧󠁢󠁳󠁣󠁴󠁿", - "🏴󠁧󠁢󠁷󠁬󠁳󠁿", }, "description": { "grinning face", diff --git a/emoji.go b/emoji.go index 5eb4372e..c9e9785e 100644 --- a/emoji.go +++ b/emoji.go @@ -1,46 +1,44 @@ package gofakeit -import "math/rand" - // Emoji will return a random fun emoji -func Emoji() string { return emoji(globalFaker.Rand) } +func Emoji() string { return emoji(GlobalFaker) } // Emoji will return a random fun emoji -func (f *Faker) Emoji() string { return emoji(f.Rand) } +func (f *Faker) Emoji() string { return emoji(f) } -func emoji(r *rand.Rand) string { return getRandValue(r, []string{"emoji", "emoji"}) } +func emoji(f *Faker) string { return getRandValue(f, []string{"emoji", "emoji"}) } // EmojiDescription will return a random fun emoji description -func EmojiDescription() string { return emojiDescription(globalFaker.Rand) } +func EmojiDescription() string { return emojiDescription(GlobalFaker) } // EmojiDescription will return a random fun emoji description -func (f *Faker) EmojiDescription() string { return emojiDescription(f.Rand) } +func (f *Faker) EmojiDescription() string { return emojiDescription(f) } -func emojiDescription(r *rand.Rand) string { return getRandValue(r, []string{"emoji", "description"}) } +func emojiDescription(f *Faker) string { return getRandValue(f, []string{"emoji", "description"}) } // EmojiCategory will return a random fun emoji category -func EmojiCategory() string { return emojiCategory(globalFaker.Rand) } +func EmojiCategory() string { return emojiCategory(GlobalFaker) } // EmojiCategory will return a random fun emoji category -func (f *Faker) EmojiCategory() string { return emojiCategory(f.Rand) } +func (f *Faker) EmojiCategory() string { return emojiCategory(f) } -func emojiCategory(r *rand.Rand) string { return getRandValue(r, []string{"emoji", "category"}) } +func emojiCategory(f *Faker) string { return getRandValue(f, []string{"emoji", "category"}) } // EmojiAlias will return a random fun emoji alias -func EmojiAlias() string { return emojiAlias(globalFaker.Rand) } +func EmojiAlias() string { return emojiAlias(GlobalFaker) } // EmojiAlias will return a random fun emoji alias -func (f *Faker) EmojiAlias() string { return emojiAlias(f.Rand) } +func (f *Faker) EmojiAlias() string { return emojiAlias(f) } -func emojiAlias(r *rand.Rand) string { return getRandValue(r, []string{"emoji", "alias"}) } +func emojiAlias(f *Faker) string { return getRandValue(f, []string{"emoji", "alias"}) } // EmojiTag will return a random fun emoji tag -func EmojiTag() string { return emojiTag(globalFaker.Rand) } +func EmojiTag() string { return emojiTag(GlobalFaker) } // EmojiTag will return a random fun emoji tag -func (f *Faker) EmojiTag() string { return emojiTag(f.Rand) } +func (f *Faker) EmojiTag() string { return emojiTag(f) } -func emojiTag(r *rand.Rand) string { return getRandValue(r, []string{"emoji", "tag"}) } +func emojiTag(f *Faker) string { return getRandValue(f, []string{"emoji", "tag"}) } func addEmojiLookup() { AddFuncLookup("emoji", Info{ @@ -49,8 +47,8 @@ func addEmojiLookup() { Description: "Digital symbol expressing feelings or ideas in text messages and online chats", Example: "🤣", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return emoji(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return emoji(f), nil }, }) @@ -60,8 +58,8 @@ func addEmojiLookup() { Description: "Brief explanation of the meaning or emotion conveyed by an emoji", Example: "face vomiting", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return emojiDescription(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return emojiDescription(f), nil }, }) @@ -71,8 +69,8 @@ func addEmojiLookup() { Description: "Group or classification of emojis based on their common theme or use, like 'smileys' or 'animals'", Example: "Smileys & Emotion", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return emojiCategory(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return emojiCategory(f), nil }, }) @@ -82,8 +80,8 @@ func addEmojiLookup() { Description: "Alternative name or keyword used to represent a specific emoji in text or code", Example: "smile", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return emojiAlias(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return emojiAlias(f), nil }, }) @@ -93,8 +91,8 @@ func addEmojiLookup() { Description: "Label or keyword associated with an emoji to categorize or search for it easily", Example: "happy", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return emojiTag(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return emojiTag(f), nil }, }) } diff --git a/emoji_test.go b/emoji_test.go index 0fa6c977..2de91dca 100644 --- a/emoji_test.go +++ b/emoji_test.go @@ -9,188 +9,98 @@ func ExampleEmoji() { Seed(11) fmt.Println(Emoji()) - // Output: 🧛 + // Output: 🇫🇴 } func ExampleFaker_Emoji() { f := New(11) fmt.Println(f.Emoji()) - // Output: 🧛 + // Output: 🇫🇴 } func BenchmarkEmoji(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Emoji() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Emoji() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Emoji() - } - }) + for i := 0; i < b.N; i++ { + Emoji() + } } func ExampleEmojiDescription() { Seed(11) fmt.Println(EmojiDescription()) - // Output: confetti ball + // Output: flag: European Union } func ExampleFaker_EmojiDescription() { f := New(11) fmt.Println(f.EmojiDescription()) - // Output: confetti ball + // Output: flag: European Union } func BenchmarkEmojiDescription(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - EmojiDescription() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.EmojiDescription() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.EmojiDescription() - } - }) + for i := 0; i < b.N; i++ { + EmojiDescription() + } } func ExampleEmojiCategory() { Seed(11) fmt.Println(EmojiCategory()) - // Output: Food & Drink + // Output: Flags } func ExampleFaker_EmojiCategory() { f := New(11) fmt.Println(f.EmojiCategory()) - // Output: Food & Drink + // Output: Flags } func BenchmarkEmojiCategory(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - EmojiCategory() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.EmojiCategory() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.EmojiCategory() - } - }) + for i := 0; i < b.N; i++ { + EmojiCategory() + } } func ExampleEmojiAlias() { Seed(11) fmt.Println(EmojiAlias()) - // Output: deaf_person + // Output: eritrea } func ExampleFaker_EmojiAlias() { f := New(11) fmt.Println(f.EmojiAlias()) - // Output: deaf_person + // Output: eritrea } func BenchmarkEmojiAlias(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - EmojiAlias() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.EmojiAlias() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.EmojiAlias() - } - }) + for i := 0; i < b.N; i++ { + EmojiAlias() + } } func ExampleEmojiTag() { Seed(11) fmt.Println(EmojiTag()) - // Output: strong + // Output: toilet } func ExampleFaker_EmojiTag() { f := New(11) fmt.Println(f.EmojiTag()) - // Output: strong + // Output: toilet } func BenchmarkEmojiTag(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - EmojiTag() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.EmojiTag() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.EmojiTag() - } - }) + for i := 0; i < b.N; i++ { + EmojiTag() + } } diff --git a/error.go b/error.go index b31d7725..f2882099 100644 --- a/error.go +++ b/error.go @@ -2,133 +2,132 @@ package gofakeit import ( "errors" - "math/rand" ) // Error will return a random generic error func Error() error { - return err(globalFaker.Rand) + return err(GlobalFaker) } // Error will return a random generic error func (f *Faker) Error() error { - return err(f.Rand) + return err(f) } -func err(r *rand.Rand) error { - return errors.New(generate(r, getRandValue(r, []string{"error", "generic"}))) +func err(f *Faker) error { + return errors.New(generate(f, getRandValue(f, []string{"error", "generic"}))) } // ErrorObject will return a random error object word func ErrorObject() error { - return errorObject(globalFaker.Rand) + return errorObject(GlobalFaker) } // ErrorObject will return a random error object word func (f *Faker) ErrorObject() error { - return errorObject(f.Rand) + return errorObject(f) } -func errorObject(r *rand.Rand) error { - return errors.New(generate(r, getRandValue(r, []string{"error", "object"}))) +func errorObject(f *Faker) error { + return errors.New(generate(f, getRandValue(f, []string{"error", "object"}))) } // ErrorDatabase will return a random database error func ErrorDatabase() error { - return errorDatabase(globalFaker.Rand) + return errorDatabase(GlobalFaker) } // ErrorDatabase will return a random database error func (f *Faker) ErrorDatabase() error { - return errorDatabase(f.Rand) + return errorDatabase(f) } -func errorDatabase(r *rand.Rand) error { - return errors.New(generate(r, getRandValue(r, []string{"error", "database"}))) +func errorDatabase(f *Faker) error { + return errors.New(generate(f, getRandValue(f, []string{"error", "database"}))) } // ErrorGRPC will return a random gRPC error func ErrorGRPC() error { - return errorGRPC(globalFaker.Rand) + return errorGRPC(GlobalFaker) } // ErrorGRPC will return a random gRPC error func (f *Faker) ErrorGRPC() error { - return errorGRPC(f.Rand) + return errorGRPC(f) } -func errorGRPC(r *rand.Rand) error { - return errors.New(generate(r, getRandValue(r, []string{"error", "grpc"}))) +func errorGRPC(f *Faker) error { + return errors.New(generate(f, getRandValue(f, []string{"error", "grpc"}))) } // ErrorHTTP will return a random HTTP error func ErrorHTTP() error { - return errorHTTP(globalFaker.Rand) + return errorHTTP(GlobalFaker) } // ErrorHTTP will return a random HTTP error func (f *Faker) ErrorHTTP() error { - return errorHTTP(f.Rand) + return errorHTTP(f) } -func errorHTTP(r *rand.Rand) error { - return errors.New(generate(r, getRandValue(r, []string{"error", "http"}))) +func errorHTTP(f *Faker) error { + return errors.New(generate(f, getRandValue(f, []string{"error", "http"}))) } // ErrorHTTPClient will return a random HTTP client error response (400-418) func ErrorHTTPClient() error { - return errorHTTPClient(globalFaker.Rand) + return errorHTTPClient(GlobalFaker) } // ErrorHTTPClient will return a random HTTP client error response (400-418) func (f *Faker) ErrorHTTPClient() error { - return errorHTTPClient(f.Rand) + return errorHTTPClient(f) } -func errorHTTPClient(r *rand.Rand) error { - return errors.New(generate(r, getRandValue(r, []string{"error", "http_client"}))) +func errorHTTPClient(f *Faker) error { + return errors.New(generate(f, getRandValue(f, []string{"error", "http_client"}))) } // ErrorHTTPServer will return a random HTTP server error response (500-511) func ErrorHTTPServer() error { - return errorHTTPServer(globalFaker.Rand) + return errorHTTPServer(GlobalFaker) } // ErrorHTTPServer will return a random HTTP server error response (500-511) func (f *Faker) ErrorHTTPServer() error { - return errorHTTPServer(f.Rand) + return errorHTTPServer(f) } -func errorHTTPServer(r *rand.Rand) error { - return errors.New(generate(r, getRandValue(r, []string{"error", "http_server"}))) +func errorHTTPServer(f *Faker) error { + return errors.New(generate(f, getRandValue(f, []string{"error", "http_server"}))) } // ErrorRuntime will return a random runtime error func ErrorRuntime() error { - return errorRuntime(globalFaker.Rand) + return errorRuntime(GlobalFaker) } // ErrorRuntime will return a random runtime error func (f *Faker) ErrorRuntime() error { - return errorRuntime(f.Rand) + return errorRuntime(f) } -func errorRuntime(r *rand.Rand) error { - return errors.New(generate(r, getRandValue(r, []string{"error", "runtime"}))) +func errorRuntime(f *Faker) error { + return errors.New(generate(f, getRandValue(f, []string{"error", "runtime"}))) } // ErrorValidation will return a random validation error func ErrorValidation() error { - return errorValidation(globalFaker.Rand) + return errorValidation(GlobalFaker) } // ErrorValidation will return a random validation error func (f *Faker) ErrorValidation() error { - return errorValidation(f.Rand) + return errorValidation(f) } -func errorValidation(r *rand.Rand) error { - return errors.New(generate(r, getRandValue(r, []string{"error", "validation"}))) +func errorValidation(f *Faker) error { + return errors.New(generate(f, getRandValue(f, []string{"error", "validation"}))) } func addErrorLookup() { @@ -138,8 +137,8 @@ func addErrorLookup() { Description: "Message displayed by a computer or software when a problem or mistake is encountered", Example: "syntax error", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return err(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return err(f), nil }, }) @@ -149,8 +148,8 @@ func addErrorLookup() { Description: "Various categories conveying details about encountered errors", Example: "protocol", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return errorObject(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return errorObject(f), nil }, }) @@ -160,8 +159,8 @@ func addErrorLookup() { Description: "A problem or issue encountered while accessing or managing a database", Example: "sql error", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return errorDatabase(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return errorDatabase(f), nil }, }) @@ -171,8 +170,8 @@ func addErrorLookup() { Description: "Communication failure in the high-performance, open-source universal RPC framework", Example: "client protocol error", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return errorGRPC(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return errorGRPC(f), nil }, }) @@ -182,8 +181,8 @@ func addErrorLookup() { Description: "A problem with a web http request", Example: "invalid method", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return errorHTTP(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return errorHTTP(f), nil }, }) @@ -193,8 +192,8 @@ func addErrorLookup() { Description: "Failure or issue occurring within a client software that sends requests to web servers", Example: "request timeout", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return errorHTTPClient(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return errorHTTPClient(f), nil }, }) @@ -204,8 +203,8 @@ func addErrorLookup() { Description: "Failure or issue occurring within a server software that recieves requests from clients", Example: "internal server error", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return errorHTTPServer(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return errorHTTPServer(f), nil }, }) @@ -215,8 +214,8 @@ func addErrorLookup() { Description: "Malfunction occuring during program execution, often causing abrupt termination or unexpected behavior", Example: "address out of bounds", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return errorRuntime(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return errorRuntime(f), nil }, }) @@ -226,8 +225,8 @@ func addErrorLookup() { Description: "Occurs when input data fails to meet required criteria or format specifications", Example: "missing required field", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return errorValidation(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return errorValidation(f), nil }, }) } diff --git a/error_test.go b/error_test.go index faf51cd6..2cf6d32b 100644 --- a/error_test.go +++ b/error_test.go @@ -9,114 +9,60 @@ func ExampleError() { Seed(11) fmt.Println(Error()) - // Output: failed to calculate pointer + // Output: variable assigned before declaration } func ExampleFaker_Error() { f := New(11) fmt.Println(f.Error()) - // Output: failed to calculate pointer + // Output: variable assigned before declaration } func BenchmarkError(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Error() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Error() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Error() - } - }) + for i := 0; i < b.N; i++ { + Error() + } } func ExampleErrorObject() { Seed(11) fmt.Println(ErrorObject()) - // Output: argument + // Output: url } func ExampleFaker_ErrorObject() { f := New(11) fmt.Println(f.ErrorObject()) - // Output: argument + // Output: url } func BenchmarkErrorObject(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ErrorObject() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ErrorObject() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ErrorObject() - } - }) + for i := 0; i < b.N; i++ { + ErrorObject() + } } func ExampleErrorDatabase() { Seed(11) fmt.Println(ErrorDatabase()) - // Output: bad connection + // Output: destination pointer is nil } func ExampleFaker_ErrorDatabase() { f := New(11) fmt.Println(f.ErrorDatabase()) - // Output: bad connection + // Output: destination pointer is nil } func BenchmarkErrorDatabase(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ErrorDatabase() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ErrorDatabase() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ErrorDatabase() - } - }) + for i := 0; i < b.N; i++ { + ErrorDatabase() + } } func ExampleErrorGRPC() { @@ -134,27 +80,9 @@ func ExampleFaker_ErrorGRPC() { } func BenchmarkErrorGRPC(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ErrorGRPC() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ErrorGRPC() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ErrorGRPC() - } - }) + for i := 0; i < b.N; i++ { + ErrorGRPC() + } } func ExampleErrorHTTP() { @@ -172,177 +100,87 @@ func ExampleFaker_ErrorHTTP() { } func BenchmarkErrorHTTP(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ErrorHTTP() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ErrorHTTP() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ErrorHTTP() - } - }) + for i := 0; i < b.N; i++ { + ErrorHTTP() + } } func ExampleErrorHTTPClient() { Seed(11) fmt.Println(ErrorHTTPClient()) - // Output: payment required + // Output: expectation failed } func ExampleFaker_ErrorHTTPClient() { f := New(11) fmt.Println(f.ErrorHTTPClient()) - // Output: payment required + // Output: expectation failed } func BenchmarkErrorHTTPClient(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ErrorHTTPClient() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ErrorHTTPClient() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ErrorHTTPClient() - } - }) + for i := 0; i < b.N; i++ { + ErrorHTTPClient() + } } func ExampleErrorHTTPServer() { Seed(11) fmt.Println(ErrorHTTPServer()) - // Output: internal server error + // Output: not extended } func ExampleFaker_ErrorHTTPServer() { f := New(11) fmt.Println(f.ErrorHTTPServer()) - // Output: internal server error + // Output: not extended } func BenchmarkErrorHTTPServer(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ErrorHTTPServer() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ErrorHTTPServer() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ErrorHTTPServer() - } - }) + for i := 0; i < b.N; i++ { + ErrorHTTPServer() + } } func ExampleErrorRuntime() { Seed(11) fmt.Println(ErrorRuntime()) - // Output: panic: runtime error: invalid memory address or nil pointer dereference + // Output: expected 2 arguments, got 3 } func ExampleFaker_ErrorRuntime() { f := New(11) fmt.Println(f.ErrorRuntime()) - // Output: panic: runtime error: invalid memory address or nil pointer dereference + // Output: expected 2 arguments, got 3 } func BenchmarkErrorRuntime(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ErrorRuntime() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ErrorRuntime() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ErrorRuntime() - } - }) + for i := 0; i < b.N; i++ { + ErrorRuntime() + } } func ExampleErrorValidation() { Seed(11) fmt.Println(ErrorValidation()) - // Output: state max length exceeded + // Output: payment details cannot be verified } func ExampleFaker_ErrorValidation() { f := New(11) fmt.Println(f.ErrorValidation()) - // Output: state max length exceeded + // Output: payment details cannot be verified } func BenchmarkErrorValidation(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ErrorValidation() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ErrorValidation() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ErrorValidation() - } - }) + for i := 0; i < b.N; i++ { + ErrorValidation() + } } diff --git a/fakeable.go b/fakeable.go index 1ed5b6fe..01932ec2 100644 --- a/fakeable.go +++ b/fakeable.go @@ -15,7 +15,7 @@ type Fakeable interface { func isFakeable(t reflect.Type) bool { fakeableTyp := reflect.TypeOf((*Fakeable)(nil)).Elem() - return t.Implements(fakeableTyp) || reflect.PtrTo(t).Implements(fakeableTyp) + return t.Implements(fakeableTyp) || reflect.PointerTo(t).Implements(fakeableTyp) } func callFake(faker *Faker, v reflect.Value, possibleKinds ...reflect.Kind) (any, error) { diff --git a/fakeable_external_test.go b/fakeable_external_test.go index 13efa17a..da7d5861 100644 --- a/fakeable_external_test.go +++ b/fakeable_external_test.go @@ -2,11 +2,10 @@ package gofakeit_test import ( "fmt" - "math/rand" "testing" "time" - "github.com/brianvoe/gofakeit/v6" + "github.com/brianvoe/gofakeit/v7" ) var ( @@ -596,7 +595,7 @@ func TestNestedOverrideCustom(t *testing.T) { Description: "Raw date time.Time object", }, }, - Generate: func(r *rand.Rand, m *gofakeit.MapParams, info *gofakeit.Info) (any, error) { + Generate: func(f *gofakeit.Faker, m *gofakeit.MapParams, info *gofakeit.Info) (any, error) { return gofakeit.Date(), nil }, }) @@ -762,7 +761,6 @@ func ExampleEvenInt() { fmt.Println(E1) fmt.Println(E2) - // Output: - // 6 - // -92 + // Output: -2 + // 122 } diff --git a/fakeable_test.go b/fakeable_test.go index a353730d..2fbc9aa1 100644 --- a/fakeable_test.go +++ b/fakeable_test.go @@ -74,23 +74,23 @@ func ExampleFakeable() { fmt.Printf("%#v\n", t2) fmt.Printf("%#v\n", t3) fmt.Printf("%#v\n", t4) - // Expected Output: - // gofakeit.testStruct1{B:"Margarette"} - // gofakeit.testStruct1{B:"Margarette"} - // gofakeit.testStruct2{B:"Margarette"} - // gofakeit.testStruct2{B:"Margarette"} + + // Output: gofakeit.testStruct1{B:"Colton"} + // gofakeit.testStruct1{B:"Colton"} + // gofakeit.testStruct2{B:"Colton"} + // gofakeit.testStruct2{B:"Colton"} } type gammaFloat64 float64 -func (gammaFloat64) Fake(faker *Faker) (any, error) { +func (gammaFloat64) Fake(f *Faker) (any, error) { alpha := 2.0 // Generate a random value from the Gamma distribution var r float64 for r == 0 { - u := faker.Float64Range(0, 1) - v := faker.Float64Range(0, 1) + u := f.Float64Range(0, 1) + v := f.Float64Range(0, 1) w := u * (1 - u) y := math.Sqrt(-2 * math.Log(w) / w) x := alpha * (y*v + u - 0.5) @@ -101,7 +101,7 @@ func (gammaFloat64) Fake(faker *Faker) (any, error) { return gammaFloat64(r), nil } -func ExampleGammaFloat64() { +func ExampleFakeable_gammaFloat64() { f1 := New(100) // Fakes random values from the Gamma distribution @@ -116,10 +116,9 @@ func ExampleGammaFloat64() { fmt.Println(A2) fmt.Println(A3) - // Output: - // 10.300651760129734 - // 5.391434877284098 - // 2.0575989252140676 + // Output: 1.9058272589164647 + // 1.951453943304136 + // 4.336093466276675 } type poissonInt64 int64 @@ -139,18 +138,18 @@ func (poissonInt64) Fake(faker *Faker) (any, error) { return poissonInt64(k - 1), nil } -type customerSupportEmployee struct { +type employee struct { Name string `fake:"{firstname} {lastname}"` CallCountPerHour poissonInt64 } -func ExamplecustomerSupportEmployee() { +func ExampleFakeable_employee() { f1 := New(100) // Fakes random values from the Gamma distribution - var A1 customerSupportEmployee - var A2 customerSupportEmployee - var A3 customerSupportEmployee + var A1 employee + var A2 employee + var A3 employee f1.Struct(&A1) f1.Struct(&A2) f1.Struct(&A3) @@ -159,8 +158,7 @@ func ExamplecustomerSupportEmployee() { fmt.Printf("%#v\n", A2) fmt.Printf("%#v\n", A3) - // Output: - // gofakeit.customerSupportEmployee{Name:"Pearline Rippin", CallCountPerHour:12} - // gofakeit.customerSupportEmployee{Name:"Sammie Renner", CallCountPerHour:23} - // gofakeit.customerSupportEmployee{Name:"Katlyn Runte", CallCountPerHour:8} + // Output: gofakeit.employee{Name:"Madelynn Hickle", CallCountPerHour:17} + // gofakeit.employee{Name:"Brooke Berge", CallCountPerHour:8} + // gofakeit.employee{Name:"Rosalee Roberts", CallCountPerHour:10} } diff --git a/faker.go b/faker.go index 715c67ca..ac0cf85b 100644 --- a/faker.go +++ b/faker.go @@ -1,103 +1,106 @@ package gofakeit import ( - crand "crypto/rand" - "encoding/binary" - "math/rand" + "errors" + "math/rand/v2" + "reflect" "sync" + + "github.com/brianvoe/gofakeit/v7/source" ) -// Create global variable to deal with global function call. -var globalFaker *Faker = New(0) +// Create global variable to deal with global function call +var GlobalFaker *Faker = New(0) -// Faker struct is the primary struct for using localized. +// Faker struct is the primary struct for using localized type Faker struct { - Rand *rand.Rand -} - -type lockedSource struct { - lk sync.Mutex - src rand.Source64 -} - -func (r *lockedSource) Int63() (n int64) { - r.lk.Lock() - n = r.src.Int63() - r.lk.Unlock() + Rand rand.Source - return + // Lock to make thread safe + Locked bool + mu sync.Mutex } -func (r *lockedSource) Uint64() (n uint64) { - r.lk.Lock() - n = r.src.Uint64() - r.lk.Unlock() - return -} - -func (r *lockedSource) Seed(seed int64) { - r.lk.Lock() - r.src.Seed(seed) - r.lk.Unlock() +// New creates and returns a new Faker struct seeded with a given seed +// using the PCG algorithm in lock mode for thread safety +func New(seed uint64) *Faker { + return &Faker{ + Rand: rand.NewPCG(seed, seed), + Locked: true, + } } -type cryptoRand struct { - sync.Mutex - buf []byte +// NewFaker takes in a rand.Source and thread lock state and returns a new Faker struct +func NewFaker(src rand.Source, lock bool) *Faker { + return &Faker{ + Rand: src, + Locked: lock, + } } -func (c *cryptoRand) Seed(seed int64) {} +// Seed attempts to seed the Faker with the given seed +func (f *Faker) Seed(args ...any) error { + // Lock if locked + if f.Locked { + f.mu.Lock() + defer f.mu.Unlock() + } -func (c *cryptoRand) Uint64() uint64 { - // Lock to make reading thread safe - c.Lock() - defer c.Unlock() + // Ensure GlobalFaker is not nil and Rand is initialized + if GlobalFaker == nil || GlobalFaker.Rand == nil { + return errors.New("GlobalFaker or GlobalFaker.Rand is nil") + } - crand.Read(c.buf) - return binary.BigEndian.Uint64(c.buf) -} + // If args is empty or 0, seed with a random crypto seed + if len(args) == 0 { + faker := NewFaker(source.NewCrypto(), false) + args = append(args, faker.Uint64()) + } -func (c *cryptoRand) Int63() int64 { - return int64(c.Uint64() & ^uint64(1<<63)) -} + if args[0] == 0 { + faker := NewFaker(source.NewCrypto(), false) + args[0] = faker.Uint64() + } -// New will utilize math/rand for concurrent random usage. -// Setting seed to 0 will use crypto/rand for the initial seed number. -func New(seed int64) *Faker { - // If passing 0 create crypto safe int64 for initial seed number - if seed == 0 { - binary.Read(crand.Reader, binary.BigEndian, &seed) + // Retrieve the Seed method + method := reflect.ValueOf(GlobalFaker.Rand).MethodByName("Seed") + if !method.IsValid() { + return errors.New("Seed method not found") } - return &Faker{Rand: rand.New(&lockedSource{src: rand.NewSource(seed).(rand.Source64)})} -} + // Adjust args if method requires exactly 2 args but only 1 was provided + if method.Type().NumIn() == 2 && len(args) == 1 { + args = append(args, args[0]) // Duplicate the first value if only one is provided + } -// NewUnlocked will utilize math/rand for non concurrent safe random usage. -// Setting seed to 0 will use crypto/rand for the initial seed number. -// NewUnlocked is more performant but not safe to run concurrently. -func NewUnlocked(seed int64) *Faker { - // If passing 0 create crypto safe int64 for initial seed number - if seed == 0 { - binary.Read(crand.Reader, binary.BigEndian, &seed) + // Get array of function argument types and prepare converted arguments + argTypes := make([]reflect.Type, method.Type().NumIn()) + convertedArgs := make([]reflect.Value, len(args)) + for i := 0; i < method.Type().NumIn(); i++ { + argTypes[i] = method.Type().In(i) } - return &Faker{Rand: rand.New(rand.NewSource(seed))} -} + // Convert args to the expected type by the Seed method + for i, arg := range args { + if i < len(argTypes) { // Ensure arg index is within argTypes bounds + argValue := reflect.ValueOf(arg) + // Check if conversion is necessary + if argValue.Type().ConvertibleTo(argTypes[i]) { + convertedArgs[i] = argValue.Convert(argTypes[i]) + } else { + // If not convertible, use the argument as is (reflectively) + convertedArgs[i] = argValue + } + } + } -// NewCrypto will utilize crypto/rand for concurrent random usage. -func NewCrypto() *Faker { - return &Faker{Rand: rand.New(&cryptoRand{ - buf: make([]byte, 8), - })} -} + // Dynamically call the Seed method with converted arguments + method.Call(convertedArgs) -// NewCustom will utilize a custom rand.Source64 for concurrent random usage -// See https://golang.org/src/math/rand/rand.go for required interface methods -func NewCustom(source rand.Source64) *Faker { - return &Faker{Rand: rand.New(source)} + return nil } -// SetGlobalFaker will allow you to set what type of faker is globally used. Defailt is math/rand -func SetGlobalFaker(faker *Faker) { - globalFaker = faker +// Seed attempts to seed the GlobalFaker with the given seed +func Seed(args ...any) error { + return GlobalFaker.Seed(args...) } diff --git a/faker_test.go b/faker_test.go index c64f00b3..6b5c191f 100644 --- a/faker_test.go +++ b/faker_test.go @@ -2,12 +2,14 @@ package gofakeit import ( "fmt" + "math/rand/v2" "sync" "testing" ) func Example() { Seed(11) + fmt.Println("Name:", Name()) fmt.Println("Email:", Email()) fmt.Println("Phone:", Phone()) @@ -21,23 +23,22 @@ func Example() { fmt.Println("Job Title:", JobTitle()) fmt.Println("Password:", Password(true, true, true, true, false, 32)) - // Output: - // Name: Markus Moen - // Email: alaynawuckert@kozey.biz - // Phone: 9948995369 - // Address: 35300 South Roadshaven, Miami, Tennessee 58302 - // BS: streamline - // Beer Name: Pliny The Elder - // Color: Gray - // Company: Center for Responsive Politics - // Credit Card: 3821714800889989 - // Hacker Phrase: Overriding the capacitor won't do anything, we need to compress the online SMTP protocol! - // Job Title: Supervisor - // Password: #8L79W6s4E9jT2Q047??YkyD0xxnC2#u + // Output: Name: Sonny Stiedemann + // Email: codydonnelly@leannon.biz + // Phone: 7598907999 + // Address: 4737 Port Hillstown, Santa Ana, Alabama 41026 + // BS: enable + // Beer Name: Chocolate St + // Color: Turquoise + // Company: Boundless + // Credit Card: 6282690620525711 + // Hacker Phrase: Try to bundle the PNG firewall, maybe it will deconstruct the open-source bandwidth! + // Job Title: Assistant + // Password: Nyf8p8ka1Kvgn**@3H&$w7j01yM1vkc2 } func ExampleNew() { - // Create new pseudo random faker struct and set initial seed + // Get new faker with default settings fake := New(11) // All global functions are also available in the structs methods @@ -46,101 +47,60 @@ func ExampleNew() { fmt.Println("Phone:", fake.Phone()) // Output: - // Name: Markus Moen - // Email: alaynawuckert@kozey.biz - // Phone: 9948995369 + // Name: Sonny Stiedemann + // Email: codydonnelly@leannon.biz + // Phone: 7598907999 } -func ExampleNewUnlocked() { - fake := NewUnlocked(11) +func ExampleNewFaker() { + // Create new faker with ChaCha8, cryptographically secure + chacha := rand.NewChaCha8([32]byte{5, 4, 3, 2, 1, 0}) + fake := NewFaker(chacha, true) - // All global functions are also available in the structs methods - fmt.Println("Name:", fake.Name()) - fmt.Println("Email:", fake.Email()) - fmt.Println("Phone:", fake.Phone()) + // or - // Output: - // Name: Markus Moen - // Email: alaynawuckert@kozey.biz - // Phone: 9948995369 -} + // Create new faker with PCG, pseudo-random + pcg := rand.NewPCG(0, 0) + fake = NewFaker(pcg, false) -func TestNewUnlocked(t *testing.T) { - fake := NewUnlocked(0) - if fake.Name() == "" { - t.Error("Name was empty") - } -} - -func ExampleNewCrypto() { - // Create new crypto faker struct - fake := NewCrypto() - - // All global functions are also available in the structs methods fmt.Println("Name:", fake.Name()) - fmt.Println("Email:", fake.Email()) - fmt.Println("Phone:", fake.Phone()) - // Cannot output example as crypto/rand cant be predicted + // Output: + // Name: Damian Pagac } -func TestNewCrypto(t *testing.T) { - // Create new crypto faker struct - fake := NewCrypto() +func TestSeed(t *testing.T) { + // Test crypto that has no parameters in Seed + GlobalFaker = New(11) - // All global functions are also available in the structs methods - name := fake.Name() - email := fake.Email() - phone := fake.Phone() + // Test a simple function + name := Name() - if name == "" || email == "" || phone == "" { - t.Error("One of the values was empty") + // Seed + err := Seed(11) + if err != nil { + t.Error(err) } -} - -type customRand struct{} - -func (c *customRand) Seed(seed int64) {} -func (c *customRand) Uint64() uint64 { return 8675309 } -func (c *customRand) Int63() int64 { return int64(c.Uint64() & ^uint64(1<<63)) } - -func ExampleNewCustom() { - // Setup stuct and methods required to meet interface needs - // type customRand struct {} - // func (c *customRand) Seed(seed int64) {} - // func (c *customRand) Uint64() uint64 { return 8675309 } - // func (c *customRand) Int63() int64 { return int64(c.Uint64() & ^uint64(1<<63)) } - - // Create new custom faker struct - fake := NewCustom(&customRand{}) - - // All global functions are also available in the structs methods - fmt.Println("Name:", fake.Name()) - fmt.Println("Email:", fake.Email()) - fmt.Println("Phone:", fake.Phone()) - // Output: - // Name: Aaliyah Abbott - // Email: aaliyahabbott@abbott.com - // Phone: 1000000000 -} - -func ExampleSetGlobalFaker() { - cryptoFaker := NewCrypto() - SetGlobalFaker(cryptoFaker) + // Make sure name is the same + if name != Name() { + t.Error("Name was different after seed") + } } func TestSetGlobalFaker(t *testing.T) { - cryptoFaker := NewCrypto() - SetGlobalFaker(cryptoFaker) + // Set global to crypto + crypto := rand.NewPCG(11, 11) + GlobalFaker = NewFaker(crypto, true) + // Test a simple function name := Name() if name == "" { t.Error("Name was empty") } - // Set global back to psuedo - SetGlobalFaker(New(0)) + // Set global back to default + GlobalFaker = New(0) } func TestConcurrency(t *testing.T) { @@ -148,7 +108,7 @@ func TestConcurrency(t *testing.T) { setupComplete.Add(1) var wg sync.WaitGroup - for i := 0; i < 10000; i++ { + for i := 0; i < 1000; i++ { wg.Add(1) go func() { setupComplete.Wait() diff --git a/file.go b/file.go index 3812021e..ffefe863 100644 --- a/file.go +++ b/file.go @@ -1,22 +1,20 @@ package gofakeit -import "math/rand" - // FileExtension will generate a random file extension -func FileExtension() string { return fileExtension(globalFaker.Rand) } +func FileExtension() string { return fileExtension(GlobalFaker) } // FileExtension will generate a random file extension -func (f *Faker) FileExtension() string { return fileExtension(f.Rand) } +func (f *Faker) FileExtension() string { return fileExtension(f) } -func fileExtension(r *rand.Rand) string { return getRandValue(r, []string{"file", "extension"}) } +func fileExtension(f *Faker) string { return getRandValue(f, []string{"file", "extension"}) } // FileMimeType will generate a random mime file type -func FileMimeType() string { return fileMimeType(globalFaker.Rand) } +func FileMimeType() string { return fileMimeType(GlobalFaker) } // FileMimeType will generate a random mime file type -func (f *Faker) FileMimeType() string { return fileMimeType(f.Rand) } +func (f *Faker) FileMimeType() string { return fileMimeType(f) } -func fileMimeType(r *rand.Rand) string { return getRandValue(r, []string{"file", "mime_type"}) } +func fileMimeType(f *Faker) string { return getRandValue(f, []string{"file", "mime_type"}) } func addFileLookup() { AddFuncLookup("fileextension", Info{ @@ -25,8 +23,8 @@ func addFileLookup() { Description: "Suffix appended to a filename indicating its format or type", Example: "nes", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return fileExtension(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return fileExtension(f), nil }, }) @@ -36,8 +34,8 @@ func addFileLookup() { Description: "Defines file format and nature for browsers and email clients using standardized identifiers", Example: "application/json", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return fileMimeType(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return fileMimeType(f), nil }, }) } diff --git a/file_test.go b/file_test.go index 08c5faef..8b239a59 100644 --- a/file_test.go +++ b/file_test.go @@ -9,74 +9,38 @@ func ExampleFileMimeType() { Seed(11) fmt.Println(FileMimeType()) - // Output: application/dsptype + // Output: application/x-wri } func ExampleFaker_FileMimeType() { f := New(11) fmt.Println(f.FileMimeType()) - // Output: application/dsptype + // Output: application/x-wri } func BenchmarkFileMimeType(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - FileMimeType() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.FileMimeType() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.FileMimeType() - } - }) + for i := 0; i < b.N; i++ { + FileMimeType() + } } func ExampleFileExtension() { Seed(11) fmt.Println(FileExtension()) - // Output: nes + // Output: dtd } func ExampleFaker_FileExtension() { f := New(11) fmt.Println(f.FileExtension()) - // Output: nes + // Output: dtd } func BenchmarkFileExtension(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - FileExtension() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.FileExtension() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.FileExtension() - } - }) + for i := 0; i < b.N; i++ { + FileExtension() + } } diff --git a/finance.go b/finance.go index a46907a6..4e363326 100644 --- a/finance.go +++ b/finance.go @@ -1,7 +1,6 @@ package gofakeit import ( - "math/rand" "strconv" "unicode" ) @@ -10,17 +9,17 @@ const cusipStr = upperStr + numericStr // CUSIP func Cusip() string { - return cusip(globalFaker.Rand) + return cusip(GlobalFaker) } func (f *Faker) Cusip() string { - return cusip(f.Rand) + return cusip(f) } -func cusip(r *rand.Rand) string { +func cusip(f *Faker) string { cusipBytes := make([]byte, 8) for i := 0; i < len(cusipBytes); i++ { - cusipBytes[i] = byte(cusipStr[r.Intn(len(cusipStr))]) + cusipBytes[i] = byte(cusipStr[f.IntN(len(cusipStr))]) } baseCusip := string(cusipBytes) @@ -31,16 +30,16 @@ func cusip(r *rand.Rand) string { // ISIN func Isin() string { - return isin(globalFaker.Rand) + return isin(GlobalFaker) } func (f *Faker) Isin() string { - return isin(f.Rand) + return isin(f) } -func isin(r *rand.Rand) string { - countryCode := CountryAbr() - nsin := cusip(r) +func isin(f *Faker) string { + countryCode := countryAbr(f) + nsin := cusip(f) isinChkDig := isinChecksumDigit(countryCode + nsin) return countryCode + nsin + isinChkDig } @@ -111,8 +110,8 @@ func addFinanceLookup() { Description: "Unique identifier for securities, especially bonds, in the United States and Canada", Example: "38259P508", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return cusip(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return cusip(f), nil }, }) AddFuncLookup("isin", Info{ @@ -121,8 +120,8 @@ func addFinanceLookup() { Description: "International standard code for uniquely identifying securities worldwide", Example: "CVLRQCZBXQ97", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return isin(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return isin(f), nil }, }) } diff --git a/finance_test.go b/finance_test.go index 9a7442bf..b824c9d7 100644 --- a/finance_test.go +++ b/finance_test.go @@ -10,14 +10,14 @@ func ExampleCusip() { Seed(11) fmt.Println(Cusip()) - // Output: MLRQCZBX0 + // Output: 64HHTI0T8 } func ExampleFaker_Cusip() { f := New(11) fmt.Println(f.Cusip()) - // Output: MLRQCZBX0 + // Output: 64HHTI0T8 } func TestCusip(t *testing.T) { @@ -54,27 +54,9 @@ func TestCusipCheckDigit(t *testing.T) { } func BenchmarkCusip(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Cusip() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Cusip() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Cusip() - } - }) + for i := 0; i < b.N; i++ { + Cusip() + } } // ISIN Tests @@ -82,14 +64,14 @@ func ExampleIsin() { Seed(11) fmt.Println(Isin()) - // Output: CVLRQCZBXQ97 + // Output: TO4HHTI0T819 } func ExampleFaker_Isin() { f := New(11) fmt.Println(f.Isin()) - // Output: AMMLRQCZBX03 + // Output: TO4HHTI0T819 } func TestIsin(t *testing.T) { @@ -126,25 +108,7 @@ func TestIsinCheckDigit(t *testing.T) { } func BenchmarkIsin(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Isin() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Isin() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Isin() - } - }) + for i := 0; i < b.N; i++ { + Isin() + } } diff --git a/food.go b/food.go index ae1bb2fd..111dbc25 100644 --- a/food.go +++ b/food.go @@ -1,89 +1,88 @@ package gofakeit import ( - "math/rand" "strings" ) // Fruit will return a random fruit name -func Fruit() string { return fruit(globalFaker.Rand) } +func Fruit() string { return fruit(GlobalFaker) } // Fruit will return a random fruit name -func (f *Faker) Fruit() string { return fruit(f.Rand) } +func (f *Faker) Fruit() string { return fruit(f) } -func fruit(r *rand.Rand) string { return getRandValue(r, []string{"food", "fruit"}) } +func fruit(f *Faker) string { return getRandValue(f, []string{"food", "fruit"}) } // Vegetable will return a random vegetable name -func Vegetable() string { return vegetable(globalFaker.Rand) } +func Vegetable() string { return vegetable(GlobalFaker) } // Vegetable will return a random vegetable name -func (f *Faker) Vegetable() string { return vegetable(f.Rand) } +func (f *Faker) Vegetable() string { return vegetable(f) } -func vegetable(r *rand.Rand) string { return getRandValue(r, []string{"food", "vegetable"}) } +func vegetable(f *Faker) string { return getRandValue(f, []string{"food", "vegetable"}) } // Breakfast will return a random breakfast name -func Breakfast() string { return breakfast(globalFaker.Rand) } +func Breakfast() string { return breakfast(GlobalFaker) } // Breakfast will return a random breakfast name -func (f *Faker) Breakfast() string { return breakfast(f.Rand) } +func (f *Faker) Breakfast() string { return breakfast(f) } -func breakfast(r *rand.Rand) string { - v := getRandValue(r, []string{"food", "breakfast"}) +func breakfast(f *Faker) string { + v := getRandValue(f, []string{"food", "breakfast"}) return strings.ToUpper(v[:1]) + v[1:] } // Lunch will return a random lunch name -func Lunch() string { return lunch(globalFaker.Rand) } +func Lunch() string { return lunch(GlobalFaker) } // Lunch will return a random lunch name -func (f *Faker) Lunch() string { return lunch(f.Rand) } +func (f *Faker) Lunch() string { return lunch(f) } -func lunch(r *rand.Rand) string { - v := getRandValue(r, []string{"food", "lunch"}) +func lunch(f *Faker) string { + v := getRandValue(f, []string{"food", "lunch"}) return strings.ToUpper(v[:1]) + v[1:] } // Dinner will return a random dinner name -func Dinner() string { return dinner(globalFaker.Rand) } +func Dinner() string { return dinner(GlobalFaker) } // Dinner will return a random dinner name -func (f *Faker) Dinner() string { return dinner(f.Rand) } +func (f *Faker) Dinner() string { return dinner(f) } -func dinner(r *rand.Rand) string { - v := getRandValue(r, []string{"food", "dinner"}) +func dinner(f *Faker) string { + v := getRandValue(f, []string{"food", "dinner"}) return strings.ToUpper(v[:1]) + v[1:] } // Drink will return a random drink name -func Drink() string { return drink(globalFaker.Rand) } +func Drink() string { return drink(GlobalFaker) } // Drink will return a random drink name -func (f *Faker) Drink() string { return drink(f.Rand) } +func (f *Faker) Drink() string { return drink(f) } -func drink(r *rand.Rand) string { - v := getRandValue(r, []string{"food", "drink"}) +func drink(f *Faker) string { + v := getRandValue(f, []string{"food", "drink"}) return strings.ToUpper(v[:1]) + v[1:] } // Snack will return a random snack name -func Snack() string { return snack(globalFaker.Rand) } +func Snack() string { return snack(GlobalFaker) } // Snack will return a random snack name -func (f *Faker) Snack() string { return snack(f.Rand) } +func (f *Faker) Snack() string { return snack(f) } -func snack(r *rand.Rand) string { - v := getRandValue(r, []string{"food", "snack"}) +func snack(f *Faker) string { + v := getRandValue(f, []string{"food", "snack"}) return strings.ToUpper(v[:1]) + v[1:] } // Dessert will return a random dessert name -func Dessert() string { return dessert(globalFaker.Rand) } +func Dessert() string { return dessert(GlobalFaker) } // Dessert will return a random dessert name -func (f *Faker) Dessert() string { return dessert(f.Rand) } +func (f *Faker) Dessert() string { return dessert(f) } -func dessert(r *rand.Rand) string { - v := getRandValue(r, []string{"food", "dessert"}) +func dessert(f *Faker) string { + v := getRandValue(f, []string{"food", "dessert"}) return strings.ToUpper(v[:1]) + v[1:] } @@ -94,8 +93,8 @@ func addFoodLookup() { Description: "Edible plant part, typically sweet, enjoyed as a natural snack or dessert", Example: "Peach", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return fruit(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return fruit(f), nil }, }) @@ -105,8 +104,8 @@ func addFoodLookup() { Description: "Edible plant or part of a plant, often used in savory cooking or salads", Example: "Amaranth Leaves", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return vegetable(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return vegetable(f), nil }, }) @@ -116,8 +115,8 @@ func addFoodLookup() { Description: "First meal of the day, typically eaten in the morning", Example: "Blueberry banana happy face pancakes", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return breakfast(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return breakfast(f), nil }, }) @@ -127,8 +126,8 @@ func addFoodLookup() { Description: "Midday meal, often lighter than dinner, eaten around noon", Example: "No bake hersheys bar pie", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return lunch(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return lunch(f), nil }, }) @@ -138,8 +137,8 @@ func addFoodLookup() { Description: "Evening meal, typically the day's main and most substantial meal", Example: "Wild addicting dip", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return dinner(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return dinner(f), nil }, }) @@ -149,8 +148,8 @@ func addFoodLookup() { Description: "Liquid consumed for hydration, pleasure, or nutritional benefits", Example: "Soda", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return drink(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return drink(f), nil }, }) @@ -160,8 +159,8 @@ func addFoodLookup() { Description: "Random snack", Example: "Small, quick food item eaten between meals", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return snack(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return snack(f), nil }, }) @@ -171,8 +170,8 @@ func addFoodLookup() { Description: "Sweet treat often enjoyed after a meal", Example: "French napoleons", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return dessert(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return dessert(f), nil }, }) } diff --git a/food_test.go b/food_test.go index 5aa3e3f1..b9027158 100644 --- a/food_test.go +++ b/food_test.go @@ -9,302 +9,158 @@ func ExampleFruit() { Seed(11) fmt.Println(Fruit()) - // Output: Peach + // Output: Redcurrant } func ExampleFaker_Fruit() { f := New(11) fmt.Println(f.Fruit()) - // Output: Peach + // Output: Redcurrant } func BenchmarkFruit(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Fruit() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Fruit() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Fruit() - } - }) + for i := 0; i < b.N; i++ { + Fruit() + } } func ExampleVegetable() { Seed(11) fmt.Println(Vegetable()) - // Output: Amaranth Leaves + // Output: Sweet Potato } func ExampleFaker_Vegetable() { f := New(11) fmt.Println(f.Vegetable()) - // Output: Amaranth Leaves + // Output: Sweet Potato } func BenchmarkVegetable(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Vegetable() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Vegetable() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Vegetable() - } - }) + for i := 0; i < b.N; i++ { + Vegetable() + } } func ExampleBreakfast() { Seed(11) fmt.Println(Breakfast()) - // Output: Blueberry banana happy face pancakes + // Output: Purple cow } func ExampleFaker_Breakfast() { f := New(11) fmt.Println(f.Breakfast()) - // Output: Blueberry banana happy face pancakes + // Output: Purple cow } func BenchmarkBreakfast(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Breakfast() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Breakfast() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Breakfast() - } - }) + for i := 0; i < b.N; i++ { + Breakfast() + } } func ExampleLunch() { Seed(11) fmt.Println(Lunch()) - // Output: No bake hersheys bar pie + // Output: Quick chile relleno casserole } func ExampleFaker_Lunch() { f := New(11) fmt.Println(f.Lunch()) - // Output: No bake hersheys bar pie + // Output: Quick chile relleno casserole } func BenchmarkLunch(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Lunch() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Lunch() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Lunch() - } - }) + for i := 0; i < b.N; i++ { + Lunch() + } } func ExampleDinner() { Seed(11) fmt.Println(Dinner()) - // Output: Wild addicting dip + // Output: German apple cake with cream cheese frosting } func ExampleFaker_Dinner() { f := New(11) fmt.Println(f.Dinner()) - // Output: Wild addicting dip + // Output: German apple cake with cream cheese frosting } func BenchmarkDinner(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Dinner() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Dinner() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Dinner() - } - }) + for i := 0; i < b.N; i++ { + Dinner() + } } func ExampleDrink() { Seed(11) fmt.Println(Drink()) - // Output: Juice + // Output: Wine } func ExampleFaker_Drink() { f := New(11) fmt.Println(f.Drink()) - // Output: Juice + // Output: Wine } func BenchmarkDrink(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Drink() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Drink() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Drink() - } - }) + for i := 0; i < b.N; i++ { + Drink() + } } func ExampleSnack() { Seed(11) fmt.Println(Snack()) - // Output: Hoisin marinated wing pieces + // Output: Fantastic banana bran muffins } func ExampleFaker_Snack() { f := New(11) fmt.Println(f.Snack()) - // Output: Hoisin marinated wing pieces + // Output: Fantastic banana bran muffins } func BenchmarkSnack(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Snack() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Snack() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Snack() - } - }) + for i := 0; i < b.N; i++ { + Snack() + } } func ExampleDessert() { Seed(11) fmt.Println(Dessert()) - // Output: French napoleons + // Output: Amish cream pie } func ExampleFaker_Dessert() { f := New(11) fmt.Println(f.Dessert()) - // Output: French napoleons + // Output: Amish cream pie } func BenchmarkDessert(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Dessert() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Dessert() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Dessert() - } - }) + for i := 0; i < b.N; i++ { + Dessert() + } } diff --git a/game.go b/game.go index 5c1bc369..0e137000 100644 --- a/game.go +++ b/game.go @@ -2,33 +2,32 @@ package gofakeit import ( "fmt" - "math/rand" "strings" ) // Gamertag will generate a random video game username -func Gamertag() string { return gamertag(globalFaker.Rand) } +func Gamertag() string { return gamertag(GlobalFaker) } // Gamertag will generate a random video game username -func (f *Faker) Gamertag() string { return gamertag(f.Rand) } +func (f *Faker) Gamertag() string { return gamertag(f) } -func gamertag(r *rand.Rand) string { +func gamertag(f *Faker) string { str := "" - num := number(r, 1, 4) + num := number(f, 1, 4) switch num { case 1: - str = fmt.Sprintf("%s%ser", title(nounConcrete(r)), title(verbAction(r))) + str = fmt.Sprintf("%s%ser", title(nounConcrete(f)), title(verbAction(f))) case 2: - str = fmt.Sprintf("%s%s", title(adjectiveDescriptive(r)), title(animal(r))) + str = fmt.Sprintf("%s%s", title(adjectiveDescriptive(f)), title(animal(f))) case 3: - str = fmt.Sprintf("%s%s", title(adjectiveDescriptive(r)), title(nounConcrete(r))) + str = fmt.Sprintf("%s%s", title(adjectiveDescriptive(f)), title(nounConcrete(f))) case 4: - str = fmt.Sprintf("%s%s", title(fruit(r)), title(adjectiveDescriptive(r))) + str = fmt.Sprintf("%s%s", title(fruit(f)), title(adjectiveDescriptive(f))) } // Randomly determine if we should add a number - if r.Intn(3) == 1 { - str += digitN(r, uint(number(r, 1, 3))) + if f.IntN(3) == 1 { + str += digitN(f, uint(number(f, 1, 3))) } // Remove any spaces @@ -38,12 +37,12 @@ func gamertag(r *rand.Rand) string { } // Dice will generate a random set of dice -func Dice(numDice uint, sides []uint) []uint { return dice(globalFaker.Rand, numDice, sides) } +func Dice(numDice uint, sides []uint) []uint { return dice(GlobalFaker, numDice, sides) } // Dice will generate a random set of dice -func (f *Faker) Dice(numDice uint, sides []uint) []uint { return dice(f.Rand, numDice, sides) } +func (f *Faker) Dice(numDice uint, sides []uint) []uint { return dice(f, numDice, sides) } -func dice(r *rand.Rand, numDice uint, sides []uint) []uint { +func dice(f *Faker, numDice uint, sides []uint) []uint { dice := make([]uint, numDice) // If we dont have any sides well set the sides to 6 @@ -54,9 +53,9 @@ func dice(r *rand.Rand, numDice uint, sides []uint) []uint { for i := range dice { // If sides[i] doesnt exist use the first side if len(sides)-1 < i { - dice[i] = uint(number(r, 1, int(sides[0]))) + dice[i] = uint(number(f, 1, int(sides[0]))) } else { - dice[i] = uint(number(r, 1, int(sides[i]))) + dice[i] = uint(number(f, 1, int(sides[i]))) } } @@ -70,8 +69,8 @@ func addGameLookup() { Description: "User-selected online username or alias used for identification in games", Example: "footinterpret63", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return gamertag(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return gamertag(f), nil }, }) @@ -85,7 +84,7 @@ func addGameLookup() { {Field: "numdice", Display: "Number of Dice", Type: "uint", Default: "1", Description: "Number of dice to roll"}, {Field: "sides", Display: "Number of Sides", Type: "[]uint", Default: "[6]", Description: "Number of sides on each dice"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { numDice, err := info.GetUint(m, "numdice") if err != nil { return nil, err @@ -96,7 +95,7 @@ func addGameLookup() { return nil, err } - return dice(r, numDice, sides), nil + return dice(f, numDice, sides), nil }, }) } diff --git a/game_test.go b/game_test.go index 6f09c66f..15c8e4a0 100644 --- a/game_test.go +++ b/game_test.go @@ -9,14 +9,14 @@ func ExampleGamertag() { Seed(11) fmt.Println(Gamertag()) - // Output: PurpleSheep5 + // Output: TurkeyThinker } func ExampleFaker_Gamertag() { f := New(11) fmt.Println(f.Gamertag()) - // Output: PurpleSheep5 + // Output: TurkeyThinker } func TestGamertag(t *testing.T) { @@ -29,27 +29,9 @@ func TestGamertag(t *testing.T) { } func BenchmarkGamertag(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Gamertag() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Gamertag() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Gamertag() - } - }) + for i := 0; i < b.N; i++ { + Gamertag() + } } func ExampleDice() { @@ -118,25 +100,7 @@ func TestDiceOneSide(t *testing.T) { } func BenchmarkDice(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Dice(1, []uint{6}) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Dice(1, []uint{6}) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Dice(1, []uint{6}) - } - }) + for i := 0; i < b.N; i++ { + Dice(1, []uint{6}) + } } diff --git a/generate.go b/generate.go index 342a3a59..d61366c2 100644 --- a/generate.go +++ b/generate.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "math" - "math/rand" "regexp/syntax" "strings" ) @@ -24,7 +23,7 @@ import ( // Ex: ??? - fda - random letters // // For a complete list of runnable functions use FuncsLookup -func Generate(dataVal string) string { return generate(globalFaker.Rand, dataVal) } +func Generate(dataVal string) string { return generate(GlobalFaker, dataVal) } // Generate fake information from given string. // Replaceable values should be within {} @@ -40,12 +39,12 @@ func Generate(dataVal string) string { return generate(globalFaker.Rand, dataVal // Ex: ??? - fda - random letters // // For a complete list of runnable functions use FuncsLookup -func (f *Faker) Generate(dataVal string) string { return generate(f.Rand, dataVal) } +func (f *Faker) Generate(dataVal string) string { return generate(f, dataVal) } -func generate(r *rand.Rand, dataVal string) string { +func generate(f *Faker, dataVal string) string { // Replace # with numbers and ? with letters - dataVal = replaceWithNumbers(r, dataVal) - dataVal = replaceWithLetters(r, dataVal) + dataVal = replaceWithNumbers(f, dataVal) + dataVal = replaceWithLetters(f, dataVal) // Check if string has any replaceable values if !strings.Contains(dataVal, "{") && !strings.Contains(dataVal, "}") { @@ -120,7 +119,7 @@ func generate(r *rand.Rand, dataVal string) string { } // Call function - fValue, err := info.Generate(r, mapParams, info) + fValue, err := info.Generate(f, mapParams, info) if err != nil { // If we came across an error just dont replace value dataVal = strings.Replace(dataVal, "{"+fParts+"}", err.Error(), 1) @@ -160,14 +159,14 @@ type FixedWidthOptions struct { // FixedWidth generates an table of random data in fixed width format // A nil FixedWidthOptions returns a randomly structured FixedWidth. -func FixedWidth(co *FixedWidthOptions) (string, error) { return fixeWidthFunc(globalFaker.Rand, co) } +func FixedWidth(co *FixedWidthOptions) (string, error) { return fixeWidthFunc(GlobalFaker, co) } // FixedWidth generates an table of random data in fixed width format // A nil FixedWidthOptions returns a randomly structured FixedWidth. -func (f *Faker) FixedWidth(co *FixedWidthOptions) (string, error) { return fixeWidthFunc(f.Rand, co) } +func (f *Faker) FixedWidth(co *FixedWidthOptions) (string, error) { return fixeWidthFunc(f, co) } // Function to generate a fixed width document -func fixeWidthFunc(r *rand.Rand, co *FixedWidthOptions) (string, error) { +func fixeWidthFunc(f *Faker, co *FixedWidthOptions) (string, error) { // If we didn't get FixedWidthOptions, create a new random one if co == nil { co = &FixedWidthOptions{} @@ -175,7 +174,7 @@ func fixeWidthFunc(r *rand.Rand, co *FixedWidthOptions) (string, error) { // Make sure you set a row count if co.RowCount <= 0 { - co.RowCount = r.Intn(10) + 1 + co.RowCount = f.IntN(10) + 1 } // Check fields @@ -208,13 +207,13 @@ func fixeWidthFunc(r *rand.Rand, co *FixedWidthOptions) (string, error) { if funcInfo == nil { // Try to run the function through generate for i := 0; i < co.RowCount; i++ { - row = append(row, generate(r, field.Function)) + row = append(row, generate(f, field.Function)) } } else { // Generate function value var err error for i := 0; i < co.RowCount; i++ { - value, err = funcInfo.Generate(r, &field.Params, funcInfo) + value, err = funcInfo.Generate(f, &field.Params, funcInfo) if err != nil { value = "" } @@ -265,12 +264,12 @@ func fixeWidthFunc(r *rand.Rand, co *FixedWidthOptions) (string, error) { } // Regex will generate a string based upon a RE2 syntax -func Regex(regexStr string) string { return regex(globalFaker.Rand, regexStr) } +func Regex(regexStr string) string { return regex(GlobalFaker, regexStr) } // Regex will generate a string based upon a RE2 syntax -func (f *Faker) Regex(regexStr string) string { return regex(f.Rand, regexStr) } +func (f *Faker) Regex(regexStr string) string { return regex(f, regexStr) } -func regex(r *rand.Rand, regexStr string) (gen string) { +func regex(f *Faker, regexStr string) (gen string) { re, err := syntax.Parse(regexStr, syntax.Perl) if err != nil { return "Could not parse regex string" @@ -279,16 +278,16 @@ func regex(r *rand.Rand, regexStr string) (gen string) { // Panic catch defer func() { if r := recover(); r != nil { - gen = fmt.Sprint(r) + gen = fmt.Sprint(f) return } }() - return regexGenerate(r, re, len(regexStr)*100) + return regexGenerate(f, re, len(regexStr)*100) } -func regexGenerate(ra *rand.Rand, re *syntax.Regexp, limit int) string { +func regexGenerate(f *Faker, re *syntax.Regexp, limit int) string { if limit <= 0 { panic("Length limit reached when generating output") } @@ -331,11 +330,11 @@ func regexGenerate(ra *rand.Rand, re *syntax.Regexp, limit int) string { } } if len(chars) > 0 { - return string([]byte{chars[ra.Intn(len(chars))]}) + return string([]byte{chars[f.IntN(len(chars))]}) } } - r := ra.Intn(int(sum)) + r := f.IntN(int(sum)) var ru rune sum = 0 for i := 0; i < len(re.Rune); i += 2 { @@ -349,7 +348,7 @@ func regexGenerate(ra *rand.Rand, re *syntax.Regexp, limit int) string { return string(ru) case syntax.OpAnyCharNotNL, syntax.OpAnyChar: // matches any character(and except newline) - return randCharacter(ra, allStr) + return randCharacter(f, allStr) case syntax.OpBeginLine: // matches empty string at beginning of line case syntax.OpEndLine: // matches empty string at end of line case syntax.OpBeginText: // matches empty string at beginning of text @@ -357,28 +356,28 @@ func regexGenerate(ra *rand.Rand, re *syntax.Regexp, limit int) string { case syntax.OpWordBoundary: // matches word boundary `\b` case syntax.OpNoWordBoundary: // matches word non-boundary `\B` case syntax.OpCapture: // capturing subexpression with index Cap, optional name Name - return regexGenerate(ra, re.Sub0[0], limit) + return regexGenerate(f, re.Sub0[0], limit) case syntax.OpStar: // matches Sub[0] zero or more times var b strings.Builder - for i := 0; i < number(ra, 0, 10); i++ { + for i := 0; i < number(f, 0, 10); i++ { for _, rs := range re.Sub { - b.WriteString(regexGenerate(ra, rs, limit-b.Len())) + b.WriteString(regexGenerate(f, rs, limit-b.Len())) } } return b.String() case syntax.OpPlus: // matches Sub[0] one or more times var b strings.Builder - for i := 0; i < number(ra, 1, 10); i++ { + for i := 0; i < number(f, 1, 10); i++ { for _, rs := range re.Sub { - b.WriteString(regexGenerate(ra, rs, limit-b.Len())) + b.WriteString(regexGenerate(f, rs, limit-b.Len())) } } return b.String() case syntax.OpQuest: // matches Sub[0] zero or one times var b strings.Builder - for i := 0; i < number(ra, 0, 1); i++ { + for i := 0; i < number(f, 0, 1); i++ { for _, rs := range re.Sub { - b.WriteString(regexGenerate(ra, rs, limit-b.Len())) + b.WriteString(regexGenerate(f, rs, limit-b.Len())) } } return b.String() @@ -387,84 +386,84 @@ func regexGenerate(ra *rand.Rand, re *syntax.Regexp, limit int) string { count := 0 re.Max = int(math.Min(float64(re.Max), float64(10))) if re.Max > re.Min { - count = ra.Intn(re.Max - re.Min + 1) + count = f.IntN(re.Max - re.Min + 1) } for i := 0; i < re.Min || i < (re.Min+count); i++ { for _, rs := range re.Sub { - b.WriteString(regexGenerate(ra, rs, limit-b.Len())) + b.WriteString(regexGenerate(f, rs, limit-b.Len())) } } return b.String() case syntax.OpConcat: // matches concatenation of Subs var b strings.Builder for _, rs := range re.Sub { - b.WriteString(regexGenerate(ra, rs, limit-b.Len())) + b.WriteString(regexGenerate(f, rs, limit-b.Len())) } return b.String() case syntax.OpAlternate: // matches alternation of Subs - return regexGenerate(ra, re.Sub[number(ra, 0, len(re.Sub)-1)], limit) + return regexGenerate(f, re.Sub[number(f, 0, len(re.Sub)-1)], limit) } return "" } // Map will generate a random set of map data -func Map() map[string]any { return mapFunc(globalFaker.Rand) } +func Map() map[string]any { return mapFunc(GlobalFaker) } // Map will generate a random set of map data -func (f *Faker) Map() map[string]any { return mapFunc(f.Rand) } +func (f *Faker) Map() map[string]any { return mapFunc(f) } -func mapFunc(r *rand.Rand) map[string]any { +func mapFunc(f *Faker) map[string]any { m := map[string]any{} randWordType := func() string { - s := randomString(r, []string{"lorem", "bs", "job", "name", "address"}) + s := randomString(f, []string{"lorem", "bs", "job", "name", "address"}) switch s { case "bs": - return bs(r) + return bs(f) case "job": - return jobTitle(r) + return jobTitle(f) case "name": - return name(r) + return name(f) case "address": - return street(r) + ", " + city(r) + ", " + state(r) + " " + zip(r) + return street(f) + ", " + city(f) + ", " + state(f) + " " + zip(f) } - return word(r) + return word(f) } randSlice := func() []string { var sl []string - for ii := 0; ii < number(r, 3, 10); ii++ { - sl = append(sl, word(r)) + for ii := 0; ii < number(f, 3, 10); ii++ { + sl = append(sl, word(f)) } return sl } - for i := 0; i < number(r, 3, 10); i++ { - t := randomString(r, []string{"string", "int", "float", "slice", "map"}) + for i := 0; i < number(f, 3, 10); i++ { + t := randomString(f, []string{"string", "int", "float", "slice", "map"}) switch t { case "string": - m[word(r)] = randWordType() + m[word(f)] = randWordType() case "int": - m[word(r)] = number(r, 1, 10000000) + m[word(f)] = number(f, 1, 10000000) case "float": - m[word(r)] = float32Range(r, 1, 1000000) + m[word(f)] = float32Range(f, 1, 1000000) case "slice": - m[word(r)] = randSlice() + m[word(f)] = randSlice() case "map": mm := map[string]any{} - tt := randomString(r, []string{"string", "int", "float", "slice"}) + tt := randomString(f, []string{"string", "int", "float", "slice"}) switch tt { case "string": - mm[word(r)] = randWordType() + mm[word(f)] = randWordType() case "int": - mm[word(r)] = number(r, 1, 10000000) + mm[word(f)] = number(f, 1, 10000000) case "float": - mm[word(r)] = float32Range(r, 1, 1000000) + mm[word(f)] = float32Range(f, 1, 1000000) case "slice": - mm[word(r)] = randSlice() + mm[word(f)] = randSlice() } - m[word(r)] = mm + m[word(f)] = mm } } @@ -481,7 +480,7 @@ func addGenerateLookup() { Params: []Param{ {Field: "str", Display: "String", Type: "string", Description: "String value to generate from"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { str, err := info.GetString(m, "str") if err != nil { return nil, err @@ -492,7 +491,7 @@ func addGenerateLookup() { return nil, errors.New("string length is too large. limit to 1000 characters") } - return generate(r, str), nil + return generate(f, str), nil }, }) @@ -510,7 +509,7 @@ Lura Lockman zacherykuhic@feil.name S8gV7Z64KlHG 12`, {Field: "rowcount", Display: "Row Count", Type: "int", Default: "10", Description: "Number of rows"}, {Field: "fields", Display: "Fields", Type: "[]Field", Description: "Fields name, function and params"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { co := FixedWidthOptions{} rowCount, err := info.GetInt(m, "rowcount") @@ -536,7 +535,7 @@ Lura Lockman zacherykuhic@feil.name S8gV7Z64KlHG 12`, return nil, errors.New("missing fields") } - out, err := fixeWidthFunc(r, &co) + out, err := fixeWidthFunc(f, &co) if err != nil { return nil, err } @@ -554,7 +553,7 @@ Lura Lockman zacherykuhic@feil.name S8gV7Z64KlHG 12`, Params: []Param{ {Field: "str", Display: "String", Type: "string", Description: "Regex RE2 syntax string"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { str, err := info.GetString(m, "str") if err != nil { return nil, err @@ -565,7 +564,7 @@ Lura Lockman zacherykuhic@feil.name S8gV7Z64KlHG 12`, return nil, errors.New("string length is too large. limit to 500 characters") } - return regex(r, str), nil + return regex(f, str), nil }, }) @@ -582,8 +581,8 @@ Lura Lockman zacherykuhic@feil.name S8gV7Z64KlHG 12`, }`, Output: "map[string]any", ContentType: "application/json", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return mapFunc(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return mapFunc(f), nil }, }) } diff --git a/generate_fuzz_test.go b/generate_fuzz_test.go deleted file mode 100644 index 4deeb6db..00000000 --- a/generate_fuzz_test.go +++ /dev/null @@ -1,112 +0,0 @@ -//go:build go1.18 -// +build go1.18 - -package gofakeit - -import ( - "encoding/binary" - "math/rand" - "regexp" - "strings" - "testing" -) - -func FuzzRegex(f *testing.F) { - for i, regex := range regexes { - buffer := make([]byte, 8) - binary.BigEndian.PutUint64(buffer, uint64(i*i*1234567)) - // Reuse TestRegex cases to seed corpus. - f.Add(buffer, regex.test) - - // Cases found and skipped by fuzz test. - f.Add([]byte("0"), string("$0")) // can not match any string - f.Add([]byte("0"), string("0^00")) // can not match any string - f.Add([]byte("0"), string("000\\A")) // `\A` gives unexpected results - f.Add([]byte("0"), string("\\b")) // `\b` gives unexpected results - - // Fixed by modifying regexGenerate. - f.Add([]byte("("), string("((5555555555555555){700})")) // OOM after fuzz run for a while. fixed by adding limit to regexGenerate - - // Fixed in notSoRandom. - f.Add([]byte("\xff\xff\xff\xff\xff\xff\xff\xf1"), string("123[0-2]w{3}")) // choose 1 in 3 loops forever if notSoRandom loops it self instead of using a random tail - } - f.Fuzz(func(t *testing.T, rand []byte, regex string) { - if len(regex) > 20 { - return // long regexes take longer to test without adding much, increase this limit will make it easer to find OOM and timeouts. - } - - // case added after each character gives bad result to get other cases - if strings.ContainsAny(regex, `^$\`) { - return - } - - regex = "^" + regex + "$" // make sure we do a full capture - - // Try to compile regexTest - regCompile, err := regexp.Compile(regex) - if err != nil { - return // Ignore bad regex - } - - // Let fuzz have control over random behavior - fuzzRand := ¬SoRandom{} - fuzzRand.useBytes(rand) - faker := NewCustom(fuzzRand) - - // Generate string and test if it matches the regex syntax - reg := faker.Regex(regex) - if reg == "Length limit reached when generating output" { - // ignore LimitReached error - return - } - if !regCompile.MatchString(reg) { - t.Error("Generated data does not match regex. Regex: ", regex, " output: ", reg) - } - }) -} - -// notSoRandom is a random source that start with a stream of predetermined data. -// This allows fuzz to slowly change sudo random behavior. -type notSoRandom struct { - data []uint64 - offset int - - // Make long tail behavior more random once we run out of data. - // This avoids dead loop in code that expects a statically random source. - tail rand.Source64 -} - -func (r *notSoRandom) Int63() int64 { - if r.tail != nil { - return r.tail.Int63() - } - return int64(r.Uint64() & ^uint64(1<<63)) -} - -func (r *notSoRandom) Uint64() uint64 { - if r.tail != nil { - return r.tail.Uint64() - } - out := r.data[r.offset] - r.offset = (r.offset + 1) % len(r.data) - if r.offset == 0 { - r.tail = rand.NewSource(int64(out)).(rand.Source64) - } - return out -} - -func (r *notSoRandom) Seed(seed int64) { - panic("unimplemented") -} - -func (r *notSoRandom) useBytes(seed []byte) { - if len(seed) == 0 || len(seed)%8 != 0 { - r.useBytes(append(seed, 0)) - return - } - var data []uint64 - for i := 0; i+7 < len(seed); i += 8 { - data = append(data, binary.BigEndian.Uint64(seed[i:])) - } - r.data = data -} diff --git a/generate_test.go b/generate_test.go index af3a95eb..ec1a1cab 100644 --- a/generate_test.go +++ b/generate_test.go @@ -24,8 +24,8 @@ func TestGenerate_Sub(t *testing.T) { Seed(11) output := Generate("{randomstring:[{firstname},{lastname}]}") - if output != "Moen" { - t.Error("Did not generate what was expected. Got: ", output) + if output == "" { + t.Error("Output was empty") } }) @@ -33,8 +33,8 @@ func TestGenerate_Sub(t *testing.T) { Seed(11) output := Generate("{randomstring:[{randomstring:[{firstname},{lastname}]},{randomstring:[{firstname},{lastname}]}]}") - if output != "Kozey" { - t.Error("Did not generate what was expected. Got: ", output) + if output == "" { + t.Error("Output was empty") } }) } @@ -50,13 +50,13 @@ func ExampleGenerate() { fmt.Println(Generate("{number:1,50}")) fmt.Println(Generate("{shufflestrings:[key:value,int:string,1:2,a:b]}")) - // Output: Markus Moen ssn is 526643139 and lives at 599 Daleton - // Congolese choir computer. - // [3 1 2] + // Output: Sonny Stiedemann ssn is 279582238 and lives at 2759 Stationside + // How shall cut. + // [1 2 3] // 2 - // 4 - // 17 - // [int:string 1:2 a:b key:value] + // 3 + // 47 + // [1:2 int:string a:b key:value] } func ExampleFaker_Generate() { @@ -70,13 +70,13 @@ func ExampleFaker_Generate() { fmt.Println(f.Generate("{number:1,50}")) fmt.Println(f.Generate("{shufflestrings:[key:value,int:string,1:2,a:b]}")) - // Output: Markus Moen ssn is 526643139 and lives at 599 Daleton - // Congolese choir computer. - // [3 1 2] + // Output: Sonny Stiedemann ssn is 279582238 and lives at 2759 Stationside + // How shall cut. + // [1 2 3] // 2 - // 4 - // 17 - // [int:string 1:2 a:b key:value] + // 3 + // 47 + // [1:2 int:string a:b key:value] } func BenchmarkGenerate(b *testing.B) { @@ -91,22 +91,6 @@ func BenchmarkGenerate(b *testing.B) { Generate("{randomstring:[{randomstring:[{firstname},{lastname}]},{randomstring:[{firstname},{lastname}]}]}") } }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Generate("{firstname} {lastname} {email} #?#?#?") - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Generate("{firstname} {lastname} {email} #?#?#?") - } - }) } func ExampleFixedWidth() { @@ -127,11 +111,10 @@ func ExampleFixedWidth() { fmt.Println(string(value)) - // Output: - // Name Email Password Age - // Markus Moen sylvanmraz@murphy.net 46HX9elvE5zl 43 - // Alayna Wuckert santinostanton@carroll.biz l6A0EVSC90w2 11 - // Lura Lockman zacherykuhic@feil.name xxL47424u8Ts 4 + // Output: Name Email Password Age + // Sonny Stiedemann mollielegros@wilderman.org 3T8l34B5F0eb 62 + // Cody Donnelly stevebins@robel.io 3fnu2C12baqe 9 + // Julius Farrell tomasaullrich@hane.name e8W8SJGZi1Y4 77 } func ExampleFixedWidth_default() { @@ -144,9 +127,16 @@ func ExampleFixedWidth_default() { fmt.Println(string(value)) - // Output: - // Name Email Password - // Marcel Pagac anibalkozey@lockman.name ETZmouyV0q1W + // Output: Name Email Password + // Russ Donnelly missourigrimes@rohan.io N3xh07881HKv + // Cole Leannon evanadams@marquardt.com n2fja08VHMgw + // Darien Rempel thorajerde@cormier.com ZhMPq5v8z6iP + // Kaitlyn Wilderman constancenienow@smitham.io MkoTT5v5Mv6Q + // Rahul Turner irvingbins@lemke.io 8Wy0UV016u88 + // April Robel beaulahmayert@kautzer.net ykgR5bO83YSa + // Tomasa Waters lelandwaelchi@beahan.net k68Ew58F9a0V + // Sunny Hane dawnbaumbach@mcdermott.biz AbUjm6x5dwd8 + // Hilma Jast lavernerobel@bailey.io MyY49BLUWKCh } func ExampleFixedWidth_noHeader() { @@ -167,10 +157,9 @@ func ExampleFixedWidth_noHeader() { fmt.Println(value) - // Output: - // Markus Moen sylvanmraz@murphy.net 46HX9elvE5zl 43 - // Alayna Wuckert santinostanton@carroll.biz l6A0EVSC90w2 11 - // Lura Lockman zacherykuhic@feil.name xxL47424u8Ts 4 + // Output: Sonny Stiedemann mollielegros@wilderman.org 3T8l34B5F0eb 62 + // Cody Donnelly stevebins@robel.io 3fnu2C12baqe 9 + // Julius Farrell tomasaullrich@hane.name e8W8SJGZi1Y4 77 } func ExampleFaker_FixedWidth() { @@ -191,11 +180,10 @@ func ExampleFaker_FixedWidth() { fmt.Println(string(value)) - // Output: - // Name Email Password Age - // Markus Moen sylvanmraz@murphy.net 46HX9elvE5zl 43 - // Alayna Wuckert santinostanton@carroll.biz l6A0EVSC90w2 11 - // Lura Lockman zacherykuhic@feil.name xxL47424u8Ts 4 + // Output: Name Email Password Age + // Sonny Stiedemann mollielegros@wilderman.org 3T8l34B5F0eb 62 + // Cody Donnelly stevebins@robel.io 3fnu2C12baqe 9 + // Julius Farrell tomasaullrich@hane.name e8W8SJGZi1Y4 77 } func TestFixedWidthLookup(t *testing.T) { @@ -213,7 +201,7 @@ func TestFixedWidthLookup(t *testing.T) { }, } - output, err := info.Generate(faker.Rand, &m, info) + output, err := info.Generate(faker, &m, info) if err != nil { t.Fatal(err.Error()) } @@ -246,56 +234,16 @@ func BenchmarkFixedWidthLookup100(b *testing.B) { m := MapParams{ "rowcount": {"100"}, "fields": { - `{"name":"Name","function":"{firstname} {lastname}"}"}`, - `{"name":"Email","function":"email"}`, - `{"name":"Password","function":"password","params":{"special":["false"],"length":["20"]}}`, - `{"name":"Age","function":"{number:1,100}"}`, - }, - } - _, err := info.Generate(faker.Rand, &m, info) - if err != nil { - b.Fatal(err.Error()) - } - } -} - -func BenchmarkFixedWidthLookup1000(b *testing.B) { - faker := New(0) - - for i := 0; i < b.N; i++ { - info := GetFuncLookup("fixed_width") - m := MapParams{ - "rowcount": {"1000"}, - "fields": { - `{"name":"Name","function":"{firstname} {lastname}"}"}`, + // `{"name":"Name","function":"{firstname} {lastname}"}`, `{"name":"Email","function":"email"}`, `{"name":"Password","function":"password","params":{"special":["false"],"length":["20"]}}`, `{"name":"Age","function":"{number:1,100}"}`, }, } - _, err := info.Generate(faker.Rand, &m, info) + _, err := info.Generate(faker, &m, info) if err != nil { - b.Fatal(err.Error()) - } - } -} - -func BenchmarkFixedWidthLookup10000(b *testing.B) { - faker := New(0) + // Stack trace - for i := 0; i < b.N; i++ { - info := GetFuncLookup("fixed_width") - m := MapParams{ - "rowcount": {"10000"}, - "fields": { - `{"name":"Name","function":"{firstname} {lastname}"}"}`, - `{"name":"Email","function":"email"}`, - `{"name":"Password","function":"password","params":{"special":["false"],"length":["20"]}}`, - `{"name":"Age","function":"{number:1,100}"}`, - }, - } - _, err := info.Generate(faker.Rand, &m, info) - if err != nil { b.Fatal(err.Error()) } } @@ -309,10 +257,10 @@ func ExampleRegex() { fmt.Println(Regex("(hello|world|whats|up)")) fmt.Println(Regex(`^[a-z]{5,10}@[a-z]{5,10}\.(com|net|org)$`)) - // Output: affec - // RXHKI - // world - // tapwyjdnsm@gtlxw.net + // Output: ffbbd + // GSNYV + // up + // tyyxi@kshtyia.net } func ExampleFaker_Regex() { @@ -323,10 +271,10 @@ func ExampleFaker_Regex() { fmt.Println(f.Regex("(hello|world|whats|up)")) fmt.Println(f.Regex(`^[a-z]{5,10}@[a-z]{5,10}\.(com|net|org)$`)) - // Output: affec - // RXHKI - // world - // tapwyjdnsm@gtlxw.net + // Output: ffbbd + // GSNYV + // up + // tyyxi@kshtyia.net } var regexes = []struct{ test string }{ @@ -387,107 +335,72 @@ func TestRegex_Struct(t *testing.T) { rg := Reggy{} Struct(&rg) - if rg.Str1 != "16" { - t.Errorf("Str1 should be 16 got: %s", rg.Str1) + // Test Str1 matches regex + if !regexp.MustCompile(`^\d+$`).MatchString(rg.Str1) { + t.Errorf("Str1 should match regex: ^\\d+$ got: %s", rg.Str1) } - if rg.Str2 != "fP}" { - t.Errorf("Str2 should be fP} got: %s", rg.Str2) + if !regexp.MustCompile(`\D{3}`).MatchString(rg.Str2) { + t.Errorf("Str2 should match regex: \\D{3} got: %s", rg.Str2) } - if rg.Str3 != "ZZ" { - t.Errorf("Str3 should be ZZ got: %s", rg.Str3) + if !regexp.MustCompile(`Z{2,5}`).MatchString(rg.Str3) { + t.Errorf("Str3 should match regex: Z{2,5} got: %s", rg.Str3) } - if rg.Str4 != "% z" { - t.Errorf("Str4 should be %s got: %s", "% z", rg.Str4) + if !regexp.MustCompile(`[^1]{3,5}`).MatchString(rg.Str4) { + t.Errorf("Str4 should match regex: [^1]{3,5} got: %s", rg.Str4) } - if rg.Str5 != "abdef" { - t.Errorf("Str5 should be abdef got: %s", rg.Str5) + if !regexp.MustCompile(`(ab|bc)def`).MatchString(rg.Str5) { + t.Errorf("Str5 should match regex: (ab|bc)def got: %s", rg.Str5) } - if rg.Str6 != "123a123a123a" { - t.Errorf("Str6 should be 123a123a123a got: %s", rg.Str6) + if !regexp.MustCompile(`((123)?){3}`).MatchString(rg.Str6) { + t.Errorf("Str6 should match regex: ((123)?){3} got: %s", rg.Str6) } - if rg.Str7 != ">=;-l" { - t.Errorf("Str7 should be >=;-l got: %s", rg.Str7) + if !regexp.MustCompile(`[^abcdef]{5}`).MatchString(rg.Str7) { + t.Errorf("Str7 should match regex: [^abcdef]{5} got: %s", rg.Str7) } - if rg.Str8 != "nSMKgtlxwn" { - t.Errorf("Str8 should be nSMKgtlxwn got: %s", rg.Str8) + if !regexp.MustCompile(`[a-zA-Z]{10}`).MatchString(rg.Str8) { + t.Errorf("Str8 should match regex: [a-zA-Z]{10} got: %s", rg.Str8) } - if rg.Str9 != "QHQCL" { - t.Errorf("Str9 should be QHQCL got: %s", rg.Str9) + if !regexp.MustCompile(`[[:upper:]]{5}`).MatchString(rg.Str9) { + t.Errorf("Str9 should match regex: [[:upper:]]{5} got: %s", rg.Str9) } - if rg.Str10 != "(T}6X" { - t.Errorf("Str10 should be (T}6X got: %s", rg.Str10) + if !regexp.MustCompile(`[^0-5a-z\s]{5}`).MatchString(rg.Str10) { + t.Errorf("Str10 should match regex: [^0-5a-z\\s]{5} got: %s", rg.Str10) } - if rg.Str11 != "123120aeD" { - t.Errorf("Str11 should be 123120aeD got: %s", rg.Str11) + if !regexp.MustCompile(`123[0-2]+.*\w{3}`).MatchString(rg.Str11) { + t.Errorf("Str11 should match regex: 123[0-2]+.*\\w{3} got: %s", rg.Str11) } - if rg.Str12 != "hello" { - t.Errorf("Str12 should be hello got: %s", rg.Str12) + if !regexp.MustCompile(`(hello|world|whats|up)`).MatchString(rg.Str12) { + t.Errorf("Str12 should match regex: (hello|world|whats|up) got: %s", rg.Str12) } - if rg.Str13 != "8/10/2022" { - t.Errorf("Str13 should be 8/10/2022 got: %s", rg.Str13) + if !regexp.MustCompile(`^\d{1,2}[/](1[0-2]|[1-9])[/]((19|20)\d{2})$`).MatchString(rg.Str13) { + t.Errorf("Str13 should match regex: ^\\d{1,2}[/](1[0-2]|[1-9])[/]((19|20)\\d{2})$ got: %s", rg.Str13) } } func BenchmarkRegex(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Regex(`(hello|world|whats|up`) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Regex(`(hello|world|whats|up`) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Regex(`(hello|world|whats|up`) - } - }) + for i := 0; i < b.N; i++ { + Regex(`(hello|world|whats|up`) + } } func BenchmarkRegexEmail(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Regex("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Regex("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Regex("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") - } - }) + for i := 0; i < b.N; i++ { + Regex("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") + } } func ExampleMap() { Seed(11) fmt.Println(Map()) - // Output: map[here:Manager herself:map[trip:[far computer was unless whom riches]] how:8504801 ouch:Keith Ullrich outstanding:1860846 that:web services] + // Output: map[a:map[that:could] above:[sometimes vast whom us scarcely these huh] am:map[how:9310653] depend:map[hey:5402877] out:381794.78 since:916659.94 these:map[frequently:2314010]] } func ExampleFaker_Map() { f := New(11) fmt.Println(f.Map()) - // Output: map[here:Manager herself:map[trip:[far computer was unless whom riches]] how:8504801 ouch:Keith Ullrich outstanding:1860846 that:web services] + // Output: map[a:map[that:could] above:[sometimes vast whom us scarcely these huh] am:map[how:9310653] depend:map[hey:5402877] out:381794.78 since:916659.94 these:map[frequently:2314010]] } func TestMap(t *testing.T) { @@ -497,25 +410,7 @@ func TestMap(t *testing.T) { } func BenchmarkMap(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Map() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Map() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Map() - } - }) + for i := 0; i < b.N; i++ { + Map() + } } diff --git a/go.mod b/go.mod index 49d8fa95..8242e1df 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,3 @@ -module github.com/brianvoe/gofakeit/v6 +module github.com/brianvoe/gofakeit/v7 -go 1.21 +go 1.22 diff --git a/hacker.go b/hacker.go index 393c558e..dd1bdc26 100644 --- a/hacker.go +++ b/hacker.go @@ -1,70 +1,69 @@ package gofakeit import ( - "math/rand" "strings" ) // HackerPhrase will return a random hacker sentence -func HackerPhrase() string { return hackerPhrase(globalFaker.Rand) } +func HackerPhrase() string { return hackerPhrase(GlobalFaker) } // HackerPhrase will return a random hacker sentence -func (f *Faker) HackerPhrase() string { return hackerPhrase(f.Rand) } +func (f *Faker) HackerPhrase() string { return hackerPhrase(f) } -func hackerPhrase(r *rand.Rand) string { - words := strings.Split(generate(r, getRandValue(r, []string{"hacker", "phrase"})), " ") +func hackerPhrase(f *Faker) string { + words := strings.Split(generate(f, getRandValue(f, []string{"hacker", "phrase"})), " ") words[0] = strings.ToUpper(words[0][0:1]) + words[0][1:] return strings.Join(words, " ") } // HackerAbbreviation will return a random hacker abbreviation -func HackerAbbreviation() string { return hackerAbbreviation(globalFaker.Rand) } +func HackerAbbreviation() string { return hackerAbbreviation(GlobalFaker) } // HackerAbbreviation will return a random hacker abbreviation -func (f *Faker) HackerAbbreviation() string { return hackerAbbreviation(f.Rand) } +func (f *Faker) HackerAbbreviation() string { return hackerAbbreviation(f) } -func hackerAbbreviation(r *rand.Rand) string { - return getRandValue(r, []string{"hacker", "abbreviation"}) +func hackerAbbreviation(f *Faker) string { + return getRandValue(f, []string{"hacker", "abbreviation"}) } // HackerAdjective will return a random hacker adjective -func HackerAdjective() string { return hackerAdjective(globalFaker.Rand) } +func HackerAdjective() string { return hackerAdjective(GlobalFaker) } // HackerAdjective will return a random hacker adjective -func (f *Faker) HackerAdjective() string { return hackerAdjective(f.Rand) } +func (f *Faker) HackerAdjective() string { return hackerAdjective(f) } -func hackerAdjective(r *rand.Rand) string { - return getRandValue(r, []string{"hacker", "adjective"}) +func hackerAdjective(f *Faker) string { + return getRandValue(f, []string{"hacker", "adjective"}) } // HackerNoun will return a random hacker noun -func HackerNoun() string { return hackerNoun(globalFaker.Rand) } +func HackerNoun() string { return hackerNoun(GlobalFaker) } // HackerNoun will return a random hacker noun -func (f *Faker) HackerNoun() string { return hackerNoun(f.Rand) } +func (f *Faker) HackerNoun() string { return hackerNoun(f) } -func hackerNoun(r *rand.Rand) string { - return getRandValue(r, []string{"hacker", "noun"}) +func hackerNoun(f *Faker) string { + return getRandValue(f, []string{"hacker", "noun"}) } // HackerVerb will return a random hacker verb -func HackerVerb() string { return hackerVerb(globalFaker.Rand) } +func HackerVerb() string { return hackerVerb(GlobalFaker) } // HackerVerb will return a random hacker verb -func (f *Faker) HackerVerb() string { return hackerVerb(f.Rand) } +func (f *Faker) HackerVerb() string { return hackerVerb(f) } -func hackerVerb(r *rand.Rand) string { - return getRandValue(r, []string{"hacker", "verb"}) +func hackerVerb(f *Faker) string { + return getRandValue(f, []string{"hacker", "verb"}) } // HackeringVerb will return a random hacker ingverb -func HackeringVerb() string { return hackeringVerb(globalFaker.Rand) } +func HackeringVerb() string { return hackeringVerb(GlobalFaker) } // HackeringVerb will return a random hacker ingverb -func (f *Faker) HackeringVerb() string { return hackeringVerb(f.Rand) } +func (f *Faker) HackeringVerb() string { return hackeringVerb(f) } -func hackeringVerb(r *rand.Rand) string { - return getRandValue(r, []string{"hacker", "ingverb"}) +func hackeringVerb(f *Faker) string { + return getRandValue(f, []string{"hacker", "ingverb"}) } func addHackerLookup() { @@ -74,8 +73,8 @@ func addHackerLookup() { Description: "Informal jargon and slang used in the hacking and cybersecurity community", Example: "If we calculate the program, we can get to the AI pixel through the redundant XSS matrix!", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hackerPhrase(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return hackerPhrase(f), nil }, }) @@ -85,8 +84,8 @@ func addHackerLookup() { Description: "Abbreviations and acronyms commonly used in the hacking and cybersecurity community", Example: "ADP", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hackerAbbreviation(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return hackerAbbreviation(f), nil }, }) @@ -96,8 +95,8 @@ func addHackerLookup() { Description: "Adjectives describing terms often associated with hackers and cybersecurity experts", Example: "wireless", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hackerAdjective(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return hackerAdjective(f), nil }, }) @@ -107,8 +106,8 @@ func addHackerLookup() { Description: "Noun representing an element, tool, or concept within the realm of hacking and cybersecurity", Example: "driver", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hackerNoun(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return hackerNoun(f), nil }, }) @@ -118,8 +117,8 @@ func addHackerLookup() { Description: "Verbs associated with actions and activities in the field of hacking and cybersecurity", Example: "synthesize", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hackerVerb(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return hackerVerb(f), nil }, }) @@ -129,8 +128,8 @@ func addHackerLookup() { Description: "Verb describing actions and activities related to hacking, often involving computer systems and security", Example: "connecting", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hackeringVerb(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return hackeringVerb(f), nil }, }) } diff --git a/hacker_test.go b/hacker_test.go index 683228d6..30247ad4 100644 --- a/hacker_test.go +++ b/hacker_test.go @@ -9,226 +9,118 @@ func ExampleHackerPhrase() { Seed(11) fmt.Println(HackerPhrase()) - // Output: If we calculate the program, we can get to the AI pixel through the redundant XSS matrix! + // Output: Use the optical CSS microchip, then you can write the open-source monitor! } func ExampleFaker_HackerPhrase() { f := New(11) fmt.Println(f.HackerPhrase()) - // Output: If we calculate the program, we can get to the AI pixel through the redundant XSS matrix! + // Output: Use the optical CSS microchip, then you can write the open-source monitor! } func BenchmarkHackerPhrase(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HackerPhrase() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HackerPhrase() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HackerPhrase() - } - }) + for i := 0; i < b.N; i++ { + HackerPhrase() + } } func ExampleHackerAbbreviation() { Seed(11) fmt.Println(HackerAbbreviation()) - // Output: ADP + // Output: SCSI } func ExampleFaker_HackerAbbreviation() { f := New(11) fmt.Println(f.HackerAbbreviation()) - // Output: ADP + // Output: SCSI } func BenchmarkHackerAbbreviation(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HackerAbbreviation() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HackerAbbreviation() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HackerAbbreviation() - } - }) + for i := 0; i < b.N; i++ { + HackerAbbreviation() + } } func ExampleHackerAdjective() { Seed(11) fmt.Println(HackerAdjective()) - // Output: wireless + // Output: solid state } func ExampleFaker_HackerAdjective() { f := New(11) fmt.Println(f.HackerAdjective()) - // Output: wireless + // Output: solid state } func BenchmarkHackerAdjective(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HackerAdjective() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HackerAdjective() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HackerAdjective() - } - }) + for i := 0; i < b.N; i++ { + HackerAdjective() + } } func ExampleHackerNoun() { Seed(11) fmt.Println(HackerNoun()) - // Output: driver + // Output: circuit } func ExampleFaker_HackerNoun() { f := New(11) fmt.Println(f.HackerNoun()) - // Output: driver + // Output: circuit } func BenchmarkHackerNoun(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HackerNoun() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HackerNoun() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HackerNoun() - } - }) + for i := 0; i < b.N; i++ { + HackerNoun() + } } func ExampleHackerVerb() { Seed(11) fmt.Println(HackerVerb()) - // Output: synthesize + // Output: lock } func ExampleFaker_HackerVerb() { f := New(11) fmt.Println(f.HackerVerb()) - // Output: synthesize + // Output: lock } func BenchmarkHackerVerb(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HackerVerb() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HackerVerb() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HackerVerb() - } - }) + for i := 0; i < b.N; i++ { + HackerVerb() + } } func ExampleHackeringVerb() { Seed(11) fmt.Println(HackeringVerb()) - // Output: connecting + // Output: compressing } func ExampleFaker_HackeringVerb() { f := New(11) fmt.Println(f.HackeringVerb()) - // Output: connecting + // Output: compressing } func BenchmarkHackeringVerb(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HackeringVerb() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HackeringVerb() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HackeringVerb() - } - }) + for i := 0; i < b.N; i++ { + HackeringVerb() + } } diff --git a/helpers.go b/helpers.go index 3dcf849b..edef038c 100644 --- a/helpers.go +++ b/helpers.go @@ -1,17 +1,14 @@ package gofakeit import ( - crand "crypto/rand" - "encoding/binary" "encoding/json" "fmt" "math" - "math/rand" "reflect" "strings" "unicode" - "github.com/brianvoe/gofakeit/v6/data" + "github.com/brianvoe/gofakeit/v7/data" ) const lowerStr = "abcdefghijklmnopqrstuvwxyz" @@ -30,16 +27,7 @@ const minUint = 0 const maxUint = ^uint(0) const minInt = -maxInt - 1 const maxInt = int(^uint(0) >> 1) - -// Seed will set the global random value. Setting seed to 0 will use crypto/rand -func Seed(seed int64) { - if seed == 0 { - binary.Read(crand.Reader, binary.BigEndian, &seed) - globalFaker.Rand.Seed(seed) - } else { - globalFaker.Rand.Seed(seed) - } -} +const is32bit = ^uint(0)>>32 == 0 // Check if in lib func dataCheck(dataVal []string) bool { @@ -56,40 +44,40 @@ func dataCheck(dataVal []string) bool { } // Get Random Value -func getRandValue(r *rand.Rand, dataVal []string) string { +func getRandValue(f *Faker, dataVal []string) string { if !dataCheck(dataVal) { return "" } - return data.Data[dataVal[0]][dataVal[1]][r.Intn(len(data.Data[dataVal[0]][dataVal[1]]))] + return data.Data[dataVal[0]][dataVal[1]][f.IntN(len(data.Data[dataVal[0]][dataVal[1]]))] } // Replace # with numbers -func replaceWithNumbers(r *rand.Rand, str string) string { +func replaceWithNumbers(f *Faker, str string) string { if str == "" { return str } bytestr := []byte(str) for i := 0; i < len(bytestr); i++ { if bytestr[i] == hashtag { - bytestr[i] = byte(randDigit(r)) + bytestr[i] = byte(randDigit(f)) } } if bytestr[0] == '0' { - bytestr[0] = byte(r.Intn(8)+1) + '0' + bytestr[0] = byte(f.IntN(8)+1) + '0' } return string(bytestr) } // Replace ? with ASCII lowercase letters -func replaceWithLetters(r *rand.Rand, str string) string { +func replaceWithLetters(f *Faker, str string) string { if str == "" { return str } bytestr := []byte(str) for i := 0; i < len(bytestr); i++ { if bytestr[i] == questionmark { - bytestr[i] = byte(randLetter(r)) + bytestr[i] = byte(randLetter(f)) } } @@ -97,14 +85,14 @@ func replaceWithLetters(r *rand.Rand, str string) string { } // Replace ? with ASCII lowercase letters between a and f -func replaceWithHexLetters(r *rand.Rand, str string) string { +func replaceWithHexLetters(f *Faker, str string) string { if str == "" { return str } bytestr := []byte(str) for i := 0; i < len(bytestr); i++ { if bytestr[i] == questionmark { - bytestr[i] = byte(randHexLetter(r)) + bytestr[i] = byte(randHexLetter(f)) } } @@ -112,81 +100,51 @@ func replaceWithHexLetters(r *rand.Rand, str string) string { } // Generate random lowercase ASCII letter -func randLetter(r *rand.Rand) rune { +func randLetter(f *Faker) rune { allLetters := upperStr + lowerStr - return rune(allLetters[r.Intn(len(allLetters))]) + return rune(allLetters[f.IntN(len(allLetters))]) } -func randCharacter(r *rand.Rand, s string) string { - return string(s[r.Int63()%int64(len(s))]) +func randCharacter(f *Faker, s string) string { + return string(s[f.Int64()%int64(len(s))]) } // Generate random lowercase ASCII letter between a and f -func randHexLetter(r *rand.Rand) rune { - return rune(byte(r.Intn(6)) + 'a') +func randHexLetter(f *Faker) rune { + return rune(byte(f.IntN(6)) + 'a') } // Generate random ASCII digit -func randDigit(r *rand.Rand) rune { - return rune(byte(r.Intn(10)) + '0') +func randDigit(f *Faker) rune { + return rune(byte(f.IntN(10)) + '0') } // Generate random integer between min and max -func randIntRange(r *rand.Rand, min, max int) int { - // If they pass in the same number, just return that number +func randIntRange(f *Faker, min, max int) int { if min == max { return min } - // If they pass in a min that is bigger than max, swap them if min > max { - ogmin := min - min = max - max = ogmin + min, max = max, min // Swap if min is greater than max } - // Figure out if the min/max numbers calculation - // would cause a panic in the Int63() function. - if max-min+1 > 0 { - return min + int(r.Int63n(int64(max-min+1))) - } - - // Loop through the range until we find a number that fits - for { - v := int(r.Uint64()) - if (v >= min) && (v <= max) { - return v - } - } + // Use f.IntN to generate a random number in [0, rangeSize) and shift it into [min, max]. + return f.IntN(max-min+1) + min } // Generate random uint between min and max -func randUintRange(r *rand.Rand, min, max uint) uint { - // If they pass in the same number, just return that number +func randUintRange(f *Faker, min, max uint) uint { if min == max { - return min + return min // Immediate return if range is zero } - // If they pass in a min that is bigger than max, swap them if min > max { - ogmin := min - min = max - max = ogmin - } - - // Figure out if the min/max numbers calculation - // would cause a panic in the Int63() function. - if int(max)-int(min)+1 > 0 { - return uint(r.Intn(int(max)-int(min)+1) + int(min)) + min, max = max, min // Swap if min is greater than max } - // Loop through the range until we find a number that fits - for { - v := uint(r.Uint64()) - if (v >= min) && (v <= max) { - return v - } - } + // Use f.UintN to generate a random number in [0, rangeSize) and shift it into [min, max]. + return f.UintN(max-min+1) + min } func toFixed(num float64, precision int) float64 { diff --git a/helpers_test.go b/helpers_test.go index b5bb9f65..a0624644 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -5,10 +5,6 @@ import ( "testing" ) -func TestSeed(t *testing.T) { - Seed(0) -} - // Test taking in two random int values and making sure the output is within the range func TestRandIntRange(t *testing.T) { // Create a set of structs to test @@ -21,6 +17,8 @@ func TestRandIntRange(t *testing.T) { {0, 0}, {1000, -1000}, {minInt, maxInt}, + {minInt, minInt + 100}, // Test min + {maxInt - 100, maxInt}, // Test max {maxInt - 20000, maxInt - 10000}, {minInt + 10000, maxInt - 10000}, } @@ -28,21 +26,21 @@ func TestRandIntRange(t *testing.T) { // Add 10000 random values to the test set for i := 0; i < 5000; i++ { tests = append(tests, testStruct{ - min: randIntRange(globalFaker.Rand, 0, maxInt), - max: randIntRange(globalFaker.Rand, 0, maxInt), + min: randIntRange(GlobalFaker, 0, maxInt), + max: randIntRange(GlobalFaker, 0, maxInt), }) } for i := 0; i < 5000; i++ { tests = append(tests, testStruct{ - min: randIntRange(globalFaker.Rand, minInt, 0), - max: randIntRange(globalFaker.Rand, 0, maxInt), + min: randIntRange(GlobalFaker, minInt, 0), + max: randIntRange(GlobalFaker, 0, maxInt), }) } // Loop through the tests for _, test := range tests { // Get the result - result := randIntRange(globalFaker.Rand, test.min, test.max) + result := randIntRange(GlobalFaker, test.min, test.max) // Check the result if test.min > test.max { @@ -67,28 +65,28 @@ func TestRandUintRange(t *testing.T) { tests := []testStruct{ {0, 0}, {100000, 100}, - {0, maxUint}, - {0 + 10000, maxUint - 10000}, + {minUint, maxUint}, + {minUint + 10000, maxUint - 10000}, } // Add 10000 random values to the test set for i := 0; i < 5000; i++ { tests = append(tests, testStruct{ - min: randUintRange(globalFaker.Rand, 0, maxUint), - max: randUintRange(globalFaker.Rand, 0, maxUint), + min: randUintRange(GlobalFaker, 0, maxUint), + max: randUintRange(GlobalFaker, 0, maxUint), }) } for i := 0; i < 5000; i++ { tests = append(tests, testStruct{ - min: randUintRange(globalFaker.Rand, 0, maxUint/2), - max: randUintRange(globalFaker.Rand, maxUint/2, maxUint), + min: randUintRange(GlobalFaker, 0, maxUint/2), + max: randUintRange(GlobalFaker, maxUint/2, maxUint), }) } // Loop through the tests for _, test := range tests { // Get the result - result := randUintRange(globalFaker.Rand, test.min, test.max) + result := randUintRange(GlobalFaker, test.min, test.max) // Check the result if test.min > test.max { @@ -104,49 +102,54 @@ func TestRandUintRange(t *testing.T) { func TestGetRandValueFail(t *testing.T) { for _, test := range [][]string{nil, {}, {"not", "found"}, {"person", "notfound"}} { - if getRandValue(globalFaker.Rand, test) != "" { + if getRandValue(GlobalFaker, test) != "" { t.Error("You should have gotten no value back") } } } func TestReplaceWithNumbers(t *testing.T) { - if replaceWithNumbers(globalFaker.Rand, "") != "" { + if replaceWithNumbers(GlobalFaker, "") != "" { t.Error("You should have gotten an empty string") } } func BenchmarkReplaceWithNumbers(b *testing.B) { for i := 0; i < b.N; i++ { - Seed(42) - replaceWithNumbers(globalFaker.Rand, "###☺#☻##☹##") + Seed(11) + replaceWithNumbers(GlobalFaker, "###☺#☻##☹##") } } func TestReplaceWithNumbersUnicode(t *testing.T) { - for _, test := range []struct{ in, should string }{ - {"#界#世#", "5界7世8"}, - {"☺#☻☹#", "☺5☻☹7"}, - {"\x80#¼#語", "\x805¼7語"}, + for _, test := range []struct{ in string }{ + {"#界#世#"}, + {"☺#☻☹#"}, + {"\x80#¼#語"}, } { - Seed(42) - got := replaceWithNumbers(globalFaker.Rand, test.in) - if got == test.should { - continue + Seed(11) + got := replaceWithNumbers(GlobalFaker, test.in) + if got == test.in { + t.Errorf("got %q, want something different", got) + } + + // Check that # were replaced with numbers + for _, r := range got { + if r == '#' { + t.Errorf("got %q, want something different", got) + } } - t.Errorf("for '%s' got '%s' should '%s'", - test.in, got, test.should) } } func TestReplaceWithLetters(t *testing.T) { - if replaceWithLetters(globalFaker.Rand, "") != "" { + if replaceWithLetters(GlobalFaker, "") != "" { t.Error("You should have gotten an empty string") } } func TestReplaceWithHexLetters(t *testing.T) { - if replaceWithHexLetters(globalFaker.Rand, "") != "" { + if replaceWithHexLetters(GlobalFaker, "") != "" { t.Error("You should have gotten an empty string") } } diff --git a/hipster.go b/hipster.go index 0369f17e..8cf7cba9 100644 --- a/hipster.go +++ b/hipster.go @@ -2,25 +2,24 @@ package gofakeit import ( "errors" - "math/rand" ) // HipsterWord will return a single hipster word -func HipsterWord() string { return hipsterWord(globalFaker.Rand) } +func HipsterWord() string { return hipsterWord(GlobalFaker) } // HipsterWord will return a single hipster word -func (f *Faker) HipsterWord() string { return hipsterWord(f.Rand) } +func (f *Faker) HipsterWord() string { return hipsterWord(f) } -func hipsterWord(r *rand.Rand) string { return getRandValue(r, []string{"hipster", "word"}) } +func hipsterWord(f *Faker) string { return getRandValue(f, []string{"hipster", "word"}) } // HipsterSentence will generate a random sentence -func HipsterSentence(wordCount int) string { return hipsterSentence(globalFaker.Rand, wordCount) } +func HipsterSentence(wordCount int) string { return hipsterSentence(GlobalFaker, wordCount) } // HipsterSentence will generate a random sentence -func (f *Faker) HipsterSentence(wordCount int) string { return hipsterSentence(f.Rand, wordCount) } +func (f *Faker) HipsterSentence(wordCount int) string { return hipsterSentence(f, wordCount) } -func hipsterSentence(r *rand.Rand, wordCount int) string { - return sentenceGen(r, wordCount, hipsterWord) +func hipsterSentence(f *Faker, wordCount int) string { + return sentenceGen(f, wordCount, hipsterWord) } // HipsterParagraph will generate a random paragraphGenerator @@ -29,7 +28,7 @@ func hipsterSentence(r *rand.Rand, wordCount int) string { // Set Word Count // Set Paragraph Separator func HipsterParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { - return hipsterParagraph(globalFaker.Rand, paragraphCount, sentenceCount, wordCount, separator) + return hipsterParagraph(GlobalFaker, paragraphCount, sentenceCount, wordCount, separator) } // HipsterParagraph will generate a random paragraphGenerator @@ -38,11 +37,11 @@ func HipsterParagraph(paragraphCount int, sentenceCount int, wordCount int, sepa // Set Word Count // Set Paragraph Separator func (f *Faker) HipsterParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { - return hipsterParagraph(f.Rand, paragraphCount, sentenceCount, wordCount, separator) + return hipsterParagraph(f, paragraphCount, sentenceCount, wordCount, separator) } -func hipsterParagraph(r *rand.Rand, paragraphCount int, sentenceCount int, wordCount int, separator string) string { - return paragraphGen(r, paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, hipsterSentence) +func hipsterParagraph(f *Faker, paragraphCount int, sentenceCount int, wordCount int, separator string) string { + return paragraphGen(f, paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, hipsterSentence) } func addHipsterLookup() { @@ -52,8 +51,8 @@ func addHipsterLookup() { Description: "Trendy and unconventional vocabulary used by hipsters to express unique cultural preferences", Example: "microdosing", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hipsterWord(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return hipsterWord(f), nil }, }) @@ -66,7 +65,7 @@ func addHipsterLookup() { Params: []Param{ {Field: "wordcount", Display: "Word Count", Type: "int", Default: "5", Description: "Number of words in a sentence"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { wordCount, err := info.GetInt(m, "wordcount") if err != nil { return nil, err @@ -75,7 +74,7 @@ func addHipsterLookup() { return nil, errors.New("invalid word count, must be greater than 0, less than 50") } - return hipsterSentence(r, wordCount), nil + return hipsterSentence(f, wordCount), nil }, }) @@ -95,7 +94,7 @@ Shabby chic typewriter VHS readymade lo-fi bitters PBR&B gentrify lomo raw denim {Field: "wordcount", Display: "Word Count", Type: "int", Default: "5", Description: "Number of words in a sentence"}, {Field: "paragraphseparator", Display: "Paragraph Separator", Type: "string", Default: "
", Description: "String value to add between paragraphs"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { paragraphCount, err := info.GetInt(m, "paragraphcount") if err != nil { return nil, err @@ -125,7 +124,7 @@ Shabby chic typewriter VHS readymade lo-fi bitters PBR&B gentrify lomo raw denim return nil, err } - return hipsterParagraph(r, paragraphCount, sentenceCount, wordCount, paragraphSeparator), nil + return hipsterParagraph(f, paragraphCount, sentenceCount, wordCount, paragraphSeparator), nil }, }) } diff --git a/hipster_test.go b/hipster_test.go index 564ad0f7..277c9eda 100644 --- a/hipster_test.go +++ b/hipster_test.go @@ -9,116 +9,62 @@ func ExampleHipsterWord() { Seed(11) fmt.Println(HipsterWord()) - // Output: microdosing + // Output: semiotics } func ExampleFaker_HipsterWord() { f := New(11) fmt.Println(f.HipsterWord()) - // Output: microdosing + // Output: semiotics } func BenchmarkHipsterWord(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HipsterWord() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HipsterWord() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HipsterWord() - } - }) + for i := 0; i < b.N; i++ { + HipsterWord() + } } func ExampleHipsterSentence() { Seed(11) fmt.Println(HipsterSentence(5)) - // Output: Microdosing roof chia echo pickled. + // Output: Semiotics everyday you probably haven't heard of them you probably haven't heard of them portland. } func ExampleFaker_HipsterSentence() { f := New(11) fmt.Println(f.HipsterSentence(5)) - // Output: Microdosing roof chia echo pickled. + // Output: Semiotics everyday you probably haven't heard of them you probably haven't heard of them portland. } func BenchmarkHipsterSentence(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HipsterSentence(10) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HipsterSentence(10) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HipsterSentence(10) - } - }) + for i := 0; i < b.N; i++ { + HipsterSentence(10) + } } func ExampleHipsterParagraph() { Seed(11) fmt.Println(HipsterParagraph(3, 5, 12, "\n")) - // Output: Microdosing roof chia echo pickled meditation cold-pressed raw denim fingerstache normcore sriracha pork belly. Wolf try-hard pop-up blog tilde hashtag health butcher waistcoat paleo portland vinegar. Microdosing sartorial blue bottle slow-carb freegan five dollar toast you probably haven't heard of them asymmetrical chia farm-to-table narwhal banjo. Gluten-free blog authentic literally synth vinyl meh ethical health fixie banh mi Yuccie. Try-hard drinking squid seitan cray VHS echo chillwave hammock kombucha food truck sustainable. - // Pug bushwick hella tote bag cliche direct trade waistcoat yr waistcoat knausgaard pour-over master. Pitchfork jean shorts franzen flexitarian distillery hella meggings austin knausgaard crucifix wolf heirloom. Crucifix food truck you probably haven't heard of them trust fund fixie gentrify pitchfork stumptown mlkshk umami chambray blue bottle. 3 wolf moon swag +1 biodiesel knausgaard semiotics taxidermy meh artisan hoodie +1 blue bottle. Fashion axe forage mixtape Thundercats pork belly whatever 90's beard selfies chambray cred mlkshk. - // Shabby chic typewriter VHS readymade lo-fi bitters PBR&B gentrify lomo raw denim freegan put a bird on it. Raw denim cliche dreamcatcher pug fixie park trust fund migas fingerstache sriracha +1 mustache. Tilde shoreditch kickstarter franzen dreamcatcher green juice mustache neutra polaroid stumptown organic schlitz. Flexitarian ramps chicharrones kogi lo-fi mustache tilde forage street church-key williamsburg taxidermy. Chia mustache plaid mumblecore squid slow-carb disrupt Thundercats goth shoreditch master direct trade. + // Output: Semiotics everyday you probably haven't heard of them you probably haven't heard of them portland austin tattooed retro cardigan Yuccie cred hoodie. Vice pug pug cred intelligentsia roof helvetica squid chambray literally ennui ugh. Chicharrones messenger bag narwhal ennui flannel twee art party mustache sartorial gluten-free cardigan cronut. Hoodie kickstarter cardigan Thundercats heirloom hashtag bitters salvia cleanse forage chartreuse keffiyeh. Sustainable tofu mustache bespoke vice aesthetic iPhone ugh lo-fi health put a bird on it blue bottle. + // Pop-up pabst pitchfork literally roof tattooed tilde shoreditch green juice ethical celiac tilde. Kombucha kinfolk occupy tacos ramps 90's echo meditation kale chips gluten-free humblebrag keffiyeh. Lo-fi bespoke wayfarers chicharrones crucifix green juice humblebrag organic viral shabby chic locavore cred. Roof forage farm-to-table YOLO williamsburg crucifix blog everyday green juice listicle wayfarers post-ironic. Single-origin coffee cray organic YOLO disrupt venmo tofu meggings fanny pack master craft beer tofu. + // Hella helvetica microdosing literally meh etsy echo pabst goth readymade +1 marfa. Pork belly hammock kale chips yr green juice stumptown crucifix hella pork belly franzen wolf austin. Offal cred chartreuse freegan intelligentsia twee trust fund paleo pinterest austin typewriter kogi. Pug single-origin coffee ethical irony helvetica beard green juice viral post-ironic Godard slow-carb put a bird on it. Schlitz hammock beard chia kitsch cred salvia irony farm-to-table loko truffaut ramps. } func ExampleFaker_HipsterParagraph() { f := New(11) fmt.Println(f.HipsterParagraph(3, 5, 12, "\n")) - // Output: Microdosing roof chia echo pickled meditation cold-pressed raw denim fingerstache normcore sriracha pork belly. Wolf try-hard pop-up blog tilde hashtag health butcher waistcoat paleo portland vinegar. Microdosing sartorial blue bottle slow-carb freegan five dollar toast you probably haven't heard of them asymmetrical chia farm-to-table narwhal banjo. Gluten-free blog authentic literally synth vinyl meh ethical health fixie banh mi Yuccie. Try-hard drinking squid seitan cray VHS echo chillwave hammock kombucha food truck sustainable. - // Pug bushwick hella tote bag cliche direct trade waistcoat yr waistcoat knausgaard pour-over master. Pitchfork jean shorts franzen flexitarian distillery hella meggings austin knausgaard crucifix wolf heirloom. Crucifix food truck you probably haven't heard of them trust fund fixie gentrify pitchfork stumptown mlkshk umami chambray blue bottle. 3 wolf moon swag +1 biodiesel knausgaard semiotics taxidermy meh artisan hoodie +1 blue bottle. Fashion axe forage mixtape Thundercats pork belly whatever 90's beard selfies chambray cred mlkshk. - // Shabby chic typewriter VHS readymade lo-fi bitters PBR&B gentrify lomo raw denim freegan put a bird on it. Raw denim cliche dreamcatcher pug fixie park trust fund migas fingerstache sriracha +1 mustache. Tilde shoreditch kickstarter franzen dreamcatcher green juice mustache neutra polaroid stumptown organic schlitz. Flexitarian ramps chicharrones kogi lo-fi mustache tilde forage street church-key williamsburg taxidermy. Chia mustache plaid mumblecore squid slow-carb disrupt Thundercats goth shoreditch master direct trade. + // Output: Semiotics everyday you probably haven't heard of them you probably haven't heard of them portland austin tattooed retro cardigan Yuccie cred hoodie. Vice pug pug cred intelligentsia roof helvetica squid chambray literally ennui ugh. Chicharrones messenger bag narwhal ennui flannel twee art party mustache sartorial gluten-free cardigan cronut. Hoodie kickstarter cardigan Thundercats heirloom hashtag bitters salvia cleanse forage chartreuse keffiyeh. Sustainable tofu mustache bespoke vice aesthetic iPhone ugh lo-fi health put a bird on it blue bottle. + // Pop-up pabst pitchfork literally roof tattooed tilde shoreditch green juice ethical celiac tilde. Kombucha kinfolk occupy tacos ramps 90's echo meditation kale chips gluten-free humblebrag keffiyeh. Lo-fi bespoke wayfarers chicharrones crucifix green juice humblebrag organic viral shabby chic locavore cred. Roof forage farm-to-table YOLO williamsburg crucifix blog everyday green juice listicle wayfarers post-ironic. Single-origin coffee cray organic YOLO disrupt venmo tofu meggings fanny pack master craft beer tofu. + // Hella helvetica microdosing literally meh etsy echo pabst goth readymade +1 marfa. Pork belly hammock kale chips yr green juice stumptown crucifix hella pork belly franzen wolf austin. Offal cred chartreuse freegan intelligentsia twee trust fund paleo pinterest austin typewriter kogi. Pug single-origin coffee ethical irony helvetica beard green juice viral post-ironic Godard slow-carb put a bird on it. Schlitz hammock beard chia kitsch cred salvia irony farm-to-table loko truffaut ramps. } func BenchmarkHipsterParagraph(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HipsterParagraph(3, 5, 12, "\n") - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HipsterParagraph(3, 5, 12, "\n") - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HipsterParagraph(3, 5, 12, "\n") - } - }) + for i := 0; i < b.N; i++ { + HipsterParagraph(3, 5, 12, "\n") + } } diff --git a/html.go b/html.go index a047617a..27385ecd 100644 --- a/html.go +++ b/html.go @@ -2,25 +2,24 @@ package gofakeit import ( "errors" - "math/rand" "strconv" "strings" - "github.com/brianvoe/gofakeit/v6/data" + "github.com/brianvoe/gofakeit/v7/data" ) // InputName will return a random input field name func InputName() string { - return inputName(globalFaker.Rand) + return inputName(GlobalFaker) } // InputName will return a random input field name func (f *Faker) InputName() string { - return inputName(f.Rand) + return inputName(f) } -func inputName(r *rand.Rand) string { - return getRandValue(r, []string{"html", "input_name"}) +func inputName(f *Faker) string { + return getRandValue(f, []string{"html", "input_name"}) } type SVGOptions struct { @@ -31,12 +30,12 @@ type SVGOptions struct { } // Generate a random svg generator -func Svg(options *SVGOptions) string { return svg(globalFaker.Rand, options) } +func Svg(options *SVGOptions) string { return svg(GlobalFaker, options) } // Generate a random svg generator -func (f *Faker) Svg(options *SVGOptions) string { return svg(f.Rand, options) } +func (f *Faker) Svg(options *SVGOptions) string { return svg(f, options) } -func svg(r *rand.Rand, options *SVGOptions) string { +func svg(f *Faker, options *SVGOptions) string { // If options is nil, set it to empty struct if options == nil { options = &SVGOptions{} @@ -44,46 +43,46 @@ func svg(r *rand.Rand, options *SVGOptions) string { // If options height and weight is not set, set it to random number between 100 and 500 if options.Width == 0 { - options.Width = number(r, 100, 500) + options.Width = number(f, 100, 500) } widthStr := strconv.Itoa(options.Width) if options.Height == 0 { - options.Height = number(r, 100, 500) + options.Height = number(f, 100, 500) } heightStr := strconv.Itoa(options.Height) // Check if type is set, if not set to random type if options.Type == "" { - options.Type = randomString(r, data.GetSubData("html", "svg")) + options.Type = randomString(f, data.GetSubData("html", "svg")) } // If the colors are not set, set it to a set of nice colors if len(options.Colors) == 0 { - options.Colors = niceColors(r) + options.Colors = niceColors(f) } // Start svg string svgStr := `` // Add a rect for the background - svgStr += `` + svgStr += `` // Add a random number of shapes - for i := 0; i < number(r, 10, 20); i++ { + for i := 0; i < number(f, 10, 20); i++ { // Add a random shape switch options.Type { case "rect": - svgStr += `` + svgStr += `` case "circle": - svgStr += `` + svgStr += `` case "ellipse": - svgStr += `` + svgStr += `` case "line": - svgStr += `` + svgStr += `` case "polyline": - svgStr += `` + svgStr += `` case "polygon": - svgStr += `` + svgStr += `` } } @@ -100,8 +99,8 @@ func addHtmlLookup() { Description: "Attribute used to define the name of an input element in web forms", Example: "first_name", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return inputName(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return inputName(f), nil }, }) @@ -121,7 +120,7 @@ func addHtmlLookup() { {Field: "type", Display: "Type", Type: "string", Optional: true, Options: data.GetSubData("html", "svg"), Description: "Sub child element type"}, {Field: "colors", Display: "Colors", Type: "[]string", Optional: true, Description: "Hex or RGB array of colors to use"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { // Setup new options options := SVGOptions{} var err error @@ -150,7 +149,7 @@ func addHtmlLookup() { // If type is empty, set with random type if options.Type == "" { - options.Type = randomString(r, svgData) + options.Type = randomString(f, svgData) } // If not in date html svg type array, return error @@ -166,10 +165,10 @@ func addHtmlLookup() { // If colors is empty, set with random colors if len(options.Colors) == 0 { - options.Colors = niceColors(r) + options.Colors = niceColors(f) } - return svg(r, &options), nil + return svg(f, &options), nil }, }) } diff --git a/html_test.go b/html_test.go index d621eb51..23ba720a 100644 --- a/html_test.go +++ b/html_test.go @@ -5,7 +5,7 @@ import ( "strings" "testing" - "github.com/brianvoe/gofakeit/v6/data" + "github.com/brianvoe/gofakeit/v7/data" ) func ExampleInputName() { @@ -23,27 +23,9 @@ func ExampleFaker_InputName() { } func BenchmarkInputName(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - InputName() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.InputName() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.InputName() - } - }) + for i := 0; i < b.N; i++ { + InputName() + } } func TestSvg(t *testing.T) { @@ -77,36 +59,18 @@ func ExampleSvg() { Seed(11) fmt.Println(Svg(nil)) - // Output: + // Output: } func ExampleFaker_Svg() { f := New(11) fmt.Println(f.Svg(nil)) - // Output: + // Output: } func BenchmarkSvg(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Svg(nil) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Svg(nil) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Svg(nil) - } - }) + for i := 0; i < b.N; i++ { + Svg(nil) + } } diff --git a/image.go b/image.go index e7c40dd8..2c03fbec 100644 --- a/image.go +++ b/image.go @@ -7,27 +7,26 @@ import ( imgCol "image/color" "image/jpeg" "image/png" - "math/rand" "strconv" ) // ImageURL will generate a random Image Based Upon Height And Width. https://picsum.photos/ -func ImageURL(width int, height int) string { return imageURL(globalFaker.Rand, width, height) } +func ImageURL(width int, height int) string { return imageURL(GlobalFaker, width, height) } // ImageURL will generate a random Image Based Upon Height And Width. https://picsum.photos/ -func (f *Faker) ImageURL(width int, height int) string { return imageURL(f.Rand, width, height) } +func (f *Faker) ImageURL(width int, height int) string { return imageURL(f, width, height) } -func imageURL(r *rand.Rand, width int, height int) string { +func imageURL(f *Faker, width int, height int) string { return "https://picsum.photos/" + strconv.Itoa(width) + "/" + strconv.Itoa(height) } // Image generates a random rgba image -func Image(width int, height int) *img.RGBA { return image(globalFaker.Rand, width, height) } +func Image(width int, height int) *img.RGBA { return image(GlobalFaker, width, height) } // Image generates a random rgba image -func (f *Faker) Image(width int, height int) *img.RGBA { return image(f.Rand, width, height) } +func (f *Faker) Image(width int, height int) *img.RGBA { return image(f, width, height) } -func image(r *rand.Rand, width int, height int) *img.RGBA { +func image(f *Faker, width int, height int) *img.RGBA { upLeft := img.Point{0, 0} lowRight := img.Point{width, height} @@ -36,7 +35,7 @@ func image(r *rand.Rand, width int, height int) *img.RGBA { // Set color for each pixel for x := 0; x < width; x++ { for y := 0; y < height; y++ { - img.Set(x, y, imgCol.RGBA{uint8(number(r, 0, 255)), uint8(number(r, 0, 255)), uint8(number(r, 0, 255)), 0xff}) + img.Set(x, y, imgCol.RGBA{uint8(number(f, 0, 255)), uint8(number(f, 0, 255)), uint8(number(f, 0, 255)), 0xff}) } } @@ -44,26 +43,26 @@ func image(r *rand.Rand, width int, height int) *img.RGBA { } // ImageJpeg generates a random rgba jpeg image -func ImageJpeg(width int, height int) []byte { return imageJpeg(globalFaker.Rand, width, height) } +func ImageJpeg(width int, height int) []byte { return imageJpeg(GlobalFaker, width, height) } // ImageJpeg generates a random rgba jpeg image -func (f *Faker) ImageJpeg(width int, height int) []byte { return imageJpeg(f.Rand, width, height) } +func (f *Faker) ImageJpeg(width int, height int) []byte { return imageJpeg(f, width, height) } -func imageJpeg(r *rand.Rand, width int, height int) []byte { +func imageJpeg(f *Faker, width int, height int) []byte { buf := new(bytes.Buffer) - jpeg.Encode(buf, image(r, width, height), nil) + jpeg.Encode(buf, image(f, width, height), nil) return buf.Bytes() } // ImagePng generates a random rgba png image -func ImagePng(width int, height int) []byte { return imagePng(globalFaker.Rand, width, height) } +func ImagePng(width int, height int) []byte { return imagePng(GlobalFaker, width, height) } // ImagePng generates a random rgba png image -func (f *Faker) ImagePng(width int, height int) []byte { return imagePng(f.Rand, width, height) } +func (f *Faker) ImagePng(width int, height int) []byte { return imagePng(f, width, height) } -func imagePng(r *rand.Rand, width int, height int) []byte { +func imagePng(f *Faker, width int, height int) []byte { buf := new(bytes.Buffer) - png.Encode(buf, image(r, width, height)) + png.Encode(buf, image(f, width, height)) return buf.Bytes() } @@ -78,7 +77,7 @@ func addImageLookup() { {Field: "width", Display: "Width", Type: "int", Default: "500", Description: "Image width in px"}, {Field: "height", Display: "Height", Type: "int", Default: "500", Description: "Image height in px"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { width, err := info.GetInt(m, "width") if err != nil { return nil, err @@ -95,7 +94,7 @@ func addImageLookup() { return nil, errors.New("invalid image height, must be greater than 10, less than 1000") } - return imageURL(r, width, height), nil + return imageURL(f, width, height), nil }, }) @@ -110,7 +109,7 @@ func addImageLookup() { {Field: "width", Display: "Width", Type: "int", Default: "500", Description: "Image width in px"}, {Field: "height", Display: "Height", Type: "int", Default: "500", Description: "Image height in px"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { width, err := info.GetInt(m, "width") if err != nil { return nil, err @@ -127,7 +126,7 @@ func addImageLookup() { return nil, errors.New("invalid image height, must be greater than 10, less than 1000") } - return imageJpeg(r, width, height), nil + return imageJpeg(f, width, height), nil }, }) @@ -142,7 +141,7 @@ func addImageLookup() { {Field: "width", Display: "Width", Type: "int", Default: "500", Description: "Image width in px"}, {Field: "height", Display: "Height", Type: "int", Default: "500", Description: "Image height in px"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { width, err := info.GetInt(m, "width") if err != nil { return nil, err @@ -159,7 +158,7 @@ func addImageLookup() { return nil, errors.New("invalid image height, must be greater than 10, less than 1000") } - return imagePng(r, width, height), nil + return imagePng(f, width, height), nil }, }) } diff --git a/image_test.go b/image_test.go index 0e1dad8a..0c9ec0cd 100644 --- a/image_test.go +++ b/image_test.go @@ -20,139 +20,67 @@ func ExampleFaker_ImageURL() { } func BenchmarkImageURL(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ImageURL(640, 480) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ImageURL(640, 480) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ImageURL(640, 480) - } - }) + for i := 0; i < b.N; i++ { + ImageURL(640, 480) + } } func ExampleImage() { Seed(11) fmt.Println(Image(1, 1)) - // Output: &{[89 176 195 255] 4 (0,0)-(1,1)} + // Output: &{[180 18 181 255] 4 (0,0)-(1,1)} } func ExampleFaker_Image() { f := New(11) fmt.Println(f.Image(1, 1)) - // Output: &{[89 176 195 255] 4 (0,0)-(1,1)} + // Output: &{[180 18 181 255] 4 (0,0)-(1,1)} } func BenchmarkImage(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Image(640, 480) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Image(640, 480) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Image(640, 480) - } - }) + for i := 0; i < b.N; i++ { + Image(640, 480) + } } func ExampleImageJpeg() { Seed(11) fmt.Println(ImageJpeg(1, 1)) - // Output: [255 216 255 219 0 132 0 8 6 6 7 6 5 8 7 7 7 9 9 8 10 12 20 13 12 11 11 12 25 18 19 15 20 29 26 31 30 29 26 28 28 32 36 46 39 32 34 44 35 28 28 40 55 41 44 48 49 52 52 52 31 39 57 61 56 50 60 46 51 52 50 1 9 9 9 12 11 12 24 13 13 24 50 33 28 33 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 255 192 0 17 8 0 1 0 1 3 1 34 0 2 17 1 3 17 1 255 196 1 162 0 0 1 5 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 16 0 2 1 3 3 2 4 3 5 5 4 4 0 0 1 125 1 2 3 0 4 17 5 18 33 49 65 6 19 81 97 7 34 113 20 50 129 145 161 8 35 66 177 193 21 82 209 240 36 51 98 114 130 9 10 22 23 24 25 26 37 38 39 40 41 42 52 53 54 55 56 57 58 67 68 69 70 71 72 73 74 83 84 85 86 87 88 89 90 99 100 101 102 103 104 105 106 115 116 117 118 119 120 121 122 131 132 133 134 135 136 137 138 146 147 148 149 150 151 152 153 154 162 163 164 165 166 167 168 169 170 178 179 180 181 182 183 184 185 186 194 195 196 197 198 199 200 201 202 210 211 212 213 214 215 216 217 218 225 226 227 228 229 230 231 232 233 234 241 242 243 244 245 246 247 248 249 250 1 0 3 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 17 0 2 1 2 4 4 3 4 7 5 4 4 0 1 2 119 0 1 2 3 17 4 5 33 49 6 18 65 81 7 97 113 19 34 50 129 8 20 66 145 161 177 193 9 35 51 82 240 21 98 114 209 10 22 36 52 225 37 241 23 24 25 26 38 39 40 41 42 53 54 55 56 57 58 67 68 69 70 71 72 73 74 83 84 85 86 87 88 89 90 99 100 101 102 103 104 105 106 115 116 117 118 119 120 121 122 130 131 132 133 134 135 136 137 138 146 147 148 149 150 151 152 153 154 162 163 164 165 166 167 168 169 170 178 179 180 181 182 183 184 185 186 194 195 196 197 198 199 200 201 202 210 211 212 213 214 215 216 217 218 226 227 228 229 230 231 232 233 234 242 243 244 245 246 247 248 249 250 255 218 0 12 3 1 0 2 17 3 17 0 63 0 216 162 138 43 213 62 92 255 217] + // Output: [255 216 255 219 0 132 0 8 6 6 7 6 5 8 7 7 7 9 9 8 10 12 20 13 12 11 11 12 25 18 19 15 20 29 26 31 30 29 26 28 28 32 36 46 39 32 34 44 35 28 28 40 55 41 44 48 49 52 52 52 31 39 57 61 56 50 60 46 51 52 50 1 9 9 9 12 11 12 24 13 13 24 50 33 28 33 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 255 192 0 17 8 0 1 0 1 3 1 34 0 2 17 1 3 17 1 255 196 1 162 0 0 1 5 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 16 0 2 1 3 3 2 4 3 5 5 4 4 0 0 1 125 1 2 3 0 4 17 5 18 33 49 65 6 19 81 97 7 34 113 20 50 129 145 161 8 35 66 177 193 21 82 209 240 36 51 98 114 130 9 10 22 23 24 25 26 37 38 39 40 41 42 52 53 54 55 56 57 58 67 68 69 70 71 72 73 74 83 84 85 86 87 88 89 90 99 100 101 102 103 104 105 106 115 116 117 118 119 120 121 122 131 132 133 134 135 136 137 138 146 147 148 149 150 151 152 153 154 162 163 164 165 166 167 168 169 170 178 179 180 181 182 183 184 185 186 194 195 196 197 198 199 200 201 202 210 211 212 213 214 215 216 217 218 225 226 227 228 229 230 231 232 233 234 241 242 243 244 245 246 247 248 249 250 1 0 3 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 17 0 2 1 2 4 4 3 4 7 5 4 4 0 1 2 119 0 1 2 3 17 4 5 33 49 6 18 65 81 7 97 113 19 34 50 129 8 20 66 145 161 177 193 9 35 51 82 240 21 98 114 209 10 22 36 52 225 37 241 23 24 25 26 38 39 40 41 42 53 54 55 56 57 58 67 68 69 70 71 72 73 74 83 84 85 86 87 88 89 90 99 100 101 102 103 104 105 106 115 116 117 118 119 120 121 122 130 131 132 133 134 135 136 137 138 146 147 148 149 150 151 152 153 154 162 163 164 165 166 167 168 169 170 178 179 180 181 182 183 184 185 186 194 195 196 197 198 199 200 201 202 210 211 212 213 214 215 216 217 218 226 227 228 229 230 231 232 233 234 242 243 244 245 246 247 248 249 250 255 218 0 12 3 1 0 2 17 3 17 0 63 0 229 40 162 138 251 3 239 15 255 217] } func ExampleFaker_ImageJpeg() { f := New(11) fmt.Println(f.ImageJpeg(1, 1)) - // Output: [255 216 255 219 0 132 0 8 6 6 7 6 5 8 7 7 7 9 9 8 10 12 20 13 12 11 11 12 25 18 19 15 20 29 26 31 30 29 26 28 28 32 36 46 39 32 34 44 35 28 28 40 55 41 44 48 49 52 52 52 31 39 57 61 56 50 60 46 51 52 50 1 9 9 9 12 11 12 24 13 13 24 50 33 28 33 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 255 192 0 17 8 0 1 0 1 3 1 34 0 2 17 1 3 17 1 255 196 1 162 0 0 1 5 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 16 0 2 1 3 3 2 4 3 5 5 4 4 0 0 1 125 1 2 3 0 4 17 5 18 33 49 65 6 19 81 97 7 34 113 20 50 129 145 161 8 35 66 177 193 21 82 209 240 36 51 98 114 130 9 10 22 23 24 25 26 37 38 39 40 41 42 52 53 54 55 56 57 58 67 68 69 70 71 72 73 74 83 84 85 86 87 88 89 90 99 100 101 102 103 104 105 106 115 116 117 118 119 120 121 122 131 132 133 134 135 136 137 138 146 147 148 149 150 151 152 153 154 162 163 164 165 166 167 168 169 170 178 179 180 181 182 183 184 185 186 194 195 196 197 198 199 200 201 202 210 211 212 213 214 215 216 217 218 225 226 227 228 229 230 231 232 233 234 241 242 243 244 245 246 247 248 249 250 1 0 3 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 17 0 2 1 2 4 4 3 4 7 5 4 4 0 1 2 119 0 1 2 3 17 4 5 33 49 6 18 65 81 7 97 113 19 34 50 129 8 20 66 145 161 177 193 9 35 51 82 240 21 98 114 209 10 22 36 52 225 37 241 23 24 25 26 38 39 40 41 42 53 54 55 56 57 58 67 68 69 70 71 72 73 74 83 84 85 86 87 88 89 90 99 100 101 102 103 104 105 106 115 116 117 118 119 120 121 122 130 131 132 133 134 135 136 137 138 146 147 148 149 150 151 152 153 154 162 163 164 165 166 167 168 169 170 178 179 180 181 182 183 184 185 186 194 195 196 197 198 199 200 201 202 210 211 212 213 214 215 216 217 218 226 227 228 229 230 231 232 233 234 242 243 244 245 246 247 248 249 250 255 218 0 12 3 1 0 2 17 3 17 0 63 0 216 162 138 43 213 62 92 255 217] + // Output: [255 216 255 219 0 132 0 8 6 6 7 6 5 8 7 7 7 9 9 8 10 12 20 13 12 11 11 12 25 18 19 15 20 29 26 31 30 29 26 28 28 32 36 46 39 32 34 44 35 28 28 40 55 41 44 48 49 52 52 52 31 39 57 61 56 50 60 46 51 52 50 1 9 9 9 12 11 12 24 13 13 24 50 33 28 33 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 50 255 192 0 17 8 0 1 0 1 3 1 34 0 2 17 1 3 17 1 255 196 1 162 0 0 1 5 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 16 0 2 1 3 3 2 4 3 5 5 4 4 0 0 1 125 1 2 3 0 4 17 5 18 33 49 65 6 19 81 97 7 34 113 20 50 129 145 161 8 35 66 177 193 21 82 209 240 36 51 98 114 130 9 10 22 23 24 25 26 37 38 39 40 41 42 52 53 54 55 56 57 58 67 68 69 70 71 72 73 74 83 84 85 86 87 88 89 90 99 100 101 102 103 104 105 106 115 116 117 118 119 120 121 122 131 132 133 134 135 136 137 138 146 147 148 149 150 151 152 153 154 162 163 164 165 166 167 168 169 170 178 179 180 181 182 183 184 185 186 194 195 196 197 198 199 200 201 202 210 211 212 213 214 215 216 217 218 225 226 227 228 229 230 231 232 233 234 241 242 243 244 245 246 247 248 249 250 1 0 3 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 11 17 0 2 1 2 4 4 3 4 7 5 4 4 0 1 2 119 0 1 2 3 17 4 5 33 49 6 18 65 81 7 97 113 19 34 50 129 8 20 66 145 161 177 193 9 35 51 82 240 21 98 114 209 10 22 36 52 225 37 241 23 24 25 26 38 39 40 41 42 53 54 55 56 57 58 67 68 69 70 71 72 73 74 83 84 85 86 87 88 89 90 99 100 101 102 103 104 105 106 115 116 117 118 119 120 121 122 130 131 132 133 134 135 136 137 138 146 147 148 149 150 151 152 153 154 162 163 164 165 166 167 168 169 170 178 179 180 181 182 183 184 185 186 194 195 196 197 198 199 200 201 202 210 211 212 213 214 215 216 217 218 226 227 228 229 230 231 232 233 234 242 243 244 245 246 247 248 249 250 255 218 0 12 3 1 0 2 17 3 17 0 63 0 229 40 162 138 251 3 239 15 255 217] } func BenchmarkImageJpeg(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ImageJpeg(640, 480) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ImageJpeg(640, 480) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ImageJpeg(640, 480) - } - }) + for i := 0; i < b.N; i++ { + ImageJpeg(640, 480) + } } func ExampleImagePng() { Seed(11) fmt.Println(ImagePng(1, 1)) - // Output: [137 80 78 71 13 10 26 10 0 0 0 13 73 72 68 82 0 0 0 1 0 0 0 1 8 2 0 0 0 144 119 83 222 0 0 0 16 73 68 65 84 120 156 98 138 220 112 24 16 0 0 255 255 3 58 1 207 38 214 44 234 0 0 0 0 73 69 78 68 174 66 96 130] + // Output: [137 80 78 71 13 10 26 10 0 0 0 13 73 72 68 82 0 0 0 1 0 0 0 1 8 2 0 0 0 144 119 83 222 0 0 0 16 73 68 65 84 120 156 98 218 34 180 21 16 0 0 255 255 3 1 1 126 242 54 123 184 0 0 0 0 73 69 78 68 174 66 96 130] } func ExampleFaker_ImagePng() { f := New(11) fmt.Println(f.ImagePng(1, 1)) - // Output: [137 80 78 71 13 10 26 10 0 0 0 13 73 72 68 82 0 0 0 1 0 0 0 1 8 2 0 0 0 144 119 83 222 0 0 0 16 73 68 65 84 120 156 98 138 220 112 24 16 0 0 255 255 3 58 1 207 38 214 44 234 0 0 0 0 73 69 78 68 174 66 96 130] + // Output: [137 80 78 71 13 10 26 10 0 0 0 13 73 72 68 82 0 0 0 1 0 0 0 1 8 2 0 0 0 144 119 83 222 0 0 0 16 73 68 65 84 120 156 98 218 34 180 21 16 0 0 255 255 3 1 1 126 242 54 123 184 0 0 0 0 73 69 78 68 174 66 96 130] } func BenchmarkImagePng(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ImagePng(640, 480) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ImagePng(640, 480) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ImagePng(640, 480) - } - }) + for i := 0; i < b.N; i++ { + ImagePng(640, 480) + } } diff --git a/internet.go b/internet.go index a0fcd9bb..68cf8580 100644 --- a/internet.go +++ b/internet.go @@ -2,203 +2,202 @@ package gofakeit import ( "fmt" - "math/rand" "strconv" "strings" - "github.com/brianvoe/gofakeit/v6/data" + "github.com/brianvoe/gofakeit/v7/data" ) // DomainName will generate a random url domain name -func DomainName() string { return domainName(globalFaker.Rand) } +func DomainName() string { return domainName(GlobalFaker) } // DomainName will generate a random url domain name -func (f *Faker) DomainName() string { return domainName(f.Rand) } +func (f *Faker) DomainName() string { return domainName(f) } -func domainName(r *rand.Rand) string { - name := strings.Replace(strings.ToLower(jobDescriptor(r)+bs(r)), " ", "", -1) +func domainName(f *Faker) string { + name := strings.Replace(strings.ToLower(jobDescriptor(f)+bs(f)), " ", "", -1) - return fmt.Sprintf("%s.%s", name, domainSuffix(r)) + return fmt.Sprintf("%s.%s", name, domainSuffix(f)) } // DomainSuffix will generate a random domain suffix -func DomainSuffix() string { return domainSuffix(globalFaker.Rand) } +func DomainSuffix() string { return domainSuffix(GlobalFaker) } // DomainSuffix will generate a random domain suffix -func (f *Faker) DomainSuffix() string { return domainSuffix(f.Rand) } +func (f *Faker) DomainSuffix() string { return domainSuffix(f) } -func domainSuffix(r *rand.Rand) string { - return getRandValue(r, []string{"internet", "domain_suffix"}) +func domainSuffix(f *Faker) string { + return getRandValue(f, []string{"internet", "domain_suffix"}) } // URL will generate a random url string -func URL() string { return url(globalFaker.Rand) } +func URL() string { return url(GlobalFaker) } // URL will generate a random url string -func (f *Faker) URL() string { return url(f.Rand) } +func (f *Faker) URL() string { return url(f) } -func url(r *rand.Rand) string { +func url(f *Faker) string { // Slugs - num := number(r, 1, 4) + num := number(f, 1, 4) slug := make([]string, num) for i := 0; i < num; i++ { - slug[i] = bs(r) + slug[i] = bs(f) } - scheme := randomString(r, []string{"https", "http"}) + scheme := randomString(f, []string{"https", "http"}) path := strings.ToLower(strings.Join(slug, "/")) - url := fmt.Sprintf("%s://www.%s/%s", scheme, domainName(r), path) + url := fmt.Sprintf("%s://www.%s/%s", scheme, domainName(f), path) url = strings.Replace(url, " ", "", -1) return url } // HTTPMethod will generate a random http method -func HTTPMethod() string { return httpMethod(globalFaker.Rand) } +func HTTPMethod() string { return httpMethod(GlobalFaker) } // HTTPMethod will generate a random http method -func (f *Faker) HTTPMethod() string { return httpMethod(f.Rand) } +func (f *Faker) HTTPMethod() string { return httpMethod(f) } -func httpMethod(r *rand.Rand) string { - return getRandValue(r, []string{"internet", "http_method"}) +func httpMethod(f *Faker) string { + return getRandValue(f, []string{"internet", "http_method"}) } // IPv4Address will generate a random version 4 ip address -func IPv4Address() string { return ipv4Address(globalFaker.Rand) } +func IPv4Address() string { return ipv4Address(GlobalFaker) } // IPv4Address will generate a random version 4 ip address -func (f *Faker) IPv4Address() string { return ipv4Address(f.Rand) } +func (f *Faker) IPv4Address() string { return ipv4Address(f) } -func ipv4Address(r *rand.Rand) string { - num := func() int { return r.Intn(256) } +func ipv4Address(f *Faker) string { + num := func() int { return f.IntN(256) } return fmt.Sprintf("%d.%d.%d.%d", num(), num(), num(), num()) } // IPv6Address will generate a random version 6 ip address -func IPv6Address() string { return ipv6Address(globalFaker.Rand) } +func IPv6Address() string { return ipv6Address(GlobalFaker) } // IPv6Address will generate a random version 6 ip address -func (f *Faker) IPv6Address() string { return ipv6Address(f.Rand) } +func (f *Faker) IPv6Address() string { return ipv6Address(f) } -func ipv6Address(r *rand.Rand) string { - num := func() int { return r.Intn(65536) } +func ipv6Address(f *Faker) string { + num := func() int { return f.IntN(65536) } return fmt.Sprintf("%x:%x:%x:%x:%x:%x:%x:%x", num(), num(), num(), num(), num(), num(), num(), num()) } // MacAddress will generate a random mac address -func MacAddress() string { return macAddress(globalFaker.Rand) } +func MacAddress() string { return macAddress(GlobalFaker) } // MacAddress will generate a random mac address -func (f *Faker) MacAddress() string { return macAddress(f.Rand) } +func (f *Faker) MacAddress() string { return macAddress(f) } -func macAddress(r *rand.Rand) string { +func macAddress(f *Faker) string { num := 255 - return fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x", r.Intn(num), r.Intn(num), r.Intn(num), r.Intn(num), r.Intn(num), r.Intn(num)) + return fmt.Sprintf("%02x:%02x:%02x:%02x:%02x:%02x", f.IntN(num), f.IntN(num), f.IntN(num), f.IntN(num), f.IntN(num), f.IntN(num)) } // HTTPStatusCode will generate a random status code -func HTTPStatusCode() int { return httpStatusCode(globalFaker.Rand) } +func HTTPStatusCode() int { return httpStatusCode(GlobalFaker) } // HTTPStatusCode will generate a random status code -func (f *Faker) HTTPStatusCode() int { return httpStatusCode(f.Rand) } +func (f *Faker) HTTPStatusCode() int { return httpStatusCode(f) } -func httpStatusCode(r *rand.Rand) int { - randInt, _ := strconv.Atoi(getRandValue(r, []string{"internet", "http_status_general"})) +func httpStatusCode(f *Faker) int { + randInt, _ := strconv.Atoi(getRandValue(f, []string{"internet", "http_status_general"})) return randInt } // HTTPStatusCodeSimple will generate a random simple status code -func HTTPStatusCodeSimple() int { return httpStatusCodeSimple(globalFaker.Rand) } +func HTTPStatusCodeSimple() int { return httpStatusCodeSimple(GlobalFaker) } // HTTPStatusCodeSimple will generate a random simple status code -func (f *Faker) HTTPStatusCodeSimple() int { return httpStatusCodeSimple(f.Rand) } +func (f *Faker) HTTPStatusCodeSimple() int { return httpStatusCodeSimple(f) } -func httpStatusCodeSimple(r *rand.Rand) int { - randInt, _ := strconv.Atoi(getRandValue(r, []string{"internet", "http_status_simple"})) +func httpStatusCodeSimple(f *Faker) int { + randInt, _ := strconv.Atoi(getRandValue(f, []string{"internet", "http_status_simple"})) return randInt } // LogLevel will generate a random log level // See data/LogLevels for list of available levels -func LogLevel(logType string) string { return logLevel(globalFaker.Rand, logType) } +func LogLevel(logType string) string { return logLevel(GlobalFaker, logType) } // LogLevel will generate a random log level // See data/LogLevels for list of available levels -func (f *Faker) LogLevel(logType string) string { return logLevel(f.Rand, logType) } +func (f *Faker) LogLevel(logType string) string { return logLevel(f, logType) } -func logLevel(r *rand.Rand, logType string) string { +func logLevel(f *Faker, logType string) string { if _, ok := data.LogLevels[logType]; ok { - return getRandValue(r, []string{"log_level", logType}) + return getRandValue(f, []string{"log_level", logType}) } - return getRandValue(r, []string{"log_level", "general"}) + return getRandValue(f, []string{"log_level", "general"}) } // UserAgent will generate a random broswer user agent -func UserAgent() string { return userAgent(globalFaker.Rand) } +func UserAgent() string { return userAgent(GlobalFaker) } // UserAgent will generate a random broswer user agent -func (f *Faker) UserAgent() string { return userAgent(f.Rand) } +func (f *Faker) UserAgent() string { return userAgent(f) } -func userAgent(r *rand.Rand) string { - randNum := randIntRange(r, 0, 4) +func userAgent(f *Faker) string { + randNum := randIntRange(f, 0, 4) switch randNum { case 0: - return chromeUserAgent(r) + return chromeUserAgent(f) case 1: - return firefoxUserAgent(r) + return firefoxUserAgent(f) case 2: - return safariUserAgent(r) + return safariUserAgent(f) case 3: - return operaUserAgent(r) + return operaUserAgent(f) default: - return chromeUserAgent(r) + return chromeUserAgent(f) } } // ChromeUserAgent will generate a random chrome browser user agent string -func ChromeUserAgent() string { return chromeUserAgent(globalFaker.Rand) } +func ChromeUserAgent() string { return chromeUserAgent(GlobalFaker) } // ChromeUserAgent will generate a random chrome browser user agent string -func (f *Faker) ChromeUserAgent() string { return chromeUserAgent(f.Rand) } +func (f *Faker) ChromeUserAgent() string { return chromeUserAgent(f) } -func chromeUserAgent(r *rand.Rand) string { - randNum1 := strconv.Itoa(randIntRange(r, 531, 536)) + strconv.Itoa(randIntRange(r, 0, 2)) - randNum2 := strconv.Itoa(randIntRange(r, 36, 40)) - randNum3 := strconv.Itoa(randIntRange(r, 800, 899)) - return "Mozilla/5.0 " + "(" + randomPlatform(r) + ") AppleWebKit/" + randNum1 + " (KHTML, like Gecko) Chrome/" + randNum2 + ".0." + randNum3 + ".0 Mobile Safari/" + randNum1 +func chromeUserAgent(f *Faker) string { + randNum1 := strconv.Itoa(randIntRange(f, 531, 536)) + strconv.Itoa(randIntRange(f, 0, 2)) + randNum2 := strconv.Itoa(randIntRange(f, 36, 40)) + randNum3 := strconv.Itoa(randIntRange(f, 800, 899)) + return "Mozilla/5.0 " + "(" + randomPlatform(f) + ") AppleWebKit/" + randNum1 + " (KHTML, like Gecko) Chrome/" + randNum2 + ".0." + randNum3 + ".0 Mobile Safari/" + randNum1 } // FirefoxUserAgent will generate a random firefox broswer user agent string -func FirefoxUserAgent() string { return firefoxUserAgent(globalFaker.Rand) } +func FirefoxUserAgent() string { return firefoxUserAgent(GlobalFaker) } // FirefoxUserAgent will generate a random firefox broswer user agent string -func (f *Faker) FirefoxUserAgent() string { return firefoxUserAgent(f.Rand) } +func (f *Faker) FirefoxUserAgent() string { return firefoxUserAgent(f) } -func firefoxUserAgent(r *rand.Rand) string { - ver := "Gecko/" + date(r).Format("2006-01-02") + " Firefox/" + strconv.Itoa(randIntRange(r, 35, 37)) + ".0" +func firefoxUserAgent(f *Faker) string { + ver := "Gecko/" + date(f).Format("2006-01-02") + " Firefox/" + strconv.Itoa(randIntRange(f, 35, 37)) + ".0" platforms := []string{ - "(" + windowsPlatformToken(r) + "; " + "en-US" + "; rv:1.9." + strconv.Itoa(randIntRange(r, 0, 3)) + ".20) " + ver, - "(" + linuxPlatformToken(r) + "; rv:" + strconv.Itoa(randIntRange(r, 5, 8)) + ".0) " + ver, - "(" + macPlatformToken(r) + " rv:" + strconv.Itoa(randIntRange(r, 2, 7)) + ".0) " + ver, + "(" + windowsPlatformToken(f) + "; " + "en-US" + "; rv:1.9." + strconv.Itoa(randIntRange(f, 0, 3)) + ".20) " + ver, + "(" + linuxPlatformToken(f) + "; rv:" + strconv.Itoa(randIntRange(f, 5, 8)) + ".0) " + ver, + "(" + macPlatformToken(f) + " rv:" + strconv.Itoa(randIntRange(f, 2, 7)) + ".0) " + ver, } - return "Mozilla/5.0 " + randomString(r, platforms) + return "Mozilla/5.0 " + randomString(f, platforms) } // SafariUserAgent will generate a random safari browser user agent string -func SafariUserAgent() string { return safariUserAgent(globalFaker.Rand) } +func SafariUserAgent() string { return safariUserAgent(GlobalFaker) } // SafariUserAgent will generate a random safari browser user agent string -func (f *Faker) SafariUserAgent() string { return safariUserAgent(f.Rand) } +func (f *Faker) SafariUserAgent() string { return safariUserAgent(f) } -func safariUserAgent(r *rand.Rand) string { - randNum := strconv.Itoa(randIntRange(r, 531, 536)) + "." + strconv.Itoa(randIntRange(r, 1, 51)) + "." + strconv.Itoa(randIntRange(r, 1, 8)) - ver := strconv.Itoa(randIntRange(r, 4, 6)) + "." + strconv.Itoa(randIntRange(r, 0, 2)) +func safariUserAgent(f *Faker) string { + randNum := strconv.Itoa(randIntRange(f, 531, 536)) + "." + strconv.Itoa(randIntRange(f, 1, 51)) + "." + strconv.Itoa(randIntRange(f, 1, 8)) + ver := strconv.Itoa(randIntRange(f, 4, 6)) + "." + strconv.Itoa(randIntRange(f, 0, 2)) mobileDevices := []string{ "iPhone; CPU iPhone OS", @@ -206,60 +205,60 @@ func safariUserAgent(r *rand.Rand) string { } platforms := []string{ - "(Windows; U; " + windowsPlatformToken(r) + ") AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + ver + " Safari/" + randNum, - "(" + macPlatformToken(r) + " rv:" + strconv.Itoa(randIntRange(r, 4, 7)) + ".0; en-US) AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + ver + " Safari/" + randNum, - "(" + randomString(r, mobileDevices) + " " + strconv.Itoa(randIntRange(r, 7, 9)) + "_" + strconv.Itoa(randIntRange(r, 0, 3)) + "_" + strconv.Itoa(randIntRange(r, 1, 3)) + " like Mac OS X; " + "en-US" + ") AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + strconv.Itoa(randIntRange(r, 3, 5)) + ".0.5 Mobile/8B" + strconv.Itoa(randIntRange(r, 111, 120)) + " Safari/6" + randNum, + "(Windows; U; " + windowsPlatformToken(f) + ") AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + ver + " Safari/" + randNum, + "(" + macPlatformToken(f) + " rv:" + strconv.Itoa(randIntRange(f, 4, 7)) + ".0; en-US) AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + ver + " Safari/" + randNum, + "(" + randomString(f, mobileDevices) + " " + strconv.Itoa(randIntRange(f, 7, 9)) + "_" + strconv.Itoa(randIntRange(f, 0, 3)) + "_" + strconv.Itoa(randIntRange(f, 1, 3)) + " like Mac OS X; " + "en-US" + ") AppleWebKit/" + randNum + " (KHTML, like Gecko) Version/" + strconv.Itoa(randIntRange(f, 3, 5)) + ".0.5 Mobile/8B" + strconv.Itoa(randIntRange(f, 111, 120)) + " Safari/6" + randNum, } - return "Mozilla/5.0 " + randomString(r, platforms) + return "Mozilla/5.0 " + randomString(f, platforms) } // OperaUserAgent will generate a random opera browser user agent string -func OperaUserAgent() string { return operaUserAgent(globalFaker.Rand) } +func OperaUserAgent() string { return operaUserAgent(GlobalFaker) } // OperaUserAgent will generate a random opera browser user agent string -func (f *Faker) OperaUserAgent() string { return operaUserAgent(f.Rand) } +func (f *Faker) OperaUserAgent() string { return operaUserAgent(f) } -func operaUserAgent(r *rand.Rand) string { - platform := "(" + randomPlatform(r) + "; en-US) Presto/2." + strconv.Itoa(randIntRange(r, 8, 13)) + "." + strconv.Itoa(randIntRange(r, 160, 355)) + " Version/" + strconv.Itoa(randIntRange(r, 10, 13)) + ".00" +func operaUserAgent(f *Faker) string { + platform := "(" + randomPlatform(f) + "; en-US) Presto/2." + strconv.Itoa(randIntRange(f, 8, 13)) + "." + strconv.Itoa(randIntRange(f, 160, 355)) + " Version/" + strconv.Itoa(randIntRange(f, 10, 13)) + ".00" - return "Opera/" + strconv.Itoa(randIntRange(r, 8, 10)) + "." + strconv.Itoa(randIntRange(r, 10, 99)) + " " + platform + return "Opera/" + strconv.Itoa(randIntRange(f, 8, 10)) + "." + strconv.Itoa(randIntRange(f, 10, 99)) + " " + platform } // linuxPlatformToken will generate a random linux platform -func linuxPlatformToken(r *rand.Rand) string { - return "X11; Linux " + getRandValue(r, []string{"computer", "linux_processor"}) +func linuxPlatformToken(f *Faker) string { + return "X11; Linux " + getRandValue(f, []string{"computer", "linux_processor"}) } // macPlatformToken will generate a random mac platform -func macPlatformToken(r *rand.Rand) string { - return "Macintosh; " + getRandValue(r, []string{"computer", "mac_processor"}) + " Mac OS X 10_" + strconv.Itoa(randIntRange(r, 5, 9)) + "_" + strconv.Itoa(randIntRange(r, 0, 10)) +func macPlatformToken(f *Faker) string { + return "Macintosh; " + getRandValue(f, []string{"computer", "mac_processor"}) + " Mac OS X 10_" + strconv.Itoa(randIntRange(f, 5, 9)) + "_" + strconv.Itoa(randIntRange(f, 0, 10)) } // windowsPlatformToken will generate a random windows platform -func windowsPlatformToken(r *rand.Rand) string { - return getRandValue(r, []string{"computer", "windows_platform"}) +func windowsPlatformToken(f *Faker) string { + return getRandValue(f, []string{"computer", "windows_platform"}) } // randomPlatform will generate a random platform -func randomPlatform(r *rand.Rand) string { +func randomPlatform(f *Faker) string { platforms := []string{ - linuxPlatformToken(r), - macPlatformToken(r), - windowsPlatformToken(r), + linuxPlatformToken(f), + macPlatformToken(f), + windowsPlatformToken(f), } - return randomString(r, platforms) + return randomString(f, platforms) } // HTTPVersion will generate a random http version -func HTTPVersion() string { return httpVersion(globalFaker.Rand) } +func HTTPVersion() string { return httpVersion(GlobalFaker) } // HTTPVersion will generate a random http version -func (f *Faker) HTTPVersion() string { return httpVersion(f.Rand) } +func (f *Faker) HTTPVersion() string { return httpVersion(f) } -func httpVersion(r *rand.Rand) string { - return getRandValue(r, []string{"internet", "http_version"}) +func httpVersion(f *Faker) string { + return getRandValue(f, []string{"internet", "http_version"}) } func addInternetLookup() { @@ -269,8 +268,8 @@ func addInternetLookup() { Description: "Web address that specifies the location of a resource on the internet", Example: "http://www.principalproductize.biz/target", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return url(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return url(f), nil }, }) @@ -280,8 +279,8 @@ func addInternetLookup() { Description: "Human-readable web address used to identify websites on the internet", Example: "centraltarget.biz", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return domainName(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return domainName(f), nil }, }) @@ -291,8 +290,8 @@ func addInternetLookup() { Description: "The part of a domain name that comes after the last dot, indicating its type or purpose", Example: "org", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return domainSuffix(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return domainSuffix(f), nil }, }) @@ -302,8 +301,8 @@ func addInternetLookup() { Description: "Numerical label assigned to devices on a network for identification and communication", Example: "222.83.191.222", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return ipv4Address(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return ipv4Address(f), nil }, }) @@ -313,8 +312,8 @@ func addInternetLookup() { Description: "Numerical label assigned to devices on a network, providing a larger address space than IPv4 for internet communication", Example: "2001:cafe:8898:ee17:bc35:9064:5866:d019", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return ipv6Address(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return ipv6Address(f), nil }, }) @@ -324,8 +323,8 @@ func addInternetLookup() { Description: "Verb used in HTTP requests to specify the desired action to be performed on a resource", Example: "HEAD", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return httpMethod(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return httpMethod(f), nil }, }) @@ -335,8 +334,8 @@ func addInternetLookup() { Description: "Classification used in logging to indicate the severity or priority of a log entry", Example: "error", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return logLevel(r, ""), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return logLevel(f, ""), nil }, }) @@ -346,8 +345,8 @@ func addInternetLookup() { Description: "String sent by a web browser to identify itself when requesting web content", Example: "Mozilla/5.0 (Windows NT 5.0) AppleWebKit/5362 (KHTML, like Gecko) Chrome/37.0.834.0 Mobile Safari/5362", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return userAgent(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return userAgent(f), nil }, }) @@ -357,8 +356,8 @@ func addInternetLookup() { Description: "The specific identification string sent by the Google Chrome web browser when making requests on the internet", Example: "Mozilla/5.0 (X11; Linux i686) AppleWebKit/5312 (KHTML, like Gecko) Chrome/39.0.836.0 Mobile Safari/5312", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return chromeUserAgent(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return chromeUserAgent(f), nil }, }) @@ -368,8 +367,8 @@ func addInternetLookup() { Description: "The specific identification string sent by the Firefox web browser when making requests on the internet", Example: "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_8_3 rv:7.0) Gecko/1900-07-01 Firefox/37.0", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return firefoxUserAgent(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return firefoxUserAgent(f), nil }, }) @@ -379,8 +378,8 @@ func addInternetLookup() { Description: "The specific identification string sent by the Opera web browser when making requests on the internet", Example: "Opera/8.39 (Macintosh; U; PPC Mac OS X 10_8_7; en-US) Presto/2.9.335 Version/10.00", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return operaUserAgent(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return operaUserAgent(f), nil }, }) @@ -390,8 +389,8 @@ func addInternetLookup() { Description: "The specific identification string sent by the Safari web browser when making requests on the internet", Example: "Mozilla/5.0 (iPad; CPU OS 8_3_2 like Mac OS X; en-US) AppleWebKit/531.15.6 (KHTML, like Gecko) Version/4.0.5 Mobile/8B120 Safari/6531.15.6", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return safariUserAgent(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return safariUserAgent(f), nil }, }) @@ -401,8 +400,8 @@ func addInternetLookup() { Description: "Random http status code", Example: "200", Output: "int", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return httpStatusCode(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return httpStatusCode(f), nil }, }) @@ -412,8 +411,8 @@ func addInternetLookup() { Description: "Three-digit number returned by a web server to indicate the outcome of an HTTP request", Example: "404", Output: "int", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return httpStatusCodeSimple(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return httpStatusCodeSimple(f), nil }, }) @@ -423,8 +422,8 @@ func addInternetLookup() { Description: "Number indicating the version of the HTTP protocol used for communication between a client and a server", Example: "HTTP/1.1", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return httpVersion(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return httpVersion(f), nil }, }) @@ -434,8 +433,8 @@ func addInternetLookup() { Description: "Unique identifier assigned to network interfaces, often used in Ethernet networks", Example: "cb:ce:06:94:22:e9", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return macAddress(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return macAddress(f), nil }, }) } diff --git a/internet_test.go b/internet_test.go index 217e3360..0d855efc 100644 --- a/internet_test.go +++ b/internet_test.go @@ -10,90 +10,54 @@ func ExampleDomainName() { Seed(11) fmt.Println(DomainName()) - // Output: centraltarget.biz + // Output: productinfrastructures.biz } func ExampleFaker_DomainName() { f := New(11) fmt.Println(f.DomainName()) - // Output: centraltarget.biz + // Output: productinfrastructures.biz } func BenchmarkDomainName(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - DomainName() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.DomainName() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.DomainName() - } - }) + for i := 0; i < b.N; i++ { + DomainName() + } } func ExampleDomainSuffix() { Seed(11) fmt.Println(DomainSuffix()) - // Output: org + // Output: io } func ExampleFaker_DomainSuffix() { f := New(11) fmt.Println(f.DomainSuffix()) - // Output: org + // Output: io } func BenchmarkDomainSuffix(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - DomainSuffix() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.DomainSuffix() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.DomainSuffix() - } - }) + for i := 0; i < b.N; i++ { + DomainSuffix() + } } func ExampleURL() { Seed(11) fmt.Println(URL()) - // Output: https://www.dynamiciterate.name/target/seamless + // Output: http://www.directinnovative.biz/infrastructures } func ExampleFaker_URL() { f := New(11) fmt.Println(f.URL()) - // Output: https://www.dynamiciterate.name/target/seamless + // Output: http://www.directinnovative.biz/infrastructures } func TestURLValid(t *testing.T) { @@ -108,269 +72,143 @@ func TestURLValid(t *testing.T) { } func BenchmarkURL(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - URL() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.URL() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.URL() - } - }) + for i := 0; i < b.N; i++ { + URL() + } } func ExampleHTTPMethod() { Seed(11) fmt.Println(HTTPMethod()) - // Output: HEAD + // Output: DELETE } func ExampleHTTPVersion() { Seed(11) fmt.Println(HTTPVersion()) - // Output: HTTP/1.0 + // Output: HTTP/2.0 } func ExampleFaker_HTTPMethod() { f := New(11) fmt.Println(f.HTTPMethod()) - // Output: HEAD + // Output: DELETE } func ExampleFaker_HTTPVersion() { f := New(11) fmt.Println(f.HTTPVersion()) - // Output: HTTP/1.0 + // Output: HTTP/2.0 } func BenchmarkHTTPMethod(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HTTPMethod() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HTTPMethod() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HTTPMethod() - } - }) + for i := 0; i < b.N; i++ { + HTTPMethod() + } } func ExampleIPv4Address() { Seed(11) fmt.Println(IPv4Address()) - // Output: 152.23.53.100 + // Output: 180.18.181.251 } func ExampleFaker_IPv4Address() { f := New(11) fmt.Println(f.IPv4Address()) - // Output: 152.23.53.100 + // Output: 180.18.181.251 } func BenchmarkIPv4Address(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - IPv4Address() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.IPv4Address() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.IPv4Address() - } - }) + for i := 0; i < b.N; i++ { + IPv4Address() + } } func ExampleIPv6Address() { Seed(11) fmt.Println(IPv6Address()) - // Output: 8898:ee17:bc35:9064:5866:d019:3b95:7857 + // Output: ddb4:9212:aab5:87fb:4e33:17a4:f7b9:bf8e } func ExampleFaker_IPv6Address() { f := New(11) fmt.Println(f.IPv6Address()) - // Output: 8898:ee17:bc35:9064:5866:d019:3b95:7857 + // Output: ddb4:9212:aab5:87fb:4e33:17a4:f7b9:bf8e } func BenchmarkIPv6Address(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - IPv6Address() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.IPv6Address() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.IPv6Address() - } - }) + for i := 0; i < b.N; i++ { + IPv6Address() + } } func ExampleMacAddress() { Seed(11) fmt.Println(MacAddress()) - // Output: e1:74:cb:01:77:91 + // Output: e4:da:32:33:86:3b } func ExampleFaker_MacAddress() { f := New(11) fmt.Println(f.MacAddress()) - // Output: e1:74:cb:01:77:91 + // Output: e4:da:32:33:86:3b } func BenchmarkMacAddress(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MacAddress() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MacAddress() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MacAddress() - } - }) + for i := 0; i < b.N; i++ { + MacAddress() + } } func ExampleHTTPStatusCode() { Seed(11) fmt.Println(HTTPStatusCode()) - // Output: 404 + // Output: 502 } func ExampleFaker_HTTPStatusCode() { f := New(11) fmt.Println(f.HTTPStatusCode()) - // Output: 404 + // Output: 502 } func BenchmarkHTTPStatusCode(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HTTPStatusCode() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HTTPStatusCode() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HTTPStatusCode() - } - }) + for i := 0; i < b.N; i++ { + HTTPStatusCode() + } } func ExampleHTTPStatusCodeSimple() { Seed(11) fmt.Println(HTTPStatusCodeSimple()) - // Output: 200 + // Output: 500 } func ExampleFaker_HTTPStatusCodeSimple() { f := New(11) fmt.Println(f.HTTPStatusCodeSimple()) - // Output: 200 + // Output: 500 } func BenchmarkHTTPStatusCodeSimple(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HTTPStatusCodeSimple() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HTTPStatusCodeSimple() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HTTPStatusCodeSimple() - } - }) + for i := 0; i < b.N; i++ { + HTTPStatusCodeSimple() + } } func ExampleLogLevel() { @@ -379,9 +217,9 @@ func ExampleLogLevel() { fmt.Println(LogLevel("syslog")) fmt.Println(LogLevel("apache")) - // Output: error - // debug - // trace1-8 + // Output: debug + // crit + // alert } func ExampleFaker_LogLevel() { @@ -390,71 +228,35 @@ func ExampleFaker_LogLevel() { fmt.Println(f.LogLevel("syslog")) fmt.Println(f.LogLevel("apache")) - // Output: error - // debug - // trace1-8 + // Output: debug + // crit + // alert } func BenchmarkLogLevel(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - LogLevel("general") - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.LogLevel("general") - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.LogLevel("general") - } - }) + for i := 0; i < b.N; i++ { + LogLevel("general") + } } func ExampleUserAgent() { Seed(11) fmt.Println(UserAgent()) - // Output: Mozilla/5.0 (Windows NT 5.0) AppleWebKit/5312 (KHTML, like Gecko) Chrome/40.0.800.0 Mobile Safari/5312 + // Output: Mozilla/5.0 (Windows 98) AppleWebKit/5360 (KHTML, like Gecko) Chrome/37.0.852.0 Mobile Safari/5360 } func ExampleFaker_UserAgent() { f := New(11) fmt.Println(f.UserAgent()) - // Output: Mozilla/5.0 (Windows NT 5.0) AppleWebKit/5312 (KHTML, like Gecko) Chrome/40.0.800.0 Mobile Safari/5312 + // Output: Mozilla/5.0 (Windows 98) AppleWebKit/5360 (KHTML, like Gecko) Chrome/37.0.852.0 Mobile Safari/5360 } func BenchmarkUserAgent(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - UserAgent() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.UserAgent() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.UserAgent() - } - }) + for i := 0; i < b.N; i++ { + UserAgent() + } } func TestUserAgent(t *testing.T) { @@ -467,150 +269,78 @@ func ExampleChromeUserAgent() { Seed(11) fmt.Println(ChromeUserAgent()) - // Output: Mozilla/5.0 (X11; Linux i686) AppleWebKit/5360 (KHTML, like Gecko) Chrome/40.0.889.0 Mobile Safari/5360 + // Output: Mozilla/5.0 (Windows CE) AppleWebKit/5362 (KHTML, like Gecko) Chrome/36.0.820.0 Mobile Safari/5362 } func ExampleFaker_ChromeUserAgent() { f := New(11) fmt.Println(f.ChromeUserAgent()) - // Output: Mozilla/5.0 (X11; Linux i686) AppleWebKit/5360 (KHTML, like Gecko) Chrome/40.0.889.0 Mobile Safari/5360 + // Output: Mozilla/5.0 (Windows CE) AppleWebKit/5362 (KHTML, like Gecko) Chrome/36.0.820.0 Mobile Safari/5362 } func BenchmarkChromeUserAgent(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ChromeUserAgent() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ChromeUserAgent() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ChromeUserAgent() - } - }) + for i := 0; i < b.N; i++ { + ChromeUserAgent() + } } func ExampleFirefoxUserAgent() { Seed(11) fmt.Println(FirefoxUserAgent()) - // Output: Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_9_10 rv:7.0) Gecko/1915-01-24 Firefox/36.0 + // Output: Mozilla/5.0 (Windows CE; en-US; rv:1.9.3.20) Gecko/2011-11-07 Firefox/36.0 } func ExampleFaker_FirefoxUserAgent() { f := New(11) fmt.Println(f.FirefoxUserAgent()) - // Output: Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_9_10 rv:7.0) Gecko/1915-01-24 Firefox/36.0 + // Output: Mozilla/5.0 (Windows CE; en-US; rv:1.9.3.20) Gecko/2011-11-07 Firefox/36.0 } func BenchmarkFirefoxUserAgent(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - FirefoxUserAgent() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.FirefoxUserAgent() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.FirefoxUserAgent() - } - }) + for i := 0; i < b.N; i++ { + FirefoxUserAgent() + } } func ExampleSafariUserAgent() { Seed(11) fmt.Println(SafariUserAgent()) - // Output: Mozilla/5.0 (iPad; CPU OS 7_0_2 like Mac OS X; en-US) AppleWebKit/536.4.4 (KHTML, like Gecko) Version/3.0.5 Mobile/8B120 Safari/6536.4.4 + // Output: Mozilla/5.0 (Windows; U; Windows NT 6.0) AppleWebKit/536.44.6 (KHTML, like Gecko) Version/4.1 Safari/536.44.6 } func ExampleFaker_SafariUserAgent() { f := New(11) fmt.Println(f.SafariUserAgent()) - // Output: Mozilla/5.0 (iPad; CPU OS 7_0_2 like Mac OS X; en-US) AppleWebKit/536.4.4 (KHTML, like Gecko) Version/3.0.5 Mobile/8B120 Safari/6536.4.4 + // Output: Mozilla/5.0 (Windows; U; Windows NT 6.0) AppleWebKit/536.44.6 (KHTML, like Gecko) Version/4.1 Safari/536.44.6 } func BenchmarkSafariUserAgent(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - SafariUserAgent() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.SafariUserAgent() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.SafariUserAgent() - } - }) + for i := 0; i < b.N; i++ { + SafariUserAgent() + } } func ExampleOperaUserAgent() { Seed(11) fmt.Println(OperaUserAgent()) - // Output: Opera/8.20 (Macintosh; U; PPC Mac OS X 10_9_10; en-US) Presto/2.9.198 Version/11.00 + // Output: Opera/10.91 (X11; Linux i686; en-US) Presto/2.12.265 Version/11.00 } func ExampleFaker_OperaUserAgent() { f := New(11) fmt.Println(f.OperaUserAgent()) - // Output: Opera/8.20 (Macintosh; U; PPC Mac OS X 10_9_10; en-US) Presto/2.9.198 Version/11.00 + // Output: Opera/10.91 (X11; Linux i686; en-US) Presto/2.12.265 Version/11.00 } func BenchmarkOperaUserAgent(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - OperaUserAgent() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.OperaUserAgent() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.OperaUserAgent() - } - }) + for i := 0; i < b.N; i++ { + OperaUserAgent() + } } diff --git a/json.go b/json.go index 8edf5b45..814f1300 100644 --- a/json.go +++ b/json.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "math/rand" "reflect" "strconv" ) @@ -59,7 +58,7 @@ func (okv jsonOrderedKeyVal) MarshalJSON() ([]byte, error) { // JSON generates an object or an array of objects in json format. // A nil JSONOptions returns a randomly structured JSON. -func JSON(jo *JSONOptions) ([]byte, error) { return jsonFunc(globalFaker, jo) } +func JSON(jo *JSONOptions) ([]byte, error) { return jsonFunc(GlobalFaker, jo) } // JSON generates an object or an array of objects in json format. // A nil JSONOptions returns a randomly structured JSON. @@ -102,7 +101,7 @@ func jsonFunc(f *Faker, jo *JSONOptions) ([]byte, error) { } // Call function value - value, err := funcInfo.Generate(f.Rand, &field.Params, funcInfo) + value, err := funcInfo.Generate(f, &field.Params, funcInfo) if err != nil { return nil, err } @@ -156,7 +155,7 @@ func jsonFunc(f *Faker, jo *JSONOptions) ([]byte, error) { } // Call function value - value, err := funcInfo.Generate(f.Rand, &field.Params, funcInfo) + value, err := funcInfo.Generate(f, &field.Params, funcInfo) if err != nil { return nil, err } @@ -208,7 +207,7 @@ func addFileJSONLookup() { {Field: "indent", Display: "Indent", Type: "bool", Default: "false", Description: "Whether or not to add indents and newlines"}, {Field: "fields", Display: "Fields", Type: "[]Field", Description: "Fields containing key name and function to run in json format"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { jo := JSONOptions{} typ, err := info.GetString(m, "type") @@ -247,7 +246,6 @@ func addFileJSONLookup() { } } - f := &Faker{Rand: r} return jsonFunc(f, &jo) }, }) @@ -296,7 +294,7 @@ func rJsonNumber(f *Faker, t reflect.Type, v reflect.Value, tag string, size int // Parse map params mapParams := parseMapParams(info, fParams) - valueIface, err := info.Generate(f.Rand, mapParams, info) + valueIface, err := info.Generate(f, mapParams, info) if err != nil { return err } diff --git a/json_test.go b/json_test.go index 4324dfc0..5a2bcb01 100644 --- a/json_test.go +++ b/json_test.go @@ -26,19 +26,19 @@ func ExampleJSON_object() { fmt.Println(string(value)) // Output: { - // "first_name": "Markus", - // "last_name": "Moen", + // "first_name": "Sonny", + // "last_name": "Stiedemann", // "address": { - // "address": "4599 Daleton, Norfolk, New Jersey 36906", - // "street": "4599 Daleton", - // "city": "Norfolk", - // "state": "New Jersey", - // "zip": "36906", - // "country": "Tokelau", - // "latitude": 23.058758, - // "longitude": 89.022594 + // "address": "52759 Stationside, San Diego, Oregon 99344", + // "street": "52759 Stationside", + // "city": "San Diego", + // "state": "Oregon", + // "zip": "99344", + // "country": "Saint Pierre and Miquelon", + // "latitude": -30.009814, + // "longitude": 154.519771 // }, - // "password": "myZ1PgF9ThVL" + // "password": "l4338TebFL55" // } } @@ -62,19 +62,19 @@ func ExampleFaker_JSON_object() { fmt.Println(string(value)) // Output: { - // "first_name": "Markus", - // "last_name": "Moen", + // "first_name": "Sonny", + // "last_name": "Stiedemann", // "address": { - // "address": "4599 Daleton, Norfolk, New Jersey 36906", - // "street": "4599 Daleton", - // "city": "Norfolk", - // "state": "New Jersey", - // "zip": "36906", - // "country": "Tokelau", - // "latitude": 23.058758, - // "longitude": 89.022594 + // "address": "52759 Stationside, San Diego, Oregon 99344", + // "street": "52759 Stationside", + // "city": "San Diego", + // "state": "Oregon", + // "zip": "99344", + // "country": "Saint Pierre and Miquelon", + // "latitude": -30.009814, + // "longitude": 154.519771 // }, - // "password": "myZ1PgF9ThVL" + // "password": "l4338TebFL55" // } } @@ -101,21 +101,21 @@ func ExampleJSON_array() { // Output: [ // { // "id": 1, - // "first_name": "Markus", - // "last_name": "Moen", - // "password": "856Y5wPZevX9" + // "first_name": "Sonny", + // "last_name": "Stiedemann", + // "password": "8nwf0o3sBXcR" // }, // { // "id": 2, - // "first_name": "Jalon", - // "last_name": "Rolfson", - // "password": "64wz4EAS0Hl0" + // "first_name": "Verda", + // "last_name": "Brakus", + // "password": "3beWLpq75Lua" // }, // { // "id": 3, - // "first_name": "Nestor", - // "last_name": "Harris", - // "password": "14GKq1j7Lx4T" + // "first_name": "Jules", + // "last_name": "Cremin", + // "password": "Uu38J14Y8W82" // } // ] } @@ -143,21 +143,21 @@ func ExampleFaker_JSON_array() { // Output: [ // { // "id": 1, - // "first_name": "Markus", - // "last_name": "Moen", - // "password": "856Y5wPZevX9" + // "first_name": "Sonny", + // "last_name": "Stiedemann", + // "password": "8nwf0o3sBXcR" // }, // { // "id": 2, - // "first_name": "Jalon", - // "last_name": "Rolfson", - // "password": "64wz4EAS0Hl0" + // "first_name": "Verda", + // "last_name": "Brakus", + // "password": "3beWLpq75Lua" // }, // { // "id": 3, - // "first_name": "Nestor", - // "last_name": "Harris", - // "password": "14GKq1j7Lx4T" + // "first_name": "Jules", + // "last_name": "Cremin", + // "password": "Uu38J14Y8W82" // } // ] } @@ -173,7 +173,7 @@ func TestJSONLookup(t *testing.T) { m.Add("fields", `{"name":"first_name","function":"firstname"}`) m.Add("fields", `{"name":"password","function":"password","params":{"special":["false"],"length":["20"]}}`) - _, err := info.Generate(faker.Rand, m, info) + _, err := info.Generate(faker, m, info) if err != nil { t.Fatal(err.Error()) } @@ -199,7 +199,7 @@ func TestJSONObjectLookupWithSubJSON(t *testing.T) { } }`) - output, err := info.Generate(faker.Rand, m, info) + output, err := info.Generate(faker, m, info) if err != nil { t.Fatal(err.Error()) } @@ -223,17 +223,17 @@ func TestJSONObjectLookupWithSubJSON(t *testing.T) { } // check that the output values are correct - if j.JStruct.ID != 1 { + if j.JStruct.ID == 0 { t.Fatalf("ID is not 1 got: %v", j.JStruct.ID) } - if j.JStruct.FirstName != "Markus" { - t.Errorf("FirstName is incorrect got: %s", j.JStruct.FirstName) + if j.JStruct.FirstName == "" { + t.Errorf("FirstName is empty") } - if j.JStruct.LastName != "Moen" { - t.Errorf("LastName is incorrect got: %s", j.JStruct.LastName) + if j.JStruct.LastName == "" { + t.Errorf("LastName is empty") } - if j.JStruct.Password != "zPlYvZw9E8e49H5X6X5l" { - t.Errorf("Password is incorrect got: %s", j.JStruct.Password) + if j.JStruct.Password == "" { + t.Errorf("Password is empty") } } @@ -259,7 +259,7 @@ func TestJSONArrayLookupWithSubJSON(t *testing.T) { } }`) - output, err := info.Generate(faker.Rand, m, info) + output, err := info.Generate(faker, m, info) if err != nil { t.Fatal(err.Error()) } @@ -278,31 +278,32 @@ func TestJSONArrayLookupWithSubJSON(t *testing.T) { } var j jsonParent + err = json.Unmarshal(output.([]byte), &j) if err != nil { t.Fatal(err.Error()) } // Check row count - if len(j.JStruct) != 10 { + if len(j.JStruct) == 0 { t.Fatalf("Row count is not 10 got: %v", len(j.JStruct)) } // check that the output values are correct - if j.JStruct[0].ID != 1 { - t.Fatalf("ID is incorrect should be 1 got: %v", j.JStruct[0].ID) + if j.JStruct[0].ID == 0 { + t.Fatalf("ID is empty") } - if j.JStruct[0].FirstName != "Markus" { - t.Errorf("FirstName is incorrect got: %s", j.JStruct[0].FirstName) + if j.JStruct[0].FirstName == "" { + t.Errorf("FirstName is empty") } - if j.JStruct[0].LastName != "Moen" { - t.Errorf("LastName is incorrect got: %s", j.JStruct[0].LastName) + if j.JStruct[0].LastName == "" { + t.Errorf("LastName is empty") } - if j.JStruct[0].Password != "zPlYvZw9E8e49H5X6X5l" { - t.Errorf("Password is incorrect got: %s", j.JStruct[0].Password) + if j.JStruct[0].Password == "" { + t.Errorf("Password is empty") } - if j.JStruct[0].Address.City != "Santa Ana" { - t.Errorf("City is incorrect got: %s", j.JStruct[0].Address.City) + if j.JStruct[0].Address.City == "" { + t.Errorf("City is empty") } } @@ -367,7 +368,7 @@ func TestJSONRawMessage(t *testing.T) { Field json.RawMessage `json:"field"` } - Seed(100) + Seed(11) var objs []J Slice(&objs) @@ -383,7 +384,7 @@ func TestJSONRawMessageWithTag(t *testing.T) { Field json.RawMessage `json:"field" faker:"json"` } - Seed(100) + Seed(11) var objs []J Slice(&objs) @@ -399,7 +400,7 @@ func TestJSONNumber(t *testing.T) { Field json.Number `json:"field"` } - Seed(100) + Seed(11) var objs []J Slice(&objs) @@ -415,7 +416,7 @@ func TestJSONNumberWithTag(t *testing.T) { Field json.Number `json:"field" fake:"number:3,7"` } - Seed(100) + Seed(11) var objs []J Slice(&objs) @@ -435,7 +436,7 @@ func TestJSONNumberWithTag(t *testing.T) { } func ExampleJSON_numberWithTag() { - Seed(10) + Seed(11) type J struct { FieldNumber json.Number `fake:"number:3,7"` @@ -466,18 +467,17 @@ func ExampleJSON_numberWithTag() { fmt.Printf("obj.FieldFloat32 = %+v\n", obj.FieldFloat32) fmt.Printf("obj.FieldFloat64 = %+v\n", obj.FieldFloat64) - // Output: - // obj.FieldNumber = 3 - // obj.FieldInt8 = 16 - // obj.FieldInt16 = 10619 - // obj.FieldInt32 = -1654523813 - // obj.FieldInt64 = -4710905755560118665 - // obj.FieldUint8 = 200 - // obj.FieldUint16 = 28555 - // obj.FieldUint32 = 162876094 - // obj.FieldUint64 = 7956601014869229133 - // obj.FieldFloat32 = 9227009415507442000000000000000000000 - // obj.FieldFloat64 = 62.323882731848215 + // Output: obj.FieldNumber = 7 + // obj.FieldInt8 = -110 + // obj.FieldInt16 = 10933 + // obj.FieldInt32 = 430103905 + // obj.FieldInt64 = 525217394518216243 + // obj.FieldUint8 = 164 + // obj.FieldUint16 = 63417 + // obj.FieldUint32 = 2307233133 + // obj.FieldUint64 = 17560678512042153749 + // obj.FieldFloat32 = 0.11857688426971436 + // obj.FieldFloat64 = 51.03971481390635 } func BenchmarkJSONLookup100(b *testing.B) { @@ -496,79 +496,7 @@ func BenchmarkJSONLookup100(b *testing.B) { m.Add("fields", `{"name":"description","function":"paragraph"}`) m.Add("fields", `{"name":"created_at","function":"date"}`) - _, err := info.Generate(faker.Rand, m, info) - if err != nil { - b.Fatal(err.Error()) - } - } -} - -func BenchmarkJSONLookup1000(b *testing.B) { - faker := New(0) - - for i := 0; i < b.N; i++ { - info := GetFuncLookup("json") - m := MapParams{ - "type": {"array"}, - "rowcount": {"1000"}, - "fields": { - `{"name":"id","function":"autoincrement"}`, - `{"name":"first_name","function":"firstname"}`, - `{"name":"last_name","function":"lastname"}`, - `{"name":"password","function":"password"}`, - `{"name":"description","function":"paragraph"}`, - `{"name":"created_at","function":"date"}`, - }, - } - _, err := info.Generate(faker.Rand, &m, info) - if err != nil { - b.Fatal(err.Error()) - } - } -} - -func BenchmarkJSONLookup10000(b *testing.B) { - faker := New(0) - - for i := 0; i < b.N; i++ { - info := GetFuncLookup("json") - m := MapParams{ - "type": {"array"}, - "rowcount": {"10000"}, - "fields": { - `{"name":"id","function":"autoincrement"}`, - `{"name":"first_name","function":"firstname"}`, - `{"name":"last_name","function":"lastname"}`, - `{"name":"password","function":"password"}`, - `{"name":"description","function":"paragraph"}`, - `{"name":"created_at","function":"date"}`, - }, - } - _, err := info.Generate(faker.Rand, &m, info) - if err != nil { - b.Fatal(err.Error()) - } - } -} - -func BenchmarkJSONLookup100000(b *testing.B) { - faker := New(0) - - for i := 0; i < b.N; i++ { - info := GetFuncLookup("json") - m := MapParams{ - "type": {"array"}, - "rowcount": {"100000"}, - "fields": { - `{"name":"id","function":"autoincrement"}`, - `{"name":"first_name","function":"firstname"}`, - `{"name":"last_name","function":"lastname"}`, - `{"name":"password","function":"password"}`, - `{"name":"description","function":"paragraph"}`, - `{"name":"created_at","function":"date"}`, - }, - } - _, err := info.Generate(faker.Rand, &m, info) + _, err := info.Generate(faker, m, info) if err != nil { b.Fatal(err.Error()) } diff --git a/languages.go b/languages.go index 43e0b877..5ac0db80 100644 --- a/languages.go +++ b/languages.go @@ -1,49 +1,39 @@ package gofakeit -import "math/rand" - // Language will return a random language -func Language() string { return language(globalFaker.Rand) } +func Language() string { return language(GlobalFaker) } // Language will return a random language -func (f *Faker) Language() string { return language(f.Rand) } +func (f *Faker) Language() string { return language(f) } -func language(r *rand.Rand) string { return getRandValue(r, []string{"language", "long"}) } +func language(f *Faker) string { return getRandValue(f, []string{"language", "long"}) } // LanguageAbbreviation will return a random language abbreviation -func LanguageAbbreviation() string { return languageAbbreviation(globalFaker.Rand) } +func LanguageAbbreviation() string { return languageAbbreviation(GlobalFaker) } // LanguageAbbreviation will return a random language abbreviation -func (f *Faker) LanguageAbbreviation() string { return languageAbbreviation(f.Rand) } +func (f *Faker) LanguageAbbreviation() string { return languageAbbreviation(f) } -func languageAbbreviation(r *rand.Rand) string { return getRandValue(r, []string{"language", "short"}) } +func languageAbbreviation(f *Faker) string { return getRandValue(f, []string{"language", "short"}) } // LanguageBCP will return a random language BCP (Best Current Practices) -func LanguageBCP() string { return languageBCP(globalFaker.Rand) } +func LanguageBCP() string { return languageBCP(GlobalFaker) } // LanguageBCP will return a random language BCP (Best Current Practices) -func (f *Faker) LanguageBCP() string { return languageBCP(f.Rand) } +func (f *Faker) LanguageBCP() string { return languageBCP(f) } -func languageBCP(r *rand.Rand) string { return getRandValue(r, []string{"language", "bcp"}) } +func languageBCP(f *Faker) string { return getRandValue(f, []string{"language", "bcp"}) } // ProgrammingLanguage will return a random programming language -func ProgrammingLanguage() string { return programmingLanguage(globalFaker.Rand) } +func ProgrammingLanguage() string { return programmingLanguage(GlobalFaker) } // ProgrammingLanguage will return a random programming language -func (f *Faker) ProgrammingLanguage() string { return programmingLanguage(f.Rand) } +func (f *Faker) ProgrammingLanguage() string { return programmingLanguage(f) } -func programmingLanguage(r *rand.Rand) string { - return getRandValue(r, []string{"language", "programming"}) +func programmingLanguage(f *Faker) string { + return getRandValue(f, []string{"language", "programming"}) } -// ProgrammingLanguageBest will return a random programming language -func ProgrammingLanguageBest() string { return programmingLanguageBest(globalFaker.Rand) } - -// ProgrammingLanguageBest will return a random programming language -func (f *Faker) ProgrammingLanguageBest() string { return programmingLanguageBest(f.Rand) } - -func programmingLanguageBest(r *rand.Rand) string { return "Go" } - func addLanguagesLookup() { AddFuncLookup("language", Info{ Display: "Language", @@ -51,8 +41,8 @@ func addLanguagesLookup() { Description: "System of communication using symbols, words, and grammar to convey meaning between individuals", Example: "Kazakh", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return language(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return language(f), nil }, }) @@ -62,8 +52,8 @@ func addLanguagesLookup() { Description: "Shortened form of a language's name", Example: "kk", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return languageAbbreviation(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return languageAbbreviation(f), nil }, }) @@ -73,8 +63,8 @@ func addLanguagesLookup() { Description: "Set of guidelines and standards for identifying and representing languages in computing and internet protocols", Example: "en-US", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return languageBCP(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return languageBCP(f), nil }, }) @@ -84,8 +74,8 @@ func addLanguagesLookup() { Description: "Formal system of instructions used to create software and perform computational tasks", Example: "Go", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return programmingLanguage(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return programmingLanguage(f), nil }, }) } diff --git a/languages_test.go b/languages_test.go index cbb3f97d..763362a3 100644 --- a/languages_test.go +++ b/languages_test.go @@ -9,188 +9,78 @@ func ExampleLanguage() { Seed(11) fmt.Println(Language()) - // Output: Kazakh + // Output: Turkish } func ExampleFaker_Language() { f := New(11) fmt.Println(f.Language()) - // Output: Kazakh + // Output: Turkish } func BenchmarkLanguage(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Language() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Language() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Language() - } - }) + for i := 0; i < b.N; i++ { + Language() + } } func ExampleLanguageAbbreviation() { Seed(11) fmt.Println(LanguageAbbreviation()) - // Output: kk + // Output: tr } func ExampleFaker_LanguageAbbreviation() { f := New(11) fmt.Println(f.LanguageAbbreviation()) - // Output: kk + // Output: tr } func BenchmarkLanguageAbbreviation(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - LanguageAbbreviation() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.LanguageAbbreviation() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.LanguageAbbreviation() - } - }) + for i := 0; i < b.N; i++ { + LanguageAbbreviation() + } } func ExampleLanguageBCP() { Seed(11) fmt.Println(LanguageBCP()) - // Output: de-DE + // Output: tr-TR } func ExampleFaker_LanguageBCP() { f := New(11) fmt.Println(f.LanguageBCP()) - // Output: de-DE + // Output: tr-TR } func BenchmarkLanguageBCP(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - LanguageBCP() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.LanguageBCP() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.LanguageBCP() - } - }) + for i := 0; i < b.N; i++ { + LanguageBCP() + } } func ExampleProgrammingLanguage() { - Seed(464) + Seed(11) fmt.Println(ProgrammingLanguage()) - // Output: Go + // Output: TELCOMP } func ExampleFaker_ProgrammingLanguage() { - f := New(464) + f := New(11) fmt.Println(f.ProgrammingLanguage()) - // Output: Go + // Output: TELCOMP } func BenchmarkProgrammingLanguage(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ProgrammingLanguage() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ProgrammingLanguage() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ProgrammingLanguage() - } - }) -} - -func ExampleProgrammingLanguageBest() { - Seed(11) - fmt.Println(ProgrammingLanguageBest()) - - // Output: Go -} - -func ExampleFaker_ProgrammingLanguageBest() { - f := New(11) - fmt.Println(f.ProgrammingLanguageBest()) - - // Output: Go -} - -func BenchmarkProgrammingLanguageBest(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ProgrammingLanguageBest() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ProgrammingLanguageBest() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ProgrammingLanguageBest() - } - }) + for i := 0; i < b.N; i++ { + ProgrammingLanguage() + } } diff --git a/lookup.go b/lookup.go index 9bb9e9d8..ea96ac6f 100644 --- a/lookup.go +++ b/lookup.go @@ -3,7 +3,6 @@ package gofakeit import ( "encoding/json" "fmt" - "math/rand" "reflect" "strconv" "strings" @@ -21,15 +20,15 @@ type MapParamsValue []string // Info structures fields to better break down what each one generates type Info struct { - Display string `json:"display"` - Category string `json:"category"` - Description string `json:"description"` - Example string `json:"example"` - Output string `json:"output"` - ContentType string `json:"content_type"` - Params []Param `json:"params"` - Any any `json:"any"` - Generate func(r *rand.Rand, m *MapParams, info *Info) (any, error) `json:"-"` + Display string `json:"display"` + Category string `json:"category"` + Description string `json:"description"` + Example string `json:"example"` + Output string `json:"output"` + ContentType string `json:"content_type"` + Params []Param `json:"params"` + Any any `json:"any"` + Generate func(f *Faker, m *MapParams, info *Info) (any, error) `json:"-"` } // Param is a breakdown of param requirements and type definition @@ -114,8 +113,8 @@ var internalFuncLookups map[string]Info = map[string]Info{ "fields": { Description: "Example fields for generating csv, json, xml, etc", Output: "gofakeit.Field", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - function, _ := GetRandomSimpleFunc(r) + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + function, _ := GetRandomSimpleFunc(f) return Field{ Name: function, Function: function, @@ -192,7 +191,7 @@ func (m *MapParamsValue) UnmarshalJSON(data []byte) error { return nil } -func GetRandomSimpleFunc(r *rand.Rand) (string, Info) { +func GetRandomSimpleFunc(f *Faker) (string, Info) { // Loop through all the functions and add them to a slice var keys []string for k, info := range FuncLookups { @@ -203,7 +202,7 @@ func GetRandomSimpleFunc(r *rand.Rand) (string, Info) { } // Randomly grab a function from the slice - randomKey := randomString(r, keys) + randomKey := randomString(f, keys) // Return the function name and info return randomKey, FuncLookups[randomKey] diff --git a/lookup_test.go b/lookup_test.go index 48d5f62f..4ef71591 100644 --- a/lookup_test.go +++ b/lookup_test.go @@ -3,7 +3,7 @@ package gofakeit import ( "encoding/json" "fmt" - "math/rand" + "math/rand/v2" "strings" "testing" ) @@ -16,7 +16,7 @@ func Example_custom() { Description: "Random friend name", Example: "bill", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { return RandomString([]string{"bill", "bob", "sally"}), nil }, }) @@ -30,7 +30,7 @@ func Example_custom() { fmt.Printf("%s", f.FriendName) - // Output: bill + // Output: sally } func Example_custom_with_params() { @@ -44,7 +44,7 @@ func Example_custom_with_params() { Params: []Param{ {Field: "word", Type: "int", Description: "Word you want to jumble"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { word, err := info.GetString(m, "word") if err != nil { return nil, err @@ -65,7 +65,7 @@ func Example_custom_with_params() { fmt.Printf("%s", f.JumbleWord) - // Output: loredlowlh + // Output: hldoolewrl } func TestMapParamsGet(t *testing.T) { @@ -173,7 +173,7 @@ func TestLookupChecking(t *testing.T) { for _, p := range info.Params { // If default is empty and has options randomly pick one if p.Default == "" && len(p.Options) != 0 { - mapData[p.Field] = []string{p.Options[rand.Intn(len(p.Options))]} + mapData[p.Field] = []string{p.Options[rand.IntN(len(p.Options))]} continue } else if p.Default != "" { // If p.Type is []uint, then we need to convert it to []string @@ -219,7 +219,7 @@ func TestLookupChecking(t *testing.T) { } } - _, err := info.Generate(faker.Rand, &mapData, &info) + _, err := info.Generate(faker, &mapData, &info) if err != nil { t.Fatalf("%s failed - Err: %s - Data: %v", field, err, mapData) } @@ -270,7 +270,7 @@ func TestLookupRemove(t *testing.T) { Description: "Random friend name", Example: "bill", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { return RandomString([]string{"bill", "bob", "sally"}), nil }, }) @@ -300,7 +300,7 @@ func TestLookupCalls(t *testing.T) { for _, p := range info.Params { // If default is empty and has options randomly pick one if p.Default == "" && len(p.Options) != 0 { - mapData.Add(p.Field, p.Options[faker.Rand.Intn(len(p.Options))]) + mapData.Add(p.Field, p.Options[faker.IntN(len(p.Options))]) continue } else if p.Default != "" { // If p.Type is []uint, then we need to convert it to []string @@ -363,7 +363,7 @@ func TestLookupCalls(t *testing.T) { } } - _, err := info.Generate(faker.Rand, &mapData, &info) + _, err := info.Generate(faker, &mapData, &info) if err != nil { t.Fatal(err) } @@ -460,7 +460,7 @@ func TestLookupCallsErrorParams(t *testing.T) { } if !skip { - _, err := info.Generate(faker.Rand, mapData, &info) + _, err := info.Generate(faker, mapData, &info) if err == nil { t.Error(funcName+" should have failed on param", currentEmptyParam) } diff --git a/lorem.go b/lorem.go index bf11bce7..b4e48f58 100644 --- a/lorem.go +++ b/lorem.go @@ -2,43 +2,42 @@ package gofakeit import ( "errors" - "math/rand" ) // LoremIpsumWord will generate a random word -func LoremIpsumWord() string { return loremIpsumWord(globalFaker.Rand) } +func LoremIpsumWord() string { return loremIpsumWord(GlobalFaker) } // LoremIpsumWord will generate a random word -func (f *Faker) LoremIpsumWord() string { return loremIpsumWord(f.Rand) } +func (f *Faker) LoremIpsumWord() string { return loremIpsumWord(f) } -func loremIpsumWord(r *rand.Rand) string { return getRandValue(r, []string{"lorem", "word"}) } +func loremIpsumWord(f *Faker) string { return getRandValue(f, []string{"lorem", "word"}) } // LoremIpsumSentence will generate a random sentence func LoremIpsumSentence(wordCount int) string { - return loremIpsumSentence(globalFaker.Rand, wordCount) + return loremIpsumSentence(GlobalFaker, wordCount) } // LoremIpsumSentence will generate a random sentence func (f *Faker) LoremIpsumSentence(wordCount int) string { - return loremIpsumSentence(f.Rand, wordCount) + return loremIpsumSentence(f, wordCount) } -func loremIpsumSentence(r *rand.Rand, wordCount int) string { - return sentenceGen(r, wordCount, loremIpsumWord) +func loremIpsumSentence(f *Faker, wordCount int) string { + return sentenceGen(f, wordCount, loremIpsumWord) } // LoremIpsumParagraph will generate a random paragraphGenerator func LoremIpsumParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { - return loremIpsumParagraph(globalFaker.Rand, paragraphCount, sentenceCount, wordCount, separator) + return loremIpsumParagraph(GlobalFaker, paragraphCount, sentenceCount, wordCount, separator) } // LoremIpsumParagraph will generate a random paragraphGenerator func (f *Faker) LoremIpsumParagraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { - return loremIpsumParagraph(f.Rand, paragraphCount, sentenceCount, wordCount, separator) + return loremIpsumParagraph(f, paragraphCount, sentenceCount, wordCount, separator) } -func loremIpsumParagraph(r *rand.Rand, paragraphCount int, sentenceCount int, wordCount int, separator string) string { - return paragraphGen(r, paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, loremIpsumSentence) +func loremIpsumParagraph(f *Faker, paragraphCount int, sentenceCount int, wordCount int, separator string) string { + return paragraphGen(f, paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, loremIpsumSentence) } func addLoremLookup() { @@ -48,8 +47,8 @@ func addLoremLookup() { Description: "Word of the Lorem Ipsum placeholder text used in design and publishing", Example: "quia", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return loremIpsumWord(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return loremIpsumWord(f), nil }, }) @@ -62,7 +61,7 @@ func addLoremLookup() { Params: []Param{ {Field: "wordcount", Display: "Word Count", Type: "int", Default: "5", Description: "Number of words in a sentence"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { wordCount, err := info.GetInt(m, "wordcount") if err != nil { return nil, err @@ -71,7 +70,7 @@ func addLoremLookup() { return nil, errors.New("invalid word count, must be greater than 0, less than 50") } - return loremIpsumSentence(r, wordCount), nil + return loremIpsumSentence(f, wordCount), nil }, }) @@ -91,7 +90,7 @@ Explicabo incidunt reprehenderit non quia dignissimos recusandae vitae soluta qu {Field: "wordcount", Display: "Word Count", Type: "int", Default: "5", Description: "Number of words in a sentence"}, {Field: "paragraphseparator", Display: "Paragraph Separator", Type: "string", Default: "
", Description: "String value to add between paragraphs"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { paragraphCount, err := info.GetInt(m, "paragraphcount") if err != nil { return nil, err @@ -121,7 +120,7 @@ Explicabo incidunt reprehenderit non quia dignissimos recusandae vitae soluta qu return nil, err } - return loremIpsumParagraph(r, paragraphCount, sentenceCount, wordCount, paragraphSeparator), nil + return loremIpsumParagraph(f, paragraphCount, sentenceCount, wordCount, paragraphSeparator), nil }, }) } diff --git a/lorem_test.go b/lorem_test.go index 973d05cc..12d6cdac 100644 --- a/lorem_test.go +++ b/lorem_test.go @@ -9,14 +9,14 @@ func ExampleLoremIpsumWord() { Seed(11) fmt.Println(LoremIpsumWord()) - // Output: quia + // Output: eveniet } func ExampleFaker_LoremIpsumWord() { f := New(11) fmt.Println(f.LoremIpsumWord()) - // Output: quia + // Output: eveniet } func BenchmarkLoremIpsumWord(b *testing.B) { @@ -29,14 +29,14 @@ func ExampleLoremIpsumSentence() { Seed(11) fmt.Println(LoremIpsumSentence(5)) - // Output: Quia quae repellat consequatur quidem. + // Output: Eveniet vero velit velit non. } func ExampleFaker_LoremIpsumSentence() { f := New(11) fmt.Println(f.LoremIpsumSentence(5)) - // Output: Quia quae repellat consequatur quidem. + // Output: Eveniet vero velit velit non. } func TestLoremIpsumSentence(t *testing.T) { @@ -57,18 +57,18 @@ func ExampleLoremIpsumParagraph() { Seed(11) fmt.Println(LoremIpsumParagraph(3, 5, 12, "\n")) - // Output: Quia quae repellat consequatur quidem nisi quo qui voluptatum accusantium quisquam amet. Quas et ut non dolorem ipsam aut enim assumenda mollitia harum ut. Dicta similique veniam nulla voluptas at excepturi non ad maxime at non. Eaque hic repellat praesentium voluptatem qui consequuntur dolor iusto autem velit aut. Fugit tempore exercitationem harum consequatur voluptatum modi minima aut eaque et et. - // Aut ea voluptatem dignissimos expedita odit tempore quod aut beatae ipsam iste. Minus voluptatibus dolorem maiores eius sed nihil vel enim odio voluptatem accusamus. Natus quibusdam temporibus tenetur cumque sint necessitatibus dolorem ex ducimus iusto ex. Voluptatem neque dicta explicabo officiis et ducimus sit ut ut praesentium pariatur. Illum molestias nisi at dolore ut voluptatem accusantium et fugiat et ut. - // Explicabo incidunt reprehenderit non quia dignissimos recusandae vitae soluta quia et quia. Aut veniam voluptas consequatur placeat sapiente non eveniet voluptatibus magni velit eum. Nobis vel repellendus sed est qui autem laudantium quidem quam ullam consequatur. Aut iusto ut commodi similique quae voluptatem atque qui fugiat eum aut. Quis distinctio consequatur voluptatem vel aliquid aut laborum facere officiis iure tempora. + // Output: Eveniet vero velit velit non incidunt est sed tenetur consequatur ut architecto. Quod non non et voluptas et esse quisquam ullam placeat molestiae laboriosam. Consequatur in perferendis molestiae quam voluptatem eaque quia facilis quo hic dignissimos. Architecto ut tenetur aut qui et optio id sint quae rerum labore. Quae deserunt quia mollitia id accusantium itaque nisi aut omnis occaecati repellendus. + // Ad sunt neque placeat et qui saepe voluptatem blanditiis voluptatum possimus saepe. Velit distinctio quia quas cupiditate sequi dolorum delectus quia quo corrupti labore. Aut mollitia et aut eligendi blanditiis corrupti aut rem voluptatibus veritatis ut. Et ab voluptas delectus repellat eligendi qui eos blanditiis et et eos. Qui ipsum aut ut voluptate nulla officia qui earum repudiandae quidem officia. + // Fugit esse beatae placeat nihil libero et sunt voluptas velit maiores voluptatem. Reiciendis quia dolor amet blanditiis labore eligendi fugit reiciendis modi est incidunt. Ut ut rerum odit sit voluptatem ipsam consequatur est incidunt aut quis. Non dolorem voluptatum pariatur esse eos blanditiis rem eos commodi accusamus occaecati. Qui voluptatem eos et tempora et id at voluptas suscipit magni cupiditate. } func ExampleFaker_LoremIpsumParagraph() { f := New(11) fmt.Println(f.LoremIpsumParagraph(3, 5, 12, "\n")) - // Output: Quia quae repellat consequatur quidem nisi quo qui voluptatum accusantium quisquam amet. Quas et ut non dolorem ipsam aut enim assumenda mollitia harum ut. Dicta similique veniam nulla voluptas at excepturi non ad maxime at non. Eaque hic repellat praesentium voluptatem qui consequuntur dolor iusto autem velit aut. Fugit tempore exercitationem harum consequatur voluptatum modi minima aut eaque et et. - // Aut ea voluptatem dignissimos expedita odit tempore quod aut beatae ipsam iste. Minus voluptatibus dolorem maiores eius sed nihil vel enim odio voluptatem accusamus. Natus quibusdam temporibus tenetur cumque sint necessitatibus dolorem ex ducimus iusto ex. Voluptatem neque dicta explicabo officiis et ducimus sit ut ut praesentium pariatur. Illum molestias nisi at dolore ut voluptatem accusantium et fugiat et ut. - // Explicabo incidunt reprehenderit non quia dignissimos recusandae vitae soluta quia et quia. Aut veniam voluptas consequatur placeat sapiente non eveniet voluptatibus magni velit eum. Nobis vel repellendus sed est qui autem laudantium quidem quam ullam consequatur. Aut iusto ut commodi similique quae voluptatem atque qui fugiat eum aut. Quis distinctio consequatur voluptatem vel aliquid aut laborum facere officiis iure tempora. + // Output: Eveniet vero velit velit non incidunt est sed tenetur consequatur ut architecto. Quod non non et voluptas et esse quisquam ullam placeat molestiae laboriosam. Consequatur in perferendis molestiae quam voluptatem eaque quia facilis quo hic dignissimos. Architecto ut tenetur aut qui et optio id sint quae rerum labore. Quae deserunt quia mollitia id accusantium itaque nisi aut omnis occaecati repellendus. + // Ad sunt neque placeat et qui saepe voluptatem blanditiis voluptatum possimus saepe. Velit distinctio quia quas cupiditate sequi dolorum delectus quia quo corrupti labore. Aut mollitia et aut eligendi blanditiis corrupti aut rem voluptatibus veritatis ut. Et ab voluptas delectus repellat eligendi qui eos blanditiis et et eos. Qui ipsum aut ut voluptate nulla officia qui earum repudiandae quidem officia. + // Fugit esse beatae placeat nihil libero et sunt voluptas velit maiores voluptatem. Reiciendis quia dolor amet blanditiis labore eligendi fugit reiciendis modi est incidunt. Ut ut rerum odit sit voluptatem ipsam consequatur est incidunt aut quis. Non dolorem voluptatum pariatur esse eos blanditiis rem eos commodi accusamus occaecati. Qui voluptatem eos et tempora et id at voluptas suscipit magni cupiditate. } func TestLoremIpsumParagraph(t *testing.T) { diff --git a/minecraft.go b/minecraft.go index 1fb740e4..5e5efa20 100644 --- a/minecraft.go +++ b/minecraft.go @@ -1,170 +1,168 @@ package gofakeit -import "math/rand" - // MinecraftOre will generate a random Minecraft ore -func MinecraftOre() string { return minecraftOre(globalFaker.Rand) } +func MinecraftOre() string { return minecraftOre(GlobalFaker) } // MinecraftOre will generate a random Minecraft ore -func (f *Faker) MinecraftOre() string { return minecraftOre(f.Rand) } +func (f *Faker) MinecraftOre() string { return minecraftOre(f) } -func minecraftOre(r *rand.Rand) string { return getRandValue(r, []string{"minecraft", "ore"}) } +func minecraftOre(f *Faker) string { return getRandValue(f, []string{"minecraft", "ore"}) } // MinecraftWood will generate a random Minecraft wood -func MinecraftWood() string { return minecraftWood(globalFaker.Rand) } +func MinecraftWood() string { return minecraftWood(GlobalFaker) } // MinecraftWood will generate a random Minecraft wood -func (f *Faker) MinecraftWood() string { return minecraftWood(f.Rand) } +func (f *Faker) MinecraftWood() string { return minecraftWood(f) } -func minecraftWood(r *rand.Rand) string { return getRandValue(r, []string{"minecraft", "wood"}) } +func minecraftWood(f *Faker) string { return getRandValue(f, []string{"minecraft", "wood"}) } // MinecraftArmorTier will generate a random Minecraft armor tier -func MinecraftArmorTier() string { return minecraftArmorTier(globalFaker.Rand) } +func MinecraftArmorTier() string { return minecraftArmorTier(GlobalFaker) } // MinecraftArmorTier will generate a random Minecraft armor tier -func (f *Faker) MinecraftArmorTier() string { return minecraftArmorTier(f.Rand) } +func (f *Faker) MinecraftArmorTier() string { return minecraftArmorTier(f) } -func minecraftArmorTier(r *rand.Rand) string { - return getRandValue(r, []string{"minecraft", "armortier"}) +func minecraftArmorTier(f *Faker) string { + return getRandValue(f, []string{"minecraft", "armortier"}) } // MinecraftArmorPart will generate a random Minecraft armor part -func MinecraftArmorPart() string { return minecraftArmorPart(globalFaker.Rand) } +func MinecraftArmorPart() string { return minecraftArmorPart(GlobalFaker) } // MinecraftArmorPart will generate a random Minecraft armor part -func (f *Faker) MinecraftArmorPart() string { return minecraftArmorPart(f.Rand) } +func (f *Faker) MinecraftArmorPart() string { return minecraftArmorPart(f) } -func minecraftArmorPart(r *rand.Rand) string { - return getRandValue(r, []string{"minecraft", "armorpart"}) +func minecraftArmorPart(f *Faker) string { + return getRandValue(f, []string{"minecraft", "armorpart"}) } // MinecraftWeapon will generate a random Minecraft weapon -func MinecraftWeapon() string { return minecraftWeapon(globalFaker.Rand) } +func MinecraftWeapon() string { return minecraftWeapon(GlobalFaker) } // MinecraftWeapon will generate a random Minecraft weapon -func (f *Faker) MinecraftWeapon() string { return minecraftWeapon(f.Rand) } +func (f *Faker) MinecraftWeapon() string { return minecraftWeapon(f) } -func minecraftWeapon(r *rand.Rand) string { return getRandValue(r, []string{"minecraft", "weapon"}) } +func minecraftWeapon(f *Faker) string { return getRandValue(f, []string{"minecraft", "weapon"}) } // MinecraftTool will generate a random Minecraft tool -func MinecraftTool() string { return minecraftTool(globalFaker.Rand) } +func MinecraftTool() string { return minecraftTool(GlobalFaker) } // MinecraftTool will generate a random Minecraft tool -func (f *Faker) MinecraftTool() string { return minecraftTool(f.Rand) } +func (f *Faker) MinecraftTool() string { return minecraftTool(f) } -func minecraftTool(r *rand.Rand) string { return getRandValue(r, []string{"minecraft", "tool"}) } +func minecraftTool(f *Faker) string { return getRandValue(f, []string{"minecraft", "tool"}) } // MinecraftDye will generate a random Minecraft dye -func MinecraftDye() string { return minecraftDye(globalFaker.Rand) } +func MinecraftDye() string { return minecraftDye(GlobalFaker) } // MinecraftDye will generate a random Minecraft dye -func (f *Faker) MinecraftDye() string { return minecraftDye(f.Rand) } +func (f *Faker) MinecraftDye() string { return minecraftDye(f) } -func minecraftDye(r *rand.Rand) string { return getRandValue(r, []string{"minecraft", "dye"}) } +func minecraftDye(f *Faker) string { return getRandValue(f, []string{"minecraft", "dye"}) } // MinecraftFood will generate a random Minecraft food -func MinecraftFood() string { return minecraftFood(globalFaker.Rand) } +func MinecraftFood() string { return minecraftFood(GlobalFaker) } // MinecraftFood will generate a random Minecraft food -func (f *Faker) MinecraftFood() string { return minecraftFood(f.Rand) } +func (f *Faker) MinecraftFood() string { return minecraftFood(f) } -func minecraftFood(r *rand.Rand) string { return getRandValue(r, []string{"minecraft", "food"}) } +func minecraftFood(f *Faker) string { return getRandValue(f, []string{"minecraft", "food"}) } // MinecraftAnimal will generate a random Minecraft animal -func MinecraftAnimal() string { return minecraftAnimal(globalFaker.Rand) } +func MinecraftAnimal() string { return minecraftAnimal(GlobalFaker) } // MinecraftAnimal will generate a random Minecraft animal -func (f *Faker) MinecraftAnimal() string { return minecraftAnimal(f.Rand) } +func (f *Faker) MinecraftAnimal() string { return minecraftAnimal(f) } -func minecraftAnimal(r *rand.Rand) string { - return getRandValue(r, []string{"minecraft", "animal"}) +func minecraftAnimal(f *Faker) string { + return getRandValue(f, []string{"minecraft", "animal"}) } // MinecraftVillagerJob will generate a random Minecraft villager job -func MinecraftVillagerJob() string { return minecraftVillagerJob(globalFaker.Rand) } +func MinecraftVillagerJob() string { return minecraftVillagerJob(GlobalFaker) } // MinecraftVillagerJob will generate a random Minecraft villager job -func (f *Faker) MinecraftVillagerJob() string { return minecraftVillagerJob(f.Rand) } +func (f *Faker) MinecraftVillagerJob() string { return minecraftVillagerJob(f) } -func minecraftVillagerJob(r *rand.Rand) string { - return getRandValue(r, []string{"minecraft", "villagerjob"}) +func minecraftVillagerJob(f *Faker) string { + return getRandValue(f, []string{"minecraft", "villagerjob"}) } // MinecraftVillagerStation will generate a random Minecraft villager station -func MinecraftVillagerStation() string { return minecraftVillagerStation(globalFaker.Rand) } +func MinecraftVillagerStation() string { return minecraftVillagerStation(GlobalFaker) } // MinecraftVillagerStation will generate a random Minecraft villager station -func (f *Faker) MinecraftVillagerStation() string { return minecraftVillagerStation(f.Rand) } +func (f *Faker) MinecraftVillagerStation() string { return minecraftVillagerStation(f) } -func minecraftVillagerStation(r *rand.Rand) string { - return getRandValue(r, []string{"minecraft", "villagerstation"}) +func minecraftVillagerStation(f *Faker) string { + return getRandValue(f, []string{"minecraft", "villagerstation"}) } // MinecraftVillagerLevel will generate a random Minecraft villager level -func MinecraftVillagerLevel() string { return minecraftVillagerLevel(globalFaker.Rand) } +func MinecraftVillagerLevel() string { return minecraftVillagerLevel(GlobalFaker) } // MinecraftVillagerLevel will generate a random Minecraft villager level -func (f *Faker) MinecraftVillagerLevel() string { return minecraftVillagerLevel(f.Rand) } +func (f *Faker) MinecraftVillagerLevel() string { return minecraftVillagerLevel(f) } -func minecraftVillagerLevel(r *rand.Rand) string { - return getRandValue(r, []string{"minecraft", "villagerlevel"}) +func minecraftVillagerLevel(f *Faker) string { + return getRandValue(f, []string{"minecraft", "villagerlevel"}) } // MinecraftMobPassive will generate a random Minecraft mob passive -func MinecraftMobPassive() string { return minecraftMobPassive(globalFaker.Rand) } +func MinecraftMobPassive() string { return minecraftMobPassive(GlobalFaker) } // MinecraftMobPassive will generate a random Minecraft mob passive -func (f *Faker) MinecraftMobPassive() string { return minecraftMobPassive(f.Rand) } +func (f *Faker) MinecraftMobPassive() string { return minecraftMobPassive(f) } -func minecraftMobPassive(r *rand.Rand) string { - return getRandValue(r, []string{"minecraft", "mobpassive"}) +func minecraftMobPassive(f *Faker) string { + return getRandValue(f, []string{"minecraft", "mobpassive"}) } // MinecraftMobNeutral will generate a random Minecraft mob neutral -func MinecraftMobNeutral() string { return minecraftMobNeutral(globalFaker.Rand) } +func MinecraftMobNeutral() string { return minecraftMobNeutral(GlobalFaker) } // MinecraftMobNeutral will generate a random Minecraft mob neutral -func (f *Faker) MinecraftMobNeutral() string { return minecraftMobNeutral(f.Rand) } +func (f *Faker) MinecraftMobNeutral() string { return minecraftMobNeutral(f) } -func minecraftMobNeutral(r *rand.Rand) string { - return getRandValue(r, []string{"minecraft", "mobneutral"}) +func minecraftMobNeutral(f *Faker) string { + return getRandValue(f, []string{"minecraft", "mobneutral"}) } // MinecraftMobHostile will generate a random Minecraft mob hostile -func MinecraftMobHostile() string { return minecraftMobHostile(globalFaker.Rand) } +func MinecraftMobHostile() string { return minecraftMobHostile(GlobalFaker) } // MinecraftMobHostile will generate a random Minecraft mob hostile -func (f *Faker) MinecraftMobHostile() string { return minecraftMobHostile(f.Rand) } +func (f *Faker) MinecraftMobHostile() string { return minecraftMobHostile(f) } -func minecraftMobHostile(r *rand.Rand) string { - return getRandValue(r, []string{"minecraft", "mobhostile"}) +func minecraftMobHostile(f *Faker) string { + return getRandValue(f, []string{"minecraft", "mobhostile"}) } // MinecraftMobBoss will generate a random Minecraft mob boss -func MinecraftMobBoss() string { return minecraftMobBoss(globalFaker.Rand) } +func MinecraftMobBoss() string { return minecraftMobBoss(GlobalFaker) } // MinecraftMobBoss will generate a random Minecraft mob boss -func (f *Faker) MinecraftMobBoss() string { return minecraftMobBoss(f.Rand) } +func (f *Faker) MinecraftMobBoss() string { return minecraftMobBoss(f) } -func minecraftMobBoss(r *rand.Rand) string { - return getRandValue(r, []string{"minecraft", "mobboss"}) +func minecraftMobBoss(f *Faker) string { + return getRandValue(f, []string{"minecraft", "mobboss"}) } // MinecraftBiome will generate a random Minecraft biome -func MinecraftBiome() string { return minecraftBiome(globalFaker.Rand) } +func MinecraftBiome() string { return minecraftBiome(GlobalFaker) } // MinecraftBiome will generate a random Minecraft biome -func (f *Faker) MinecraftBiome() string { return minecraftBiome(f.Rand) } +func (f *Faker) MinecraftBiome() string { return minecraftBiome(f) } -func minecraftBiome(r *rand.Rand) string { return getRandValue(r, []string{"minecraft", "biome"}) } +func minecraftBiome(f *Faker) string { return getRandValue(f, []string{"minecraft", "biome"}) } // MinecraftWeather will generate a random Minecraft weather -func MinecraftWeather() string { return minecraftWeather(globalFaker.Rand) } +func MinecraftWeather() string { return minecraftWeather(GlobalFaker) } // MinecraftWeather will generate a random Minecraft weather -func (f *Faker) MinecraftWeather() string { return minecraftWeather(f.Rand) } +func (f *Faker) MinecraftWeather() string { return minecraftWeather(f) } -func minecraftWeather(r *rand.Rand) string { return getRandValue(r, []string{"minecraft", "weather"}) } +func minecraftWeather(f *Faker) string { return getRandValue(f, []string{"minecraft", "weather"}) } func addMinecraftLookup() { AddFuncLookup("minecraftore", Info{ @@ -173,8 +171,8 @@ func addMinecraftLookup() { Description: "Naturally occurring minerals found in the game Minecraft, used for crafting purposes", Example: "coal", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftOre(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftOre(f), nil }, }) @@ -184,8 +182,8 @@ func addMinecraftLookup() { Description: "Natural resource in Minecraft, used for crafting various items and building structures", Example: "oak", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftWood(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftWood(f), nil }, }) @@ -195,8 +193,8 @@ func addMinecraftLookup() { Description: "Classification system for armor sets in Minecraft, indicating their effectiveness and protection level", Example: "iron", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftArmorTier(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftArmorTier(f), nil }, }) @@ -206,8 +204,8 @@ func addMinecraftLookup() { Description: "Component of an armor set in Minecraft, such as a helmet, chestplate, leggings, or boots", Example: "helmet", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftArmorPart(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftArmorPart(f), nil }, }) @@ -217,8 +215,8 @@ func addMinecraftLookup() { Description: "Tools and items used in Minecraft for combat and defeating hostile mobs", Example: "bow", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftWeapon(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftWeapon(f), nil }, }) @@ -228,8 +226,8 @@ func addMinecraftLookup() { Description: "Items in Minecraft designed for specific tasks, including mining, digging, and building", Example: "shovel", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftTool(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftTool(f), nil }, }) @@ -239,8 +237,8 @@ func addMinecraftLookup() { Description: "Items used to change the color of various in-game objects", Example: "white", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftDye(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftDye(f), nil }, }) @@ -250,8 +248,8 @@ func addMinecraftLookup() { Description: "Consumable items in Minecraft that provide nourishment to the player character", Example: "apple", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftFood(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftFood(f), nil }, }) @@ -261,8 +259,8 @@ func addMinecraftLookup() { Description: "Non-hostile creatures in Minecraft, often used for resources and farming", Example: "chicken", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftAnimal(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftAnimal(f), nil }, }) @@ -272,8 +270,8 @@ func addMinecraftLookup() { Description: "The profession or occupation assigned to a villager character in the game", Example: "farmer", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftVillagerJob(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftVillagerJob(f), nil }, }) @@ -283,8 +281,8 @@ func addMinecraftLookup() { Description: "Designated area or structure in Minecraft where villagers perform their job-related tasks and trading", Example: "furnace", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftVillagerStation(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftVillagerStation(f), nil }, }) @@ -294,8 +292,8 @@ func addMinecraftLookup() { Description: "Measure of a villager's experience and proficiency in their assigned job or profession", Example: "master", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftVillagerLevel(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftVillagerLevel(f), nil }, }) @@ -305,8 +303,8 @@ func addMinecraftLookup() { Description: "Non-aggressive creatures in the game that do not attack players", Example: "cow", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftMobPassive(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftMobPassive(f), nil }, }) @@ -316,8 +314,8 @@ func addMinecraftLookup() { Description: "Creature in the game that only becomes hostile if provoked, typically defending itself when attacked", Example: "bee", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftMobNeutral(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftMobNeutral(f), nil }, }) @@ -327,8 +325,8 @@ func addMinecraftLookup() { Description: "Aggressive creatures in the game that actively attack players when encountered", Example: "spider", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftMobHostile(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftMobHostile(f), nil }, }) @@ -338,8 +336,8 @@ func addMinecraftLookup() { Description: "Powerful hostile creature in the game, often found in challenging dungeons or structures", Example: "ender dragon", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftMobBoss(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftMobBoss(f), nil }, }) @@ -349,8 +347,8 @@ func addMinecraftLookup() { Description: "Distinctive environmental regions in the game, characterized by unique terrain, vegetation, and weather", Example: "forest", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftBiome(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftBiome(f), nil }, }) @@ -360,8 +358,8 @@ func addMinecraftLookup() { Description: "Atmospheric conditions in the game that include rain, thunderstorms, and clear skies, affecting gameplay and ambiance", Example: "rain", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minecraftWeather(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minecraftWeather(f), nil }, }) } diff --git a/minecraft_test.go b/minecraft_test.go index d4428c94..6e7ba053 100644 --- a/minecraft_test.go +++ b/minecraft_test.go @@ -9,120 +9,60 @@ func ExampleMinecraftOre() { Seed(11) fmt.Println(MinecraftOre()) - // Output: - // coal + // Output: redstone } func ExampleFaker_MinecraftOre() { f := New(11) fmt.Println(f.MinecraftOre()) - // Output: - // coal + // Output: redstone } func BenchmarkMinecraftOre(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftOre() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftOre() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftOre() - } - }) + for i := 0; i < b.N; i++ { + MinecraftOre() + } } func ExampleMinecraftWood() { Seed(11) fmt.Println(MinecraftWood()) - // Output: - // oak + // Output: dark oak } func ExampleFaker_MinecraftWood() { f := New(11) fmt.Println(f.MinecraftWood()) - // Output: - // oak + // Output: dark oak } func BenchmarkMinecraftWood(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftWood() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftWood() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftWood() - } - }) + for i := 0; i < b.N; i++ { + MinecraftWood() + } } func ExampleMinecraftArmorTier() { Seed(11) fmt.Println(MinecraftArmorTier()) - // Output: - // leather + // Output: netherite } func ExampleFaker_MinecraftArmorTier() { f := New(11) fmt.Println(f.MinecraftArmorTier()) - // Output: - // leather + // Output: netherite } func BenchmarkMinecraftArmorTier(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftArmorTier() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftArmorTier() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftArmorTier() - } - }) + for i := 0; i < b.N; i++ { + MinecraftArmorTier() + } } func ExampleMinecraftArmorPart() { @@ -142,235 +82,116 @@ func ExampleFaker_MinecraftArmorPart() { } func BenchmarkMinecraftArmorPart(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftArmorPart() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftArmorPart() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftArmorPart() - } - }) + for i := 0; i < b.N; i++ { + MinecraftArmorPart() + } } func ExampleMinecraftWeapon() { Seed(11) fmt.Println(MinecraftWeapon()) - // Output: - // sword + // Output: shield } func ExampleFaker_MinecraftWeapon() { f := New(11) fmt.Println(f.MinecraftWeapon()) - // Output: - // sword + // Output: shield } func BenchmarkMinecraftWeapon(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftWeapon() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftWeapon() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftWeapon() - } - }) + for i := 0; i < b.N; i++ { + MinecraftWeapon() + } } func ExampleMinecraftTool() { Seed(11) fmt.Println(MinecraftTool()) - // Output: - // pickaxe + // Output: fishing rod } func ExampleFaker_MinecraftTool() { f := New(11) fmt.Println(f.MinecraftTool()) - // Output: - // pickaxe + // Output: fishing rod } func BenchmarkMinecraftTool(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftTool() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftTool() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftTool() - } - }) + for i := 0; i < b.N; i++ { + MinecraftTool() + } } func ExampleMinecraftDye() { Seed(11) fmt.Println(MinecraftDye()) - // Output: - // light gray + // Output: yellow } func ExampleFaker_MinecraftDye() { f := New(11) fmt.Println(f.MinecraftDye()) - // Output: - // light gray + // Output: yellow } func BenchmarkMinecraftDye(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftDye() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftDye() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftDye() - } - }) + for i := 0; i < b.N; i++ { + MinecraftDye() + } } func ExampleMinecraftFood() { Seed(11) fmt.Println(MinecraftFood()) - // Output: - // beetroot + // Output: steak } func ExampleFaker_MinecraftFood() { f := New(11) fmt.Println(f.MinecraftFood()) - // Output: - // beetroot + // Output: steak } func BenchmarkMinecraftFood(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftFood() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftFood() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftFood() - } - }) + for i := 0; i < b.N; i++ { + MinecraftFood() + } } func ExampleMinecraftAnimal() { Seed(11) fmt.Println(MinecraftAnimal()) - // Output: - // chicken + // Output: wolf } func ExampleFaker_MinecraftAnimal() { f := New(11) fmt.Println(f.MinecraftAnimal()) - // Output: - // chicken + // Output: wolf } func BenchmarkMinecraftAnimal(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftAnimal() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftAnimal() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftAnimal() - } - }) + for i := 0; i < b.N; i++ { + MinecraftAnimal() + } } func ExampleMinecraftVillagerJob() { Seed(11) fmt.Println(MinecraftVillagerJob()) - // Output: - // toolsmith + // Output: toolsmith } func ExampleFaker_MinecraftVillagerJob() { @@ -382,155 +203,76 @@ func ExampleFaker_MinecraftVillagerJob() { } func BenchmarkMinecraftVillagerJob(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftVillagerJob() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftVillagerJob() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftVillagerJob() - } - }) + for i := 0; i < b.N; i++ { + MinecraftVillagerJob() + } } func ExampleMinecraftVillagerStation() { Seed(11) fmt.Println(MinecraftVillagerStation()) - // Output: - // cauldron + // Output: stonecutter } func ExampleFaker_MinecraftVillagerStation() { f := New(11) fmt.Println(f.MinecraftVillagerStation()) - // Output: - // cauldron + // Output: stonecutter } func BenchmarkMinecraftVillagerStation(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftVillagerStation() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftVillagerStation() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftVillagerStation() - } - }) + for i := 0; i < b.N; i++ { + MinecraftVillagerStation() + } } func ExampleMinecraftVillagerLevel() { Seed(11) fmt.Println(MinecraftVillagerLevel()) - // Output: - // novice + // Output: master } func ExampleFaker_MinecraftVillagerLevel() { f := New(11) fmt.Println(f.MinecraftVillagerLevel()) - // Output: - // novice + // Output: master } func BenchmarkMinecraftVillagerLevel(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftVillagerLevel() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftVillagerLevel() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftVillagerLevel() - } - }) + for i := 0; i < b.N; i++ { + MinecraftVillagerLevel() + } } func ExampleMinecraftMobPassive() { Seed(11) fmt.Println(MinecraftMobPassive()) - // Output: - // chicken + // Output: turtle } func ExampleFaker_MinecraftMobPassive() { f := New(11) fmt.Println(f.MinecraftMobPassive()) - // Output: - // chicken + // Output: turtle } func BenchmarkMinecraftMobPassive(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftMobPassive() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftMobPassive() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftMobPassive() - } - }) + for i := 0; i < b.N; i++ { + MinecraftMobPassive() + } } func ExampleMinecraftMobNeutral() { Seed(11) fmt.Println(MinecraftMobNeutral()) - // Output: - // wolf + // Output: wolf } func ExampleFaker_MinecraftMobNeutral() { @@ -542,67 +284,29 @@ func ExampleFaker_MinecraftMobNeutral() { } func BenchmarkMinecraftMobNeutral(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftMobNeutral() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftMobNeutral() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftMobNeutral() - } - }) + for i := 0; i < b.N; i++ { + MinecraftMobNeutral() + } } func ExampleMinecraftMobHostile() { Seed(11) fmt.Println(MinecraftMobHostile()) - // Output: - // blaze + // Output: wither skeleton } func ExampleFaker_MinecraftMobHostile() { f := New(11) fmt.Println(f.MinecraftMobHostile()) - // Output: - // blaze + // Output: wither skeleton } func BenchmarkMinecraftMobHostile(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftMobHostile() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftMobHostile() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftMobHostile() - } - }) + for i := 0; i < b.N; i++ { + MinecraftMobHostile() + } } func ExampleMinecraftMobBoss() { @@ -622,105 +326,47 @@ func ExampleFaker_MinecraftMobBoss() { } func BenchmarkMinecraftMobBoss(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftMobBoss() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftMobBoss() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftMobBoss() - } - }) + for i := 0; i < b.N; i++ { + MinecraftMobBoss() + } } func ExampleMinecraftBiome() { Seed(11) fmt.Println(MinecraftBiome()) - // Output: - // stone shore + // Output: the nether } func ExampleFaker_MinecraftBiome() { f := New(11) fmt.Println(f.MinecraftBiome()) - // Output: - // stone shore + // Output: the nether } func BenchmarkMinecraftBiome(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftBiome() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftBiome() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftBiome() - } - }) + for i := 0; i < b.N; i++ { + MinecraftBiome() + } } func ExampleMinecraftWeather() { Seed(11) fmt.Println(MinecraftWeather()) - // Output: - // clear + // Output: thunder } func ExampleFaker_MinecraftWeather() { f := New(11) fmt.Println(f.MinecraftWeather()) - // Output: - // clear + // Output: thunder } func BenchmarkMinecraftWeather(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MinecraftWeather() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MinecraftWeather() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MinecraftWeather() - } - }) + for i := 0; i < b.N; i++ { + MinecraftWeather() + } } diff --git a/misc.go b/misc.go index aa55911e..b40ba1ef 100644 --- a/misc.go +++ b/misc.go @@ -2,38 +2,34 @@ package gofakeit import ( "encoding/hex" - "math/rand" "reflect" - "github.com/brianvoe/gofakeit/v6/data" + "github.com/brianvoe/gofakeit/v7/data" ) // Bool will generate a random boolean value -func Bool() bool { return boolFunc(globalFaker.Rand) } +func Bool() bool { return boolFunc(GlobalFaker) } // Bool will generate a random boolean value -func (f *Faker) Bool() bool { return boolFunc(f.Rand) } +func (f *Faker) Bool() bool { return boolFunc(f) } -func boolFunc(r *rand.Rand) bool { return randIntRange(r, 0, 1) == 1 } +func boolFunc(f *Faker) bool { return randIntRange(f, 0, 1) == 1 } // UUID (version 4) will generate a random unique identifier based upon random numbers // Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -func UUID() string { return uuid(globalFaker.Rand) } +func UUID() string { return uuid(GlobalFaker) } // UUID (version 4) will generate a random unique identifier based upon random numbers // Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 8-4-4-4-12 -func (f *Faker) UUID() string { return uuid(f.Rand) } +func (f *Faker) UUID() string { return uuid(f) } -func uuid(r *rand.Rand) string { +func uuid(f *Faker) string { version := byte(4) uuid := make([]byte, 16) - // Commented out due to io.ReadFull not being race condition safe - // io.ReadFull(r, uuid[:]) - // Read 16 random bytes for i := 0; i < 16; i++ { - uuid[i] = byte(r.Intn(256)) + uuid[i] = byte(f.IntN(256)) } // Set version @@ -57,12 +53,12 @@ func uuid(r *rand.Rand) string { } // ShuffleAnySlice takes in a slice and outputs it in a random order -func ShuffleAnySlice(v any) { shuffleAnySlice(globalFaker.Rand, v) } +func ShuffleAnySlice(v any) { shuffleAnySlice(GlobalFaker, v) } // ShuffleAnySlice takes in a slice and outputs it in a random order -func (f *Faker) ShuffleAnySlice(v any) { shuffleAnySlice(f.Rand, v) } +func (f *Faker) ShuffleAnySlice(v any) { shuffleAnySlice(f, v) } -func shuffleAnySlice(r *rand.Rand, v any) { +func shuffleAnySlice(f *Faker, v any) { if v == nil { return } @@ -89,19 +85,19 @@ func shuffleAnySlice(r *rand.Rand, v any) { //if size is > int32 probably it will never finish, or ran out of entropy i := n - 1 for ; i > 0; i-- { - j := int(r.Int31n(int32(i + 1))) + j := int(int32NFunc(f, int32(i+1))) swap(i, j) } } // FlipACoin will return a random value of Heads or Tails -func FlipACoin() string { return flipACoin(globalFaker.Rand) } +func FlipACoin() string { return flipACoin(GlobalFaker) } // FlipACoin will return a random value of Heads or Tails -func (f *Faker) FlipACoin() string { return flipACoin(f.Rand) } +func (f *Faker) FlipACoin() string { return flipACoin(f) } -func flipACoin(r *rand.Rand) string { - if boolFunc(r) { +func flipACoin(f *Faker) string { + if boolFunc(f) { return "Heads" } @@ -109,14 +105,14 @@ func flipACoin(r *rand.Rand) string { } // RandomMapKey will return a random key from a map -func RandomMapKey(mapI any) any { return randomMapKey(globalFaker.Rand, mapI) } +func RandomMapKey(mapI any) any { return randomMapKey(GlobalFaker, mapI) } // RandomMapKey will return a random key from a map -func (f *Faker) RandomMapKey(mapI any) any { return randomMapKey(f.Rand, mapI) } +func (f *Faker) RandomMapKey(mapI any) any { return randomMapKey(f, mapI) } -func randomMapKey(r *rand.Rand, mapI any) any { +func randomMapKey(f *Faker, mapI any) any { keys := reflect.ValueOf(mapI).MapKeys() - return keys[r.Intn(len(keys))].Interface() + return keys[f.IntN(len(keys))].Interface() } // Categories will return a map string array of available data categories and sub categories @@ -139,8 +135,8 @@ func addMiscLookup() { Description: "128-bit identifier used to uniquely identify objects or entities in computer systems", Example: "590c1440-9888-45b0-bd51-a817ee07c3f2", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return uuid(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return uuid(f), nil }, }) @@ -150,8 +146,8 @@ func addMiscLookup() { Description: "Data type that represents one of two possible values, typically true or false", Example: "true", Output: "bool", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return boolFunc(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return boolFunc(f), nil }, }) @@ -161,8 +157,8 @@ func addMiscLookup() { Description: "Decision-making method involving the tossing of a coin to determine outcomes", Example: "Tails", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return flipACoin(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return flipACoin(f), nil }, }) } diff --git a/misc_test.go b/misc_test.go index 8be388ba..adf6075b 100644 --- a/misc_test.go +++ b/misc_test.go @@ -6,45 +6,27 @@ import ( "sort" "testing" - "github.com/brianvoe/gofakeit/v6/data" + "github.com/brianvoe/gofakeit/v7/data" ) func ExampleBool() { Seed(11) fmt.Println(Bool()) - // Output: true + // Output: false } func ExampleFaker_Bool() { f := New(11) fmt.Println(f.Bool()) - // Output: true + // Output: false } func BenchmarkBool(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Bool() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Bool() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Bool() - } - }) + for i := 0; i < b.N; i++ { + Bool() + } } func TestUUID(t *testing.T) { @@ -67,38 +49,20 @@ func ExampleUUID() { Seed(11) fmt.Println(UUID()) - // Output: 98173564-6619-4557-888e-65b16bb5def5 + // Output: b412b5fb-33a4-498e-9503-21c6b7e01dcf } func ExampleFaker_UUID() { f := New(11) fmt.Println(f.UUID()) - // Output: 98173564-6619-4557-888e-65b16bb5def5 + // Output: b412b5fb-33a4-498e-9503-21c6b7e01dcf } func BenchmarkUUID(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - UUID() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.UUID() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.UUID() - } - }) + for i := 0; i < b.N; i++ { + UUID() + } } func TestShuffleAnySlice(t *testing.T) { @@ -142,9 +106,8 @@ func ExampleShuffleAnySlice() { ShuffleAnySlice(ints) fmt.Println(ints) - // Output: - // [good everyone have for times a day happy] - // [777 74125 941 854 89416 52 8413 841657] + // Output: [for day happy everyone good times a have] + // [854 52 74125 941 777 8413 841657 89416] } func ExampleFaker_ShuffleAnySlice() { @@ -158,50 +121,29 @@ func ExampleFaker_ShuffleAnySlice() { f.ShuffleAnySlice(ints) fmt.Println(ints) - // Output: - // [good everyone have for times a day happy] - // [777 74125 941 854 89416 52 8413 841657] + // Output: [for day happy everyone good times a have] + // [854 52 74125 941 777 8413 841657 89416] } func BenchmarkShuffleAnySlice(b *testing.B) { - b.Run("package", func(b *testing.B) { - a := []any{"a", 1, "c", 3, []string{"a", "b", "c"}, -555, []byte{1, 5}, "h"} - for i := 0; i < b.N; i++ { - ShuffleAnySlice(a) - } - }) - - b.Run("Faker math", func(b *testing.B) { - a := []any{"a", 1, "c", 3, []string{"a", "b", "c"}, -555, []byte{1, 5}, "h"} - f := New(0) - - for i := 0; i < b.N; i++ { - f.ShuffleAnySlice(a) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - a := []any{"a", 1, "c", 3, []string{"a", "b", "c"}, -555, []byte{1, 5}, "h"} - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ShuffleAnySlice(a) - } - }) + a := []any{"a", 1, "c", 3, []string{"a", "b", "c"}, -555, []byte{1, 5}, "h"} + for i := 0; i < b.N; i++ { + ShuffleAnySlice(a) + } } func ExampleFlipACoin() { Seed(11) fmt.Println(FlipACoin()) - // Output: Heads + // Output: Tails } func ExampleFaker_FlipACoin() { f := New(11) fmt.Println(f.FlipACoin()) - // Output: Heads + // Output: Tails } func TestFlipACoin(t *testing.T) { @@ -211,27 +153,9 @@ func TestFlipACoin(t *testing.T) { } func BenchmarkFlipACoin(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - FlipACoin() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.FlipACoin() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.FlipACoin() - } - }) + for i := 0; i < b.N; i++ { + FlipACoin() + } } func TestRandomMapKey(t *testing.T) { diff --git a/movie.go b/movie.go index 21fcbd73..27199cd6 100644 --- a/movie.go +++ b/movie.go @@ -1,32 +1,30 @@ package gofakeit -import "math/rand" +func MovieName() string { return movieName(GlobalFaker) } -func MovieName() string { return movieName(globalFaker.Rand) } +func (f *Faker) MovieName() string { return movieName(f) } -func (f *Faker) MovieName() string { return movieName(f.Rand) } +func movieName(f *Faker) string { return getRandValue(f, []string{"movie", "name"}) } -func movieName(r *rand.Rand) string { return getRandValue(r, []string{"movie", "name"}) } +func MovieGenre() string { return movieGenre(GlobalFaker) } -func MovieGenre() string { return movieGenre(globalFaker.Rand) } +func (f *Faker) MovieGenre() string { return movieGenre(f) } -func (f *Faker) MovieGenre() string { return movieGenre(f.Rand) } - -func movieGenre(r *rand.Rand) string { return getRandValue(r, []string{"movie", "genre"}) } +func movieGenre(f *Faker) string { return getRandValue(f, []string{"movie", "genre"}) } type MovieInfo struct { Name string `json:"name" xml:"name"` Genre string `json:"genre" xml:"genre"` } -func Movie() *MovieInfo { return movie(globalFaker.Rand) } +func Movie() *MovieInfo { return movie(GlobalFaker) } -func (f *Faker) Movie() *MovieInfo { return movie(f.Rand) } +func (f *Faker) Movie() *MovieInfo { return movie(f) } -func movie(r *rand.Rand) *MovieInfo { +func movie(f *Faker) *MovieInfo { return &MovieInfo{ - Name: movieName(r), - Genre: movieGenre(r), + Name: movieName(f), + Genre: movieGenre(f), } } @@ -41,8 +39,8 @@ func addMovieLookup() { }`, Output: "map[string]string", ContentType: "application/json", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return movie(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return movie(f), nil }, }) @@ -52,8 +50,8 @@ func addMovieLookup() { Description: "Title or name of a specific film used for identification and reference", Example: "The Matrix", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return movieName(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return movieName(f), nil }, }) @@ -63,8 +61,8 @@ func addMovieLookup() { Description: "Category that classifies movies based on common themes, styles, and storytelling approaches", Example: "Action", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return movieGenre(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return movieGenre(f), nil }, }) } diff --git a/movie_test.go b/movie_test.go index 6e2c0d66..36344569 100644 --- a/movie_test.go +++ b/movie_test.go @@ -11,8 +11,8 @@ func ExampleMovie() { fmt.Println(movie.Name) fmt.Println(movie.Genre) - // Output: Psycho - // Mystery + // Output: The Terminator + // Sport } func ExampleFaker_Movie() { @@ -21,32 +21,14 @@ func ExampleFaker_Movie() { fmt.Println(movie.Name) fmt.Println(movie.Genre) - // Output: Psycho - // Mystery + // Output: The Terminator + // Sport } func BenchmarkMovie(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Movie() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Movie() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Movie() - } - }) + for i := 0; i < b.N; i++ { + Movie() + } } func TestMovie(t *testing.T) { @@ -59,74 +41,38 @@ func ExampleMovieName() { Seed(11) fmt.Println(MovieName()) - // Output: Psycho + // Output: The Terminator } func ExampleFaker_MovieName() { f := New(11) fmt.Println(f.MovieName()) - // Output: Psycho + // Output: The Terminator } func BenchmarkMovieName(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MovieName() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MovieName() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MovieName() - } - }) + for i := 0; i < b.N; i++ { + MovieName() + } } func ExampleMovieGenre() { Seed(11) fmt.Println(MovieGenre()) - // Output: Music + // Output: Thriller } func ExampleFaker_MovieGenre() { f := New(11) fmt.Println(f.MovieGenre()) - // Output: Music + // Output: Thriller } func BenchmarkMovieGenre(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MovieGenre() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MovieGenre() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MovieGenre() - } - }) + for i := 0; i < b.N; i++ { + MovieGenre() + } } diff --git a/number.go b/number.go index 7200a598..e4cdfb9c 100644 --- a/number.go +++ b/number.go @@ -2,175 +2,283 @@ package gofakeit import ( "math" - "math/rand" + "math/bits" ) -// Number will generate a random number between given min And max -func Number(min int, max int) int { return number(globalFaker.Rand, min, max) } +// Number will generate a random number between given min and max +func Number(min int, max int) int { return number(GlobalFaker, min, max) } -// Number will generate a random number between given min And max -func (f *Faker) Number(min int, max int) int { return number(f.Rand, min, max) } +// Number will generate a random number between given min and max +func (f *Faker) Number(min int, max int) int { return number(f, min, max) } -func number(r *rand.Rand, min int, max int) int { return randIntRange(r, min, max) } +func number(f *Faker, min int, max int) int { return randIntRange(f, min, max) } + +// Uint will generate a random uint value +func Uint() uint { return uintFunc(GlobalFaker) } + +// Uint will generate a random uint value +func (f *Faker) Uint() uint { return uintFunc(f) } + +func uintFunc(f *Faker) uint { return uint(f.Uint64()) } + +// UintN will generate a random uint value between 0 and n +func UintN(n uint) uint { return uintNFunc(GlobalFaker, n) } + +// UintN will generate a random uint value between 0 and n +func (f *Faker) UintN(n uint) uint { return uintNFunc(f, n) } + +func uintNFunc(f *Faker, n uint) uint { + if n == 0 { + return 0 + } + return uint(uint64NFunc(f, uint64(n))) +} // Uint8 will generate a random uint8 value -func Uint8() uint8 { return uint8Func(globalFaker.Rand) } +func Uint8() uint8 { return uint8Func(GlobalFaker) } // Uint8 will generate a random uint8 value -func (f *Faker) Uint8() uint8 { return uint8Func(f.Rand) } +func (f *Faker) Uint8() uint8 { return uint8Func(f) } -func uint8Func(r *rand.Rand) uint8 { return uint8(randUintRange(r, minUint, math.MaxUint8)) } +func uint8Func(f *Faker) uint8 { return uint8(randIntRange(f, minUint, math.MaxUint8)) } // Uint16 will generate a random uint16 value -func Uint16() uint16 { return uint16Func(globalFaker.Rand) } +func Uint16() uint16 { return uint16Func(GlobalFaker) } // Uint16 will generate a random uint16 value -func (f *Faker) Uint16() uint16 { return uint16Func(f.Rand) } +func (f *Faker) Uint16() uint16 { return uint16Func(f) } -func uint16Func(r *rand.Rand) uint16 { return uint16(randUintRange(r, minUint, math.MaxUint16)) } +func uint16Func(f *Faker) uint16 { return uint16(randIntRange(f, minUint, math.MaxUint16)) } // Uint32 will generate a random uint32 value -func Uint32() uint32 { return uint32Func(globalFaker.Rand) } +func Uint32() uint32 { return uint32Func(GlobalFaker) } // Uint32 will generate a random uint32 value -func (f *Faker) Uint32() uint32 { return uint32Func(f.Rand) } +func (f *Faker) Uint32() uint32 { return uint32Func(f) } -func uint32Func(r *rand.Rand) uint32 { return uint32(randUintRange(r, minUint, math.MaxUint32)) } +func uint32Func(f *Faker) uint32 { return uint32(f.Uint64() >> 32) } // Uint64 will generate a random uint64 value -func Uint64() uint64 { return uint64Func(globalFaker.Rand) } +func Uint64() uint64 { return GlobalFaker.Uint64() } // Uint64 will generate a random uint64 value -func (f *Faker) Uint64() uint64 { return uint64Func(f.Rand) } +// This is the primary location in which the random number is generated. +// This will be the only location in which reading from Rand.Uint64() is lockable +func (f *Faker) Uint64() uint64 { + // Check if the source is locked + if f.Locked { + // Lock the source + f.mu.Lock() + defer f.mu.Unlock() + } -func uint64Func(r *rand.Rand) uint64 { return uint64(randUintRange(r, minUint, maxUint)) } + return f.Rand.Uint64() +} + +// uint64n is the no-bounds-checks version of Uint64N. +// See https://cs.opensource.google/go/go/+/refs/tags/go1.22.0:src/math/rand/v2/rand.go;l=78 +// hidden as to not clutter with additional N functions +func uint64NFunc(f *Faker, n uint64) uint64 { + if is32bit && uint64(uint32(n)) == n { + // create reusable function here + uint32NFunc := func(f *Faker, n uint32) uint32 { + if n&(n-1) == 0 { // n is power of two, can mask + return uint32(f.Uint64()) & (n - 1) + } + + x := f.Uint64() + lo1a, lo0 := bits.Mul32(uint32(x), n) + hi, lo1b := bits.Mul32(uint32(x>>32), n) + lo1, c := bits.Add32(lo1a, lo1b, 0) + hi += c + if lo1 == 0 && lo0 < uint32(n) { + n64 := uint64(n) + thresh := uint32(-n64 % n64) + for lo1 == 0 && lo0 < thresh { + x := f.Uint64() + lo1a, lo0 = bits.Mul32(uint32(x), n) + hi, lo1b = bits.Mul32(uint32(x>>32), n) + lo1, c = bits.Add32(lo1a, lo1b, 0) + hi += c + } + } + return hi + } + + return uint64(uint32NFunc(f, uint32(n))) + } + if n&(n-1) == 0 { // n is power of two, can mask + return f.Uint64() & (n - 1) + } + + hi, lo := bits.Mul64(f.Uint64(), n) + if lo < n { + thresh := -n % n + for lo < thresh { + hi, lo = bits.Mul64(f.Uint64(), n) + } + } + return hi +} // UintRange will generate a random uint value between min and max -func UintRange(min, max uint) uint { return uintRangeFunc(globalFaker.Rand, min, max) } +func UintRange(min, max uint) uint { return uintRangeFunc(GlobalFaker, min, max) } // UintRange will generate a random uint value between min and max -func (f *Faker) UintRange(min, max uint) uint { return uintRangeFunc(f.Rand, min, max) } +func (f *Faker) UintRange(min, max uint) uint { return uintRangeFunc(f, min, max) } -func uintRangeFunc(r *rand.Rand, min, max uint) uint { return randUintRange(r, min, max) } +func uintRangeFunc(f *Faker, min, max uint) uint { return randUintRange(f, min, max) } + +// Int will generate a random int value +func Int() int { return intFunc(GlobalFaker) } + +// Int will generate a random int value +func (f *Faker) Int() int { return intFunc(f) } + +func intFunc(f *Faker) int { return int(uint(f.Uint64()) << 1 >> 1) } + +// IntN will generate a random int value between 0 and n +func IntN(n int) int { return intNFunc(GlobalFaker, n) } + +// IntN will generate a random int value between 0 and n +func (f *Faker) IntN(n int) int { return intNFunc(f, n) } + +func intNFunc(f *Faker, n int) int { + if n <= 0 { + return 0 + } + return int(uint64NFunc(f, uint64(n))) +} // Int8 will generate a random Int8 value -func Int8() int8 { return int8Func(globalFaker.Rand) } +func Int8() int8 { return int8Func(GlobalFaker) } // Int8 will generate a random Int8 value -func (f *Faker) Int8() int8 { return int8Func(f.Rand) } +func (f *Faker) Int8() int8 { return int8Func(f) } -func int8Func(r *rand.Rand) int8 { return int8(randIntRange(r, math.MinInt8, math.MaxInt8)) } +func int8Func(f *Faker) int8 { return int8(randIntRange(f, math.MinInt8, math.MaxInt8)) } // Int16 will generate a random int16 value -func Int16() int16 { return int16Func(globalFaker.Rand) } +func Int16() int16 { return int16Func(GlobalFaker) } // Int16 will generate a random int16 value -func (f *Faker) Int16() int16 { return int16Func(f.Rand) } +func (f *Faker) Int16() int16 { return int16Func(f) } -func int16Func(r *rand.Rand) int16 { return int16(randIntRange(r, math.MinInt16, math.MaxInt16)) } +func int16Func(f *Faker) int16 { return int16(randIntRange(f, math.MinInt16, math.MaxInt16)) } // Int32 will generate a random int32 value -func Int32() int32 { return int32Func(globalFaker.Rand) } +func Int32() int32 { return int32Func(GlobalFaker) } // Int32 will generate a random int32 value -func (f *Faker) Int32() int32 { return int32Func(f.Rand) } +func (f *Faker) Int32() int32 { return int32Func(f) } + +func int32Func(f *Faker) int32 { return int32(f.Uint64() >> 33) } -func int32Func(r *rand.Rand) int32 { return int32(randIntRange(r, math.MinInt32, math.MaxInt32)) } +// int32n is an identical computation to int64n +// hidden as to not clutter with additional N functions +func int32NFunc(f *Faker, n int32) int32 { + if n <= 0 { + return 0 + } + return int32(uint64NFunc(f, uint64(n))) +} // Int64 will generate a random int64 value -func Int64() int64 { return int64Func(globalFaker.Rand) } +func Int64() int64 { return int64Func(GlobalFaker) } // Int64 will generate a random int64 value -func (f *Faker) Int64() int64 { return int64Func(f.Rand) } +func (f *Faker) Int64() int64 { return int64Func(f) } -func int64Func(r *rand.Rand) int64 { return int64(randIntRange(r, minInt, maxInt)) } +func int64Func(f *Faker) int64 { return int64(f.Uint64() &^ (1 << 63)) } // IntRange will generate a random int value between min and max -func IntRange(min, max int) int { return intRangeFunc(globalFaker.Rand, min, max) } +func IntRange(min, max int) int { return intRangeFunc(GlobalFaker, min, max) } // IntRange will generate a random int value between min and max -func (f *Faker) IntRange(min, max int) int { return intRangeFunc(f.Rand, min, max) } +func (f *Faker) IntRange(min, max int) int { return intRangeFunc(f, min, max) } -func intRangeFunc(r *rand.Rand, min, max int) int { return randIntRange(r, min, max) } +func intRangeFunc(f *Faker, min, max int) int { return randIntRange(f, min, max) } // Float32 will generate a random float32 value -func Float32() float32 { return float32Func(globalFaker.Rand) } +func Float32() float32 { return float32Func(GlobalFaker) } // Float32 will generate a random float32 value -func (f *Faker) Float32() float32 { return float32Func(f.Rand) } +func (f *Faker) Float32() float32 { return float32Func(f) } -func float32Func(r *rand.Rand) float32 { - return float32Range(r, math.SmallestNonzeroFloat32, math.MaxFloat32) +func float32Func(f *Faker) float32 { + // There are exactly 1<<24 float32s in [0,1). Use Intn(1<<24) / (1<<24). + return float32(f.Uint32()<<8>>8) / (1 << 24) } // Float32Range will generate a random float32 value between min and max func Float32Range(min, max float32) float32 { - return float32Range(globalFaker.Rand, min, max) + return float32Range(GlobalFaker, min, max) } // Float32Range will generate a random float32 value between min and max func (f *Faker) Float32Range(min, max float32) float32 { - return float32Range(f.Rand, min, max) + return float32Range(f, min, max) } -func float32Range(r *rand.Rand, min, max float32) float32 { +func float32Range(f *Faker, min, max float32) float32 { if min == max { return min } - return r.Float32()*(max-min) + min + return f.Float32()*(max-min) + min } // Float64 will generate a random float64 value func Float64() float64 { - return float64Func(globalFaker.Rand) + return float64Func(GlobalFaker) } // Float64 will generate a random float64 value func (f *Faker) Float64() float64 { - return float64Func(f.Rand) + return float64Func(f) } -func float64Func(r *rand.Rand) float64 { - return float64Range(r, math.SmallestNonzeroFloat64, math.MaxFloat64) +func float64Func(f *Faker) float64 { + // There are exactly 1<<53 float64s in [0,1). Use Intn(1<<53) / (1<<53). + return float64(f.Uint64()<<11>>11) / (1 << 53) } // Float64Range will generate a random float64 value between min and max func Float64Range(min, max float64) float64 { - return float64Range(globalFaker.Rand, min, max) + return float64Range(GlobalFaker, min, max) } // Float64Range will generate a random float64 value between min and max func (f *Faker) Float64Range(min, max float64) float64 { - return float64Range(f.Rand, min, max) + return float64Range(f, min, max) } -func float64Range(r *rand.Rand, min, max float64) float64 { +func float64Range(f *Faker, min, max float64) float64 { if min == max { return min } - return r.Float64()*(max-min) + min + return f.Float64()*(max-min) + min } // ShuffleInts will randomize a slice of ints -func ShuffleInts(a []int) { shuffleInts(globalFaker.Rand, a) } +func ShuffleInts(a []int) { shuffleInts(GlobalFaker, a) } // ShuffleInts will randomize a slice of ints -func (f *Faker) ShuffleInts(a []int) { shuffleInts(f.Rand, a) } +func (f *Faker) ShuffleInts(a []int) { shuffleInts(f, a) } -func shuffleInts(r *rand.Rand, a []int) { +func shuffleInts(f *Faker, a []int) { for i := range a { - j := r.Intn(i + 1) + j := f.IntN(i + 1) a[i], a[j] = a[j], a[i] } } // RandomInt will take in a slice of int and return a randomly selected value -func RandomInt(i []int) int { return randomInt(globalFaker.Rand, i) } +func RandomInt(i []int) int { return randomInt(GlobalFaker, i) } // RandomInt will take in a slice of int and return a randomly selected value -func (f *Faker) RandomInt(i []int) int { return randomInt(f.Rand, i) } +func (f *Faker) RandomInt(i []int) int { return randomInt(f, i) } -func randomInt(r *rand.Rand, i []int) int { +func randomInt(f *Faker, i []int) int { size := len(i) if size == 0 { return 0 @@ -178,16 +286,16 @@ func randomInt(r *rand.Rand, i []int) int { if size == 1 { return i[0] } - return i[r.Intn(size)] + return i[f.IntN(size)] } // RandomUint will take in a slice of uint and return a randomly selected value -func RandomUint(u []uint) uint { return randomUint(globalFaker.Rand, u) } +func RandomUint(u []uint) uint { return randomUint(GlobalFaker, u) } // RandomUint will take in a slice of uint and return a randomly selected value -func (f *Faker) RandomUint(u []uint) uint { return randomUint(f.Rand, u) } +func (f *Faker) RandomUint(u []uint) uint { return randomUint(f, u) } -func randomUint(r *rand.Rand, u []uint) uint { +func randomUint(f *Faker, u []uint) uint { size := len(u) if size == 0 { return 0 @@ -195,46 +303,16 @@ func randomUint(r *rand.Rand, u []uint) uint { if size == 1 { return u[0] } - return u[r.Intn(size)] + return u[f.IntN(size)] } -// HexUint8 will generate a random uint8 hex value with "0x" prefix -func HexUint8() string { return hexUint(globalFaker.Rand, 8) } - -// HexUint8 will generate a random uint8 hex value with "0x" prefix -func (f *Faker) HexUint8() string { return hexUint(f.Rand, 8) } - -// HexUint16 will generate a random uint16 hex value with "0x" prefix -func HexUint16() string { return hexUint(globalFaker.Rand, 16) } - -// HexUint16 will generate a random uint16 hex value with "0x" prefix -func (f *Faker) HexUint16() string { return hexUint(f.Rand, 16) } - -// HexUint32 will generate a random uint32 hex value with "0x" prefix -func HexUint32() string { return hexUint(globalFaker.Rand, 32) } - -// HexUint32 will generate a random uint32 hex value with "0x" prefix -func (f *Faker) HexUint32() string { return hexUint(f.Rand, 32) } - -// HexUint64 will generate a random uint64 hex value with "0x" prefix -func HexUint64() string { return hexUint(globalFaker.Rand, 64) } +// HexUint will generate a random uint hex value with "0x" prefix +func HexUint(bitSize int) string { return hexUint(GlobalFaker, bitSize) } -// HexUint64 will generate a random uint64 hex value with "0x" prefix -func (f *Faker) HexUint64() string { return hexUint(f.Rand, 64) } +// HexUint will generate a random uint hex value with "0x" prefix +func (f *Faker) HexUint(bitSize int) string { return hexUint(f, bitSize) } -// HexUint128 will generate a random uint128 hex value with "0x" prefix -func HexUint128() string { return hexUint(globalFaker.Rand, 128) } - -// HexUint128 will generate a random uint128 hex value with "0x" prefix -func (f *Faker) HexUint128() string { return hexUint(f.Rand, 128) } - -// HexUint256 will generate a random uint256 hex value with "0x" prefix -func HexUint256() string { return hexUint(globalFaker.Rand, 256) } - -// HexUint256 will generate a random uint256 hex value with "0x" prefix -func (f *Faker) HexUint256() string { return hexUint(f.Rand, 256) } - -func hexUint(r *rand.Rand, bitSize int) string { +func hexUint(f *Faker, bitSize int) string { digits := []byte("0123456789abcdef") hexLen := (bitSize >> 2) + 2 if hexLen <= 2 { @@ -244,7 +322,7 @@ func hexUint(r *rand.Rand, bitSize int) string { s := make([]byte, hexLen) s[0], s[1] = '0', 'x' for i := 2; i < hexLen; i++ { - s[i] = digits[r.Intn(16)] + s[i] = digits[f.IntN(16)] } return string(s) } @@ -260,7 +338,7 @@ func addNumberLookup() { {Field: "min", Display: "Min", Type: "int", Default: "-2147483648", Description: "Minimum integer value"}, {Field: "max", Display: "Max", Type: "int", Default: "2147483647", Description: "Maximum integer value"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { min, err := info.GetInt(m, "min") if err != nil { return nil, err @@ -271,7 +349,37 @@ func addNumberLookup() { return nil, err } - return number(r, min, max), nil + return number(f, min, max), nil + }, + }) + + AddFuncLookup("uint", Info{ + Display: "Uint", + Category: "number", + Description: "Unsigned integer", + Example: "14866", + Output: "uint", + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return uintFunc(f), nil + }, + }) + + AddFuncLookup("uintn", Info{ + Display: "UintN", + Category: "number", + Description: "Unsigned integer between 0 and n", + Example: "32783", + Output: "uint", + Params: []Param{ + {Field: "n", Display: "N", Type: "uint", Default: "4294967295", Description: "Maximum uint value"}, + }, + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + n, err := info.GetUint(m, "n") + if err != nil { + return nil, err + } + + return uintNFunc(f, n), nil }, }) @@ -281,8 +389,8 @@ func addNumberLookup() { Description: "Unsigned 8-bit integer, capable of representing values from 0 to 255", Example: "152", Output: "uint8", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return uint8Func(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return uint8Func(f), nil }, }) @@ -292,8 +400,8 @@ func addNumberLookup() { Description: "Unsigned 16-bit integer, capable of representing values from 0 to 65,535", Example: "34968", Output: "uint16", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return uint16Func(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return uint16Func(f), nil }, }) @@ -303,8 +411,8 @@ func addNumberLookup() { Description: "Unsigned 32-bit integer, capable of representing values from 0 to 4,294,967,295", Example: "1075055705", Output: "uint32", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return uint32Func(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return uint32Func(f), nil }, }) @@ -314,8 +422,8 @@ func addNumberLookup() { Description: "Unsigned 64-bit integer, capable of representing values from 0 to 18,446,744,073,709,551,615", Example: "843730692693298265", Output: "uint64", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return uint64Func(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return f.Uint64(), nil }, }) @@ -329,7 +437,7 @@ func addNumberLookup() { {Field: "min", Display: "Min", Type: "uint", Default: "0", Description: "Minimum uint value"}, {Field: "max", Display: "Max", Type: "uint", Default: "4294967295", Description: "Maximum uint value"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { min, err := info.GetUint(m, "min") if err != nil { return nil, err @@ -340,7 +448,37 @@ func addNumberLookup() { return nil, err } - return uintRangeFunc(r, min, max), nil + return uintRangeFunc(f, min, max), nil + }, + }) + + AddFuncLookup("int", Info{ + Display: "Int", + Category: "number", + Description: "Signed integer", + Example: "14866", + Output: "int", + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return intFunc(f), nil + }, + }) + + AddFuncLookup("intn", Info{ + Display: "IntN", + Category: "number", + Description: "Integer value between 0 and n", + Example: "32783", + Output: "int", + Params: []Param{ + {Field: "n", Display: "N", Type: "int", Default: "2147483647", Description: "Maximum int value"}, + }, + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + n, err := info.GetInt(m, "n") + if err != nil { + return nil, err + } + + return intNFunc(f, n), nil }, }) @@ -350,8 +488,8 @@ func addNumberLookup() { Description: "Signed 8-bit integer, capable of representing values from -128 to 127", Example: "24", Output: "int8", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return int8Func(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return int8Func(f), nil }, }) @@ -361,8 +499,8 @@ func addNumberLookup() { Description: "Signed 16-bit integer, capable of representing values from 32,768 to 32,767", Example: "2200", Output: "int16", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return int16Func(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return int16Func(f), nil }, }) @@ -372,8 +510,8 @@ func addNumberLookup() { Description: "Signed 32-bit integer, capable of representing values from -2,147,483,648 to 2,147,483,647", Example: "-1072427943", Output: "int32", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return int32Func(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return int32Func(f), nil }, }) @@ -383,8 +521,8 @@ func addNumberLookup() { Description: "Signed 64-bit integer, capable of representing values from -9,223,372,036,854,775,808 to -9,223,372,036,854,775,807", Example: "-8379641344161477543", Output: "int64", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return int64Func(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return int64Func(f), nil }, }) @@ -398,7 +536,7 @@ func addNumberLookup() { {Field: "min", Display: "Min", Type: "int", Description: "Minimum int value"}, {Field: "max", Display: "Max", Type: "int", Description: "Maximum int value"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { min, err := info.GetInt(m, "min") if err != nil { return nil, err @@ -409,7 +547,7 @@ func addNumberLookup() { return nil, err } - return intRangeFunc(r, min, max), nil + return intRangeFunc(f, min, max), nil }, }) @@ -419,8 +557,8 @@ func addNumberLookup() { Description: "Data type representing floating-point numbers with 32 bits of precision in computing", Example: "3.1128167e+37", Output: "float32", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return float32Func(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return float32Func(f), nil }, }) @@ -434,7 +572,7 @@ func addNumberLookup() { {Field: "min", Display: "Min", Type: "float", Description: "Minimum float32 value"}, {Field: "max", Display: "Max", Type: "float", Description: "Maximum float32 value"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { min, err := info.GetFloat32(m, "min") if err != nil { return nil, err @@ -445,7 +583,7 @@ func addNumberLookup() { return nil, err } - return float32Range(r, min, max), nil + return float32Range(f, min, max), nil }, }) @@ -455,8 +593,8 @@ func addNumberLookup() { Description: "Data type representing floating-point numbers with 64 bits of precision in computing", Example: "1.644484108270445e+307", Output: "float64", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return float64Func(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return float64Func(f), nil }, }) @@ -470,7 +608,7 @@ func addNumberLookup() { {Field: "min", Display: "Min", Type: "float", Description: "Minimum float64 value"}, {Field: "max", Display: "Max", Type: "float", Description: "Maximum float64 value"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { min, err := info.GetFloat64(m, "min") if err != nil { return nil, err @@ -481,7 +619,7 @@ func addNumberLookup() { return nil, err } - return float64Range(r, min, max), nil + return float64Range(f, min, max), nil }, }) @@ -494,13 +632,13 @@ func addNumberLookup() { Params: []Param{ {Field: "ints", Display: "Integers", Type: "[]int", Description: "Delimited separated integers"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { ints, err := info.GetIntArray(m, "ints") if err != nil { return nil, err } - shuffleInts(r, ints) + shuffleInts(f, ints) return ints, nil }, @@ -515,13 +653,13 @@ func addNumberLookup() { Params: []Param{ {Field: "ints", Display: "Integers", Type: "[]int", Description: "Delimited separated integers"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { ints, err := info.GetIntArray(m, "ints") if err != nil { return nil, err } - return randomInt(r, ints), nil + return randomInt(f, ints), nil }, }) @@ -534,79 +672,32 @@ func addNumberLookup() { Params: []Param{ {Field: "uints", Display: "Unsigned Integers", Type: "[]uint", Description: "Delimited separated unsigned integers"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { uints, err := info.GetUintArray(m, "uints") if err != nil { return nil, err } - return randomUint(r, uints), nil + return randomUint(f, uints), nil }, }) - AddFuncLookup("hexuint8", Info{ - Display: "HexUint8", + AddFuncLookup("hexuint", Info{ + Display: "HexUint", Category: "number", - Description: "Hexadecimal representation of an 8-bit unsigned integer", + Description: "Hexadecimal representation of an unsigned integer", Example: "0x87", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hexUint(r, 8), nil - }, - }) - - AddFuncLookup("hexuint16", Info{ - Display: "HexUint16", - Category: "number", - Description: "Hexadecimal representation of an 16-bit unsigned integer", - Example: "0x8754", - Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hexUint(r, 16), nil - }, - }) - - AddFuncLookup("hexuint32", Info{ - Display: "HexUint32", - Category: "number", - Description: "Hexadecimal representation of an 32-bit unsigned integer", - Example: "0x87546957", - Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hexUint(r, 32), nil - }, - }) - - AddFuncLookup("hexuint64", Info{ - Display: "HexUint64", - Category: "number", - Description: "Hexadecimal representation of an 64-bit unsigned integer", - Example: "0x875469578e51b5e5", - Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hexUint(r, 64), nil - }, - }) - - AddFuncLookup("hexuint128", Info{ - Display: "HexUint128", - Category: "number", - Description: "Hexadecimal representation of an 128-bit unsigned integer", - Example: "0x875469578e51b5e56c95b64681d147a1", - Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hexUint(r, 128), nil + Params: []Param{ + {Field: "bitSize", Display: "Bit Size", Type: "int", Default: "8", Description: "Bit size of the unsigned integer"}, }, - }) + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + bitSize, err := info.GetInt(m, "bitSize") + if err != nil { + return nil, err + } - AddFuncLookup("hexuint256", Info{ - Display: "HexUint256", - Category: "number", - Description: "Hexadecimal representation of an 256-bit unsigned integer", - Example: "0x875469578e51b5e56c95b64681d147a12cde48a4f417231b0c486abbc263e48d", - Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hexUint(r, 256), nil + return hexUint(f, bitSize), nil }, }) } diff --git a/number_test.go b/number_test.go index 3c76f873..fbef50ed 100644 --- a/number_test.go +++ b/number_test.go @@ -9,502 +9,270 @@ func ExampleNumber() { Seed(11) fmt.Println(Number(50, 23456)) - // Output: 12583 + // Output: 21019 } func ExampleFaker_Number() { f := New(11) fmt.Println(f.Number(50, 23456)) - // Output: 12583 + // Output: 21019 } func BenchmarkNumber(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Number(10, 999999) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Number(10, 999999) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Number(10, 999999) - } - }) + for i := 0; i < b.N; i++ { + Number(10, 999999) + } } func ExampleUint8() { Seed(11) fmt.Println(Uint8()) - // Output: 152 + // Output: 180 } func ExampleFaker_Uint8() { f := New(11) fmt.Println(f.Uint8()) - // Output: 152 + // Output: 180 } func BenchmarkUint8(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Uint8() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Uint8() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Uint8() - } - }) + for i := 0; i < b.N; i++ { + Uint8() + } } func ExampleUint16() { Seed(11) fmt.Println(Uint16()) - // Output: 34968 + // Output: 56756 } func ExampleFaker_Uint16() { f := New(11) fmt.Println(f.Uint16()) - // Output: 34968 + // Output: 56756 } func BenchmarkUint16(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Uint16() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Uint16() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Uint16() - } - }) + for i := 0; i < b.N; i++ { + Uint16() + } } func ExampleUint32() { Seed(11) fmt.Println(Uint32()) - // Output: 1075055705 + // Output: 3847792206 } func ExampleFaker_Uint32() { f := New(11) fmt.Println(f.Uint32()) - // Output: 1075055705 + // Output: 3847792206 } func BenchmarkUint32(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Uint32() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Uint32() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Uint32() - } - }) + for i := 0; i < b.N; i++ { + Uint32() + } } func ExampleUint64() { Seed(11) fmt.Println(Uint64()) - // Output: 10067102729548074073 + // Output: 16526141687177076148 } func ExampleFaker_Uint64() { f := New(11) fmt.Println(f.Uint64()) - // Output: 10067102729548074073 + // Output: 16526141687177076148 } func BenchmarkUint64(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Uint64() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Uint64() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Uint64() - } - }) + for i := 0; i < b.N; i++ { + Uint64() + } } func ExampleUintRange() { Seed(11) fmt.Println(UintRange(1, 10)) - // Output: 1 + // Output: 9 } func ExampleFaker_UintRange() { f := New(11) fmt.Println(f.UintRange(1, 10)) - // Output: 1 + // Output: 9 } func BenchmarkUintRange(b *testing.B) { min := uint(1) max := uint(10) - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - UintRange(min, max) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.UintRange(min, max) - } - }) - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.UintRange(min, max) - } - }) + for i := 0; i < b.N; i++ { + UintRange(min, max) + } } func ExampleInt8() { Seed(11) fmt.Println(Int8()) - // Output: -39 + // Output: 52 } func ExampleFaker_Int8() { f := New(11) fmt.Println(f.Int8()) - // Output: -39 + // Output: 52 } func BenchmarkInt8(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Int8() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Int8() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Int8() - } - }) + for i := 0; i < b.N; i++ { + Int8() + } } func ExampleInt16() { Seed(11) fmt.Println(Int16()) - // Output: -29607 + // Output: 23988 } func ExampleFaker_Int16() { f := New(11) fmt.Println(f.Int16()) - // Output: -29607 + // Output: 23988 } func BenchmarkInt16(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Int16() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Int16() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Int16() - } - }) + for i := 0; i < b.N; i++ { + Int16() + } } func ExampleInt32() { Seed(11) fmt.Println(Int32()) - // Output: -1072427943 + // Output: 1923896103 } func ExampleFaker_Int32() { f := New(11) fmt.Println(f.Int32()) - // Output: -1072427943 + // Output: 1923896103 } func BenchmarkInt32(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Int32() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Int32() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Int32() - } - }) + for i := 0; i < b.N; i++ { + Int32() + } } func ExampleInt64() { Seed(11) fmt.Println(Int64()) - // Output: -8379641344161477543 + // Output: 7302769650322300340 } func ExampleFaker_Int64() { f := New(11) fmt.Println(f.Int64()) - // Output: -8379641344161477543 + // Output: 7302769650322300340 } func BenchmarkInt64(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Int64() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Int64() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Int64() - } - }) + for i := 0; i < b.N; i++ { + Int64() + } } func ExampleIntRange() { Seed(11) fmt.Println(IntRange(1, 10)) - // Output: 6 + // Output: 9 } func ExampleFaker_IntRange() { f := New(11) fmt.Println(f.IntRange(1, 10)) - // Output: 6 + // Output: 9 } func BenchmarkIntRange(b *testing.B) { min := int(1) max := int(10) - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - IntRange(min, max) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.IntRange(min, max) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - for i := 0; i < b.N; i++ { - f.IntRange(min, max) - } - }) + for i := 0; i < b.N; i++ { + IntRange(min, max) + } } func ExampleFloat32() { Seed(11) fmt.Println(Float32()) - // Output: 3.1128167e+37 + // Output: 0.3462876 } func ExampleFaker_Float32() { f := New(11) fmt.Println(f.Float32()) - // Output: 3.1128167e+37 + // Output: 0.3462876 } func BenchmarkFloat32(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Float32() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Float32() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Float32() - } - }) + for i := 0; i < b.N; i++ { + Float32() + } } func ExampleFloat32Range() { Seed(11) fmt.Println(Float32Range(0, 9999999)) - // Output: 914774.6 + // Output: 3.4628758e+06 } func ExampleFaker_Float32Range() { f := New(11) fmt.Println(f.Float32Range(0, 9999999)) - // Output: 914774.6 + // Output: 3.4628758e+06 } func BenchmarkFloat32Range(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Float32Range(10, 999999) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Float32Range(10, 999999) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Float32Range(10, 999999) - } - }) + for i := 0; i < b.N; i++ { + Float32Range(10, 999999) + } } func TestFloat32RangeSame(t *testing.T) { - if float32Range(globalFaker.Rand, 5.0, 5.0) != 5.0 { + if float32Range(GlobalFaker, 5.0, 5.0) != 5.0 { t.Error("You should have gotten 5.0 back") } } @@ -513,80 +281,44 @@ func ExampleFloat64() { Seed(11) fmt.Println(Float64()) - // Output: 1.644484108270445e+307 + // Output: 0.7703009321621068 } func ExampleFaker_Float64() { f := New(11) fmt.Println(f.Float64()) - // Output: 1.644484108270445e+307 + // Output: 0.7703009321621068 } func BenchmarkFloat64(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Float64() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Float64() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Float64() - } - }) + for i := 0; i < b.N; i++ { + Float64() + } } func ExampleFloat64Range() { Seed(11) fmt.Println(Float64Range(0, 9999999)) - // Output: 914774.5585333086 + // Output: 7.703008551320136e+06 } func ExampleFaker_Float64Range() { f := New(11) fmt.Println(f.Float64Range(0, 9999999)) - // Output: 914774.5585333086 + // Output: 7.703008551320136e+06 } func BenchmarkFloat64Range(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Float64Range(0, 999999) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Float64Range(0, 999999) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Float64Range(0, 999999) - } - }) + for i := 0; i < b.N; i++ { + Float64Range(0, 999999) + } } func TestRandFloat64RangeSame(t *testing.T) { - if float64Range(globalFaker.Rand, 5.0, 5.0) != 5.0 { + if float64Range(GlobalFaker, 5.0, 5.0) != 5.0 { t.Error("You should have gotten 5.0 back") } } @@ -598,7 +330,7 @@ func ExampleShuffleInts() { ShuffleInts(ints) fmt.Println(ints) - // Output: [74125 777 941 89416 8413 854 52 841657] + // Output: [941 777 8413 74125 854 89416 841657 52] } func ExampleFaker_ShuffleInts() { @@ -608,31 +340,13 @@ func ExampleFaker_ShuffleInts() { f.ShuffleInts(ints) fmt.Println(ints) - // Output: [74125 777 941 89416 8413 854 52 841657] + // Output: [941 777 8413 74125 854 89416 841657 52] } func BenchmarkShuffleInts(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - ShuffleInts([]int{52, 854, 941, 74125, 8413, 777, 89416, 841657}) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.ShuffleInts([]int{52, 854, 941, 74125, 8413, 777, 89416, 841657}) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.ShuffleInts([]int{52, 854, 941, 74125, 8413, 777, 89416, 841657}) - } - }) + for i := 0; i < b.N; i++ { + ShuffleInts([]int{52, 854, 941, 74125, 8413, 777, 89416, 841657}) + } } func ExampleRandomInt() { @@ -641,7 +355,7 @@ func ExampleRandomInt() { ints := []int{52, 854, 941, 74125, 8413, 777, 89416, 841657} fmt.Println(RandomInt(ints)) - // Output: 52 + // Output: 8413 } func ExampleFaker_RandomInt() { @@ -650,7 +364,7 @@ func ExampleFaker_RandomInt() { ints := []int{52, 854, 941, 74125, 8413, 777, 89416, 841657} fmt.Println(f.RandomInt(ints)) - // Output: 52 + // Output: 8413 } func TestRandomInt(t *testing.T) { @@ -673,7 +387,7 @@ func ExampleRandomUint() { ints := []uint{52, 854, 941, 74125, 8413, 777, 89416, 841657} fmt.Println(RandomUint(ints)) - // Output: 52 + // Output: 8413 } func ExampleFaker_RandomUint() { @@ -682,7 +396,7 @@ func ExampleFaker_RandomUint() { ints := []uint{52, 854, 941, 74125, 8413, 777, 89416, 841657} fmt.Println(f.RandomUint(ints)) - // Output: 52 + // Output: 8413 } func TestRandomUint(t *testing.T) { @@ -694,253 +408,27 @@ func TestRandomUint(t *testing.T) { } func BenchmarkRandomUint(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - RandomUint([]uint{52, 854, 941, 74125, 8413, 777, 89416, 841657}) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.RandomUint([]uint{52, 854, 941, 74125, 8413, 777, 89416, 841657}) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.RandomUint([]uint{52, 854, 941, 74125, 8413, 777, 89416, 841657}) - } - }) -} - -func ExampleHexUint8() { - Seed(11) - fmt.Println(HexUint8()) - - // Output: 0x87 -} - -func ExampleFaker_HexUint8() { - f := New(11) - fmt.Println(f.HexUint8()) - - // Output: 0x87 -} - -func BenchmarkHexUint8(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HexUint8() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HexUint8() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HexUint8() - } - }) -} - -func ExampleHexUint16() { - Seed(11) - fmt.Println(HexUint16()) - - // Output: 0x8754 -} - -func ExampleFaker_HexUint16() { - f := New(11) - fmt.Println(f.HexUint16()) - - // Output: 0x8754 -} - -func BenchmarkHexUint16(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HexUint16() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HexUint16() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HexUint16() - } - }) -} - -func ExampleHexUint32() { - Seed(11) - fmt.Println(HexUint32()) - - // Output: 0x87546957 -} - -func ExampleFaker_HexUint32() { - f := New(11) - fmt.Println(f.HexUint32()) - - // Output: 0x87546957 -} - -func BenchmarkHexUint32(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HexUint32() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HexUint32() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HexUint32() - } - }) -} - -func ExampleHexUint64() { - Seed(11) - fmt.Println(HexUint64()) - - // Output: 0x875469578e51b5e5 -} - -func ExampleFaker_HexUint64() { - f := New(11) - fmt.Println(f.HexUint64()) - - // Output: 0x875469578e51b5e5 -} - -func BenchmarkHexUint64(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HexUint64() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HexUint64() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HexUint64() - } - }) -} - -func ExampleHexUint128() { - Seed(11) - fmt.Println(HexUint128()) - - // Output: 0x875469578e51b5e56c95b64681d147a1 -} - -func ExampleFaker_HexUint128() { - f := New(11) - fmt.Println(f.HexUint128()) - - // Output: 0x875469578e51b5e56c95b64681d147a1 -} - -func BenchmarkHexUint128(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HexUint128() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HexUint128() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HexUint128() - } - }) + for i := 0; i < b.N; i++ { + RandomUint([]uint{52, 854, 941, 74125, 8413, 777, 89416, 841657}) + } } -func ExampleHexUint256() { +func ExampleHexUint() { Seed(11) - fmt.Println(HexUint256()) + fmt.Println(HexUint(16)) - // Output: 0x875469578e51b5e56c95b64681d147a12cde48a4f417231b0c486abbc263e48d + // Output: 0x425b } -func ExampleFaker_HexUint256() { +func ExampleFaker_HexUint() { f := New(11) - fmt.Println(f.HexUint256()) + fmt.Println(f.HexUint(16)) - // Output: 0x875469578e51b5e56c95b64681d147a12cde48a4f417231b0c486abbc263e48d + // Output: 0x425b } -func BenchmarkHexUint256(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - HexUint256() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.HexUint256() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.HexUint256() - } - }) +func BenchmarkHexUint(b *testing.B) { + for i := 0; i < b.N; i++ { + HexUint(16) + } } diff --git a/payment.go b/payment.go index dc4b0057..c9f0616f 100644 --- a/payment.go +++ b/payment.go @@ -2,12 +2,11 @@ package gofakeit import ( "math" - "math/rand" "strconv" "strings" "time" - "github.com/brianvoe/gofakeit/v6/data" + "github.com/brianvoe/gofakeit/v7/data" ) // CurrencyInfo is a struct of currency information @@ -17,13 +16,13 @@ type CurrencyInfo struct { } // Currency will generate a struct with random currency information -func Currency() *CurrencyInfo { return currency(globalFaker.Rand) } +func Currency() *CurrencyInfo { return currency(GlobalFaker) } // Currency will generate a struct with random currency information -func (f *Faker) Currency() *CurrencyInfo { return currency(f.Rand) } +func (f *Faker) Currency() *CurrencyInfo { return currency(f) } -func currency(r *rand.Rand) *CurrencyInfo { - index := r.Intn(len(data.Data["currency"]["short"])) +func currency(f *Faker) *CurrencyInfo { + index := f.IntN(len(data.Data["currency"]["short"])) return &CurrencyInfo{ Short: data.Data["currency"]["short"][index], Long: data.Data["currency"]["long"][index], @@ -31,29 +30,29 @@ func currency(r *rand.Rand) *CurrencyInfo { } // CurrencyShort will generate a random short currency value -func CurrencyShort() string { return currencyShort(globalFaker.Rand) } +func CurrencyShort() string { return currencyShort(GlobalFaker) } // CurrencyShort will generate a random short currency value -func (f *Faker) CurrencyShort() string { return currencyShort(f.Rand) } +func (f *Faker) CurrencyShort() string { return currencyShort(f) } -func currencyShort(r *rand.Rand) string { return getRandValue(r, []string{"currency", "short"}) } +func currencyShort(f *Faker) string { return getRandValue(f, []string{"currency", "short"}) } // CurrencyLong will generate a random long currency name -func CurrencyLong() string { return currencyLong(globalFaker.Rand) } +func CurrencyLong() string { return currencyLong(GlobalFaker) } // CurrencyLong will generate a random long currency name -func (f *Faker) CurrencyLong() string { return currencyLong(f.Rand) } +func (f *Faker) CurrencyLong() string { return currencyLong(f) } -func currencyLong(r *rand.Rand) string { return getRandValue(r, []string{"currency", "long"}) } +func currencyLong(f *Faker) string { return getRandValue(f, []string{"currency", "long"}) } // Price will take in a min and max value and return a formatted price -func Price(min, max float64) float64 { return price(globalFaker.Rand, min, max) } +func Price(min, max float64) float64 { return price(GlobalFaker, min, max) } // Price will take in a min and max value and return a formatted price -func (f *Faker) Price(min, max float64) float64 { return price(f.Rand, min, max) } +func (f *Faker) Price(min, max float64) float64 { return price(f, min, max) } -func price(r *rand.Rand, min, max float64) float64 { - return math.Floor(float64Range(r, min, max)*100) / 100 +func price(f *Faker, min, max float64) float64 { + return math.Floor(float64Range(f, min, max)*100) / 100 } // CreditCardInfo is a struct containing credit variables @@ -65,29 +64,29 @@ type CreditCardInfo struct { } // CreditCard will generate a struct full of credit card information -func CreditCard() *CreditCardInfo { return creditCard(globalFaker.Rand) } +func CreditCard() *CreditCardInfo { return creditCard(GlobalFaker) } // CreditCard will generate a struct full of credit card information -func (f *Faker) CreditCard() *CreditCardInfo { return creditCard(f.Rand) } +func (f *Faker) CreditCard() *CreditCardInfo { return creditCard(f) } -func creditCard(r *rand.Rand) *CreditCardInfo { - ccType := randomString(r, data.CreditCardTypes) +func creditCard(f *Faker) *CreditCardInfo { + ccType := randomString(f, data.CreditCardTypes) return &CreditCardInfo{ - Type: data.CreditCards[randomString(r, data.CreditCardTypes)].Display, - Number: creditCardNumber(r, &CreditCardOptions{Types: []string{ccType}}), - Exp: creditCardExp(r), - Cvv: generate(r, strings.Repeat("#", int(data.CreditCards[randomString(r, data.CreditCardTypes)].Code.Size))), + Type: data.CreditCards[randomString(f, data.CreditCardTypes)].Display, + Number: creditCardNumber(f, &CreditCardOptions{Types: []string{ccType}}), + Exp: creditCardExp(f), + Cvv: generate(f, strings.Repeat("#", int(data.CreditCards[randomString(f, data.CreditCardTypes)].Code.Size))), } } // CreditCardType will generate a random credit card type string -func CreditCardType() string { return creditCardType(globalFaker.Rand) } +func CreditCardType() string { return creditCardType(GlobalFaker) } // CreditCardType will generate a random credit card type string -func (f *Faker) CreditCardType() string { return creditCardType(f.Rand) } +func (f *Faker) CreditCardType() string { return creditCardType(f) } -func creditCardType(r *rand.Rand) string { - return data.CreditCards[randomString(r, data.CreditCardTypes)].Display +func creditCardType(f *Faker) string { + return data.CreditCards[randomString(f, data.CreditCardTypes)].Display } // CreditCardOptions is the options for credit card number @@ -98,39 +97,39 @@ type CreditCardOptions struct { } // CreditCardNumber will generate a random luhn credit card number -func CreditCardNumber(cco *CreditCardOptions) string { return creditCardNumber(globalFaker.Rand, cco) } +func CreditCardNumber(cco *CreditCardOptions) string { return creditCardNumber(GlobalFaker, cco) } // CreditCardNumber will generate a random luhn credit card number -func (f *Faker) CreditCardNumber(cco *CreditCardOptions) string { return creditCardNumber(f.Rand, cco) } +func (f *Faker) CreditCardNumber(cco *CreditCardOptions) string { return creditCardNumber(f, cco) } -func creditCardNumber(r *rand.Rand, cco *CreditCardOptions) string { +func creditCardNumber(f *Faker, cco *CreditCardOptions) string { if cco == nil { cco = &CreditCardOptions{} } if cco.Types == nil || len(cco.Types) == 0 { cco.Types = data.CreditCardTypes } - ccType := randomString(r, cco.Types) + ccType := randomString(f, cco.Types) // Get Card info var cardInfo data.CreditCardInfo if info, ok := data.CreditCards[ccType]; ok { cardInfo = info } else { - ccType = randomString(r, data.CreditCardTypes) + ccType = randomString(f, data.CreditCardTypes) cardInfo = data.CreditCards[ccType] } // Get length and pattern - length := randomUint(r, cardInfo.Lengths) + length := randomUint(f, cardInfo.Lengths) numStr := "" if len(cco.Bins) >= 1 { - numStr = randomString(r, cco.Bins) + numStr = randomString(f, cco.Bins) } else { - numStr = strconv.FormatUint(uint64(randomUint(r, cardInfo.Patterns)), 10) + numStr = strconv.FormatUint(uint64(randomUint(f, cardInfo.Patterns)), 10) } numStr += strings.Repeat("#", int(length)-len(numStr)) - numStr = numerify(r, numStr) + numStr = numerify(f, numStr) ui, _ := strconv.ParseUint(numStr, 10, 64) // Loop through until its a valid luhn @@ -155,31 +154,31 @@ func creditCardNumber(r *rand.Rand, cco *CreditCardOptions) string { // CreditCardExp will generate a random credit card expiration date string // Exp date will always be a future date -func CreditCardExp() string { return creditCardExp(globalFaker.Rand) } +func CreditCardExp() string { return creditCardExp(GlobalFaker) } // CreditCardExp will generate a random credit card expiration date string // Exp date will always be a future date -func (f *Faker) CreditCardExp() string { return creditCardExp(f.Rand) } +func (f *Faker) CreditCardExp() string { return creditCardExp(f) } -func creditCardExp(r *rand.Rand) string { - month := strconv.Itoa(randIntRange(r, 1, 12)) +func creditCardExp(f *Faker) string { + month := strconv.Itoa(randIntRange(f, 1, 12)) if len(month) == 1 { month = "0" + month } var currentYear = time.Now().Year() - 2000 - return month + "/" + strconv.Itoa(randIntRange(r, currentYear+1, currentYear+10)) + return month + "/" + strconv.Itoa(randIntRange(f, currentYear+1, currentYear+10)) } // CreditCardCvv will generate a random CVV number // Its a string because you could have 017 as an exp date -func CreditCardCvv() string { return creditCardCvv(globalFaker.Rand) } +func CreditCardCvv() string { return creditCardCvv(GlobalFaker) } // CreditCardCvv will generate a random CVV number // Its a string because you could have 017 as an exp date -func (f *Faker) CreditCardCvv() string { return creditCardCvv(f.Rand) } +func (f *Faker) CreditCardCvv() string { return creditCardCvv(f) } -func creditCardCvv(r *rand.Rand) string { return numerify(r, "###") } +func creditCardCvv(f *Faker) string { return numerify(f, "###") } // isLuhn check is used for checking if credit card is a valid luhn card func isLuhn(s string) bool { @@ -200,43 +199,43 @@ func isLuhn(s string) bool { } // AchRouting will generate a 9 digit routing number -func AchRouting() string { return achRouting(globalFaker.Rand) } +func AchRouting() string { return achRouting(GlobalFaker) } // AchRouting will generate a 9 digit routing number -func (f *Faker) AchRouting() string { return achRouting(f.Rand) } +func (f *Faker) AchRouting() string { return achRouting(f) } -func achRouting(r *rand.Rand) string { return numerify(r, "#########") } +func achRouting(f *Faker) string { return numerify(f, "#########") } // AchAccount will generate a 12 digit account number -func AchAccount() string { return achAccount(globalFaker.Rand) } +func AchAccount() string { return achAccount(GlobalFaker) } // AchAccount will generate a 12 digit account number -func (f *Faker) AchAccount() string { return achAccount(f.Rand) } +func (f *Faker) AchAccount() string { return achAccount(f) } -func achAccount(r *rand.Rand) string { return numerify(r, "############") } +func achAccount(f *Faker) string { return numerify(f, "############") } // BitcoinAddress will generate a random bitcoin address consisting of numbers, upper and lower characters -func BitcoinAddress() string { return bitcoinAddress(globalFaker.Rand) } +func BitcoinAddress() string { return bitcoinAddress(GlobalFaker) } // BitcoinAddress will generate a random bitcoin address consisting of numbers, upper and lower characters -func (f *Faker) BitcoinAddress() string { return bitcoinAddress(f.Rand) } +func (f *Faker) BitcoinAddress() string { return bitcoinAddress(f) } -func bitcoinAddress(r *rand.Rand) string { - return randomString(r, []string{"1", "3"}) + password(r, true, true, true, false, false, number(r, 25, 34)) +func bitcoinAddress(f *Faker) string { + return randomString(f, []string{"1", "3"}) + password(f, true, true, true, false, false, number(f, 25, 34)) } // BitcoinPrivateKey will generate a random bitcoin private key base58 consisting of numbers, upper and lower characters -func BitcoinPrivateKey() string { return bitcoinPrivateKey(globalFaker.Rand) } +func BitcoinPrivateKey() string { return bitcoinPrivateKey(GlobalFaker) } // BitcoinPrivateKey will generate a random bitcoin private key base58 consisting of numbers, upper and lower characters -func (f *Faker) BitcoinPrivateKey() string { return bitcoinPrivateKey(f.Rand) } +func (f *Faker) BitcoinPrivateKey() string { return bitcoinPrivateKey(f) } -func bitcoinPrivateKey(r *rand.Rand) string { +func bitcoinPrivateKey(f *Faker) string { var b strings.Builder for i := 0; i < 49; i++ { - b.WriteString(randCharacter(r, base58)) + b.WriteString(randCharacter(f, base58)) } - return "5" + randomString(r, []string{"H", "J", "K"}) + b.String() + return "5" + randomString(f, []string{"H", "J", "K"}) + b.String() } func addPaymentLookup() { @@ -250,8 +249,8 @@ func addPaymentLookup() { }`, Output: "map[string]string", ContentType: "application/json", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return currency(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return currency(f), nil }, }) @@ -261,8 +260,8 @@ func addPaymentLookup() { Description: "Short 3-letter word used to represent a specific currency", Example: "USD", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return currencyShort(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return currencyShort(f), nil }, }) @@ -272,8 +271,8 @@ func addPaymentLookup() { Description: "Complete name of a specific currency used for official identification in financial transactions", Example: "United States Dollar", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return currencyLong(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return currencyLong(f), nil }, }) @@ -287,7 +286,7 @@ func addPaymentLookup() { {Field: "min", Display: "Min", Type: "float", Default: "0", Description: "Minimum price value"}, {Field: "max", Display: "Max", Type: "float", Default: "1000", Description: "Maximum price value"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { min, err := info.GetFloat64(m, "min") if err != nil { return nil, err @@ -298,7 +297,7 @@ func addPaymentLookup() { return nil, err } - return price(r, min, max), nil + return price(f, min, max), nil }, }) @@ -314,8 +313,8 @@ func addPaymentLookup() { }`, Output: "map[string]any", ContentType: "application/json", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return creditCard(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return creditCard(f), nil }, }) @@ -325,8 +324,8 @@ func addPaymentLookup() { Description: "Classification of credit cards based on the issuing company", Example: "Visa", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return creditCardType(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return creditCardType(f), nil }, }) @@ -345,7 +344,7 @@ func addPaymentLookup() { {Field: "bins", Display: "Bins", Type: "[]string", Optional: true, Description: "Optional list of prepended bin numbers to pick from"}, {Field: "gaps", Display: "Gaps", Type: "bool", Default: "false", Description: "Whether or not to have gaps in number"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { types, err := info.GetStringArray(m, "types") if err != nil { return nil, err @@ -370,7 +369,7 @@ func addPaymentLookup() { options.Bins = bins } - return creditCardNumber(r, &options), nil + return creditCardNumber(f, &options), nil }, }) @@ -380,8 +379,8 @@ func addPaymentLookup() { Description: "Date when a credit card becomes invalid and cannot be used for transactions", Example: "01/21", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return creditCardExp(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return creditCardExp(f), nil }, }) @@ -391,8 +390,8 @@ func addPaymentLookup() { Description: "Three or four-digit security code on a credit card used for online and remote transactions", Example: "513", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return creditCardCvv(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return creditCardCvv(f), nil }, }) @@ -402,8 +401,8 @@ func addPaymentLookup() { Description: "Unique nine-digit code used in the U.S. for identifying the bank and processing electronic transactions", Example: "513715684", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return achRouting(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return achRouting(f), nil }, }) @@ -413,8 +412,8 @@ func addPaymentLookup() { Description: "A bank account number used for Automated Clearing House transactions and electronic transfers", Example: "491527954328", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return achAccount(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return achAccount(f), nil }, }) @@ -424,8 +423,8 @@ func addPaymentLookup() { Description: "Cryptographic identifier used to receive, store, and send Bitcoin cryptocurrency in a peer-to-peer network", Example: "1lWLbxojXq6BqWX7X60VkcDIvYA", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return bitcoinAddress(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return bitcoinAddress(f), nil }, }) @@ -435,8 +434,8 @@ func addPaymentLookup() { Description: "Secret, secure code that allows the owner to access and control their Bitcoin holdings", Example: "5vrbXTADWJ6sQBSYd6lLkG97jljNc0X9VPBvbVqsIH9lWOLcoqg", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return bitcoinPrivateKey(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return bitcoinPrivateKey(f), nil }, }) } diff --git a/payment_test.go b/payment_test.go index 2eca3b8d..c48c3852 100644 --- a/payment_test.go +++ b/payment_test.go @@ -11,9 +11,8 @@ func ExampleCurrency() { fmt.Println(currency.Short) fmt.Println(currency.Long) - // Output: - // IQD - // Iraq Dinar + // Output: UGX + // Uganda Shilling } func ExampleFaker_Currency() { @@ -22,9 +21,8 @@ func ExampleFaker_Currency() { fmt.Println(currency.Short) fmt.Println(currency.Long) - // Output: - // IQD - // Iraq Dinar + // Output: UGX + // Uganda Shilling } func BenchmarkCurrency(b *testing.B) { @@ -37,14 +35,14 @@ func ExampleCurrencyShort() { Seed(11) fmt.Println(CurrencyShort()) - // Output: IQD + // Output: UGX } func ExampleFaker_CurrencyShort() { f := New(11) fmt.Println(f.CurrencyShort()) - // Output: IQD + // Output: UGX } func BenchmarkCurrencyShort(b *testing.B) { @@ -57,14 +55,14 @@ func ExampleCurrencyLong() { Seed(11) fmt.Println(CurrencyLong()) - // Output: Iraq Dinar + // Output: Uganda Shilling } func ExampleFaker_CurrencyLong() { f := New(11) fmt.Println(f.CurrencyLong()) - // Output: Iraq Dinar + // Output: Uganda Shilling } func BenchmarkCurrencyLong(b *testing.B) { @@ -77,14 +75,14 @@ func ExamplePrice() { Seed(11) fmt.Printf("%.2f", Price(0.8618, 1000)) - // Output: 92.26 + // Output: 770.49 } func ExampleFaker_Price() { f := New(11) fmt.Printf("%.2f", f.Price(0.8618, 1000)) - // Output: 92.26 + // Output: 770.49 } func BenchmarkPrice(b *testing.B) { @@ -101,11 +99,10 @@ func ExampleCreditCard() { fmt.Println(ccInfo.Exp) fmt.Println(ccInfo.Cvv) - // Output: - // UnionPay - // 4364599489953698 - // 02/25 - // 300 + // Output: Hiper + // 6370952527598909 + // 12/34 + // 344 } func ExampleFaker_CreditCard() { @@ -116,11 +113,10 @@ func ExampleFaker_CreditCard() { fmt.Println(ccInfo.Exp) fmt.Println(ccInfo.Cvv) - // Output: - // UnionPay - // 4364599489953698 - // 02/25 - // 300 + // Output: Hiper + // 6370952527598909 + // 12/34 + // 344 } func BenchmarkCreditCard(b *testing.B) { @@ -133,14 +129,14 @@ func ExampleCreditCardType() { Seed(11) fmt.Println(CreditCardType()) - // Output: Visa + // Output: Hiper } func ExampleFaker_CreditCardType() { f := New(11) fmt.Println(f.CreditCardType()) - // Output: Visa + // Output: Hiper } func BenchmarkCreditCardType(b *testing.B) { @@ -156,11 +152,10 @@ func ExampleCreditCardNumber() { fmt.Println(CreditCardNumber(&CreditCardOptions{Bins: []string{"4111"}})) fmt.Println(CreditCardNumber(&CreditCardOptions{Gaps: true})) - // Output: - // 4136459948995375 - // 4635300425914586 - // 4111232020276132 - // 3054 800889 9827 + // Output: 6376121252759896 + // 6449344737930519 + // 4111026894059156 + // 6706 2052 5709 6 } func ExampleFaker_CreditCardNumber() { @@ -170,11 +165,10 @@ func ExampleFaker_CreditCardNumber() { fmt.Println(f.CreditCardNumber(&CreditCardOptions{Bins: []string{"4111"}})) fmt.Println(f.CreditCardNumber(&CreditCardOptions{Gaps: true})) - // Output: - // 4136459948995375 - // 4635300425914586 - // 4111232020276132 - // 3054 800889 9827 + // Output: 6376121252759896 + // 6449344737930519 + // 4111026894059156 + // 6706 2052 5709 6 } func TestCreditCardNumber(t *testing.T) { @@ -192,7 +186,7 @@ func TestCreditCardNumberLookup(t *testing.T) { m := NewMapParams() m.Add("gaps", "true") - _, err := info.Generate(faker.Rand, m, info) + _, err := info.Generate(faker, m, info) if err != nil { t.Fatal(err.Error()) } @@ -222,14 +216,14 @@ func ExampleCreditCardExp() { Seed(11) fmt.Println(CreditCardExp()) - // Output: 06/31 + // Output: 11/33 } func ExampleFaker_CreditCardExp() { f := New(11) fmt.Println(f.CreditCardExp()) - // Output: 06/31 + // Output: 11/33 } func BenchmarkCreditCardExp(b *testing.B) { @@ -242,14 +236,14 @@ func ExampleCreditCardCvv() { Seed(11) fmt.Println(CreditCardCvv()) - // Output: 513 + // Output: 881 } func ExampleFaker_CreditCardCvv() { f := New(11) fmt.Println(f.CreditCardCvv()) - // Output: 513 + // Output: 881 } func BenchmarkCreditCardCvv(b *testing.B) { @@ -262,14 +256,14 @@ func ExampleAchRouting() { Seed(11) fmt.Println(AchRouting()) - // Output: 713645994 + // Output: 881252759 } func ExampleFaker_AchRouting() { f := New(11) fmt.Println(f.AchRouting()) - // Output: 713645994 + // Output: 881252759 } func BenchmarkAchRouting(b *testing.B) { @@ -282,14 +276,14 @@ func ExampleAchAccount() { Seed(11) fmt.Println(AchAccount()) - // Output: 413645994899 + // Output: 881252759890 } func ExampleFaker_AchAccount() { f := New(11) fmt.Println(f.AchAccount()) - // Output: 413645994899 + // Output: 881252759890 } func BenchmarkAchAccount(b *testing.B) { @@ -302,14 +296,14 @@ func ExampleBitcoinAddress() { Seed(11) fmt.Println(BitcoinAddress()) - // Output: 1zXE46Al58w4vS0459PHl6YwElXZH09e + // Output: 13blsBo8bffq7a35c5nwLT4eXWu0pReLF1 } func ExampleFaker_BitcoinAddress() { f := New(11) fmt.Println(f.BitcoinAddress()) - // Output: 1zXE46Al58w4vS0459PHl6YwElXZH09e + // Output: 13blsBo8bffq7a35c5nwLT4eXWu0pReLF1 } func BenchmarkBitcoinAddress(b *testing.B) { @@ -322,14 +316,14 @@ func ExampleBitcoinPrivateKey() { Seed(11) fmt.Println(BitcoinPrivateKey()) - // Output: 5KWjEJ7SnBNJyDjdPUjLuYByYzM9rG1trax8c2NTSBtv7YtR57v + // Output: 5JMZxkQX2PgaasaHc8wnWLNdMu7rxeU7xS64ev7RWNinacicPfm } func ExampleFaker_BitcoinPrivateKey() { f := New(11) fmt.Println(f.BitcoinPrivateKey()) - // Output: 5KWjEJ7SnBNJyDjdPUjLuYByYzM9rG1trax8c2NTSBtv7YtR57v + // Output: 5JMZxkQX2PgaasaHc8wnWLNdMu7rxeU7xS64ev7RWNinacicPfm } func BenchmarkBitcoinPrivateKey(b *testing.B) { diff --git a/person.go b/person.go index c1fe99f3..fbd173da 100644 --- a/person.go +++ b/person.go @@ -2,7 +2,6 @@ package gofakeit import ( "math" - "math/rand" "strconv" "strings" ) @@ -22,92 +21,92 @@ type PersonInfo struct { } // Person will generate a struct with person information -func Person() *PersonInfo { return person(globalFaker.Rand) } +func Person() *PersonInfo { return person(GlobalFaker) } // Person will generate a struct with person information -func (f *Faker) Person() *PersonInfo { return person(f.Rand) } +func (f *Faker) Person() *PersonInfo { return person(f) } -func person(r *rand.Rand) *PersonInfo { +func person(f *Faker) *PersonInfo { return &PersonInfo{ - FirstName: firstName(r), - LastName: lastName(r), - Gender: gender(r), - SSN: ssn(r), - Image: imageURL(r, number(r, 100, 500), number(r, 100, 500)), - Hobby: hobby(r), - Job: job(r), - Address: address(r), - Contact: contact(r), - CreditCard: creditCard(r), + FirstName: firstName(f), + LastName: lastName(f), + Gender: gender(f), + SSN: ssn(f), + Image: imageURL(f, number(f, 100, 500), number(f, 100, 500)), + Hobby: hobby(f), + Job: job(f), + Address: address(f), + Contact: contact(f), + CreditCard: creditCard(f), } } // Name will generate a random First and Last Name -func Name() string { return name(globalFaker.Rand) } +func Name() string { return name(GlobalFaker) } // Name will generate a random First and Last Name -func (f *Faker) Name() string { return name(f.Rand) } +func (f *Faker) Name() string { return name(f) } -func name(r *rand.Rand) string { - return getRandValue(r, []string{"person", "first"}) + " " + getRandValue(r, []string{"person", "last"}) +func name(f *Faker) string { + return getRandValue(f, []string{"person", "first"}) + " " + getRandValue(f, []string{"person", "last"}) } // FirstName will generate a random first name -func FirstName() string { return firstName(globalFaker.Rand) } +func FirstName() string { return firstName(GlobalFaker) } // FirstName will generate a random first name -func (f *Faker) FirstName() string { return firstName(f.Rand) } +func (f *Faker) FirstName() string { return firstName(f) } -func firstName(r *rand.Rand) string { return getRandValue(r, []string{"person", "first"}) } +func firstName(f *Faker) string { return getRandValue(f, []string{"person", "first"}) } // MiddleName will generate a random middle name -func MiddleName() string { return middleName(globalFaker.Rand) } +func MiddleName() string { return middleName(GlobalFaker) } // MiddleName will generate a random middle name -func (f *Faker) MiddleName() string { return middleName(f.Rand) } +func (f *Faker) MiddleName() string { return middleName(f) } -func middleName(r *rand.Rand) string { return getRandValue(r, []string{"person", "middle"}) } +func middleName(f *Faker) string { return getRandValue(f, []string{"person", "middle"}) } // LastName will generate a random last name -func LastName() string { return lastName(globalFaker.Rand) } +func LastName() string { return lastName(GlobalFaker) } // LastName will generate a random last name -func (f *Faker) LastName() string { return lastName(f.Rand) } +func (f *Faker) LastName() string { return lastName(f) } -func lastName(r *rand.Rand) string { return getRandValue(r, []string{"person", "last"}) } +func lastName(f *Faker) string { return getRandValue(f, []string{"person", "last"}) } // NamePrefix will generate a random name prefix -func NamePrefix() string { return namePrefix(globalFaker.Rand) } +func NamePrefix() string { return namePrefix(GlobalFaker) } // NamePrefix will generate a random name prefix -func (f *Faker) NamePrefix() string { return namePrefix(f.Rand) } +func (f *Faker) NamePrefix() string { return namePrefix(f) } -func namePrefix(r *rand.Rand) string { return getRandValue(r, []string{"person", "prefix"}) } +func namePrefix(f *Faker) string { return getRandValue(f, []string{"person", "prefix"}) } // NameSuffix will generate a random name suffix -func NameSuffix() string { return nameSuffix(globalFaker.Rand) } +func NameSuffix() string { return nameSuffix(GlobalFaker) } // NameSuffix will generate a random name suffix -func (f *Faker) NameSuffix() string { return nameSuffix(f.Rand) } +func (f *Faker) NameSuffix() string { return nameSuffix(f) } -func nameSuffix(r *rand.Rand) string { return getRandValue(r, []string{"person", "suffix"}) } +func nameSuffix(f *Faker) string { return getRandValue(f, []string{"person", "suffix"}) } // SSN will generate a random Social Security Number -func SSN() string { return ssn(globalFaker.Rand) } +func SSN() string { return ssn(GlobalFaker) } // SSN will generate a random Social Security Number -func (f *Faker) SSN() string { return ssn(f.Rand) } +func (f *Faker) SSN() string { return ssn(f) } -func ssn(r *rand.Rand) string { return strconv.Itoa(randIntRange(r, 100000000, 999999999)) } +func ssn(f *Faker) string { return strconv.Itoa(randIntRange(f, 100000000, 999999999)) } // Gender will generate a random gender string -func Gender() string { return gender(globalFaker.Rand) } +func Gender() string { return gender(GlobalFaker) } // Gender will generate a random gender string -func (f *Faker) Gender() string { return gender(f.Rand) } +func (f *Faker) Gender() string { return gender(f) } -func gender(r *rand.Rand) string { - if boolFunc(r) { +func gender(f *Faker) string { + if boolFunc(f) { return "male" } @@ -115,12 +114,12 @@ func gender(r *rand.Rand) string { } // Hobby will generate a random hobby string -func Hobby() string { return hobby(globalFaker.Rand) } +func Hobby() string { return hobby(GlobalFaker) } // Hobby will generate a random hobby string -func (f *Faker) Hobby() string { return hobby(f.Rand) } +func (f *Faker) Hobby() string { return hobby(f) } -func hobby(r *rand.Rand) string { return getRandValue(r, []string{"person", "hobby"}) } +func hobby(f *Faker) string { return getRandValue(f, []string{"person", "hobby"}) } // ContactInfo struct full of contact info type ContactInfo struct { @@ -129,64 +128,64 @@ type ContactInfo struct { } // Contact will generate a struct with information randomly populated contact information -func Contact() *ContactInfo { return contact(globalFaker.Rand) } +func Contact() *ContactInfo { return contact(GlobalFaker) } // Contact will generate a struct with information randomly populated contact information -func (f *Faker) Contact() *ContactInfo { return contact(f.Rand) } +func (f *Faker) Contact() *ContactInfo { return contact(f) } -func contact(r *rand.Rand) *ContactInfo { +func contact(f *Faker) *ContactInfo { return &ContactInfo{ - Phone: phone(r), - Email: email(r), + Phone: phone(f), + Email: email(f), } } // Phone will generate a random phone number string -func Phone() string { return phone(globalFaker.Rand) } +func Phone() string { return phone(GlobalFaker) } // Phone will generate a random phone number string -func (f *Faker) Phone() string { return phone(f.Rand) } +func (f *Faker) Phone() string { return phone(f) } -func phone(r *rand.Rand) string { return replaceWithNumbers(r, "##########") } +func phone(f *Faker) string { return replaceWithNumbers(f, "##########") } // PhoneFormatted will generate a random phone number string -func PhoneFormatted() string { return phoneFormatted(globalFaker.Rand) } +func PhoneFormatted() string { return phoneFormatted(GlobalFaker) } // PhoneFormatted will generate a random phone number string -func (f *Faker) PhoneFormatted() string { return phoneFormatted(f.Rand) } +func (f *Faker) PhoneFormatted() string { return phoneFormatted(f) } -func phoneFormatted(r *rand.Rand) string { - return replaceWithNumbers(r, getRandValue(r, []string{"person", "phone"})) +func phoneFormatted(f *Faker) string { + return replaceWithNumbers(f, getRandValue(f, []string{"person", "phone"})) } // Email will generate a random email string -func Email() string { return email(globalFaker.Rand) } +func Email() string { return email(GlobalFaker) } // Email will generate a random email string -func (f *Faker) Email() string { return email(f.Rand) } +func (f *Faker) Email() string { return email(f) } -func email(r *rand.Rand) string { - email := getRandValue(r, []string{"person", "first"}) + getRandValue(r, []string{"person", "last"}) +func email(f *Faker) string { + email := getRandValue(f, []string{"person", "first"}) + getRandValue(f, []string{"person", "last"}) email += "@" - email += getRandValue(r, []string{"person", "last"}) + "." + getRandValue(r, []string{"internet", "domain_suffix"}) + email += getRandValue(f, []string{"person", "last"}) + "." + getRandValue(f, []string{"internet", "domain_suffix"}) return strings.ToLower(email) } // Teams takes in an array of people and team names and randomly places the people into teams as evenly as possible func Teams(peopleArray []string, teamsArray []string) map[string][]string { - return teams(globalFaker.Rand, peopleArray, teamsArray) + return teams(GlobalFaker, peopleArray, teamsArray) } // Teams takes in an array of people and team names and randomly places the people into teams as evenly as possible func (f *Faker) Teams(peopleArray []string, teamsArray []string) map[string][]string { - return teams(f.Rand, peopleArray, teamsArray) + return teams(f, peopleArray, teamsArray) } -func teams(r *rand.Rand, people []string, teams []string) map[string][]string { +func teams(f *Faker, people []string, teams []string) map[string][]string { // Shuffle the people if more than 1 if len(people) > 1 { - shuffleStrings(r, people) + shuffleStrings(f, people) } peopleIndex := 0 @@ -246,8 +245,8 @@ func addPersonLookup() { }`, Output: "map[string]any", ContentType: "application/json", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return person(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return person(f), nil }, }) @@ -257,8 +256,8 @@ func addPersonLookup() { Description: "The given and family name of an individual", Example: "Markus Moen", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return name(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return name(f), nil }, }) @@ -268,8 +267,8 @@ func addPersonLookup() { Description: "A title or honorific added before a person's name", Example: "Mr.", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return namePrefix(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return namePrefix(f), nil }, }) @@ -279,8 +278,8 @@ func addPersonLookup() { Description: "A title or designation added after a person's name", Example: "Jr.", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return nameSuffix(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return nameSuffix(f), nil }, }) @@ -290,8 +289,8 @@ func addPersonLookup() { Description: "The name given to a person at birth", Example: "Markus", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return firstName(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return firstName(f), nil }, }) @@ -301,8 +300,8 @@ func addPersonLookup() { Description: "Name between a person's first name and last name", Example: "Belinda", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return middleName(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return middleName(f), nil }, }) @@ -312,8 +311,8 @@ func addPersonLookup() { Description: "The family name or surname of an individual", Example: "Daniel", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return lastName(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return lastName(f), nil }, }) @@ -323,8 +322,8 @@ func addPersonLookup() { Description: "Classification based on social and cultural norms that identifies an individual", Example: "male", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return gender(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return gender(f), nil }, }) @@ -334,8 +333,8 @@ func addPersonLookup() { Description: "Unique nine-digit identifier used for government and financial purposes in the United States", Example: "296446360", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return ssn(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return ssn(f), nil }, }) @@ -345,8 +344,8 @@ func addPersonLookup() { Description: "An activity pursued for leisure and pleasure", Example: "Swimming", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hobby(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return hobby(f), nil }, }) @@ -356,8 +355,8 @@ func addPersonLookup() { Description: "Electronic mail used for sending digital messages and communication over the internet", Example: "markusmoen@pagac.net", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return email(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return email(f), nil }, }) @@ -367,8 +366,8 @@ func addPersonLookup() { Description: "Numerical sequence used to contact individuals via telephone or mobile devices", Example: "6136459948", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return phone(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return phone(f), nil }, }) @@ -378,8 +377,8 @@ func addPersonLookup() { Description: "Formatted phone number of a person", Example: "136-459-9489", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return phoneFormatted(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return phoneFormatted(f), nil }, }) @@ -409,7 +408,7 @@ func addPersonLookup() { {Field: "people", Display: "Strings", Type: "[]string", Description: "Array of people"}, {Field: "teams", Display: "Strings", Type: "[]string", Description: "Array of teams"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { people, err := info.GetStringArray(m, "people") if err != nil { return nil, err @@ -420,7 +419,7 @@ func addPersonLookup() { return nil, err } - return teams(r, people, teamsArray), nil + return teams(f, people, teamsArray), nil }, }) } diff --git a/person_test.go b/person_test.go index 9bd14bba..13fca3ef 100644 --- a/person_test.go +++ b/person_test.go @@ -9,14 +9,14 @@ func ExampleName() { Seed(11) fmt.Println(Name()) - // Output: Markus Moen + // Output: Sonny Stiedemann } func ExampleFaker_Name() { f := New(11) fmt.Println(f.Name()) - // Output: Markus Moen + // Output: Sonny Stiedemann } func BenchmarkName(b *testing.B) { @@ -29,14 +29,14 @@ func ExampleFirstName() { Seed(11) fmt.Println(FirstName()) - // Output: Markus + // Output: Sonny } func ExampleFaker_FirstName() { f := New(11) fmt.Println(f.FirstName()) - // Output: Markus + // Output: Sonny } func BenchmarkFirstName(b *testing.B) { @@ -49,14 +49,14 @@ func ExampleMiddleName() { Seed(11) fmt.Println(MiddleName()) - // Output: Belinda + // Output: Star } func ExampleFaker_MiddleName() { f := New(11) fmt.Println(f.MiddleName()) - // Output: Belinda + // Output: Star } func BenchmarkMiddleName(b *testing.B) { @@ -69,14 +69,14 @@ func ExampleLastName() { Seed(11) fmt.Println(LastName()) - // Output: Daniel + // Output: Treutel } func ExampleFaker_LastName() { f := New(11) fmt.Println(f.LastName()) - // Output: Daniel + // Output: Treutel } func BenchmarkLastName(b *testing.B) { @@ -89,14 +89,14 @@ func ExampleNamePrefix() { Seed(11) fmt.Println(NamePrefix()) - // Output: Mr. + // Output: Dr. } func ExampleFaker_NamePrefix() { f := New(11) fmt.Println(f.NamePrefix()) - // Output: Mr. + // Output: Dr. } func BenchmarkNamePrefix(b *testing.B) { @@ -109,14 +109,14 @@ func ExampleNameSuffix() { Seed(11) fmt.Println(NameSuffix()) - // Output: Jr. + // Output: PhD } func ExampleFaker_NameSuffix() { f := New(11) fmt.Println(f.NameSuffix()) - // Output: Jr. + // Output: PhD } func BenchmarkNameSuffix(b *testing.B) { @@ -129,14 +129,14 @@ func ExampleSSN() { Seed(11) fmt.Println(SSN()) - // Output: 493298265 + // Output: 906295542 } func ExampleFaker_SSN() { f := New(11) fmt.Println(f.SSN()) - // Output: 493298265 + // Output: 906295542 } func BenchmarkSSN(b *testing.B) { @@ -149,14 +149,14 @@ func ExampleGender() { Seed(11) fmt.Println(Gender()) - // Output: male + // Output: female } func ExampleFaker_Gender() { f := New(11) fmt.Println(f.Gender()) - // Output: male + // Output: female } func BenchmarkGender(b *testing.B) { @@ -169,14 +169,14 @@ func ExampleHobby() { Seed(11) fmt.Println(Hobby()) - // Output: Transit map collecting + // Output: Marching band } func ExampleFaker_Hobby() { f := New(11) fmt.Println(f.Hobby()) - // Output: Transit map collecting + // Output: Marching band } func BenchmarkHobby(b *testing.B) { @@ -222,31 +222,30 @@ func ExamplePerson() { fmt.Println(creditCard.Exp) fmt.Println(creditCard.Cvv) - // Output: - // Markus - // Moen + // Output: Sonny + // Stiedemann // male - // 275413589 - // https://picsum.photos/208/500 - // Lacrosse - // Intermap Technologies - // Developer - // Direct - // Paradigm - // 369 North Cornerbury, Miami, North Dakota 24259 - // 369 North Cornerbury - // Miami - // North Dakota - // 24259 - // Ghana - // -6.662595 - // 23.921575 - // 3023202027 - // lamarkoelpin@heaney.biz + // 280254464 + // https://picsum.photos/311/192 + // Sea glass collecting + // Mango Transit + // Supervisor + // National + // Solutions + // 999 West Lanebury, Lincoln, Kansas 93050 + // 999 West Lanebury + // Lincoln + // Kansas + // 93050 + // Uganda + // -0.729058 + // -53.873895 + // 6268940591 + // hopeprohaska@metz.io // Maestro - // 39800889982276 - // 01/30 - // 932 + // 4205257093875723 + // 02/32 + // 782 } func ExampleFaker_Person() { @@ -286,31 +285,30 @@ func ExampleFaker_Person() { fmt.Println(creditCard.Exp) fmt.Println(creditCard.Cvv) - // Output: - // Markus - // Moen + // Output: Sonny + // Stiedemann // male - // 275413589 - // https://picsum.photos/208/500 - // Lacrosse - // Intermap Technologies - // Developer - // Direct - // Paradigm - // 369 North Cornerbury, Miami, North Dakota 24259 - // 369 North Cornerbury - // Miami - // North Dakota - // 24259 - // Ghana - // -6.662595 - // 23.921575 - // 3023202027 - // lamarkoelpin@heaney.biz + // 280254464 + // https://picsum.photos/311/192 + // Sea glass collecting + // Mango Transit + // Supervisor + // National + // Solutions + // 999 West Lanebury, Lincoln, Kansas 93050 + // 999 West Lanebury + // Lincoln + // Kansas + // 93050 + // Uganda + // -0.729058 + // -53.873895 + // 6268940591 + // hopeprohaska@metz.io // Maestro - // 39800889982276 - // 01/30 - // 932 + // 4205257093875723 + // 02/32 + // 782 } func BenchmarkPerson(b *testing.B) { @@ -325,8 +323,8 @@ func ExampleContact() { fmt.Println(contact.Phone) fmt.Println(contact.Email) - // Output: 6136459948 - // carolecarroll@bosco.com + // Output: 8812527598 + // stevebins@robel.io } func ExampleFaker_Contact() { @@ -335,8 +333,8 @@ func ExampleFaker_Contact() { fmt.Println(contact.Phone) fmt.Println(contact.Email) - // Output: 6136459948 - // carolecarroll@bosco.com + // Output: 8812527598 + // stevebins@robel.io } func BenchmarkContact(b *testing.B) { @@ -349,14 +347,14 @@ func ExamplePhone() { Seed(11) fmt.Println(Phone()) - // Output: 6136459948 + // Output: 8812527598 } func ExampleFaker_Phone() { f := New(11) fmt.Println(f.Phone()) - // Output: 6136459948 + // Output: 8812527598 } func BenchmarkPhone(b *testing.B) { @@ -369,14 +367,14 @@ func ExamplePhoneFormatted() { Seed(11) fmt.Println(PhoneFormatted()) - // Output: 136-459-9489 + // Output: 812-527-5989 } func ExampleFaker_PhoneFormatted() { f := New(11) fmt.Println(f.PhoneFormatted()) - // Output: 136-459-9489 + // Output: 812-527-5989 } func BenchmarkPhoneFormatted(b *testing.B) { @@ -389,14 +387,14 @@ func ExampleEmail() { Seed(11) fmt.Println(Email()) - // Output: markusmoen@pagac.net + // Output: sonnystiedemann@donnelly.biz } func ExampleFaker_Email() { f := New(11) fmt.Println(f.Email()) - // Output: markusmoen@pagac.net + // Output: sonnystiedemann@donnelly.biz } func BenchmarkEmail(b *testing.B) { @@ -412,7 +410,7 @@ func ExampleTeams() { []string{"Team 1", "Team 2", "Team 3"}, )) - // Output: map[Team 1:[Fabian Connor Steve] Team 2:[Jeff Sharon Justin] Team 3:[Robert Billy]] + // Output: map[Team 1:[Jeff Robert Billy] Team 2:[Connor Fabian Sharon] Team 3:[Justin Steve]] } func ExampleFaker_Teams() { @@ -422,7 +420,7 @@ func ExampleFaker_Teams() { []string{"Team 1", "Team 2", "Team 3"}, )) - // Output: map[Team 1:[Fabian Connor Steve] Team 2:[Jeff Sharon Justin] Team 3:[Robert Billy]] + // Output: map[Team 1:[Jeff Robert Billy] Team 2:[Connor Fabian Sharon] Team 3:[Justin Steve]] } func BenchmarkTeams(b *testing.B) { diff --git a/product.go b/product.go index 7483ecbe..f0f8ea76 100644 --- a/product.go +++ b/product.go @@ -2,7 +2,6 @@ package gofakeit import ( "fmt" - "math/rand" "strings" ) @@ -18,140 +17,140 @@ type ProductInfo struct { } // Product will generate a random set of product information -func Product() *ProductInfo { return product(globalFaker.Rand) } +func Product() *ProductInfo { return product(GlobalFaker) } // Product will generate a random set of product information -func (f *Faker) Product() *ProductInfo { return product(f.Rand) } +func (f *Faker) Product() *ProductInfo { return product(f) } -func product(r *rand.Rand) *ProductInfo { +func product(f *Faker) *ProductInfo { // Categories categories := []string{} - weightedCategory, _ := weighted(r, []any{1, 2, 3, 4}, []float32{1, 4, 3, 4}) + weightedCategory, _ := weighted(f, []any{1, 2, 3, 4}, []float32{1, 4, 3, 4}) for i := 0; i < weightedCategory.(int); i++ { - categories = append(categories, productCategory(r)) + categories = append(categories, productCategory(f)) } // Features features := []string{} - for i := 0; i < number(r, 1, 5); i++ { - features = append(features, productFeature(r)) + for i := 0; i < number(f, 1, 5); i++ { + features = append(features, productFeature(f)) } product := &ProductInfo{ - Name: productName(r), - Description: productDescription(r), + Name: productName(f), + Description: productDescription(f), Categories: categories, - Price: price(r, 3.00, 100.00), - UPC: productUPC(r), + Price: price(f, 3.00, 100.00), + UPC: productUPC(f), Features: features, - Color: safeColor(r), - Material: productMaterial(r), + Color: safeColor(f), + Material: productMaterial(f), } return product } // ProductName will generate a random product name -func ProductName() string { return productName(globalFaker.Rand) } +func ProductName() string { return productName(GlobalFaker) } // ProductName will generate a random product name -func (f *Faker) ProductName() string { return productName(f.Rand) } +func (f *Faker) ProductName() string { return productName(f) } -func productName(r *rand.Rand) string { - name := getRandValue(r, []string{"product", "name"}) - switch number(r, 0, 9) { +func productName(f *Faker) string { + name := getRandValue(f, []string{"product", "name"}) + switch number(f, 0, 9) { case 1: // Name + Adjective + Feature - return title(fmt.Sprintf("%s %s %s", name, getRandValue(r, []string{"product", "adjective"}), productFeature(r))) + return title(fmt.Sprintf("%s %s %s", name, getRandValue(f, []string{"product", "adjective"}), productFeature(f))) case 2: // Adjective + Material + Name - return title(fmt.Sprintf("%s %s %s", getRandValue(r, []string{"product", "adjective"}), productMaterial(r), name)) + return title(fmt.Sprintf("%s %s %s", getRandValue(f, []string{"product", "adjective"}), productMaterial(f), name)) case 3: // Color + Name + Suffix - return title(fmt.Sprintf("%s %s %s", safeColor(r), name, getRandValue(r, []string{"product", "suffix"}))) + return title(fmt.Sprintf("%s %s %s", safeColor(f), name, getRandValue(f, []string{"product", "suffix"}))) case 4: // Feature + Name + Adjective - return title(fmt.Sprintf("%s %s %s", productFeature(r), name, getRandValue(r, []string{"product", "adjective"}))) + return title(fmt.Sprintf("%s %s %s", productFeature(f), name, getRandValue(f, []string{"product", "adjective"}))) case 5: // Material + Color + Name - return title(fmt.Sprintf("%s %s %s", productMaterial(r), safeColor(r), name)) + return title(fmt.Sprintf("%s %s %s", productMaterial(f), safeColor(f), name)) case 6: // Name + Suffix + Material - return title(fmt.Sprintf("%s %s %s", name, getRandValue(r, []string{"product", "suffix"}), productMaterial(r))) + return title(fmt.Sprintf("%s %s %s", name, getRandValue(f, []string{"product", "suffix"}), productMaterial(f))) case 7: // Adjective + Feature + Name - return title(fmt.Sprintf("%s %s %s", getRandValue(r, []string{"product", "adjective"}), productFeature(r), name)) + return title(fmt.Sprintf("%s %s %s", getRandValue(f, []string{"product", "adjective"}), productFeature(f), name)) case 8: // Color + Material + Name - return title(fmt.Sprintf("%s %s %s", safeColor(r), productMaterial(r), name)) + return title(fmt.Sprintf("%s %s %s", safeColor(f), productMaterial(f), name)) case 9: // Suffix + Adjective + Name - return title(fmt.Sprintf("%s %s %s", getRandValue(r, []string{"product", "suffix"}), getRandValue(r, []string{"product", "adjective"}), name)) + return title(fmt.Sprintf("%s %s %s", getRandValue(f, []string{"product", "suffix"}), getRandValue(f, []string{"product", "adjective"}), name)) } // case: 0 - Adjective + Name + Suffix - return title(fmt.Sprintf("%s %s %s", getRandValue(r, []string{"product", "adjective"}), name, getRandValue(r, []string{"product", "suffix"}))) + return title(fmt.Sprintf("%s %s %s", getRandValue(f, []string{"product", "adjective"}), name, getRandValue(f, []string{"product", "suffix"}))) } // ProductDescription will generate a random product description -func ProductDescription() string { return productDescription(globalFaker.Rand) } +func ProductDescription() string { return productDescription(GlobalFaker) } // ProductDescription will generate a random product description -func (f *Faker) ProductDescription() string { return productDescription(f.Rand) } +func (f *Faker) ProductDescription() string { return productDescription(f) } -func productDescription(r *rand.Rand) string { +func productDescription(f *Faker) string { desc := []string{} - for i := 0; i < number(r, 1, 3); i++ { - desc = append(desc, sentence(r, number(r, 5, 15))) + for i := 0; i < number(f, 1, 3); i++ { + desc = append(desc, sentence(f, number(f, 5, 15))) } return strings.Join(desc, " ") } // ProductCategory will generate a random product category -func ProductCategory() string { return productCategory(globalFaker.Rand) } +func ProductCategory() string { return productCategory(GlobalFaker) } // ProductCategory will generate a random product category -func (f *Faker) ProductCategory() string { return productCategory(f.Rand) } +func (f *Faker) ProductCategory() string { return productCategory(f) } -func productCategory(r *rand.Rand) string { - return getRandValue(r, []string{"product", "category"}) +func productCategory(f *Faker) string { + return getRandValue(f, []string{"product", "category"}) } // ProductFeature will generate a random product feature -func ProductFeature() string { return productFeature(globalFaker.Rand) } +func ProductFeature() string { return productFeature(GlobalFaker) } // ProductFeature will generate a random product feature -func (f *Faker) ProductFeature() string { return productFeature(f.Rand) } +func (f *Faker) ProductFeature() string { return productFeature(f) } -func productFeature(r *rand.Rand) string { - return getRandValue(r, []string{"product", "feature"}) +func productFeature(f *Faker) string { + return getRandValue(f, []string{"product", "feature"}) } // ProductMaterial will generate a random product material -func ProductMaterial() string { return productMaterial(globalFaker.Rand) } +func ProductMaterial() string { return productMaterial(GlobalFaker) } // ProductMaterial will generate a random product material -func (f *Faker) ProductMaterial() string { return productMaterial(f.Rand) } +func (f *Faker) ProductMaterial() string { return productMaterial(f) } -func productMaterial(r *rand.Rand) string { - return getRandValue(r, []string{"product", "material"}) +func productMaterial(f *Faker) string { + return getRandValue(f, []string{"product", "material"}) } // ProductUPC will generate a random product UPC -func ProductUPC() string { return productUPC(globalFaker.Rand) } +func ProductUPC() string { return productUPC(GlobalFaker) } // ProductUPC will generate a random product UPC -func (f *Faker) ProductUPC() string { return productUPC(f.Rand) } +func (f *Faker) ProductUPC() string { return productUPC(f) } -func productUPC(r *rand.Rand) string { +func productUPC(f *Faker) string { // The first digit of a UPC is a fixed digit (usually 0) upc := "0" // Generate the remaining 11 digits randomly for i := 1; i < 12; i++ { - digit := number(r, 0, 9) + digit := number(f, 0, 9) upc += fmt.Sprintf("%d", digit) } @@ -180,8 +179,8 @@ func addProductLookup() { }`, Output: "map[string]any", ContentType: "application/json", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return product(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return product(f), nil }, }) @@ -191,8 +190,8 @@ func addProductLookup() { Description: "Distinctive title or label assigned to a product for identification and marketing", Example: "olive copper monitor", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return productName(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return productName(f), nil }, }) @@ -202,8 +201,8 @@ func addProductLookup() { Description: "Explanation detailing the features and characteristics of a product", Example: "Backwards caused quarterly without week it hungry thing someone him regularly. Whomever this revolt hence from his timing as quantity us these yours.", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return productDescription(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return productDescription(f), nil }, }) @@ -213,8 +212,8 @@ func addProductLookup() { Description: "Classification grouping similar products based on shared characteristics or functions", Example: "clothing", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return productCategory(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return productCategory(f), nil }, }) @@ -224,8 +223,8 @@ func addProductLookup() { Description: "Specific characteristic of a product that distinguishes it from others products", Example: "ultra-lightweight", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return productFeature(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return productFeature(f), nil }, }) @@ -235,8 +234,8 @@ func addProductLookup() { Description: "The substance from which a product is made, influencing its appearance, durability, and properties", Example: "brass", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return productMaterial(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return productMaterial(f), nil }, }) @@ -246,8 +245,8 @@ func addProductLookup() { Description: "Standardized barcode used for product identification and tracking in retail and commerce", Example: "012780949980", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return productUPC(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return productUPC(f), nil }, }) } diff --git a/product_test.go b/product_test.go index 0688d93a..408cc281 100644 --- a/product_test.go +++ b/product_test.go @@ -17,14 +17,14 @@ func ExampleProduct() { fmt.Println(product.Material) fmt.Println(product.UPC) - // Output: Olive Copper Monitor - // Choir computer still far unless army party riches theirs instead here. Whichever that those instance growth has ouch enough Swiss us since down he. Aha us you to upon how this this furniture way no play towel. - // [clothing tools and hardware] - // 41.61 - // [ultra-lightweight] - // olive - // stainless - // 074937734366 + // Output: Wave Precision Lamp + // Since previously was that there a tennis occur why. Heels out can fire anyone sometimes. Leap whom troop now scarcely. + // [cosmetics outdoor gear] + // 49.18 + // [touchscreen ultra-lightweight gps-enabled biometric] + // green + // brass + // 082447816155 } func ExampleFaker_Product() { @@ -39,14 +39,14 @@ func ExampleFaker_Product() { fmt.Println(product.Material) fmt.Println(product.UPC) - // Output: Olive Copper Monitor - // Choir computer still far unless army party riches theirs instead here. Whichever that those instance growth has ouch enough Swiss us since down he. Aha us you to upon how this this furniture way no play towel. - // [clothing tools and hardware] - // 41.61 - // [ultra-lightweight] - // olive - // stainless - // 074937734366 + // Output: Wave Precision Lamp + // Since previously was that there a tennis occur why. Heels out can fire anyone sometimes. Leap whom troop now scarcely. + // [cosmetics outdoor gear] + // 49.18 + // [touchscreen ultra-lightweight gps-enabled biometric] + // green + // brass + // 082447816155 } func TestProduct(t *testing.T) { @@ -87,41 +87,23 @@ func TestProduct(t *testing.T) { } func BenchmarkProduct(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Product() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Product() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Product() - } - }) + for i := 0; i < b.N; i++ { + Product() + } } func ExampleProductName() { Seed(11) fmt.Println(ProductName()) - // Output: Appliance Pulse Leather + // Output: Green Glass Hair Dryer } func ExampleFaker_ProductName() { f := New(11) fmt.Println(f.ProductName()) - // Output: Appliance Pulse Leather + // Output: Green Glass Hair Dryer } func BenchmarkProductName(b *testing.B) { @@ -134,14 +116,14 @@ func ExampleProductDescription() { Seed(11) fmt.Println(ProductDescription()) - // Output: How these keep trip Congolese choir computer still far unless army party riches theirs instead. Mine whichever that those instance. Has ouch enough Swiss us since down. + // Output: Regularly quiver these sprint fight something am elsewhere since previously was that there a. Occur why depend heels out can fire anyone sometimes that leap whom troop now. } func ExampleFaker_ProductDescription() { f := New(11) fmt.Println(f.ProductDescription()) - // Output: How these keep trip Congolese choir computer still far unless army party riches theirs instead. Mine whichever that those instance. Has ouch enough Swiss us since down. + // Output: Regularly quiver these sprint fight something am elsewhere since previously was that there a. Occur why depend heels out can fire anyone sometimes that leap whom troop now. } func BenchmarkProductDescription(b *testing.B) { @@ -154,14 +136,14 @@ func ExampleProductCategory() { Seed(11) fmt.Println(ProductCategory()) - // Output: pet supplies + // Output: pet food } func ExampleFaker_ProductCategory() { f := New(11) fmt.Println(f.ProductCategory()) - // Output: pet supplies + // Output: pet food } func BenchmarkProductCategory(b *testing.B) { @@ -174,14 +156,14 @@ func ExampleProductFeature() { Seed(11) fmt.Println(ProductFeature()) - // Output: wireless + // Output: fast-charging } func ExampleFaker_ProductFeature() { f := New(11) fmt.Println(f.ProductFeature()) - // Output: wireless + // Output: fast-charging } func BenchmarkProductFeature(b *testing.B) { @@ -194,14 +176,14 @@ func ExampleProductMaterial() { Seed(11) fmt.Println(ProductMaterial()) - // Output: silicon + // Output: quartz } func ExampleFaker_ProductMaterial() { f := New(11) fmt.Println(f.ProductMaterial()) - // Output: silicon + // Output: quartz } func BenchmarkProductMaterial(b *testing.B) { @@ -214,14 +196,14 @@ func ExampleProductUPC() { Seed(11) fmt.Println(ProductUPC()) - // Output: 056990598130 + // Output: 088125275989 } func ExampleFaker_ProductUPC() { f := New(11) fmt.Println(f.ProductUPC()) - // Output: 056990598130 + // Output: 088125275989 } func BenchmarkProductUPC(b *testing.B) { diff --git a/school.go b/school.go index f90daef5..b100ab80 100644 --- a/school.go +++ b/school.go @@ -1,17 +1,14 @@ package gofakeit -import "math/rand" - // School will generate a random School type -func School() string { return school(globalFaker.Rand) } +func School() string { return school(GlobalFaker) } -func (f *Faker) School() string { return school(f.Rand) } +func (f *Faker) School() string { return school(f) } -func school(r *rand.Rand) string { - return getRandValue( - r, []string{"school", "name"}) + " " + - getRandValue(r, []string{"school", "isPrivate"}) + " " + - getRandValue(r, []string{"school", "type"}) +func school(f *Faker) string { + return getRandValue(f, []string{"school", "name"}) + " " + + getRandValue(f, []string{"school", "isPrivate"}) + " " + + getRandValue(f, []string{"school", "type"}) } func addSchoolLookup() { @@ -21,8 +18,8 @@ func addSchoolLookup() { Description: "An institution for formal education and learning", Example: `Harborview State Academy`, Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return school(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return school(f), nil }, }) } diff --git a/school_test.go b/school_test.go index 63531e27..b0b7141d 100644 --- a/school_test.go +++ b/school_test.go @@ -8,37 +8,19 @@ import ( func ExampleSchool() { Seed(11) fmt.Println(School()) - // Output: - // Harborview State Academy + + // Output: Hillside Private Academy } func ExampleFaker_School() { f := New(11) fmt.Println(f.School()) - // Output: - // Harborview State Academy + + // Output: Hillside Private Academy } func BenchmarkSchool(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - School() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.School() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.School() - } - }) + for i := 0; i < b.N; i++ { + School() + } } diff --git a/slice.go b/slice.go index eec5e43d..f9636eec 100644 --- a/slice.go +++ b/slice.go @@ -5,7 +5,7 @@ import ( ) // Slice fills built-in types and exported fields of a struct with random data. -func Slice(v any) { sliceFunc(globalFaker, v) } +func Slice(v any) { sliceFunc(GlobalFaker, v) } // Slice fills built-in types and exported fields of a struct with random data. func (f *Faker) Slice(v any) { sliceFunc(f, v) } diff --git a/slice_test.go b/slice_test.go index 61bca3d5..ba568d54 100644 --- a/slice_test.go +++ b/slice_test.go @@ -16,8 +16,8 @@ func ExampleSlice() { fmt.Println(S) fmt.Println(I) - // Output: [RMaRxHkiJ PtapWYJdn MKgtlxwnq qclaYkWw oRLOPxLIok qanPAKaXS] - // [-88 -101 60] + // Output: [KKbMlbxqu mwwv WVlPmw AeAwVH Khrx DcxFeWk vChMCeKf BwRtnboOE mWluN] + // [102 -7 -125] } func ExampleFaker_Slice() { @@ -32,8 +32,8 @@ func ExampleFaker_Slice() { fmt.Println(S) fmt.Println(I) - // Output: [RMaRxHkiJ PtapWYJdn MKgtlxwnq qclaYkWw oRLOPxLIok qanPAKaXS] - // [-88 -101 60] + // Output: [KKbMlbxqu mwwv WVlPmw AeAwVH Khrx DcxFeWk vChMCeKf BwRtnboOE mWluN] + // [102 -7 -125] } func ExampleSlice_struct() { @@ -50,7 +50,7 @@ func ExampleSlice_struct() { fmt.Println(B) - // Output: [{Marcel -1697368647228132669 1.9343967e+38} {Lura 1052100795806789315 2.670526e+38} {Lucinda 4409580151121052361 1.0427679e+38} {Santino 2168696190310795206 2.2573786e+38} {Dawn 3859340644268985534 4.249854e+37} {Alice 9082579350789565885 1.0573345e+38}] + // Output: [{Russ 3680786209731553973 0.27238095} {Julius 4268594234476337060 0.0051180124} {Kaitlyn 8337306475187377941 0.118576884} {Steve 1365845625386394310 0.27625358} {Tomasa 7952567920265354269 0.648698} {Ernest 7933890822314871011 0.37052673} {Missouri 5542429450337529393 0.36615264} {Tiana 6292602578870227868 0.9382272} {Koby 229639691709918065 0.5914113}] } func ExampleFaker_Slice_struct() { @@ -67,5 +67,5 @@ func ExampleFaker_Slice_struct() { fmt.Println(B) - // Output: [{Marcel -1697368647228132669 1.9343967e+38} {Lura 1052100795806789315 2.670526e+38} {Lucinda 4409580151121052361 1.0427679e+38} {Santino 2168696190310795206 2.2573786e+38} {Dawn 3859340644268985534 4.249854e+37} {Alice 9082579350789565885 1.0573345e+38}] + // Output: [{Russ 3680786209731553973 0.27238095} {Julius 4268594234476337060 0.0051180124} {Kaitlyn 8337306475187377941 0.118576884} {Steve 1365845625386394310 0.27625358} {Tomasa 7952567920265354269 0.648698} {Ernest 7933890822314871011 0.37052673} {Missouri 5542429450337529393 0.36615264} {Tiana 6292602578870227868 0.9382272} {Koby 229639691709918065 0.5914113}] } diff --git a/source/BENCHMARKS.md b/source/BENCHMARKS.md new file mode 100644 index 00000000..fdef2811 --- /dev/null +++ b/source/BENCHMARKS.md @@ -0,0 +1,16 @@ +go test -bench=. -benchmem +goos: darwin +goarch: amd64 +pkg: github.com/brianvoe/gofakeit/v7 +cpu: Apple M1 Max +Table generated with tablesgenerator.com/markdown_tables File->Paste table data + +| Benchmark | Iterations| Time/Iter | Bytes | Allocations | +|---------------------|-----------|-------------|--------|-------------| +| BenchmarkCrypto-10 | 15747936 | 77.15 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkDumb-10 | 458967214 | 2.611 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkJSF-10 | 323858558 | 3.712 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkOld-10 | 207714157 | 5.733 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkChaCha8-10 | 228052915 | 5.262 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkPCG-10 | 251946703 | 4.763 ns/op | 0 B/op | 0 allocs/op | +| BenchmarkSFC-10 | 394809136 | 3.035 ns/op | 0 B/op | 0 allocs/op | \ No newline at end of file diff --git a/source/README.md b/source/README.md new file mode 100644 index 00000000..3358ebea --- /dev/null +++ b/source/README.md @@ -0,0 +1,65 @@ +# Random Number Generators Collection + +This repository contains a collection of random number generators (RNGs) implemented in Go, designed to cater to a wide range of applications, from cryptographic operations to testing environments. Each RNG in the collection offers distinct features and performance characteristics, making it suitable for various use cases, including those requiring cryptographic security. + +## Generators + +### Crypto + +- **Description**: Utilizes Go's `crypto/rand` package to provide cryptographically secure random numbers, suitable for security-sensitive applications. +- **Usage**: + ```go + source := NewCryptoSource() + number := source.Uint64() + ``` + +### JSF (Jenkins Small Fast) + +- **Description**: An implementation of the Jenkins Small Fast hash function for efficient pseudo-random number generation, balancing speed and randomness quality for general use. +- **Usage**: + ```go + source := NewJSFSource(seed) + number := source.Uint64() + ``` + +### SFC (Simple Fast Counter) + +- **Description**: Based on the Simple Fast Counter algorithm, this source offers rapid number generation with satisfactory randomness properties, ideal for simulations and non-cryptographic applications. +- **Usage**: + ```go + source := NewSFCSource(seed) + number := source.Uint64() + ``` + +### Dumb + +- **Description**: A deterministic generator designed primarily for testing, providing predictable output for scenarios where consistent results are more beneficial than high-quality randomness. +- **Usage**: + ```go + source := NewDumb(seed) + number := source.Uint64() + ``` + +## Installation + +To use these RNGs in your Go project, import the package as follows: + +```go +import "github.com/yourusername/randsource" +``` + +Replace `yourusername` with your GitHub username or organization name where the repository is hosted. + +## Usage + +After importing the package, initialize the desired RNG with or without a seed (as applicable) and use the `Uint64` method to generate random numbers. See the usage examples under each generator's description for more details. + +## Benchmarks + +Performance benchmarks for each RNG are provided to help you choose the right generator for your application. These benchmarks cover various aspects, including speed and randomness quality. + +For detailed benchmark results, see the [Benchmarks](https://github.com/brianvoe/gofakeit/blob/master/source/BENCHMARKS.md) file. + +## Contributing + +We welcome contributions and suggestions! Please open an issue or submit a pull request with your improvements. diff --git a/source/crypto.go b/source/crypto.go new file mode 100644 index 00000000..95634092 --- /dev/null +++ b/source/crypto.go @@ -0,0 +1,55 @@ +package source + +import ( + "crypto/rand" + "encoding/binary" +) + +// Package source implements a cryptographically secure pseudo-random number generator (CSPRNG) +// using Go's crypto/rand. The Crypto type is designed for generating high-quality random +// uint64 values, suitable for cryptographic applications like secure token generation, +// cryptographic key creation, and other security-sensitive operations. It offers optional +// thread safety through a locking mechanism, making it suitable for concurrent usage. + +// Pros: +// - Provides cryptographically secure randomness, suitable for security-sensitive applications. +// - Optional thread safety with locking, enabling safe concurrent access. + +// Cons: +// - Locking mechanism, when enabled, may introduce performance overhead. +// - Does not utilize a seed, as it leverages the system's cryptographic RNG, which may be a +// limitation in scenarios where deterministic pseudo-randomness is desired. + +type Crypto struct { + buffer [64]byte // Buffer to hold a block of random data + offset int // Current offset in the buffer +} + +// NewCrypto creates a new instance of Crypto. +func NewCrypto() *Crypto { + return &Crypto{ + buffer: [64]byte{}, // Initialize buffer with zeros + offset: 64, // Set offset to the end of the buffer to trigger a refill on the first call + } +} + +// refillBuffer fills the buffer with random data from crypto/rand. +func (s *Crypto) refillBuffer() { + if _, err := rand.Read(s.buffer[:]); err != nil { + panic("crypto/rand failed: " + err.Error()) // Handle the error appropriately for your application + } + s.offset = 0 // Reset offset after refilling +} + +// Uint64 generates a pseudo-random 64-bit value using crypto/rand, served from a buffered block of data. +func (s *Crypto) Uint64() uint64 { + if s.offset+8 > len(s.buffer) { // Check if we need to refill the buffer + s.refillBuffer() + } + + // Extract a uint64 value from the current position in the buffer + val := binary.BigEndian.Uint64(s.buffer[s.offset:]) + s.offset += 8 // Move the offset for the next call + + return val +} diff --git a/source/crypto_test.go b/source/crypto_test.go new file mode 100644 index 00000000..7a9bd59f --- /dev/null +++ b/source/crypto_test.go @@ -0,0 +1,25 @@ +package source + +import "testing" + +func TestCrypto(t *testing.T) { + crypto := NewCrypto() + + // test for duplicates + m := make(map[uint64]bool) + for i := 0; i < 100000; i++ { + v := crypto.Uint64() + if m[v] { + t.Errorf("Duplicate value: %v", v) + } + m[v] = true + } +} + +func BenchmarkCrypto(b *testing.B) { + crypto := NewCrypto() + + for i := 0; i < b.N; i++ { + crypto.Uint64() + } +} diff --git a/source/dumb.go b/source/dumb.go new file mode 100644 index 00000000..784f5589 --- /dev/null +++ b/source/dumb.go @@ -0,0 +1,44 @@ +package source + +import "time" + +// Dumb is a deterministic pseudo-random number generator designed specifically for testing purposes. +// It offers predictable sequences of numbers based on the provided seed, making it ideal for scenarios +// where consistent and reproducible test results are critical. By default, if initialized with a seed of 0, +// Dumb uses the current timestamp to generate a starting point, ensuring some level of variability between runs. + +// Pros: +// - Predictability: Ensures reproducible outcomes in tests by providing a consistent sequence of numbers for a given seed. +// - Simplicity: Easy to understand and integrate into testing frameworks, with minimal overhead. +// - Default Variability: Uses the current timestamp as the default seed, providing variability across different test runs when no seed is specified. + +// Cons: +// - Not Suitable for Production: Lacks the randomness quality required for production-level cryptographic or statistical applications. +// - Limited Randomness: The simple incrementation approach does not simulate the complexity of real-world random number generation. + +// Dumb is a simplistic generator for predictable testing. +type Dumb struct { + state uint64 +} + +// NewDumb initializes a Dumb generator. +// If the seed is 0, initializes with the current timestamp. +func NewDumb(seed uint64) *Dumb { + d := &Dumb{} + d.Seed(seed) + return d +} + +// Seed sets the generator's state. If the seed is 0, it uses the current timestamp as the seed. +func (d *Dumb) Seed(seed uint64) { + if seed == 0 { + seed = uint64(time.Now().UnixNano()) + } + d.state = seed +} + +// Uint64 returns the next number in the sequence, incrementing the state. +func (d *Dumb) Uint64() uint64 { + d.state += 1 + return d.state +} diff --git a/source/dumb_test.go b/source/dumb_test.go new file mode 100644 index 00000000..8dd9b667 --- /dev/null +++ b/source/dumb_test.go @@ -0,0 +1,26 @@ +package source + +import "testing" + +func TestDumb(t *testing.T) { + dumb := NewDumb(0) + dumb.Seed(0) + + // test for duplicates + m := make(map[uint64]bool) + for i := 0; i < 10000; i++ { + v := dumb.Uint64() + if m[v] { + t.Errorf("Duplicate value: %v", v) + } + m[v] = true + } +} + +func BenchmarkDumb(b *testing.B) { + dumb := NewDumb(0) + + for i := 0; i < b.N; i++ { + dumb.Uint64() + } +} diff --git a/source/jsf.go b/source/jsf.go new file mode 100644 index 00000000..1432d662 --- /dev/null +++ b/source/jsf.go @@ -0,0 +1,50 @@ +package source + +// The JSF(Jenkins Small Fast) pseudo-random number generator. +// Developed by Bob Jenkins, JSF is known for its speed and efficiency, making it suitable +// for applications requiring fast, non-cryptographic quality random numbers. This implementation +// offers seamless integration with Go's math/rand package and includes an improved seeding mechanism. + +// Pros: +// - Fast and efficient, ideal for high-performance requirements. +// - Good randomness quality for non-cryptographic applications. +// - Small state size and simple operations, ensuring a minimal memory footprint. + +// Cons: +// - Not suitable for cryptographic purposes due to its non-cryptographic security level. +// - Quality of randomness may not match that of more complex algorithms. + +type JSF struct { + a, b, c, d uint32 +} + +// NewJSF creates and returns a new JSF pseudo-random number generator. +func NewJSF(seed uint64) *JSF { + jsf := &JSF{} + jsf.Seed(seed) + return jsf +} + +// Seed sets the seed of the JSF with an improved seeding mechanism. +func (jsf *JSF) Seed(seed uint64) { + // Use the seed to derive initial values for a, b, c, d with better distribution + // Splitting the 64-bit seed into parts and using different operations to diversify + s1 := uint32(seed) + s2 := uint32(seed >> 32) + jsf.a = 0xf1ea5eed + jsf.b = s1 ^ jsf.a + jsf.c = s2 ^ jsf.b + jsf.d = s1 +} + +// Uint64 generates a pseudo-random 64-bit value using the improved JSF algorithm. +func (jsf *JSF) Uint64() uint64 { + e := jsf.a - (jsf.b<<27 | jsf.b>>(32-27)) + f := jsf.b ^ (jsf.c << 17) + jsf.c += jsf.d + jsf.d += e + jsf.a = jsf.b + f + jsf.b = jsf.c + e + jsf.c = f + jsf.a + return uint64(jsf.d)<<32 | uint64(jsf.a) +} diff --git a/source/jsf_test.go b/source/jsf_test.go new file mode 100644 index 00000000..23a5ab78 --- /dev/null +++ b/source/jsf_test.go @@ -0,0 +1,26 @@ +package source + +import "testing" + +func TestJSF(t *testing.T) { + jsf := NewJSF(0) + jsf.Seed(0) + + // test for duplicates + m := make(map[uint64]bool) + for i := 0; i < 10000; i++ { + v := jsf.Uint64() + if m[v] { + t.Errorf("Duplicate value: %v", v) + } + m[v] = true + } +} + +func BenchmarkJSF(b *testing.B) { + jsf := NewJSF(0) + + for i := 0; i < b.N; i++ { + jsf.Uint64() + } +} diff --git a/source/others_test.go b/source/others_test.go new file mode 100644 index 00000000..a72bce93 --- /dev/null +++ b/source/others_test.go @@ -0,0 +1,22 @@ +package source + +import ( + "math/rand/v2" + "testing" +) + +func BenchmarkChaCha8(b *testing.B) { + chacha := rand.NewChaCha8([32]byte{0, 1, 2, 3, 4, 5}) + + for i := 0; i < b.N; i++ { + chacha.Uint64() + } +} + +func BenchmarkPCG(b *testing.B) { + pcg := rand.NewPCG(0, 0) + + for i := 0; i < b.N; i++ { + pcg.Uint64() + } +} diff --git a/source/sfc.go b/source/sfc.go new file mode 100644 index 00000000..0357aeec --- /dev/null +++ b/source/sfc.go @@ -0,0 +1,44 @@ +package source + +// The SFC(Simple Fast Counter) algorithm is designed for fast and efficient generation of pseudo-random numbers, +// utilizing arithmetic and bitwise operations across state variables and a counter to ensure +// good randomness quality. It is particularly well-suited for applications requiring rapid +// number generation without the need for cryptographic security. + +// Pros: +// - High efficiency and speed, ideal for performance-sensitive applications. +// - Simple to implement and maintain, with minimal computational overhead. +// - Offers a balance between speed and randomness quality, suitable for a wide range of uses. + +// Cons: +// - Not designed for cryptographic applications due to its level of randomness. +// - Initial seeding mechanism is basic; may require enhancement for more complex use cases. + +type SFC struct { + a, b, c, counter uint64 +} + +// NewSFC creates and returns a new SFC pseudo-random number generator seeded with a given seed. +func NewSFC(seed uint64) *SFC { + s := &SFC{} + s.Seed(seed) + return s +} + +// Seed sets the seed of the SFC. This implementation can be enhanced to +// provide a more distributed seeding process across the state variables. +func (s *SFC) Seed(seed uint64) { + s.a = seed + s.b = seed + s.c = seed + s.counter = 1 // Reset counter with new seed +} + +// Uint64 generates a pseudo-random 64-bit value using the SFC algorithm. +func (s *SFC) Uint64() uint64 { + s.a += s.b + s.counter + s.b ^= s.c + s.c -= s.a + s.counter++ + return s.c + s.b +} diff --git a/source/sfc_test.go b/source/sfc_test.go new file mode 100644 index 00000000..13b9319e --- /dev/null +++ b/source/sfc_test.go @@ -0,0 +1,26 @@ +package source + +import "testing" + +func TestSFC(t *testing.T) { + sfc := NewSFC(0) + sfc.Seed(0) + + // test for duplicates + m := make(map[uint64]bool) + for i := 0; i < 10000; i++ { + v := sfc.Uint64() + if m[v] { + t.Errorf("Duplicate value: %v", v) + } + m[v] = true + } +} + +func BenchmarkSFC(b *testing.B) { + sfc := NewSFC(0) + + for i := 0; i < b.N; i++ { + sfc.Uint64() + } +} diff --git a/sql.go b/sql.go index b9918b23..cf767758 100644 --- a/sql.go +++ b/sql.go @@ -4,7 +4,6 @@ import ( "encoding/json" "errors" "fmt" - "math/rand" "strings" ) @@ -14,11 +13,11 @@ type SQLOptions struct { Fields []Field `json:"fields" xml:"fields"` // The fields to be generated } -func SQL(so *SQLOptions) (string, error) { return sqlFunc(globalFaker.Rand, so) } +func SQL(so *SQLOptions) (string, error) { return sqlFunc(GlobalFaker, so) } -func (f *Faker) SQL(so *SQLOptions) (string, error) { return sqlFunc(f.Rand, so) } +func (f *Faker) SQL(so *SQLOptions) (string, error) { return sqlFunc(f, so) } -func sqlFunc(r *rand.Rand, so *SQLOptions) (string, error) { +func sqlFunc(f *Faker, so *SQLOptions) (string, error) { if so.Table == "" { return "", errors.New("must provide table name to generate SQL") } @@ -66,7 +65,7 @@ func sqlFunc(r *rand.Rand, so *SQLOptions) (string, error) { } // Generate the value - val, err := funcInfo.Generate(r, &field.Params, funcInfo) + val, err := funcInfo.Generate(f, &field.Params, funcInfo) if err != nil { return "", err } @@ -118,7 +117,7 @@ VALUES {Field: "count", Display: "Count", Type: "int", Default: "100", Description: "Number of inserts to generate"}, {Field: "fields", Display: "Fields", Type: "[]Field", Description: "Fields containing key name and function to run in json format"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { so := SQLOptions{} table, err := info.GetString(m, "table") @@ -151,7 +150,7 @@ VALUES } } - return sqlFunc(r, &so) + return sqlFunc(f, &so) }, }) } diff --git a/sql_test.go b/sql_test.go index 9b320774..101eaf38 100644 --- a/sql_test.go +++ b/sql_test.go @@ -2,7 +2,6 @@ package gofakeit import ( "fmt" - "math/rand" "strings" "testing" ) @@ -24,8 +23,7 @@ func ExampleSQL() { fmt.Println(string(res)) - // Output: - // INSERT INTO people (id, first_name, price, age, created_at) VALUES (1, 'Markus', 804.92, 21, '1989-01-30 07:58:01'),(2, 'Santino', 235.13, 40, '1919-07-07 22:25:40'); + // Output: INSERT INTO people (id, first_name, price, age, created_at) VALUES (1, 'Sonny', 985.96, 20, '1925-07-08 17:32:57'),(2, 'Steve', 639.32, 74, '2016-12-29 07:25:24'); } func ExampleFaker_SQL() { @@ -45,8 +43,7 @@ func ExampleFaker_SQL() { fmt.Println(string(res)) - // Output: - // INSERT INTO people (id, first_name, price, age, created_at) VALUES (1, 'Markus', 804.92, 21, '1901-11-22 07:34:00'),(2, 'Anibal', 674.87, 60, '2006-01-03 11:07:53'); + // Output: INSERT INTO people (id, first_name, price, age, created_at) VALUES (1, 'Sonny', 985.96, 20, '1925-07-08 17:32:57'),(2, 'Steve', 639.32, 74, '2016-12-29 07:25:24'); } func TestSQLJSON(t *testing.T) { @@ -57,7 +54,7 @@ func TestSQLJSON(t *testing.T) { Description: "random JSON of a person", Example: `{"first_name":"Bob", "last_name":"Jones"}`, Output: "[]byte", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { v, _ := JSON(&JSONOptions{ Type: "object", @@ -84,8 +81,8 @@ func TestSQLJSON(t *testing.T) { t.Fatal(err) } - if res != `INSERT INTO people (data) VALUES ('{"first_name":"Markus","last_name":"Moen"}'),('{"first_name":"Alayna","last_name":"Wuckert"}');` { - t.Error("SQL query does not match") + if res != `INSERT INTO people (data) VALUES ('{"first_name":"Sonny","last_name":"Stiedemann"}'),('{"first_name":"Cody","last_name":"Donnelly"}');` { + t.Errorf("SQL query did not match expected output: %s", res) } } diff --git a/string.go b/string.go index 778772bc..5be37826 100644 --- a/string.go +++ b/string.go @@ -1,90 +1,88 @@ package gofakeit -import "math/rand" - // Letter will generate a single random lower case ASCII letter -func Letter() string { return letter(globalFaker.Rand) } +func Letter() string { return letter(GlobalFaker) } // Letter will generate a single random lower case ASCII letter -func (f *Faker) Letter() string { return letter(f.Rand) } +func (f *Faker) Letter() string { return letter(f) } -func letter(r *rand.Rand) string { return string(randLetter(r)) } +func letter(f *Faker) string { return string(randLetter(f)) } // LetterN will generate a random ASCII string with length N. Note that this function returns a string with a length of 1 when 0 is passed. -func LetterN(n uint) string { return letterN(globalFaker.Rand, n) } +func LetterN(n uint) string { return letterN(GlobalFaker, n) } // LetterN will generate a random ASCII string with length N. Note that this function returns a string with a length of 1 when 0 is passed. -func (f *Faker) LetterN(n uint) string { return letterN(f.Rand, n) } +func (f *Faker) LetterN(n uint) string { return letterN(f, n) } -func letterN(r *rand.Rand, n uint) string { +func letterN(f *Faker, n uint) string { // Make sure we dont use 0 if n == 0 { n = 1 } out := make([]rune, n) for i := 0; i < int(n); i++ { - out[i] = randLetter(r) + out[i] = randLetter(f) } return string(out) } // Vowel will generate a single random lower case vowel -func Vowel() string { return vowel(globalFaker.Rand) } +func Vowel() string { return vowel(GlobalFaker) } // Vowel will generate a single random lower case vowel -func (f *Faker) Vowel() string { return vowel(f.Rand) } +func (f *Faker) Vowel() string { return vowel(f) } -func vowel(r *rand.Rand) string { return string(randCharacter(r, vowels)) } +func vowel(f *Faker) string { return string(randCharacter(f, vowels)) } // Digit will generate a single ASCII digit -func Digit() string { return digit(globalFaker.Rand) } +func Digit() string { return digit(GlobalFaker) } // Digit will generate a single ASCII digit -func (f *Faker) Digit() string { return digit(f.Rand) } +func (f *Faker) Digit() string { return digit(f) } -func digit(r *rand.Rand) string { return string(randDigit(r)) } +func digit(f *Faker) string { return string(randDigit(f)) } // DigitN will generate a random string of length N consists of ASCII digits. Note that the string generated can start with 0 and this function returns a string with a length of 1 when 0 is passed. -func DigitN(n uint) string { return digitN(globalFaker.Rand, n) } +func DigitN(n uint) string { return digitN(GlobalFaker, n) } // DigitN will generate a random string of length N consists of ASCII digits. Note that the string generated can start with 0 and this function returns a string with a length of 1 when 0 is passed. -func (f *Faker) DigitN(n uint) string { return digitN(f.Rand, n) } +func (f *Faker) DigitN(n uint) string { return digitN(f, n) } -func digitN(r *rand.Rand, n uint) string { +func digitN(f *Faker, n uint) string { // Make sure we dont use 0 if n == 0 { n = 1 } out := make([]rune, n) for i := 0; i < int(n); i++ { - out[i] = randDigit(r) + out[i] = randDigit(f) } return string(out) } // Numerify will replace # with random numerical values -func Numerify(str string) string { return numerify(globalFaker.Rand, str) } +func Numerify(str string) string { return numerify(GlobalFaker, str) } // Numerify will replace # with random numerical values -func (f *Faker) Numerify(str string) string { return numerify(f.Rand, str) } +func (f *Faker) Numerify(str string) string { return numerify(f, str) } -func numerify(r *rand.Rand, str string) string { return replaceWithNumbers(r, str) } +func numerify(f *Faker, str string) string { return replaceWithNumbers(f, str) } // Lexify will replace ? with random generated letters -func Lexify(str string) string { return lexify(globalFaker.Rand, str) } +func Lexify(str string) string { return lexify(GlobalFaker, str) } // Lexify will replace ? with random generated letters -func (f *Faker) Lexify(str string) string { return lexify(f.Rand, str) } +func (f *Faker) Lexify(str string) string { return lexify(f, str) } -func lexify(r *rand.Rand, str string) string { return replaceWithLetters(r, str) } +func lexify(f *Faker, str string) string { return replaceWithLetters(f, str) } // ShuffleStrings will randomize a slice of strings -func ShuffleStrings(a []string) { shuffleStrings(globalFaker.Rand, a) } +func ShuffleStrings(a []string) { shuffleStrings(GlobalFaker, a) } // ShuffleStrings will randomize a slice of strings -func (f *Faker) ShuffleStrings(a []string) { shuffleStrings(f.Rand, a) } +func (f *Faker) ShuffleStrings(a []string) { shuffleStrings(f, a) } -func shuffleStrings(r *rand.Rand, a []string) { +func shuffleStrings(f *Faker, a []string) { swap := func(i, j int) { a[i], a[j] = a[j], a[i] } @@ -97,18 +95,18 @@ func shuffleStrings(r *rand.Rand, a []string) { //if size is > int32 probably it will never finish, or ran out of entropy i := n - 1 for ; i > 0; i-- { - j := int(r.Int31n(int32(i + 1))) + j := int(int32NFunc(f, int32(i+1))) swap(i, j) } } // RandomString will take in a slice of string and return a randomly selected value -func RandomString(a []string) string { return randomString(globalFaker.Rand, a) } +func RandomString(a []string) string { return randomString(GlobalFaker, a) } // RandomString will take in a slice of string and return a randomly selected value -func (f *Faker) RandomString(a []string) string { return randomString(f.Rand, a) } +func (f *Faker) RandomString(a []string) string { return randomString(f, a) } -func randomString(r *rand.Rand, a []string) string { +func randomString(f *Faker, a []string) string { size := len(a) if size == 0 { return "" @@ -116,7 +114,7 @@ func randomString(r *rand.Rand, a []string) string { if size == 1 { return a[0] } - return a[r.Intn(size)] + return a[f.IntN(size)] } func addStringLookup() { @@ -126,8 +124,8 @@ func addStringLookup() { Description: "Character or symbol from the American Standard Code for Information Interchange (ASCII) character set", Example: "g", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return letter(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return letter(f), nil }, }) @@ -140,13 +138,13 @@ func addStringLookup() { Params: []Param{ {Field: "count", Display: "Count", Type: "uint", Description: "Number of digits to generate"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { ui, err := info.GetUint(m, "count") if err != nil { return nil, err } - return letterN(r, ui), nil + return letterN(f, ui), nil }, }) @@ -156,8 +154,8 @@ func addStringLookup() { Description: "Speech sound produced with an open vocal tract", Example: "a", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return vowel(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return vowel(f), nil }, }) @@ -167,8 +165,8 @@ func addStringLookup() { Description: "Numerical symbol used to represent numbers", Example: "0", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return digit(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return digit(f), nil }, }) @@ -181,13 +179,13 @@ func addStringLookup() { Params: []Param{ {Field: "count", Display: "Count", Type: "uint", Description: "Number of digits to generate"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { ui, err := info.GetUint(m, "count") if err != nil { return nil, err } - return digitN(r, ui), nil + return digitN(f, ui), nil }, }) @@ -200,13 +198,13 @@ func addStringLookup() { Params: []Param{ {Field: "str", Display: "String", Type: "string", Description: "String value to replace #'s"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { str, err := info.GetString(m, "str") if err != nil { return nil, err } - return numerify(r, str), nil + return numerify(f, str), nil }, }) @@ -219,13 +217,13 @@ func addStringLookup() { Params: []Param{ {Field: "str", Display: "String", Type: "string", Description: "String value to replace ?'s"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { str, err := info.GetString(m, "str") if err != nil { return nil, err } - return lexify(r, str), nil + return lexify(f, str), nil }, }) @@ -239,13 +237,13 @@ func addStringLookup() { Params: []Param{ {Field: "strs", Display: "Strings", Type: "[]string", Description: "Delimited separated strings"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { strs, err := info.GetStringArray(m, "strs") if err != nil { return nil, err } - shuffleStrings(r, strs) + shuffleStrings(f, strs) return strs, nil }, @@ -260,13 +258,13 @@ func addStringLookup() { Params: []Param{ {Field: "strs", Display: "Strings", Type: "[]string", Description: "Delimited separated strings"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { strs, err := info.GetStringArray(m, "strs") if err != nil { return nil, err } - return randomString(r, strs), nil + return randomString(f, strs), nil }, }) } diff --git a/string_test.go b/string_test.go index ea112c32..a0427f13 100644 --- a/string_test.go +++ b/string_test.go @@ -2,6 +2,7 @@ package gofakeit import ( "fmt" + "regexp" "testing" "unicode" ) @@ -10,14 +11,14 @@ func ExampleLetter() { Seed(11) fmt.Println(Letter()) - // Output: g + // Output: u } func ExampleFaker_Letter() { f := New(11) fmt.Println(f.Letter()) - // Output: g + // Output: u } func BenchmarkLetter(b *testing.B) { @@ -48,14 +49,14 @@ func ExampleLetterN() { Seed(11) fmt.Println(LetterN(10)) - // Output: gbRMaRxHki + // Output: usKKbMlbxq } func ExampleFaker_LetterN() { f := New(11) fmt.Println(f.LetterN(10)) - // Output: gbRMaRxHki + // Output: usKKbMlbxq } func BenchmarkLetterN(b *testing.B) { @@ -90,14 +91,14 @@ func ExampleDigit() { Seed(11) fmt.Println(Digit()) - // Output: 0 + // Output: 8 } func ExampleFaker_Digit() { f := New(11) fmt.Println(f.Digit()) - // Output: 0 + // Output: 8 } func BenchmarkDigit(b *testing.B) { @@ -129,14 +130,14 @@ func ExampleDigitN() { Seed(11) fmt.Println(DigitN(10)) - // Output: 0136459948 + // Output: 8812527598 } func ExampleFaker_DigitN() { f := New(11) fmt.Println(f.DigitN(10)) - // Output: 0136459948 + // Output: 8812527598 } func BenchmarkDigitN(b *testing.B) { @@ -150,14 +151,14 @@ func ExampleNumerify() { Seed(11) fmt.Println(Numerify("###-###-####")) - // Output: 613-645-9948 + // Output: 881-252-7598 } func ExampleFaker_Numerify() { f := New(11) fmt.Println(f.Numerify("###-###-####")) - // Output: 613-645-9948 + // Output: 881-252-7598 } func BenchmarkNumerify(b *testing.B) { @@ -170,14 +171,14 @@ func ExampleLexify() { Seed(11) fmt.Println(Lexify("?????")) - // Output: gbRMa + // Output: usKKb } func ExampleFaker_Lexify() { f := New(11) fmt.Println(f.Lexify("?????")) - // Output: gbRMa + // Output: usKKb } func BenchmarkLexify(b *testing.B) { @@ -192,7 +193,7 @@ func ExampleShuffleStrings() { ShuffleStrings(strings) fmt.Println(strings) - // Output: [good everyone have for times a day happy] + // Output: [for day happy everyone good times a have] } func ExampleFaker_ShuffleStrings() { @@ -201,7 +202,7 @@ func ExampleFaker_ShuffleStrings() { f.ShuffleStrings(strings) fmt.Println(strings) - // Output: [good everyone have for times a day happy] + // Output: [for day happy everyone good times a have] } func TestShuffleStrings(t *testing.T) { @@ -240,21 +241,25 @@ func ExampleFaker_RandomString() { func TestRandomString(t *testing.T) { for _, test := range []struct { - in []string - should string + in []string + shouldRegex string }{ {[]string{}, ""}, {nil, ""}, {[]string{"a"}, "a"}, - {[]string{"a", "b", "c", "d", "e", "f"}, "f"}, + {[]string{"a", "b", "c", "d", "e", "f"}, "[abcdef]"}, } { - Seed(44) - got := RandomString(test.in) - if got == test.should { - continue + Seed(11) + + res := RandomString(test.in) + matched, err := regexp.MatchString(test.shouldRegex, res) + if err != nil { + t.Error(err) + } + + if !matched { + t.Errorf("expected %s to match %s", res, test.shouldRegex) } - t.Errorf("for '%v' should '%s' got '%s'", - test.in, test.should, got) } } diff --git a/struct.go b/struct.go index a01728fc..9796d5f7 100644 --- a/struct.go +++ b/struct.go @@ -16,7 +16,7 @@ import ( // Use `fake:"skip"` to explicitly skip an element. // All built-in types are supported, with templating support // for string types. -func Struct(v any) error { return structFunc(globalFaker, v) } +func Struct(v any) error { return structFunc(GlobalFaker, v) } // Struct fills in exported fields of a struct with random data // based on the value of `fake` tag of exported fields. @@ -90,7 +90,7 @@ func rCustom(f *Faker, t reflect.Type, v reflect.Value, tag string) error { mapParams := parseMapParams(info, fParams) // Call function - fValue, err := info.Generate(f.Rand, mapParams, info) + fValue, err := info.Generate(f, mapParams, info) if err != nil { return err } @@ -200,7 +200,7 @@ func rStruct(f *Faker, t reflect.Type, v reflect.Value, tag string) error { return err } - size = f.Rand.Intn(sizeMax-sizeMin+1) + sizeMin + size = f.IntN(sizeMax-sizeMin+1) + sizeMin } } else { size, err = strconv.Atoi(fs) @@ -270,7 +270,7 @@ func rSlice(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) err // use that instead of the requested size elemLen := v.Len() if elemLen == 0 && size == -1 { - size = number(f.Rand, 1, 10) + size = number(f, 1, 10) } else if elemLen != 0 && (size == -1 || elemLen < size) { size = elemLen } @@ -321,7 +321,7 @@ func rMap(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) error // Set a size newSize := size if newSize == -1 { - newSize = number(f.Rand, 1, 10) + newSize = number(f, 1, 10) } // Create new map based upon map key value type @@ -358,7 +358,7 @@ func rMap(f *Faker, t reflect.Type, v reflect.Value, tag string, size int) error func rString(f *Faker, t reflect.Type, v reflect.Value, tag string) error { if tag != "" { - v.SetString(generate(f.Rand, tag)) + v.SetString(generate(f, tag)) } else if isFakeable(t) { value, err := callFake(f, v, reflect.String) if err != nil { @@ -371,7 +371,7 @@ func rString(f *Faker, t reflect.Type, v reflect.Value, tag string) error { } v.SetString(valueStr) } else { - v.SetString(generate(f.Rand, strings.Repeat("?", number(f.Rand, 4, 10)))) + v.SetString(generate(f, strings.Repeat("?", number(f, 4, 10)))) } return nil @@ -379,7 +379,7 @@ func rString(f *Faker, t reflect.Type, v reflect.Value, tag string) error { func rInt(f *Faker, t reflect.Type, v reflect.Value, tag string) error { if tag != "" { - i, err := strconv.ParseInt(generate(f.Rand, tag), 10, 64) + i, err := strconv.ParseInt(generate(f, tag), 10, 64) if err != nil { return err } @@ -409,15 +409,15 @@ func rInt(f *Faker, t reflect.Type, v reflect.Value, tag string) error { // If no tag or error converting to int, set with random value switch t.Kind() { case reflect.Int: - v.SetInt(int64Func(f.Rand)) + v.SetInt(int64Func(f)) case reflect.Int8: - v.SetInt(int64(int8Func(f.Rand))) + v.SetInt(int64(int8Func(f))) case reflect.Int16: - v.SetInt(int64(int16Func(f.Rand))) + v.SetInt(int64(int16Func(f))) case reflect.Int32: - v.SetInt(int64(int32Func(f.Rand))) + v.SetInt(int64(int32Func(f))) case reflect.Int64: - v.SetInt(int64Func(f.Rand)) + v.SetInt(int64Func(f)) } } @@ -426,7 +426,7 @@ func rInt(f *Faker, t reflect.Type, v reflect.Value, tag string) error { func rUint(f *Faker, t reflect.Type, v reflect.Value, tag string) error { if tag != "" { - u, err := strconv.ParseUint(generate(f.Rand, tag), 10, 64) + u, err := strconv.ParseUint(generate(f, tag), 10, 64) if err != nil { return err } @@ -456,15 +456,15 @@ func rUint(f *Faker, t reflect.Type, v reflect.Value, tag string) error { // If no tag or error converting to uint, set with random value switch t.Kind() { case reflect.Uint: - v.SetUint(uint64Func(f.Rand)) + v.SetUint(f.Uint64()) case reflect.Uint8: - v.SetUint(uint64(uint8Func(f.Rand))) + v.SetUint(uint64(uint8Func(f))) case reflect.Uint16: - v.SetUint(uint64(uint16Func(f.Rand))) + v.SetUint(uint64(uint16Func(f))) case reflect.Uint32: - v.SetUint(uint64(uint32Func(f.Rand))) + v.SetUint(uint64(uint32Func(f))) case reflect.Uint64: - v.SetUint(uint64Func(f.Rand)) + v.SetUint(f.Uint64()) } } @@ -473,7 +473,7 @@ func rUint(f *Faker, t reflect.Type, v reflect.Value, tag string) error { func rFloat(f *Faker, t reflect.Type, v reflect.Value, tag string) error { if tag != "" { - f, err := strconv.ParseFloat(generate(f.Rand, tag), 64) + f, err := strconv.ParseFloat(generate(f, tag), 64) if err != nil { return err } @@ -497,9 +497,9 @@ func rFloat(f *Faker, t reflect.Type, v reflect.Value, tag string) error { // If no tag or error converting to float, set with random value switch t.Kind() { case reflect.Float64: - v.SetFloat(float64Func(f.Rand)) + v.SetFloat(float64Func(f)) case reflect.Float32: - v.SetFloat(float64(float32Func(f.Rand))) + v.SetFloat(float64(float32Func(f))) } } @@ -508,7 +508,7 @@ func rFloat(f *Faker, t reflect.Type, v reflect.Value, tag string) error { func rBool(f *Faker, t reflect.Type, v reflect.Value, tag string) error { if tag != "" { - b, err := strconv.ParseBool(generate(f.Rand, tag)) + b, err := strconv.ParseBool(generate(f, tag)) if err != nil { return err } @@ -528,7 +528,7 @@ func rBool(f *Faker, t reflect.Type, v reflect.Value, tag string) error { } } else { // If no tag or error converting to boolean, set with random value - v.SetBool(boolFunc(f.Rand)) + v.SetBool(boolFunc(f)) } return nil @@ -538,7 +538,7 @@ func rBool(f *Faker, t reflect.Type, v reflect.Value, tag string) error { func rTime(f *Faker, t reflect.StructField, v reflect.Value, tag string) error { if tag != "" { // Generate time - timeOutput := generate(f.Rand, tag) + timeOutput := generate(f, tag) // Check to see if timeOutput has monotonic clock reading // if so, remove it. This is because time.Parse() does not @@ -578,6 +578,6 @@ func rTime(f *Faker, t reflect.StructField, v reflect.Value, tag string) error { return nil } - v.Set(reflect.ValueOf(date(f.Rand))) + v.Set(reflect.ValueOf(date(f))) return nil } diff --git a/struct_test.go b/struct_test.go index ef65419e..833249e9 100644 --- a/struct_test.go +++ b/struct_test.go @@ -2,8 +2,8 @@ package gofakeit import ( "fmt" - "math/rand" "net" + "regexp" "testing" "time" ) @@ -114,18 +114,18 @@ func ExampleStruct() { fmt.Printf("%v\n", f.MapRange) fmt.Printf("%+v\n", f.Bar) - // Output: bRMaRx - // 8474499440427634498 - // 4409580151121052361 - // Andre - // 1 + // Output: sKKbMlbxqu + // 1365845625386394310 + // 4415419407664574903 + // Tomasa + // 10 // // - // [PtapWYJdn MKgtlxwnq] - // [claYk wfoRL PxLIok qanPAKaXS QFpZysVaHG] - // map[DjRRGUns:xdBXGY yvqqdH:eUxcvUVS] - // map[Oyrwg:LhewLkDVtD XpYcnVTKpB:eubY jQZsZt:eUpXhOq ynojqPYDrH:HWYKFgji] - // {Name:ANhYxKtSH Number:-5807586752746953977 Float:4.558046e+37} + // [RWVlPmwRAe wVHB] + // [rxXDcxFe kfvChMC KfmBwRtn] + // map[gyJrZ:tfZAk oOEImWl:NXYnuKiGab] + // map[WigEnVzBy:JJXMkG aHqIpyVs:UxvheGVE pYyDuWC:yzjqsX] + // {Name:LfLRuhFRHQ Number:5737279083624806933 Float:0.59020466} } func ExampleFaker_Struct() { @@ -165,16 +165,16 @@ func ExampleFaker_Struct() { fmt.Printf("%v\n", f.MapRange) fmt.Printf("%+v\n", f.Bar) - // Output: bRMaRx - // 8474499440427634498 - // 4409580151121052361 - // Andre - // 1 + // Output: sKKbMlbxqu + // 1365845625386394310 + // 4415419407664574903 + // Tomasa + // 10 // - // [PtapWYJdn MKgtlxwnq] - // map[DjRRGUns:xdBXGY yvqqdH:eUxcvUVS] - // map[Oyrwg:LhewLkDVtD XpYcnVTKpB:eubY jQZsZt:eUpXhOq ynojqPYDrH:HWYKFgji] - // {Name:ANhYxKtSH Number:-5807586752746953977 Float:4.558046e+37} + // [RWVlPmwRAe wVHB] + // map[gyJrZ:tfZAk oOEImWl:NXYnuKiGab] + // map[WigEnVzBy:JJXMkG aHqIpyVs:UxvheGVE pYyDuWC:yzjqsX] + // {Name:LfLRuhFRHQ Number:5737279083624806933 Float:0.59020466} } func ExampleStruct_array() { @@ -201,10 +201,9 @@ func ExampleStruct_array() { fmt.Printf("%v\n", fm.Names) fmt.Printf("%v\n", fm.NamesRange) - // Output: - // [{bRMaRx 8474499440427634498 Paolo 4 }] - // [Santino Carole Enrique] - // [Zachery Amie Alice Zachary] + // Output: [{sKKbMlbxqu 1365845625386394310 Myrtis 10 }] + // [Tomasa Sunny Ernest] + // [Hassan Missouri Elisabeth Nedra Tiana Evan] } func ExampleFaker_Struct_array() { @@ -231,10 +230,9 @@ func ExampleFaker_Struct_array() { fmt.Printf("%v\n", fm.Names) fmt.Printf("%v\n", fm.NamesRange) - // Output: - // [{bRMaRx 8474499440427634498 Paolo 4 }] - // [Santino Carole Enrique] - // [Zachery Amie Alice Zachary] + // Output: [{sKKbMlbxqu 1365845625386394310 Myrtis 10 }] + // [Tomasa Sunny Ernest] + // [Hassan Missouri Elisabeth Nedra Tiana Evan] } func TestStructBasic(t *testing.T) { @@ -365,7 +363,7 @@ func TestCustomArrayType(t *testing.T) { Description: "Random int array", Example: "[1]", Output: "CustomType", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { data := make([]int, 1) data[0] = 42 return data, nil @@ -378,7 +376,7 @@ func TestCustomArrayType(t *testing.T) { Description: "Random byte", Example: "[1]", Output: "byte", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { data := byte(42) return data, nil }, @@ -579,7 +577,7 @@ func TestStructToFloat(t *testing.T) { if sf.FloatConst != 123.456789 { t.Errorf("FloatConst should be 123.456.789 and instead got %f", sf.FloatConst) } - if sf.FloatGenerate != 54.887310 { + if sf.FloatGenerate != 87.473328 { t.Errorf("FloatGenerate should be 31.477726 but got %f", sf.FloatGenerate) } } @@ -593,14 +591,14 @@ func TestStructToBool(t *testing.T) { BoolGenerate bool `fake:"{bool}"` } Struct(&sf) - if sf.Bool == false { - t.Error("Bool should be false got true") + if sf.Bool == true { + t.Error("Bool should be true got true") } if sf.BoolConst != true { t.Errorf("BoolConst should be true got false") } if sf.BoolGenerate != false { - t.Errorf("BoolGenerate should be false got true") + t.Errorf("Bool Generate should be %t but got %t", false, sf.BoolGenerate) } } @@ -611,7 +609,7 @@ func TestStructToDateTime(t *testing.T) { Description: "A static date time", Example: "2021-11-26 15:22:00", Output: "time.Time", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { // Create new static date time return time.Date(2021, 11, 26, 15, 22, 0, 0, time.UTC), nil }, @@ -646,12 +644,12 @@ func TestStructToDateTime(t *testing.T) { { name: "Simple", observed: datetime.Simple.String(), - expected: "1915-01-24 13:00:35.820738079 +0000 UTC", + expected: "2011-11-07 04:31:13.726582492 +0000 UTC", }, { name: "Tag", observed: datetime.Tag.String(), - expected: "2023-02-10 22:06:24 +0000 UTC", + expected: "1967-12-26 21:04:44 +0000 UTC", }, { name: "TagCustom", @@ -661,27 +659,27 @@ func TestStructToDateTime(t *testing.T) { { name: "TagFormat", observed: datetime.TagFormat.String(), - expected: "1945-12-05 00:00:00 +0000 UTC", + expected: "1947-12-05 00:00:00 +0000 UTC", }, { name: "TagJavaFormat", observed: datetime.TagJavaFormat.String(), - expected: "1929-12-05 00:00:00 +0000 UTC", + expected: "1946-12-05 00:00:00 +0000 UTC", }, { name: "Range", observed: datetime.Range.String(), - expected: "1998-10-27 00:00:00 +0000 UTC", + expected: "1980-03-10 00:00:00 +0000 UTC", }, { name: "PointerSimple", observed: datetime.PointerSimple.String(), - expected: "1967-05-17 13:55:34.57634154 +0000 UTC", + expected: "1953-05-23 07:44:55.341122669 +0000 UTC", }, { name: "PointerTag", observed: datetime.PointerTag.String(), - expected: "1902-06-03 07:35:07 +0000 UTC", + expected: "1900-07-01 22:25:09 +0000 UTC", }, { name: "PointerTagCustom", @@ -691,17 +689,17 @@ func TestStructToDateTime(t *testing.T) { { name: "PointerTagFormat", observed: datetime.PointerTagFormat.String(), - expected: "1907-12-05 00:00:00 +0000 UTC", + expected: "1910-12-05 00:00:00 +0000 UTC", }, { name: "PointerTagJavaFormat", observed: datetime.PointerTagJavaFormat.String(), - expected: "1904-12-05 00:00:00 +0000 UTC", + expected: "1932-12-05 00:00:00 +0000 UTC", }, { name: "PointerRange", observed: datetime.PointerRange.String(), - expected: "2000-02-05 00:00:00 +0000 UTC", + expected: "1995-12-07 00:00:00 +0000 UTC", }, } for _, c := range testComparisons { @@ -727,7 +725,7 @@ func TestStructSetSubStruct(t *testing.T) { } AddFuncLookup("setstruct", Info{ - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { return Sub{Str: "string", Num: 123, Flo: 123.456}, nil }, }) @@ -857,16 +855,23 @@ func TestExternalCustomType(t *testing.T) { Description: "Random IPv4 Address of type net.IP", Example: "1.1.1.1", Output: "net.IP", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - data := net.IPv4(byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256)), byte(r.Intn(256))) + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + data := net.IPv4(byte(f.IntN(256)), byte(f.IntN(256)), byte(f.IntN(256)), byte(f.IntN(256))) return data, nil }, }) defer RemoveFuncLookup("netip") Struct(&f) - if fmt.Sprintf("%s - %T", f.IP, f.IP) != "152.23.53.100 - net.IP" { - t.Errorf("IP should be empty and instead got %s - %T", f.IP, f.IP) + // Regex check its an IP + reg := `^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$` + matched, err := regexp.MatchString(reg, f.IP.String()) + if err != nil { + t.Error(err) + } + + if !matched { + t.Errorf("IP address is not valid: %s", f.IP.String()) } } @@ -876,7 +881,7 @@ func TestStructArrayWithInvalidCustomFunc(t *testing.T) { Description: "Random int array", Example: "[1]", Output: "CustomType", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { data := make([]int, 1) data[0] = 42 return data, nil @@ -895,7 +900,7 @@ func TestStructArrayWithInvalidCustomFunc(t *testing.T) { func TestStructMapWithCustomFunction(t *testing.T) { AddFuncLookup("custom_map", Info{ - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { return map[string]string{"abc": "123"}, nil }, }) diff --git a/template.go b/template.go index 329d6f78..5921fbf6 100644 --- a/template.go +++ b/template.go @@ -6,7 +6,6 @@ import ( "strconv" "time" - "math/rand" "reflect" "strings" "text/template" @@ -22,9 +21,9 @@ type TemplateOptions struct { func Template(template string, co *TemplateOptions) (string, error) { if co == nil { co = &TemplateOptions{} - globalFaker.Struct(co) + GlobalFaker.Struct(co) } - return templateFunc(template, templateFuncMap(globalFaker.Rand, &co.Funcs), co) + return templateFunc(template, templateFuncMap(GlobalFaker, &co.Funcs), co) } // Template generates an document based on the the supplied template @@ -33,7 +32,7 @@ func (f *Faker) Template(template string, co *TemplateOptions) (string, error) { co = &TemplateOptions{} f.Struct(co) } - return templateFunc(template, templateFuncMap(f.Rand, &co.Funcs), co) + return templateFunc(template, templateFuncMap(f, &co.Funcs), co) } // MarkdownOptions defines values needed for markdown document generation @@ -92,9 +91,9 @@ console.log("{{ToLower $repo}} result:", "{{ToLower $result}}"); func Markdown(co *MarkdownOptions) (string, error) { if co == nil { co = &MarkdownOptions{} - globalFaker.Struct(co) + GlobalFaker.Struct(co) } - return templateFunc(templateMarkdown, templateFuncMap(globalFaker.Rand, nil), co) + return templateFunc(templateMarkdown, templateFuncMap(GlobalFaker, nil), co) } // Markdown will return a single random Markdown template document @@ -103,7 +102,7 @@ func (f *Faker) Markdown(co *MarkdownOptions) (string, error) { co = &MarkdownOptions{} f.Struct(co) } - return templateFunc(templateMarkdown, templateFuncMap(f.Rand, nil), co) + return templateFunc(templateMarkdown, templateFuncMap(f, nil), co) } // EmailOptions defines values needed for email document generation @@ -138,9 +137,9 @@ Dear {{LastName}}, func EmailText(co *EmailOptions) (string, error) { if co == nil { co = &EmailOptions{} - globalFaker.Struct(co) + GlobalFaker.Struct(co) } - return templateFunc(templateEmail, templateFuncMap(globalFaker.Rand, nil), co) + return templateFunc(templateEmail, templateFuncMap(GlobalFaker, nil), co) } // EmailText will return a single random text email template document @@ -149,7 +148,7 @@ func (f *Faker) EmailText(co *EmailOptions) (string, error) { co = &EmailOptions{} f.Struct(co) } - return templateFunc(templateEmail, templateFuncMap(f.Rand, nil), co) + return templateFunc(templateEmail, templateFuncMap(f, nil), co) } // functions that wont work with template engine @@ -160,14 +159,11 @@ var templateExclusion = []string{ } // Build the template.FuncMap for the template engine -func templateFuncMap(r *rand.Rand, fm *template.FuncMap) *template.FuncMap { +func templateFuncMap(f *Faker, fm *template.FuncMap) *template.FuncMap { // create a new function map funcMap := template.FuncMap{} - // build the function map from a faker using their rand - f := &Faker{Rand: r} - v := reflect.ValueOf(f) // loop through the methods @@ -350,7 +346,7 @@ Markus Moen`, {Field: "template", Display: "Template", Type: "string", Description: "Golang template to generate the document from"}, {Field: "data", Display: "Custom Data", Type: "string", Default: "", Optional: true, Description: "Custom data to pass to the template"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { tpl, err := info.GetString(m, "template") if err != nil { return nil, err @@ -361,7 +357,7 @@ Markus Moen`, return nil, err } - templateOut, err := templateFunc(tpl, templateFuncMap(r, nil), &TemplateOptions{Data: data}) + templateOut, err := templateFunc(tpl, templateFuncMap(f, nil), &TemplateOptions{Data: data}) if err != nil { return nil, err } @@ -401,8 +397,8 @@ print("purplesheep5 result:", "in progress") ## License MIT`, Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - template_result, err := templateFunc(templateMarkdown, templateFuncMap(r, nil), &MarkdownOptions{}) + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + template_result, err := templateFunc(templateMarkdown, templateFuncMap(f, nil), &MarkdownOptions{}) return string(template_result), err }, }) @@ -436,8 +432,8 @@ Milford Johnston jamelhaag@king.org (507)096-3058`, Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - template_result, err := templateFunc(templateEmail, templateFuncMap(r, nil), &EmailOptions{}) + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + template_result, err := templateFunc(templateEmail, templateFuncMap(f, nil), &EmailOptions{}) return string(template_result), err }, }) diff --git a/template_test.go b/template_test.go index 928e4586..448f5e7e 100644 --- a/template_test.go +++ b/template_test.go @@ -2,6 +2,7 @@ package gofakeit import ( "fmt" + "regexp" "strings" "testing" "text/template" @@ -19,11 +20,10 @@ func ExampleTemplate() { fmt.Println(string(value)) - // Output: - // Markus Moen - // Alayna Wuckert - // Lura Lockman - // Sylvan Mraz + // Output: Sonny Stiedemann + // Cody Donnelly + // Julius Farrell + // Mollie Legros } @@ -39,11 +39,10 @@ func ExampleFaker_Template() { fmt.Println(string(value)) - // Output: - // Markus Moen - // Alayna Wuckert - // Lura Lockman - // Sylvan Mraz + // Output: Sonny Stiedemann + // Cody Donnelly + // Julius Farrell + // Mollie Legros } func TestPassedInFunctionMap(t *testing.T) { @@ -148,13 +147,20 @@ func TestTemplateLookup(t *testing.T) { "data": {"5"}, } - value, err := info.Generate(f.Rand, &m, info) + value, err := info.Generate(f, &m, info) if err != nil { t.Fatal(err.Error()) } - if value != "Markus Moen\nAlayna Wuckert\nLura Lockman\nSylvan Mraz\nPaolo Rutherford\n" { - t.Error("Expected `Markus Moen Pagac`, got ", value) + // Check if value is in the expected format. name[space]name\n + reg := `^(\w+\s\w+\n){5}$` + matched, err := regexp.MatchString(reg, value.(string)) + if err != nil { + t.Fatal(err.Error()) + } + + if !matched { + t.Errorf("expected %s to match %s", value, reg) } } @@ -200,24 +206,17 @@ func TestTemplateInternalFunctions(t *testing.T) { func TestTemplateNoOptions(t *testing.T) { Seed(11) - tests := []string{ - "Markus Moen", - "Alayna Wuckert", - "Lura Lockman", - "Sylvan Mraz", - "Paolo Rutherford", + // The above code is declaring a variable named "value" in the Go programming language. + value, err := Template("{{FirstName}} {{LastName}}", nil) + if err != nil { + t.Fatal(err) } - for k, v := range tests { - // The above code is declaring a variable named "value" in the Go programming language. - value, err := Template("{{FirstName}} {{LastName}}", nil) - if err != nil { - t.Fatal(err) - } - if !strings.Contains(value, v) { - t.Errorf("Test: %v could not find `%s`, in result %s", k, v, value) - } + // Make sure value has a space in it + if !strings.Contains(value, " ") { + t.Errorf("expected a space in %s", value) } + } func ExampleEmailText() { @@ -230,31 +229,30 @@ func ExampleEmailText() { fmt.Println(string(value)) - // Output: - // Subject: Greetings from Marcel! + // Output: Subject: Hi from Russ! // - // Dear Pagac, + // Dear Donnelly, // - // Hello there! Sending positive vibes your way. + // Greetings! I hope your day is going well. // - // I hope you're doing great. May your week be filled with joy. + // I trust this email finds you well. Sending good vibes your way. // - // This me far smile where was by army party riches. Theirs instead here mine whichever that those instance growth has. Ouch enough Swiss us since down he she aha us. You to upon how this this furniture way no play. Towel that us to accordingly theirs purse enough so though. + // Galaxy they how shall cut lastly that someone additionally ambulance. Could a tennis occur why depend heels out can fire. Anyone sometimes that leap whom troop now scarcely since dance. Huh somebody constantly Italian outfit certain weekly murder who cackle. Because her break write nobody could according whoa bevy we. // - // Election often until eek weekly yet oops until conclude his. Stay elsewhere such that galaxy clean that last each stack. Reluctantly theirs wisp aid firstly highly butter accordingly should already. Calm shake according fade neither kuban upon this he fortnightly. Occasionally bunch on who elsewhere lastly hourly right there honesty. + // Them summation to oxygen Greek how previously a what answer. Handle daily ouch upon encourage that after his every she. Wearily still he herself huge failure for yay sparse thoughtfully. Box anyway Jungian regularly world great daily recently whose Elizabethan. Outside to theirs block while French closely sit you to. // - // We is how result out Shakespearean have whom yearly another. Packet are behind late lot finally time themselves goodness quizzical. Our therefore could fact cackle yourselves zebra for whose enormously. All bowl out wandering secondly yellow another your hourly spit. Since tomorrow hers words little think will our by Polynesian. + // Out fight bored yours those bale Parisian host which so. Today Ecuadorian hourly decidedly his everybody this play this little. Them on recently eager usually bunch daily whose somebody them. Few tonight dishonesty spell battery less patience whose inside hair. Your answer hand tonight these she team which today Einsteinian. // - // I'm curious to know what you think about it. If you have a moment, please feel free to check out the project on GitLab + // I'm eager to hear your feedback on it. If you have a moment, please feel free to check out the project on GitLab // // Your insights would be invaluable. Your thoughts matter to me. // // I appreciate your attention to this matter. Your feedback is greatly appreciated. // - // Best wishes - // Daryl Leannon - // oceaneokuneva@roberts.org - // 1-816-608-2233 + // Sincerely + // Hyman Rogahn + // mervingottlieb@goldner.com + // 1-275-132-4165 } func ExampleFaker_EmailText() { @@ -267,31 +265,30 @@ func ExampleFaker_EmailText() { fmt.Println(string(value)) - // Output: - // Subject: Greetings from Marcel! + // Output: Subject: Hi from Russ! // - // Dear Pagac, + // Dear Donnelly, // - // Hello there! Sending positive vibes your way. + // Greetings! I hope your day is going well. // - // I hope you're doing great. May your week be filled with joy. + // I trust this email finds you well. Sending good vibes your way. // - // This me far smile where was by army party riches. Theirs instead here mine whichever that those instance growth has. Ouch enough Swiss us since down he she aha us. You to upon how this this furniture way no play. Towel that us to accordingly theirs purse enough so though. + // Galaxy they how shall cut lastly that someone additionally ambulance. Could a tennis occur why depend heels out can fire. Anyone sometimes that leap whom troop now scarcely since dance. Huh somebody constantly Italian outfit certain weekly murder who cackle. Because her break write nobody could according whoa bevy we. // - // Election often until eek weekly yet oops until conclude his. Stay elsewhere such that galaxy clean that last each stack. Reluctantly theirs wisp aid firstly highly butter accordingly should already. Calm shake according fade neither kuban upon this he fortnightly. Occasionally bunch on who elsewhere lastly hourly right there honesty. + // Them summation to oxygen Greek how previously a what answer. Handle daily ouch upon encourage that after his every she. Wearily still he herself huge failure for yay sparse thoughtfully. Box anyway Jungian regularly world great daily recently whose Elizabethan. Outside to theirs block while French closely sit you to. // - // We is how result out Shakespearean have whom yearly another. Packet are behind late lot finally time themselves goodness quizzical. Our therefore could fact cackle yourselves zebra for whose enormously. All bowl out wandering secondly yellow another your hourly spit. Since tomorrow hers words little think will our by Polynesian. + // Out fight bored yours those bale Parisian host which so. Today Ecuadorian hourly decidedly his everybody this play this little. Them on recently eager usually bunch daily whose somebody them. Few tonight dishonesty spell battery less patience whose inside hair. Your answer hand tonight these she team which today Einsteinian. // - // I'm curious to know what you think about it. If you have a moment, please feel free to check out the project on GitLab + // I'm eager to hear your feedback on it. If you have a moment, please feel free to check out the project on GitLab // // Your insights would be invaluable. Your thoughts matter to me. // // I appreciate your attention to this matter. Your feedback is greatly appreciated. // - // Best wishes - // Daryl Leannon - // oceaneokuneva@roberts.org - // 1-816-608-2233 + // Sincerely + // Hyman Rogahn + // mervingottlieb@goldner.com + // 1-275-132-4165 } // TemplateMarkdown examples and tests @@ -305,14 +302,13 @@ func ExampleMarkdown() { fmt.Println(string(value)) - // Output: - // # PurpleSheep5 + // Output: # TurkeyThinker // - // *Author: Amie Feil* + // *Author: Tomasa Waters* // - // Was by army party riches theirs instead. Here mine whichever that those instance growth. Has ouch enough Swiss us since down. He she aha us you to upon. How this this furniture way no play. + // Cut lastly that someone additionally ambulance could. A tennis occur why depend heels out. Can fire anyone sometimes that leap whom. Troop now scarcely since dance huh somebody. Constantly Italian outfit certain weekly murder who. // - // Towel that us to accordingly theirs purse. Enough so though election often until eek. Weekly yet oops until conclude his stay. Elsewhere such that galaxy clean that last. Each stack reluctantly theirs wisp aid firstly. + // Cackle because her break write nobody could. According whoa bevy we them summation to. Oxygen Greek how previously a what answer. Handle daily ouch upon encourage that after. His every she wearily still he herself. // // ## Table of Contents // - [Installation](#installation) @@ -321,13 +317,13 @@ func ExampleMarkdown() { // // ## Installation // '''bash - // pip install PurpleSheep5 + // pip install TurkeyThinker // ''' // // ## Usage // '''python - // result = purplesheep5.process("funny request") - // print("purplesheep5 result:", "in progress") + // result = turkeythinker.handle("whimsical story") + // print("turkeythinker result:", "terminated") // ''' // // ## License @@ -344,14 +340,13 @@ func ExampleFaker_Markdown() { fmt.Println(string(value)) - // Output: - // # PurpleSheep5 + // Output: # TurkeyThinker // - // *Author: Amie Feil* + // *Author: Tomasa Waters* // - // Was by army party riches theirs instead. Here mine whichever that those instance growth. Has ouch enough Swiss us since down. He she aha us you to upon. How this this furniture way no play. + // Cut lastly that someone additionally ambulance could. A tennis occur why depend heels out. Can fire anyone sometimes that leap whom. Troop now scarcely since dance huh somebody. Constantly Italian outfit certain weekly murder who. // - // Towel that us to accordingly theirs purse. Enough so though election often until eek. Weekly yet oops until conclude his stay. Elsewhere such that galaxy clean that last. Each stack reluctantly theirs wisp aid firstly. + // Cackle because her break write nobody could. According whoa bevy we them summation to. Oxygen Greek how previously a what answer. Handle daily ouch upon encourage that after. His every she wearily still he herself. // // ## Table of Contents // - [Installation](#installation) @@ -360,38 +355,26 @@ func ExampleFaker_Markdown() { // // ## Installation // '''bash - // pip install PurpleSheep5 + // pip install TurkeyThinker // ''' // // ## Usage // '''python - // result = purplesheep5.process("funny request") - // print("purplesheep5 result:", "in progress") + // result = turkeythinker.handle("whimsical story") + // print("turkeythinker result:", "terminated") // ''' // // ## License // MIT } -func BenchmarkTemplate100(b *testing.B) { +func BenchmarkTemplate(b *testing.B) { f := New(11) - for i := 0; i < 100; i++ { + for i := 0; i < b.N; i++ { _, err := f.Template("{{range IntRange 1 (ToInt .Data)}}{{FirstName}} {{LastName}}\n{{end}}", &TemplateOptions{Data: 5}) if err != nil { b.Fatal(err.Error()) } } } - -func BenchmarkTemplateLookup1000(b *testing.B) { - f := New(11) - - for i := 0; i < 1000; i++ { - _, err := f.Template("{{range $y := IntRange 1 (ToInt .Data)}}{{FirstName}} {{LastName}}\n{{end}}", &TemplateOptions{Data: 5}) - if err != nil { - b.Fatal(err.Error()) - } - - } -} diff --git a/time.go b/time.go index ecd0c1ca..cf1db473 100644 --- a/time.go +++ b/time.go @@ -1,164 +1,165 @@ package gofakeit import ( - "math/rand" "strconv" "strings" "time" ) +var currentYear = time.Now().Year() + // Date will generate a random time.Time struct -func Date() time.Time { return date(globalFaker.Rand) } +func Date() time.Time { return date(GlobalFaker) } // Date will generate a random time.Time struct -func (f *Faker) Date() time.Time { return date(f.Rand) } +func (f *Faker) Date() time.Time { return date(f) } -func date(r *rand.Rand) time.Time { - return time.Date(year(r), time.Month(month(r)), day(r), hour(r), minute(r), second(r), nanoSecond(r), time.UTC) +func date(f *Faker) time.Time { + return time.Date(year(f), time.Month(month(f)), day(f), hour(f), minute(f), second(f), nanoSecond(f), time.UTC) } // FutureDate will generate a random past time.Time struct -func PastDate() time.Time { return pastDate(globalFaker.Rand) } +func PastDate() time.Time { return pastDate(GlobalFaker) } // FutureDate will generate a random past time.Time struct -func (f *Faker) PastDate() time.Time { return pastDate(f.Rand) } +func (f *Faker) PastDate() time.Time { return pastDate(f) } -func pastDate(r *rand.Rand) time.Time { - return time.Now().Add(time.Hour * -time.Duration(number(r, 1, 12))) +func pastDate(f *Faker) time.Time { + return time.Now().Add(time.Hour * -time.Duration(number(f, 1, 12))) } // FutureDate will generate a random future time.Time struct -func FutureDate() time.Time { return futureDate(globalFaker.Rand) } +func FutureDate() time.Time { return futureDate(GlobalFaker) } // FutureDate will generate a random future time.Time struct -func (f *Faker) FutureDate() time.Time { return futureDate(f.Rand) } +func (f *Faker) FutureDate() time.Time { return futureDate(f) } -func futureDate(r *rand.Rand) time.Time { - return time.Now().Add(time.Hour * time.Duration(number(r, 1, 12))) +func futureDate(f *Faker) time.Time { + return time.Now().Add(time.Hour * time.Duration(number(f, 1, 12))) } // DateRange will generate a random time.Time struct between a start and end date -func DateRange(start, end time.Time) time.Time { return dateRange(globalFaker.Rand, start, end) } +func DateRange(start, end time.Time) time.Time { return dateRange(GlobalFaker, start, end) } // DateRange will generate a random time.Time struct between a start and end date -func (f *Faker) DateRange(start, end time.Time) time.Time { return dateRange(f.Rand, start, end) } +func (f *Faker) DateRange(start, end time.Time) time.Time { return dateRange(f, start, end) } -func dateRange(r *rand.Rand, start time.Time, end time.Time) time.Time { - return time.Unix(0, int64(number(r, int(start.UnixNano()), int(end.UnixNano())))).UTC() +func dateRange(f *Faker, start time.Time, end time.Time) time.Time { + return time.Unix(0, int64(number(f, int(start.UnixNano()), int(end.UnixNano())))).UTC() } // NanoSecond will generate a random nano second -func NanoSecond() int { return nanoSecond(globalFaker.Rand) } +func NanoSecond() int { return nanoSecond(GlobalFaker) } // NanoSecond will generate a random nano second -func (f *Faker) NanoSecond() int { return nanoSecond(f.Rand) } +func (f *Faker) NanoSecond() int { return nanoSecond(f) } -func nanoSecond(r *rand.Rand) int { return number(r, 0, 999999999) } +func nanoSecond(f *Faker) int { return number(f, 0, 999999999) } // Second will generate a random second -func Second() int { return second(globalFaker.Rand) } +func Second() int { return second(GlobalFaker) } // Second will generate a random second -func (f *Faker) Second() int { return second(f.Rand) } +func (f *Faker) Second() int { return second(f) } -func second(r *rand.Rand) int { return number(r, 0, 59) } +func second(f *Faker) int { return number(f, 0, 59) } // Minute will generate a random minute -func Minute() int { return minute(globalFaker.Rand) } +func Minute() int { return minute(GlobalFaker) } // Minute will generate a random minute -func (f *Faker) Minute() int { return minute(f.Rand) } +func (f *Faker) Minute() int { return minute(f) } -func minute(r *rand.Rand) int { return number(r, 0, 59) } +func minute(f *Faker) int { return number(f, 0, 59) } // Hour will generate a random hour - in military time -func Hour() int { return hour(globalFaker.Rand) } +func Hour() int { return hour(GlobalFaker) } // Hour will generate a random hour - in military time -func (f *Faker) Hour() int { return hour(f.Rand) } +func (f *Faker) Hour() int { return hour(f) } -func hour(r *rand.Rand) int { return number(r, 0, 23) } +func hour(f *Faker) int { return number(f, 0, 23) } // Day will generate a random day between 1 - 31 -func Day() int { return day(globalFaker.Rand) } +func Day() int { return day(GlobalFaker) } // Day will generate a random day between 1 - 31 -func (f *Faker) Day() int { return day(f.Rand) } +func (f *Faker) Day() int { return day(f) } -func day(r *rand.Rand) int { return number(r, 1, 31) } +func day(f *Faker) int { return number(f, 1, 31) } // WeekDay will generate a random weekday string (Monday-Sunday) -func WeekDay() string { return weekDay(globalFaker.Rand) } +func WeekDay() string { return weekDay(GlobalFaker) } // WeekDay will generate a random weekday string (Monday-Sunday) -func (f *Faker) WeekDay() string { return weekDay(f.Rand) } +func (f *Faker) WeekDay() string { return weekDay(f) } -func weekDay(r *rand.Rand) string { return time.Weekday(number(r, 0, 6)).String() } +func weekDay(f *Faker) string { return time.Weekday(number(f, 0, 6)).String() } // Month will generate a random month int -func Month() int { return month(globalFaker.Rand) } +func Month() int { return month(GlobalFaker) } // Month will generate a random month int -func (f *Faker) Month() int { return month(f.Rand) } +func (f *Faker) Month() int { return month(f) } -func month(r *rand.Rand) int { return number(r, 1, 12) } +func month(f *Faker) int { return number(f, 1, 12) } // MonthString will generate a random month string -func MonthString() string { return monthString(globalFaker.Rand) } +func MonthString() string { return monthString(GlobalFaker) } // MonthString will generate a random month string -func (f *Faker) MonthString() string { return monthString(f.Rand) } +func (f *Faker) MonthString() string { return monthString(f) } -func monthString(r *rand.Rand) string { return time.Month(number(r, 1, 12)).String() } +func monthString(f *Faker) string { return time.Month(number(f, 1, 12)).String() } // Year will generate a random year between 1900 - current year -func Year() int { return year(globalFaker.Rand) } +func Year() int { return year(GlobalFaker) } // Year will generate a random year between 1900 - current year -func (f *Faker) Year() int { return year(f.Rand) } +func (f *Faker) Year() int { return year(f) } -func year(r *rand.Rand) int { return number(r, 1900, time.Now().Year()) } +func year(f *Faker) int { return number(f, 1900, currentYear) } // TimeZone will select a random timezone string -func TimeZone() string { return timeZone(globalFaker.Rand) } +func TimeZone() string { return timeZone(GlobalFaker) } // TimeZone will select a random timezone string -func (f *Faker) TimeZone() string { return timeZone(f.Rand) } +func (f *Faker) TimeZone() string { return timeZone(f) } -func timeZone(r *rand.Rand) string { return getRandValue(r, []string{"timezone", "text"}) } +func timeZone(f *Faker) string { return getRandValue(f, []string{"timezone", "text"}) } // TimeZoneFull will select a random full timezone string -func TimeZoneFull() string { return timeZoneFull(globalFaker.Rand) } +func TimeZoneFull() string { return timeZoneFull(GlobalFaker) } // TimeZoneFull will select a random full timezone string -func (f *Faker) TimeZoneFull() string { return timeZoneFull(f.Rand) } +func (f *Faker) TimeZoneFull() string { return timeZoneFull(f) } -func timeZoneFull(r *rand.Rand) string { return getRandValue(r, []string{"timezone", "full"}) } +func timeZoneFull(f *Faker) string { return getRandValue(f, []string{"timezone", "full"}) } // TimeZoneRegion will select a random region style timezone string, e.g. "America/Chicago" -func TimeZoneRegion() string { return timeZoneRegion(globalFaker.Rand) } +func TimeZoneRegion() string { return timeZoneRegion(GlobalFaker) } // TimeZoneRegion will select a random region style timezone string, e.g. "America/Chicago" -func (f *Faker) TimeZoneRegion() string { return timeZoneRegion(f.Rand) } +func (f *Faker) TimeZoneRegion() string { return timeZoneRegion(f) } -func timeZoneRegion(r *rand.Rand) string { return getRandValue(r, []string{"timezone", "region"}) } +func timeZoneRegion(f *Faker) string { return getRandValue(f, []string{"timezone", "region"}) } // TimeZoneAbv will select a random timezone abbreviation string -func TimeZoneAbv() string { return timeZoneAbv(globalFaker.Rand) } +func TimeZoneAbv() string { return timeZoneAbv(GlobalFaker) } // TimeZoneAbv will select a random timezone abbreviation string -func (f *Faker) TimeZoneAbv() string { return timeZoneAbv(f.Rand) } +func (f *Faker) TimeZoneAbv() string { return timeZoneAbv(f) } -func timeZoneAbv(r *rand.Rand) string { return getRandValue(r, []string{"timezone", "abr"}) } +func timeZoneAbv(f *Faker) string { return getRandValue(f, []string{"timezone", "abr"}) } // TimeZoneOffset will select a random timezone offset -func TimeZoneOffset() float32 { return timeZoneOffset(globalFaker.Rand) } +func TimeZoneOffset() float32 { return timeZoneOffset(GlobalFaker) } // TimeZoneOffset will select a random timezone offset -func (f *Faker) TimeZoneOffset() float32 { return timeZoneOffset(f.Rand) } +func (f *Faker) TimeZoneOffset() float32 { return timeZoneOffset(f) } -func timeZoneOffset(r *rand.Rand) float32 { - value, _ := strconv.ParseFloat(getRandValue(r, []string{"timezone", "offset"}), 32) +func timeZoneOffset(f *Faker) float32 { + value, _ := strconv.ParseFloat(getRandValue(f, []string{"timezone", "offset"}), 32) return float32(value) } @@ -226,7 +227,7 @@ func addDateTimeLookup() { Description: "Date time string format output. You may also use golang time format or java time format", }, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { format, err := info.GetString(m, "format") if err != nil { return nil, err @@ -234,31 +235,31 @@ func addDateTimeLookup() { switch format { case "ANSIC": - return Date().Format(time.ANSIC), nil + return f.Date().Format(time.ANSIC), nil case "UnixDate": - return Date().Format(time.UnixDate), nil + return f.Date().Format(time.UnixDate), nil case "RubyDate": - return Date().Format(time.RubyDate), nil + return f.Date().Format(time.RubyDate), nil case "RFC822": - return Date().Format(time.RFC822), nil + return f.Date().Format(time.RFC822), nil case "RFC822Z": - return Date().Format(time.RFC822Z), nil + return f.Date().Format(time.RFC822Z), nil case "RFC850": - return Date().Format(time.RFC850), nil + return f.Date().Format(time.RFC850), nil case "RFC1123": - return Date().Format(time.RFC1123), nil + return f.Date().Format(time.RFC1123), nil case "RFC1123Z": - return Date().Format(time.RFC1123Z), nil + return f.Date().Format(time.RFC1123Z), nil case "RFC3339": - return Date().Format(time.RFC3339), nil + return f.Date().Format(time.RFC3339), nil case "RFC3339Nano": - return Date().Format(time.RFC3339Nano), nil + return f.Date().Format(time.RFC3339Nano), nil default: if format == "" { - return Date().Format(time.RFC3339), nil + return f.Date().Format(time.RFC3339), nil } - return Date().Format(javaDateFormatToGolangDateFormat(format)), nil + return f.Date().Format(javaDateFormatToGolangDateFormat(format)), nil } }, }) @@ -292,7 +293,7 @@ func addDateTimeLookup() { Description: "Date time string format", }, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { format, err := info.GetString(m, "format") if err != nil { return nil, err @@ -326,9 +327,9 @@ func addDateTimeLookup() { Category: "time", Description: "Date that has occurred before the current moment in time", Example: "2007-01-24 13:00:35.820738079 +0000 UTC", - Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return pastDate(r), nil + Output: "time", + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return pastDate(f), nil }, }) @@ -337,9 +338,9 @@ func addDateTimeLookup() { Category: "time", Description: "Date that has occurred after the current moment in time", Example: "2107-01-24 13:00:35.820738079 +0000 UTC", - Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return futureDate(r), nil + Output: "time", + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return futureDate(f), nil }, }) @@ -349,8 +350,8 @@ func addDateTimeLookup() { Description: "Unit of time equal to One billionth (10^-9) of a second", Example: "196446360", Output: "int", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return nanoSecond(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return nanoSecond(f), nil }, }) @@ -360,8 +361,8 @@ func addDateTimeLookup() { Description: "Unit of time equal to 1/60th of a minute", Example: "43", Output: "int", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return second(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return second(f), nil }, }) @@ -371,8 +372,8 @@ func addDateTimeLookup() { Description: "Unit of time equal to 60 seconds", Example: "34", Output: "int", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return minute(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return minute(f), nil }, }) @@ -382,8 +383,8 @@ func addDateTimeLookup() { Description: "Unit of time equal to 60 minutes", Example: "8", Output: "int", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return hour(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return hour(f), nil }, }) @@ -393,8 +394,8 @@ func addDateTimeLookup() { Description: "24-hour period equivalent to one rotation of Earth on its axis", Example: "12", Output: "int", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return day(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return day(f), nil }, }) @@ -404,8 +405,8 @@ func addDateTimeLookup() { Description: "Day of the week excluding the weekend", Example: "Friday", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return weekDay(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return weekDay(f), nil }, }) @@ -415,8 +416,8 @@ func addDateTimeLookup() { Description: "Division of the year, typically 30 or 31 days long", Example: "1", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return month(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return month(f), nil }, }) @@ -426,8 +427,8 @@ func addDateTimeLookup() { Description: "String Representation of a month name", Example: "September", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return monthString(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return monthString(f), nil }, }) @@ -437,8 +438,8 @@ func addDateTimeLookup() { Description: "Period of 365 days, the time Earth takes to orbit the Sun", Example: "1900", Output: "int", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return year(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return year(f), nil }, }) @@ -448,8 +449,8 @@ func addDateTimeLookup() { Description: "Region where the same standard time is used, based on longitudinal divisions of the Earth", Example: "Kaliningrad Standard Time", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return timeZone(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return timeZone(f), nil }, }) @@ -459,8 +460,8 @@ func addDateTimeLookup() { Description: "Abbreviated 3-letter word of a timezone", Example: "KST", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return timeZoneAbv(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return timeZoneAbv(f), nil }, }) @@ -470,8 +471,8 @@ func addDateTimeLookup() { Description: "Full name of a timezone", Example: "(UTC+03:00) Kaliningrad, Minsk", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return timeZoneFull(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return timeZoneFull(f), nil }, }) @@ -481,8 +482,8 @@ func addDateTimeLookup() { Description: "The difference in hours from Coordinated Universal Time (UTC) for a specific region", Example: "3", Output: "float32", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return timeZoneOffset(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return timeZoneOffset(f), nil }, }) @@ -492,8 +493,8 @@ func addDateTimeLookup() { Description: "Geographic area sharing the same standard time", Example: "America/Alaska", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return timeZoneRegion(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return timeZoneRegion(f), nil }, }) diff --git a/time_test.go b/time_test.go index da5bc38a..99e75943 100644 --- a/time_test.go +++ b/time_test.go @@ -10,14 +10,14 @@ func ExampleDate() { Seed(11) fmt.Println(Date()) - // Output: 1915-01-24 13:00:35.820738079 +0000 UTC + // Output: 2011-11-07 04:31:13.726582492 +0000 UTC } func ExampleFaker_Date() { f := New(11) fmt.Println(f.Date()) - // Output: 1915-01-24 13:00:35.820738079 +0000 UTC + // Output: 2011-11-07 04:31:13.726582492 +0000 UTC } func TestDateLookup(t *testing.T) { @@ -25,7 +25,7 @@ func TestDateLookup(t *testing.T) { for _, o := range info.Params[0].Options { mapParams := NewMapParams() mapParams.Add("format", o) - val, _ := info.Generate(globalFaker.Rand, mapParams, info) + val, _ := info.Generate(GlobalFaker, mapParams, info) if val == "" { t.Error("value was empty") } @@ -33,27 +33,9 @@ func TestDateLookup(t *testing.T) { } func BenchmarkDate(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Date() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Date() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Date() - } - }) + for i := 0; i < b.N; i++ { + Date() + } } func ExamplePastDate() { @@ -75,27 +57,9 @@ func TestPastDate(t *testing.T) { } func BenchmarkPastDate(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - PastDate() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.PastDate() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.PastDate() - } - }) + for i := 0; i < b.N; i++ { + PastDate() + } } func ExampleFutureDate() { @@ -117,593 +81,305 @@ func TestFutureDate(t *testing.T) { } func BenchmarkFutureDate(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - FutureDate() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.FutureDate() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.FutureDate() - } - }) + for i := 0; i < b.N; i++ { + FutureDate() + } } func ExampleDateRange() { Seed(11) fmt.Println(DateRange(time.Unix(0, 484633944473634951), time.Unix(0, 1431318744473668209))) // May 10, 1985 years to May 10, 2015 - // Output: 2012-02-04 14:10:37.166933216 +0000 UTC + // Output: 2012-03-26 09:20:49.250961474 +0000 UTC } func ExampleFaker_DateRange() { f := New(11) fmt.Println(f.DateRange(time.Unix(0, 484633944473634951), time.Unix(0, 1431318744473668209))) // May 10, 1985 years to May 10, 2015 - // Output: 2012-02-04 14:10:37.166933216 +0000 UTC + // Output: 2012-03-26 09:20:49.250961474 +0000 UTC } func BenchmarkDateRange(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - DateRange(time.Now().AddDate(-30, 0, 0), time.Now()) - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.DateRange(time.Now().AddDate(-30, 0, 0), time.Now()) - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.DateRange(time.Now().AddDate(-30, 0, 0), time.Now()) - } - }) + for i := 0; i < b.N; i++ { + DateRange(time.Now().AddDate(-30, 0, 0), time.Now()) + } } func ExampleMonth() { Seed(11) fmt.Println(Month()) - // Output: 6 + // Output: 11 } func ExampleFaker_Month() { f := New(11) fmt.Println(f.Month()) - // Output: 6 + // Output: 11 } func BenchmarkMonth(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Month() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Month() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Month() - } - }) + for i := 0; i < b.N; i++ { + Month() + } } func ExampleMonthString() { Seed(11) fmt.Println(MonthString()) - // Output: June + // Output: November } func ExampleFaker_MonthString() { f := New(11) fmt.Println(f.MonthString()) - // Output: June + // Output: November } func BenchmarkMonthString(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - MonthString() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.MonthString() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.MonthString() - } - }) + for i := 0; i < b.N; i++ { + MonthString() + } } func ExampleWeekDay() { Seed(11) fmt.Println(WeekDay()) - // Output: Tuesday + // Output: Saturday } func ExampleFaker_WeekDay() { f := New(11) fmt.Println(f.WeekDay()) - // Output: Tuesday + // Output: Saturday } func BenchmarkWeekDay(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - WeekDay() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.WeekDay() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.WeekDay() - } - }) + for i := 0; i < b.N; i++ { + WeekDay() + } } func ExampleDay() { Seed(11) fmt.Println(Day()) - // Output: 23 + // Output: 28 } func ExampleFaker_Day() { f := New(11) fmt.Println(f.Day()) - // Output: 23 + // Output: 28 } func BenchmarkDay(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Day() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Day() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Day() - } - }) + for i := 0; i < b.N; i++ { + Day() + } } func ExampleYear() { Seed(11) fmt.Println(Year()) - // Output: 1915 + // Output: 2011 } func ExampleFaker_Year() { f := New(11) fmt.Println(f.Year()) - // Output: 1915 + // Output: 2011 } func BenchmarkYear(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Year() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Year() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Year() - } - }) + for i := 0; i < b.N; i++ { + Year() + } } func ExampleHour() { Seed(11) fmt.Println(Hour()) - // Output: 17 + // Output: 21 } func ExampleFaker_Hour() { f := New(11) fmt.Println(f.Hour()) - // Output: 17 + // Output: 21 } func BenchmarkHour(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Hour() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Hour() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Hour() - } - }) + for i := 0; i < b.N; i++ { + Hour() + } } func ExampleMinute() { Seed(11) fmt.Println(Minute()) - // Output: 5 + // Output: 53 } func ExampleFaker_Minute() { f := New(11) fmt.Println(f.Minute()) - // Output: 5 + // Output: 53 } func BenchmarkMinute(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Minute() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Minute() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Minute() - } - }) + for i := 0; i < b.N; i++ { + Minute() + } } func ExampleSecond() { Seed(11) fmt.Println(Second()) - // Output: 5 + // Output: 53 } func ExampleFaker_Second() { f := New(11) fmt.Println(f.Second()) - // Output: 5 + // Output: 53 } func BenchmarkSecond(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - Second() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.Second() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.Second() - } - }) + for i := 0; i < b.N; i++ { + Second() + } } func ExampleNanoSecond() { Seed(11) fmt.Println(NanoSecond()) - // Output: 693298265 + // Output: 895883936 } func ExampleFaker_NanoSecond() { f := New(11) fmt.Println(f.NanoSecond()) - // Output: 693298265 + // Output: 895883936 } func BenchmarkNanoSecond(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - NanoSecond() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.NanoSecond() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.NanoSecond() - } - }) + for i := 0; i < b.N; i++ { + NanoSecond() + } } func ExampleTimeZone() { Seed(11) fmt.Println(TimeZone()) - // Output: Kaliningrad Standard Time + // Output: West Pacific Standard Time } func ExampleFaker_TimeZone() { f := New(11) fmt.Println(f.TimeZone()) - // Output: Kaliningrad Standard Time + // Output: West Pacific Standard Time } func BenchmarkTimeZone(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - TimeZone() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.TimeZone() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.TimeZone() - } - }) + for i := 0; i < b.N; i++ { + TimeZone() + } } func ExampleTimeZoneFull() { Seed(11) fmt.Println(TimeZoneFull()) - // Output: (UTC+03:00) Kaliningrad, Minsk + // Output: (UTC+10:00) Guam, Port Moresby } func ExampleFaker_TimeZoneFull() { f := New(11) fmt.Println(f.TimeZoneFull()) - // Output: (UTC+03:00) Kaliningrad, Minsk + // Output: (UTC+10:00) Guam, Port Moresby } func BenchmarkTimeZoneFull(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - TimeZoneFull() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.TimeZoneFull() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.TimeZoneFull() - } - }) + for i := 0; i < b.N; i++ { + TimeZoneFull() + } } func ExampleTimeZoneAbv() { Seed(11) fmt.Println(TimeZoneAbv()) - // Output: KST + // Output: WPST } func ExampleFaker_TimeZoneAbv() { f := New(11) fmt.Println(f.TimeZoneAbv()) - // Output: KST + // Output: WPST } func BenchmarkTimeZoneAbv(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - TimeZoneAbv() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.TimeZoneAbv() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.TimeZoneAbv() - } - }) + for i := 0; i < b.N; i++ { + TimeZoneAbv() + } } func ExampleTimeZoneOffset() { Seed(11) fmt.Println(TimeZoneOffset()) - // Output: 3 + // Output: 10 } func ExampleFaker_TimeZoneOffset() { f := New(11) fmt.Println(f.TimeZoneOffset()) - // Output: 3 + // Output: 10 } func BenchmarkTimeZoneOffset(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - TimeZoneOffset() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.TimeZoneOffset() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.TimeZoneOffset() - } - }) + for i := 0; i < b.N; i++ { + TimeZoneOffset() + } } func ExampleTimeZoneRegion() { Seed(11) fmt.Println(TimeZoneRegion()) - // Output: America/Vancouver + // Output: Indian/Chagos } func ExampleFaker_TimeZoneRegion() { f := New(11) fmt.Println(f.TimeZoneRegion()) - // Output: America/Vancouver + // Output: Indian/Chagos } func BenchmarkTimeZoneRegion(b *testing.B) { - b.Run("package", func(b *testing.B) { - for i := 0; i < b.N; i++ { - TimeZoneRegion() - } - }) - - b.Run("Faker math", func(b *testing.B) { - f := New(0) - - for i := 0; i < b.N; i++ { - f.TimeZoneRegion() - } - }) - - b.Run("Faker crypto", func(b *testing.B) { - f := NewCrypto() - - for i := 0; i < b.N; i++ { - f.TimeZoneRegion() - } - }) + for i := 0; i < b.N; i++ { + TimeZoneRegion() + } } diff --git a/weighted.go b/weighted.go index c04fa6bd..cedfe42d 100644 --- a/weighted.go +++ b/weighted.go @@ -2,21 +2,20 @@ package gofakeit import ( "errors" - "math/rand" ) // Weighted will take in an array of options and weights and return a random selection based upon its indexed weight func Weighted(options []any, weights []float32) (any, error) { - return weighted(globalFaker.Rand, options, weights) + return weighted(GlobalFaker, options, weights) } // Weighted will take in an array of options and weights and return a random selection based upon its indexed weight func (f *Faker) Weighted(options []any, weights []float32) (any, error) { - return weighted(f.Rand, options, weights) + return weighted(f, options, weights) } // Weighted will take in an array of options and weights and return a random selection based upon its indexed weight -func weighted(r *rand.Rand, options []any, weights []float32) (any, error) { +func weighted(f *Faker, options []any, weights []float32) (any, error) { ol := len(options) wl := len(weights) @@ -55,7 +54,7 @@ func weighted(r *rand.Rand, options []any, weights []float32) (any, error) { } // Get rand value from a multple of sumOfWeights - randSumOfWeights := r.Float32() * sumOfWeights + randSumOfWeights := f.Float32() * sumOfWeights var l int = 0 var h int = wl - 1 @@ -85,7 +84,7 @@ func addWeightedLookup() { {Field: "options", Display: "Options", Type: "[]string", Description: "Array of any values"}, {Field: "weights", Display: "Weights", Type: "[]float", Description: "Array of weights"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { options, err := info.GetStringArray(m, "options") if err != nil { return nil, err @@ -101,7 +100,7 @@ func addWeightedLookup() { optionsInterface[i] = o } - return weighted(r, optionsInterface, weights) + return weighted(f, optionsInterface, weights) }, }) } diff --git a/weighted_test.go b/weighted_test.go index 3f77683d..0cf4f921 100644 --- a/weighted_test.go +++ b/weighted_test.go @@ -14,7 +14,7 @@ func ExampleWeighted() { fmt.Println(option) - // Output: hello + // Output: 2 } func TestWeighted(t *testing.T) { @@ -62,8 +62,10 @@ func TestWeightedStruct(t *testing.T) { var weight weighted Struct(&weight) - if weight.S != "hello" { - t.Errorf("Expected hello got %s", weight.S) + + // Make sure it is one of the options + if weight.S != "hello" && weight.S != "2" && weight.S != "6.9" { + t.Error("Weighted did not return one of the options") } } diff --git a/word_adjective.go b/word_adjective.go index c9fcbd8e..01efb032 100644 --- a/word_adjective.go +++ b/word_adjective.go @@ -1,14 +1,12 @@ package gofakeit -import "math/rand" - // Adjective will generate a random adjective -func Adjective() string { return adjective(globalFaker.Rand) } +func Adjective() string { return adjective(GlobalFaker) } // Adjective will generate a random adjective -func (f *Faker) Adjective() string { return adjective(f.Rand) } +func (f *Faker) Adjective() string { return adjective(f) } -func adjective(r *rand.Rand) string { +func adjective(f *Faker) string { var adjType = map[int]string{ 0: "adjective_descriptive", 1: "adjective_quantitative", @@ -18,77 +16,77 @@ func adjective(r *rand.Rand) string { 5: "adjective_interrogative", 6: "adjective_indefinite", } - return getRandValue(r, []string{"word", adjType[number(r, 0, 6)]}) + return getRandValue(f, []string{"word", adjType[number(f, 0, 6)]}) } // AdjectiveDescriptive will generate a random descriptive adjective -func AdjectiveDescriptive() string { return adjectiveDescriptive(globalFaker.Rand) } +func AdjectiveDescriptive() string { return adjectiveDescriptive(GlobalFaker) } // AdjectiveDescriptive will generate a random descriptive adjective -func (f *Faker) AdjectiveDescriptive() string { return adjectiveDescriptive(f.Rand) } +func (f *Faker) AdjectiveDescriptive() string { return adjectiveDescriptive(f) } -func adjectiveDescriptive(r *rand.Rand) string { - return getRandValue(r, []string{"word", "adjective_descriptive"}) +func adjectiveDescriptive(f *Faker) string { + return getRandValue(f, []string{"word", "adjective_descriptive"}) } // AdjectiveQuantitative will generate a random quantitative adjective -func AdjectiveQuantitative() string { return adjectiveQuantitative(globalFaker.Rand) } +func AdjectiveQuantitative() string { return adjectiveQuantitative(GlobalFaker) } // AdjectiveQuantitative will generate a random quantitative adjective -func (f *Faker) AdjectiveQuantitative() string { return adjectiveQuantitative(f.Rand) } +func (f *Faker) AdjectiveQuantitative() string { return adjectiveQuantitative(f) } -func adjectiveQuantitative(r *rand.Rand) string { - return getRandValue(r, []string{"word", "adjective_quantitative"}) +func adjectiveQuantitative(f *Faker) string { + return getRandValue(f, []string{"word", "adjective_quantitative"}) } // AdjectiveProper will generate a random proper adjective -func AdjectiveProper() string { return adjectiveProper(globalFaker.Rand) } +func AdjectiveProper() string { return adjectiveProper(GlobalFaker) } // AdjectiveProper will generate a random proper adjective -func (f *Faker) AdjectiveProper() string { return adjectiveProper(f.Rand) } +func (f *Faker) AdjectiveProper() string { return adjectiveProper(f) } -func adjectiveProper(r *rand.Rand) string { - return getRandValue(r, []string{"word", "adjective_proper"}) +func adjectiveProper(f *Faker) string { + return getRandValue(f, []string{"word", "adjective_proper"}) } // AdjectiveDemonstrative will generate a random demonstrative adjective -func AdjectiveDemonstrative() string { return adjectiveDemonstrative(globalFaker.Rand) } +func AdjectiveDemonstrative() string { return adjectiveDemonstrative(GlobalFaker) } // AdjectiveDemonstrative will generate a random demonstrative adjective -func (f *Faker) AdjectiveDemonstrative() string { return adjectiveDemonstrative(f.Rand) } +func (f *Faker) AdjectiveDemonstrative() string { return adjectiveDemonstrative(f) } -func adjectiveDemonstrative(r *rand.Rand) string { - return getRandValue(r, []string{"word", "adjective_demonstrative"}) +func adjectiveDemonstrative(f *Faker) string { + return getRandValue(f, []string{"word", "adjective_demonstrative"}) } // AdjectivePossessive will generate a random possessive adjective -func AdjectivePossessive() string { return adjectivePossessive(globalFaker.Rand) } +func AdjectivePossessive() string { return adjectivePossessive(GlobalFaker) } // AdjectivePossessive will generate a random possessive adjective -func (f *Faker) AdjectivePossessive() string { return adjectivePossessive(f.Rand) } +func (f *Faker) AdjectivePossessive() string { return adjectivePossessive(f) } -func adjectivePossessive(r *rand.Rand) string { - return getRandValue(r, []string{"word", "adjective_possessive"}) +func adjectivePossessive(f *Faker) string { + return getRandValue(f, []string{"word", "adjective_possessive"}) } // AdjectiveInterrogative will generate a random interrogative adjective -func AdjectiveInterrogative() string { return adjectiveInterrogative(globalFaker.Rand) } +func AdjectiveInterrogative() string { return adjectiveInterrogative(GlobalFaker) } // AdjectiveInterrogative will generate a random interrogative adjective -func (f *Faker) AdjectiveInterrogative() string { return adjectiveInterrogative(f.Rand) } +func (f *Faker) AdjectiveInterrogative() string { return adjectiveInterrogative(f) } -func adjectiveInterrogative(r *rand.Rand) string { - return getRandValue(r, []string{"word", "adjective_interrogative"}) +func adjectiveInterrogative(f *Faker) string { + return getRandValue(f, []string{"word", "adjective_interrogative"}) } // AdjectiveIndefinite will generate a random indefinite adjective -func AdjectiveIndefinite() string { return adjectiveIndefinite(globalFaker.Rand) } +func AdjectiveIndefinite() string { return adjectiveIndefinite(GlobalFaker) } // AdjectiveIndefinite will generate a random indefinite adjective -func (f *Faker) AdjectiveIndefinite() string { return adjectiveIndefinite(f.Rand) } +func (f *Faker) AdjectiveIndefinite() string { return adjectiveIndefinite(f) } -func adjectiveIndefinite(r *rand.Rand) string { - return getRandValue(r, []string{"word", "adjective_indefinite"}) +func adjectiveIndefinite(f *Faker) string { + return getRandValue(f, []string{"word", "adjective_indefinite"}) } func addWordAdjectiveLookup() { @@ -98,8 +96,8 @@ func addWordAdjectiveLookup() { Description: "Word describing or modifying a noun", Example: "genuine", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adjective(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adjective(f), nil }, }) @@ -109,8 +107,8 @@ func addWordAdjectiveLookup() { Description: "Adjective that provides detailed characteristics about a noun", Example: "brave", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adjectiveDescriptive(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adjectiveDescriptive(f), nil }, }) @@ -120,8 +118,8 @@ func addWordAdjectiveLookup() { Description: "Adjective that indicates the quantity or amount of something", Example: "a little", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adjectiveQuantitative(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adjectiveQuantitative(f), nil }, }) @@ -131,8 +129,8 @@ func addWordAdjectiveLookup() { Description: "Adjective derived from a proper noun, often used to describe nationality or origin", Example: "Afghan", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adjectiveProper(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adjectiveProper(f), nil }, }) @@ -142,8 +140,8 @@ func addWordAdjectiveLookup() { Description: "Adjective used to point out specific things", Example: "this", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adjectiveDemonstrative(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adjectiveDemonstrative(f), nil }, }) @@ -153,8 +151,8 @@ func addWordAdjectiveLookup() { Description: "Adjective indicating ownership or possession", Example: "my", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adjectivePossessive(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adjectivePossessive(f), nil }, }) @@ -164,8 +162,8 @@ func addWordAdjectiveLookup() { Description: "Adjective used to ask questions", Example: "what", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adjectiveInterrogative(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adjectiveInterrogative(f), nil }, }) @@ -175,8 +173,8 @@ func addWordAdjectiveLookup() { Description: "Adjective describing a non-specific noun", Example: "few", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adjectiveIndefinite(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adjectiveIndefinite(f), nil }, }) } diff --git a/word_adjective_test.go b/word_adjective_test.go index cae1265a..6d5d7d91 100644 --- a/word_adjective_test.go +++ b/word_adjective_test.go @@ -9,14 +9,14 @@ func ExampleAdjective() { Seed(11) fmt.Println(Adjective()) - // Output: Dutch + // Output: none } func ExampleFaker_Adjective() { f := New(11) fmt.Println(f.Adjective()) - // Output: Dutch + // Output: none } func BenchmarkAdjective(b *testing.B) { @@ -29,14 +29,14 @@ func ExampleAdjectiveDescriptive() { Seed(11) fmt.Println(AdjectiveDescriptive()) - // Output: brave + // Output: tired } func ExampleFaker_AdjectiveDescriptive() { f := New(11) fmt.Println(f.AdjectiveDescriptive()) - // Output: brave + // Output: tired } func BenchmarkAdjectiveDescriptive(b *testing.B) { @@ -49,14 +49,14 @@ func ExampleAdjectiveQuantitative() { Seed(11) fmt.Println(AdjectiveQuantitative()) - // Output: a little + // Output: sparse } func ExampleFaker_AdjectiveQuantitative() { f := New(11) fmt.Println(f.AdjectiveQuantitative()) - // Output: a little + // Output: sparse } func BenchmarkAdjectiveQuantitative(b *testing.B) { @@ -69,14 +69,14 @@ func ExampleAdjectiveProper() { Seed(11) fmt.Println(AdjectiveProper()) - // Output: Afghan + // Output: Swiss } func ExampleFaker_AdjectiveProper() { f := New(11) fmt.Println(f.AdjectiveProper()) - // Output: Afghan + // Output: Swiss } func BenchmarkAdjectiveProper(b *testing.B) { @@ -89,14 +89,14 @@ func ExampleAdjectiveDemonstrative() { Seed(11) fmt.Println(AdjectiveDemonstrative()) - // Output: this + // Output: it } func ExampleFaker_AdjectiveDemonstrative() { f := New(11) fmt.Println(f.AdjectiveDemonstrative()) - // Output: this + // Output: it } func BenchmarkAdjectiveDemonstrative(b *testing.B) { @@ -109,14 +109,14 @@ func ExampleAdjectivePossessive() { Seed(11) fmt.Println(AdjectivePossessive()) - // Output: our + // Output: their } func ExampleFaker_AdjectivePossessive() { f := New(11) fmt.Println(f.AdjectivePossessive()) - // Output: our + // Output: their } func BenchmarkAdjectivePossessive(b *testing.B) { @@ -129,14 +129,14 @@ func ExampleAdjectiveInterrogative() { Seed(11) fmt.Println(AdjectiveInterrogative()) - // Output: what + // Output: which } func ExampleFaker_AdjectiveInterrogative() { f := New(11) fmt.Println(f.AdjectiveInterrogative()) - // Output: what + // Output: which } func BenchmarkAdjectiveInterrogative(b *testing.B) { @@ -149,14 +149,14 @@ func ExampleAdjectiveIndefinite() { Seed(11) fmt.Println(AdjectiveIndefinite()) - // Output: few + // Output: several } func ExampleFaker_AdjectiveIndefinite() { f := New(11) fmt.Println(f.AdjectiveIndefinite()) - // Output: few + // Output: several } func BenchmarkAdjectiveIndefinite(b *testing.B) { diff --git a/word_adverb.go b/word_adverb.go index b148bf8d..4cafb8a8 100644 --- a/word_adverb.go +++ b/word_adverb.go @@ -1,14 +1,12 @@ package gofakeit -import "math/rand" - // Adverb will generate a random adverb -func Adverb() string { return adverb(globalFaker.Rand) } +func Adverb() string { return adverb(GlobalFaker) } // Adverb will generate a random adverb -func (f *Faker) Adverb() string { return adverb(f.Rand) } +func (f *Faker) Adverb() string { return adverb(f) } -func adverb(r *rand.Rand) string { +func adverb(f *Faker) string { var adverbType = map[int]string{ 0: "adverb_manner", 1: "adverb_degree", @@ -18,71 +16,71 @@ func adverb(r *rand.Rand) string { 5: "adverb_frequency_definite", 6: "adverb_frequency_indefinite", } - return getRandValue(r, []string{"word", adverbType[number(r, 0, 6)]}) + return getRandValue(f, []string{"word", adverbType[number(f, 0, 6)]}) } // AdverbManner will generate a random manner adverb -func AdverbManner() string { return adverbManner(globalFaker.Rand) } +func AdverbManner() string { return adverbManner(GlobalFaker) } // AdverbManner will generate a random manner adverb -func (f *Faker) AdverbManner() string { return adverbManner(f.Rand) } +func (f *Faker) AdverbManner() string { return adverbManner(f) } -func adverbManner(r *rand.Rand) string { return getRandValue(r, []string{"word", "adverb_manner"}) } +func adverbManner(f *Faker) string { return getRandValue(f, []string{"word", "adverb_manner"}) } // AdverbDegree will generate a random degree adverb -func AdverbDegree() string { return adverbDegree(globalFaker.Rand) } +func AdverbDegree() string { return adverbDegree(GlobalFaker) } // AdverbDegree will generate a random degree adverb -func (f *Faker) AdverbDegree() string { return adverbDegree(f.Rand) } +func (f *Faker) AdverbDegree() string { return adverbDegree(f) } -func adverbDegree(r *rand.Rand) string { return getRandValue(r, []string{"word", "adverb_degree"}) } +func adverbDegree(f *Faker) string { return getRandValue(f, []string{"word", "adverb_degree"}) } // AdverbPlace will generate a random place adverb -func AdverbPlace() string { return adverbPlace(globalFaker.Rand) } +func AdverbPlace() string { return adverbPlace(GlobalFaker) } // AdverbPlace will generate a random place adverb -func (f *Faker) AdverbPlace() string { return adverbPlace(f.Rand) } +func (f *Faker) AdverbPlace() string { return adverbPlace(f) } -func adverbPlace(r *rand.Rand) string { return getRandValue(r, []string{"word", "adverb_place"}) } +func adverbPlace(f *Faker) string { return getRandValue(f, []string{"word", "adverb_place"}) } // AdverbTimeDefinite will generate a random time definite adverb -func AdverbTimeDefinite() string { return adverbTimeDefinite(globalFaker.Rand) } +func AdverbTimeDefinite() string { return adverbTimeDefinite(GlobalFaker) } // AdverbTimeDefinite will generate a random time definite adverb -func (f *Faker) AdverbTimeDefinite() string { return adverbTimeDefinite(f.Rand) } +func (f *Faker) AdverbTimeDefinite() string { return adverbTimeDefinite(f) } -func adverbTimeDefinite(r *rand.Rand) string { - return getRandValue(r, []string{"word", "adverb_time_definite"}) +func adverbTimeDefinite(f *Faker) string { + return getRandValue(f, []string{"word", "adverb_time_definite"}) } // AdverbTimeIndefinite will generate a random time indefinite adverb -func AdverbTimeIndefinite() string { return adverbTimeIndefinite(globalFaker.Rand) } +func AdverbTimeIndefinite() string { return adverbTimeIndefinite(GlobalFaker) } // AdverbTimeIndefinite will generate a random time indefinite adverb -func (f *Faker) AdverbTimeIndefinite() string { return adverbTimeIndefinite(f.Rand) } +func (f *Faker) AdverbTimeIndefinite() string { return adverbTimeIndefinite(f) } -func adverbTimeIndefinite(r *rand.Rand) string { - return getRandValue(r, []string{"word", "adverb_time_indefinite"}) +func adverbTimeIndefinite(f *Faker) string { + return getRandValue(f, []string{"word", "adverb_time_indefinite"}) } // AdverbFrequencyDefinite will generate a random frequency definite adverb -func AdverbFrequencyDefinite() string { return adverbFrequencyDefinite(globalFaker.Rand) } +func AdverbFrequencyDefinite() string { return adverbFrequencyDefinite(GlobalFaker) } // AdverbFrequencyDefinite will generate a random frequency definite adverb -func (f *Faker) AdverbFrequencyDefinite() string { return adverbFrequencyDefinite(f.Rand) } +func (f *Faker) AdverbFrequencyDefinite() string { return adverbFrequencyDefinite(f) } -func adverbFrequencyDefinite(r *rand.Rand) string { - return getRandValue(r, []string{"word", "adverb_frequency_definite"}) +func adverbFrequencyDefinite(f *Faker) string { + return getRandValue(f, []string{"word", "adverb_frequency_definite"}) } // AdverbFrequencyIndefinite will generate a random frequency indefinite adverb -func AdverbFrequencyIndefinite() string { return adverbFrequencyIndefinite(globalFaker.Rand) } +func AdverbFrequencyIndefinite() string { return adverbFrequencyIndefinite(GlobalFaker) } // AdverbFrequencyIndefinite will generate a random frequency indefinite adverb -func (f *Faker) AdverbFrequencyIndefinite() string { return adverbFrequencyIndefinite(f.Rand) } +func (f *Faker) AdverbFrequencyIndefinite() string { return adverbFrequencyIndefinite(f) } -func adverbFrequencyIndefinite(r *rand.Rand) string { - return getRandValue(r, []string{"word", "adverb_frequency_indefinite"}) +func adverbFrequencyIndefinite(f *Faker) string { + return getRandValue(f, []string{"word", "adverb_frequency_indefinite"}) } func addWordAdverbLookup() { @@ -92,8 +90,8 @@ func addWordAdverbLookup() { Description: "Word that modifies verbs, adjectives, or other adverbs", Example: "smoothly", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adverb(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adverb(f), nil }, }) @@ -103,8 +101,8 @@ func addWordAdverbLookup() { Description: "Adverb that describes how an action is performed", Example: "stupidly", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adverbManner(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adverbManner(f), nil }, }) @@ -114,8 +112,8 @@ func addWordAdverbLookup() { Description: "Adverb that indicates the degree or intensity of an action or adjective", Example: "intensely", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adverbDegree(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adverbDegree(f), nil }, }) @@ -125,8 +123,8 @@ func addWordAdverbLookup() { Description: "Adverb that indicates the location or direction of an action", Example: "east", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adverbPlace(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adverbPlace(f), nil }, }) @@ -136,8 +134,8 @@ func addWordAdverbLookup() { Description: "Adverb that specifies the exact time an action occurs", Example: "now", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adverbTimeDefinite(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adverbTimeDefinite(f), nil }, }) @@ -147,8 +145,8 @@ func addWordAdverbLookup() { Description: "Adverb that gives a general or unspecified time frame", Example: "already", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adverbTimeIndefinite(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adverbTimeIndefinite(f), nil }, }) @@ -158,8 +156,8 @@ func addWordAdverbLookup() { Description: "Adverb that specifies how often an action occurs with a clear frequency", Example: "hourly", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adverbFrequencyDefinite(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adverbFrequencyDefinite(f), nil }, }) @@ -169,8 +167,8 @@ func addWordAdverbLookup() { Description: "Adverb that specifies how often an action occurs without specifying a particular frequency", Example: "occasionally", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return adverbFrequencyIndefinite(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return adverbFrequencyIndefinite(f), nil }, }) } diff --git a/word_adverb_test.go b/word_adverb_test.go index ba48dbda..e74f560d 100644 --- a/word_adverb_test.go +++ b/word_adverb_test.go @@ -9,14 +9,14 @@ func ExampleAdverb() { Seed(11) fmt.Println(Adverb()) - // Output: over + // Output: ever } func ExampleFaker_Adverb() { f := New(11) fmt.Println(f.Adverb()) - // Output: over + // Output: ever } func BenchmarkAdverb(b *testing.B) { @@ -29,14 +29,14 @@ func ExampleAdverbManner() { Seed(11) fmt.Println(AdverbManner()) - // Output: stupidly + // Output: tensely } func ExampleFaker_AdverbManner() { f := New(11) fmt.Println(f.AdverbManner()) - // Output: stupidly + // Output: tensely } func BenchmarkAdverbManner(b *testing.B) { @@ -49,14 +49,14 @@ func ExampleAdverbDegree() { Seed(11) fmt.Println(AdverbDegree()) - // Output: intensely + // Output: too } func ExampleFaker_AdverbDegree() { f := New(11) fmt.Println(f.AdverbDegree()) - // Output: intensely + // Output: too } func BenchmarkAdverbDegree(b *testing.B) { @@ -69,14 +69,14 @@ func ExampleAdverbPlace() { Seed(11) fmt.Println(AdverbPlace()) - // Output: east + // Output: under } func ExampleFaker_AdverbPlace() { f := New(11) fmt.Println(f.AdverbPlace()) - // Output: east + // Output: under } func BenchmarkAdverbPlace(b *testing.B) { @@ -89,14 +89,14 @@ func ExampleAdverbTimeDefinite() { Seed(11) fmt.Println(AdverbTimeDefinite()) - // Output: now + // Output: yesterday } func ExampleFaker_AdverbTimeDefinite() { f := New(11) fmt.Println(f.AdverbTimeDefinite()) - // Output: now + // Output: yesterday } func BenchmarkAdverbTimeDefinite(b *testing.B) { @@ -109,14 +109,14 @@ func ExampleAdverbTimeIndefinite() { Seed(11) fmt.Println(AdverbTimeIndefinite()) - // Output: already + // Output: soon } func ExampleFaker_AdverbTimeIndefinite() { f := New(11) fmt.Println(f.AdverbTimeIndefinite()) - // Output: already + // Output: soon } func BenchmarkAdverbTimeIndefinite(b *testing.B) { @@ -129,14 +129,14 @@ func ExampleAdverbFrequencyDefinite() { Seed(11) fmt.Println(AdverbFrequencyDefinite()) - // Output: hourly + // Output: yearly } func ExampleFaker_AdverbFrequencyDefinite() { f := New(11) fmt.Println(f.AdverbFrequencyDefinite()) - // Output: hourly + // Output: yearly } func BenchmarkAdverbFrequencyDefinite(b *testing.B) { @@ -149,14 +149,14 @@ func ExampleAdverbFrequencyIndefinite() { Seed(11) fmt.Println(AdverbFrequencyIndefinite()) - // Output: occasionally + // Output: generally } func ExampleFaker_AdverbFrequencyIndefinite() { f := New(11) fmt.Println(f.AdverbFrequencyIndefinite()) - // Output: occasionally + // Output: generally } func BenchmarkAdverbFrequencyIndefinite(b *testing.B) { diff --git a/word_comment.go b/word_comment.go index 3f5d3e41..f73d1f03 100644 --- a/word_comment.go +++ b/word_comment.go @@ -1,17 +1,16 @@ package gofakeit import ( - "math/rand" "strings" ) // Comment will generate a random statement or remark expressing an opinion, observation, or reaction -func Comment() string { return comment(globalFaker.Rand) } +func Comment() string { return comment(GlobalFaker) } // Comment will generate a random statement or remark expressing an opinion, observation, or reaction -func (f *Faker) Comment() string { return comment(f.Rand) } +func (f *Faker) Comment() string { return comment(f) } -func comment(r *rand.Rand) string { +func comment(f *Faker) string { structures := [][]string{ {"interjection", "adjective", "noun", "verb", "adverb"}, {"noun", "verb", "preposition", "determiner", "adjective", "noun"}, @@ -21,26 +20,26 @@ func comment(r *rand.Rand) string { } // Randomly select a structure - structure := structures[number(r, 0, len(structures)-1)] + structure := structures[number(f, 0, len(structures)-1)] // Build the sentence var commentParts []string for _, wordType := range structure { switch wordType { case "noun": - commentParts = append(commentParts, noun(r)) + commentParts = append(commentParts, noun(f)) case "verb": - commentParts = append(commentParts, verb(r)) + commentParts = append(commentParts, verb(f)) case "adjective": - commentParts = append(commentParts, adjective(r)) + commentParts = append(commentParts, adjective(f)) case "adverb": - commentParts = append(commentParts, adverb(r)) + commentParts = append(commentParts, adverb(f)) case "interjection": - commentParts = append(commentParts, interjection(r)) + commentParts = append(commentParts, interjection(f)) case "preposition": - commentParts = append(commentParts, preposition(r)) + commentParts = append(commentParts, preposition(f)) case "determiner": - commentParts = append(commentParts, nounDeterminer(r)) + commentParts = append(commentParts, nounDeterminer(f)) default: // Should never hit panic("Invalid word type") @@ -66,8 +65,8 @@ func addWordCommentLookup() { Description: "Statement or remark expressing an opinion, observation, or reaction", Example: "wow", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return interjection(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return interjection(f), nil }, }) } diff --git a/word_comment_test.go b/word_comment_test.go index bb7780a4..4ea222b2 100644 --- a/word_comment_test.go +++ b/word_comment_test.go @@ -9,14 +9,14 @@ func ExampleComment() { Seed(11) fmt.Println(Comment()) - // Output: Phew Substantial Thing Had Regularly. + // Output: Fear Drink To Heart. } func ExampleFaker_Comment() { f := New(11) fmt.Println(f.Comment()) - // Output: Phew Substantial Thing Had Regularly. + // Output: Fear Drink To Heart. } func TestComment(t *testing.T) { diff --git a/word_connective.go b/word_connective.go index 5be26166..92dc025f 100644 --- a/word_connective.go +++ b/word_connective.go @@ -1,14 +1,12 @@ package gofakeit -import "math/rand" - // Connective will generate a random connective -func Connective() string { return connective(globalFaker.Rand) } +func Connective() string { return connective(GlobalFaker) } // Connective will generate a random connective -func (f *Faker) Connective() string { return connective(f.Rand) } +func (f *Faker) Connective() string { return connective(f) } -func connective(r *rand.Rand) string { +func connective(f *Faker) string { var connectiveType = map[int]string{ 0: "connective_time", 1: "connective_comparative", @@ -17,68 +15,68 @@ func connective(r *rand.Rand) string { 4: "connective_casual", 5: "connective_examplify", } - return getRandValue(r, []string{"word", connectiveType[number(r, 0, 5)]}) + return getRandValue(f, []string{"word", connectiveType[number(f, 0, 5)]}) } // ConnectiveTime will generate a random connective time -func ConnectiveTime() string { return connectiveTime(globalFaker.Rand) } +func ConnectiveTime() string { return connectiveTime(GlobalFaker) } // ConnectiveTime will generate a random connective time -func (f *Faker) ConnectiveTime() string { return connectiveTime(f.Rand) } +func (f *Faker) ConnectiveTime() string { return connectiveTime(f) } -func connectiveTime(r *rand.Rand) string { - return getRandValue(r, []string{"word", "connective_time"}) +func connectiveTime(f *Faker) string { + return getRandValue(f, []string{"word", "connective_time"}) } // ConnectiveComparative will generate a random comparative connective -func ConnectiveComparative() string { return connectiveComparative(globalFaker.Rand) } +func ConnectiveComparative() string { return connectiveComparative(GlobalFaker) } // ConnectiveComparative will generate a random comparative connective -func (f *Faker) ConnectiveComparative() string { return connectiveComparative(f.Rand) } +func (f *Faker) ConnectiveComparative() string { return connectiveComparative(f) } -func connectiveComparative(r *rand.Rand) string { - return getRandValue(r, []string{"word", "connective_comparative"}) +func connectiveComparative(f *Faker) string { + return getRandValue(f, []string{"word", "connective_comparative"}) } // ConnectiveComplaint will generate a random complaint connective -func ConnectiveComplaint() string { return connectiveComplaint(globalFaker.Rand) } +func ConnectiveComplaint() string { return connectiveComplaint(GlobalFaker) } // ConnectiveComplaint will generate a random complaint connective -func (f *Faker) ConnectiveComplaint() string { return connectiveComplaint(f.Rand) } +func (f *Faker) ConnectiveComplaint() string { return connectiveComplaint(f) } -func connectiveComplaint(r *rand.Rand) string { - return getRandValue(r, []string{"word", "connective_complaint"}) +func connectiveComplaint(f *Faker) string { + return getRandValue(f, []string{"word", "connective_complaint"}) } // ConnectiveListing will generate a random listing connective -func ConnectiveListing() string { return connectiveListing(globalFaker.Rand) } +func ConnectiveListing() string { return connectiveListing(GlobalFaker) } // ConnectiveListing will generate a random listing connective -func (f *Faker) ConnectiveListing() string { return connectiveListing(f.Rand) } +func (f *Faker) ConnectiveListing() string { return connectiveListing(f) } -func connectiveListing(r *rand.Rand) string { - return getRandValue(r, []string{"word", "connective_listing"}) +func connectiveListing(f *Faker) string { + return getRandValue(f, []string{"word", "connective_listing"}) } // ConnectiveCasual will generate a random casual connective -func ConnectiveCasual() string { return connectiveCasual(globalFaker.Rand) } +func ConnectiveCasual() string { return connectiveCasual(GlobalFaker) } // ConnectiveCasual will generate a random casual connective -func (f *Faker) ConnectiveCasual() string { return connectiveCasual(f.Rand) } +func (f *Faker) ConnectiveCasual() string { return connectiveCasual(f) } -func connectiveCasual(r *rand.Rand) string { - return getRandValue(r, []string{"word", "connective_casual"}) +func connectiveCasual(f *Faker) string { + return getRandValue(f, []string{"word", "connective_casual"}) } // ConnectiveExamplify will generate a random examplify connective -func ConnectiveExamplify() string { return connectiveExamplify(globalFaker.Rand) } +func ConnectiveExamplify() string { return connectiveExamplify(GlobalFaker) } // ConnectiveExamplify will generate a random examplify connective -func (f *Faker) ConnectiveExamplify() string { return connectiveExamplify(f.Rand) } +func (f *Faker) ConnectiveExamplify() string { return connectiveExamplify(f) } -func connectiveExamplify(r *rand.Rand) string { - return getRandValue(r, []string{"word", "connective_examplify"}) +func connectiveExamplify(f *Faker) string { + return getRandValue(f, []string{"word", "connective_examplify"}) } func addWordConnectiveLookup() { @@ -88,8 +86,8 @@ func addWordConnectiveLookup() { Description: "Word used to connect words or sentences", Example: "such as", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return connective(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return connective(f), nil }, }) @@ -99,8 +97,8 @@ func addWordConnectiveLookup() { Description: "Connective word used to indicate a temporal relationship between events or actions", Example: "finally", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return connectiveTime(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return connectiveTime(f), nil }, }) @@ -110,8 +108,8 @@ func addWordConnectiveLookup() { Description: "Connective word used to indicate a comparison between two or more things", Example: "in addition", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return connectiveComparative(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return connectiveComparative(f), nil }, }) @@ -121,8 +119,8 @@ func addWordConnectiveLookup() { Description: "Connective word used to express dissatisfaction or complaints about a situation", Example: "besides", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return connectiveComplaint(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return connectiveComplaint(f), nil }, }) @@ -132,8 +130,8 @@ func addWordConnectiveLookup() { Description: "Connective word used to list or enumerate items or examples", Example: "firstly", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return connectiveListing(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return connectiveListing(f), nil }, }) @@ -143,8 +141,8 @@ func addWordConnectiveLookup() { Description: "Connective word used to indicate a cause-and-effect relationship between events or actions", Example: "an outcome of", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return connectiveCasual(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return connectiveCasual(f), nil }, }) @@ -154,8 +152,8 @@ func addWordConnectiveLookup() { Description: "Connective word used to provide examples or illustrations of a concept or idea", Example: "then", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return connectiveExamplify(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return connectiveExamplify(f), nil }, }) } diff --git a/word_connective_test.go b/word_connective_test.go index 57655655..c1caa68b 100644 --- a/word_connective_test.go +++ b/word_connective_test.go @@ -9,14 +9,14 @@ func ExampleConnective() { Seed(11) fmt.Println(Connective()) - // Output: such as + // Output: through } func ExampleFaker_Connective() { f := New(11) fmt.Println(f.Connective()) - // Output: such as + // Output: through } func BenchmarkConnective(b *testing.B) { @@ -29,14 +29,14 @@ func ExampleConnectiveTime() { Seed(11) fmt.Println(ConnectiveTime()) - // Output: finally + // Output: when } func ExampleFaker_ConnectiveTime() { f := New(11) fmt.Println(f.ConnectiveTime()) - // Output: finally + // Output: when } func BenchmarkConnectiveTime(b *testing.B) { @@ -49,14 +49,14 @@ func ExampleConnectiveComparative() { Seed(11) fmt.Println(ConnectiveComparative()) - // Output: in addition + // Output: after all } func ExampleFaker_ConnectiveComparative() { f := New(11) fmt.Println(f.ConnectiveComparative()) - // Output: in addition + // Output: after all } func BenchmarkConnectiveComparative(b *testing.B) { @@ -69,14 +69,14 @@ func ExampleConnectiveComplaint() { Seed(11) fmt.Println(ConnectiveComplaint()) - // Output: besides + // Output: i.e. } func ExampleFaker_ConnectiveComplaint() { f := New(11) fmt.Println(f.ConnectiveComplaint()) - // Output: besides + // Output: i.e. } func BenchmarkConnectiveComplaint(b *testing.B) { @@ -89,14 +89,14 @@ func ExampleConnectiveListing() { Seed(11) fmt.Println(ConnectiveListing()) - // Output: firstly + // Output: in summation } func ExampleFaker_ConnectiveListing() { f := New(11) fmt.Println(f.ConnectiveListing()) - // Output: firstly + // Output: in summation } func BenchmarkConnectiveListing(b *testing.B) { @@ -109,14 +109,14 @@ func ExampleConnectiveCasual() { Seed(11) fmt.Println(ConnectiveCasual()) - // Output: an outcome of + // Output: though } func ExampleFaker_ConnectiveCasual() { f := New(11) fmt.Println(f.ConnectiveCasual()) - // Output: an outcome of + // Output: though } func BenchmarkConnectiveCasual(b *testing.B) { @@ -129,14 +129,14 @@ func ExampleConnectiveExamplify() { Seed(11) fmt.Println(ConnectiveExamplify()) - // Output: then + // Output: unless } func ExampleFaker_ConnectiveExamplify() { f := New(11) fmt.Println(f.ConnectiveExamplify()) - // Output: then + // Output: unless } func BenchmarkConnectiveExamplify(b *testing.B) { diff --git a/word_general.go b/word_general.go index d2a84f92..548ef125 100644 --- a/word_general.go +++ b/word_general.go @@ -1,24 +1,23 @@ package gofakeit import ( - "math/rand" "strings" - "github.com/brianvoe/gofakeit/v6/data" + "github.com/brianvoe/gofakeit/v7/data" ) // Word will generate a random word -func Word() string { return word(globalFaker.Rand) } +func Word() string { return word(GlobalFaker) } // Word will generate a random word -func (f *Faker) Word() string { return word(f.Rand) } +func (f *Faker) Word() string { return word(f) } -func word(r *rand.Rand) string { - word := getRandValue(r, []string{"word", randomString(r, data.WordKeys)}) +func word(f *Faker) string { + word := getRandValue(f, []string{"word", randomString(f, data.WordKeys)}) // Word may return a couple of words, if so we will split on space and return a random word if strings.Contains(word, " ") { - return randomString(r, strings.Split(word, " ")) + return randomString(f, strings.Split(word, " ")) } return word @@ -31,8 +30,8 @@ func addWordGeneralLookup() { Description: "Basic unit of language representing a concept or thing, consisting of letters and having meaning", Example: "man", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return word(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return word(f), nil }, }) } diff --git a/word_general_test.go b/word_general_test.go index 455468e8..9ba20411 100644 --- a/word_general_test.go +++ b/word_general_test.go @@ -9,14 +9,14 @@ func ExampleWord() { Seed(11) fmt.Println(Word()) - // Output: none + // Output: bathe } func ExampleFaker_Word() { f := New(11) fmt.Println(f.Word()) - // Output: none + // Output: bathe } func BenchmarkWord(b *testing.B) { diff --git a/word_grammar.go b/word_grammar.go index 77722d76..b3690bee 100644 --- a/word_grammar.go +++ b/word_grammar.go @@ -1,19 +1,18 @@ package gofakeit import ( - "math/rand" "unicode" ) // SentenceSimple will generate a random simple sentence -func SentenceSimple() string { return sentenceSimple(globalFaker.Rand) } +func SentenceSimple() string { return sentenceSimple(GlobalFaker) } // SentenceSimple will generate a random simple sentence -func (f *Faker) SentenceSimple() string { return sentenceSimple(f.Rand) } +func (f *Faker) SentenceSimple() string { return sentenceSimple(f) } -func sentenceSimple(r *rand.Rand) string { +func sentenceSimple(f *Faker) string { // simple sentence consists of a noun phrase and a verb phrase - str := phraseNoun(r) + " " + phraseVerb(r) + "." + str := phraseNoun(f) + " " + phraseVerb(f) + "." // capitalize the first letter strR := []rune(str) @@ -28,8 +27,8 @@ func addWordGrammerLookup() { Description: "Group of words that expresses a complete thought", Example: "A tribe fly the lemony kitchen.", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return sentenceSimple(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return sentenceSimple(f), nil }, }) } diff --git a/word_grammar_test.go b/word_grammar_test.go index 1ae9fa53..86775e86 100644 --- a/word_grammar_test.go +++ b/word_grammar_test.go @@ -9,14 +9,14 @@ func ExampleSentenceSimple() { Seed(11) fmt.Println(SentenceSimple()) - // Output: The purple tribe indeed swiftly laugh. + // Output: A fear selfishly cook a tough doctor hardly innocently to realistic project utterly ingeniously. } func ExampleFaker_SentenceSimple() { f := New(11) fmt.Println(f.SentenceSimple()) - // Output: The purple tribe indeed swiftly laugh. + // Output: A fear selfishly cook a tough doctor hardly innocently to realistic project utterly ingeniously. } func BenchmarkSentenceSimple(b *testing.B) { diff --git a/word_misc.go b/word_misc.go index 59d47e59..58c8799b 100644 --- a/word_misc.go +++ b/word_misc.go @@ -1,14 +1,12 @@ package gofakeit -import "math/rand" - // Interjection will generate a random word expressing emotion -func Interjection() string { return interjection(globalFaker.Rand) } +func Interjection() string { return interjection(GlobalFaker) } // Interjection will generate a random word expressing emotion -func (f *Faker) Interjection() string { return interjection(f.Rand) } +func (f *Faker) Interjection() string { return interjection(f) } -func interjection(r *rand.Rand) string { return getRandValue(r, []string{"word", "interjection"}) } +func interjection(f *Faker) string { return getRandValue(f, []string{"word", "interjection"}) } func addWordMiscLookup() { AddFuncLookup("interjection", Info{ @@ -17,8 +15,8 @@ func addWordMiscLookup() { Description: "Word expressing emotion", Example: "wow", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return interjection(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return interjection(f), nil }, }) } diff --git a/word_misc_test.go b/word_misc_test.go index 48302f25..95d24cb1 100644 --- a/word_misc_test.go +++ b/word_misc_test.go @@ -9,14 +9,14 @@ func ExampleInterjection() { Seed(11) fmt.Println(Interjection()) - // Output: wow + // Output: alas } func ExampleFaker_Interjection() { f := New(11) fmt.Println(f.Interjection()) - // Output: wow + // Output: alas } func BenchmarkInterjection(b *testing.B) { diff --git a/word_noun.go b/word_noun.go index fbf9e806..36e0331a 100644 --- a/word_noun.go +++ b/word_noun.go @@ -1,14 +1,12 @@ package gofakeit -import "math/rand" - // Noun will generate a random noun -func Noun() string { return noun(globalFaker.Rand) } +func Noun() string { return noun(GlobalFaker) } // Noun will generate a random noun -func (f *Faker) Noun() string { return noun(f.Rand) } +func (f *Faker) Noun() string { return noun(f) } -func noun(r *rand.Rand) string { +func noun(f *Faker) string { var nounType = map[int]string{ 0: "noun_common", 1: "noun_concrete", @@ -19,105 +17,105 @@ func noun(r *rand.Rand) string { 6: "noun_countable", 7: "noun_uncountable", } - return getRandValue(r, []string{"word", nounType[number(r, 0, 7)]}) + return getRandValue(f, []string{"word", nounType[number(f, 0, 7)]}) } // NounCommon will generate a random common noun -func NounCommon() string { return nounCommon(globalFaker.Rand) } +func NounCommon() string { return nounCommon(GlobalFaker) } // NounCommon will generate a random common noun -func (f *Faker) NounCommon() string { return nounCommon(f.Rand) } +func (f *Faker) NounCommon() string { return nounCommon(f) } -func nounCommon(r *rand.Rand) string { return getRandValue(r, []string{"word", "noun_common"}) } +func nounCommon(f *Faker) string { return getRandValue(f, []string{"word", "noun_common"}) } // NounConcrete will generate a random concrete noun -func NounConcrete() string { return nounConcrete(globalFaker.Rand) } +func NounConcrete() string { return nounConcrete(GlobalFaker) } // NounConcrete will generate a random concrete noun -func (f *Faker) NounConcrete() string { return nounConcrete(f.Rand) } +func (f *Faker) NounConcrete() string { return nounConcrete(f) } -func nounConcrete(r *rand.Rand) string { return getRandValue(r, []string{"word", "noun_concrete"}) } +func nounConcrete(f *Faker) string { return getRandValue(f, []string{"word", "noun_concrete"}) } // NounAbstract will generate a random abstract noun -func NounAbstract() string { return nounAbstract(globalFaker.Rand) } +func NounAbstract() string { return nounAbstract(GlobalFaker) } // NounAbstract will generate a random abstract noun -func (f *Faker) NounAbstract() string { return nounAbstract(f.Rand) } +func (f *Faker) NounAbstract() string { return nounAbstract(f) } -func nounAbstract(r *rand.Rand) string { return getRandValue(r, []string{"word", "noun_abstract"}) } +func nounAbstract(f *Faker) string { return getRandValue(f, []string{"word", "noun_abstract"}) } // NounCollectivePeople will generate a random collective noun person -func NounCollectivePeople() string { return nounCollectivePeople(globalFaker.Rand) } +func NounCollectivePeople() string { return nounCollectivePeople(GlobalFaker) } // NounCollectivePeople will generate a random collective noun person -func (f *Faker) NounCollectivePeople() string { return nounCollectivePeople(f.Rand) } +func (f *Faker) NounCollectivePeople() string { return nounCollectivePeople(f) } -func nounCollectivePeople(r *rand.Rand) string { - return getRandValue(r, []string{"word", "noun_collective_people"}) +func nounCollectivePeople(f *Faker) string { + return getRandValue(f, []string{"word", "noun_collective_people"}) } // NounCollectiveAnimal will generate a random collective noun animal -func NounCollectiveAnimal() string { return nounCollectiveAnimal(globalFaker.Rand) } +func NounCollectiveAnimal() string { return nounCollectiveAnimal(GlobalFaker) } // NounCollectiveAnimal will generate a random collective noun animal -func (f *Faker) NounCollectiveAnimal() string { return nounCollectiveAnimal(f.Rand) } +func (f *Faker) NounCollectiveAnimal() string { return nounCollectiveAnimal(f) } -func nounCollectiveAnimal(r *rand.Rand) string { - return getRandValue(r, []string{"word", "noun_collective_animal"}) +func nounCollectiveAnimal(f *Faker) string { + return getRandValue(f, []string{"word", "noun_collective_animal"}) } // NounCollectiveThing will generate a random collective noun thing -func NounCollectiveThing() string { return nounCollectiveThing(globalFaker.Rand) } +func NounCollectiveThing() string { return nounCollectiveThing(GlobalFaker) } // NounCollectiveThing will generate a random collective noun thing -func (f *Faker) NounCollectiveThing() string { return nounCollectiveThing(f.Rand) } +func (f *Faker) NounCollectiveThing() string { return nounCollectiveThing(f) } -func nounCollectiveThing(r *rand.Rand) string { - return getRandValue(r, []string{"word", "noun_collective_thing"}) +func nounCollectiveThing(f *Faker) string { + return getRandValue(f, []string{"word", "noun_collective_thing"}) } // NounCountable will generate a random countable noun -func NounCountable() string { return nounCountable(globalFaker.Rand) } +func NounCountable() string { return nounCountable(GlobalFaker) } // NounCountable will generate a random countable noun -func (f *Faker) NounCountable() string { return nounCountable(f.Rand) } +func (f *Faker) NounCountable() string { return nounCountable(f) } -func nounCountable(r *rand.Rand) string { return getRandValue(r, []string{"word", "noun_countable"}) } +func nounCountable(f *Faker) string { return getRandValue(f, []string{"word", "noun_countable"}) } // NounUncountable will generate a random uncountable noun -func NounUncountable() string { return nounUncountable(globalFaker.Rand) } +func NounUncountable() string { return nounUncountable(GlobalFaker) } // NounUncountable will generate a random uncountable noun -func (f *Faker) NounUncountable() string { return nounUncountable(f.Rand) } +func (f *Faker) NounUncountable() string { return nounUncountable(f) } -func nounUncountable(r *rand.Rand) string { - return getRandValue(r, []string{"word", "noun_uncountable"}) +func nounUncountable(f *Faker) string { + return getRandValue(f, []string{"word", "noun_uncountable"}) } // NounProper will generate a random proper noun -func NounProper() string { return nounProper(globalFaker.Rand) } +func NounProper() string { return nounProper(GlobalFaker) } // NounProper will generate a random proper noun -func (f *Faker) NounProper() string { return nounProper(f.Rand) } +func (f *Faker) NounProper() string { return nounProper(f) } -func nounProper(r *rand.Rand) string { - switch randInt := randIntRange(r, 1, 3); randInt { +func nounProper(f *Faker) string { + switch randInt := randIntRange(f, 1, 3); randInt { case 1: - return getRandValue(r, []string{"celebrity", "actor"}) + return getRandValue(f, []string{"celebrity", "actor"}) case 2: - return generate(r, getRandValue(r, []string{"address", "city"})) + return generate(f, getRandValue(f, []string{"address", "city"})) } - return getRandValue(r, []string{"person", "first"}) + return getRandValue(f, []string{"person", "first"}) } // NounDeterminer will generate a random noun determiner -func NounDeterminer() string { return nounDeterminer(globalFaker.Rand) } +func NounDeterminer() string { return nounDeterminer(GlobalFaker) } // NounDeterminer will generate a random noun determiner -func (f *Faker) NounDeterminer() string { return nounDeterminer(f.Rand) } +func (f *Faker) NounDeterminer() string { return nounDeterminer(f) } -func nounDeterminer(r *rand.Rand) string { return getRandValue(r, []string{"word", "noun_determiner"}) } +func nounDeterminer(f *Faker) string { return getRandValue(f, []string{"word", "noun_determiner"}) } func addWordNounLookup() { AddFuncLookup("noun", Info{ @@ -126,8 +124,8 @@ func addWordNounLookup() { Description: "Person, place, thing, or idea, named or referred to in a sentence", Example: "aunt", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return noun(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return noun(f), nil }, }) @@ -137,8 +135,8 @@ func addWordNounLookup() { Description: "General name for people, places, or things, not specific or unique", Example: "part", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return nounCommon(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return nounCommon(f), nil }, }) @@ -148,8 +146,8 @@ func addWordNounLookup() { Description: "Names for physical entities experienced through senses like sight, touch, smell, or taste", Example: "snowman", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return nounConcrete(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return nounConcrete(f), nil }, }) @@ -159,8 +157,8 @@ func addWordNounLookup() { Description: "Ideas, qualities, or states that cannot be perceived with the five senses", Example: "confusion", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return nounAbstract(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return nounAbstract(f), nil }, }) @@ -170,8 +168,8 @@ func addWordNounLookup() { Description: "Group of people or things regarded as a unit", Example: "body", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return nounCollectivePeople(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return nounCollectivePeople(f), nil }, }) @@ -181,8 +179,8 @@ func addWordNounLookup() { Description: "Group of animals, like a 'pack' of wolves or a 'flock' of birds", Example: "party", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return nounCollectiveAnimal(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return nounCollectiveAnimal(f), nil }, }) @@ -192,8 +190,8 @@ func addWordNounLookup() { Description: "Group of objects or items, such as a 'bundle' of sticks or a 'cluster' of grapes", Example: "hand", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return nounCollectiveThing(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return nounCollectiveThing(f), nil }, }) @@ -203,8 +201,8 @@ func addWordNounLookup() { Description: "Items that can be counted individually", Example: "neck", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return nounCountable(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return nounCountable(f), nil }, }) @@ -214,8 +212,8 @@ func addWordNounLookup() { Description: "Items that can't be counted individually", Example: "seafood", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return nounUncountable(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return nounUncountable(f), nil }, }) @@ -225,8 +223,8 @@ func addWordNounLookup() { Description: "Specific name for a particular person, place, or organization", Example: "John", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return nounProper(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return nounProper(f), nil }, }) @@ -236,8 +234,8 @@ func addWordNounLookup() { Description: "Word that introduces a noun and identifies it as a noun", Example: "your", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return nounDeterminer(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return nounDeterminer(f), nil }, }) } diff --git a/word_noun_test.go b/word_noun_test.go index 29d4e69b..01e0d232 100644 --- a/word_noun_test.go +++ b/word_noun_test.go @@ -9,14 +9,14 @@ func ExampleNoun() { Seed(11) fmt.Println(Noun()) - // Output: aunt + // Output: nest } func ExampleFaker_Noun() { f := New(11) fmt.Println(f.Noun()) - // Output: aunt + // Output: nest } func BenchmarkNoun(b *testing.B) { @@ -29,14 +29,14 @@ func ExampleNounCommon() { Seed(11) fmt.Println(NounCommon()) - // Output: part + // Output: group } func ExampleFaker_NounCommon() { f := New(11) fmt.Println(f.NounCommon()) - // Output: part + // Output: group } func BenchmarkNounCommon(b *testing.B) { @@ -49,14 +49,14 @@ func ExampleNounConcrete() { Seed(11) fmt.Println(NounConcrete()) - // Output: snowman + // Output: theater } func ExampleFaker_NounConcrete() { f := New(11) fmt.Println(f.NounConcrete()) - // Output: snowman + // Output: theater } func BenchmarkNounConcrete(b *testing.B) { @@ -69,14 +69,14 @@ func ExampleNounAbstract() { Seed(11) fmt.Println(NounAbstract()) - // Output: confusion + // Output: speed } func ExampleFaker_NounAbstract() { f := New(11) fmt.Println(f.NounAbstract()) - // Output: confusion + // Output: speed } func BenchmarkNounAbstract(b *testing.B) { @@ -89,14 +89,14 @@ func ExampleNounCollectivePeople() { Seed(11) fmt.Println(NounCollectivePeople()) - // Output: body + // Output: posse } func ExampleFaker_NounCollectivePeople() { f := New(11) fmt.Println(f.NounCollectivePeople()) - // Output: body + // Output: posse } func BenchmarkNounCollectivePeople(b *testing.B) { @@ -109,14 +109,14 @@ func ExampleNounCollectiveAnimal() { Seed(11) fmt.Println(NounCollectiveAnimal()) - // Output: party + // Output: leap } func ExampleFaker_NounCollectiveAnimal() { f := New(11) fmt.Println(f.NounCollectiveAnimal()) - // Output: party + // Output: leap } func BenchmarkNounCollectiveAnimal(b *testing.B) { @@ -129,14 +129,14 @@ func ExampleNounCollectiveThing() { Seed(11) fmt.Println(NounCollectiveThing()) - // Output: hand + // Output: hail } func ExampleFaker_NounCollectiveThing() { f := New(11) fmt.Println(f.NounCollectiveThing()) - // Output: hand + // Output: hail } func BenchmarkNounCollectiveThing(b *testing.B) { @@ -149,14 +149,14 @@ func ExampleNounCountable() { Seed(11) fmt.Println(NounCountable()) - // Output: neck + // Output: smile } func ExampleFaker_NounCountable() { f := New(11) fmt.Println(f.NounCountable()) - // Output: neck + // Output: smile } func BenchmarkNounCountable(b *testing.B) { @@ -169,14 +169,14 @@ func ExampleNounUncountable() { Seed(11) fmt.Println(NounUncountable()) - // Output: seafood + // Output: usage } func ExampleFaker_NounUncountable() { f := New(11) fmt.Println(f.NounUncountable()) - // Output: seafood + // Output: usage } func BenchmarkNounUncountable(b *testing.B) { @@ -189,14 +189,14 @@ func ExampleNounProper() { Seed(11) fmt.Println(NounProper()) - // Output: Marcel + // Output: Russ } func ExampleFaker_NounProper() { f := New(11) fmt.Println(f.NounProper()) - // Output: Marcel + // Output: Russ } func TestNounProper(t *testing.T) { @@ -218,14 +218,14 @@ func ExampleNounDeterminer() { Seed(11) fmt.Println(NounDeterminer()) - // Output: an + // Output: every } func ExampleFaker_NounDeterminer() { f := New(11) fmt.Println(f.NounDeterminer()) - // Output: an + // Output: every } func TestNounDeterminer(t *testing.T) { diff --git a/word_phrase.go b/word_phrase.go index 1432f173..68ff015a 100644 --- a/word_phrase.go +++ b/word_phrase.go @@ -1,36 +1,35 @@ package gofakeit import ( - "math/rand" "strings" ) // Phrase will return a random phrase -func Phrase() string { return phrase(globalFaker.Rand) } +func Phrase() string { return phrase(GlobalFaker) } // Phrase will return a random phrase -func (f *Faker) Phrase() string { return phrase(f.Rand) } +func (f *Faker) Phrase() string { return phrase(f) } -func phrase(r *rand.Rand) string { return getRandValue(r, []string{"sentence", "phrase"}) } +func phrase(f *Faker) string { return getRandValue(f, []string{"sentence", "phrase"}) } // PhraseNoun will return a random noun phrase -func PhraseNoun() string { return phraseNoun(globalFaker.Rand) } +func PhraseNoun() string { return phraseNoun(GlobalFaker) } // PhraseNoun will return a random noun phrase -func (f *Faker) PhraseNoun() string { return phraseNoun(f.Rand) } +func (f *Faker) PhraseNoun() string { return phraseNoun(f) } -func phraseNoun(r *rand.Rand) string { +func phraseNoun(f *Faker) string { str := "" // You may also want to add an adjective to describe the noun - if boolFunc(r) { - str = adjectiveDescriptive(r) + " " + noun(r) + if boolFunc(f) { + str = adjectiveDescriptive(f) + " " + noun(f) } else { - str = noun(r) + str = noun(f) } // Add determiner from weighted list - prob, _ := weighted(r, []any{1, 2, 3}, []float32{2, 1.5, 1}) + prob, _ := weighted(f, []any{1, 2, 3}, []float32{2, 1.5, 1}) if prob == 1 { str = getArticle(str) + " " + str } else if prob == 2 { @@ -41,40 +40,40 @@ func phraseNoun(r *rand.Rand) string { } // PhraseVerb will return a random preposition phrase -func PhraseVerb() string { return phraseVerb(globalFaker.Rand) } +func PhraseVerb() string { return phraseVerb(GlobalFaker) } // PhraseVerb will return a random preposition phrase -func (f *Faker) PhraseVerb() string { return phraseVerb(f.Rand) } +func (f *Faker) PhraseVerb() string { return phraseVerb(f) } -func phraseVerb(r *rand.Rand) string { +func phraseVerb(f *Faker) string { // Put together a string builder sb := []string{} // You may have an adverb phrase - if boolFunc(r) { - sb = append(sb, phraseAdverb(r)) + if boolFunc(f) { + sb = append(sb, phraseAdverb(f)) } // Lets add the primary verb - sb = append(sb, verbAction(r)) + sb = append(sb, verbAction(f)) // You may have a noun phrase - if boolFunc(r) { - sb = append(sb, phraseNoun(r)) + if boolFunc(f) { + sb = append(sb, phraseNoun(f)) } // You may have an adverb phrase - if boolFunc(r) { - sb = append(sb, phraseAdverb(r)) + if boolFunc(f) { + sb = append(sb, phraseAdverb(f)) // You may also have a preposition phrase - if boolFunc(r) { - sb = append(sb, phrasePreposition(r)) + if boolFunc(f) { + sb = append(sb, phrasePreposition(f)) } // You may also hae an adverb phrase - if boolFunc(r) { - sb = append(sb, phraseAdverb(r)) + if boolFunc(f) { + sb = append(sb, phraseAdverb(f)) } } @@ -82,27 +81,27 @@ func phraseVerb(r *rand.Rand) string { } // PhraseAdverb will return a random adverb phrase -func PhraseAdverb() string { return phraseAdverb(globalFaker.Rand) } +func PhraseAdverb() string { return phraseAdverb(GlobalFaker) } // PhraseAdverb will return a random adverb phrase -func (f *Faker) PhraseAdverb() string { return phraseAdverb(f.Rand) } +func (f *Faker) PhraseAdverb() string { return phraseAdverb(f) } -func phraseAdverb(r *rand.Rand) string { - if boolFunc(r) { - return adverbDegree(r) + " " + adverbManner(r) +func phraseAdverb(f *Faker) string { + if boolFunc(f) { + return adverbDegree(f) + " " + adverbManner(f) } - return adverbManner(r) + return adverbManner(f) } // PhrasePreposition will return a random preposition phrase -func PhrasePreposition() string { return phrasePreposition(globalFaker.Rand) } +func PhrasePreposition() string { return phrasePreposition(GlobalFaker) } // PhrasePreposition will return a random preposition phrase -func (f *Faker) PhrasePreposition() string { return phrasePreposition(f.Rand) } +func (f *Faker) PhrasePreposition() string { return phrasePreposition(f) } -func phrasePreposition(r *rand.Rand) string { - return prepositionSimple(r) + " " + phraseNoun(r) +func phrasePreposition(f *Faker) string { + return prepositionSimple(f) + " " + phraseNoun(f) } func addWordPhraseLookup() { @@ -112,8 +111,8 @@ func addWordPhraseLookup() { Description: "A small group of words standing together", Example: "time will tell", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return phrase(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return phrase(f), nil }, }) @@ -123,8 +122,8 @@ func addWordPhraseLookup() { Description: "Phrase with a noun as its head, functions within sentence like a noun", Example: "a tribe", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return phraseNoun(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return phraseNoun(f), nil }, }) @@ -134,8 +133,8 @@ func addWordPhraseLookup() { Description: "Phrase that Consists of a verb and its modifiers, expressing an action or state", Example: "a tribe", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return phraseVerb(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return phraseVerb(f), nil }, }) @@ -145,8 +144,8 @@ func addWordPhraseLookup() { Description: "Phrase that modifies a verb, adjective, or another adverb, providing additional information.", Example: "fully gladly", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return phraseAdverb(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return phraseAdverb(f), nil }, }) @@ -156,8 +155,8 @@ func addWordPhraseLookup() { Description: "Phrase starting with a preposition, showing relation between elements in a sentence.", Example: "out the black thing", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return phrasePreposition(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return phrasePreposition(f), nil }, }) } diff --git a/word_phrase_test.go b/word_phrase_test.go index 462b1fb6..b478316c 100644 --- a/word_phrase_test.go +++ b/word_phrase_test.go @@ -9,14 +9,14 @@ func ExamplePhrase() { Seed(11) fmt.Println(Phrase()) - // Output: horses for courses + // Output: how many siblings do you have } func ExampleFaker_Phrase() { f := New(11) fmt.Println(f.Phrase()) - // Output: horses for courses + // Output: how many siblings do you have } func BenchmarkPhrase(b *testing.B) { @@ -29,14 +29,14 @@ func ExamplePhraseNoun() { Seed(11) fmt.Println(PhraseNoun()) - // Output: the purple tribe + // Output: a fear } func ExampleFaker_PhraseNoun() { f := New(11) fmt.Println(f.PhraseNoun()) - // Output: the purple tribe + // Output: a fear } func BenchmarkPhraseNoun(b *testing.B) { @@ -49,14 +49,14 @@ func ExamplePhraseVerb() { Seed(11) fmt.Println(PhraseVerb()) - // Output: gladly dream indeed swiftly till a problem poorly + // Output: bathe the jittery trip totally brightly under a troubling part scarcely unexpectedly } func ExampleFaker_PhraseVerb() { f := New(11) fmt.Println(f.PhraseVerb()) - // Output: gladly dream indeed swiftly till a problem poorly + // Output: bathe the jittery trip totally brightly under a troubling part scarcely unexpectedly } func BenchmarkPhraseVerb(b *testing.B) { @@ -69,14 +69,14 @@ func ExamplePhraseAdverb() { Seed(11) fmt.Println(PhraseAdverb()) - // Output: fully gladly + // Output: successfully } func ExampleFaker_PhraseAdverb() { f := New(11) fmt.Println(f.PhraseAdverb()) - // Output: fully gladly + // Output: successfully } func BenchmarkPhraseAdverb(b *testing.B) { @@ -89,14 +89,14 @@ func ExamplePhrasePreposition() { Seed(11) fmt.Println(PhrasePreposition()) - // Output: out the tribe + // Output: with an archipelago } func ExampleFaker_PhrasePreposition() { f := New(11) fmt.Println(f.PhrasePreposition()) - // Output: out the tribe + // Output: with an archipelago } func BenchmarkPhrasePreposition(b *testing.B) { diff --git a/word_preposition.go b/word_preposition.go index bf1d2f74..17902dc6 100644 --- a/word_preposition.go +++ b/word_preposition.go @@ -1,50 +1,48 @@ package gofakeit -import "math/rand" - // Preposition will generate a random preposition -func Preposition() string { return preposition(globalFaker.Rand) } +func Preposition() string { return preposition(GlobalFaker) } // Preposition will generate a random preposition -func (f *Faker) Preposition() string { return preposition(f.Rand) } +func (f *Faker) Preposition() string { return preposition(f) } -func preposition(r *rand.Rand) string { +func preposition(f *Faker) string { var prepType = map[int]string{ 0: "preposition_simple", 1: "preposition_double", 2: "preposition_compound", } - return getRandValue(r, []string{"word", prepType[number(r, 0, 2)]}) + return getRandValue(f, []string{"word", prepType[number(f, 0, 2)]}) } // PrepositionSimple will generate a random simple preposition -func PrepositionSimple() string { return prepositionSimple(globalFaker.Rand) } +func PrepositionSimple() string { return prepositionSimple(GlobalFaker) } // PrepositionSimple will generate a random simple preposition -func (f *Faker) PrepositionSimple() string { return prepositionSimple(f.Rand) } +func (f *Faker) PrepositionSimple() string { return prepositionSimple(f) } -func prepositionSimple(r *rand.Rand) string { - return getRandValue(r, []string{"word", "preposition_simple"}) +func prepositionSimple(f *Faker) string { + return getRandValue(f, []string{"word", "preposition_simple"}) } // PrepositionDouble will generate a random double preposition -func PrepositionDouble() string { return prepositionDouble(globalFaker.Rand) } +func PrepositionDouble() string { return prepositionDouble(GlobalFaker) } // PrepositionDouble will generate a random double preposition -func (f *Faker) PrepositionDouble() string { return prepositionDouble(f.Rand) } +func (f *Faker) PrepositionDouble() string { return prepositionDouble(f) } -func prepositionDouble(r *rand.Rand) string { - return getRandValue(r, []string{"word", "preposition_double"}) +func prepositionDouble(f *Faker) string { + return getRandValue(f, []string{"word", "preposition_double"}) } // PrepositionCompound will generate a random compound preposition -func PrepositionCompound() string { return prepositionCompound(globalFaker.Rand) } +func PrepositionCompound() string { return prepositionCompound(GlobalFaker) } // PrepositionCompound will generate a random compound preposition -func (f *Faker) PrepositionCompound() string { return prepositionCompound(f.Rand) } +func (f *Faker) PrepositionCompound() string { return prepositionCompound(f) } -func prepositionCompound(r *rand.Rand) string { - return getRandValue(r, []string{"word", "preposition_compound"}) +func prepositionCompound(f *Faker) string { + return getRandValue(f, []string{"word", "preposition_compound"}) } func addWordPrepositionLookup() { @@ -54,8 +52,8 @@ func addWordPrepositionLookup() { Description: "Words used to express the relationship of a noun or pronoun to other words in a sentence", Example: "other than", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return preposition(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return preposition(f), nil }, }) @@ -65,8 +63,8 @@ func addWordPrepositionLookup() { Description: "Single-word preposition showing relationships between 2 parts of a sentence", Example: "out", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return prepositionSimple(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return prepositionSimple(f), nil }, }) @@ -76,8 +74,8 @@ func addWordPrepositionLookup() { Description: "Two-word combination preposition, indicating a complex relation", Example: "before", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return prepositionDouble(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return prepositionDouble(f), nil }, }) @@ -87,8 +85,8 @@ func addWordPrepositionLookup() { Description: "Preposition that can be formed by combining two or more prepositions", Example: "according to", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return prepositionCompound(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return prepositionCompound(f), nil }, }) } diff --git a/word_preposition_test.go b/word_preposition_test.go index a0199e53..31b7549f 100644 --- a/word_preposition_test.go +++ b/word_preposition_test.go @@ -9,14 +9,14 @@ func ExamplePreposition() { Seed(11) fmt.Println(Preposition()) - // Output: other than + // Output: instead of } func ExampleFaker_Preposition() { f := New(11) fmt.Println(f.Preposition()) - // Output: other than + // Output: instead of } func BenchmarkPreposition(b *testing.B) { @@ -29,14 +29,14 @@ func ExamplePrepositionSimple() { Seed(11) fmt.Println(PrepositionSimple()) - // Output: out + // Output: with } func ExampleFaker_PrepositionSimple() { f := New(11) fmt.Println(f.PrepositionSimple()) - // Output: out + // Output: with } func BenchmarkPrepositionSimple(b *testing.B) { @@ -49,14 +49,14 @@ func ExamplePrepositionDouble() { Seed(11) fmt.Println(PrepositionDouble()) - // Output: before + // Output: next to } func ExampleFaker_PrepositionDouble() { f := New(11) fmt.Println(f.PrepositionDouble()) - // Output: before + // Output: next to } func BenchmarkPrepositionDouble(b *testing.B) { @@ -69,14 +69,14 @@ func ExamplePrepositionCompound() { Seed(11) fmt.Println(PrepositionCompound()) - // Output: according to + // Output: other than } func ExampleFaker_PrepositionCompound() { f := New(11) fmt.Println(f.PrepositionCompound()) - // Output: according to + // Output: other than } func BenchmarkPrepositionCompound(b *testing.B) { diff --git a/word_pronoun.go b/word_pronoun.go index 00c53310..f511f7d7 100644 --- a/word_pronoun.go +++ b/word_pronoun.go @@ -1,14 +1,12 @@ package gofakeit -import "math/rand" - // Pronoun will generate a random pronoun -func Pronoun() string { return pronoun(globalFaker.Rand) } +func Pronoun() string { return pronoun(GlobalFaker) } // Pronoun will generate a random pronoun -func (f *Faker) Pronoun() string { return pronoun(f.Rand) } +func (f *Faker) Pronoun() string { return pronoun(f) } -func pronoun(r *rand.Rand) string { +func pronoun(f *Faker) string { var pronounType = map[int]string{ 0: "pronoun_personal", 1: "pronoun_object", @@ -19,87 +17,87 @@ func pronoun(r *rand.Rand) string { 6: "pronoun_interrogative", 7: "pronoun_relative", } - return getRandValue(r, []string{"word", pronounType[number(r, 0, 7)]}) + return getRandValue(f, []string{"word", pronounType[number(f, 0, 7)]}) } // PronounPersonal will generate a random personal pronoun -func PronounPersonal() string { return pronounPersonal(globalFaker.Rand) } +func PronounPersonal() string { return pronounPersonal(GlobalFaker) } // PronounPersonal will generate a random personal pronoun -func (f *Faker) PronounPersonal() string { return pronounPersonal(f.Rand) } +func (f *Faker) PronounPersonal() string { return pronounPersonal(f) } -func pronounPersonal(r *rand.Rand) string { - return getRandValue(r, []string{"word", "pronoun_personal"}) +func pronounPersonal(f *Faker) string { + return getRandValue(f, []string{"word", "pronoun_personal"}) } // PronounObject will generate a random object pronoun -func PronounObject() string { return pronounObject(globalFaker.Rand) } +func PronounObject() string { return pronounObject(GlobalFaker) } // PronounObject will generate a random object pronoun -func (f *Faker) PronounObject() string { return pronounObject(f.Rand) } +func (f *Faker) PronounObject() string { return pronounObject(f) } -func pronounObject(r *rand.Rand) string { - return getRandValue(r, []string{"word", "pronoun_object"}) +func pronounObject(f *Faker) string { + return getRandValue(f, []string{"word", "pronoun_object"}) } // PronounPossessive will generate a random possessive pronoun -func PronounPossessive() string { return pronounPossessive(globalFaker.Rand) } +func PronounPossessive() string { return pronounPossessive(GlobalFaker) } // PronounPossessive will generate a random possessive pronoun -func (f *Faker) PronounPossessive() string { return pronounPossessive(f.Rand) } +func (f *Faker) PronounPossessive() string { return pronounPossessive(f) } -func pronounPossessive(r *rand.Rand) string { - return getRandValue(r, []string{"word", "pronoun_possessive"}) +func pronounPossessive(f *Faker) string { + return getRandValue(f, []string{"word", "pronoun_possessive"}) } // PronounReflective will generate a random reflective pronoun -func PronounReflective() string { return pronounReflective(globalFaker.Rand) } +func PronounReflective() string { return pronounReflective(GlobalFaker) } // PronounReflective will generate a random reflective pronoun -func (f *Faker) PronounReflective() string { return pronounReflective(f.Rand) } +func (f *Faker) PronounReflective() string { return pronounReflective(f) } -func pronounReflective(r *rand.Rand) string { - return getRandValue(r, []string{"word", "pronoun_reflective"}) +func pronounReflective(f *Faker) string { + return getRandValue(f, []string{"word", "pronoun_reflective"}) } // PronounIndefinite will generate a random indefinite pronoun -func PronounIndefinite() string { return pronounIndefinite(globalFaker.Rand) } +func PronounIndefinite() string { return pronounIndefinite(GlobalFaker) } // PronounIndefinite will generate a random indefinite pronoun -func (f *Faker) PronounIndefinite() string { return pronounIndefinite(f.Rand) } +func (f *Faker) PronounIndefinite() string { return pronounIndefinite(f) } -func pronounIndefinite(r *rand.Rand) string { - return getRandValue(r, []string{"word", "pronoun_indefinite"}) +func pronounIndefinite(f *Faker) string { + return getRandValue(f, []string{"word", "pronoun_indefinite"}) } // PronounDemonstrative will generate a random demonstrative pronoun -func PronounDemonstrative() string { return pronounDemonstrative(globalFaker.Rand) } +func PronounDemonstrative() string { return pronounDemonstrative(GlobalFaker) } // PronounDemonstrative will generate a random demonstrative pronoun -func (f *Faker) PronounDemonstrative() string { return pronounDemonstrative(f.Rand) } +func (f *Faker) PronounDemonstrative() string { return pronounDemonstrative(f) } -func pronounDemonstrative(r *rand.Rand) string { - return getRandValue(r, []string{"word", "pronoun_demonstrative"}) +func pronounDemonstrative(f *Faker) string { + return getRandValue(f, []string{"word", "pronoun_demonstrative"}) } // PronounInterrogative will generate a random interrogative pronoun -func PronounInterrogative() string { return pronounInterrogative(globalFaker.Rand) } +func PronounInterrogative() string { return pronounInterrogative(GlobalFaker) } // PronounInterrogative will generate a random interrogative pronoun -func (f *Faker) PronounInterrogative() string { return pronounInterrogative(f.Rand) } +func (f *Faker) PronounInterrogative() string { return pronounInterrogative(f) } -func pronounInterrogative(r *rand.Rand) string { - return getRandValue(r, []string{"word", "pronoun_interrogative"}) +func pronounInterrogative(f *Faker) string { + return getRandValue(f, []string{"word", "pronoun_interrogative"}) } // PronounRelative will generate a random relative pronoun -func PronounRelative() string { return pronounRelative(globalFaker.Rand) } +func PronounRelative() string { return pronounRelative(GlobalFaker) } // PronounRelative will generate a random relative pronoun -func (f *Faker) PronounRelative() string { return pronounRelative(f.Rand) } +func (f *Faker) PronounRelative() string { return pronounRelative(f) } -func pronounRelative(r *rand.Rand) string { - return getRandValue(r, []string{"word", "pronoun_relative"}) +func pronounRelative(f *Faker) string { + return getRandValue(f, []string{"word", "pronoun_relative"}) } func addWordPronounLookup() { @@ -109,8 +107,8 @@ func addWordPronounLookup() { Description: "Word used in place of a noun to avoid repetition", Example: "me", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return pronoun(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return pronoun(f), nil }, }) @@ -120,8 +118,8 @@ func addWordPronounLookup() { Description: "Pronoun referring to a specific persons or things", Example: "it", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return pronounPersonal(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return pronounPersonal(f), nil }, }) @@ -131,8 +129,8 @@ func addWordPronounLookup() { Description: "Pronoun used as the object of a verb or preposition", Example: "it", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return pronounObject(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return pronounObject(f), nil }, }) @@ -142,8 +140,8 @@ func addWordPronounLookup() { Description: "Pronoun indicating ownership or belonging", Example: "mine", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return pronounPossessive(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return pronounPossessive(f), nil }, }) @@ -153,8 +151,8 @@ func addWordPronounLookup() { Description: "Pronoun referring back to the subject of the sentence", Example: "myself", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return pronounReflective(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return pronounReflective(f), nil }, }) @@ -164,8 +162,8 @@ func addWordPronounLookup() { Description: "Pronoun that does not refer to a specific person or thing", Example: "few", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return pronounIndefinite(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return pronounIndefinite(f), nil }, }) @@ -175,8 +173,8 @@ func addWordPronounLookup() { Description: "Pronoun that points out specific people or things", Example: "this", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return pronounDemonstrative(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return pronounDemonstrative(f), nil }, }) @@ -186,8 +184,8 @@ func addWordPronounLookup() { Description: "Pronoun used to ask questions", Example: "what", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return pronounInterrogative(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return pronounInterrogative(f), nil }, }) @@ -197,8 +195,8 @@ func addWordPronounLookup() { Description: "Pronoun that introduces a clause, referring back to a noun or pronoun", Example: "as", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return pronounRelative(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return pronounRelative(f), nil }, }) } diff --git a/word_pronoun_test.go b/word_pronoun_test.go index bdff8ab4..7ce24e19 100644 --- a/word_pronoun_test.go +++ b/word_pronoun_test.go @@ -9,14 +9,14 @@ func ExamplePronoun() { Seed(11) fmt.Println(Pronoun()) - // Output: me + // Output: some } func ExampleFaker_Pronoun() { f := New(11) fmt.Println(f.Pronoun()) - // Output: me + // Output: some } func BenchmarkPronoun(b *testing.B) { @@ -29,14 +29,14 @@ func ExamplePronounPersonal() { Seed(11) fmt.Println(PronounPersonal()) - // Output: it + // Output: they } func ExampleFaker_PronounPersonal() { f := New(11) fmt.Println(f.PronounPersonal()) - // Output: it + // Output: they } func BenchmarkPronounPersonal(b *testing.B) { @@ -49,14 +49,14 @@ func ExamplePronounObject() { Seed(11) fmt.Println(PronounObject()) - // Output: it + // Output: them } func ExampleFaker_PronounObject() { f := New(11) fmt.Println(f.PronounObject()) - // Output: it + // Output: them } func BenchmarkPronounObject(b *testing.B) { @@ -69,14 +69,14 @@ func ExamplePronounPossessive() { Seed(11) fmt.Println(PronounPossessive()) - // Output: mine + // Output: theirs } func ExampleFaker_PronounPossessive() { f := New(11) fmt.Println(f.PronounPossessive()) - // Output: mine + // Output: theirs } func BenchmarkPronounPossessive(b *testing.B) { @@ -89,14 +89,14 @@ func ExamplePronounReflective() { Seed(11) fmt.Println(PronounReflective()) - // Output: myself + // Output: itself } func ExampleFaker_PronounReflective() { f := New(11) fmt.Println(f.PronounReflective()) - // Output: myself + // Output: itself } func BenchmarkPronounReflective(b *testing.B) { @@ -109,14 +109,14 @@ func ExamplePronounIndefinite() { Seed(11) fmt.Println(PronounIndefinite()) - // Output: few + // Output: somebody } func ExampleFaker_PronounIndefinite() { f := New(11) fmt.Println(f.PronounIndefinite()) - // Output: few + // Output: somebody } func BenchmarkPronounIndefinite(b *testing.B) { @@ -149,14 +149,14 @@ func ExamplePronounInterrogative() { Seed(11) fmt.Println(PronounInterrogative()) - // Output: what + // Output: how } func ExampleFaker_PronounInterrogative() { f := New(11) fmt.Println(f.PronounInterrogative()) - // Output: what + // Output: how } func BenchmarkPronounInterrogative(b *testing.B) { @@ -169,14 +169,14 @@ func ExamplePronounRelative() { Seed(11) fmt.Println(PronounRelative()) - // Output: as + // Output: whomever } func ExampleFaker_PronounRelative() { f := New(11) fmt.Println(f.PronounRelative()) - // Output: as + // Output: whomever } func BenchmarkPronounRelative(b *testing.B) { diff --git a/word_sentence.go b/word_sentence.go index de8d41e9..1cbc874e 100644 --- a/word_sentence.go +++ b/word_sentence.go @@ -3,7 +3,6 @@ package gofakeit import ( "bytes" "errors" - "math/rand" "strings" "unicode" ) @@ -17,34 +16,34 @@ type paragrapOptions struct { const bytesPerWordEstimation = 6 -type sentenceGenerator func(r *rand.Rand, wordCount int) string -type wordGenerator func(r *rand.Rand) string +type sentenceGenerator func(f *Faker, wordCount int) string +type wordGenerator func(f *Faker) string // Sentence will generate a random sentence -func Sentence(wordCount int) string { return sentence(globalFaker.Rand, wordCount) } +func Sentence(wordCount int) string { return sentence(GlobalFaker, wordCount) } // Sentence will generate a random sentence -func (f *Faker) Sentence(wordCount int) string { return sentence(f.Rand, wordCount) } +func (f *Faker) Sentence(wordCount int) string { return sentence(f, wordCount) } -func sentence(r *rand.Rand, wordCount int) string { - return sentenceGen(r, wordCount, word) +func sentence(f *Faker, wordCount int) string { + return sentenceGen(f, wordCount, word) } // Paragraph will generate a random paragraphGenerator func Paragraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { - return paragraph(globalFaker.Rand, paragraphCount, sentenceCount, wordCount, separator) + return paragraph(GlobalFaker, paragraphCount, sentenceCount, wordCount, separator) } // Paragraph will generate a random paragraphGenerator func (f *Faker) Paragraph(paragraphCount int, sentenceCount int, wordCount int, separator string) string { - return paragraph(f.Rand, paragraphCount, sentenceCount, wordCount, separator) + return paragraph(f, paragraphCount, sentenceCount, wordCount, separator) } -func paragraph(r *rand.Rand, paragraphCount int, sentenceCount int, wordCount int, separator string) string { - return paragraphGen(r, paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, sentence) +func paragraph(f *Faker, paragraphCount int, sentenceCount int, wordCount int, separator string) string { + return paragraphGen(f, paragrapOptions{paragraphCount, sentenceCount, wordCount, separator}, sentence) } -func sentenceGen(r *rand.Rand, wordCount int, word wordGenerator) string { +func sentenceGen(f *Faker, wordCount int, word wordGenerator) string { if wordCount <= 0 { return "" } @@ -54,7 +53,7 @@ func sentenceGen(r *rand.Rand, wordCount int, word wordGenerator) string { sentence.Grow(wordCount * bytesPerWordEstimation) for i := 0; i < wordCount; i++ { - word := word(r) + word := word(f) if i == 0 { runes := []rune(word) runes[0] = unicode.ToTitle(runes[0]) @@ -69,7 +68,7 @@ func sentenceGen(r *rand.Rand, wordCount int, word wordGenerator) string { return sentence.String() } -func paragraphGen(r *rand.Rand, opts paragrapOptions, sentecer sentenceGenerator) string { +func paragraphGen(f *Faker, opts paragrapOptions, sentecer sentenceGenerator) string { if opts.paragraphCount <= 0 || opts.sentenceCount <= 0 || opts.wordCount <= 0 { return "" } @@ -82,7 +81,7 @@ func paragraphGen(r *rand.Rand, opts paragrapOptions, sentecer sentenceGenerator for i := 0; i < opts.paragraphCount; i++ { for e := 0; e < opts.sentenceCount; e++ { - paragraphs.WriteString(sentecer(r, opts.wordCount)) + paragraphs.WriteString(sentecer(f, opts.wordCount)) if e < opts.sentenceCount-1 { paragraphs.WriteRune(wordSeparator) } @@ -98,26 +97,26 @@ func paragraphGen(r *rand.Rand, opts paragrapOptions, sentecer sentenceGenerator // Question will return a random question func Question() string { - return question(globalFaker.Rand) + return question(GlobalFaker) } // Question will return a random question func (f *Faker) Question() string { - return question(f.Rand) + return question(f) } -func question(r *rand.Rand) string { - return strings.Replace(hipsterSentence(r, number(r, 3, 10)), ".", "?", 1) +func question(f *Faker) string { + return strings.Replace(hipsterSentence(f, number(f, 3, 10)), ".", "?", 1) } // Quote will return a random quote from a random person -func Quote() string { return quote(globalFaker.Rand) } +func Quote() string { return quote(GlobalFaker) } // Quote will return a random quote from a random person -func (f *Faker) Quote() string { return quote(f.Rand) } +func (f *Faker) Quote() string { return quote(f) } -func quote(r *rand.Rand) string { - return `"` + hipsterSentence(r, number(r, 3, 10)) + `" - ` + firstName(r) + " " + lastName(r) +func quote(f *Faker) string { + return `"` + hipsterSentence(f, number(f, 3, 10)) + `" - ` + firstName(f) + " " + lastName(f) } func addWordSentenceLookup() { @@ -130,7 +129,7 @@ func addWordSentenceLookup() { Params: []Param{ {Field: "wordcount", Display: "Word Count", Type: "int", Default: "5", Description: "Number of words in a sentence"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { wordCount, err := info.GetInt(m, "wordcount") if err != nil { return nil, err @@ -139,7 +138,7 @@ func addWordSentenceLookup() { return nil, errors.New("invalid word count, must be greater than 0, less than 50") } - return sentence(r, wordCount), nil + return sentence(f, wordCount), nil }, }) @@ -155,7 +154,7 @@ func addWordSentenceLookup() { {Field: "wordcount", Display: "Word Count", Type: "int", Default: "5", Description: "Number of words in a sentence"}, {Field: "paragraphseparator", Display: "Paragraph Separator", Type: "string", Default: "
", Description: "String value to add between paragraphs"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { paragraphCount, err := info.GetInt(m, "paragraphcount") if err != nil { return nil, err @@ -185,7 +184,7 @@ func addWordSentenceLookup() { return nil, err } - return paragraph(r, paragraphCount, sentenceCount, wordCount, paragraphSeparator), nil + return paragraph(f, paragraphCount, sentenceCount, wordCount, paragraphSeparator), nil }, }) @@ -195,8 +194,8 @@ func addWordSentenceLookup() { Description: "Statement formulated to inquire or seek clarification", Example: "Roof chia echo?", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return question(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return question(f), nil }, }) @@ -206,8 +205,8 @@ func addWordSentenceLookup() { Description: "Direct repetition of someone else's words", Example: `"Roof chia echo." - Lura Lockman`, Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return quote(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return quote(f), nil }, }) } diff --git a/word_sentence_test.go b/word_sentence_test.go index b4824f8b..40d6edba 100644 --- a/word_sentence_test.go +++ b/word_sentence_test.go @@ -10,14 +10,14 @@ func ExampleSentence() { Seed(11) fmt.Println(Sentence(5)) - // Output: None how these keep trip. + // Output: Bathe regularly quiver these sprint. } func ExampleFaker_Sentence() { f := New(11) fmt.Println(f.Sentence(5)) - // Output: None how these keep trip. + // Output: Bathe regularly quiver these sprint. } func TestSentence(t *testing.T) { @@ -45,18 +45,18 @@ func ExampleParagraph() { Seed(11) fmt.Println(Paragraph(3, 5, 12, "\n")) - // Output: None how these keep trip Congolese choir computer still far unless army. Party riches theirs instead here mine whichever that those instance growth has. Ouch enough Swiss us since down he she aha us you to. Upon how this this furniture way no play towel that us to. Accordingly theirs purse enough so though election often until eek weekly yet. - // Oops until conclude his stay elsewhere such that galaxy clean that last. Each stack reluctantly theirs wisp aid firstly highly butter accordingly should already. Calm shake according fade neither kuban upon this he fortnightly occasionally bunch. On who elsewhere lastly hourly right there honesty we is how result. Out Shakespearean have whom yearly another packet are behind late lot finally. - // Time themselves goodness quizzical our therefore could fact cackle yourselves zebra for. Whose enormously all bowl out wandering secondly yellow another your hourly spit. Since tomorrow hers words little think will our by Polynesian write much. Of herself uptight these composer these any firstly stack you much terribly. Over pose place sprint it child is joyously that I whom mango. + // Output: Bathe regularly quiver these sprint fight something am elsewhere since previously was. That there a tennis occur why depend heels out can fire anyone. Sometimes that leap whom troop now scarcely since dance huh somebody constantly. Italian outfit certain weekly murder who cackle because her break write nobody. Could according whoa bevy we them summation to oxygen Greek how previously. + // A what answer handle daily ouch upon encourage that after his every. She wearily still he herself huge failure for yay sparse thoughtfully box. Anyway Jungian regularly world great daily recently whose Elizabethan outside to theirs. Block while French closely sit you to out fight bored yours those. Bale Parisian host which so today Ecuadorian hourly decidedly his everybody this. + // Play this little them on recently eager usually bunch daily whose somebody. Them few tonight dishonesty spell battery less patience whose inside hair your. Answer hand tonight these she team which today Einsteinian country yesterday for. Phew for now your him hourly infrequently lots drink absolutely when east. Conclude little annually hers nobody since troop it it whoever the park. } func ExampleFaker_Paragraph() { f := New(11) fmt.Println(f.Paragraph(3, 5, 12, "\n")) - // Output: None how these keep trip Congolese choir computer still far unless army. Party riches theirs instead here mine whichever that those instance growth has. Ouch enough Swiss us since down he she aha us you to. Upon how this this furniture way no play towel that us to. Accordingly theirs purse enough so though election often until eek weekly yet. - // Oops until conclude his stay elsewhere such that galaxy clean that last. Each stack reluctantly theirs wisp aid firstly highly butter accordingly should already. Calm shake according fade neither kuban upon this he fortnightly occasionally bunch. On who elsewhere lastly hourly right there honesty we is how result. Out Shakespearean have whom yearly another packet are behind late lot finally. - // Time themselves goodness quizzical our therefore could fact cackle yourselves zebra for. Whose enormously all bowl out wandering secondly yellow another your hourly spit. Since tomorrow hers words little think will our by Polynesian write much. Of herself uptight these composer these any firstly stack you much terribly. Over pose place sprint it child is joyously that I whom mango. + // Output: Bathe regularly quiver these sprint fight something am elsewhere since previously was. That there a tennis occur why depend heels out can fire anyone. Sometimes that leap whom troop now scarcely since dance huh somebody constantly. Italian outfit certain weekly murder who cackle because her break write nobody. Could according whoa bevy we them summation to oxygen Greek how previously. + // A what answer handle daily ouch upon encourage that after his every. She wearily still he herself huge failure for yay sparse thoughtfully box. Anyway Jungian regularly world great daily recently whose Elizabethan outside to theirs. Block while French closely sit you to out fight bored yours those. Bale Parisian host which so today Ecuadorian hourly decidedly his everybody this. + // Play this little them on recently eager usually bunch daily whose somebody. Them few tonight dishonesty spell battery less patience whose inside hair your. Answer hand tonight these she team which today Einsteinian country yesterday for. Phew for now your him hourly infrequently lots drink absolutely when east. Conclude little annually hers nobody since troop it it whoever the park. } func TestParagraph(t *testing.T) { @@ -85,14 +85,14 @@ func ExampleQuestion() { Seed(11) fmt.Println(Question()) - // Output: Roof chia echo pickled? + // Output: Everyday you probably haven't heard of them you probably haven't heard of them portland austin tattooed retro? } func ExampleFaker_Question() { f := New(11) fmt.Println(f.Question()) - // Output: Roof chia echo pickled? + // Output: Everyday you probably haven't heard of them you probably haven't heard of them portland austin tattooed retro? } func BenchmarkQuestion(b *testing.B) { @@ -105,14 +105,14 @@ func ExampleQuote() { Seed(11) fmt.Println(Quote()) - // Output: "Roof chia echo pickled." - Marques Jakubowski + // Output: "Everyday you probably haven't heard of them you probably haven't heard of them portland austin tattooed retro." - Vance Schroeder } func ExampleFaker_Quote() { f := New(11) fmt.Println(f.Quote()) - // Output: "Roof chia echo pickled." - Marques Jakubowski + // Output: "Everyday you probably haven't heard of them you probably haven't heard of them portland austin tattooed retro." - Vance Schroeder } func BenchmarkQuote(b *testing.B) { diff --git a/word_verb.go b/word_verb.go index 6a5db234..d268784b 100644 --- a/word_verb.go +++ b/word_verb.go @@ -1,63 +1,61 @@ package gofakeit -import "math/rand" - // Verb will generate a random verb -func Verb() string { return verb(globalFaker.Rand) } +func Verb() string { return verb(GlobalFaker) } // Verb will generate a random verb -func (f *Faker) Verb() string { return verb(f.Rand) } +func (f *Faker) Verb() string { return verb(f) } -func verb(r *rand.Rand) string { +func verb(f *Faker) string { var verbType = map[int]string{ 0: "verb_action", 1: "verb_linking", 2: "verb_helping", } - return getRandValue(r, []string{"word", verbType[number(r, 0, 2)]}) + return getRandValue(f, []string{"word", verbType[number(f, 0, 2)]}) } // VerbAction will generate a random action verb -func VerbAction() string { return verbAction(globalFaker.Rand) } +func VerbAction() string { return verbAction(GlobalFaker) } // VerbAction will generate a random action verb -func (f *Faker) VerbAction() string { return verbAction(f.Rand) } +func (f *Faker) VerbAction() string { return verbAction(f) } -func verbAction(r *rand.Rand) string { return getRandValue(r, []string{"word", "verb_action"}) } +func verbAction(f *Faker) string { return getRandValue(f, []string{"word", "verb_action"}) } // VerbTransitive will generate a random transitive verb -func VerbTransitive() string { return verbTransitive(globalFaker.Rand) } +func VerbTransitive() string { return verbTransitive(GlobalFaker) } // VerbTransitive will generate a random transitive verb -func (f *Faker) VerbTransitive() string { return verbTransitive(f.Rand) } +func (f *Faker) VerbTransitive() string { return verbTransitive(f) } -func verbTransitive(r *rand.Rand) string { return getRandValue(r, []string{"word", "verb_transitive"}) } +func verbTransitive(f *Faker) string { return getRandValue(f, []string{"word", "verb_transitive"}) } // VerbIntransitive will generate a random intransitive verb -func VerbIntransitive() string { return verbIntransitive(globalFaker.Rand) } +func VerbIntransitive() string { return verbIntransitive(GlobalFaker) } // VerbIntransitive will generate a random intransitive verb -func (f *Faker) VerbIntransitive() string { return verbIntransitive(f.Rand) } +func (f *Faker) VerbIntransitive() string { return verbIntransitive(f) } -func verbIntransitive(r *rand.Rand) string { - return getRandValue(r, []string{"word", "verb_intransitive"}) +func verbIntransitive(f *Faker) string { + return getRandValue(f, []string{"word", "verb_intransitive"}) } // VerbLinking will generate a random linking verb -func VerbLinking() string { return verbLinking(globalFaker.Rand) } +func VerbLinking() string { return verbLinking(GlobalFaker) } // VerbLinking will generate a random linking verb -func (f *Faker) VerbLinking() string { return verbLinking(f.Rand) } +func (f *Faker) VerbLinking() string { return verbLinking(f) } -func verbLinking(r *rand.Rand) string { return getRandValue(r, []string{"word", "verb_linking"}) } +func verbLinking(f *Faker) string { return getRandValue(f, []string{"word", "verb_linking"}) } // VerbHelping will generate a random helping verb -func VerbHelping() string { return verbHelping(globalFaker.Rand) } +func VerbHelping() string { return verbHelping(GlobalFaker) } // VerbHelping will generate a random helping verb -func (f *Faker) VerbHelping() string { return verbHelping(f.Rand) } +func (f *Faker) VerbHelping() string { return verbHelping(f) } -func verbHelping(r *rand.Rand) string { return getRandValue(r, []string{"word", "verb_helping"}) } +func verbHelping(f *Faker) string { return getRandValue(f, []string{"word", "verb_helping"}) } func addWordVerbLookup() { AddFuncLookup("verb", Info{ @@ -66,8 +64,8 @@ func addWordVerbLookup() { Description: "Word expressing an action, event or state", Example: "release", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return verb(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return verb(f), nil }, }) @@ -77,8 +75,8 @@ func addWordVerbLookup() { Description: "Verb Indicating a physical or mental action", Example: "close", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return verbAction(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return verbAction(f), nil }, }) @@ -88,8 +86,8 @@ func addWordVerbLookup() { Description: "Verb that requires a direct object to complete its meaning", Example: "follow", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return verbTransitive(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return verbTransitive(f), nil }, }) @@ -99,8 +97,8 @@ func addWordVerbLookup() { Description: "Verb that does not require a direct object to complete its meaning", Example: "laugh", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return verbIntransitive(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return verbIntransitive(f), nil }, }) @@ -110,8 +108,8 @@ func addWordVerbLookup() { Description: "Verb that Connects the subject of a sentence to a subject complement", Example: "was", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return verbLinking(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return verbLinking(f), nil }, }) @@ -121,8 +119,8 @@ func addWordVerbLookup() { Description: "Auxiliary verb that helps the main verb complete the sentence", Example: "be", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { - return verbHelping(r), nil + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { + return verbHelping(f), nil }, }) } diff --git a/word_verb_test.go b/word_verb_test.go index 58a9dd97..8fe34426 100644 --- a/word_verb_test.go +++ b/word_verb_test.go @@ -9,14 +9,14 @@ func ExampleVerb() { Seed(11) fmt.Println(Verb()) - // Output: does + // Output: would } func ExampleFaker_Verb() { f := New(11) fmt.Println(f.Verb()) - // Output: does + // Output: would } func BenchmarkVerb(b *testing.B) { @@ -29,14 +29,14 @@ func ExampleVerbAction() { Seed(11) fmt.Println(VerbAction()) - // Output: close + // Output: paint } func ExampleFaker_VerbAction() { f := New(11) fmt.Println(f.VerbAction()) - // Output: close + // Output: paint } func BenchmarkVerbAction(b *testing.B) { @@ -49,14 +49,14 @@ func ExampleVerbTransitive() { Seed(11) fmt.Println(VerbTransitive()) - // Output: follow + // Output: upgrade } func ExampleFaker_VerbTransitive() { f := New(11) fmt.Println(f.VerbTransitive()) - // Output: follow + // Output: upgrade } func BenchmarkVerbTransitive(b *testing.B) { @@ -69,14 +69,14 @@ func ExampleVerbIntransitive() { Seed(11) fmt.Println(VerbIntransitive()) - // Output: laugh + // Output: vomit } func ExampleFaker_VerbIntransitive() { f := New(11) fmt.Println(f.VerbIntransitive()) - // Output: laugh + // Output: vomit } func BenchmarkVerbIntransitive(b *testing.B) { @@ -89,14 +89,14 @@ func ExampleVerbLinking() { Seed(11) fmt.Println(VerbLinking()) - // Output: was + // Output: must } func ExampleFaker_VerbLinking() { f := New(11) fmt.Println(f.VerbLinking()) - // Output: was + // Output: must } func BenchmarkVerbLinking(b *testing.B) { @@ -109,14 +109,14 @@ func ExampleVerbHelping() { Seed(11) fmt.Println(VerbHelping()) - // Output: be + // Output: am } func ExampleFaker_VerbHelping() { f := New(11) fmt.Println(f.VerbHelping()) - // Output: be + // Output: am } func BenchmarkVerbHelping(b *testing.B) { diff --git a/xml.go b/xml.go index b922d0de..98ad7924 100644 --- a/xml.go +++ b/xml.go @@ -5,7 +5,6 @@ import ( "encoding/json" "encoding/xml" "errors" - "math/rand" "reflect" ) @@ -129,7 +128,7 @@ func xmlMapLoop(e *xml.Encoder, m *xmlMap) error { // XML generates an object or an array of objects in json format // A nil XMLOptions returns a randomly structured XML. -func XML(xo *XMLOptions) ([]byte, error) { return xmlFunc(globalFaker, xo) } +func XML(xo *XMLOptions) ([]byte, error) { return xmlFunc(GlobalFaker, xo) } // XML generates an object or an array of objects in json format // A nil XMLOptions returns a randomly structured XML. @@ -185,7 +184,7 @@ func xmlFunc(f *Faker, xo *XMLOptions) ([]byte, error) { return nil, errors.New("invalid function, " + field.Function + " does not exist") } - value, err := funcInfo.Generate(f.Rand, &field.Params, funcInfo) + value, err := funcInfo.Generate(f, &field.Params, funcInfo) if err != nil { return nil, err } @@ -238,7 +237,7 @@ func xmlFunc(f *Faker, xo *XMLOptions) ([]byte, error) { return nil, errors.New("invalid function, " + field.Function + " does not exist") } - value, err := funcInfo.Generate(f.Rand, &field.Params, funcInfo) + value, err := funcInfo.Generate(f, &field.Params, funcInfo) if err != nil { return nil, err } @@ -293,7 +292,7 @@ func addFileXMLLookup() { {Field: "indent", Display: "Indent", Type: "bool", Default: "false", Description: "Whether or not to add indents and newlines"}, {Field: "fields", Display: "Fields", Type: "[]Field", Description: "Fields containing key name and function to run in json format"}, }, - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { xo := XMLOptions{} typ, err := info.GetString(m, "type") @@ -344,7 +343,6 @@ func addFileXMLLookup() { } } - f := &Faker{Rand: r} return xmlFunc(f, &xo) }, }) diff --git a/xml_test.go b/xml_test.go index 9c35426d..a33f92b8 100644 --- a/xml_test.go +++ b/xml_test.go @@ -2,7 +2,6 @@ package gofakeit import ( "fmt" - "math/rand" "testing" ) @@ -27,11 +26,10 @@ func ExampleXML_single() { fmt.Println(string(value)) - // Output: - // - // Markus - // Moen - // 856Y5wPZevX9 + // Output: + // Sonny + // Stiedemann + // 8nwf0o3sBXcR // } @@ -56,11 +54,10 @@ func ExampleFaker_XML_single() { fmt.Println(string(value)) - // Output: - // - // Markus - // Moen - // 856Y5wPZevX9 + // Output: + // Sonny + // Stiedemann + // 8nwf0o3sBXcR // } @@ -85,17 +82,16 @@ func ExampleXML_array() { fmt.Println(string(value)) - // Output: - // + // Output: // - // Markus - // Moen - // 856Y5wPZevX9 + // Sonny + // Stiedemann + // 8nwf0o3sBXcR // // - // Jalon - // Rolfson - // 64wz4EAS0Hl0 + // Verda + // Brakus + // 3beWLpq75Lua // // } @@ -121,17 +117,16 @@ func ExampleFaker_XML_array() { fmt.Println(string(value)) - // Output: - // + // Output: // - // Markus - // Moen - // 856Y5wPZevX9 + // Sonny + // Stiedemann + // 8nwf0o3sBXcR // // - // Jalon - // Rolfson - // 64wz4EAS0Hl0 + // Verda + // Brakus + // 3beWLpq75Lua // // } @@ -145,7 +140,7 @@ func TestXMLSingle(t *testing.T) { Description: "", Example: "", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { return map[string]any{ "string": "string value", "int": 123456789, @@ -186,7 +181,7 @@ func TestXMLArray(t *testing.T) { Description: "", Example: "", Output: "string", - Generate: func(r *rand.Rand, m *MapParams, info *Info) (any, error) { + Generate: func(f *Faker, m *MapParams, info *Info) (any, error) { return map[string]any{ "string": "string value", "int": 123456789, @@ -233,7 +228,7 @@ func TestXMLLookup(t *testing.T) { m.Add("fields", `{"name":"first_name","function":"firstname"}`) m.Add("fields", `{"name":"password","function":"password","params":{"special":["false"],"length":["20"]}}`) - _, err := info.Generate(faker.Rand, m, info) + _, err := info.Generate(faker, m, info) if err != nil { t.Fatal(err.Error()) } @@ -265,75 +260,7 @@ func BenchmarkXMLLookup100(b *testing.B) { m.Add("fields", `{"name":"description","function":"paragraph"}`) m.Add("fields", `{"name":"created_at","function":"date"}`) - _, err := info.Generate(faker.Rand, m, info) - if err != nil { - b.Fatal(err.Error()) - } - } -} - -func BenchmarkXMLLookup1000(b *testing.B) { - faker := New(0) - - for i := 0; i < b.N; i++ { - info := GetFuncLookup("xml") - - m := NewMapParams() - m.Add("type", "array") - m.Add("rowcount", "1000") - m.Add("fields", `{"name":"id","function":"autoincrement"}`) - m.Add("fields", `{"name":"first_name","function":"firstname"}`) - m.Add("fields", `{"name":"last_name","function":"lastname"}`) - m.Add("fields", `{"name":"password","function":"password"}`) - m.Add("fields", `{"name":"description","function":"paragraph"}`) - m.Add("fields", `{"name":"created_at","function":"date"}`) - - _, err := info.Generate(faker.Rand, m, info) - if err != nil { - b.Fatal(err.Error()) - } - } -} - -func BenchmarkXMLLookup10000(b *testing.B) { - faker := New(0) - - for i := 0; i < b.N; i++ { - info := GetFuncLookup("xml") - - m := NewMapParams() - m.Add("type", "array") - m.Add("rowcount", "10000") - m.Add("fields", `{"name":"id","function":"autoincrement"}`) - m.Add("fields", `{"name":"first_name","function":"firstname"}`) - m.Add("fields", `{"name":"last_name","function":"lastname"}`) - m.Add("fields", `{"name":"password","function":"password"}`) - m.Add("fields", `{"name":"description","function":"paragraph"}`) - m.Add("fields", `{"name":"created_at","function":"date"}`) - - _, err := info.Generate(faker.Rand, m, info) - if err != nil { - b.Fatal(err.Error()) - } - } -} -func BenchmarkXMLLookup100000(b *testing.B) { - faker := New(0) - - for i := 0; i < b.N; i++ { - info := GetFuncLookup("xml") - - m := NewMapParams() - m.Add("type", "array") - m.Add("rowcount", "100000") - m.Add("fields", `{"name":"id","function":"autoincrement"}`) - m.Add("fields", `{"name":"first_name","function":"firstname"}`) - m.Add("fields", `{"name":"last_name","function":"lastname"}`) - m.Add("fields", `{"name":"password","function":"password"}`) - m.Add("fields", `{"name":"description","function":"paragraph"}`) - m.Add("fields", `{"name":"created_at","function":"date"}`) - - _, err := info.Generate(faker.Rand, m, info) + _, err := info.Generate(faker, m, info) if err != nil { b.Fatal(err.Error()) }