Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove conversions from String<>ScSymbol/ScVal #329

Merged
merged 17 commits into from
Dec 1, 2023
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ stellar-strkey = { version = "0.0.8", optional = true }
base64 = { version = "0.13.0", optional = true }
serde = { version = "1.0.139", features = ["derive"], optional = true }
serde_with = { version = "3.0.0", optional = true }
escape-bytes = { version = "0.1.0", default-features = false }
hex = { version = "0.4.3", optional = true }
arbitrary = {version = "1.1.3", features = ["derive"], optional = true}
clap = { version = "4.2.4", default-features = false, features = ["std", "derive", "usage", "help"], optional = true }
Expand All @@ -35,7 +36,7 @@ serde_json = "1.0.89"
[features]
default = ["std", "curr"]
std = ["alloc"]
alloc = ["dep:hex", "dep:stellar-strkey"]
alloc = ["dep:hex", "dep:stellar-strkey", "escape-bytes/alloc"]
curr = []
next = []

Expand Down
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ CARGO_HACK_ARGS=--feature-powerset --exclude-features default --group-features b

CARGO_DOC_ARGS?=--open

XDRGEN_VERSION=cbff4b31
XDRGEN_TYPES_CUSTOM_STR_IMPL=PublicKey,AccountId,MuxedAccount,MuxedAccountMed25519,SignerKey,SignerKeyEd25519SignedPayload,NodeId,ScAddress
XDRGEN_VERSION=e90b9ee62a89f346a86ef66f889bcfd8e1a8fbcb
XDRGEN_TYPES_CUSTOM_STR_IMPL=PublicKey,AccountId,MuxedAccount,MuxedAccountMed25519,SignerKey,SignerKeyEd25519SignedPayload,NodeId,ScAddress,AssetCode,AssetCode4,AssetCode12

all: build test

Expand Down
94 changes: 25 additions & 69 deletions src/curr/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1703,6 +1703,17 @@ impl<const MAX: u32> WriteXdr for BytesM<MAX> {

// StringM ------------------------------------------------------------------------

/// A string type that contains arbitrary bytes.
///
/// Convertible, fallibly, to/from a Rust UTF-8 String using
/// [`TryFrom`]/[`TryInto`]/[`StringM::to_utf8_string`].
///
/// Convertible, lossyly, to a Rust UTF-8 String using
/// [`StringM::to_utf8_string_lossy`].
///
/// Convertible to/from escaped printable-ASCII using
/// [`Display`]/[`ToString`]/[`FromStr`].

#[cfg(feature = "alloc")]
#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(
Expand All @@ -1717,38 +1728,15 @@ pub struct StringM<const MAX: u32 = { u32::MAX }>(Vec<u8>);
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
pub struct StringM<const MAX: u32 = { u32::MAX }>(Vec<u8>);

/// `write_utf8_lossy` is a modified copy of the Rust stdlib docs examples here:
/// <https://doc.rust-lang.org/stable/core/str/struct.Utf8Error.html#examples>
fn write_utf8_lossy(f: &mut impl core::fmt::Write, mut input: &[u8]) -> core::fmt::Result {
loop {
match core::str::from_utf8(input) {
Ok(valid) => {
write!(f, "{valid}")?;
break;
}
Err(error) => {
let (valid, after_valid) = input.split_at(error.valid_up_to());
write!(f, "{}", core::str::from_utf8(valid).unwrap())?;
write!(f, "\u{FFFD}")?;

if let Some(invalid_sequence_length) = error.error_len() {
input = &after_valid[invalid_sequence_length..];
} else {
break;
}
}
}
}
Ok(())
}

impl<const MAX: u32> core::fmt::Display for StringM<MAX> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
#[cfg(feature = "alloc")]
let v = &self.0;
#[cfg(not(feature = "alloc"))]
let v = self.0;
write_utf8_lossy(f, v)?;
for b in escape_bytes::Escape::new(v) {
write!(f, "{}", b as char)?;
}
Ok(())
}
}
Expand All @@ -1760,7 +1748,9 @@ impl<const MAX: u32> core::fmt::Debug for StringM<MAX> {
#[cfg(not(feature = "alloc"))]
let v = self.0;
write!(f, "StringM(")?;
write_utf8_lossy(f, v)?;
for b in escape_bytes::Escape::new(v) {
write!(f, "{}", b as char)?;
}
write!(f, ")")?;
Ok(())
}
Expand All @@ -1770,7 +1760,8 @@ impl<const MAX: u32> core::fmt::Debug for StringM<MAX> {
impl<const MAX: u32> core::str::FromStr for StringM<MAX> {
type Err = Error;
fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
s.try_into()
let b = escape_bytes::unescape(s.as_bytes()).map_err(|_| Error::Invalid)?;
Ok(Self(b))
}
}

Expand Down Expand Up @@ -1818,24 +1809,24 @@ impl<const MAX: u32> StringM<MAX> {

impl<const MAX: u32> StringM<MAX> {
#[cfg(feature = "alloc")]
pub fn to_string(&self) -> Result<String> {
pub fn to_utf8_string(&self) -> Result<String> {
self.try_into()
}

#[cfg(feature = "alloc")]
pub fn into_string(self) -> Result<String> {
pub fn into_utf8_string(self) -> Result<String> {
self.try_into()
}

#[cfg(feature = "alloc")]
#[must_use]
pub fn to_string_lossy(&self) -> String {
pub fn to_utf8_string_lossy(&self) -> String {
String::from_utf8_lossy(&self.0).into_owned()
}

#[cfg(feature = "alloc")]
#[must_use]
pub fn into_string_lossy(self) -> String {
pub fn into_utf8_string_lossy(self) -> String {
String::from_utf8_lossy(&self.0).into_owned()
}
}
Expand Down Expand Up @@ -10345,23 +10336,6 @@ impl core::fmt::Debug for AssetCode4 {
Ok(())
}
}
impl core::fmt::Display for AssetCode4 {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let v = &self.0;
for b in v {
write!(f, "{b:02x}")?;
}
Ok(())
}
}

#[cfg(feature = "alloc")]
impl core::str::FromStr for AssetCode4 {
type Err = Error;
fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
hex::decode(s).map_err(|_| Error::InvalidHex)?.try_into()
}
}
impl From<AssetCode4> for [u8; 4] {
#[must_use]
fn from(x: AssetCode4) -> Self {
Expand Down Expand Up @@ -10461,23 +10435,6 @@ impl core::fmt::Debug for AssetCode12 {
Ok(())
}
}
impl core::fmt::Display for AssetCode12 {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let v = &self.0;
for b in v {
write!(f, "{b:02x}")?;
}
Ok(())
}
}

#[cfg(feature = "alloc")]
impl core::str::FromStr for AssetCode12 {
type Err = Error;
fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {
hex::decode(s).map_err(|_| Error::InvalidHex)?.try_into()
}
}
impl From<AssetCode12> for [u8; 12] {
#[must_use]
fn from(x: AssetCode12) -> Self {
Expand Down Expand Up @@ -10689,8 +10646,7 @@ impl WriteXdr for AssetType {
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(
all(feature = "serde", feature = "alloc"),
derive(serde::Serialize, serde::Deserialize),
serde(rename_all = "snake_case")
derive(serde_with::SerializeDisplay, serde_with::DeserializeFromStr)
)]
#[allow(clippy::large_enum_variant)]
pub enum AssetCode {
Expand Down Expand Up @@ -52095,7 +52051,7 @@ impl Type {
}

#[cfg(feature = "base64")]
pub fn from_xdr_base64(v: TypeVariant, b64: String, limits: Limits) -> Result<Self> {
pub fn from_xdr_base64(v: TypeVariant, b64: impl AsRef<[u8]>, limits: Limits) -> Result<Self> {
let mut b64_reader = Cursor::new(b64);
let mut dec = Limited::new(
base64::read::DecoderReader::new(&mut b64_reader, base64::STANDARD),
Expand Down
80 changes: 1 addition & 79 deletions src/curr/scval_conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use super::{
#[cfg(all(not(feature = "std"), feature = "alloc"))]
extern crate alloc;
#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::{string::String, vec, vec::Vec};
use alloc::{vec, vec::Vec};

// TODO: Use the Error type for conversions in this file.

Expand Down Expand Up @@ -300,84 +300,6 @@ impl TryFrom<ScVal> for ScSymbol {
}
}

#[cfg(feature = "alloc")]
impl TryFrom<String> for ScVal {
type Error = ();
fn try_from(v: String) -> Result<Self, ()> {
Ok(ScVal::Symbol(v.try_into().map_err(|()| ())?))
}
}

#[cfg(feature = "alloc")]
impl TryFrom<&String> for ScVal {
type Error = ();
fn try_from(v: &String) -> Result<Self, ()> {
Ok(ScVal::Symbol(v.try_into().map_err(|()| ())?))
}
}

#[cfg(feature = "alloc")]
impl TryFrom<String> for ScSymbol {
type Error = ();
fn try_from(v: String) -> Result<Self, Self::Error> {
Ok(ScSymbol(v.try_into().map_err(|_| ())?))
}
}

#[cfg(feature = "alloc")]
impl TryFrom<&String> for ScSymbol {
type Error = ();
fn try_from(v: &String) -> Result<Self, Self::Error> {
Ok(ScSymbol(v.try_into().map_err(|_| ())?))
}
}

#[cfg(feature = "alloc")]
impl TryFrom<&str> for ScVal {
type Error = ();
fn try_from(v: &str) -> Result<Self, ()> {
Ok(ScVal::Symbol(v.try_into().map_err(|()| ())?))
}
}

#[cfg(not(feature = "alloc"))]
impl TryFrom<&'static str> for ScVal {
type Error = ();
fn try_from(v: &'static str) -> Result<Self, ()> {
Ok(ScVal::Symbol(v.try_into().map_err(|()| ())?))
}
}

#[cfg(feature = "alloc")]
impl TryFrom<&str> for ScSymbol {
type Error = ();
fn try_from(v: &str) -> Result<Self, Self::Error> {
Ok(ScSymbol(v.try_into().map_err(|_| ())?))
}
}

#[cfg(not(feature = "alloc"))]
impl TryFrom<&'static str> for ScSymbol {
type Error = ();
fn try_from(v: &'static str) -> Result<Self, Self::Error> {
Ok(ScSymbol(v.try_into().map_err(|_| ())?))
}
}

#[cfg(feature = "alloc")]
impl TryFrom<ScVal> for String {
type Error = ();
fn try_from(v: ScVal) -> Result<Self, Self::Error> {
if let ScVal::Symbol(s) = v {
// TODO: It might be worth distinguishing the error case where this
// is an invalid symbol with invalid characters.
Ok(s.0.into_string().map_err(|_| ())?)
} else {
Err(())
}
}
}

#[cfg(feature = "alloc")]
impl TryFrom<Vec<u8>> for ScVal {
type Error = ();
Expand Down
Loading