Skip to content

Commit

Permalink
Replace lazy_static with once_cell
Browse files Browse the repository at this point in the history
The ecosystem has generally accepted that the approach used in
`once_cell` is a better way to lazily initialize statics.

This change also makes it easier to later use `std::cell::LazyCell`. See
rust-lang/rust#109736.
  • Loading branch information
nvzqz committed Jun 1, 2023
1 parent 94c6243 commit 2afd45e
Show file tree
Hide file tree
Showing 23 changed files with 103 additions and 121 deletions.
12 changes: 6 additions & 6 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion demo-hytradboi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ futures-executor = "0.3.21"
git-url-parse = "0.4.0"
hn_api = "0.1.0"
itertools = "0.10.3"
lazy_static = "1.4.0"
once_cell = "1.17"
maplit = "1.0.2"
octorust = "0.1.35"
regex = "1.5.4"
Expand Down
35 changes: 21 additions & 14 deletions demo-hytradboi/src/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use std::{fs, rc::Rc, sync::Arc};

use git_url_parse::GitUrl;
use hn_api::{types::Item, HnClient};
use lazy_static::__Deref;
use octorust::types::{ContentFile, FullRepository};
use once_cell::sync::Lazy;
use tokio::runtime::Runtime;
use trustfall_core::{
interpreter::{
Expand All @@ -24,28 +24,35 @@ use crate::{

const USER_AGENT: &str = "demo-hytradboi (github.com/obi1kenobi/trustfall)";

lazy_static! {
static ref HN_CLIENT: HnClient = HnClient::init().unwrap();
static ref CRATES_CLIENT: consecrates::Client = consecrates::Client::new(USER_AGENT);
static ref GITHUB_CLIENT: octorust::Client = octorust::Client::new(
static HN_CLIENT: Lazy<HnClient> = Lazy::new(|| HnClient::init().unwrap());

static CRATES_CLIENT: Lazy<consecrates::Client> =
Lazy::new(|| consecrates::Client::new(USER_AGENT));

static GITHUB_CLIENT: Lazy<octorust::Client> = Lazy::new(|| {
octorust::Client::new(
USER_AGENT,
Some(octorust::auth::Credentials::Token(
std::env::var("GITHUB_TOKEN").unwrap_or_else(|_| {
fs::read_to_string("./localdata/gh_token")
.expect("could not find creds file")
.trim()
.to_string()
})
}),
)),
)
.unwrap();
static ref REPOS_CLIENT: octorust::repos::Repos =
octorust::repos::Repos::new(GITHUB_CLIENT.clone());
static ref RUNTIME: Runtime = tokio::runtime::Builder::new_current_thread()
.unwrap()
});

static REPOS_CLIENT: Lazy<octorust::repos::Repos> =
Lazy::new(|| octorust::repos::Repos::new(GITHUB_CLIENT.clone()));

static RUNTIME: Lazy<Runtime> = Lazy::new(|| {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
}
.unwrap()
});

pub struct DemoAdapter;

Expand Down Expand Up @@ -119,7 +126,7 @@ impl DemoAdapter {

fn most_downloaded_crates(&self) -> VertexIterator<'static, Vertex> {
Box::new(
CratesPager::new(CRATES_CLIENT.deref())
CratesPager::new(&CRATES_CLIENT)
.into_iter()
.map(|x| x.into()),
)
Expand Down Expand Up @@ -596,7 +603,7 @@ impl Adapter<'static> for DemoAdapter {
let neighbors: VertexIterator<'static, Self::Vertex> = match vertex {
None => Box::new(std::iter::empty()),
Some(vertex) => Box::new(
WorkflowsPager::new(GITHUB_CLIENT.clone(), vertex, RUNTIME.deref())
WorkflowsPager::new(GITHUB_CLIENT.clone(), vertex, &RUNTIME)
.into_iter()
.map(|x| x.into()),
),
Expand Down
10 changes: 3 additions & 7 deletions demo-hytradboi/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,21 @@ use std::sync::Arc;
use std::time::{Duration, Instant};

use adapter::DemoAdapter;
use once_cell::sync::Lazy;
use serde::Deserialize;
use trustfall_core::ir::TransparentValue;
use trustfall_core::{
frontend::parse, interpreter::execution::interpret_ir, ir::FieldValue, schema::Schema,
};

#[macro_use]
extern crate lazy_static;

mod actions_parser;
mod adapter;
mod pagers;
mod util;
mod vertex;

lazy_static! {
static ref SCHEMA: Schema =
Schema::parse(fs::read_to_string("./schema.graphql").unwrap()).unwrap();
}
static SCHEMA: Lazy<Schema> =
Lazy::new(|| Schema::parse(fs::read_to_string("./schema.graphql").unwrap()).unwrap());

#[derive(Debug, Clone, Deserialize)]
struct InputQuery<'a> {
Expand Down
2 changes: 1 addition & 1 deletion experiments/schemaless/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@ edition = "2021"
async-graphql-parser = "2.11.3"
async-graphql-value = "2.11.3"
derive-new = "0.5.9"
lazy_static = "1.4.0"
once_cell = "1.17"
maplit = "1.0.2"
trustfall_core = { path = "../../trustfall_core" }
2 changes: 1 addition & 1 deletion pytrustfall/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
async-graphql-parser = "2.11.3"
async-graphql-value = "2.11.3"
lazy_static = "1.4.0"
once_cell = "1.17"
pyo3 = { version = "0.17.2", features = ["extension-module"] }
trustfall_core = { path = "../trustfall_core" }
2 changes: 1 addition & 1 deletion trustfall/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ ron = "0.7.0"
serde = { version = "^1.0", features = ["derive"] }
serde_json = "1.0.69"
feed-rs = "1.0.0"
lazy_static = "1.4.0"
once_cell = "1.17"
reqwest = { version = "0.11.6", features = ["blocking", "json"] }
hn_api = "0.1.0"
csv = "1.1.6"
Expand Down
10 changes: 3 additions & 7 deletions trustfall/examples/feeds/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,10 @@ use std::{
};

use feed_rs::{model::Feed, parser};
use once_cell::sync::Lazy;
use serde::Deserialize;
use trustfall::{execute_query, FieldValue, Schema, TransparentValue};

#[macro_use]
extern crate lazy_static;

use crate::adapter::FeedAdapter;

mod adapter;
Expand All @@ -25,10 +23,8 @@ const WIRED_FEED_URI: &str = "https://www.wired.com/feed";
const PCGAMER_FEED_LOCATION: &str = "/tmp/feeds-pcgamer.xml";
const WIRED_FEED_LOCATION: &str = "/tmp/feeds-wired.xml";

lazy_static! {
static ref SCHEMA: Schema =
Schema::parse(util::read_file("./examples/feeds/feeds.graphql")).unwrap();
}
static SCHEMA: Lazy<Schema> =
Lazy::new(|| Schema::parse(util::read_file("./examples/feeds/feeds.graphql")).unwrap());

#[derive(Debug, Clone, Deserialize)]
struct InputQuery<'a> {
Expand Down
5 changes: 2 additions & 3 deletions trustfall/examples/hackernews/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use std::collections::HashSet;

use hn_api::{types::Item, HnClient};
use once_cell::sync::Lazy;
use trustfall::{
provider::{
field_property, resolve_coercion_using_schema, resolve_neighbors_with,
Expand All @@ -14,9 +15,7 @@ use trustfall::{

use crate::{vertex::Vertex, SCHEMA};

lazy_static! {
static ref CLIENT: HnClient = HnClient::init().expect("HnClient instantiated");
}
static CLIENT: Lazy<HnClient> = Lazy::new(|| HnClient::init().expect("HnClient instantiated"));

#[derive(Debug, Clone, Default)]
pub struct HackerNewsAdapter {
Expand Down
11 changes: 4 additions & 7 deletions trustfall/examples/hackernews/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,19 @@ use std::collections::BTreeMap;
use std::sync::Arc;
use std::{env, process};

use once_cell::sync::Lazy;
use serde::Deserialize;
use trustfall::{execute_query, FieldValue, Schema, TransparentValue};

use crate::adapter::HackerNewsAdapter;

#[macro_use]
extern crate lazy_static;

pub mod adapter;
mod util;
pub mod vertex;

lazy_static! {
static ref SCHEMA: Schema =
Schema::parse(util::read_file("./examples/hackernews/hackernews.graphql")).unwrap();
}
static SCHEMA: Lazy<Schema> = Lazy::new(|| {
Schema::parse(util::read_file("./examples/hackernews/hackernews.graphql")).unwrap()
});

#[derive(Debug, Clone, Deserialize)]
struct InputQuery<'a> {
Expand Down
13 changes: 5 additions & 8 deletions trustfall/examples/weather/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::io::{BufRead, BufReader, BufWriter, Write};
use std::sync::Arc;
use std::{env, process};

use once_cell::sync::Lazy;
use serde::Deserialize;
use trustfall::{execute_query, FieldValue, Schema, TransparentValue};

Expand All @@ -13,18 +14,14 @@ use crate::{
metar::{CsvMetarReport, MetarReport},
};

#[macro_use]
extern crate lazy_static;

mod adapter;
mod metar;
mod util;

lazy_static! {
static ref SCHEMA: Schema =
Schema::parse(util::read_file("./examples/weather/metar_weather.graphql"))
.expect("failed to parse schema");
}
static SCHEMA: Lazy<Schema> = Lazy::new(|| {
Schema::parse(util::read_file("./examples/weather/metar_weather.graphql"))
.expect("failed to parse schema")
});

const METAR_DOC_URL: &str =
"https://aviationweather.gov/adds/dataserver_current/current/metars.cache.csv";
Expand Down
14 changes: 8 additions & 6 deletions trustfall/examples/weather/metar.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::fmt;

use chrono::{DateTime, Utc};
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{de::Visitor, Deserialize, Deserializer};

Expand Down Expand Up @@ -225,19 +226,20 @@ static METAR_WIND_VARIABILITY_PATTERN: &str = r"(?:[0-9/]{3}V[0-9/]{3} )?";
// |raw meters|vis.ok| statute mi |
static METAR_VISIBILITY_PATTERN: &str = r"(?:[0-9]{4}|CAVOK|(?:[0-9/ ]+SM)) ";

lazy_static! {
static ref METAR_VISIBILITY_CAPTURE_PATTERN: String = METAR_STATION_AND_DATE_PATTERN.to_owned()
static METAR_VISIBILITY_CAPTURE_PATTERN: Lazy<String> = Lazy::new(|| {
METAR_STATION_AND_DATE_PATTERN.to_owned()
+ METAR_AUTO_OPTIONAL_MARKER_PATTERN
+ "(?:"
+ METAR_WIND_PATTERN
+ ")?"
+ METAR_WIND_VARIABILITY_PATTERN
+ "("
+ METAR_VISIBILITY_PATTERN
+ ")";
static ref METAR_VISIBILITY_CAPTURE_RE: Regex =
Regex::new(&METAR_VISIBILITY_CAPTURE_PATTERN).unwrap();
}
+ ")"
});

static METAR_VISIBILITY_CAPTURE_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(&METAR_VISIBILITY_CAPTURE_PATTERN).unwrap());

fn get_visibility(raw_metar: &str) -> Visibility {
if let Some(capture) = METAR_VISIBILITY_CAPTURE_RE.captures(raw_metar) {
Expand Down
2 changes: 1 addition & 1 deletion trustfall_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ serde = { version = "^1.0", features = ["derive", "rc"] }
async-graphql-parser = "^2.11.3"
async-graphql-value = "^2.11.3"
maplit = "^1.0.2"
lazy_static = "^1.4.0"
once_cell = "1.17"
smallvec = { version = "^1.6.1", features = ["serde"] }
chrono = { version = "0.4.19", features = ["serde"] }
regex = "1.5.4"
Expand Down
12 changes: 3 additions & 9 deletions trustfall_core/fuzz/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion trustfall_core/fuzz/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ cargo-fuzz = true
async-graphql-parser = "^2.11.3"
async-graphql-value = "^2.11.3"
byteorder = "1"
lazy_static = "1.4.0"
once_cell = "1.17"
ron = "0.7.0"
serde = { version = "^1.0", features = ["derive"] }
libfuzzer-sys = "0.4"
Expand Down
Loading

0 comments on commit 2afd45e

Please sign in to comment.