{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes       #-}
import           Control.DeepSeq
import           Criterion.Main
import qualified Data.Attoparsec.Text as A
import           Data.List            (sortOn)
import qualified Data.RadixTree       as R
import           Data.Text            (Text)
import qualified Data.Text            as T
import qualified Data.Vector          as V
import           GHC.Compact
import           Text.QuasiText

parseNaiive :: [Text] -> A.Parser Text
parseNaiive = A.choice . map A.string . sortOn (negate . T.length)

main :: IO ()
main = defaultMain
  [ env (return (source, sourceRadix, sourceRadixCompressed, tests0)) $ \
      ~(src, radix, radix2, tests) ->
      bgroup "attoparsec"
      [ bench "radix" $
        V.foldl' (\() t -> rnf $ A.parseOnly (R.parse const radix) t) () `nf` tests

      , bench "radix compressed" $
        V.foldl' (\() t -> rnf $ A.parseOnly (R.parse const radix2) t) () `nf` tests

      , env (getCompact <$> compact radix2) $ \compactR ->
        bench "radix compressed compact" $
        V.foldl' (\() t -> rnf $ A.parseOnly (R.parse const radix2) t) () `nf` tests

      , bench "naiive" $
        V.foldl' (\() t -> rnf $ A.parseOnly (parseNaiive src) t) () `nf` tests
      ]
  ]

tests0 :: V.Vector Text
tests0 = V.fromList $! T.lines
  "acceleration\n\
  \acceleration, braking or coasting\n\
  \axle\n\
  \AAA\n\
  \2+2 seating\n\
  \long thing that doesn't parse\n\
  \z"

sourceRadixCompressed :: R.CompressedRadixTree ()
sourceRadixCompressed =
  case R.compressBy (T.concat source) sourceRadix of
    Just ct -> ct
    Nothing -> error "could not compress source"

sourceRadix :: R.RadixTree ()
sourceRadix = R.fromFoldable_ source

source :: [Text]
source = T.lines [embed|
%
+/-
2+2 seating
A.
AAA
AAR-10A Contoured Coupler
able
able-bodied
AC auxiliary power
accelerating, braking or coasting
acceleration
access
accessible
accessible toilet
accidental operation
accordance
accreditation
accumulate
accuracy
action
activation
active
activities
Adapter Coupling
adjacent
adjust
adverse
air
air pressure
Air Spring
air suspension
aisle
alarm
alerts
aligned
allocated
Alpha-Numeric Trip Codes
alternative
aluminium
announcements
apples
apportioned
appropriate
approval
approved
area calculation
armrests
arrival
ASA standards
asdf
asdff
Asset Information System
assistive listening
attack
audio
Australian
Authorised Crew Member
Authorised Crew Members
authorised personnel
authorised persons
autocoupler electrical connections
automatic
Automatic Coupler
Average
away
axle
Axle Bod
axle box
Axle Box
Axle Load
B.
baby change table
Ballast
Ballast strikes
balr
based
battery
bearings
being
bell
bend
bicycles
blue
body
bodyside
bogie
Bogie
Bogie Conditions
bogies
Bogies
bottom
bounce
bounce test
boundary
brake
brake controller
braking
build quality
button
C.
cab
cable
Cabling and Earth Brush
calculation
call
calls
camera
camera location
cameras
cant
capability
capacity
capital spares
car
Car
cars
Cars
case
casting
cat
Category-1b Train
CCTV
CCTV cameras
CCTV system storage
character
chemical substances
clauses
clear
clearances
climate
climate requirements
closing
coefficient of friction
colour
combined
comfort
Commencement
communication
company
comparable
compared
compatible
complete
completely
components
compressed air
Compressed Air Supply
concurrently
condition
condition
conditions
configuration
connections
connectivity
considering
contact
control
control panels
conversely
converters
cores
Coupling Faces
cover
coverage
covers
cow
cows
crane
crew
crew.
Crew
crew cab door
Crew calls
Crew-Only Accessible Panel
critical
Critical Speed
Crush Load
cubic metres
cups
current
curve stability test
cyclists
D.
damage
damper
data
data storage
date
day
days
dB(A) LpAFmax
DCS 1800 Frequency Band
Dead Mass
decals
deficiency
defined
deflated
deflating
degC
degraded
degrees
degrees of freedom
departure
deployment
design
Design
Design Category C-I
design life
Design Life
destination
detail
details
detection
developed
device
devices
diameter
different
differentiate
direction
direct solar heat transmission
dispatch
distance
Distance
dog
door
doors
doorways
downloadable
draught
draught screen
drawings
drinking fountain
drinking fountains
drinks
driver
Driver
drivers ear
drivers workstation
driving
drop down table
drop down tables
dry conditions
DSAPT
DTS Area Numbers
Duggan Method
E.
ears
Earth Brush
Earth Brush
ease
edge
effluent
egress
EIRENE Functional Numbers
electrical
electrical power
Electric Traction and Brake
electro-dynamic
electromotive force
emergency
emergency brake
Emergency Brakes
Emergency Services
EN 14752
EN 15227
end
End Detrainment System
engagement
enter
envelope
environmental
environmental conditions
Environmental Conditions
equipment
equivalent
etching
ETCS level 2 operation
evacuation
event
event recorder
events
exceptional
Exceptional Payload
Exceptional Pay Load
existing
existing intercity trains
Existing Tanking Facilities
exposed
exterior
external
external passenger information displays
facilities
facility
factor
failure
failures of self-tests should be recorded in the train-borne recorder
fasteners
fault
faults
film
finishes
fire
fire and smoke detection system (NIF_RSS_460).
first
fish
flexible
flood
flooring
floors
following
Forward call to the driver handportable
forward facing
four
four-hour maintenance window
fourth
frame
freedom
freight
freight traffic
fresh air intake dampers
Fresh Air Intake Dampers
From
fruit
full-duplex
funtional
future
g
gangway
gangways
gap
Gavin
Gearbox
gear hanger bracket
generated
geographical location
glass
grabrails
graffiti
green
ground
groups
GSM-R Train radio equipment
GUS
hail stones
handrails
heights
hello
High Speed Boards
high voltage
holding brake
hook
hooks
hoses
hours
Hunter Rail Car
Hunting
identical
identification
identity
image
images
In
incapacitated
incorporates
index
individuals
information
infrared
initial
Initiate automated request
input
inserting
intercar access doors
inter-car connections
intercar jumper
interchangeable
intercom
interface
interior
intermediate
Intermediate Cars
intermittent noises
internal
internal noise
internal passenger information display
internal tonal noise
international standards
internet
interval
intervention
isolated
items
joints
kg
kg/m2
kilo
kilograms
kinematic
km
km/h
kN
ladder
ladders
Landing Edge
lateral
Lathe
Leading Edge
legible
legislation.
length
letters
level
levels
life
lifting
lifting points
line
liner(s)
Line Speed
liquid
list
live OHLE
load
location
Location information
locations
lock
logo
Long Distance Train
Long Train
Long Unit
lower deck
lowered
low-level
luggage
luminous transmittance
m2
magnetic particle testing
Maintainer
Maintainers
maintenance
Maintenance Facility
major
management
manual
manually
manufactured
mass
material
materials
maximum
Maximum
Maximum Design Speed
maximum safe operating speed
Maximum Safe Operating Speed
Maximum Service Speed
MDBF
Mean Comfort Complete Method
mechanical
Mechanical Brakes
medical
medical devices
Medium Electric Outline
member
members
messages
methods
metres
MetroNet Transponder System
minimum
Minimum Operating Standards
minute
minutes
mm
MMT
mobile telecommunication network
mode
More
MOS
Motor Bogie
movements
MTTR
n
name
nearest
network
Network
Network Re-railing facility
new
New
newton
next
night.
NN
noise
nominated MMT tasks
Non-destructive test
non-receptive network
normal
Normal Seats
normal use
NSW Digital Train Radio System (DTRS)
obstruction
occupant
odours
office
OHW Current Draw Limit
OHW Current Limited Zone
OHW Current Return Limit
onboard
one
open
opening
operable
operating
operating speed
operation
operational spares
Operator
OPEX
orange
OSCar
OSCar Motor Bogie
OSCar Trailer Bogie
Other Elastomer components
otherwise
OTR
outlet
output
overhaul
overhead
Overhead Crane
Overhead Power Supply Harmonics
P2 force
pad
pairs
panels
parking brake
passage
passenger
passenger bodyside door
Passenger Bodyside Door
Passenger Bodyside Doors
passenger ears
passenger information system
passenger loading
passengers
passengers ear
passenger services
path
paths
payload
Payload Conditions
Peak Heat Release Rate
performance
performed
permitted
person
persons
photo luminescent
pitch
Plan
planned
platform
platforms
Pneumatic
points
pony bogie
Pony Bogie
portable
portal
position
possible
power
power cable
power distribution panel
practicable
Preparation
pre-recorded
presentation
primary
Primary Controller
Primary Suspension
priority
Priority
procedures
profile
Prohibited Items
protective
proven
provision
psi
public address announcements
public address system
push-button
quality
Quality Assurance system
radio
Radio faults
radius
rail
Rail Emergency Train Recovery Unit
rail network
Rail Safety National Law
rain
raised
rate
ready
real time
real-time
rear
rear pasenger door
recessed region
recorder
recovered
recovery
recovery.
rectification
red
reduce
Reference Masses
reflectance
regenerative mode
rejection
relevant
remain
remote
remotely
removable
required
requirement
requirements
re-railing
reservoir
resonance
restraints
results
RETRU
rheostatic mode
ride
Ride Comfort Index
robust interior fittings
route
rows
running
running times
safe
safe operating speed
Safety Device
Safety Management System
saloon
Scharfenberg Type-10 Coupler
schedule
Schedule of Finishes
scratching
screens
sdfsdf
seat
seated
seating
seats
second
Secondary
seconds
Section 13.3.2.2 of AS 7533.3
Section-2-1-1-3
Section 4.1.1.1 of EN 14752
Section 5.2.1.4 of EN 14752
Section 6.5 of GM/RT 2100
Section-8.3
secure
securing mechanism
Selective Door Operation
separation
service
Serviceable
Service Type B
servicing
shear
shear pad casting
Short Train
Short Unit
side
sides
sign
signage
signs
similar
simultaneous
situations
slip resistant surfaces
slogan
smart card
smart cards
socket
solution
sound
spaces
spare
special tools
specific
specification
speech transmission index
speed
speeding
spreader
spreader beam
spring
stable
staff members
stakeholder
standard
standard toilet
standees
standing
Standing Area
Standing Area Calculation
Standing Passenger Density
startup
static
Static Rolling Stock Outline
station
stationary
status
steps
stiffness
stopping
Stopping Pattern
storage
stove
strategy
strength
stretcher
subsystem
sub-system
sub-systems
suitable
sunlight
super
supplier
Supplier
surface
surface finish
surfing
suspension
Suspension
suspensions
Sustained
swept path
Sydney Trains
Sydney Trains Washplants
synchronised
system
systems
table
tailored
tampering
tangent
tanks
TBD
temperature
Terminal End
termination
test
Test Routes
tests
text
TfNSW
TfNSW
TfNSW External Livery Principles for 'NSW Trains'
TfNSW Internal Decal Approach for 'Trains' or 'NSW Trains'
than
third
third party freight services
through
T HR RS 00100 ST
T HR RS 08001 ST
T HR RS 12001 ST
T HR TE 41001
T HR TE 41002
T HR TE 81001
T HR TE 81002
time
Timetable
Timetable.
Tip Up Seats
TMS
T MU RS 01000 ST for P-II vehicles
toilet
toilets
tolerances
ton
tonnes
total solar energy rejection
track
Track
track cant deficiency
Track Gauge
traction
traction equipment
Traction Motor
traffic
Trailer Bogie
trailing edge
Trailing Edge
train
train
Train
Train Controller
Train Management System
Train Protection and Security
trains
transmission
transverse
transverse seats
travel
trespasser
Trip Codes
Trip Gear
tunnels
tyjhgdyfhukfhk
ultrasonic testing
underframe
unique car identification
Unit
unloading
unrestricted
update
upper deck
upright
USB socket
use
used
user decisions
user groups
users
UV
VAC
vandalism
vehicle
Vehicle Body
vehicles
vertical
vestibule
vision impairment
visual and audible alarm
volume
warning
warranty spares
washplant
waste
water
weather conditions
weekday
weld
Weld
Welding
weld quality
wet conditions
wheel
Wheel
wheelchair
wheelchairs
wheel-rail adhesion modifiers
wheel slide
wheel slip
width
window
windowr
windows
wire
work
workshop
Workstation
worn
xxxx1
yaw
year
years
yellow|]