1
2
Fork 0
mirror of https://github.com/mat-1/azalea.git synced 2025-08-02 06:16:04 +00:00

Replace lazy_static with once_cell::sync::Lazy (#43)

* Remove lazy_static in azalea-chat

* replace lazy_static with once_cell everywhere

* fix

* fix import

* ignore a clippy warning in shape codegen
This commit is contained in:
mat 2022-11-19 15:21:54 -06:00 committed by GitHub
parent befa22c1f3
commit 619984fa33
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 1745 additions and 1755 deletions

8
Cargo.lock generated
View file

@ -194,7 +194,7 @@ version = "0.3.0"
dependencies = [ dependencies = [
"azalea-buf", "azalea-buf",
"azalea-language", "azalea-language",
"lazy_static", "once_cell",
"serde", "serde",
"serde_json", "serde_json",
] ]
@ -213,9 +213,9 @@ dependencies = [
"azalea-physics", "azalea-physics",
"azalea-protocol", "azalea-protocol",
"azalea-world", "azalea-world",
"lazy_static",
"log", "log",
"nohash-hasher", "nohash-hasher",
"once_cell",
"parking_lot", "parking_lot",
"regex", "regex",
"thiserror", "thiserror",
@ -253,7 +253,7 @@ dependencies = [
name = "azalea-language" name = "azalea-language"
version = "0.3.0" version = "0.3.0"
dependencies = [ dependencies = [
"lazy_static", "once_cell",
"serde", "serde",
"serde_json", "serde_json",
] ]
@ -279,7 +279,7 @@ dependencies = [
"azalea-block", "azalea-block",
"azalea-core", "azalea-core",
"azalea-world", "azalea-world",
"lazy_static", "once_cell",
"parking_lot", "parking_lot",
"uuid", "uuid",
] ]

View file

@ -11,6 +11,6 @@ repository = "https://github.com/mat-1/azalea/tree/main/azalea-chat"
[dependencies] [dependencies]
azalea-buf = {path = "../azalea-buf", features = ["serde_json"], version = "^0.3.0" } azalea-buf = {path = "../azalea-buf", features = ["serde_json"], version = "^0.3.0" }
azalea-language = {path = "../azalea-language", version = "^0.3.0" } azalea-language = {path = "../azalea-language", version = "^0.3.0" }
lazy_static = "^1.4.0" once_cell = "1.16.0"
serde = "^1.0.130" serde = "^1.0.130"
serde_json = "^1.0.72" serde_json = "^1.0.72"

View file

@ -1,17 +1,16 @@
use std::{
fmt::Display,
io::{Cursor, Write},
};
use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
use serde::{de, Deserialize, Deserializer};
use crate::{ use crate::{
base_component::BaseComponent, base_component::BaseComponent,
style::{ChatFormatting, Style}, style::{ChatFormatting, Style},
text_component::TextComponent, text_component::TextComponent,
translatable_component::{StringOrComponent, TranslatableComponent}, translatable_component::{StringOrComponent, TranslatableComponent},
}; };
use azalea_buf::{BufReadError, McBufReadable, McBufWritable};
use once_cell::sync::Lazy;
use serde::{de, Deserialize, Deserializer};
use std::{
fmt::Display,
io::{Cursor, Write},
};
/// A chat component, basically anything you can see in chat. /// A chat component, basically anything you can see in chat.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@ -20,12 +19,10 @@ pub enum Component {
Translatable(TranslatableComponent), Translatable(TranslatableComponent),
} }
lazy_static! { pub static DEFAULT_STYLE: Lazy<Style> = Lazy::new(|| Style {
pub static ref DEFAULT_STYLE: Style = Style { color: Some(ChatFormatting::White.try_into().unwrap()),
color: Some(ChatFormatting::White.try_into().unwrap()), ..Style::default()
..Style::default() });
};
}
/// A chat component /// A chat component
impl Component { impl Component {

View file

@ -1,9 +1,6 @@
//! Things for working with Minecraft chat messages. //! Things for working with Minecraft chat messages.
//! This was inspired by Minecraft and prismarine-chat. //! This was inspired by Minecraft and prismarine-chat.
#[macro_use]
extern crate lazy_static;
pub mod base_component; pub mod base_component;
mod component; mod component;
pub mod style; pub mod style;

View file

@ -1,6 +1,7 @@
use std::{collections::HashMap, fmt}; use std::{collections::HashMap, fmt};
use azalea_buf::McBuf; use azalea_buf::McBuf;
use once_cell::sync::Lazy;
use serde_json::Value; use serde_json::Value;
#[derive(Clone, PartialEq, Eq, Debug)] #[derive(Clone, PartialEq, Eq, Debug)]
@ -28,8 +29,8 @@ impl TextColor {
} }
} }
lazy_static! { static LEGACY_FORMAT_TO_COLOR: Lazy<HashMap<&'static ChatFormatting, TextColor>> =
static ref LEGACY_FORMAT_TO_COLOR: HashMap<&'static ChatFormatting, TextColor> = { Lazy::new(|| {
let mut legacy_format_to_color = HashMap::new(); let mut legacy_format_to_color = HashMap::new();
for formatter in &ChatFormatting::FORMATTERS { for formatter in &ChatFormatting::FORMATTERS {
if !formatter.is_format() && *formatter != ChatFormatting::Reset { if !formatter.is_format() && *formatter != ChatFormatting::Reset {
@ -43,15 +44,14 @@ lazy_static! {
} }
} }
legacy_format_to_color legacy_format_to_color
}; });
static ref NAMED_COLORS: HashMap<String, TextColor> = { static NAMED_COLORS: Lazy<HashMap<String, TextColor>> = Lazy::new(|| {
let mut named_colors = HashMap::new(); let mut named_colors = HashMap::new();
for color in LEGACY_FORMAT_TO_COLOR.values() { for color in LEGACY_FORMAT_TO_COLOR.values() {
named_colors.insert(color.name.clone().unwrap(), color.clone()); named_colors.insert(color.name.clone().unwrap(), color.clone());
} }
named_colors named_colors
}; });
}
pub struct Ansi {} pub struct Ansi {}
impl Ansi { impl Ansi {

View file

@ -19,9 +19,9 @@ azalea-crypto = {path = "../azalea-crypto", version = "0.3.0"}
azalea-physics = {path = "../azalea-physics", version = "0.3.0"} azalea-physics = {path = "../azalea-physics", version = "0.3.0"}
azalea-protocol = {path = "../azalea-protocol", version = "0.3.0"} azalea-protocol = {path = "../azalea-protocol", version = "0.3.0"}
azalea-world = {path = "../azalea-world", version = "0.3.0"} azalea-world = {path = "../azalea-world", version = "0.3.0"}
lazy_static = "1.4.0"
log = "0.4.17" log = "0.4.17"
nohash-hasher = "0.2.0" nohash-hasher = "0.2.0"
once_cell = "1.16.0"
parking_lot = {version = "^0.12.1", features = ["deadlock_detection"]} parking_lot = {version = "^0.12.1", features = ["deadlock_detection"]}
regex = "1.7.0" regex = "1.7.0"
thiserror = "^1.0.34" thiserror = "^1.0.34"

View file

@ -9,8 +9,6 @@ use azalea_protocol::packets::game::{
serverbound_chat_command_packet::ServerboundChatCommandPacket, serverbound_chat_command_packet::ServerboundChatCommandPacket,
serverbound_chat_packet::ServerboundChatPacket, serverbound_chat_packet::ServerboundChatPacket,
}; };
use lazy_static::lazy_static;
use regex::Regex;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
/// A chat packet, either a system message or a chat message. /// A chat packet, either a system message or a chat message.
@ -20,6 +18,13 @@ pub enum ChatPacket {
Player(Box<ClientboundPlayerChatPacket>), Player(Box<ClientboundPlayerChatPacket>),
} }
macro_rules! regex {
($re:literal $(,)?) => {{
static RE: once_cell::sync::OnceCell<regex::Regex> = once_cell::sync::OnceCell::new();
RE.get_or_init(|| regex::Regex::new($re).unwrap())
}};
}
impl ChatPacket { impl ChatPacket {
/// Get the message shown in chat for this packet. /// Get the message shown in chat for this packet.
pub fn message(&self) -> Component { pub fn message(&self) -> Component {
@ -49,11 +54,7 @@ impl ChatPacket {
} }
// It's a system message, so we'll have to match the content // It's a system message, so we'll have to match the content
// with regex // with regex
lazy_static! { if let Some(m) = regex!("^<([a-zA-Z_0-9]{1,16})> (.+)$").captures(&message) {
static ref ANGLE_BRACKETS_RE: Regex =
Regex::new("^<([a-zA-Z_0-9]{1,16})> (.+)$").unwrap();
}
if let Some(m) = ANGLE_BRACKETS_RE.captures(&message) {
return (Some(m[1].to_string()), m[2].to_string()); return (Some(m[1].to_string()), m[2].to_string());
} }

View file

@ -9,7 +9,7 @@ version = "0.3.0"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
lazy_static = "1.4.0" once_cell = "1.16.0"
serde = "1.0.137" serde = "1.0.137"
serde_json = "1.0.81" serde_json = "1.0.81"
# tokio = {version = "^1.21.2", features = ["fs"]} # tokio = {version = "^1.21.2", features = ["fs"]}

View file

@ -1,6 +1,6 @@
//! Translate Minecraft strings from their id. //! Translate Minecraft strings from their id.
use lazy_static::lazy_static; use once_cell::sync::Lazy;
use std::io::Read; use std::io::Read;
use std::path::Path; use std::path::Path;
use std::{collections::HashMap, fs::File}; use std::{collections::HashMap, fs::File};
@ -31,16 +31,16 @@ use std::{collections::HashMap, fs::File};
// Language object that we passed around everywhere which is not convenient // Language object that we passed around everywhere which is not convenient
// The code above is kept in case I come up with a better solution // The code above is kept in case I come up with a better solution
lazy_static! { pub static STORAGE: Lazy<HashMap<String, String>> = Lazy::new(|| {
pub static ref STORAGE: HashMap<String, String> = serde_json::from_str(&{ serde_json::from_str(&{
let src_dir = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src/en_us.json")); let src_dir = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src/en_us.json"));
let mut file = File::open(src_dir).unwrap(); let mut file = File::open(src_dir).unwrap();
let mut contents = String::new(); let mut contents = String::new();
file.read_to_string(&mut contents).unwrap(); file.read_to_string(&mut contents).unwrap();
contents contents
}) })
.unwrap(); .unwrap()
} });
pub fn get(key: &str) -> Option<&str> { pub fn get(key: &str) -> Option<&str> {
STORAGE.get(key).map(|s| s.as_str()) STORAGE.get(key).map(|s| s.as_str())

View file

@ -12,7 +12,7 @@ version = "0.3.0"
azalea-block = {path = "../azalea-block", version = "^0.3.0"} azalea-block = {path = "../azalea-block", version = "^0.3.0"}
azalea-core = {path = "../azalea-core", version = "^0.3.0"} azalea-core = {path = "../azalea-core", version = "^0.3.0"}
azalea-world = {path = "../azalea-world", version = "^0.3.0"} azalea-world = {path = "../azalea-world", version = "^0.3.0"}
lazy_static = "1.4.0" once_cell = "1.16.0"
parking_lot = "^0.12.1" parking_lot = "^0.12.1"
[dev-dependencies] [dev-dependencies]

File diff suppressed because it is too large Load diff

View file

@ -49,14 +49,8 @@ def generate_block_shapes_code(blocks: dict, shapes: dict, block_states_report,
# look at downloads/generator-mod-*/blockCollisionShapes.json for format of blocks and shapes # look at downloads/generator-mod-*/blockCollisionShapes.json for format of blocks and shapes
generated_shape_code = '' generated_shape_code = ''
# we make several lazy_static! blocks so it doesn't complain about for (shape_id, shape) in sorted(shapes.items(), key=lambda shape: int(shape[0])):
# recursion and hopefully the compiler can paralleize it?
generated_shape_code += 'lazy_static! {'
for i, (shape_id, shape) in enumerate(sorted(shapes.items(), key=lambda shape: int(shape[0]))):
if i > 0 and i % 10 == 0:
generated_shape_code += '}\nlazy_static! {'
generated_shape_code += generate_code_for_shape(shape_id, shape) generated_shape_code += generate_code_for_shape(shape_id, shape)
generated_shape_code += '}'
# BlockState::PurpurStairs_NorthTopStraightTrue => &SHAPE24, # BlockState::PurpurStairs_NorthTopStraightTrue => &SHAPE24,
generated_match_inner_code = '' generated_match_inner_code = ''
@ -93,11 +87,12 @@ def generate_block_shapes_code(blocks: dict, shapes: dict, block_states_report,
// modify it, change that file. // modify it, change that file.
#![allow(clippy::explicit_auto_deref)] #![allow(clippy::explicit_auto_deref)]
#![allow(clippy::redundant_closure)]
use super::VoxelShape; use super::VoxelShape;
use crate::collision::{{self, Shapes}}; use crate::collision::{{self, Shapes}};
use azalea_block::*; use azalea_block::*;
use lazy_static::lazy_static; use once_cell::sync::Lazy;
pub trait BlockWithShape {{ pub trait BlockWithShape {{
fn shape(&self) -> &'static VoxelShape; fn shape(&self) -> &'static VoxelShape;
@ -119,7 +114,7 @@ def generate_code_for_shape(shape_id: str, parts: list[list[float]]):
def make_arguments(part: list[float]): def make_arguments(part: list[float]):
return ', '.join(map(lambda n: str(n).rstrip('0'), part)) return ', '.join(map(lambda n: str(n).rstrip('0'), part))
code = '' code = ''
code += f'static ref SHAPE{shape_id}: VoxelShape = ' code += f'static SHAPE{shape_id}: Lazy<VoxelShape> = Lazy::new(|| {{'
steps = [] steps = []
if parts == []: if parts == []:
steps.append('collision::empty_shape()') steps.append('collision::empty_shape()')
@ -136,5 +131,6 @@ def generate_code_for_shape(shape_id: str, parts: list[list[float]]):
for step in steps[:-1]: for step in steps[:-1]:
code += f' let s = {step};\n' code += f' let s = {step};\n'
code += f' {steps[-1]}\n' code += f' {steps[-1]}\n'
code += '};\n' code += '}\n'
code += '});\n'
return code return code