ANDROID: rust: Use From instances for JSON encoder

This makes it easier to deal with nested objects or arrays.

This is Android specific because Rust KCFI is incomplete, and we are
using the binder driver as a staging ground to fix it. This patch is
intended to go upstream once the compiler behaves properly.

Signed-off-by: Matthew Maurer <mmaurer@google.com>
Bug: 316623888
Change-Id: I1eb623bfa522fd46fe2850278dce78b7c4e2cdf1
This commit is contained in:
Matthew Maurer 2023-09-14 23:37:36 +00:00 committed by Treehugger Robot
parent 2b93c38ece
commit 6be7b55440

View File

@ -60,33 +60,33 @@ impl Display for Value {
}
}
struct TargetSpec(Object);
impl TargetSpec {
fn new() -> TargetSpec {
TargetSpec(Vec::new())
impl From<bool> for Value {
fn from(value: bool) -> Self {
Self::Boolean(value)
}
}
trait Push<T> {
fn push(&mut self, key: &str, value: T);
}
impl Push<bool> for TargetSpec {
fn push(&mut self, key: &str, value: bool) {
self.0.push((key.to_string(), Value::Boolean(value)));
impl From<i32> for Value {
fn from(value: i32) -> Self {
Self::Number(value)
}
}
impl Push<i32> for TargetSpec {
fn push(&mut self, key: &str, value: i32) {
self.0.push((key.to_string(), Value::Number(value)));
impl From<String> for Value {
fn from(value: String) -> Self {
Self::String(value)
}
}
impl Push<String> for TargetSpec {
fn push(&mut self, key: &str, value: String) {
self.0.push((key.to_string(), Value::String(value)));
impl From<&str> for Value {
fn from(value: &str) -> Self {
Self::String(value.to_string())
}
}
impl From<Object> for Value {
fn from(object: Object) -> Self {
Self::Object(object)
}
}
@ -96,9 +96,15 @@ impl <T: Into<Value>, const N: usize> From<[T; N]> for Value {
}
}
impl Push<Object> for TargetSpec {
fn push(&mut self, key: &str, value: Object) {
self.0.push((key.to_string(), Value::Object(value)));
struct TargetSpec(Object);
impl TargetSpec {
fn new() -> TargetSpec {
TargetSpec(Vec::new())
}
fn push(&mut self, key: &str, value: impl Into<Value>) {
self.0.push((key.to_string(), value.into()));
}
}