mirror of
https://github.com/italicsjenga/valence.git
synced 2025-01-11 07:11:30 +11:00
Rewrite ident module (again) (#111)
Ident is now a wrapper around any string type `S`.
This commit is contained in:
parent
afe390836c
commit
7d0c254874
|
@ -16,7 +16,6 @@ aes = "0.7.5"
|
||||||
anyhow = "1.0.65"
|
anyhow = "1.0.65"
|
||||||
approx = "0.5.1"
|
approx = "0.5.1"
|
||||||
arrayvec = "0.7.2"
|
arrayvec = "0.7.2"
|
||||||
ascii = "1.1.0"
|
|
||||||
async-trait = "0.1.57"
|
async-trait = "0.1.57"
|
||||||
base64 = "0.13.0"
|
base64 = "0.13.0"
|
||||||
bitfield-struct = "0.1.7"
|
bitfield-struct = "0.1.7"
|
||||||
|
@ -36,12 +35,12 @@ rsa = "0.6.1"
|
||||||
rsa-der = "0.3.0"
|
rsa-der = "0.3.0"
|
||||||
serde = { version = "1.0.145", features = ["derive"] }
|
serde = { version = "1.0.145", features = ["derive"] }
|
||||||
serde_json = "1.0.85"
|
serde_json = "1.0.85"
|
||||||
valence_nbt = "0.2.0"
|
|
||||||
sha1 = "0.10.5"
|
sha1 = "0.10.5"
|
||||||
sha2 = "0.10.6"
|
sha2 = "0.10.6"
|
||||||
thiserror = "1.0.35"
|
thiserror = "1.0.35"
|
||||||
url = { version = "2.2.2", features = ["serde"] }
|
url = { version = "2.2.2", features = ["serde"] }
|
||||||
uuid = { version = "1.1.2", features = ["serde"] }
|
uuid = { version = "1.1.2", features = ["serde"] }
|
||||||
|
valence_nbt = "0.2.0"
|
||||||
vek = "0.15.8"
|
vek = "0.15.8"
|
||||||
|
|
||||||
[dependencies.tokio]
|
[dependencies.tokio]
|
||||||
|
|
12
src/biome.rs
12
src/biome.rs
|
@ -26,7 +26,7 @@ pub struct BiomeId(pub(crate) u16);
|
||||||
pub struct Biome {
|
pub struct Biome {
|
||||||
/// The unique name for this biome. The name can be
|
/// The unique name for this biome. The name can be
|
||||||
/// seen in the F3 debug menu.
|
/// seen in the F3 debug menu.
|
||||||
pub name: Ident<'static>,
|
pub name: Ident<String>,
|
||||||
pub precipitation: BiomePrecipitation,
|
pub precipitation: BiomePrecipitation,
|
||||||
pub sky_color: u32,
|
pub sky_color: u32,
|
||||||
pub water_fog_color: u32,
|
pub water_fog_color: u32,
|
||||||
|
@ -36,7 +36,7 @@ pub struct Biome {
|
||||||
pub grass_color: Option<u32>,
|
pub grass_color: Option<u32>,
|
||||||
pub grass_color_modifier: BiomeGrassColorModifier,
|
pub grass_color_modifier: BiomeGrassColorModifier,
|
||||||
pub music: Option<BiomeMusic>,
|
pub music: Option<BiomeMusic>,
|
||||||
pub ambient_sound: Option<Ident<'static>>,
|
pub ambient_sound: Option<Ident<String>>,
|
||||||
pub additions_sound: Option<BiomeAdditionsSound>,
|
pub additions_sound: Option<BiomeAdditionsSound>,
|
||||||
pub mood_sound: Option<BiomeMoodSound>,
|
pub mood_sound: Option<BiomeMoodSound>,
|
||||||
pub particle: Option<BiomeParticle>,
|
pub particle: Option<BiomeParticle>,
|
||||||
|
@ -202,20 +202,20 @@ pub enum BiomeGrassColorModifier {
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct BiomeMusic {
|
pub struct BiomeMusic {
|
||||||
pub replace_current_music: bool,
|
pub replace_current_music: bool,
|
||||||
pub sound: Ident<'static>,
|
pub sound: Ident<String>,
|
||||||
pub min_delay: i32,
|
pub min_delay: i32,
|
||||||
pub max_delay: i32,
|
pub max_delay: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct BiomeAdditionsSound {
|
pub struct BiomeAdditionsSound {
|
||||||
pub sound: Ident<'static>,
|
pub sound: Ident<String>,
|
||||||
pub tick_chance: f64,
|
pub tick_chance: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct BiomeMoodSound {
|
pub struct BiomeMoodSound {
|
||||||
pub sound: Ident<'static>,
|
pub sound: Ident<String>,
|
||||||
pub tick_delay: i32,
|
pub tick_delay: i32,
|
||||||
pub offset: f64,
|
pub offset: f64,
|
||||||
pub block_search_extent: i32,
|
pub block_search_extent: i32,
|
||||||
|
@ -224,5 +224,5 @@ pub struct BiomeMoodSound {
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct BiomeParticle {
|
pub struct BiomeParticle {
|
||||||
pub probability: f32,
|
pub probability: f32,
|
||||||
pub kind: Ident<'static>,
|
pub kind: Ident<String>,
|
||||||
}
|
}
|
||||||
|
|
|
@ -505,7 +505,7 @@ impl<C: Config> Client<C> {
|
||||||
/// Plays a sound to the client at a given position.
|
/// Plays a sound to the client at a given position.
|
||||||
pub fn play_sound(
|
pub fn play_sound(
|
||||||
&mut self,
|
&mut self,
|
||||||
name: Ident<'static>,
|
name: Ident<String>,
|
||||||
category: SoundCategory,
|
category: SoundCategory,
|
||||||
pos: Vec3<f64>,
|
pos: Vec3<f64>,
|
||||||
volume: f32,
|
volume: f32,
|
||||||
|
|
|
@ -17,11 +17,11 @@ use crate::{ident, LIBRARY_NAMESPACE};
|
||||||
pub struct DimensionId(pub(crate) u16);
|
pub struct DimensionId(pub(crate) u16);
|
||||||
|
|
||||||
impl DimensionId {
|
impl DimensionId {
|
||||||
pub(crate) fn dimension_type_name(self) -> Ident<'static> {
|
pub(crate) fn dimension_type_name(self) -> Ident<String> {
|
||||||
ident!("{LIBRARY_NAMESPACE}:dimension_type_{}", self.0)
|
ident!("{LIBRARY_NAMESPACE}:dimension_type_{}", self.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn dimension_name(self) -> Ident<'static> {
|
pub(crate) fn dimension_name(self) -> Ident<String> {
|
||||||
ident!("{LIBRARY_NAMESPACE}:dimension_{}", self.0)
|
ident!("{LIBRARY_NAMESPACE}:dimension_{}", self.0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
374
src/ident.rs
374
src/ident.rs
|
@ -1,20 +1,23 @@
|
||||||
//! Resource identifiers.
|
//! Resource identifiers.
|
||||||
|
|
||||||
use std::borrow::Cow;
|
use std::borrow::Borrow;
|
||||||
use std::cmp::Ordering;
|
use std::cmp::Ordering;
|
||||||
|
use std::error::Error;
|
||||||
|
use std::fmt;
|
||||||
|
use std::fmt::Formatter;
|
||||||
|
use std::hash::{Hash, Hasher};
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::{fmt, hash};
|
|
||||||
|
|
||||||
use ascii::{AsAsciiStr, AsciiChar, AsciiStr, IntoAsciiString};
|
use serde::de::Error as _;
|
||||||
use hash::Hash;
|
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||||
use serde::de::Visitor;
|
|
||||||
use serde::{de, Deserialize, Deserializer, Serialize};
|
|
||||||
use thiserror::Error;
|
|
||||||
|
|
||||||
use crate::nbt;
|
use crate::nbt;
|
||||||
use crate::protocol::{Decode, Encode};
|
use crate::protocol::{Decode, Encode};
|
||||||
|
|
||||||
|
/// A wrapper around a string type `S` which guarantees the wrapped string is a
|
||||||
|
/// valid resource identifier.
|
||||||
|
///
|
||||||
/// A resource identifier is a string divided into a "namespace" part and a
|
/// A resource identifier is a string divided into a "namespace" part and a
|
||||||
/// "path" part. For instance `minecraft:apple` and `valence:frobnicator` are
|
/// "path" part. For instance `minecraft:apple` and `valence:frobnicator` are
|
||||||
/// both valid identifiers.
|
/// both valid identifiers.
|
||||||
|
@ -25,270 +28,267 @@ use crate::protocol::{Decode, Encode};
|
||||||
///
|
///
|
||||||
/// A string must match the regex `^([a-z0-9_-]+:)?[a-z0-9_\/.-]+$` to be a
|
/// A string must match the regex `^([a-z0-9_-]+:)?[a-z0-9_\/.-]+$` to be a
|
||||||
/// valid identifier.
|
/// valid identifier.
|
||||||
#[derive(Clone, Eq)]
|
#[derive(Copy, Clone, Debug)]
|
||||||
pub struct Ident<'a> {
|
pub struct Ident<S> {
|
||||||
string: Cow<'a, AsciiStr>,
|
string: S,
|
||||||
/// The index of the first character of the path part in the string.
|
|
||||||
path_start: usize,
|
path_start: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The error type created when an [`Ident`] cannot be parsed from a
|
impl<S: Borrow<str>> Ident<S> {
|
||||||
/// string. Contains the offending string.
|
pub fn new(string: S) -> Result<Self, IdentError<S>> {
|
||||||
#[derive(Clone, Debug, Error)]
|
let check_namespace = |s: &str| {
|
||||||
#[error("invalid resource identifier \"{0}\"")]
|
|
||||||
pub struct IdentParseError<'a>(pub Cow<'a, str>);
|
|
||||||
|
|
||||||
impl<'a> Ident<'a> {
|
|
||||||
/// Parses a new identifier from a string.
|
|
||||||
///
|
|
||||||
/// An error is returned containing the input string if it is not a valid
|
|
||||||
/// resource identifier.
|
|
||||||
pub fn new(string: impl Into<Cow<'a, str>>) -> Result<Ident<'a>, IdentParseError<'a>> {
|
|
||||||
#![allow(bindings_with_variant_name)]
|
|
||||||
|
|
||||||
let cow = match string.into() {
|
|
||||||
Cow::Borrowed(s) => {
|
|
||||||
Cow::Borrowed(s.as_ascii_str().map_err(|_| IdentParseError(s.into()))?)
|
|
||||||
}
|
|
||||||
Cow::Owned(s) => Cow::Owned(
|
|
||||||
s.into_ascii_string()
|
|
||||||
.map_err(|e| IdentParseError(e.into_source().into()))?,
|
|
||||||
),
|
|
||||||
};
|
|
||||||
|
|
||||||
let str = cow.as_ref();
|
|
||||||
|
|
||||||
let check_namespace = |s: &AsciiStr| {
|
|
||||||
!s.is_empty()
|
!s.is_empty()
|
||||||
&& s.chars()
|
&& s.chars()
|
||||||
.all(|c| matches!(c.as_char(), 'a'..='z' | '0'..='9' | '_' | '-'))
|
.all(|c| matches!(c, 'a'..='z' | '0'..='9' | '_' | '-'))
|
||||||
};
|
};
|
||||||
let check_path = |s: &AsciiStr| {
|
let check_path = |s: &str| {
|
||||||
!s.is_empty()
|
!s.is_empty()
|
||||||
&& s.chars()
|
&& s.chars()
|
||||||
.all(|c| matches!(c.as_char(), 'a'..='z' | '0'..='9' | '_' | '/' | '.' | '-'))
|
.all(|c| matches!(c, 'a'..='z' | '0'..='9' | '_' | '/' | '.' | '-'))
|
||||||
};
|
};
|
||||||
|
|
||||||
match str.chars().position(|c| c == AsciiChar::Colon) {
|
let str = string.borrow();
|
||||||
Some(colon_idx)
|
|
||||||
if check_namespace(&str[..colon_idx]) && check_path(&str[colon_idx + 1..]) =>
|
match str.split_once(':') {
|
||||||
{
|
Some((namespace, path)) if check_namespace(namespace) && check_path(path) => {
|
||||||
Ok(Self {
|
let path_start = namespace.len() + 1;
|
||||||
string: cow,
|
Ok(Self { string, path_start })
|
||||||
path_start: colon_idx + 1,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
None if check_path(str) => Ok(Self {
|
None if check_path(str) => Ok(Self {
|
||||||
string: cow,
|
string,
|
||||||
path_start: 0,
|
path_start: 0,
|
||||||
}),
|
}),
|
||||||
_ => Err(IdentParseError(ascii_cow_to_str_cow(cow))),
|
_ => Err(IdentError(string)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the namespace part of this resource identifier.
|
/// Returns the namespace part of this resource identifier.
|
||||||
///
|
///
|
||||||
/// If this identifier was constructed from a string without a namespace,
|
/// If the underlying string does not contain a namespace followed by a
|
||||||
/// then "minecraft" is returned.
|
/// ':' character, `"minecraft"` is returned.
|
||||||
pub fn namespace(&self) -> &str {
|
pub fn namespace(&self) -> &str {
|
||||||
if self.path_start == 0 {
|
if self.path_start == 0 {
|
||||||
"minecraft"
|
"minecraft"
|
||||||
} else {
|
} else {
|
||||||
self.string[..self.path_start - 1].as_str()
|
&self.string.borrow()[..self.path_start - 1]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the path part of this resource identifier.
|
|
||||||
pub fn path(&self) -> &str {
|
pub fn path(&self) -> &str {
|
||||||
self.string[self.path_start..].as_str()
|
&self.string.borrow()[self.path_start..]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the underlying string as a `str`.
|
/// Returns the underlying string as a `str`.
|
||||||
pub fn as_str(&self) -> &str {
|
pub fn as_str(&self) -> &str {
|
||||||
self.string.as_str()
|
self.string.borrow()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Borrows the underlying string and returns it as an `Ident`. This
|
||||||
|
/// operation is infallible and no checks need to be performed.
|
||||||
|
pub fn as_str_ident(&self) -> Ident<&str> {
|
||||||
|
Ident {
|
||||||
|
string: self.string.borrow(),
|
||||||
|
path_start: self.path_start,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Converts the underlying string to its owned representation and returns
|
||||||
|
/// it as an `Ident`. This operation is infallible and no checks need to be
|
||||||
|
/// performed.
|
||||||
|
pub fn to_owned_ident(&self) -> Ident<S::Owned>
|
||||||
|
where
|
||||||
|
S: ToOwned,
|
||||||
|
S::Owned: Borrow<str>,
|
||||||
|
{
|
||||||
|
Ident {
|
||||||
|
string: self.string.to_owned(),
|
||||||
|
path_start: self.path_start,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Consumes the identifier and returns the underlying string.
|
/// Consumes the identifier and returns the underlying string.
|
||||||
pub fn into_inner(self) -> Cow<'a, str> {
|
pub fn into_inner(self) -> S {
|
||||||
ascii_cow_to_str_cow(self.string)
|
self.string
|
||||||
}
|
|
||||||
|
|
||||||
/// Used as the argument to `#[serde(deserialize_with = "...")]` when you
|
|
||||||
/// don't want to borrow data from the `'de` lifetime.
|
|
||||||
pub fn deserialize_to_owned<'de, D>(deserializer: D) -> Result<Ident<'static>, D::Error>
|
|
||||||
where
|
|
||||||
D: Deserializer<'de>,
|
|
||||||
{
|
|
||||||
Ident::new(String::deserialize(deserializer)?).map_err(de::Error::custom)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ascii_cow_to_str_cow(cow: Cow<AsciiStr>) -> Cow<str> {
|
/// The error type created when an [`Ident`] cannot be parsed from a
|
||||||
match cow {
|
/// string. Contains the offending string.
|
||||||
Cow::Borrowed(s) => Cow::Borrowed(s.as_str()),
|
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
Cow::Owned(s) => Cow::Owned(s.into()),
|
pub struct IdentError<S>(pub S);
|
||||||
|
|
||||||
|
impl<S> fmt::Debug for IdentError<S>
|
||||||
|
where
|
||||||
|
S: Borrow<str>,
|
||||||
|
{
|
||||||
|
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||||
|
f.debug_tuple("IdentError").field(&self.0.borrow()).finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> fmt::Debug for Ident<'a> {
|
impl<S> fmt::Display for IdentError<S>
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
where
|
||||||
f.debug_tuple("Ident").field(&self.as_str()).finish()
|
S: Borrow<str>,
|
||||||
|
{
|
||||||
|
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
|
||||||
|
write!(f, "invalid resource identifier \"{}\"", self.0.borrow())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> FromStr for Ident<'a> {
|
impl<S> Error for IdentError<S> where S: Borrow<str> {}
|
||||||
type Err = IdentParseError<'a>;
|
|
||||||
|
impl FromStr for Ident<String> {
|
||||||
|
type Err = IdentError<String>;
|
||||||
|
|
||||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||||
Ident::new(s.to_owned())
|
Ident::new(s.to_owned())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> From<Ident<'a>> for String {
|
impl TryFrom<String> for Ident<String> {
|
||||||
fn from(id: Ident) -> Self {
|
type Error = IdentError<String>;
|
||||||
id.string.into_owned().into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> From<Ident<'a>> for Cow<'a, str> {
|
|
||||||
fn from(id: Ident<'a>) -> Self {
|
|
||||||
id.into_inner()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> AsRef<str> for Ident<'a> {
|
|
||||||
fn as_ref(&self) -> &str {
|
|
||||||
self.as_str()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, 'b> PartialEq<Ident<'b>> for Ident<'a> {
|
|
||||||
fn eq(&self, other: &Ident<'b>) -> bool {
|
|
||||||
(self.namespace(), self.path()) == (other.namespace(), other.path())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, 'b> PartialOrd<Ident<'b>> for Ident<'a> {
|
|
||||||
fn partial_cmp(&self, other: &Ident<'b>) -> Option<Ordering> {
|
|
||||||
(self.namespace(), self.path()).partial_cmp(&(other.namespace(), other.path()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Hash for Ident<'a> {
|
|
||||||
fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
|
||||||
self.namespace().hash(state);
|
|
||||||
self.path().hash(state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> fmt::Display for Ident<'a> {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
write!(f, "{}:{}", self.namespace(), self.path())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TryFrom<String> for Ident<'a> {
|
|
||||||
type Error = IdentParseError<'a>;
|
|
||||||
|
|
||||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||||
Ident::new(value)
|
Ident::new(value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> TryFrom<&'a str> for Ident<'a> {
|
impl<S> From<Ident<S>> for String
|
||||||
type Error = IdentParseError<'a>;
|
where
|
||||||
|
S: Into<String> + Borrow<str>,
|
||||||
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
|
{
|
||||||
Ident::new(value)
|
fn from(id: Ident<S>) -> Self {
|
||||||
|
if id.path_start == 0 {
|
||||||
|
format!("minecraft:{}", id.string.borrow())
|
||||||
|
} else {
|
||||||
|
id.string.into()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> From<Ident<'a>> for nbt::Value {
|
impl<S: Borrow<str>> fmt::Display for Ident<S> {
|
||||||
fn from(id: Ident<'a>) -> Self {
|
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||||
String::from(id).into()
|
write!(f, "{}:{}", self.namespace(), self.path())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> Encode for Ident<'a> {
|
impl<S, T> PartialEq<Ident<T>> for Ident<S>
|
||||||
fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
|
where
|
||||||
self.as_str().encode(w)
|
S: Borrow<str>,
|
||||||
|
T: Borrow<str>,
|
||||||
|
{
|
||||||
|
fn eq(&self, other: &Ident<T>) -> bool {
|
||||||
|
self.namespace() == other.namespace() && self.path() == other.path()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> Decode for Ident<'a> {
|
impl<S> Eq for Ident<S> where S: Borrow<str> {}
|
||||||
fn decode(r: &mut &[u8]) -> anyhow::Result<Self> {
|
|
||||||
Ok(Ident::new(String::decode(r)?)?)
|
impl<S, T> PartialOrd<Ident<T>> for Ident<S>
|
||||||
|
where
|
||||||
|
S: Borrow<str>,
|
||||||
|
T: Borrow<str>,
|
||||||
|
{
|
||||||
|
fn partial_cmp(&self, other: &Ident<T>) -> Option<Ordering> {
|
||||||
|
(self.namespace(), self.path()).partial_cmp(&(other.namespace(), other.path()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> Serialize for Ident<'a> {
|
impl<S> Ord for Ident<S>
|
||||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
where
|
||||||
self.as_str().serialize(serializer)
|
S: Borrow<str>,
|
||||||
|
{
|
||||||
|
fn cmp(&self, other: &Self) -> Ordering {
|
||||||
|
(self.namespace(), self.path()).cmp(&(other.namespace(), other.path()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// This uses borrowed data from the `'de` lifetime. If you just want owned
|
impl<S> Hash for Ident<S>
|
||||||
/// data, see [`Ident::deserialize_to_owned`].
|
where
|
||||||
impl<'de> Deserialize<'de> for Ident<'de> {
|
S: Borrow<str>,
|
||||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
{
|
||||||
deserializer.deserialize_string(IdentVisitor)
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||||
|
(self.namespace(), self.path()).hash(state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct IdentVisitor;
|
impl<T> Serialize for Ident<T>
|
||||||
|
where
|
||||||
impl<'de> Visitor<'de> for IdentVisitor {
|
T: Serialize,
|
||||||
type Value = Ident<'de>;
|
{
|
||||||
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
||||||
write!(f, "a valid Minecraft resource identifier")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_str<E: de::Error>(self, s: &str) -> Result<Self::Value, E> {
|
|
||||||
Ident::from_str(s).map_err(E::custom)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
|
|
||||||
where
|
where
|
||||||
E: de::Error,
|
S: Serializer,
|
||||||
{
|
{
|
||||||
Ident::new(v).map_err(E::custom)
|
self.string.serialize(serializer)
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_string<E: de::Error>(self, s: String) -> Result<Self::Value, E> {
|
|
||||||
Ident::new(s).map_err(E::custom)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Convenience macro for constructing an [`Ident`] from a format string.
|
impl<'de, T> Deserialize<'de> for Ident<T>
|
||||||
|
where
|
||||||
|
T: Deserialize<'de> + Borrow<str>,
|
||||||
|
{
|
||||||
|
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||||
|
where
|
||||||
|
D: Deserializer<'de>,
|
||||||
|
{
|
||||||
|
Ident::new(T::deserialize(deserializer)?).map_err(D::Error::custom)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S: Encode> Encode for Ident<S> {
|
||||||
|
fn encode(&self, w: &mut impl Write) -> anyhow::Result<()> {
|
||||||
|
self.string.encode(w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S> Decode for Ident<S>
|
||||||
|
where
|
||||||
|
S: Decode + Borrow<str> + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
fn decode(r: &mut &[u8]) -> anyhow::Result<Self> {
|
||||||
|
Ok(Ident::new(S::decode(r)?)?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S> From<Ident<S>> for nbt::Value
|
||||||
|
where
|
||||||
|
S: Into<nbt::Value>,
|
||||||
|
{
|
||||||
|
fn from(id: Ident<S>) -> Self {
|
||||||
|
id.string.into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience macro for constructing an [`Ident<String>`] from a format
|
||||||
|
/// string.
|
||||||
///
|
///
|
||||||
/// The arguments to this macro are forwarded to [`std::format_args`].
|
/// The arguments to this macro are forwarded to [`std::format`].
|
||||||
///
|
///
|
||||||
/// # Panics
|
/// # Panics
|
||||||
///
|
///
|
||||||
/// The macro will cause a panic if the formatted string is not a valid
|
/// The macro will cause a panic if the formatted string is not a valid resource
|
||||||
/// identifier. See [`Ident`] for more information.
|
/// identifier. See [`Ident`] for more information.
|
||||||
///
|
///
|
||||||
|
/// [`Ident<String>`]: [Ident]
|
||||||
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use valence::ident;
|
/// use valence::ident;
|
||||||
///
|
///
|
||||||
/// let namespace = "my_namespace";
|
/// let namespace = "my_namespace";
|
||||||
/// let path = ident!("{namespace}:my_path");
|
/// let path = "my_path";
|
||||||
///
|
///
|
||||||
/// assert_eq!(path.namespace(), "my_namespace");
|
/// let id = ident!("{namespace}:{path}");
|
||||||
/// assert_eq!(path.path(), "my_path");
|
///
|
||||||
|
/// assert_eq!(id.namespace(), "my_namespace");
|
||||||
|
/// assert_eq!(id.path(), "my_path");
|
||||||
/// ```
|
/// ```
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! ident {
|
macro_rules! ident {
|
||||||
($($arg:tt)*) => {{
|
($($arg:tt)*) => {{
|
||||||
let errmsg = "invalid resource identifier in `ident` macro";
|
$crate::ident::Ident::new(::std::format!($($arg)*)).unwrap()
|
||||||
#[allow(clippy::redundant_closure_call)]
|
|
||||||
(|args: ::std::fmt::Arguments| match args.as_str() {
|
|
||||||
Some(s) => $crate::ident::Ident::new(s).expect(errmsg),
|
|
||||||
None => $crate::ident::Ident::new(args.to_string()).expect(errmsg),
|
|
||||||
})(format_args!($($arg)*))
|
|
||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -346,26 +346,4 @@ mod tests {
|
||||||
|
|
||||||
assert_eq!(h1.finish(), h2.finish());
|
assert_eq!(h1.finish(), h2.finish());
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_borrowed(id: Ident) {
|
|
||||||
if let Cow::Owned(_) = id.into_inner() {
|
|
||||||
panic!("not borrowed!");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn literal_is_borrowed() {
|
|
||||||
check_borrowed(ident!("akjghsjkhebf"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn visit_borrowed_str_borrows() {
|
|
||||||
let data = String::from("valence:frobnicator");
|
|
||||||
|
|
||||||
check_borrowed(
|
|
||||||
IdentVisitor
|
|
||||||
.visit_borrowed_str::<de::value::Error>(data.as_ref())
|
|
||||||
.unwrap(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -52,7 +52,7 @@ pub trait Decode: Sized {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The maximum number of bytes in a single packet.
|
/// The maximum number of bytes in a single packet.
|
||||||
pub const MAX_PACKET_SIZE: i32 = 2097151;
|
pub const MAX_PACKET_SIZE: i32 = 2097152;
|
||||||
|
|
||||||
impl Encode for () {
|
impl Encode for () {
|
||||||
fn encode(&self, _w: &mut impl Write) -> anyhow::Result<()> {
|
fn encode(&self, _w: &mut impl Write) -> anyhow::Result<()> {
|
||||||
|
|
|
@ -281,7 +281,7 @@ pub mod play {
|
||||||
|
|
||||||
def_struct! {
|
def_struct! {
|
||||||
PluginMessageC2s {
|
PluginMessageC2s {
|
||||||
channel: Ident<'static>,
|
channel: Ident<String>,
|
||||||
data: RawBytes,
|
data: RawBytes,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -407,7 +407,7 @@ pub mod play {
|
||||||
def_struct! {
|
def_struct! {
|
||||||
PlaceRecipe {
|
PlaceRecipe {
|
||||||
window_id: i8,
|
window_id: i8,
|
||||||
recipe: Ident<'static>,
|
recipe: Ident<String>,
|
||||||
make_all: bool,
|
make_all: bool,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -520,7 +520,7 @@ pub mod play {
|
||||||
|
|
||||||
def_struct! {
|
def_struct! {
|
||||||
SetSeenRecipe {
|
SetSeenRecipe {
|
||||||
recipe_id: Ident<'static>,
|
recipe_id: Ident<String>,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -542,7 +542,7 @@ pub mod play {
|
||||||
|
|
||||||
def_enum! {
|
def_enum! {
|
||||||
SeenAdvancements: VarInt {
|
SeenAdvancements: VarInt {
|
||||||
OpenedTab: Ident<'static> = 0,
|
OpenedTab: Ident<String> = 0,
|
||||||
ClosedScreen = 1,
|
ClosedScreen = 1,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -610,9 +610,9 @@ pub mod play {
|
||||||
def_struct! {
|
def_struct! {
|
||||||
ProgramJigsawBlock {
|
ProgramJigsawBlock {
|
||||||
location: BlockPos,
|
location: BlockPos,
|
||||||
name: Ident<'static>,
|
name: Ident<String>,
|
||||||
target: Ident<'static>,
|
target: Ident<String>,
|
||||||
pool: Ident<'static>,
|
pool: Ident<String>,
|
||||||
final_state: String,
|
final_state: String,
|
||||||
joint_type: String,
|
joint_type: String,
|
||||||
}
|
}
|
||||||
|
|
|
@ -62,7 +62,7 @@ pub mod login {
|
||||||
def_struct! {
|
def_struct! {
|
||||||
LoginPluginRequest {
|
LoginPluginRequest {
|
||||||
message_id: VarInt,
|
message_id: VarInt,
|
||||||
channel: Ident<'static>,
|
channel: Ident<String>,
|
||||||
data: RawBytes,
|
data: RawBytes,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -277,7 +277,7 @@ pub mod play {
|
||||||
|
|
||||||
def_struct! {
|
def_struct! {
|
||||||
CustomSoundEffect {
|
CustomSoundEffect {
|
||||||
name: Ident<'static>,
|
name: Ident<String>,
|
||||||
category: SoundCategory,
|
category: SoundCategory,
|
||||||
position: Vec3<i32>,
|
position: Vec3<i32>,
|
||||||
volume: f32,
|
volume: f32,
|
||||||
|
@ -388,13 +388,13 @@ pub mod play {
|
||||||
is_hardcore: bool,
|
is_hardcore: bool,
|
||||||
gamemode: GameMode,
|
gamemode: GameMode,
|
||||||
previous_gamemode: GameMode,
|
previous_gamemode: GameMode,
|
||||||
dimension_names: Vec<Ident<'static>>,
|
dimension_names: Vec<Ident<String>>,
|
||||||
/// Contains information about dimensions, biomes, and chats.
|
/// Contains information about dimensions, biomes, and chats.
|
||||||
registry_codec: Compound,
|
registry_codec: Compound,
|
||||||
/// The name of the dimension type being spawned into.
|
/// The name of the dimension type being spawned into.
|
||||||
dimension_type_name: Ident<'static>,
|
dimension_type_name: Ident<String>,
|
||||||
/// The name of the dimension being spawned into.
|
/// The name of the dimension being spawned into.
|
||||||
dimension_name: Ident<'static>,
|
dimension_name: Ident<String>,
|
||||||
/// Hash of the world's seed used for client biome noise.
|
/// Hash of the world's seed used for client biome noise.
|
||||||
hashed_seed: i64,
|
hashed_seed: i64,
|
||||||
/// No longer used by the client.
|
/// No longer used by the client.
|
||||||
|
@ -409,7 +409,7 @@ pub mod play {
|
||||||
/// If this is a superflat world.
|
/// If this is a superflat world.
|
||||||
/// Superflat worlds have different void fog and horizon levels.
|
/// Superflat worlds have different void fog and horizon levels.
|
||||||
is_flat: bool,
|
is_flat: bool,
|
||||||
last_death_location: Option<(Ident<'static>, BlockPos)>,
|
last_death_location: Option<(Ident<String>, BlockPos)>,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -529,15 +529,15 @@ pub mod play {
|
||||||
|
|
||||||
def_struct! {
|
def_struct! {
|
||||||
Respawn {
|
Respawn {
|
||||||
dimension_type_name: Ident<'static>,
|
dimension_type_name: Ident<String>,
|
||||||
dimension_name: Ident<'static>,
|
dimension_name: Ident<String>,
|
||||||
hashed_seed: u64,
|
hashed_seed: u64,
|
||||||
game_mode: GameMode,
|
game_mode: GameMode,
|
||||||
previous_game_mode: GameMode,
|
previous_game_mode: GameMode,
|
||||||
is_debug: bool,
|
is_debug: bool,
|
||||||
is_flat: bool,
|
is_flat: bool,
|
||||||
copy_metadata: bool,
|
copy_metadata: bool,
|
||||||
last_death_location: Option<(Ident<'static>, BlockPos)>,
|
last_death_location: Option<(Ident<String>, BlockPos)>,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -708,7 +708,7 @@ pub mod play {
|
||||||
|
|
||||||
def_struct! {
|
def_struct! {
|
||||||
EntityAttributesProperty {
|
EntityAttributesProperty {
|
||||||
key: Ident<'static>,
|
key: Ident<String>,
|
||||||
value: f64,
|
value: f64,
|
||||||
modifiers: Vec<EntityAttributesModifiers>
|
modifiers: Vec<EntityAttributesModifiers>
|
||||||
}
|
}
|
||||||
|
|
|
@ -378,15 +378,14 @@ enum ClickEvent {
|
||||||
enum HoverEvent {
|
enum HoverEvent {
|
||||||
ShowText(Box<Text>),
|
ShowText(Box<Text>),
|
||||||
ShowItem {
|
ShowItem {
|
||||||
#[serde(deserialize_with = "Ident::deserialize_to_owned")]
|
id: Ident<String>,
|
||||||
id: Ident<'static>,
|
|
||||||
count: Option<i32>,
|
count: Option<i32>,
|
||||||
// TODO: tag
|
// TODO: tag
|
||||||
},
|
},
|
||||||
ShowEntity {
|
ShowEntity {
|
||||||
name: Box<Text>,
|
name: Box<Text>,
|
||||||
#[serde(rename = "type", deserialize_with = "Ident::deserialize_to_owned")]
|
#[serde(rename = "type")]
|
||||||
kind: Ident<'static>,
|
kind: Ident<String>,
|
||||||
// TODO: id (hyphenated entity UUID as a string)
|
// TODO: id (hyphenated entity UUID as a string)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue