mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
From: Douglas Anderson <dianders@chromium.org>
To: Devicetree-compiler@vger.kernel.org,
	Rob Herring <robh@kernel.org>,
	Krzysztof Kozlowski <krzk+dt@kernel.org>,
	Conor Dooley <conor+dt@kernel.org>,
	Konrad Dybcio <konradybcio@kernel.org>
Cc: Devicetree@vger.kernel.org,
	"Tudor Ambarus" <tudor.ambarus@linaro.org>,
	"Chen-Yu Tsai" <wenst@chromium.org>,
	"Saravana Kannan" <saravanak@kernel.org>,
	"David Gibson" <david@gibson.dropbear.id.au>,
	"André Draszik" <andre.draszik@linaro.org>,
	"Simon Glass" <sjg@chromium.org>,
	linux-kernel@vger.kernel.org,
	"Brian Norris" <briannorris@chromium.org>,
	"Peter Griffin" <peter.griffin@linaro.org>,
	"Julius Werner" <jwerner@chromium.org>,
	"Douglas Anderson" <dianders@chromium.org>
Subject: [PATCH v4 04/14] pylibfdt: Add Property.from_*() creation methods
Date: Mon, 16 Nov 2026 12:53:01 -0800	[thread overview]
Message-ID: <20261116205320.1621386-5-dianders@chromium.org> (raw)
In-Reply-To: <20261116205320.1621386-1-dianders@chromium.org>

`libfdt.Property` provides `as_*()` methods (`as_cell`, `as_uint32`,
`as_int32`, `as_uint64`, `as_int64`, `as_list`, `as_uint32_list`,
`as_int32_list`, `as_uint64_list`, `as_int64_list`, `as_str`, and
`as_stringlist`) to decode typed values from a `Property`, but lacks the
corresponding creation methods to construct a `Property` from typed
values.

Add `from_*()` classmethods mirroring each `as_*()` method so callers
(such as `DeviceTree` users) can construct typed `Property` instances
directly without duplicating encoding helpers on `DeviceTree`.

Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
---

Changes in v4:
- New patch adding Property.from_*() creation classmethods so
  DeviceTree does not need its own get_*/set_* wrapper methods (David
  Gibson)

 pylibfdt/libfdt.i       | 56 +++++++++++++++++++++++++++++++++++++++++
 tests/pylibfdt_tests.py | 49 ++++++++++++++++++++++++++++++++++++
 2 files changed, 105 insertions(+)

diff --git a/pylibfdt/libfdt.i b/pylibfdt/libfdt.i
index 68f22e316ece..ff9210d123cb 100644
--- a/pylibfdt/libfdt.i
+++ b/pylibfdt/libfdt.i
@@ -962,6 +962,62 @@ class Property(bytes):
         parts = self[:-1].split(b'\x00')
         return list(map(lambda x: x.decode('utf-8'), parts))
 
+    @classmethod
+    def from_cell(cls, name, fmt, val):
+        return cls(name, struct.pack('>' + fmt, val))
+
+    @classmethod
+    def from_uint32(cls, name, val):
+        return cls.from_cell(name, 'L', val)
+
+    @classmethod
+    def from_int32(cls, name, val):
+        return cls.from_cell(name, 'l', val)
+
+    @classmethod
+    def from_uint64(cls, name, val):
+        return cls.from_cell(name, 'Q', val)
+
+    @classmethod
+    def from_int64(cls, name, val):
+        return cls.from_cell(name, 'q', val)
+
+    @classmethod
+    def from_list(cls, name, fmt, vals):
+        vals = list(vals)
+        return cls(name, struct.pack(f'>{len(vals)}{fmt}', *vals))
+
+    @classmethod
+    def from_uint32_list(cls, name, vals):
+        return cls.from_list(name, 'L', vals)
+
+    @classmethod
+    def from_int32_list(cls, name, vals):
+        return cls.from_list(name, 'l', vals)
+
+    @classmethod
+    def from_uint64_list(cls, name, vals):
+        return cls.from_list(name, 'Q', vals)
+
+    @classmethod
+    def from_int64_list(cls, name, vals):
+        return cls.from_list(name, 'q', vals)
+
+    @classmethod
+    def from_str(cls, name, val):
+        """Unicode is supported by encoding to UTF-8"""
+        if '\x00' in val:
+            raise ValueError('String value contains embedded nul characters')
+        return cls(name, val.encode('utf-8') + b'\x00')
+
+    @classmethod
+    def from_stringlist(cls, name, vals):
+        """Unicode is supported by encoding to UTF-8"""
+        vals = list(vals)
+        if any('\x00' in v for v in vals):
+            raise ValueError('String value contains embedded nul characters')
+        return cls(name, b''.join(v.encode('utf-8') + b'\x00' for v in vals))
+
 
 class FdtSw(FdtRo):
     """Software interface to create a device tree from scratch
diff --git a/tests/pylibfdt_tests.py b/tests/pylibfdt_tests.py
index 26915a015ccb..e2f9c6d5afe4 100644
--- a/tests/pylibfdt_tests.py
+++ b/tests/pylibfdt_tests.py
@@ -414,6 +414,16 @@ class PyLibfdtBasicTests(unittest.TestCase):
         self.assertEqual(9223372036854775807,
                           self.get_prop("prop-uint64").as_uint64())
         self.assertEqual(-2, self.get_prop("prop-int64").as_int64())
+        self.assertEqual(self.get_prop("prop-hex32"),
+                          libfdt.Property.from_uint32("prop-hex32", 0xdeadbeef))
+        self.assertEqual(self.get_prop("prop-int32"),
+                          libfdt.Property.from_int32("prop-int32", -2))
+        self.assertEqual(
+            self.get_prop("prop-uint64"),
+            libfdt.Property.from_uint64("prop-uint64", 9223372036854775807),
+        )
+        self.assertEqual(self.get_prop("prop-int64"),
+                          libfdt.Property.from_int64("prop-int64", -2))
 
     def testGetIntListProperties(self):
         """Test that we can access properties as integer lists"""
@@ -425,6 +435,28 @@ class PyLibfdtBasicTests(unittest.TestCase):
                          self.get_prop("prop-int64-array").as_int64_list())
         self.assertEqual([0x100000000, 0x1],
                          self.get_prop("prop-uint64-array").as_uint64_list())
+        self.assertEqual(
+            self.get_prop("prop-int32-array"),
+            libfdt.Property.from_int32_list("prop-int32-array", [128, -16, -2]),
+        )
+        self.assertEqual(
+            self.get_prop("prop-uint32-array"),
+            libfdt.Property.from_uint32_list(
+                "prop-uint32-array", [0x1, 0x98765432, 0xdeadbeef]
+            ),
+        )
+        self.assertEqual(
+            self.get_prop("prop-int64-array"),
+            libfdt.Property.from_int64_list(
+                "prop-int64-array", [0x100000000, -2]
+            ),
+        )
+        self.assertEqual(
+            self.get_prop("prop-uint64-array"),
+            libfdt.Property.from_uint64_list(
+                "prop-uint64-array", [0x100000000, 0x1]
+            ),
+        )
 
     def testGetStringlistProperties(self):
         """Test that we can access properties as string list"""
@@ -434,6 +466,17 @@ class PyLibfdtBasicTests(unittest.TestCase):
         self.assertEqual(["this is a placeholder string", "string2"],
                          self.fdt.getprop(node, "placeholder").as_stringlist())
         self.assertEqual([], libfdt.Property('empty', b'').as_stringlist())
+        self.assertEqual(
+            self.fdt.getprop(node, "compatible"),
+            libfdt.Property.from_stringlist(
+                "compatible", ["subsubnode1", "subsubnode"]
+            ),
+        )
+        self.assertEqual(
+            b'', libfdt.Property.from_stringlist("empty", [])
+        )
+        with self.assertRaises(ValueError):
+            libfdt.Property.from_stringlist("bad", ["embedded\x00nul"])
         with self.assertRaises(ValueError) as e:
             libfdt.Property('bad', b'no-nul').as_stringlist()
         self.assertIn('lacks nul termination', str(e.exception))
@@ -552,6 +595,12 @@ class PyLibfdtBasicTests(unittest.TestCase):
         self.fdt.setprop_str(node, prop, TEST_STRING_3)
         self.assertEqual(TEST_STRING_3,
                           self.fdt.getprop(node, prop).as_str())
+        self.assertEqual(
+            self.fdt.getprop(node, prop),
+            libfdt.Property.from_str(prop, TEST_STRING_3),
+        )
+        with self.assertRaises(ValueError):
+            libfdt.Property.from_str(prop, 'embedded\x00nul')
 
     def testHasProp(self):
         """Test that we can check if a node has a property"""
-- 
2.56.0.679.gc527c65306-goog


  parent reply	other threads:[~2026-11-16 20:53 UTC|newest]

Thread overview: 15+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-16 20:52 [PATCH v4 00/14] fdtfactor: Introduce fdtfactor to auto-factor overlays Douglas Anderson
2026-11-16 20:52 ` [PATCH v4 01/14] README: Add overview blurbs for dtc and ancillary tools Douglas Anderson
2026-11-16 20:52 ` [PATCH v4 02/14] pylibfdt: Make Property a subclass of bytes instead of bytearray Douglas Anderson
2026-11-16 20:53 ` [PATCH v4 03/14] pylibfdt: Trim Fdt bytearray to totalsize() in FdtSw.as_fdt() Douglas Anderson
2026-11-16 20:53 ` Douglas Anderson [this message]
2026-11-16 20:53 ` [PATCH v4 05/14] pylibfdt: Unpack Property.as_list() in a single struct.unpack() call Douglas Anderson
2026-11-16 20:53 ` [PATCH v4 06/14] pylibfdt: Speed up FdtRo.properties() with a C helper Douglas Anderson
2026-11-16 20:53 ` [PATCH v4 07/14] libpydt: Add DeviceTree live tree representation Douglas Anderson
2026-11-16 20:53 ` [PATCH v4 08/14] libfdt: Speed up fdt_find_string_len_() with memchr() Douglas Anderson
2026-11-16 20:53 ` [PATCH v4 09/14] libfdt: overlay: Update base /__local_fixups__ on apply Douglas Anderson
2026-11-16 20:53 ` [PATCH v4 10/14] fdtfactor: Add tool to split DTBs into a base DTB and overlays Douglas Anderson
2026-11-16 20:53 ` [PATCH v4 11/14] fdtfactor: Add -S/--strip-local-fixups option Douglas Anderson
2026-11-16 20:53 ` [PATCH v4 12/14] fdtfactor: Support compressed DTB inputs and outputs Douglas Anderson
2026-11-16 20:53 ` [PATCH v4 13/14] fdtfactor: Add compiled FIT factoring support Douglas Anderson
2026-11-16 20:53 ` [PATCH v4 14/14] fdtfactor: Parallelize blob compression and decompression Douglas Anderson

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261116205320.1621386-5-dianders@chromium.org \
    --to=dianders@chromium.org \
    --cc=Devicetree-compiler@vger.kernel.org \
    --cc=Devicetree@vger.kernel.org \
    --cc=andre.draszik@linaro.org \
    --cc=briannorris@chromium.org \
    --cc=conor+dt@kernel.org \
    --cc=david@gibson.dropbear.id.au \
    --cc=jwerner@chromium.org \
    --cc=konradybcio@kernel.org \
    --cc=krzk+dt@kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=peter.griffin@linaro.org \
    --cc=robh@kernel.org \
    --cc=saravanak@kernel.org \
    --cc=sjg@chromium.org \
    --cc=tudor.ambarus@linaro.org \
    --cc=wenst@chromium.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®