sxyazi/yazi · error

Failed to get the C string from CFString

Error message

Failed to get the C string from CFString

What it means

CFString::os_string extracts the string's bytes with CFStringGetCString using UTF-8; the bails fires when that function returns 0, meaning the conversion to a C string failed. The CFString content could not be represented (or the buffer was insufficient), so no OsString can be produced.

Solutions

  1. Fall back to CFStringGetCStringPtr or CFStringGetBytes with lossy conversion instead of strict UTF-8 C-string extraction.
  2. Verify the capacity passed to CFStringGetCString accounts for the NUL terminator (len + 1).
  3. Inspect the source data for non-UTF-8 or embedded-NUL content and sanitize it upstream.
Defensive patterns

Strategy: try-catch

Validate before calling

// Before extraction you cannot easily validate encoding; guard by checking length fits the buffer
let capacity = (unsafe { CFStringGetLength(s.0) } + 1) as usize;
// if capacity exceeds what os_string allocates, expect failure

Try / catch

let name = cf_string.os_string().unwrap_or_else(|_| OsString::from("<unreadable>"));

Prevention

When it happens

Trigger: Calling os_string() on a CFString whose contents are not valid UTF-8 (e.g. legacy MacRoman filenames) or whose length exceeds the computed capacity, causing CFStringGetCString to fail.

Common situations: Reading macOS metadata strings that contain legacy non-UTF-8 encodings from old files or Finder aliases; corrupted metadata blobs; strings with embedded NUL bytes.

Related errors


AI-assisted analysis of sxyazi/yazi@a541adde4e (2026-09-18). Data as JSON: /api/errors/0df7fb607bd2da5b. Report an issue: GitHub.

Appendix: source

Thrown at yazi-ffi/src/cf_string.rs:38

		if key.is_null() {
			bail!("Allocation failed while creating CFString");
		}
		Ok(Self(key))
	}

	fn len(&self) -> usize { unsafe { CFStringGetLength(self.0) as _ } }

	pub(crate) fn os_string(&self) -> Result<OsString> {
		let len = self.len();
		let capacity =
			unsafe { CFStringGetMaximumSizeForEncoding(len as _, kCFStringEncodingUTF8) } + 1;

		let mut out: Vec<u8> = Vec::with_capacity(capacity as usize);
		let result = unsafe {
			CFStringGetCString(self.0, out.as_mut_ptr().cast(), capacity, kCFStringEncodingUTF8)
		};
		if result == 0 {
			bail!("Failed to get the C string from CFString");
		}

		unsafe { out.set_len(CStr::from_ptr(out.as_ptr().cast()).count_bytes()) };
		out.shrink_to_fit();
		Ok(OsString::from_vec(out))
	}
}

impl Deref for CFString {
	type Target = CFStringRef;

	fn deref(&self) -> &Self::Target { &self.0 }
}

impl Drop for CFString {
	fn drop(&mut self) { unsafe { CFRelease(self.0 as _) }; }
}

View on GitHub (pinned to a541adde4e)