Skip to content

Commit 5aa8ed4

Browse files
committed
Add into_static for schema::Document
I'm running into issues using `schema::Document` with strings. I have a function that looks roughly like this: ```rust fn load_schema(filename: String) -> schema::Document<'static, String> { let schema = std::fs::read_to_string(filename); graphql_parser::schema::parse_schema<String>(&schema).unwrap() } ``` However this won't compile, because the generated `Document` has taken a lifetime from `schema` which doesn't outlive the function. I was looking around the library and saw that the `query::Document` has an `into_static` function when using `Strings` which resolves this. This duplicates that functionality for `schema::Document`.
1 parent b0fbd45 commit 5aa8ed4

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/schema/ast.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,26 @@ pub struct Document<'a, T: Text<'a>>
1212
pub definitions: Vec<Definition<'a, T>>,
1313
}
1414

15+
impl<'a> Document<'a, String> {
16+
pub fn into_static(self) -> Document<'static, String> {
17+
// To support both reference and owned values in the AST,
18+
// all string data is represented with the ::common::Str<'a, T: Text<'a>>
19+
// wrapper type.
20+
// This type must carry the liftetime of the schema string,
21+
// and is stored in a PhantomData value on the Str type.
22+
// When using owned String types, the actual lifetime of
23+
// the Ast nodes is 'static, since no references are kept,
24+
// but the nodes will still carry the input lifetime.
25+
// To continue working with Document<String> in a owned fasion
26+
// the lifetime needs to be transmuted to 'static.
27+
//
28+
// This is safe because no references are present.
29+
// Just the PhantomData lifetime reference is transmuted away.
30+
unsafe { std::mem::transmute::<_, Document<'static, String>>(self) }
31+
}
32+
}
33+
34+
1535
#[derive(Debug, Clone, PartialEq)]
1636
pub enum Definition<'a, T: Text<'a>> {
1737
SchemaDefinition(SchemaDefinition<'a, T>),

0 commit comments

Comments
 (0)