Skip to main content

pop_chains/try_runtime/
parse.rs

1// This file is part of try-runtime-cli.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use sp_version::StateVersion;
19
20use crate::Error;
21
22/// Parse a block hash from a string.
23pub fn hash(block_hash: &str) -> Result<String, Error> {
24	let (block_hash, offset) = if let Some(block_hash) = block_hash.strip_prefix("0x") {
25		(block_hash, 2)
26	} else {
27		(block_hash, 0)
28	};
29
30	if let Some(pos) = block_hash.chars().position(|c| !c.is_ascii_hexdigit()) {
31		Err(Error::ParamParsingError(format!(
32			"Expected block hash, found illegal hex character at position: {}",
33			offset + pos,
34		)))
35	} else {
36		Ok(block_hash.into())
37	}
38}
39
40/// Parse a URL from a string.
41pub fn url(s: &str) -> Result<String, Error> {
42	if s.starts_with("ws://") || s.starts_with("wss://") {
43		Ok(s.to_string())
44	} else {
45		Err(Error::ParamParsingError(
46			"not a valid WS(S) url: must start with 'ws://' or 'wss://'".to_string(),
47		))
48	}
49}
50
51/// Parse a state version from a string.
52pub fn state_version(s: &str) -> Result<StateVersion, Error> {
53	s.parse::<u8>()
54		.map_err(|_| ())
55		.and_then(StateVersion::try_from)
56		.map_err(|_| Error::ParamParsingError("Invalid state version.".to_string()))
57}
58
59#[cfg(test)]
60mod tests {
61	use super::*;
62
63	#[test]
64	fn parse_hash_works() {
65		assert!(hash("0x1234567890abcdef").is_ok());
66		assert!(hash("1234567890abcdef").is_ok());
67		assert!(hash("0x1234567890abcdefg").is_err());
68		assert!(hash("1234567890abcdefg").is_err());
69	}
70
71	#[test]
72	fn parse_url_works() {
73		assert!(url("ws://localhost:9944").is_ok());
74		assert!(url("wss://localhost:9944").is_ok());
75		assert!(url("http://localhost:9944").is_err());
76		assert!(url("https://localhost:9944").is_err());
77	}
78
79	#[test]
80	fn parse_state_version_works() {
81		assert!(state_version("0").is_ok());
82		assert!(state_version("1").is_ok());
83		assert!(state_version("100").is_err());
84		assert!(state_version("200").is_err());
85	}
86}