Skip to content

Commit

Permalink
Use modern associated const Lazy initializer
Browse files Browse the repository at this point in the history
  • Loading branch information
stepancheg committed Mar 23, 2020
1 parent 858a5e1 commit f362d93
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 20 deletions.
25 changes: 5 additions & 20 deletions protobuf-codegen/src/code_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,29 +103,14 @@ impl<'a> CodeWriter<'a> {
}

pub fn lazy_static(&mut self, name: &str, ty: &str) {
self.stmt_block(
&format!(
"static mut {}: ::protobuf::lazy::Lazy<{}> = ::protobuf::lazy::Lazy",
name, ty
),
|w| {
w.field_entry("lock", "::protobuf::lazy::ONCE_INIT");
w.field_entry("ptr", &format!("0 as *const {}", ty));
},
);
self.lazy_static_protobuf_path(name, ty, "::protobuf")
}

pub fn lazy_static_protobuf_path(&mut self, name: &str, ty: &str, protobuf_crate_path: &str) {
self.stmt_block(
&format!(
"static mut {}: {}::lazy::Lazy<{}> = ::protobuf::lazy::Lazy",
name, protobuf_crate_path, ty
),
|w| {
w.field_entry("lock", &format!("{}::lazy::ONCE_INIT", protobuf_crate_path));
w.field_entry("ptr", &format!("0 as *const {}", ty));
},
);
self.write_line(&format!(
"static mut {}: {}::lazy::Lazy<{}> = {}::lazy::Lazy::INIT;",
name, protobuf_crate_path, ty, protobuf_crate_path,
));
}

pub fn lazy_static_decl_get<F>(&mut self, name: &str, ty: &str, init: F)
Expand Down
9 changes: 9 additions & 0 deletions protobuf/src/lazy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@ pub struct Lazy<T> {
}

impl<T> Lazy<T> {
/// Uninitialized `Lazy` object.
///
/// The initializer is added in rust-protobuf 2.11, for compatibility with
/// previously generated code, existing fields are kept public.
pub const INIT: Lazy<T> = Lazy {
lock: sync::Once::new(),
ptr: 0 as *const T,
};

/// Get lazy field value, initialize it with given function if not yet.
pub fn get<F>(&'static mut self, init: F) -> &'static T
where
Expand Down

0 comments on commit f362d93

Please sign in to comment.