From cf947eebec0643651aca8da08b140f795eb734bb Mon Sep 17 00:00:00 2001
From: Xavier Robin <xavier.robin@unibas.ch>
Date: Wed, 6 Sep 2023 15:03:09 +0200
Subject: [PATCH] fix: avoid writing invalid SDF files

SDF V2000 supports up to 999 atoms/bonds. For more we need to implement
the V3000 format. For now we throw an error.
---
 modules/io/src/mol/sdf_writer.cc | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/modules/io/src/mol/sdf_writer.cc b/modules/io/src/mol/sdf_writer.cc
index e39444d0c..21e168be1 100644
--- a/modules/io/src/mol/sdf_writer.cc
+++ b/modules/io/src/mol/sdf_writer.cc
@@ -197,6 +197,21 @@ void SDFWriter::Write(const mol::EntityHandle& ent) {
 }
 
 bool SDFWriter::VisitChain(const mol::ChainView& chain) {
+  // Santiy check: only 999 atoms / bonds supported in SDF V2000
+  // If more are needed we need to implement V3000
+  if (chain.GetAtomCount() > 999) {
+    std::stringstream msg_at;
+    msg_at << "Can't write SDF file. Too many atoms (";
+    msg_at << chain.GetAtomCount() <<")";
+    throw IOException(msg_at.str());
+  }
+  if (chain.GetBondCount() > 999) {
+    std::stringstream msg_bo;
+    msg_bo << "Can't write SDF file. Too many bonds (";
+    msg_bo << chain.GetBondCount() <<")";
+    throw IOException(msg_bo.str());
+  }
+
   // print end of molecule line
   if(counter_ != 0) {
     ostr_ << "$$$$" << std::endl;
-- 
GitLab