rust_rcs_core/security/authentication/
auth_param.rs

1// Copyright 2023 宋昊文
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::internet::syntax;
16
17pub struct AuthParam<'a> {
18    pub name: &'a [u8],
19    pub value: &'a [u8],
20}
21
22pub trait AuthParamParser<'a> {
23    type Target;
24    fn try_auth_param(&'a self) -> Option<(Self::Target, usize)>;
25}
26
27impl<'a> AuthParamParser<'a> for [u8] {
28    type Target = AuthParam<'a>;
29    fn try_auth_param(&'a self) -> Option<(Self::Target, usize)> {
30        let (chunk, mut advance) = if let Some(idx) = syntax::index_with_token_escaping(self, b',')
31        {
32            (&self[..idx], idx)
33        } else {
34            (self, self.len())
35        };
36
37        let chunk = syntax::trim(chunk);
38
39        if let Some(idx) = chunk.iter().position(|c| *c == b'=') {
40            let name = &chunk[..idx];
41            let value = &chunk[idx + 1..];
42
43            if advance + 1 < self.len() {
44                advance += syntax::index_skipping_ows_and_obs_fold(&self[advance + 1..]);
45                advance += 1;
46            }
47
48            Some((
49                AuthParam {
50                    name,
51                    value: syntax::unquote(value),
52                },
53                advance,
54            ))
55        } else {
56            None
57        }
58    }
59}