1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
use std::cmp::min;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::rc::Rc;

use regex::{escape, Regex};
use url::Url;

use error::UrlGenerationError;
use handler::{AsyncResult, FromRequest, Responder, RouteHandler};
use http::{Method, StatusCode};
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use param::{ParamItem, Params};
use pred::Predicate;
use resource::{DefaultResource, Resource};
use scope::Scope;
use server::Request;

#[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) enum ResourceId {
    Default,
    Normal(u16),
}

enum ResourcePattern<S> {
    Resource(ResourceDef),
    Handler(ResourceDef, Option<Vec<Box<Predicate<S>>>>),
    Scope(ResourceDef, Vec<Box<Predicate<S>>>),
}

enum ResourceItem<S> {
    Resource(Resource<S>),
    Handler(Box<RouteHandler<S>>),
    Scope(Scope<S>),
}

/// Interface for application router.
pub struct Router<S> {
    rmap: Rc<ResourceMap>,
    patterns: Vec<ResourcePattern<S>>,
    resources: Vec<ResourceItem<S>>,
    default: Option<DefaultResource<S>>,
}

/// Information about current resource
#[derive(Clone)]
pub struct ResourceInfo {
    rmap: Rc<ResourceMap>,
    resource: ResourceId,
    params: Params,
    prefix: u16,
}

impl ResourceInfo {
    /// Name os the resource
    #[inline]
    pub fn name(&self) -> &str {
        if let ResourceId::Normal(idx) = self.resource {
            self.rmap.patterns[idx as usize].0.name()
        } else {
            ""
        }
    }

    /// This method returns reference to matched `ResourceDef` object.
    #[inline]
    pub fn rdef(&self) -> Option<&ResourceDef> {
        if let ResourceId::Normal(idx) = self.resource {
            Some(&self.rmap.patterns[idx as usize].0)
        } else {
            None
        }
    }

    pub(crate) fn set_prefix(&mut self, prefix: u16) {
        self.prefix = prefix;
    }

    /// Get a reference to the Params object.
    ///
    /// Params is a container for url parameters.
    /// A variable segment is specified in the form `{identifier}`,
    /// where the identifier can be used later in a request handler to
    /// access the matched value for that segment.
    #[inline]
    pub fn match_info(&self) -> &Params {
        &self.params
    }

    #[inline]
    pub(crate) fn merge(&mut self, info: &ResourceInfo) {
        let mut p = info.params.clone();
        p.set_tail(self.params.tail);
        for item in &self.params.segments {
            p.add(item.0.clone(), item.1.clone());
        }

        self.prefix = info.params.tail;
        self.params = p;
    }

    /// Generate url for named resource
    ///
    /// Check [`HttpRequest::url_for()`](../struct.HttpRequest.html#method.
    /// url_for) for detailed information.
    pub fn url_for<U, I>(
        &self, req: &Request, name: &str, elements: U,
    ) -> Result<Url, UrlGenerationError>
    where
        U: IntoIterator<Item = I>,
        I: AsRef<str>,
    {
        if let Some(pattern) = self.rmap.named.get(name) {
            let path =
                pattern.resource_path(elements, &req.path()[..(self.prefix as usize)])?;
            if path.starts_with('/') {
                let conn = req.connection_info();
                Ok(Url::parse(&format!(
                    "{}://{}{}",
                    conn.scheme(),
                    conn.host(),
                    path
                ))?)
            } else {
                Ok(Url::parse(&path)?)
            }
        } else {
            Err(UrlGenerationError::ResourceNotFound)
        }
    }

    /// Check if application contains matching resource.
    ///
    /// This method does not take `prefix` into account.
    /// For example if prefix is `/test` and router contains route `/name`,
    /// following path would be recognizable `/test/name` but `has_resource()` call
    /// would return `false`.
    pub fn has_resource(&self, path: &str) -> bool {
        self.rmap.has_resource(path)
    }

    /// Check if application contains matching resource.
    ///
    /// This method does take `prefix` into account
    /// but behaves like `has_route` in case `prefix` is not set in the router.
    ///
    /// For example if prefix is `/test` and router contains route `/name`, the
    /// following path would be recognizable `/test/name` and `has_prefixed_route()` call
    /// would return `true`.
    /// It will not match against prefix in case it's not given. For example for `/name`
    /// with a `/test` prefix would return `false`
    pub fn has_prefixed_resource(&self, path: &str) -> bool {
        let prefix = self.prefix as usize;
        if prefix >= path.len() {
            return false;
        }
        self.rmap.has_resource(&path[prefix..])
    }
}

pub(crate) struct ResourceMap {
    named: HashMap<String, ResourceDef>,
    patterns: Vec<(ResourceDef, Option<Rc<ResourceMap>>)>,
}

impl ResourceMap {
    pub fn has_resource(&self, path: &str) -> bool {
        let path = if path.is_empty() { "/" } else { path };

        for (pattern, rmap) in &self.patterns {
            if let Some(ref rmap) = rmap {
                if let Some(plen) = pattern.is_prefix_match(path) {
                    return rmap.has_resource(&path[plen..]);
                }
            } else if pattern.is_match(path) {
                return true;
            }
        }
        false
    }
}

impl<S: 'static> Default for Router<S> {
    fn default() -> Self {
        Router::new()
    }
}

impl<S: 'static> Router<S> {
    pub(crate) fn new() -> Self {
        Router {
            rmap: Rc::new(ResourceMap {
                named: HashMap::new(),
                patterns: Vec::new(),
            }),
            resources: Vec::new(),
            patterns: Vec::new(),
            default: None,
        }
    }

    #[inline]
    pub(crate) fn route_info_params(&self, idx: u16, params: Params) -> ResourceInfo {
        ResourceInfo {
            params,
            prefix: 0,
            rmap: self.rmap.clone(),
            resource: ResourceId::Normal(idx),
        }
    }

    #[cfg(test)]
    pub(crate) fn route_info(&self, req: &Request, prefix: u16) -> ResourceInfo {
        let mut params = Params::with_url(req.url());
        params.set_tail(prefix);

        ResourceInfo {
            params,
            prefix: 0,
            rmap: self.rmap.clone(),
            resource: ResourceId::Default,
        }
    }

    #[cfg(test)]
    pub(crate) fn default_route_info(&self) -> ResourceInfo {
        ResourceInfo {
            params: Params::new(),
            rmap: self.rmap.clone(),
            resource: ResourceId::Default,
            prefix: 0,
        }
    }

    pub(crate) fn register_resource(&mut self, resource: Resource<S>) {
        {
            let rmap = Rc::get_mut(&mut self.rmap).unwrap();

            let name = resource.get_name();
            if !name.is_empty() {
                assert!(
                    !rmap.named.contains_key(name),
                    "Named resource {:?} is registered.",
                    name
                );
                rmap.named.insert(name.to_owned(), resource.rdef().clone());
            }
            rmap.patterns.push((resource.rdef().clone(), None));
        }
        self.patterns
            .push(ResourcePattern::Resource(resource.rdef().clone()));
        self.resources.push(ResourceItem::Resource(resource));
    }

    pub(crate) fn register_scope(&mut self, mut scope: Scope<S>) {
        Rc::get_mut(&mut self.rmap)
            .unwrap()
            .patterns
            .push((scope.rdef().clone(), Some(scope.router().rmap.clone())));
        let filters = scope.take_filters();
        self.patterns
            .push(ResourcePattern::Scope(scope.rdef().clone(), filters));
        self.resources.push(ResourceItem::Scope(scope));
    }

    pub(crate) fn register_handler(
        &mut self, path: &str, hnd: Box<RouteHandler<S>>,
        filters: Option<Vec<Box<Predicate<S>>>>,
    ) {
        let rdef = ResourceDef::prefix(path);
        Rc::get_mut(&mut self.rmap)
            .unwrap()
            .patterns
            .push((rdef.clone(), None));
        self.resources.push(ResourceItem::Handler(hnd));
        self.patterns.push(ResourcePattern::Handler(rdef, filters));
    }

    pub(crate) fn has_default_resource(&self) -> bool {
        self.default.is_some()
    }

    pub(crate) fn register_default_resource(&mut self, resource: DefaultResource<S>) {
        self.default = Some(resource);
    }

    pub(crate) fn finish(&mut self) {
        if let Some(ref default) = self.default {
            for resource in &mut self.resources {
                match resource {
                    ResourceItem::Resource(_) => (),
                    ResourceItem::Scope(scope) => {
                        if !scope.has_default_resource() {
                            scope.default_resource(default.clone());
                        }
                        scope.finish()
                    }
                    ResourceItem::Handler(hnd) => {
                        if !hnd.has_default_resource() {
                            hnd.default_resource(default.clone());
                        }
                        hnd.finish()
                    }
                }
            }
        }
    }

    pub(crate) fn register_external(&mut self, name: &str, rdef: ResourceDef) {
        let rmap = Rc::get_mut(&mut self.rmap).unwrap();
        assert!(
            !rmap.named.contains_key(name),
            "Named resource {:?} is registered.",
            name
        );
        rmap.named.insert(name.to_owned(), rdef);
    }

    pub(crate) fn register_route<T, F, R>(&mut self, path: &str, method: Method, f: F)
    where
        F: Fn(T) -> R + 'static,
        R: Responder + 'static,
        T: FromRequest<S> + 'static,
    {
        let out = {
            // get resource handler
            let mut iterator = self.resources.iter_mut();

            loop {
                if let Some(ref mut resource) = iterator.next() {
                    if let ResourceItem::Resource(ref mut resource) = resource {
                        if resource.rdef().pattern() == path {
                            resource.method(method).with(f);
                            break None;
                        }
                    }
                } else {
                    let mut resource = Resource::new(ResourceDef::new(path));
                    resource.method(method).with(f);
                    break Some(resource);
                }
            }
        };
        if let Some(out) = out {
            self.register_resource(out);
        }
    }

    /// Handle request
    pub fn handle(&self, req: &HttpRequest<S>) -> AsyncResult<HttpResponse> {
        let resource = match req.resource().resource {
            ResourceId::Normal(idx) => &self.resources[idx as usize],
            ResourceId::Default => {
                if let Some(ref default) = self.default {
                    if let Some(id) = default.get_route_id(req) {
                        return default.handle(id, req);
                    }
                }
                return AsyncResult::ok(HttpResponse::new(StatusCode::NOT_FOUND));
            }
        };
        match resource {
            ResourceItem::Resource(ref resource) => {
                if let Some(id) = resource.get_route_id(req) {
                    return resource.handle(id, req);
                }

                if let Some(ref default) = self.default {
                    if let Some(id) = default.get_route_id(req) {
                        return default.handle(id, req);
                    }
                }
            }
            ResourceItem::Handler(hnd) => return hnd.handle(req),
            ResourceItem::Scope(hnd) => return hnd.handle(req),
        }
        AsyncResult::ok(HttpResponse::new(StatusCode::NOT_FOUND))
    }

    /// Query for matched resource
    pub fn recognize(&self, req: &Request, state: &S, tail: usize) -> ResourceInfo {
        if tail <= req.path().len() {
            'outer: for (idx, resource) in self.patterns.iter().enumerate() {
                match resource {
                    ResourcePattern::Resource(rdef) => {
                        if let Some(params) = rdef.match_with_params(req, tail) {
                            return self.route_info_params(idx as u16, params);
                        }
                    }
                    ResourcePattern::Handler(rdef, filters) => {
                        if let Some(params) = rdef.match_prefix_with_params(req, tail) {
                            if let Some(ref filters) = filters {
                                for filter in filters {
                                    if !filter.check(req, state) {
                                        continue 'outer;
                                    }
                                }
                            }
                            return self.route_info_params(idx as u16, params);
                        }
                    }
                    ResourcePattern::Scope(rdef, filters) => {
                        if let Some(params) = rdef.match_prefix_with_params(req, tail) {
                            for filter in filters {
                                if !filter.check(req, state) {
                                    continue 'outer;
                                }
                            }
                            return self.route_info_params(idx as u16, params);
                        }
                    }
                }
            }
        }
        ResourceInfo {
            prefix: tail as u16,
            params: Params::new(),
            rmap: self.rmap.clone(),
            resource: ResourceId::Default,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
enum PatternElement {
    Str(String),
    Var(String),
}

#[derive(Clone, Debug)]
enum PatternType {
    Static(String),
    Prefix(String),
    Dynamic(Regex, Vec<Rc<String>>, usize),
}

#[derive(Debug, Copy, Clone, PartialEq)]
/// Resource type
pub enum ResourceType {
    /// Normal resource
    Normal,
    /// Resource for application default handler
    Default,
    /// External resource
    External,
    /// Unknown resource type
    Unset,
}

/// Resource type describes an entry in resources table
#[derive(Clone, Debug)]
pub struct ResourceDef {
    tp: PatternType,
    rtp: ResourceType,
    name: String,
    pattern: String,
    elements: Vec<PatternElement>,
}

impl ResourceDef {
    /// Parse path pattern and create new `Resource` instance.
    ///
    /// Panics if path pattern is wrong.
    pub fn new(path: &str) -> Self {
        ResourceDef::with_prefix(path, "/", false)
    }

    /// Parse path pattern and create new `Resource` instance.
    ///
    /// Use `prefix` type instead of `static`.
    ///
    /// Panics if path regex pattern is wrong.
    pub fn prefix(path: &str) -> Self {
        ResourceDef::with_prefix(path, "/", true)
    }

    /// Construct external resource
    ///
    /// Panics if path pattern is wrong.
    pub fn external(path: &str) -> Self {
        let mut resource = ResourceDef::with_prefix(path, "/", false);
        resource.rtp = ResourceType::External;
        resource
    }

    /// Parse path pattern and create new `Resource` instance with custom prefix
    pub fn with_prefix(path: &str, prefix: &str, for_prefix: bool) -> Self {
        let (pattern, elements, is_dynamic, len) =
            ResourceDef::parse(path, prefix, for_prefix);

        let tp = if is_dynamic {
            let re = match Regex::new(&pattern) {
                Ok(re) => re,
                Err(err) => panic!("Wrong path pattern: \"{}\" {}", path, err),
            };
            // actix creates one router per thread
            let names = re
                .capture_names()
                .filter_map(|name| name.map(|name| Rc::new(name.to_owned())))
                .collect();
            PatternType::Dynamic(re, names, len)
        } else if for_prefix {
            PatternType::Prefix(pattern.clone())
        } else {
            PatternType::Static(pattern.clone())
        };

        ResourceDef {
            tp,
            elements,
            name: "".to_string(),
            rtp: ResourceType::Normal,
            pattern: path.to_owned(),
        }
    }

    /// Resource type
    pub fn rtype(&self) -> ResourceType {
        self.rtp
    }

    /// Resource name
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Resource name
    pub(crate) fn set_name(&mut self, name: &str) {
        self.name = name.to_owned();
    }

    /// Path pattern of the resource
    pub fn pattern(&self) -> &str {
        &self.pattern
    }

    /// Is this path a match against this resource?
    pub fn is_match(&self, path: &str) -> bool {
        match self.tp {
            PatternType::Static(ref s) => s == path,
            PatternType::Dynamic(ref re, _, _) => re.is_match(path),
            PatternType::Prefix(ref s) => path.starts_with(s),
        }
    }

    fn is_prefix_match(&self, path: &str) -> Option<usize> {
        let plen = path.len();
        let path = if path.is_empty() { "/" } else { path };

        match self.tp {
            PatternType::Static(ref s) => if s == path {
                Some(plen)
            } else {
                None
            },
            PatternType::Dynamic(ref re, _, len) => {
                if let Some(captures) = re.captures(path) {
                    let mut pos = 0;
                    let mut passed = false;
                    for capture in captures.iter() {
                        if let Some(ref m) = capture {
                            if !passed {
                                passed = true;
                                continue;
                            }

                            pos = m.end();
                        }
                    }
                    Some(plen + pos + len)
                } else {
                    None
                }
            }
            PatternType::Prefix(ref s) => {
                let len = if path == s {
                    s.len()
                } else if path.starts_with(s)
                    && (s.ends_with('/') || path.split_at(s.len()).1.starts_with('/'))
                {
                    if s.ends_with('/') {
                        s.len() - 1
                    } else {
                        s.len()
                    }
                } else {
                    return None;
                };
                Some(min(plen, len))
            }
        }
    }

    /// Are the given path and parameters a match against this resource?
    pub fn match_with_params(&self, req: &Request, plen: usize) -> Option<Params> {
        let path = &req.path()[plen..];

        match self.tp {
            PatternType::Static(ref s) => if s != path {
                None
            } else {
                Some(Params::with_url(req.url()))
            },
            PatternType::Dynamic(ref re, ref names, _) => {
                if let Some(captures) = re.captures(path) {
                    let mut params = Params::with_url(req.url());
                    let mut idx = 0;
                    let mut passed = false;
                    for capture in captures.iter() {
                        if let Some(ref m) = capture {
                            if !passed {
                                passed = true;
                                continue;
                            }
                            params.add(
                                names[idx].clone(),
                                ParamItem::UrlSegment(
                                    (plen + m.start()) as u16,
                                    (plen + m.end()) as u16,
                                ),
                            );
                            idx += 1;
                        }
                    }
                    params.set_tail(req.path().len() as u16);
                    Some(params)
                } else {
                    None
                }
            }
            PatternType::Prefix(ref s) => if !path.starts_with(s) {
                None
            } else {
                Some(Params::with_url(req.url()))
            },
        }
    }

    /// Is the given path a prefix match and do the parameters match against this resource?
    pub fn match_prefix_with_params(
        &self, req: &Request, plen: usize,
    ) -> Option<Params> {
        let path = &req.path()[plen..];
        let path = if path.is_empty() { "/" } else { path };

        match self.tp {
            PatternType::Static(ref s) => if s == path {
                let mut params = Params::with_url(req.url());
                params.set_tail(req.path().len() as u16);
                Some(params)
            } else {
                None
            },
            PatternType::Dynamic(ref re, ref names, len) => {
                if let Some(captures) = re.captures(path) {
                    let mut params = Params::with_url(req.url());
                    let mut pos = 0;
                    let mut passed = false;
                    let mut idx = 0;
                    for capture in captures.iter() {
                        if let Some(ref m) = capture {
                            if !passed {
                                passed = true;
                                continue;
                            }

                            params.add(
                                names[idx].clone(),
                                ParamItem::UrlSegment(
                                    (plen + m.start()) as u16,
                                    (plen + m.end()) as u16,
                                ),
                            );
                            idx += 1;
                            pos = m.end();
                        }
                    }
                    params.set_tail((plen + pos + len) as u16);
                    Some(params)
                } else {
                    None
                }
            }
            PatternType::Prefix(ref s) => {
                let len = if path == s {
                    s.len()
                } else if path.starts_with(s)
                    && (s.ends_with('/') || path.split_at(s.len()).1.starts_with('/'))
                {
                    if s.ends_with('/') {
                        s.len() - 1
                    } else {
                        s.len()
                    }
                } else {
                    return None;
                };
                let mut params = Params::with_url(req.url());
                params.set_tail(min(req.path().len(), plen + len) as u16);
                Some(params)
            }
        }
    }

    /// Build resource path.
    pub fn resource_path<U, I>(
        &self, elements: U, prefix: &str,
    ) -> Result<String, UrlGenerationError>
    where
        U: IntoIterator<Item = I>,
        I: AsRef<str>,
    {
        let mut path = match self.tp {
            PatternType::Prefix(ref p) => p.to_owned(),
            PatternType::Static(ref p) => p.to_owned(),
            PatternType::Dynamic(..) => {
                let mut path = String::new();
                let mut iter = elements.into_iter();
                for el in &self.elements {
                    match *el {
                        PatternElement::Str(ref s) => path.push_str(s),
                        PatternElement::Var(_) => {
                            if let Some(val) = iter.next() {
                                path.push_str(val.as_ref())
                            } else {
                                return Err(UrlGenerationError::NotEnoughElements);
                            }
                        }
                    }
                }
                path
            }
        };

        if self.rtp != ResourceType::External {
            if prefix.ends_with('/') {
                if path.starts_with('/') {
                    path.insert_str(0, &prefix[..prefix.len() - 1]);
                } else {
                    path.insert_str(0, prefix);
                }
            } else {
                if !path.starts_with('/') {
                    path.insert(0, '/');
                }
                path.insert_str(0, prefix);
            }
        }
        Ok(path)
    }

    fn parse(
        pattern: &str, prefix: &str, for_prefix: bool,
    ) -> (String, Vec<PatternElement>, bool, usize) {
        const DEFAULT_PATTERN: &str = "[^/]+";

        let mut re1 = String::from("^") + prefix;
        let mut re2 = String::from(prefix);
        let mut el = String::new();
        let mut in_param = false;
        let mut in_param_pattern = false;
        let mut param_name = String::new();
        let mut param_pattern = String::from(DEFAULT_PATTERN);
        let mut is_dynamic = false;
        let mut elems = Vec::new();
        let mut len = 0;

        for (index, ch) in pattern.chars().enumerate() {
            // All routes must have a leading slash so its optional to have one
            if index == 0 && ch == '/' {
                continue;
            }

            if in_param {
                // In parameter segment: `{....}`
                if ch == '}' {
                    elems.push(PatternElement::Var(param_name.clone()));
                    re1.push_str(&format!(r"(?P<{}>{})", &param_name, &param_pattern));

                    param_name.clear();
                    param_pattern = String::from(DEFAULT_PATTERN);

                    len = 0;
                    in_param_pattern = false;
                    in_param = false;
                } else if ch == ':' {
                    // The parameter name has been determined; custom pattern land
                    in_param_pattern = true;
                    param_pattern.clear();
                } else if in_param_pattern {
                    // Ignore leading whitespace for pattern
                    if !(ch == ' ' && param_pattern.is_empty()) {
                        param_pattern.push(ch);
                    }
                } else {
                    param_name.push(ch);
                }
            } else if ch == '{' {
                in_param = true;
                is_dynamic = true;
                elems.push(PatternElement::Str(el.clone()));
                el.clear();
            } else {
                re1.push_str(escape(&ch.to_string()).as_str());
                re2.push(ch);
                el.push(ch);
                len += 1;
            }
        }

        if !el.is_empty() {
            elems.push(PatternElement::Str(el.clone()));
        }

        let re = if is_dynamic {
            if !for_prefix {
                re1.push('$');
            }
            re1
        } else {
            re2
        };
        (re, elems, is_dynamic, len)
    }
}

impl PartialEq for ResourceDef {
    fn eq(&self, other: &ResourceDef) -> bool {
        self.pattern == other.pattern
    }
}

impl Eq for ResourceDef {}

impl Hash for ResourceDef {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.pattern.hash(state);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test::TestRequest;

    #[test]
    fn test_recognizer10() {
        let mut router = Router::<()>::new();
        router.register_resource(Resource::new(ResourceDef::new("/name")));
        router.register_resource(Resource::new(ResourceDef::new("/name/{val}")));
        router.register_resource(Resource::new(ResourceDef::new(
            "/name/{val}/index.html",
        )));
        router.register_resource(Resource::new(ResourceDef::new("/file/{file}.{ext}")));
        router.register_resource(Resource::new(ResourceDef::new(
            "/v{val}/{val2}/index.html",
        )));
        router.register_resource(Resource::new(ResourceDef::new("/v/{tail:.*}")));
        router.register_resource(Resource::new(ResourceDef::new("/test2/{test}.html")));
        router.register_resource(Resource::new(ResourceDef::new("{test}/index.html")));

        let req = TestRequest::with_uri("/name").finish();
        let info = router.recognize(&req, &(), 0);
        assert_eq!(info.resource, ResourceId::Normal(0));
        assert!(info.match_info().is_empty());

        let req = TestRequest::with_uri("/name/value").finish();
        let info = router.recognize(&req, &(), 0);
        assert_eq!(info.resource, ResourceId::Normal(1));
        assert_eq!(info.match_info().get("val").unwrap(), "value");
        assert_eq!(&info.match_info()["val"], "value");

        let req = TestRequest::with_uri("/name/value2/index.html").finish();
        let info = router.recognize(&req, &(), 0);
        assert_eq!(info.resource, ResourceId::Normal(2));
        assert_eq!(info.match_info().get("val").unwrap(), "value2");

        let req = TestRequest::with_uri("/file/file.gz").finish();
        let info = router.recognize(&req, &(), 0);
        assert_eq!(info.resource, ResourceId::Normal(3));
        assert_eq!(info.match_info().get("file").unwrap(), "file");
        assert_eq!(info.match_info().get("ext").unwrap(), "gz");

        let req = TestRequest::with_uri("/vtest/ttt/index.html").finish();
        let info = router.recognize(&req, &(), 0);
        assert_eq!(info.resource, ResourceId::Normal(4));
        assert_eq!(info.match_info().get("val").unwrap(), "test");
        assert_eq!(info.match_info().get("val2").unwrap(), "ttt");

        let req = TestRequest::with_uri("/v/blah-blah/index.html").finish();
        let info = router.recognize(&req, &(), 0);
        assert_eq!(info.resource, ResourceId::Normal(5));
        assert_eq!(
            info.match_info().get("tail").unwrap(),
            "blah-blah/index.html"
        );

        let req = TestRequest::with_uri("/test2/index.html").finish();
        let info = router.recognize(&req, &(), 0);
        assert_eq!(info.resource, ResourceId::Normal(6));
        assert_eq!(info.match_info().get("test").unwrap(), "index");

        let req = TestRequest::with_uri("/bbb/index.html").finish();
        let info = router.recognize(&req, &(), 0);
        assert_eq!(info.resource, ResourceId::Normal(7));
        assert_eq!(info.match_info().get("test").unwrap(), "bbb");
    }

    #[test]
    fn test_recognizer_2() {
        let mut router = Router::<()>::new();
        router.register_resource(Resource::new(ResourceDef::new("/index.json")));
        router.register_resource(Resource::new(ResourceDef::new("/{source}.json")));

        let req = TestRequest::with_uri("/index.json").finish();
        let info = router.recognize(&req, &(), 0);
        assert_eq!(info.resource, ResourceId::Normal(0));

        let req = TestRequest::with_uri("/test.json").finish();
        let info = router.recognize(&req, &(), 0);
        assert_eq!(info.resource, ResourceId::Normal(1));
    }

    #[test]
    fn test_recognizer_with_prefix() {
        let mut router = Router::<()>::new();
        router.register_resource(Resource::new(ResourceDef::new("/name")));
        router.register_resource(Resource::new(ResourceDef::new("/name/{val}")));

        let req = TestRequest::with_uri("/name").finish();
        let info = router.recognize(&req, &(), 5);
        assert_eq!(info.resource, ResourceId::Default);

        let req = TestRequest::with_uri("/test/name").finish();
        let info = router.recognize(&req, &(), 5);
        assert_eq!(info.resource, ResourceId::Normal(0));

        let req = TestRequest::with_uri("/test/name/value").finish();
        let info = router.recognize(&req, &(), 5);
        assert_eq!(info.resource, ResourceId::Normal(1));
        assert_eq!(info.match_info().get("val").unwrap(), "value");
        assert_eq!(&info.match_info()["val"], "value");

        // same patterns
        let mut router = Router::<()>::new();
        router.register_resource(Resource::new(ResourceDef::new("/name")));
        router.register_resource(Resource::new(ResourceDef::new("/name/{val}")));

        let req = TestRequest::with_uri("/name").finish();
        let info = router.recognize(&req, &(), 6);
        assert_eq!(info.resource, ResourceId::Default);

        let req = TestRequest::with_uri("/test2/name").finish();
        let info = router.recognize(&req, &(), 6);
        assert_eq!(info.resource, ResourceId::Normal(0));

        let req = TestRequest::with_uri("/test2/name-test").finish();
        let info = router.recognize(&req, &(), 6);
        assert_eq!(info.resource, ResourceId::Default);

        let req = TestRequest::with_uri("/test2/name/ttt").finish();
        let info = router.recognize(&req, &(), 6);
        assert_eq!(info.resource, ResourceId::Normal(1));
        assert_eq!(&info.match_info()["val"], "ttt");
    }

    #[test]
    fn test_parse_static() {
        let re = ResourceDef::new("/");
        assert!(re.is_match("/"));
        assert!(!re.is_match("/a"));

        let re = ResourceDef::new("/name");
        assert!(re.is_match("/name"));
        assert!(!re.is_match("/name1"));
        assert!(!re.is_match("/name/"));
        assert!(!re.is_match("/name~"));

        let re = ResourceDef::new("/name/");
        assert!(re.is_match("/name/"));
        assert!(!re.is_match("/name"));
        assert!(!re.is_match("/name/gs"));

        let re = ResourceDef::new("/user/profile");
        assert!(re.is_match("/user/profile"));
        assert!(!re.is_match("/user/profile/profile"));
    }

    #[test]
    fn test_parse_param() {
        let re = ResourceDef::new("/user/{id}");
        assert!(re.is_match("/user/profile"));
        assert!(re.is_match("/user/2345"));
        assert!(!re.is_match("/user/2345/"));
        assert!(!re.is_match("/user/2345/sdg"));

        let req = TestRequest::with_uri("/user/profile").finish();
        let info = re.match_with_params(&req, 0).unwrap();
        assert_eq!(info.get("id").unwrap(), "profile");

        let req = TestRequest::with_uri("/user/1245125").finish();
        let info = re.match_with_params(&req, 0).unwrap();
        assert_eq!(info.get("id").unwrap(), "1245125");

        let re = ResourceDef::new("/v{version}/resource/{id}");
        assert!(re.is_match("/v1/resource/320120"));
        assert!(!re.is_match("/v/resource/1"));
        assert!(!re.is_match("/resource"));

        let req = TestRequest::with_uri("/v151/resource/adahg32").finish();
        let info = re.match_with_params(&req, 0).unwrap();
        assert_eq!(info.get("version").unwrap(), "151");
        assert_eq!(info.get("id").unwrap(), "adahg32");
    }

    #[test]
    fn test_resource_prefix() {
        let re = ResourceDef::prefix("/name");
        assert!(re.is_match("/name"));
        assert!(re.is_match("/name/"));
        assert!(re.is_match("/name/test/test"));
        assert!(re.is_match("/name1"));
        assert!(re.is_match("/name~"));

        let re = ResourceDef::prefix("/name/");
        assert!(re.is_match("/name/"));
        assert!(re.is_match("/name/gs"));
        assert!(!re.is_match("/name"));
    }

    #[test]
    fn test_reousrce_prefix_dynamic() {
        let re = ResourceDef::prefix("/{name}/");
        assert!(re.is_match("/name/"));
        assert!(re.is_match("/name/gs"));
        assert!(!re.is_match("/name"));

        let req = TestRequest::with_uri("/test2/").finish();
        let info = re.match_with_params(&req, 0).unwrap();
        assert_eq!(&info["name"], "test2");
        assert_eq!(&info[0], "test2");

        let req = TestRequest::with_uri("/test2/subpath1/subpath2/index.html").finish();
        let info = re.match_with_params(&req, 0).unwrap();
        assert_eq!(&info["name"], "test2");
        assert_eq!(&info[0], "test2");
    }

    #[test]
    fn test_request_resource() {
        let mut router = Router::<()>::new();
        let mut resource = Resource::new(ResourceDef::new("/index.json"));
        resource.name("r1");
        router.register_resource(resource);
        let mut resource = Resource::new(ResourceDef::new("/test.json"));
        resource.name("r2");
        router.register_resource(resource);

        let req = TestRequest::with_uri("/index.json").finish();
        let info = router.recognize(&req, &(), 0);
        assert_eq!(info.resource, ResourceId::Normal(0));

        assert_eq!(info.name(), "r1");

        let req = TestRequest::with_uri("/test.json").finish();
        let info = router.recognize(&req, &(), 0);
        assert_eq!(info.resource, ResourceId::Normal(1));
        assert_eq!(info.name(), "r2");
    }

    #[test]
    fn test_has_resource() {
        let mut router = Router::<()>::new();
        let scope = Scope::new("/test").resource("/name", |_| "done");
        router.register_scope(scope);

        {
            let info = router.default_route_info();
            assert!(!info.has_resource("/test"));
            assert!(info.has_resource("/test/name"));
        }

        let scope =
            Scope::new("/test2").nested("/test10", |s| s.resource("/name", |_| "done"));
        router.register_scope(scope);

        let info = router.default_route_info();
        assert!(info.has_resource("/test2/test10/name"));
    }
}