typescript_definitions_ufo_patch/
lib.rs

1// Copyright 2019 Ian Castleden
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8#![allow(unused_imports)]
9
10//! # Generate Typescript types from Rust source code.
11//!
12//! Please see documentation at [crates.io](https://crates.io/crates/typescript-definitions)
13//! or the [README](README/index.html).
14//!
15// we add this so `cargo doc` shows re-export.
16
17#[macro_use]
18pub extern crate typescript_definitions_derive;
19
20// re-export macros (note pub)
21use serde::ser::Serializer;
22use std::borrow::Cow;
23pub use typescript_definitions_derive::*;
24
25// just for doc tests
26#[allow(unused, non_snake_case)]
27pub mod README;
28
29/// # Trait implemented by `TypeScriptify` derive macro.
30///
31/// Please see documentation at [crates.io](https://crates.io/crates/typescript-definitions)
32/// or the [README](README/index.html).
33///
34///
35pub trait TypeScriptifyTrait {
36    fn type_script_ify() -> Cow<'static, str>;
37
38    #[cfg(feature = "type-guards")]
39    /// Available with `--features="type-guards"`
40    fn type_script_guard() -> Option<Cow<'static, str>>;
41}
42/// # String serializer for `u8` byte buffers.
43///
44/// Use `#[serde(serialize_with="typescript_definitions::as_byte_string")]`
45/// on a `[u8]` or `Vec<u8>` object to  make the output type a `string` (instead of a `number[]`).
46/// The encoding is a simple `\xdd` format.
47///
48/// Or provide your own serializer:
49/// `typescript-definitions` only checks the final *name* "as_byte_string" of the path.
50///
51pub fn as_byte_string<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
52where
53    S: Serializer,
54{
55    // probably not possible to serialze this as a stream
56    // we have no access to the underlying io stream... :(
57    let t = bytes
58        .iter()
59        .map(|b| format!(r"\x{:02x}", b))
60        .collect::<Vec<_>>()
61        .join("");
62
63    serializer.serialize_str(&t)
64}