diff --git a/src/core/IronPython.Modules/_struct.cs b/src/core/IronPython.Modules/_struct.cs index 57180a832..115a08770 100644 --- a/src/core/IronPython.Modules/_struct.cs +++ b/src/core/IronPython.Modules/_struct.cs @@ -899,15 +899,21 @@ private readonly struct Format(FormatType type, int count) { private static CacheDict _cache = new CacheDict(MAX_CACHE_SIZE); private static string FormatObjectToString(object fmt) { - if (fmt is IList b) { - return PythonOps.MakeString(b); - } - if (Converter.TryConvertToString(fmt, out string res)) { - // replicate CPython behaviour: throws UnicodeEncodeError if non-ASCII - StringOps.DoEncodeAscii(res); - return res; + if (fmt is Bytes b) return PythonOps.MakeString(b); + + string str = fmt switch { + string s => s, + Extensible es => es.Value, + _ => throw PythonOps.TypeError("Struct() argument 1 must be a str or bytes object, not {0}", PythonOps.GetPythonTypeName(fmt)), + }; + foreach (char c in str) { + if (c > 0x7f) { + // replicate CPython behaviour: throws UnicodeEncodeError if non-ASCII + StringOps.DoEncodeAscii(str); + break; + } } - throw PythonOps.TypeError("Struct() argument 1 must be a str or bytes object, not {0}", PythonOps.GetPythonTypeName(fmt)); + return str; } private static Struct GetStructFromCache(CodeContext/*!*/ context, object fmt) { diff --git a/src/core/IronPython/Runtime/PythonTuple.cs b/src/core/IronPython/Runtime/PythonTuple.cs index fa10ba3ff..5a254ac02 100644 --- a/src/core/IronPython/Runtime/PythonTuple.cs +++ b/src/core/IronPython/Runtime/PythonTuple.cs @@ -120,7 +120,7 @@ internal static PythonTuple Make(object o) { internal static PythonTuple MakeTuple(params object?[] items) { if (items.Length == 0) return EMPTY; - return new PythonTuple(DefaultContext.Default, items); + return new PythonTuple(items); } private static object?[] MakeItems(CodeContext context, object? o) { diff --git a/tests/suite/test_struct.py b/tests/suite/test_struct.py index a3b44abd5..e1bc9b8d0 100644 --- a/tests/suite/test_struct.py +++ b/tests/suite/test_struct.py @@ -65,6 +65,21 @@ def test_format_string_ascii_and_whitespace(self): with self.assertRaises(struct.error): struct.calcsize(bytes([0xff])) + def test_format_types(self): + class B(bytes): pass + class S(str): pass + for fmt in (b'>H', B(b'>H'), S('>H')): + self.assertEqual(struct.Struct(fmt).format, '>H') + self.assertEqual(struct.calcsize(fmt), 2) + with self.assertRaises(UnicodeEncodeError): + struct.calcsize(S(chr(0x0662))) + class C: + def __str__(self): return '>H' + # avoid a cached format: memoryview(b'>H') == b'>H' hits CPython's cache (fixed by https://github.com/python/cpython/issues/85943) + for fmt in (bytearray(b'@7x'), memoryview(b'@7x'), C(), 1): + self.assertRaises(TypeError, struct.Struct, fmt) + self.assertRaises(TypeError, struct.calcsize, fmt) + def test_pack_into(self): # test string format string result = array.array('b', [0, 0])