From 5aa8ed4c90cb37e309421b55ef97f4f034645e56 Mon Sep 17 00:00:00 2001 From: Graeme Coupar Date: Sat, 13 Jun 2020 13:19:30 +0100 Subject: [PATCH] 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(&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`. --- src/schema/ast.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/schema/ast.rs b/src/schema/ast.rs index 39a5582..824703b 100644 --- a/src/schema/ast.rs +++ b/src/schema/ast.rs @@ -12,6 +12,26 @@ pub struct Document<'a, T: Text<'a>> pub definitions: Vec>, } +impl<'a> Document<'a, String> { + pub fn into_static(self) -> Document<'static, String> { + // To support both reference and owned values in the AST, + // all string data is represented with the ::common::Str<'a, T: Text<'a>> + // wrapper type. + // This type must carry the liftetime of the schema string, + // and is stored in a PhantomData value on the Str type. + // When using owned String types, the actual lifetime of + // the Ast nodes is 'static, since no references are kept, + // but the nodes will still carry the input lifetime. + // To continue working with Document in a owned fasion + // the lifetime needs to be transmuted to 'static. + // + // This is safe because no references are present. + // Just the PhantomData lifetime reference is transmuted away. + unsafe { std::mem::transmute::<_, Document<'static, String>>(self) } + } +} + + #[derive(Debug, Clone, PartialEq)] pub enum Definition<'a, T: Text<'a>> { SchemaDefinition(SchemaDefinition<'a, T>),